Files
lunch/lib/recipe-import.ts
kai 582b4a0fca
release / which version (push) Successful in 3s
release / olares chart · sanity (push) Successful in 4s
release / app (push) Successful in 1m3s
release / tag and release (push) Successful in 2s
26.11.49: Portionen rechnen mit, mehr Maße (#50)
2026-11-08 16:55:49 +00:00

230 lines
9.0 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Rezept aus einer Webseite lesen — ohne KI, wo es geht (Konzept, „Technik“):
// Die meisten Rezeptseiten tragen schema.org/Recipe als JSON-LD. Hier steht
// nur das Lesen und Zerlegen, rein und testbar; das Holen der Seite macht
// lib/fetch-safe.ts, das Zuordnen der Zutaten lib/ingredient-search.ts.
import { searchIngredients, type IngredientEntry } from "./ingredient-search";
import { isPackKind, needsSize, parseNumber, sizeOf, toBase, type InputUnit, type KitchenUnit, type PackKind } from "./units";
export type RawRecipe = {
title: string;
yield: number | null;
totalMinutes: number | null;
ingredients: string[];
steps: string[];
image: string | null;
};
type Json = Record<string, unknown>;
function decodeEntities(text: string): string {
return text
.replace(/&nbsp;/g, " ")
.replace(/&amp;/g, "&")
.replace(/&quot;/g, '"')
.replace(/&#0?39;|&apos;/g, "'")
.replace(/&lt;/g, "<")
.replace(/&gt;/g, ">")
.replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(Number(n)));
}
const clean = (text: unknown) =>
typeof text === "string" ? decodeEntities(text.replace(/<[^>]*>/g, " ")).replace(/\s+/g, " ").trim() : "";
function isRecipe(node: unknown): node is Json {
if (!node || typeof node !== "object") return false;
const type = (node as Json)["@type"];
return type === "Recipe" || (Array.isArray(type) && type.includes("Recipe"));
}
function findRecipe(node: unknown): Json | null {
if (Array.isArray(node)) {
for (const n of node) {
const r = findRecipe(n);
if (r) return r;
}
return null;
}
if (!node || typeof node !== "object") return null;
if (isRecipe(node)) return node;
const graph = (node as Json)["@graph"];
return graph ? findRecipe(graph) : null;
}
/** ISO-8601-Dauer („PT1H30M“) in Minuten. */
export function durationMinutes(value: unknown): number | null {
if (typeof value !== "string") return null;
const m = value.match(/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:\d+S)?)?$/i);
if (!m) return null;
const total = Number(m[1] ?? 0) * 1440 + Number(m[2] ?? 0) * 60 + Number(m[3] ?? 0);
return total > 0 ? total : null;
}
function yieldNumber(value: unknown): number | null {
const first = Array.isArray(value) ? value[0] : value;
if (typeof first === "number") return first > 0 ? Math.round(first) : null;
const m = typeof first === "string" ? first.match(/\d+/) : null;
return m ? Math.min(30, Number(m[0])) || null : null;
}
function instructionTexts(value: unknown): string[] {
if (typeof value === "string") {
return value
.split(/\n+|(?<=\.)\s+(?=[A-ZÄÖÜ])/)
.map(clean)
.filter(Boolean);
}
if (Array.isArray(value)) return value.flatMap(instructionTexts);
if (value && typeof value === "object") {
const node = value as Json;
if (node.itemListElement) return instructionTexts(node.itemListElement); // HowToSection
return [clean(node.text ?? node.name)].filter(Boolean);
}
return [];
}
function imageUrl(value: unknown): string | null {
if (typeof value === "string") return value;
if (Array.isArray(value)) return imageUrl(value[0]);
if (value && typeof value === "object") return imageUrl((value as Json).url);
return null;
}
/** Das erste Recipe aus den JSON-LD-Blöcken einer Seite, oder null. */
export function extractRecipe(html: string): RawRecipe | null {
const blocks = [...html.matchAll(/<script[^>]*type=["']application\/ld\+json["'][^>]*>([\s\S]*?)<\/script>/gi)];
for (const [, body] of blocks) {
let data: unknown;
try {
data = JSON.parse(body!.trim());
} catch {
continue;
}
const recipe = findRecipe(data);
if (!recipe) continue;
const ingredients = (Array.isArray(recipe.recipeIngredient) ? recipe.recipeIngredient : []).map(clean).filter(Boolean);
return {
title: clean(recipe.name).slice(0, 120),
yield: yieldNumber(recipe.recipeYield),
totalMinutes: durationMinutes(recipe.totalTime) ?? durationMinutes(recipe.cookTime),
ingredients,
steps: instructionTexts(recipe.recipeInstructions).slice(0, 40),
image: imageUrl(recipe.image),
};
}
return null;
}
// Mengenwörter in vier Sprachen → Eingabeeinheit (lib/units.ts).
const UNIT_WORDS: [RegExp, InputUnit, number?][] = [
[/^(kg|kilo(gramm)?s?)$/i, "kg"],
[/^(g|gr|gramm|grams?|gramos?|grammes?)$/i, "g"],
[/^(l|liter|litres?|liters?|litros?)$/i, "l"],
[/^(ml|milliliter|millilitres?)$/i, "ml"],
[/^(cl)$/i, "cl"],
[/^(el|essl[öo]ffel|tbsp|tablespoons?|cs|c\.\s?à\s?s\.?|cucharadas?)$/i, "tbsp"],
[/^(tl|teel[öo]ffel|tsp|teaspoons?|cc|c\.\s?à\s?c\.?|cucharaditas?)$/i, "tsp"],
[/^(prisen?|pinch(es)?|pinc[ée]es?|pizcas?)$/i, "pinch"],
[/^(cups?|tassen?|tazas?)$/i, "cup"],
// Seit 26.11.49 eigene Maße: Schuss, Messerspitze, Becher, Würfel, Zehe, Scheibe.
[/^(schuss|sch(ü|ue)sse|dash(es)?|traits?|chorritos?)$/i, "dash"],
[/^(msp|messerspitzen?)$/i, "knifepoint"],
[/^(becher|tubs?|pots?|tarrinas?)$/i, "tub"],
[/^(w(ü|ue)rfel|cubes?|cubitos?)$/i, "cube"],
[/^(zehen?|cloves?|gousses?|dientes?)$/i, "clove"],
[/^(scheiben?|slices?|tranches?|rebanadas?|lonchas?)$/i, "slice"],
[/^(oz|ounces?)$/i, "g", 28.35],
[/^(lbs?|pounds?)$/i, "g", 453.6],
// Gebinde (26.11.39): Größe kommt aus der Zutat, nie aus dem Text oder einem Modell.
[/^(dosen?|cans?|tins?|bo[iî]tes?|latas?)$/i, "can"],
[/^(gl(a|ä)s(er)?|jars?|bocal|bocaux|tarros?|frascos?)$/i, "jar"],
[/^(pck|pkg|pack(ung(en)?|s)?|p(a|ä)ckchen|paquets?|paquetes?|sachets?|sobres?|kugeln?)$/i, "pack"],
[/^(bund|bunch(es)?|bouquets?|bottes?|manojos?)$/i, "bunch"],
[/^(st(ü|ue)ck|stk\.?|pieces?|pi[eè]ces?|unidad(es)?)$/i, "piece"],
];
export type ParsedLine = { raw: string; qty: number | null; unit: InputUnit | null; factor: number; name: string };
/** „500 g Rinderhackfleisch“ → Menge, Einheit, Name. „Salz und Pfeffer“ → nur Name. */
export function parseIngredientLine(raw: string): ParsedLine {
let rest = raw.replace(/\(.*?\)/g, " ").replace(/\s+/g, " ").trim();
let qty: number | null = null;
const num = rest.match(
/^(\d+\s+\d+\/\d+|\d+\s*[¼½¾⅓⅔]|\d+(?:[.,]\d+)?|\d+\/\d+|[¼½¾⅓⅔])(?:\s*(?:-|–|bis)\s*\d+(?:[.,]\d+)?)?\s*/,
);
if (num) {
qty = parseNumber(num[1]!.replace(/(\d)\s+([¼½¾⅓⅔])/, "$1$2"));
rest = rest.slice(num[0].length);
}
let unit: InputUnit | null = null;
let factor = 1;
const word = rest.match(/^([^\s\d]+\.?)\s+/);
if (word) {
const w = word[1]!.replace(/\.$/, "");
const hit = UNIT_WORDS.find(([re]) => re.test(w));
if (hit) {
unit = hit[1];
factor = hit[2] ?? 1;
rest = rest.slice(word[0].length);
}
} else {
const glued = rest.match(/^(kg|g|ml|l|cl)\b\s*/i); // „500g Mehl“ nach der Zahl
if (glued) {
unit = glued[1]!.toLowerCase() as InputUnit;
rest = rest.slice(glued[0].length);
}
}
const name = rest.replace(/^(of|de|d'|von)\s+/i, "").replace(/,.*$/, "").trim();
return { raw, qty, unit: qty !== null && !unit ? "piece" : unit, factor, name };
}
export type MatchedLine = {
raw: string;
ingredient: {
id: string;
name: string;
unit: "g" | "ml" | "piece";
kitchenUnit?: KitchenUnit | null;
packKind?: PackKind | null;
packSize?: number | null;
sizes?: Partial<Record<string, number>>;
} | null;
qty: number | null;
unit: InputUnit | null;
note: string | null;
};
/**
* Zeilen den kanonischen Zutaten zuordnen. Passt die Einheit nicht zur Zutat
* (z. B. „1 Becher Sahne“), bleibt die Menge leer — die Person trägt sie ein.
*/
export function matchLines(lines: string[], list: IngredientEntry[], locale: string): MatchedLine[] {
return lines.map((raw) => {
const p = parseIngredientLine(raw);
const hit = p.name ? searchIngredients(list, p.name, locale, 1)[0] ?? searchIngredients(list, p.name.split(" ").at(-1) ?? "", locale, 1)[0] : undefined;
if (!hit) return { raw, ingredient: null, qty: null, unit: null, note: null };
const ingredient = {
id: hit.id,
name: hit.names[locale] ?? hit.names.en ?? "",
unit: hit.unit,
kitchenUnit: hit.kitchenUnit ?? null,
packKind: hit.packKind ?? null,
packSize: hit.packSize ?? null,
sizes: hit.sizes ?? {},
};
let qty = p.qty !== null ? p.qty * p.factor : null;
let unit = p.unit;
// Ein Gebinde ist das der Zutat („1 Becher Sahne“ → ihre Packung); ohne Gebinde
// zählt bei Stück-Zutaten das Stück („1 Bund Petersilie“ ist ein Stück Petersilie).
if (unit && isPackKind(unit)) unit = hit.packKind && hit.packSize ? hit.packKind : hit.unit === "piece" ? "piece" : unit;
// Ein Zählmaß ohne bekannte Größe („2 Zehen“ bei Knoblauch in Gramm) bleibt stehen:
// Das Formular fragt nach der Größe (26.11.49). Sonst passt das Maß nicht — Menge leer.
const size = unit ? sizeOf(unit, hit.unit, hit) : null;
if (qty !== null && unit && toBase(qty, unit, hit.unit, size) === null && !(needsSize(unit, hit.unit) && size === null)) {
qty = null;
unit = null;
}
return { raw, ingredient, qty, unit: unit ?? hit.unit, note: qty === null ? raw : null };
});
}