janasumit2911 commited on
Commit
c2aa6b9
·
verified ·
1 Parent(s): 8076355

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +149 -7
app.py CHANGED
@@ -1,3 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import tensorflow as tf
3
  import tensorflow_hub as hub
@@ -5,16 +139,16 @@ 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
 
19
  def class_names_from_csv(class_map_csv_text):
20
  """Returns list of class names corresponding to score vector."""
@@ -35,9 +169,18 @@ def ensure_sample_rate(original_sample_rate, waveform, desired_sample_rate=16000
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
 
@@ -60,7 +203,6 @@ def process_audio_file(file_data, url):
60
  confidence_threshold = 0.60
61
  confident_classes = set()
62
 
63
- solutions=[]
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):
 
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
+
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
+ # solutions=[]
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
  import os
136
  import tensorflow as tf
137
  import tensorflow_hub as hub
 
139
  import csv
140
  import requests
141
  import json
 
142
  from scipy.io import wavfile
 
143
  import gradio as gr
144
  import io
145
  from io import BytesIO
146
  import soundfile as sf
147
+ import scipy
148
+ import ffmpeg
149
 
150
  # Load the model
151
+ model = hub.load('https://tfhub.dev/google/yamnet/1')
152
 
153
  def class_names_from_csv(class_map_csv_text):
154
  """Returns list of class names corresponding to score vector."""
 
169
  return desired_sample_rate, waveform
170
 
171
  def convert_mp3_to_wav(mp3_data):
172
+ mp3_buffer = BytesIO(mp3_data)
173
+ wav_buffer = BytesIO()
174
+ process = (
175
+ ffmpeg
176
+ .input('pipe:0', format='mp3')
177
+ .output('pipe:1', format='wav')
178
+ .run_async(pipe_stdin=True, pipe_stdout=True, pipe_stderr=True)
179
+ )
180
+ out, err = process.communicate(input=mp3_buffer.read())
181
+ if process.returncode != 0:
182
+ raise RuntimeError(f"ffmpeg process failed with error: {err}")
183
+ wav_buffer.write(out)
184
  wav_buffer.seek(0)
185
  return wav_buffer
186
 
 
203
  confidence_threshold = 0.60
204
  confident_classes = set()
205
 
 
206
  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' ]
207
  for frame_scores in scores_np:
208
  for i, score in enumerate(frame_scores):