"""Portable, owner-scoped structured nutrition import and lookup.""" import hashlib import json import re from datetime import date from decimal import Decimal, InvalidOperation from django.core import signing from django.db import transaction from django.db.models import Exists, OuterRef, Q from .models import CanonicalIngredient, KitchenInventoryItem, NutritionSource, SuggestedIngredient CATEGORIES = {'vegetable', 'fruit', 'herb', 'spice', 'bread', 'grain', 'meat', 'fish', 'dairy', 'legume', 'nuts_seeds', 'oil_fat', 'sauce', 'beverage', 'other', 'unresolved'} UNITS = {'g', 'kg', 'ml', 'L', 'pieces', 'tsp', 'tbsp', 'portions'} PREPARATIONS = {'raw', 'cooked', 'dry', 'prepared', 'unknown'} MAX_ROWS = 100 def normalized(value): return re.sub(r'\s+', ' ', value.strip()).casefold() def digest(value): return hashlib.sha256(json.dumps(value, sort_keys=True, ensure_ascii=False, separators=(',', ':')).encode()).hexdigest() def validate(user, payload): if not isinstance(payload, dict): raise ValueError('Provide a structured import payload.') source = payload.get('source') rows = payload.get('ingredients') if not isinstance(source, dict) or not isinstance(rows, list) or not 1 <= len(rows) <= MAX_ROWS: raise ValueError('Provide source and 1–100 ingredient rows.') programme = str(source.get('programme', '')).strip() name = str(source.get('document_name', '')).strip() sha = str(source.get('sha256', '')).lower() if not programme or len(programme) > 80 or not name or len(name) > 255 or not re.fullmatch(r'[0-9a-f]{64}', sha): raise ValueError('Source needs programme, document_name and a PDF SHA-256 hash.') for field in ('week_start', 'week_end'): if source.get(field): date.fromisoformat(source[field]) existing_source = NutritionSource.objects.filter(user=user, sha256=sha).first() seen = set() output = [] blocking = [] for index, row in enumerate(rows): if not isinstance(row, dict): raise ValueError(f'Row {index + 1} must be an object.') label = str(row.get('original_label', '')).strip() canonical_name = str(row.get('canonical_name', '')).strip() form = str(row.get('form', '')).strip().lower() prep = str(row.get('preparation', 'unknown')).lower() category = str(row.get('category', 'unresolved')).lower() unit = str(row.get('unit', '')).strip() key = str(row.get('row_key', index + 1)).strip() page = row.get('page') try: quantity = Decimal(str(row.get('quantity'))) except (InvalidOperation, TypeError): raise ValueError(f'Row {index + 1}: invalid quantity.') from None if not label or not canonical_name or len(label) > 255 or len(canonical_name) > 180 or not key or len(key) > 100 or quantity <= 0 or not quantity.is_finite() or quantity.as_tuple().exponent < -3 or quantity >= 10000000 or not isinstance(page, int) or isinstance(page, bool) or page < 1: raise ValueError(f'Row {index + 1}: label, name, positive quantity, row key and page are required.') if key in seen: blocking.append(f'row {index + 1}: duplicate row_key {key}') seen.add(key) if unit not in UNITS or prep == 'unknown' or category == 'unresolved': blocking.append(f'row {index + 1}: review unit, preparation or classification') if prep not in PREPARATIONS or category not in CATEGORIES or len(form) > 80: raise ValueError(f'Row {index + 1}: invalid preparation, category or form.') try: confidence = Decimal(str(row.get('confidence', '0.5'))) except (InvalidOperation, TypeError): raise ValueError(f'Row {index + 1}: invalid confidence.') from None if not confidence.is_finite() or not 0 <= confidence <= 1: raise ValueError(f'Row {index + 1}: confidence must be 0–1.') nutrition = row.get('nutrition') or {} if not isinstance(nutrition, dict) or any(k not in {'energy_kcal', 'protein_g', 'carbohydrates_g', 'fat_g', 'fibre_g'} for k in nutrition): raise ValueError(f'Row {index + 1}: invalid nutrition fields.') for field, value in nutrition.items(): if value is not None: try: nutrient = Decimal(str(value)) except (InvalidOperation, TypeError): raise ValueError(f'Row {index + 1}: invalid {field}.') from None if not nutrient.is_finite() or nutrient < 0: raise ValueError(f'Row {index + 1}: invalid {field}.') candidates = list(CanonicalIngredient.objects.filter(user=user, normalized_name=normalized(canonical_name), form=form, preparation=prep).values('id', 'name', 'category')[:2]) aliases = row.get('aliases') or [] if not isinstance(aliases, list) or len(aliases) > 20 or any(not isinstance(a, str) or len(a) > 180 for a in aliases): raise ValueError(f'Row {index + 1}: invalid aliases.') uncertainty = row.get('uncertainty') or [] if not isinstance(uncertainty, list) or len(uncertainty) > 20 or any(not isinstance(note, str) or len(note) > 255 for note in uncertainty): raise ValueError(f'Row {index + 1}: invalid uncertainty notes.') output.append({'row_key': key, 'original_label': label, 'canonical_name': canonical_name, 'quantity': str(quantity), 'unit': unit, 'preparation': prep, 'category': category, 'subcategory': str(row.get('subcategory', ''))[:80], 'form': form, 'page': page, 'confidence': str(confidence), 'aliases': aliases, 'nutrition': {k: str(v) if v is not None else None for k, v in nutrition.items()}, 'uncertainty': uncertainty, 'candidates': [{'id': str(c['id']), 'name': c['name'], 'category': c['category']} for c in candidates]}) if candidates and candidates[0]['category'] != category: blocking.append(f'row {index + 1}: existing canonical classification differs') return {'source': {'programme': programme, 'document_name': name, 'sha256': sha, 'week_start': source.get('week_start'), 'week_end': source.get('week_end')}, 'ingredients': output, 'existing_source_id': str(existing_source.pk) if existing_source else None, 'blocking': blocking} def preview(user, payload): result = validate(user, payload) result['version'] = 1 result['payload_hash'] = digest(payload) result['confirmation'] = signing.dumps({'user': user.pk, 'hash': result['payload_hash']}, salt='nutrition-import') return result @transaction.atomic def commit(user, payload, confirmation, idempotency_key): if not isinstance(payload, dict): raise ValueError('Provide a structured import payload.') if not idempotency_key or len(idempotency_key) > 128: raise ValueError('Provide an idempotency key.') try: signed = signing.loads(confirmation, salt='nutrition-import', max_age=600) except signing.BadSignature: raise ValueError('Preview confirmation expired or invalid.') from None if signed != {'user': user.pk, 'hash': digest(payload)}: raise ValueError('Preview does not match this user and payload.') prior = NutritionSource.objects.filter(user=user, idempotency_key=idempotency_key).first() if prior: if prior.payload_hash != digest(payload): raise ValueError('Idempotency key reused with different payload.') return {'source_id': str(prior.pk), 'created': 0, 'skipped': prior.ingredients.count(), 'idempotent': True} result = validate(user, payload) if result['blocking']: raise ValueError('Resolve preview blockers before commit: ' + '; '.join(result['blocking'])) if result['existing_source_id']: raise ValueError('This PDF was already imported; amended extraction requires a reviewed revision.') source = NutritionSource.objects.create(user=user, payload_hash=digest(payload), idempotency_key=idempotency_key, **result['source']) for row in result['ingredients']: canonical, _ = CanonicalIngredient.objects.get_or_create(user=user, normalized_name=normalized(row['canonical_name']), form=row['form'], preparation=row['preparation'], defaults={'name': row['canonical_name'], 'category': row['category'], 'subcategory': row['subcategory'], 'aliases': row['aliases'], 'confidence': row['confidence']}) SuggestedIngredient.objects.create(source=source, canonical=canonical, row_key=row['row_key'], original_label=row['original_label'], quantity=row['quantity'], unit=row['unit'], preparation=row['preparation'], page=row['page'], nutrition=row['nutrition'], uncertainty=row['uncertainty']) return {'source_id': str(source.pk), 'created': len(result['ingredients']), 'skipped': 0, 'idempotent': False} def search(user, *, category='', subcategory='', programme='', query='', form='', verified=None, inventory_status='', limit=20, offset=0): if inventory_status not in ('', 'in_stock', 'not_found'): raise ValueError('Invalid inventory_status.') qs = CanonicalIngredient.objects.filter(user=user) if category: qs = qs.filter(category=category) if subcategory: qs = qs.filter(subcategory=subcategory) if form: qs = qs.filter(form=form) if verified is not None: qs = qs.filter(verified=verified) if programme: qs = qs.filter(suggestions__source__programme__iexact=programme) if query: qs = qs.filter(Q(name__icontains=query) | Q(aliases__icontains=query)) stock_query = KitchenInventoryItem.objects.filter(user=user, archived_at__isnull=True, product__product_name__iexact=OuterRef('name')) qs = qs.annotate(has_stock_name=Exists(stock_query)) if inventory_status == 'in_stock': qs = qs.filter(has_stock_name=True) if inventory_status == 'not_found': qs = qs.filter(has_stock_name=False) qs = qs.distinct().order_by('name', 'pk') results = [] for ingredient in qs[offset:offset + limit]: stock = list(KitchenInventoryItem.objects.filter(user=user, archived_at__isnull=True, product__product_name__iexact=ingredient.name).values('api_id', 'product__product_name')[:10]) sources = list(SuggestedIngredient.objects.filter(canonical=ingredient).select_related('source').order_by('-source__imported_at')[:5]) results.append({'id': str(ingredient.pk), 'name': ingredient.name, 'category': ingredient.category, 'subcategory': ingredient.subcategory, 'form': ingredient.form, 'preparation': ingredient.preparation, 'aliases': ingredient.aliases, 'confidence': str(ingredient.confidence), 'provenance': ingredient.provenance, 'verified': ingredient.verified, 'sources': [{'programme': s.source.programme, 'document_name': s.source.document_name, 'source_id': str(s.source_id), 'page': s.page, 'original_label': s.original_label, 'quantity': str(s.quantity), 'unit': s.unit, 'nutrition': s.nutrition} for s in sources], 'inventory': {'status': 'exact_name_candidate' if stock else 'not_found', 'items': [{'id': str(s['api_id']), 'product_name': s['product__product_name']} for s in stock], 'note': 'Name match requires product and quantity review; no nutritional equivalence is inferred.'}}) return {'count': qs.count(), 'limit': limit, 'offset': offset, 'results': results} @transaction.atomic def correct_classification(user, identifier, changes): ingredient = CanonicalIngredient.objects.select_for_update().get(pk=identifier, user=user) allowed = {'category', 'subcategory', 'aliases'} if not isinstance(changes, dict) or not changes or set(changes) - allowed: raise ValueError('Provide category, subcategory or aliases only.') if 'category' in changes and changes['category'] not in CATEGORIES: raise ValueError('Invalid category.') if 'aliases' in changes and (not isinstance(changes['aliases'], list) or len(changes['aliases']) > 20 or any(not isinstance(x, str) or len(x) > 180 for x in changes['aliases'])): raise ValueError('Invalid aliases.') for field in ('subcategory',): if field in changes and (not isinstance(changes[field], str) or len(changes[field]) > 80): raise ValueError(f'Invalid {field}.') for field, value in changes.items(): setattr(ingredient, field, value) ingredient.verified = True ingredient.provenance = 'manual_correction' ingredient.save(update_fields=[*changes, 'verified', 'provenance']) return {'id': str(ingredient.pk), 'category': ingredient.category, 'subcategory': ingredient.subcategory, 'aliases': ingredient.aliases, 'form': ingredient.form, 'verified': ingredient.verified, 'provenance': ingredient.provenance}