-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
267 lines (214 loc) · 8.88 KB
/
Copy pathapp.py
File metadata and controls
267 lines (214 loc) · 8.88 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
import os
import json
import difflib
import streamlit as st
import requests
# Configuration
HF_TOKEN = os.getenv("HF_API_KEY")
MODEL_REPO = os.getenv("HF_MODEL_REPO") or "HuggingFaceH4/zephyr-7b-beta:featherless-ai"
API_URL = "https://router.huggingface.co/v1/chat/completions"
if not HF_TOKEN:
st.error("Missing Hugging Face API key. Set HF_TOKEN as an environment variable.")
st.stop()
HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"}
# Load product links
try:
with open("product_links.json", "r", encoding="utf-8") as f:
PRODUCT_LINKS = json.load(f)
except FileNotFoundError:
PRODUCT_LINKS = {}
# Gluten substitutions
SUBS = {
"wheat flour": "gluten-free all-purpose flour or rice flour",
"flour": "gluten-free all-purpose flour",
"breadcrumbs": "gluten-free breadcrumbs or crushed cornflakes",
"soy sauce": "tamari (gluten-free) or coconut aminos",
"pasta": "gluten-free pasta (rice/corn/quinoa)",
"noodles": "rice noodles or glass noodles",
"tortilla": "corn tortilla (check GF certified)",
"barley": "brown rice or quinoa",
"rye": "buckwheat groats (naturally GF)",
"couscous": "quinoa or millet",
"bulgur": "quinoa or cauliflower rice",
"semolina": "rice flour or cornmeal",
"malt": "omit or use maple syrup (for flavoring)",
"beer": "gluten-free beer or stock"
}
def get_product_link(product_name: str, region: str = "uk"):
"""
Retrieve the product link for a given product and region.
Args:
product_name (str): The name of the product to look up.
region (str, optional): The market region code (default is "uk").
Returns:
str or None: The product link if available, otherwise None.
"""
product = product_name.lower()
if product in PRODUCT_LINKS and region in PRODUCT_LINKS[product]:
base_url = PRODUCT_LINKS[product][region]
tag = st.secrets.get(f"product_tag_{region}", "")
return f"{base_url}?tag={tag}" if tag else base_url
return None
def possible_gluten_flags_with_links(ingredients_text: str, region: str = "uk"):
"""
Identify gluten-containing ingredients in the input text and suggest gluten-free substitutes,
including product links where available. Skips warnings if the ingredient is already labeled as gluten-free.
Uses fuzzy matching to detect misspelled ingredients.
Args:
ingredients_text (str): The list of ingredients as a string.
region (str, optional): The market region code (default is "uk").
Returns:
list: A list of dictionaries with keys 'ingredient', 'substitute', and 'link'.
"""
import difflib
text = ingredients_text.lower()
words = text.split()
flagged = []
for k, v in SUBS.items():
# Direct match check
if k in text:
if f"gluten-free {k}" in text or f"gf {k}" in text:
continue
link = get_product_link(v, region)
flagged.append({
"ingredient": k,
"substitute": v,
"link": link
})
continue
# Handle typos
for word in words:
close = difflib.get_close_matches(word, k.split(), cutoff=0.8)
if close:
if f"gluten-free {word}" in text or f"gf {word}" in text:
continue
link = get_product_link(v, region)
flagged.append({
"ingredient": k,
"substitute": v,
"link": link
})
break
return flagged
def get_product_recommendations(ingredients_text: str, region: str = "uk"):
"""
Suggest relevant gluten-free products based on detected ingredients.
Uses fuzzy matching to catch variations (e.g., 'spaguetti' → 'spaghetti').
Args:
ingredients_text (str): The list of ingredients as a string.
region (str, optional): The market region code (default is "uk").
Returns:
list: A list of tuples (product, product_link) for recommended products.
"""
recs = []
text = ingredients_text.lower().split()
for product, links in PRODUCT_LINKS.items():
link = links.get(region)
if not link:
continue
product_words = product.lower().split()
# Exact phrase match first
if all(word in " ".join(text) for word in product_words):
recs.append((product, link))
continue
# Fuzzy match (handles typos & variations)
for word in text:
close = difflib.get_close_matches(word, product_words, cutoff=0.75)
if close:
recs.append((product, link))
break
return recs
def hf_generate_chat(prompt_text: str):
"""
Sends a prompt to the Hugging Face chat completion API and returns the generated response.
Args:
prompt_text (str): The prompt or user message to send to the model.
Returns:
str: The generated message content from the model.
Raises:
RuntimeError: If the API response status is not 200 (success).
"""
messages = [{"role": "user", "content": prompt_text}]
payload = {"model": MODEL_REPO, "messages": messages}
resp = requests.post(API_URL, headers=HEADERS, json=payload, timeout=60)
if resp.status_code != 200:
raise RuntimeError(f"HF API error {resp.status_code}: {resp.text[:500]}")
data = resp.json()
return data["choices"][0]["message"]["content"]
def build_prompt(ingredients: str, avoid: str, servings: int, recipes_count: int):
"""
Constructs a prompt for the LLM to generate gluten-free recipes.
Args:
ingredients (str): Ingredients provided by the user.
avoid (str): Allergens or diets to avoid.
servings (int): Number of servings required.
recipes_count (int): Number of recipe options to generate.
Returns:
str: A formatted prompt string for the model.
"""
return f"""
You are a culinary assistant specialized in gluten-free cooking. Ensure every recipe is 100% gluten-free.
If any provided ingredient contains gluten, automatically swap it for safe alternatives and mention the swap.
User ingredients: {ingredients}
Allergens/diet to avoid (besides gluten): {avoid if avoid.strip() else "None specified"}
Servings: {servings}
TASK: Create {recipes_count} distinct gluten-free recipe OPTIONS that primarily use the user's ingredients.
Each option must follow EXACTLY this Markdown format:
# Recipe Title
Servings: <number>
Prep: <minutes> | Cook: <minutes>
## Ingredients
- <bullet list of GF ingredients only>
## Method
1. <step>
2. <step>
3. <step>
## Substitutions & Notes
- <list any swaps or GF cautions>
- <tips for variations or storage>
Keep it concise but practical. Avoid brand names. Always ensure substitutes are safe for celiac/gluten intolerance.
"""
# Streamlit UI
st.set_page_config(page_title="SinGlu", page_icon="🍲", layout="centered")
st.title("🍲 SinGlu - Gluten-Free Recipe Generator")
st.write("Enter your ingredients and get **gluten-free** recipes with substitutions and recommended products.")
with st.expander("Advanced options"):
recipes_count = st.slider("How many recipe options?", min_value=1, max_value=3, value=2)
servings = st.slider("Servings", min_value=1, max_value=8, value=2)
region = st.selectbox("Market region", options=["uk", "es"], index=0)
ingredients = st.text_area(
"Ingredients you have (comma or line separated)",
height=120,
placeholder="e.g., chicken thighs, tomatoes, onions, garlic, spinach, rice, soy sauce"
)
avoid = st.text_input("Avoid (optional, e.g., dairy, nuts)")
if st.button("Generate recipe(s)"):
if not ingredients.strip():
st.warning("Please enter some ingredients first.")
st.stop()
# Show substitutions with product links
flags = possible_gluten_flags_with_links(ingredients, region)
if flags:
st.info("Heads up! We detected potential gluten-containing items and suggested swaps:")
for f in flags:
sub_text = f"**{f['ingredient']}** → {f['substitute']}"
if f['link']:
sub_text += f" ([try here]({f['link']}))"
st.markdown(f"- {sub_text}")
# Generate recipe from HF
with st.spinner("Cooking up ideas..."):
prompt = build_prompt(ingredients, avoid, servings, recipes_count)
try:
output = hf_generate_chat(prompt)
except Exception as e:
st.error(f"Generation error: {e}")
else:
st.markdown(output)
st.caption(f"Model: {MODEL_REPO}")
# Show general product recommendations
recs = get_product_recommendations(ingredients, region)
if recs:
st.subheader("🛒 Recommended Gluten-Free Products")
for product, link in recs:
st.markdown(f"- [{product.title()}]({link})")
st.caption("⚠️ Set your Hugging Face API key as an environment variable: HF_TOKEN=...")