#!/usr/bin/env python3 """ StableSigner plugin backend Handles prompt/text -> gloss -> pose video generation for the ControlWorld panel. """ from __future__ import annotations import base64 import contextlib import io import os import subprocess import threading import time import uuid from dataclasses import dataclass from datetime import datetime from pathlib import Path from typing import Any, Dict, List, Optional import cv2 # ControlWorld provides plugin_base in the parent directory of every plugin import sys PLUGIN_DIR = Path(__file__).resolve().parent def _inject_plugin_base_path(): candidates = [ PLUGIN_DIR.parent, # actual repo root PLUGIN_DIR.parent / "ControlWorld" / "plugins", Path(__file__).resolve().parent.parent, # fallback two-level parent ] for candidate in candidates: plugin_base_file = candidate / "plugin_base.py" if plugin_base_file.exists(): candidate_str = str(candidate) if candidate_str not in sys.path: sys.path.append(candidate_str) return _inject_plugin_base_path() if str(PLUGIN_DIR) not in sys.path: sys.path.append(str(PLUGIN_DIR)) from plugin_base import PluginBackendBase # type: ignore # pylint: disable=wrong-import-position # Import local helpers lazily when needed from prompt2gloss import build_input as build_prompt_input # type: ignore from pipeline01_text2gloss import load_available_glosses, translate_text_to_gloss # type: ignore def _to_bool(value: Any, default: bool = False) -> bool: if isinstance(value, bool): return value if value is None: return default if isinstance(value, str): return value.strip().lower() in {"1", "true", "yes", "on"} return bool(value) def _safe_int(value: Any, default: int) -> int: try: return int(value) except (TypeError, ValueError): return default def _safe_float(value: Any, default: float) -> float: try: return float(value) except (TypeError, ValueError): return default @dataclass class VideoInfo: path: Path url: str class StableSignerBackend(PluginBackendBase): """Backend logic for StableSigner tab (no Viser visualization required).""" def __init__(self, server): super().__init__(server) self.name = "stable-signer" self.display_name = "StableSigner" self.plugin_root = PLUGIN_DIR self.web_base_url = f"/plugins/{self.plugin_root.name}" self.output_dir = self.plugin_root / "generated_pose_video" self.output_dir.mkdir(parents=True, exist_ok=True) self.sign_output_dir = self.plugin_root / "generated_sign_video" self.sign_output_dir.mkdir(parents=True, exist_ok=True) self.refine_output_dir = self.plugin_root / "generated_sign_video_refine" self.refine_output_dir.mkdir(parents=True, exist_ok=True) self._refine_jobs: Dict[str, Dict[str, Any]] = {} self._refine_jobs_lock = threading.Lock() self._pose_stream_jobs: Dict[str, Dict[str, Any]] = {} self._pose_stream_jobs_lock = threading.Lock() self._prompt_tokenizer = None self._prompt_model = None self._prompt_device = None self._prompt_lock = threading.Lock() self._torch = None self._qa_instances: Dict[int, SignLanguageQA] = {} self._generation_lock = threading.Lock() self._available_glosses = None # ------------------------------------------------------------------ # Lazy loaders # ------------------------------------------------------------------ def _load_prompt_model(self): if self._prompt_model is not None: return model_dir = self.plugin_root / "prompt2gloss" / "t5_finetuned" if not model_dir.exists(): raise FileNotFoundError( f"Prompt2Gloss checkpoint not found at {model_dir}. " "Please train or copy the fine-tuned weights." ) with self._prompt_lock: if self._prompt_model is not None: return from transformers import AutoTokenizer, AutoModelForSeq2SeqLM # lazy import import torch self._prompt_tokenizer = AutoTokenizer.from_pretrained(model_dir) self._prompt_model = AutoModelForSeq2SeqLM.from_pretrained(model_dir) self._torch = torch device = torch.device("cuda" if torch.cuda.is_available() else "cpu") self._prompt_device = device self._prompt_model.to(device) self._prompt_model.eval() def _get_prompt_model(self): self._load_prompt_model() return self._prompt_tokenizer, self._prompt_model, self._prompt_device, self._torch def _get_qa_system(self, max_candidates: int) -> SignLanguageQA: from gloss2pose import SignLanguageQA # type: ignore # local import key = max_candidates if max_candidates >= 0 else 10 if key not in self._qa_instances: self._qa_instances[key] = SignLanguageQA(max_candidates=key) return self._qa_instances[key] def _get_available_glosses(self): if self._available_glosses is None: self._available_glosses = load_available_glosses(self.plugin_root / "pose_dict" / "WLASL_train.json") return self._available_glosses # ------------------------------------------------------------------ # Helpers # ------------------------------------------------------------------ def _format_logs(self, buffer: io.StringIO) -> str: text = buffer.getvalue().strip() return text if text else "(no logs)" def _to_web_url(self, file_path: Path) -> Optional[str]: try: rel = file_path.relative_to(self.plugin_root) return f"{self.web_base_url}/{rel.as_posix()}" except ValueError: return None def _resolve_existing_video(self, user_value: str) -> Optional[VideoInfo]: if not user_value: return None candidates = [] user_path = Path(user_value.strip()) candidates.append(user_path) candidates.append(self.output_dir / user_path.name) candidates.append(self.plugin_root / user_path) for candidate in candidates: if candidate.exists() and candidate.is_file(): url = self._to_web_url(candidate) if url is None: continue return VideoInfo(path=candidate, url=url) return None def _generate_gloss(self, text: str, prompt: Optional[str], max_new_tokens: int) -> str: tokenizer, model, device, torch = self._get_prompt_model() prompt_text = prompt.strip() if prompt else text.strip() if not prompt_text: raise ValueError("Prompt/text input is empty.") input_text = build_prompt_input(prompt_text, text) encoded = tokenizer( input_text, return_tensors="pt", truncation=True, max_length=512, ).to(device) with torch.no_grad(): outputs = model.generate( **encoded, max_new_tokens=max_new_tokens, num_beams=4, length_penalty=1.0, early_stopping=True, ) decoded = tokenizer.batch_decode(outputs, skip_special_tokens=True)[0].strip().upper() return decoded def _generate_constrained_text_gloss(self, text: str, max_tokens: int, use_semantic: bool = False) -> Dict[str, Any]: result = translate_text_to_gloss( text, vocab=self._get_available_glosses(), max_tokens=max_tokens, use_semantic=use_semantic, ) return { "gloss": result.gloss, "tokens": result.tokens, "matched": result.matched, "dropped": result.dropped, "semantic": result.semantic, "mode": "semantic" if use_semantic else "rule", } def _build_output_path(self, gloss_tokens: List[str], draw_style: str) -> Path: timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") slug = "_".join(gloss_tokens[:4]) if gloss_tokens else "gloss" suffix = f"_{draw_style}_style" if draw_style else "" filename = f"{slug}_{timestamp}{suffix}.mp4" return self.output_dir / filename def _list_recent_videos(self, limit: int = 12) -> List[Dict[str, Any]]: if not self.output_dir.exists(): return [] videos = sorted( [p for p in self.output_dir.glob("*.mp4") if p.is_file()], key=lambda p: p.stat().st_mtime, reverse=True, ) result = [] for video in videos[:limit]: url = self._to_web_url(video) if not url: continue result.append( { "name": video.name, "url": url, "path": str(video), "updated": datetime.fromtimestamp(video.stat().st_mtime).isoformat(), "size_mb": round(video.stat().st_size / (1024 * 1024), 2), } ) return result def _list_recent_videos_in_dir(self, base_dir: Path, limit: int = 12, recursive: bool = False) -> List[Dict[str, Any]]: if not base_dir.exists(): return [] if recursive: candidates = [p for p in base_dir.rglob("*.mp4") if p.is_file()] else: candidates = [p for p in base_dir.glob("*.mp4") if p.is_file()] videos = sorted(candidates, key=lambda p: p.stat().st_mtime, reverse=True) result = [] for video in videos[:limit]: url = self._to_web_url(video) if not url: continue result.append( { "name": video.name, "url": url, "path": str(video), "updated": datetime.fromtimestamp(video.stat().st_mtime).isoformat(), "size_mb": round(video.stat().st_size / (1024 * 1024), 2), } ) return result # ------------------------------------------------------------------ # Message handling # ------------------------------------------------------------------ def handle_message(self, message: Dict[str, Any]) -> Optional[Dict[str, Any]]: action = message.get("action") data = message.get("data", {}) or {} if action == "generate_pose": return self.handle_generate_pose(data) if action == "generate_pose_stream": return self.handle_generate_pose_stream(data) if action == "get_pose_stream_status": return self.handle_get_pose_stream_status(data) if action == "list_recent_videos": return {"status": "success", "videos": self._list_recent_videos()} if action == "list_sign_videos": return {"status": "success", "videos": self._list_recent_videos_in_dir(self.sign_output_dir, recursive=True)} if action == "list_refine_videos": return {"status": "success", "videos": self._list_recent_videos_in_dir(self.refine_output_dir, recursive=True)} if action == "generate_refine": return self.handle_generate_refine(data) if action == "get_refine_status": return self.handle_get_refine_status(data) if action == "probe_video": return self.handle_probe_video(data) if action == "prompt_to_gloss": return self.handle_prompt_to_gloss(data) if action == "text_to_gloss": return self.handle_text_to_gloss(data) if action == "prewarm": return self.handle_prewarm(data) return super().handle_message(message) def handle_probe_video(self, data: Dict[str, Any]) -> Dict[str, Any]: candidate = (data.get("path") or "").strip() info = self._resolve_existing_video(candidate) if info: return { "status": "success", "video": { "name": info.path.name, "url": info.url, "path": str(info.path), "size_mb": round(info.path.stat().st_size / (1024 * 1024), 2), }, } return {"status": "error", "message": "Video not found or outside plugin directory."} def handle_prompt_to_gloss(self, data: Dict[str, Any]) -> Dict[str, Any]: prompt_text = (data.get("text") or data.get("prompt") or "").strip() if not prompt_text: return {"status": "error", "message": "Prompt/Text is empty."} max_new_tokens = _safe_int(data.get("maxNewTokens"), 64) try: gloss = self._generate_gloss(prompt_text, prompt_text, max_new_tokens) return {"status": "success", "gloss": gloss} except Exception as exc: # pylint: disable=broad-except return {"status": "error", "message": str(exc)} def handle_text_to_gloss(self, data: Dict[str, Any]) -> Dict[str, Any]: text = (data.get("text") or data.get("prompt") or "").strip() if not text: return {"status": "error", "message": "Text is empty."} max_tokens = _safe_int(data.get("maxNewTokens"), 64) mode = str(data.get("mode") or data.get("translationMode") or "rule").lower() use_semantic = bool(data.get("useSemantic")) or mode in {"semantic", "semantic_text2gloss", "semantic-text2gloss"} try: result = self._generate_constrained_text_gloss(text, max_tokens, use_semantic=use_semantic) if not result["gloss"]: return { "status": "error", "message": "No renderable gloss tokens found in the current pose vocabulary.", **result, } return {"status": "success", **result} except Exception as exc: # pylint: disable=broad-except return {"status": "error", "message": str(exc)} def handle_prewarm(self, data: Dict[str, Any]) -> Dict[str, Any]: candidate_counts = data.get("candidateCounts") if isinstance(candidate_counts, list): try: counts = [max(1, int(value)) for value in candidate_counts if int(value) > 0] except (TypeError, ValueError): counts = [] else: counts = [] if not counts: counts = [5, 10, 20] log_buffer = io.StringIO() with contextlib.redirect_stdout(log_buffer), contextlib.redirect_stderr(log_buffer): try: self._load_prompt_model() print("[Prewarm] Prompt2Gloss model ready.") except Exception as exc: # pylint: disable=broad-except print("[Prewarm] Failed to load Prompt2Gloss model:", exc) return {"status": "error", "message": f"Prompt2Gloss load failed: {exc}", "logs": log_buffer.getvalue()} warmed_counts = [] for count in counts: try: self._get_qa_system(count) warmed_counts.append(count) print(f"[Prewarm] QA system ready for max_candidates={count}.") except Exception as exc: # pylint: disable=broad-except print(f"[Prewarm] Failed to warm QA system (max_candidates={count}):", exc) logs = log_buffer.getvalue() if not warmed_counts: return { "status": "error", "message": "Prewarm failed: unable to initialize QA systems.", "logs": logs or "(no logs)", } return { "status": "success", "message": f"Prewarm done: Prompt2Gloss and {len(warmed_counts)} QA configs loaded.", "counts": warmed_counts, "logs": logs or "(no logs)", } def _encode_stream_frame(self, frame, quality: int = 72) -> Optional[str]: try: frame_bgr = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR) ok, encoded = cv2.imencode(".jpg", frame_bgr, [int(cv2.IMWRITE_JPEG_QUALITY), quality]) if not ok: return None return "data:image/jpeg;base64," + base64.b64encode(encoded.tobytes()).decode("ascii") except Exception: return None def _create_pose_stream_job(self, gloss: str, output_path: Path) -> Dict[str, Any]: job_id = f"pose_stream_{int(time.time() * 1000)}_{uuid.uuid4().hex[:6]}" job = { "id": job_id, "status": "running", "created_at": time.time(), "updated_at": time.time(), "gloss": gloss, "output_path": str(output_path), "video_url": None, "video_path": None, "frames": [], "total_frames": None, "logs": "", "error": None, } with self._pose_stream_jobs_lock: self._pose_stream_jobs[job_id] = job return job def _append_pose_stream_frame(self, job_id: str, frame_idx: int, frame, total_frames: int): data_url = self._encode_stream_frame(frame) if not data_url: return with self._pose_stream_jobs_lock: job = self._pose_stream_jobs.get(job_id) if not job: return job["frames"].append({"index": frame_idx, "image": data_url}) job["total_frames"] = total_frames job["updated_at"] = time.time() def _execute_pose_stream_job(self, job_id: str, qa_system, gloss_tokens: List[str], output_path: Path, settings: Dict[str, Any]): log_buffer = io.StringIO() try: def frame_callback(frame_idx, frame, total_frames): self._append_pose_stream_frame(job_id, frame_idx, frame, total_frames) with contextlib.redirect_stdout(log_buffer), contextlib.redirect_stderr(log_buffer): success = qa_system.generate_video_from_glosses( gloss_tokens, output_path, fps=settings["fps"], width=settings["width"], height=settings["height"], smoothing_frames=settings["smoothing_frames"], smoothing_method=settings["smoothing_method"], npz_interpolation_frames=settings["npz_interp"], scale_x=settings["scale_x"], scale_y=settings["scale_y"], hide_torso_lines=settings["hide_torso"], ref_image_path=settings["ref_image"], draw_style=settings["draw_style"], normalize_pose=settings["normalize_pose"], draw_conf_threshold=settings["draw_threshold"], frame_callback=frame_callback, ) logs = self._format_logs(log_buffer) with self._pose_stream_jobs_lock: job = self._pose_stream_jobs.get(job_id) if not job: return job["logs"] = logs if success and output_path.exists(): job["status"] = "success" job["video_path"] = str(output_path) job["video_url"] = self._to_web_url(output_path) else: job["status"] = "error" job["error"] = "Video generation failed." job["updated_at"] = time.time() except Exception as exc: # pylint: disable=broad-except with self._pose_stream_jobs_lock: job = self._pose_stream_jobs.get(job_id) if job: job["status"] = "error" job["error"] = str(exc) job["logs"] = log_buffer.getvalue() job["updated_at"] = time.time() finally: self._generation_lock.release() def handle_generate_pose_stream(self, data: Dict[str, Any]) -> Dict[str, Any]: if not self._generation_lock.acquire(blocking=False): return {"status": "error", "message": "A generation job is already running. Please wait."} try: prompt_input_raw = (data.get("prompt") or "").strip() text_input = (data.get("text") or prompt_input_raw).strip() prompt_input = prompt_input_raw or text_input gloss_input = (data.get("gloss") or "").strip() max_new_tokens = _safe_int(data.get("maxNewTokens"), 64) if not gloss_input: if not text_input: self._generation_lock.release() return {"status": "error", "message": "Please enter Prompt/Text or a gloss sequence."} translation_mode = (data.get("translationMode") or "text2gloss").strip().lower() use_semantic = bool(data.get("useSemantic")) or translation_mode in {"semantic", "semantic_text2gloss", "semantic-text2gloss"} if translation_mode == "prompt2gloss": gloss_input = self._generate_gloss(text_input, prompt_input, max_new_tokens) else: gloss_input = self._generate_constrained_text_gloss(text_input, max_new_tokens, use_semantic=use_semantic)["gloss"] gloss_tokens = [token for token in gloss_input.upper().split() if token] if not gloss_tokens: self._generation_lock.release() return {"status": "error", "message": "Gloss string is empty after normalization."} settings = { "fps": _safe_int(data.get("fps"), 25), "width": _safe_int(data.get("width"), 512), "height": _safe_int(data.get("height"), 512), "smoothing_method": data.get("smoothing", "none") or "none", "smoothing_frames": _safe_int(data.get("smoothingFrames"), 0), "npz_interp": _safe_int(data.get("npzInterpolation"), 20), "scale_x": _safe_float(data.get("scaleX"), 1.4), "scale_y": _safe_float(data.get("scaleY"), 1.5), "hide_torso": _to_bool(data.get("hideTorsoLines"), False), "normalize_pose": _to_bool(data.get("normalizePose"), True), "draw_style": (data.get("drawStyle") or "openpose").lower(), "draw_threshold": _safe_float(data.get("drawConfidenceThreshold"), 0.6), "ref_image": (data.get("refImagePath") or "").strip() or None, } max_candidates = _safe_int(data.get("maxCandidates"), 10) qa_system = self._get_qa_system(max_candidates if max_candidates >= 0 else 10) output_path = self._build_output_path(gloss_tokens, settings["draw_style"]) job = self._create_pose_stream_job(" ".join(gloss_tokens), output_path) thread = threading.Thread( target=self._execute_pose_stream_job, args=(job["id"], qa_system, gloss_tokens, output_path, settings), name=f"stable-pose-stream-{job['id']}", daemon=True, ) thread.start() return {"status": "running", "job_id": job["id"], "gloss": " ".join(gloss_tokens), "fps": settings["fps"]} except Exception as exc: # pylint: disable=broad-except self._generation_lock.release() return {"status": "error", "message": str(exc)} def handle_get_pose_stream_status(self, data: Dict[str, Any]) -> Dict[str, Any]: job_id = (data.get("jobId") or data.get("job_id") or "").strip() cursor = _safe_int(data.get("cursor"), 0) if not job_id: return {"status": "error", "message": "jobId is required."} with self._pose_stream_jobs_lock: job = self._pose_stream_jobs.get(job_id) if not job: return {"status": "error", "message": "Stream job not found."} frames = job["frames"][cursor:] return { "status": job["status"], "job_id": job_id, "gloss": job["gloss"], "frames": frames, "cursor": cursor + len(frames), "frame_count": len(job["frames"]), "total_frames": job.get("total_frames"), "video_url": job.get("video_url"), "video_path": job.get("video_path"), "logs": job.get("logs") if job["status"] != "running" else "", "message": job.get("error"), } def handle_generate_pose(self, data: Dict[str, Any]) -> Dict[str, Any]: if not self._generation_lock.acquire(blocking=False): return {"status": "error", "message": "A generation job is already running. Please wait."} try: prompt_input_raw = (data.get("prompt") or "").strip() text_input = (data.get("text") or prompt_input_raw).strip() prompt_input = prompt_input_raw or text_input gloss_input = (data.get("gloss") or "").strip() max_new_tokens = _safe_int(data.get("maxNewTokens"), 64) # Allow reusing an existing video without regeneration reuse_target = (data.get("existingVideo") or "").strip() if reuse_target: info = self._resolve_existing_video(reuse_target) if not info: return {"status": "error", "message": "Specified video path/name not found."} return { "status": "success", "gloss": gloss_input.upper(), "video_url": info.url, "video_path": str(info.path), "logs": f"Reused existing video: {info.path.name}", "generated": False, } if not gloss_input: if not text_input: return {"status": "error", "message": "Please enter Prompt/Text or a gloss sequence."} translation_mode = (data.get("translationMode") or "text2gloss").strip().lower() use_semantic = bool(data.get("useSemantic")) or translation_mode in {"semantic", "semantic_text2gloss", "semantic-text2gloss"} if translation_mode == "prompt2gloss": gloss_input = self._generate_gloss(text_input, prompt_input, max_new_tokens) else: gloss_result = self._generate_constrained_text_gloss(text_input, max_new_tokens, use_semantic=use_semantic) gloss_input = gloss_result["gloss"] gloss_tokens = [token for token in gloss_input.upper().split() if token] if not gloss_tokens: return {"status": "error", "message": "Gloss string is empty after normalization."} fps = _safe_int(data.get("fps"), 25) width = _safe_int(data.get("width"), 512) height = _safe_int(data.get("height"), 512) smoothing_method = data.get("smoothing", "none") or "none" smoothing_frames = _safe_int(data.get("smoothingFrames"), 0) npz_interp = _safe_int(data.get("npzInterpolation"), 20) scale_x = _safe_float(data.get("scaleX"), 1.4) scale_y = _safe_float(data.get("scaleY"), 1.5) hide_torso = _to_bool(data.get("hideTorsoLines"), False) normalize_pose = _to_bool(data.get("normalizePose"), True) draw_style = (data.get("drawStyle") or "openpose").lower() draw_threshold = _safe_float(data.get("drawConfidenceThreshold"), 0.6) max_candidates = _safe_int(data.get("maxCandidates"), 10) ref_image = (data.get("refImagePath") or "").strip() or None qa_system = self._get_qa_system(max_candidates if max_candidates >= 0 else 10) output_path = self._build_output_path(gloss_tokens, draw_style) log_buffer = io.StringIO() success = False with contextlib.redirect_stdout(log_buffer), contextlib.redirect_stderr(log_buffer): success = qa_system.generate_video_from_glosses( gloss_tokens, output_path, fps=fps, width=width, height=height, smoothing_frames=smoothing_frames, smoothing_method=smoothing_method, npz_interpolation_frames=npz_interp, scale_x=scale_x, scale_y=scale_y, hide_torso_lines=hide_torso, ref_image_path=ref_image, draw_style=draw_style, normalize_pose=normalize_pose, draw_conf_threshold=draw_threshold, ) logs = self._format_logs(log_buffer) if not success or not output_path.exists(): return { "status": "error", "message": "Video generation failed. See logs for details.", "logs": logs, } url = self._to_web_url(output_path) if not url: return { "status": "error", "message": "Video generated but cannot be served (outside plugin directory).", "logs": logs, } return { "status": "success", "gloss": " ".join(gloss_tokens), "video_url": url, "video_path": str(output_path), "logs": logs, "generated": True, "settings": { "fps": fps, "width": width, "height": height, "smoothing": smoothing_method, "npzInterpolation": npz_interp, "drawStyle": draw_style, "drawConfidenceThreshold": draw_threshold, }, } except Exception as exc: # pylint: disable=broad-except log = io.StringIO() with contextlib.redirect_stdout(log), contextlib.redirect_stderr(log): import traceback traceback.print_exc() logs = log.getvalue() return {"status": "error", "message": str(exc), "logs": logs} finally: self._generation_lock.release() def handle_generate_refine(self, data: Dict[str, Any]) -> Dict[str, Any]: if not self._generation_lock.acquire(blocking=False): return {"status": "error", "message": "A generation job is already running. Please wait."} try: pose_video_raw = (data.get("poseVideoPath") or "").strip() if not pose_video_raw: self._generation_lock.release() return {"status": "error", "message": "Pose video path is required."} pose_path = Path(pose_video_raw) if not pose_path.is_file(): info = self._resolve_existing_video(pose_video_raw) if not info: self._generation_lock.release() return {"status": "error", "message": "Pose video not found."} pose_path = info.path ref_image_raw = (data.get("refImagePath") or "").strip() if ref_image_raw: ref_path = Path(ref_image_raw) if not ref_path.is_absolute(): ref_path = (self.plugin_root / ref_path).resolve() else: ref_path = self.plugin_root / "ref_img_dict" / "man.jpg" if not ref_path.exists(): self._generation_lock.release() return {"status": "error", "message": f"Reference image not found: {ref_path}"} ref_cfg = _safe_float(data.get("refCfg"), 2.5) pose_cfg = _safe_float(data.get("poseCfg"), 1.5) stage1_out_raw = (data.get("stage1Out") or "").strip() stage2_out_raw = (data.get("stage2Out") or "").strip() stage1_out = self._resolve_output_dir(stage1_out_raw, self.sign_output_dir) stage2_out = self._resolve_output_dir(stage2_out_raw, self.refine_output_dir) gpu_id = (data.get("gpu") or "").strip() script_path = self.plugin_root / "pipeline03_pose2video.sh" if not script_path.exists(): self._generation_lock.release() return {"status": "error", "message": f"Pipeline script not found: {script_path}"} cmd = [ "bash", str(script_path), "--pose-video", str(pose_path), "--ref-image", str(ref_path), "--stage1-out", str(stage1_out), "--stage2-out", str(stage2_out), "--ref-cfg", str(ref_cfg), "--pose-cfg", str(pose_cfg), ] if gpu_id: cmd.extend(["--gpu", gpu_id]) job = self._create_refine_job( pose_path=str(pose_path), ref_path=str(ref_path), stage1_out=str(stage1_out), stage2_out=str(stage2_out), ) self._append_refine_log(job["id"], f"🧩 Pose video: {pose_path}") self._append_refine_log(job["id"], f"🖼️ Ref image: {ref_path}") self._append_refine_log(job["id"], f"📦 Stage1 out: {stage1_out}") self._append_refine_log(job["id"], f"📦 Stage2 out: {stage2_out}") if gpu_id: self._append_refine_log(job["id"], f"🎯 GPU: {gpu_id}") self._append_refine_log(job["id"], f"🚀 Command: {' '.join(cmd)}") thread = threading.Thread( target=self._execute_refine_job, args=(job["id"], cmd), name=f"stable-refine-{job['id']}", daemon=True, ) job["thread"] = thread thread.start() return {"status": "running", "job_id": job["id"], "message": "Refine job started."} except Exception as exc: # pylint: disable=broad-except self._generation_lock.release() log = io.StringIO() with contextlib.redirect_stdout(log), contextlib.redirect_stderr(log): import traceback traceback.print_exc() logs = log.getvalue() return {"status": "error", "message": str(exc), "logs": logs} def _resolve_output_dir(self, raw_value: str, fallback: Path) -> Path: if not raw_value: target = fallback else: candidate = Path(raw_value) if not candidate.is_absolute(): candidate = (self.plugin_root / candidate).resolve() target = candidate try: target.relative_to(self.plugin_root) except ValueError as exc: raise ValueError(f"Output dir must be inside plugin root: {target}") from exc target.mkdir(parents=True, exist_ok=True) return target def _pick_latest_video(self, base_dir: Path) -> Optional[Path]: if not base_dir.exists(): return None videos = sorted( [p for p in base_dir.rglob("*.mp4") if p.is_file()], key=lambda p: p.stat().st_mtime, reverse=True, ) return videos[0] if videos else None def _create_refine_job(self, pose_path: str, ref_path: str, stage1_out: str, stage2_out: str) -> Dict[str, Any]: job_id = f"refine_{int(time.time() * 1000)}_{uuid.uuid4().hex[:6]}" job = { "id": job_id, "pose_path": pose_path, "ref_path": ref_path, "stage1_out": stage1_out, "stage2_out": stage2_out, "status": "running", "created_at": time.time(), "updated_at": time.time(), "logs": [], "result": None, "error": None, "thread": None, } with self._refine_jobs_lock: self._refine_jobs[job_id] = job return job def _get_refine_job(self, job_id: str) -> Optional[Dict[str, Any]]: with self._refine_jobs_lock: return self._refine_jobs.get(job_id) def _append_refine_log(self, job_id: str, line: str): if not line: return job = self._get_refine_job(job_id) if not job: return job["logs"].append(line.rstrip()) job["updated_at"] = time.time() if len(job["logs"]) > 2000: job["logs"] = job["logs"][-2000:] def _finalize_refine_job(self, job_id: str, status: str, *, result: Optional[Dict[str, Any]] = None, error: Optional[str] = None): job = self._get_refine_job(job_id) if not job: return job["status"] = status job["result"] = result job["error"] = error job["finished_at"] = time.time() job["updated_at"] = job["finished_at"] def _execute_refine_job(self, job_id: str, cmd: List[str]): try: env = os.environ.copy() env["PYTHONUNBUFFERED"] = "1" process = subprocess.Popen( cmd, cwd=str(self.plugin_root), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1, env=env, ) if process.stdout: for line in iter(process.stdout.readline, ''): if line: self._append_refine_log(job_id, line.rstrip()) returncode = process.wait() if returncode != 0: self._append_refine_log(job_id, f"❌ Refine failed (exit={returncode})") self._finalize_refine_job(job_id, "error", error=f"Exit code {returncode}") return job = self._get_refine_job(job_id) stage1_video = self._pick_latest_video(Path(job["stage1_out"])) if job else None stage2_video = self._pick_latest_video(Path(job["stage2_out"])) if job else None result: Dict[str, Any] = {} if stage1_video: result["stage1_video_path"] = str(stage1_video) result["stage1_video_url"] = self._to_web_url(stage1_video) if stage2_video: result["stage2_video_path"] = str(stage2_video) result["stage2_video_url"] = self._to_web_url(stage2_video) self._append_refine_log(job_id, "✅ Refine completed") self._finalize_refine_job(job_id, "success", result=result) except Exception as exc: # pylint: disable=broad-except self._append_refine_log(job_id, f"❌ Refine error: {exc}") self._finalize_refine_job(job_id, "error", error=str(exc)) finally: if self._generation_lock.locked(): self._generation_lock.release() def handle_get_refine_status(self, data: Dict[str, Any]) -> Dict[str, Any]: job_id = data.get("job_id") if not job_id: return {"status": "error", "message": "Missing job_id"} job = self._get_refine_job(job_id) if not job: return {"status": "error", "message": f"Job not found: {job_id}"} last_index = data.get("last_index", 0) try: last_index = int(last_index) if last_index < 0: last_index = 0 except (TypeError, ValueError): last_index = 0 logs = job["logs"][last_index:] response: Dict[str, Any] = { "status": "success", "job_id": job_id, "job_status": job["status"], "logs": logs, "next_index": last_index + len(logs), "finished": job["status"] in ("success", "error"), "started_at": job.get("created_at"), } if job["status"] == "success" and job.get("result"): response["result"] = job["result"] elif job["status"] == "error": response["error_message"] = job.get("error") or "Refine failed" return response # Entry point required by ControlWorld's loader PluginBackend = StableSignerBackend