From b32a9a9fcbec00ed189f2f723eebd90c713a2649 Mon Sep 17 00:00:00 2001 From: Henrik Jess Nielsen Date: Fri, 30 Oct 2026 14:27:30 +0100 Subject: [PATCH] =?UTF-8?q?feat(add-item):=20photo=20=E2=86=92=20Claude=20?= =?UTF-8?q?vision=20suggests=20name=20+=20category?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In 'Tilføj vare', taking/choosing a photo now sends it (downscaled client- side) to Claude vision, which identifies the product and returns a Danish name, German name, best-fit catalog section and a short note. The form is prefilled and the suggested category shown — you just confirm and type the price. Full photo is still uploaded on submit. Degrades gracefully: no credential or a failed call just falls back to manual entry. - /api/item/analyze (vision via _claude_json, now accepts image content) - VISION_MODEL (Haiku by default; bump to sonnet via env for harder photos) --- app.py | 64 +++++++++++++++++++++++++++++++++++++++----- templates/index.html | 63 ++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 119 insertions(+), 8 deletions(-) diff --git a/app.py b/app.py index 0c7ad6e..a9444f4 100644 --- a/app.py +++ b/app.py @@ -43,6 +43,8 @@ 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": [ @@ -312,15 +314,15 @@ def _claude_mode(): return None -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.""" +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.""" extra = {"anthropic-beta": "oauth-2025-04-20"} if _claude_mode() == "oauth" else {} kwargs = dict(model=model, max_tokens=max_tokens, - messages=[{"role": "user", "content": prompt}], + messages=[{"role": "user", "content": content}], extra_headers=extra) try: msg = client.messages.create(thinking={"type": "disabled"}, **kwargs) @@ -673,6 +675,54 @@ 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/', methods=['DELETE']) def delete_item(item_id): with get_db() as c: diff --git a/templates/index.html b/templates/index.html index 7376e5c..3ed0492 100644 --- a/templates/index.html +++ b/templates/index.html @@ -157,6 +157,8 @@ .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; } @@ -482,6 +484,7 @@ +
@@ -750,11 +753,69 @@ 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'; } + 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: ' + (d.name || '?') + ' · ' + cat + + ' — ret hvis forkert, og tast prisen'; + } catch (e) { + box.className = 'ai-suggest'; + box.innerHTML = 'Kunne ikke analysere billedet — udfyld manuelt.'; + } } async function submitItem(e) { -- 2.53.0