215 lines
8.3 KiB
Python
215 lines
8.3 KiB
Python
"""Private OpenAI-compatible speech endpoint; model execution stays in a CPU child."""
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
from dataclasses import dataclass
|
|
import hmac
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import shutil
|
|
import signal
|
|
import sys
|
|
import tempfile
|
|
from typing import Literal
|
|
|
|
from fastapi import Depends, FastAPI, Header, HTTPException, Request
|
|
from fastapi.responses import FileResponse
|
|
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
|
|
|
|
|
PROCESS_GROUP_GRACE_SECONDS = 2
|
|
|
|
|
|
class TemporaryFileResponse(FileResponse):
|
|
"""Remove request files even when sending the response fails or is cancelled."""
|
|
|
|
def __init__(self, *args, cleanup, **kwargs):
|
|
super().__init__(*args, **kwargs)
|
|
self.cleanup = cleanup
|
|
|
|
async def __call__(self, scope, receive, send):
|
|
try:
|
|
await super().__call__(scope, receive, send)
|
|
finally:
|
|
self.cleanup()
|
|
|
|
|
|
async def stop_process_group(process):
|
|
if os.name != 'posix':
|
|
if process.returncode is None:
|
|
process.terminate()
|
|
try:
|
|
await asyncio.wait_for(process.wait(), PROCESS_GROUP_GRACE_SECONDS)
|
|
except asyncio.TimeoutError:
|
|
process.kill()
|
|
await process.wait()
|
|
return
|
|
|
|
def group_alive():
|
|
try:
|
|
os.killpg(process.pid, 0)
|
|
return True
|
|
except ProcessLookupError:
|
|
return False
|
|
|
|
# The leader can exit while a descendant still belongs to its session/group.
|
|
if group_alive():
|
|
try:
|
|
os.killpg(process.pid, signal.SIGTERM)
|
|
except ProcessLookupError:
|
|
pass
|
|
loop = asyncio.get_running_loop()
|
|
deadline = loop.time() + PROCESS_GROUP_GRACE_SECONDS
|
|
while group_alive() and loop.time() < deadline:
|
|
await asyncio.sleep(min(.05, max(0, deadline - loop.time())))
|
|
if group_alive():
|
|
try:
|
|
os.killpg(process.pid, signal.SIGKILL)
|
|
except ProcessLookupError:
|
|
pass
|
|
await process.wait()
|
|
|
|
|
|
@dataclass
|
|
class TTSSettings:
|
|
api_key: str
|
|
model_dir: Path
|
|
work_dir: Path
|
|
timeout_seconds: float = 240
|
|
|
|
@classmethod
|
|
def from_env(cls):
|
|
return cls(os.environ.get('TTS_API_KEY', ''),
|
|
Path(os.environ.get('TTS_MODEL_DIR', '/workspace/models/kokoro-82m')),
|
|
Path(os.environ.get('TTS_WORK_DIR', '/workspace/cmvr-visual/tts-work')),
|
|
float(os.environ.get('TTS_TIMEOUT_SECONDS', '240')))
|
|
|
|
def ready(self):
|
|
return all((self.model_dir / name).is_file() and (self.model_dir / name).stat().st_size > 0
|
|
for name in ['config.json', 'kokoro-v1_0.pth',
|
|
'voices/zf_xiaobei.pt', 'voices/zm_yunxi.pt'])
|
|
|
|
|
|
class SpeechRequest(BaseModel):
|
|
model_config = ConfigDict(extra='forbid')
|
|
model: Literal['kokoro-82m'] = 'kokoro-82m'
|
|
input: str = Field(min_length=1, max_length=2000)
|
|
voice: Literal['zf_xiaobei', 'zm_yunxi'] = 'zf_xiaobei'
|
|
speed: float = Field(default=1.0, ge=.5, le=2.0, allow_inf_nan=False)
|
|
response_format: Literal['wav'] = 'wav'
|
|
|
|
@field_validator('input')
|
|
@classmethod
|
|
def nonempty(cls, value):
|
|
if not value.strip():
|
|
raise ValueError('Speech text cannot be blank')
|
|
return value.strip()
|
|
|
|
|
|
async def run_synthesis(body: SpeechRequest, output: Path, settings: TTSSettings):
|
|
request_path = output.with_suffix('.json')
|
|
request_path.write_text(json.dumps(body.model_dump(), ensure_ascii=False), encoding='utf-8')
|
|
command = [sys.executable, '-I', str(Path(__file__).with_name('synthesize.py')),
|
|
'--request', str(request_path), '--output', str(output),
|
|
'--model-dir', str(settings.model_dir)]
|
|
runtime_keys = {'PATH', 'LANG', 'LC_ALL', 'LC_CTYPE', 'HOME', 'TMPDIR', 'TEMP', 'TMP',
|
|
'HF_HOME', 'XDG_CACHE_HOME', 'SystemRoot', 'SYSTEMROOT', 'WINDIR'}
|
|
env = {name: value for name, value in os.environ.items() if name in runtime_keys}
|
|
env.update({'CUDA_VISIBLE_DEVICES': '', 'OMP_NUM_THREADS': '4', 'MKL_NUM_THREADS': '4',
|
|
'HF_HUB_OFFLINE': '1', 'TRANSFORMERS_OFFLINE': '1'})
|
|
process = await asyncio.create_subprocess_exec(*command, env=env,
|
|
stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.DEVNULL,
|
|
start_new_session=os.name == 'posix')
|
|
try:
|
|
await asyncio.wait_for(process.wait(), settings.timeout_seconds)
|
|
if process.returncode != 0:
|
|
raise RuntimeError('speech_process_failed')
|
|
finally:
|
|
cleanup = asyncio.create_task(stop_process_group(process))
|
|
interrupted = False
|
|
while not cleanup.done():
|
|
try:
|
|
await asyncio.shield(cleanup)
|
|
except asyncio.CancelledError:
|
|
interrupted = True
|
|
await cleanup
|
|
if interrupted:
|
|
raise asyncio.CancelledError()
|
|
|
|
|
|
def create_app(settings: TTSSettings | None = None, *, synthesize=run_synthesis):
|
|
settings = settings or TTSSettings.from_env()
|
|
semaphore = asyncio.Semaphore(1)
|
|
application = FastAPI(title='CMVR local speech', docs_url=None, redoc_url=None, openapi_url=None)
|
|
|
|
def authenticate(authorization: str | None = Header(default=None)):
|
|
if not settings.api_key:
|
|
raise HTTPException(503, 'Speech authentication is not configured')
|
|
supplied = authorization[7:] if authorization and authorization.startswith('Bearer ') else ''
|
|
if not hmac.compare_digest(supplied.encode(), settings.api_key.encode()):
|
|
raise HTTPException(401, 'Invalid speech API key')
|
|
|
|
@application.get('/health', dependencies=[Depends(authenticate)])
|
|
def health():
|
|
if not settings.ready():
|
|
raise HTTPException(503, 'Speech weights are not ready')
|
|
return {'status': 'ok', 'model': 'kokoro-82m', 'device': 'cpu',
|
|
'voices': ['zf_xiaobei', 'zm_yunxi']}
|
|
|
|
@application.post('/v1/audio/speech', dependencies=[Depends(authenticate)])
|
|
async def speech(body: SpeechRequest, request: Request):
|
|
if not settings.ready():
|
|
raise HTTPException(503, 'Speech weights are not ready')
|
|
settings.work_dir.mkdir(parents=True, exist_ok=True)
|
|
root = settings.work_dir.resolve(strict=True)
|
|
directory = Path(tempfile.mkdtemp(prefix='speech-', dir=root))
|
|
|
|
def cleanup():
|
|
# This random child directory belongs only to this request.
|
|
if directory.parent.resolve() == root and not directory.is_symlink():
|
|
shutil.rmtree(directory, ignore_errors=True)
|
|
|
|
task = None
|
|
try:
|
|
async def execute():
|
|
async with semaphore:
|
|
if await request.is_disconnected():
|
|
raise asyncio.CancelledError()
|
|
await synthesize(body, directory / 'speech.wav', settings)
|
|
|
|
task = asyncio.create_task(execute())
|
|
while not task.done():
|
|
if await request.is_disconnected():
|
|
task.cancel()
|
|
await asyncio.gather(task, return_exceptions=True)
|
|
raise asyncio.CancelledError()
|
|
await asyncio.sleep(.1)
|
|
await task
|
|
path = directory / 'speech.wav'
|
|
if not path.is_file() or path.stat().st_size > 100 * 1024 * 1024:
|
|
raise RuntimeError('speech_output_invalid')
|
|
with path.open('rb') as handle:
|
|
header = handle.read(12)
|
|
if not (header[:4] == b'RIFF' and header[8:] == b'WAVE'):
|
|
raise RuntimeError('speech_output_invalid')
|
|
return TemporaryFileResponse(path, media_type='audio/wav', filename='speech.wav',
|
|
cleanup=cleanup)
|
|
except BaseException as exc:
|
|
if task is not None and not task.done():
|
|
task.cancel()
|
|
await asyncio.gather(task, return_exceptions=True)
|
|
cleanup()
|
|
if isinstance(exc, asyncio.CancelledError):
|
|
raise
|
|
if isinstance(exc, asyncio.TimeoutError):
|
|
raise HTTPException(504, 'Speech synthesis timed out') from None
|
|
if isinstance(exc, HTTPException):
|
|
raise
|
|
raise HTTPException(502, 'Local speech synthesis failed') from None
|
|
|
|
return application
|
|
|
|
|
|
app = create_app()
|