Compare commits

..

11 Commits

Author SHA1 Message Date
d464fe9edc Merge pull request 'worktree-citti-arkiver-tur' (#11) from worktree-citti-arkiver-tur into main
All checks were successful
Build and Deploy citti / build-and-deploy (push) Successful in 49s
Reviewed-on: #11
2026-10-30 13:59:38 +01:00
dfac0f67ad Merge pull request 'worktree-citti-arkiver-tur' (#10) from worktree-citti-arkiver-tur into main
All checks were successful
Build and Deploy citti / build-and-deploy (push) Successful in 41s
Reviewed-on: #10
2026-10-30 13:46:36 +01:00
ec403f4324 Merge pull request 'worktree-citti-arkiver-tur' (#9) from worktree-citti-arkiver-tur into main
All checks were successful
Build and Deploy citti / build-and-deploy (push) Successful in 47s
Reviewed-on: #9
2026-10-30 13:29:44 +01:00
12a4e197f3 Merge pull request 'worktree-citti-arkiver-tur' (#8) from worktree-citti-arkiver-tur into main
All checks were successful
Build and Deploy citti / build-and-deploy (push) Successful in 43s
Reviewed-on: #8
2026-10-30 12:53:39 +01:00
6de7b02aba Merge pull request 'worktree-citti-arkiver-tur' (#7) from worktree-citti-arkiver-tur into main
All checks were successful
Build and Deploy citti / build-and-deploy (push) Successful in 44s
Reviewed-on: #7
2026-10-30 12:28:47 +01:00
90ed399cd9 Merge pull request 'fix(offers): survive Claude rate limits (429)' (#6) from worktree-citti-arkiver-tur into main
All checks were successful
Build and Deploy citti / build-and-deploy (push) Successful in 45s
Reviewed-on: #6
2026-10-30 12:09:37 +01:00
92fa8df574 Merge pull request 'worktree-citti-arkiver-tur' (#5) from worktree-citti-arkiver-tur into main
All checks were successful
Build and Deploy citti / build-and-deploy (push) Successful in 1m57s
Reviewed-on: #5
2026-10-30 12:00:31 +01:00
ed2121e4f8 Merge pull request 'worktree-citti-arkiver-tur' (#4) from worktree-citti-arkiver-tur into main
All checks were successful
Build and Deploy citti / build-and-deploy (push) Successful in 46s
Reviewed-on: #4
2026-10-30 11:47:44 +01:00
b7141d787b Merge pull request 'fix(offers): DE→DA translation returned nothing — disable thinking, batch big' (#3) from worktree-citti-arkiver-tur into main
All checks were successful
Build and Deploy citti / build-and-deploy (push) Successful in 41s
Reviewed-on: #3
2026-10-30 11:23:41 +01:00
21c870189f Merge pull request 'worktree-citti-arkiver-tur' (#2) from worktree-citti-arkiver-tur into main
All checks were successful
Build and Deploy citti / build-and-deploy (push) Successful in 1m4s
Reviewed-on: #2
2026-10-30 11:09:31 +01:00
b0eef226ce Merge pull request 'worktree-citti-arkiver-tur' (#1) from worktree-citti-arkiver-tur into main
All checks were successful
Build and Deploy citti / build-and-deploy (push) Successful in 1m4s
Reviewed-on: #1
2026-10-30 10:44:55 +01:00
4 changed files with 25 additions and 163 deletions

76
app.py
View File

@@ -43,8 +43,6 @@ CLAUDE_MAX_RETRIES = int(os.environ.get("CLAUDE_MAX_RETRIES", "8"))
# 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")
# Vision: identify + categorise a product from a photo in "Tilføj vare".
VISION_MODEL = os.environ.get("VISION_MODEL", "claude-haiku-5-5")
SECTIONS = [
{"id": "koed", "emoji": "🥩", "title": "Kød & fisk", "est": 1580, "varer": [
@@ -314,15 +312,15 @@ def _claude_mode():
return None
def _claude_json(client, model, max_tokens, content):
"""One Claude call returning text. `content` is a prompt string or a list of
content blocks (e.g. an image + text for vision). Thinking is disabled (these
are mechanical JSON tasks and thinking would eat the token budget); if a model
rejects the disabled flag we retry without it. OAuth tokens require the oauth
beta header on /v1/messages, so add it when authenticating with a token."""
def _claude_json(client, model, max_tokens, prompt):
"""One Claude call returning text. Thinking is disabled (these are mechanical
JSON tasks and thinking would eat the token budget); if a model rejects the
disabled flag we retry without it, and the large max_tokens still fits the
output alongside thinking. OAuth tokens require the oauth beta header on
/v1/messages, so add it when authenticating with a token."""
extra = {"anthropic-beta": "oauth-2025-04-20"} if _claude_mode() == "oauth" else {}
kwargs = dict(model=model, max_tokens=max_tokens,
messages=[{"role": "user", "content": content}],
messages=[{"role": "user", "content": prompt}],
extra_headers=extra)
try:
msg = client.messages.create(thinking={"type": "disabled"}, **kwargs)
@@ -423,12 +421,9 @@ def match_offers_ai():
# Skip the (daily) match call when the offer set hasn't changed since the
# last successful match — the avis only turns over weekly, so this avoids a
# pointless Claude call most days. The leading version forces a re-match
# whenever the matching logic/prompt changes (bump it when editing them).
MATCH_VERSION = "v2-standard-not-premium"
# pointless Claude call most days.
sig = hashlib.md5(
(MATCH_VERSION + "\n" + "\n".join(
sorted(o['id'] + '|' + (o.get('heading') or '') for o in offers)))
"\n".join(sorted(o['id'] + '|' + (o.get('heading') or '') for o in offers))
.encode('utf-8')).hexdigest()
with get_db() as c:
if _meta_get(c, 'last_match_sig') == sig and \
@@ -455,10 +450,7 @@ def match_offers_ai():
"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'). Når varen er generisk (fx 'Entrecote ½ kg'), vælg den "
"ALMINDELIGE/standard variant til den LAVESTE pris — undgå premium-/"
"luksus-varianter (Wagyu, Dry-Aged, US-Beef, øko-premium) medmindre varen "
"selv nævner det, da de giver et urealistisk højt estimat. Returnér KUN et "
"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(max_retries=CLAUDE_MAX_RETRIES)
@@ -681,54 +673,6 @@ def add_item():
name=name, section_key=section_key, price=price, note=note)
@app.route('/api/item/analyze', methods=['POST'])
def analyze_item():
"""Identify + categorise a product from a photo via Claude vision. Returns
suggestions {name, de, section, note}; price is always entered manually."""
if not _claude_mode():
return jsonify(ok=False, error='no-credential'), 503
f = request.files.get('photo')
if not f or not f.filename:
return jsonify(ok=False, error='no-photo'), 400
import base64
ext = (os.path.splitext(f.filename)[1] or '.jpg').lower()
media = {'png': 'image/png', 'webp': 'image/webp', 'gif': 'image/gif'}.get(
ext.lstrip('.'), 'image/jpeg')
b64 = base64.standard_b64encode(f.read()).decode()
secs = "; ".join(f"{s['id']}={s['title']}" for s in SECTIONS)
prompt = (
"Billedet viser én dagligvare fra et tysk supermarked (CITTI). "
"Identificér varen og returnér KUN JSON, intet andet:\n"
'{"name":"kort dansk produktnavn","de":"tysk navn hvis synligt ellers null",'
'"section":"bedst passende sektions-id fra listen, ellers null",'
'"note":"kort note, fx mærke eller størrelse, ellers null"}\n'
"Sektioner: " + secs)
content = [
{"type": "image", "source": {"type": "base64", "media_type": media, "data": b64}},
{"type": "text", "text": prompt},
]
try:
import anthropic
client = anthropic.Anthropic(max_retries=2)
text = _claude_json(client, VISION_MODEL, 1000, content)
except Exception as e:
app.logger.warning("citti analyze failed: %s", e)
return jsonify(ok=False, error='analyze-failed'), 502
m = re.search(r"\{.*\}", text, re.DOTALL)
if not m:
return jsonify(ok=True, name=None, section=None, note=None, de=None)
try:
d = json.loads(m.group(0))
except Exception:
return jsonify(ok=True, name=None, section=None, note=None, de=None)
sec = d.get('section')
if sec not in {s['id'] for s in SECTIONS}:
sec = None
return jsonify(ok=True, name=d.get('name'), de=d.get('de'),
section=sec, note=d.get('note'))
@app.route('/api/item/<int:item_id>', methods=['DELETE'])
def delete_item(item_id):
with get_db() as c:

View File

@@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Citti Analyse</title>
<title>Citti Analyse — Uge 23-25</title>
<link href="https://fonts.googleapis.com/css2?family=DM+Mono:wght@400;500&family=DM+Sans:wght@300;400;500;600&display=swap" rel="stylesheet">
<style>
:root {
@@ -85,7 +85,7 @@
<header>
<div>
<h1>Citti <span>Analyse</span></h1>
<div style="font-size:12px;color:var(--muted);margin-top:4px">CITTI Lübeck · Herrenholz 14</div>
<div style="font-size:12px;color:var(--muted);margin-top:4px">Uge 23–25 · 03.06–23.06.2026</div>
</div>
<a href="/" class="btn-back">← Indkøbsseddel</a>
</header>

View File

@@ -10,7 +10,7 @@
<link rel="apple-touch-icon" href="/icon.svg">
<link rel="icon" href="/icon.svg">
<script src="/offline.js" defer></script>
<title>Citti Indkøbsseddel</title>
<title>Citti Indkøbsseddel — Uge 23-25</title>
<link href="https://fonts.googleapis.com/css2?family=DM+Mono:wght@400;500&family=DM+Sans:wght@300;400;500;600&display=swap" rel="stylesheet">
<style>
:root {
@@ -71,7 +71,6 @@
.item-name { padding: 0.7rem 0.5rem; font-size: 14px; }
.item-name .note { font-size: 11px; color: var(--muted); display: block; margin-top: 1px; }
.item-name .de { font-size: 10px; color: #b0aba3; display: block; margin-top: 0; font-style: italic; }
.item-name .row-est-m { display: none; font-size: 10px; color: var(--muted); font-family: var(--mono); margin-top: 2px; }
.badge { display: inline-block; font-size: 9px; padding: 1px 5px; border-radius: 3px; margin-left: 5px; vertical-align: middle; font-weight: 500; }
.badge-card { background: var(--blue-light); color: var(--blue); }
.badge-kasse { background: var(--amber-light); color: var(--amber); }
@@ -158,8 +157,6 @@
.btn-submit { width: 100%; background: var(--accent); color: white; border: none; border-radius: 10px; padding: 14px; font-size: 16px; font-weight: 600; font-family: var(--sans); cursor: pointer; margin-top: 0.5rem; }
.btn-submit:active { opacity: 0.85; }
.modal-context { background: var(--accent-light); border-radius: 8px; padding: 8px 12px; font-size: 13px; color: var(--accent); font-weight: 500; margin-bottom: 1rem; }
.ai-suggest { background: var(--green-light); border: 1px solid #a8d5bc; border-radius: 8px; padding: 9px 12px; font-size: 13px; color: var(--green); margin-bottom: 1rem; line-height: 1.4; }
.ai-suggest.loading { background: var(--bg); color: var(--muted); border-color: var(--border); }
.saving-indicator { position: fixed; top: 0.75rem; right: 0.75rem; background: var(--green); color: white; border-radius: 6px; padding: 4px 10px; font-size: 12px; font-family: var(--mono); opacity: 0; transition: opacity 0.3s; z-index: 50; pointer-events: none; }
.saving-indicator.show { opacity: 1; }
@@ -170,7 +167,6 @@
.header-actions { flex-direction: row; align-items: center; }
.item-row { grid-template-columns: 28px 1fr 64px 78px; }
.item-est { display: none; }
.item-name .row-est-m { display: block; }
.col-headers { grid-template-columns: 28px 1fr 64px 78px; }
.col-h:nth-child(4) { display: none; }
.extra-item-row { grid-template-columns: 28px 1fr auto auto; }
@@ -186,8 +182,9 @@
<div class="header-left">
<h1>Citti <span>Indkøbsseddel</span></h1>
<div class="header-meta">
<span><strong>Uge 23–25</strong> · 03.06–23.06.2026</span>
<span>Man–lør 08–20</span>
<span>CITTI Lübeck · Herrenholz 14</span>
<span>Langberger Weg 4, Flensburg</span>
<span>1 EUR ≈ 7,46 DKK</span>
</div>
</div>
@@ -268,7 +265,6 @@
{% 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_da or d.heading }}</a>{% endif %}
<span class="row-est-m"></span>
</div>
<div class="item-qty">
<input type="text" value="{{ s.get('qty') or item.qty }}" placeholder="{{ item.qty }}"
@@ -470,7 +466,7 @@
</div>
</div>
<footer>CITTI Lübeck · Herrenholz 14</footer>
<footer>Citti Flensborg · Langberger Weg 4 · Tilbud 03.06–23.06.2026</footer>
</div><!-- /page -->
@@ -487,7 +483,6 @@
<button class="modal-close" onclick="closeItemModal()">×</button>
</div>
<div class="modal-context" id="item-modal-ctx" style="display:none"></div>
<div id="ai-suggest" class="ai-suggest" style="display:none"></div>
<form id="add-form" onsubmit="submitItem(event)">
<input type="hidden" name="section_key" id="item-section-key">
<div class="form-group">
@@ -712,34 +707,16 @@ function recalcAll() {
// picked offers), live from each row's data-est. Reflects add/remove/pick.
let est = 0;
document.querySelectorAll('[data-est]').forEach(r => {
const qi = r.querySelector('.item-qty input');
const offer = offerLineDkk(r); // real offer price if matched
let line;
if (offer != null) {
line = offer;
} else {
line = parseFloat(r.dataset.est) || 0;
if (qi) { // scale estimate with quantity
if (offer != null) { est += offer; return; }
let base = parseFloat(r.dataset.est) || 0;
const qi = r.querySelector('.item-qty input'); // scale estimate with quantity
if (qi) {
const cur = qtyNum(qi.value.trim() || qi.placeholder);
const def = qtyNum(qi.placeholder);
if (cur != null && def != null && def > 0) line = line * (cur / def);
}
}
est += line;
// Per-row display: computed estimate + ½kg price (for weight items). The
// est column is hidden on phones, so also fill the mobile sub-line.
if (qi) {
const col = r.querySelector('.item-est');
if (col) col.textContent = line > 0 ? Math.round(line).toLocaleString('da-DK') : '—';
const sub = r.querySelector('.row-est-m');
if (sub) {
const kg = qtyToKg(qi.value.trim() || qi.placeholder);
const per500 = (kg > 0 && line > 0) ? Math.round(line / kg * 0.5) : null;
sub.textContent = (line > 0 ? 'est ' + Math.round(line).toLocaleString('da-DK') + ' kr' : '')
+ (per500 ? ' · ½kg ' + per500 + ' kr' : '');
}
if (cur != null && def != null && def > 0) base = base * (cur / def);
}
est += base;
});
document.getElementById('stat-est').textContent = est > 0 ? Math.round(est).toLocaleString('da-DK') : '—';
@@ -774,69 +751,11 @@ function closeItemModal() {
document.getElementById('item-modal').classList.remove('open');
document.getElementById('add-form').reset();
document.getElementById('photo-preview').style.display = 'none';
document.getElementById('ai-suggest').style.display = 'none';
}
function previewPhoto(input) {
const p = document.getElementById('photo-preview');
if (input.files && input.files[0]) {
p.src = URL.createObjectURL(input.files[0]); p.style.display = 'block';
analyzePhoto(input.files[0]);
}
}
const SEC_NAMES = {koed:'🥩 Kød & fisk', frost:'🧊 Frostgrønt', mejeri:'🧀 Mejeri & ost',
pasta:'🍝 Pasta', groent:'🥗 Grønt & tørvarer', konserves:'🥫 Konserves',
indisk:'🌶️ Indisk & karry', mex:'🌮 Mexicansk & asiatisk', drikke:'🍺 Drikkevarer', hus:'🏠 Husholdning'};
// Downscale for the AI call only (fast/cheap, avoids size limits); the full
// photo is still uploaded on submit.
function downscaleImage(file, maxDim) {
return new Promise((resolve) => {
const img = new Image();
img.onload = () => {
const scale = Math.min(1, maxDim / Math.max(img.width, img.height));
const w = Math.round(img.width * scale), h = Math.round(img.height * scale);
const c = document.createElement('canvas');
c.width = w; c.height = h;
c.getContext('2d').drawImage(img, 0, 0, w, h);
c.toBlob((b) => resolve(b || file), 'image/jpeg', 0.85);
};
img.onerror = () => resolve(file);
img.src = URL.createObjectURL(file);
});
}
async function analyzePhoto(file) {
const box = document.getElementById('ai-suggest');
box.style.display = 'block';
box.className = 'ai-suggest loading';
box.textContent = '🪄 Analyserer billede…';
try {
const small = await downscaleImage(file, 1024);
const fd = new FormData(); fd.append('photo', small, 'photo.jpg');
const res = await fetch('/api/item/analyze', {method: 'POST', body: fd});
if (!res.ok) throw new Error('fail');
const d = await res.json();
const form = document.getElementById('add-form');
const skInput = document.getElementById('item-section-key');
if (d.name && !form.name.value.trim()) form.name.value = d.name;
if (!form.note.value.trim()) {
const parts = [];
if (d.note) parts.push(d.note);
if (d.de) parts.push('🇩🇪 ' + d.de);
if (parts.length) form.note.value = parts.join(' · ');
}
if (d.section && !skInput.value) skInput.value = d.section; // keep an explicitly chosen section
const eff = skInput.value;
const cat = eff ? (SEC_NAMES[eff] || eff) : 'Diverse (ingen kategori)';
box.className = 'ai-suggest done';
box.innerHTML = '🪄 Forslag: <b>' + (d.name || '?') + '</b> · ' + cat
+ ' <span style="color:var(--muted)">— ret hvis forkert, og tast prisen</span>';
} catch (e) {
box.className = 'ai-suggest';
box.innerHTML = '<span style="color:var(--muted)">Kunne ikke analysere billedet — udfyld manuelt.</span>';
}
if (input.files && input.files[0]) { p.src = URL.createObjectURL(input.files[0]); p.style.display = 'block'; }
}
async function submitItem(e) {

View File

@@ -69,8 +69,7 @@
<h1>Citti <span>Tilbud</span></h1>
<div class="sub">
CITTI Lübeck · Herrenholz 14 · priser i EUR (≈ ×{{ "{:.2f}".format(eur_dkk).replace(".",",") }} kr.)<br>
{% if last_refresh %}Opdateret {{ last_refresh[:16].replace("T"," ") }} · {% endif %}{{ total }} tilbud<br>
<a href="https://www.cittimarkt.de/angebote" target="_blank" rel="noopener" style="color:var(--accent);font-weight:600;text-decoration:none">📄 Se hele avisen hos CITTI Lübeck →</a>
{% if last_refresh %}Opdateret {{ last_refresh[:16].replace("T"," ") }} · {% endif %}{{ total }} tilbud
</div>
</div>
<div style="display:flex;flex-direction:column;gap:8px;align-items:flex-end">