Spaces:
Sleeping
Sleeping
Create app2.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687import gradio as grimport numpy as npfrom scipy.signal import bilinear, lfilter
# ==========================================# 1. YOUR ORIGINAL DSP LOGIC (Unchanged)# ==========================================
def a_weighting(fs): f1 = 20.598997 f2 = 107.65265 f3 = 737.86223 f4 = 12194.217 A1000 = 1.9997 NUMs = [(2*np.pi*f4)**2 * (10**(A1000/20.0)), 0.0, 0.0, 0.0, 0.0] DENs = np.convolve([1.0, 4*np.pi*f4, (2*np.pi*f4)**2], [1.0, 4*np.pi*f1, (2*np.pi*f1)**2]) DENs = np.convolve(np.convolve(DENs, [1.0, 2*np.pi*f3]), [1.0, 2*np.pi*f2]) # Bilinear converts analog filter to digital b, a = bilinear(NUMs, DENs, fs) return b, a
def process_audio(audio, threshold=20.0, calibration=55.0): # Gradio passes audio as (sample_rate, numpy_array) if audio is None: return "No Audio", 0.0, "Waiting..."
sr, samples = audio # Convert to float32 if needed (Gradio sometimes gives int16) if samples.dtype != np.float32: samples = samples.astype(np.float32) # If stereo (2 channels), average them to mono if len(samples.shape) > 1: samples = np.mean(samples, axis=1)
# Normalize to -1.0 to 1.0 range if it's raw PCM data (often large integers) if np.max(np.abs(samples)) > 1.0: samples = samples / 32768.0
if samples.size == 0: return "Empty Audio", 0.0, "QUIET"
try: # Apply the A-Weighting Filter b, a = a_weighting(sr) y = lfilter(b, a, samples) except Exception as e: print("Filter error:", e) y = samples # Fallback
# Calculate RMS and dB rms = np.sqrt(np.mean(np.square(y))) level_db = 20.0 * np.log10(rms + 1e-12) level_dba = float(level_db + calibration) # Decision decision = "NOISY 🚨" if level_dba >= threshold else "QUIET 🍃" return decision, f"{level_dba:.2f} dBA", decision
# ==========================================# 2. GRADIO INTERFACE# ==========================================
with gr.Interface( fn=process_audio, inputs=[ gr.Audio(sources=["microphone"], type="numpy"), # Capture Mic gr.Slider(0, 100, value=20, label="Threshold (dB)"), gr.Slider(0, 100, value=55, label="Calibration Offset") ], outputs=[ "text", # Decision Text "text", # dB Number "text" # Redundant visual ], title="DSP Noise Detector", description="Speak into the microphone to calculate Decibels (dBA) using A-Weighting filters.", live=True # Updates immediately as you speak) as demo: pass
demo.launch()app2.pyAdded+87