janasumit2911 commited on
Commit
30676d6
·
verified ·
1 Parent(s): f34383d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +212 -75
app.py CHANGED
@@ -1,3 +1,4 @@
 
1
  # import os
2
  # import tensorflow as tf
3
  # import tensorflow_hub as hub
@@ -133,8 +134,6 @@
133
 
134
 
135
 
136
-
137
-
138
  import os
139
  import tensorflow as tf
140
  import tensorflow_hub as hub
@@ -142,24 +141,14 @@ import numpy as np
142
  import csv
143
  import requests
144
  import json
145
- import scipy
146
  from scipy.io import wavfile
147
  from pydub import AudioSegment
148
- import gradio as gr
149
  import io
150
  from io import BytesIO
151
- import soundfile as sf
152
- import warnings
153
- import logging
154
-
155
- # Suppress specific warnings
156
- warnings.filterwarnings("ignore", category=scipy.io.wavfile.WavFileWarning)
157
-
158
- # Configure logging
159
- logging.basicConfig(level=logging.INFO) # Set logging level as needed
160
 
161
  # Load the model
162
- model = hub.load('https://tfhub.dev/google/yamnet/1')
163
 
164
  def class_names_from_csv(class_map_csv_text):
165
  """Returns list of class names corresponding to score vector."""
@@ -176,7 +165,7 @@ class_names = class_names_from_csv(class_map_path)
176
  def ensure_sample_rate(original_sample_rate, waveform, desired_sample_rate=16000):
177
  if original_sample_rate != desired_sample_rate: # Resample waveform if required
178
  desired_length = int(round(float(len(waveform)) / original_sample_rate * desired_sample_rate))
179
- waveform = scipy.signal.resample(waveform, desired_length)
180
  return desired_sample_rate, waveform
181
 
182
  def convert_mp3_to_wav(mp3_data):
@@ -184,54 +173,54 @@ def convert_mp3_to_wav(mp3_data):
184
  wav_buffer = io.BytesIO()
185
  audio.export(wav_buffer, format='wav')
186
  wav_buffer.seek(0)
187
- return wav_buffer
188
 
189
  def process_audio_file(file_data, url):
190
  try:
191
  sample_rate, wav_data = wavfile.read(BytesIO(file_data))
192
- except Exception as e:
193
- logging.error(f"Error reading WAV file from {url}: {e}")
194
- return
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
195
 
196
- if wav_data.ndim > 1:
197
- wav_data = np.mean(wav_data, axis=1)
198
- sample_rate, wav_data = ensure_sample_rate(sample_rate, wav_data)
199
-
200
- waveform = wav_data / tf.int16.max
201
-
202
- scores, embeddings, spectrogram = model(waveform)
203
-
204
- scores_np = scores.numpy()
205
- mean_scores = np.mean(scores, axis=0)
206
-
207
- inferred_class = class_names[mean_scores.argmax()]
208
-
209
- confidence_threshold = 0.60
210
- confident_classes = set()
211
-
212
- exclusion_list = ['Mechanisms','Domestic animals, pets', 'Animal', 'Silence', 'Alarm', 'Wind chime', 'Water', 'Livestock, farm animals, working animals', 'Wild animals', 'Bleat', 'Siren', 'Computer keyboard', 'Toot', 'Shatter', 'Bird','Caw', 'Independent music', 'Tender music', 'Ocean', 'House music', 'Middle Eastern music', 'Swing music', 'Soul music', 'Shofar', 'Motor vehicle (road)', 'White noise','Pink noise', 'Cacophony', 'Sidetone', 'Static', 'Outside, rural or natural', 'Outside, urban or manmade', 'Inside, public space', 'Inside, large room or hall', 'Inside, small room', 'Sound effect']
213
- for frame_scores in scores_np:
214
- for i, score in enumerate(frame_scores):
215
- if score > confidence_threshold:
216
- class_name = class_names[i]
217
-
218
- if class_name =='Child speech, kid speaking':
219
- class_name='Child speech'
220
- elif class_name =='Vehicle horn, car horn, honking':
221
- class_name='Vehicle horn'
222
- elif class_name =='Railroad car, train wagon':
223
- class_name='Train/wagon'
224
- elif class_name=='Rail transport':
225
- class_name='Train/wagon'
226
-
227
- if class_name not in exclusion_list:
228
- confident_classes.add(class_name)
229
-
230
- confident_classes = sorted(confident_classes)
231
-
232
- answer_dict= {}
233
- answer_dict.update({'file_name': url, 'class_names': confident_classes}) #os.path.basename(file_path
234
- solutions.append(answer_dict)
235
 
236
  def get_audio_data(url):
237
  response = requests.get(url)
@@ -250,30 +239,24 @@ def process_audio(params):
250
 
251
  solutions = []
252
  for audio_url in audio_files:
253
- try:
254
- audio_data = get_audio_data(audio_url)
255
 
256
- if audio_url.endswith(".mp3"):
257
- wav_buffer = convert_mp3_to_wav(audio_data)
258
- process_audio_file(wav_buffer.getvalue(), audio_url)
259
 
260
- elif audio_url.endswith(".wav"):
261
- process_audio_file(audio_data, audio_url)
262
- except Exception as e:
263
- logging.error(f"Error processing {audio_url}: {e}")
 
264
 
265
  result_url = f"{api}/{job_id}"
266
  response = requests.patch(result_url, json={"solutions": solutions})
267
 
268
- return json.dumps({"solutions": solutions}, indent=4)
269
 
270
- def send_results_to_api(data, result_url):
271
- headers = {"Content-Type": "application/json"}
272
- response = requests.patch(result_url, json=data, headers=headers)
273
- if response.status_code == 200:
274
- return response.json() # Return any response from the API if needed
275
- else:
276
- return {"error": f"Failed to send results to API: {response.status_code}"}
277
 
278
  inputt = gr.Textbox(label="Parameters (JSON format) Eg. {'audio_files':['file1.mp3','file2.wav'], 'api':'https://api.example.com', 'job_id':'12345'}")
279
  outputs = gr.JSON()
@@ -288,6 +271,160 @@ application.launch()
288
 
289
 
290
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
291
  # import os
292
  # import tensorflow as tf
293
  # import tensorflow_hub as hub
 
1
+ #1
2
  # import os
3
  # import tensorflow as tf
4
  # import tensorflow_hub as hub
 
134
 
135
 
136
 
 
 
137
  import os
138
  import tensorflow as tf
139
  import tensorflow_hub as hub
 
141
  import csv
142
  import requests
143
  import json
144
+ import logging
145
  from scipy.io import wavfile
146
  from pydub import AudioSegment
 
147
  import io
148
  from io import BytesIO
 
 
 
 
 
 
 
 
 
149
 
150
  # Load the model
151
+ model = hub.load('Audio_Multiple_v1')
152
 
153
  def class_names_from_csv(class_map_csv_text):
154
  """Returns list of class names corresponding to score vector."""
 
165
  def ensure_sample_rate(original_sample_rate, waveform, desired_sample_rate=16000):
166
  if original_sample_rate != desired_sample_rate: # Resample waveform if required
167
  desired_length = int(round(float(len(waveform)) / original_sample_rate * desired_sample_rate))
168
+ waveform = np.array(scipy.signal.resample(waveform, desired_length), dtype=np.float32)
169
  return desired_sample_rate, waveform
170
 
171
  def convert_mp3_to_wav(mp3_data):
 
173
  wav_buffer = io.BytesIO()
174
  audio.export(wav_buffer, format='wav')
175
  wav_buffer.seek(0)
176
+ return wav_buffer.getvalue()
177
 
178
  def process_audio_file(file_data, url):
179
  try:
180
  sample_rate, wav_data = wavfile.read(BytesIO(file_data))
181
+
182
+ if wav_data.ndim > 1:
183
+ wav_data = np.mean(wav_data, axis=1)
184
+ sample_rate, wav_data = ensure_sample_rate(sample_rate, wav_data)
185
+
186
+ waveform = wav_data / tf.int16.max
187
+
188
+ scores, embeddings, spectrogram = model(waveform)
189
+
190
+ scores_np = scores.numpy()
191
+ mean_scores = np.mean(scores, axis=0)
192
+
193
+ inferred_class = class_names[mean_scores.argmax()]
194
+
195
+ confidence_threshold = 0.60
196
+ confident_classes = set()
197
+
198
+ exclusion_list = ['Mechanisms','Domestic animals, pets', 'Animal', 'Silence', 'Alarm', 'Wind chime', 'Water', 'Livestock, farm animals, working animals', 'Wild animals', 'Bleat', 'Siren', 'Computer keyboard', 'Toot', 'Shatter', 'Bird','Caw', 'Independent music', 'Tender music', 'Ocean', 'House music', 'Middle Eastern music', 'Swing music', 'Soul music', 'Shofar', 'Motor vehicle (road)', 'White noise','Pink noise', 'Cacophony', 'Sidetone', 'Static', 'Outside, rural or natural', 'Outside, urban or manmade', 'Inside, public space', 'Inside, large room or hall', 'Inside, small room', 'Sound effect']
199
+ for frame_scores in scores_np:
200
+ for i, score in enumerate(frame_scores):
201
+ if score > confidence_threshold:
202
+ class_name = class_names[i]
203
+
204
+ if class_name =='Child speech, kid speaking':
205
+ class_name='Child speech'
206
+ elif class_name =='Vehicle horn, car horn, honking':
207
+ class_name='Vehicle horn'
208
+ elif class_name =='Railroad car, train wagon':
209
+ class_name='Train/wagon'
210
+ elif class_name=='Rail transport':
211
+ class_name='Train/wagon'
212
+
213
+ if class_name not in exclusion_list:
214
+ confident_classes.add(class_name)
215
+
216
+ confident_classes = sorted(confident_classes)
217
+
218
+ answer_dict = {'file_name': url, 'class_names': confident_classes}
219
+ return answer_dict
220
 
221
+ except Exception as e:
222
+ logging.error(f"Error processing {url}: {e}")
223
+ return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
 
225
  def get_audio_data(url):
226
  response = requests.get(url)
 
239
 
240
  solutions = []
241
  for audio_url in audio_files:
242
+ audio_data = get_audio_data(audio_url)
 
243
 
244
+ if audio_url.endswith(".mp3"):
245
+ wav_data = convert_mp3_to_wav(audio_data)
246
+ result = process_audio_file(wav_data, audio_url)
247
 
248
+ elif audio_url.endswith(".wav"):
249
+ result = process_audio_file(audio_data, audio_url)
250
+
251
+ if result:
252
+ solutions.append(result)
253
 
254
  result_url = f"{api}/{job_id}"
255
  response = requests.patch(result_url, json={"solutions": solutions})
256
 
257
+ return {"solutions": solutions}
258
 
259
+ import gradio as gr
 
 
 
 
 
 
260
 
261
  inputt = gr.Textbox(label="Parameters (JSON format) Eg. {'audio_files':['file1.mp3','file2.wav'], 'api':'https://api.example.com', 'job_id':'12345'}")
262
  outputs = gr.JSON()
 
271
 
272
 
273
 
274
+ # import os
275
+ # import tensorflow as tf
276
+ # import tensorflow_hub as hub
277
+ # import numpy as np
278
+ # import csv
279
+ # import requests
280
+ # import json
281
+ # import scipy
282
+ # from scipy.io import wavfile
283
+ # from pydub import AudioSegment
284
+ # import gradio as gr
285
+ # import io
286
+ # from io import BytesIO
287
+ # import soundfile as sf
288
+ # import warnings
289
+ # import logging
290
+
291
+ # # Suppress specific warnings
292
+ # warnings.filterwarnings("ignore", category=scipy.io.wavfile.WavFileWarning)
293
+
294
+ # # Configure logging
295
+ # logging.basicConfig(level=logging.INFO) # Set logging level as needed
296
+
297
+ # # Load the model
298
+ # model = hub.load('https://tfhub.dev/google/yamnet/1')
299
+
300
+ # def class_names_from_csv(class_map_csv_text):
301
+ # """Returns list of class names corresponding to score vector."""
302
+ # class_names = []
303
+ # with tf.io.gfile.GFile(class_map_csv_text) as csvfile:
304
+ # reader = csv.DictReader(csvfile)
305
+ # for row in reader:
306
+ # class_names.append(row['display_name'])
307
+ # return class_names
308
+
309
+ # class_map_path = model.class_map_path().numpy()
310
+ # class_names = class_names_from_csv(class_map_path)
311
+
312
+ # def ensure_sample_rate(original_sample_rate, waveform, desired_sample_rate=16000):
313
+ # if original_sample_rate != desired_sample_rate: # Resample waveform if required
314
+ # desired_length = int(round(float(len(waveform)) / original_sample_rate * desired_sample_rate))
315
+ # waveform = scipy.signal.resample(waveform, desired_length)
316
+ # return desired_sample_rate, waveform
317
+
318
+ # def convert_mp3_to_wav(mp3_data):
319
+ # audio = AudioSegment.from_file(io.BytesIO(mp3_data), format="mp3")
320
+ # wav_buffer = io.BytesIO()
321
+ # audio.export(wav_buffer, format='wav')
322
+ # wav_buffer.seek(0)
323
+ # return wav_buffer
324
+
325
+ # def process_audio_file(file_data, url):
326
+ # try:
327
+ # sample_rate, wav_data = wavfile.read(BytesIO(file_data))
328
+ # except Exception as e:
329
+ # logging.error(f"Error reading WAV file from {url}: {e}")
330
+ # return
331
+
332
+ # if wav_data.ndim > 1:
333
+ # wav_data = np.mean(wav_data, axis=1)
334
+ # sample_rate, wav_data = ensure_sample_rate(sample_rate, wav_data)
335
+
336
+ # waveform = wav_data / tf.int16.max
337
+
338
+ # scores, embeddings, spectrogram = model(waveform)
339
+
340
+ # scores_np = scores.numpy()
341
+ # mean_scores = np.mean(scores, axis=0)
342
+
343
+ # inferred_class = class_names[mean_scores.argmax()]
344
+
345
+ # confidence_threshold = 0.60
346
+ # confident_classes = set()
347
+
348
+ # exclusion_list = ['Mechanisms','Domestic animals, pets', 'Animal', 'Silence', 'Alarm', 'Wind chime', 'Water', 'Livestock, farm animals, working animals', 'Wild animals', 'Bleat', 'Siren', 'Computer keyboard', 'Toot', 'Shatter', 'Bird','Caw', 'Independent music', 'Tender music', 'Ocean', 'House music', 'Middle Eastern music', 'Swing music', 'Soul music', 'Shofar', 'Motor vehicle (road)', 'White noise','Pink noise', 'Cacophony', 'Sidetone', 'Static', 'Outside, rural or natural', 'Outside, urban or manmade', 'Inside, public space', 'Inside, large room or hall', 'Inside, small room', 'Sound effect']
349
+ # for frame_scores in scores_np:
350
+ # for i, score in enumerate(frame_scores):
351
+ # if score > confidence_threshold:
352
+ # class_name = class_names[i]
353
+
354
+ # if class_name =='Child speech, kid speaking':
355
+ # class_name='Child speech'
356
+ # elif class_name =='Vehicle horn, car horn, honking':
357
+ # class_name='Vehicle horn'
358
+ # elif class_name =='Railroad car, train wagon':
359
+ # class_name='Train/wagon'
360
+ # elif class_name=='Rail transport':
361
+ # class_name='Train/wagon'
362
+
363
+ # if class_name not in exclusion_list:
364
+ # confident_classes.add(class_name)
365
+
366
+ # confident_classes = sorted(confident_classes)
367
+
368
+ # answer_dict= {}
369
+ # answer_dict.update({'file_name': url, 'class_names': confident_classes}) #os.path.basename(file_path
370
+ # solutions.append(answer_dict)
371
+ # return solutions
372
+
373
+ # def get_audio_data(url):
374
+ # response = requests.get(url)
375
+ # response.raise_for_status()
376
+ # return response.content
377
+
378
+ # def process_audio(params):
379
+ # try:
380
+ # params = json.loads(params)
381
+ # except json.JSONDecodeError as e:
382
+ # return {"error": f"Invalid JSON input: {e.msg} at line {e.lineno} column {e.colno}"}
383
+
384
+ # audio_files = params.get("audio_files", [])
385
+ # api = params.get("api", "")
386
+ # job_id = params.get("job_id", "")
387
+
388
+ # solutions = []
389
+ # for audio_url in audio_files:
390
+ # try:
391
+ # audio_data = get_audio_data(audio_url)
392
+
393
+ # if audio_url.endswith(".mp3"):
394
+ # wav_buffer = convert_mp3_to_wav(audio_data)
395
+ # process_audio_file(wav_buffer.getvalue(), audio_url)
396
+
397
+ # elif audio_url.endswith(".wav"):
398
+ # process_audio_file(audio_data, audio_url)
399
+ # except Exception as e:
400
+ # logging.error(f"Error processing {audio_url}: {e}")
401
+
402
+ # result_url = f"{api}/{job_id}"
403
+ # response = requests.patch(result_url, json={"solutions": solutions})
404
+
405
+ # return json.dumps({"solutions": solutions}, indent=4)
406
+
407
+ # def send_results_to_api(data, result_url):
408
+ # headers = {"Content-Type": "application/json"}
409
+ # response = requests.patch(result_url, json=data, headers=headers)
410
+ # if response.status_code == 200:
411
+ # return response.json() # Return any response from the API if needed
412
+ # else:
413
+ # return {"error": f"Failed to send results to API: {response.status_code}"}
414
+
415
+ # inputt = gr.Textbox(label="Parameters (JSON format) Eg. {'audio_files':['file1.mp3','file2.wav'], 'api':'https://api.example.com', 'job_id':'12345'}")
416
+ # outputs = gr.JSON()
417
+
418
+ # application = gr.Interface(fn=process_audio, inputs=inputt, outputs=outputs, title="Audio Classification with API Integration")
419
+ # application.launch()
420
+
421
+
422
+
423
+
424
+
425
+
426
+
427
+
428
  # import os
429
  # import tensorflow as tf
430
  # import tensorflow_hub as hub