janasumit2911 commited on
Commit
6d852cd
·
verified ·
1 Parent(s): 14e7e09

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +119 -0
app.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from scipy.io import wavfile
9
+ from pydub import AudioSegment
10
+ import gradio as gr
11
+
12
+ model = hub.load('Audio_Multiple_v1') #loading model
13
+
14
+ def class_names_from_csv(class_map_csv_text): # Function to load class names from CSV.
15
+ """Returns list of class names corresponding to score vector."""
16
+ class_names = []
17
+ with tf.io.gfile.GFile(class_map_csv_text) as csvfile:
18
+ reader = csv.DictReader(csvfile)
19
+ for row in reader:
20
+ class_names.append(row['display_name'])
21
+ return class_names
22
+
23
+ class_map_path = model.class_map_path().numpy()
24
+ class_names = class_names_from_csv(class_map_path)
25
+
26
+ def ensure_sample_rate(original_sample_rate, waveform, desired_sample_rate=16000): #to ensure/make a standard sample rate for audio
27
+ if original_sample_rate != desired_sample_rate: # Resample waveform if required
28
+ desired_length = int(round(float(len(waveform)) / original_sample_rate * desired_sample_rate))
29
+ waveform = scipy.signal.resample(waveform, desired_length)
30
+ return desired_sample_rate, waveform
31
+
32
+ def convert_mp3_to_wav(mp3_file_path): #if audio file is mp3 then convert it to wav
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): #reading audio file and making stereo to mono
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
+ #excluding some unwanted classes
58
+ 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' ]
59
+ for frame_scores in scores_np:
60
+ for i, score in enumerate(frame_scores):
61
+ if score > confidence_threshold:
62
+ class_name = class_names[i]
63
+
64
+ if class_name == 'Child speech, kid speaking':
65
+ class_name = 'Child speech'
66
+ elif class_name == 'Vehicle horn, car horn, honking':
67
+ class_name = 'Vehicle horn'
68
+ elif class_name == 'Railroad car, train wagon':
69
+ class_name = 'Train/wagon'
70
+ elif class_name == 'Rail transport':
71
+ class_name = 'Train/wagon'
72
+
73
+ if class_name not in exclusion_list:
74
+ confident_classes.add(class_name)
75
+
76
+ confident_classes = sorted(confident_classes)
77
+ return confident_classes
78
+
79
+ #main function to get the input
80
+ def process_audio(params):
81
+ try:
82
+ params = json.loads(params)
83
+ except json.JSONDecodeError:
84
+ return {"error": "Invalid JSON input"}
85
+
86
+ audio_files = params.get("audio_files", [])
87
+ api = params.get("api", "")
88
+ job_id = params.get("job_id", "")
89
+
90
+ solutions = []
91
+ for audio in audio_files:
92
+ if audio.endswith(".mp3"):
93
+ wav_file_path = convert_mp3_to_wav(audio)
94
+ class_names = process_audio_file(wav_file_path)
95
+ elif audio.endswith(".wav"):
96
+ class_names = process_audio_file(audio)
97
+
98
+ answer_dict = {'file_name': audio, 'class_names': class_names}
99
+ solutions.append(answer_dict)
100
+
101
+ result_url = f"{api}/{job_id}"
102
+
103
+ # send_results_to_api(solutions, result_url)
104
+
105
+ return json.dumps({"solutions": solutions}, indent=4)
106
+
107
+ def send_results_to_api(data, result_url):
108
+ headers = {"Content-Type": "application/json"}
109
+ response = requests.patch(result_url, json=data, headers=headers)
110
+ if response.status_code == 200:
111
+ return response.json() # Return any response from the API if needed
112
+ else:
113
+ return {"error": f"Failed to send results to API: {response.status_code}"}
114
+
115
+ inputt = gr.Textbox(label="Parameters (JSON format) Eg. audio_files:['',''], api:'', job_id:''")
116
+ outputts = gr.JSON()
117
+
118
+ application = gr.Interface(fn=process_audio, inputs=inputt, outputs=outputts, title="Audio Classification with API Integration")
119
+ application.launch()