1717from dataclasses import dataclass
1818from datetime import datetime , timezone
1919from pathlib import Path
20+ from types import SimpleNamespace
2021from typing import Any
2122
2223import numpy as np
2526DEFAULT_CONFIG = Path (__file__ ).resolve ().with_name ("config.json" )
2627DEFAULT_INPUT_AUDIO = REPO_ROOT / "input_audio/reference_10_2.mp3"
2728DEFAULT_SAMPLE_RATE = 24000
29+ PRIMARY_PYTHON = REPO_ROOT / ".venv" / "bin" / "python"
2830DEFAULT_THRESHOLDS = {
2931 "corr_min" : 0.99 ,
3032 "mse_max" : 0.0001 ,
@@ -233,10 +235,318 @@ def parse_model_class(class_spec: str) -> tuple[str, str]:
233235 return module_name , class_name
234236
235237
238+ def preferred_python_executable () -> str :
239+ if PRIMARY_PYTHON .is_file ():
240+ return str (PRIMARY_PYTHON )
241+ return sys .executable
242+
243+
244+ def resolve_model_local_path (model_cfg : dict [str , Any ]) -> Path :
245+ local_path = model_cfg .get ("local_path" )
246+ if not local_path :
247+ return REPO_ROOT / "models" / model_cfg ["name" ]
248+ path = Path (local_path )
249+ if not path .is_absolute ():
250+ path = REPO_ROOT / path
251+ return path .resolve ()
252+
253+
254+ class NativeDacAdapter :
255+ def __init__ (self , model : Any ):
256+ self .model = model
257+
258+ def eval (self ):
259+ if hasattr (self .model , "eval" ):
260+ self .model .eval ()
261+ return self
262+
263+ def encode (self , * args , ** kwargs ):
264+ import torch
265+
266+ audio = kwargs .pop ("input_values" , None )
267+ if audio is None :
268+ audio = kwargs .pop ("audio_values" , None )
269+ if audio is None and args :
270+ audio = args [0 ]
271+ if audio is None :
272+ raise TypeError ("missing audio input" )
273+
274+ n_quantizers = kwargs .pop ("n_quantizers" , None )
275+ if kwargs :
276+ raise TypeError (f"unexpected kwargs: { sorted (kwargs .keys ())} " )
277+
278+ x = audio
279+ if isinstance (x , np .ndarray ):
280+ x = torch .from_numpy (x .astype (np .float32 , copy = False ))
281+ if x .ndim == 2 :
282+ x = x .unsqueeze (1 )
283+
284+ encode_calls : list [tuple [tuple [Any , ...], dict [str , Any ]]] = [((x ,), {})]
285+ if n_quantizers is not None :
286+ encode_calls .insert (0 , ((x ,), {"n_quantizers" : int (n_quantizers )}))
287+
288+ out = call_with_fallback (self .model .encode , encode_calls , "dac.native.encode" )
289+ if isinstance (out , tuple ):
290+ # Common DAC output: (latents, codes, ...)
291+ if len (out ) < 2 :
292+ raise RuntimeError ("dac native encode returned tuple without codes" )
293+ codes = out [1 ]
294+ elif hasattr (out , "audio_codes" ):
295+ codes = out .audio_codes
296+ else :
297+ raise RuntimeError ("dac native encode output does not expose codes" )
298+ return SimpleNamespace (audio_codes = codes )
299+
300+ def decode (self , * args , ** kwargs ):
301+ audio_codes = kwargs .pop ("audio_codes" , None )
302+ if audio_codes is None and args :
303+ audio_codes = args [0 ]
304+ if audio_codes is None :
305+ raise TypeError ("missing audio codes" )
306+ if kwargs :
307+ raise TypeError (f"unexpected kwargs: { sorted (kwargs .keys ())} " )
308+
309+ if hasattr (self .model , "quantizer" ) and hasattr (self .model .quantizer , "from_codes" ):
310+ latent = self .model .quantizer .from_codes (audio_codes )
311+ if isinstance (latent , tuple ):
312+ latent = latent [0 ]
313+ decoded = call_with_fallback (
314+ self .model .decode ,
315+ [((latent ,), {})],
316+ "dac.native.decode(latent)" ,
317+ )
318+ else :
319+ decoded = call_with_fallback (
320+ self .model .decode ,
321+ [((audio_codes ,), {})],
322+ "dac.native.decode(codes)" ,
323+ )
324+ return SimpleNamespace (audio_values = decoded )
325+
326+
327+ class NativeWavTokenizerAdapter :
328+ def __init__ (self , model : Any , default_bandwidth_id : int ):
329+ self .model = model
330+ self .default_bandwidth_id = int (default_bandwidth_id )
331+
332+ def eval (self ):
333+ if hasattr (self .model , "eval" ):
334+ self .model .eval ()
335+ return self
336+
337+ def encode (self , * args , ** kwargs ):
338+ import torch
339+
340+ audio = kwargs .pop ("input_values" , None )
341+ if audio is None :
342+ audio = kwargs .pop ("audio_values" , None )
343+ if audio is None and args :
344+ audio = args [0 ]
345+ if audio is None :
346+ raise TypeError ("missing audio input" )
347+
348+ bandwidth_id = kwargs .pop ("bandwidth_id" , None )
349+ if kwargs :
350+ raise TypeError (f"unexpected kwargs: { sorted (kwargs .keys ())} " )
351+ if bandwidth_id is None :
352+ bandwidth_id = torch .tensor ([self .default_bandwidth_id ], dtype = torch .long )
353+
354+ x = audio
355+ if isinstance (x , np .ndarray ):
356+ x = torch .from_numpy (x .astype (np .float32 , copy = False ))
357+ if x .ndim == 3 and x .shape [1 ] == 1 :
358+ x = x [:, 0 , :]
359+ if x .ndim == 1 :
360+ x = x .view (1 , - 1 )
361+
362+ if hasattr (self .model , "encode_infer" ):
363+ return call_with_fallback (
364+ self .model .encode_infer ,
365+ [
366+ ((x ,), {"bandwidth_id" : bandwidth_id }),
367+ ((x ,), {}),
368+ ],
369+ "wavtokenizer.native.encode_infer" ,
370+ )
371+
372+ return call_with_fallback (
373+ self .model .encode ,
374+ [
375+ ((x ,), {"bandwidth_id" : bandwidth_id }),
376+ ((x ,), {}),
377+ ],
378+ "wavtokenizer.native.encode" ,
379+ )
380+
381+ def decode (self , * args , ** kwargs ):
382+ if not args :
383+ raise TypeError ("missing features/tokens for decode" )
384+ return call_with_fallback (
385+ self .model .decode ,
386+ [
387+ (args , kwargs ),
388+ (args , {}),
389+ ],
390+ "wavtokenizer.native.decode" ,
391+ )
392+
393+
394+ def load_native_dac_model (model_cfg : dict [str , Any ]):
395+ try :
396+ dac = importlib .import_module ("dac" )
397+ except Exception as exc :
398+ raise RuntimeError (
399+ "dac model requires descript-audio-codec package in the active Python env"
400+ ) from exc
401+
402+ local_path = resolve_model_local_path (model_cfg )
403+ repo_id = model_cfg .get ("hf_repo_id" )
404+ errors : list [str ] = []
405+
406+ if local_path .exists ():
407+ load_fn = getattr (getattr (dac , "DAC" , None ), "load" , None )
408+ if callable (load_fn ):
409+ candidate_paths : list [Path ] = []
410+ if local_path .is_file ():
411+ candidate_paths .append (local_path )
412+ elif local_path .is_dir ():
413+ candidate_paths .extend (sorted (local_path .rglob ("*.pt" )))
414+ candidate_paths .extend (sorted (local_path .rglob ("*.ckpt" )))
415+
416+ for ckpt in candidate_paths :
417+ try :
418+ return NativeDacAdapter (load_fn (str (ckpt ))).eval ()
419+ except Exception as exc :
420+ errors .append (f"DAC.load({ ckpt } ) failed: { exc } " )
421+
422+ from_pretrained_fn = getattr (getattr (dac , "DAC" , None ), "from_pretrained" , None )
423+ if callable (from_pretrained_fn ) and repo_id :
424+ try :
425+ return NativeDacAdapter (from_pretrained_fn (repo_id )).eval ()
426+ except Exception as exc :
427+ errors .append (f"DAC.from_pretrained({ repo_id } ) failed: { exc } " )
428+
429+ raise RuntimeError (
430+ "failed to load dac model via descript-audio-codec; "
431+ f"local_path={ local_path } , hf_repo_id={ repo_id } , errors={ errors } "
432+ )
433+
434+
435+ def ensure_wavtokenizer_source () -> Path :
436+ """Clone WavTokenizer official repo to models/wavtokenizer-src/ if not exists."""
437+ src_path = REPO_ROOT / "models" / "wavtokenizer-src"
438+
439+ if src_path .exists () and (src_path / "decoder" / "pretrained.py" ).is_file ():
440+ return src_path
441+
442+ # Clone the official repo
443+ print (f"[wavtokenizer] Cloning official source to { src_path } ..." )
444+ src_path .parent .mkdir (parents = True , exist_ok = True )
445+
446+ cmd = [
447+ "git" , "clone" ,
448+ "--depth" , "1" ,
449+ "https://github.com/jishengpeng/WavTokenizer.git" ,
450+ str (src_path )
451+ ]
452+ result = subprocess .run (cmd , capture_output = True , text = True )
453+ if result .returncode != 0 :
454+ raise RuntimeError (f"Failed to clone WavTokenizer repo: { result .stderr } " )
455+
456+ if not (src_path / "decoder" / "pretrained.py" ).is_file ():
457+ raise RuntimeError (f"WavTokenizer source cloned but decoder/pretrained.py not found in { src_path } " )
458+
459+ print (f"[wavtokenizer] Source cloned to { src_path } " )
460+ return src_path
461+
462+
463+ def load_native_wavtokenizer_model (model_cfg : dict [str , Any ]):
464+ """Load WavTokenizer model using official source code from models/wavtokenizer-src/."""
465+ # 1. Ensure official source is cloned
466+ src_path = ensure_wavtokenizer_source ()
467+
468+ # 2. Model weights/checkpoints are in local_path (downloaded from HF)
469+ local_path = resolve_model_local_path (model_cfg )
470+
471+ # 3. Add source path to sys.path for importing
472+ src_path_str = str (src_path )
473+ if src_path_str not in sys .path :
474+ sys .path .insert (0 , src_path_str )
475+
476+ # Also need the repo root for other imports like encoder/decoder
477+ repo_path_str = str (src_path )
478+ if repo_path_str not in sys .path :
479+ sys .path .insert (0 , repo_path_str )
480+
481+ try :
482+ module = importlib .import_module ("decoder.pretrained" )
483+ wavtokenizer_cls = getattr (module , "WavTokenizer" )
484+ except Exception as exc :
485+ raise RuntimeError (
486+ f"failed to import WavTokenizer from source path={ src_path } "
487+ ) from exc
488+
489+ # Find config file (in local_path which contains HF downloaded files)
490+ config_candidates : list [Path ] = []
491+ explicit_config = model_cfg .get ("config_path" )
492+ if explicit_config :
493+ config_path = Path (explicit_config )
494+ config_candidates .append (config_path if config_path .is_absolute () else local_path / config_path )
495+ config_candidates .extend (
496+ [
497+ local_path / "checkpoints" / "config.yaml" ,
498+ local_path / "config.yaml" ,
499+ ]
500+ )
501+ config_path = next ((p for p in config_candidates if p .is_file ()), None )
502+ if config_path is None :
503+ raise RuntimeError (
504+ f"wavtokenizer config not found under local_path={ local_path } ; "
505+ "set model config_path or place checkpoints/config.yaml"
506+ )
507+
508+ # Find checkpoint file (in local_path)
509+ ckpt_candidates : list [Path ] = []
510+ explicit_ckpt = model_cfg .get ("checkpoint" )
511+ if explicit_ckpt :
512+ ckpt_path = Path (explicit_ckpt )
513+ ckpt_candidates .append (ckpt_path if ckpt_path .is_absolute () else local_path / ckpt_path )
514+ ckpt_candidates .extend (sorted ((local_path / "checkpoints" ).glob ("*.ckpt" )))
515+ ckpt_candidates .extend (sorted (local_path .glob ("*.ckpt" )))
516+ checkpoint_path = next ((p for p in ckpt_candidates if p .is_file ()), None )
517+
518+ load_errors : list [str ] = []
519+ model = None
520+
521+ # Use from_pretrained0802(config_path, checkpoint_path) as specified
522+ if checkpoint_path is not None and hasattr (wavtokenizer_cls , "from_pretrained0802" ):
523+ try :
524+ model = wavtokenizer_cls .from_pretrained0802 (str (config_path ), str (checkpoint_path ))
525+ except Exception as exc :
526+ load_errors .append (f"from_pretrained0802({ config_path } , { checkpoint_path } ) failed: { exc } " )
527+
528+ if model is None and hasattr (wavtokenizer_cls , "from_hparams0802" ):
529+ try :
530+ model = wavtokenizer_cls .from_hparams0802 (str (config_path ))
531+ except Exception as exc :
532+ load_errors .append (f"from_hparams0802({ config_path } ) failed: { exc } " )
533+
534+ if model is None :
535+ raise RuntimeError (
536+ "failed to construct WavTokenizer model; "
537+ f"src_path={ src_path } , local_path={ local_path } , config={ config_path } , checkpoint={ checkpoint_path } , "
538+ f"errors={ load_errors } "
539+ )
540+
541+ return NativeWavTokenizerAdapter (model , int (model_cfg .get ("bandwidth_id" , 0 ))).eval ()
542+
543+
236544def load_hf_model (model_cfg : dict [str , Any ]):
237545 module_name , class_name = parse_model_class (model_cfg ["class" ])
238- if module_name in {"dac" , "wavtokenizer" }:
239- return None
546+ if module_name == "dac" :
547+ return load_native_dac_model (model_cfg )
548+ if module_name == "wavtokenizer" :
549+ return load_native_wavtokenizer_model (model_cfg )
240550
241551 cache_dir = str (REPO_ROOT / "models" / "hf" )
242552 kwargs : dict [str , Any ] = {
@@ -500,7 +810,7 @@ def auto_convert_gguf(model_cfg: dict[str, Any], output_path: Path, log_path: Pa
500810 # For transformers models, use direct HF conversion
501811 if class_spec .startswith ("transformers:" ) and model_cfg .get ("converter" ) is None :
502812 cmd = [
503- sys . executable ,
813+ preferred_python_executable () ,
504814 str (REPO_ROOT / "scripts" / "convert-to-gguf.py" ),
505815 "--model-id" , model_cfg ["hf_repo_id" ],
506816 "--output" , str (output_path ),
@@ -511,7 +821,7 @@ def auto_convert_gguf(model_cfg: dict[str, Any], output_path: Path, log_path: Pa
511821
512822 converter = model_cfg .get ("converter" , model_name )
513823 cmd = [
514- sys . executable ,
824+ preferred_python_executable () ,
515825 str (REPO_ROOT / "scripts" / "convert-to-gguf.py" ),
516826 "--input-dir" , str (local_path ),
517827 "--output" , str (output_path ),
@@ -586,14 +896,14 @@ def run_model(report_dir: Path, model_cfg: dict[str, Any], input_audio: Path, sa
586896 if not input_audio .is_file ():
587897 raise RuntimeError (f"input audio not found: { input_audio } " )
588898
589- gguf_path = resolve_gguf_path (model_cfg )
590- if not gguf_path . is_file ( ):
591- # Auto-convert from HF if GGUF doesn't exist
592- if model_cfg . get ( "auto_convert" , True ):
593- print ( f"[ { name } ] GGUF not found, auto-converting from HF..." )
594- gguf_path = auto_convert_gguf ( model_cfg , gguf_path , log_path , name )
595- else :
596- raise RuntimeError (f"GGUF model not found: { gguf_path } " )
899+ expected_gguf = resolve_gguf_path (model_cfg )
900+ if model_cfg . get ( "auto_convert" , True ):
901+ print ( f"[ { name } ] Always regenerating GGUF from HF..." )
902+ gguf_path = auto_convert_gguf ( model_cfg , expected_gguf , log_path , name )
903+ else :
904+ gguf_path = expected_gguf
905+ if not gguf_path . is_file () :
906+ raise RuntimeError (f"GGUF model not found and auto_convert disabled : { gguf_path } " )
597907
598908 if mode == "conversion-only" :
599909 duration = time .monotonic () - start
0 commit comments