dschandra commited on
Commit
2a3bbc6
·
verified ·
1 Parent(s): 68169e2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -264
app.py CHANGED
@@ -7,17 +7,17 @@ import whisper
7
  import asyncio
8
  import platform
9
 
10
- # === Load Whisper Model (tiny for speed) ===
11
  whisper_model = whisper.load_model("tiny")
12
 
13
- # === Supported Languages ===
14
  lang_map = {
15
  "English": "en", "Hindi": "hi", "Telugu": "te", "Spanish": "es",
16
  "Tamil": "ta", "Gujarati": "gu", "Kannada": "kn", "Bengali": "bn",
17
  "Marathi": "mr", "Punjabi": "pa", "Urdu": "ur"
18
  }
19
 
20
- # === Local Food List ===
21
  local_foods = {
22
  "vegetables": [
23
  {"name": "carrot", "calories": 41, "iron": 0.3, "fiber": 2.8, "vitamin_c": 6},
@@ -36,7 +36,7 @@ local_foods = {
36
  ]
37
  }
38
 
39
- # === Precompute Food Selections ===
40
  def precompute_foods():
41
  return {
42
  "grain": random.choice(local_foods['grains']),
@@ -45,7 +45,7 @@ def precompute_foods():
45
  "protein": random.choice(local_foods['proteins'])
46
  }
47
 
48
- # === Output Templates ===
49
  def get_output_template(lang):
50
  templates = {
51
  "English": """
@@ -69,278 +69,45 @@ def get_output_template(lang):
69
  {dinner}
70
 
71
  📊 Summary: Balanced meals with local ingredients.
72
- """,
73
- "Hindi": """
74
- 🌾 व्यक्तिगत आहार योजना
75
- ────────────────────────────
76
- 👤 आयु: {age}, लिंग: {gender}
77
- 💼 पेशा: {occupation}
78
- 🏃 गतिविधि स्तर: {activity_level}
79
- ⚕️ स्वास्थ्य स्थितियाँ: {health_conditions}
80
- 🍽️ वरीयताएँ: {dietary_preferences}
81
- ⚠️ एलर्जी: {allergies}
82
- 💰 बजट: ₹{budget}/दिन
83
-
84
- 🥣 नाश्ता:
85
- {breakfast}
86
-
87
- 🍛 दोपहर का भोजन:
88
- {lunch}
89
-
90
- 🥗 रात का खाना:
91
- {dinner}
92
-
93
- 📊 सारांश: स्थानीय खाद्य पदार्थों के साथ संतुलित भोजन।
94
- """,
95
- "Telugu": """
96
- 🌾 వ్యక్తిగత ఆహార ప్రణాళిక
97
- ────────────────────────────
98
- 👤 వయస్సు: {age}, లింగం: {gender}
99
- 💼 వృత్తి: {occupation}
100
- 🏃 చర్య స్థాయి: {activity_level}
101
- ⚕️ ఆరోగ్య పరిస్థితులు: {health_conditions}
102
- 🍽️ అభిరుచులు: {dietary_preferences}
103
- ⚠️ అలర్జీలు: {allergies}
104
- 💰 బడ్జెట్: ₹{budget}/రోజు
105
-
106
- 🥣 అల్పాహారం:
107
- {breakfast}
108
-
109
- 🍛 మధ్యాహ్న భోజనం:
110
- {lunch}
111
-
112
- 🥗 రాత్రి భోజనం:
113
- {dinner}
114
-
115
- 📊 సారాంశం: స్థానిక పదార్థాలతో సంతులిత ఆహారం.
116
- """,
117
- "Spanish": """
118
- 🌾 Plan de dieta personalizado
119
- ────────────────────────────
120
- 👤 Edad: {age}, Género: {gender}
121
- 💼 Ocupación: {occupation}
122
- 🏃 Nivel de actividad: {activity_level}
123
- ⚕️ Condiciones de salud: {health_conditions}
124
- 🍽️ Preferencias: {dietary_preferences}
125
- ⚠️ Alergias: {allergies}
126
- 💰 Presupuesto: ₹{budget}/día
127
-
128
- 🥣 Desayuno:
129
- {breakfast}
130
-
131
- 🍛 Almuerzo:
132
- {lunch}
133
-
134
- 🥗 Cena:
135
- {dinner}
136
-
137
- 📊 Resumen: Comidas equilibradas con ingredientes locales.
138
- """,
139
- "Tamil": """
140
- 🌾 தனிப்பட்ட உணவுக் குறிப்பு
141
- ────────────────────────────
142
- 👤 வயது: {age}, பாலினம்: {gender}
143
- 💼 தொழில்: {occupation}
144
- 🏃 செயல்திறன் அளவு: {activity_level}
145
- ⚕️ உடல்நிலை: {health_conditions}
146
- 🍽️ விருப்பங்கள்: {dietary_preferences}
147
- ⚠️ ஒவ்வாமைகள்: {allergies}
148
- 💰 தினசரி செலவு: ₹{budget}/நாள்
149
-
150
- 🥣 காலை உணவு:
151
- {breakfast}
152
-
153
- 🍛 மதிய உணவு:
154
- {lunch}
155
-
156
- 🥗 இரவு உணவு:
157
- {dinner}
158
-
159
- 📊 சுருக்கம்: உள்ளூர் பொருட்களுடன் சமநிலையுடைய உணவு.
160
- """,
161
- "Gujarati": """
162
- 🌾 વ્યક્તિગત આહાર યોજના
163
- ────────────────────────────
164
- 👤 ઉંમર: {age}, લિંગ: {gender}
165
- 💼 વ્યવસાય: {occupation}
166
- 🏃 પ્રવૃત્તિ સ્તર: {activity_level}
167
- ⚕️ આરોગ્ય સ્થિતિઓ: {health_conditions}
168
- 🍽️ પસંદગીઓ: {dietary_preferences}
169
- ⚠️ એલર્જી: {allergies}
170
- 💰 બજેટ: ₹{budget}/દિવસ
171
-
172
- 🥣 નાસ્તો:
173
- {breakfast}
174
-
175
- 🍛 બપોરનું ભોજન:
176
- {lunch}
177
-
178
- 🥗 રાત્રિ ભોજન:
179
- {dinner}
180
-
181
- 📊 સારાંશ: સ્થાનિક ઘટકો સાથે સંતુલિત ભોજન.
182
- """,
183
- "Kannada": """
184
- 🌾 ವೈಯಕ್ತಿಕ ಆಹಾರ ಯೋಜನೆ
185
- ────────────────────────────
186
- 👤 ವಯಸ್ಸು: {age}, ಲಿಂಗ: {gender}
187
- 💼 ಉದ್ಯೋಗ: {occupation}
188
- 🏃 ಚಟುವಟಿಕೆ ಮಟ್ಟ: {activity_level}
189
- ⚕️ ಆರೋಗ್ಯ ಸ್ಥಿತಿಗಳು: {health_conditions}
190
- 🍽️ ಆಯ್ಕೆಗಳು: {dietary_preferences}
191
- ⚠️ ಅಲರ್ಜಿ: {allergies}
192
- 💰 ದಿನವೂ ಖರ್ಚು: ₹{budget}/ದಿನ
193
-
194
- 🥣 ಉಪಾಹಾರ:
195
- {breakfast}
196
-
197
- 🍛 ಮಧ್ಯಾಹ್ನ ಭೋಜನ:
198
- {lunch}
199
-
200
- 🥗 ರಾತ್ರಿಯ ಭೋಜನ:
201
- {dinner}
202
-
203
- 📊 ಸಾರಾಂಶ: ಸ್ಥಳೀಯ ಪದಾರ್ಥಗಳಿಂದ ಸಮತೋಲಿತ ಆಹಾರ.
204
- """,
205
- "Bengali": """
206
- 🌾 ব্যক্তিগত ডায়েট প্ল্যান
207
- ────────────────────────────
208
- 👤 বয়স: {age}, লিঙ্গ: {gender}
209
- 💼 পেশা: {occupation}
210
- 🏃 কার্যকলাপ স্তর: {activity_level}
211
- ⚕️ স্বাস্থ্য অবস্থা: {health_conditions}
212
- 🍽️ পছন্দ: {dietary_preferences}
213
- ⚠️ অ্যালার্জি: {allergies}
214
- 💰 বাজেট: ₹{budget}/দিন
215
-
216
- 🥣 প্রাতঃরাশ:
217
- {breakfast}
218
-
219
- 🍛 মধ্যাহ্নভোজ:
220
- {lunch}
221
-
222
- 🥗 রাতের খাবার:
223
- {dinner}
224
-
225
- 📊 সারাংশ: স্থানীয় উপাদানসহ সুষম আহার।
226
- """,
227
- "Marathi": """
228
- 🌾 वैयक्तिक आहार योजना
229
- ────────────────────────────
230
- 👤 वय: {age}, लिंग: {gender}
231
- 💼 व्यवसाय: {occupation}
232
- 🏃 क्रियाशीलतेचा स्तर: {activity_level}
233
- ⚕️ आरोग्य स्थिती: {health_conditions}
234
- 🍽️ प्राधान्ये: {dietary_preferences}
235
- ⚠️ अॅलर्जी: {allergies}
236
- 💰 बजेट: ₹{budget}/दिवस
237
-
238
- 🥣 न्याहारी:
239
- {breakfast}
240
-
241
- 🍛 दुपारचे जेवण:
242
- {lunch}
243
-
244
- 🥗 रात्रीचे जेवण:
245
- {dinner}
246
-
247
- 📊 सारांश: स्थानिक घटकांसह संतुलित आहार.
248
- """,
249
- "Punjabi": """
250
- 🌾 ਨਿੱਜੀ ਖੁਰਾਕ ਯੋਜਨਾ
251
- ────────────────────────────
252
- 👤 ਉਮਰ: {age}, ਲਿੰਗ: {gender}
253
- 💼 ਪੇਸ਼ਾ: {occupation}
254
- 🏃 ਗਤੀਵਿਧੀ ਪੱਧਰ: {activity_level}
255
- ⚕️ ਸਿਹਤ ਦੀ ਹਾਲਤ: {health_conditions}
256
- 🍽️ ਪਸੰਦਾਂ: {dietary_preferences}
257
- ⚠️ ਐਲਰਜੀ: {allergies}
258
- 💰 ਰੋਜ਼ਾਨਾ ਬਜਟ: ₹{budget}/ਦਿਨ
259
-
260
- 🥣 ਨਾਸ਼ਤਾ:
261
- {breakfast}
262
-
263
- 🍛 ਦੁਪਿਹਰ ਦਾ ਭੋਜਨ:
264
- {lunch}
265
-
266
- 🥗 ਰਾਤ ਦਾ ਭੋਜਨ:
267
- {dinner}
268
-
269
- 📊 ਸੰਖੇਪ: ਸਥਾਨਕ ਸਮੱਗਰੀ ਨਾਲ ਸੰਤੁਲਿਤ ਭੋਜਨ।
270
- """,
271
- "Urdu": """
272
- 🌾 ذاتی غذا کا منصوبہ
273
- ────────────────────────────
274
- 👤 عمر: {age}, جنس: {gender}
275
- 💼 پیشہ: {occupation}
276
- 🏃 سرگرمی کی سطح: {activity_level}
277
- ⚕️ صحت کی حالتیں: {health_conditions}
278
- 🍽️ ترجیحات: {dietary_preferences}
279
- ⚠️ الرجی: {allergies}
280
- 💰 یومیہ بجٹ: ₹{budget}/دن
281
-
282
- 🥣 ناشتہ:
283
- {breakfast}
284
-
285
- 🍛 دوپہر کا کھانا:
286
- {lunch}
287
-
288
- 🥗 رات کا کھانا:
289
- {dinner}
290
-
291
- 📊 خلاصہ: مقامی اجزاء کے ساتھ متوازن غذا۔
292
  """
293
  }
294
  return templates.get(lang, templates["English"])
295
 
296
- # === Transcription Function ===
297
  async def transcribe_audio(audio_path, lang):
298
  try:
299
  if not audio_path or not os.path.exists(audio_path):
300
- return "❌ No audio file found."
301
-
302
  temp_wav = f"temp_{uuid.uuid4().hex}.wav"
303
  audio = AudioSegment.from_file(audio_path)
304
  audio = audio.set_frame_rate(16000).set_channels(1)
305
  audio.export(temp_wav, format="wav")
306
-
307
  result = whisper_model.transcribe(temp_wav, language=lang_map.get(lang, "en"), fp16=False)
308
  os.remove(temp_wav)
309
-
310
- return result.get("text", "❌ Could not understand the speech.").strip()
311
  except Exception as e:
312
  return f"❌ Error: {str(e)}"
313
 
314
- # === Unified Processing ===
315
- async def full_pipeline(health_audio, diet_audio, allergy_audio, health_text, diet_text, allergy_text, age, gender, weight, height, occupation, activity, budget, lang):
316
- # Use text inputs if provided, else transcribe audio
317
  health_conditions = health_text or await transcribe_audio(health_audio, lang)
318
  dietary_preferences = diet_text or await transcribe_audio(diet_audio, lang)
319
  allergies = allergy_text or await transcribe_audio(allergy_audio, lang)
 
 
320
 
321
- return generate_diet(age, gender, weight, height, occupation, activity, health_conditions, dietary_preferences, allergies, budget, lang)
322
-
323
- # === Diet Generation ===
324
- def generate_diet(age, gender, weight, height, occupation, activity_level, health_conditions, dietary_preferences, allergies, budget, lang):
325
- # Use precomputed foods
326
  foods = precompute_foods()
327
  grain, veg1, veg2, protein = foods['grain'], foods['veg1'], foods['veg2'], foods['protein']
328
-
329
- # Build meals
330
  breakfast = f"{grain['name']} porridge with {veg1['name']}"
331
  lunch = f"{protein['name']} with {grain['name']} and {veg2['name']}"
332
  dinner = f"{veg1['name']} curry, {veg2['name']} salad, and {protein['name']}"
333
-
334
- # Nutritional Totals (optimized)
335
  nutrients = ["calories", "iron", "fiber", "protein", "vitamin_c"]
336
- nutrition = {nutrient: round(
337
- grain.get(nutrient, 0) * 2 +
338
- veg1.get(nutrient, 0) +
339
- veg2.get(nutrient, 0) * 2 +
340
- protein.get(nutrient, 0) * 2, 1
341
- ) for nutrient in nutrients}
342
-
343
- # Plan Output
344
  plan = get_output_template(lang).format(
345
  age=age, gender=gender, occupation=occupation, activity_level=activity_level,
346
  health_conditions=health_conditions or "None",
@@ -348,7 +115,6 @@ def generate_diet(age, gender, weight, height, occupation, activity_level, healt
348
  allergies=allergies or "None", budget=budget,
349
  breakfast=breakfast, lunch=lunch, dinner=dinner
350
  )
351
-
352
  nutrition_summary = f"""
353
  🍽️ Nutritional Summary:
354
  ------------------------------
@@ -360,9 +126,9 @@ def generate_diet(age, gender, weight, height, occupation, activity_level, healt
360
  """
361
  return plan + nutrition_summary
362
 
363
- # === UI ===
364
  def render_ui(default_lang="English"):
365
- with gr.Blocks(theme=gr.themes.Monochrome()) as demo:
366
  lang_sel = gr.Dropdown(label="Language", choices=list(lang_map.keys()), value=default_lang)
367
  age = gr.Number(label="Age", value=30, minimum=1)
368
  gender = gr.Radio(["Male", "Female", "Other"], label="Gender")
@@ -386,19 +152,15 @@ def render_ui(default_lang="English"):
386
 
387
  gr.Button("🎯 Generate Plan").click(
388
  full_pipeline,
389
- inputs=[health_audio, diet_audio, allergy_audio, health_text, diet_text, allergy_text, age, gender, weight, height, occupation, activity, budget, lang_sel],
390
- outputs=output,
391
- queue=True
392
  )
393
-
394
  return demo
395
 
396
  async def main():
397
  demo = render_ui()
398
- await demo.launch()
399
 
400
- if platform.system() == "Emscripten":
401
- asyncio.ensure_future(main())
402
- else:
403
- if __name__ == "__main__":
404
- asyncio.run(main())
 
7
  import asyncio
8
  import platform
9
 
10
+ # Load Whisper model
11
  whisper_model = whisper.load_model("tiny")
12
 
13
+ # Supported languages
14
  lang_map = {
15
  "English": "en", "Hindi": "hi", "Telugu": "te", "Spanish": "es",
16
  "Tamil": "ta", "Gujarati": "gu", "Kannada": "kn", "Bengali": "bn",
17
  "Marathi": "mr", "Punjabi": "pa", "Urdu": "ur"
18
  }
19
 
20
+ # Local food database
21
  local_foods = {
22
  "vegetables": [
23
  {"name": "carrot", "calories": 41, "iron": 0.3, "fiber": 2.8, "vitamin_c": 6},
 
36
  ]
37
  }
38
 
39
+ # Select random foods
40
  def precompute_foods():
41
  return {
42
  "grain": random.choice(local_foods['grains']),
 
45
  "protein": random.choice(local_foods['proteins'])
46
  }
47
 
48
+ # Output templates (shortened for brevity here, use your full dictionary)
49
  def get_output_template(lang):
50
  templates = {
51
  "English": """
 
69
  {dinner}
70
 
71
  📊 Summary: Balanced meals with local ingredients.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  """
73
  }
74
  return templates.get(lang, templates["English"])
75
 
76
+ # Transcription
77
  async def transcribe_audio(audio_path, lang):
78
  try:
79
  if not audio_path or not os.path.exists(audio_path):
80
+ return ""
 
81
  temp_wav = f"temp_{uuid.uuid4().hex}.wav"
82
  audio = AudioSegment.from_file(audio_path)
83
  audio = audio.set_frame_rate(16000).set_channels(1)
84
  audio.export(temp_wav, format="wav")
 
85
  result = whisper_model.transcribe(temp_wav, language=lang_map.get(lang, "en"), fp16=False)
86
  os.remove(temp_wav)
87
+ return result.get("text", "").strip()
 
88
  except Exception as e:
89
  return f"❌ Error: {str(e)}"
90
 
91
+ # Full pipeline
92
+ async def full_pipeline(health_audio, diet_audio, allergy_audio, health_text, diet_text, allergy_text,
93
+ age, gender, weight, height, occupation, activity, budget, lang):
94
  health_conditions = health_text or await transcribe_audio(health_audio, lang)
95
  dietary_preferences = diet_text or await transcribe_audio(diet_audio, lang)
96
  allergies = allergy_text or await transcribe_audio(allergy_audio, lang)
97
+ return generate_diet(age, gender, weight, height, occupation, activity,
98
+ health_conditions, dietary_preferences, allergies, budget, lang)
99
 
100
+ # Diet generator
101
+ def generate_diet(age, gender, weight, height, occupation, activity_level,
102
+ health_conditions, dietary_preferences, allergies, budget, lang):
 
 
103
  foods = precompute_foods()
104
  grain, veg1, veg2, protein = foods['grain'], foods['veg1'], foods['veg2'], foods['protein']
 
 
105
  breakfast = f"{grain['name']} porridge with {veg1['name']}"
106
  lunch = f"{protein['name']} with {grain['name']} and {veg2['name']}"
107
  dinner = f"{veg1['name']} curry, {veg2['name']} salad, and {protein['name']}"
 
 
108
  nutrients = ["calories", "iron", "fiber", "protein", "vitamin_c"]
109
+ nutrition = {n: round(grain.get(n, 0) * 2 + veg1.get(n, 0) + veg2.get(n, 0) * 2 + protein.get(n, 0) * 2, 1)
110
+ for n in nutrients}
 
 
 
 
 
 
111
  plan = get_output_template(lang).format(
112
  age=age, gender=gender, occupation=occupation, activity_level=activity_level,
113
  health_conditions=health_conditions or "None",
 
115
  allergies=allergies or "None", budget=budget,
116
  breakfast=breakfast, lunch=lunch, dinner=dinner
117
  )
 
118
  nutrition_summary = f"""
119
  🍽️ Nutritional Summary:
120
  ------------------------------
 
126
  """
127
  return plan + nutrition_summary
128
 
129
+ # UI
130
  def render_ui(default_lang="English"):
131
+ with gr.Blocks() as demo:
132
  lang_sel = gr.Dropdown(label="Language", choices=list(lang_map.keys()), value=default_lang)
133
  age = gr.Number(label="Age", value=30, minimum=1)
134
  gender = gr.Radio(["Male", "Female", "Other"], label="Gender")
 
152
 
153
  gr.Button("🎯 Generate Plan").click(
154
  full_pipeline,
155
+ inputs=[health_audio, diet_audio, allergy_audio, health_text, diet_text, allergy_text,
156
+ age, gender, weight, height, occupation, activity, budget, lang_sel],
157
+ outputs=output
158
  )
 
159
  return demo
160
 
161
  async def main():
162
  demo = render_ui()
163
+ await demo.launch(server_name="0.0.0.0", server_port=7860)
164
 
165
+ if __name__ == "__main__":
166
+ asyncio.run(main())