feat(offers): Danish translation and AI matching via Claude

Offers come from the German avis, so add Claude-backed language help,
reusing BlaaAi's ANTHROPIC_API_KEY + Haiku pattern. Both degrade
gracefully: without a key, offers stay German and the token heuristic
still matches.

- Translate offer headings DE→DA in the fetch job, cached per heading
  in a translations table (only new headings cost a call). UI shows
  Danish primary + German subtitle for in-store navigation.
- AI match the fixed list against offers (offer_matches table): Claude
  returns same-product matches, far more precise than the token
  heuristic (which false-matched e.g. Nutella jar → advent calendar).
  load_deals() prefers AI matches, falls back to the heuristic.
- Haiku 5.5 by default (MATCH_MODEL/TRANSLATE_MODEL env overridable to
  Sonnet); no temperature param (Haiku 5.5 rejects non-default).
- requirements: add anthropic
This commit is contained in:
Henrik Jess Nielsen
2026-10-30 11:02:47 +01:00
parent 3b0ea28db5
commit 8dd435a7d0
5 changed files with 182 additions and 10 deletions

174
app.py
View File

@@ -29,6 +29,15 @@ TJEK_UA = ("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
EUR_DKK = float(os.environ.get("EUR_DKK", "7.46"))
OFFERS_REFRESH_HOURS = float(os.environ.get("OFFERS_REFRESH_HOURS", "20"))
# German→Danish translation of offer headings via Claude (BlaaAi uses the same
# ANTHROPIC_API_KEY + Haiku pattern). Cached per heading, so only new headings
# cost a call. Without a key, offers simply stay in German.
TRANSLATE_MODEL = os.environ.get("TRANSLATE_MODEL", "claude-haiku-5-5")
TRANSLATE_BATCH = int(os.environ.get("TRANSLATE_BATCH", "40"))
# AI matching of the fixed list against offers (more precise than the token
# heuristic). Bump to claude-sonnet-5-5 via env for harder cases.
MATCH_MODEL = os.environ.get("MATCH_MODEL", "claude-haiku-5-5")
SECTIONS = [
{"id": "koed", "emoji": "🥩", "title": "Kød & fisk", "est": 1580, "varer": [
{"key": "entrecote", "name": "Entrecote ½ kg", "de": "Entrecôte ½ kg", "note": "Frisk sydamerikansk", "qty": "6 × ½ kg", "est": 605.94, "badges": ["card"]},
@@ -158,6 +167,10 @@ def init_db():
picked INTEGER DEFAULT 0)""")
c.execute("""CREATE TABLE IF NOT EXISTS offer_meta (
k TEXT PRIMARY KEY, v TEXT)""")
c.execute("""CREATE TABLE IF NOT EXISTS translations (
de TEXT PRIMARY KEY, da TEXT, created TEXT)""")
c.execute("""CREATE TABLE IF NOT EXISTS offer_matches (
item_key TEXT PRIMARY KEY, offer_id TEXT, updated TEXT)""")
try:
c.execute("ALTER TABLE extras ADD COLUMN section_key TEXT")
except Exception:
@@ -278,7 +291,157 @@ def fetch_offers():
total = c.execute("SELECT COUNT(*) FROM offers").fetchone()[0]
_meta_set(c, 'last_refresh', now_iso)
_meta_set(c, 'last_error', '')
return {'catalogs': cat_count, 'offers_seen': len(seen), 'offers_total': total}
translated = translate_missing() # own short transactions, outside the write above
matched = match_offers_ai()
return {'catalogs': cat_count, 'offers_seen': len(seen),
'offers_total': total, 'translated': translated, 'matched': matched}
def _translate_batch(client, headings):
"""Translate a list of German headings to short Danish names. Returns list
aligned to input (falls back to the German text on any parse gap)."""
numbered = "\n".join(f"{i}. {h}" for i, h in enumerate(headings))
prompt = (
"Oversæt disse tyske dagligvare-tilbudsoverskrifter til korte, naturlige "
"danske produktnavne. Behold mærke-/egennavne uændret. Svar KUN med et JSON-"
'array på formen [{"i":0,"da":"..."}], ét element per linje, intet andet.\n\n'
+ numbered)
msg = client.messages.create(
model=TRANSLATE_MODEL,
max_tokens=4000,
messages=[{"role": "user", "content": prompt}],
)
text = "".join(b.text for b in msg.content if b.type == "text")
m = re.search(r"\[.*\]", text, re.DOTALL)
out = list(headings)
if not m:
app.logger.warning("citti translate: unparseable response: %s", text[:200])
return out
for item in json.loads(m.group(0)):
idx, da = item.get("i"), (item.get("da") or "").strip()
if isinstance(idx, int) and 0 <= idx < len(out) and da:
out[idx] = da
return out
def translate_missing():
"""Translate offer headings that have no Danish cache entry yet. Needs
ANTHROPIC_API_KEY (as in BlaaAi); without it, headings stay German."""
if not os.environ.get("ANTHROPIC_API_KEY"):
return 0
with get_db() as c:
todo = [r['heading'] for r in c.execute(
"SELECT DISTINCT heading FROM offers WHERE heading IS NOT NULL "
"AND heading NOT IN (SELECT de FROM translations)")]
if not todo:
return 0
try:
import anthropic
except Exception as e:
app.logger.warning("citti translate: anthropic SDK unavailable: %s", e)
return 0
client = anthropic.Anthropic()
now = datetime.now(timezone.utc).isoformat()
done = 0
for i in range(0, len(todo), TRANSLATE_BATCH):
batch = todo[i:i + TRANSLATE_BATCH]
try:
das = _translate_batch(client, batch)
except Exception as e:
app.logger.warning("citti translate batch failed: %s", e)
continue
with get_db() as c:
for de, da in zip(batch, das):
c.execute("INSERT OR REPLACE INTO translations(de,da,created) "
"VALUES(?,?,?)", (de, da, now))
done += len(batch)
app.logger.info("citti translate: %d headings translated", done)
return done
def load_translations(c):
return {r['de']: r['da'] for r in c.execute("SELECT de,da FROM translations")}
def attach_da(tmap, *offer_lists):
"""Set heading_da on each offer dict (falls back to German heading)."""
for lst in offer_lists:
for o in lst:
o['heading_da'] = tmap.get(o.get('heading')) or o.get('heading')
# --- AI matching: fixed list ↔ offers (more precise than the token heuristic) -
def match_offers_ai():
"""Ask Claude which offer (if any) is the same product as each fixed item.
Stores results in offer_matches. Needs ANTHROPIC_API_KEY; on no key or
failure the heuristic matcher remains the fallback."""
if not os.environ.get("ANTHROPIC_API_KEY"):
return 0
with get_db() as c:
offers = [dict(r) for r in c.execute(
"SELECT id, heading, catalog FROM offers")]
if not offers:
return 0
try:
import anthropic
except Exception as e:
app.logger.warning("citti match: anthropic SDK unavailable: %s", e)
return 0
items = "\n".join(
f"{it['key']} | {it['name']} | {it.get('de') or ''}"
for it in ITEM_BY_KEY.values())
offer_lines = "\n".join(
f"{o['id']} | {o['heading']} | {o['catalog']}" for o in offers)
prompt = (
"Du matcher en fast dansk indkøbsliste mod aktuelle tyske "
"supermarkeds-tilbud.\n\n"
"VARER (key | dansk navn | tysk navn):\n" + items +
"\n\nTILBUD (offer_id | tysk overskrift | katalog):\n" + offer_lines +
"\n\nFind for hver vare det tilbud der er SAMME slags produkt, hvis et "
"findes. Vær striks: match kun når det tydeligt er samme varetype "
"(fx entrecôte↔entrecôte-tilbud). Match IKKE blot på mærke eller løst "
"beslægtede varer (fx 'Nutella 1kg glas' må IKKE matche 'Nutella "
"julekalender'). Vælg det billigste ved flere ens. Returnér KUN et "
'JSON-array [{"item_key":"...","offer_id":"..."}] med de sikre match, '
"intet andet.")
client = anthropic.Anthropic()
msg = client.messages.create(
model=MATCH_MODEL, max_tokens=4000,
messages=[{"role": "user", "content": prompt}])
text = "".join(b.text for b in msg.content if b.type == "text")
m = re.search(r"\[.*\]", text, re.DOTALL)
if not m:
app.logger.warning("citti match: unparseable response: %s", text[:200])
return 0
valid_items = set(ITEM_BY_KEY)
valid_offers = {o['id'] for o in offers}
pairs = []
for row in json.loads(m.group(0)):
ik, oid = row.get("item_key"), row.get("offer_id")
if ik in valid_items and oid in valid_offers:
pairs.append((ik, oid))
now = datetime.now(timezone.utc).isoformat()
with get_db() as c:
c.execute("DELETE FROM offer_matches")
for ik, oid in pairs:
c.execute("INSERT OR REPLACE INTO offer_matches(item_key,offer_id,updated) "
"VALUES(?,?,?)", (ik, oid, now))
app.logger.info("citti match: %d AI matches", len(pairs))
return len(pairs)
def load_deals(c, offers):
"""Return {item_key: offer_dict}. Prefer stored AI matches; fall back to the
token heuristic when there are none (e.g. no API key yet)."""
by_id = {o['id']: o for o in offers}
ai = {r['item_key']: by_id[r['offer_id']]
for r in c.execute("SELECT item_key, offer_id FROM offer_matches")
if r['offer_id'] in by_id}
if ai:
return ai
return match_catalog_offers(offers) if offers else {}
def refresh_offers_safe():
@@ -382,10 +545,12 @@ def index():
picks = [dict(r) for r in c.execute(
"SELECT * FROM offers WHERE picked=1 ORDER BY catalog, heading")]
all_offers = [dict(r) for r in c.execute("SELECT * FROM offers")]
tmap = load_translations(c)
deals = load_deals(c, all_offers)
by_sec = {}
for e in extras:
by_sec.setdefault(e.get('section_key') or '', []).append(e)
deals = match_catalog_offers(all_offers) if all_offers else {}
attach_da(tmap, picks, list(deals.values()))
return render_template('index.html', sections=SECTIONS, saved=saved,
by_sec=by_sec, custom_secs=custom_secs,
picks=picks, eur_dkk=EUR_DKK, deals=deals)
@@ -582,6 +747,7 @@ def tilbud():
"SELECT * FROM offers ORDER BY catalog, heading")]
last_refresh = _meta_get(c, 'last_refresh')
last_error = _meta_get(c, 'last_error')
attach_da(load_translations(c), offers)
by_cat = {}
for o in offers:
by_cat.setdefault(o.get('catalog') or 'Øvrige', []).append(o)
@@ -623,7 +789,9 @@ def koeb_nu():
offers = [dict(r) for r in c.execute("SELECT * FROM offers")]
picks = [dict(r) for r in c.execute(
"SELECT * FROM offers WHERE picked=1 ORDER BY catalog, heading")]
deals = match_catalog_offers(offers) if offers else {}
tmap = load_translations(c)
deals = load_deals(c, offers)
attach_da(tmap, offers, picks)
# 1) Your fixed items currently on offer. No "saving vs estimate" — the
# estimate is the whole line (e.g. 6 × ½ kg) while the offer price is per