Some checks are pending
build-images / api (push) Waiting to run
build-images / worker-gpu (push) Waiting to run
build-images / web (push) Waiting to run
codeql / Analyze (javascript-typescript) (push) Waiting to run
codeql / Analyze (python) (push) Waiting to run
perf / API hot-path micro-smoke (budgeted) (push) Waiting to run
perf / Desktop engine crates (release build check) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Waiting to run
vision2026-ci / API phase modules (ruff + pytest) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Waiting to run
vision2026-ci / Python SDK resource tests (push) Waiting to run
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Waiting to run
vision2026-ci / Alembic upgrade + drift check (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Waiting to run
Paid, hosted product at menivor.com, now retired as a company project. Fresh squashed history of the cleaned working tree (secret-scanned, no .env, no customer data, no outreach logs). Built on MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
198 lines
9.0 KiB
Python
198 lines
9.0 KiB
Python
"""RunPod serverless worker: InfiniteTalk (MeiGen-AI/InfiniteTalk, Apache-2.0) lip-sync.
|
|
|
|
Tasks (``job["input"]["task"]``):
|
|
|
|
* ``infinitetalk`` image + speech -> talking video. Input: ``image_base64``, ``audio_base64``,
|
|
``prompt``, ``seconds``, ``aspect_ratio``. Used by Ad Clone's ``runpod_wan`` engine.
|
|
* ``infinitetalk_dub`` video + new speech -> the same video lip-synced to the new speech
|
|
(video-to-video dubbing). Input: ``video_url`` (https, an allowed media host),
|
|
``audio_base64``, ``seconds``. Used by lip-sync translation.
|
|
|
|
Output: ``{"video_url": <public URL of the uploaded mp4>, "seconds": <float>}``. RunPod
|
|
wraps it as ``output`` and reports ``executionTime`` (GPU ms), which the API books.
|
|
|
|
Environment (set on the RunPod endpoint, never in code):
|
|
``INFINITETALK_DIR`` (repo checkout, default /workspace/InfiniteTalk), ``INFINITETALK_CKPT_DIR``,
|
|
``INFINITETALK_WAV2VEC_DIR``, ``INFINITETALK_WEIGHTS`` (infinitetalk.safetensors),
|
|
``INFINITETALK_SIZE`` (default infinitetalk-480), ``INFINITETALK_STEPS`` (default 8 with the
|
|
lightx2v LoRA in ``INFINITETALK_LORA``, else 40), ``MEDIA_ALLOWED_HOSTS`` (comma list),
|
|
``BUCKET_ENDPOINT_URL`` / ``BUCKET_ACCESS_KEY_ID`` / ``BUCKET_SECRET_ACCESS_KEY`` /
|
|
``BUCKET_NAME`` / ``BUCKET_PUBLIC_URL`` (S3-compatible output bucket, e.g. Cloudflare R2).
|
|
|
|
Every step (download, ffmpeg, the model, upload) is an injectable seam, so the handler is
|
|
tested without a GPU. Command-line flags follow the InfiniteTalk README
|
|
(``generate_infinitetalk.py --input_json ... --mode streaming``); confirm on the GPU image.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import json
|
|
import os
|
|
import shutil
|
|
import subprocess
|
|
import tempfile
|
|
import time
|
|
import urllib.request
|
|
import uuid
|
|
from dataclasses import dataclass, field
|
|
from typing import Any, Callable, Mapping
|
|
from urllib.parse import urlparse
|
|
|
|
TASKS = ("infinitetalk", "infinitetalk_dub")
|
|
MAX_VIDEO_BYTES = 300 * 1024 * 1024
|
|
MAX_AUDIO_BYTES = 40 * 1024 * 1024
|
|
MAX_SECONDS = 120.0
|
|
SIZES = {"9:16": "infinitetalk-480", "16:9": "infinitetalk-480", "1:1": "infinitetalk-480"}
|
|
|
|
|
|
class WorkerError(Exception):
|
|
"""A refused or failed job; the message is returned to the API as ``error``."""
|
|
|
|
|
|
@dataclass
|
|
class Deps:
|
|
env: Mapping[str, str] = field(default_factory=lambda: dict(os.environ))
|
|
download: Callable[[str, str, int], str] | None = None # (url, dest, max_bytes) -> path
|
|
run: Callable[[list[str], str], None] | None = None # (argv, cwd) -> None, raises on failure
|
|
upload: Callable[[str, str], str] | None = None # (path, key) -> public url
|
|
clock: Callable[[], float] = time.time
|
|
|
|
|
|
# --------------------------------------------------------------------------- input checks
|
|
def _allowed_hosts(env: Mapping[str, str]) -> set[str]:
|
|
return {h.strip().lower() for h in str(env.get("MEDIA_ALLOWED_HOSTS") or "").split(",") if h.strip()}
|
|
|
|
|
|
def check_video_url(url: str, env: Mapping[str, str]) -> str:
|
|
parsed = urlparse(str(url or ""))
|
|
host = (parsed.hostname or "").lower()
|
|
allowed = _allowed_hosts(env)
|
|
if parsed.scheme != "https" or not host:
|
|
raise WorkerError("video_url must be an https URL")
|
|
if not allowed or not any(host == a or host.endswith("." + a) for a in allowed):
|
|
raise WorkerError("video_url host is not an allowed media host")
|
|
return url
|
|
|
|
|
|
def _b64(value: Any, limit: int, what: str) -> bytes:
|
|
try:
|
|
raw = base64.b64decode(str(value or ""), validate=True)
|
|
except (ValueError, TypeError) as exc:
|
|
raise WorkerError(f"{what} is not base64") from exc
|
|
if not raw:
|
|
raise WorkerError(f"{what} is empty")
|
|
if len(raw) > limit:
|
|
raise WorkerError(f"{what} is too large")
|
|
return raw
|
|
|
|
|
|
def _seconds(value: Any) -> float:
|
|
try:
|
|
secs = float(value)
|
|
except (TypeError, ValueError) as exc:
|
|
raise WorkerError("seconds must be a number") from exc
|
|
if not 0 < secs <= MAX_SECONDS:
|
|
raise WorkerError(f"seconds must be between 0 and {MAX_SECONDS:.0f}")
|
|
return secs
|
|
|
|
|
|
# --------------------------------------------------------------------------- default seams
|
|
def default_download(url: str, dest: str, max_bytes: int) -> str:
|
|
req = urllib.request.Request(url, headers={"User-Agent": "menivor-infinitetalk"})
|
|
with urllib.request.urlopen(req, timeout=120) as resp, open(dest, "wb") as out: # noqa: S310 - host checked
|
|
total = 0
|
|
while chunk := resp.read(1 << 20):
|
|
total += len(chunk)
|
|
if total > max_bytes:
|
|
raise WorkerError("the input video is too large")
|
|
out.write(chunk)
|
|
return dest
|
|
|
|
|
|
def default_run(argv: list[str], cwd: str) -> None:
|
|
done = subprocess.run(argv, cwd=cwd, capture_output=True, text=True, check=False) # noqa: S603 - fixed argv
|
|
if done.returncode != 0:
|
|
raise WorkerError(f"{os.path.basename(argv[1] if len(argv) > 1 else argv[0])} failed: "
|
|
f"{(done.stderr or '')[-300:]}")
|
|
|
|
|
|
def default_upload(env: Mapping[str, str]) -> Callable[[str, str], str]:
|
|
def upload(path: str, key: str) -> str:
|
|
import boto3 # available in the worker image
|
|
|
|
bucket = env["BUCKET_NAME"]
|
|
client = boto3.client("s3", endpoint_url=env["BUCKET_ENDPOINT_URL"],
|
|
aws_access_key_id=env["BUCKET_ACCESS_KEY_ID"],
|
|
aws_secret_access_key=env["BUCKET_SECRET_ACCESS_KEY"])
|
|
client.upload_file(path, bucket, key, ExtraArgs={"ContentType": "video/mp4"})
|
|
return f"{env['BUCKET_PUBLIC_URL'].rstrip('/')}/{key}"
|
|
|
|
return upload
|
|
|
|
|
|
# --------------------------------------------------------------------------- the job
|
|
def model_argv(env: Mapping[str, str], input_json: str, out_stem: str, size: str) -> list[str]:
|
|
repo = env.get("INFINITETALK_DIR") or "/workspace/InfiniteTalk"
|
|
lora = env.get("INFINITETALK_LORA") or ""
|
|
steps = env.get("INFINITETALK_STEPS") or ("8" if lora else "40")
|
|
argv = ["python", os.path.join(repo, "generate_infinitetalk.py"),
|
|
"--ckpt_dir", env.get("INFINITETALK_CKPT_DIR") or "/models/Wan2.1-I2V-14B-480P",
|
|
"--wav2vec_dir", env.get("INFINITETALK_WAV2VEC_DIR") or "/models/chinese-wav2vec2-base",
|
|
"--infinitetalk_dir", env.get("INFINITETALK_WEIGHTS") or "/models/InfiniteTalk/single/infinitetalk.safetensors",
|
|
"--input_json", input_json, "--size", size, "--sample_steps", steps, "--mode", "streaming",
|
|
"--motion_frame", "9", "--save_file", out_stem]
|
|
if lora:
|
|
argv += ["--lora_dir", lora, "--lora_scale", "1.0", "--sample_text_guide_scale", "1.0",
|
|
"--sample_audio_guide_scale", "2.0", "--sample_shift", "2"]
|
|
return argv
|
|
|
|
|
|
def handle(job: Mapping[str, Any], deps: Deps | None = None) -> dict[str, Any]:
|
|
d = deps or Deps()
|
|
env = d.env
|
|
data = dict((job or {}).get("input") or {})
|
|
task = str(data.get("task") or "")
|
|
if task not in TASKS:
|
|
return {"error": f"unknown task {task!r}; expected one of {', '.join(TASKS)}"}
|
|
root = tempfile.mkdtemp(prefix="infinitetalk-")
|
|
run = d.run or default_run
|
|
try:
|
|
seconds = _seconds(data.get("seconds"))
|
|
audio_in = os.path.join(root, "speech.bin")
|
|
with open(audio_in, "wb") as f:
|
|
f.write(_b64(data.get("audio_base64"), MAX_AUDIO_BYTES, "audio_base64"))
|
|
audio = os.path.join(root, "speech.wav")
|
|
run(["ffmpeg", "-v", "error", "-y", "-i", audio_in, "-ac", "1", "-ar", "16000", audio], root)
|
|
if task == "infinitetalk_dub":
|
|
cond = (d.download or default_download)(check_video_url(str(data.get("video_url")), env),
|
|
os.path.join(root, "source.mp4"), MAX_VIDEO_BYTES)
|
|
prompt = str(data.get("prompt") or "The same person keeps talking naturally, same framing and light.")
|
|
else:
|
|
cond = os.path.join(root, "first_frame.png")
|
|
with open(cond, "wb") as f:
|
|
f.write(_b64(data.get("image_base64"), 20 * 1024 * 1024, "image_base64"))
|
|
prompt = str(data.get("prompt") or "A person talking to the camera.")
|
|
spec = os.path.join(root, "input.json")
|
|
with open(spec, "w", encoding="utf-8") as f:
|
|
json.dump({"prompt": prompt[:2000], "cond_video": cond, "cond_audio": {"person1": audio}}, f)
|
|
out_stem = os.path.join(root, "out")
|
|
size = env.get("INFINITETALK_SIZE") or SIZES.get(str(data.get("aspect_ratio") or "9:16"), "infinitetalk-480")
|
|
run(model_argv(env, spec, out_stem, size), env.get("INFINITETALK_DIR") or root)
|
|
made = out_stem + ".mp4"
|
|
if not os.path.exists(made):
|
|
raise WorkerError("InfiniteTalk finished without a video")
|
|
key = f"render-workers/infinitetalk/{uuid.uuid4().hex}.mp4"
|
|
url = (d.upload or default_upload(env))(made, key)
|
|
return {"video_url": url, "seconds": seconds, "task": task}
|
|
except WorkerError as exc:
|
|
return {"error": str(exc)}
|
|
finally:
|
|
shutil.rmtree(root, ignore_errors=True)
|
|
|
|
|
|
if __name__ == "__main__": # pragma: no cover - RunPod entry point
|
|
import runpod
|
|
|
|
runpod.serverless.start({"handler": handle})
|