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
+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