199 lines
9.6 KiB
TypeScript
199 lines
9.6 KiB
TypeScript
// Kassenbons lesen (Konzept, „Bon-Pipeline, lokal“) — rein, ohne Datenbank.
|
||
// Das Bildmodell schreibt ab, was auf dem Bon steht; es rechnet nichts. Preise
|
||
// und Mengen sind abgeschrieben und werden vor dem Speichern von einem Menschen
|
||
// bestätigt. Datum: das Modell nennt es wie gedruckt, gerechnet wird hier.
|
||
|
||
export const RECEIPT_PROMPT = `You read a supermarket receipt photo. Answer with one JSON object only, no prose:
|
||
{"store": string|null, "date": string|null, "total": number|null, "lines": [[text, qty, unit_price, total_price], ...]}
|
||
One short array per article, in printed order. text: the article text exactly as printed (abbreviations included),
|
||
without its price and without the tax class after it. qty and unit_price only if a quantity or weight is printed, else null.
|
||
total_price: the article's price. Prices as numbers in the receipt's currency (1,29 → 1.29).
|
||
Some stores (Aldi, Lidl) print the quantity ABOVE its article: a line "2 x 1,49 €" or "0,416 kg x 2,79 €/kg" belongs to
|
||
the next article line — put it into that article's qty and unit_price, never as a line of its own.
|
||
Skip deposit lines (Pfand, Pfandwert, Leergut), payment, change, tax and sum lines. "total": the amount to pay.
|
||
"date" exactly as printed (e.g. "07.11.26"), null if none is visible. Never invent a line, a price or a date.`;
|
||
|
||
/** weighed: Menge stammt aus einer Gewichtszeile („0,416 kg x 2,79 €/kg“), qty ist dann in kg. */
|
||
export type ReadLine = { text: string; qty: number | null; unitPrice: number | null; totalPrice: number | null; weighed?: boolean };
|
||
export type ReadReceipt = { store: string | null; date: string | null; total: number | null; lines: ReadLine[]; partial?: boolean };
|
||
|
||
const money = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) && v >= 0 && v < 10000 ? Math.round(v * 100) / 100 : null);
|
||
const amount = (v: unknown): number | null => (typeof v === "number" && v > 0 && v < 1000 ? v : null);
|
||
const num = (t: string) => Number(t.replace(",", "."));
|
||
|
||
// Pfand ist kein Lebensmittel und Leergut kein Einkauf.
|
||
const DEPOSIT = /\b(pfand\w*|leergut\w*|einweg|mehrweg)\b/i;
|
||
// Eine Mengen- oder Gewichtszeile für sich: „2 x 1,49 €“, „0,416 kg x 2,79 €/kg“.
|
||
const QTY_LINE = /^-?(\d+(?:[.,]\d+)?)\s*(?:kg|stk?)?\s*[x×*]\s*(\d+[.,]\d{2})\s*(?:€|eur)?\s*(?:\/\s*kg)?$/i;
|
||
// Preis und Steuerklasse am Zeilenende, falls das Modell sie mit abschreibt: „… 2,98 € 1“.
|
||
const TRAILING_PRICE = /\s+-?\d+[.,]\d{2}\s*(?:€|eur)?\s*[a-z0-9]?$/i;
|
||
|
||
function rawLine(raw: unknown): ReadLine | null {
|
||
// Kurzform [text, qty, unit_price, total_price] oder die alte Objektform.
|
||
const [t, q, u, p] = Array.isArray(raw)
|
||
? raw
|
||
: (() => {
|
||
const l = (raw ?? {}) as Record<string, unknown>;
|
||
return [l.text, l.qty, l.unit_price, l.total_price];
|
||
})();
|
||
const spaced = typeof t === "string" ? t.replace(/\s+/g, " ").trim() : "";
|
||
// Eine Mengenzeile behält ihren Preis, sonst fällt der Stückpreis weg.
|
||
const text = (QTY_LINE.test(spaced) ? spaced : spaced.replace(TRAILING_PRICE, "")).slice(0, 120);
|
||
if (!text) return null;
|
||
return { text, qty: amount(q), unitPrice: money(u), totalPrice: money(p) };
|
||
}
|
||
|
||
/** Zeilen aufräumen: Mengenzeilen zum Artikel darunter, Pfand und Leergut weg. */
|
||
export function tidyLines(lines: ReadLine[]): ReadLine[] {
|
||
const out: ReadLine[] = [];
|
||
let pending: { qty: number; unitPrice: number; weighed: boolean } | null = null;
|
||
for (const line of lines) {
|
||
const q = line.text.match(QTY_LINE);
|
||
if (q) {
|
||
const qty = num(q[1]!);
|
||
pending = qty > 0 ? { qty, unitPrice: num(q[2]!), weighed: /kg\s*[x×*]/i.test(line.text) } : null; // „-41 x 0,25“ gehört zum Leergut
|
||
continue;
|
||
}
|
||
if (DEPOSIT.test(line.text)) {
|
||
pending = null;
|
||
continue;
|
||
}
|
||
out.push(
|
||
pending && line.qty === null
|
||
? { ...line, qty: pending.qty, unitPrice: line.unitPrice ?? pending.unitPrice, ...(pending.weighed ? { weighed: true } : {}) }
|
||
: line,
|
||
);
|
||
pending = null;
|
||
}
|
||
return out;
|
||
}
|
||
|
||
/** Antwort des Bildmodells prüfen; ohne lesbare Zeile null. */
|
||
export function fromReceiptReply(reply: unknown): ReadReceipt | null {
|
||
const r = (reply ?? {}) as Record<string, unknown>;
|
||
if (!Array.isArray(r.lines)) return null;
|
||
const lines = tidyLines(r.lines.slice(0, 300).map(rawLine).filter((l): l is ReadLine => !!l));
|
||
if (!lines.length) return null;
|
||
return {
|
||
store: typeof r.store === "string" && r.store.trim() ? r.store.trim().slice(0, 80) : null,
|
||
date: parseReceiptDate(typeof r.date === "string" ? r.date : null),
|
||
total: money(r.total),
|
||
lines,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* Den Antworttext lesen. Ein langer Bon (Aldi, 50 Zeilen) kann das Modell über
|
||
* sein Limit treiben; dann bricht das JSON mitten in den Zeilen ab. Statt „keine
|
||
* Zeilen erkannt“ retten wir jede vollständige Zeile davor — der Mensch prüft ohnehin.
|
||
*/
|
||
export function receiptFromText(text: string): ReadReceipt | null {
|
||
const cleaned = text.replace(/<think>[\s\S]*?<\/think>/g, "").replace(/```(?:json)?/g, "");
|
||
const start = cleaned.indexOf("{");
|
||
const end = cleaned.lastIndexOf("}");
|
||
if (start >= 0 && end > start) {
|
||
try {
|
||
const whole = fromReceiptReply(JSON.parse(cleaned.slice(start, end + 1)));
|
||
if (whole) return whole;
|
||
} catch {}
|
||
}
|
||
const at = cleaned.search(/"lines"\s*:\s*\[/);
|
||
if (at < 0) return null;
|
||
const head = cleaned.slice(0, at);
|
||
const field = (key: string) => head.match(new RegExp(`"${key}"\\s*:\\s*("(?:[^"\\\\]|\\\\.)*"|-?\\d+(?:\\.\\d+)?|null)`))?.[1];
|
||
const value = (key: string) => {
|
||
const v = field(key);
|
||
try {
|
||
return v ? JSON.parse(v) : null;
|
||
} catch {
|
||
return null;
|
||
}
|
||
};
|
||
const items: unknown[] = [];
|
||
const body = cleaned.slice(at);
|
||
const item = /\[\s*"(?:[^"\\]|\\.)*"\s*(?:,\s*(?:-?\d+(?:\.\d+)?|null)\s*){0,3}\]|\{[^{}]*"text"[^{}]*\}/g;
|
||
for (const m of body.slice(body.indexOf("[") + 1).matchAll(item)) {
|
||
try {
|
||
items.push(JSON.parse(m[0]));
|
||
} catch {}
|
||
}
|
||
const read = fromReceiptReply({ store: value("store"), date: value("date"), total: value("total"), lines: items });
|
||
return read ? { ...read, partial: true } : null;
|
||
}
|
||
|
||
/** „07.11.26“, „07.11.2026“, „2026-11-07“ → ISO-Datum; Unplausibles → null. */
|
||
export function parseReceiptDate(text: string | null, today = new Date()): string | null {
|
||
if (!text) return null;
|
||
let y: number, m: number, d: number;
|
||
const de = text.match(/(\d{1,2})[./](\d{1,2})[./](\d{2,4})/);
|
||
const iso = text.match(/(\d{4})-(\d{2})-(\d{2})/);
|
||
if (iso) [y, m, d] = [Number(iso[1]), Number(iso[2]), Number(iso[3])];
|
||
else if (de) [d, m, y] = [Number(de[1]), Number(de[2]), Number(de[3])];
|
||
else return null;
|
||
if (y < 100) y += 2000;
|
||
const date = new Date(Date.UTC(y, m - 1, d));
|
||
if (date.getUTCMonth() !== m - 1 || date.getUTCDate() !== d) return null;
|
||
const age = (today.getTime() - date.getTime()) / 86400000;
|
||
if (age < -2 || age > 400) return null; // Zukunft oder älter als ein gutes Jahr: lieber fragen
|
||
return date.toISOString().slice(0, 10);
|
||
}
|
||
|
||
/** Schlüssel für gelernte Zuordnungen: klein, ohne Preise und doppelte Leerzeichen. */
|
||
export function normalizeLine(text: string): string {
|
||
return text
|
||
.toLocaleLowerCase("de")
|
||
.replace(/-?\d+[.,]\d{2}\s*[a-z]?$/i, "")
|
||
.replace(/[^\p{L}\p{N}%.,/ ]+/gu, " ")
|
||
.replace(/\s+/g, " ")
|
||
.trim();
|
||
}
|
||
|
||
/** Packungsgröße aus dem Bontext („RINDERHACK 500G“ → 500 g, „MILCH 1L“ → 1000 ml, „EIER 10ST“ → 10 Stück). */
|
||
export function packFromText(text: string): { qty: number; unit: "g" | "ml" | "piece" } | null {
|
||
const m = text.match(/(\d+(?:[.,]\d+)?)\s*(kg|gr?|ml|cl|l|ltr|st|stk|stück|er)\b/i);
|
||
if (!m) return null;
|
||
const n = Number(m[1]!.replace(",", "."));
|
||
const u = m[2]!.toLowerCase();
|
||
if (!(n > 0)) return null;
|
||
if (u === "kg") return { qty: n * 1000, unit: "g" };
|
||
if (u === "g" || u === "gr") return { qty: n, unit: "g" };
|
||
if (u === "l" || u === "ltr") return { qty: n * 1000, unit: "ml" };
|
||
if (u === "cl") return { qty: n * 10, unit: "ml" };
|
||
if (u === "ml") return { qty: n, unit: "ml" };
|
||
return { qty: n, unit: "piece" };
|
||
}
|
||
|
||
/** Wörter eines Bontexts oder Produktnamens zum Vergleichen („BARILLA SPAGH N5“ ~ „Barilla Spaghetti Nr. 5“). */
|
||
export function tokens(text: string): string[] {
|
||
return text
|
||
.toLocaleLowerCase("de")
|
||
.replace(/nr\.?\s*(\d)/g, "n$1")
|
||
.split(/[^\p{L}\p{N}]+/u)
|
||
.filter((t) => t.length >= 2);
|
||
}
|
||
|
||
/** Passt eine Bonzeile zu einem Produkt? Jedes Wort der Zeile muss den Anfang eines Produktworts treffen (Abkürzungen). */
|
||
export function matchesProduct(line: string, product: string): boolean {
|
||
const ls = tokens(line).filter((t) => !/^\d+(g|kg|ml|l|st)?$/.test(t));
|
||
const ps = tokens(product);
|
||
if (ls.length < 2) return false;
|
||
const hits = ls.filter((l) => ps.some((p) => p.startsWith(l) || l.startsWith(p)));
|
||
return hits.length >= 2 && hits.length / ls.length >= 0.6;
|
||
}
|
||
|
||
/**
|
||
* Preis je Grundeinheit (g, ml, Stück) einer Bonzeile: Zeilenpreis ÷ (Anzahl × Packung).
|
||
* 2 × 400 g Hack für 17,58 € → 0,021975 € je g. Ohne Packung oder Preis: null — dann
|
||
* merkt sich Lunch keinen Preis.
|
||
*/
|
||
export function unitPrice(total: number | null, qty: number | null, pack: number | null): number | null {
|
||
if (total === null || !(total > 0) || pack === null || !(pack > 0)) return null;
|
||
const amount = (qty && qty > 0 ? qty : 1) * pack;
|
||
return amount > 0 ? total / amount : null;
|
||
}
|
||
|
||
/** Zum Anzeigen: je 100 g / 100 ml, bei Stück je Stück. */
|
||
export function pricePer(perUnit: number, unit: "g" | "ml" | "piece"): { price: number; per: "100g" | "100ml" | "piece" } {
|
||
return unit === "piece" ? { price: perUnit, per: "piece" } : { price: perUnit * 100, per: unit === "g" ? "100g" : "100ml" };
|
||
}
|