import os import sys import numpy as np import torch import gradio as gr import spaces # noqa: F401 from typing import Optional, Tuple from funasr import AutoModel from pathlib import Path os.environ["TOKENIZERS_PARALLELISM"] = "false" if os.environ.get("HF_REPO_ID", "").strip() == "": os.environ["HF_REPO_ID"] = "openbmb/VoxCPM2" import voxcpm class VoxCPMDemo: def __init__(self) -> None: self.device = "cuda" if torch.cuda.is_available() else "cpu" print(f"🚀 Running on device: {self.device}", file=sys.stderr) # ASR model for prompt text recognition self.asr_model_id = "iic/SenseVoiceSmall" self.asr_model: Optional[AutoModel] = AutoModel( model=self.asr_model_id, disable_update=True, log_level="DEBUG", device="cuda:0" if self.device == "cuda" else "cpu", ) # TTS model (lazy init) self.voxcpm_model: Optional[voxcpm.VoxCPM] = None self.default_local_model_dir = "/Users/xinliu/Downloads/VoxCPM2-0.5B-newaudiovae-6hz-0316" # ---------- Model helpers ---------- def _resolve_model_dir(self) -> str: """ Resolve model directory: 1) Use local checkpoint directory if exists 2) If HF_REPO_ID env is set, download into models/{repo} 3) Fallback to 'models' """ if os.path.isdir(self.default_local_model_dir): return self.default_local_model_dir repo_id = os.environ.get("HF_REPO_ID", "").strip() if len(repo_id) > 0: target_dir = os.path.join("models", repo_id.replace("/", "__")) if not os.path.isdir(target_dir): try: from huggingface_hub import snapshot_download # type: ignore os.makedirs(target_dir, exist_ok=True) print(f"Downloading model from HF repo '{repo_id}' to '{target_dir}' ...", file=sys.stderr) snapshot_download(repo_id=repo_id, local_dir=target_dir, local_dir_use_symlinks=False) except Exception as e: print(f"Warning: HF download failed: {e}. Falling back to 'data'.", file=sys.stderr) return "models" return target_dir return "models" def get_or_load_voxcpm(self) -> voxcpm.VoxCPM: if self.voxcpm_model is not None: return self.voxcpm_model print("Model not loaded, initializing...", file=sys.stderr) model_dir = self._resolve_model_dir() print(f"Using model dir: {model_dir}", file=sys.stderr) self.voxcpm_model = voxcpm.VoxCPM(voxcpm_model_path=model_dir, optimize=False) print("Model loaded successfully.", file=sys.stderr) return self.voxcpm_model # ---------- Functional endpoints ---------- def prompt_wav_recognition(self, prompt_wav: Optional[str]) -> str: if prompt_wav is None: return "" res = self.asr_model.generate(input=prompt_wav, language="auto", use_itn=True) text = res[0]["text"].split("|>")[-1] return text def generate_tts_audio( self, text_input: str, control_instruction: str = "", reference_wav_path_input: Optional[str] = None, cfg_value_input: float = 2.0, inference_timesteps_input: int = 10, do_normalize: bool = True, denoise: bool = True, ) -> Tuple[int, np.ndarray]: """ Generate speech from text using VoxCPM. - If reference_wav provided: Prompt isolation mode (voice cloning) - If no reference_wav: Voice design mode (use control_instruction to describe voice) Returns (sample_rate, waveform_numpy) """ current_model = self.get_or_load_voxcpm() text = (text_input or "").strip() if len(text) == 0: raise ValueError("Please input text to synthesize.") # 处理 control instruction control = (control_instruction or "").strip() if control: final_text = f"({control}){text}" else: final_text = text reference_wav_path = reference_wav_path_input if reference_wav_path_input else None # 判断模式 if reference_wav_path: print(f"[Prompt Isolation Mode] reference_wav: {reference_wav_path}", file=sys.stderr) else: print(f"[Voice Design Mode] control: {control[:50] if control else 'None'}...", file=sys.stderr) print(f"Generating audio for text: '{final_text[:80]}...'", file=sys.stderr) wav = current_model.generate( text=final_text, reference_wav_path=reference_wav_path, cfg_value=float(cfg_value_input), inference_timesteps=int(inference_timesteps_input), normalize=do_normalize, denoise=denoise, ) return (current_model.tts_model.sample_rate, wav) # ---------- UI Builders ---------- THEME = gr.themes.Soft( primary_hue="blue", secondary_hue="gray", neutral_hue="slate", font=[gr.themes.GoogleFont("Inter"), "Arial", "sans-serif"], ) CSS = """ .logo-container { text-align: center; margin: 0.5rem 0 1rem 0; } .logo-container img { height: 80px; width: auto; max-width: 200px; display: inline-block; } /* Bold accordion labels */ #acc_quick > .label-wrap, #acc_tips > .label-wrap, #acc_quick > .label-wrap > span, #acc_tips > .label-wrap > span, #acc_quick summary, #acc_tips summary { font-weight: 600 !important; font-size: 1.1em !important; } /* Bold labels for specific checkboxes */ #chk_denoise label, #chk_denoise span, #chk_normalize label, #chk_normalize span { font-weight: 600; } """ def create_demo_interface(demo: VoxCPMDemo): """Build the Gradio UI for VoxCPM demo.""" gr.set_static_paths(paths=[Path.cwd().absolute() / "assets"]) with gr.Blocks() as interface: gr.HTML( '
