food logger context tips

This commit is contained in:
Joren de Graaf
2026-10-11 15:21:10 +02:00
parent 559c51e9bb
commit 400e8254c0
51 changed files with 1988 additions and 41 deletions
+15 -5
View File
@@ -5,6 +5,7 @@ from django.utils import timezone
from django.utils.dateparse import parse_date
from food.models import FoodLogEntry, MealType
from food.services.nutrient_help import nutrient_guidance
from planner.models import UserSettings
from planner.timezones import localdate_for_user
@@ -22,12 +23,15 @@ def selected_date(request):
return day
def diary_context(user, day):
def diary_context(user, day, language='en'):
goals, _ = UserSettings.objects.get_or_create(user=user)
entries = list(FoodLogEntry.objects.filter(user=user, date=day).select_related('product')
.prefetch_related('attachments').defer('product__raw_data'))
totals = {name: sum((getattr(entry, name) or ZERO for entry in entries), ZERO) for name in
('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g')}
fibre_values = [entry.fibre_g for entry in entries if entry.fibre_g is not None]
fibre_incomplete = len(fibre_values) != len(entries)
totals['fibre_g'] = sum(fibre_values, ZERO) if fibre_values or not entries else None
meals = []
for key, label in MealType.choices:
items = [entry for entry in entries if entry.meal == key]
@@ -35,16 +39,22 @@ def diary_context(user, day):
'calories': sum((entry.calories_kcal or ZERO for entry in items), ZERO)})
macros = []
for label, name, goal, color in (
('Carbohydrates', 'carbohydrates_g', goals.carbohydrate_goal_g, 'pink'),
('Protein', 'protein_g', goals.protein_goal_g, 'blue'),
('Carbohydrates', 'carbohydrates_g', goals.carbohydrate_goal_g, 'pink'),
('Fat', 'fat_g', goals.fat_goal_g, 'orange'),
('Fibre', 'fibre_g', goals.fibre_goal_g, 'green'),
):
eaten = totals[name]
macros.append({'label': label, 'eaten': eaten, 'goal': goal, 'remaining': goal - eaten if goal is not None else None,
'percent': min(100, int(eaten * 100 / goal)) if goal else None, 'color': color})
incomplete = name == 'fibre_g' and fibre_incomplete
macros.append({'label': label, 'slug': name, 'guidance': nutrient_guidance(name, language),
'eaten': eaten, 'goal': goal,
'remaining': goal - eaten if goal is not None and eaten is not None and not incomplete else None,
'percent': min(100, int(eaten * 100 / goal)) if goal and eaten is not None else None,
'color': color, 'incomplete': incomplete})
calorie_goal = goals.daily_calorie_goal
calories = totals['calories_kcal']
return {'day': day, 'previous_day': day - timedelta(days=1), 'next_day': day + timedelta(days=1),
'meals': meals, 'totals': totals, 'macros': macros, 'calorie_goal': calorie_goal,
'meals': meals, 'totals': totals, 'macros': macros, 'help_language': language,
'calorie_goal': calorie_goal,
'calorie_remaining': Decimal(calorie_goal) - calories if calorie_goal is not None else None,
'calorie_percent': min(100, int(calories * 100 / calorie_goal)) if calorie_goal else 0}
+76
View File
@@ -0,0 +1,76 @@
"""Static, bilingual guidance for the food diary nutrient cards."""
GUIDANCE = {
'protein_g': {
'en': ('Helps build and maintain muscles and supports recovery.', [
('Poultry', 'chicken breast, turkey'), ('Fish', 'tuna, salmon, cod'),
('Eggs', ''), ('Dairy', 'skyr, quark (kwark), cottage cheese'),
('Legumes', 'lentils, chickpeas, beans'),
('Plant proteins', 'tofu, tempeh, edamame')], ''),
'nl': ('Helpt spieren opbouwen en behouden en ondersteunt herstel.', [
('Gevogelte', 'kipfilet, kalkoen'), ('Vis', 'tonijn, zalm, kabeljauw'),
('Eieren', ''), ('Zuivel', 'skyr, kwark, hüttenkäse'),
('Peulvruchten', 'linzen, kikkererwten, bonen'),
('Plantaardige eiwitten', 'tofu, tempeh, edamame')], ''),
},
'carbohydrates_g': {
'en': ('Provide energy for your brain, muscles and everyday activity.', [
('Whole grains', 'oats, wholemeal bread, brown rice'),
('Starchy foods', 'potatoes, pasta, rice'),
('Fruit', 'bananas, apples, berries'),
('Legumes', 'beans, lentils, chickpeas'),
('Vegetables', 'sweetcorn, peas')],
'Whole grains and fibre-rich carbohydrate sources are generally preferable to highly refined options.'),
'nl': ('Geven energie voor je hersenen, spieren en dagelijkse activiteiten.', [
('Volkoren granen', 'havermout, volkorenbrood, zilvervliesrijst'),
('Zetmeelrijke producten', 'aardappelen, pasta, rijst'),
('Fruit', 'bananen, appels, bessen'),
('Peulvruchten', 'bonen, linzen, kikkererwten'),
('Groenten', 'suikermaïs, erwten')],
'Volkoren en vezelrijke koolhydraatbronnen hebben doorgaans de voorkeur boven sterk geraffineerde producten.'),
},
'fat_g': {
'en': ('Supports hormone production, cell function and absorption of certain vitamins.', [
('Nuts', 'walnuts, almonds, cashews'),
('Seeds', 'chia, flaxseed, sunflower seeds'),
('Oils', 'olive oil, rapeseed oil'), ('Avocado', ''),
('Oily fish', 'salmon, mackerel, sardines'),
('Dairy and butter', 'cheese, cream, butter')],
'Unsaturated fats are generally preferable to saturated fats.'),
'nl': ('Ondersteunt de hormoonproductie, celfunctie en opname van bepaalde vitamines.', [
('Noten', 'walnoten, amandelen, cashewnoten'),
('Zaden', 'chiazaad, lijnzaad, zonnebloempitten'),
('Oliën', 'olijfolie, koolzaadolie'), ('Avocado', ''),
('Vette vis', 'zalm, makreel, sardines'),
('Zuivel en boter', 'kaas, room, boter')],
'Onverzadigde vetten hebben doorgaans de voorkeur boven verzadigde vetten.'),
},
'fibre_g': {
'en': ('Supports digestion, gut health and feelings of fullness.', [
('Legumes', 'lentils, kidney beans, chickpeas'),
('Whole grains', 'oats, wholemeal bread, barley'),
('Seeds', 'chia seeds, flaxseed'),
('Fruit', 'raspberries, pears, apples with skin'),
('Vegetables', 'broccoli, carrots, Brussels sprouts'),
('Nuts', 'almonds, pistachios')],
'Increase fibre gradually and drink enough fluids.'),
'nl': ('Ondersteunt de spijsvertering, darmgezondheid en een vol gevoel.', [
('Peulvruchten', 'linzen, kidneybonen, kikkererwten'),
('Volkoren granen', 'havermout, volkorenbrood, gerst'),
('Zaden', 'chiazaad, lijnzaad'),
('Fruit', 'frambozen, peren, appels met schil'),
('Groenten', 'broccoli, wortels, spruitjes'),
('Noten', 'amandelen, pistachenoten')],
'Verhoog je vezelinname geleidelijk en drink voldoende.'),
},
}
def nutrient_guidance(slug, language):
explanation, sources, tip = GUIDANCE[slug]['nl' if language.startswith('nl') else 'en']
titles = {'protein_g': 'Eiwitten', 'carbohydrates_g': 'Koolhydraten',
'fat_g': 'Vetten', 'fibre_g': 'Vezels'}
return {'title': titles[slug] if language.startswith('nl') else {
'protein_g': 'Protein', 'carbohydrates_g': 'Carbohydrates',
'fat_g': 'Fat', 'fibre_g': 'Fibre'}[slug],
'explanation': explanation, 'sources': sources, 'tip': tip}
+13 -2
View File
@@ -68,6 +68,15 @@ def map_product(data):
match = re.search(r'(?i)(\d+(?:[.,]\d+)?)\s*(g|ml)\b', serving_text)
serving_amount = _decimal(match.group(1).replace(',', '.')) if match else None
serving_unit = match.group(2).lower() if match else ''
package_text = str(data.get('quantity') or '')[:100]
package_match = re.fullmatch(r'\s*(\d+(?:[.,]\d+)?)\s*(kg|g|ml|l)\s*', package_text, re.IGNORECASE)
package_amount = _decimal(package_match.group(1).replace(',', '.')) if package_match else None
package_unit = package_match.group(2).lower() if package_match else ''
if package_amount is not None and package_unit in ('kg', 'l'):
package_amount *= 1000
package_unit = 'g' if package_unit == 'kg' else 'ml'
if package_amount is not None and package_amount <= 0:
package_amount = None
image_url = str(data.get('image_front_small_url') or data.get('image_front_url') or '')
try:
parsed_image = urlparse(image_url)
@@ -78,7 +87,9 @@ def map_product(data):
image_url = ''
return {'barcode': code[:64], 'product_name': name[:255], 'brand': str(data.get('brands') or '')[:255],
'image_url': image_url[:200],
'package_quantity': str(data.get('quantity') or '')[:100], 'serving_size_text': serving_text,
'package_quantity': package_text, 'package_amount': package_amount,
'package_unit': package_unit if package_amount is not None else '',
'serving_size_text': serving_text,
'serving_amount': serving_amount, 'serving_unit': serving_unit,
'base_unit': Unit.MILLILITRE if serving_unit == 'ml' else Unit.GRAM, **values}
@@ -148,7 +159,7 @@ def cached_product(user, barcode, *, refresh=False):
return product
raise
mapped = map_product(data)
if not mapped:
if not mapped or mapped['barcode'] != barcode:
return product
mapped['source'] = FoodProduct.Source.OPEN_FOOD_FACTS
mapped['fetched_at'] = timezone.now()
+171
View File
@@ -0,0 +1,171 @@
"""Owner-scoped product matching and creation shared by the HTTP API."""
import re
from decimal import Decimal, InvalidOperation
from django.contrib.auth import get_user_model
from django.db import transaction
from django.db.models import Q
from food.models import FoodProduct, Unit
from food.services.openfoodfacts import cached_product, cached_search
NUTRITION_FIELDS = {
'calories_kcal': 'energy_kcal_100', 'carbohydrates_g': 'carbohydrates_100',
'protein_g': 'protein_100', 'fat_g': 'fat_100', 'saturated_fat_g': 'saturated_fat_100',
'sugars_g': 'sugars_100', 'fibre_g': 'fibre_100', 'salt_g': 'salt_100',
}
def _name(value, field, limit, required=False):
if not isinstance(value, str):
raise ValueError(f'{field} must be text.')
cleaned = ' '.join(value.split())
if len(cleaned) > limit or (required and not cleaned):
raise ValueError(f'Invalid {field}.')
return cleaned
def _amount(value, field, positive=True):
if isinstance(value, bool):
raise ValueError(f'Invalid {field}.')
try:
amount = Decimal(str(value))
except (InvalidOperation, TypeError, ValueError):
raise ValueError(f'Invalid {field}.') from None
if not amount.is_finite() or amount < 0 or (positive and amount == 0) or amount > Decimal('9999999.999'):
raise ValueError(f'Invalid {field}.')
return amount
def package_size(product):
if product.package_amount is not None:
return product.package_amount, product.package_unit
match = re.fullmatch(r'\s*(\d+(?:[.,]\d+)?)\s*(g|ml)\s*', product.package_quantity, re.IGNORECASE)
if match:
return Decimal(match.group(1).replace(',', '.')), match.group(2).lower()
return None, ''
def match_data(product, confidence, source=None):
amount, unit = package_size(product)
return {'product_id': str(product.api_id), 'source': source or product.source,
'external_id': product.barcode if product.source == FoodProduct.Source.OPEN_FOOD_FACTS else None,
'name': product.product_name, 'brand': product.brand, 'barcode': product.barcode or None,
'package_quantity': str(amount) if amount is not None else None, 'package_unit': unit or None,
'nutrition_per_100': {field: str(getattr(product, model_field)) if getattr(product, model_field) is not None else None
for field, model_field in NUTRITION_FIELDS.items()}, 'confidence': confidence}
def _same_package(product, amount, unit):
existing_amount, existing_unit = package_size(product)
return amount is None or (existing_amount == amount and existing_unit == unit)
def local_matches(user, name='', brand='', barcode='', amount=None, unit='', limit=10, include_partial=False):
qs = FoodProduct.objects.filter(owner=user)
if barcode:
exact = qs.filter(barcode=barcode).first()
if exact:
return [match_data(exact, 'exact_barcode')]
if not name:
return []
if include_partial:
for token in name.split():
qs = qs.filter(Q(product_name__icontains=token) | Q(brand__icontains=token))
else:
qs = qs.filter(product_name__iexact=name)
candidates = list(qs.order_by('pk')[:100])
if brand:
candidates = [p for p in candidates if p.brand.casefold() == brand.casefold()]
if amount is not None and not include_partial:
candidates = [p for p in candidates if _same_package(p, amount, unit)]
candidates.sort(key=lambda p: (p.product_name.casefold() != name.casefold(),
p.brand.casefold() != brand.casefold() if brand else False,
not _same_package(p, amount, unit), p.pk))
return [match_data(p, 'exact_details' if p.product_name.casefold() == name.casefold() and
brand and p.brand.casefold() == brand.casefold() and amount is not None and
_same_package(p, amount, unit) else 'candidate') for p in candidates[:limit]]
def external_matches(user, query='', barcode='', brand='', amount=None, unit='', limit=10):
if barcode:
# A lookup must never mutate the product catalogue. Search results are read-only.
from food.services.openfoodfacts import OpenFoodFactsClient, _rate_limit, map_product
_rate_limit(user.pk, 'product', 10)
raw = OpenFoodFactsClient().get_product(barcode)
products = [map_product(raw)] if raw else []
else:
products = cached_search(user, query)[:20]
matches = []
for product in products:
if not product:
continue
if barcode and product['barcode'] != barcode:
continue
package_amount = product.get('package_amount')
package_unit = product.get('package_unit') or None
exact = bool(barcode and product['barcode'] == barcode)
details = bool(query and brand and amount is not None and
product['product_name'].casefold() == query.casefold() and
product['brand'].casefold() == brand.casefold() and
package_amount == amount and package_unit == unit)
matches.append({'product_id': None, 'source': 'open_food_facts', 'external_id': product['barcode'],
'name': product['product_name'], 'brand': product['brand'], 'barcode': product['barcode'],
'package_quantity': str(package_amount) if package_amount is not None else None,
'package_unit': package_unit,
'nutrition_per_100': {field: str(product[model_field]) if product.get(model_field) is not None else None
for field, model_field in NUTRITION_FIELDS.items()},
'confidence': 'exact_barcode' if exact else 'exact_details' if details else 'candidate'})
matches.sort(key=lambda item: (
0 if item['confidence'] == 'exact_barcode' else 1 if item['confidence'] == 'exact_details' else 2,
item['name'].casefold() != query.casefold() if query else False,
item['brand'].casefold() != brand.casefold() if brand else False,
Decimal(item['package_quantity']) != amount if amount is not None and item['package_quantity'] else bool(amount)))
return matches[:limit]
def create_manual(user, data):
allowed = {'name', 'brand', 'barcode', 'package_quantity', 'package_unit', 'nutrition_per_100', 'source'}
if set(data) - allowed or data.get('source', 'manual') != 'manual':
raise ValueError('Invalid manual product fields.')
name = _name(data.get('name'), 'name', 255, True)
brand = _name(data.get('brand', ''), 'brand', 255)
barcode = _name(data.get('barcode') or '', 'barcode', 64)
if barcode and not re.fullmatch(r'[0-9]{1,64}', barcode):
raise ValueError('Barcode must be numeric.')
amount = data.get('package_quantity')
unit = data.get('package_unit') or ''
if (amount is None) != (not unit) or (unit and unit not in Unit.values):
raise ValueError('Package quantity and unit must be supplied together.')
amount = _amount(amount, 'package_quantity') if amount is not None else None
nutrition = data.get('nutrition_per_100') or {}
if not isinstance(nutrition, dict) or set(nutrition) - NUTRITION_FIELDS.keys():
raise ValueError('Invalid nutrition fields.')
nutrients = {model_field: _amount(value, field, False) if value is not None else None
for field, model_field in NUTRITION_FIELDS.items() for value in [nutrition.get(field)]}
with transaction.atomic():
# Serialize concurrent creates for one owner, including products without barcodes.
get_user_model().objects.select_for_update().get(pk=user.pk)
if barcode:
existing = FoodProduct.objects.filter(owner=user, barcode=barcode).first()
if existing:
return existing, 'reused', []
exact = local_matches(user, name, brand, '', amount, unit, 20)
if exact:
if len(exact) == 1 and not barcode and (amount is not None or not exact[0]['package_quantity']):
return FoodProduct.objects.get(api_id=exact[0]['product_id']), 'reused', []
return None, 'needs_review', exact
product = FoodProduct(owner=user, product_name=name, brand=brand, barcode=barcode,
package_quantity=f'{amount:g} {unit}' if amount is not None else '',
package_amount=amount, package_unit=unit, base_unit=unit or Unit.GRAM,
source=FoodProduct.Source.MANUAL, **nutrients)
product.full_clean()
product.save()
return product, 'created', []
def import_off(user, barcode):
if not isinstance(barcode, str) or not re.fullmatch(r'[0-9]{1,64}', barcode):
raise ValueError('Enter a numeric Open Food Facts barcode.')
product = cached_product(user, barcode)
return product