Update app.py
Browse files3 unmodified lines45678910111211 unmodified lines242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031043 unmodified linesimport matplotlib.pyplot as pltimport gradio as grimport soundfile as sffrom scipy.signal import resampleimport uuidimport os# Load YAMNet model from TensorFlow Hubyamnet_model_handle = "https://tfhub.dev/google/yamnet/1"11 unmodified linesclass_names = load_class_map()# Audio classificationdef classify_audio(file_path):try:# Load and normalize audioaudio_data, sample_rate = sf.read(file_path)if len(audio_data.shape) > 1:audio_data = np.mean(audio_data, axis=1)audio_data = audio_data / np.max(np.abs(audio_data))# Resample to 16 kHztarget_rate = 16000if sample_rate != target_rate:duration = len(audio_data) / sample_ratenew_len = int(duration * target_rate)audio_data = resample(audio_data, new_len)waveform = 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_indices = np.argsort(mean_scores)[::-1][:5]top_prediction = class_names[top_5_indices[0]]confidence = float(mean_scores[top_5_indices[0]])# Dominant classesdominant_bands = ", ".join([class_names[i] for i in top_5_indices[:3]])# Waveform imagefig, ax = plt.subplots()ax.plot(audio_data)ax.set_title("Waveform")ax.set_xlabel("Time")ax.set_ylabel("Amplitude")plt.tight_layout()waveform_filename = f"waveform_{uuid.uuid4().hex}.png"fig.savefig(waveform_filename)plt.close(fig)# Structured JSON outputreturn {"classification": top_prediction,"confidence": confidence,"denoised_audio_url": "N/A","spectrogram_url": "N/A","bonus": {"frequency_range": "0–8000 Hz","dominant_bands": dominant_bands},"waveform_url": waveform_filename}except Exception as e:return {"classification": "Error","confidence": 0.0,"denoised_audio_url": "N/A","spectrogram_url": "N/A","bonus": {"frequency_range": "N/A","dominant_bands": "N/A"},"waveform_url": "N/A","error": str(e)}# Gradio interfaceinterface = gr.Interface(fn=classify_audio,inputs=gr.Audio(type="filepath", label="Upload .wav or .mp3"),outputs="json",title="Audtheia YAMNet Audio Classifier",description="Classify audio using YAMNet and return structured JSON output for n8n.")if __name__ == "__main__":interface.launch()3 unmodified lines4567891011 unmodified lines22232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182833 unmodified linesimport 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"11 unmodified linesclass_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+26-47