amritn8 commited on
Commit
da4b1de
·
verified ·
1 Parent(s): 1629667

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -0
app.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tensorflow as tf
2
+ import joblib
3
+ import numpy as np
4
+ import gradio as gr
5
+ import librosa
6
+ import soundfile as sf
7
+
8
+ # Load model and label encoder
9
+ model = tf.keras.models.load_model("animal_sound_cnn.keras")
10
+ label_encoder = joblib.load("label_encoder.joblib")
11
+
12
+ def preprocess_audio(audio_path, target_shape=(64, 64)):
13
+ """
14
+ Convert audio file to spectrogram with correct shape for model
15
+ """
16
+ try:
17
+ # 1. Load audio file
18
+ y, sr = librosa.load(audio_path, sr=None)
19
+
20
+ # 2. Create mel spectrogram
21
+ S = librosa.feature.melspectrogram(y=y, sr=sr, n_mels=target_shape[0])
22
+ log_S = librosa.power_to_db(S, ref=np.max)
23
+
24
+ # 3. Resize to target dimensions
25
+ if log_S.shape[1] < target_shape[1]:
26
+ pad_width = target_shape[1] - log_S.shape[1]
27
+ log_S = np.pad(log_S, ((0, 0), (0, pad_width))
28
+ else:
29
+ log_S = log_S[:, :target_shape[1]]
30
+
31
+ # 4. Add channel dimension and batch dimension
32
+ spectrogram = log_S[np.newaxis, ..., np.newaxis]
33
+
34
+ return spectrogram.astype(np.float32)
35
+
36
+ except Exception as e:
37
+ print(f"Preprocessing error: {str(e)}")
38
+ return None
39
+
40
+ def predict(audio_path):
41
+ try:
42
+ # 1. Preprocess audio
43
+ spectrogram = preprocess_audio(audio_path)
44
+ if spectrogram is None:
45
+ return "Error processing audio"
46
+
47
+ # 2. Check input shape matches model expectations
48
+ print(f"Input shape: {spectrogram.shape}") # Debug log
49
+
50
+ # 3. Predict
51
+ pred = model.predict(spectrogram)
52
+ animal = label_encoder.inverse_transform([np.argmax(pred)])[0]
53
+
54
+ return animal
55
+ except Exception as e:
56
+ return f"Prediction error: {str(e)}"
57
+
58
+ # Update requirements.txt to include:
59
+ # librosa==0.10.1
60
+ # soundfile==0.12.1
61
+
62
+ gr.Interface(
63
+ fn=predict,
64
+ inputs=gr.Audio(type="filepath"),
65
+ outputs="label",
66
+ examples=["example1.wav", "example2.wav"] if os.path.exists("example1.wav") else None
67
+ ).launch()