janasumit2911 commited on
Commit
4bfc802
·
verified ·
1 Parent(s): 21f4a91

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -40
app.py CHANGED
@@ -8,7 +8,11 @@ import json
8
  from scipy.io import wavfile
9
  from pydub import AudioSegment
10
  import gradio as gr
 
 
 
11
 
 
12
  model = hub.load('Audio_Multiple_v1')
13
 
14
  def class_names_from_csv(class_map_csv_text):
@@ -29,76 +33,84 @@ def ensure_sample_rate(original_sample_rate, waveform, desired_sample_rate=16000
29
  waveform = scipy.signal.resample(waveform, desired_length)
30
  return desired_sample_rate, waveform
31
 
32
- def convert_mp3_to_wav(mp3_file_path):
33
- audio = AudioSegment.from_mp3(mp3_file_path)
34
- wav_file_path = mp3_file_path.replace('.mp3', '.wav')
35
- audio.export(wav_file_path, format='wav')
36
- return wav_file_path
37
-
38
- def process_audio_file(file_path):
39
- sample_rate, wav_data = wavfile.read(file_path, 'rb')
40
- if wav_data.ndim > 1: # Convert stereo to mono if needed
 
 
41
  wav_data = np.mean(wav_data, axis=1)
42
  sample_rate, wav_data = ensure_sample_rate(sample_rate, wav_data)
43
 
44
  waveform = wav_data / tf.int16.max
45
- waveform = tf.convert_to_tensor(waveform, dtype=tf.float32)
46
 
47
- scores, embeddings, spectrogram = model(waveform)
48
 
49
  scores_np = scores.numpy()
50
  mean_scores = np.mean(scores, axis=0)
51
 
52
- inferred_class = class_names[mean_scores.argmax()]
53
-
54
- confidence_threshold = 0.60
55
  confident_classes = set()
56
 
57
- 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']
58
  for frame_scores in scores_np:
59
  for i, score in enumerate(frame_scores):
60
  if score > confidence_threshold:
61
  class_name = class_names[i]
62
 
63
- if class_name == 'Child speech, kid speaking':
64
- class_name = 'Child speech'
65
- elif class_name == 'Vehicle horn, car horn, honking':
66
- class_name = 'Vehicle horn'
67
- elif class_name == 'Railroad car, train wagon':
68
- class_name = 'Train/wagon'
69
- elif class_name == 'Rail transport':
70
- class_name = 'Train/wagon'
71
 
72
  if class_name not in exclusion_list:
73
  confident_classes.add(class_name)
74
 
75
- confident_classes = sorted(confident_classes)
 
 
 
 
76
 
77
- return confident_classes
 
 
 
78
 
79
  def process_audio(params):
80
- # try
81
- params = json.loads(params)
82
- # except json.JSONDecodeError:
83
- # return {"error": "Invalid JSON input"}
84
 
85
  audio_files = params.get("audio_files", [])
86
  api = params.get("api", "")
87
  job_id = params.get("job_id", "")
88
 
89
  solutions = []
90
- for audio in audio_files:
91
- if audio.endswith(".mp3"):
92
- wav_file_path = convert_mp3_to_wav(audio)
93
- class_names = process_audio_file(wav_file_path)
94
- elif audio.endswith(".wav"):
95
- class_names = process_audio_file(audio)
96
-
97
- answer_dict = {'file_name': audio, 'class_names': class_names}
98
- solutions.append(answer_dict)
99
 
100
  result_url = f"{api}/{job_id}"
101
- # send_results_to_api(solutions, result_url)
102
 
103
  return json.dumps({"solutions": solutions}, indent=4)
104
 
@@ -114,4 +126,4 @@ inputt = gr.Textbox(label="Parameters (JSON format) Eg. {'audio_files':['file1.m
114
  outputs = gr.JSON()
115
 
116
  application = gr.Interface(fn=process_audio, inputs=inputt, outputs=outputs, title="Audio Classification with API Integration")
117
- application.launch()
 
8
  from scipy.io import wavfile
9
  from pydub import AudioSegment
10
  import gradio as gr
11
+ import io
12
+ from io import BytesIO
13
+ import soundfile as sf
14
 
15
+ # Load the model
16
  model = hub.load('Audio_Multiple_v1')
17
 
18
  def class_names_from_csv(class_map_csv_text):
 
33
  waveform = scipy.signal.resample(waveform, desired_length)
34
  return desired_sample_rate, waveform
35
 
36
+ def convert_mp3_to_wav(mp3_data):
37
+ audio = AudioSegment.from_file(io.BytesIO(mp3_data), format="mp3")
38
+ wav_buffer = io.BytesIO()
39
+ audio.export(wav_buffer, format='wav')
40
+ wav_buffer.seek(0)
41
+ return wav_buffer
42
+
43
+ def process_audio_file(file_data, url):
44
+ sample_rate, wav_data = wavfile.read(BytesIO(file_data))
45
+
46
+ if wav_data.ndim > 1:
47
  wav_data = np.mean(wav_data, axis=1)
48
  sample_rate, wav_data = ensure_sample_rate(sample_rate, wav_data)
49
 
50
  waveform = wav_data / tf.int16.max
 
51
 
52
+ scores, embeddings, spectrogram = model(waveform)
53
 
54
  scores_np = scores.numpy()
55
  mean_scores = np.mean(scores, axis=0)
56
 
57
+ inferred_class = class_names[mean_scores.argmax()]
58
+
59
+ confidence_threshold = 0.60
60
  confident_classes = set()
61
 
62
+ 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' ]
63
  for frame_scores in scores_np:
64
  for i, score in enumerate(frame_scores):
65
  if score > confidence_threshold:
66
  class_name = class_names[i]
67
 
68
+ if class_name =='Child speech, kid speaking':
69
+ class_name='Child speech'
70
+ elif class_name =='Vehicle horn, car horn, honking':
71
+ class_name='Vehicle horn'
72
+ elif class_name =='Railroad car, train wagon':
73
+ class_name='Train/wagon'
74
+ elif class_name=='Rail transport':
75
+ class_name='Train/wagon'
76
 
77
  if class_name not in exclusion_list:
78
  confident_classes.add(class_name)
79
 
80
+ confident_classes = sorted(confident_classes)
81
+
82
+ answer_dict= {}
83
+ answer_dict.update({'file_name': url, 'class_names': confident_classes}) #os.path.basename(file_path
84
+ solutions.append(answer_dict)
85
 
86
+ def get_audio_data(url):
87
+ response = requests.get(url)
88
+ response.raise_for_status()
89
+ return response.content
90
 
91
  def process_audio(params):
92
+ try:
93
+ params = json.loads(params)
94
+ except json.JSONDecodeError as e:
95
+ return {"error": f"Invalid JSON input: {e.msg} at line {e.lineno} column {e.colno}"}
96
 
97
  audio_files = params.get("audio_files", [])
98
  api = params.get("api", "")
99
  job_id = params.get("job_id", "")
100
 
101
  solutions = []
102
+ for audio_url in audio_files:
103
+ audio_data = get_audio_data(audio_url)
104
+
105
+ if audio_url.endswith(".mp3"):
106
+ wav_buffer = convert_mp3_to_wav(audio_data)
107
+ process_audio_file(wav_buffer.getvalue(), audio_url)
108
+
109
+ elif audio_url.endswith(".wav"):
110
+ process_audio_file(audio_data, audio_url)
111
 
112
  result_url = f"{api}/{job_id}"
113
+ response = requests.patch(result_url, json={"solutions": solutions})
114
 
115
  return json.dumps({"solutions": solutions}, indent=4)
116
 
 
126
  outputs = gr.JSON()
127
 
128
  application = gr.Interface(fn=process_audio, inputs=inputt, outputs=outputs, title="Audio Classification with API Integration")
129
+ application.launch()