kxrthik05 commited on
Commit
ef8a9a4
·
verified ·
1 Parent(s): ffe21d4

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +307 -0
app.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # (Paste your full Gradio app.py code here)
2
+ !pip install -q gradio soundfile
3
+
4
+ import gradio as gr
5
+ from pathlib import Path
6
+
7
+ # Use your project brief path from the notebook
8
+ PROJECT_BRIEF_LOCAL = "/mnt/data/Project_description.pdf"
9
+
10
+
11
+ def normalize_audio_path(audio_file):
12
+ """Return a filesystem path (or None) from Gradio's audio input."""
13
+ if audio_file is None:
14
+ return None
15
+ if isinstance(audio_file, str):
16
+ return audio_file
17
+ if hasattr(audio_file, "name"):
18
+ return audio_file.name
19
+ if isinstance(audio_file, (tuple, list)) and len(audio_file) > 0:
20
+ # In some cases Gradio gives (filepath, ...other stuff)
21
+ return audio_file[0]
22
+ return str(audio_file)
23
+
24
+
25
+ # Extended cuisine map: starters / main / desserts, separated veg / non-veg
26
+ CUISINE_MAP = {
27
+ "kerala": {
28
+ "region": "Kerala",
29
+ "starters_veg": ["Banana Chips", "Vegetable Uzhunnu Vada"],
30
+ "starters_nonveg": ["Kerala Fish Fry", "Chicken 65 (Kerala Style)"],
31
+ "main_veg": ["Appam with Vegetable Stew", "Puttu with Kadala Curry"],
32
+ "main_nonveg": ["Kerala Fish Curry", "Beef Ularthiyathu", "Chicken Stew"],
33
+ "desserts": ["Palada Payasam", "Ada Pradhaman"],
34
+ },
35
+
36
+ "hindi": {
37
+ "region": "North India (Hindi-speaking belt)",
38
+ "starters_veg": ["Paneer Tikka", "Veg Samosa"],
39
+ "starters_nonveg": ["Chicken 65", "Mutton Seekh Kabab"],
40
+ "main_veg": ["Paneer Butter Masala", "Dal Makhani", "Aloo Paratha"],
41
+ "main_nonveg": ["Butter Chicken", "Rogan Josh", "Mutton Biryani"],
42
+ "desserts": ["Gulab Jamun", "Kheer"],
43
+ },
44
+
45
+ "telugu": {
46
+ "region": "Andhra / Telangana",
47
+ "starters_veg": ["Mirchi Bajji", "Pesarattu"],
48
+ "starters_nonveg": ["Gongura Chicken Fry", "Chepala Vepudu"],
49
+ "main_veg": ["Pappu (dal) with rice", "Pesara Pappu", "Gutti Vankaya"],
50
+ "main_nonveg": ["Andhra Chicken Biryani", "Kodi Pulusu (Chicken Curry)"],
51
+ "desserts": ["Bobbatlu (Puran Poli)", "Pootharekulu"],
52
+ },
53
+
54
+ "tamil": {
55
+ "region": "Tamil Nadu",
56
+ "starters_veg": ["Medu Vada", "Sundal"],
57
+ "starters_nonveg": ["Chicken 65 (TN style)", "Fish Fry"],
58
+ "main_veg": ["Idli & Sambar", "Masala Dosa", "Rasam Rice"],
59
+ "main_nonveg": ["Chettinad Chicken", "Fish Curry (Meen Kuzhambu)"],
60
+ "desserts": ["Payasam", "Kesari"],
61
+ },
62
+
63
+ "malayalam": {
64
+ "region": "Kerala",
65
+ "starters_veg": ["Banana Chips", "Vegetable Uzhunnu Vada"],
66
+ "starters_nonveg": ["Kerala Fish Fry", "Chicken 65 (Kerala)"],
67
+ "main_veg": ["Appam with Vegetable Stew", "Puttu and Kadala Curry"],
68
+ "main_nonveg": ["Kerala Fish Curry", "Beef Ularthiyathu", "Chicken Stew"],
69
+ "desserts": ["Palada Payasam", "Ada Pradhaman"],
70
+ },
71
+
72
+ "kannada": {
73
+ "region": "Karnataka",
74
+ "starters_veg": ["Maddur Vada", "Bonda"],
75
+ "starters_nonveg": ["Kheema Cutlet"],
76
+ "main_veg": ["Bisi Bele Bath", "Ragi Mudde", "Akki Roti"],
77
+ "main_nonveg": ["Mangalorean Chicken Curry", "Neer Dosa with Fish Curry"],
78
+ "desserts": ["Mysore Pak", "Kesari"],
79
+ },
80
+
81
+ "bengali": {
82
+ "region": "West Bengal",
83
+ "starters_veg": ["Vegetable Chop"],
84
+ "starters_nonveg": ["Fish Kabiraji", "Kolkata-style Chicken Pakora"],
85
+ "main_veg": ["Shukto", "Cholar Dal with Luchi"],
86
+ "main_nonveg": ["Machher Jhol (Fish Curry)", "Ilish Bhapa (Hilsa)"],
87
+ "desserts": ["Mishti Doi", "Rasgulla"],
88
+ },
89
+
90
+ # Jharkhand-specific mapping (use label "Jharkhand" -> "jharkhand")
91
+ "jharkhand": {
92
+ "region": "Jharkhand",
93
+ "starters_veg": ["Dhuska", "Chilka Roti"],
94
+ "starters_nonveg": ["Sohari Chicken Fry", "Kodo Chicken", "Jhal Murg"],
95
+ "main_veg": ["Thekua with Chana Sabzi", "Litti Chokha"],
96
+ "main_nonveg": [
97
+ "Chicken Jhol",
98
+ "Mutton with Kodo/Kutki Millet",
99
+ "Bamboo Shoot Chicken",
100
+ ],
101
+ "desserts": ["Dudh Pitha", "Gur ki Roti"],
102
+ },
103
+
104
+ "gujarati": {
105
+ "region": "Gujarat",
106
+ "starters_veg": ["Dhokla", "Khandvi"],
107
+ "starters_nonveg": ["(Typically veg cuisine; pick local non-veg if needed)"],
108
+ "main_veg": ["Undhiyu", "Khichdi", "Thepla"],
109
+ "main_nonveg": ["(Typically veg cuisine; pick local non-veg if needed)"],
110
+ "desserts": ["Basundi", "Shrikhand"],
111
+ },
112
+
113
+ # default fallback
114
+ "default": {
115
+ "region": "Unknown / Other",
116
+ "starters_veg": ["Local vegetarian starters"],
117
+ "starters_nonveg": ["Local non-veg starters"],
118
+ "main_veg": ["Local vegetarian mains"],
119
+ "main_nonveg": ["Local non-veg mains"],
120
+ "desserts": ["Local desserts"],
121
+ },
122
+ }
123
+
124
+ # NEW: map HuBERT / MFCC labels (state names etc.) to cuisine keys above
125
+ LABEL_ALIAS = {
126
+ # Andhra / Telangana
127
+ "andhra_pradesh": "telugu",
128
+ "ap": "telugu",
129
+ "andhra": "telugu",
130
+ "telugu": "telugu",
131
+ "telangana": "telugu",
132
+
133
+ # Kerala
134
+ "kerala": "kerala",
135
+ "malayalam": "malayalam",
136
+
137
+ # Tamil Nadu
138
+ "tamil_nadu": "tamil",
139
+ "tamil": "tamil",
140
+
141
+ # Karnataka
142
+ "karnataka": "kannada",
143
+ "kannada": "kannada",
144
+
145
+ # Jharkhand
146
+ "jharkhand": "jharkhand",
147
+ "jharkhand_state": "jharkhand",
148
+
149
+ # Gujarat
150
+ "gujarat": "gujarati",
151
+ "gujarati": "gujarati",
152
+
153
+ # West Bengal
154
+ "west_bengal": "bengali",
155
+ "bengal": "bengali",
156
+ "bengali": "bengali",
157
+
158
+ # North India / Hindi belt
159
+ "hindi": "hindi",
160
+ "north_india": "hindi",
161
+ "delhi": "hindi",
162
+ }
163
+
164
+
165
+ def format_cuisine_output(pred_label: str) -> str:
166
+ """Format cuisine recommendations as a readable multiline string."""
167
+ key = pred_label.lower().strip()
168
+ key = key.replace(" ", "_") # handle "Andhra Pradesh" → "andhra_pradesh"
169
+ key = LABEL_ALIAS.get(key, key) # map state-style labels → cuisine keys
170
+
171
+ info = CUISINE_MAP.get(key, CUISINE_MAP["default"])
172
+
173
+ lines = []
174
+ lines.append(f"Inferred region: {info['region']}")
175
+ lines.append("")
176
+ lines.append("Starters (Veg): " + ", ".join(info["starters_veg"]))
177
+ lines.append("Starters (Non-Veg): " + ", ".join(info["starters_nonveg"]))
178
+ lines.append("")
179
+ lines.append("Main Course (Veg): " + ", ".join(info["main_veg"]))
180
+ lines.append("Main Course (Non-Veg): " + ", ".join(info["main_nonveg"]))
181
+ lines.append("")
182
+ lines.append("Desserts: " + ", ".join(info["desserts"]))
183
+ return "\n".join(lines)
184
+
185
+
186
+ def ui_predict_multi(audio_file, feature_choice, hubert_layer_idx, use_trained_model):
187
+ """Main function used by Gradio UI."""
188
+ audio_path = normalize_audio_path(audio_file)
189
+ if audio_path is None:
190
+ return "No audio provided", ""
191
+
192
+ feat = "hubert" if feature_choice == "HuBERT" else "mfcc"
193
+
194
+ # If using trained model, pick the correct model info
195
+ if use_trained_model:
196
+ model_info = app_state.get("models", {}).get(feat)
197
+ if not model_info:
198
+ return (
199
+ f"No trained {feat.upper()} model available on server. "
200
+ "Train it or uncheck 'Use trained model'.",
201
+ "",
202
+ )
203
+
204
+ clf = model_info["clf"]
205
+ scaler = model_info["scaler"]
206
+ le = model_info["le"]
207
+
208
+ if feat == "hubert" and hubert_layer_idx != model_info.get(
209
+ "layer", hubert_layer_idx
210
+ ):
211
+ return (
212
+ f"Note: the HuBERT model was trained on layer "
213
+ f"{model_info.get('layer')}. Set the slider to that layer or re-train.",
214
+ "",
215
+ )
216
+ else:
217
+ # Fallback path: only MFCC fallback is implemented
218
+ if feat != "mfcc":
219
+ return (
220
+ "Fallback training is only available for MFCC. "
221
+ "Choose MFCC or upload HuBERT artifacts.",
222
+ "",
223
+ )
224
+
225
+ # Try to train a quick MFCC model using local data/ folder
226
+ wav_paths = []
227
+ if Path("data").exists():
228
+ wav_paths = [str(p) for p in Path("data").rglob("*.wav")]
229
+
230
+ model_info = train_fast_mfcc_fallback(wav_paths[:200])
231
+ if model_info is None:
232
+ return (
233
+ "No fallback MFCC model could be trained (not enough data). "
234
+ "Upload model artifacts or provide a data/ folder.",
235
+ "",
236
+ )
237
+
238
+ clf = model_info["clf"]
239
+ scaler = model_info["scaler"]
240
+ le = model_info["le"]
241
+
242
+ # Extract features
243
+ try:
244
+ if feat == "mfcc":
245
+ x = extract_mfcc_pooled(audio_path)
246
+ else:
247
+ x = get_hubert_layer_embedding(audio_path, layer_idx=hubert_layer_idx)
248
+ except Exception as e:
249
+ return f"Feature extraction failed: {e}", ""
250
+
251
+ # Predict
252
+ try:
253
+ Xs = scaler.transform(x.reshape(1, -1))
254
+ pred_idx = clf.predict(Xs)[0]
255
+ pred_label = le.inverse_transform([pred_idx])[0]
256
+ except Exception as e:
257
+ return f"Prediction failed (shape mismatch or model error): {e}", ""
258
+
259
+ # Format cuisine recommendations
260
+ cuisine_text = format_cuisine_output(pred_label)
261
+ return pred_label, cuisine_text
262
+
263
+
264
+ # Build Gradio UI
265
+ with gr.Blocks() as demo:
266
+ gr.Markdown("## Accent Detection + Cuisine Recommendation Demo")
267
+ gr.Markdown(f"[📄 Open Project Brief]({PROJECT_BRIEF_LOCAL})")
268
+
269
+ with gr.Row():
270
+ audio_in = gr.Audio(
271
+ type="filepath",
272
+ label="Upload audio (.wav/.flac/.mp3)",
273
+ )
274
+
275
+ with gr.Column():
276
+ feature_choice = gr.Radio(
277
+ ["MFCC", "HuBERT"],
278
+ value="MFCC",
279
+ label="Feature Type",
280
+ )
281
+ hubert_layer_idx = gr.Slider(
282
+ minimum=0,
283
+ maximum=24,
284
+ value=11,
285
+ step=1,
286
+ label="HuBERT Layer",
287
+ )
288
+ use_trained_model = gr.Checkbox(
289
+ value=True,
290
+ label="Use trained model from notebook",
291
+ )
292
+ btn = gr.Button("Predict & Recommend")
293
+
294
+ output_label = gr.Textbox(label="Predicted Accent")
295
+ output_cuisines = gr.Textbox(
296
+ label="Recommended Cuisines (starters, mains, desserts separated)",
297
+ lines=12,
298
+ )
299
+
300
+ btn.click(
301
+ ui_predict_multi,
302
+ inputs=[audio_in, feature_choice, hubert_layer_idx, use_trained_model],
303
+ outputs=[output_label, output_cuisines],
304
+ )
305
+
306
+ demo.launch(share=True)
307
+