from fastapi import FastAPI, UploadFile, File, HTTPException from fastapi.responses import FileResponse import subprocess import shutil import os app = FastAPI( title="Wav2Lip API", version="1.0" ) os.makedirs("sample_data", exist_ok=True) os.makedirs("results", exist_ok=True) def merge_audio_video(video_path, audio_path, output_path): if os.path.exists(output_path): os.remove(output_path) subprocess.run( [ "ffmpeg", "-y", "-i", video_path, "-i", audio_path, "-c:v", "copy", "-c:a", "aac", "-map", "0:v:0", "-map", "1:a:0", output_path ], check=True ) return output_path @app.get("/") def root(): return { "message": "Wav2Lip API is running", "docs": "/docs" } @app.post("/generate-video") async def generate_video( image: UploadFile = File(...), audio: UploadFile = File(...) ): image_path = "sample_data/input_image.png" audio_path = "sample_data/input_audio.mp3" with open(image_path, "wb") as f: shutil.copyfileobj(image.file, f) with open(audio_path, "wb") as f: shutil.copyfileobj(audio.file, f) process = subprocess.run( [ "python", "inference.py", "--checkpoint_path", "checkpoints/wav2lip_gan.pth", "--face", image_path, "--audio", audio_path ], capture_output=True, text=True ) # دمج stdout و stderr output = (process.stdout or "") + "\n" + (process.stderr or "") if process.returncode != 0: # خطأ عدم اكتشاف وجه if "Face not detected!" in output or "No face detected" in output: raise HTTPException( status_code=400, detail="No face detected in the uploaded image. Please upload a clear front-facing image." ) # خطأ الملف الصوتي if "Mel contains nan" in output: raise HTTPException( status_code=400, detail="The uploaded audio is invalid or unsupported." ) # أي خطأ آخر raise HTTPException( status_code=500, detail=output ) wav2lip_video = "results/result_voice.mp4" if not os.path.exists(wav2lip_video): raise HTTPException( status_code=500, detail="Wav2Lip output video not found." ) final_video = "results/final_output.mp4" merge_audio_video( wav2lip_video, audio_path, final_video ) return FileResponse( final_video, media_type="video/mp4", filename="final_output.mp4" )