Update app.py
Browse files2 unmodified lines3456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778792 unmodified linesimport numpy as npimport matplotlib.pyplot as pltimport gradio as grfrom scipy.signal import resample# Load YAMNet modelyamnet_model = hub.load("https://tfhub.dev/google/yamnet/1")# Load class namesdef load_class_map():class_map_path = tf.keras.utils.get_file('yamnet_class_map.csv','https://raw.githubusercontent.com/tensorflow/models/master/research/audioset/yamnet/yamnet_class_map.csv')with open(class_map_path, 'r') as f:return [line.strip().split(',')[2] for line in f.readlines()[1:]]class_names = load_class_map()# Classification functiondef classify_audio(audio, sample_rate):try:# Convert stereo to monoif len(audio.shape) > 1:audio = np.mean(audio, axis=1)# Normalizeaudio = audio / np.max(np.abs(audio))# Resample to 16kHz if neededtarget_sr = 16000if sample_rate != target_sr:duration = audio.shape[0] / sample_ratenew_length = int(duration * target_sr)audio = resample(audio, new_length)sample_rate = target_sr# Convert to tensorwaveform = tf.convert_to_tensor(audio, dtype=tf.float32)# Predictscores, embeddings, spectrogram = yamnet_model(waveform)mean_scores = tf.reduce_mean(scores, axis=0).numpy()top_5 = np.argsort(mean_scores)[::-1][:5]# Extract predictionstop_prediction = class_names[top_5[0]]top_scores = {class_names[i]: float(mean_scores[i]) for i in top_5}# Create waveform plotfig, ax = plt.subplots()ax.plot(audio)ax.set_title("Waveform")ax.set_xlabel("Time (samples)")ax.set_ylabel("Amplitude")plt.tight_layout()return top_prediction, top_scores, figexcept Exception as e:return f"Error: {str(e)}", {}, None# Gradio Interface (binary audio compatible for n8n)interface = gr.Interface(fn=classify_audio,inputs=gr.Audio(source="upload", type="numpy", label="Upload .wav or .mp3"),outputs=[gr.Textbox(label="Top Prediction"),gr.Label(label="Top 5 Class Scores"),gr.Plot(label="Waveform")],title="Audtheia YAMNet Audio Classifier",description="Classifies audio with YAMNet and returns predictions with waveform plot.")if __name__ == "__main__":interface.launch()2 unmodified lines345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182832 unmodified linesimport numpy as npimport matplotlib.pyplot as pltimport gradio as grimport soundfile as sffrom scipy.signal import resample # Correct resampling method# Load YAMNet model from TensorFlow Hubyamnet_model_handle = "https://tfhub.dev/google/yamnet/1"yamnet_model = hub.load(yamnet_model_handle)# Load class labelsdef load_class_map():class_map_path = tf.keras.utils.get_file('yamnet_class_map.csv','https://raw.githubusercontent.com/tensorflow/models/master/research/audioset/yamnet/yamnet_class_map.csv')with open(class_map_path, 'r') as f:class_names = [line.strip().split(',')[2] for line in f.readlines()[1:]]return class_namesclass_names = load_class_map()# Classification functiondef classify_audio(file_path):try:# Load audio file (WAV, MP3, etc.)audio_data, sample_rate = sf.read(file_path)# Convert stereo to mono if neededif len(audio_data.shape) > 1:audio_data = np.mean(audio_data, axis=1)# Normalize audioaudio_data = audio_data / np.max(np.abs(audio_data))# Resample to 16kHz if necessarytarget_rate = 16000if sample_rate != target_rate:duration = audio_data.shape[0] / sample_ratenew_length = int(duration * target_rate)audio_data = resample(audio_data, new_length)# Convert to tensorwaveform = tf.convert_to_tensor(audio_data, dtype=tf.float32)# Run YAMNetscores, embeddings, spectrogram = yamnet_model(waveform)mean_scores = tf.reduce_mean(scores, axis=0).numpy()top_5 = np.argsort(mean_scores)[::-1][:5]top_prediction = class_names[top_5[0]]top_scores = {class_names[i]: float(mean_scores[i]) for i in top_5}# Create waveform plotfig, ax = plt.subplots()ax.plot(audio_data)ax.set_title("Waveform")ax.set_xlabel("Time")ax.set_ylabel("Amplitude")plt.tight_layout()return top_prediction, top_scores, figexcept Exception as e:return f"Error processing audio: {e}", {}, None# Gradio interfaceinterface = gr.Interface(fn=classify_audio,inputs=gr.Audio(type="filepath", label="Upload .wav or .mp3 audio file"),outputs=[gr.Textbox(label="Top Prediction"),gr.Label(label="Top 5 Classes with Scores"),gr.Plot(label="Waveform")],title="Audtheia YAMNet Audio Classifier",description="Upload an environmental or animal sound to classify using the YAMNet model. Returns label predictions and waveform.")if __name__ == "__main__":interface.launch()
app.py+33-29