File size: 12,795 Bytes
68b44a1
be85c0f
e522f34
68b44a1
be85c0f
f9f777d
68b44a1
be85c0f
 
 
e84f64a
 
68b44a1
be85c0f
 
 
68b44a1
be85c0f
36f8bee
 
 
 
 
68b44a1
 
470953a
 
e522f34
68b44a1
 
7c7c63c
68b44a1
 
 
be85c0f
68b44a1
 
 
 
 
 
 
 
 
be85c0f
68b44a1
 
31c0008
be85c0f
b52eab0
68b44a1
470953a
 
 
68b44a1
470953a
68b44a1
 
 
470953a
68b44a1
 
 
e522f34
470953a
68b44a1
470953a
 
68b44a1
470953a
 
 
 
68b44a1
470953a
68b44a1
 
470953a
 
 
 
 
 
 
 
 
68b44a1
470953a
 
 
 
 
 
 
 
68b44a1
470953a
be85c0f
68b44a1
470953a
be85c0f
e522f34
 
 
 
470953a
 
e522f34
 
 
68b44a1
e522f34
 
 
 
 
 
be85c0f
68b44a1
be85c0f
 
68b44a1
 
 
 
 
be85c0f
 
 
 
 
68b44a1
be85c0f
 
 
68b44a1
be85c0f
 
7c7c63c
68b44a1
 
 
 
 
be85c0f
 
68b44a1
be85c0f
 
 
68b44a1
be85c0f
68b44a1
be85c0f
 
 
68b44a1
 
 
470953a
 
68b44a1
 
470953a
68b44a1
 
 
470953a
68b44a1
e84f64a
68b44a1
 
e84f64a
 
68b44a1
 
e84f64a
 
 
 
68b44a1
470953a
 
 
 
 
68b44a1
e84f64a
 
68b44a1
 
 
 
e84f64a
 
 
 
f9f777d
68b44a1
f9f777d
 
 
 
 
68b44a1
f9f777d
 
68b44a1
f9f777d
 
 
68b44a1
f9f777d
 
be85c0f
 
68b44a1
 
 
 
 
 
 
 
f52f228
 
f9f777d
470953a
 
 
 
 
 
be85c0f
470953a
be85c0f
f9f777d
68b44a1
be85c0f
470953a
f9f777d
68b44a1
 
470953a
 
 
 
 
 
 
 
 
68b44a1
470953a
68b44a1
 
470953a
 
 
e522f34
470953a
 
 
 
e522f34
68b44a1
470953a
 
 
 
 
68b44a1
470953a
 
 
 
 
 
 
 
 
 
 
 
f52f228
68b44a1
 
 
 
470953a
 
f9f777d
470953a
f9f777d
470953a
f9f777d
f52f228
be85c0f
68b44a1
 
 
 
470953a
 
 
 
 
 
68b44a1
64b50bd
f9f777d
 
 
 
 
 
68b44a1
470953a
68b44a1
470953a
 
 
 
68b44a1
f9f777d
68b44a1
f9f777d
 
68b44a1
470953a
e522f34
68b44a1
f9f777d
 
 
 
 
 
 
 
 
 
 
 
68b44a1
 
f9f777d
68b44a1
f9f777d
 
 
68b44a1
 
 
 
 
 
f9f777d
68b44a1
 
 
f9f777d
 
 
68b44a1
 
 
 
 
 
f9f777d
68b44a1
f9f777d
 
 
68b44a1
 
 
 
 
 
 
 
f9f777d
 
 
68b44a1
 
 
f9f777d
68b44a1
 
 
 
 
 
 
 
 
 
 
 
 
470953a
 
 
68b44a1
 
 
 
 
 
470953a
 
 
 
 
 
68b44a1
470953a
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
import base64
import os
import tempfile
import uuid
from pathlib import Path
from threading import Lock
from typing import Dict, Optional

import requests
import torch
import torchaudio
from torchaudio.transforms import Resample
from fastapi import BackgroundTasks, Body, FastAPI, Header, HTTPException
from fastapi.responses import FileResponse, JSONResponse
from pydantic import BaseModel, Field, HttpUrl

# Environment configuration
SPACE_API_KEY = os.getenv("SPACE_API_KEY")
HF_TOKEN = (
    os.getenv("HUGGING_FACE_HUB_TOKEN")
    or os.getenv("HUGGINGFACEHUB_API_TOKEN")
    or os.getenv("HF_TOKEN")
)

# Model configuration
OPENVOICE_REPO = "myshell-ai/OpenVoiceV2"
MODEL_DIR = os.getenv("MODEL_DIR", "/data/openvoice")
MAX_TEXT_LENGTH = 1000
DEFAULT_LANGUAGE = "en"
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"

# Job management
JOBS: Dict[str, Dict[str, str]] = {}
JOB_LOCK = Lock()

# Set token in environment before importing
if HF_TOKEN:
    os.environ["HUGGING_FACE_HUB_TOKEN"] = HF_TOKEN
    os.environ["HF_TOKEN"] = HF_TOKEN
    try:
        from huggingface_hub import login
        login(token=HF_TOKEN, add_to_git_credential=False)
    except ImportError:
        pass

# Download model checkpoints from Hugging Face
os.makedirs(MODEL_DIR, exist_ok=True)

try:
    from huggingface_hub import snapshot_download
    
    # Download OpenVoice model if not already present
    if not Path(MODEL_DIR, "converter").exists():
        print(f"Downloading OpenVoice model from {OPENVOICE_REPO}...")
        snapshot_download(
            repo_id=OPENVOICE_REPO,
            local_dir=MODEL_DIR,
            token=HF_TOKEN,
        )
        print("OpenVoice model download complete.")
except Exception as exc:
    print(f"Warning: Could not download model: {exc}")
    # Continue anyway - model might already be present

# Initialize OpenVoice
try:
    from openvoice import se_extractor
    from openvoice.api import BaseSpeakerTTS, ToneColorConverter
    
    # Initialize base TTS model (MeloTTS)
    ckpt_converter = os.path.join(MODEL_DIR, "converter")
    
    if not Path(ckpt_converter).exists():
        raise FileNotFoundError(
            f"Converter checkpoint not found at {ckpt_converter}. Model may not be downloaded."
        )
    
    # Initialize TTS and Tone Color Converter
    base_speaker_tts = BaseSpeakerTTS(
        f'{MODEL_DIR}/base_speakers/EN/config.json',
        device=DEVICE
    )
    
    tone_color_converter = ToneColorConverter(
        f'{ckpt_converter}/config.json',
        device=DEVICE
    )
    
    # Load source speaker embedding (default voice)
    source_se = torch.load(
        f'{MODEL_DIR}/base_speakers/EN/en_default_se.pth',
        map_location=DEVICE
    )
    
    print("OpenVoice model loaded successfully.")
except Exception as exc:
    raise RuntimeError(f"Failed to load OpenVoice model: {exc}") from exc

# Initialize FastAPI app
app = FastAPI(title="openvoice-api", version="1.0.0")


class GenerateRequest(BaseModel):
    text: str = Field(..., min_length=1, max_length=MAX_TEXT_LENGTH)
    speaker_wav: str = Field(..., description="HTTPS URL or base64-encoded audio")
    language: Optional[str] = Field(DEFAULT_LANGUAGE, description="ISO code: en, es, fr, zh, ja, ko")
    speed: Optional[float] = Field(1.0, ge=0.5, le=2.0, description="Speech speed (0.5-2.0)")


def _require_api_key(x_api_key: Optional[str]):
    """Validate API key if configured."""
    if not SPACE_API_KEY:
        return
    if x_api_key != SPACE_API_KEY:
        raise HTTPException(status_code=401, detail="Unauthorized")


def _write_temp_audio_from_url(url: HttpUrl) -> str:
    """Download audio from URL to temporary file."""
    response = requests.get(url, stream=True, timeout=30)
    if response.status_code >= 400:
        raise HTTPException(
            status_code=400,
            detail=f"Could not fetch speaker audio: {response.status_code}"
        )
    
    suffix = Path(url.path).suffix or ".wav"
    with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
        for chunk in response.iter_content(chunk_size=8192):
            if chunk:
                tmp.write(chunk)
    return tmp.name


def _write_temp_audio_from_base64(payload: str) -> str:
    """Decode base64 audio to temporary file."""
    try:
        raw = base64.b64decode(payload)
    except Exception as exc:
        raise HTTPException(
            status_code=400,
            detail="Invalid base64 speaker_wav"
        ) from exc
    
    with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp:
        tmp.write(raw)
    return tmp.name


def _temp_speaker_file(speaker_wav: str) -> str:
    """Handle speaker audio input from URL or base64."""
    if speaker_wav.startswith("http://") or speaker_wav.startswith("https://"):
        return _write_temp_audio_from_url(HttpUrl(speaker_wav))
    return _write_temp_audio_from_base64(speaker_wav)


def _preprocess_audio_wav(
    path: str, 
    target_sr: int = 24000, 
    target_peak: float = 0.98,
    min_duration: float = 3.0
) -> str:
    """
    Preprocess audio for optimal voice cloning:
    - convert to mono
    - resample to target_sr
    - peak-normalize to target_peak (avoid clipping)
    - ensure minimum duration (OpenVoice works better with 3-10s audio)
    """
    wav, sr = torchaudio.load(path)
    
    # Convert to mono
    if wav.shape[0] > 1:
        wav = wav.mean(dim=0, keepdim=True)
    
    # Resample if needed
    if sr != target_sr:
        resampler = Resample(orig_freq=sr, new_freq=target_sr)
        wav = resampler(wav)
        sr = target_sr
    
    # Check duration (OpenVoice recommends 3-10 seconds)
    duration = wav.shape[1] / sr
    if duration < min_duration:
        print(f"Warning: Reference audio is {duration:.2f}s. OpenVoice works best with 3-10s audio.")
    
    # Peak normalize
    peak = wav.abs().max().item() if wav.numel() else 0.0
    if peak > 0:
        scale = min(target_peak / peak, 1.0)
        wav = wav * scale
    
    # Overwrite input file to avoid extra temp files
    torchaudio.save(path, wav, sr, bits_per_sample=16)
    return path


def _set_job(job_id: str, **kwargs):
    """Thread-safe job update."""
    with JOB_LOCK:
        JOBS[job_id] = {**JOBS.get(job_id, {}), **kwargs}


def _get_job(job_id: str) -> Optional[Dict[str, str]]:
    """Thread-safe job retrieval."""
    with JOB_LOCK:
        data = JOBS.get(job_id)
        return dict(data) if data else None


def _pop_job(job_id: str) -> Optional[Dict[str, str]]:
    """Thread-safe job removal."""
    with JOB_LOCK:
        return JOBS.pop(job_id, None)


def _cleanup_files(*files: str):
    """Background task to clean up temporary files after response is sent."""
    for file_path in files:
        if file_path and Path(file_path).exists():
            try:
                Path(file_path).unlink(missing_ok=True)
            except Exception:
                pass  # Ignore cleanup errors


def _run_generate_job(job_id: str, payload: Dict[str, str]):
    """
    Background job for TTS generation using OpenVoice.
    Two-step process:
    1. Generate base speech with BaseSpeakerTTS
    2. Apply target voice characteristics with ToneColorConverter
    """
    speaker_file = None
    temp_audio = None
    output_file = None
    _set_job(job_id, status="processing")
    
    try:
        # Step 1: Prepare reference audio and extract speaker embedding
        speaker_file = _temp_speaker_file(payload["speaker_wav"])
        speaker_file = _preprocess_audio_wav(speaker_file)
        
        # Extract target speaker embedding
        target_se, _ = se_extractor.get_se(
            speaker_file, 
            tone_color_converter, 
            vad=True  # Voice activity detection for better extraction
        )
        
        # Step 2: Generate base speech with default voice
        temp_audio = os.path.join(
            tempfile.gettempdir(), 
            f"openvoice-temp-{uuid.uuid4()}.wav"
        )
        
        speed = float(payload.get("speed", 1.0))
        
        base_speaker_tts.tts(
            text=payload["text"],
            output_path=temp_audio,
            speaker='default',
            language=payload.get("language", "en").upper(),
            speed=speed
        )
        
        # Step 3: Apply target voice characteristics
        output_file = os.path.join(
            tempfile.gettempdir(), 
            f"openvoice-{uuid.uuid4()}.wav"
        )
        
        # Encode with watermark (set to False if not needed)
        encode_message = "@MyShell"
        
        tone_color_converter.convert(
            audio_src_path=temp_audio,
            src_se=source_se,
            tgt_se=target_se,
            output_path=output_file,
            message=encode_message
        )
        
        # Verify output exists
        if not Path(output_file).exists():
            raise RuntimeError(
                f"TTS generation failed: output file was not created at {output_file}"
            )
        
        # Cleanup intermediate files
        _cleanup_files(speaker_file, temp_audio)
        _set_job(job_id, status="completed", output_file=output_file)
        
    except Exception as exc:
        _cleanup_files(speaker_file, temp_audio, output_file)
        _set_job(job_id, status="error", error=str(exc))


@app.post("/health")
def health(x_api_key: Optional[str] = Header(default=None)):
    """Health check endpoint."""
    _require_api_key(x_api_key)
    return {
        "status": "ok", 
        "model": "openvoice-v2", 
        "device": DEVICE,
        "supported_languages": ["en", "es", "fr", "zh", "ja", "ko"]
    }


@app.post("/generate")
def generate(
    payload: GenerateRequest = Body(...),
    background_tasks: BackgroundTasks = BackgroundTasks(),
    x_api_key: Optional[str] = Header(default=None),
):
    """
    Generate speech from text using voice cloning with OpenVoice.
    Returns job information for async processing.
    
    OpenVoice uses a two-step process:
    1. Generate base speech with MeloTTS
    2. Apply voice characteristics from reference audio
    """
    _require_api_key(x_api_key)
    
    job_id = str(uuid.uuid4())
    _set_job(job_id, status="queued")
    
    # Offload the synthesis to background task
    background_tasks.add_task(_run_generate_job, job_id, payload.dict())
    
    return JSONResponse(
        status_code=202,
        content={
            "job_id": job_id,
            "status": "queued",
            "status_url": f"/status/{job_id}",
            "result_url": f"/result/{job_id}",
        },
    )


@app.get("/status/{job_id}")
def job_status(job_id: str, x_api_key: Optional[str] = Header(default=None)):
    """Check the status of a generation job."""
    _require_api_key(x_api_key)
    
    job = _get_job(job_id)
    if not job:
        raise HTTPException(status_code=404, detail="Job not found")
    
    payload: Dict[str, str] = {
        "job_id": job_id,
        "status": job.get("status", "unknown")
    }
    
    if "error" in job:
        payload["error"] = job["error"]
    
    return payload


@app.get("/result/{job_id}")
def job_result(
    job_id: str,
    background_tasks: BackgroundTasks = BackgroundTasks(),
    x_api_key: Optional[str] = Header(default=None),
):
    """Retrieve the result of a completed generation job."""
    _require_api_key(x_api_key)
    
    job = _get_job(job_id)
    if not job:
        raise HTTPException(status_code=404, detail="Job not found")
    
    status = job.get("status")
    if status != "completed":
        raise HTTPException(
            status_code=409, 
            detail=f"Job not ready (status={status})"
        )
    
    output_file = job.get("output_file")
    if not output_file or not Path(output_file).exists():
        _pop_job(job_id)
        raise HTTPException(status_code=410, detail="Result expired or missing")
    
    # Remove job from memory and cleanup output after sending
    _pop_job(job_id)
    background_tasks.add_task(_cleanup_files, output_file)
    
    return FileResponse(
        output_file, 
        media_type="audio/wav", 
        filename="output.wav"
    )


@app.get("/")
def root():
    """API root with available endpoints."""
    return {
        "name": "openvoice-api",
        "version": "2.0.0",
        "model": "OpenVoice V2",
        "endpoints": [
            "/health", 
            "/generate", 
            "/status/{job_id}", 
            "/result/{job_id}"
        ],
        "features": [
            "Voice cloning with 3-10s reference audio",
            "Multi-language support (EN, ES, FR, ZH, JA, KO)",
            "Adjustable speech speed (0.5-2.0x)",
            "Fast CPU performance (5-10x faster than IndexTTS2)"
        ]
    }