Spaces:
Paused
Paused
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139import gradio as grimport torchimport subprocessimport osfrom pathlib import Pathimport shutildef setup_hallo():"""Setup Hallo2 on first run"""if Path("hallo2_installed.txt").exists():return Truetry:print("Installing Hallo2...")# Clone reposubprocess.run("git clone https://github.com/fudan-generative-vision/hallo2.git /tmp/hallo2", shell=True, check=True)# Install requirementssubprocess.run("pip install -q diffusers[torch] transformers av insightface onnxruntime-gpu", shell=True, check=True)# Download modelssubprocess.run("huggingface-cli download fudan-generative-ai/hallo2 --local-dir /tmp/hallo2/pretrained_models", shell=True, check=True)Path("hallo2_installed.txt").touch()print("β Hallo2 setup complete!")return Trueexcept Exception as e:print(f"Setup error: {e}")return Falsedef generate_video(image, audio):"""Generate lip-synced video"""try:if not image or not audio:return None, "β Please upload both image and audio!"# Setup on first runif not setup_hallo():return None, "β Setup failed"# Prepare pathsoutput_dir = Path("/tmp/outputs")output_dir.mkdir(exist_ok=True)output_file = output_dir / "result.mp4"# Copy inputsimg_path = "/tmp/input_img.jpg"aud_path = "/tmp/input_audio.wav"shutil.copy(image, img_path)shutil.copy(audio, aud_path)# Run inferenceprint("π¬ Generating video...")cmd = f"""cd /tmp/hallo2 && python scripts/inference.py \--source_image {img_path} \--driving_audio {aud_path} \--output {output_file} \--pose_weight 1.0 \--face_weight 1.0 \--lip_weight 1.0"""result = subprocess.run(cmd, shell=True, capture_output=True, text=True)if output_file.exists():return str(output_file), "β Video generated successfully!"else:return None, f"β Generation failed. Error: {result.stderr[:200]}"except Exception as e:return None, f"β Error: {str(e)}"# Gradio Interfacewith gr.Blocks(theme=gr.themes.Soft(), title="AI Lip Sync") as app:gr.Markdown("""# π€ AI Lip Sync GeneratorUpload a portrait image and audio to create a realistic lip-synced video!**β‘ Fast generation on T4 GPU (~30-60 seconds)**""")with gr.Row():with gr.Column(scale=1):gr.Markdown("### π€ Upload Files")image_input = gr.Image(type="filepath",label="Portrait Image (JPG/PNG)",height=300)audio_input = gr.Audio(type="filepath",label="Audio File (WAV/MP3)")generate_btn = gr.Button("π Generate Lip-Synced Video",variant="primary",size="lg")with gr.Column(scale=1):gr.Markdown("### πΉ Output")video_output = gr.Video(label="Generated Video",height=400)status_output = gr.Textbox(label="Status",lines=3,interactive=False)gr.Markdown("""---### π‘ Tips:- Use clear, front-facing portrait images- Best resolution: 512x512 or higher- Audio length: Up to 60 seconds recommended- First generation will download models (~2GB)### β±οΈ Performance:- First run: ~3-5 minutes (model download)- Subsequent runs: ~30-60 seconds per video""")generate_btn.click(fn=generate_video,inputs=[image_input, audio_input],outputs=[video_output, status_output])if __name__ == "__main__":app.launch()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162import gradio as grfrom gradio_client import Client, handle_fileimport shutilfrom pathlib import Pathdef generate_video(image, audio):"""Use existing HF Space API"""try:if not image or not audio:return None, "β Please upload both files!"print("π Connecting to API...")# Use the working MuseTalk spaceclient = Client("TMElyralab/MuseTalk")print("π€ Uploading files...")result = client.predict(audio_path=handle_file(audio),video_path=None,bbox_shift=0,api_name="/predict")# Result is a file pathif result and Path(result).exists():# Copy to local outputoutput = "result.mp4"shutil.copy(result, output)return output, "β Video generated successfully!"else:return None, "β API returned no result"except Exception as e:return None, f"β Error: {str(e)}"# Gradio UIwith gr.Blocks(theme=gr.themes.Soft()) as app:gr.Markdown("# π¬ AI Lip Sync Generator")gr.Markdown("Upload a face image and audio to create lip-synced video")with gr.Row():with gr.Column():img = gr.Image(type="filepath", label="π· Face Image")aud = gr.Audio(type="filepath", label="π΅ Audio File")btn = gr.Button("π Generate Video", variant="primary")with gr.Column():vid = gr.Video(label="πΉ Result")status = gr.Textbox(label="Status", lines=2)btn.click(generate_video, [img, aud], [vid, status])gr.Markdown("""### π‘ Notes:- Uses MuseTalk API (no local installation needed)- Processing time: 30-90 seconds- Best with clear front-facing images""")app.launch()
app.py+39-116