81 lines
2.4 KiB
Python
81 lines
2.4 KiB
Python
import json
|
|
from fastapi import FastAPI
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from fastapi.responses import StreamingResponse
|
|
from pydantic import BaseModel
|
|
from text_to_blendshapes_service import TextToBlendShapesService
|
|
|
|
app = FastAPI()
|
|
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=["*"],
|
|
allow_credentials=True,
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
class TextRequest(BaseModel):
|
|
text: str
|
|
language: str = 'zh-CN'
|
|
segment: bool = False
|
|
split_punctuations: str = None
|
|
max_sentence_length: int = None
|
|
first_sentence_split_size: int = None
|
|
tts_provider: str = 'pyttsx3' # 'pyttsx3' 或 'edge-tts'
|
|
|
|
@app.get('/health')
|
|
async def health():
|
|
return {'status': 'ok'}
|
|
|
|
@app.post('/text-to-blendshapes')
|
|
async def text_to_blendshapes(request: TextRequest):
|
|
try:
|
|
service = TextToBlendShapesService(
|
|
lang=request.language,
|
|
tts_provider=request.tts_provider
|
|
)
|
|
result = service.text_to_blend_shapes(
|
|
request.text,
|
|
segment=request.segment,
|
|
split_punctuations=request.split_punctuations,
|
|
max_sentence_length=request.max_sentence_length
|
|
)
|
|
return result
|
|
except Exception as e:
|
|
import traceback
|
|
traceback.print_exc()
|
|
return {'success': False, 'error': str(e)}
|
|
|
|
@app.post('/text-to-blendshapes/stream')
|
|
async def text_to_blendshapes_stream(request: TextRequest):
|
|
async def generate():
|
|
service = TextToBlendShapesService(
|
|
lang=request.language,
|
|
tts_provider=request.tts_provider
|
|
)
|
|
try:
|
|
for message in service.iter_text_to_blend_shapes_stream(
|
|
request.text,
|
|
split_punctuations=request.split_punctuations,
|
|
max_sentence_length=request.max_sentence_length,
|
|
first_sentence_split_size=request.first_sentence_split_size
|
|
):
|
|
yield json.dumps(message) + "\n"
|
|
except Exception as e:
|
|
yield json.dumps({'type': 'error', 'message': str(e)}) + "\n"
|
|
|
|
return StreamingResponse(
|
|
generate(),
|
|
media_type='application/x-ndjson',
|
|
headers={
|
|
'Cache-Control': 'no-cache',
|
|
'X-Accel-Buffering': 'no'
|
|
}
|
|
)
|
|
|
|
if __name__ == '__main__':
|
|
import uvicorn
|
|
print("Text to BlendShapes API: http://localhost:5001")
|
|
uvicorn.run(app, host='0.0.0.0', port=5001)
|