Offline gym log for Android. No account, no ads, no internet.
Dart androidbodybuildingdartexercisesf-droidfitnessfluttergymgym-apphealthprivacyself-hostedworkoutworkout-appworkout-tracker
Fill in a new food with an AI
InlitX9b757387fe23
diff --git a/lib/screens/nutrition/ai.dart b/lib/screens/nutrition/ai.dartindex db81856..56db83f 100644--- a/lib/screens/nutrition/ai.dart+++ b/lib/screens/nutrition/ai.dart@@ -695,3 +695,225 @@ class _MealAiSheetState extends State<_MealAiSheet> {]);}}++Future<AiFoodPick?> showFoodAiSheet(BuildContext context) =>+ _sheet<AiFoodPick?>(context, (_) => const _FoodAiSheet());++class _FoodAiSheet extends StatefulWidget {+ const _FoodAiSheet();++ @override+ State<_FoodAiSheet> createState() => _FoodAiSheetState();+}++class _FoodAiSheetState extends State<_FoodAiSheet> {+ final _answer = TextEditingController();+ int _step = 0;+ bool _showText = false;+ bool _failed = false;++ String get _prompt => buildFoodAiPrompt(languageNameOf(appLanguage));++ @override+ void dispose() {+ _answer.dispose();+ super.dispose();+ }++ Future<void> _copy() async {+ await Clipboard.setData(ClipboardData(text: _prompt));+ if (!mounted) return;+ HapticFeedback.lightImpact();+ showNotchToast(context, t.mealAiCopied,+ subtitle: t.mealAiCopiedHint, icon: PhosphorIconsFill.copy, accent: context.gc.sage);+ setState(() => _step = 1);+ }++ Future<void> _paste() async {+ final data = await Clipboard.getData(Clipboard.kTextPlain);+ final text = data?.text;+ if (text == null || text.trim().isEmpty || !mounted) return;+ _answer.text = text;+ _fill();+ }++ Future<void> _file() async {+ final text = await pickTextFile();+ if (text == null || !mounted) return;+ _answer.text = text;+ _fill();+ }++ void _fill() {+ final raw = _answer.text;+ if (raw.trim().isEmpty) return;+ FocusScope.of(context).unfocus();+ final pick = parseFoodAi(raw);+ if (pick == null) {+ HapticFeedback.heavyImpact();+ setState(() => _failed = true);+ return;+ }+ HapticFeedback.selectionClick();+ Navigator.of(context).pop(pick);+ }++ Future<void> _copyFix() async {+ await Clipboard.setData(const ClipboardData(text: mealAiRetrySentence));+ if (!mounted) return;+ showNotchToast(context, t.copiedDone, icon: PhosphorIconsFill.copy, accent: context.gc.sage);+ }++ Widget _chipButton(GymColors gc, IconData icon, String label, VoidCallback onTap, {Color? bg}) => Pressable(+ onTap: onTap,+ scale: 0.95,+ child: Container(+ padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),+ decoration: BoxDecoration(color: bg ?? gc.bgRaised2, borderRadius: BorderRadius.circular(100)),+ child: Row(mainAxisSize: MainAxisSize.min, children: [+ Icon(icon, size: 15, color: gc.text),+ const SizedBox(width: 7),+ Text(label, style: AppTheme.f(12.5, weight: FontWeight.w700, color: gc.text)),+ ]),+ ),+ );++ Widget _askPage(GymColors gc) {+ return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [+ Text(t.foodAiHow, style: AppTheme.s(13.5, color: gc.textSecondary, height: 1.45)),+ const SizedBox(height: 10),+ Text(t.foodAiCheck, style: AppTheme.s(13.5, color: gc.textSecondary, height: 1.45)),+ const SizedBox(height: 20),+ PrimaryButton(label: t.mealAiCopy, onTap: _copy),+ const SizedBox(height: 4),+ Pressable(+ onTap: () => setState(() => _showText = !_showText),+ scale: 0.97,+ child: Padding(+ padding: const EdgeInsets.symmetric(vertical: 12),+ child: Center(+ child: Text(_showText ? t.mealAiHideText : t.mealAiShowText,+ style: AppTheme.f(12.5, weight: FontWeight.w700, color: gc.accent)),+ ),+ ),+ ),+ AnimatedSize(+ duration: const Duration(milliseconds: 260),+ curve: Curves.easeOutCubic,+ alignment: Alignment.topCenter,+ child: _showText+ ? Container(+ padding: const EdgeInsets.all(14),+ decoration: BoxDecoration(color: gc.bgRaised2, borderRadius: BorderRadius.circular(16)),+ child: Ltr(+ child: SelectableText(_prompt,+ style: TextStyle(fontFamily: 'monospace', fontSize: 11, color: gc.textSecondary, height: 1.4)),+ ),+ )+ : const SizedBox(width: double.infinity),+ ),+ ]);+ }++ Widget _pastePage(GymColors gc) {+ final empty = _answer.text.trim().isEmpty;+ return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [+ TextField(+ controller: _answer,+ minLines: 5,+ maxLines: 9,+ keyboardType: TextInputType.multiline,+ onChanged: (_) => setState(() => _failed = false),+ style: AppTheme.f(12.5, weight: FontWeight.w500, color: gc.text, height: 1.35),+ cursorColor: gc.accent,+ decoration: InputDecoration(+ hintText: t.mealAiPasteHint,+ hintStyle: AppTheme.f(14, weight: FontWeight.w500, color: gc.textTertiary),+ filled: true,+ fillColor: gc.bgRaised2,+ contentPadding: const EdgeInsets.all(16),+ border: OutlineInputBorder(borderRadius: BorderRadius.circular(16), borderSide: BorderSide.none),+ ),+ ),+ const SizedBox(height: 10),+ Row(children: [+ _chipButton(gc, PhosphorIconsRegular.clipboardText, t.pasteAction, _paste),+ const SizedBox(width: 8),+ _chipButton(gc, PhosphorIconsRegular.fileArrowUp, t.chooseFile, _file),+ ]),+ const SizedBox(height: 16),+ PrimaryButton(+ label: t.foodAiFill,+ bg: empty ? gc.bgRaised2 : gc.ember,+ fg: empty ? gc.textTertiary : gc.onEmber,+ onTap: _fill,+ ),+ AnimatedSize(+ duration: const Duration(milliseconds: 220),+ curve: Curves.easeOutCubic,+ alignment: Alignment.topCenter,+ child: !_failed+ ? const SizedBox(width: double.infinity)+ : Padding(+ padding: const EdgeInsets.only(top: 22),+ child: Container(+ padding: const EdgeInsets.all(16),+ decoration: BoxDecoration(+ color: gc.bgRaised2,+ borderRadius: BorderRadius.circular(16),+ border: Border.all(color: gc.warn.withValues(alpha: 0.55)),+ ),+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [+ Text(t.mealAiUnreadable, style: AppTheme.f(14, weight: FontWeight.w700, color: gc.text)),+ const SizedBox(height: 6),+ Text(t.mealAiUnreadableHint,+ style: AppTheme.f(12.5, weight: FontWeight.w500, color: gc.textSecondary, height: 1.45)),+ const SizedBox(height: 12),+ _chipButton(gc, PhosphorIconsRegular.copy, t.mealAiCopyFix, _copyFix, bg: gc.bgRaised),+ ]),+ ),+ ),+ ),+ ]);+ }++ @override+ Widget build(BuildContext context) {+ final gc = context.gc;+ return _sheetFrame(context, [+ SheetTitle(t.foodAiTitle, subtitle: t.mealAiSubtitle),+ const SizedBox(height: 10),+ Center(child: BetaTag(t.sectionBeta, small: true)),+ const SizedBox(height: 16),+ Center(+ child: SegToggle([+ SegOption('1 · ${t.mealAiStepAsk}', _step == 0, () => setState(() => _step = 0)),+ SegOption('2 · ${t.mealAiStepPaste}', _step == 1, () => setState(() => _step = 1)),+ ], hPad: 18, vPad: 9, fontSize: 13),+ ),+ const SizedBox(height: 20),+ AnimatedSize(+ duration: const Duration(milliseconds: 340),+ curve: Curves.easeOutCubic,+ alignment: Alignment.topCenter,+ child: AnimatedSwitcher(+ duration: const Duration(milliseconds: 240),+ switchInCurve: Curves.easeOutCubic,+ switchOutCurve: Curves.easeInCubic,+ layoutBuilder: (current, previous) => Stack(+ alignment: Alignment.topCenter,+ children: [+ for (final p in previous) Positioned(top: 0, left: 0, right: 0, child: p),+ ?current,+ ],+ ),+ transitionBuilder: (child, a) => FadeTransition(opacity: a, child: child),+ child: KeyedSubtree(+ key: ValueKey(_step),+ child: _step == 0 ? _askPage(gc) : _pastePage(gc),+ ),+ ),+ ),+ ]);+ }+}diff --git a/lib/screens/nutrition/food.dart b/lib/screens/nutrition/food.dartindex fabf8c4..9630dfd 100644--- a/lib/screens/nutrition/food.dart+++ b/lib/screens/nutrition/food.dart@@ -1941,8 +1941,9 @@ class _FoodEditorState extends State<_FoodEditor> with _StickerDrafts {late final _name = TextEditingController(text: _base?.name ?? widget.name.trim());late final _serving = TextEditingController(text: _base?.serving ?? '');late final _grams = TextEditingController(text: _seed((_base?.grams ?? 0) / _k));+ late bool _liquid = _base?.liquid ?? false;- double get _k => fit.isLb ? _ozOf(_base?.liquid ?? false) : 1;+ double get _k => fit.isLb ? _ozOf(_liquid) : 1;late final _kcal = TextEditingController(text: _seed(fit.energyOf(_base?.macros.kcal ?? 0).toDouble()));late final _fi = TextEditingController(text: _seed(_base?.macros.fiber ?? 0));late final _su = TextEditingController(text: _seed(_base?.macros.sugar ?? 0));@@ -1997,7 +1998,7 @@ class _FoodEditorState extends State<_FoodEditor> with _StickerDrafts {photo: _photo,serving: _serving.text,grams: grams,- liquid: _base?.liquid ?? false,+ liquid: _liquid,cookedYield: _base?.cookedYield ?? 0,macros: _withSource(_keepDetail(_per100 ? typed * (grams / 100) : typed)),cat: _cat,@@ -2015,6 +2016,37 @@ class _FoodEditorState extends State<_FoodEditor> with _StickerDrafts {if (meal != null) showLogFoodSheet(context, saved, meal);}+ Future<void> _fromAi() async {+ final pick = await showFoodAiSheet(context);+ if (pick == null || !mounted) return;+ final f = pick.food;+ String v(double? x) => _seed(x ?? 0);+ setState(() {+ _liquid = pick.liquid;+ if (f.name.isNotEmpty) _name.text = f.name;+ if (pick.serving.isNotEmpty) _serving.text = pick.serving;+ final g = f.grams;+ _grams.text = g == null || g <= 0 ? '' : _seed(g / _k);+ _per100 = f.per100 || g == null;+ _kcal.text = f.kcal == null ? '' : _seed(fit.energyOf(f.kcal!).toDouble());+ _p.text = v(f.protein);+ _c.text = v(f.carbs);+ _f.text = v(f.fat);+ _fi.text = v(f.fiber);+ _su.text = v(f.sugar);+ _na.text = v(f.sodium);+ _chol.text = v(f.chol);+ _sat.text = v(f.sat);+ _trans.text = v(f.trans);+ _mono.text = v(f.mono);+ _poly.text = v(f.poly);+ final extra = [f.fiber, f.sugar, f.sodium, f.chol, f.sat, f.trans, f.mono, f.poly];+ if (extra.any((x) => (x ?? 0) > 0)) _extras = true;+ });+ showNotchToast(context, t.foodAiFilled,+ subtitle: t.foodAiFilledHint, icon: PhosphorIconsFill.checkCircle, accent: context.gc.sage);+ }+void _setPer100(bool on) {if (on == _per100) return;HapticFeedback.selectionClick();@@ -2179,6 +2211,21 @@ class _FoodEditorState extends State<_FoodEditor> with _StickerDrafts {: t.newFood,subtitle: widget.from != null ? t.editLibraryHint : null),const SizedBox(height: 16),+ if (widget.food == null && widget.from == null) ...[+ _FoodRow(+ leading: Container(+ width: 38,+ height: 38,+ decoration: BoxDecoration(color: gc.accent.withValues(alpha: 0.14), shape: BoxShape.circle),+ child: Icon(PhosphorIconsRegular.sparkle, size: 17, color: gc.accent),+ ),+ title: t.foodAiRow,+ detail: t.foodAiRowHint,+ badge: BetaTag(t.sectionBeta, small: true),+ onTap: _fromAi,+ ),+ const SizedBox(height: 12),+ ],Center(child: Pressable(onTap: _working ? () {} : _pick,@@ -2226,7 +2273,7 @@ class _FoodEditorState extends State<_FoodEditor> with _StickerDrafts {Expanded(flex: 2,child: _NumberField(- label: t.servingWeight, controller: _grams, color: gc.textTertiary, suffix: _amtUnit(_base?.liquid ?? false)),+ label: t.servingWeight, controller: _grams, color: gc.textTertiary, suffix: _amtUnit(_liquid)),),]),const SizedBox(height: 14),@@ -2236,12 +2283,12 @@ class _FoodEditorState extends State<_FoodEditor> with _StickerDrafts {const SizedBox(height: 14),Row(children: [Expanded(- child: Text(_per100 ? t.per100(_unitOf(_base?.liquid ?? false)).toUpperCase() : t.perServing,+ child: Text(_per100 ? t.per100(_unitOf(_liquid)).toUpperCase() : t.perServing,style: AppTheme.f(10.5, weight: FontWeight.w700, color: gc.textTertiary, letterSpacing: 1.4)),),SegToggle([SegOption(t.perServingShort, !_per100, () => _setPer100(false)),- SegOption('100 ${_unitOf(_base?.liquid ?? false)}', _per100, () => _setPer100(true)),+ SegOption('100 ${_unitOf(_liquid)}', _per100, () => _setPer100(true)),], hPad: 11, vPad: 5, fontSize: 11.5),]),const SizedBox(height: 8),@@ -2320,7 +2367,7 @@ class _FoodEditorState extends State<_FoodEditor> with _StickerDrafts {onChanged: (v) => setState(() => _water = v),suggest: () {final g = double.tryParse(_grams.text.replaceAll(',', '.')) ?? 0;- final ml = (_base?.liquid ?? false) && g > 0 ? (g * _k).round() : 0;+ final ml = _liquid && g > 0 ? (g * _k).round() : 0;return ml > 0 ? ml : (_shake ? 400 : 250);},),diff --git a/lib/services/meal_ai.dart b/lib/services/meal_ai.dartindex 1bf1543..f3eabde 100644--- a/lib/services/meal_ai.dart+++ b/lib/services/meal_ai.dart@@ -1107,3 +1107,104 @@ String buildMealAiPrompt(MealAiBrief b) {];return lines.join('\n');}++const kFoodAiTag = 'gymmane-food';++class AiFoodPick {+ const AiFoodPick(this.food, {this.serving = '', this.liquid = false});++ final AiFood food;+ final String serving;+ final bool liquid;+}++const _servingNameKeys = ['servingname', 'servinglabel', 'portionname', 'serving', 'portion', 'racion', 'porcion', 'nombreracion'];+const _liquidKeys = ['liquid', 'drink', 'isliquid', 'liquido', 'bebida'];+const _saltKeys = ['salt', 'sal', 'saltg', 'salg'];+const _foodWrapKeys = ['food', 'item', 'product', 'alimento', 'producto', 'result', 'data'];++Map? _foodNode(Object? v, int depth) {+ if (depth > 5) return null;+ if (v is List) {+ for (final e in v) {+ final hit = _foodNode(e, depth + 1);+ if (hit != null) return hit;+ }+ return null;+ }+ if (v is! Map) return null;+ if (_isItem(v)) return v;+ final nm = _norm(v);+ for (final k in _foodWrapKeys) {+ final hit = _foodNode(nm[k], depth + 1);+ if (hit != null) return hit;+ }+ for (final e in nm.values) {+ final hit = _foodNode(e, depth + 1);+ if (hit != null) return hit;+ }+ return null;+}++AiFoodPick? parseFoodAi(String raw) {+ final text = _clean(raw);+ for (final (v, _) in [..._candidates(text, '{'), ..._candidates(text, '[')]) {+ final node = _foodNode(v, 0);+ if (node == null) continue;+ final food = _food(node, '');+ if (food == null || !food.hasMacros) continue;+ final nm = _norm(node);+ final per = _macroSource(nm, per100: true);+ final src = per.isNotEmpty ? per : _macroSource(nm, per100: false);+ if (food.sodium == null) {+ final salt = _numOf(_first({...nm, ...src}, _saltKeys));+ if (salt != null && salt > 0) food.sodium = salt * 400;+ }+ final label = _first(nm, _servingNameKeys);+ final liquid = _first(nm, _liquidKeys);+ final serving = label is String ? label.replaceAll(RegExp(r'\s+'), ' ').trim() : '';+ return AiFoodPick(+ food,+ serving: serving.length > 40 ? serving.substring(0, 40).trim() : serving,+ liquid: liquid == true || food.liquid,+ );+ }+ return null;+}++String buildFoodAiPrompt(String language) {+ final lines = <String>[+ 'You are the nutrition assistant of GymMane, an offline fitness app. A program, not a person, will read your reply, so the format below is strict.',+ '',+ 'REQUEST',+ '- Together with this message I give you a nutrition label, a photo or screenshot of a product, a link to it, or just the name of a food. Turn it into ONE food for my food list.',+ '- If nothing came with this message, reply only with one short sentence asking me for the label, a photo, a link or the name of the food, and wait.',+ '- When there is a label, copy its values exactly. Only when there is no label, use typical values for that food.',+ '- Write the food name in $language. Keep the brand if the product has one.',+ '',+ 'FORMAT RULES (follow every one)',+ '1. Reply with exactly one JSON object inside one ```json code block. Nothing before it, nothing after it.',+ '2. Use exactly the keys shown in the example. Keep "gymmane" as "$kFoodAiTag" and "v" as 1.',+ '3. "per100" holds the values per 100 g (per 100 ml for drinks): "kcal", plus "protein", "carbs" and "fat" in grams. Optional, only when you know them: "fiber", "sugar", "saturated", "trans", "monounsaturated" and "polyunsaturated" in grams, "sodium" and "cholesterol" in milligrams. If the label gives salt instead of sodium, sodium in mg is salt in g x 400. Leave a key out when you do not know it, never write 0 for unknown.',+ '4. Plain numbers only: dot as decimal separator, no units, no quotes.',+ '5. "serving_name" is the serving the label uses, short (for example "1 bar" or "1 glass"), and "grams" is the weight of that serving in grams (millilitres for drinks). With no serving, use "100 g" and 100.',+ '6. "liquid" is true for drinks and false for everything else.',+ '7. Before you reply, check that the JSON is valid and has "name", "grams" and "per100" with "kcal", "protein", "carbs" and "fat".',+ '',+ 'EXAMPLE OF A VALID REPLY (the numbers are only an illustration)',+ '```json',+ '{',+ ' "gymmane": "$kFoodAiTag",',+ ' "v": 1,',+ ' "food": {',+ ' "name": "Greek yogurt 2%",',+ ' "serving_name": "1 pot",',+ ' "grams": 170,',+ ' "liquid": false,',+ ' "per100": {"kcal": 73, "protein": 9.9, "carbs": 3.9, "fat": 2, "sugar": 3.6, "saturated": 1.3, "sodium": 36}',+ ' }',+ '}',+ '```',+ ];+ return lines.join('\n');+}diff --git a/test/meal_ai_test.dart b/test/meal_ai_test.dartindex 45b021e..2e30385 100644--- a/test/meal_ai_test.dart+++ b/test/meal_ai_test.dart@@ -463,4 +463,40 @@ void main() {expect(p, contains('leave the key out otherwise'));});});-}++ group('alimento con IA', () {+ test('lee la respuesta con el formato pedido y los valores por 100 g', () {+ final pick = parseFoodAi('Aquí tienes:\n```json\n{"gymmane": "gymmane-food", "v": 1, "food": {"name": "Yogur griego Hacendado", "serving_name": "1 tarrina", "grams": 125, "liquid": false, "per100": {"kcal": 97, "protein": 6.5, "carbs": 3.4, "fat": 6.4, "sugar": 3.4, "saturated": 4.2, "sodium": 40}}}\n```');+ expect(pick, isNotNull);+ final f = pick!.food;+ expect(f.name, 'Yogur griego Hacendado');+ expect(pick.serving, '1 tarrina');+ expect(pick.liquid, isFalse);+ expect(f.grams, 125);+ expect(f.per100, isTrue);+ expect([f.kcal, f.protein, f.carbs, f.fat, f.sugar, f.sat, f.sodium], [97, 6.5, 3.4, 6.4, 3.4, 4.2, 40]);+ });++ test('pasa la sal a sodio y entiende bebidas', () {+ final pick = parseFoodAi('{"producto": {"nombre": "Bebida de avena", "racion": "1 vaso", "ml": 250, "bebida": true, "per100ml": {"calorias": 46, "proteinas": 0.4, "hidratos": 7.6, "grasas": 1.5, "sal": 0.1}}}');+ expect(pick, isNotNull);+ expect(pick!.liquid, isTrue);+ expect(pick.serving, '1 vaso');+ expect(pick.food.grams, 250);+ expect(pick.food.sodium, closeTo(40, 0.001));+ });++ test('sin valores no rellena nada', () {+ expect(parseFoodAi('Mándame la etiqueta, una foto, un enlace o el nombre del alimento.'), isNull);+ expect(parseFoodAi('{"food": {"name": "Pan"}}'), isNull);+ });++ test('la petición pide un solo alimento por 100 g en el idioma de la app y su ejemplo se lee bien', () {+ final p = buildFoodAiPrompt('Spanish');+ expect(p, contains('ONE food'));+ expect(p, contains('"per100"'));+ expect(p, contains('in Spanish'));+ expect(parseFoodAi(p), isNotNull);+ });+ });+}\ No newline at end of file