MeysamSh commited on
Commit
cc5180f
·
1 Parent(s): b6d53e5

Add application file

Browse files
Files changed (2) hide show
  1. app.py +130 -0
  2. requirements.txt +5 -0
app.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Hugging Face Spaces – Phone Vibration Sound Classifier
2
+ # -------------------------------------------------
3
+ # Features:
4
+ # - Record 2x 60-second audio samples (Class A and Class B)
5
+ # - Sliding window segmentation (20 ms)
6
+ # - MFCC feature extraction
7
+ # - Train / fine‑tune a classifier
8
+ # - Record a 3rd sample for testing and predict class
9
+ #
10
+ # Requirements (automatically handled by Spaces):
11
+ # gradio, numpy, librosa, scikit-learn, soundfile
12
+ #
13
+ # Space type: Gradio
14
+
15
+ import gradio as gr
16
+ import numpy as np
17
+ import librosa
18
+ from sklearn.linear_model import LogisticRegression
19
+ from sklearn.preprocessing import StandardScaler
20
+ from sklearn.pipeline import Pipeline
21
+ import tempfile
22
+ import os
23
+
24
+ SAMPLE_RATE = 16000
25
+ WINDOW_MS = 20
26
+ WINDOW_SAMPLES = int(SAMPLE_RATE * WINDOW_MS / 1000)
27
+ N_MFCC = 13
28
+
29
+ # Global model storage
30
+ model_pipeline = None
31
+ class_names = ["Class A", "Class B"]
32
+
33
+
34
+ def audio_to_windows(y: np.ndarray, sr: int):
35
+ hop = WINDOW_SAMPLES
36
+ windows = []
37
+ for start in range(0, len(y) - WINDOW_SAMPLES, hop):
38
+ windows.append(y[start:start + WINDOW_SAMPLES])
39
+ return windows
40
+
41
+
42
+ def extract_features(y: np.ndarray, sr: int):
43
+ windows = audio_to_windows(y, sr)
44
+ feats = []
45
+ for w in windows:
46
+ mfcc = librosa.feature.mfcc(y=w, sr=sr, n_mfcc=N_MFCC)
47
+ mfcc_mean = mfcc.mean(axis=1)
48
+ feats.append(mfcc_mean)
49
+ return np.array(feats)
50
+
51
+
52
+ def load_audio(file):
53
+ y, sr = librosa.load(file, sr=SAMPLE_RATE, mono=True)
54
+ return y, sr
55
+
56
+
57
+ def train_model(audio_a, audio_b):
58
+ global model_pipeline
59
+
60
+ if audio_a is None or audio_b is None:
61
+ return "Please record both Class A and Class B samples."
62
+
63
+ y_a, sr_a = load_audio(audio_a)
64
+ y_b, sr_b = load_audio(audio_b)
65
+
66
+ X_a = extract_features(y_a, sr_a)
67
+ X_b = extract_features(y_b, sr_b)
68
+
69
+ y_labels = np.concatenate([
70
+ np.zeros(len(X_a)),
71
+ np.ones(len(X_b))
72
+ ])
73
+
74
+ X = np.vstack([X_a, X_b])
75
+
76
+ model_pipeline = Pipeline([
77
+ ("scaler", StandardScaler()),
78
+ ("clf", LogisticRegression(max_iter=200))
79
+ ])
80
+
81
+ model_pipeline.fit(X, y_labels)
82
+
83
+ return f"Model trained successfully. Windows used: {len(X)}"
84
+
85
+
86
+ def predict(audio_test):
87
+ global model_pipeline
88
+
89
+ if model_pipeline is None:
90
+ return "Model not trained yet."
91
+
92
+ if audio_test is None:
93
+ return "Please record a test sample."
94
+
95
+ y, sr = load_audio(audio_test)
96
+ X_test = extract_features(y, sr)
97
+
98
+ probs = model_pipeline.predict_proba(X_test)
99
+ avg_prob = probs.mean(axis=0)
100
+
101
+ predicted_class = int(np.argmax(avg_prob))
102
+
103
+ return (
104
+ f"Prediction: {class_names[predicted_class]} (Confidence: {avg_prob[predicted_class]*100:.1f}%)"
105
+ )
106
+
107
+
108
+ with gr.Blocks(title="Phone Vibration Sound Classifier") as demo:
109
+ gr.Markdown("# Phone Vibration Sound Classifier")
110
+ gr.Markdown("Record two 1‑minute samples for two vibration sources, train the model, then test a third recording.")
111
+
112
+ with gr.Row():
113
+ audio_a = gr.Audio(sources=["microphone"], type="filepath", label="Record Class A (60 seconds)")
114
+ audio_b = gr.Audio(sources=["microphone"], type="filepath", label="Record Class B (60 seconds)")
115
+
116
+ train_btn = gr.Button("Train / Fine‑tune Model")
117
+ train_status = gr.Textbox(label="Training Status")
118
+
119
+ train_btn.click(train_model, inputs=[audio_a, audio_b], outputs=train_status)
120
+
121
+ gr.Markdown("---")
122
+
123
+ audio_test = gr.Audio(sources=["microphone"], type="filepath", label="Record Test Sample (up to 60 seconds)")
124
+ predict_btn = gr.Button("Predict Class")
125
+ prediction_output = gr.Textbox(label="Prediction Result")
126
+
127
+ predict_btn.click(predict, inputs=audio_test, outputs=prediction_output)
128
+
129
+
130
+ demo.launch(share=True,server_port=7861)
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ gradio
2
+ numpy
3
+ librosa
4
+ scikit-learn
5
+ soundfile