Files changed (1) hide show
  1. app.py +0 -181
app.py DELETED
@@ -1,181 +0,0 @@
1
- # app.py
2
-
3
- import os, random, wave, json, uuid, urllib.request, zipfile
4
- import gradio as gr
5
- from pydub import AudioSegment
6
- from vosk import Model, KaldiRecognizer
7
-
8
- # === Model Download ===
9
- MODEL_DIR = "vosk-model-small-en-us-0.15"
10
- MODEL_URL = "https://alphacephei.com/vosk/models/vosk-model-small-en-us-0.15.zip"
11
- MODEL_ZIP = "vosk-model-small-en-us-0.15.zip"
12
-
13
- if not os.path.exists(MODEL_DIR):
14
- print("🔽 Downloading Vosk model...")
15
- urllib.request.urlretrieve(MODEL_URL, MODEL_ZIP)
16
- with zipfile.ZipFile(MODEL_ZIP, "r") as zip_ref:
17
- zip_ref.extractall()
18
- print("✅ Model ready.")
19
-
20
- vosk_model = Model(MODEL_DIR)
21
-
22
- # === Vosk Transcription ===
23
- def transcribe_vosk(audio_path):
24
- try:
25
- if not audio_path or not os.path.exists(audio_path):
26
- return "❌ No audio file provided."
27
-
28
- temp_wav = f"converted_{uuid.uuid4().hex}.wav"
29
- audio = AudioSegment.from_file(audio_path)
30
- if len(audio) < 1000:
31
- return "⚠️ Please record at least 1 second."
32
-
33
- audio = audio.set_frame_rate(16000).set_channels(1).set_sample_width(2)
34
- audio.export(temp_wav, format="wav")
35
-
36
- wf = wave.open(temp_wav, "rb")
37
- rec = KaldiRecognizer(vosk_model, wf.getframerate())
38
- result = ""
39
-
40
- while True:
41
- data = wf.readframes(4000)
42
- if not data:
43
- break
44
- if rec.AcceptWaveform(data):
45
- result += json.loads(rec.Result()).get("text", "") + " "
46
-
47
- result += json.loads(rec.FinalResult()).get("text", "")
48
- wf.close()
49
- os.remove(temp_wav)
50
-
51
- return result.strip() or "⚠️ Speech not recognized clearly."
52
- except Exception as e:
53
- return f"❌ Error: {str(e)}"
54
-
55
- # === Diet Logic ===
56
- local_foods = {
57
- "vegetables": ["carrot", "tomato", "cucumber", "spinach", "beetroot"],
58
- "grains": ["rice", "wheat", "millet", "barley"],
59
- "proteins": ["lentils", "eggs", "chicken", "soybeans", "peas"]
60
- }
61
-
62
- def generate_diet(age, gender, weight, height, occupation, activity_level,
63
- health_conditions, dietary_preferences, allergies, budget):
64
- return f"""
65
- 🌿 Personalized Healthy Diet Plan 🌿
66
- ──────────────────────────────────────
67
- 👨‍🌾 Occupation: {occupation}
68
- ⚡ Activity Level: {activity_level}
69
- 💰 Daily Budget: ₹{budget}
70
-
71
- 🍽️ Meals for Today:
72
- 🥣 Breakfast: {random.choice(local_foods['grains'])} with {random.choice(local_foods['vegetables'])}
73
- 🍛 Lunch: {random.choice(local_foods['proteins'])} with {random.choice(local_foods['grains'])}
74
- 🥗 Dinner: {random.choice(local_foods['vegetables'])}, {random.choice(local_foods['vegetables'])} with {random.choice(local_foods['proteins'])}
75
-
76
- 🩺 Health Conditions: {health_conditions or 'None'}
77
- 🌱 Preferences: {dietary_preferences or 'None'}
78
- ⚠️ Allergies: {allergies or 'None'}
79
- """
80
-
81
- # === Translations ===
82
- translations = {
83
- "English": {
84
- "title": "🥗 Personalized Diet Generator (Voice Input)",
85
- "record_tip": "🎤 Record → Stop → Transcribe",
86
- "age": "Age", "gender": "Gender", "weight": "Weight (kg)", "height": "Height (cm)",
87
- "occupation": "Occupation", "activity": "Activity Level",
88
- "health_audio": "🩺 Speak Health Conditions", "diet_audio": "🥗 Speak Dietary Preferences",
89
- "allergy_audio": "⚠️ Speak Allergies", "health_text": "Recognized Health Conditions",
90
- "diet_text": "Recognized Dietary Preferences", "allergy_text": "Recognized Allergies",
91
- "transcribe_health": "Transcribe Health", "transcribe_diet": "Transcribe Preferences",
92
- "transcribe_allergy": "Transcribe Allergies", "budget": "Daily Budget (₹)",
93
- "generate": "Generate Diet Plan", "output": "Generated Diet Plan"
94
- },
95
- "Spanish": {
96
- "title": "🥗 Generador de Dieta Personalizada (Entrada por Voz)",
97
- "record_tip": "🎤 Grabar → Detener → Transcribir", "age": "Edad", "gender": "Género",
98
- "weight": "Peso (kg)", "height": "Altura (cm)", "occupation": "Ocupación",
99
- "activity": "Nivel de actividad", "health_audio": "🩺 Decir condiciones de salud",
100
- "diet_audio": "🥗 Decir preferencias dietéticas", "allergy_audio": "⚠️ Decir alergias",
101
- "health_text": "Condiciones reconocidas", "diet_text": "Preferencias reconocidas",
102
- "allergy_text": "Alergias reconocidas", "transcribe_health": "Transcribir salud",
103
- "transcribe_diet": "Transcribir preferencias", "transcribe_allergy": "Transcribir alergias",
104
- "budget": "Presupuesto diario (₹)", "generate": "Generar plan", "output": "Plan generado"
105
- },
106
- "Hindi": {
107
- "title": "🥗 व्यक्तिगत डाइट जनरेटर (वॉइस इनपुट)",
108
- "record_tip": "🎤 रिकॉर्ड करें → रुकें → ट्रांसक्राइब करें", "age": "आयु", "gender": "लि��ग",
109
- "weight": "वज़न (किग्रा)", "height": "ऊंचाई (सेमी)", "occupation": "पेशा",
110
- "activity": "गतिविधि स्तर", "health_audio": "🩺 स्वास्थ्य स्थिति बोलें",
111
- "diet_audio": "🥗 आहार वरीयताएँ बोलें", "allergy_audio": "⚠️ एलर्जी बोलें",
112
- "health_text": "पहचानी गई स्वास्थ्य स्थितियाँ", "diet_text": "पहचानी गई आहार वरीयताएँ",
113
- "allergy_text": "पहचानी गई एलर्जी", "transcribe_health": "स्वास्थ्य ट्रांसक्राइब करें",
114
- "transcribe_diet": "आहार ट्रांसक्राइब करें", "transcribe_allergy": "एलर्जी ट्रांसक्राइब करें",
115
- "budget": "दैनिक बजट (₹)", "generate": "डाइट प्लान बनाएं", "output": "बनाया गया डाइट प्लान"
116
- },
117
- "Telugu": {
118
- "title": "🥗 వ్యక్తిగత ఆహార ప్రణాళిక (వాయిస్ ఇన్పుట్)",
119
- "record_tip": "🎤 రికార్డ్ చేయండి → ఆపు → ట్రాన్స్‌క్రైబ్", "age": "వయస్సు", "gender": "లింగం",
120
- "weight": "బరువు (kg)", "height": "ఎత్తు (cm)", "occupation": "వృత్తి", "activity": "చర్య స్థాయి",
121
- "health_audio": "🩺 ఆరోగ్య పరిస్థితులు చెప్పండి", "diet_audio": "🥗 ఆహార అభిరుచులు చెప్పండి",
122
- "allergy_audio": "⚠️ అలర్జీలు చెప్పండి", "health_text": "ఆరోగ్య పరిస్థితులు గుర్తించబడ్డాయి",
123
- "diet_text": "ఆహార అభిరుచులు గుర్తించబడ్డాయి", "allergy_text": "అలర్జీలు గుర్తించబడ్డాయి",
124
- "transcribe_health": "హెల్త్ ట్రాన్స్‌క్రైబ్", "transcribe_diet": "డైట్ ట్రాన్స్‌క్రైబ్",
125
- "transcribe_allergy": "అలర్జీ ట్రాన్స్‌క్రైబ్", "budget": "రోజువారీ బడ్జెట్ (₹)",
126
- "generate": "ప్లాన్ రూపొందించండి", "output": "ఆహార ప్రణాళిక"
127
- }
128
- }
129
-
130
- # === UI ===
131
- def render_ui(language="English"):
132
- t = translations[language]
133
- with gr.Blocks() as demo:
134
- gr.Markdown(f"## {t['title']}")
135
- gr.Markdown(t["record_tip"])
136
-
137
- lang_sel = gr.Dropdown(list(translations.keys()), value=language, label="🌐 Language")
138
-
139
- with gr.Row():
140
- age = gr.Number(label=t["age"], value=30)
141
- gender = gr.Radio(["Male", "Female", "Other"], label=t["gender"])
142
- weight = gr.Number(label=t["weight"], value=70)
143
- height = gr.Number(label=t["height"], value=170)
144
-
145
- occupation = gr.Textbox(label=t["occupation"])
146
- activity_level = gr.Radio(["Low", "Medium", "High"], label=t["activity"], value="Medium")
147
-
148
- health_audio = gr.Audio(label=t["health_audio"], type="filepath")
149
- health_text = gr.Textbox(label=t["health_text"])
150
-
151
- diet_audio = gr.Audio(label=t["diet_audio"], type="filepath")
152
- diet_text = gr.Textbox(label=t["diet_text"])
153
-
154
- allergy_audio = gr.Audio(label=t["allergy_audio"], type="filepath")
155
- allergy_text = gr.Textbox(label=t["allergy_text"])
156
-
157
- with gr.Row():
158
- gr.Button(t["transcribe_health"]).click(transcribe_vosk, inputs=health_audio, outputs=health_text)
159
- gr.Button(t["transcribe_diet"]).click(transcribe_vosk, inputs=diet_audio, outputs=diet_text)
160
- gr.Button(t["transcribe_allergy"]).click(transcribe_vosk, inputs=allergy_audio, outputs=allergy_text)
161
-
162
- budget = gr.Number(label=t["budget"], value=200)
163
- output = gr.Textbox(label=t["output"], lines=20, show_copy_button=True)
164
-
165
- gr.Button(t["generate"]).click(
166
- generate_diet,
167
- inputs=[age, gender, weight, height, occupation, activity_level,
168
- health_text, diet_text, allergy_text, budget],
169
- outputs=output
170
- )
171
-
172
- def reload_lang(new_lang):
173
- return render_ui(new_lang)
174
-
175
- lang_sel.change(fn=reload_lang, inputs=lang_sel, outputs=None)
176
-
177
- return demo
178
-
179
- # === Launch ===
180
- if __name__ == "__main__":
181
- render_ui("English").launch(server_name="0.0.0.0", server_port=7860)