Spaces:
Sleeping
Sleeping
File size: 14,979 Bytes
f950969 4d83a0a f950969 4d83a0a f950969 4d83a0a f950969 4d83a0a f950969 4d83a0a f950969 4d83a0a f950969 4d83a0a f950969 4d83a0a f950969 4d83a0a f950969 4d83a0a f950969 4d83a0a f950969 4d83a0a f950969 4d83a0a f950969 4d83a0a f950969 4d83a0a f950969 4d83a0a f950969 4d83a0a f950969 4d83a0a f950969 4d83a0a f950969 4d83a0a f950969 4d83a0a f950969 4d83a0a f950969 4d83a0a f950969 4d83a0a f950969 4d83a0a f950969 4d83a0a f950969 4d83a0a f950969 4d83a0a f950969 4d83a0a f950969 4d83a0a f950969 4d83a0a f950969 4f9f7ee f950969 4d83a0a f950969 4d83a0a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 | # Copyright 2020 ewan xu<ewan_xu@outlook.com>
#
# 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) |