It seems like you encountered a "Not Found" error message. Could you please provide more context or specify what you were trying to do when this occurred? This will help me assist you better.
Assistant
Hello! How can I assist you today? If you have any questions or need help with something, feel free to let me know.
User
tôi có đoạn code sau
Assistant
Bạn có thể gửi đoạn code mà bạn muốn chia sẻ được không? Mình sẽ giúp bạn xem xét và hỗ trợ nhé!
User
import asyncio
import logging
import os
import io
import uuid
from fastapi import FastAPI, UploadFile, File, HTTPException
from fastapi.responses import FileResponse
import torch
import aiofiles
import edge_tts
from pydub import AudioSegment
from pydub.utils import which
from transformers import (
WhisperProcessor,
WhisperForConditionalGeneration,
MT5Tokenizer,
AutoModelForSeq2SeqLM
)
from inference_wav2lip import run_wav2lip
from concurrent.futures import ThreadPoolExecutor
async def speech2text(audio_bytes: bytes) -> str:
def _speech2text_sync(audio_bytes_sync):
import soundfile as sf
import torchaudio
import io
code
try:
# Thử đọc bằng soundfile
audio_input, sample_rate = sf.read(io.BytesIO(audio_bytes_sync))
if sample_rate != 16000:
waveform, sr = torchaudio.load(io.BytesIO(audio_bytes_sync))
resampler = torchaudio.transforms.Resample(sr, 16000)
audio_input = resampler(waveform).squeeze().numpy()
except RuntimeError:
# Fallback đọc bằng torchaudio cho mp3 hoặc lỗi đọc
waveform, sr = torchaudio.load(io.BytesIO(audio_bytes_sync))
if sr != 16000:
resampler = torchaudio.transforms.Resample(sr, 16000)
waveform = resampler(waveform)
audio_input = waveform.squeeze().numpy()
inputs = processor_asr(audio_input, sampling_rate=16000, return_tensors="pt")
with torch.no_grad():
predicted_ids = model_asr.generate(inputs.input_features)
transcription = processor_asr.batch_decode(predicted_ids, skip_special_tokens=True)
return transcription[0] if transcription else ""
loop = asyncio.get_event_loop()
result = await loop.run_in_executor(executor, _speech2text_sync, audio_bytes_sync)
if result is None:
return ""
return result
Assistant
Cảm ơn bạn đã gửi đoạn code. Đây là ứng dụng FastAPI thực hiện pipeline:
Nhận ảnh mặt (face) và file audio đầu vào.
Chuyển audio thành text (speech2text).
Chat với mô hình LLM (chat_llm) dựa trên text đầu vào.
Tạo audio trả lời từ text (text2speech).
Chạy Wav2Lip đồng bộ môi với ảnh mặt và audio trả lời.
Trả về video tạo được.
Mình thấy code của bạn khá rõ ràng và đầy đủ. Tuy nhiên, mình có một vài góp ý để bạn có thể cân nhắc cải thiện hoặc kiểm tra lại:
Biến audio_bytes_sync chưa được định nghĩa ở hàm speech2text:
Trong hàm speech2text, bạn gọi:
python
result = await loop.run_in_executor(executor, _speech2text_sync, audio_bytes_sync)
Nhưng tham số audio_bytes_sync không tồn tại trong scope, đúng ra ở đây bạn cần truyền audio_bytes:
python
result = await loop.run_in_executor(executor, _speech2text_sync, audio_bytes)
Nếu không sửa, bạn sẽ gặp lỗi NameError.
Quản lý tài nguyên (file tạm):
Hiện bạn xóa file tạm trong finally, điều này rất tốt. Tuy nhiên, nếu run_wav2lip hoặc bất kỳ bước nào cần giữ file output cho tới khi trả về FileResponse, thì không nên xóa quá sớm. Nhưng đoạn code hiện tại xóa sau khi trả về rồi nên có thể hoạt động ổn.
Sử dụng asyncio.get_running_loop() thay vì get_event_loop():
Từ Python 3.7+, ưu tiên dùng:
python
loop = asyncio.get_running_loop()
Xử lý lỗi:
Bạn đang bắt chung tất cả lỗi và trả về 500, đó là cách tốt. Có thể phân biệt lỗi client (ví dụ lỗi format file, lỗi không phát hiện giọng nói...) và lỗi server để trả mã chính xác hơn.
Yêu cầu cài đặt phụ thuộc:
Bạn cần đảm bảo trên server có ffmpeg hoặc ffprobe để pydub hoạt động, và các thư viện edge_tts, transformers, torch, aiofiles, pydub, fastapi, ...
Nếu bạn có thắc mắc cụ thể về phần nào hoặc gặp lỗi khi chạy, bạn có thể cung cấp thêm, mình sẽ giúp bạn chi tiết nhé!
User
khi chạy thì lỗi {"detail":"Not Found"}
Assistant
Lỗi {"detail":"Not Found"} khi bạn chạy FastAPI thường xảy ra khi bạn gọi một endpoint mà server không xử lý được, tức là route bạn gọi không tồn tại trên server.
Các nguyên nhân và cách kiểm tra - xử lý:
Kiểm tra URL và phương thức HTTP bạn gọi
Đoạn code bạn gửi định nghĩa duy nhất endpoint POST /chat:
python
@app.post("/chat")
async def chat_api(...)
Bạn phải gọi request POST tới URL http://<host>:8000/chat
Nếu bạn gọi GET hoặc gọi sai URL (ví dụ /chat/ hoặc /chats) thì sẽ lỗi Not Found.
Kiểm tra cách bạn gọi API (ví dụ Postman, cURL,...):
Ví dụ cURL đúng:
bash
curl -X POST "http://localhost:8000/chat" \
-F "face=@/path/to/face.jpg" -F "audio=@/path/to/audio.wav"
Phải upload 2 file: face và audio (multipart/form-data)
Nếu bạn gọi GET hoặc thiếu file, server có thể trả 404 hoặc 422
Kiểm tra chạy server và logs:
Khi bạn chạy uvicorn main:app (giả định file ở main.py), server sẽ log các route được load, ví dụ dòng gần đầu dạng:
code
INFO: Started server process [12345]
INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
INFO: Application startup complete.
Bạn có thể kiểm tra các endpoint hiển thị tại http://localhost:8000/docs hoặc http://localhost:8000/redoc (FastAPI tự động tạo trang docs)
Nếu truy cập các trang docs này cũng bị 404 nghĩa là app chưa khởi chạy đúng hoặc không có route nào được load.
Kiểm tra tên file chính khi chạy uvicorn:
Nếu bạn đặt file script của bạn là your_script.py, thì chạy:
bash
uvicorn your_script:app --reload
Nếu bạn chạy sai tên file hoặc biến app không đúng, server sẽ không load app đúng và không có route.
User
hãy sửa code sau, để có giao diện đẹp, chuyên nghiệp
Assistant
Bạn muốn mình chỉnh sửa đoạn code FastAPI hiện tại thành một phiên bản có giao diện web đẹp và chuyên nghiệp đúng không? Vì FastAPI mặc định chỉ cung cấp backend API (không kèm giao diện frontend), để có giao diện đẹp bạn sẽ cần thêm phần frontend vào.
1. Tổng quan cách làm
FastAPI vẫn giữ vai trò backend xử lý logic (nhận file, trả kết quả video).
Thêm frontend sử dụng Jinja2 template để có trang HTML upload file đẹp, hiện đại.
Sử dụng CSS framework như Bootstrap 5 để giao diện responsive, đẹp mắt.
Hiển thị form upload ảnh + audio, nút submit, và hiển thị video trả về (nếu có).
Bổ sung thêm route GET / để hiển thị trang upload file.
2. Code sửa đổi mẫu
Dưới đây là bản sửa code với frontend đơn giản nhưng chuyên nghiệp dùng Bootstrap, trình bày form upload. Mình giữ nguyên logic backend bạn có, chỉ thêm phần giao diện:
python
User
code này chạy không đúng
Assistant
Cảm ơn bạn đã phản hồi! Mình xin rà soát lại đoạn code mẫu mình đã gửi để sửa các lỗi có thể gây ra lỗi chạy.
Một số điểm cần chú ý sửa và điểm hay gây lỗi:
Trong hàm speech2text bạn truyền audio_bytes đúng chưa?
Trước đó bạn sửa lại dùng asyncio.get_running_loop() đúng, nhưng đoạn:
python
result = await loop.run_in_executor(executor, _speech2text_sync, audio_bytes)
Phải đúng là audio_bytes (không dùng biến audio_bytes_sync).
Bạn đã đặt đúng thư mục templates/ và static/ và các file html/css/js chưa?
Trong finally khối xóa file bạn chưa xóa video đầu ra. Nếu bạn vừa trả video rồi xóa file luôn thì client có thể không kịp tải video.
Nên thay vì trả về HTML video với đường dẫn /video/{video_name}, bạn nên trả về file trực tiếp hoặc lưu file video lại ít nhất cho đến khi client tải xong.
Bạn chạy uvicorn thế nào? Câu lệnh chạy có chính xác?
Ví dụ: nếu file của bạn là main.py và đối tượng app của bạn là app, hãy chạy:
bash
uvicorn main:app --reload
Đây là bản sửa code chú ý phần:
Sửa truyền audio_bytes đúng.
Sửa finally không xóa video output, chỉ xóa các file tạm.
Thêm kiểm tra logger.
Thêm templates và static folder chuẩn.
Đảm bảo route /video/{video_name} phục vụ FileResponse đúng.
Ví dụ file chạy tên main.py
Mã hoàn chỉnh sửa lại (phần backend chính):
python
User
thế thì link truy cập web
Assistant
Trong đoạn code FastAPI mà mình đã chỉnh sửa, khi bạn chạy server (ví dụ với câu lệnh):
bash
uvicorn main:app --reload
thì server sẽ chạy mặc định trên địa chỉ:
code
http://127.0.0.1:8000/
hoặc
code
http://localhost:8000/
Link truy cập web:
Trang chính (form upload ảnh + audio):
code
http://localhost:8000/
Ở trang này bạn sẽ thấy form để upload file ảnh mặt (face) và audio (audio).
Khi gửi form sẽ gửi POST tới endpoint /chat (đã được định nghĩa trong backend).
Sau khi xử lý, server sẽ trả về trang kết quả hiển thị video đồng bộ môi.
Link để xem video kết quả từng request:
Video được phục vụ qua đường dẫn dạng:
code
http://localhost:8000/video/{video_name}
Trong đó {video_name} là tên file video trả về, ví dụ uuid_out.mp4.
Video này sẽ được nhúng sẵn trong trang kết quả để bạn xem trực tiếp trên trình duyệt.
Tóm lại, bạn chỉ cần mở trình duyệt và truy cập:
http://localhost:8000/
để bắt đầu sử dụng giao diện upload file và xem kết quả.
Nếu bạn chạy trên máy chủ (server) hoặc ở môi trường không phải localhost, hãy thay localhost thành IP hoặc domain của server.
Ví dụ:
code
http://<ip-server>:8000/
Nếu còn thắc mắc hay cần hướng dẫn cụ thể hơn về cách chạy hoặc cấu hình, bạn cứ hỏi nhé!
Mở trình duyệt truy cập http://localhost:8000/ để xem trang upload file đẹp, từ đây upload ảnh + audio, submit sẽ nhận video trả về trực tiếp trong trang.
Nếu bạn muốn mình giúp code thêm các tính năng UI nâng cao hoặc hỗ trợ client upload bằng JavaScript, thông báo tiến trình..., bạn có thể nói thêm nhé!
Hy vọng bạn sẽ thích phiên bản giao diện này!
import asyncio
import logging
import os
import io
import uuid
from fastapi import FastAPI, UploadFile, File, HTTPException, Request
from fastapi.responses import FileResponse, HTMLResponse
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
import torch
import aiofiles
import edge_tts
from pydub import AudioSegment
from pydub.utils import which
from transformers import (
WhisperProcessor,
WhisperForConditionalGeneration,
MT5Tokenizer,
AutoModelForSeq2SeqLM
)
from inference_wav2lip import run_wav2lip
from concurrent.futures import ThreadPoolExecutor
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
AudioSegment.converter = which("ffmpeg") or "ffmpeg.exe"
UPLOAD_DIR = "uploads"
OUTPUT_DIR = "outputs"
os.makedirs(UPLOAD_DIR, exist_ok=True)
os.makedirs(OUTPUT_DIR, exist_ok=True)
app = FastAPI()
templates = Jinja2Templates(directory="templates")
app.mount("/static", StaticFiles(directory="static"), name="static")
model_asr_name = "hoangdeeptry/whisper-vietnamese-3"
processor_asr = WhisperProcessor.from_pretrained(model_asr_name)
model_asr = WhisperForConditionalGeneration.from_pretrained(model_asr_name)
model_asr.eval()
model_chat_name = "google/mt5-base"
tokenizer_chat = MT5Tokenizer.from_pretrained(model_chat_name, use_fast=False)
model_chat = AutoModelForSeq2SeqLM.from_pretrained(model_chat_name)
model_chat.eval()
executor = ThreadPoolExecutor(max_workers=2)
async def speech2text(audio_bytes: bytes) -> str:
def _speech2text_sync(audio_bytes_sync):
import soundfile as sf
import torchaudio
import io
try:
audio_input, sample_rate = sf.read(io.BytesIO(audio_bytes_sync))
if sample_rate != 16000:
waveform, sr = torchaudio.load(io.BytesIO(audio_bytes_sync))
resampler = torchaudio.transforms.Resample(sr, 16000)
audio_input = resampler(waveform).squeeze().numpy()
except RuntimeError:
waveform, sr = torchaudio.load(io.BytesIO(audio_bytes_sync))
if sr != 16000:
resampler = torchaudio.transforms.Resample(sr, 16000)
waveform = resampler(waveform)
audio_input = waveform.squeeze().numpy()
inputs = processor_asr(audio_input, sampling_rate=16000, return_tensors="pt")
with torch.no_grad():
predicted_ids = model_asr.generate(inputs.input_features)
transcription = processor_asr.batch_decode(predicted_ids, skip_special_tokens=True)
return transcription[0] if transcription else ""
loop = asyncio.get_running_loop()
result = await loop.run_in_executor(executor, _speech2text_sync, audio_bytes)
return result or ""
async def chat_llm(text: str) -> str:
def _chat_llm_sync(text_sync):
inputs = tokenizer_chat.encode(text_sync, return_tensors="pt", max_length=512, truncation=True)
outputs = model_chat.generate(inputs, max_length=128, num_beams=5)
reply = tokenizer_chat.decode(outputs[0], skip_special_tokens=True)
return reply
loop = asyncio.get_running_loop()
return await loop.run_in_executor(executor, _chat_llm_sync, text)
async def text2speech(text: str) -> io.BytesIO:
communicate = edge_tts.Communicate(text, voice="vi-VN-Nam-AiNeural")
buffer = io.BytesIO()
async for chunk in communicate.stream():
buffer.write(chunk)
buffer.seek(0)
return buffer
@app.get("/", response_class=HTMLResponse)
async def home(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
@app.post("/chat", response_class=HTMLResponse)
async def chat_api(request: Request, face: UploadFile = File(...), audio: UploadFile = File(...)):
unique_id = str(uuid.uuid4())
face_path = os.path.join(UPLOAD_DIR, f"{unique_id}_{face.filename}")
audio_path = os.path.join(UPLOAD_DIR, f"{unique_id}_{audio.filename}")
output_video_path = os.path.join(OUTPUT_DIR, f"{unique_id}_out.mp4")
tts_mp3_path = None
tts_wav_path = None
try:
logger.info("Saving face image...")
async with aiofiles.open(face_path, "wb") as f_face:
await f_face.write(await face.read())
logger.info("Saving audio file...")
async with aiofiles.open(audio_path, "wb") as f_audio:
audio_bytes = await audio.read()
await f_audio.write(audio_bytes)
logger.info("Running speech to text...")
transcription = await speech2text(audio_bytes)
if not transcription.strip():
return templates.TemplateResponse("index.html", {
"request": request,
"error": "Không phát hiện giọng nói trong audio."
})
logger.info(f"Transcription result: {transcription}")
logger.info("Generating chatbot reply...")
reply_text = await chat_llm(transcription)
logger.info(f"Chatbot reply: {reply_text}")
logger.info("Generating TTS audio...")
tts_audio = await text2speech(reply_text)
tts_mp3_path = os.path.join(UPLOAD_DIR, f"{unique_id}_tts.mp3")
with open(tts_mp3_path, "wb") as f_tts:
f_tts.write(tts_audio.getbuffer())
logger.info("Converting TTS mp3 to wav...")
tts_wav_path = os.path.join(UPLOAD_DIR, f"{unique_id}_tts.wav")
audio_seg = AudioSegment.from_file(tts_mp3_path, format="mp3")
audio_seg.export(tts_wav_path, format="wav")
logger.info("Running Wav2Lip...")
loop = asyncio.get_running_loop()
await loop.run_in_executor(executor, run_wav2lip, face_path, tts_wav_path, output_video_path)
video_url = f"/video/{unique_id}_out.mp4"
logger.info(f"Finished processing. Video URL: {video_url}")
return templates.TemplateResponse("result.html", {
"request": request,
"video_url": video_url,
"reply_text": reply_text,
"transcription": transcription
})
except Exception as e:
logger.error(f"Internal server error: {e}", exc_info=True)
return templates.TemplateResponse("index.html", {
"request": request,
"error": f"Lỗi nội bộ: {str(e)}"
})
finally:
# Xóa file tạm nhưng không xóa video output để client tải
for f in [face_path, audio_path, tts_mp3_path, tts_wav_path]:
if f and os.path.exists(f):
try:
os.remove(f)
except Exception as ex:
logger.warning(f"Failed to delete temp file {f}: {ex}")
@app.get("/video/{video_name}")
async def get_video(video_name: str):
video_path = os.path.join(OUTPUT_DIR, video_name)
if not os.path.exists(video_path):
raise HTTPException(status_code=404, detail="Video not found")
return FileResponse(video_path, media_type="video/mp4")
Mỗi lần bạn submit trên form sẽ trả về trang kết quả kèm video khả dụng xem hoặc tải về.
Vài bước kiểm tra để đảm bảo hoạt động:
Bạn cài đầy đủ thư viện python cần thiết.
Có ffmpeg trong PATH.
Folder uploads và outputs có quyền tạo, ghi, đọc file.
Upload file ảnh và audio đúng format được phép.
Truy cập GET / để kiểm tra trang form upload có hiện không (đừng quên port bạn chạy).