Spaces:
Running
Running
| # Hugging Face Spaces – Phone Vibration Sound Classifier | |
| # ------------------------------------------------- | |
| # Features: | |
| # - Record 2x 60-second audio samples (Class A and Class B) | |
| # - Sliding window segmentation (20 ms) | |
| # - MFCC feature extraction | |
| # - Train / fine‑tune a classifier | |
| # - Record a 3rd sample for testing and predict class | |
| # | |
| # Requirements (automatically handled by Spaces): | |
| # gradio, numpy, librosa, scikit-learn, soundfile | |
| # | |
| # Space type: Gradio | |
| import gradio as gr | |
| import numpy as np | |
| import librosa | |
| from sklearn.linear_model import LogisticRegression | |
| from sklearn.preprocessing import StandardScaler | |
| from sklearn.pipeline import Pipeline | |
| import tempfile | |
| import os | |
| SAMPLE_RATE = 16000 | |
| WINDOW_MS = 20 | |
| WINDOW_SAMPLES = int(SAMPLE_RATE * WINDOW_MS / 1000) | |
| N_MFCC = 13 | |
| # Global model storage | |
| model_pipeline = None | |
| class_names = ["Class A", "Class B"] | |
| def audio_to_windows(y: np.ndarray, sr: int): | |
| hop = WINDOW_SAMPLES | |
| windows = [] | |
| for start in range(0, len(y) - WINDOW_SAMPLES, hop): | |
| windows.append(y[start:start + WINDOW_SAMPLES]) | |
| return windows | |
| def extract_features(y: np.ndarray, sr: int): | |
| windows = audio_to_windows(y, sr) | |
| feats = [] | |
| for w in windows: | |
| mfcc = librosa.feature.mfcc(y=w, sr=sr, n_mfcc=N_MFCC) | |
| mfcc_mean = mfcc.mean(axis=1) | |
| feats.append(mfcc_mean) | |
| return np.array(feats) | |
| def load_audio(file): | |
| y, sr = librosa.load(file, sr=SAMPLE_RATE, mono=True) | |
| return y, sr | |
| def train_model(audio_a, audio_b): | |
| global model_pipeline | |
| if audio_a is None or audio_b is None: | |
| return "Please record both Class A and Class B samples." | |
| y_a, sr_a = load_audio(audio_a) | |
| y_b, sr_b = load_audio(audio_b) | |
| X_a = extract_features(y_a, sr_a) | |
| X_b = extract_features(y_b, sr_b) | |
| y_labels = np.concatenate([ | |
| np.zeros(len(X_a)), | |
| np.ones(len(X_b)) | |
| ]) | |
| X = np.vstack([X_a, X_b]) | |
| model_pipeline = Pipeline([ | |
| ("scaler", StandardScaler()), | |
| ("clf", LogisticRegression(max_iter=200)) | |
| ]) | |
| model_pipeline.fit(X, y_labels) | |
| return f"Model trained successfully. Windows used: {len(X)}" | |
| def predict(audio_test): | |
| global model_pipeline | |
| if model_pipeline is None: | |
| return "Model not trained yet." | |
| if audio_test is None: | |
| return "Please record a test sample." | |
| y, sr = load_audio(audio_test) | |
| X_test = extract_features(y, sr) | |
| probs = model_pipeline.predict_proba(X_test) | |
| avg_prob = probs.mean(axis=0) | |
| predicted_class = int(np.argmax(avg_prob)) | |
| return ( | |
| f"Prediction: {class_names[predicted_class]} (Confidence: {avg_prob[predicted_class]*100:.1f}%)" | |
| ) | |
| with gr.Blocks(title="Phone Vibration Sound Classifier") as demo: | |
| gr.Markdown("# Phone Vibration Sound Classifier") | |
| gr.Markdown("Record two 1‑minute samples for two vibration sources, train the model, then test a third recording.") | |
| with gr.Row(): | |
| audio_a = gr.Audio(sources=["microphone"], type="filepath", label="Record Class A (60 seconds)") | |
| audio_b = gr.Audio(sources=["microphone"], type="filepath", label="Record Class B (60 seconds)") | |
| train_btn = gr.Button("Train / Fine‑tune Model") | |
| train_status = gr.Textbox(label="Training Status") | |
| train_btn.click(train_model, inputs=[audio_a, audio_b], outputs=train_status) | |
| gr.Markdown("---") | |
| audio_test = gr.Audio(sources=["microphone"], type="filepath", label="Record Test Sample (up to 60 seconds)") | |
| predict_btn = gr.Button("Predict Class") | |
| prediction_output = gr.Textbox(label="Prediction Result") | |
| predict_btn.click(predict, inputs=audio_test, outputs=prediction_output) | |
| demo.launch(share=True,server_port=7861) | |