Tofu/scripts/import-recipes/recipes/alignParsedIngredients.js
2026-09-18 01:41:02 +02:00

29 lines
1.5 KiB
JavaScript

// Keeps the structured split index-aligned with the raw lines, whatever the
// model returned. The raw line is the one thing that gets printed, so it always
// wins: an entry that is missing, reordered or rewritten is replaced by an
// openly imprecise one - name falls back to the whole line, quantity to null -
// rather than by an invented quantity. `repaired` counts those, so a document
// where the model drifted shows up in the run summary.
export function alignParsedIngredients(recipeIngredient, parsedIngredients) {
if (!Array.isArray(recipeIngredient)) return { parsedIngredients: [], repaired: 0 }
const candidates = Array.isArray(parsedIngredients) ? parsedIngredients : []
const aligned = []
let repaired = 0
for (const [index, line] of recipeIngredient.entries()) {
const atIndex = candidates[index]
const entry = atIndex && atIndex.raw === line
? atIndex
: candidates.find((candidate) => candidate && candidate.raw === line)
if (entry !== atIndex || !entry) repaired += 1
const name = typeof entry?.name === 'string' && entry.name.trim() !== '' ? entry.name.trim() : line
const unit = typeof entry?.unit === 'string' && entry.unit.trim() !== '' ? entry.unit.trim() : null
aligned.push({
raw: line,
name,
quantity: typeof entry?.quantity === 'number' && Number.isFinite(entry.quantity) ? entry.quantity : null,
unit,
imprecise: entry ? entry.imprecise === true : true
})
}
return { parsedIngredients: aligned, repaired }
}