Spaces:
Sleeping
Sleeping
Update services/recipe_service.py
Browse files- services/recipe_service.py +61 -266
services/recipe_service.py
CHANGED
|
@@ -1,268 +1,63 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
@dataclass
|
| 44 |
-
class IngredientResult:
|
| 45 |
-
original: str
|
| 46 |
-
normalized: str
|
| 47 |
-
compliant: bool
|
| 48 |
-
substitute: str
|
| 49 |
-
instructions: str
|
| 50 |
-
source: str
|
| 51 |
-
matched_ingredient: Optional[str] = None
|
| 52 |
-
confidence: float = 1.0
|
| 53 |
-
notes: Optional[str] = None
|
| 54 |
-
|
| 55 |
-
def as_dict(self) -> Dict[str, Any]:
|
| 56 |
-
payload = {
|
| 57 |
-
"original": self.original,
|
| 58 |
-
"normalized": self.normalized,
|
| 59 |
-
"compliant": self.compliant,
|
| 60 |
-
"substitute": self.substitute,
|
| 61 |
-
"instructions": self.instructions,
|
| 62 |
-
"source": self.source,
|
| 63 |
-
"matched_ingredient": self.matched_ingredient,
|
| 64 |
-
"confidence": round(float(self.confidence), 3),
|
| 65 |
-
}
|
| 66 |
-
if self.notes:
|
| 67 |
-
payload["notes"] = self.notes
|
| 68 |
-
return payload
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
class RecipeAdapterService:
|
| 72 |
-
def __init__(self, db: SubstitutionDatabase, semantic: WordVectorFallback):
|
| 73 |
-
self.db = db
|
| 74 |
-
self.semantic = semantic
|
| 75 |
-
|
| 76 |
-
def _row_to_result(self, ingredient: str, row, diet: Diet) -> IngredientResult:
|
| 77 |
-
substitute, instructions, compliant = self.db.pick_substitution(row, diet)
|
| 78 |
-
normalized = normalize_text(ingredient)
|
| 79 |
-
|
| 80 |
-
if compliant:
|
| 81 |
-
return IngredientResult(
|
| 82 |
-
original=ingredient,
|
| 83 |
-
normalized=normalized,
|
| 84 |
-
compliant=True,
|
| 85 |
-
substitute=ingredient,
|
| 86 |
-
instructions="Already compatible — no substitution needed.",
|
| 87 |
-
source="database match",
|
| 88 |
-
matched_ingredient=row.ingredient,
|
| 89 |
-
confidence=1.0,
|
| 90 |
-
)
|
| 91 |
-
|
| 92 |
-
return IngredientResult(
|
| 93 |
-
original=ingredient,
|
| 94 |
-
normalized=normalized,
|
| 95 |
-
compliant=False,
|
| 96 |
-
substitute=substitute,
|
| 97 |
-
instructions=instructions or "",
|
| 98 |
-
source="database match",
|
| 99 |
-
matched_ingredient=row.ingredient,
|
| 100 |
-
confidence=0.96,
|
| 101 |
-
)
|
| 102 |
-
|
| 103 |
-
def _rule_fallback(self, ingredient: str, diet: Diet, recipe_type: str) -> Optional[IngredientResult]:
|
| 104 |
-
text = normalize_text(ingredient)
|
| 105 |
-
singular = singularize(text)
|
| 106 |
-
if singular != text:
|
| 107 |
-
text = f"{text} {singular}"
|
| 108 |
-
|
| 109 |
-
def result(sub: str, instr: str, source: str = "diet rule fallback", conf: float = 0.94) -> IngredientResult:
|
| 110 |
-
return IngredientResult(
|
| 111 |
-
original=ingredient,
|
| 112 |
-
normalized=normalize_text(ingredient),
|
| 113 |
-
compliant=False,
|
| 114 |
-
substitute=sub,
|
| 115 |
-
instructions=instr,
|
| 116 |
-
source=source,
|
| 117 |
-
matched_ingredient=None,
|
| 118 |
-
confidence=conf,
|
| 119 |
-
)
|
| 120 |
-
|
| 121 |
-
if diet in {"vegan", "both"}:
|
| 122 |
-
if any(hint in text for hint in VEGAN_EGG_HINTS):
|
| 123 |
-
if recipe_type == "baked":
|
| 124 |
-
return result("Flax Egg", "1 tbsp ground flax + 3 tbsp water per egg. Rest 5 min before using.")
|
| 125 |
-
if diet == "both":
|
| 126 |
-
return result("Silken Tofu", "Blend until smooth and use as a creamy egg-free binder.")
|
| 127 |
-
return result("Silken Tofu or Tofu Scramble", "Blend silken tofu for sauces or use crumbled tofu for savory dishes.")
|
| 128 |
-
|
| 129 |
-
if any(hint in text for hint in VEGAN_ANIMAL_HINTS):
|
| 130 |
-
if any(hint in text for hint in {"pancetta", "bacon", "guanciale", "pork", "ham", "prosciutto", "sausage"}):
|
| 131 |
-
if diet == "both":
|
| 132 |
-
return result("Extra Firm Tofu", "Press tofu 30 min, cube and pan-fry until golden.")
|
| 133 |
-
return result("Smoked Tofu or Tempeh Bacon", "Dice and pan-fry until crispy.")
|
| 134 |
-
if any(hint in text for hint in {"chicken", "beef", "turkey", "lamb", "fish", "shrimp", "anchovy"}):
|
| 135 |
-
if diet == "both":
|
| 136 |
-
return result("Extra Firm Tofu", "Use as a 1:1 savory protein substitute.")
|
| 137 |
-
return result("Soy Curls or Extra Firm Tofu", "Use as a 1:1 meat substitute.")
|
| 138 |
-
return result("Plant-based alternative", "Choose a vegan substitute that matches the recipe context.")
|
| 139 |
-
|
| 140 |
-
if any(hint in text for hint in VEGAN_DAIRY_HINTS):
|
| 141 |
-
if "butter" in text:
|
| 142 |
-
return result("Vegan Butter", "Use 1:1 in place of butter.")
|
| 143 |
-
if "milk" in text:
|
| 144 |
-
return result("Unsweetened Plant Milk", "Use 1:1 in place of dairy milk.")
|
| 145 |
-
if "cream" in text:
|
| 146 |
-
return result("Cashew Cream", "Use as a rich dairy-free cream substitute.")
|
| 147 |
-
if "cheese" in text:
|
| 148 |
-
return result("Vegan Cheese", "Use a meltable vegan cheese or nutritional yeast blend.")
|
| 149 |
-
return result("Plant-based alternative", "Choose a vegan substitute that matches the recipe context.")
|
| 150 |
-
|
| 151 |
-
if diet in {"keto", "both"}:
|
| 152 |
-
if any(hint in text for hint in KETO_CARB_HINTS):
|
| 153 |
-
if "spaghetti" in text or "pasta" in text or "noodle" in text:
|
| 154 |
-
return result("Zucchini Noodles or Shirataki Noodles", "Use in a 1:1 swap for pasta-style dishes.")
|
| 155 |
-
if "rice" in text:
|
| 156 |
-
return result("Cauliflower Rice", "Use as a low-carb rice substitute.")
|
| 157 |
-
if "flour" in text:
|
| 158 |
-
return result("Almond Flour", "Use a keto baking flour blend.")
|
| 159 |
-
if "sugar" in text or "honey" in text or "syrup" in text:
|
| 160 |
-
return result("Erythritol or Allulose", "Use a keto-friendly sweetener to taste.")
|
| 161 |
-
if "potato" in text:
|
| 162 |
-
return result("Cauliflower", "Use roasted cauliflower or cauliflower mash.")
|
| 163 |
-
return result("Low-carb alternative", "Choose a keto-friendly substitute that matches the recipe context.")
|
| 164 |
-
|
| 165 |
-
return None
|
| 166 |
-
|
| 167 |
-
def _semantic_fallback(self, ingredient: str, diet: Diet, recipe_type: str) -> Optional[IngredientResult]:
|
| 168 |
-
if not self.semantic.available:
|
| 169 |
-
return None
|
| 170 |
-
|
| 171 |
-
candidates = self.db.semantic_terms(recipe_type)
|
| 172 |
-
if not candidates:
|
| 173 |
-
return None
|
| 174 |
-
|
| 175 |
-
hits = self.semantic.nearest(ingredient, candidates, top_k=5)
|
| 176 |
-
if not hits:
|
| 177 |
-
return None
|
| 178 |
-
|
| 179 |
-
for hit in hits:
|
| 180 |
-
if hit.score < settings.similarity_threshold:
|
| 181 |
-
continue
|
| 182 |
-
matched_rows = self.db.find_rows(hit.term, recipe_type)
|
| 183 |
-
if not matched_rows:
|
| 184 |
continue
|
| 185 |
-
row = matched_rows[0]
|
| 186 |
-
result = self._row_to_result(ingredient, row, diet)
|
| 187 |
-
result.source = f"glove semantic match ({hit.term}, score={hit.score:.2f})"
|
| 188 |
-
result.confidence = max(0.5, min(0.95, hit.score))
|
| 189 |
-
return result
|
| 190 |
-
|
| 191 |
-
return None
|
| 192 |
-
|
| 193 |
-
def _manual_review_result(self, ingredient: str) -> IngredientResult:
|
| 194 |
-
text = normalize_text(ingredient)
|
| 195 |
-
if text in NEUTRAL_OK:
|
| 196 |
-
return IngredientResult(
|
| 197 |
-
original=ingredient,
|
| 198 |
-
normalized=text,
|
| 199 |
-
compliant=True,
|
| 200 |
-
substitute=ingredient,
|
| 201 |
-
instructions="Already compatible — no substitution needed.",
|
| 202 |
-
source="known compatible",
|
| 203 |
-
matched_ingredient=None,
|
| 204 |
-
confidence=0.9,
|
| 205 |
-
)
|
| 206 |
-
|
| 207 |
-
return IngredientResult(
|
| 208 |
-
original=ingredient,
|
| 209 |
-
normalized=text,
|
| 210 |
-
compliant=False,
|
| 211 |
-
substitute=ingredient,
|
| 212 |
-
instructions="No reliable substitution found — please review manually.",
|
| 213 |
-
source="not in database",
|
| 214 |
-
matched_ingredient=None,
|
| 215 |
-
confidence=0.35,
|
| 216 |
-
notes="No reliable database or semantic match found.",
|
| 217 |
-
)
|
| 218 |
-
|
| 219 |
-
def adapt(self, recipe_text: str, diet: Diet) -> Dict[str, Any]:
|
| 220 |
-
if diet not in {"vegan", "keto", "both"}:
|
| 221 |
-
raise ValueError("diet must be one of: vegan, keto, both")
|
| 222 |
-
|
| 223 |
-
recipe_text = (recipe_text or "").strip()
|
| 224 |
-
if len(recipe_text) < 5:
|
| 225 |
-
raise ValueError("recipe_text is too short")
|
| 226 |
-
|
| 227 |
-
recipe_type = classify_recipe(recipe_text)
|
| 228 |
-
ingredients = extract_ingredients(recipe_text, max_items=settings.max_ingredients)
|
| 229 |
-
|
| 230 |
-
results: List[IngredientResult] = []
|
| 231 |
-
substitutions = 0
|
| 232 |
-
|
| 233 |
-
for ingredient in ingredients:
|
| 234 |
-
matches = self.db.find_rows(ingredient, recipe_type)
|
| 235 |
-
if matches:
|
| 236 |
-
result = self._row_to_result(ingredient, matches[0], diet)
|
| 237 |
-
else:
|
| 238 |
-
result = self._rule_fallback(ingredient, diet, recipe_type)
|
| 239 |
-
if result is None:
|
| 240 |
-
result = self._semantic_fallback(ingredient, diet, recipe_type)
|
| 241 |
-
if result is None:
|
| 242 |
-
result = self._manual_review_result(ingredient)
|
| 243 |
-
|
| 244 |
-
if not result.compliant:
|
| 245 |
-
substitutions += 1
|
| 246 |
-
results.append(result)
|
| 247 |
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
),
|
| 268 |
-
}
|
|
|
|
| 1 |
+
def _head_token(text: str) -> str:
|
| 2 |
+
parts = (text or "").split()
|
| 3 |
+
return parts[-1] if parts else ""
|
| 4 |
+
|
| 5 |
+
def _token_overlap(a: str, b: str) -> bool:
|
| 6 |
+
sa = set((a or "").split())
|
| 7 |
+
sb = set((b or "").split())
|
| 8 |
+
return bool(sa & sb)
|
| 9 |
+
|
| 10 |
+
def lookup(self, ingredient: str, recipe_type: str, diet: str):
|
| 11 |
+
preferred = BAKE_CONTEXTS if recipe_type == "baked" else COOK_CONTEXTS
|
| 12 |
+
variants = ingredient_lookup_variants(ingredient)
|
| 13 |
+
query_norm = normalize_ingredient_for_lookup(ingredient)
|
| 14 |
+
query_head = _head_token(query_norm)
|
| 15 |
+
|
| 16 |
+
# 1) exact match first
|
| 17 |
+
for v in variants:
|
| 18 |
+
row = self.db.find_exact(v, preferred_contexts=preferred)
|
| 19 |
+
if row is not None:
|
| 20 |
+
return self._format_result(ingredient, row, diet, "database match", 1.0)
|
| 21 |
+
|
| 22 |
+
# 2) alias / partial match second, but only for real ingredient-length tokens
|
| 23 |
+
for v in variants:
|
| 24 |
+
if len(v) < 4:
|
| 25 |
+
continue
|
| 26 |
+
row = self.db.find_partial(v, preferred_contexts=preferred)
|
| 27 |
+
if row is not None:
|
| 28 |
+
return self._format_result(ingredient, row, diet, "partial match", 0.85)
|
| 29 |
+
|
| 30 |
+
# 3) semantic fallback only if it is actually close AND same ingredient family
|
| 31 |
+
if self.semantic and self.semantic.available:
|
| 32 |
+
best = self.semantic.most_similar(query_norm, topn=10)
|
| 33 |
+
|
| 34 |
+
for candidate_text, score in best:
|
| 35 |
+
if score < 0.82:
|
| 36 |
+
break
|
| 37 |
+
|
| 38 |
+
cand_norm = normalize_ingredient_for_lookup(candidate_text)
|
| 39 |
+
cand_head = _head_token(cand_norm)
|
| 40 |
+
|
| 41 |
+
# reject nonsense like spinach -> sparkling water
|
| 42 |
+
if query_head and cand_head and query_head != cand_head and not _token_overlap(query_norm, cand_norm):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
+
row = self.db.find_exact(cand_norm, preferred_contexts=preferred)
|
| 46 |
+
if row is None:
|
| 47 |
+
row = self.db.find_partial(cand_norm, preferred_contexts=preferred)
|
| 48 |
+
|
| 49 |
+
if row is not None:
|
| 50 |
+
return self._format_result(ingredient, row, diet, f"semantic match ({candidate_text})", float(score))
|
| 51 |
+
|
| 52 |
+
# 4) do NOT guess
|
| 53 |
+
return {
|
| 54 |
+
"original": ingredient,
|
| 55 |
+
"normalized": query_norm,
|
| 56 |
+
"compliant": False,
|
| 57 |
+
"substitute": ingredient,
|
| 58 |
+
"instructions": "No reliable match found — verify manually.",
|
| 59 |
+
"source": "unmatched",
|
| 60 |
+
"matched_ingredient": None,
|
| 61 |
+
"confidence": 0.0,
|
| 62 |
+
"notes": "No exact, alias, or safe semantic match found.",
|
| 63 |
+
}
|
|
|
|
|
|