feat(add-item): photo → Claude vision suggests name + category
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)
This commit is contained in:
64
app.py
64
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/<int:item_id>', methods=['DELETE'])
|
||||
def delete_item(item_id):
|
||||
with get_db() as c:
|
||||
|
||||
Reference in New Issue
Block a user