Update app.py
Browse files
app.py
CHANGED
|
@@ -2,24 +2,17 @@ from fastapi import FastAPI, UploadFile, File
|
|
| 2 |
from fastapi.responses import FileResponse
|
| 3 |
from huggingface_hub import InferenceClient
|
| 4 |
import os
|
| 5 |
-
import google.generativeai as genai # Dùng Gemini AI
|
| 6 |
|
| 7 |
# Khởi tạo FastAPI
|
| 8 |
app = FastAPI()
|
| 9 |
|
| 10 |
# Lấy API key từ biến môi trường
|
| 11 |
HF_API_KEY = os.getenv("HF_API_KEY")
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
if not HF_API_KEY or not GOOGLE_API_KEY:
|
| 15 |
-
raise ValueError("❌ Missing API keys! Add HF_API_KEY and GOOGLE_API_KEY to Hugging Face Spaces Secrets.")
|
| 16 |
|
| 17 |
# Khởi tạo Hugging Face Client
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
# Khởi tạo Google Gemini AI
|
| 21 |
-
genai.configure(api_key=GOOGLE_API_KEY)
|
| 22 |
-
gemini = genai.GenerativeModel("gemini-pro")
|
| 23 |
|
| 24 |
# Tạo thư mục lưu file tạm
|
| 25 |
TEMP_DIR = "temp"
|
|
@@ -34,8 +27,8 @@ TTS_MODEL = "facebook/mms-tts-eng"
|
|
| 34 |
async def text_to_speech(text: str):
|
| 35 |
output_path = os.path.join(TEMP_DIR, "output.wav")
|
| 36 |
try:
|
| 37 |
-
print(f"🔄 Đang xử lý TTS với model {TTS_MODEL}...")
|
| 38 |
-
audio =
|
| 39 |
with open(output_path, "wb") as f:
|
| 40 |
f.write(audio)
|
| 41 |
return FileResponse(output_path, media_type="audio/wav", filename="output.wav")
|
|
@@ -47,68 +40,22 @@ async def text_to_speech(text: str):
|
|
| 47 |
@app.post("/stt")
|
| 48 |
async def speech_to_text(file: UploadFile = File(...)):
|
| 49 |
try:
|
| 50 |
-
print(f"🔄 Đang xử lý STT với model {STT_MODEL}...")
|
| 51 |
audio_data = await file.read()
|
| 52 |
-
response =
|
| 53 |
-
text = response.get("text", "")
|
| 54 |
return {"text": text}
|
| 55 |
except Exception as e:
|
| 56 |
print(f"❌ Lỗi STT: {e}")
|
| 57 |
return {"error": str(e)}
|
| 58 |
|
| 59 |
-
# 🤖 API Chatbot: Xử lý hội thoại với AI
|
| 60 |
-
@app.post("/chat")
|
| 61 |
-
async def chat_with_ai(message: str):
|
| 62 |
-
try:
|
| 63 |
-
print(f"💬 Chatbot nhận tin nhắn: {message}")
|
| 64 |
-
response = gemini.generate_content(message)
|
| 65 |
-
reply = response.text
|
| 66 |
-
return {"reply": reply}
|
| 67 |
-
except Exception as e:
|
| 68 |
-
print(f"❌ Lỗi chatbot: {e}")
|
| 69 |
-
return {"error": str(e)}
|
| 70 |
-
|
| 71 |
-
# 🎙 API Voice Chat: Nhận giọng nói -> STT -> AI -> TTS
|
| 72 |
-
@app.post("/voice_chat")
|
| 73 |
-
async def voice_chat(file: UploadFile = File(...)):
|
| 74 |
-
try:
|
| 75 |
-
print("🎙 Nhận giọng nói và xử lý...")
|
| 76 |
-
|
| 77 |
-
# 1️⃣ STT: Chuyển giọng nói thành văn bản
|
| 78 |
-
audio_data = await file.read()
|
| 79 |
-
stt_response = hf_client.automatic_speech_recognition(model=STT_MODEL, data=audio_data)
|
| 80 |
-
user_message = stt_response.get("text", "")
|
| 81 |
-
|
| 82 |
-
if not user_message:
|
| 83 |
-
return {"error": "Không nhận diện được giọng nói."}
|
| 84 |
-
|
| 85 |
-
print(f"📜 Văn bản nhận được: {user_message}")
|
| 86 |
-
|
| 87 |
-
# 2️⃣ Chatbot AI: Phản hồi lại
|
| 88 |
-
response = gemini.generate_content(user_message)
|
| 89 |
-
ai_reply = response.text
|
| 90 |
-
|
| 91 |
-
print(f"🤖 Trả lời: {ai_reply}")
|
| 92 |
-
|
| 93 |
-
# 3️⃣ TTS: Chuyển phản hồi thành giọng nói
|
| 94 |
-
output_path = os.path.join(TEMP_DIR, "response.wav")
|
| 95 |
-
tts_audio = hf_client.text_to_speech(model=TTS_MODEL, text=ai_reply)
|
| 96 |
-
|
| 97 |
-
with open(output_path, "wb") as f:
|
| 98 |
-
f.write(tts_audio)
|
| 99 |
-
|
| 100 |
-
return FileResponse(output_path, media_type="audio/wav", filename="response.wav")
|
| 101 |
-
except Exception as e:
|
| 102 |
-
print(f"❌ Lỗi voice chat: {e}")
|
| 103 |
-
return {"error": str(e)}
|
| 104 |
-
|
| 105 |
# Kiểm tra API
|
| 106 |
@app.get("/")
|
| 107 |
async def root():
|
| 108 |
-
return {"message": "✅
|
| 109 |
|
| 110 |
-
# Chạy Uvicorn
|
| 111 |
if __name__ == "__main__":
|
| 112 |
import uvicorn
|
| 113 |
print("🚀 Khởi động FastAPI Server...")
|
| 114 |
-
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 2 |
from fastapi.responses import FileResponse
|
| 3 |
from huggingface_hub import InferenceClient
|
| 4 |
import os
|
|
|
|
| 5 |
|
| 6 |
# Khởi tạo FastAPI
|
| 7 |
app = FastAPI()
|
| 8 |
|
| 9 |
# Lấy API key từ biến môi trường
|
| 10 |
HF_API_KEY = os.getenv("HF_API_KEY")
|
| 11 |
+
if not HF_API_KEY:
|
| 12 |
+
raise ValueError("❌ Missing HF_API_KEY! Add it to Hugging Face Spaces Secrets.")
|
|
|
|
|
|
|
| 13 |
|
| 14 |
# Khởi tạo Hugging Face Client
|
| 15 |
+
client = InferenceClient(token=HF_API_KEY)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
# Tạo thư mục lưu file tạm
|
| 18 |
TEMP_DIR = "temp"
|
|
|
|
| 27 |
async def text_to_speech(text: str):
|
| 28 |
output_path = os.path.join(TEMP_DIR, "output.wav")
|
| 29 |
try:
|
| 30 |
+
print(f"🔄 Đang xử lý TTS với model {TTS_MODEL}...") # Debug log
|
| 31 |
+
audio = client.text_to_speech(model=TTS_MODEL, text=text) # Sửa lỗi ở đây
|
| 32 |
with open(output_path, "wb") as f:
|
| 33 |
f.write(audio)
|
| 34 |
return FileResponse(output_path, media_type="audio/wav", filename="output.wav")
|
|
|
|
| 40 |
@app.post("/stt")
|
| 41 |
async def speech_to_text(file: UploadFile = File(...)):
|
| 42 |
try:
|
| 43 |
+
print(f"🔄 Đang xử lý STT với model {STT_MODEL}...") # Debug log
|
| 44 |
audio_data = await file.read()
|
| 45 |
+
response = client.automatic_speech_recognition(model=STT_MODEL, data=audio_data)
|
| 46 |
+
text = response.get("text", "") # Lấy nội dung từ JSON trả về
|
| 47 |
return {"text": text}
|
| 48 |
except Exception as e:
|
| 49 |
print(f"❌ Lỗi STT: {e}")
|
| 50 |
return {"error": str(e)}
|
| 51 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
# Kiểm tra API
|
| 53 |
@app.get("/")
|
| 54 |
async def root():
|
| 55 |
+
return {"message": "✅ TTS & STT API is running!"}
|
| 56 |
|
| 57 |
+
# Chạy Uvicorn (tránh lỗi "application does not seem to be initialized")
|
| 58 |
if __name__ == "__main__":
|
| 59 |
import uvicorn
|
| 60 |
print("🚀 Khởi động FastAPI Server...")
|
| 61 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|