fix(off): usar search-a-licious (el cgi/search.pl legacy da 503 a datacenter)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Carlos Narro
2026-07-01 19:57:45 +02:00
parent 461a1c8a8c
commit b90c48c257

23
off.py
View File

@@ -2,7 +2,9 @@
alimento de la app. Tolerante a fallos: devuelve [] si algo va mal.""" alimento de la app. Tolerante a fallos: devuelve [] si algo va mal."""
import httpx import httpx
_SEARCH = "https://world.openfoodfacts.org/cgi/search.pl" # Search-a-licious: el endpoint de texto fiable de OFF (el legacy cgi/search.pl
# devuelve 503 a IPs de datacenter).
_SEARCH = "https://search.openfoodfacts.org/search"
def search(q: str, limit: int = 12) -> list[dict]: def search(q: str, limit: int = 12) -> list[dict]:
@@ -11,22 +13,19 @@ def search(q: str, limit: int = 12) -> list[dict]:
resp = httpx.get( resp = httpx.get(
_SEARCH, _SEARCH,
params={ params={
"search_terms": q, "q": q,
"search_simple": 1,
"action": "process",
"json": 1,
"page_size": limit, "page_size": limit,
"fields": "product_name,nutriments,code", "fields": "code,product_name,nutriments",
}, },
timeout=6.0, timeout=6.0,
headers={"User-Agent": "autoayuno/1.0 (self-hosted)"}, headers={"User-Agent": "autoayuno/1.0 (self-hosted; carlos)"},
) )
if resp.status_code != 200: if resp.status_code != 200:
return [] return []
out = [] out = []
for p in resp.json().get("products", []): for h in resp.json().get("hits", []):
name = (p.get("product_name") or "").strip() name = (h.get("product_name") or "").replace("\n", " ").strip()
kcal = p.get("nutriments", {}).get("energy-kcal_100g") kcal = (h.get("nutriments") or {}).get("energy-kcal_100g")
if not name or kcal is None: if not name or kcal is None:
continue continue
try: try:
@@ -38,8 +37,8 @@ def search(q: str, limit: int = 12) -> list[dict]:
out.append({ out.append({
"name": name[:120], "name": name[:120],
"kcal_100g": kcal, "kcal_100g": kcal,
"off_id": p.get("code"), "off_id": h.get("code"),
"barcode": p.get("code"), "barcode": h.get("code"),
}) })
return out return out
except Exception: except Exception: