adigabay2003 commited on
Commit
015cb5f
ยท
verified ยท
1 Parent(s): d310093

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +111 -51
app.py CHANGED
@@ -1,64 +1,105 @@
 
 
1
 
2
  import gradio as gr
3
  import pandas as pd
4
  import numpy as np
5
  import os
6
- import random
7
- from sklearn.feature_extraction.text import TfidfVectorizer
8
- from sklearn.pipeline import Pipeline
9
  from sklearn.linear_model import LogisticRegression
 
10
  from huggingface_hub import InferenceClient
11
 
12
- # --- LIBRARIES & LOGIC ---
13
- print("๐Ÿš€ Generating Synthetic Data...")
14
- proteins = ["Chicken", "Beef", "Tofu", "Salmon", "Shrimp", "Chickpeas", "Lentils", "Turkey", "Duck", "Egg"]
15
- carbs = ["Rice", "Pasta", "Quinoa", "Potatoes", "Bread", "Noodles", "Tortilla", "Bun", "Couscous"]
16
- veggies = ["Broccoli", "Spinach", "Carrots", "Tomatoes", "Mushrooms", "Onions", "Peppers", "Kale", "Avocado", "Corn"]
17
- sauces = ["Tomato Sauce", "Cream", "Soy Sauce", "Pesto", "BBQ Sauce", "Tahini", "Olive Oil", "Balsamic", "Curry", "Mayo"]
18
- spices = ["Garlic", "Basil", "Chili", "Curry Powder", "Cumin", "Oregano", "Ginger", "Thyme", "Paprika"]
19
- adjectives = ["Spicy", "Creamy", "Roasted", "Grilled", "Fresh", "Zesty", "Hearty", "Crispy", "Savory", "Sweet"]
20
-
21
- def generate_recipe():
22
- p = random.choice(proteins); c = random.choice(carbs); v1 = random.choice(veggies); s = random.choice(sauces); sp = random.choice(spices); adj = random.choice(adjectives)
23
- title = f"{adj} {p} with {c}"
24
- ingredients = f"{p}, {c}, {v1}, {s}, {sp}"
25
- vibe = "Quick Lunch"
26
- if "Salmon" in p or "Shrimp" in p or "Duck" in p: vibe = "Fancy Dinner"
27
- elif "Chocolate" in ingredients or "Risotto" in title: vibe = "Romantic"
28
- elif "Tofu" in p or "Kale" in v1 or "Quinoa" in c: vibe = "Healthy Boost"
29
- elif "Tortilla" in c or "BBQ" in s or "Crispy" in title: vibe = "Party Snack"
30
- elif "Potatoes" in c or "Cream" in s or "Pasta" in c: vibe = "Comfort Food"
31
- return {"title": title, "ingredients": ingredients, "Vibe_AI": vibe}
32
-
33
- data = [generate_recipe() for _ in range(5000)]
34
- df = pd.DataFrame(data)
35
- X = df['ingredients']; y = df['Vibe_AI']
36
- pipeline = Pipeline([('tfidf', TfidfVectorizer(stop_words='english')),('clf', LogisticRegression(max_iter=1000))])
37
- pipeline.fit(X, y)
38
-
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  def get_recipe_vibe(title, ingredients):
40
- full_text = f"{title} {ingredients}"
41
- return pipeline.predict([full_text])[0]
42
-
 
 
 
 
 
43
  def generate_food_image(title, vibe):
44
  token = os.getenv("HF_TOKEN")
45
- if not token: return None
46
- client = InferenceClient(model="stabilityai/stable-diffusion-xl-base-1.0", token=token)
47
- prompt = f"Professional food photography of {title}, {vibe} style, 4k, highly detailed, appetizing, dramatic lighting, vibrant colors"
48
- try: return client.text_to_image(prompt)
49
- except: return None
50
-
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  def smart_chef_app(title, ingredients):
52
  vibe = get_recipe_vibe(title, ingredients)
53
- messages = {"Romantic": "๐ŸŒน Love is in the air!", "Quick Lunch": "โšก Fast & Delicious!", "Comfort Food": "๐Ÿงธ Warm & Cozy.", "Party Snack": "๐ŸŽ‰ Party Time!", "Healthy Boost": "๐Ÿฅ— Feel Good Food.", "Fancy Dinner": "๐Ÿท Chef's Kiss!"}
 
 
 
 
 
 
 
54
  msg = messages.get(vibe, "Yum!")
55
  img = generate_food_image(title, vibe)
56
  return vibe, msg, img
57
 
58
- # --- THE NEW ULTRA-PREMIUM UI CSS ---
 
 
59
  ultra_css = """
60
  @import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@300;500;800&display=swap');
61
-
62
  .gradio-container {
63
  background: linear-gradient(-45deg, #0f0c29, #302b63, #24243e, #4a1c1c);
64
  background-size: 400% 400%;
@@ -126,6 +167,9 @@ theme = gr.themes.Soft(primary_hue="orange", neutral_hue="slate").set(
126
  block_border_width="0px"
127
  )
128
 
 
 
 
129
  with gr.Blocks(css=ultra_css, theme=theme) as demo:
130
  gr.Markdown("# โœจ SMARTCHEF AI โœจ")
131
  gr.Markdown("### Experience the future of culinary magic.")
@@ -133,23 +177,39 @@ with gr.Blocks(css=ultra_css, theme=theme) as demo:
133
  with gr.Row():
134
  with gr.Column(elem_classes="group-container"):
135
  gr.Markdown("#### ๐Ÿ“ CREATE YOUR DISH")
136
- t_in = gr.Textbox(label="Dish Name", placeholder="e.g., Mystical Truffle Risotto")
137
- i_in = gr.Textbox(label="Ingredients", placeholder="e.g., Arborio rice, black truffle dust, parmesan magic...", lines=4)
 
 
 
 
 
 
 
138
  btn = gr.Button("โœจ UNLEASH MAGIC โœจ", elem_classes="primary-btn")
139
 
140
  with gr.Column(elem_classes="group-container"):
141
  gr.Markdown("#### ๐Ÿ”ฎ THE REVELATION")
142
- v_out = gr.Textbox(label="Vibe Detected", interactive=False, show_label=True)
 
 
 
143
  m_out = gr.Markdown()
144
- # ืชื™ืงื•ืŸ: ื”ื•ืจื“ื ื• ืืช show_download_button ืฉื’ืจื ืœืฉื’ื™ืื”
145
- im_out = gr.Image(label="AI Visualization", type="pil", interactive=False)
 
 
 
146
 
147
  gr.Markdown("### โšก Instant Inspirations (Click to try):")
148
  gr.Examples(
149
  examples=[
150
- ["Midnight Burger", "Black bun, wagyu beef, spicy aioli, caramelized onions"],
151
- ["Neon Sushi Roll", "Tuna, salmon, avocado, glowing tobiko, eel sauce"],
152
- ["Enchanted Forest Salad", "Kale, edible flowers, berries, nuts, fairy dust dressing"]
 
 
 
153
  ],
154
  inputs=[t_in, i_in],
155
  elem_id="examples-table"
@@ -158,4 +218,4 @@ with gr.Blocks(css=ultra_css, theme=theme) as demo:
158
  btn.click(smart_chef_app, [t_in, i_in], [v_out, m_out, im_out])
159
 
160
  if __name__ == "__main__":
161
- demo.launch()
 
1
+ import warnings
2
+ warnings.filterwarnings("ignore")
3
 
4
  import gradio as gr
5
  import pandas as pd
6
  import numpy as np
7
  import os
8
+ import json
9
+ from sentence_transformers import SentenceTransformer
 
10
  from sklearn.linear_model import LogisticRegression
11
+ from datasets import load_dataset
12
  from huggingface_hub import InferenceClient
13
 
14
+ # ============================================
15
+ # 1. Load Dataset from HuggingFace
16
+ # ============================================
17
+ print("Loading dataset from HuggingFace...")
18
+ ds = load_dataset("adigabay2003/smartchef-recipes", split="train")
19
+ df = ds.to_pandas()
20
+ df = df.dropna(subset=["text"])
21
+ df = df[df["text"].str.strip() != ""]
22
+ df = df.reset_index(drop=True)
23
+ print(f"Loaded {len(df)} recipes")
24
+
25
+ # ============================================
26
+ # 2. Load Optimal Model from JSON
27
+ # ============================================
28
+ with open("optimal_model.json", "r") as f:
29
+ optimal = json.load(f)
30
+
31
+ MODEL_NAME = optimal["model_name"]
32
+ print(f"Using embedding model: {MODEL_NAME}")
33
+
34
+ # ============================================
35
+ # 3. Load Precomputed Embeddings
36
+ # ============================================
37
+ print("Loading precomputed embeddings...")
38
+ X = np.load("best_embeddings.npy")
39
+ y = df["vibe"].tolist()
40
+ print(f"Embeddings shape: {X.shape}")
41
+
42
+ # ============================================
43
+ # 4. Train Classifier on Embeddings
44
+ # ============================================
45
+ print("Training classifier...")
46
+ embedder = SentenceTransformer(MODEL_NAME)
47
+ clf = LogisticRegression(max_iter=1000)
48
+ clf.fit(X, y)
49
+ print("Classifier ready!")
50
+
51
+ # ============================================
52
+ # 5. Prediction Function
53
+ # ============================================
54
  def get_recipe_vibe(title, ingredients):
55
+ text = f"{title}. Ingredients: {ingredients}"
56
+ embedding = embedder.encode([text])
57
+ vibe = clf.predict(embedding)[0]
58
+ return vibe
59
+
60
+ # ============================================
61
+ # 6. Image Generation
62
+ # ============================================
63
  def generate_food_image(title, vibe):
64
  token = os.getenv("HF_TOKEN")
65
+ if not token:
66
+ return None
67
+ client = InferenceClient(
68
+ model="stabilityai/stable-diffusion-xl-base-1.0",
69
+ token=token
70
+ )
71
+ prompt = (
72
+ f"Professional food photography of {title}, "
73
+ f"{vibe} style, 4k, highly detailed, "
74
+ f"appetizing, dramatic lighting, vibrant colors"
75
+ )
76
+ try:
77
+ return client.text_to_image(prompt)
78
+ except:
79
+ return None
80
+
81
+ # ============================================
82
+ # 7. Main App Function
83
+ # ============================================
84
  def smart_chef_app(title, ingredients):
85
  vibe = get_recipe_vibe(title, ingredients)
86
+ messages = {
87
+ "Romantic": "๐ŸŒน Love is in the air!",
88
+ "Quick Lunch": "โšก Fast & Delicious!",
89
+ "Comfort Food": "๐Ÿงธ Warm & Cozy.",
90
+ "Party Snack": "๐ŸŽ‰ Party Time!",
91
+ "Healthy Boost":"๐Ÿฅ— Feel Good Food.",
92
+ "Fancy Dinner": "๐Ÿท Chef's Kiss!"
93
+ }
94
  msg = messages.get(vibe, "Yum!")
95
  img = generate_food_image(title, vibe)
96
  return vibe, msg, img
97
 
98
+ # ============================================
99
+ # 8. CSS & Theme
100
+ # ============================================
101
  ultra_css = """
102
  @import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@300;500;800&display=swap');
 
103
  .gradio-container {
104
  background: linear-gradient(-45deg, #0f0c29, #302b63, #24243e, #4a1c1c);
105
  background-size: 400% 400%;
 
167
  block_border_width="0px"
168
  )
169
 
170
+ # ============================================
171
+ # 9. Gradio UI
172
+ # ============================================
173
  with gr.Blocks(css=ultra_css, theme=theme) as demo:
174
  gr.Markdown("# โœจ SMARTCHEF AI โœจ")
175
  gr.Markdown("### Experience the future of culinary magic.")
 
177
  with gr.Row():
178
  with gr.Column(elem_classes="group-container"):
179
  gr.Markdown("#### ๐Ÿ“ CREATE YOUR DISH")
180
+ t_in = gr.Textbox(
181
+ label="Dish Name",
182
+ placeholder="e.g., Mystical Truffle Risotto"
183
+ )
184
+ i_in = gr.Textbox(
185
+ label="Ingredients",
186
+ placeholder="e.g., Arborio rice, black truffle dust, parmesan...",
187
+ lines=4
188
+ )
189
  btn = gr.Button("โœจ UNLEASH MAGIC โœจ", elem_classes="primary-btn")
190
 
191
  with gr.Column(elem_classes="group-container"):
192
  gr.Markdown("#### ๐Ÿ”ฎ THE REVELATION")
193
+ v_out = gr.Textbox(
194
+ label="Vibe Detected",
195
+ interactive=False
196
+ )
197
  m_out = gr.Markdown()
198
+ im_out = gr.Image(
199
+ label="AI Visualization",
200
+ type="pil",
201
+ interactive=False
202
+ )
203
 
204
  gr.Markdown("### โšก Instant Inspirations (Click to try):")
205
  gr.Examples(
206
  examples=[
207
+ ["Midnight Burger",
208
+ "Black bun, wagyu beef, spicy aioli, caramelized onions"],
209
+ ["Neon Sushi Roll",
210
+ "Tuna, salmon, avocado, glowing tobiko, eel sauce"],
211
+ ["Enchanted Forest Salad",
212
+ "Kale, edible flowers, berries, nuts, fairy dust dressing"]
213
  ],
214
  inputs=[t_in, i_in],
215
  elem_id="examples-table"
 
218
  btn.click(smart_chef_app, [t_in, i_in], [v_out, m_out, im_out])
219
 
220
  if __name__ == "__main__":
221
+ demo.launch()