Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,6 +6,10 @@ import whisper
|
|
| 6 |
import torch
|
| 7 |
from gtts import gTTS
|
| 8 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
hf_token = os.getenv("HF_TOKEN")
|
| 10 |
app = FastAPI()
|
| 11 |
|
|
@@ -25,6 +29,33 @@ whisper_model = whisper.load_model("base")
|
|
| 25 |
# Lưu hội thoại
|
| 26 |
conversation = [{"role": "system", "content": "Bạn là một trợ lý AI. Hãy trả lời ngắn gọn, súc tích, tối đa 2 câu."}]
|
| 27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
class ChatRequest(BaseModel):
|
| 29 |
message: str
|
| 30 |
|
|
@@ -45,23 +76,31 @@ async def chat(request: ChatRequest):
|
|
| 45 |
# Endpoint voice chat + TTS
|
| 46 |
@app.post("/voice_chat")
|
| 47 |
async def voice_chat(file: UploadFile = File(...)):
|
| 48 |
-
# Lưu file tạm
|
| 49 |
file_location = f"temp_{file.filename}"
|
| 50 |
with open(file_location, "wb") as f:
|
| 51 |
f.write(await file.read())
|
| 52 |
|
| 53 |
-
# Chuyển âm thanh thành text
|
| 54 |
result = whisper_model.transcribe(file_location, language="vi")
|
| 55 |
user_text = result["text"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
|
| 57 |
-
#
|
| 58 |
conversation.append({"role": "user", "content": user_text})
|
| 59 |
text = tokenizer.apply_chat_template(conversation, tokenize=False, add_generation_prompt=True)
|
| 60 |
model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
|
| 61 |
response_text = generate_full_response(model_inputs)
|
| 62 |
conversation.append({"role": "assistant", "content": response_text})
|
| 63 |
|
| 64 |
-
# Tạo file âm thanh từ phản hồi
|
| 65 |
tts = gTTS(response_text, lang="vi")
|
| 66 |
audio_file = "response.mp3"
|
| 67 |
tts.save(audio_file)
|
|
|
|
| 6 |
import torch
|
| 7 |
from gtts import gTTS
|
| 8 |
import os
|
| 9 |
+
import yt_dlp
|
| 10 |
+
import re
|
| 11 |
+
|
| 12 |
+
|
| 13 |
hf_token = os.getenv("HF_TOKEN")
|
| 14 |
app = FastAPI()
|
| 15 |
|
|
|
|
| 29 |
# Lưu hội thoại
|
| 30 |
conversation = [{"role": "system", "content": "Bạn là một trợ lý AI. Hãy trả lời ngắn gọn, súc tích, tối đa 2 câu."}]
|
| 31 |
|
| 32 |
+
# Hàm trích xuất tên bài hát từ văn bản
|
| 33 |
+
def extract_song_name(text):
|
| 34 |
+
import re
|
| 35 |
+
match = re.search(r"(bài|bài hát|nghe nhạc|mở nhạc)\s+(.*)", text.lower())
|
| 36 |
+
if match:
|
| 37 |
+
return match.group(2).strip()
|
| 38 |
+
return None
|
| 39 |
+
|
| 40 |
+
def download_youtube_as_wav(song_name, output_path="song.wav"):
|
| 41 |
+
search_query = f"ytsearch1:{song_name}"
|
| 42 |
+
ydl_opts = {
|
| 43 |
+
'format': 'bestaudio/best',
|
| 44 |
+
'outtmpl': 'temp_audio.%(ext)s',
|
| 45 |
+
'postprocessors': [{
|
| 46 |
+
'key': 'FFmpegExtractAudio',
|
| 47 |
+
'preferredcodec': 'wav',
|
| 48 |
+
'preferredquality': '192',
|
| 49 |
+
}],
|
| 50 |
+
'quiet': True,
|
| 51 |
+
}
|
| 52 |
+
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
| 53 |
+
ydl.download([search_query])
|
| 54 |
+
if os.path.exists("temp_audio.wav"):
|
| 55 |
+
os.rename("temp_audio.wav", output_path)
|
| 56 |
+
return output_path
|
| 57 |
+
return None
|
| 58 |
+
|
| 59 |
class ChatRequest(BaseModel):
|
| 60 |
message: str
|
| 61 |
|
|
|
|
| 76 |
# Endpoint voice chat + TTS
|
| 77 |
@app.post("/voice_chat")
|
| 78 |
async def voice_chat(file: UploadFile = File(...)):
|
|
|
|
| 79 |
file_location = f"temp_{file.filename}"
|
| 80 |
with open(file_location, "wb") as f:
|
| 81 |
f.write(await file.read())
|
| 82 |
|
|
|
|
| 83 |
result = whisper_model.transcribe(file_location, language="vi")
|
| 84 |
user_text = result["text"]
|
| 85 |
+
os.remove(file_location)
|
| 86 |
+
|
| 87 |
+
# Kiểm tra yêu cầu mở nhạc
|
| 88 |
+
if any(kw in user_text.lower() for kw in ["nghe nhạc", "mở bài hát", "bài hát", "bài"]):
|
| 89 |
+
song_name = extract_song_name(user_text)
|
| 90 |
+
if song_name:
|
| 91 |
+
wav_path = download_youtube_as_wav(song_name)
|
| 92 |
+
if wav_path:
|
| 93 |
+
return FileResponse(wav_path, media_type="audio/wav", filename="song.wav")
|
| 94 |
+
else:
|
| 95 |
+
return {"error": "Không tìm thấy hoặc tải được bài hát."}
|
| 96 |
|
| 97 |
+
# Nếu không phải yêu cầu mở nhạc → xử lý như cũ
|
| 98 |
conversation.append({"role": "user", "content": user_text})
|
| 99 |
text = tokenizer.apply_chat_template(conversation, tokenize=False, add_generation_prompt=True)
|
| 100 |
model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
|
| 101 |
response_text = generate_full_response(model_inputs)
|
| 102 |
conversation.append({"role": "assistant", "content": response_text})
|
| 103 |
|
|
|
|
| 104 |
tts = gTTS(response_text, lang="vi")
|
| 105 |
audio_file = "response.mp3"
|
| 106 |
tts.save(audio_file)
|