File size: 6,555 Bytes
3afd6d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
from __future__ import annotations

import importlib.util
import random
import re
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Any

import folder_paths

from .models import MissingEasyMediaModelError, notify_missing_model
from .model_memory import cleanup_model_memory


VOXCPM2_MODEL_NAME = "voxcpm2"
VOXCPM2_DISPLAY_NAME = "VoxCPM2"
VOXCPM2_OUTPUT_SUBFOLDER = "easy_media"
_ARABIC_DIGIT_PATTERN = re.compile(r"\d")
_UNSAFE_FILENAME_PATTERN = re.compile(r'[\\/:*?"<>|\r\n\t]+')


@dataclass(frozen=True)
class GeneratedSpeechAudio:
    file_path: str
    absolute_path: str
    source_type: str
    duration: float | None = None


def missing_speech_dependencies() -> list[str]:
    missing: list[str] = []
    if importlib.util.find_spec("voxcpm") is None:
        missing.append("voxcpm")
    return missing


def voxcpm2_model_dir() -> Path:
    return Path(folder_paths.models_dir) / "voxcpm" / "VoxCPM2"


def require_voxcpm2_model_dir() -> Path:
    path = voxcpm2_model_dir()
    if path.is_dir():
        return path
    notify_missing_model(VOXCPM2_MODEL_NAME)
    from .models import get_model_info

    raise MissingEasyMediaModelError(get_model_info(VOXCPM2_MODEL_NAME))


def contains_arabic_digits(text: str) -> bool:
    return _ARABIC_DIGIT_PATTERN.search(text) is not None


def default_speech_filename(text: str, suffix: str = ".wav") -> str:
    prefix = _UNSAFE_FILENAME_PATTERN.sub("_", text.strip())[:10].strip(" ._")
    if not prefix:
        prefix = "speech"
    stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    return f"{prefix}_{stamp}_{random.randint(1000, 9999)}{suffix}"


def _output_path_for_text(text: str) -> tuple[Path, str]:
    output_root = Path(folder_paths.get_output_directory())
    output_dir = output_root / VOXCPM2_OUTPUT_SUBFOLDER
    output_dir.mkdir(parents=True, exist_ok=True)
    filename = default_speech_filename(text)
    absolute_path = output_dir / filename
    relative_path = f"{VOXCPM2_OUTPUT_SUBFOLDER}/{filename}"
    return absolute_path, relative_path


def _write_audio_file(path: Path, audio: Any, sample_rate: int) -> None:
    try:
        import soundfile as sf  # type: ignore[import]
    except ImportError as error:
        raise RuntimeError("Saving VoxCPM2 audio requires soundfile. Install with: pip install soundfile") from error
    sf.write(path, audio, sample_rate)


def _model_sample_rate(model: Any) -> int | None:
    for owner in (model, getattr(model, "tts_model", None)):
        sample_rate = getattr(owner, "sample_rate", None)
        if isinstance(sample_rate, (int, float)):
            return int(sample_rate)
    return None


def _normalize_voxcpm_generate_result(result: Any, model: Any = None) -> tuple[int, Any]:
    if isinstance(result, tuple) and len(result) == 2:
        left, right = result
        if isinstance(left, (int, float)):
            return int(left), right
        if isinstance(right, (int, float)):
            return int(right), left
    if isinstance(result, dict):
        sample_rate = result.get("sample_rate") or result.get("sampling_rate") or result.get("sr")
        audio = result.get("audio") or result.get("wav") or result.get("waveform")
        if isinstance(sample_rate, (int, float)) and audio is not None:
            return int(sample_rate), audio
    sample_rate = _model_sample_rate(model)
    if sample_rate is not None:
        return sample_rate, result
    raise RuntimeError("VoxCPM2 returned an unsupported audio result.")


def _select_voxcpm_device() -> str:
    try:
        import torch  # type: ignore[import]
    except ImportError:
        return "cpu"

    if torch.cuda.is_available():
        return "cuda"

    mps_backend = getattr(getattr(torch, "backends", None), "mps", None)
    if mps_backend is not None and mps_backend.is_available():
        return "mps"

    return "cpu"


def _voxcpm_load_options() -> dict[str, Any]:
    device = _select_voxcpm_device()
    return {
        "device": device,
        "optimize": device.startswith("cuda"),
    }


def _seed_voxcpm_generation() -> int:
    seed = random.randint(0, 2**31 - 1)
    random.seed(seed)

    try:
        import numpy as np  # type: ignore[import]

        np.random.seed(seed)
    except ImportError:
        pass

    try:
        import torch  # type: ignore[import]

        manual_seed = getattr(torch, "manual_seed", None)
        if callable(manual_seed):
            manual_seed(seed)
        if torch.cuda.is_available():
            manual_seed_all = getattr(torch.cuda, "manual_seed_all", None)
            if callable(manual_seed_all):
                manual_seed_all(seed)
    except ImportError:
        pass

    return seed


def _voxcpm_target_text(text: str, prompt: str) -> str:
    prompt = prompt.strip()
    if not prompt:
        return text
    return f"({prompt}){text}"


def generate_voxcpm2_speech(
    *,
    text: str,
    prompt: str,
    cfg: float,
    steps: int,
    reference_audio_path: Path | None = None,
) -> GeneratedSpeechAudio:
    missing_dependencies = missing_speech_dependencies()
    if missing_dependencies:
        packages = " ".join(missing_dependencies)
        raise RuntimeError(f"Missing Python dependencies: {packages}. Install with: pip install {packages}")

    model_dir = require_voxcpm2_model_dir()
    from voxcpm import VoxCPM  # type: ignore[import]

    model = None
    try:
        model = VoxCPM.from_pretrained(str(model_dir), **_voxcpm_load_options())
        target_text = _voxcpm_target_text(text, prompt)
        generate_kwargs: dict[str, Any] = {
            "text": target_text,
            "cfg_value": float(cfg),
            "inference_timesteps": int(steps),
            "normalize": contains_arabic_digits(target_text),
        }
        if reference_audio_path is not None:
            generate_kwargs["reference_wav_path"] = str(reference_audio_path)

        _seed_voxcpm_generation()
        sample_rate, audio = _normalize_voxcpm_generate_result(model.generate(**generate_kwargs), model)
        output_path, relative_path = _output_path_for_text(text)
        _write_audio_file(output_path, audio, sample_rate)
    finally:
        cleanup_model_memory(model)

    duration: float | None = None
    try:
        duration = len(audio) / float(sample_rate)
    except Exception:
        duration = None

    return GeneratedSpeechAudio(
        file_path=relative_path,
        absolute_path=str(output_path),
        source_type="output",
        duration=duration,
    )