Cause racine du signalement "beaucoup d'ingredients ne sont pas linkes,
de meme pour les unites et les quantites" sur Marmiton/750g/Manger
Bouger : translateRecipe (recipe-translation.ts) ET previewSourceItem
(sources.service.ts) sautaient integralement loadIngredientCatalog/
loadUnitCatalog/translateRecipeIngredients des que locale !== "en" —
aucune tentative de matching n'etait jamais faite pour une source
francaise, pas un probleme de qualite de matching. Les trois sources
ajoutees dans cette session sont toutes locale: "fr".
Corrige en trois temps :
- packages/shared/src/data/catalog-labels-fr.ts (nouveau) :
INGREDIENT_LABELS_FR (554 entrees, copiees depuis
apps/web/src/locales/fr/translation.json qui les avait deja pour
l'UI — pas une nouvelle redaction), INGREDIENT_LABEL_SYNONYMS_FR
(mecanisme existant, pour patcher au cas par cas les libelles dont le
phrasage "affichage" ne correspond pas a l'ordre naturel d'un texte
de recette — ex. vanillaBean), UNIT_LABELS_FR (17 entrees,
redigees a la main comme UNIT_LABELS_EN — abreviations/variantes
reellement utilisees en francais : cuillere a soupe/cas/c.a.s...).
- ingredient-matcher.ts : stemWord se scinde en stemWordEn/stemWordFr
(locale parametrable, defaut "en" pour ne rien casser) — le stemmer
anglais appliquait sa regle "es" -> "" a des pluriels francais
reguliers ("carottes" -> "carott" au lieu de "carotte"), cassant
silencieusement le matching pour la quasi-totalite des ingredients
francais dont le singulier se termine par une voyelle. matchUnit est
reecrit pour chercher une sous-sequence ordonnee (comme
matchIngredientName) plutot qu'une egalite du seul premier mot : un
synonyme francais peut etre multi-mots ("cuillere a soupe"), une
phrase entiere ne pouvant jamais egaler un seul mot extrait.
loadIngredientCatalog/loadUnitCatalog prennent un parametre locale.
- recipe-translation.ts/sources.service.ts : suppression du
if (locale !== "en") qui court-circuitait tout — les catalogues sont
desormais toujours charges avec la locale de la source ; une locale
sans table de libelles recoit simplement des catalogues vides (degrade
gracieusement, ne plante pas).
Tests : 14 nouveaux tests purs (matchIngredientName/matchUnit fr,
stemmer, regression), 3 nouveaux tests DB (loadIngredientCatalog/
loadUnitCatalog fr + locale inconnue), 3 nouveaux tests
recipe-translation remplacant un test qui figeait l'ancien comportement
cassé, 1 nouveau test d'integration HTTP (sources.test.ts) avec un
adaptateur factice francais bout en bout. Les tests DB n'ont pas pu
etre executes localement (pas de Postgres/Docker dans cet environnement
sandbox) — a verifier en CI.
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
364 lines
15 KiB
TypeScript
364 lines
15 KiB
TypeScript
import { INGREDIENT_LABEL_SYNONYMS_EN, INGREDIENT_LABEL_SYNONYMS_FR } from "@batch-cooking/shared";
|
|
import { expect } from "chai";
|
|
import { prisma } from "../../src/db/prisma.js";
|
|
import {
|
|
extractQuantity,
|
|
type IngredientMatchEntry,
|
|
loadIngredientCatalog,
|
|
loadUnitCatalog,
|
|
matchIngredientName,
|
|
matchUnit,
|
|
type UnitMatchEntry,
|
|
} from "../../src/lib/recipe-matching/ingredient-matcher.js";
|
|
import { resetDatabase } from "../../test-support/reset-db.js";
|
|
|
|
describe("ingredient-matcher", () => {
|
|
describe("matchIngredientName", () => {
|
|
const tomato: IngredientMatchEntry = { ingredientId: 1, label: "Tomato" };
|
|
const chicken: IngredientMatchEntry = { ingredientId: 2, label: "Chicken" };
|
|
const chickenBreast: IngredientMatchEntry = { ingredientId: 3, label: "Chicken breast" };
|
|
const onion: IngredientMatchEntry = { ingredientId: 4, label: "Onion" };
|
|
const allPurposeFlour: IngredientMatchEntry = { ingredientId: 5, label: "All-purpose flour" };
|
|
const catalog = [tomato, chicken, chickenBreast, onion, allPurposeFlour];
|
|
|
|
it("matches an exact single-word label", () => {
|
|
expect(matchIngredientName("tomato", catalog)).to.equal(tomato.ingredientId);
|
|
});
|
|
|
|
it("is case- and accent-insensitive", () => {
|
|
expect(matchIngredientName("TOMATO", catalog)).to.equal(tomato.ingredientId);
|
|
expect(matchIngredientName("Tömato", catalog)).to.equal(tomato.ingredientId);
|
|
});
|
|
|
|
it("tolerates a regular plural", () => {
|
|
expect(matchIngredientName("tomatoes", catalog)).to.equal(tomato.ingredientId);
|
|
expect(matchIngredientName("onions", catalog)).to.equal(onion.ingredientId);
|
|
});
|
|
|
|
it("tolerates extra descriptive words around the match", () => {
|
|
expect(matchIngredientName("2 large diced yellow onions", catalog)).to.equal(
|
|
onion.ingredientId,
|
|
);
|
|
});
|
|
|
|
it("prefers the more specific multi-word label over a shorter one it contains", () => {
|
|
expect(matchIngredientName("boneless skinless chicken breasts", catalog)).to.equal(
|
|
chickenBreast.ingredientId,
|
|
);
|
|
});
|
|
|
|
it("still matches the shorter label when the more specific one isn't mentioned", () => {
|
|
expect(matchIngredientName("diced chicken thighs", catalog)).to.equal(chicken.ingredientId);
|
|
});
|
|
|
|
it("matches a hyphenated multi-word label", () => {
|
|
expect(matchIngredientName("2 cups all-purpose flour", catalog)).to.equal(
|
|
allPurposeFlour.ingredientId,
|
|
);
|
|
});
|
|
|
|
it("doesn't false-positive a short label inside an unrelated longer word", () => {
|
|
// "egg" must not match inside "eggplant" — whole-token comparison, not substring.
|
|
const eggplant: IngredientMatchEntry = { ingredientId: 6, label: "Eggplant" };
|
|
const egg: IngredientMatchEntry = { ingredientId: 7, label: "Egg" };
|
|
expect(matchIngredientName("eggplant", [egg, eggplant])).to.equal(eggplant.ingredientId);
|
|
});
|
|
|
|
it("returns null when nothing matches", () => {
|
|
expect(matchIngredientName("mango", catalog)).to.equal(null);
|
|
});
|
|
|
|
it("returns null for an empty catalog", () => {
|
|
expect(matchIngredientName("tomato", [])).to.equal(null);
|
|
});
|
|
|
|
it("returns null for an empty name", () => {
|
|
expect(matchIngredientName("", catalog)).to.equal(null);
|
|
});
|
|
|
|
it("matches an alternate wording of the same ingredient via a second catalog entry sharing its ingredientId (issue #54)", () => {
|
|
const vanillaBean: IngredientMatchEntry = { ingredientId: 8, label: "Vanilla bean" };
|
|
const vanillaBeanSynonym: IngredientMatchEntry = { ingredientId: 8, label: "Vanilla pod" };
|
|
const synonymCatalog = [vanillaBean, vanillaBeanSynonym];
|
|
|
|
expect(matchIngredientName("1 vanilla pod", synonymCatalog)).to.equal(8);
|
|
expect(matchIngredientName("1 vanilla bean", synonymCatalog)).to.equal(8);
|
|
});
|
|
|
|
it("breaks a same-specificity tie by the lowest ingredientId", () => {
|
|
const onionA: IngredientMatchEntry = { ingredientId: 20, label: "Onion" };
|
|
const onionB: IngredientMatchEntry = { ingredientId: 21, label: "Onion" };
|
|
expect(matchIngredientName("onion", [onionB, onionA])).to.equal(20);
|
|
});
|
|
|
|
describe("locale: fr", () => {
|
|
const carotte: IngredientMatchEntry = { ingredientId: 30, label: "Carotte" };
|
|
const poulet: IngredientMatchEntry = { ingredientId: 31, label: "Poulet" };
|
|
const blancDePoulet: IngredientMatchEntry = { ingredientId: 32, label: "Blanc de poulet" };
|
|
const frCatalog = [carotte, poulet, blancDePoulet];
|
|
|
|
it("tolerates a regular French plural (a bare 's', unlike English's several suffix patterns)", () => {
|
|
// Regression case: French plurals like "carottes" end in "es", which
|
|
// the English stemmer's own "es" rule would wrongly strip down to
|
|
// "carott" (losing the "e" that's part of the singular "carotte")
|
|
// — see stemWordFr's own doc comment. Locale "fr" must use the
|
|
// French stemmer instead, or this never matches.
|
|
expect(matchIngredientName("carottes", frCatalog, "fr")).to.equal(carotte.ingredientId);
|
|
});
|
|
|
|
it("is accent-insensitive the same way the English path is", () => {
|
|
expect(matchIngredientName("CAROTTES", frCatalog, "fr")).to.equal(carotte.ingredientId);
|
|
});
|
|
|
|
it("tolerates extra descriptive words around the match", () => {
|
|
expect(matchIngredientName("2 carottes râpées", frCatalog, "fr")).to.equal(
|
|
carotte.ingredientId,
|
|
);
|
|
});
|
|
|
|
it("prefers the more specific multi-word label over a shorter one it contains", () => {
|
|
expect(matchIngredientName("blancs de poulet fermier", frCatalog, "fr")).to.equal(
|
|
blancDePoulet.ingredientId,
|
|
);
|
|
});
|
|
|
|
it("defaults to the English stemmer when no locale is passed — 'fr' text needs to opt in explicitly", () => {
|
|
// Without locale: "fr", "carottes" stems via the English rules
|
|
// (endsWith("es") -> strip 2 chars) into "carott", which doesn't
|
|
// equal the catalog's own (also English-stemmed) "carotte" — no
|
|
// match. This is the exact bug locale-aware stemming fixes; this
|
|
// test pins down that the *default* stays exactly as it was for
|
|
// every pre-existing English-only caller.
|
|
expect(matchIngredientName("carottes", frCatalog)).to.equal(null);
|
|
});
|
|
});
|
|
});
|
|
|
|
describe("matchUnit", () => {
|
|
const gram: UnitMatchEntry = { unitId: 1, synonyms: ["g", "gram", "grams"] };
|
|
const tablespoon: UnitMatchEntry = {
|
|
unitId: 2,
|
|
synonyms: ["tbsp", "tbs", "tablespoon", "tablespoons"],
|
|
};
|
|
const cup: UnitMatchEntry = { unitId: 3, synonyms: ["cup", "cups"] };
|
|
const catalog = [gram, tablespoon, cup];
|
|
|
|
it("matches a full word synonym", () => {
|
|
expect(matchUnit("tablespoon", catalog)).to.equal(tablespoon.unitId);
|
|
});
|
|
|
|
it("matches an abbreviation synonym", () => {
|
|
expect(matchUnit("tbsp", catalog)).to.equal(tablespoon.unitId);
|
|
});
|
|
|
|
it("matches a plural synonym via the same stemming as ingredients", () => {
|
|
expect(matchUnit("cups", catalog)).to.equal(cup.unitId);
|
|
});
|
|
|
|
it("is case-insensitive", () => {
|
|
expect(matchUnit("TBSP", catalog)).to.equal(tablespoon.unitId);
|
|
});
|
|
|
|
it("ignores trailing text after the unit word", () => {
|
|
expect(matchUnit("cup flour", catalog)).to.equal(cup.unitId);
|
|
});
|
|
|
|
it("also finds the unit word when it isn't first — unlike before French support existed, this is no longer only a first-word check (see the function's own doc comment)", () => {
|
|
expect(matchUnit("a heaped tablespoon of sugar", catalog)).to.equal(tablespoon.unitId);
|
|
});
|
|
|
|
it("doesn't match a short abbreviation inside an unrelated word", () => {
|
|
// "g" alone must not match "grated" — whole-token comparison.
|
|
expect(matchUnit("grated", catalog)).to.equal(null);
|
|
});
|
|
|
|
it("returns null when nothing matches", () => {
|
|
expect(matchUnit("pound", catalog)).to.equal(null);
|
|
});
|
|
|
|
it("returns null for an empty catalog", () => {
|
|
expect(matchUnit("cup", [])).to.equal(null);
|
|
});
|
|
|
|
it("returns null for an empty string", () => {
|
|
expect(matchUnit("", catalog)).to.equal(null);
|
|
});
|
|
|
|
describe("locale: fr", () => {
|
|
const gramme: UnitMatchEntry = { unitId: 40, synonyms: ["g", "gr", "gramme", "grammes"] };
|
|
const cuillereASoupe: UnitMatchEntry = {
|
|
unitId: 41,
|
|
synonyms: ["cuillère à soupe", "cuillères à soupe", "càs"],
|
|
};
|
|
const frCatalog = [gramme, cuillereASoupe];
|
|
|
|
it("matches a genuinely multi-word synonym — the bug this locale support fixes: the old single-first-token check could never equal a whole multi-word phrase", () => {
|
|
expect(matchUnit("cuillères à soupe de farine", frCatalog, "fr")).to.equal(
|
|
cuillereASoupe.unitId,
|
|
);
|
|
});
|
|
|
|
it("matches a single-word abbreviation the same way English units do", () => {
|
|
expect(matchUnit("càs de farine", frCatalog, "fr")).to.equal(cuillereASoupe.unitId);
|
|
});
|
|
|
|
it("is accent-insensitive", () => {
|
|
expect(matchUnit("2 CUILLÈRES À SOUPE de farine", frCatalog, "fr")).to.equal(
|
|
cuillereASoupe.unitId,
|
|
);
|
|
});
|
|
|
|
it("doesn't match a multi-word phrase against unrelated text mentioning the same first word alone", () => {
|
|
expect(matchUnit("cuillère de bois", frCatalog, "fr")).to.equal(null);
|
|
});
|
|
});
|
|
});
|
|
|
|
describe("extractQuantity", () => {
|
|
it("extracts a plain integer", () => {
|
|
expect(extractQuantity("2 onions")).to.deep.equal({ quantity: 2, remainder: "onions" });
|
|
});
|
|
|
|
it("extracts a decimal using a dot", () => {
|
|
expect(extractQuantity("1.5 cups flour")).to.deep.equal({
|
|
quantity: 1.5,
|
|
remainder: "cups flour",
|
|
});
|
|
});
|
|
|
|
it("extracts a decimal using a comma", () => {
|
|
expect(extractQuantity("1,5 cups flour")).to.deep.equal({
|
|
quantity: 1.5,
|
|
remainder: "cups flour",
|
|
});
|
|
});
|
|
|
|
it("extracts a simple fraction", () => {
|
|
expect(extractQuantity("1/2 cup sugar")).to.deep.equal({
|
|
quantity: 0.5,
|
|
remainder: "cup sugar",
|
|
});
|
|
});
|
|
|
|
it("extracts a mixed number", () => {
|
|
expect(extractQuantity("1 1/2 cups sugar")).to.deep.equal({
|
|
quantity: 1.5,
|
|
remainder: "cups sugar",
|
|
});
|
|
});
|
|
|
|
it("returns null quantity and the trimmed original text when there's no leading number", () => {
|
|
expect(extractQuantity("salt to taste")).to.deep.equal({
|
|
quantity: null,
|
|
remainder: "salt to taste",
|
|
});
|
|
});
|
|
|
|
it("trims surrounding whitespace", () => {
|
|
expect(extractQuantity(" 2 eggs ")).to.deep.equal({ quantity: 2, remainder: "eggs" });
|
|
});
|
|
|
|
it("only takes the first number of a hyphenated range", () => {
|
|
expect(extractQuantity("2-3 carrots")).to.deep.equal({
|
|
quantity: 2,
|
|
remainder: "-3 carrots",
|
|
});
|
|
});
|
|
});
|
|
|
|
describe("loadIngredientCatalog / loadUnitCatalog", () => {
|
|
beforeEach(async () => {
|
|
await resetDatabase();
|
|
});
|
|
|
|
after(async () => {
|
|
await prisma.$disconnect();
|
|
});
|
|
|
|
it("loads one entry per Ingredient that has an English label, plus one per alternate wording (INGREDIENT_LABEL_SYNONYMS_EN), keyed by real ingredientId", async () => {
|
|
const tomato = await prisma.ingredient.findFirstOrThrow({ where: { key: "tomato" } });
|
|
const vanillaBean = await prisma.ingredient.findFirstOrThrow({
|
|
where: { key: "vanillaBean" },
|
|
});
|
|
const ingredientCount = await prisma.ingredient.count();
|
|
const synonymCount = Object.values(INGREDIENT_LABEL_SYNONYMS_EN).reduce(
|
|
(sum, synonyms) => sum + synonyms.length,
|
|
0,
|
|
);
|
|
|
|
const catalog = await loadIngredientCatalog();
|
|
|
|
// Every seeded ingredient has an authored English label (verified at
|
|
// generation time — see packages/shared/src/data/catalog-labels-en.ts),
|
|
// so nothing should be silently skipped — plus one extra entry per
|
|
// synonym (issue #54), sharing the same ingredientId as the primary
|
|
// label's entry.
|
|
expect(catalog).to.have.length(ingredientCount + synonymCount);
|
|
const tomatoEntry = catalog.find((entry) => entry.ingredientId === tomato.id);
|
|
expect(tomatoEntry?.label).to.equal("Tomato");
|
|
|
|
const vanillaBeanEntries = catalog.filter((entry) => entry.ingredientId === vanillaBean.id);
|
|
expect(vanillaBeanEntries.map((entry) => entry.label)).to.deep.equal([
|
|
"Vanilla bean",
|
|
"Vanilla pod",
|
|
]);
|
|
});
|
|
|
|
it("loads one entry per Unit that has English synonyms, keyed by real unitId", async () => {
|
|
const cup = await prisma.unit.findFirstOrThrow({ where: { key: "cup" } });
|
|
const unitCount = await prisma.unit.count();
|
|
|
|
const catalog = await loadUnitCatalog();
|
|
|
|
expect(catalog).to.have.length(unitCount);
|
|
const cupEntry = catalog.find((entry) => entry.unitId === cup.id);
|
|
expect(cupEntry?.synonyms).to.deep.equal(["cup", "cups"]);
|
|
});
|
|
|
|
it("loads one entry per Ingredient that has a French label, plus one per alternate wording (INGREDIENT_LABEL_SYNONYMS_FR), keyed by real ingredientId", async () => {
|
|
const carrot = await prisma.ingredient.findFirstOrThrow({ where: { key: "carrot" } });
|
|
const vanillaBean = await prisma.ingredient.findFirstOrThrow({
|
|
where: { key: "vanillaBean" },
|
|
});
|
|
const ingredientCount = await prisma.ingredient.count();
|
|
const synonymCount = Object.values(INGREDIENT_LABEL_SYNONYMS_FR).reduce(
|
|
(sum, synonyms) => sum + synonyms.length,
|
|
0,
|
|
);
|
|
|
|
const catalog = await loadIngredientCatalog("fr");
|
|
|
|
// Every seeded ingredient has an authored French label too (copied
|
|
// from apps/web's fr locale — see catalog-labels-fr.ts's own doc
|
|
// comment), so this mirrors the English test above 1:1.
|
|
expect(catalog).to.have.length(ingredientCount + synonymCount);
|
|
const carrotEntry = catalog.find((entry) => entry.ingredientId === carrot.id);
|
|
expect(carrotEntry?.label).to.equal("Carotte");
|
|
|
|
const vanillaBeanEntries = catalog.filter((entry) => entry.ingredientId === vanillaBean.id);
|
|
expect(vanillaBeanEntries.map((entry) => entry.label)).to.deep.equal([
|
|
"Vanille (gousse)",
|
|
"Gousse de vanille",
|
|
]);
|
|
});
|
|
|
|
it("loads one entry per Unit that has French synonyms, keyed by real unitId", async () => {
|
|
const cup = await prisma.unit.findFirstOrThrow({ where: { key: "cup" } });
|
|
const unitCount = await prisma.unit.count();
|
|
|
|
const catalog = await loadUnitCatalog("fr");
|
|
|
|
expect(catalog).to.have.length(unitCount);
|
|
const cupEntry = catalog.find((entry) => entry.unitId === cup.id);
|
|
expect(cupEntry?.synonyms).to.deep.equal(["tasse", "tasses"]);
|
|
});
|
|
|
|
it("returns an empty catalog for a locale with no label table at all — the DB is still queried, there's just nothing in either table to match a row against", async () => {
|
|
const ingredientCatalog = await loadIngredientCatalog("de");
|
|
const unitCatalog = await loadUnitCatalog("de");
|
|
|
|
expect(ingredientCatalog).to.deep.equal([]);
|
|
expect(unitCatalog).to.deep.equal([]);
|
|
});
|
|
});
|
|
});
|