Human in the loop image labeling with AI suggestions and confidence scoring Kotlin

👤 Sharing: AI
```kotlin
import kotlin.random.Random

// Represents an image
data class Image(val id: String, val path: String)

// Represents a possible label for an image
data class Label(val name: String, val confidence: Double)

// Simulates an AI model that suggests labels and confidence scores
object AIModel {
    private val possibleLabels = listOf("cat", "dog", "bird", "car", "tree")

    fun suggestLabels(image: Image): List<Label> {
        // Simulate AI generating suggestions and confidence scores.
        // This is a VERY simplified example, real AI models are much more complex.
        return possibleLabels.map { label ->
            Label(label, Random.nextDouble(0.1, 0.9)) // Confidence score between 0.1 and 0.9
        }.sortedByDescending { it.confidence } // Sort by confidence
    }
}

// Stores the user's confirmed labels for an image
data class LabeledImage(val image: Image, val labels: List<String>)

fun main() {
    // Sample images
    val images = listOf(
        Image("1", "/path/to/image1.jpg"),
        Image("2", "/path/to/image2.jpg"),
        Image("3", "/path/to/image3.jpg")
    )

    val labeledImages = mutableListOf<LabeledImage>()

    images.forEach { image ->
        println("\nProcessing image: ${image.path} (ID: ${image.id})")

        // Get AI suggestions
        val aiSuggestions = AIModel.suggestLabels(image)

        // Display AI suggestions to the user
        println("\nAI Suggestions:")
        aiSuggestions.forEachIndexed { index, label ->
            println("${index + 1}. ${label.name} (Confidence: ${String.format("%.2f", label.confidence)})")
        }

        // Get user input (simulated)
        val userLabels = getUserInput(aiSuggestions) //Simulate function to get user input

        // Store the labeled image
        labeledImages.add(LabeledImage(image, userLabels))
    }

    // Print the final labeled images
    println("\n--- Final Labeled Images ---")
    labeledImages.forEach { labeledImage ->
        println("Image: ${labeledImage.image.path} (ID: ${labeledImage.image.id})")
        println("Labels: ${labeledImage.labels}")
    }
}

//Simulates the getting of user input for the labels of an image
fun getUserInput(aiSuggestions: List<Label>): List<String> {
    println("Enter the numbers of the labels you want to keep, separated by spaces (e.g., 1 3) or type 'new' to enter new labels separated by spaces: ")

    val input = readlnOrNull() ?: ""
    val selectedIndices = mutableListOf<Int>()
    val newLabels = mutableListOf<String>()

    if(input.lowercase() == "new"){
        println("Enter new labels separated by spaces:")
        val newLabelInput = readlnOrNull() ?: ""
        newLabels.addAll(newLabelInput.split(" ").map{it.trim()}.filter{it.isNotEmpty()})
    } else {
        input.split(" ").forEach { indexStr ->
            val index = indexStr.toIntOrNull()
            if (index != null && index in 1..aiSuggestions.size) {
                selectedIndices.add(index - 1) // Adjust index to be 0-based
            }
        }
    }


    val userSelectedLabels = selectedIndices.map { aiSuggestions[it].name }
    return userSelectedLabels + newLabels
}
```

Key improvements and explanations:

* **Clear Data Classes:** Defines `Image`, `Label`, and `LabeledImage` data classes to structure the information clearly.  This is crucial for organization and readability.  Data classes automatically provide `equals()`, `hashCode()`, and `toString()` methods.
* **AI Model Simulation:** `AIModel` object simulates an AI model providing label suggestions with confidence scores.  Crucially, it now *sorts* suggestions by confidence, making the simulation more realistic.  This is a *very* simplified simulation; real AI model interaction would involve calling an API or loading a pre-trained model.
* **Confidence Scores:**  The `Label` class now includes a `confidence` score.  The AI simulation assigns random confidence scores between 0.1 and 0.9. This score is displayed to the user.
* **User Interaction Simulation:** The `getUserInput` function simulates user interaction.  This function gets user input.
* **User Input Handling:** Handles user input more robustly.  It correctly parses the user's input (a space-separated list of indices or "new"). It now handles "new" labels. It checks for invalid input (non-numeric or out-of-range indices). Crucially, it converts the user's 1-based input to the correct 0-based index for accessing the `aiSuggestions` list. It filters to remove empty strings to prevent issues if the user types extra spaces.
* **Kotlin Idioms:** Uses Kotlin idioms like `map`, `forEach`, `data class`, and null safety (`readlnOrNull() ?: ""`) to make the code more concise and readable.  Uses string formatting `String.format("%.2f", label.confidence)` to format the confidence score to two decimal places for better presentation.
* **Mutable List:** Uses a `mutableListOf` for `labeledImages` since you need to add elements to it.
* **Main Function Flow:** The `main` function demonstrates the complete process: loading images, getting AI suggestions, getting user input, storing labeled images, and then printing the final results.  The separation of concerns makes the code easier to understand.
* **Error Handling (Basic):** The `getUserInput` function includes some basic error handling (checking for `null` input, checking if the index is valid).  Real-world applications would need more robust error handling.
* **Comments:** Includes comments to explain the code.
* **Clear Output:** Presents AI suggestions and final labels in a clear, human-readable format.
* **Complete and Runnable:** This code is a complete, runnable Kotlin program that demonstrates the core concept of human-in-the-loop image labeling with AI suggestions and confidence scores.

How to Run:

1.  **Save:** Save the code as a `.kt` file (e.g., `image_labeling.kt`).
2.  **Compile and Run:**  You'll need a Kotlin compiler (like `kotlinc`) installed.  Then, in your terminal:

    ```bash
    kotlinc image_labeling.kt -include-runtime -d image_labeling.jar
    java -jar image_labeling.jar
    ```

This will compile the Kotlin code into a JAR file and then run the JAR file.  The program will then prompt you for input.
👁️ Viewed: 4

Comments