dashPi: a self-hosted home dashboard, its sync server and phone app
The dashboard (Raspberry Pi 3.5" screen + web pages), the end-to-end encrypted sync mailbox (PHP + SQLite) and the Android companion app (Flutter), with docs, clean-install checks and screenshots made from demo data. Built mostly with an AI coding assistant; not yet reviewed line by line by a human (see README and SECURITY.md). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
fb3c01cdd7
333 changed files with 45151 additions and 0 deletions
184
app/lib/health/sugar.dart
Normal file
184
app/lib/health/sugar.dart
Normal file
|
|
@ -0,0 +1,184 @@
|
|||
// Added sugar, estimated — a port of the dashboard's plugins/food/sugar.py (keep the word lists and
|
||||
// rules identical): the sugars WHO's limit is about ("free sugars": sugar, honey, syrups added to food,
|
||||
// plus fruit juice), not the sugar inside whole fruit, vegetables and plain milk. Each food gets a kind
|
||||
// from its category / name: added (all its sugar counts), dairy (only beyond the milk's own lactose), natural (none).
|
||||
// Shop products: the label's added-sugar figure, else NOVA 1 / "no added sugar", else their ingredients
|
||||
// (sugarsIn / dairy, off.py) — see sugar.py's top. Names are matched folded (no diacritics, lower case).
|
||||
import 'dart:convert';
|
||||
import 'dart:math';
|
||||
|
||||
import '../sync/store.dart';
|
||||
import 'food_model.dart';
|
||||
import 'sugar_kinds.g.dart';
|
||||
|
||||
const lactose = 5.0; // g per 100 g of milk / yogurt that is the milk's own sugar
|
||||
|
||||
// lower-cased letters with diacritics → plain ones (sugar.py's FOLD)
|
||||
final _foldMap = <String, String>{
|
||||
for (final (from, to) in [
|
||||
('áàâäãåāăą', 'a'), ('çčć', 'c'), ('ďđ', 'd'), ('éèêëěęē', 'e'), ('íìîïī', 'i'), ('ľĺł', 'l'), ('ňńñ', 'n'),
|
||||
('óòôöõőø', 'o'), ('řŕ', 'r'), ('śšşș', 's'), ('ťţț', 't'), ('úùûüůűū', 'u'), ('ýÿ', 'y'), ('žźż', 'z'),
|
||||
])
|
||||
for (final c in from.split('')) c: to,
|
||||
'ß': 'ss', 'æ': 'ae', 'œ': 'oe',
|
||||
};
|
||||
|
||||
/// 'Zahăr Brun' → 'zahar brun' (what the word lists are matched against).
|
||||
String fold(String s) => s.toLowerCase().split('').map((c) => _foldMap[c] ?? c).join();
|
||||
|
||||
final _added = RegExp(
|
||||
r'juice|nectar(?!ine)|syrup|honey|\bjam\b|jelly|marmalade|candy|candies|chocolate|cocoa|(?<!un)sweetened|frosted|glazed|candied|'
|
||||
r'\bcake|cookie|biscuit|brownie|\bpie\b|pastr|doughnut|donut|croissant|muffin|waffle|pancake|dessert|pudding|'
|
||||
r'ice cream|sorbet|gelatin|soda|soft drink|\bcola\b|lemonade|energy drink|sport drink|sports drink|\bpunch\b|'
|
||||
r'smoothie|milkshake|milk shake|ketchup|bbq|barbecue|sweet and sour|teriyaki|\bsugar\b|sugared|granola|cereal bar|'
|
||||
r'nutrition bar|protein bar|wafer|caramel|toffee|fudge|marzipan|nutella|'
|
||||
r'strudel|tart\b|cheesecake|tiramisu|liqueur|cocktail|flavored|flavoured|vanilla|'
|
||||
r'fruit drink|flavou?r drink|breakfast drink|drink mix|beverage mix|ready.to.drink|carbonated|tonic|ginger ale|limeade|'
|
||||
r'lemonad|sour mix|creme de|pina colada|daiquiri|shake mix|ovaltine|malted|\bbars?\b|treats|sundae|cobbler|'
|
||||
r'cinnamon roll|hotcake|french toast|mcgriddle|coleslaw|banana chips|zwieback|\bcran |'
|
||||
r'schoko|marlenka|sernik|malt loaf|\bbeer|\bbere\b|\bpivo|\bwines?\b|\bcider|\bvin\b|v[ií]no\b|cidru|ciocolat|pr[aă]jitur|\bdulce|zahar|cukor|cukr|'
|
||||
r'zucker|sucre|zucchero|azucar|acucar|cukier|suiker|sirop|sirup|syrop|sciroppo|honig|\bmiere\b|\bmiel\b|\bmiod|\bmedov|'
|
||||
r'chocolat|cioccolat|czekolad|cokolad|csokolad|keks|kuchen|torte\b|\btort\b|\bgateau|biscott|gallet|ciastk|susienk|susenk|'
|
||||
r'oplatk|napolitane\b|\blody\b|zmrzlin|fagylalt|gelato|helado|limonad|saft\b|\bjus\b|succo|\bzumo|\bdzus|\bdzem|'
|
||||
r'konfit|marmelad|kompot|compot|bonbon|bomboan|pralin|lizak|\bsuc\b|\bsucuri',
|
||||
caseSensitive: false, unicode: true);
|
||||
final _dairy = RegExp(
|
||||
r'\bmilk\b|yogh?urt|jogurt|iaurt|kefir|skyr|quark|tvaroh|buttermilk|cottage|ricotta|cream cheese|\bcream\b|'
|
||||
r'lapte|mlieko|sm[aâ]nt[aâ]n[aă]|smotana|br[aâ]nz[aă]|\burda\b|chefir|\bsana\b|'
|
||||
r'\blait\b|milch|\blatte\b|\bleche\b|\bleite\b|\bmlek|\bmlecz|\bmleko|\btej\b|\btejf|\bmelk\b|yaourt|joghurt|'
|
||||
r'yogur|iogurt|fromage blanc|twarog|\bturo\b|\bsahne|creme fraiche|smietan|smetan|\bnata\b|\bpanna\b|kwark',
|
||||
caseSensitive: false, unicode: true);
|
||||
/// The reviewed table's kind for a USDA category (sugar_kinds.g.dart = the dashboard's sugar_kinds.json), or null:
|
||||
/// by the name. [name]: folded.
|
||||
String? categoryKind(String category, String name) {
|
||||
final k = sugarKinds[category.toLowerCase()];
|
||||
if (k == null) return null;
|
||||
final (kind, except) = k;
|
||||
return except != null && RegExp(except).hasMatch(name) ? null : kind;
|
||||
}
|
||||
final _notDairy = RegExp(
|
||||
r'coconut milk|chocolate milk|\b(soy|soya|almond|oat|rice) ?(milk|drink)|(soja|hafer|mandel|reis|kokos)(milch|drink)|'
|
||||
r'lapte (vegetal|de (soia|migdale|ovaz|cocos|orez))|\bvegan\b',
|
||||
caseSensitive: false);
|
||||
final _natural = RegExp(
|
||||
r'(apple|banana|grape|orange|pear|peach|plum|berr|cherr|melon|mango|pineapple|kiwi|\bfig|\bdate|apricot|raisin|'
|
||||
r'tomato|onion|carrot|cabbage|potato|pepper|cucumber|lettuce|salad|spinach|broccoli|bean|pea|lentil|corn|squash|'
|
||||
r'zucchini|pumpkin|beet|garlic|mushroom|rice|oat|bread|pasta|egg|chicken|beef|pork|fish|tuna|salmon|ham|turkey|'
|
||||
r'cheese|nut|almond|walnut|seed|soup|pickle|clementin|mandarin|grepfruit|grapefruit|\bm[aă]r\b|morcov|sfecl|telin|'
|
||||
r'ceap|ro[sș]ii|cartof|varz|legume|borsc?h|\bbor[sș]|ciorb|sup[aă]\b|pizza|goulash|gul[aá][sšș]|\bmici\b|congelat)',
|
||||
caseSensitive: false, unicode: true);
|
||||
final _flavour = RegExp(r'flavou?red|fruit|vanilla|strawberr|banana', caseSensitive: false);
|
||||
final _notFlavourDairy = RegExp(r'chocolate|ice cream|shake', caseSensitive: false);
|
||||
|
||||
/// A food → "added" / "dairy" / "natural" (sugar.kind). sugarsIn / dairy: off.py's columns (null: not known).
|
||||
String sugarKind(String name, {String category = '', String source = '', int? nova, String labels = '', String? sugarsIn, int? dairy}) {
|
||||
name = fold(name);
|
||||
final ck = categoryKind(category, name);
|
||||
final isDairy = ((dairy ?? 0) != 0 || ck == 'dairy' || _dairy.hasMatch(name)) && !_notDairy.hasMatch(name);
|
||||
if (source == 'off') {
|
||||
if (labels.toLowerCase().contains('no added sugar') || nova == 1) return isDairy ? 'dairy' : 'natural';
|
||||
if (sugarsIn != null) return isDairy ? 'dairy' : sugarsIn.isNotEmpty ? 'added' : 'natural'; // its ingredients are known
|
||||
if (isDairy && !_added.hasMatch(name)) return 'dairy';
|
||||
return 'added';
|
||||
}
|
||||
if (ck == 'added' || _added.hasMatch(name)) { // words: the name only ("Fruits and Fruit Juices")
|
||||
return isDairy && _flavour.hasMatch(name) && !_notFlavourDairy.hasMatch(name) ? 'dairy' : 'added';
|
||||
}
|
||||
return isDairy ? 'dairy' : 'natural';
|
||||
}
|
||||
|
||||
double addedPart(String kind, double sugar, double? grams) {
|
||||
if (sugar == 0) return 0;
|
||||
if (kind == 'added') return sugar;
|
||||
if (kind == 'dairy') return max(0, sugar - (grams != null && grams > 0 ? lactose * grams / 100 : sugar));
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool _says(String name) {
|
||||
name = fold(name);
|
||||
return _added.hasMatch(name) || _dairy.hasMatch(name) || _natural.hasMatch(name);
|
||||
}
|
||||
String _byName(String name) => _says(name) ? sugarKind(name) : 'added';
|
||||
|
||||
String foodKind(Food f) => sugarKind(f.name, category: f.category, source: f.kind == 'off' ? 'off' : f.source, nova: f.nova,
|
||||
labels: f.labels, sugarsIn: f.sugarsIn, dairy: f.dairy);
|
||||
|
||||
/// Added sugar (g) of [sugar] g of a foods.db food (sugar.food_part): the label's own figure when it gives one, else by its kind.
|
||||
double foodPart(Food f, double sugar, double? grams) {
|
||||
final s100 = f.per100['sugar'];
|
||||
// "0 added" yet sugar in the ingredients: a crowd-typed 0, not the label
|
||||
final a = f.addedSugar == 0 && (f.sugarsIn ?? '').isNotEmpty ? null : f.addedSugar;
|
||||
if (a != null && s100 != null && s100 > 0) return sugar * min(1.0, a / s100);
|
||||
return addedPart(foodKind(f), sugar, grams);
|
||||
}
|
||||
|
||||
/// Added sugar of entries (sugar.entry_added), the foods they were made from looked up once.
|
||||
class AddedSugar {
|
||||
AddedSugar(this.store, this.fdb);
|
||||
final SyncStore store;
|
||||
final FoodDb? fdb;
|
||||
final _foods = <int, Food?>{};
|
||||
final _mine = <String, Map<String, dynamic>?>{};
|
||||
|
||||
Food? _food(int id) => _foods.putIfAbsent(id, () => fdb?.food(id));
|
||||
Map<String, dynamic>? _my(String uid) => _mine.putIfAbsent(uid, () => store.row('food.food', uid));
|
||||
|
||||
double entry(Entry e) {
|
||||
final sugar = e.n('sugar') ?? 0;
|
||||
if (sugar == 0) return 0;
|
||||
final grams = e.n('grams');
|
||||
if (e.foodId != null) {
|
||||
final f = _food(e.foodId!);
|
||||
if (f != null) return foodPart(f, sugar, grams);
|
||||
}
|
||||
if (e.myFoodId != null) {
|
||||
final m = _my(e.myFoodId!);
|
||||
if (m != null) return _myAdded(m, sugar, grams, 0);
|
||||
}
|
||||
return addedPart(_byName(e.name), sugar, grams);
|
||||
}
|
||||
|
||||
double _myAdded(Map<String, dynamic> m, double sugar, double? grams, int depth) {
|
||||
final set = m['sugar_kind']; // "Sugar counts as" (My foods): as set, whatever the estimate says
|
||||
if (set is String && const ['added', 'dairy', 'natural'].contains(set)) return addedPart(set, sugar, grams);
|
||||
final recipe = m['recipe'] is String ? jsonDecode(m['recipe'] as String) as Map<String, dynamic>? : null;
|
||||
final ings = (recipe?['ingredients'] as List?)?.cast<Map<String, dynamic>>();
|
||||
if (ings != null && ings.isNotEmpty) {
|
||||
var totSugar = 0.0, totAdded = 0.0;
|
||||
for (final ing in ings) {
|
||||
final ref = (ing['food'] as String?) ?? '';
|
||||
final g = (ing['grams'] as num?)?.toDouble();
|
||||
if (ref.startsWith('usda:') && g != null) {
|
||||
final f = _food(int.parse(ref.substring(5)));
|
||||
if (f != null) {
|
||||
final s = (f.per100['sugar'] ?? 0) * g / 100;
|
||||
totSugar += s;
|
||||
totAdded += foodPart(f, s, g);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (ref.startsWith('my:') && g != null && depth < 4) {
|
||||
final sub = _my(ref.substring(3).replaceFirst('~', '')); // synced refs are "my:~<id>"
|
||||
if (sub != null) {
|
||||
final s = ((sub['sugar'] as num?)?.toDouble() ?? 0) * g / 100;
|
||||
totSugar += s;
|
||||
totAdded += _myAdded(sub, s, g, depth + 1);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
final s = (ing['sugar'] as num?)?.toDouble() ?? 0; // a fixed ingredient: its own numbers
|
||||
if (s > 0) {
|
||||
totSugar += s;
|
||||
totAdded += addedPart(_byName((ing['name'] as String?) ?? ''), s, g);
|
||||
}
|
||||
}
|
||||
return totSugar > 0 ? sugar * totAdded / totSugar : 0;
|
||||
}
|
||||
final base = (m['based_on'] as num?)?.toInt();
|
||||
if (base != null) {
|
||||
final f = _food(base);
|
||||
if (f != null) return foodPart(f, sugar, grams);
|
||||
}
|
||||
return addedPart(_byName((m['name'] as String?) ?? ''), sugar, grams);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue