From 997d6770b275ccbbefa9bb4b6c74a170df9470cd Mon Sep 17 00:00:00 2001 From: bleack Date: Tue, 1 Dec 2026 22:13:01 +0100 Subject: [PATCH] feat(meal): add AI food recognition from meal plate photos --- .../com/example/domain/MealPhotoAnalyzer.kt | 249 +++++++++++++ .../com/example/ui/meal/MealEntrySheet.kt | 215 ++++++++++- .../meal/components/MealPhotoReviewDialog.kt | 337 ++++++++++++++++++ .../ui/meal/components/MealPhotosSection.kt | 106 ++++++ .../java/com/example/MealPhotoAnalyzerTest.kt | 147 ++++++++ 5 files changed, 1049 insertions(+), 5 deletions(-) create mode 100644 app/src/main/java/com/example/domain/MealPhotoAnalyzer.kt create mode 100644 app/src/main/java/com/example/ui/meal/components/MealPhotoReviewDialog.kt create mode 100644 app/src/test/java/com/example/MealPhotoAnalyzerTest.kt diff --git a/app/src/main/java/com/example/domain/MealPhotoAnalyzer.kt b/app/src/main/java/com/example/domain/MealPhotoAnalyzer.kt new file mode 100644 index 0000000..34bcd53 --- /dev/null +++ b/app/src/main/java/com/example/domain/MealPhotoAnalyzer.kt @@ -0,0 +1,249 @@ +package com.example.domain + +import android.graphics.Bitmap +import android.util.Log +import com.example.data.model.FoodCategory +import com.example.data.model.FoodUnit +import com.example.data.model.MealFoodItem +import com.google.firebase.Firebase +import com.google.firebase.ai.ai +import com.google.firebase.ai.type.Schema +import com.google.firebase.ai.type.content +import com.google.firebase.ai.type.generationConfig +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.TimeoutCancellationException +import kotlinx.coroutines.withTimeout +import org.json.JSONObject +import java.util.UUID + +data class RecognizedPlateFood( + val id: String = "plate_${UUID.randomUUID().toString().take(8)}", + val name: String, + val weight: Double? = null, + val unit: FoodUnit = FoodUnit.G, + val categories: List = listOf(FoodCategory.OTHER), + val selected: Boolean = true +) { + fun toMealFoodItem(): MealFoodItem { + val sanitized = FoodCategory.sanitizeSelection(categories).ifEmpty { listOf(FoodCategory.OTHER) } + return MealFoodItem( + name = name.trim(), + weight = weight?.takeIf { it.isFinite() && it > 0.0 }, + unit = unit, + category = sanitized.first(), + categories = sanitized + ) + } +} + +sealed interface MealPhotoAnalysisUiState { + data object Idle : MealPhotoAnalysisUiState + data object Analyzing : MealPhotoAnalysisUiState + data class Preview(val items: List) : MealPhotoAnalysisUiState + data class Error(val message: String) : MealPhotoAnalysisUiState +} + +/** + * Recognizes foods, estimated quantities/weights, and multi-category dietary tags + * from 1 to 4 meal plate photos (e.g. starter, main, dessert) using Firebase AI Logic + * (gemini-3.8-flash multimodal with strict JSON Schema output). + */ +class MealPhotoAnalyzer { + + private val allowedCategoryCodes = FoodCategory.entries.map { it.code } + private val allowedUnitCodes = listOf("g", "ml", "portion") + + private val responseSchema by lazy { + val itemSchema = Schema.obj( + properties = mapOf( + "name" to Schema.string( + description = "Nom français clair et simple de l'aliment ou du plat reconnu (ex: 'Blanc de poulet', 'Riz basmati', 'Haricots verts', 'Yaourt nature')" + ), + "weight" to Schema.double( + description = "Estimation visuelle réaliste de la quantité dans l'unité choisie (ex: 150 pour 150 g de poulet, 120 pour 120 g de riz, 1 pour 1 pomme en portion, 200 pour 200 ml de soupe)", + nullable = true + ), + "unit" to Schema.enumeration( + values = allowedUnitCodes, + description = "Unité : g (grammes pour les solides), ml (millilitres pour les boissons/soupes/sauces liquides) ou portion (pièces/unités)" + ), + "categories" to Schema.array( + items = Schema.enumeration(values = allowedCategoryCodes), + description = "1 à 4 codes de catégories alimentaires exactes (plusieurs catégories pour un plat composé comme lasagnes, quiche ou pizza)" + ) + ) + ) + + Schema.obj( + properties = mapOf( + "items" to Schema.array( + items = itemSchema, + description = "Liste dédupliquée des aliments et boissons visibles sur l'ensemble des photos du repas" + ) + ) + ) + } + + private val model by lazy { + val config = generationConfig { + responseMimeType = "application/json" + responseSchema = this@MealPhotoAnalyzer.responseSchema + temperature = 0.25f + } + Firebase.ai.generativeModel( + modelName = "gemini-3.8-flash", + generationConfig = config + ) + } + + suspend fun analyzePlatePhotos(bitmaps: List): Result> { + if (bitmaps.isEmpty()) { + return Result.failure( + IllegalStateException("Aucune photo d'assiette valide à analyser.") + ) + } + + val categoriesHelp = FoodCategory.entries.joinToString("\n") { "- ${it.code}: ${it.displayName}" } + val photoCountLabel = if (bitmaps.size == 1) "cette photo de repas" else "ces ${bitmaps.size} photos d'un même repas (ex: entrée, plat, dessert)" + + val prompt = """ +Analyse $photoCountLabel et identifie tous les aliments et boissons consommés. + +RÈGLES STRICTES : +1. Décompose l'assiette en aliments simples et lisibles en français (ex: "Filet de saumon", "Riz basmati", "Brocolis", "Salade verte", "Pain complet", "Yaourt nature"). Pour un plat composé indissociable (ex: "Lasagnes bolognaise", "Quiche lorraine", "Pizza margherita"), garde le nom du plat et assigne TOUTES ses catégories alimentaires principales dans `categories`. +2. Si plusieurs photos sont fournies, regroupe l'ensemble du repas SANS dupliquer un même aliment visible sous deux angles. +3. Estime visuellement la quantité (`weight`) de manière réaliste dans l'une de ces 3 unités exactes : + - "g" pour les aliments solides pesés (ex: 150 g de poulet, 180 g de pâtes cuites, 120 g de légumes, 40 g de pain) + - "ml" pour les liquides/soupes/boissons (ex: 250 ml de soupe, 150 ml de jus) + - "portion" pour les pièces/unités évidentes (ex: 1 pomme, 2 œufs, 1 yaourt, 1 tranche de tarte) +4. Choisis 1 à 4 catégories exactes dans `categories` parmi ces codes : +$categoriesHelp +5. Ignore les couverts, assiettes, verres d'eau plate et éléments non comestibles. Si aucun aliment n'est visible, renvoie une liste `items` vide. + """.trimIndent() + + return try { + val response = withTimeout(60_000L) { + model.generateContent( + content { + bitmaps.forEach { bmp -> image(bmp) } + text(prompt) + } + ) + } + val jsonText = response.text + if (jsonText.isNullOrBlank()) { + Result.failure( + IllegalStateException("L'analyse de l'assiette n'a renvoyé aucune donnée. Réessayez avec une photo plus nette.") + ) + } else { + val parsed = parsePlateJson(jsonText) + if (parsed.isEmpty()) { + Result.failure( + IllegalStateException("Aucun aliment n'a été reconnu sur cette photo. Essayez de cadrer l'assiette bien éclairée.") + ) + } else { + Result.success(parsed) + } + } + } catch (e: TimeoutCancellationException) { + Log.e(TAG, "Plate photo analysis timed out", e) + Result.failure( + IllegalStateException("L'analyse de la photo a dépassé le délai (60 s). Vérifiez votre connexion et réessayez.") + ) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.e(TAG, "Plate photo analysis failed", e) + Result.failure( + IllegalStateException( + e.localizedMessage ?: "Impossible d'analyser cette photo pour le moment." + ) + ) + } + } + + companion object { + private const val TAG = "MealPhotoAnalyzer" + + fun parsePlateJson(jsonString: String): List { + val root = try { + JSONObject(jsonString) + } catch (_: Exception) { + return emptyList() + } + val itemsArr = root.optJSONArray("items") ?: return emptyList() + val results = mutableListOf() + val seenNorms = mutableSetOf() + + for (i in 0 until itemsArr.length()) { + val obj = itemsArr.optJSONObject(i) ?: continue + val name = obj.optString("name", "").trim() + if (name.isBlank()) continue + + val norm = IngredientMatcher.normalize(name) + if (norm.isNotBlank() && !seenNorms.add(norm)) continue + + val weight = if (obj.has("weight") && !obj.isNull("weight")) { + obj.optDouble("weight", Double.NaN) + .takeIf { it.isFinite() && it > 0.0 } + ?.let { Math.round(it * 10.0) / 10.0 } + } else { + null + } + + val unit = FoodUnit.fromCode(obj.optString("unit", "g")) + + val rawCatsArr = obj.optJSONArray("categories") + val parsedCats = mutableListOf() + if (rawCatsArr != null) { + for (j in 0 until rawCatsArr.length()) { + FoodCategory.fromCode(rawCatsArr.optString(j))?.let { parsedCats.add(it) } + } + } + val resolvedCats = FoodCategory.sanitizeSelection(parsedCats) + .ifEmpty { FoodCategory.inferCategoriesFromName(name) } + + results.add( + RecognizedPlateFood( + id = "plate_${i}_${UUID.randomUUID().toString().take(6)}", + name = name, + weight = weight, + unit = unit, + categories = resolvedCats, + selected = true + ) + ) + } + return results + } + + /** + * Appends selected recognized foods into the existing plate list without overwriting + * already-entered items (deduplicated by normalized food name). + */ + fun mergeIntoExistingFoods( + existing: List, + recognized: List, + maxItems: Int = 30 + ): List { + val merged = existing.toMutableList() + val existingNorms = existing + .map { IngredientMatcher.normalize(it.name) } + .filter { it.isNotBlank() } + .toMutableSet() + + for (candidate in recognized) { + if (!candidate.selected) continue + val cleanName = candidate.name.trim() + if (cleanName.isBlank()) continue + if (merged.size >= maxItems) break + + val norm = IngredientMatcher.normalize(cleanName) + if (norm.isNotBlank() && !existingNorms.add(norm)) continue + + merged.add(candidate.toMealFoodItem()) + } + return merged + } + } +} diff --git a/app/src/main/java/com/example/ui/meal/MealEntrySheet.kt b/app/src/main/java/com/example/ui/meal/MealEntrySheet.kt index 02eeac6..02e34e9 100644 --- a/app/src/main/java/com/example/ui/meal/MealEntrySheet.kt +++ b/app/src/main/java/com/example/ui/meal/MealEntrySheet.kt @@ -1,6 +1,10 @@ package com.example.ui.meal +import android.Manifest +import android.app.Activity +import android.content.pm.PackageManager import android.net.Uri +import android.util.Log import androidx.activity.compose.BackHandler import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.PickVisualMediaRequest @@ -17,7 +21,10 @@ import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.CameraAlt import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.PhotoLibrary +import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.ExperimentalMaterial3Api @@ -25,11 +32,13 @@ import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.SheetValue import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.material3.rememberModalBottomSheetState +import androidx.core.content.ContextCompat import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf @@ -56,11 +65,14 @@ import com.example.data.model.FoodUnit import com.example.data.model.MealEntry import com.example.data.model.MealFoodItem import com.example.data.model.MealType +import com.example.domain.MealPhotoAnalysisUiState +import com.example.domain.MealPhotoAnalyzer import com.example.ui.common.UnsavedChangesDiscardDialog import com.example.ui.journal.components.DietaryGuideSheet import com.example.ui.meal.components.FoodItemBuilderSection import com.example.ui.meal.components.MealDateTimePicker import com.example.ui.meal.components.MealHungerSatietySection +import com.example.ui.meal.components.MealPhotoReviewDialog import com.example.ui.meal.components.MealPhotosSection import com.example.ui.meal.components.MealTypeSelector import com.example.util.ImageUtils @@ -264,6 +276,49 @@ fun MealEntrySheet( } var isProcessingPhoto by remember { mutableStateOf(false) } + var showPhotoSourceDialog by remember { mutableStateOf(false) } + var pendingCameraUriString by rememberSaveable { mutableStateOf(null) } + var showCameraAnalyzePrompt by remember { mutableStateOf(false) } + var plateAnalysisState by remember { mutableStateOf(MealPhotoAnalysisUiState.Idle) } + val mealPhotoAnalyzer = remember { MealPhotoAnalyzer() } + + val triggerPlateAnalysis: () -> Unit = { + val currentUris = photoUrisList.toList() + if (currentUris.isNotEmpty()) { + showCameraAnalyzePrompt = false + plateAnalysisState = MealPhotoAnalysisUiState.Analyzing + coroutineScope.launch { + val bitmaps = currentUris.mapNotNull { uriStr -> + ImageUtils.loadResizedBitmapForAi( + context = context, + sourceUri = Uri.parse(uriStr), + maxDimension = 1280 + ) + } + if (bitmaps.isEmpty()) { + plateAnalysisState = MealPhotoAnalysisUiState.Error( + "Impossible de lire les photos de l'assiette. Essayez d'en prendre une nouvelle." + ) + return@launch + } + try { + val result = mealPhotoAnalyzer.analyzePlatePhotos(bitmaps) + plateAnalysisState = result.fold( + onSuccess = { items -> MealPhotoAnalysisUiState.Preview(items) }, + onFailure = { err -> + MealPhotoAnalysisUiState.Error( + err.message ?: "Impossible d'analyser cette photo pour le moment." + ) + } + ) + } finally { + bitmaps.forEach { bmp -> + if (!bmp.isRecycled) bmp.recycle() + } + } + } + } + } val photoPickerLauncher = rememberLauncherForActivityResult( contract = ActivityResultContracts.PickVisualMedia() @@ -281,6 +336,63 @@ fun MealEntrySheet( } } + val takeMealPhotoLauncher = rememberLauncherForActivityResult( + contract = ActivityResultContracts.StartActivityForResult() + ) { result -> + val expectedUri = pendingCameraUriString?.let(Uri::parse) + pendingCameraUriString = null + if (result.resultCode == Activity.RESULT_OK) { + val resultData = result.data + isProcessingPhoto = true + coroutineScope.launch { + val resolvedUri = ImageUtils.resolveCapturedReceiptUri( + context = context, + expectedUri = expectedUri, + resultData = resultData + ) + val savedUri = resolvedUri?.let { ImageUtils.saveImageToPrivateStorage(context, it) } + if (savedUri != null && photoUrisList.size < 4) { + photoUrisList.add(savedUri) + newlyCapturedPhotos.add(savedUri) + showCameraAnalyzePrompt = true + } + isProcessingPhoto = false + } + } + } + + val launchMealCamera = { + try { + val uri = ImageUtils.createReceiptCaptureUri(context) + pendingCameraUriString = uri.toString() + val captureIntent = ImageUtils.buildCameraCaptureIntent(context, uri) + takeMealPhotoLauncher.launch(captureIntent) + } catch (e: Exception) { + pendingCameraUriString = null + Log.e("MealEntrySheet", "Failed to launch meal camera capture", e) + } + } + + val cameraPermissionLauncher = rememberLauncherForActivityResult( + contract = ActivityResultContracts.RequestPermission() + ) { granted -> + if (granted) { + launchMealCamera() + } + } + + val triggerMealCamera = { + val hasCameraPerm = ContextCompat.checkSelfPermission( + context, + Manifest.permission.CAMERA + ) == PackageManager.PERMISSION_GRANTED + if (hasCameraPerm) { + launchMealCamera() + } else { + cameraPermissionLauncher.launch(Manifest.permission.CAMERA) + } + } + val performDiscardAndDismiss = { showDiscardDialog = false newlyCapturedPhotos.forEach { photoUri -> @@ -366,14 +478,17 @@ fun MealEntrySheet( MealPhotosSection( photoUris = photoUrisList, isProcessingPhoto = isProcessingPhoto, - onAddPhotoClick = { - photoPickerLauncher.launch( - PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly) - ) - }, + isAnalyzingPlate = plateAnalysisState is MealPhotoAnalysisUiState.Analyzing, + showCameraAnalyzePrompt = showCameraAnalyzePrompt, + onDismissCameraAnalyzePrompt = { showCameraAnalyzePrompt = false }, + onAnalyzePlateClick = triggerPlateAnalysis, + onAddPhotoClick = { showPhotoSourceDialog = true }, onDeletePhotoClick = { photoUri -> photoUrisList.remove(photoUri) photosMarkedForDeletion.add(photoUri) + if (photoUrisList.isEmpty()) { + showCameraAnalyzePrompt = false + } } ) @@ -538,6 +653,96 @@ fun MealEntrySheet( ) } + if (showPhotoSourceDialog) { + AlertDialog( + onDismissRequest = { showPhotoSourceDialog = false }, + modifier = Modifier.testTag("meal_photo_source_dialog"), + title = { + Text( + text = "Ajouter une photo de l'assiette", + style = MaterialTheme.typography.titleLarge, + fontWeight = FontWeight.Bold + ) + }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { + Text( + text = "Prenez votre plat en photo ou choisissez depuis votre galerie pour reconnaître automatiquement les aliments.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + Button( + onClick = { + showPhotoSourceDialog = false + triggerMealCamera() + }, + shape = RoundedCornerShape(12.dp), + modifier = Modifier + .fillMaxWidth() + .testTag("meal_photo_source_camera_button") + ) { + Icon(Icons.Default.CameraAlt, contentDescription = null) + Spacer(modifier = Modifier.width(8.dp)) + Text("Prendre une photo") + } + OutlinedButton( + onClick = { + showPhotoSourceDialog = false + photoPickerLauncher.launch( + PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly) + ) + }, + shape = RoundedCornerShape(12.dp), + modifier = Modifier + .fillMaxWidth() + .testTag("meal_photo_source_gallery_button") + ) { + Icon(Icons.Default.PhotoLibrary, contentDescription = null) + Spacer(modifier = Modifier.width(8.dp)) + Text("Choisir depuis la galerie") + } + } + }, + confirmButton = {}, + dismissButton = { + TextButton(onClick = { showPhotoSourceDialog = false }) { + Text("Annuler") + } + } + ) + } + + MealPhotoReviewDialog( + state = plateAnalysisState, + onUpdateItem = { updated -> + val current = plateAnalysisState + if (current is MealPhotoAnalysisUiState.Preview) { + plateAnalysisState = current.copy( + items = current.items.map { if (it.id == updated.id) updated else it } + ) + } + }, + onRemoveItem = { idToRemove -> + val current = plateAnalysisState + if (current is MealPhotoAnalysisUiState.Preview) { + plateAnalysisState = current.copy( + items = current.items.filterNot { it.id == idToRemove } + ) + } + }, + onConfirmAdd = { recognizedItems -> + val merged = MealPhotoAnalyzer.mergeIntoExistingFoods( + existing = foodItemsList.toList(), + recognized = recognizedItems + ) + foodItemsList.clear() + foodItemsList.addAll(merged) + plateAnalysisState = MealPhotoAnalysisUiState.Idle + }, + onRetry = triggerPlateAnalysis, + onDismiss = { plateAnalysisState = MealPhotoAnalysisUiState.Idle } + ) + if (showDietaryGuide) { DietaryGuideSheet(onDismiss = { showDietaryGuide = false }) } diff --git a/app/src/main/java/com/example/ui/meal/components/MealPhotoReviewDialog.kt b/app/src/main/java/com/example/ui/meal/components/MealPhotoReviewDialog.kt new file mode 100644 index 0000000..439f7a9 --- /dev/null +++ b/app/src/main/java/com/example/ui/meal/components/MealPhotoReviewDialog.kt @@ -0,0 +1,337 @@ +package com.example.ui.meal.components + +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.AutoAwesome +import androidx.compose.material.icons.filled.DeleteOutline +import androidx.compose.material.icons.filled.ErrorOutline +import androidx.compose.material3.Button +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.Checkbox +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.FilterChip +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Dialog +import androidx.compose.ui.window.DialogProperties +import com.example.data.model.FoodCategory +import com.example.data.model.FoodUnit +import com.example.domain.MealPhotoAnalysisUiState +import com.example.domain.RecognizedPlateFood +import com.example.ui.common.FoodCategorySelectorRow + +@Composable +fun MealPhotoReviewDialog( + state: MealPhotoAnalysisUiState, + onUpdateItem: (RecognizedPlateFood) -> Unit, + onRemoveItem: (String) -> Unit, + onConfirmAdd: (List) -> Unit, + onRetry: () -> Unit, + onDismiss: () -> Unit +) { + if (state is MealPhotoAnalysisUiState.Idle) return + + Dialog( + onDismissRequest = { + if (state !is MealPhotoAnalysisUiState.Analyzing) { + onDismiss() + } + }, + properties = DialogProperties(usePlatformDefaultWidth = false) + ) { + Surface( + shape = RoundedCornerShape(24.dp), + color = MaterialTheme.colorScheme.surface, + tonalElevation = 6.dp, + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 24.dp) + .testTag("meal_photo_review_dialog") + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(20.dp), + verticalArrangement = Arrangement.spacedBy(12.dp) + ) { + when (state) { + MealPhotoAnalysisUiState.Idle -> Unit + + MealPhotoAnalysisUiState.Analyzing -> { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(vertical = 28.dp) + .testTag("meal_photo_analyzing_indicator"), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(14.dp) + ) { + CircularProgressIndicator() + Text( + text = "Reconnaissance de votre assiette...", + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold, + textAlign = TextAlign.Center + ) + Text( + text = "Identification des aliments, estimation des portions et des catégories alimentaires.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center + ) + } + } + + is MealPhotoAnalysisUiState.Error -> { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(vertical = 16.dp) + .testTag("meal_photo_analysis_error"), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(12.dp) + ) { + Icon( + imageVector = Icons.Default.ErrorOutline, + contentDescription = null, + tint = MaterialTheme.colorScheme.error, + modifier = Modifier.size(40.dp) + ) + Text( + text = "Analyse impossible", + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold + ) + Text( + text = state.message, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center + ) + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(10.dp) + ) { + OutlinedButton( + onClick = onDismiss, + modifier = Modifier.weight(1f) + ) { + Text("Fermer") + } + Button( + onClick = onRetry, + modifier = Modifier.weight(1f) + ) { + Text("Réessayer") + } + } + } + } + + is MealPhotoAnalysisUiState.Preview -> { + val selectedCount = state.items.count { it.selected && it.name.isNotBlank() } + + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp) + ) { + Icon( + imageVector = Icons.Default.AutoAwesome, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary + ) + Column { + Text( + text = "Aliments reconnus", + style = MaterialTheme.typography.titleLarge, + fontWeight = FontWeight.Bold + ) + Text( + text = "Vérifiez et ajustez avant d'ajouter à votre assiette", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + + LazyColumn( + modifier = Modifier + .fillMaxWidth() + .heightIn(max = 400.dp) + .testTag("meal_photo_review_list"), + verticalArrangement = Arrangement.spacedBy(10.dp) + ) { + items(state.items, key = { it.id }) { item -> + RecognizedPlateFoodCard( + item = item, + onUpdate = onUpdateItem, + onRemove = { onRemoveItem(item.id) } + ) + } + } + + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(10.dp) + ) { + OutlinedButton( + onClick = onDismiss, + shape = RoundedCornerShape(14.dp), + modifier = Modifier.weight(0.4f) + ) { + Text("Annuler") + } + Button( + onClick = { onConfirmAdd(state.items) }, + enabled = selectedCount > 0, + shape = RoundedCornerShape(14.dp), + modifier = Modifier + .weight(0.6f) + .testTag("confirm_plate_foods_button") + ) { + Text("Ajouter ($selectedCount)") + } + } + } + } + } + } + } +} + +@Composable +private fun RecognizedPlateFoodCard( + item: RecognizedPlateFood, + onUpdate: (RecognizedPlateFood) -> Unit, + onRemove: () -> Unit +) { + var weightText by remember(item.id) { + mutableStateOf( + item.weight?.let { w -> + if (w % 1.0 == 0.0) w.toInt().toString() else w.toString() + }.orEmpty() + ) + } + + Card( + shape = RoundedCornerShape(16.dp), + colors = CardDefaults.cardColors( + containerColor = if (item.selected) { + MaterialTheme.colorScheme.surface + } else { + MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.35f) + } + ), + border = BorderStroke( + width = 1.dp, + color = if (item.selected) { + MaterialTheme.colorScheme.outlineVariant + } else { + MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.3f) + } + ), + modifier = Modifier.fillMaxWidth() + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(10.dp), + verticalArrangement = Arrangement.spacedBy(8.dp) + ) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically + ) { + Checkbox( + checked = item.selected, + onCheckedChange = { onUpdate(item.copy(selected = it)) } + ) + OutlinedTextField( + value = item.name, + onValueChange = { onUpdate(item.copy(name = it)) }, + placeholder = { Text("Nom de l'aliment") }, + singleLine = true, + shape = RoundedCornerShape(12.dp), + modifier = Modifier.weight(1f) + ) + IconButton(onClick = onRemove) { + Icon( + imageVector = Icons.Default.DeleteOutline, + contentDescription = "Retirer ${item.name}", + tint = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(6.dp), + verticalAlignment = Alignment.CenterVertically + ) { + OutlinedTextField( + value = weightText, + onValueChange = { raw -> + weightText = raw + val parsed = raw.replace(',', '.').toDoubleOrNull()?.takeIf { it > 0.0 } + onUpdate(item.copy(weight = parsed)) + }, + label = { Text("Qté") }, + singleLine = true, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal), + shape = RoundedCornerShape(12.dp), + modifier = Modifier.width(88.dp) + ) + + Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) { + FoodUnit.entries.forEach { unit -> + FilterChip( + selected = item.unit == unit, + onClick = { onUpdate(item.copy(unit = unit)) }, + label = { Text(unit.label) } + ) + } + } + } + + FoodCategorySelectorRow( + selectedCategories = item.categories, + onCategoryToggled = { toggled -> + val updatedCats = FoodCategory.toggleCategorySelection(item.categories, toggled) + onUpdate(item.copy(categories = updatedCats)) + } + ) + } + } +} diff --git a/app/src/main/java/com/example/ui/meal/components/MealPhotosSection.kt b/app/src/main/java/com/example/ui/meal/components/MealPhotosSection.kt index 9897232..dffa12b 100644 --- a/app/src/main/java/com/example/ui/meal/components/MealPhotosSection.kt +++ b/app/src/main/java/com/example/ui/meal/components/MealPhotosSection.kt @@ -1,27 +1,36 @@ package com.example.ui.meal.components +import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.AddAPhoto +import androidx.compose.material.icons.filled.AutoAwesome import androidx.compose.material.icons.filled.Close +import androidx.compose.material3.Button +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.FilledTonalButton import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -29,6 +38,7 @@ import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.testTag +import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import coil.compose.AsyncImage @@ -38,6 +48,10 @@ fun MealPhotosSection( isProcessingPhoto: Boolean, onAddPhotoClick: () -> Unit, onDeletePhotoClick: (String) -> Unit, + isAnalyzingPlate: Boolean = false, + showCameraAnalyzePrompt: Boolean = false, + onDismissCameraAnalyzePrompt: () -> Unit = {}, + onAnalyzePlateClick: (() -> Unit)? = null, modifier: Modifier = Modifier ) { Column(modifier = modifier.fillMaxWidth()) { @@ -129,5 +143,97 @@ fun MealPhotosSection( } } } + + if (photoUris.isNotEmpty() && onAnalyzePlateClick != null) { + Spacer(modifier = Modifier.height(10.dp)) + + if (showCameraAnalyzePrompt && !isAnalyzingPlate) { + Card( + shape = RoundedCornerShape(14.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.55f) + ), + border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary.copy(alpha = 0.35f)), + modifier = Modifier + .fillMaxWidth() + .testTag("camera_analyze_prompt_card") + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(12.dp), + verticalArrangement = Arrangement.spacedBy(8.dp) + ) { + Text( + text = "Reconnaître les aliments de cette assiette ?", + style = MaterialTheme.typography.titleSmall, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.onPrimaryContainer + ) + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp) + ) { + TextButton( + onClick = onDismissCameraAnalyzePrompt, + modifier = Modifier.weight(0.4f) + ) { + Text("Plus tard") + } + Button( + onClick = { + onDismissCameraAnalyzePrompt() + onAnalyzePlateClick() + }, + shape = RoundedCornerShape(10.dp), + modifier = Modifier + .weight(0.6f) + .testTag("camera_analyze_now_button") + ) { + Icon( + imageVector = Icons.Default.AutoAwesome, + contentDescription = null, + modifier = Modifier.size(16.dp) + ) + Spacer(modifier = Modifier.width(6.dp)) + Text("Analyser") + } + } + } + } + } else { + FilledTonalButton( + onClick = onAnalyzePlateClick, + enabled = !isAnalyzingPlate && !isProcessingPhoto, + shape = RoundedCornerShape(12.dp), + modifier = Modifier + .fillMaxWidth() + .testTag("analyze_plate_button") + ) { + if (isAnalyzingPlate) { + CircularProgressIndicator( + modifier = Modifier.size(16.dp), + strokeWidth = 2.dp + ) + Spacer(modifier = Modifier.width(8.dp)) + Text("Analyse de l'assiette...") + } else { + Icon( + imageVector = Icons.Default.AutoAwesome, + contentDescription = null, + modifier = Modifier.size(18.dp) + ) + Spacer(modifier = Modifier.width(8.dp)) + Text( + text = if (photoUris.size == 1) { + "Analyser l'assiette (IA)" + } else { + "Analyser les ${photoUris.size} photos (IA)" + } + ) + } + } + } + } } } diff --git a/app/src/test/java/com/example/MealPhotoAnalyzerTest.kt b/app/src/test/java/com/example/MealPhotoAnalyzerTest.kt new file mode 100644 index 0000000..524ab37 --- /dev/null +++ b/app/src/test/java/com/example/MealPhotoAnalyzerTest.kt @@ -0,0 +1,147 @@ +package com.example + +import com.example.data.model.FoodCategory +import com.example.data.model.FoodUnit +import com.example.data.model.MealFoodItem +import com.example.domain.MealPhotoAnalyzer +import com.example.domain.RecognizedPlateFood +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [36]) +class MealPhotoAnalyzerTest { + + @Test + fun parsePlateJson_parsesMultiCategoryDishesWeightsAndDeduplicates() { + val sampleJson = """ + { + "items": [ + { + "name": "Lasagnes bolognaise", + "weight": 320, + "unit": "g", + "categories": ["STARCH", "PROTEIN", "VEGETABLE", "CHEESE"] + }, + { + "name": "Salade verte", + "weight": 80, + "unit": "g", + "categories": ["VEGETABLE"] + }, + { + "name": "salade verte", + "weight": 50, + "unit": "g", + "categories": ["VEGETABLE"] + }, + { + "name": "Pomme", + "weight": 1, + "unit": "portion", + "categories": ["FRUIT"] + }, + { + "name": " ", + "weight": 100, + "unit": "g", + "categories": ["OTHER"] + } + ] + } + """.trimIndent() + + val parsed = MealPhotoAnalyzer.parsePlateJson(sampleJson) + assertEquals(3, parsed.size) + + assertEquals("Lasagnes bolognaise", parsed[0].name) + assertEquals(320.0, parsed[0].weight!!, 0.01) + assertEquals(FoodUnit.G, parsed[0].unit) + assertEquals( + listOf(FoodCategory.STARCH, FoodCategory.PROTEIN, FoodCategory.VEGETABLE, FoodCategory.CHEESE), + parsed[0].categories + ) + + assertEquals("Salade verte", parsed[1].name) + assertEquals(80.0, parsed[1].weight!!, 0.01) + + assertEquals("Pomme", parsed[2].name) + assertEquals(1.0, parsed[2].weight!!, 0.01) + assertEquals(FoodUnit.PORTION, parsed[2].unit) + assertEquals(listOf(FoodCategory.FRUIT), parsed[2].categories) + } + + @Test + fun parsePlateJson_handlesMalformedJsonAndInvalidWeightsGracefully() { + assertTrue(MealPhotoAnalyzer.parsePlateJson("not json").isEmpty()) + + val jsonWithBadWeight = """ + { + "items": [ + { + "name": "Pain complet", + "weight": -10, + "unit": "g", + "categories": [] + } + ] + } + """.trimIndent() + + val parsed = MealPhotoAnalyzer.parsePlateJson(jsonWithBadWeight) + assertEquals(1, parsed.size) + assertNull(parsed[0].weight) + assertEquals(listOf(FoodCategory.BREAD), parsed[0].categories) + } + + @Test + fun mergeIntoExistingFoods_preservesExistingSkipsDuplicatesAndUnselected() { + val existing = listOf( + MealFoodItem( + name = "Riz basmati", + weight = 150.0, + unit = FoodUnit.G, + category = FoodCategory.STARCH, + categories = listOf(FoodCategory.STARCH) + ) + ) + + val recognized = listOf( + RecognizedPlateFood( + name = "riz basmati", + weight = 200.0, + unit = FoodUnit.G, + categories = listOf(FoodCategory.STARCH), + selected = true + ), + RecognizedPlateFood( + name = "Blanc de poulet", + weight = 140.0, + unit = FoodUnit.G, + categories = listOf(FoodCategory.PROTEIN), + selected = true + ), + RecognizedPlateFood( + name = "Sauce soja", + weight = 15.0, + unit = FoodUnit.ML, + categories = listOf(FoodCategory.FAT_SEASONING), + selected = false + ) + ) + + val merged = MealPhotoAnalyzer.mergeIntoExistingFoods(existing, recognized) + assertEquals(2, merged.size) + // Existing item preserved untouched + assertEquals("Riz basmati", merged[0].name) + assertEquals(150.0, merged[0].weight!!, 0.01) + // Selected new item added + assertEquals("Blanc de poulet", merged[1].name) + assertEquals(140.0, merged[1].weight!!, 0.01) + } +}