File size: 3,975 Bytes
043d9c7
f8f20a2
4c5db1f
dc86243
0c96139
f8f20a2
abebfdf
a38030b
78f7e4b
4c5db1f
dc86243
78f7e4b
4c5db1f
cb5cebf
f8f20a2
8c68791
a0493a8
cb5cebf
78f7e4b
 
4c5db1f
 
0ef1f97
a0493a8
8c68791
 
03e226b
628f1d6
78f7e4b
8317765
 
 
 
 
 
 
 
 
 
 
 
3f061cb
 
8317765
 
3f061cb
8317765
 
 
 
 
 
 
 
 
 
 
0c96139
 
 
 
 
f8f20a2
4c5db1f
8c68791
0c96139
27837f9
8c68791
27837f9
63db033
 
 
8c68791
dda3962
f8f20a2
4c5db1f
f8f20a2
8c68791
0c96139
8c68791
27837f9
 
8c68791
dda3962
f8f20a2
8c68791
f8f20a2
628f1d6
41a451a
27837f9
 
628f1d6
41a451a
a0493a8
628f1d6
14d5dc4
3f061cb
78f7e4b
14d5dc4
 
 
 
 
 
 
 
41a451a
 
f8f20a2
 
78f7e4b
 
 
dda3962
 
03e226b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
from fastapi import FastAPI, UploadFile, File, HTTPException, Form
from fastapi.responses import HTMLResponse
from huggingface_hub import InferenceClient
import os
import uvicorn
import base64
import requests

# Khởi tạo FastAPI
app = FastAPI()

# Lấy API key từ biến môi trường
HF_API_KEY = os.getenv("HF_API_KEY")
if not HF_API_KEY:
    raise ValueError("❌ Thiếu HF_API_KEY! Thêm vào biến môi trường.")

# Khởi tạo Hugging Face Client
client = InferenceClient(token=HF_API_KEY)

# Tạo thư mục lưu file tạm
TEMP_DIR = "temp"
os.makedirs(TEMP_DIR, exist_ok=True)

# Mô hình sử dụng
STT_MODEL = "openai/whisper-tiny.en"
TTS_MODEL = "facebook/mms-tts-eng"
CHAT_MODEL = "mistralai/Mistral-7B-Instruct-v0.1"  # Model nhẹ hơn

# Giao diện HTML
HTML_CONTENT = """
<html>
<head>
    <title>Chatbot AI</title>
    <script>
        async function sendMessage() {
            let prompt = document.getElementById("prompt").value;
            let responseBox = document.getElementById("response");
            responseBox.innerText = "Đang xử lý...";
            
            let response = await fetch("/chatbot", {
                method: "POST",
                headers: { "Content-Type": "application/x-www-form-urlencoded" },
                body: new URLSearchParams({ "prompt": prompt })
            });
            let data = await response.json();
            responseBox.innerText = data.text || "Lỗi xảy ra!";
        }
    </script>
</head>
<body>
    <h1>Chatbot AI</h1>
    <input type="text" id="prompt" placeholder="Nhập nội dung..." />
    <button onclick="sendMessage()">Gửi</button>
    <p id="response"></p>
</body>
</html>
"""

@app.get("/", response_class=HTMLResponse)
async def root():
    return HTML_CONTENT

async def text_to_speech(text: str) -> str:
    output_path = os.path.join(TEMP_DIR, "output.wav")
    try:
        print(f"🔄 Đang xử lý TTS với model {TTS_MODEL}...")
        response = client.post(f"{TTS_MODEL}", json={"inputs": text})
        with open(output_path, "wb") as f:
            f.write(response)
        with open(output_path, "rb") as f:
            audio_data = f.read()
        return base64.b64encode(audio_data).decode('utf-8')
    except Exception as e:
        print(f"❌ Lỗi TTS: {e}")
        raise

async def speech_to_text(file: UploadFile) -> str:
    try:
        print(f"🔄 Đang xử lý STT với model {STT_MODEL}...")
        audio_data = await file.read()
        response = client.post(f"{STT_MODEL}", files={"file": audio_data})
        return response.get("text", "Không nghe được gì.")
    except Exception as e:
        print(f"❌ Lỗi STT: {e}")
        raise

async def generate_text(prompt: str) -> str:
    try:
        print(f"🔄 Đang xử lý hội thoại với model {CHAT_MODEL}...")
        response = client.post(f"{CHAT_MODEL}", json={"inputs": prompt})
        return response.get("generated_text", "Xin lỗi, tôi gặp lỗi khi xử lý câu hỏi của bạn.").strip()
    except Exception as e:
        print(f"❌ Lỗi xử lý hội thoại: {e}")
        return "Xin lỗi, tôi gặp lỗi khi xử lý câu hỏi của bạn."

@app.post("/chatbot")
async def chatbot(prompt: str = Form(None), file: UploadFile = None):
    try:
        if file:
            stt_output = await speech_to_text(file)
            chat_output = await generate_text(stt_output)
        elif prompt:
            chat_output = await generate_text(prompt)
        else:
            raise HTTPException(status_code=422, detail="Thiếu dữ liệu đầu vào")
        
        audio_base64 = await text_to_speech(chat_output)
        return {"text": chat_output, "audio": audio_base64}
    except HTTPException as he:
        raise he
    except Exception as e:
        return {"error": str(e)}

if __name__ == "__main__":
    print("🚀 Khởi động FastAPI Server...")
    uvicorn.run(app, host="0.0.0.0", port=7860)