Spaces:
Runtime error
Runtime error
Update app.py
Browse files3 unmodified lines4567891011121314151617181920212 unmodified lines2425262728293031323334353637383940414243444546473 unmodified linesapp = FastAPI()# Bật CORS để cho phép App của bạn gọi API từ bất kỳ đâuapp.add_middleware(CORSMiddleware,allow_origins=["*"],allow_credentials=False, # <-- ĐỔI TRUE THÀNH FALSE Ở ĐÂYallow_methods=["*"],allow_headers=["*"],)@app.get("/health")async def health_check():return {"status": "ok", "message": "Edge TTS Python API is running"}@app.post("/tts")async def generate_tts(request: Request):2 unmodified linestext = data.get("text", "").strip()voice = data.get("voice", "vi-VN-NamMinhNeural")# Nhận pitch và rate từ App, nếu không có thì để mặc định +0%pitch = data.get("pitch", "+0%")rate = data.get("rate", "+0%")if not text:return Response(content='{"error": "Text is required"}', status_code=400, media_type="application/json")# Khởi tạo luồng giao tiếp với máy chủ Edge WebSocketcommunicate = edge_tts.Communicate(text, voice, rate=rate, pitch=pitch)# Tải luồng âm thanh về bộ nhớaudio_data = bytearray()async for chunk in communicate.stream():if chunk["type"] == "audio":audio_data.extend(chunk["data"])# Trả thẳng file MP3 về cho Appreturn Response(content=bytes(audio_data), media_type="audio/mpeg")except Exception as e:return Response(content=f'{{"error": "{str(e)}"}}', status_code=500, media_type="application/json")3 unmodified lines4567891011121314151617181920212 unmodified lines24252627282930313233343536373839404142434445464748495051523 unmodified linesapp = FastAPI()# Mở toang cửa CORS cho mọi trình duyệtapp.add_middleware(CORSMiddleware,allow_origins=["*"],allow_credentials=False,allow_methods=["*"],allow_headers=["*"],)@app.get("/health")async def health_check():return {"status": "ok", "message": "API đang chạy ngon lành!"}@app.post("/tts")async def generate_tts(request: Request):2 unmodified linestext = data.get("text", "").strip()voice = data.get("voice", "vi-VN-NamMinhNeural")pitch = str(data.get("pitch", "+0%"))rate = str(data.get("rate", "+0%"))# BẮT BUỘC: Tự động thêm dấu % nếu JS quên gửi để chống crashif not pitch.endswith("%") and not pitch.endswith("Hz") and not pitch.endswith("st"):pitch += "%"if not rate.endswith("%") and not rate.endswith("Hz") and not rate.endswith("st"):rate += "%"if not text:return Response(content='{"error": "Không có văn bản"}', status_code=400, media_type="application/json")communicate = edge_tts.Communicate(text, voice, rate=rate, pitch=pitch)audio_data = bytearray()async for chunk in communicate.stream():if chunk["type"] == "audio":audio_data.extend(chunk["data"])return Response(content=bytes(audio_data), media_type="audio/mpeg")except Exception as e:# IN LỖI RA LOGS ĐỂ CHÚNG TA BẮT BỆNHprint("====== LỖI PHÁT SINH ======")print(str(e))return Response(content=f'{{"error": "{str(e)}"}}', status_code=500, media_type="application/json")
app.py+15-10