Download ecodec_fast/decoder.py from ESpeech/ECodec-FAST: direct link, hf CLI and curl.
- Browser
- Download file 4.58 kB
-
https://huggingface.co/ESpeech/ECodec-FAST/resolve/main/ecodec_fast/decoder.py
- Command line
-
hf download hf://ESpeech/ECodec-FAST/ecodec_fast/decoder.py
-
curl -L -o decoder.py https://huggingface.co/ESpeech/ECodec-FAST/resolve/main/ecodec_fast/decoder.py
4.58 kB
| """Public inference API for the ECodec-nano NSF decoder (binned-F0, v2). | |
| from decoder import NanoDecoderV2 | |
| dec = NanoDecoderV2() # loads weights + frozen ECodec front-end | |
| audio = dec.from_codes(codes) # MODE A: free-running pitch | |
| ref = dec.speaker_ref("prompt.wav") # MODE B: anchor pitch to a speaker | |
| audio = dec.from_codes(codes, ref=ref) | |
| See README.md for what the two modes are for. | |
| """ | |
| import os | |
| import sys | |
| import torch | |
| sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | |
| from nano_core import ECodecFrontend # noqa: E402 | |
| from model_nsf_v2 import NSFNanoDecoderV2 # noqa: E402 | |
| from nsf_source import F0BinnedPredictor # noqa: E402 | |
| WEIGHTS = os.path.join(os.environ.get("ECODEC_WEIGHTS") or os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."), "nano_nsf_v2_60k.pt") | |
| OUT_SR = 24000 | |
| MIN_NQ = 3 # below this the F0 predictor loses voicing (nq1 = 0% voiced, see README) | |
| class NanoDecoderV2: | |
| """codes [B,N,T] @21.53Hz -> 24kHz audio. Causal/streamable; N in 1..10 (use >=3).""" | |
| def __init__(self, weights: str = WEIGHTS, device: str = "cpu", threads: int | None = None): | |
| if threads: | |
| torch.set_num_threads(threads) | |
| # mmap + assign keeps the weights file-backed (evictable, shared between | |
| # worker processes) instead of copying them into anonymous memory. | |
| ck = torch.load(weights, map_location="cpu", weights_only=False, mmap=True) | |
| self.device = device | |
| self.G = NSFNanoDecoderV2(dim=ck.get("dim", 768), n_blocks=ck.get("n_blocks", 12)) | |
| try: | |
| self.G.load_state_dict(ck["G"], assign=True) | |
| except TypeError: # torch < 2.1 | |
| self.G.load_state_dict(ck["G"]) | |
| self.G.eval().to(device) | |
| self.fe = ECodecFrontend().eval().to(device) | |
| self.meta = {k: v for k, v in ck.items() if k != "G"} | |
| # ---- MODE B helper: speaker reference ------------------------------------------------- | |
| def speaker_ref(self, wav, sr: int | None = None): | |
| """Speaker prompt -> (log-F0 mean, std), to be passed as `ref`. Accepts a path or a tensor. | |
| Computed once per speaker; needs torchcrepe (only for this call, not for decoding).""" | |
| if isinstance(wav, str): | |
| import torchaudio | |
| wav, sr = torchaudio.load(wav) | |
| assert sr is not None, "sr required when passing a tensor" | |
| return F0BinnedPredictor.ref_stats_from_wav(wav, sr, device=self.device) | |
| # ---- decoding -------------------------------------------------------------------------- | |
| def from_codes(self, codes, nq: int | None = None, ref=None, ref_strength: float = 3.0, | |
| return_f0: bool = False): | |
| """codes [B,N,T] long -> audio [B,L] @24kHz. | |
| ref=None -> MODE A (free-running pitch, predicted from the codes alone) | |
| ref=speaker_ref(..) -> MODE B (pitch anchored to that speaker's range)""" | |
| if codes.dim() == 2: | |
| codes = codes[None] | |
| if nq is not None: | |
| codes = codes[:, :nq] | |
| if codes.shape[1] < MIN_NQ: | |
| print(f"warning: nq={codes.shape[1]} < {MIN_NQ}; voiced frames collapse (nq1 -> whisper)", | |
| file=sys.stderr) | |
| z86 = self.fe(codes.to(self.device)) | |
| out = self.G(z86, return_f0=return_f0, ref_stats=ref, | |
| prior_strength=(ref_strength if ref is not None else 0.0)) | |
| if return_f0: | |
| audio, _, f0 = out | |
| return audio.clamp(-1, 1), f0 | |
| return out.clamp(-1, 1) | |
| def from_z86(self, z86, ref=None, ref_strength: float = 3.0): | |
| """Latent [B,1024,T] @86.13Hz -> audio. For when the front-end already ran upstream.""" | |
| return self.G(z86.to(self.device), ref_stats=ref, | |
| prior_strength=(ref_strength if ref is not None else 0.0)).clamp(-1, 1) | |
| if __name__ == "__main__": | |
| import glob | |
| import numpy as np | |
| import torchaudio | |
| dec = NanoDecoderV2(threads=8) | |
| print(f"loaded {dec.meta.get('arch')} @step{dec.meta.get('step')} | " | |
| f"{sum(p.numel() for p in dec.G.parameters())/1e6:.2f}M | out {OUT_SR}Hz") | |
| import sys as _s | |
| codes = torch.from_numpy(np.load(_s.argv[1])[:10].astype(np.int64)) | |
| a = dec.from_codes(codes) | |
| torchaudio.save("prod_smoke.wav", a.cpu(), OUT_SR) | |
| print(f"MODE A ok: {tuple(a.shape)} -> prod_smoke.wav ({a.shape[-1]/OUT_SR:.2f}s)") | |