# Copyright 2020 ewan xu # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================= """ Partitioned-Block-Based Frequency Domain Kalman Filter - Gradio demo """ import os import uuid import tempfile import traceback from math import gcd import gradio as gr import numpy as np import soundfile as sf from numpy.fft import irfft as ifft from numpy.fft import rfft as fft from scipy.signal import resample_poly # ---------------------------------------------------------------------------- # ZeroGPU compatibility # # A Space running on ZeroGPU hardware fails at runtime unless at least one # function is decorated with @spaces.GPU. This filter is pure NumPy and needs # no GPU, so the decorator is applied only when the Space actually runs on # ZeroGPU; on CPU hardware it is a no-op. # ---------------------------------------------------------------------------- IS_ZERO_GPU = bool(os.environ.get("SPACES_ZERO_GPU")) if IS_ZERO_GPU: try: import spaces def gpu_shim(fn): return spaces.GPU(duration=120)(fn) except Exception: # spaces not installed -> run as plain CPU code def gpu_shim(fn): return fn else: def gpu_shim(fn): return fn # Files handed back to Gradio live here, and this directory is registered # with launch(allowed_paths=...) so Gradio is always willing to serve them. OUTPUT_DIR = os.path.join(tempfile.gettempdir(), "pfdkf_outputs") os.makedirs(OUTPUT_DIR, exist_ok=True) # ---------------------------------------------------------------------------- # Filter # ---------------------------------------------------------------------------- class PFDKF: def __init__(self, N, M, A=0.999, P_initial=1e2, partial_constrain=True): self.N = N self.M = M self.N_freq = 1 + M self.N_fft = 2 * M self.A2 = A ** 2 self.partial_constrain = partial_constrain self.p = 0 self.x = np.zeros(shape=(2 * self.M), dtype=np.float32) self.P = np.full((self.N, self.N_freq), P_initial) # np.complex was removed in NumPy 1.24 -> use the builtin complex self.X = np.zeros((N, self.N_freq), dtype=complex) self.window = np.hanning(self.M) self.H = np.zeros((self.N, self.N_freq), dtype=complex) def filt(self, x, d): assert len(x) == self.M self.x[self.M:] = x X = fft(self.x) self.X[1:] = self.X[:-1] self.X[0] = X self.x[:self.M] = self.x[self.M:] Y = np.sum(self.H * self.X, axis=0) y = ifft(Y)[self.M:] e = d - y return e, y def update(self, e): e_fft = np.zeros(shape=(self.N_fft,), dtype=np.float32) e_fft[self.M:] = e * self.window E = fft(e_fft) X2 = np.sum(np.abs(self.X) ** 2, axis=0) Pe = 0.5 * self.P * X2 + np.abs(E) ** 2 / self.N mu = self.P / (Pe + 1e-10) self.P = self.A2 * (1 - 0.5 * mu * X2) * self.P + (1 - self.A2) * np.abs(self.H) ** 2 G = mu * self.X.conj() self.H += E * G if self.partial_constrain: h = ifft(self.H[self.p]) h[self.M:] = 0 self.H[self.p] = fft(h) self.p = (self.p + 1) % self.N else: for p in range(self.N): h = ifft(self.H[p]) h[self.M:] = 0 self.H[p] = fft(h) def pfdkf(x, d, N=4, M=64, A=0.999, P_initial=1e2, partial_constrain=True): """Run the filter over the whole signal. Returns (e, y): the echo-cancelled signal and the estimated echo, both the same length as the (trimmed) inputs. """ length = min(len(x), len(d)) x = np.asarray(x[:length], dtype=np.float32) d = np.asarray(d[:length], dtype=np.float32) remainder = length % M if remainder: pad = M - remainder x = np.pad(x, (0, pad)) d = np.pad(d, (0, pad)) num_block = len(x) // M ft = PFDKF(N, M, A, P_initial, partial_constrain) e = np.zeros(num_block * M, dtype=np.float32) y = np.zeros(num_block * M, dtype=np.float32) for n in range(num_block): x_n = x[n * M:(n + 1) * M] d_n = d[n * M:(n + 1) * M] e_n, y_n = ft.filt(x_n, d_n) ft.update(e_n) e[n * M:(n + 1) * M] = e_n y[n * M:(n + 1) * M] = y_n return e[:length], y[:length] # ---------------------------------------------------------------------------- # Audio helpers # ---------------------------------------------------------------------------- def read_audio(path): """Read a file as (samples, channels) float32 plus its sample rate.""" data, sr = sf.read(path, dtype="float32", always_2d=True) return data, int(sr) def to_mono(data): if data.shape[1] == 1: return np.ascontiguousarray(data[:, 0], dtype=np.float32) return data.mean(axis=1).astype(np.float32) def resample(signal, sr_in, sr_out): sr_in, sr_out = int(sr_in), int(sr_out) if sr_in == sr_out: return np.asarray(signal, dtype=np.float32) g = gcd(sr_in, sr_out) return resample_poly(signal, sr_out // g, sr_in // g).astype(np.float32) def write_wav(signal, sr, prefix): signal = np.nan_to_num(signal, nan=0.0, posinf=0.0, neginf=0.0) signal = np.clip(signal, -1.0, 1.0).astype(np.float32) path = os.path.join(OUTPUT_DIR, f"{prefix}_{uuid.uuid4().hex[:8]}.wav") sf.write(path, signal, int(sr), subtype="FLOAT") return path # ---------------------------------------------------------------------------- # Main processing callback # ---------------------------------------------------------------------------- @gpu_shim def process( mode, mic_file, ref_file, stereo_file, target_sr, N, M, A, P_initial, partial_constrain, restore_original_sr, normalize_output, ): try: target_sr = int(float(target_sr)) N = int(float(N)) M = int(float(M)) A = float(A) P_initial = float(P_initial) except (TypeError, ValueError): raise gr.Error("One of the numeric fields is empty or not a number.") if not 4000 <= target_sr <= 192000: raise gr.Error("Target sample rate must be between 4000 and 192000 Hz.") if N < 1: raise gr.Error("N (number of partitions) must be at least 1.") if M < 8: raise gr.Error("M (block size) must be at least 8.") if not 0.0 < A < 1.0: raise gr.Error("A must be strictly between 0 and 1 (e.g. 0.999).") if P_initial <= 0: raise gr.Error("P_initial must be positive.") try: # --- load -------------------------------------------------------- if str(mode).startswith("Single"): if not stereo_file: raise gr.Error("Please upload a 2-channel file (L = mic, R = reference).") data, sr_in = read_audio(stereo_file) if data.shape[1] < 2: raise gr.Error( "That file is mono. Switch to two-file mode, or upload a stereo " "file with the mic on the left and the reference on the right." ) d_raw = np.ascontiguousarray(data[:, 0], dtype=np.float32) x_raw = np.ascontiguousarray(data[:, 1], dtype=np.float32) sr_mic = sr_ref = sr_in else: if not mic_file or not ref_file: raise gr.Error("Please upload both the microphone and the reference signal.") d_data, sr_mic = read_audio(mic_file) x_data, sr_ref = read_audio(ref_file) d_raw = to_mono(d_data) x_raw = to_mono(x_data) original_sr = sr_mic # --- resample to the processing rate ----------------------------- d = resample(d_raw, sr_mic, target_sr) x = resample(x_raw, sr_ref, target_sr) length = min(len(d), len(x)) if length < M: raise gr.Error( f"Signals are too short after resampling ({length} samples) " f"for a block size of {M}." ) # --- filter ------------------------------------------------------ e, y = pfdkf( x, d, N=N, M=M, A=A, P_initial=P_initial, partial_constrain=bool(partial_constrain), ) erle = 10 * np.log10( (float(np.sum(d[:length] ** 2)) + 1e-12) / (float(np.sum(e[:length] ** 2)) + 1e-12) ) # --- back to the original rate, if asked ------------------------- out_sr = target_sr if restore_original_sr and original_sr != target_sr: e = resample(e, target_sr, original_sr) y = resample(y, target_sr, original_sr) out_sr = original_sr if normalize_output: peak = float(np.max(np.abs(e))) if len(e) else 0.0 if peak > 0: e = (e / peak) * 0.98 out_path = write_wav(e, out_sr, "pfdkf_output") echo_path = write_wav(y, out_sr, "pfdkf_estimated_echo") info = ( f"Input sample rate: {original_sr} Hz (mic), {sr_ref} Hz (reference)\n" f"Processing sample rate: {target_sr} Hz\n" f"Output sample rate: {out_sr} Hz\n" f"Processed length: {length / target_sr:.2f} s " f"({length // M} blocks of {M})\n" f"Filter tail: {N * M} samples = " f"{1000.0 * N * M / target_sr:.1f} ms\n" f"Parameters: N={N}, M={M}, A={A}, P_initial={P_initial}, " f"partial_constrain={bool(partial_constrain)}\n" f"Overall ERLE: {erle:.2f} dB" ) return out_path, echo_path, info except gr.Error: raise except Exception as exc: traceback.print_exc() raise gr.Error(f"Processing failed: {type(exc).__name__}: {exc}") # ---------------------------------------------------------------------------- # UI # ---------------------------------------------------------------------------- DESCRIPTION = """ # Partitioned-Block Frequency-Domain Kalman Filter (PFDKF) Acoustic echo cancellation. Upload the **microphone (near-end) signal** and the **far-end reference signal**, choose a processing sample rate, tune the filter, and download the echo-cancelled result. Any input sample rate works: files are resampled to the target rate, filtered, then written out at that rate (or back at the original rate, if you tick it). """ PARAM_HELP = """ * **N** — number of partitions. Filter tail = `N x M` samples. Raise it for rooms with longer echo. * **M** — block size per partition, and the processing latency. Powers of two are fastest. * **A** — state transition / forgetting factor, just under 1. Lower adapts faster but noisier. * **P_initial** — initial state covariance. Larger means a more aggressive start. * **Partial constrain** — constrain one partition per block (fast) instead of all (slightly better, slower). Defaults of `N=4, M=64` cover only 16 ms of echo tail at 16 kHz. Real rooms need 100-300 ms, so try `N=16, M=256` for actual recordings. """ with gr.Blocks(title="PFDKF Echo Cancellation") as demo: gr.Markdown(DESCRIPTION) with gr.Row(): with gr.Column(): mode = gr.Radio( choices=[ "Two files (microphone + reference)", "Single stereo file (L = microphone, R = reference)", ], value="Two files (microphone + reference)", label="Input mode", ) mic_file = gr.Audio(label="Microphone / near-end signal (d)", type="filepath") ref_file = gr.Audio(label="Far-end / reference signal (x)", type="filepath") stereo_file = gr.Audio( label="Stereo file (L = mic, R = reference)", type="filepath", visible=False, ) target_sr = gr.Number(value=16000, label="Target sample rate (Hz)") with gr.Accordion("Filter parameters", open=True): N = gr.Slider(1, 64, value=4, step=1, label="N - number of partitions") M = gr.Dropdown( choices=[32, 64, 128, 256, 512, 1024], value=64, label="M - block size (samples)", ) A = gr.Slider( 0.90, 0.99999, value=0.999, step=0.00001, label="A - state transition factor", ) P_initial = gr.Number(value=100.0, label="P_initial") partial_constrain = gr.Checkbox(value=True, label="Partial constrain") gr.Markdown(PARAM_HELP) with gr.Accordion("Output options", open=False): restore_original_sr = gr.Checkbox( value=False, label="Resample the output back to the original sample rate", ) normalize_output = gr.Checkbox( value=False, label="Peak-normalize the output" ) run = gr.Button("Run echo cancellation", variant="primary") with gr.Column(): out_audio = gr.Audio(label="Output - echo-cancelled signal (e)", type="filepath") echo_audio = gr.Audio(label="Estimated echo (y)", type="filepath") info = gr.Textbox(label="Details", lines=9) def toggle_mode(selected): single = str(selected).startswith("Single") return ( gr.Audio(visible=not single), gr.Audio(visible=not single), gr.Audio(visible=single), ) mode.change(toggle_mode, inputs=mode, outputs=[mic_file, ref_file, stereo_file]) run.click( process, inputs=[ mode, mic_file, ref_file, stereo_file, target_sr, N, M, A, P_initial, partial_constrain, restore_original_sr, normalize_output, ], outputs=[out_audio, echo_audio, info], ) if __name__ == "__main__": base = dict( server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860)), allowed_paths=[OUTPUT_DIR], show_error=True, ) app = demo.queue(max_size=10) try: app.launch(**base) except TypeError: # Older/newer Gradio that rejects one of the kwargs above app.launch(server_name="0.0.0.0", server_port=7860)