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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +167 -11
app.py CHANGED
@@ -1,3 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import tensorflow as tf
3
  import tensorflow_hub as hub
@@ -12,10 +149,18 @@ import gradio as gr
12
  import io
13
  from io import BytesIO
14
  import soundfile as sf
 
 
 
 
 
 
 
 
15
 
16
  # Load the model
17
- model = hub.load('Audio_Multiple_v1')
18
- solutions=[]
19
  def class_names_from_csv(class_map_csv_text):
20
  """Returns list of class names corresponding to score vector."""
21
  class_names = []
@@ -42,7 +187,11 @@ def convert_mp3_to_wav(mp3_data):
42
  return wav_buffer
43
 
44
  def process_audio_file(file_data, url):
45
- sample_rate, wav_data = wavfile.read(BytesIO(file_data))
 
 
 
 
46
 
47
  if wav_data.ndim > 1:
48
  wav_data = np.mean(wav_data, axis=1)
@@ -60,8 +209,7 @@ def process_audio_file(file_data, url):
60
  confidence_threshold = 0.60
61
  confident_classes = set()
62
 
63
-
64
- 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' ]
65
  for frame_scores in scores_np:
66
  for i, score in enumerate(frame_scores):
67
  if score > confidence_threshold:
@@ -102,14 +250,17 @@ def process_audio(params):
102
 
103
  solutions = []
104
  for audio_url in audio_files:
105
- audio_data = get_audio_data(audio_url)
 
106
 
107
- if audio_url.endswith(".mp3"):
108
- wav_buffer = convert_mp3_to_wav(audio_data)
109
- process_audio_file(wav_buffer.getvalue(), audio_url)
110
 
111
- elif audio_url.endswith(".wav"):
112
- process_audio_file(audio_data, audio_url)
 
 
113
 
114
  result_url = f"{api}/{job_id}"
115
  response = requests.patch(result_url, json={"solutions": solutions})
@@ -132,6 +283,11 @@ application.launch()
132
 
133
 
134
 
 
 
 
 
 
135
  # import os
136
  # import tensorflow as tf
137
  # import tensorflow_hub as hub
 
1
+ # import os
2
+ # import tensorflow as tf
3
+ # import tensorflow_hub as hub
4
+ # import numpy as np
5
+ # import csv
6
+ # import requests
7
+ # import json
8
+ # import scipy
9
+ # from scipy.io import wavfile
10
+ # from pydub import AudioSegment
11
+ # import gradio as gr
12
+ # import io
13
+ # from io import BytesIO
14
+ # import soundfile as sf
15
+
16
+ # # Load the model
17
+ # model = hub.load('Audio_Multiple_v1')
18
+ # solutions=[]
19
+ # def class_names_from_csv(class_map_csv_text):
20
+ # """Returns list of class names corresponding to score vector."""
21
+ # class_names = []
22
+ # with tf.io.gfile.GFile(class_map_csv_text) as csvfile:
23
+ # reader = csv.DictReader(csvfile)
24
+ # for row in reader:
25
+ # class_names.append(row['display_name'])
26
+ # return class_names
27
+
28
+ # class_map_path = model.class_map_path().numpy()
29
+ # class_names = class_names_from_csv(class_map_path)
30
+
31
+ # def ensure_sample_rate(original_sample_rate, waveform, desired_sample_rate=16000):
32
+ # if original_sample_rate != desired_sample_rate: # Resample waveform if required
33
+ # desired_length = int(round(float(len(waveform)) / original_sample_rate * desired_sample_rate))
34
+ # waveform = scipy.signal.resample(waveform, desired_length)
35
+ # return desired_sample_rate, waveform
36
+
37
+ # def convert_mp3_to_wav(mp3_data):
38
+ # audio = AudioSegment.from_file(io.BytesIO(mp3_data), format="mp3")
39
+ # wav_buffer = io.BytesIO()
40
+ # audio.export(wav_buffer, format='wav')
41
+ # wav_buffer.seek(0)
42
+ # return wav_buffer
43
+
44
+ # def process_audio_file(file_data, url):
45
+ # sample_rate, wav_data = wavfile.read(BytesIO(file_data))
46
+
47
+ # if wav_data.ndim > 1:
48
+ # wav_data = np.mean(wav_data, axis=1)
49
+ # sample_rate, wav_data = ensure_sample_rate(sample_rate, wav_data)
50
+
51
+ # waveform = wav_data / tf.int16.max
52
+
53
+ # scores, embeddings, spectrogram = model(waveform)
54
+
55
+ # scores_np = scores.numpy()
56
+ # mean_scores = np.mean(scores, axis=0)
57
+
58
+ # inferred_class = class_names[mean_scores.argmax()]
59
+
60
+ # confidence_threshold = 0.60
61
+ # confident_classes = set()
62
+
63
+
64
+ # 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' ]
65
+ # for frame_scores in scores_np:
66
+ # for i, score in enumerate(frame_scores):
67
+ # if score > confidence_threshold:
68
+ # class_name = class_names[i]
69
+
70
+ # if class_name =='Child speech, kid speaking':
71
+ # class_name='Child speech'
72
+ # elif class_name =='Vehicle horn, car horn, honking':
73
+ # class_name='Vehicle horn'
74
+ # elif class_name =='Railroad car, train wagon':
75
+ # class_name='Train/wagon'
76
+ # elif class_name=='Rail transport':
77
+ # class_name='Train/wagon'
78
+
79
+ # if class_name not in exclusion_list:
80
+ # confident_classes.add(class_name)
81
+
82
+ # confident_classes = sorted(confident_classes)
83
+
84
+ # answer_dict= {}
85
+ # answer_dict.update({'file_name': url, 'class_names': confident_classes}) #os.path.basename(file_path
86
+ # solutions.append(answer_dict)
87
+
88
+ # def get_audio_data(url):
89
+ # response = requests.get(url)
90
+ # response.raise_for_status()
91
+ # return response.content
92
+
93
+ # def process_audio(params):
94
+ # try:
95
+ # params = json.loads(params)
96
+ # except json.JSONDecodeError as e:
97
+ # return {"error": f"Invalid JSON input: {e.msg} at line {e.lineno} column {e.colno}"}
98
+
99
+ # audio_files = params.get("audio_files", [])
100
+ # api = params.get("api", "")
101
+ # job_id = params.get("job_id", "")
102
+
103
+ # solutions = []
104
+ # for audio_url in audio_files:
105
+ # audio_data = get_audio_data(audio_url)
106
+
107
+ # if audio_url.endswith(".mp3"):
108
+ # wav_buffer = convert_mp3_to_wav(audio_data)
109
+ # process_audio_file(wav_buffer.getvalue(), audio_url)
110
+
111
+ # elif audio_url.endswith(".wav"):
112
+ # process_audio_file(audio_data, audio_url)
113
+
114
+ # result_url = f"{api}/{job_id}"
115
+ # response = requests.patch(result_url, json={"solutions": solutions})
116
+
117
+ # return json.dumps({"solutions": solutions}, indent=4)
118
+
119
+ # def send_results_to_api(data, result_url):
120
+ # headers = {"Content-Type": "application/json"}
121
+ # response = requests.patch(result_url, json=data, headers=headers)
122
+ # if response.status_code == 200:
123
+ # return response.json() # Return any response from the API if needed
124
+ # else:
125
+ # return {"error": f"Failed to send results to API: {response.status_code}"}
126
+
127
+ # inputt = gr.Textbox(label="Parameters (JSON format) Eg. {'audio_files':['file1.mp3','file2.wav'], 'api':'https://api.example.com', 'job_id':'12345'}")
128
+ # outputs = gr.JSON()
129
+
130
+ # application = gr.Interface(fn=process_audio, inputs=inputt, outputs=outputs, title="Audio Classification with API Integration")
131
+ # application.launch()
132
+
133
+
134
+
135
+
136
+
137
+
138
  import os
139
  import tensorflow as tf
140
  import tensorflow_hub as hub
 
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."""
166
  class_names = []
 
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)
 
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:
 
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})
 
283
 
284
 
285
 
286
+
287
+
288
+
289
+
290
+
291
  # import os
292
  # import tensorflow as tf
293
  # import tensorflow_hub as hub