The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Clean up voice: the ComfyUI-RE-USE node pack (RE-USE speech enhancement without mamba-ssm)
Adarsh8cc0417b5cb8
diff --git a/comfy-nodes/ComfyUI-RE-USE/LICENSE b/comfy-nodes/ComfyUI-RE-USE/LICENSEnew file mode 100644index 00000000..4746ad80--- /dev/null+++ b/comfy-nodes/ComfyUI-RE-USE/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 workingprototype and the Fuobe contributors++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/comfy-nodes/ComfyUI-RE-USE/LICENSE.OpenMDW-1.1-NVIDIA b/comfy-nodes/ComfyUI-RE-USE/LICENSE.OpenMDW-1.1-NVIDIAnew file mode 100644index 00000000..280d88be--- /dev/null+++ b/comfy-nodes/ComfyUI-RE-USE/LICENSE.OpenMDW-1.1-NVIDIA@@ -0,0 +1,70 @@+[PRIMARY MODEL LICENSE]++Use of this model is governed by the OpenMDWv1.1 License.+A copy of the OpenMDWv1.1 License is included below for convenience.++Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.++OpenMDW License Agreement, version 1.1 (OpenMDW-1.1)++By exercising rights granted to you under this agreement, you accept and agree+to its terms.++As used in this agreement, "Model Materials" means the materials provided to+you under this agreement, consisting of: (1) one or more machine learning+models (including architecture and parameters); and (2) all related artifacts+(including associated data, documentation and software) that are provided to+you hereunder.++Subject to your compliance with this agreement, permission is hereby granted,+free of charge, to deal in the Model Materials without restriction, including+under all copyright, patent, database, and trade secret rights included or+embodied therein.++If you distribute any portion of the Model Materials, you shall retain in your+distribution (1) a copy of this agreement, and (2) all copyright notices and+other notices of origin included in the Model Materials that are applicable to+your distribution.++If you file, maintain, or voluntarily participate in a lawsuit against any+person or entity asserting that the Model Materials directly or indirectly+infringe any patent or copyright, then all rights and grants made to you+hereunder are terminated, unless that lawsuit was in response to a+corresponding lawsuit first brought against you.++This agreement does not impose any restrictions or obligations with respect to+any use, modification, or sharing of any outputs generated by using the Model+Materials.++THE MODEL MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS+OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE, TITLE, NONINFRINGEMENT, ACCURACY, OR THE+ABSENCE OF LATENT OR OTHER DEFECTS OR ERRORS, WHETHER OR NOT DISCOVERABLE, ALL+TO THE GREATEST EXTENT PERMISSIBLE UNDER APPLICABLE LAW.++YOU ARE SOLELY RESPONSIBLE FOR (1) CLEARING RIGHTS OF OTHER PERSONS THAT MAY+APPLY TO THE MODEL MATERIALS OR ANY USE THEREOF, INCLUDING WITHOUT LIMITATION+ANY PERSON'S COPYRIGHTS OR OTHER RIGHTS INCLUDED OR EMBODIED IN THE MODEL+MATERIALS; (2) OBTAINING ANY NECESSARY CONSENTS, PERMISSIONS OR OTHER RIGHTS+REQUIRED FOR ANY USE OF THE MODEL MATERIALS; OR (3) PERFORMING ANY DUE+DILIGENCE OR UNDERTAKING ANY OTHER INVESTIGATIONS INTO THE MODEL MATERIALS OR+ANYTHING INCORPORATED OR EMBODIED THEREIN.++IN NO EVENT SHALL THE PROVIDERS OF THE MODEL MATERIALS BE LIABLE FOR ANY CLAIM,+DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR+OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MODEL MATERIALS, THE+USE THEREOF OR OTHER DEALINGS THEREIN.++----------------------------------------------------------------------+Third-Party Notices+----------------------------------------------------------------------+Python library:++librosa: ISC+torch: BSD-3-Clause+torchaudio: BSD-3-Clause+PyYAML: MIT+einops : MIT+mamba_ssm: Apache License 2.0++diff --git a/comfy-nodes/ComfyUI-RE-USE/NOTICE b/comfy-nodes/ComfyUI-RE-USE/NOTICEnew file mode 100644index 00000000..bfc98008--- /dev/null+++ b/comfy-nodes/ComfyUI-RE-USE/NOTICE@@ -0,0 +1,18 @@+ComfyUI-RE-USE+Copyright (c) 2026 workingprototype and the Fuobe contributors (MIT, see LICENSE)++This pack contains code adapted from NVIDIA's RE-USE repository+(https://huggingface.co/nvidia/NVIDIA-NemotronLabs-RE-USE): the network classes and the STFT settings in+reuse_engine.py, from models/generator_SEMamba_time_d4.py, models/codec_module_time_d4.py,+models/mamba_block2_SEMamba.py and inference.py.++ SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+ SPDX-License-Identifier: OpenMDW-1.1++The OpenMDW-1.1 licence text, with NVIDIA's third-party notices, is in LICENSE.OpenMDW-1.1-NVIDIA.++The Mamba layer is a plain-PyTorch rewrite (no mamba_ssm). It loads the published weights unchanged and matches the+reference maths numerically, but it is not NVIDIA's code path.++The model weights are not part of this pack. They are NVIDIA's (OpenMDW-1.1) and are downloaded separately into+models/reuse/ (see README.md).diff --git a/comfy-nodes/ComfyUI-RE-USE/README.md b/comfy-nodes/ComfyUI-RE-USE/README.mdnew file mode 100644index 00000000..4625ed58--- /dev/null+++ b/comfy-nodes/ComfyUI-RE-USE/README.md@@ -0,0 +1,72 @@+# ComfyUI-RE-USE++ComfyUI nodes for **NVIDIA NemotronLabs RE-USE**, a universal speech enhancement model (9.6M parameters, 39 MB). It+removes noise, echo, clipping, codec damage and the limits of a poor mic or a phone line, and keeps the main+speaker. Run above the source's rate, it fills the empty high band (bandwidth extension). Fuobe's "Clean up voice"+runs on it.++- No `mamba-ssm` and no `causal-conv1d`. The Mamba layer is plain PyTorch with the same parameter names, so the+ published weights load unchanged. The selective scan uses Triton on CUDA and numba on the CPU when they are+ importable (most ComfyUI installs have both), else a PyTorch loop. A Triton that imports but can't compile (no+ Python headers, or a build that doesn't fit torch or the GPU) falls back to the loop once, with a line in the log.+ The node does not install anything.+- Works on Windows and Linux, on an NVIDIA GPU or a CPU.+- Requirements: ComfyUI 0.42 or later, Python 3.10 or later, torch 2.x and torchaudio (all part of ComfyUI).++## Install++Copy this folder into `ComfyUI/custom_nodes/ComfyUI-RE-USE`, put the weights in `ComfyUI/models/reuse/`, and restart+ComfyUI. Fuobe's Workflows page and GPU board print the exact commands (a sparse checkout of this folder at a pinned+commit).++| File in `models/reuse/` | Download (pinned revision) | Bytes | SHA-256 |+|---|---|---|---|+| `NemotronLabs-RE-USE.safetensors` | https://huggingface.co/nvidia/NVIDIA-NemotronLabs-RE-USE/resolve/31f82f2efad1095034492f236e8dac9239ba713b/model.safetensors | 38,592,940 | `06badaf4029b297f97f7fe48d62990b48d5482608210df577354e0d4e0ed70e1` |+| `NemotronLabs-RE-USE-laughter.safetensors` (optional: keeps laughs and breaths a little more) | https://huggingface.co/nvidia/NVIDIA-NemotronLabs-RE-USE-laughter/resolve/1b1521dd659608e1e063ada83e0acfe1da473a8b/model.safetensors | 38,592,940 | `35c2a4e284515275d2e49a8e8cb5cd392ae67a1f1d345de1c12a0202c7b6b610` |++Use only these two NemotronLabs repositories (OpenMDW-1.1). The older `nvidia/RE-USE` repository is a research+release under NVIDIA's non-commercial licence.++## Nodes++**Load RE-USE** (`REUSELoader`): `model` (a file in `models/reuse`), `device` (auto, cuda, cpu). The loader refuses a+file that is not a RE-USE model.++**Clean up voice** (`REUSEEnhance`):++| Input | What it does |+|---|---|+| `rate` | The rate the model runs at: `source`, `source up to 24000` / `16000` (the source's rate, capped), or 8 to 48 kHz. Lower runs faster and gives a band-limited result. Higher than the source is bandwidth extension. |+| `pre_lowpass` | Resample down to this rate first (NVIDIA's demo does this before bandwidth extension). |+| `channels` | `mono` (the mean of the channels) or `each channel`. More than 2 channels always run in mono. |+| `chunk_seconds` | 0 = from the free memory (2 to 20 s on CUDA; 10 s on a CPU, 5 s at 32 kHz or more). |+| `overlap_seconds` | The crossfade at each join (1 s). Cancel works between chunks. |+| `room_tone_db` | Mixes the original in under the clean voice at this level (-60 = off), so the gaps between words are not dead silent. |+| `level` | `match input` (the model's output is about 3 dB quieter; this puts the speech level back), `-16 LUFS` (voice-over), or `off`. The peak is kept at or under -1 dBFS. |+| `bed`, `bed_db` | Optional music and effects to mix back under the clean voice (for a video's soundtrack, with a separator such as DBS). |++Outputs: `audio`, and `report` (JSON: model, device, scan, rates, chunk, seconds, time taken, times real time, the+level gain and the peak VRAM).++## Speed (RTX 5090 and i9-13900K, both shared with other work, so these are worst cases)++| Device | 8 kHz | 16 kHz | 24 kHz | 44.1 kHz | 48 kHz |+|---|---|---|---|---|---|+| CUDA with Triton (seconds of work per second of audio) | 0.13 | 0.26 | 0.4 | 1.3 | 1.4 |+| CPU with numba | 2 | 4 | 5 | 13 | 15 |++Without Triton, CUDA is about 6x slower. A CPU is good for voice samples and short clips; a long video soundtrack wants+a GPU or a lower rate. Memory is about 0.35 GB plus 0.13 GB per second of chunk at 16 kHz (more at higher rates): the+whole file, the result and the crossfade weights stay in system memory, and only one chunk is on the GPU at a time.++## Tests++In a venv of its own (never a live ComfyUI's Python): `python -I -m pytest -q tests`. The real-weight tests run when+`RE_USE_WEIGHTS` (and the other variables named in `tests/test_real_weights.py`) are set.++## Licence++The pack's code is MIT (`LICENSE`). The network code is adapted from NVIDIA's RE-USE repository (OpenMDW-1.1): see+`NOTICE` and `LICENSE.OpenMDW-1.1-NVIDIA`. The plain-PyTorch Mamba layer matches the reference maths numerically, but+it is not NVIDIA's code path. The weights are NVIDIA's, under OpenMDW-1.1 (the model card says "ready for commercial+use"; its safety section points to the NVIDIA Open Model License for use-case limits).diff --git a/comfy-nodes/ComfyUI-RE-USE/__init__.py b/comfy-nodes/ComfyUI-RE-USE/__init__.pynew file mode 100644index 00000000..f05cc7b9--- /dev/null+++ b/comfy-nodes/ComfyUI-RE-USE/__init__.py@@ -0,0 +1,4 @@+"""ComfyUI-RE-USE: NVIDIA NemotronLabs RE-USE speech enhancement as ComfyUI nodes (Fuobe's own pack, MIT)."""+from .nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS++__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"]diff --git a/comfy-nodes/ComfyUI-RE-USE/nodes.py b/comfy-nodes/ComfyUI-RE-USE/nodes.pynew file mode 100644index 00000000..03fdb094--- /dev/null+++ b/comfy-nodes/ComfyUI-RE-USE/nodes.py@@ -0,0 +1,255 @@+"""ComfyUI nodes for NVIDIA NemotronLabs RE-USE (universal speech enhancement). Fuobe's own pack, MIT.++REUSELoader -> models/reuse/<file>.safetensors (RE-USE, or RE-USE-laughter), on auto / cuda / cpu.+REUSEEnhance -> AUDIO in, AUDIO out, and a JSON report. It removes noise, echo, clipping, codec damage and the+ limits of a poor mic or a phone line, and keeps the main speaker. Run above the source's rate, it fills+ the empty high band (bandwidth extension). Long files run a chunk at a time with crossfaded joins.++No mamba_ssm or causal_conv1d: the Mamba layers run in plain PyTorch (reuse_engine.py), with a Triton scan on CUDA or a+numba scan on the CPU when those are importable, else a PyTorch loop. No package beyond what ComfyUI has.+"""+import json+import os+import time++import torch+import torchaudio++import folder_paths++from . import reuse_engine as E++FOLDER = "reuse"+DEFAULT_FILE = "NemotronLabs-RE-USE.safetensors"++# models/reuse, listed by GET /models/reuse (Fuobe's presence check reads it).+_dir = os.path.join(folder_paths.models_dir, FOLDER)+if FOLDER not in folder_paths.folder_names_and_paths:+ folder_paths.folder_names_and_paths[FOLDER] = ([_dir], {".safetensors"})++# "source up to N": the source's rate, or N when the source is higher (a CPU's pick when the source rate is unknown).+RATES = ["source", "source up to 24000", "source up to 16000", "8000", "16000", "22050", "24000", "32000", "44100", "48000"]+LOWPASS = ["off", "8000", "16000", "22050", "24000"]+LEVELS = ["match input", "-16 LUFS", "off"]+ROOM_TONE_OFF = -60.0+MATCH_MAX_GAIN_DB = 12.0+++def _device(choice):+ if choice == "cpu" or not torch.cuda.is_available():+ return torch.device("cpu")+ if choice == "cuda":+ return torch.device("cuda")+ try:+ import comfy.model_management as mm++ return mm.get_torch_device()+ except Exception:+ return torch.device("cuda")+++def _interrupt_check():+ """ComfyUI's Cancel, checked between chunks (nothing outside ComfyUI)."""+ try:+ import comfy.model_management as mm+ except ImportError:+ return None+ return mm.throw_exception_if_processing_interrupted+++def _progress_bar(total):+ try:+ from comfy.utils import ProgressBar++ return ProgressBar(total)+ except Exception:+ return None+++def _resample(x, src, dst):+ if src == dst:+ return x+ return torchaudio.functional.resample(x, src, dst, resampling_method="sinc_interp_kaiser")+++def work_rate(rate, source_rate):+ """The rate the model runs at: the source's (8-48 kHz) or the one asked for, inside 8-48 kHz."""+ if rate == "source":+ want = source_rate+ elif rate.startswith("source up to "):+ want = min(source_rate, int(rate.rsplit(" ", 1)[1]))+ else:+ want = int(rate)+ return int(min(E.MAX_RATE, max(E.MIN_RATE, want)))+++def prepare(x, sr, rate, pre_lowpass="off"):+ """x (C, N) at sr -> (x at the work rate, the work rate). The model's range is 8-48 kHz; an optional pre-low-pass+ resamples down first (NVIDIA's demo does this before bandwidth extension)."""+ cur = int(min(E.MAX_RATE, max(E.MIN_RATE, sr)))+ x = _resample(x, sr, cur)+ if pre_lowpass != "off" and int(pre_lowpass) < cur:+ x = _resample(x, cur, int(pre_lowpass))+ cur = int(pre_lowpass)+ target = work_rate(rate, int(min(E.MAX_RATE, max(E.MIN_RATE, sr))))+ return _resample(x, cur, target), target+++def match_level(y, ref, sr):+ """Gain that brings y's speech level (95th percentile of 30 ms frame RMS) to ref's, at most +12 dB. Returns (y, dB)."""+ a, b = E.frame_rms_p(ref, sr), E.frame_rms_p(y, sr)+ if a <= 1e-6 or b <= 1e-6:+ return y, 0.0+ import math++ db = min(MATCH_MAX_GAIN_DB, 20 * math.log10(a / b))+ return y * 10 ** (db / 20), db+++def to_lufs(y, sr, target=-16.0):+ import math++ cur = E.lufs(y, sr)+ if not math.isfinite(cur) or cur <= -70:+ return y, 0.0+ db = min(MATCH_MAX_GAIN_DB * 2, target - cur)+ return y * 10 ** (db / 20), db+++def mix_bed(voice, v_sr, bed, b_sr, bed_db):+ """The clean voice (C, N) over a bed (Cb, M): at the higher of the two rates, mono voice on every bed channel, the+ bed at bed_db, and the sum scaled down to -1 dBFS if it peaks over. Returns (mix, rate)."""+ sr = max(v_sr, b_sr)+ voice, bed = _resample(voice, v_sr, sr), _resample(bed, b_sr, sr)+ ch = max(voice.shape[0], bed.shape[0])+ if voice.shape[0] != ch:+ voice = voice.mean(0, keepdim=True).expand(ch, -1)+ if bed.shape[0] != ch:+ bed = bed.mean(0, keepdim=True).expand(ch, -1)+ n = max(voice.shape[1], bed.shape[1])+ out = torch.zeros(ch, n)+ out[:, : voice.shape[1]] += voice+ out[:, : bed.shape[1]] += bed * 10 ** (bed_db / 20)+ return E.peak_limit(out), sr+++class REUSELoader:+ @classmethod+ def INPUT_TYPES(cls):+ files = folder_paths.get_filename_list(FOLDER)+ return {+ "required": {+ "model": (files or [DEFAULT_FILE], {"default": DEFAULT_FILE if DEFAULT_FILE in files or not files else files[0], "tooltip": "A RE-USE model in models/reuse"}),+ "device": (["auto", "cuda", "cpu"], {"default": "auto"}),+ }+ }++ RETURN_TYPES = ("REUSE_MODEL",)+ FUNCTION = "load"+ CATEGORY = "audio/RE-USE"+ DESCRIPTION = "Loads NVIDIA RE-USE (speech enhancement, 9.6M parameters) from models/reuse."++ def load(self, model, device):+ get = getattr(folder_paths, "get_full_path_or_raise", None) or folder_paths.get_full_path+ path = get(FOLDER, model)+ if not path:+ raise FileNotFoundError(f"RE-USE isn't in models/reuse yet ({model})")+ dev = _device(device)+ return ({"model": E.load_reuse(path, dev), "device": dev, "name": model},)+++class REUSEEnhance:+ @classmethod+ def INPUT_TYPES(cls):+ return {+ "required": {+ "reuse_model": ("REUSE_MODEL",),+ "audio": ("AUDIO",),+ "rate": (RATES, {"default": "source", "tooltip": "The rate the model runs at. Lower is faster and band-limited; higher than the source fills the empty high band (bandwidth extension)."}),+ "pre_lowpass": (LOWPASS, {"default": "off", "tooltip": "Resample down to this rate first (before bandwidth extension)"}),+ "channels": (["mono", "each channel"], {"default": "mono", "tooltip": "Mono is the mean of the channels; more than 2 channels always run in mono"}),+ "chunk_seconds": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 30.0, "step": 0.5, "tooltip": "0 = from the free memory"}),+ "overlap_seconds": ("FLOAT", {"default": 1.0, "min": 0.25, "max": 5.0, "step": 0.25}),+ "room_tone_db": ("FLOAT", {"default": ROOM_TONE_OFF, "min": -60.0, "max": -6.0, "step": 1.0, "tooltip": "Mix the original in under the clean voice at this level (-60 = off): no dead silence between words"}),+ "level": (LEVELS, {"default": "match input"}),+ },+ "optional": {+ "bed": ("AUDIO", {"tooltip": "Music and effects to mix back under the clean voice"}),+ "bed_db": ("FLOAT", {"default": 0.0, "min": -30.0, "max": 6.0, "step": 0.5}),+ },+ }++ RETURN_TYPES = ("AUDIO", "STRING")+ RETURN_NAMES = ("audio", "report")+ FUNCTION = "enhance"+ CATEGORY = "audio/RE-USE"+ DESCRIPTION = "Clean up voice: removes noise, echo, clipping and codec damage from speech and keeps the main speaker."++ def enhance(self, reuse_model, audio, rate="source", pre_lowpass="off", channels="mono", chunk_seconds=0.0, overlap_seconds=1.0, room_tone_db=ROOM_TONE_OFF, level="match input", bed=None, bed_db=0.0):+ model, dev = reuse_model["model"], reuse_model["device"]+ wav = audio["waveform"] # (B, C, N)+ sr_in = int(audio["sample_rate"])+ mono = channels == "mono" or wav.shape[1] > 2+ work = work_rate(rate, sr_in)+ chunk = float(chunk_seconds) if chunk_seconds and chunk_seconds > 0 else E.auto_chunk_seconds(work, dev)+ check = _interrupt_check()+ t0 = time.time()+ if dev.type == "cuda":+ torch.cuda.reset_peak_memory_stats(dev)++ def segment(x):+ return E.enhance_segment(model, x.to(dev), work).float()++ outs, gains = [], []+ n_items = wav.shape[0]+ pbar = _progress_bar(1000)+ for b in range(n_items):+ x = wav[b].float()+ if mono and x.shape[0] > 1:+ x = x.mean(0, keepdim=True)+ dry, sr = prepare(x, sr_in, rate, pre_lowpass)+ prog = (lambda d, t, b=b: pbar.update_absolute(int(1000 * (b + d / t) / n_items))) if pbar else None+ # dry stays on the CPU: enhance_chunked moves one chunk at a time to the device.+ y = E.enhance_chunked(segment, dry, sr, chunk, overlap_seconds, progress=prog, check=check)+ if room_tone_db > ROOM_TONE_OFF:+ y = y + dry * 10 ** (room_tone_db / 20)+ gain = 0.0+ if level == "match input":+ y, gain = match_level(y, dry, sr)+ elif level == "-16 LUFS":+ y, gain = to_lufs(y, sr)+ y = E.peak_limit(y)+ if bed is not None:+ bw = bed["waveform"][min(b, bed["waveform"].shape[0] - 1)].float()+ y, sr = mix_bed(y, sr, bw, int(bed["sample_rate"]), bed_db)+ outs.append(y)+ gains.append(gain)+ out_sr = sr+ n = max(o.shape[-1] for o in outs)+ ch = max(o.shape[0] for o in outs)+ out = torch.zeros(len(outs), ch, n)+ for i, o in enumerate(outs):+ out[i, : o.shape[0], : o.shape[-1]] = o+ seconds = wav.shape[-1] / sr_in+ took = time.time() - t0+ report = {+ "model": reuse_model["name"],+ "device": str(dev),+ "scan": E.scan_kind(dev),+ "input_rate": sr_in,+ "rate": work,+ "output_rate": out_sr,+ "channels": "mono" if mono else "each channel",+ "chunk_seconds": round(chunk, 2),+ "overlap_seconds": overlap_seconds,+ "seconds": round(seconds, 2),+ "took": round(took, 2),+ "times_real_time": round(seconds / took, 2) if took > 0 else None,+ "level_gain_db": round(gains[0], 2) if gains else 0.0,+ "peak_vram_gb": round(torch.cuda.max_memory_allocated(dev) / 1024**3, 2) if dev.type == "cuda" else None,+ }+ return ({"waveform": out, "sample_rate": out_sr}, json.dumps(report))+++NODE_CLASS_MAPPINGS = {"REUSELoader": REUSELoader, "REUSEEnhance": REUSEEnhance}+NODE_DISPLAY_NAME_MAPPINGS = {"REUSELoader": "Load RE-USE (speech enhancement)", "REUSEEnhance": "Clean up voice (RE-USE)"}diff --git a/comfy-nodes/ComfyUI-RE-USE/reuse_engine.py b/comfy-nodes/ComfyUI-RE-USE/reuse_engine.pynew file mode 100644index 00000000..3c65c1b5--- /dev/null+++ b/comfy-nodes/ComfyUI-RE-USE/reuse_engine.py@@ -0,0 +1,557 @@+# ComfyUI-RE-USE: a plain-PyTorch runtime for NVIDIA NemotronLabs RE-USE (universal speech enhancement).+#+# The network classes below (REUSE, the dense encoder and decoders, the time-frequency Mamba blocks) and the STFT+# settings are adapted from NVIDIA's RE-USE repository:+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: OpenMDW-1.1+# (see LICENSE.OpenMDW-1.1-NVIDIA and NOTICE). The Mamba layer is re-written here without the mamba_ssm and+# causal_conv1d CUDA extensions, with the same parameter names, so the published model.safetensors loads unchanged+# (strict=True). The scans, the chunking and everything else in this file are Fuobe's own code (MIT, see LICENSE).+import math++import torch+import torch.nn as nn+import torch.nn.functional as F++# ---------------------------------------------------------------- selective scan+++class PureMamba(nn.Module):+ """Mamba v1 block with the state_dict layout of mamba_ssm.Mamba (in_proj, conv1d, x_proj, dt_proj, A_log, D, out_proj)."""++ # "auto" picks triton on CUDA, numba on the CPU, and the PyTorch loop when neither is importable.+ scan_mode = "auto"++ def __init__(self, d_model, d_state=16, d_conv=4, expand=2):+ super().__init__()+ self.d_model, self.d_state, self.d_conv = d_model, d_state, d_conv+ self.d_inner = int(expand * d_model)+ self.dt_rank = math.ceil(d_model / 16)+ self.in_proj = nn.Linear(d_model, self.d_inner * 2, bias=False)+ self.conv1d = nn.Conv1d(self.d_inner, self.d_inner, d_conv, groups=self.d_inner, padding=d_conv - 1, bias=True)+ self.x_proj = nn.Linear(self.d_inner, self.dt_rank + 2 * d_state, bias=False)+ self.dt_proj = nn.Linear(self.dt_rank, self.d_inner, bias=True)+ self.A_log = nn.Parameter(torch.zeros(self.d_inner, d_state))+ self.D = nn.Parameter(torch.ones(self.d_inner))+ self.out_proj = nn.Linear(self.d_inner, d_model, bias=False)++ def forward(self, h): # h: (B, L, d_model)+ L = h.shape[1]+ x, z = self.in_proj(h).chunk(2, dim=-1)+ x = F.silu(self.conv1d(x.transpose(1, 2))[..., :L]).transpose(1, 2) # (B, L, Di)+ dt, Bm, Cm = torch.split(self.x_proj(x), [self.dt_rank, self.d_state, self.d_state], dim=-1)+ delta = F.softplus(self.dt_proj(dt)) # dt_proj's bias is mamba_ssm's delta_bias+ A = -torch.exp(self.A_log.float()) # (Di, N)+ y = scan(x.float(), delta.float(), A, Bm.float(), Cm.float(), self.scan_mode)+ y = y + x * self.D+ y = y * F.silu(z)+ return self.out_proj(y)+++def scan_kind(device, mode="auto"):+ """The scan back end a device runs: "triton" (CUDA), "numba" (CPU) or "torch-loop"."""+ if mode != "auto":+ return mode+ if torch.device(device).type == "cuda":+ return "triton" if triton_ok() else "torch-loop"+ return "numba" if numba_ok() else "torch-loop"+++def scan(u, delta, A, Bm, Cm, mode="auto"):+ """h_t = exp(delta_t * A) * h_{t-1} + delta_t * u_t * B_t; y_t = <h_t, C_t>.+ u, delta: (B, L, Di); Bm, Cm: (B, L, N); A: (Di, N) -> y: (B, L, Di)."""+ kind = scan_kind(u.device, mode)+ if kind == "triton":+ try:+ return _TR(u, delta, A, Bm, Cm)+ except Exception as e: # imports but can't compile here (no Python.h, a Triton that doesn't fit torch or the GPU)+ if mode != "auto":+ raise+ _triton_failed(e)+ return scan_loop(u, delta, A, Bm, Cm)+ if kind == "numba":+ return scan_numba(u, delta, A, Bm, Cm)+ return scan_loop(u, delta, A, Bm, Cm)+++def scan_loop(u, delta, A, Bm, Cm):+ """The reference: a PyTorch loop over time. Works everywhere."""+ Bsz, L, Di = u.shape+ h = u.new_zeros(Bsz, Di, A.shape[1])+ ys = u.new_empty(Bsz, L, Di)+ du = delta * u+ for t in range(L):+ dA = torch.exp(delta[:, t, :, None] * A) # (B, Di, N)+ h = torch.addcmul(du[:, t, :, None] * Bm[:, t, None, :], dA, h)+ ys[:, t] = torch.einsum("bdn,bn->bd", h, Cm[:, t])+ return ys+++# ---- fused CPU scan: numba comes with librosa, which most ComfyUI installs have. Optional.+_NB = None+++def numba_ok():+ global _NB+ if _NB is None:+ try:+ _NB = _build_numba()+ except Exception:+ _NB = False+ return _NB is not False+++def _build_numba():+ import math as _m++ import numpy as np+ from numba import njit, prange++ @njit(parallel=True, fastmath=True, cache=False)+ def kern(u, dl, A, Bm, Cm, y):+ Bsz, L, Di = u.shape+ N = A.shape[1]+ for idx in prange(Bsz * Di):+ b = idx // Di+ d = idx - b * Di+ h = np.zeros(N, np.float32)+ a = A[d]+ for t in range(L):+ dt = dl[b, t, d]+ du = dt * u[b, t, d]+ acc = np.float32(0.0)+ for n in range(N):+ hn = _m.exp(dt * a[n]) * h[n] + du * Bm[b, t, n]+ h[n] = hn+ acc += hn * Cm[b, t, n]+ y[b, t, d] = acc++ return kern+++def scan_numba(u, delta, A, Bm, Cm):+ import numpy as np++ if not numba_ok():+ raise RuntimeError("numba is not available")+ un = u.detach().cpu().contiguous().numpy()+ y = np.empty_like(un)+ _NB(un, delta.detach().cpu().contiguous().numpy(), A.detach().cpu().contiguous().numpy(), Bm.detach().cpu().contiguous().numpy(), Cm.detach().cpu().contiguous().numpy(), y)+ return torch.from_numpy(y).to(u.device)+++# ---- fused GPU scan: triton (triton-windows on Windows), which most CUDA ComfyUI installs have. Optional.+_TR = None+++def _triton_failed(e):+ """Triton's first launch failed: use the PyTorch loop from now on (scan_kind then says "torch-loop")."""+ global _TR+ _TR = False+ print(f"[RE-USE] the Triton scan can't run here ({type(e).__name__}: {str(e).splitlines()[0][:200] if str(e) else ''}); using the PyTorch scan")+++def triton_ok():+ global _TR+ if _TR is None:+ try:+ _TR = _build_triton()+ except Exception:+ _TR = False+ return _TR is not False+++def _build_triton():+ import triton+ import triton.language as tl++ @triton.jit+ def kern(u_ptr, dt_ptr, A_ptr, B_ptr, C_ptr, y_ptr, L, Di, N: tl.constexpr, BLOCK_D: tl.constexpr):+ pid_b = tl.program_id(0)+ pid_d = tl.program_id(1)+ d = pid_d * BLOCK_D + tl.arange(0, BLOCK_D)+ n = tl.arange(0, N)+ md = d < Di+ A = tl.load(A_ptr + d[:, None] * N + n[None, :], mask=md[:, None], other=0.0)+ h = tl.zeros((BLOCK_D, N), dtype=tl.float32)+ bud = pid_b.to(tl.int64) * L * Di+ bn = pid_b.to(tl.int64) * L * N+ for t in range(L):+ uu = tl.load(u_ptr + bud + t * Di + d, mask=md, other=0.0)+ dl = tl.load(dt_ptr + bud + t * Di + d, mask=md, other=0.0)+ Bv = tl.load(B_ptr + bn + t * N + n)+ Cv = tl.load(C_ptr + bn + t * N + n)+ h = tl.exp(dl[:, None] * A) * h + (dl * uu)[:, None] * Bv[None, :]+ tl.store(y_ptr + bud + t * Di + d, tl.sum(h * Cv[None, :], axis=1), mask=md)++ def run(u, delta, A, Bm, Cm):+ Bsz, L, Di = u.shape+ N = A.shape[1]+ u, delta, A, Bm, Cm = (t.contiguous() for t in (u, delta, A, Bm, Cm))+ y = torch.empty_like(u)+ BLOCK_D = 64+ kern[(Bsz, triton.cdiv(Di, BLOCK_D))](u, delta, A, Bm, Cm, y, L, Di, N=N, BLOCK_D=BLOCK_D)+ return y++ return run+++# ---------------------------------------------------------------- the RE-USE network (SEMamba, time_d4)+# Adapted from NVIDIA's RE-USE repository (OpenMDW-1.1): models/generator_SEMamba_time_d4.py,+# models/codec_module_time_d4.py and models/mamba_block2_SEMamba.py.+++def _pad2d(k, d=(1, 1)):+ return (int((k[0] * d[0] - d[0]) / 2), int((k[1] * d[1] - d[1]) / 2))+++class SPConvTranspose2d(nn.Module):+ def __init__(self, cin, cout, k, r=1):+ super().__init__()+ self.pad1 = nn.ConstantPad2d((1, 1, 0, 0), 0.0)+ self.conv = nn.Conv2d(cin, cout * r, kernel_size=k, stride=(1, 1))+ self.r = r++ def forward(self, x):+ out = self.conv(self.pad1(x))+ b, c, H, W = out.shape+ out = out.view(b, self.r, c // self.r, H, W).permute(0, 2, 3, 4, 1)+ return out.contiguous().view(b, c // self.r, H, -1)+++class DenseBlock(nn.Module):+ def __init__(self, h, k=(3, 3), depth=4):+ super().__init__()+ self.depth = depth+ self.dense_block = nn.ModuleList()+ for i in range(depth):+ dil = 2**i+ self.dense_block.append(nn.Sequential(nn.Conv2d(h * (i + 1), h, k, dilation=(dil, 1), padding=_pad2d(k, (dil, 1))), nn.InstanceNorm2d(h, affine=True), nn.PReLU(h)))++ def forward(self, x):+ skip = x+ for i in range(self.depth):+ x = self.dense_block[i](skip)+ skip = torch.cat([x, skip], 1)+ return x+++class DenseEncoder(nn.Module):+ def __init__(self, h, cin=2):+ super().__init__()+ self.dense_conv_1 = nn.Sequential(nn.Conv2d(cin, h, (1, 1)), nn.InstanceNorm2d(h, affine=True), nn.PReLU(h))+ self.dense_block = DenseBlock(h, depth=4)+ self.dense_conv_2 = nn.Sequential(nn.Conv2d(h, h, (1, 3), stride=(4, 2)), nn.InstanceNorm2d(h, affine=True), nn.PReLU(h))++ def forward(self, x):+ return self.dense_conv_2(self.dense_block(self.dense_conv_1(x)))+++class _Dec(nn.Module):+ def __init__(self, h):+ super().__init__()+ self.dense_block = DenseBlock(h, depth=4)+ self.up_conv1 = nn.Sequential(SPConvTranspose2d(h, h, (1, 3), 2), nn.InstanceNorm2d(h, affine=True), nn.PReLU(h))+ self.up_conv2 = nn.Sequential(SPConvTranspose2d(h, h, (1, 3), 4), nn.InstanceNorm2d(h, affine=True), nn.PReLU(h))++ def trunk(self, x):+ x = self.up_conv1(self.dense_block(x))+ return self.up_conv2(x.permute(0, 1, 3, 2)).permute(0, 1, 3, 2)+++class MagDecoder(_Dec):+ def __init__(self, h, cout=1):+ super().__init__(h)+ self.final_conv = nn.Conv2d(h, cout, (1, 1))++ def forward(self, x):+ return self.final_conv(self.trunk(x))+++class PhaseDecoder(_Dec):+ def __init__(self, h, cout=1):+ super().__init__(h)+ self.phase_conv_r = nn.Conv2d(h, cout, (1, 1))+ self.phase_conv_i = nn.Conv2d(h, cout, (1, 1))++ def forward(self, x):+ x = self.trunk(x)+ return torch.atan2(self.phase_conv_i(x), self.phase_conv_r(x))+++class BiMamba(nn.Module):+ def __init__(self, d, d_state, d_conv, expand):+ super().__init__()+ self.forward_blocks = PureMamba(d, d_state, d_conv, expand)+ self.backward_blocks = PureMamba(d, d_state, d_conv, expand)+ self.output_proj = nn.Linear(2 * d, d)+ self.norm = nn.LayerNorm(d)++ def forward(self, x):+ fw = self.forward_blocks(x) + x+ xr = torch.flip(x, dims=[1])+ bw = torch.flip(self.backward_blocks(xr) + xr, dims=[1])+ return self.norm(self.output_proj(torch.cat([fw, bw], -1)))+++class TFMambaBlock(nn.Module):+ def __init__(self, h, d_state, d_conv, expand):+ super().__init__()+ self.time_mamba = BiMamba(h, d_state, d_conv, expand)+ self.freq_mamba = BiMamba(h, d_state, d_conv, expand)++ def forward(self, x):+ b, c, t, f = x.size()+ x = x.permute(0, 3, 2, 1).contiguous().view(b * f, t, c)+ x = self.time_mamba(x) + x+ x = x.view(b, f, t, c).permute(0, 2, 1, 3).contiguous().view(b * t, f, c)+ x = self.freq_mamba(x) + x+ return x.view(b, t, f, c).permute(0, 3, 1, 2)+++class REUSE(nn.Module):+ def __init__(self, hid=64, n_blocks=30, d_state=16, d_conv=4, expand=4):+ super().__init__()+ self.dense_encoder = DenseEncoder(hid)+ self.TSMamba = nn.ModuleList([TFMambaBlock(hid, d_state, d_conv, expand) for _ in range(n_blocks)])+ self.mask_decoder = MagDecoder(hid)+ self.phase_decoder = PhaseDecoder(hid)++ def forward(self, mag, pha): # (B, F, T)+ x = torch.stack((mag.transpose(1, 2), pha.transpose(1, 2)), 1) # (B, 2, T, F)+ T, Fq = x.shape[2], x.shape[3]+ x = self.dense_encoder(F.pad(x, (0, 2, 0, 2)))+ for blk in self.TSMamba:+ x = blk(x)+ m = self.mask_decoder(x).squeeze(1).transpose(1, 2)[:, :Fq, :T]+ p = self.phase_decoder(x).squeeze(1).transpose(1, 2)[:, :Fq, :T]+ return m, p+++class NotReuseError(ValueError):+ pass+++def load_reuse(path, device="cpu"):+ """The published model.safetensors (RE-USE or RE-USE-laughter), loaded with strict=True."""+ from safetensors.torch import load_file++ model = REUSE()+ try:+ model.load_state_dict(load_file(path), strict=True)+ except Exception as e: # a different network, or not a safetensors file+ raise NotReuseError("This file is not a RE-USE model") from e+ return model.to(device).eval()+++# ---------------------------------------------------------------- STFT and one segment (as the repo's inference.py)+# The STFT is scaled to the rate: n_fft 320, hop 40, window 320 at 8 kHz (a 40 ms window and a 5 ms hop at any rate).++BASE_SR, BASE_NFFT, BASE_HOP, BASE_WIN = 8000, 320, 40, 320+MIN_RATE, MAX_RATE = 8000, 48000+++def _even(v):+ v = int(round(v))+ return v if v % 2 == 0 else v + 1+++def stft_params(sr):+ return _even(BASE_NFFT * sr // BASE_SR), _even(BASE_HOP * sr // BASE_SR), _even(BASE_WIN * sr // BASE_SR)++[email protected]_grad()+def enhance_segment(model, wav, sr):+ """wav: (1, N) on the model's device -> (1, N)."""+ n_fft, hop, win = stft_params(sr)+ n = wav.shape[1]+ if n <= n_fft // 2: # shorter than the reflect padding allows (about 20 ms): zero-pad, run, trim+ wav = F.pad(wav, (0, n_fft - n))+ window = torch.hann_window(win, device=wav.device)+ spec = torch.stft(wav, n_fft, hop_length=hop, win_length=win, window=window, center=True, pad_mode="reflect", normalized=False, return_complex=True)+ amp_g, pha_g = model(torch.log1p(spec.abs()), spec.angle())+ lin = torch.expm1(F.relu(amp_g))+ # The repo's guard against a "strange sweep artifact": frames where more than half the bins are zero become zero.+ zero_portion = (lin == 0).sum(1) / lin.shape[1]+ amp_g[:, :, (zero_portion > 0.5)[0]] = 0+ lin = torch.expm1(F.relu(amp_g))+ out = torch.istft(torch.polar(lin, pha_g), n_fft, hop_length=hop, win_length=win, window=window, center=True)+ if out.shape[1] >= n:+ return out[:, :n]+ return F.pad(out, (0, n - out.shape[1]))+++# ---------------------------------------------------------------- chunking+++def chunk_spans(n, chunk, overlap):+ """Start and end of every chunk over n samples: chunks of `chunk` samples, `overlap` apart at each join; the last+ chunk ends at n (so it may overlap its neighbour by more)."""+ if n <= chunk:+ return [(0, n)]+ hop = max(1, chunk - overlap)+ spans = []+ s = 0+ while s + chunk < n:+ spans.append((s, s + chunk))+ s += hop+ spans.append((n - chunk, n))+ return spans+++def crossfade_weights(length, ramp, skip=0, ramp_in=True, ramp_out=True, device=None):+ """A chunk's weights: 0 for its first `skip` samples (covered by the chunk before), then a raised-cosine ramp in over+ `ramp` samples, 1, and a ramp out over its last `ramp` samples. A ramp out and the next chunk's ramp in fall on the+ same samples and add up to 1."""+ w = torch.ones(length, device=device)+ if ramp > 0:+ t = (torch.arange(ramp, device=device, dtype=torch.float32) + 0.5) / ramp+ if ramp_in:+ w[:skip] = 0+ w[skip : skip + ramp] = 0.5 * (1 - torch.cos(math.pi * t))+ if ramp_out:+ w[length - ramp :] = w[length - ramp :] * 0.5 * (1 + torch.cos(math.pi * t))+ return w+++def auto_chunk_seconds(rate, device, free_bytes=None):+ """Chunk length from the memory model: about (0.35 + 0.13 x rate/16 kHz x seconds) GB on CUDA, 60% of what is free;+ 10 s on a CPU below 32 kHz, else 5 s."""+ if torch.device(device).type != "cuda":+ return 10.0 if rate < 32000 else 5.0+ if free_bytes is None:+ try:+ free_bytes = torch.cuda.mem_get_info(torch.device(device))[0]+ except Exception:+ free_bytes = 2 * 1024**3+ free_gb = free_bytes / 1024**3+ return float(min(20.0, max(2.0, (0.6 * free_gb - 0.35) / (0.13 * rate / 16000))))++[email protected]_grad()+def enhance_chunked(segment, wav, sr, chunk_seconds, overlap_seconds, progress=None, check=None, window="crossfade"):+ """Run `segment(x (1, n)) -> (1, n)` over wav (C, N), a chunk at a time, joined by overlap-add.++ The input, the output and the weights stay where wav is (the CPU, from the node): `segment` moves each chunk to the+ model's device and its result comes back here, so only one chunk is ever in VRAM.++ window "crossfade": raised-cosine ramps over the overlap and weight 1 elsewhere (about 1.1x the work of one pass with+ 10-20 s chunks and 1 s of overlap). "hann": the repo's inference_chunk.py, a Hann window over each chunk at 50% hop.+ `check()` runs before every chunk (ComfyUI's Cancel), `progress(done, total)` after it."""+ C, N = wav.shape+ chunk = max(1, int(round(chunk_seconds * sr)))+ if window == "hann":+ overlap = chunk // 2+ else:+ overlap = min(int(round(overlap_seconds * sr)), chunk // 2)+ spans = chunk_spans(N, chunk, overlap)+ total = C * len(spans)+ out = torch.zeros_like(wav)+ wsum = torch.zeros(N, device=wav.device)+ done = 0+ for c in range(C):+ for i, (s, e) in enumerate(spans):+ if check:+ check()+ y = segment(wav[c : c + 1, s:e]).to(wav.device)+ if len(spans) == 1:+ w = torch.ones(e - s, device=wav.device)+ elif window == "hann":+ w = torch.clamp(torch.hann_window(e - s, device=wav.device), min=1e-7)+ else:+ # The last chunk ends at N, so it can start earlier than the others: it fades in where the chunk before+ # fades out, and its samples before that are left to the chunk before.+ skip = max(0, spans[i - 1][1] - overlap - s) if i > 0 else 0+ w = crossfade_weights(e - s, overlap, skip, ramp_in=i > 0, ramp_out=i < len(spans) - 1, device=wav.device)+ out[c, s:e] += y[0] * w+ if c == 0:+ wsum[s:e] += w+ del y+ done += 1+ if progress:+ progress(done, total)+ return out / wsum.clamp(min=1e-7)+++# ---------------------------------------------------------------- levels+++def frame_rms_p(x, sr, q=0.95, frame_s=0.03):+ """The q-th quantile of 30 ms frame RMS over all channels (the speech level when q is high)."""+ n = max(1, int(sr * frame_s))+ mono = x.float().mean(0) if x.dim() > 1 else x.float()+ frames = mono.shape[-1] // n+ if frames < 1:+ return float(mono.pow(2).mean().sqrt())+ rms = mono[: frames * n].reshape(frames, n).pow(2).mean(1).sqrt()+ return float(torch.quantile(rms, q))+++def lufs(x, sr):+ """Integrated loudness (ITU-R BS.1770, gated). x: (C, N)."""+ try:+ import torchaudio++ return float(torchaudio.functional.loudness(x.float().cpu(), sr))+ except Exception:+ return _lufs_fallback(x.float().cpu(), sr)+++def _biquad(x, b, a):+ # One biquad over a channel (only used when torchaudio has no loudness()): scipy when it is there, else a loop.+ import numpy as np++ try:+ from scipy.signal import lfilter++ return lfilter(b, a, x)+ except Exception:+ pass+ y = np.zeros_like(x)+ x1 = x2 = y1 = y2 = 0.0+ for i, v in enumerate(x):+ o = b[0] * v + b[1] * x1 + b[2] * x2 - a[1] * y1 - a[2] * y2+ x2, x1, y2, y1 = x1, v, y1, o+ y[i] = o+ return y+++def _lufs_fallback(x, sr):+ import numpy as np++ # K-weighting: a high shelf (+4 dB above about 1.5 kHz) then a high-pass at about 38 Hz (BS.1770-4's 48 kHz design,+ # re-derived for this rate).+ f0, G, Q = 1681.974450955533, 3.999843853973347, 0.7071752369554196+ K = math.tan(math.pi * f0 / sr)+ Vh = 10 ** (G / 20)+ Vb = Vh**0.4996667741545416+ a0 = 1 + K / Q + K * K+ shelf_b = [(Vh + Vb * K / Q + K * K) / a0, 2 * (K * K - Vh) / a0, (Vh - Vb * K / Q + K * K) / a0]+ shelf_a = [1.0, 2 * (K * K - 1) / a0, (1 - K / Q + K * K) / a0]+ f0, Q = 38.13547087602444, 0.5003270373238773+ K = math.tan(math.pi * f0 / sr)+ a0 = 1 + K / Q + K * K+ hp_b = [1.0, -2.0, 1.0]+ hp_a = [1.0, 2 * (K * K - 1) / a0, (1 - K / Q + K * K) / a0]+ chans = [_biquad(_biquad(c.numpy().astype(np.float64), shelf_b, shelf_a), hp_b, hp_a) for c in x]+ block, step = int(0.4 * sr), int(0.1 * sr)+ if x.shape[-1] < block:+ z = sum(float(np.mean(c**2)) for c in chans)+ return -0.691 + 10 * math.log10(max(z, 1e-12))+ zs = np.array([sum(float(np.mean(c[s : s + block] ** 2)) for c in chans) for s in range(0, x.shape[-1] - block + 1, step)])+ loud = -0.691 + 10 * np.log10(np.maximum(zs, 1e-12))+ zs = zs[loud > -70]+ if not len(zs):+ return -70.0+ rel = -0.691 + 10 * math.log10(float(np.mean(zs))) - 10+ zs2 = zs[(-0.691 + 10 * np.log10(zs)) > rel]+ return -0.691 + 10 * math.log10(float(np.mean(zs2 if len(zs2) else zs)))+++PEAK_CEILING = 10 ** (-1 / 20) # -1 dBFS+++def peak_limit(x, ceiling=PEAK_CEILING):+ """Scale x down (gain only) so its peak is at most `ceiling`."""+ peak = float(x.abs().max()) if x.numel() else 0.0+ return x * (ceiling / peak) if peak > ceiling else xdiff --git a/comfy-nodes/ComfyUI-RE-USE/tests/conftest.py b/comfy-nodes/ComfyUI-RE-USE/tests/conftest.pynew file mode 100644index 00000000..9a5124a4--- /dev/null+++ b/comfy-nodes/ComfyUI-RE-USE/tests/conftest.py@@ -0,0 +1,72 @@+"""Load the pack outside ComfyUI: a stand-in folder_paths module, and the pack imported as a package by its path.++Run from the pack's folder, in a venv of its own (never a live ComfyUI's Python):+ python -I -m pytest -q tests+The real-weight tests run only when RE_USE_WEIGHTS names model.safetensors (see test_real_weights.py).+"""+import importlib.util+import os+import sys+import tempfile+import types++import pytest++PACK = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+++def _fake_folder_paths(models_dir):+ fp = types.ModuleType("folder_paths")+ fp.models_dir = models_dir+ fp.folder_names_and_paths = {}++ def get_filename_list(name):+ out = []+ for d in fp.folder_names_and_paths[name][0]:+ if os.path.isdir(d):+ out += sorted(f for f in os.listdir(d) if os.path.splitext(f)[1] in fp.folder_names_and_paths[name][1])+ return out++ def get_full_path(name, f):+ for d in fp.folder_names_and_paths[name][0]:+ p = os.path.join(d, f)+ if os.path.isfile(p):+ return p+ return None++ fp.get_filename_list = get_filename_list+ fp.get_full_path = get_full_path+ return fp+++def _load_pack():+ models = tempfile.mkdtemp(prefix="reuse-models-")+ sys.modules["folder_paths"] = _fake_folder_paths(models)+ spec = importlib.util.spec_from_file_location("comfyui_re_use", os.path.join(PACK, "__init__.py"), submodule_search_locations=[PACK])+ mod = importlib.util.module_from_spec(spec)+ sys.modules["comfyui_re_use"] = mod+ spec.loader.exec_module(mod)+ return mod, models+++_PACK, _MODELS = _load_pack()++[email protected](scope="session")+def pack():+ return _PACK++[email protected](scope="session")+def engine():+ return sys.modules["comfyui_re_use.reuse_engine"]++[email protected](scope="session")+def nodes():+ return sys.modules["comfyui_re_use.nodes"]++[email protected](scope="session")+def models_dir():+ return _MODELSdiff --git a/comfy-nodes/ComfyUI-RE-USE/tests/pytest.ini b/comfy-nodes/ComfyUI-RE-USE/tests/pytest.ininew file mode 100644index 00000000..9e413647--- /dev/null+++ b/comfy-nodes/ComfyUI-RE-USE/tests/pytest.ini@@ -0,0 +1,3 @@+[pytest]+# The rootdir is this folder, so pytest never imports the pack folder above as a package (conftest.py loads it).+addopts = -p no:cacheproviderdiff --git a/comfy-nodes/ComfyUI-RE-USE/tests/test_engine.py b/comfy-nodes/ComfyUI-RE-USE/tests/test_engine.pynew file mode 100644index 00000000..cd25aa32--- /dev/null+++ b/comfy-nodes/ComfyUI-RE-USE/tests/test_engine.py@@ -0,0 +1,179 @@+"""The runtime without the real weights: the network's layout, the scans, chunking and levels."""+import hashlib+import math++import pytest+import torch++# The published model.safetensors (both NemotronLabs repositories): 1,416 tensors, these names and shapes.+STATE_DICT_SHA256 = "dd8f55c595948a376465faf60da9e4bac757d855d849697796c8a543fe1de57f"+PARAMETERS = 9_607_747+++def test_state_dict_has_the_published_layout(engine):+ m = engine.REUSE()+ lines = sorted(f"{k}:{'x'.join(map(str, v.shape))}" for k, v in m.state_dict().items())+ assert len(lines) == 1416+ assert hashlib.sha256("\n".join(lines).encode()).hexdigest() == STATE_DICT_SHA256+ assert sum(p.numel() for p in m.parameters()) == PARAMETERS+++def test_a_file_that_is_not_reuse_is_refused_in_words(engine, tmp_path):+ from safetensors.torch import save_file++ p = tmp_path / "other.safetensors"+ save_file({"weight": torch.zeros(2, 2)}, str(p))+ with pytest.raises(engine.NotReuseError, match="This file is not a RE-USE model"):+ engine.load_reuse(str(p))+++def _scan_inputs(B=2, L=37, Di=64, N=16, seed=0):+ g = torch.Generator().manual_seed(seed)+ u = torch.randn(B, L, Di, generator=g)+ delta = torch.nn.functional.softplus(torch.randn(B, L, Di, generator=g))+ # Trained A values run from about -593 to -0.05.+ A = -torch.exp(torch.empty(Di, N).uniform_(math.log(0.05), math.log(600), generator=g))+ Bm = torch.randn(B, L, N, generator=g)+ Cm = torch.randn(B, L, N, generator=g)+ return u, delta, A, Bm, Cm+++def _reference_scan(u, delta, A, Bm, Cm):+ # mamba_ssm's selective_scan_ref, written out: a float64 loop.+ u, delta, A, Bm, Cm = (t.double() for t in (u, delta, A, Bm, Cm))+ h = torch.zeros(u.shape[0], u.shape[2], A.shape[1], dtype=torch.float64)+ ys = []+ for t in range(u.shape[1]):+ h = torch.exp(delta[:, t, :, None] * A) * h + (delta[:, t] * u[:, t])[:, :, None] * Bm[:, t, None, :]+ ys.append((h * Cm[:, t, None, :]).sum(-1))+ return torch.stack(ys, 1).float()+++def test_the_pytorch_loop_matches_the_reference(engine):+ args = _scan_inputs()+ torch.testing.assert_close(engine.scan_loop(*args), _reference_scan(*args), atol=2e-4, rtol=1e-4)+++def test_the_numba_scan_matches_the_reference(engine):+ if not engine.numba_ok():+ pytest.skip("numba isn't installed here")+ args = _scan_inputs(seed=1)+ torch.testing.assert_close(engine.scan_numba(*args), _reference_scan(*args), atol=2e-4, rtol=1e-4)+++def test_the_triton_scan_matches_the_reference(engine):+ if not torch.cuda.is_available() or torch.cuda.device_count() < 1 or not engine.triton_ok():+ pytest.skip("no CUDA with Triton here")+ args = _scan_inputs(seed=2)+ y = engine.scan(*(t.cuda() for t in args), mode="triton").cpu()+ torch.testing.assert_close(y, _reference_scan(*args), atol=2e-4, rtol=1e-4)+++def test_auto_picks_a_scan_by_device(engine):+ assert engine.scan_kind("cpu") in ("numba", "torch-loop")+ assert engine.scan_kind("cpu", "torch-loop") == "torch-loop"++[email protected]("n", [1, 999, 8000, 8001, 47_000, 160_000])[email protected]("chunk,overlap", [(1.0, 0.25), (2.0, 1.0), (5.0, 1.0), (0.5, 0.25)])+def test_crossfade_chunking_gives_back_an_identity_exactly(engine, n, chunk, overlap):+ x = torch.randn(2, n)+ calls = []++ def ident(seg):+ calls.append(seg.shape[1])+ return seg.clone()++ y = engine.enhance_chunked(ident, x, 8000, chunk, overlap)+ torch.testing.assert_close(y, x, atol=1e-6, rtol=0)+ assert all(c <= max(1, int(chunk * 8000)) for c in calls)+++def test_crossfade_weights_add_up_to_one(engine):+ sr, chunk, ov = 1000, 3000, 500+ n = 10_400+ spans = engine.chunk_spans(n, chunk, ov)+ total = torch.zeros(n)+ for i, (s, e) in enumerate(spans):+ skip = max(0, spans[i - 1][1] - ov - s) if i > 0 else 0+ total[s:e] += engine.crossfade_weights(e - s, ov, skip, ramp_in=i > 0, ramp_out=i < len(spans) - 1)+ torch.testing.assert_close(total, torch.ones(n), atol=1e-6, rtol=0)+ assert spans[-1][1] == n and spans[0][0] == 0+++def test_hann_chunking_gives_back_an_identity(engine):+ x = torch.randn(1, 50_000)+ torch.testing.assert_close(engine.enhance_chunked(lambda s: s.clone(), x, 8000, 2.0, 1.0, window="hann"), x, atol=1e-5, rtol=0)+++def test_the_check_runs_before_every_chunk(engine):+ seen = []+ engine.enhance_chunked(lambda s: s.clone(), torch.randn(1, 40_000), 8000, 1.0, 0.25, check=lambda: seen.append(1))+ assert len(seen) == len(engine.chunk_spans(40_000, 8000, 2000))+++def test_auto_chunk_length(engine):+ assert engine.auto_chunk_seconds(16000, "cpu") == 10.0+ assert engine.auto_chunk_seconds(44100, "cpu") == 5.0+ gb = 1024**3+ # 2 GB free at 16 kHz: (1.2 - 0.35) / 0.13 = 6.5 s; plenty free: 20 s; almost nothing: 2 s.+ assert engine.auto_chunk_seconds(16000, "cuda", 2 * gb) == pytest.approx(6.54, abs=0.01)+ assert engine.auto_chunk_seconds(16000, "cuda", 30 * gb) == 20.0+ assert engine.auto_chunk_seconds(48000, "cuda", int(0.5 * gb)) == 2.0+++def test_loudness_fallback_agrees_with_torchaudio(engine):+ g = torch.Generator().manual_seed(3)+ sr = 24000+ t = torch.arange(sr * 3) / sr+ x = (0.2 * torch.sin(2 * math.pi * 440 * t) + 0.05 * torch.randn(sr * 3, generator=g)).unsqueeze(0)+ assert engine._lufs_fallback(x, sr) == pytest.approx(engine.lufs(x, sr), abs=0.3)+++def test_peak_limit(engine):+ x = torch.tensor([[0.5, -1.4, 0.2]])+ y = engine.peak_limit(x)+ assert float(y.abs().max()) == pytest.approx(10 ** (-1 / 20))+ assert torch.equal(engine.peak_limit(x * 0.1), x * 0.1)+++def test_a_triton_that_cannot_compile_falls_back_to_the_loop(engine, monkeypatch):+ def broken(*a):+ raise RuntimeError("Python.h: No such file or directory")++ monkeypatch.setattr(engine, "_TR", broken)+ monkeypatch.setattr(engine, "scan_kind", lambda device, mode="auto": "triton" if engine._TR else "torch-loop")+ args = _scan_inputs(seed=3)+ torch.testing.assert_close(engine.scan(*args), engine.scan_loop(*args))+ assert engine._TR is False+ assert engine.scan_kind("cuda") == "torch-loop"+++def test_a_forced_triton_scan_still_raises(engine, monkeypatch):+ def broken(*a):+ raise RuntimeError("no compiler")++ monkeypatch.setattr(engine, "_TR", broken)+ monkeypatch.setattr(engine, "scan_kind", lambda device, mode="auto": "triton")+ with pytest.raises(RuntimeError, match="no compiler"):+ engine.scan(*_scan_inputs(), mode="triton")+++def test_chunks_reach_the_model_one_at_a_time_and_the_result_stays_with_the_input(engine):+ # The node's segment moves a chunk to the model's device; the buffers stay with wav (the CPU).+ x = torch.randn(1, 40_000)+ seen = []++ def seg(s):+ seen.append(s.shape[1])+ return s.clone()++ y = engine.enhance_chunked(seg, x, 8000, 1.0, 0.25)+ assert y.device == x.device and max(seen) <= 8000+++def test_a_clip_shorter_than_the_stft_padding_still_runs(engine):+ m = engine.REUSE().eval()+ for n in (1, 50, 400):+ y = engine.enhance_segment(m, torch.randn(1, n) * 0.1, 48000)+ assert y.shape == (1, n)diff --git a/comfy-nodes/ComfyUI-RE-USE/tests/test_nodes.py b/comfy-nodes/ComfyUI-RE-USE/tests/test_nodes.pynew file mode 100644index 00000000..b20458cd--- /dev/null+++ b/comfy-nodes/ComfyUI-RE-USE/tests/test_nodes.py@@ -0,0 +1,166 @@+"""The nodes with a stand-in model (no weights): rates, channels, levels, room tone, the bed and Cancel."""+import json+import math+import sys+import types++import pytest+import torch+++def speech(sr, seconds=3.0, channels=1, level=0.3, seed=0):+ """Bursts of a harmonic tone with gaps, a little like speech (a level to match, pauses to fill)."""+ g = torch.Generator().manual_seed(seed)+ t = torch.arange(int(sr * seconds)) / sr+ gate = (torch.sin(2 * math.pi * 1.5 * t) > 0).float()+ x = level * gate * (torch.sin(2 * math.pi * 180 * t) + 0.4 * torch.sin(2 * math.pi * 360 * t)) + 0.01 * torch.randn(t.shape, generator=g)+ return x.repeat(channels, 1) * torch.linspace(1, 0.8, channels).unsqueeze(1)+++def run(nodes, monkeypatch, segment, audio, **kw):+ monkeypatch.setattr(nodes.E, "enhance_segment", lambda model, x, sr: segment(x))+ model = {"model": object(), "device": torch.device("cpu"), "name": "stand-in"}+ out, report = nodes.REUSEEnhance().enhance(model, audio, **kw)+ return out, json.loads(report)+++def audio_of(x, sr):+ return {"waveform": x.unsqueeze(0), "sample_rate": sr}+++def test_the_node_lists_the_inputs_fuobe_binds(nodes):+ t = nodes.REUSEEnhance.INPUT_TYPES()+ for k in ("reuse_model", "audio", "rate", "pre_lowpass", "channels", "chunk_seconds", "overlap_seconds", "room_tone_db", "level"):+ assert k in t["required"]+ assert set(t["optional"]) == {"bed", "bed_db"}+ assert t["required"]["rate"][0] == ["source", "source up to 24000", "source up to 16000", "8000", "16000", "22050", "24000", "32000", "44100", "48000"]+ assert nodes.REUSEEnhance.RETURN_TYPES == ("AUDIO", "STRING")+++def test_the_loader_registers_models_reuse(nodes, pack, models_dir):+ import folder_paths++ assert "reuse" in folder_paths.folder_names_and_paths+ assert nodes.REUSELoader.INPUT_TYPES()["required"]["model"][1]["default"] == "NemotronLabs-RE-USE.safetensors"+ with pytest.raises(FileNotFoundError, match="models/reuse"):+ nodes.REUSELoader().load("missing.safetensors", "cpu")+++ "sr,rate,want",+ [(44100, "source", 44100), (44100, "source up to 24000", 24000), (16000, "source up to 24000", 16000), (48000, "source up to 16000", 16000), (44100, "16000", 16000), (8000, "48000", 48000), (6000, "source", 8000), (96000, "source", 48000), (96000, "16000", 16000), (6000, "48000", 48000)],+)+def test_rates(nodes, monkeypatch, sr, rate, want):+ x = speech(sr, 1.0)+ out, rep = run(nodes, monkeypatch, lambda s: s.clone(), audio_of(x, sr), rate=rate, level="off")+ assert out["sample_rate"] == want and rep["rate"] == want and rep["input_rate"] == sr+ # Exactly the input's length at the new rate (a sample of rounding at most).+ assert abs(out["waveform"].shape[-1] - round(x.shape[-1] * want / sr)) <= 1+++def test_pre_lowpass_runs_down_then_up(nodes, monkeypatch):+ seen = []+ x = speech(48000, 1.0)+ out, _ = run(nodes, monkeypatch, lambda s: seen.append(s.shape[-1]) or s.clone(), audio_of(x, 48000), rate="48000", pre_lowpass="8000", level="off")+ assert out["sample_rate"] == 48000+ # The 8 kHz copy has no energy above 4 kHz: so neither has what the model got.+ spec = torch.fft.rfft(out["waveform"][0, 0])+ freqs = torch.fft.rfftfreq(out["waveform"].shape[-1], 1 / 48000)+ assert spec[freqs > 5000].abs().pow(2).sum() < 1e-3 * spec.abs().pow(2).sum()++[email protected]("channels,src,want", [("mono", 2, 1), ("each channel", 2, 2), ("each channel", 1, 1), ("each channel", 6, 1), ("mono", 6, 1)])+def test_channels(nodes, monkeypatch, channels, src, want):+ out, rep = run(nodes, monkeypatch, lambda s: s.clone(), audio_of(speech(16000, 1.0, src), 16000), channels=channels, level="off")+ assert out["waveform"].shape[1] == want+ assert rep["channels"] == ("mono" if want == 1 and (channels == "mono" or src > 2) else channels)+++def test_each_channel_runs_the_model_once_per_channel(nodes, monkeypatch):+ calls = []+ run(nodes, monkeypatch, lambda s: calls.append(1) or s.clone(), audio_of(speech(16000, 1.0, 2), 16000), channels="each channel", chunk_seconds=10.0, level="off")+ assert len(calls) == 2+++def db(x):+ return 20 * math.log10(x)+++def test_match_input_brings_back_the_speech_level(nodes, engine, monkeypatch):+ x = speech(24000, 3.0)+ # The model's output is quieter than its input (about 3 dB in practice): -6 dB here.+ out, rep = run(nodes, monkeypatch, lambda s: s * 0.5, audio_of(x, 24000), level="match input")+ y = out["waveform"][0]+ assert db(engine.frame_rms_p(y, 24000)) == pytest.approx(db(engine.frame_rms_p(x, 24000)), abs=0.5)+ assert rep["level_gain_db"] == pytest.approx(6.02, abs=0.1)+ assert float(y.abs().max()) <= 10 ** (-1 / 20) + 1e-6+++def test_match_input_gains_at_most_12_db_and_never_clips(nodes, monkeypatch):+ out, rep = run(nodes, monkeypatch, lambda s: s * 0.01, audio_of(speech(16000, 2.0, level=0.9), 16000), level="match input")+ assert rep["level_gain_db"] == pytest.approx(12.0)+ out, _ = run(nodes, monkeypatch, lambda s: s * 3, audio_of(speech(16000, 2.0, level=0.9), 16000), level="off")+ assert float(out["waveform"].abs().max()) <= 10 ** (-1 / 20) + 1e-6+++def test_voice_over_level(nodes, engine, monkeypatch):+ out, _ = run(nodes, monkeypatch, lambda s: s.clone(), audio_of(speech(24000, 4.0, level=0.05), 24000), level="-16 LUFS")+ assert engine.lufs(out["waveform"][0], 24000) == pytest.approx(-16, abs=1.0)+++def test_room_tone_adds_the_dry_signal_at_its_level(nodes, monkeypatch):+ x = speech(16000, 1.0)+ out, _ = run(nodes, monkeypatch, lambda s: torch.zeros_like(s), audio_of(x, 16000), room_tone_db=-24.0, level="off")+ torch.testing.assert_close(out["waveform"][0], x * 10 ** (-24 / 20), atol=1e-6, rtol=0)+ out, _ = run(nodes, monkeypatch, lambda s: torch.zeros_like(s), audio_of(x, 16000), room_tone_db=-60.0, level="off")+ assert float(out["waveform"].abs().max()) == 0+++def test_bed_is_matched_in_rate_and_channels_and_kept_under_full_scale(nodes, monkeypatch):+ voice = speech(16000, 2.0, level=0.6)+ bed = speech(48000, 2.0, channels=2, level=0.6, seed=4) * 1.2+ out, rep = run(nodes, monkeypatch, lambda s: s.clone(), audio_of(voice, 16000), level="off", bed={"waveform": bed.unsqueeze(0), "sample_rate": 48000}, bed_db=0.0)+ assert out["sample_rate"] == 48000 and rep["output_rate"] == 48000 and rep["rate"] == 16000+ assert out["waveform"].shape[1] == 2+ assert abs(out["waveform"].shape[-1] - bed.shape[-1]) <= 1+ assert float(out["waveform"].abs().max()) <= 10 ** (-1 / 20) + 1e-6+++def test_bed_at_a_lower_rate_takes_the_voice_rate(nodes, monkeypatch):+ bed = speech(16000, 1.0, channels=1, level=0.1, seed=5)+ out, _ = run(nodes, monkeypatch, lambda s: s.clone(), audio_of(speech(24000, 1.0, level=0.1), 24000), level="off", bed={"waveform": bed.unsqueeze(0), "sample_rate": 16000}, bed_db=-6.0)+ assert out["sample_rate"] == 24000 and out["waveform"].shape[1] == 1+++def test_cancel_is_checked_between_chunks(nodes, monkeypatch):+ calls = {"n": 0}++ def check():+ calls["n"] += 1+ if calls["n"] == 2:+ raise InterruptedError("cancelled")++ comfy = types.ModuleType("comfy")+ mm = types.ModuleType("comfy.model_management")+ mm.throw_exception_if_processing_interrupted = check+ comfy.model_management = mm+ monkeypatch.setitem(sys.modules, "comfy", comfy)+ monkeypatch.setitem(sys.modules, "comfy.model_management", mm)+ seen = []+ with pytest.raises(InterruptedError):+ run(nodes, monkeypatch, lambda s: seen.append(1) or s.clone(), audio_of(speech(8000, 5.0), 8000), chunk_seconds=1.0, level="off")+ assert len(seen) == 1+++def test_the_report_has_every_field(nodes, monkeypatch):+ _, rep = run(nodes, monkeypatch, lambda s: s.clone(), audio_of(speech(16000, 1.0), 16000))+ for k in ("model", "device", "scan", "input_rate", "rate", "output_rate", "channels", "chunk_seconds", "overlap_seconds", "seconds", "took", "times_real_time", "level_gain_db", "peak_vram_gb"):+ assert k in rep+ assert rep["device"] == "cpu" and rep["chunk_seconds"] == 10.0+++def test_a_batch_keeps_each_item(nodes, monkeypatch):+ x = torch.stack([speech(16000, 1.0), speech(16000, 1.0, seed=9)])+ out, _ = run(nodes, monkeypatch, lambda s: s.clone(), {"waveform": x, "sample_rate": 16000}, level="off")+ assert out["waveform"].shape == (2, 1, 16000)+ torch.testing.assert_close(out["waveform"], x, atol=1e-6, rtol=0)diff --git a/comfy-nodes/ComfyUI-RE-USE/tests/test_real_weights.py b/comfy-nodes/ComfyUI-RE-USE/tests/test_real_weights.pynew file mode 100644index 00000000..6f491944--- /dev/null+++ b/comfy-nodes/ComfyUI-RE-USE/tests/test_real_weights.py@@ -0,0 +1,63 @@+"""With the real weights. Skipped unless these are set (paths to local files):+ RE_USE_WEIGHTS models/reuse/NemotronLabs-RE-USE.safetensors+ RE_USE_SAMPLE noisy_audio/mic_test2.wav from NVIDIA's repository (5.1 s, 44.1 kHz)+ RE_USE_REFERENCE the same sample through the reference runtime at its own rate, in one pass (a WAV)+ RE_USE_LONG a longer recording (the chunking test uses its first 20 s at 8 kHz, so a CPU runs it in about 2 min)+"""+import math+import os++import pytest+import torch+import torchaudio++W = os.environ.get("RE_USE_WEIGHTS")+pytestmark = pytest.mark.skipif(not W or not os.path.isfile(W), reason="RE_USE_WEIGHTS isn't set")+++def read(path):+ import soundfile as sf++ x, sr = sf.read(path, dtype="float32", always_2d=True)+ return torch.from_numpy(x.T.copy()), sr+++def diff_snr(ref, y):+ n = min(ref.shape[-1], y.shape[-1])+ ref, y = ref[..., :n].double(), y[..., :n].double()+ return 10 * math.log10(float(ref.pow(2).sum()) / max(float((ref - y).pow(2).sum()), 1e-20))++[email protected](scope="module")+def model(engine):+ return engine.load_reuse(W, "cpu")+++def test_the_node_matches_the_reference_runtime(nodes, model):+ sample, ref = os.environ.get("RE_USE_SAMPLE"), os.environ.get("RE_USE_REFERENCE")+ if not (sample and ref):+ pytest.skip("RE_USE_SAMPLE / RE_USE_REFERENCE aren't set")+ x, sr = read(sample)+ out, _ = nodes.REUSEEnhance().enhance({"model": model, "device": torch.device("cpu"), "name": "test"}, {"waveform": x.unsqueeze(0), "sample_rate": sr}, chunk_seconds=10.0, level="off")+ r, rsr = read(ref)+ assert out["sample_rate"] == rsr+ assert diff_snr(r[:1], out["waveform"][0][:1]) >= 40+++def test_crossfade_chunks_are_as_close_to_one_pass_as_the_repos_hann_chunks(engine, model):+ """One pass over a long file is not the truth either: the network normalises over the whole input (InstanceNorm) and+ reads it both ways (bidirectional Mamba), so any chunking differs from it everywhere, not only at the joins. Measured+ on 20 s at 8 kHz: 5 s chunks 8.5 dB (crossfade) against 8.9 dB (the repo's Hann at 50%); 10 s chunks 14.8 against+ 14.9 dB. The crossfade must stay within 1 dB of the repo's method, at about half its work."""+ long = os.environ.get("RE_USE_LONG")+ if not long:+ pytest.skip("RE_USE_LONG isn't set")+ x, sr = read(long)+ x = torchaudio.functional.resample(x.mean(0, keepdim=True), sr, 8000)[:, : 20 * 8000]+ seg = lambda s: engine.enhance_segment(model, s, 8000) # noqa: E731+ whole = seg(x)+ cross = engine.enhance_chunked(seg, x, 8000, 10.0, 1.0)+ hann = engine.enhance_chunked(seg, x, 8000, 10.0, 1.0, window="hann")+ print(f"crossfade {diff_snr(whole, cross):.1f} dB, hann 50% {diff_snr(whole, hann):.1f} dB against one pass; crossfade against hann {diff_snr(hann, cross):.1f} dB")+ assert diff_snr(whole, cross) >= diff_snr(whole, hann) - 1.0+ assert diff_snr(hann, cross) >= 18