Files
Django_TasksApp/main/food/services/openfoodfacts.py
T

185 lines
7.4 KiB
Python

"""Explicit Open Food Facts reads and user-owned local product caching."""
import json
import logging
import re
from hashlib import sha256
from datetime import timedelta
from decimal import Decimal, InvalidOperation
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.parse import urlparse
from urllib.request import Request, urlopen
from django.conf import settings
from django.core.cache import cache
from django.utils import timezone
from food.models import FoodProduct, Unit
logger = logging.getLogger(__name__)
FIELDS = 'code,product_name,brands,quantity,serving_size,serving_quantity,image_front_small_url,image_front_url,nutriments'
NUTRIENTS = {
'energy-kcal_100g': 'energy_kcal_100',
'carbohydrates_100g': 'carbohydrates_100',
'proteins_100g': 'protein_100',
'fat_100g': 'fat_100',
'saturated-fat_100g': 'saturated_fat_100',
'sugars_100g': 'sugars_100',
'fiber_100g': 'fibre_100',
'salt_100g': 'salt_100',
}
class OpenFoodFactsError(Exception):
pass
class OpenFoodFactsRateLimit(OpenFoodFactsError):
pass
def normalise_query(query):
return ' '.join(query.split()).casefold()
def _decimal(value):
try:
number = Decimal(str(value))
if not number.is_finite() or number < 0:
return None
return number.quantize(Decimal('0.001'))
except (InvalidOperation, TypeError, ValueError):
return None
def map_product(data):
"""Map only trusted display fields; unknown nutrients remain NULL."""
if not isinstance(data, dict):
return None
code = str(data.get('code') or '').strip()
name = str(data.get('product_name') or '').strip()
if not re.fullmatch(r'[0-9]{1,64}', code) or not name:
return None
nutriments = data.get('nutriments') or {}
if not isinstance(nutriments, dict):
nutriments = {}
values = {field: _decimal(nutriments.get(key)) for key, field in NUTRIENTS.items()}
serving_text = str(data.get('serving_size') or '')[:100]
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 ''
image_url = str(data.get('image_front_small_url') or data.get('image_front_url') or '')
try:
parsed_image = urlparse(image_url)
trusted_image = parsed_image.scheme == 'https' and parsed_image.hostname in {'images.openfoodfacts.org', 'static.openfoodfacts.org'}
except ValueError:
trusted_image = False
if not trusted_image:
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,
'serving_amount': serving_amount, 'serving_unit': serving_unit,
'base_unit': Unit.MILLILITRE if serving_unit == 'ml' else Unit.GRAM, **values}
def _rate_limit(user_id, kind, limit):
"""Simple per-user, per-minute guard; a shared cache backend is advised in production."""
key = f'off:limit:{kind}:{user_id}:{timezone.now():%Y%m%d%H%M}'
cache.add(key, 0, 70)
try:
count = cache.incr(key)
except ValueError:
cache.set(key, 1, 70)
count = 1
if count > limit:
raise OpenFoodFactsRateLimit('Open Food Facts request limit reached. Try again in a minute.')
class OpenFoodFactsClient:
def _get_json(self, url, params=None):
if not settings.OPENFOODFACTS_ENABLED:
raise OpenFoodFactsError('Open Food Facts is unavailable.')
if params:
url = f'{url}?{urlencode(params)}'
request = Request(url, headers={'User-Agent': settings.OPENFOODFACTS_USER_AGENT, 'Accept': 'application/json'})
try:
with urlopen(request, timeout=settings.OPENFOODFACTS_TIMEOUT_SECONDS) as response:
data = json.load(response)
except (HTTPError, URLError, TimeoutError, ValueError, OSError) as error:
logger.warning('Open Food Facts request failed: %s', error)
raise OpenFoodFactsError('Open Food Facts is temporarily unavailable.') from error
if not isinstance(data, dict):
raise OpenFoodFactsError('Open Food Facts returned an invalid response.')
return data
def get_product(self, barcode):
if not re.fullmatch(r'[0-9]{1,64}', barcode):
raise ValueError('Enter a numeric barcode.')
data = self._get_json(settings.OPENFOODFACTS_PRODUCT_URL.format(barcode=barcode), {'fields': FIELDS})
return data.get('product') if data.get('status') == 1 else None
def search(self, query, page=1):
query = normalise_query(query)
if not query or len(query) > 100 or page < 1 or page > 20:
raise ValueError('Enter a search query and valid page.')
data = self._get_json(settings.OPENFOODFACTS_SEARCH_URL, {'action': 'process', 'search_simple': 1,
'json': 1, 'search_terms': query, 'page': page, 'page_size': 20, 'fields': FIELDS})
products = data.get('products')
if not isinstance(products, list):
raise OpenFoodFactsError('Open Food Facts returned an invalid response.')
return [mapped for item in products if (mapped := map_product(item))]
def cached_product(user, barcode, *, refresh=False):
if not re.fullmatch(r'[0-9]{1,64}', barcode):
raise ValueError('Enter a numeric barcode.')
product = FoodProduct.objects.filter(owner=user, barcode=barcode).first()
if product and (product.source == FoodProduct.Source.MANUAL or
(not refresh and product.fetched_at and product.fetched_at >= timezone.now() - timedelta(days=7))):
return product
if not settings.OPENFOODFACTS_ENABLED:
return product
_rate_limit(user.pk, 'product', 10)
try:
data = OpenFoodFactsClient().get_product(barcode)
except OpenFoodFactsError:
if product:
return product
raise
mapped = map_product(data)
if not mapped:
return product
mapped['source'] = FoodProduct.Source.OPEN_FOOD_FACTS
mapped['fetched_at'] = timezone.now()
nutrients = data.get('nutriments') if isinstance(data.get('nutriments'), dict) else {}
mapped['raw_data'] = {'code': barcode, 'product_name': mapped['product_name'],
'nutriments': {key: nutrients.get(key) for key in NUTRIENTS}}
product, _ = FoodProduct.objects.update_or_create(owner=user, barcode=barcode, defaults=mapped)
return product
def cached_search(user, query, page=1):
normalized = normalise_query(query)
if not normalized or len(normalized) > 100 or page < 1 or page > 20:
raise ValueError('Enter a search query and valid page.')
digest = sha256(normalized.encode()).hexdigest()
key = f'off:search:{digest}:{page}'
result = cache.get(key)
if result is not None:
return result
_rate_limit(user.pk, 'search', 5)
_rate_limit('all', 'search', 8)
lock_key = f'{key}:lock'
if not cache.add(lock_key, True, 20):
result = cache.get(key)
if result is not None:
return result
raise OpenFoodFactsError('This search is already running. Try again shortly.')
try:
result = OpenFoodFactsClient().search(normalized, page)
cache.set(key, result, 24 * 60 * 60)
return result
finally:
cache.delete(lock_key)