dschandra commited on
Commit
df46197
·
verified ·
1 Parent(s): 29e3a03

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +404 -0
app.py ADDED
@@ -0,0 +1,404 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import random
3
+ import uuid
4
+ import gradio as gr
5
+ from pydub import AudioSegment
6
+ 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},
24
+ {"name": "spinach", "calories": 23, "iron": 2.7, "fiber": 2.2, "vitamin_c": 28},
25
+ {"name": "beetroot", "calories": 43, "iron": 0.8, "fiber": 2.0, "vitamin_c": 4}
26
+ ],
27
+ "grains": [
28
+ {"name": "rice", "calories": 130, "iron": 1.2, "fiber": 0.4, "protein": 2.7},
29
+ {"name": "wheat", "calories": 340, "iron": 3.2, "fiber": 12.2, "protein": 13},
30
+ {"name": "millet", "calories": 119, "iron": 3.0, "fiber": 8.5, "protein": 3.5}
31
+ ],
32
+ "proteins": [
33
+ {"name": "lentils", "calories": 116, "iron": 3.3, "fiber": 7.9, "protein": 9},
34
+ {"name": "chicken", "calories": 239, "iron": 1.3, "fiber": 0.0, "protein": 27},
35
+ {"name": "tofu", "calories": 76, "iron": 1.6, "fiber": 0.3, "protein": 8}
36
+ ]
37
+ }
38
+
39
+ # === Precompute Food Selections ===
40
+ def precompute_foods():
41
+ return {
42
+ "grain": random.choice(local_foods['grains']),
43
+ "veg1": random.choice(local_foods['vegetables']),
44
+ "veg2": random.choice(local_foods['vegetables']),
45
+ "protein": random.choice(local_foods['proteins'])
46
+ }
47
+
48
+ # === Output Templates ===
49
+ def get_output_template(lang):
50
+ templates = {
51
+ "English": """
52
+ 🌾 Personalized Diet Plan
53
+ ────────────────────────────
54
+ 👤 Age: {age}, Gender: {gender}
55
+ 💼 Occupation: {occupation}
56
+ 🏃 Activity Level: {activity_level}
57
+ ⚕️ Health Conditions: {health_conditions}
58
+ 🍽️ Preferences: {dietary_preferences}
59
+ ⚠️ Allergies: {allergies}
60
+ 💰 Budget: ₹{budget}/day
61
+
62
+ 🥣 Breakfast:
63
+ {breakfast}
64
+
65
+ 🍛 Lunch:
66
+ {lunch}
67
+
68
+ 🥗 Dinner:
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",
347
+ dietary_preferences=dietary_preferences or "None",
348
+ allergies=allergies or "None", budget=budget,
349
+ breakfast=breakfast, lunch=lunch, dinner=dinner
350
+ )
351
+
352
+ nutrition_summary = f"""
353
+ 🍽️ Nutritional Summary:
354
+ ------------------------------
355
+ 🔥 Calories: {nutrition['calories']} kcal
356
+ 🩸 Iron: {nutrition['iron']} mg
357
+ 🧬 Protein: {nutrition['protein']} g
358
+ 🌾 Fiber: {nutrition['fiber']} g
359
+ 🍊 Vitamin C: {nutrition['vitamin_c']} mg
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")
369
+ weight = gr.Number(label="Weight (kg)", value=70, minimum=1)
370
+ height = gr.Number(label="Height (cm)", value=170, minimum=1)
371
+ occupation = gr.Textbox(label="Occupation")
372
+ activity = gr.Radio(["Low", "Moderate", "High"], label="Activity Level")
373
+
374
+ with gr.Row():
375
+ health_audio = gr.Audio(label="🎤 Speak Health Conditions", type="filepath")
376
+ health_text = gr.Textbox(label="Or Type Health Conditions")
377
+ with gr.Row():
378
+ diet_audio = gr.Audio(label="🎤 Speak Dietary Preferences", type="filepath")
379
+ diet_text = gr.Textbox(label="Or Type Dietary Preferences")
380
+ with gr.Row():
381
+ allergy_audio = gr.Audio(label="🎤 Speak Allergies", type="filepath")
382
+ allergy_text = gr.Textbox(label="Or Type Allergies")
383
+
384
+ budget = gr.Number(label="Daily Budget (₹)", value=200, minimum=0)
385
+ output = gr.Textbox(label="Generated Diet Plan", lines=15)
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())