Liori25 commited on
Commit
9a1f40d
Β·
verified Β·
1 Parent(s): 6ff0916

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -101
app.py CHANGED
@@ -47,27 +47,37 @@ logo_b64 = image_to_base64("logo.jpg")
47
  profile_b64 = image_to_base64("232px-Tv_the_muppet_show_bein_green.jpg")
48
 
49
  # ==========================================
50
- # 3. BACKEND LOGIC
51
  # ==========================================
52
  def get_embedding_via_api(text):
53
  if not client: raise ValueError("HF_TOKEN missing")
54
  response = client.feature_extraction(text, model=API_MODEL)
55
  return np.array(response)
56
 
57
- def find_similar_recipes(query_text):
58
- if stored_embeddings is None: return "Database error."
 
59
  query_vec = get_embedding_via_api("Represent this recipe for retrieving similar dishes: " + query_text)
60
  if len(query_vec.shape) == 1: query_vec = query_vec.reshape(1, -1)
61
 
62
  scores = cosine_similarity(query_vec, stored_embeddings)[0]
63
  top_indices = scores.argsort()[-3:][::-1]
64
 
65
- results = ""
66
  for idx in top_indices:
67
  row = df_recipes.iloc[idx]
68
- desc = str(row['Raw_Output'])[:150] + "..."
69
- results += f"πŸ† Match: {row['Title']}\nπŸ“ {desc}\n\n"
70
- return results
 
 
 
 
 
 
 
 
 
71
 
72
  def format_recipe(json_data):
73
  if "error" in json_data: return f"Error: {json_data['error']}", ""
@@ -77,17 +87,24 @@ def format_recipe(json_data):
77
  text = f"🍽️ {title}\n\nπŸ›’ INGREDIENTS:\n{ing}\n\n🍳 INSTRUCTIONS:\n{inst}"
78
  return text, f"{title} {ing} {inst}"
79
 
 
80
  def magic_pipeline(image_path):
81
- if not hf_token: return "Error: HF_TOKEN missing", ""
82
  try:
83
  os.environ["HF_TOKEN"] = hf_token
84
  digitizer = RecipeDigitalizerPipeline()
85
  json_res = digitizer.run_pipeline(image_path)
86
  readable, query = format_recipe(json_res)
87
- similar = find_similar_recipes(query) if query else "No search query."
88
- return readable, similar
 
 
 
 
 
 
89
  except Exception as e:
90
- return f"Error: {e}", f"Error: {e}"
91
 
92
  # ==========================================
93
  # 4. MODERN UI THEME & CSS
@@ -107,7 +124,7 @@ body, .gradio-container { background-color: #f0f2f5; }
107
  background: rgba(255, 255, 255, 0.95);
108
  backdrop-filter: blur(10px);
109
  border-bottom: 1px solid #e4e6eb;
110
- padding: 10px 20px;
111
  display: flex;
112
  align-items: center;
113
  justify-content: space-between;
@@ -117,16 +134,18 @@ body, .gradio-container { background-color: #f0f2f5; }
117
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
118
  }
119
 
120
- .logo-area { display: flex; align-items: center; gap: 15px; }
121
  .logo-img { height: 120px; width: 120px; border-radius: 12px; object-fit: cover; border: 1px solid #ddd; }
122
-
123
  .app-name {
124
  font-weight: 800;
125
- font-size: 28px;
126
  background: -webkit-linear-gradient(45deg, #1877f2, #6b21a8);
127
  -webkit-background-clip: text;
128
  -webkit-text-fill-color: transparent;
 
129
  }
 
130
 
131
  /* Sidebar Navigation */
132
  .nav-btn {
@@ -151,7 +170,7 @@ body, .gradio-container { background-color: #f0f2f5; }
151
  border-left: 4px solid #1877f2 !important;
152
  }
153
 
154
- /* Feed Cards */
155
  .content-card {
156
  background: white;
157
  border-radius: 12px;
@@ -159,21 +178,16 @@ body, .gradio-container { background-color: #f0f2f5; }
159
  border: 1px solid #ddd;
160
  padding: 20px;
161
  margin-bottom: 20px;
162
- transition: transform 0.2s;
163
  }
164
- .content-card:hover { box-shadow: 0 4px 12px rgba(0,0,0,0.1); transform: translateY(-2px); }
165
-
166
- /* Feed User Info */
167
- .feed-user-row { display: flex; gap: 10px; align-items: center; margin-bottom: 12px; }
168
- .feed-avatar { width: 40px; height: 40px; background: #e4e6eb; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 20px; }
169
- .feed-meta { display: flex; flex-direction: column; }
170
- .feed-name { font-weight: 700; color: #050505; font-size: 15px; }
171
- .feed-time { font-size: 12px; color: #65676b; }
172
 
173
- /* Innovation/Digitalizer Styling */
174
- .digitalizer-container {
175
- background: linear-gradient(135deg, #ffffff 0%, #f0f7ff 100%);
176
- border: 1px solid #1877f2;
 
 
 
 
177
  }
178
 
179
  /* Right Side Trending Box */
@@ -198,28 +212,27 @@ with gr.Blocks(title="Legacy Kitchen") as demo:
198
  <div class="custom-header">
199
  <div class="logo-area">
200
  <img src="data:image/jpeg;base64,{logo_b64}" class="logo-img">
201
- <span class="app-name">Legacy Kitchen</span>
 
 
 
202
  </div>
203
- <div style="color: #65676b; font-weight: 600;">v2.2 Beta</div>
204
  </div>
205
  """)
206
 
207
  with gr.Row():
208
 
209
- # --- LEFT SIDEBAR (Navigation) ---
210
  with gr.Column(scale=1, min_width=200):
211
- # My Profile Section
212
  gr.HTML(f"""
213
  <div style="display:flex; align-items:center; padding: 10px 10px 5px 10px;">
214
  <img src="data:image/jpeg;base64,{profile_b64}" style="width:40px; height:40px; border-radius:50%; margin-right:10px; object-fit:cover;">
215
  <b style="font-size: 16px;">My Profile</b>
216
  </div>
217
  """)
218
-
219
- # Separator
220
  gr.HTML("<hr style='border: 0; border-top: 1px solid #e4e6eb; margin: 10px 0 20px 0;'>")
221
 
222
- # FIX: Digitalizer is now FIRST and SELECTED by default
223
  nav_digital = gr.Button("✨ AI Digitizer", elem_classes=["nav-btn", "selected"])
224
  nav_feed = gr.Button("πŸ“° News Feed", elem_classes=["nav-btn"])
225
  nav_about = gr.Button("ℹ️ About", elem_classes=["nav-btn"])
@@ -227,30 +240,44 @@ with gr.Blocks(title="Legacy Kitchen") as demo:
227
  # --- CENTER CONTENT ---
228
  with gr.Column(scale=3):
229
 
230
- # === VIEW 1: AI DIGITALIZER (Now DEFAULT: visible=True) ===
231
  with gr.Group(visible=True) as digitalizer_view:
232
- gr.Markdown("## πŸ“Έ Recipe Digitalizer", elem_classes=["content-card"])
233
 
 
234
  with gr.Row():
235
- with gr.Column(elem_classes=["content-card", "digitalizer-container"]):
236
- input_img = gr.Image(type="filepath", label="Upload Handwritten Note", height=300)
237
- magic_btn = gr.Button("✨ Convert to Text", variant="primary", size="lg")
 
 
 
238
 
239
- with gr.Column(elem_classes=["content-card"]):
240
- out_text = gr.Textbox(label="Digitized Text", lines=6, interactive=False)
241
- out_sim = gr.Textbox(label="Similar Recipes in Database", lines=6)
242
-
243
- magic_btn.click(magic_pipeline, input_img, [out_text, out_sim])
 
 
 
 
 
 
 
 
 
 
 
 
 
244
 
245
- # === VIEW 2: FEED (Now HIDDEN by default: visible=False) ===
246
  with gr.Group(visible=False) as feed_view:
247
- # "What's on your mind" Box
248
  with gr.Group(elem_classes=["content-card"]):
249
  with gr.Row():
250
  gr.HTML(f'<img src="data:image/jpeg;base64,{profile_b64}" style="width:40px; height:40px; border-radius:50%; object-fit:cover;">')
251
  gr.Textbox(placeholder=f"What recipe are you cooking today?", show_label=False, container=False, scale=10)
252
 
253
- # Dynamic Feed Generation
254
  if not df_recipes.empty:
255
  feed_samples = df_recipes.sample(10)
256
  for index, row in feed_samples.iterrows():
@@ -259,85 +286,45 @@ with gr.Blocks(title="Legacy Kitchen") as demo:
259
 
260
  with gr.Group(elem_classes=["content-card"]):
261
  gr.HTML(f"""
262
- <div class="feed-user-row">
263
- <div class="feed-avatar">{emoji}</div>
264
- <div class="feed-meta">
265
- <span class="feed-name">{user_name}</span>
266
- <span class="feed-time">2h · 🌍 Public</span>
267
- </div>
268
  </div>
269
  """)
270
  gr.Markdown(f"### {row['Title']}")
271
  gr.Markdown(f"{str(row['Raw_Output'])[:250]}...")
272
- gr.Markdown(f"*[Click to see full recipe...]*")
273
-
274
  with gr.Row():
275
  gr.Button("πŸ‘ Like", size="sm", variant="secondary")
276
  gr.Button("πŸ’¬ Comment", size="sm", variant="secondary")
277
  gr.Button("↗️ Share", size="sm", variant="secondary")
278
  else:
279
- gr.Markdown("⚠️ Database is empty. Please check your CSV file.")
280
 
281
- # === VIEW 3: ABOUT ===
282
  with gr.Group(visible=False) as about_view:
283
  with gr.Group(elem_classes=["content-card"]):
284
- gr.Markdown("""
285
- # ℹ️ About Legacy Kitchen
286
- **Preserving Heritage through AI.**
287
- Legacy Kitchen allows you to upload photos of your grandmother's handwritten recipe cards and instantly converts them into digital text using OCR and AI models.
288
- """)
289
 
290
  # --- RIGHT COLUMN (Trending) ---
291
  with gr.Column(scale=1, min_width=200):
292
  gr.Markdown("### Trending Recipes")
293
-
294
- # Helper to create trending box
295
  def trend_box(title, likes):
296
- return f"""
297
- <div class="trend-box">
298
- <b>{title}</b><br>
299
- <span style="color:gray; font-size:12px;">{likes} likes</span>
300
- </div>"""
301
-
302
- # FIX: Added the 2 requested items
303
- gr.HTML(trend_box("🍜 Ramen Hack", "12k") +
304
- trend_box("πŸͺ Best Cookies", "8k") +
305
- trend_box("🍰 Cheese Cake", "15k") +
306
- trend_box("πŸͺ Nana's Tahini Cookies", "9k"))
307
 
308
  # ==========================================
309
- # 6. JAVASCRIPT LOGIC (Client Side)
310
  # ==========================================
311
-
312
- # FIX: Updated logic to match the new button order
313
- # ORDER OF OUTPUTS: [DigitalizerView, FeedView, AboutView, NavDigital, NavFeed, NavAbout]
314
-
315
  def go_digi():
316
- return (
317
- gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), # Views: Digi, Feed, About
318
- gr.update(elem_classes=["nav-btn", "selected"]), # Nav Digi
319
- gr.update(elem_classes=["nav-btn"]), # Nav Feed
320
- gr.update(elem_classes=["nav-btn"]) # Nav About
321
- )
322
 
323
  def go_feed():
324
- return (
325
- gr.update(visible=False), gr.update(visible=True), gr.update(visible=False),
326
- gr.update(elem_classes=["nav-btn"]),
327
- gr.update(elem_classes=["nav-btn", "selected"]),
328
- gr.update(elem_classes=["nav-btn"])
329
- )
330
 
331
  def go_about():
332
- return (
333
- gr.update(visible=False), gr.update(visible=False), gr.update(visible=True),
334
- gr.update(elem_classes=["nav-btn"]),
335
- gr.update(elem_classes=["nav-btn"]),
336
- gr.update(elem_classes=["nav-btn", "selected"])
337
- )
338
 
339
  outputs_ui = [digitalizer_view, feed_view, about_view, nav_digital, nav_feed, nav_about]
340
-
341
  nav_digital.click(go_digi, None, outputs_ui)
342
  nav_feed.click(go_feed, None, outputs_ui)
343
  nav_about.click(go_about, None, outputs_ui)
 
47
  profile_b64 = image_to_base64("232px-Tv_the_muppet_show_bein_green.jpg")
48
 
49
  # ==========================================
50
+ # 3. BACKEND LOGIC (UPDATED FOR 3 SEPARATE OUTPUTS)
51
  # ==========================================
52
  def get_embedding_via_api(text):
53
  if not client: raise ValueError("HF_TOKEN missing")
54
  response = client.feature_extraction(text, model=API_MODEL)
55
  return np.array(response)
56
 
57
+ # UPDATED: Returns a LIST of 3 strings instead of one big string
58
+ def find_similar_recipes_list(query_text):
59
+ if stored_embeddings is None: return ["Database error."] * 3
60
  query_vec = get_embedding_via_api("Represent this recipe for retrieving similar dishes: " + query_text)
61
  if len(query_vec.shape) == 1: query_vec = query_vec.reshape(1, -1)
62
 
63
  scores = cosine_similarity(query_vec, stored_embeddings)[0]
64
  top_indices = scores.argsort()[-3:][::-1]
65
 
66
+ results_list = []
67
  for idx in top_indices:
68
  row = df_recipes.iloc[idx]
69
+ title = row['Title']
70
+ desc = str(row['Raw_Output'])[:200] + "..." # Truncate for UI card
71
+
72
+ # Markdown format for individual card
73
+ card_content = f"### πŸ† {title}\n\n{desc}"
74
+ results_list.append(card_content)
75
+
76
+ # Ensure we always return exactly 3 items (pad if fewer matches found)
77
+ while len(results_list) < 3:
78
+ results_list.append("No match found.")
79
+
80
+ return results_list
81
 
82
  def format_recipe(json_data):
83
  if "error" in json_data: return f"Error: {json_data['error']}", ""
 
87
  text = f"🍽️ {title}\n\nπŸ›’ INGREDIENTS:\n{ing}\n\n🍳 INSTRUCTIONS:\n{inst}"
88
  return text, f"{title} {ing} {inst}"
89
 
90
+ # UPDATED: Returns 4 outputs (1 text + 3 similar cards)
91
  def magic_pipeline(image_path):
92
+ if not hf_token: return "Error: HF_TOKEN missing", "", "", ""
93
  try:
94
  os.environ["HF_TOKEN"] = hf_token
95
  digitizer = RecipeDigitalizerPipeline()
96
  json_res = digitizer.run_pipeline(image_path)
97
  readable, query = format_recipe(json_res)
98
+
99
+ if query:
100
+ sim_list = find_similar_recipes_list(query)
101
+ else:
102
+ sim_list = ["No query generated.", "", ""]
103
+
104
+ return readable, sim_list[0], sim_list[1], sim_list[2]
105
+
106
  except Exception as e:
107
+ return f"Error: {e}", "Error", "Error", "Error"
108
 
109
  # ==========================================
110
  # 4. MODERN UI THEME & CSS
 
124
  background: rgba(255, 255, 255, 0.95);
125
  backdrop-filter: blur(10px);
126
  border-bottom: 1px solid #e4e6eb;
127
+ padding: 15px 20px;
128
  display: flex;
129
  align-items: center;
130
  justify-content: space-between;
 
134
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
135
  }
136
 
137
+ .logo-area { display: flex; align-items: center; gap: 20px; }
138
  .logo-img { height: 120px; width: 120px; border-radius: 12px; object-fit: cover; border: 1px solid #ddd; }
139
+ .text-area { display: flex; flex-direction: column; }
140
  .app-name {
141
  font-weight: 800;
142
+ font-size: 32px;
143
  background: -webkit-linear-gradient(45deg, #1877f2, #6b21a8);
144
  -webkit-background-clip: text;
145
  -webkit-text-fill-color: transparent;
146
+ line-height: 1.2;
147
  }
148
+ .app-slogan { font-size: 16px; color: #65676b; font-weight: 500; }
149
 
150
  /* Sidebar Navigation */
151
  .nav-btn {
 
170
  border-left: 4px solid #1877f2 !important;
171
  }
172
 
173
+ /* General Cards */
174
  .content-card {
175
  background: white;
176
  border-radius: 12px;
 
178
  border: 1px solid #ddd;
179
  padding: 20px;
180
  margin-bottom: 20px;
 
181
  }
 
 
 
 
 
 
 
 
182
 
183
+ /* Similar Recipe Cards (Special Look) */
184
+ .sim-card {
185
+ background: #fff;
186
+ border: 1px solid #eee;
187
+ border-radius: 8px;
188
+ padding: 15px;
189
+ height: 100%;
190
+ border-top: 4px solid #1877f2; /* Blue accent top */
191
  }
192
 
193
  /* Right Side Trending Box */
 
212
  <div class="custom-header">
213
  <div class="logo-area">
214
  <img src="data:image/jpeg;base64,{logo_b64}" class="logo-img">
215
+ <div class="text-area">
216
+ <span class="app-name">Legacy Kitchen</span>
217
+ <span class="app-slogan">Turning Handwritten Notes into a Digital Cookbook.</span>
218
+ </div>
219
  </div>
220
+ <div style="color: #65676b; font-weight: 600;">v3.0</div>
221
  </div>
222
  """)
223
 
224
  with gr.Row():
225
 
226
+ # --- LEFT SIDEBAR ---
227
  with gr.Column(scale=1, min_width=200):
 
228
  gr.HTML(f"""
229
  <div style="display:flex; align-items:center; padding: 10px 10px 5px 10px;">
230
  <img src="data:image/jpeg;base64,{profile_b64}" style="width:40px; height:40px; border-radius:50%; margin-right:10px; object-fit:cover;">
231
  <b style="font-size: 16px;">My Profile</b>
232
  </div>
233
  """)
 
 
234
  gr.HTML("<hr style='border: 0; border-top: 1px solid #e4e6eb; margin: 10px 0 20px 0;'>")
235
 
 
236
  nav_digital = gr.Button("✨ AI Digitizer", elem_classes=["nav-btn", "selected"])
237
  nav_feed = gr.Button("πŸ“° News Feed", elem_classes=["nav-btn"])
238
  nav_about = gr.Button("ℹ️ About", elem_classes=["nav-btn"])
 
240
  # --- CENTER CONTENT ---
241
  with gr.Column(scale=3):
242
 
243
+ # === VIEW 1: AI DIGITALIZER (Default) ===
244
  with gr.Group(visible=True) as digitalizer_view:
 
245
 
246
+ # SECTION 1: UPLOAD & TEXT (Side by Side)
247
  with gr.Row():
248
+ # Left: Upload & Button
249
+ with gr.Column(scale=1):
250
+ gr.Markdown("### 1. Upload Note", elem_classes=["content-card"])
251
+ with gr.Group(elem_classes=["content-card"]):
252
+ input_img = gr.Image(type="filepath", label="Upload", height=300)
253
+ magic_btn = gr.Button("✨ Convert to Digital", variant="primary", size="lg")
254
 
255
+ # Right: Digitized Text Result
256
+ with gr.Column(scale=1):
257
+ gr.Markdown("### 2. Digital Text", elem_classes=["content-card"])
258
+ with gr.Group(elem_classes=["content-card"]):
259
+ out_text = gr.Textbox(label="Result", lines=12, interactive=False, show_label=False)
260
+
261
+ # SECTION 2: SIMILAR RECIPES (Below, 3 distinct cards)
262
+ gr.Markdown("### 3. Similar Recipes from Database")
263
+ with gr.Row():
264
+ with gr.Column(elem_classes=["sim-card"]):
265
+ sim1 = gr.Markdown("Match #1 will appear here...")
266
+ with gr.Column(elem_classes=["sim-card"]):
267
+ sim2 = gr.Markdown("Match #2 will appear here...")
268
+ with gr.Column(elem_classes=["sim-card"]):
269
+ sim3 = gr.Markdown("Match #3 will appear here...")
270
+
271
+ # UPDATED CLICK EVENT: Returns 4 outputs
272
+ magic_btn.click(magic_pipeline, input_img, [out_text, sim1, sim2, sim3])
273
 
274
+ # === VIEW 2: FEED (Hidden) ===
275
  with gr.Group(visible=False) as feed_view:
 
276
  with gr.Group(elem_classes=["content-card"]):
277
  with gr.Row():
278
  gr.HTML(f'<img src="data:image/jpeg;base64,{profile_b64}" style="width:40px; height:40px; border-radius:50%; object-fit:cover;">')
279
  gr.Textbox(placeholder=f"What recipe are you cooking today?", show_label=False, container=False, scale=10)
280
 
 
281
  if not df_recipes.empty:
282
  feed_samples = df_recipes.sample(10)
283
  for index, row in feed_samples.iterrows():
 
286
 
287
  with gr.Group(elem_classes=["content-card"]):
288
  gr.HTML(f"""
289
+ <div style="display:flex; gap:10px; align-items:center; margin-bottom:12px;">
290
+ <div style="width:40px; height:40px; background:#e4e6eb; border-radius:50%; display:flex; align-items:center; justify-content:center; font-size:20px;">{emoji}</div>
291
+ <div><b>{user_name}</b><br><span style="color:gray; font-size:12px;">2h · 🌍 Public</span></div>
 
 
 
292
  </div>
293
  """)
294
  gr.Markdown(f"### {row['Title']}")
295
  gr.Markdown(f"{str(row['Raw_Output'])[:250]}...")
 
 
296
  with gr.Row():
297
  gr.Button("πŸ‘ Like", size="sm", variant="secondary")
298
  gr.Button("πŸ’¬ Comment", size="sm", variant="secondary")
299
  gr.Button("↗️ Share", size="sm", variant="secondary")
300
  else:
301
+ gr.Markdown("⚠️ Database is empty.")
302
 
303
+ # === VIEW 3: ABOUT (Hidden) ===
304
  with gr.Group(visible=False) as about_view:
305
  with gr.Group(elem_classes=["content-card"]):
306
+ gr.Markdown("# ℹ️ About Legacy Kitchen\n\n**Turning Handwritten Notes into a Digital Cookbook.**")
 
 
 
 
307
 
308
  # --- RIGHT COLUMN (Trending) ---
309
  with gr.Column(scale=1, min_width=200):
310
  gr.Markdown("### Trending Recipes")
 
 
311
  def trend_box(title, likes):
312
+ return f"<div class='trend-box'><b>{title}</b><br><span style='color:gray; font-size:12px;'>{likes} likes</span></div>"
313
+ gr.HTML(trend_box("🍜 Ramen Hack", "12k") + trend_box("πŸͺ Best Cookies", "8k") + trend_box("🍰 Cheese Cake", "15k") + trend_box("πŸͺ Nana's Tahini Cookies", "9k"))
 
 
 
 
 
 
 
 
 
314
 
315
  # ==========================================
316
+ # 6. JAVASCRIPT LOGIC
317
  # ==========================================
 
 
 
 
318
  def go_digi():
319
+ return (gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(elem_classes=["nav-btn", "selected"]), gr.update(elem_classes=["nav-btn"]), gr.update(elem_classes=["nav-btn"]))
 
 
 
 
 
320
 
321
  def go_feed():
322
+ return (gr.update(visible=False), gr.update(visible=True), gr.update(visible=False), gr.update(elem_classes=["nav-btn"]), gr.update(elem_classes=["nav-btn", "selected"]), gr.update(elem_classes=["nav-btn"]))
 
 
 
 
 
323
 
324
  def go_about():
325
+ return (gr.update(visible=False), gr.update(visible=False), gr.update(visible=True), gr.update(elem_classes=["nav-btn"]), gr.update(elem_classes=["nav-btn"]), gr.update(elem_classes=["nav-btn", "selected"]))
 
 
 
 
 
326
 
327
  outputs_ui = [digitalizer_view, feed_view, about_view, nav_digital, nav_feed, nav_about]
 
328
  nav_digital.click(go_digi, None, outputs_ui)
329
  nav_feed.click(go_feed, None, outputs_ui)
330
  nav_about.click(go_about, None, outputs_ui)