Update app.py
Browse files
app.py
CHANGED
|
@@ -75,15 +75,13 @@ HTML_CONTENT = """
|
|
| 75 |
let mediaRecorder;
|
| 76 |
let audioChunks = [];
|
| 77 |
|
| 78 |
-
// Hàm gửi chat (văn bản -> LLaMA -> TTS)
|
| 79 |
async function sendChat() {
|
| 80 |
const text = document.getElementById('textInput').value;
|
| 81 |
if (!text) return;
|
| 82 |
addMessage('Bạn: ' + text);
|
| 83 |
-
document.getElementById('textInput').value = '';
|
| 84 |
|
| 85 |
try {
|
| 86 |
-
// Gửi tới endpoint /chat (tích hợp LLaMA và TTS)
|
| 87 |
const response = await fetch('/chat', {
|
| 88 |
method: 'POST',
|
| 89 |
headers: { 'Content-Type': 'application/json' },
|
|
@@ -98,16 +96,13 @@ HTML_CONTENT = """
|
|
| 98 |
audio.style.display = 'block';
|
| 99 |
audio.play();
|
| 100 |
|
| 101 |
-
// Lấy văn bản từ LLaMA để hiển thị
|
| 102 |
const textResponse = await fetch('/llama', {
|
| 103 |
method: 'POST',
|
| 104 |
headers: { 'Content-Type': 'application/json' },
|
| 105 |
body: JSON.stringify({ prompt: text })
|
| 106 |
});
|
| 107 |
const textData = await textResponse.json();
|
| 108 |
-
|
| 109 |
-
addMessage('Bot: ' + textData.text);
|
| 110 |
-
}
|
| 111 |
} else {
|
| 112 |
const errorData = await response.json();
|
| 113 |
addMessage('Bot: Lỗi - ' + (errorData.error || 'Không có phản hồi'));
|
|
@@ -117,7 +112,6 @@ HTML_CONTENT = """
|
|
| 117 |
}
|
| 118 |
}
|
| 119 |
|
| 120 |
-
// Ghi âm (STT -> LLaMA -> TTS)
|
| 121 |
async function startRecording() {
|
| 122 |
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
| 123 |
mediaRecorder = new MediaRecorder(stream);
|
|
@@ -142,7 +136,6 @@ HTML_CONTENT = """
|
|
| 142 |
formData.append('file', audioBlob, 'recording.wav');
|
| 143 |
|
| 144 |
try {
|
| 145 |
-
// Gửi tới endpoint /audio_chat (STT -> LLaMA -> TTS)
|
| 146 |
const response = await fetch('/audio_chat', {
|
| 147 |
method: 'POST',
|
| 148 |
body: formData
|
|
@@ -156,7 +149,6 @@ HTML_CONTENT = """
|
|
| 156 |
audio.style.display = 'block';
|
| 157 |
audio.play();
|
| 158 |
|
| 159 |
-
// Lấy văn bản STT và LLaMA để hiển thị
|
| 160 |
const sttResponse = await fetch('/stt', {
|
| 161 |
method: 'POST',
|
| 162 |
body: formData
|
|
@@ -170,9 +162,7 @@ HTML_CONTENT = """
|
|
| 170 |
body: JSON.stringify({ prompt: sttData.text })
|
| 171 |
});
|
| 172 |
const llamaData = await llamaResponse.json();
|
| 173 |
-
|
| 174 |
-
addMessage('Bot: ' + llamaData.text);
|
| 175 |
-
}
|
| 176 |
}
|
| 177 |
} else {
|
| 178 |
const errorData = await response.json();
|
|
@@ -231,18 +221,23 @@ async def generate_text(prompt: str):
|
|
| 231 |
print(f"🔄 Đang xử lý LLaMA với model {LLAMA_MODEL}...")
|
| 232 |
output = llama_pipeline(prompt, max_new_tokens=100)[0]["generated_text"]
|
| 233 |
print(f"Output từ LLaMA: {output}")
|
|
|
|
|
|
|
|
|
|
| 234 |
return {"text": output}
|
| 235 |
except Exception as e:
|
| 236 |
print(f"❌ Lỗi LLaMA: {e}")
|
| 237 |
return {"error": str(e)}
|
| 238 |
|
| 239 |
-
# Endpoint tích hợp văn bản -> LLaMA -> TTS
|
| 240 |
@app.post("/chat")
|
| 241 |
async def chat(prompt: str):
|
| 242 |
try:
|
| 243 |
# Gửi tới LLaMA
|
| 244 |
llama_output = llama_pipeline(prompt, max_new_tokens=100)[0]["generated_text"]
|
| 245 |
print(f"LLaMA output: {llama_output}")
|
|
|
|
|
|
|
|
|
|
| 246 |
|
| 247 |
# Tạo TTS từ output của LLaMA
|
| 248 |
output_path = os.path.join(TEMP_DIR, "output.wav")
|
|
@@ -254,7 +249,6 @@ async def chat(prompt: str):
|
|
| 254 |
print(f"❌ Lỗi chat: {e}")
|
| 255 |
return {"error": str(e)}
|
| 256 |
|
| 257 |
-
# Endpoint tích hợp STT -> LLaMA -> TTS
|
| 258 |
@app.post("/audio_chat")
|
| 259 |
async def audio_chat(file: UploadFile = File(...)):
|
| 260 |
try:
|
|
@@ -266,6 +260,8 @@ async def audio_chat(file: UploadFile = File(...)):
|
|
| 266 |
# LLaMA: Sinh câu trả lời
|
| 267 |
llama_output = llama_pipeline(stt_output, max_new_tokens=100)[0]["generated_text"]
|
| 268 |
print(f"LLaMA output: {llama_output}")
|
|
|
|
|
|
|
| 269 |
|
| 270 |
# TTS: Chuyển câu trả lời thành âm thanh
|
| 271 |
output_path = os.path.join(TEMP_DIR, "output.wav")
|
|
|
|
| 75 |
let mediaRecorder;
|
| 76 |
let audioChunks = [];
|
| 77 |
|
|
|
|
| 78 |
async function sendChat() {
|
| 79 |
const text = document.getElementById('textInput').value;
|
| 80 |
if (!text) return;
|
| 81 |
addMessage('Bạn: ' + text);
|
| 82 |
+
document.getElementById('textInput').value = '';
|
| 83 |
|
| 84 |
try {
|
|
|
|
| 85 |
const response = await fetch('/chat', {
|
| 86 |
method: 'POST',
|
| 87 |
headers: { 'Content-Type': 'application/json' },
|
|
|
|
| 96 |
audio.style.display = 'block';
|
| 97 |
audio.play();
|
| 98 |
|
|
|
|
| 99 |
const textResponse = await fetch('/llama', {
|
| 100 |
method: 'POST',
|
| 101 |
headers: { 'Content-Type': 'application/json' },
|
| 102 |
body: JSON.stringify({ prompt: text })
|
| 103 |
});
|
| 104 |
const textData = await textResponse.json();
|
| 105 |
+
addMessage('Bot: ' + (textData.text || 'Tôi không hiểu bạn nói gì.'));
|
|
|
|
|
|
|
| 106 |
} else {
|
| 107 |
const errorData = await response.json();
|
| 108 |
addMessage('Bot: Lỗi - ' + (errorData.error || 'Không có phản hồi'));
|
|
|
|
| 112 |
}
|
| 113 |
}
|
| 114 |
|
|
|
|
| 115 |
async function startRecording() {
|
| 116 |
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
| 117 |
mediaRecorder = new MediaRecorder(stream);
|
|
|
|
| 136 |
formData.append('file', audioBlob, 'recording.wav');
|
| 137 |
|
| 138 |
try {
|
|
|
|
| 139 |
const response = await fetch('/audio_chat', {
|
| 140 |
method: 'POST',
|
| 141 |
body: formData
|
|
|
|
| 149 |
audio.style.display = 'block';
|
| 150 |
audio.play();
|
| 151 |
|
|
|
|
| 152 |
const sttResponse = await fetch('/stt', {
|
| 153 |
method: 'POST',
|
| 154 |
body: formData
|
|
|
|
| 162 |
body: JSON.stringify({ prompt: sttData.text })
|
| 163 |
});
|
| 164 |
const llamaData = await llamaResponse.json();
|
| 165 |
+
addMessage('Bot: ' + (llamaData.text || 'Tôi không hiểu bạn nói gì.'));
|
|
|
|
|
|
|
| 166 |
}
|
| 167 |
} else {
|
| 168 |
const errorData = await response.json();
|
|
|
|
| 221 |
print(f"🔄 Đang xử lý LLaMA với model {LLAMA_MODEL}...")
|
| 222 |
output = llama_pipeline(prompt, max_new_tokens=100)[0]["generated_text"]
|
| 223 |
print(f"Output từ LLaMA: {output}")
|
| 224 |
+
# Nếu output rỗng hoặc không có ý nghĩa, trả về mặc định
|
| 225 |
+
if not output or output.strip() == prompt.strip():
|
| 226 |
+
output = "Tôi không hiểu bạn nói gì."
|
| 227 |
return {"text": output}
|
| 228 |
except Exception as e:
|
| 229 |
print(f"❌ Lỗi LLaMA: {e}")
|
| 230 |
return {"error": str(e)}
|
| 231 |
|
|
|
|
| 232 |
@app.post("/chat")
|
| 233 |
async def chat(prompt: str):
|
| 234 |
try:
|
| 235 |
# Gửi tới LLaMA
|
| 236 |
llama_output = llama_pipeline(prompt, max_new_tokens=100)[0]["generated_text"]
|
| 237 |
print(f"LLaMA output: {llama_output}")
|
| 238 |
+
# Xử lý nếu LLaMA không trả về kết quả hợp lệ
|
| 239 |
+
if not llama_output or llama_output.strip() == prompt.strip():
|
| 240 |
+
llama_output = "Tôi không hiểu bạn nói gì."
|
| 241 |
|
| 242 |
# Tạo TTS từ output của LLaMA
|
| 243 |
output_path = os.path.join(TEMP_DIR, "output.wav")
|
|
|
|
| 249 |
print(f"❌ Lỗi chat: {e}")
|
| 250 |
return {"error": str(e)}
|
| 251 |
|
|
|
|
| 252 |
@app.post("/audio_chat")
|
| 253 |
async def audio_chat(file: UploadFile = File(...)):
|
| 254 |
try:
|
|
|
|
| 260 |
# LLaMA: Sinh câu trả lời
|
| 261 |
llama_output = llama_pipeline(stt_output, max_new_tokens=100)[0]["generated_text"]
|
| 262 |
print(f"LLaMA output: {llama_output}")
|
| 263 |
+
if not llama_output or llama_output.strip() == stt_output.strip():
|
| 264 |
+
llama_output = "Tôi không hiểu bạn nói gì."
|
| 265 |
|
| 266 |
# TTS: Chuyển câu trả lời thành âm thanh
|
| 267 |
output_path = os.path.join(TEMP_DIR, "output.wav")
|