worktree-citti-arkiver-tur #2

Merged
hjess merged 2 commits from worktree-citti-arkiver-tur into main 2026-10-30 11:09:31 +01:00
5 changed files with 182 additions and 10 deletions
Showing only changes of commit 8dd435a7d0 - Show all commits

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

View File

@@ -1 +1,2 @@
flask>=3.0
anthropic>=0.40

View File

@@ -238,7 +238,7 @@
{% if item.get('de') %}<span class="de">🇩🇪 {{ item.de }}</span>{% endif %}
{% if item.get('note') %}<span class="note">{{ item.note }}</span>{% endif %}
{% set d = deals.get(item.key) %}
{% if d %}<a class="deal" href="/tilbud" title="{{ d.heading }} ({{ d.catalog }})">🏷 på tilbud: {{ "{:.2f}".format(d.price_eur).replace(".",",") }} € ≈ {{ "{:.0f}".format(d.price_eur * eur_dkk) }} kr. · {{ d.heading }}</a>{% endif %}
{% if d %}<a class="deal" href="/tilbud" title="{{ d.heading }} ({{ d.catalog }})">🏷 på tilbud: {{ "{:.2f}".format(d.price_eur).replace(".",",") }} € ≈ {{ "{:.0f}".format(d.price_eur * eur_dkk) }} kr. · {{ d.heading_da or d.heading }}</a>{% endif %}
</div>
<div class="item-qty">
<input type="text" value="{{ s.get('qty') or item.qty }}" placeholder="{{ item.qty }}"
@@ -278,7 +278,8 @@
<div class="item-row{% if ps.get('checked') %} checked{% endif %}" data-key="{{ o.id }}" id="pick-{{ o.id }}">
<div class="item-check"><input type="checkbox" {% if ps.get('checked') %}checked{% endif %} onchange="toggleOffer(this)"></div>
<div class="item-name">
{{ o.heading }}
{{ o.heading_da or o.heading }}
{% if o.heading_da and o.heading_da != o.heading %}<span class="de">🇩🇪 {{ o.heading }}</span>{% endif %}
<span class="note">{{ o.catalog }}{% if o.page %} · s. {{ o.page }}{% endif %}{% if o.unit %} · {{ o.size_from|int if o.size_from else '' }}{{ o.unit }}{% endif %}</span>
</div>
<div class="item-qty" style="display:flex;align-items:center;color:var(--muted);font-size:12px">

View File

@@ -95,7 +95,7 @@
<div class="row{% if r.bought %} bought{% endif %}">
<div>
<div class="r-name">{{ r.sec.emoji }} {{ r.item.name }}{% if r.bought %} ✓{% endif %}</div>
<div class="r-meta">{{ r.offer.heading }} · {{ r.offer.catalog }}{% if r.offer.page %} · s. {{ r.offer.page }}{% endif %}</div>
<div class="r-meta">🏷 {{ r.offer.heading_da or r.offer.heading }} · {{ r.offer.catalog }}{% if r.offer.page %} · s. {{ r.offer.page }}{% endif %}</div>
</div>
<div class="r-right">
<div class="r-price">{{ "{:.2f}".format(r.offer.price_eur).replace(".",",") }} € <span class="r-dkk">≈ {{ "{:.0f}".format(r.offer_dkk) }} kr.</span></div>
@@ -124,7 +124,7 @@
<div class="sec-group">
<div class="sec-h">🏷 Lübeck-tilbud</div>
<div class="chips">
{% for p in picks_remaining %}<span class="chip">{{ p.heading }}</span>{% endfor %}
{% for p in picks_remaining %}<span class="chip">{{ p.heading_da or p.heading }}</span>{% endfor %}
</div>
</div>
{% endif %}
@@ -140,8 +140,8 @@
{% for o in other %}
<div class="row">
<div>
<div class="r-name">{{ o.heading }}</div>
<div class="r-meta">{{ o.catalog }}{% if o.page %} · s. {{ o.page }}{% endif %}{% if o.unit and o.size_from %} · {{ o.size_from|int }} {{ o.unit }}{% endif %}</div>
<div class="r-name">{{ o.heading_da or o.heading }}</div>
<div class="r-meta">{% 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 %}</div>
</div>
<div class="r-right">
<div class="r-price">{{ "{:.2f}".format(o.price_eur).replace(".",",") }} €</div>

View File

@@ -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 @@
<label class="offer{% if o.picked %} picked{% endif %}" data-name="{{ o.heading|lower }}">
<input type="checkbox" {% if o.picked %}checked{% endif %} onchange="togglePick(this, '{{ o.id }}')">
<div>
<div class="o-name">{{ o.heading }}</div>
<div class="o-name">{{ o.heading_da or o.heading }}</div>
{% if o.heading_da and o.heading_da != o.heading %}<div class="o-de">🇩🇪 {{ o.heading }}</div>{% endif %}
<div class="o-meta">
{% if o.page %}s. {{ o.page }}{% endif %}
{% if o.unit and o.size_from %} · {{ o.size_from|int }}{% if o.size_to and o.size_to != o.size_from %}–{{ o.size_to|int }}{% endif %} {{ o.unit }}{% endif %}