Spaces:
Sleeping
Sleeping
Download app.py from phanquocdat123/esp32_robot: direct link, hf CLI and curl.
- Browser
- Download file 1.44 kB
-
https://huggingface.co/spaces/phanquocdat123/esp32_robot/resolve/main/app.py
- Command line
-
hf download hf://spaces/phanquocdat123/esp32_robot/app.py
-
curl -L -o app.py https://huggingface.co/spaces/phanquocdat123/esp32_robot/resolve/main/app.py
1.44 kB
| import os | |
| from fastapi import FastAPI, HTTPException | |
| from fastapi.responses import FileResponse, JSONResponse | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from google import genai | |
| import edge_tts | |
| app = FastAPI() | |
| app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"]) | |
| # Lấy API Key | |
| API_KEY = os.getenv("GEMINI_API_KEY") | |
| client = genai.Client(api_key=API_KEY) | |
| VOICE = "vi-VN-NamMinhNeural" | |
| async def chat(text: str): | |
| try: | |
| # Cách gọi chuẩn của thư viện google-genai | |
| response = client.models.generate_content( | |
| model="gemini-3.5-flash", | |
| contents=text | |
| ) | |
| if not response.text: | |
| raise ValueError("Không nhận được nội dung từ Gemini") | |
| answer = response.text | |
| output_file = "response.mp3" | |
| # Tạo âm thanh | |
| communicate = edge_tts.Communicate(answer, VOICE) | |
| await communicate.save(output_file) | |
| return FileResponse(output_file, media_type="audio/mpeg") | |
| except Exception as e: | |
| # CỰC KỲ QUAN TRỌNG: In lỗi chi tiết ra log để bạn nhìn thấy | |
| print(f"--- LỖI HỆ THỐNG: {str(e)} ---") | |
| return JSONResponse(status_code=500, content={"error_detail": str(e)}) | |
| if __name__ == "__main__": | |
| import uvicorn | |
| uvicorn.run(app, host="0.0.0.0", port=7860) |