"""Portable, pinned-base inference for Humane Voice Large Alpha 1.4. This is a custom Linear adapter, not a PEFT PeftModel. Adapter arithmetic stays FP32 even when the frozen base and codec execute in BF16. """ import argparse import hashlib import importlib.util import json from pathlib import Path HERE = Path(__file__).resolve().parent def sha256(path): digest = hashlib.sha256() with Path(path).open('rb') as stream: for block in iter(lambda: stream.read(8 << 20), b''): digest.update(block) return digest.hexdigest() def _module(name, path): spec = importlib.util.spec_from_file_location(name, path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module def resolve_base(base=None): """Download only the pinned model revision, or use an explicitly local copy. A caller-supplied local copy must contain that revision's unchanged files. It is useful for offline servers but its provenance is the caller's duty. """ cfg = json.loads((HERE / 'adapter_config.json').read_text()) if base is not None: directory = Path(base) if not (directory / 'infer.py').is_file(): raise ValueError('--base must be a downloaded base-model directory') return directory from huggingface_hub import snapshot_download return Path(snapshot_download(cfg['base_model'], revision=cfg['base_revision'])) def attach_adapter(model, directory=HERE): from safetensors.torch import load_file module = _module('humane14_custom_adapters', HERE / 'training' / 'adapters.py') cfg = json.loads((Path(directory) / 'adapter_config.json').read_text()) filename = Path(directory) / 'adapter.safetensors' if sha256(filename) != cfg['adapter_sha256']: raise ValueError('Adapter integrity check failed') module.attach(model, cfg['rank']) state = load_file(str(filename), device='cpu') params = {name: value for name, value in model.named_parameters() if value.requires_grad} if set(state) != set(params): raise ValueError('Adapter/base tensor names differ; do not use another base revision') if len(state) != cfg['parameter_tensors'] or sum(v.numel() for v in state.values()) != cfg['trainable_parameters']: raise ValueError('Unexpected adapter size') if any(tuple(state[n].shape) != tuple(p.shape) for n, p in params.items()): raise ValueError('Adapter/base tensor shapes differ') module.restore(model, state) model.requires_grad_(False).eval() return model def load(directory=HERE, *, base=None, device='cuda:0'): base = resolve_base(base) api = _module('humane14_pinned_base_infer', base / 'infer.py') model, processor = api.load_model(base, device=device) attach_adapter(model, directory) return model, processor, api def main(): p = argparse.ArgumentParser(description=__doc__) p.add_argument('--base', type=Path) p.add_argument('--codec', default='OpenMOSS-Team/MOSS-Audio-Tokenizer-v2') p.add_argument('--text', required=True, help='Only the words to be spoken') prompt = p.add_mutually_exclusive_group(required=True) prompt.add_argument('--prompt') prompt.add_argument('--prompt-file', type=Path) voice = p.add_mutually_exclusive_group() voice.add_argument('--reference-wav', type=Path) voice.add_argument('--voice-name', help='Optional alias from the pinned base catalog') p.add_argument('--language', choices=['en', 'de', 'fr', 'nl', 'es'], default='en') p.add_argument('--seconds', type=float, default=8.) p.add_argument('--seed', type=int, default=777) p.add_argument('--output', required=True, type=Path) a = p.parse_args() if not 1 <= a.seconds <= 60: p.error('Requested duration must be between 1 and 60 seconds') if a.output.exists(): raise FileExistsError('Refusing to overwrite ' + str(a.output)) import numpy as np import soundfile as sf import torch if not torch.cuda.is_available(): raise RuntimeError('The tested generation path requires a CUDA GPU') model, proc, api = load(base=a.base) api.load_codec(proc, a.codec) reference = None if a.reference_wav: wave, rate = sf.read(a.reference_wav, dtype='float32', always_2d=True) if not np.isfinite(wave).all() or len(wave) / rate < 5.04: raise ValueError('Use clean, single-speaker reference speech lasting at least 5.04 seconds') # Preserve 5.04–14.96 s. Never silently restore the historical 2.96 s cap. wave = wave[:int(rate * 14.96)] with torch.inference_mode(): reference = proc.encode_audios_from_wav([torch.from_numpy(wave.T.copy())], int(rate), n_vq=12)[0][:187] directions = a.prompt_file.read_text() if a.prompt_file else a.prompt.replace('\\n', '\n') frames = round(a.seconds * 12.5) user = api.build_user(proc, text=a.text, prompt=directions, frames=frames, language=a.language, reference=reference, alias=a.voice_name) codes = api.generate(model, proc, user, seed=a.seed, max_frames=min(1000, frames + 190)) wave, rate = api.decode(proc, codes) a.output.parent.mkdir(parents=True, exist_ok=True) sf.write(a.output, wave, rate, subtype='PCM_16') print(json.dumps({'duration_s': len(wave) / rate, 'frames': len(codes), 'seed': a.seed, 'reference_frames': len(reference) if reference is not None else 0, 'adapter': 'Humane Voice Large Alpha 1.4', 'adapter_scale': 1.0})) if __name__ == '__main__': main()