import os import shutil import uuid from pathlib import Path import subprocess import gradio as gr from PIL import Image # SadTalker is in the root of the repo SADTALKER_DIR = Path(".") SRC_DIR = SADTALKER_DIR / "examples" / "source_image" AUD_DIR = SADTALKER_DIR / "examples" / "driven_audio" OUT_DIR = SADTALKER_DIR / "results" SRC_DIR.mkdir(parents=True, exist_ok=True) AUD_DIR.mkdir(parents=True, exist_ok=True) OUT_DIR.mkdir(parents=True, exist_ok=True) def generate_video(image, audio, prompt): if image is None: raise ValueError("Please upload an image.") if audio is None or not os.path.exists(audio): raise ValueError("Please upload an audio file.") run_id = uuid.uuid4().hex[:8] # Save image into SadTalker source_image folder img_path = SRC_DIR / f"src_{run_id}.png" if not isinstance(image, Image.Image): image = Image.fromarray(image) image.save(img_path) # Copy audio into SadTalker driven_audio folder aud_path = AUD_DIR / f"aud_{run_id}.wav" shutil.copy(audio, aud_path) # Build SadTalker inference command cmd = [ "python", "inference.py", "--source_image", str(img_path), "--driven_audio", str(aud_path), "--result_dir", str(OUT_DIR), # add your usual flags here if needed, e.g.: # "--still", # "--enhancer", "gfpgan", ] # Run SadTalker and capture errors result = subprocess.run( cmd, cwd=SADTALKER_DIR, capture_output=True, text=True, ) if result.returncode != 0: raise RuntimeError( "SadTalker failed.\n" f"Command: {' '.join(cmd)}\n\n" f"STDOUT:\n{result.stdout}\n\n" f"STDERR:\n{result.stderr}" ) # Get newest generated video in results/ videos = sorted(OUT_DIR.glob("*.mp4"), key=os.path.getmtime) if not videos: raise RuntimeError("SadTalker did not generate a video.") return str(videos[-1]) with gr.Blocks() as demo: gr.Markdown("# Image + Audio → Talking Head (SadTalker)") with gr.Row(): img = gr.Image(label="Upload image", type="pil") aud = gr.Audio(label="Upload audio", type="filepath") prompt = gr.Textbox( label="Prompt (optional)", placeholder="Notes only; motion is not prompt-controlled.", ) btn = gr.Button("Generate video") out_vid = gr.Video(label="Result video") btn.click(fn=generate_video, inputs=[img, aud, prompt], outputs=out_vid) if __name__ == "__main__": demo.launch()