-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
717 lines (594 loc) · 25.5 KB
/
app.py
File metadata and controls
717 lines (594 loc) · 25.5 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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
import streamlit as st
import os
import re
import json
import pandas as pd
from google import genai
from google.genai.errors import APIError
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
# Load environment variables (for local development)
try:
from dotenv import load_dotenv
load_dotenv()
except ImportError:
pass # dotenv not available in deployment
# --- PAGE CONFIG (Must be first Streamlit command) ---
st.set_page_config(
layout="wide",
page_title="The Recipe Analyst",
page_icon="🍳",
initial_sidebar_state="collapsed"
)
# --- CUSTOM CSS FOR MODERN DESIGN ---
st.markdown("""
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
/* Main app styling */
.main {
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}
/* Header styling */
.main-header {
text-align: center;
padding: 1rem 0;
margin-bottom: 1rem;
}
.main-header h1 {
color: #2c3e50;
font-size: 3rem;
margin: 0;
font-weight: bold;
}
.main-header p {
color: #5a6c7d;
font-size: 1.2rem;
margin-top: 0.5rem;
}
/* Card styling */
.recipe-card {
background: transparent;
border-radius: 0;
padding: 1rem;
box-shadow: none;
margin-bottom: 0.5rem;
margin-top: 0;
transition: none;
border: none;
}
/* Remove extra spacing from columns */
.stColumn {
padding-top: 0 !important;
margin-top: 0 !important;
}
.recipe-card:hover {
transform: translateY(-5px);
box-shadow: 0 12px 30px rgba(0,0,0,0.15);
}
/* Input section */
.input-section {
background: transparent;
padding: 1rem 0;
border-radius: 0;
box-shadow: none;
margin-bottom: 1rem;
}
/* Button styling */
.stButton > button {
background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%) !important;
color: white !important;
border: none !important;
border-radius: 8px !important;
padding: 0.75rem 2rem !important;
font-weight: 600 !important;
font-size: 1rem !important;
transition: all 0.3s ease !important;
box-shadow: 0 4px 15px rgba(231, 76, 60, 0.3) !important;
}
.stButton > button:hover {
background: linear-gradient(135deg, #c0392b 0%, #a93226 100%) !important;
transform: translateY(-2px) !important;
box-shadow: 0 6px 20px rgba(231, 76, 60, 0.4) !important;
}
/* Stats cards */
.stat-card {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 1.5rem;
border-radius: 12px;
text-align: center;
box-shadow: 0 5px 15px rgba(102, 126, 234, 0.3);
}
.stat-value {
font-size: 2.5rem;
font-weight: bold;
margin: 0.5rem 0;
}
.stat-label {
font-size: 0.9rem;
opacity: 0.9;
text-transform: uppercase;
letter-spacing: 1px;
}
/* Section headers */
.section-header {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 1.8rem;
font-weight: 600;
color: #2c3e50;
margin: 2rem 0 1rem 0;
padding-bottom: 0.5rem;
border-bottom: none;
}
/* Disclaimer box */
.disclaimer-box {
background: #fff3cd;
border-left: 4px solid #ffc107;
padding: 1rem;
border-radius: 8px;
margin: 1rem 0;
}
/* Button customization */
.stButton > button {
width: 100%;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
padding: 0.8rem 2rem;
font-size: 1.1rem;
font-weight: 600;
border-radius: 10px;
transition: all 0.3s ease;
}
.stButton > button:hover {
transform: translateY(-2px);
box-shadow: 0 5px 20px rgba(102, 126, 234, 0.4);
}
/* Dataframe styling */
.dataframe {
border-radius: 10px;
overflow: hidden;
}
/* Goal optimization section */
.goal-section {
background: white;
padding: 2rem;
border-radius: 15px;
border: 1px solid #e0e0e0;
margin-top: 2rem;
}
/* Comparison section */
.comparison-section {
background: white;
padding: 2rem;
border-radius: 15px;
box-shadow: 0 8px 20px rgba(0,0,0,0.08);
margin: 2rem 0;
}
</style>
""", unsafe_allow_html=True)
# --- GEMINI CLIENT INITIALIZATION ---
# Get API key from environment variables or Streamlit secrets
api_key = os.getenv('GEMINI_API_KEY')
# Try to get from Streamlit secrets if not found in environment
if not api_key:
try:
api_key = st.secrets['GEMINI_API_KEY']
except (KeyError, FileNotFoundError):
pass # No secrets file or key found
if not api_key:
st.error("🔑 **API Key Missing!** Please set your GEMINI_API_KEY in:")
st.markdown("""
- **Local development:** Add `GEMINI_API_KEY=your_key_here` to your `.env` file
- **Streamlit Cloud:** Add it to your app's secrets in the dashboard
- **Get your API key:** [Google AI Studio](https://makersuite.google.com/app/apikey)
""")
st.stop()
try:
client = genai.Client(api_key=api_key)
except Exception as e:
st.error(f"❌ Error initializing Gemini client: {e}")
st.stop()
# --- PROMPT DEFINITION ---
def create_master_prompt(ingredients_list):
prompt = f"""
You are a highly analytical chef and recipe generator. Your task is to generate three distinct and creative recipes.
***CRITICAL INGREDIENT FILTERING TASK***:
The user has provided the following natural language text: "{ingredients_list}".
You must intelligently parse this text and **EXTRACT ALL CORE INGREDIENT ITEMS AND THEIR QUANTITIES** (e.g., Chicken, Potato, Egg). **CRITICAL NOTE:** These quantities are merely the available stock, NOT a limit for the *total recipe*, **BUT YOU MUST NOT EXCEED THE SPECIFIC QUANTITY GIVEN FOR ANY SINGLE INGREDIENT** (e.g., if the user listed '50g broccoli', you must use 50g or less). Each recipe should assume it uses the necessary standard portion sizes required for a complete meal (e.g., 300g chicken per recipe is fine).
For each of the three recipes, you must assume **DIFFERENT STANDARD PORTION SIZES** to ensure variety (e.g., Recipe 1 uses a large chicken portion, Recipe 2 uses a small chicken portion). IT IS **ABSOLUTELY REQUIRED** that the final "calories_kcal" value **MUST BE UNIQUE** for Recipe 1, Recipe 2, and Recipe 3.
Generate recipes using ONLY the identified ingredients. **CRITICAL RULE:** Each of the three generated recipes MUST utilize ALL core ingredients identified from the user's input (Chicken, Broccoli, Potato, Egg, etc.) in some capacity, even if the usage is minimal.
For each of the three recipes, you must provide:
1. **Title:** A creative, theme-based name.
2. **Recipe Steps:** Clear, concise instructions using bullet points.
3. **Analysis Report (JSON format):** A strictly formatted JSON object containing nutritional data. The calorie, carbo, protein, and fat values must be numerical **estimates** based on standard food data and are intended for **relative comparison** between the three generated recipes.
---
Ensure the final output is a single text block structured exactly as follows. Do not include any introductory or concluding text outside of this structure.
---
### Recipe 1: [Creative Title]
- [Step 1]
- [Step 2]
```json
{{
"recipe_name": "[Creative Title]",
"recipe_id": 1,
"calories_kcal": [NUMBER],
"carbohydrates_g": [NUMBER],
"protein_g": [NUMBER],
"fat_g": [NUMBER],
"assumed_quantities": "[e.g., Used 300g Chicken, 1 Tomato, small pinch of Chilli]",
"vitamin_highlight": "[E.g., High in Vitamin C, Good source of Iron]"
}}
```
---RECIPE-END---
### Recipe 2: [Creative Title]
- [Step 1]
- [Step 2]
```json
{{
"recipe_name": "[Creative Title]",
"recipe_id": 2,
"calories_kcal": [NUMBER],
"carbohydrates_g": [NUMBER],
"protein_g": [NUMBER],
"fat_g": [NUMBER],
"assumed_quantities": "[e.g., Used 200g Chicken, 2 Tomatoes, 1/2 of available Chilli]",
"vitamin_highlight": "[E.g., High in Vitamin C, Good source of Iron]"
}}
```
---RECIPE-END---
### Recipe 3: [Creative Title]
- [Step 1]
- [Step 2]
```json
{{
"recipe_name": "[Creative Title]",
"recipe_id": 3,
"calories_kcal": [NUMBER],
"carbohydrates_g": [NUMBER],
"protein_g": [NUMBER],
"fat_g": [NUMBER],
"assumed_quantities": "[e.g., Used 100g Chicken, all Broccoli, no Chilli]",
"vitamin_highlight": "[E.g., High in Vitamin C, Good source of Iron]"
}}
```
"""
return prompt
# --- EXTRACTION LOGIC ---
def extract_recipe_data(response_text):
"""Splits the response into recipes and extracts the JSON data."""
recipe_blocks = response_text.split("---RECIPE-END---")
parsed_recipes = []
for block in recipe_blocks:
if not block.strip():
continue
json_match = re.search(r'```json\s*(\{[\s\S]*?\})\s*```', block)
recipe_text = re.sub(r'```json[\s\S]*?```', '', block, flags=re.DOTALL).strip()
nutrition_data = {}
if json_match:
try:
nutrition_data = json.loads(json_match.group(1))
except json.JSONDecodeError as e:
st.warning(f"Could not parse JSON for a recipe. Error: {e}")
continue
if nutrition_data:
parsed_recipes.append({
'text': recipe_text,
'analysis': nutrition_data
})
return parsed_recipes
def generate_and_parse(ingredients_list):
"""Calls the Gemini API and returns the parsed data."""
prompt = create_master_prompt(ingredients_list)
try:
response = client.models.generate_content(
model='gemini-2.5-flash',
contents=prompt
)
return extract_recipe_data(response.text)
except APIError as e:
st.error(f"Gemini API call failed. Status: {e}. Check your API Key and network connection.")
return []
except Exception as e:
st.error(f"An unexpected error occurred: {e}")
return []
# --- OPTIMIZATION PROMPT & API CALL ---
def create_optimization_prompt(original_recipe_text, opt_metric, opt_reason):
"""Generates the constrained prompt for recipe optimization."""
optimization_prompt = f"""
You are tasked with optimizing a recipe.
Your task is to take the following recipe and rewrite it to {opt_metric} by adjusting **{opt_reason}**.
***CRITICAL PRECISION TASK (MUST BE FOLLOWED)***:
1. First, analyze the user's goal (contained in opt_metric) and the Original Recipe to determine the **required nutritional gap** (e.g., "Need to remove 150 kcal" or "Need to add 20g protein").
2. Rewrite the recipe's ingredients and steps, making **quantifiable modifications** (e.g., changing '100g chicken' to '50g chicken' or 'pan-fry' to 'poach').
3. The **Analysis Report** of the resulting Optimized Recipe **MUST** reflect the achieved target value as closely as possible, using the revised portion sizes calculated in Step 2.
Original Recipe Text:
---
{original_recipe_text}
---
Generate the new, optimized recipe using the exact same required JSON format. The Title should clearly indicate it is the 'Optimized' version.
The final output must strictly adhere to the following structure:
### Optimized Recipe: [New Creative Title]
- [Step 1]
- [Step 2]
**ANALYSIS REPORT:**
```json
{{
"recipe_name": "[Optimized Title]",
"recipe_id": 4,
"calories_kcal": [NUMBER, rounded to the nearest integer],
"carbohydrates_g": [NUMBER, rounded to one decimal place],
"protein_g": [NUMBER, rounded to one decimal place],
"fat_g": [NUMBER, rounded to one decimal place],
"assumed_quantities": "[List precise quantities used for this calculation]",
"vitamin_highlight": "[Highlight]"
}}
```
"""
return optimization_prompt
def generate_optimized_recipe(original_recipe_text, opt_metric, opt_reason):
"""Calls the Gemini API for optimization."""
optimization_prompt = create_optimization_prompt(original_recipe_text, opt_metric, opt_reason)
try:
response = client.models.generate_content(
model='gemini-2.5-flash',
contents=optimization_prompt
)
json_match = re.search(r'```json\s*(\{[\s\S]*?\})\s*```', response.text)
if not json_match:
st.error("Optimization failed: Could not find structured JSON output.")
return None
recipe_text = re.sub(r'```json[\s\S]*?```', '', response.text, flags=re.DOTALL).strip()
json_string = json_match.group(1)
return {'text': recipe_text, 'analysis': json.loads(json_string)}
except Exception as e:
st.error(f"Optimization failed: {e}")
return None
def analyze_and_target_recipe(recipes, goal_text):
"""Uses Gemini to identify the best starting recipe for the custom goal."""
recipe_summary = "\n".join([
f"Recipe {i+1}: Title={r['analysis'].get('recipe_name')}, Calories={r['analysis'].get('calories_kcal')}, Protein={r['analysis'].get('protein_g')}"
for i, r in enumerate(recipes)
])
target_prompt = f"""
Analyze the user's goal: '{goal_text}'.
Analyze the nutritional data below:
---
{recipe_summary}
---
Based on the goal, identify the single best recipe (Recipe 1, 2, or 3) to *start* the modification from.
* If the goal is a maximum (e.g., Max 400 kcal), choose the recipe closest to the target.
* If the goal is a minimum (e.g., Min 70g Protein), choose the recipe that has the highest current value to minimize changes.
Your final output must be a single, strict JSON object with your determination.
{{
"target_recipe_index": [The number 1, 2, or 3],
"target_recipe_name": "[The title of the chosen recipe]",
"justification": "[A brief reason for choosing this recipe]"
}}
"""
try:
response = client.models.generate_content(
model='gemini-2.5-flash',
contents=target_prompt
)
json_string = response.text.strip().replace('```json', '').replace('```', '')
return json.loads(json_string)
except Exception as e:
st.error(f"AI Goal Targeting Failed: {e}")
return None
# --- DISPLAY HELPERS ---
def display_recipe(container, recipe_data, recipe_number=None):
"""Displays a single recipe and its analysis report in a given Streamlit container."""
# Check if container is the st module itself
is_st_module = hasattr(container, '__name__') and container.__name__ == 'streamlit'
if is_st_module:
# Direct usage without context manager
st.markdown('<div class="recipe-card">', unsafe_allow_html=True)
if recipe_number:
st.markdown(f"### <i class='fas fa-utensils'></i> Recipe {recipe_number}", unsafe_allow_html=True)
st.markdown(recipe_data['text'], unsafe_allow_html=True)
analysis = recipe_data['analysis']
# Complete nutritional analysis table
st.markdown("#### <i class='fas fa-chart-bar'></i> Nutritional Analysis", unsafe_allow_html=True)
nutrition_df = pd.DataFrame({
'Nutritional Metric': [
'🔥 Calories (kcal)',
'🍞 Carbohydrates (g)',
'🥩 Protein (g)',
'🥑 Fat (g)',
'📏 Quantities Assumed',
'💊 Vitamin Highlights'
],
'Value': [
str(analysis.get('calories_kcal', 'N/A')),
str(analysis.get('carbohydrates_g', 'N/A')),
str(analysis.get('protein_g', 'N/A')),
str(analysis.get('fat_g', 'N/A')),
str(analysis.get('assumed_quantities', 'N/A')),
str(analysis.get('vitamin_highlight', 'N/A'))
]
})
st.dataframe(nutrition_df, hide_index=True, width='stretch')
st.markdown('</div>', unsafe_allow_html=True)
else:
# Column container usage
with container:
st.markdown('<div class="recipe-card">', unsafe_allow_html=True)
if recipe_number:
st.markdown(f"### <i class='fas fa-utensils'></i> Recipe {recipe_number}", unsafe_allow_html=True)
st.markdown(recipe_data['text'], unsafe_allow_html=True)
analysis = recipe_data['analysis']
# Complete nutritional analysis table
st.markdown("#### <i class='fas fa-chart-bar'></i> Nutritional Analysis", unsafe_allow_html=True)
nutrition_df = pd.DataFrame({
'Nutritional Metric': [
'🔥 Calories (kcal)',
'🍞 Carbohydrates (g)',
'🥩 Protein (g)',
'🥑 Fat (g)',
'📏 Quantities Assumed',
'💊 Vitamin Highlights'
],
'Value': [
str(analysis.get('calories_kcal', 'N/A')),
str(analysis.get('carbohydrates_g', 'N/A')),
str(analysis.get('protein_g', 'N/A')),
str(analysis.get('fat_g', 'N/A')),
str(analysis.get('assumed_quantities', 'N/A')),
str(analysis.get('vitamin_highlight', 'N/A'))
]
})
st.dataframe(nutrition_df, hide_index=True, width='stretch')
st.markdown('</div>', unsafe_allow_html=True)
# --- STREAMLIT APP LAYOUT ---
# Custom Header
st.markdown("""
<div class="main-header">
<h1><i class="fas fa-utensils"></i> The Recipe Analyst</h1>
<p>Transform your ingredients into culinary masterpieces with AI-powered nutritional insights</p>
</div>
""", unsafe_allow_html=True)
# Input Section
st.markdown("### <i class='fas fa-carrot'></i> What's in Your Kitchen?", unsafe_allow_html=True)
ingredients = st.text_area(
"Enter your ingredients",
placeholder="e.g., I have 1/2 kg chicken, 50g broccoli, 3 tomatoes and chili powder",
height=120,
label_visibility="collapsed"
)
if st.button("⚡ Generate Recipes & Analysis", type="primary"):
if not ingredients:
st.warning("Please enter some ingredients first!")
else:
with st.spinner("🔮 Analyzing ingredients and crafting three unique recipes..."):
all_recipes = generate_and_parse(ingredients)
if all_recipes and len(all_recipes) == 3:
st.session_state['recipes'] = all_recipes
st.success("✅ Analysis complete! 3 recipes generated with full nutritional breakdowns.")
st.rerun()
elif all_recipes and len(all_recipes) < 3:
st.warning(f"Generated only {len(all_recipes)} recipes. Try adjusting your ingredients.")
st.session_state['recipes'] = all_recipes
else:
pass
# Results Display
if 'recipes' in st.session_state and st.session_state['recipes']:
recipes = st.session_state['recipes']
st.markdown("## <i class='fas fa-book-open'></i> Your Personalized Recipe Collection", unsafe_allow_html=True)
# Display recipes in columns (remove any extra spacing)
recipe_cols = st.columns(len(recipes))
for idx, recipe in enumerate(recipes):
display_recipe(recipe_cols[idx], recipe, idx + 1)
# Common disclaimer for all recipes
st.markdown("---")
st.markdown("<i class='fas fa-exclamation-triangle'></i> **Disclaimer:** Nutritional values are AI-generated estimates for comparative planning only.", unsafe_allow_html=True)
# Comparison Section
st.markdown('<div class="comparison-section">', unsafe_allow_html=True)
st.markdown('<div class="section-header"><i class="fas fa-chart-line"></i> Nutritional Comparison</div>', unsafe_allow_html=True)
calories = []
for i, recipe in enumerate(recipes):
cal_val = recipe['analysis'].get('calories_kcal')
if isinstance(cal_val, str) and cal_val.strip().upper() == '[NUMBER]':
cal = 0
elif isinstance(cal_val, (int, float)):
cal = cal_val
else:
try:
cal = int(cal_val)
except (ValueError, TypeError):
cal = 0
calories.append((cal, i + 1))
if calories:
highest_cal = max(calories, key=lambda item: item[0])
highest_cal_value = highest_cal[0]
highest_cal_index = highest_cal[1]
# Stats cards
stat_cols = st.columns(3)
with stat_cols[0]:
st.markdown(f"""
<div class="stat-card">
<div class="stat-label">Highest Calorie Recipe</div>
<div class="stat-value">Recipe {highest_cal_index}</div>
</div>
""", unsafe_allow_html=True)
with stat_cols[1]:
st.markdown(f"""
<div class="stat-card">
<div class="stat-label">Calorie Count</div>
<div class="stat-value">{highest_cal_value:,.0f}</div>
</div>
""", unsafe_allow_html=True)
valid_calories = sorted([c[0] for c in calories if c[0] > 0], reverse=True)
if len(valid_calories) > 1:
second_highest_value = valid_calories[1]
calorie_difference = highest_cal_value - second_highest_value
with stat_cols[2]:
st.markdown(f"""
<div class="stat-card">
<div class="stat-label">More Than Next</div>
<div class="stat-value">+{calorie_difference:,.0f}</div>
</div>
""", unsafe_allow_html=True)
st.markdown("<br>", unsafe_allow_html=True)
# Bar Chart
chart_data = pd.DataFrame(
{'Recipe': [f'Recipe {c[1]}' for c in calories],
'Calories (kcal)': [c[0] for c in calories]},
)
st.bar_chart(chart_data.set_index('Recipe'), height=350, width='stretch')
st.markdown('</div>', unsafe_allow_html=True)
# Custom Goal Optimization Section
st.markdown("---")
st.markdown("### <i class='fas fa-bullseye'></i> Custom Goal Optimization", unsafe_allow_html=True)
st.markdown("Transform a recipe to meet your specific nutritional targets")
custom_goal = st.text_input(
"Enter your nutritional goal",
placeholder="e.g., Max 400 kcal or Min 70g Protein",
key='custom_goal_input',
label_visibility="collapsed"
)
if st.button("🎯 Find & Optimize for Goal", key="btn_custom_optimize", type="primary"):
if custom_goal and 'recipes' in st.session_state:
st.session_state['optimization_goal'] = 'CUSTOM_GOAL'
st.session_state['custom_goal_text'] = custom_goal
st.rerun()
elif 'recipes' not in st.session_state:
st.warning("⚠️ Please generate the initial recipes first.")
else:
st.warning("⚠️ Please enter a goal.")
# Custom Optimization Logic
if 'optimization_goal' in st.session_state and st.session_state.get('optimization_goal') == 'CUSTOM_GOAL':
recipes = st.session_state['recipes']
goal_text = st.session_state['custom_goal_text']
with st.spinner(f"🔍 Analyzing recipes for goal: {goal_text}..."):
target_info = analyze_and_target_recipe(recipes, goal_text)
if target_info and target_info.get('target_recipe_index'):
target_index = int(target_info['target_recipe_index'])
original_recipe_text = recipes[target_index - 1]['text']
st.info(f"🤖 AI Selected: Recipe {target_index} ({target_info['target_recipe_name']}) - {target_info['justification']}")
with st.spinner("⚙️ Optimizing recipe..."):
opt_metric = f"achieve the user's goal of: {goal_text}"
optimized_recipe = generate_optimized_recipe(original_recipe_text, opt_metric, "modifying ingredients and cooking methods/portion sizes")
if optimized_recipe:
st.session_state['optimized_recipe'] = optimized_recipe
st.session_state['optimized_original_index'] = target_index
st.session_state['custom_goal_achieved'] = goal_text
del st.session_state['optimization_goal']
st.rerun()
else:
st.error("❌ Could not determine the best recipe to modify.")
# Optimized Recipe Display
if 'optimized_recipe' in st.session_state and 'custom_goal_achieved' in st.session_state:
optimized_data = st.session_state['optimized_recipe']
original_index = st.session_state['optimized_original_index']
goal_text = st.session_state['custom_goal_achieved']
st.markdown('<div class="section-header"><i class="fas fa-check-circle"></i> Goal Achieved: Optimized Recipe</div>', unsafe_allow_html=True)
st.success(f"Recipe optimized to meet your goal: **{goal_text}** (Based on Recipe {original_index})")
display_recipe(st, optimized_data)
# Clean up state
del st.session_state['custom_goal_achieved']
del st.session_state['optimized_recipe']
del st.session_state['optimized_original_index']