Skip to content

Offline gym log for Android. No account, no ads, no internet.

Read label fields and improve nutrition AI answers

InlitX9ef7c7ebe14e
diff --git a/lib/models/nutrition.dart b/lib/models/nutrition.dart
index bcaf1d3..8840295 100644
--- a/lib/models/nutrition.dart
+++ b/lib/models/nutrition.dart
@@ -58,6 +58,7 @@ class Macros {
this.fiber = 0,
this.sugar = 0,
this.sodium = 0,
+ this.chol = 0,
this.animal = 0,
this.sat = 0,
this.trans = 0,
@@ -74,6 +75,7 @@ class Macros {
final double fiber;
final double sugar;
final double sodium;
+ final double chol;
final double animal;
final double sat;
final double trans;
@@ -98,6 +100,7 @@ class Macros {
fiber: fiber + o.fiber,
sugar: sugar + o.sugar,
sodium: sodium + o.sodium,
+ chol: chol + o.chol,
animal: animal + o.animal,
sat: sat + o.sat,
trans: trans + o.trans,
@@ -115,6 +118,7 @@ class Macros {
fiber: fiber * k,
sugar: sugar * k,
sodium: sodium * k,
+ chol: chol * k,
animal: animal * k,
sat: sat * k,
trans: trans * k,
@@ -126,7 +130,7 @@ class Macros {
bool get isEmpty => kcal <= 0 && protein <= 0 && carbs <= 0 && fat <= 0;
- bool get hasExtras => fiber > 0 || sugar > 0 || sodium > 0;
+ bool get hasExtras => fiber > 0 || sugar > 0 || sodium > 0 || chol > 0;
bool get hasFatTypes => sat > 0 || trans > 0 || mono > 0 || poly > 0;
@@ -159,6 +163,7 @@ class Macros {
if (fiber > 0) 'fi': fiber,
if (sugar > 0) 'su': sugar,
if (sodium > 0) 'na': sodium,
+ if (chol > 0) 'ch': chol,
if (animal > 0) 'an': animal,
if (sat > 0) 'sa': sat,
if (trans > 0) 'tf': trans,
@@ -181,6 +186,7 @@ class Macros {
fiber: _num(j?['fi']),
sugar: _num(j?['su']),
sodium: _num(j?['na']),
+ chol: _num(j?['ch']),
animal: _num(j?['an']),
sat: _num(j?['sa']),
trans: _num(j?['tf']),
diff --git a/lib/screens/nutrition/ai.dart b/lib/screens/nutrition/ai.dart
index 558a12a..db81856 100644
--- a/lib/screens/nutrition/ai.dart
+++ b/lib/screens/nutrition/ai.dart
@@ -154,6 +154,18 @@ class _MealAiSheetState extends State<_MealAiSheet> {
showNotchToast(context, t.copiedDone, icon: PhosphorIconsFill.copy, accent: context.gc.sage);
}
+ void _useAsNew(AiDraft d) {
+ final fresh = d.asNew;
+ if (fresh == null) return;
+ HapticFeedback.selectionClick();
+ setState(() {
+ for (final o in _drafts) {
+ final i = o.items.indexOf(d);
+ if (i >= 0) o.items[i] = fresh..on = d.on;
+ }
+ });
+ }
+
Future<void> _editAmount(AiDraft d) async {
final unit = _amtUnit(d.entry.liquid);
final shown = d.shownGrams;
@@ -529,6 +541,7 @@ class _MealAiSheetState extends State<_MealAiSheet> {
if (d.flags.contains(AiFlag.doubtful)) return t.mealAiFlagDoubtful;
if (d.flags.contains(AiFlag.adjusted)) return t.mealAiFlagAdjusted;
if (d.flags.contains(AiFlag.noAmount)) return t.mealAiFlagNoAmount;
+ if (d.flags.contains(AiFlag.matched)) return t.mealAiFlagMatched;
if (d.source == AiSource.ai) return t.mealAiFlagEstimated;
return null;
}
@@ -588,6 +601,18 @@ class _MealAiSheetState extends State<_MealAiSheet> {
overflow: TextOverflow.ellipsis,
style: AppTheme.f(11, weight: FontWeight.w600, color: tone, height: 1.25)),
],
+ if (d.asNew != null && d.flags.contains(AiFlag.matched)) ...[
+ const SizedBox(height: 2),
+ GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: () => _useAsNew(d),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(vertical: 3),
+ child: Text(t.mealAiNotSame,
+ style: AppTheme.f(11.5, weight: FontWeight.w800, color: gc.accent)),
+ ),
+ ),
+ ],
]),
),
]),
diff --git a/lib/screens/nutrition/cards.dart b/lib/screens/nutrition/cards.dart
index b831131..852979c 100644
--- a/lib/screens/nutrition/cards.dart
+++ b/lib/screens/nutrition/cards.dart
@@ -105,6 +105,7 @@ String _extrasLine(Macros m) => [
if (m.fiber > 0) '${t.fiberLabel} ${_g(m.fiber)} g',
if (m.sugar > 0) '${t.sugarLabel} ${_g(m.sugar)} g',
if (m.sodium > 0) '${t.sodiumLabel} ${m.sodium.round()} mg',
+ if (m.chol > 0) '${t.cholesterolLabel} ${m.chol.round()} mg',
].join(' · ');
class _RingCard extends StatelessWidget {
diff --git a/lib/screens/nutrition/food.dart b/lib/screens/nutrition/food.dart
index b85d4d0..71992a7 100644
--- a/lib/screens/nutrition/food.dart
+++ b/lib/screens/nutrition/food.dart
@@ -945,6 +945,7 @@ class _ValueRows extends StatelessWidget {
if (per.fiber > 0) row(t.fiberLabel, '${_g(per.fiber)} g', gc.sage),
if (per.sugar > 0) row(t.sugarLabel, '${_g(per.sugar)} g', gc.warn),
if (per.sodium > 0) row(t.sodiumLabel, '${per.sodium.round()} mg', gc.info),
+ if (per.chol > 0) row(t.cholesterolLabel, '${per.chol.round()} mg', gc.textSecondary),
]),
);
}
@@ -1451,6 +1452,7 @@ class _EntryValuesSheetState extends State<_EntryValuesSheet> {
fiber: old.fiber,
sugar: old.sugar,
sodium: old.sodium,
+ chol: old.chol,
animal: old.protein <= 0 ? 0 : old.animal / old.protein * m.protein,
sat: old.sat,
trans: old.trans,
@@ -1591,6 +1593,7 @@ Macros _macrosOf(
TextEditingController? fiber,
TextEditingController? sugar,
TextEditingController? sodium,
+ TextEditingController? chol,
TextEditingController? sat,
TextEditingController? trans,
TextEditingController? mono,
@@ -1607,6 +1610,7 @@ Macros _macrosOf(
fiber: fiber == null ? 0 : _read(fiber),
sugar: sugar == null ? 0 : _read(sugar),
sodium: sodium == null ? 0 : _read(sodium),
+ chol: chol == null ? 0 : _read(chol),
sat: sat == null ? 0 : _read(sat),
trans: trans == null ? 0 : _read(trans),
mono: mono == null ? 0 : _read(mono),
@@ -1941,6 +1945,7 @@ class _FoodEditorState extends State<_FoodEditor> with _StickerDrafts {
late final _fi = TextEditingController(text: _seed(_base?.macros.fiber ?? 0));
late final _su = TextEditingController(text: _seed(_base?.macros.sugar ?? 0));
late final _na = TextEditingController(text: _seed(_base?.macros.sodium ?? 0));
+ late final _chol = TextEditingController(text: _seed(_base?.macros.chol ?? 0));
late final _sat = TextEditingController(text: _seed(_base?.macros.sat ?? 0));
late final _trans = TextEditingController(text: _seed(_base?.macros.trans ?? 0));
late final _mono = TextEditingController(text: _seed(_base?.macros.mono ?? 0));
@@ -1967,7 +1972,7 @@ class _FoodEditorState extends State<_FoodEditor> with _StickerDrafts {
@override
void dispose() {
- for (final c in [_name, _serving, _grams, _kcal, _p, _c, _f, _fi, _su, _na, _sat, _trans, _mono, _poly]) {
+ for (final c in [_name, _serving, _grams, _kcal, _p, _c, _f, _fi, _su, _na, _chol, _sat, _trans, _mono, _poly]) {
c.dispose();
}
_dropDrafts();
@@ -1983,7 +1988,7 @@ class _FoodEditorState extends State<_FoodEditor> with _StickerDrafts {
var grams = (_read(_grams) * _k).clamp(0, 5000).toDouble();
if (_per100 && grams <= 0) grams = 100;
final typed = _macrosOf(_kcal, _p, _c, _f,
- fiber: _fi, sugar: _su, sodium: _na, sat: _sat, trans: _trans, mono: _mono, poly: _poly);
+ fiber: _fi, sugar: _su, sodium: _na, chol: _chol, sat: _sat, trans: _trans, mono: _mono, poly: _poly);
final saved = fit.saveFood(
id: widget.food?.id,
name: name,
@@ -2014,7 +2019,7 @@ class _FoodEditorState extends State<_FoodEditor> with _StickerDrafts {
final grams = _read(_grams) * _k;
if (grams > 0) {
final k = on ? 100 / grams : grams / 100;
- for (final c in [_kcal, _p, _c, _f, _fi, _su, _na, _sat, _trans, _mono, _poly]) {
+ for (final c in [_kcal, _p, _c, _f, _fi, _su, _na, _chol, _sat, _trans, _mono, _poly]) {
final v = _read(c);
if (v > 0) c.text = _seed(v * k);
}
@@ -2095,6 +2100,7 @@ class _FoodEditorState extends State<_FoodEditor> with _StickerDrafts {
fiber: m.fiber,
sugar: m.sugar,
sodium: m.sodium,
+ chol: m.chol,
animal: m.protein * _animalShare,
sat: m.sat,
trans: m.trans,
@@ -2117,6 +2123,7 @@ class _FoodEditorState extends State<_FoodEditor> with _StickerDrafts {
fiber: m.fiber,
sugar: m.sugar,
sodium: m.sodium,
+ chol: m.chol,
animal: old.animal * k,
sat: m.sat,
trans: m.trans,
@@ -2248,6 +2255,15 @@ class _FoodEditorState extends State<_FoodEditor> with _StickerDrafts {
label: t.sodiumLabel.toUpperCase(), controller: _na, color: gc.textSecondary, suffix: 'mg'),
),
]),
+ const SizedBox(height: 8),
+ Row(children: [
+ Expanded(
+ child: _NumberField(
+ label: t.cholesterolLabel.toUpperCase(), controller: _chol, color: gc.textSecondary, suffix: 'mg'),
+ ),
+ const SizedBox(width: 8),
+ const Spacer(flex: 2),
+ ]),
const SizedBox(height: 14),
Text(t.fatTypes.toUpperCase(),
style: AppTheme.f(10.5, weight: FontWeight.w700, color: gc.textTertiary, letterSpacing: 1.4)),
diff --git a/lib/services/meal_ai.dart b/lib/services/meal_ai.dart
index 02cb68b..1bf1543 100644
--- a/lib/services/meal_ai.dart
+++ b/lib/services/meal_ai.dart
@@ -10,7 +10,7 @@ const kMealAiMaxItems = 40;
enum AiSource { library, mine, ai }
-enum AiFlag { adjusted, doubtful, noValues, noAmount }
+enum AiFlag { adjusted, doubtful, noValues, noAmount, matched }
class AiFood {
AiFood({
@@ -25,6 +25,7 @@ class AiFood {
this.fiber,
this.sugar,
this.sodium,
+ this.chol,
this.sat,
this.trans,
this.mono,
@@ -44,6 +45,7 @@ class AiFood {
double? fiber;
double? sugar;
double? sodium;
+ double? chol;
double? sat;
double? trans;
double? mono;
@@ -314,6 +316,7 @@ const _fatKeys = ['fat', 'fats', 'grasa', 'grasas', 'lipids', 'lipidos', 'f', 'f
const _fiberKeys = ['fiber', 'fibre', 'fibra', 'fiberg'];
const _sugarKeys = ['sugar', 'sugars', 'azucar', 'azucares', 'sugarg', 'totalsugars'];
const _sodiumKeys = ['sodium', 'sodio', 'natrium', 'sodiummg', 'sodiomg'];
+const _cholKeys = ['cholesterol', 'colesterol', 'cholesterolmg', 'colesterolmg', 'chol'];
const _satKeys = ['saturated', 'saturatedfat', 'saturadas', 'saturada', 'grasassaturadas', 'grasasaturada', 'satfat', 'saturates', 'saturatedfatg'];
const _transKeys = ['trans', 'transfat', 'transfats', 'grasastrans', 'grasatrans', 'transfatg'];
const _monoKeys = ['monounsaturated', 'monounsaturatedfat', 'monoinsaturadas', 'monoinsaturada', 'grasasmonoinsaturadas', 'monofat', 'mono'];
@@ -516,6 +519,7 @@ AiFood? _food(Object? raw, String defaultMeal) {
fiber: macro(_fiberKeys),
sugar: macro(_sugarKeys),
sodium: macro(_sodiumKeys),
+ chol: macro(_cholKeys),
sat: macro(_satKeys),
trans: macro(_transKeys),
mono: macro(_monoKeys),
@@ -670,11 +674,12 @@ AiReply parseMealAi(String raw) {
}
class AiDraft {
- AiDraft({required this.entry, required this.source, this.flags = const {}, this.on = true});
+ AiDraft({required this.entry, required this.source, this.flags = const {}, this.on = true, this.asNew});
FoodEntry entry;
final AiSource source;
final Set<AiFlag> flags;
+ final AiDraft? asNew;
bool on;
String get name => entry.name;
@@ -830,7 +835,7 @@ Meal _mealFor(String raw, List<MealSlot> slots, Meal fallback) {
Macros _aiMacros(AiFood f, double? grams, Set<AiFlag> flags) {
var kcal = f.kcal, p = f.protein, c = f.carbs, fat = f.fat, fi = f.fiber;
- var su = f.sugar, na = f.sodium, sa = f.sat, tr = f.trans, mu = f.mono, po = f.poly;
+ var su = f.sugar, na = f.sodium, ch = f.chol, sa = f.sat, tr = f.trans, mu = f.mono, po = f.poly;
if (f.per100) {
final k = (grams ?? 100) / 100;
kcal = kcal == null ? null : kcal * k;
@@ -840,6 +845,7 @@ Macros _aiMacros(AiFood f, double? grams, Set<AiFlag> flags) {
fi = fi == null ? null : fi * k;
su = su == null ? null : su * k;
na = na == null ? null : na * k;
+ ch = ch == null ? null : ch * k;
sa = sa == null ? null : sa * k;
tr = tr == null ? null : tr * k;
mu = mu == null ? null : mu * k;
@@ -879,6 +885,7 @@ Macros _aiMacros(AiFood f, double? grams, Set<AiFlag> flags) {
fiber: fi ?? 0,
sugar: su ?? 0,
sodium: na ?? 0,
+ chol: ch ?? 0,
sat: sa ?? 0,
trans: tr ?? 0,
mono: mu ?? 0,
@@ -886,10 +893,46 @@ Macros _aiMacros(AiFood f, double? grams, Set<AiFlag> flags) {
);
}
+bool _near(double a, double b, double abs, double rel) => (a - b).abs() <= math.max(abs, math.max(a, b) * rel);
+
+FoodItem? _byValues(AiFood f, double? grams, List<FoodItem> own) {
+ if (grams == null || grams <= 0 || f.per100) return null;
+ final kcal = f.kcal, p = f.protein, c = f.carbs, fat = f.fat;
+ if (kcal == null || p == null || c == null || fat == null || kcal <= 0) return null;
+ FoodItem? best;
+ var bestGap = double.infinity;
+ for (final item in own) {
+ if (item.grams <= 0) continue;
+ final m = item.macros * (grams / item.grams);
+ if (m.kcal <= 0) continue;
+ if (!_near(kcal, m.kcal, 8, 0.04) ||
+ !_near(p, m.protein, 0.6, 0.06) ||
+ !_near(c, m.carbs, 0.6, 0.06) ||
+ !_near(fat, m.fat, 0.6, 0.06)) {
+ continue;
+ }
+ if (f.sodium != null && m.sodium > 0 && !_near(f.sodium!, m.sodium, 15, 0.08)) continue;
+ if (f.sat != null && m.sat > 0 && !_near(f.sat!, m.sat, 0.4, 0.1)) continue;
+ final gap = (kcal - m.kcal).abs() + (p - m.protein).abs() + (c - m.carbs).abs() + (fat - m.fat).abs();
+ if (gap < bestGap) {
+ bestGap = gap;
+ best = item;
+ }
+ }
+ return best;
+}
+
AiDraft _draft(AiFood f, Meal meal, String lang, List<FoodItem> own, DateTime now) {
- final flags = <AiFlag>{};
var grams = f.grams;
- final hit = _match(f.name, lang, own);
+ var hit = _match(f.name, lang, own);
+ var byValues = false;
+ if (hit?.own == null) {
+ final same = _byValues(f, grams, own);
+ if (same != null) {
+ hit = _Hit(null, same, 1);
+ byValues = true;
+ }
+ }
if (hit != null) {
final lib = hit.library;
final mine = hit.own;
@@ -921,10 +964,20 @@ AiDraft _draft(AiFood f, Meal meal, String lang, List<FoodItem> own, DateTime no
agrees = !((ratio < 0.55 || ratio > 1.8) && gap > 40);
}
if (agrees) {
- return AiDraft(entry: entry, source: lib != null ? AiSource.library : AiSource.mine, flags: const {});
+ return AiDraft(
+ entry: entry,
+ source: lib != null ? AiSource.library : AiSource.mine,
+ flags: byValues ? const {AiFlag.matched} : const {},
+ asNew: byValues ? _aiDraft(f, meal, grams, now) : null,
+ );
}
}
}
+ return _aiDraft(f, meal, grams, now);
+}
+
+AiDraft _aiDraft(AiFood f, Meal meal, double? grams, DateTime now) {
+ final flags = <AiFlag>{};
final macros = f.hasMacros ? _aiMacros(f, grams, flags) : Macros.zero;
if (!f.hasMacros) flags.add(AiFlag.noValues);
if (grams == null && !flags.contains(AiFlag.noValues)) flags.add(AiFlag.noAmount);
@@ -1026,7 +1079,7 @@ String buildMealAiPrompt(MealAiBrief b) {
'2. Use exactly the keys shown in the example. Keep "gymmane" as "$kMealAiTag" and "v" as $kMealAiVersion.',
'3. One entry in "items" per food or ingredient. Split mixed dishes into their ingredients (for example "Rice, cooked" and "Chicken breast, grilled").',
'4. "grams" is the weight in grams of that item (for liquids, the volume in millilitres). Always a plain number, never a range.',
- '5. "kcal", "protein", "carbs" and "fat" are the TOTAL for the amount in "grams", not per 100 g. Plain numbers only: dot as decimal separator, no units, no quotes. Protein, carbs and fat are in grams. kcal must be close to 4 x protein + 4 x carbs + 9 x fat. Optional, same rules (totals for the amount in "grams"): "fiber", "sugar", "saturated", "trans", "monounsaturated" and "polyunsaturated" in grams, and "sodium" in milligrams. Add them only when you know them, for example from a nutrition label I gave you; leave the key out otherwise, never write 0 for unknown.',
+ '5. "kcal", "protein", "carbs" and "fat" are the TOTAL for the amount in "grams", not per 100 g. Plain numbers only: dot as decimal separator, no units, no quotes. Protein, carbs and fat are in grams. kcal must be close to 4 x protein + 4 x carbs + 9 x fat. Optional, same rules (totals for the amount in "grams"): "fiber", "sugar", "saturated", "trans", "monounsaturated" and "polyunsaturated" in grams, and "sodium" and "cholesterol" in milligrams. Add them only when you know them, for example from a nutrition label I gave you; leave the key out otherwise, never write 0 for unknown.',
'6. Use simple, common, generic food names (for example "Greek yogurt", "Rolled oats", "Banana", "Olive oil"). No brands, no adjectives, no cooking instructions inside the name. Add "cooked" or "grilled" to the name only when the weight is the cooked weight.',
'7. Use realistic amounts that a person can weigh at home. Do not put the same food twice in one option.',
'8. "meal" is one of these ids: ${ids.map((e) => '"$e"').join(', ')}.${b.day ? ' Spread the foods across the meals.' : ' Use "${b.mealId}" for every item.'}',
diff --git a/test/meal_ai_test.dart b/test/meal_ai_test.dart
index 109336f..45b021e 100644
--- a/test/meal_ai_test.dart
+++ b/test/meal_ai_test.dart
@@ -368,6 +368,46 @@ void main() {
expect(d.total.kcal, 120);
});
+ test('un alimento propio con los mismos valores se reutiliza aunque el nombre no se parezca', () {
+ const mine = FoodItem(
+ id: 'f9',
+ name: 'Jack Links',
+ grams: 40,
+ macros: Macros(kcal: 150, protein: 9, carbs: 3, fat: 11, sodium: 480, sat: 5, chol: 35),
+ );
+ final d = resolve(
+ '{"items":[{"food":"Beef stick and cheese snack","grams":40,"kcal":150,"protein":9,"carbs":3,"fat":11,"sodium":480,"saturated":5}]}',
+ own: [mine])
+ .single
+ .items
+ .single;
+ expect(d.source, AiSource.mine);
+ expect(d.name, 'Jack Links');
+ expect(d.entry.foodId, 'f9');
+ expect(d.total.chol, closeTo(35, 0.01));
+ expect(d.flags, contains(AiFlag.matched));
+ final fresh = d.asNew!;
+ expect(fresh.source, AiSource.ai);
+ expect(fresh.name, 'Beef stick and cheese snack');
+ });
+
+ test('valores distintos no se confunden con un alimento propio', () {
+ const mine = FoodItem(
+ id: 'f9',
+ name: 'Jack Links',
+ grams: 40,
+ macros: Macros(kcal: 150, protein: 9, carbs: 3, fat: 11),
+ );
+ final d = resolve(
+ '{"items":[{"food":"Beef stick and cheese snack","grams":40,"kcal":190,"protein":9,"carbs":3,"fat":15}]}',
+ own: [mine])
+ .single
+ .items
+ .single;
+ expect(d.source, AiSource.ai);
+ expect(d.asNew, isNull);
+ });
+
test('con piezas usa el peso de la pieza de la biblioteca', () {
final d = resolve('{"items":[{"food":"Banana","count":2,"kcal":214,"protein":2.6,"carbs":54,"fat":0.7}]}').single.items.single;
expect(d.source, AiSource.library);
@@ -390,12 +430,13 @@ void main() {
group('etiqueta completa', () {
test('lee fibra, azucar, sodio y tipos de grasa del alimento', () {
- final d = resolve('{"items":[{"food":"Beef stick and cheese protein snack","grams":40,"kcal":150,"protein":9,"carbs":3,"fat":11,"sodium":480,"saturated":5,"trans":0.2,"sugar":1,"fiber":0.5,"monounsaturated":4,"polyunsaturated":0.8}]}')
+ final d = resolve('{"items":[{"food":"Beef stick and cheese protein snack","grams":40,"kcal":150,"protein":9,"carbs":3,"fat":11,"sodium":480,"cholesterol":35,"saturated":5,"trans":0.2,"sugar":1,"fiber":0.5,"monounsaturated":4,"polyunsaturated":0.8}]}')
.single
.items
.single;
expect(d.source, AiSource.ai);
expect(d.total.sodium, closeTo(480, 0.01));
+ expect(d.total.chol, closeTo(35, 0.01));
expect(d.total.sat, closeTo(5, 0.01));
expect(d.total.trans, closeTo(0.2, 0.01));
expect(d.total.sugar, closeTo(1, 0.01));
@@ -418,7 +459,7 @@ void main() {
test('el prompt pide los campos opcionales sin hacerlos obligatorios', () {
final p = buildMealAiPrompt(brief);
- expect(p, contains('"sodium" in milligrams'));
+ expect(p, contains('"sodium" and "cholesterol" in milligrams'));
expect(p, contains('leave the key out otherwise'));
});
});
diff --git a/test/nutrition_beta_keys.txt b/test/nutrition_beta_keys.txt
index 92266f3..a65e919 100644
--- a/test/nutrition_beta_keys.txt
+++ b/test/nutrition_beta_keys.txt
@@ -334,3 +334,6 @@ mealAiTruncated
mealAiUnreadable
mealAiUnreadableHint
mealAiWholeDay
+cholesterolLabel
+mealAiFlagMatched
+mealAiNotSame