-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
355 lines (286 loc) · 11.9 KB
/
server.py
File metadata and controls
355 lines (286 loc) · 11.9 KB
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
"""
Studio Server - AI-powered studio utilities for video production.
Provides REST API endpoints for:
- TTS: Text-to-speech with voice cloning (Qwen3-TTS)
- Face: Face embedding extraction for IP-Adapter (InsightFace)
- Transcription: Audio transcription with word timings (Whisper)
All backends are modular and can be swapped via environment variables.
"""
import io
import os
from typing import Optional
from contextlib import asynccontextmanager
import soundfile as sf
from fastapi import FastAPI, UploadFile, File, Form, HTTPException
from fastapi.responses import StreamingResponse, JSONResponse
from pydantic import BaseModel
from backends.tts import TTSBackend, get_tts_backend, TTS_BACKENDS
from backends.face import FaceBackend, get_face_backend, FACE_BACKENDS
from backends.transcription import TranscriptionBackend, get_transcription_backend, TRANSCRIPTION_BACKENDS
# =============================================================================
# Backend Instances
# =============================================================================
tts_backend: Optional[TTSBackend] = None
face_backend: Optional[FaceBackend] = None
transcription_backend: Optional[TranscriptionBackend] = None
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Load backends on startup based on environment config."""
global tts_backend, face_backend, transcription_backend
# Load TTS backend (always enabled)
tts_name = os.environ.get("TTS_BACKEND", "qwen3-tts")
print(f"\n=== Loading TTS backend: {tts_name} ===")
tts_backend = get_tts_backend(tts_name)
tts_backend.load()
# Load Face backend (optional, enabled by default)
if os.environ.get("FACE_ENABLED", "true").lower() == "true":
face_name = os.environ.get("FACE_BACKEND", "insightface")
print(f"\n=== Loading Face backend: {face_name} ===")
face_backend = get_face_backend(face_name)
face_backend.load()
# Load Transcription backend (optional, enabled by default)
if os.environ.get("TRANSCRIPTION_ENABLED", "true").lower() == "true":
transcription_name = os.environ.get("TRANSCRIPTION_BACKEND", "whisper")
print(f"\n=== Loading Transcription backend: {transcription_name} ===")
transcription_backend = get_transcription_backend(transcription_name)
transcription_backend.load()
print("\n=== Studio Server Ready ===\n")
yield
# Cleanup
if tts_backend:
tts_backend.unload()
if face_backend:
face_backend.unload()
if transcription_backend:
transcription_backend.unload()
app = FastAPI(
title="Studio Server",
description="AI-powered studio utilities for video production: TTS, face embedding, transcription",
version="0.4.0",
lifespan=lifespan,
)
# =============================================================================
# Health & Info Endpoints
# =============================================================================
@app.get("/health")
async def health():
"""Health check endpoint."""
backends = {}
if tts_backend:
backends["tts"] = tts_backend.get_info()
if face_backend:
backends["face"] = face_backend.get_info()
if transcription_backend:
backends["transcription"] = transcription_backend.get_info()
return {
"status": "ok",
"backends": backends,
}
@app.get("/v1/models")
async def list_models():
"""List available backends by category."""
return {
"tts": list(TTS_BACKENDS.keys()),
"face": list(FACE_BACKENDS.keys()),
"transcription": list(TRANSCRIPTION_BACKENDS.keys()),
}
# =============================================================================
# TTS Endpoints
# =============================================================================
@app.get("/v1/tts/speakers")
async def list_speakers():
"""List available preset speakers for basic TTS."""
if tts_backend is None:
raise HTTPException(status_code=503, detail="TTS backend not loaded")
return {"speakers": tts_backend.get_speakers()}
@app.post("/v1/tts/extract")
async def extract_voice_prompt(
ref_audio: UploadFile = File(..., description="Reference audio for voice extraction"),
ref_text: Optional[str] = Form(None, description="Transcript of reference audio"),
):
"""
Extract a reusable voice prompt from reference audio.
The returned `voice_prompt` can be cached and reused with `/v1/tts/synthesize`
to avoid re-processing the reference audio on every request.
"""
if tts_backend is None:
raise HTTPException(status_code=503, detail="TTS backend not loaded")
try:
audio_bytes = await ref_audio.read()
audio_buffer = io.BytesIO(audio_bytes)
audio_data, sample_rate = sf.read(audio_buffer)
ref_audio_data = (audio_data, sample_rate)
voice_prompt = tts_backend.extract_voice_prompt(
ref_audio=ref_audio_data,
ref_text=ref_text,
)
return JSONResponse({
"voice_prompt": voice_prompt,
"format": "base64-torch",
"ref_text": ref_text,
})
except NotImplementedError as e:
raise HTTPException(status_code=501, detail=str(e))
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/v1/tts/synthesize")
async def synthesize_speech(
text: str = Form(..., description="Text to synthesize"),
language: str = Form("English", description="Target language"),
speaker: Optional[str] = Form(None, description="Preset speaker for basic TTS"),
ref_audio: Optional[UploadFile] = File(None, description="Reference audio for voice cloning"),
ref_text: Optional[str] = Form(None, description="Transcript of reference audio"),
voice_prompt: Optional[str] = Form(None, description="Pre-extracted voice prompt"),
speed: float = Form(1.0, description="Speech speed multiplier"),
):
"""
Synthesize speech from text.
**Basic TTS:** Just provide `text` and optionally `speaker`.
**Voice Cloning (on-the-fly):** Provide `ref_audio` and `ref_text`.
**Voice Cloning (cached):** Provide `voice_prompt` from `/v1/tts/extract`.
"""
if tts_backend is None:
raise HTTPException(status_code=503, detail="TTS backend not loaded")
try:
if voice_prompt:
wav_bytes, sample_rate = tts_backend.synthesize_with_prompt(
text=text,
voice_prompt=voice_prompt,
language=language,
speed=speed,
)
elif ref_audio:
audio_bytes = await ref_audio.read()
audio_buffer = io.BytesIO(audio_bytes)
audio_data, sample_rate = sf.read(audio_buffer)
ref_audio_data = (audio_data, sample_rate)
wav_bytes, sample_rate = tts_backend.synthesize(
text=text,
language=language,
speaker=speaker,
ref_audio=ref_audio_data,
ref_text=ref_text,
speed=speed,
)
else:
wav_bytes, sample_rate = tts_backend.synthesize(
text=text,
language=language,
speaker=speaker,
ref_audio=None,
ref_text=None,
speed=speed,
)
return StreamingResponse(
io.BytesIO(wav_bytes),
media_type="audio/wav",
headers={
"Content-Disposition": "attachment; filename=speech.wav",
"X-Sample-Rate": str(sample_rate),
}
)
except NotImplementedError as e:
raise HTTPException(status_code=501, detail=str(e))
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# =============================================================================
# Face Embedding Endpoints
# =============================================================================
@app.post("/v1/face/embed")
async def extract_face_embedding(
image: UploadFile = File(..., description="Image containing a face"),
return_bbox: bool = Form(False, description="Include bounding box in response"),
):
"""
Extract face embedding from an image.
Returns a 512-dimensional embedding compatible with IP-Adapter FaceID
for maintaining face consistency across video generation (PerformerDNA).
"""
if face_backend is None:
raise HTTPException(status_code=503, detail="Face backend not loaded")
try:
image_bytes = await image.read()
result = face_backend.extract_embedding(image_bytes, return_bbox=return_bbox)
return JSONResponse(result)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/v1/face/embed-all")
async def extract_all_face_embeddings(
image: UploadFile = File(..., description="Image containing faces"),
max_faces: int = Form(5, description="Maximum number of faces to extract"),
):
"""
Extract face embeddings for all faces in an image.
Useful when processing reference images that may contain multiple people.
Returns faces sorted by size (largest first).
"""
if face_backend is None:
raise HTTPException(status_code=503, detail="Face backend not loaded")
try:
image_bytes = await image.read()
results = face_backend.extract_embeddings(image_bytes, max_faces=max_faces)
return JSONResponse({"faces": results, "count": len(results)})
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
class CompareEmbeddingsRequest(BaseModel):
"""Request body for comparing face embeddings."""
embedding1: str
embedding2: str
@app.post("/v1/face/compare")
async def compare_face_embeddings(request: CompareEmbeddingsRequest):
"""
Compare two face embeddings for similarity.
Returns a cosine similarity score between 0 and 1.
Scores above 0.6 typically indicate the same person.
"""
if face_backend is None:
raise HTTPException(status_code=503, detail="Face backend not loaded")
try:
similarity = face_backend.compare_embeddings(
request.embedding1,
request.embedding2,
)
return JSONResponse({
"similarity": similarity,
"same_person": similarity > 0.6,
})
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# =============================================================================
# Transcription Endpoints
# =============================================================================
@app.post("/v1/transcribe")
async def transcribe_audio(
audio: UploadFile = File(..., description="Audio file to transcribe"),
language: Optional[str] = Form(None, description="Language code (auto-detect if empty)"),
word_timestamps: bool = Form(True, description="Include word-level timestamps"),
):
"""
Transcribe audio to text with word-level timestamps.
Returns the full transcript and per-word timing information
for lip-sync alignment.
"""
if transcription_backend is None:
raise HTTPException(status_code=503, detail="Transcription backend not loaded")
try:
audio_bytes = await audio.read()
result = transcription_backend.transcribe(
audio_bytes,
language=language,
word_timestamps=word_timestamps,
)
return JSONResponse(result.to_dict())
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# =============================================================================
# Main
# =============================================================================
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)