Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(longcat): plan segments from audio length and report weight completeness
nirholas5f9f54d15b0a
diff --git a/workers/longcat/main.py b/workers/longcat/main.pyindex 0d15f4b0e..a7403101c 100644--- a/workers/longcat/main.py+++ b/workers/longcat/main.py@@ -4,17 +4,20 @@ LongCat Video Avatar service — audio-driven talking avatar video generation.POST /generate { image_url, audio_url, prompt?, job_id? }→ 202 { job_id, status: "queued" }- GET /jobs/:id → { job_id, status, progress?, video_url?, error?, updated_at }+ GET /jobs/:id → { job_id, status, progress?, segments?, audio_seconds?,+ video_url?, error?, updated_at }- GET /health → { ok, model_loaded }+ GET /health → { ok, model_loaded, missing_weights, resolution, ... }Environment variables (all required unless noted):API_KEY — shared bearer secret (set via GCP Secret Manager)GCS_BUCKET — Cloud Storage bucket for output MP4sFIRESTORE_PROJECT — GCP project hosting Firestore- WEIGHTS_DIR — path to LongCat model weights (default: /weights)+ WEIGHTS_DIR root holding both LongCat repos (default: /weights/longcat;+ see model_weights.py for the required layout)LONGCAT_REPO_DIR — path to cloned LongCat repo (default: /longcat)MAX_CONCURRENT — parallel inference jobs (default: 1; GPU-bound)+ MAX_SEGMENTS cap on generated segments (default: 8, about 26 s of video)RESOLUTION — 480p or 720p (default: 720p)"""@@ -25,7 +28,6 @@ import base64import jsonimport loggingimport os-import reimport shutilimport subprocessimport tempfile@@ -39,6 +41,13 @@ from fastapi import BackgroundTasks, FastAPI, HTTPException, Headerfrom google.cloud import firestore, storagefrom pydantic import BaseModel+import model_weights+from inference_plan import (+ ProgressTracker,+ segment_span_seconds,+ segments_for_audio,+ select_output_video,+)from worker_security import (UnsafeUrlError,fetch_remote_bytes_async,@@ -57,40 +66,24 @@ log = logging.getLogger("main")API_KEY = os.environ["API_KEY"]GCS_BUCKET = os.environ["GCS_BUCKET"]FIRESTORE_PROJECT = os.environ["FIRESTORE_PROJECT"]-WEIGHTS_DIR = Path(os.environ.get("WEIGHTS_DIR", "/weights"))+WEIGHTS_DIR = Path(os.environ.get("WEIGHTS_DIR", "/weights/longcat"))LONGCAT_REPO_DIR = Path(os.environ.get("LONGCAT_REPO_DIR", "/longcat"))-MAX_CONCURRENT = int(os.environ.get("MAX_CONCURRENT", "1"))+MAX_CONCURRENT = max(1, int(os.environ.get("MAX_CONCURRENT", "1")))+MAX_SEGMENTS = max(1, int(os.environ.get("MAX_SEGMENTS", "8")))RESOLUTION = os.environ.get("RESOLUTION", "720p")-WEIGHTS_SUBDIR = WEIGHTS_DIR / "LongCat-Video-Avatar"--# Progress line patterns, tried in order. Each yields a 0–1 float.-# Covers tqdm bars ("42%|"), "frame X/Y", "step X/Y", and bare "X%".-_PROGRESS_PATTERNS: list[tuple[re.Pattern, callable]] = [- # tqdm: "42%|████..." or "42it [" (no denominator → skip)- (re.compile(r'^\s*(\d+)%\|'), lambda m: float(m.group(1)) / 100),- # "frame(s) X / Y" or "frame X/Y"- (re.compile(r'frames?\s+(\d+)\s*/\s*(\d+)', re.IGNORECASE),- lambda m: int(m.group(1)) / int(m.group(2)) if int(m.group(2)) > 0 else None),- # "step(s) X / Y"- (re.compile(r'steps?\s+(\d+)\s*/\s*(\d+)', re.IGNORECASE),- lambda m: int(m.group(1)) / int(m.group(2)) if int(m.group(2)) > 0 else None),- # bare percentage anywhere in the line- (re.compile(r'\b(\d{1,3})%'), lambda m: min(float(m.group(1)) / 100, 1.0)),-]---def _parse_progress(line: str) -> float | None:- for pattern, extractor in _PROGRESS_PATTERNS:- m = pattern.search(line)- if m:- try:- val = extractor(m)- if val is not None and 0.0 <= val <= 1.0:- return val- except (ZeroDivisionError, ValueError):- continue- return None+# Upstream's argparse restricts --resolution to these two. Catching a typo here+# turns a 40-minute-late CUDA crash into a boot failure the deploy can see.+SUPPORTED_RESOLUTIONS = ("480p", "720p")+if RESOLUTION not in SUPPORTED_RESOLUTIONS:+ raise RuntimeError(+ f"RESOLUTION={RESOLUTION!r} is not supported; expected one of {SUPPORTED_RESOLUTIONS}"+ )++CHECKPOINT_DIR = model_weights.avatar_dir(WEIGHTS_DIR)+BASE_MODEL_DIR = model_weights.base_dir(WEIGHTS_DIR)++INFERENCE_SCRIPT = "run_demo_avatar_single_audio_to_video.py"# ── global state ───────────────────────────────────────────────────────────────@@ -115,49 +108,36 @@ async def lifespan(app: FastAPI):_db = firestore.Client(project=FIRESTORE_PROJECT)_bucket = storage.Client().bucket(GCS_BUCKET)- if not WEIGHTS_SUBDIR.exists():- log.warning(- "Model weights not found at %s — downloading from HuggingFace Hub...",- WEIGHTS_SUBDIR,+ missing = model_weights.missing_paths(WEIGHTS_DIR)+ if missing:+ # Deliberately not downloading here. The required set is ~45 GB across+ # two HuggingFace repos; pulling it inside the startup hook guarantees a+ # startup-probe timeout and re-pulls on every cold start. Weights are+ # staged into the GCS weights bucket once (stage-weights.sh) and mounted.+ log.error(+ "Model weights incomplete under %s: /generate will answer 503. Missing: %s. "+ "Stage them with workers/longcat/stage-weights.sh.",+ WEIGHTS_DIR,+ model_weights.describe_missing(missing),)- _download_weights()else:- log.info("Model weights found at %s", WEIGHTS_SUBDIR)+ log.info("Model weights complete under %s", WEIGHTS_DIR)log.info(- "Server ready — resolution=%s, max_concurrent=%d, weights=%s",- RESOLUTION, MAX_CONCURRENT, WEIGHTS_SUBDIR,+ "Server ready: resolution=%s, max_concurrent=%d, max_segments=%d, weights=%s",+ RESOLUTION, MAX_CONCURRENT, MAX_SEGMENTS, WEIGHTS_DIR,)yieldawait _http.aclose()-def _download_weights() -> None:- WEIGHTS_DIR.mkdir(parents=True, exist_ok=True)- subprocess.run(- [- "python", "-c",- (- "from huggingface_hub import snapshot_download; "- "snapshot_download("- " 'meituan-longcat/LongCat-Video-Avatar-1.5',"- f" local_dir='{WEIGHTS_SUBDIR}',"- " ignore_patterns=['*.pt']"- ")"- ),- ],- check=True,- )- log.info("Weights downloaded to %s", WEIGHTS_SUBDIR)--app = FastAPI(title="longcat-video-avatar", lifespan=lifespan)# ── auth ───────────────────────────────────────────────────────────────────────-def _require_api_key(authorization: str) -> None:+def _require_api_key(authorization: str | None) -> None:try:require_api_key(authorization, API_KEY)except PermissionError as exc:@@ -180,6 +160,27 @@ def _get_job(job_id: str) -> dict | None:# ── inference worker ───────────────────────────────────────────────────────────+def _probe_audio_seconds(path: Path) -> float | None:+ """Duration of ``path`` per ffprobe, or None when it cannot be determined."""+ try:+ completed = subprocess.run(+ [+ "ffprobe", "-v", "error",+ "-show_entries", "format=duration",+ "-of", "default=noprint_wrappers=1:nokey=1",+ str(path),+ ],+ capture_output=True,+ text=True,+ timeout=60,+ check=True,+ )+ return float(completed.stdout.strip())+ except (subprocess.SubprocessError, ValueError) as exc:+ log.warning("ffprobe could not read a duration from %s: %s", path, exc)+ return None++async def _process_job(job_id: str,image_url: str,@@ -200,6 +201,21 @@ async def _process_job(await _download_file(image_url, image_path)await _download_file(audio_url, audio_path)+ # One segment covers 3.72 s. Sizing from the real audio length is+ # what stops a 20-second voice clip rendering as a 4-second video.+ audio_seconds = await asyncio.get_event_loop().run_in_executor(+ None, lambda: _probe_audio_seconds(audio_path)+ )+ segments = segments_for_audio(audio_seconds, MAX_SEGMENTS)+ log.info(+ "[%s] audio=%.2fs → %d segment(s) covering %.2fs",+ job_id,+ audio_seconds if audio_seconds is not None else -1.0,+ segments,+ segment_span_seconds(segments),+ )+ _set_job(job_id, {"audio_seconds": audio_seconds, "segments": segments})+config = {"prompt": prompt,"cond_image": str(image_path),@@ -212,16 +228,23 @@ async def _process_job(loop = asyncio.get_event_loop()await loop.run_in_executor(None,- lambda: _run_inference(job_id, config_path, output_dir),+ lambda: _run_inference(job_id, config_path, output_dir, segments),)- # Find the generated MP4- mp4_files = list(output_dir.glob("**/*.mp4"))- if not mp4_files:- raise RuntimeError("No MP4 output found after inference")- mp4_path = mp4_files[0]-- log.info("[%s] uploading %d bytes to GCS", job_id, mp4_path.stat().st_size)+ names = sorted(+ p.relative_to(output_dir).as_posix() for p in output_dir.rglob("*.mp4")+ )+ chosen = select_output_video(names)+ if chosen is None:+ raise RuntimeError(+ f"inference produced no final MP4 (saw {len(names)} candidate file(s))"+ )+ mp4_path = output_dir / chosen++ log.info(+ "[%s] uploading %s (%d bytes) to GCS",+ job_id, chosen, mp4_path.stat().st_size,+ )blob_name = f"avatar-videos/{job_id}.mp4"blob = _bucket.blob(blob_name)blob.content_type = "video/mp4"@@ -244,19 +267,29 @@ async def _process_job(shutil.rmtree(workdir, ignore_errors=True)-def _run_inference(job_id: str, config_path: Path, output_dir: Path) -> None:+def _run_inference(+ job_id: str,+ config_path: Path,+ output_dir: Path,+ segments: int,+) -> None:cmd = ["torchrun","--nproc_per_node=1",- "run_demo_avatar_single_audio_to_video.py",+ INFERENCE_SCRIPT,"--input_json", str(config_path),"--output_dir", str(output_dir),- "--checkpoint_dir", str(WEIGHTS_SUBDIR),+ "--checkpoint_dir", str(CHECKPOINT_DIR),"--resolution", RESOLUTION,"--model_type", "avatar-v1.5",+ # ai2v is audio-image-to-video: it consumes config.cond_image. at2v+ # ignores the reference image entirely, which is never what this service+ # wants. Upstream's default happens to be ai2v; pin it so an upstream+ # default change cannot silently drop the caller's avatar.+ "--stage_1", "ai2v",+ "--num_segments", str(segments),"--use_distill","--use_int8",- "--num_inference_steps", "8",]log.info("[%s] cmd: %s", job_id, " ".join(cmd))@@ -271,16 +304,19 @@ def _run_inference(job_id: str, config_path: Path, output_dir: Path) -> None:)stdout_lines: list[str] = []- last_progress: float | None = None+ tracker = ProgressTracker(expected_segments=segments)for raw_line in process.stdout:line = raw_line.rstrip()stdout_lines.append(line)+ # Keep only enough tail for a failure report; a multi-segment 720p run+ # emits tens of thousands of tqdm lines.+ if len(stdout_lines) > 200:+ del stdout_lines[:100]log.info("[%s] %s", job_id, line)- progress = _parse_progress(line)- if progress is not None and progress != last_progress:- last_progress = progress+ progress = tracker.update(line)+ if progress is not None:_set_job(job_id, {"progress": progress})process.wait()@@ -323,9 +359,23 @@ class GenerateRequest(BaseModel):async def generate(body: GenerateRequest,background_tasks: BackgroundTasks,- authorization: str = Header(...),+ authorization: str | None = Header(default=None),) -> dict:_require_api_key(authorization)++ # Fail fast and loudly instead of queueing a job that will spend two minutes+ # loading models and then die on a missing checkpoint.+ missing = model_weights.missing_paths(WEIGHTS_DIR)+ if missing:+ log.error(+ "rejecting /generate: weights incomplete under %s (%s)",+ WEIGHTS_DIR, model_weights.describe_missing(missing),+ )+ raise HTTPException(+ status_code=503,+ detail="model weights are not staged on this instance",+ )+job_id = body.job_id or str(uuid.uuid4())_set_job(job_id, {"job_id": job_id,@@ -343,7 +393,10 @@ async def generate(@app.get("/jobs/{job_id}")-async def get_job(job_id: str, authorization: str = Header(...)) -> dict:+async def get_job(+ job_id: str,+ authorization: str | None = Header(default=None),+) -> dict:_require_api_key(authorization)job = _get_job(job_id)if job is None:@@ -356,10 +409,15 @@ async def get_job(job_id: str, authorization: str = Header(...)) -> dict:@app.get("/health")async def health() -> dict:+ missing = model_weights.missing_paths(WEIGHTS_DIR)return {"ok": True,"pipeline": "longcat-avatar-1.5",- "model_loaded": WEIGHTS_SUBDIR.exists(),- "weights_dir": str(WEIGHTS_SUBDIR),+ "model_loaded": not missing,+ "missing_weights": [str(path) for path in missing],+ "weights_dir": str(WEIGHTS_DIR),+ "checkpoint_dir": str(CHECKPOINT_DIR),+ "base_model_dir": str(BASE_MODEL_DIR),"resolution": RESOLUTION,+ "max_segments": MAX_SEGMENTS,}