tts-server-v2 / main.py
MaenGit
.
4782c2d
from fastapi import FastAPI, HTTPException, Query
from fastapi.responses import StreamingResponse
from fastapi.middleware.cors import CORSMiddleware
import edge_tts
import logging
# إعداد السجلات بشكل صحيح
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__) # تم التصحيح هنا
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/")
async def home():
return {"status": "running", "message": "Ready to stream audio"}
async def generate_audio_stream(text, voice, rate, pitch):
try:
communicate = edge_tts.Communicate(text, voice, rate=rate, pitch=pitch)
async for chunk in communicate.stream():
if chunk["type"] == "audio":
yield chunk["data"]
except Exception as e:
logger.error(f"Error during streaming: {e}")
@app.get("/tts")
async def tts_endpoint(
text: str = Query(..., min_length=1),
voice: str = "en-US-AriaNeural",
rate: str = "+0%",
pitch: str = "+0Hz"
):
try:
return StreamingResponse(
generate_audio_stream(text, voice, rate, pitch),
media_type="audio/mpeg",
headers={"Cache-Control": "no-cache"}
)
except Exception as e:
logger.error(f"TTS Endpoint Error: {e}")
raise HTTPException(status_code=500, detail="Internal Server Error")