Spaces:
Paused
Paused
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185import osimport subprocessimport gradio as grfrom pathlib import Pathfrom datetime import datetimeimport shutil# Environment setupos.environ["GRADIO_TEMP_DIR"] = "/tmp/gradio"os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"ROOT = Path(__file__).parentMUSETALK_DIR = ROOT / "MuseTalk"MODELS_DIR = MUSETALK_DIR / "models"RESULTS_DIR = MUSETALK_DIR / "results"def run_command(cmd, cwd=None):"""Run shell command safely"""try:result = subprocess.run(cmd,shell=True,cwd=cwd,capture_output=True,text=True,check=True)print(result.stdout)return Trueexcept subprocess.CalledProcessError as e:print(f"Error: {e.stderr}")return Falsedef setup_musetalk():"""Setup MuseTalk repository and models"""if not MUSETALK_DIR.exists():print("π¦ Cloning MuseTalk...")run_command(f"git clone https://github.com/TMElyralab/MuseTalk.git {MUSETALK_DIR}")# Create necessary directoriesMODELS_DIR.mkdir(parents=True, exist_ok=True)RESULTS_DIR.mkdir(parents=True, exist_ok=True)# Download models if not presentif not (MODELS_DIR / "musetalk").exists():print("π₯ Downloading MuseTalk models...")run_command("huggingface-cli download TMElyralab/MuseTalk --local-dir models",cwd=MUSETALK_DIR)# Download Whisper model for audio processingif not (MODELS_DIR / "whisper").exists():print("π₯ Downloading Whisper...")run_command("huggingface-cli download openai/whisper-tiny --local-dir models/whisper",cwd=MUSETALK_DIR)print("β Setup complete!")return Truedef generate_video(avatar_image, audio_file, bbox_shift=0):"""Generate lip-synced video using MuseTalk"""try:# Setup on first runif not MUSETALK_DIR.exists():if not setup_musetalk():return None, "β Setup failed"if not avatar_image or not audio_file:return None, "β Please upload both image and audio"# Prepare input filestimestamp = datetime.now().strftime("%Y%m%d_%H%M%S")input_img = MUSETALK_DIR / f"input_img_{timestamp}.jpg"input_audio = MUSETALK_DIR / f"input_audio_{timestamp}.wav"shutil.copy(avatar_image, input_img)shutil.copy(audio_file, input_audio)# Run MuseTalk inferenceprint("π¬ Generating lip-synced video...")output_path = RESULTS_DIR / f"output_{timestamp}.mp4"cmd = f"""python -m scripts.inference \--avatar_id "{input_img}" \--audio_path "{input_audio}" \--bbox_shift {bbox_shift} \--result_dir "{RESULTS_DIR}""""if not run_command(cmd, cwd=MUSETALK_DIR):return None, "β Video generation failed"# Find generated videovideo_files = list(RESULTS_DIR.glob(f"*{timestamp}*.mp4"))if not video_files:# Try finding any recent videovideo_files = sorted(RESULTS_DIR.glob("*.mp4"), key=os.path.getmtime, reverse=True)if video_files:return str(video_files[0]), "β Video generated successfully!"else:return None, "β Output video not found"except Exception as e:return None, f"β Error: {str(e)}"# Gradio Interfacewith gr.Blocks(theme=gr.themes.Soft(), title="MuseTalk Lip Sync") as demo:gr.Markdown("""# π€ MuseTalk - AI Lip Sync GeneratorUpload a face image and audio to create realistic lip-synced videos!**β¨ Features:**- Fast generation (~30 seconds)- High quality lip sync- Works on T4 GPU- Supports various face angles""")with gr.Row():with gr.Column(scale=1):avatar = gr.Image(type="filepath",label="π· Face Image",height=300)audio = gr.Audio(type="filepath",label="π΅ Audio File")bbox_shift = gr.Slider(-20, 20, value=0, step=1,label="Face Alignment Adjustment",info="Adjust if face detection is off")with gr.Column(scale=1):output_video = gr.Video(label="π¬ Generated Video",height=400)status = gr.Textbox(label="Status",interactive=False,value="Ready to generate...")generate_btn = gr.Button("π Generate Lip-Synced Video",variant="primary",size="lg")generate_btn.click(fn=generate_video,inputs=[avatar, audio, bbox_shift],outputs=[output_video, status])gr.Markdown("""---### π Tips:- Use clear, front-facing images for best results- Recommended resolution: 512x512 or higher- Audio should be clear with minimal background noise- First run downloads models (~3GB) - please wait### β‘ Performance:- T4 GPU: ~30-60 seconds per video- Supports videos up to 2 minutes**Powered by [MuseTalk](https://github.com/TMElyralab/MuseTalk)**""")if __name__ == "__main__":demo.queue(max_size=5)demo.launch(server_name="0.0.0.0", server_port=7860)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677import osimport gradio as grimport subprocessfrom pathlib import Pathimport shutil# Simple setupROOT = Path("/tmp/musehub")ROOT.mkdir(exist_ok=True)def generate_lipsync(image_path, audio_path):"""Generate lip-synced video using simple ffmpeg + ML approach"""try:if not image_path or not audio_path:return None, "β Please upload both image and audio"output = ROOT / "output.mp4"# Method 1: Use video-retalking (simpler and works on T4)cmd = ["python", "inference.py","--face", image_path,"--audio", audio_path,"--outfile", str(output)]subprocess.run(cmd, check=True, cwd="/app/video-retalking")if output.exists():return str(output), "β Video generated!"return None, "β Generation failed"except Exception as e:return None, f"β Error: {str(e)}"def setup_model():"""Download and setup video-retalking"""repo_dir = Path("/app/video-retalking")if repo_dir.exists():return Truetry:# Clone reposubprocess.run(["git", "clone","https://github.com/OpenTalker/video-retalking.git",str(repo_dir)], check=True)# Download checkpointssubprocess.run(["bash", "scripts/download_models.sh"], cwd=repo_dir, check=True)return Trueexcept:return False# Gradio UIwith gr.Blocks(title="AI Lip Sync") as demo:gr.Markdown("# π€ AI Lip Sync Generator\nUpload a face image and audio to create lip-synced video")with gr.Row():with gr.Column():image = gr.Image(type="filepath", label="Face Image")audio = gr.Audio(type="filepath", label="Audio File")btn = gr.Button("π Generate", variant="primary")with gr.Column():video = gr.Video(label="Result")status = gr.Textbox(label="Status")btn.click(generate_lipsync, [image, audio], [video, status])if __name__ == "__main__":setup_model()demo.launch()
app.py+53-161