diff --git a/app.py b/app.py index 22167a3..9abd138 100644 --- a/app.py +++ b/app.py @@ -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 diff --git a/requirements.txt b/requirements.txt index 001e7c4..56f9b6e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1 +1,2 @@ flask>=3.0 +anthropic>=0.40 diff --git a/templates/index.html b/templates/index.html index 6f33465..788d29b 100644 --- a/templates/index.html +++ b/templates/index.html @@ -238,7 +238,7 @@ {% if item.get('de') %}🇩🇪 {{ item.de }}{% endif %} {% if item.get('note') %}{{ item.note }}{% endif %} {% set d = deals.get(item.key) %} - {% if d %}🏷 på tilbud: {{ "{:.2f}".format(d.price_eur).replace(".",",") }} € ≈ {{ "{:.0f}".format(d.price_eur * eur_dkk) }} kr. · {{ d.heading }}{% endif %} + {% if d %}🏷 på tilbud: {{ "{:.2f}".format(d.price_eur).replace(".",",") }} € ≈ {{ "{:.0f}".format(d.price_eur * eur_dkk) }} kr. · {{ d.heading_da or d.heading }}{% endif %}
- {{ o.heading }} + {{ o.heading_da or o.heading }} + {% if o.heading_da and o.heading_da != o.heading %}🇩🇪 {{ o.heading }}{% endif %} {{ o.catalog }}{% if o.page %} · s. {{ o.page }}{% endif %}{% if o.unit %} · {{ o.size_from|int if o.size_from else '' }}{{ o.unit }}{% endif %}
diff --git a/templates/koeb_nu.html b/templates/koeb_nu.html index e862d45..d186705 100644 --- a/templates/koeb_nu.html +++ b/templates/koeb_nu.html @@ -95,7 +95,7 @@
{{ r.sec.emoji }} {{ r.item.name }}{% if r.bought %} ✓{% endif %}
-
{{ r.offer.heading }} · {{ r.offer.catalog }}{% if r.offer.page %} · s. {{ r.offer.page }}{% endif %}
+
🏷 {{ r.offer.heading_da or r.offer.heading }} · {{ r.offer.catalog }}{% if r.offer.page %} · s. {{ r.offer.page }}{% endif %}
{{ "{:.2f}".format(r.offer.price_eur).replace(".",",") }} € ≈ {{ "{:.0f}".format(r.offer_dkk) }} kr.
@@ -124,7 +124,7 @@
🏷 Lübeck-tilbud
- {% for p in picks_remaining %}{{ p.heading }}{% endfor %} + {% for p in picks_remaining %}{{ p.heading_da or p.heading }}{% endfor %}
{% endif %} @@ -140,8 +140,8 @@ {% for o in other %}
-
{{ o.heading }}
-
{{ o.catalog }}{% if o.page %} · s. {{ o.page }}{% endif %}{% if o.unit and o.size_from %} · {{ o.size_from|int }} {{ o.unit }}{% endif %}
+
{{ o.heading_da or o.heading }}
+
{% if o.heading_da and o.heading_da != o.heading %}🇩🇪 {{ o.heading }} · {% endif %}{{ o.catalog }}{% if o.page %} · s. {{ o.page }}{% endif %}{% if o.unit and o.size_from %} · {{ o.size_from|int }} {{ o.unit }}{% endif %}
{{ "{:.2f}".format(o.price_eur).replace(".",",") }} €
diff --git a/templates/tilbud.html b/templates/tilbud.html index 94edfec..6c6810c 100644 --- a/templates/tilbud.html +++ b/templates/tilbud.html @@ -35,6 +35,7 @@ .offer.picked { background: var(--green-light); } .offer input[type=checkbox] { width: 20px; height: 20px; accent-color: var(--green); cursor: pointer; } .o-name { font-size: 14px; } + .o-de { font-size: 10px; color: #b0aba3; font-style: italic; margin-top: 1px; } .o-meta { font-size: 11px; color: var(--muted); margin-top: 1px; } .o-price { text-align: right; white-space: nowrap; } .o-eur { font-family: var(--mono); font-weight: 600; font-size: 15px; } @@ -87,7 +88,8 @@