Spaces:
Paused
Paused
Update app.py
Browse files1234562 unmodified lines910111213141516171819202122232425262728293031323334353637383940414243444546474810 unmodified lines59606162636465666768697071725 unmodified lines78798081828384858687882 unmodified lines91929394959697import osimport shutilimport subprocessfrom pathlib import Pathimport gradio as gr2 unmodified linesOUTPUT_DIR = Path("outputs")OUTPUT_DIR.mkdir(exist_ok=True)def run(cmd, cwd=None):"""Run a shell command safely and raise a helpful error if it fails."""p = subprocess.run(cmd,cwd=str(cwd) if cwd else None,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True,check=False)if p.returncode != 0:raise RuntimeError(f"Command failed ({p.returncode}): {' '.join(cmd)}\n\n{p.stdout}")return p.stdoutdef setup():"""One-time setup: clone repo + download models.Uses a flag file so it doesn't redo work every request."""if SETUP_FLAG.exists() and REPO_DIR.exists():returnprint("Setting up Video-Retalking...")if not REPO_DIR.exists():run(["git", "clone", "https://github.com/OpenTalker/video-retalking.git", str(REPO_DIR)])# Download models (idempotent in most cases)run(["bash", "scripts/download_models.sh"], cwd=REPO_DIR)SETUP_FLAG.touch()print("β Setup complete!")def generate(image_path, audio_path):if not image_path or not audio_path:10 unmodified linesif not audio_path.exists():return None, f"β Audio not found: {audio_path}"# Unique output name per runout_path = (OUTPUT_DIR / "result.mp4").resolve()# Clean old output if anyif out_path.exists():out_path.unlink()# Run inferencecmd = ["python","inference.py",5 unmodified linesif out_path.exists():return str(out_path), "β Video generated successfully!"return None, "β Failed to generate video (no output file created)."except Exception as e:return None, f"β Error: {e}"demo = gr.Interface(fn=generate,inputs=[2 unmodified lines],outputs=[gr.Video(label="πΉ Generated Video"),gr.Textbox(label="Status", lines=3),],title="π¬ Video-Retalking Lip Sync",description="Upload a face image and audio to generate a lip-synced video.",123452 unmodified lines8910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510 unmodified lines1161171181191201211221231241255 unmodified lines1311321331341351361371381391401411422 unmodified lines145146147148149150151import subprocessimport threadingfrom pathlib import Pathimport gradio as gr2 unmodified linesOUTPUT_DIR = Path("outputs")OUTPUT_DIR.mkdir(exist_ok=True)# Hugging Face mirror containing the checkpoint files (fast + reliable)HF_BASE = "https://huggingface.co/camenduru/video-retalking/resolve/main"# Files needed by Video-Retalking pipeline (common minimal set)CHECKPOINT_FILES = ["30_net_gen.pth","BFM.zip","DNet.pt","ENet.pth","LNet.pth","ParseNet-latest.pth","RetinaFace-R50.pth","expression.mat","face3d_pretrain_epoch_20.pth","GFPGANv1.3.pth","GPEN-BFR-512.pth","shape_predictor_68_face_landmarks.dat",]_setup_lock = threading.Lock()def run(cmd, cwd=None):p = subprocess.run(cmd,cwd=str(cwd) if cwd else None,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True,check=False,)if p.returncode != 0:raise RuntimeError(f"Command failed ({p.returncode}): {' '.join(cmd)}\n\n{p.stdout}")return p.stdoutdef download_file(url: str, dest: Path):"""Download using curl with resume support (-C -) and follow redirects (-L)."""dest.parent.mkdir(parents=True, exist_ok=True)# Skip if already presentif dest.exists() and dest.stat().st_size > 0:returnrun(["bash", "-lc", f'curl -L -C - --retry 5 --retry-delay 2 -o "{dest}" "{url}"'])def ensure_checkpoints():ckpt_dir = REPO_DIR / "checkpoints"ckpt_dir.mkdir(parents=True, exist_ok=True)# Download required checkpoint filesfor fname in CHECKPOINT_FILES:url = f"{HF_BASE}/{fname}"download_file(url, ckpt_dir / fname)# Unzip BFM.zip -> checkpoints/BFM/bfm_zip = ckpt_dir / "BFM.zip"bfm_dir = ckpt_dir / "BFM"if not bfm_dir.exists():bfm_dir.mkdir(parents=True, exist_ok=True)run(["unzip", "-q", str(bfm_zip), "-d", str(bfm_dir)])def setup():"""One-time setup: clone repo, pull LFS (best effort), download checkpoints.Guarded by a lock to prevent multiple concurrent setup runs."""with _setup_lock:if SETUP_FLAG.exists() and REPO_DIR.exists():returnprint("Setting up Video-Retalking...")if not REPO_DIR.exists():run(["git", "clone", "https://github.com/OpenTalker/video-retalking.git", str(REPO_DIR)])# Best-effort: fetch any git-lfs files if repo uses themtry:run(["git", "lfs", "pull"], cwd=REPO_DIR)except Exception:# Not fatal; we'll fetch checkpoints from HF mirror anywaypassensure_checkpoints()SETUP_FLAG.touch()print("β Setup complete!")def generate(image_path, audio_path):if not image_path or not audio_path:10 unmodified linesif not audio_path.exists():return None, f"β Audio not found: {audio_path}"out_path = (OUTPUT_DIR / "result.mp4").resolve()if out_path.exists():out_path.unlink()cmd = ["python","inference.py",5 unmodified linesif out_path.exists():return str(out_path), "β Video generated successfully!"return None, "β Failed (no output file created)."except Exception as e:return None, f"β Error: {e}"demo = gr.Interface(fn=generate,inputs=[2 unmodified lines],outputs=[gr.Video(label="πΉ Generated Video"),gr.Textbox(label="Status", lines=4),],title="π¬ Video-Retalking Lip Sync",description="Upload a face image and audio to generate a lip-synced video.",
app.py+78-24