FangSen9000 commited on
Commit ·
5255536
1
Parent(s): 4b6769b
Adding support for Stable Signer mainly involves adding support for plugin aliases.
Browse files- easy_dwpose/__init__.py +6 -2
- gloss2pose.py +166 -9
- index.js +620 -0
- viser_backend.py +371 -0
easy_dwpose/__init__.py
CHANGED
|
@@ -1,3 +1,7 @@
|
|
| 1 |
-
from easy_dwpose.dwpose import DWposeDetector
|
| 2 |
-
|
| 3 |
__all__ = ["DWposeDetector"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
__all__ = ["DWposeDetector"]
|
| 2 |
+
|
| 3 |
+
def __getattr__(name):
|
| 4 |
+
if name == "DWposeDetector":
|
| 5 |
+
from .dwpose import DWposeDetector # Local import to avoid heavy deps until needed
|
| 6 |
+
return DWposeDetector
|
| 7 |
+
raise AttributeError(name)
|
gloss2pose.py
CHANGED
|
@@ -16,17 +16,133 @@ import cv2
|
|
| 16 |
from tqdm import tqdm
|
| 17 |
import re
|
| 18 |
from datetime import datetime
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
-
from easy_dwpose import DWposeDetector
|
| 21 |
from easy_dwpose.draw.controlnext import draw_pose as draw_pose_controlnext, process_pose_data
|
| 22 |
from easy_dwpose.draw.openpose import draw_pose as draw_pose_openpose
|
| 23 |
from utils.npz_interpolation import interpolate_pose_npz, ease_in_out_cubic
|
| 24 |
import copy
|
| 25 |
|
| 26 |
-
# Fixed configuration
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
|
| 32 |
class SignLanguageQA:
|
|
@@ -711,9 +827,16 @@ class SignLanguageQA:
|
|
| 711 |
"""Get the top of head position from reference image"""
|
| 712 |
try:
|
| 713 |
# Lazy load detector
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 714 |
if self.detector is None:
|
| 715 |
device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
| 716 |
-
self.detector =
|
| 717 |
|
| 718 |
# Load and detect pose in reference image
|
| 719 |
ref_image = Image.open(ref_image_path).convert("RGB")
|
|
@@ -1036,9 +1159,12 @@ class SignLanguageQA:
|
|
| 1036 |
import subprocess
|
| 1037 |
import threading
|
| 1038 |
|
|
|
|
|
|
|
|
|
|
| 1039 |
# Create FFmpeg command for pipe input
|
| 1040 |
ffmpeg_cmd = [
|
| 1041 |
-
|
| 1042 |
'-y', # Overwrite output file
|
| 1043 |
'-f', 'rawvideo',
|
| 1044 |
'-vcodec', 'rawvideo',
|
|
@@ -1103,8 +1229,9 @@ class SignLanguageQA:
|
|
| 1103 |
# Fallback to OpenCV if FFmpeg pipe fails
|
| 1104 |
if not use_ffmpeg_pipe:
|
| 1105 |
print("⚠️ Falling back to OpenCV writer...")
|
|
|
|
| 1106 |
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
| 1107 |
-
video_writer = cv2.VideoWriter(str(
|
| 1108 |
|
| 1109 |
if not video_writer.isOpened():
|
| 1110 |
print("❌ Unable to create video file")
|
|
@@ -1115,7 +1242,37 @@ class SignLanguageQA:
|
|
| 1115 |
video_writer.write(pose_frame_bgr)
|
| 1116 |
|
| 1117 |
video_writer.release()
|
| 1118 |
-
print(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1119 |
|
| 1120 |
print(f" 📁 File: {output_path}")
|
| 1121 |
print(f" 📊 {len(final_frames)} frames, {fps}fps, {width}x{height}")
|
|
|
|
| 16 |
from tqdm import tqdm
|
| 17 |
import re
|
| 18 |
from datetime import datetime
|
| 19 |
+
import shutil
|
| 20 |
+
import subprocess
|
| 21 |
+
from typing import Optional
|
| 22 |
+
|
| 23 |
+
_DWposeDetector = None
|
| 24 |
+
_DWPOSE_IMPORT_ERROR = None
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _ensure_dwpose_imported():
|
| 28 |
+
"""Lazy import DWposeDetector to avoid hard dependency unless needed."""
|
| 29 |
+
global _DWposeDetector, _DWPOSE_IMPORT_ERROR # noqa: PLW0603
|
| 30 |
+
if _DWposeDetector is not None or _DWPOSE_IMPORT_ERROR is not None:
|
| 31 |
+
return
|
| 32 |
+
try:
|
| 33 |
+
from easy_dwpose import DWposeDetector # type: ignore
|
| 34 |
+
_DWposeDetector = DWposeDetector
|
| 35 |
+
except Exception as exc: # pylint: disable=broad-except
|
| 36 |
+
_DWPOSE_IMPORT_ERROR = exc
|
| 37 |
|
|
|
|
| 38 |
from easy_dwpose.draw.controlnext import draw_pose as draw_pose_controlnext, process_pose_data
|
| 39 |
from easy_dwpose.draw.openpose import draw_pose as draw_pose_openpose
|
| 40 |
from utils.npz_interpolation import interpolate_pose_npz, ease_in_out_cubic
|
| 41 |
import copy
|
| 42 |
|
| 43 |
+
# Fixed configuration (resolve relative to this file so plugins/symlinks work)
|
| 44 |
+
BASE_DIR = Path(__file__).resolve().parent
|
| 45 |
+
POSE_DICT_ROOT = BASE_DIR / "pose_dict"
|
| 46 |
+
JSON_FILE = os.environ.get(
|
| 47 |
+
"STABLE_SIGNER_GLOSS_JSON",
|
| 48 |
+
str(POSE_DICT_ROOT / "WLASL_train.json"),
|
| 49 |
+
) # JSON mapping file
|
| 50 |
+
NPZ_DIR = os.environ.get(
|
| 51 |
+
"STABLE_SIGNER_NPZ_DIR",
|
| 52 |
+
str(POSE_DICT_ROOT / "WLASL_train"),
|
| 53 |
+
) # Directory containing NPZ files
|
| 54 |
+
OUTPUT_DIR = os.environ.get(
|
| 55 |
+
"STABLE_SIGNER_OUTPUT_DIR",
|
| 56 |
+
str(BASE_DIR / "generated_pose_video"),
|
| 57 |
+
) # Output video directory
|
| 58 |
+
|
| 59 |
+
_FFMPEG_BINARY = None
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _known_ffmpeg_search_roots() -> list[Path]:
|
| 63 |
+
roots = []
|
| 64 |
+
env_hint = os.environ.get("STABLE_SIGNER_FFMPEG")
|
| 65 |
+
if env_hint:
|
| 66 |
+
roots.append(Path(env_hint).parent if Path(env_hint).is_file() else Path(env_hint))
|
| 67 |
+
|
| 68 |
+
env_dir_hint = os.environ.get("STABLE_SIGNER_FFMPEG_DIR")
|
| 69 |
+
if env_dir_hint:
|
| 70 |
+
roots.append(Path(env_dir_hint))
|
| 71 |
+
|
| 72 |
+
roots.extend(
|
| 73 |
+
[
|
| 74 |
+
BASE_DIR / "tools",
|
| 75 |
+
Path.home() / "miniforge3",
|
| 76 |
+
Path.home() / "miniconda3",
|
| 77 |
+
Path.home() / "anaconda3",
|
| 78 |
+
Path("/research/cbim/vast/sf895/miniforge3"),
|
| 79 |
+
]
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
# Remove duplicates while preserving order
|
| 83 |
+
seen = set()
|
| 84 |
+
unique_roots = []
|
| 85 |
+
for root in roots:
|
| 86 |
+
if not root:
|
| 87 |
+
continue
|
| 88 |
+
try:
|
| 89 |
+
key = str(root.resolve())
|
| 90 |
+
except Exception:
|
| 91 |
+
key = str(root)
|
| 92 |
+
if key in seen:
|
| 93 |
+
continue
|
| 94 |
+
seen.add(key)
|
| 95 |
+
unique_roots.append(root)
|
| 96 |
+
return unique_roots
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def _probe_ffmpeg_in_known_locations() -> Optional[str]:
|
| 100 |
+
patterns = [
|
| 101 |
+
"lib/python*/site-packages/imageio_ffmpeg/binaries/ffmpeg*",
|
| 102 |
+
"envs/*/lib/python*/site-packages/imageio_ffmpeg/binaries/ffmpeg*",
|
| 103 |
+
"site-packages/imageio_ffmpeg/binaries/ffmpeg*",
|
| 104 |
+
"imageio_ffmpeg/binaries/ffmpeg*",
|
| 105 |
+
"ffmpeg*",
|
| 106 |
+
]
|
| 107 |
+
for root in _known_ffmpeg_search_roots():
|
| 108 |
+
if not root or not root.exists():
|
| 109 |
+
continue
|
| 110 |
+
for pattern in patterns:
|
| 111 |
+
for candidate in root.glob(pattern):
|
| 112 |
+
if candidate.is_file() and os.access(candidate, os.X_OK):
|
| 113 |
+
return str(candidate)
|
| 114 |
+
return None
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def _get_ffmpeg_binary() -> str:
|
| 118 |
+
"""Locate an FFmpeg executable that actually works inside this environment."""
|
| 119 |
+
global _FFMPEG_BINARY # noqa: PLW0603
|
| 120 |
+
if _FFMPEG_BINARY:
|
| 121 |
+
return _FFMPEG_BINARY
|
| 122 |
+
|
| 123 |
+
try:
|
| 124 |
+
from imageio_ffmpeg import get_ffmpeg_exe # type: ignore
|
| 125 |
+
|
| 126 |
+
ffmpeg_path = get_ffmpeg_exe()
|
| 127 |
+
if ffmpeg_path and Path(ffmpeg_path).exists():
|
| 128 |
+
_FFMPEG_BINARY = ffmpeg_path
|
| 129 |
+
return ffmpeg_path
|
| 130 |
+
except Exception:
|
| 131 |
+
pass
|
| 132 |
+
|
| 133 |
+
probed = _probe_ffmpeg_in_known_locations()
|
| 134 |
+
if probed:
|
| 135 |
+
_FFMPEG_BINARY = probed
|
| 136 |
+
return probed
|
| 137 |
+
|
| 138 |
+
fallback = shutil.which("ffmpeg")
|
| 139 |
+
if fallback:
|
| 140 |
+
_FFMPEG_BINARY = fallback
|
| 141 |
+
return fallback
|
| 142 |
+
|
| 143 |
+
# Last resort: just return string "ffmpeg" and let subprocess raise a clearer error.
|
| 144 |
+
_FFMPEG_BINARY = "ffmpeg"
|
| 145 |
+
return _FFMPEG_BINARY
|
| 146 |
|
| 147 |
|
| 148 |
class SignLanguageQA:
|
|
|
|
| 827 |
"""Get the top of head position from reference image"""
|
| 828 |
try:
|
| 829 |
# Lazy load detector
|
| 830 |
+
_ensure_dwpose_imported()
|
| 831 |
+
if _DWposeDetector is None:
|
| 832 |
+
if _DWPOSE_IMPORT_ERROR:
|
| 833 |
+
print(f"⚠️ DWposeDetector unavailable: {_DWPOSE_IMPORT_ERROR}")
|
| 834 |
+
else:
|
| 835 |
+
print("⚠️ DWposeDetector module not available")
|
| 836 |
+
return None
|
| 837 |
if self.detector is None:
|
| 838 |
device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
| 839 |
+
self.detector = _DWposeDetector(device=device)
|
| 840 |
|
| 841 |
# Load and detect pose in reference image
|
| 842 |
ref_image = Image.open(ref_image_path).convert("RGB")
|
|
|
|
| 1159 |
import subprocess
|
| 1160 |
import threading
|
| 1161 |
|
| 1162 |
+
ffmpeg_path = _get_ffmpeg_binary()
|
| 1163 |
+
print(f" ▶ Using FFmpeg binary: {ffmpeg_path}")
|
| 1164 |
+
|
| 1165 |
# Create FFmpeg command for pipe input
|
| 1166 |
ffmpeg_cmd = [
|
| 1167 |
+
ffmpeg_path,
|
| 1168 |
'-y', # Overwrite output file
|
| 1169 |
'-f', 'rawvideo',
|
| 1170 |
'-vcodec', 'rawvideo',
|
|
|
|
| 1229 |
# Fallback to OpenCV if FFmpeg pipe fails
|
| 1230 |
if not use_ffmpeg_pipe:
|
| 1231 |
print("⚠️ Falling back to OpenCV writer...")
|
| 1232 |
+
tmp_output_path = output_path.with_name(f"{output_path.stem}_mp4v_tmp{output_path.suffix}")
|
| 1233 |
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
| 1234 |
+
video_writer = cv2.VideoWriter(str(tmp_output_path), fourcc, fps, (width, height))
|
| 1235 |
|
| 1236 |
if not video_writer.isOpened():
|
| 1237 |
print("❌ Unable to create video file")
|
|
|
|
| 1242 |
video_writer.write(pose_frame_bgr)
|
| 1243 |
|
| 1244 |
video_writer.release()
|
| 1245 |
+
print("✅ Video generated successfully (raw MP4V). Re-encoding to H.264 for browser compatibility...")
|
| 1246 |
+
|
| 1247 |
+
try:
|
| 1248 |
+
ffmpeg_bin = _get_ffmpeg_binary()
|
| 1249 |
+
print(f" ▶ Using FFmpeg binary: {ffmpeg_bin}")
|
| 1250 |
+
reencode_cmd = [
|
| 1251 |
+
ffmpeg_bin,
|
| 1252 |
+
'-y',
|
| 1253 |
+
'-i', str(tmp_output_path),
|
| 1254 |
+
'-c:v', 'libx264',
|
| 1255 |
+
'-pix_fmt', 'yuv420p',
|
| 1256 |
+
'-movflags', '+faststart',
|
| 1257 |
+
str(output_path)
|
| 1258 |
+
]
|
| 1259 |
+
result = subprocess.run(
|
| 1260 |
+
reencode_cmd,
|
| 1261 |
+
stdout=subprocess.PIPE,
|
| 1262 |
+
stderr=subprocess.PIPE,
|
| 1263 |
+
check=True
|
| 1264 |
+
)
|
| 1265 |
+
tmp_output_path.unlink(missing_ok=True)
|
| 1266 |
+
print("✅ Re-encoded video with libx264 successfully!")
|
| 1267 |
+
if result.stderr:
|
| 1268 |
+
stderr_tail = result.stderr.decode('utf-8', errors='ignore')[-300:]
|
| 1269 |
+
if stderr_tail.strip():
|
| 1270 |
+
print(stderr_tail)
|
| 1271 |
+
except Exception as re_err:
|
| 1272 |
+
print(f"⚠️ H.264 re-encode failed: {re_err}")
|
| 1273 |
+
print(" Keeping MP4V file; some browsers may not play it.")
|
| 1274 |
+
if tmp_output_path.exists():
|
| 1275 |
+
shutil.move(str(tmp_output_path), str(output_path))
|
| 1276 |
|
| 1277 |
print(f" 📁 File: {output_path}")
|
| 1278 |
print(f" 📊 {len(final_frames)} frames, {fps}fps, {width}x{height}")
|
index.js
ADDED
|
@@ -0,0 +1,620 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { ControlWavePlugin } from '../plugin-loader.js';
|
| 2 |
+
|
| 3 |
+
const STYLE_ID = 'stable-signer-plugin-style';
|
| 4 |
+
const toInt = (value, fallback) => {
|
| 5 |
+
const parsed = parseInt(value, 10);
|
| 6 |
+
return Number.isNaN(parsed) ? fallback : parsed;
|
| 7 |
+
};
|
| 8 |
+
const toFloat = (value, fallback) => {
|
| 9 |
+
const parsed = parseFloat(value);
|
| 10 |
+
return Number.isNaN(parsed) ? fallback : parsed;
|
| 11 |
+
};
|
| 12 |
+
|
| 13 |
+
function ensureStyles() {
|
| 14 |
+
if (document.getElementById(STYLE_ID)) {
|
| 15 |
+
return;
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
const style = document.createElement('style');
|
| 19 |
+
style.id = STYLE_ID;
|
| 20 |
+
style.textContent = `
|
| 21 |
+
.stable-signer-root {
|
| 22 |
+
display: flex;
|
| 23 |
+
gap: 20px;
|
| 24 |
+
width: 100%;
|
| 25 |
+
height: 100%;
|
| 26 |
+
padding: 20px;
|
| 27 |
+
box-sizing: border-box;
|
| 28 |
+
}
|
| 29 |
+
.stable-signer-left,
|
| 30 |
+
.stable-signer-right {
|
| 31 |
+
background: #fff;
|
| 32 |
+
border-radius: 12px;
|
| 33 |
+
box-shadow: 0 4px 16px rgba(15, 23, 42, 0.08);
|
| 34 |
+
padding: 20px;
|
| 35 |
+
display: flex;
|
| 36 |
+
flex-direction: column;
|
| 37 |
+
}
|
| 38 |
+
.stable-signer-left {
|
| 39 |
+
flex: 1.2;
|
| 40 |
+
}
|
| 41 |
+
.stable-signer-right {
|
| 42 |
+
flex: 1;
|
| 43 |
+
}
|
| 44 |
+
.stable-video-frame {
|
| 45 |
+
position: relative;
|
| 46 |
+
width: 100%;
|
| 47 |
+
padding-top: 56.25%;
|
| 48 |
+
background: #0f172a;
|
| 49 |
+
border-radius: 10px;
|
| 50 |
+
overflow: hidden;
|
| 51 |
+
}
|
| 52 |
+
.stable-video-frame video {
|
| 53 |
+
position: absolute;
|
| 54 |
+
top: 0;
|
| 55 |
+
left: 0;
|
| 56 |
+
width: 100%;
|
| 57 |
+
height: 100%;
|
| 58 |
+
object-fit: contain;
|
| 59 |
+
background: #0f172a;
|
| 60 |
+
}
|
| 61 |
+
.stable-video-placeholder {
|
| 62 |
+
position: absolute;
|
| 63 |
+
inset: 0;
|
| 64 |
+
display: flex;
|
| 65 |
+
align-items: center;
|
| 66 |
+
justify-content: center;
|
| 67 |
+
color: #94a3b8;
|
| 68 |
+
font-size: 15px;
|
| 69 |
+
text-align: center;
|
| 70 |
+
padding: 20px;
|
| 71 |
+
}
|
| 72 |
+
.stable-video-controls {
|
| 73 |
+
margin-top: 15px;
|
| 74 |
+
display: flex;
|
| 75 |
+
gap: 10px;
|
| 76 |
+
align-items: center;
|
| 77 |
+
}
|
| 78 |
+
.stable-video-controls select,
|
| 79 |
+
.stable-video-controls button {
|
| 80 |
+
flex: 1;
|
| 81 |
+
}
|
| 82 |
+
.stable-meta {
|
| 83 |
+
font-family: "JetBrains Mono", "Fira Code", monospace;
|
| 84 |
+
background: #0f172a;
|
| 85 |
+
color: #e2e8f0;
|
| 86 |
+
padding: 12px;
|
| 87 |
+
border-radius: 8px;
|
| 88 |
+
margin-top: 15px;
|
| 89 |
+
min-height: 60px;
|
| 90 |
+
font-size: 13px;
|
| 91 |
+
}
|
| 92 |
+
.stable-control-header {
|
| 93 |
+
display: flex;
|
| 94 |
+
align-items: center;
|
| 95 |
+
justify-content: space-between;
|
| 96 |
+
gap: 12px;
|
| 97 |
+
margin-bottom: 15px;
|
| 98 |
+
}
|
| 99 |
+
.stable-control-header button {
|
| 100 |
+
flex: none;
|
| 101 |
+
}
|
| 102 |
+
.stable-status-chip {
|
| 103 |
+
font-size: 13px;
|
| 104 |
+
padding: 6px 12px;
|
| 105 |
+
border-radius: 999px;
|
| 106 |
+
background: #e2e8f0;
|
| 107 |
+
color: #0f172a;
|
| 108 |
+
}
|
| 109 |
+
.stable-form-row {
|
| 110 |
+
display: flex;
|
| 111 |
+
gap: 12px;
|
| 112 |
+
margin-bottom: 15px;
|
| 113 |
+
}
|
| 114 |
+
.stable-form-row .form-group {
|
| 115 |
+
flex: 1;
|
| 116 |
+
}
|
| 117 |
+
.form-group label {
|
| 118 |
+
font-size: 13px;
|
| 119 |
+
font-weight: 600;
|
| 120 |
+
display: block;
|
| 121 |
+
margin-bottom: 6px;
|
| 122 |
+
color: #0f172a;
|
| 123 |
+
}
|
| 124 |
+
.form-group textarea,
|
| 125 |
+
.form-group input,
|
| 126 |
+
.form-group select {
|
| 127 |
+
width: 100%;
|
| 128 |
+
padding: 10px 12px;
|
| 129 |
+
border: 1px solid #cbd5f5;
|
| 130 |
+
border-radius: 8px;
|
| 131 |
+
font-size: 14px;
|
| 132 |
+
transition: border-color 0.2s, box-shadow 0.2s;
|
| 133 |
+
}
|
| 134 |
+
.form-group textarea {
|
| 135 |
+
min-height: 110px;
|
| 136 |
+
resize: vertical;
|
| 137 |
+
}
|
| 138 |
+
.form-group input:focus,
|
| 139 |
+
.form-group textarea:focus,
|
| 140 |
+
.form-group select:focus {
|
| 141 |
+
outline: none;
|
| 142 |
+
border-color: #6366f1;
|
| 143 |
+
box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
|
| 144 |
+
}
|
| 145 |
+
details.stable-advanced {
|
| 146 |
+
margin-top: 10px;
|
| 147 |
+
border: 1px solid #cbd5f5;
|
| 148 |
+
border-radius: 10px;
|
| 149 |
+
padding: 12px;
|
| 150 |
+
}
|
| 151 |
+
details.stable-advanced summary {
|
| 152 |
+
cursor: pointer;
|
| 153 |
+
font-weight: 600;
|
| 154 |
+
color: #1d4ed8;
|
| 155 |
+
}
|
| 156 |
+
.stable-advanced-grid {
|
| 157 |
+
margin-top: 12px;
|
| 158 |
+
display: grid;
|
| 159 |
+
grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
|
| 160 |
+
gap: 12px;
|
| 161 |
+
}
|
| 162 |
+
.stable-switch {
|
| 163 |
+
display: flex;
|
| 164 |
+
align-items: center;
|
| 165 |
+
gap: 8px;
|
| 166 |
+
font-size: 13px;
|
| 167 |
+
}
|
| 168 |
+
.stable-switch input {
|
| 169 |
+
width: auto;
|
| 170 |
+
}
|
| 171 |
+
.stable-logs {
|
| 172 |
+
margin-top: 18px;
|
| 173 |
+
}
|
| 174 |
+
.stable-logs pre {
|
| 175 |
+
background: #0f172a;
|
| 176 |
+
color: #cbd5f5;
|
| 177 |
+
border-radius: 8px;
|
| 178 |
+
padding: 14px;
|
| 179 |
+
font-size: 12px;
|
| 180 |
+
max-height: 220px;
|
| 181 |
+
overflow: auto;
|
| 182 |
+
}
|
| 183 |
+
.btn.primary {
|
| 184 |
+
background: linear-gradient(120deg, #6366f1, #8b5cf6);
|
| 185 |
+
border: none;
|
| 186 |
+
color: #fff;
|
| 187 |
+
border-radius: 10px;
|
| 188 |
+
padding: 10px 18px;
|
| 189 |
+
font-weight: 600;
|
| 190 |
+
cursor: pointer;
|
| 191 |
+
transition: transform 0.15s ease, box-shadow 0.2s ease;
|
| 192 |
+
}
|
| 193 |
+
.btn.primary:disabled {
|
| 194 |
+
opacity: 0.6;
|
| 195 |
+
cursor: not-allowed;
|
| 196 |
+
box-shadow: none;
|
| 197 |
+
}
|
| 198 |
+
.btn.primary:not(:disabled):hover {
|
| 199 |
+
transform: translateY(-2px);
|
| 200 |
+
box-shadow: 0 10px 20px rgba(99, 102, 241, 0.2);
|
| 201 |
+
}
|
| 202 |
+
.btn.secondary {
|
| 203 |
+
background: #e2e8f0;
|
| 204 |
+
border: none;
|
| 205 |
+
color: #0f172a;
|
| 206 |
+
border-radius: 8px;
|
| 207 |
+
padding: 8px 14px;
|
| 208 |
+
font-weight: 600;
|
| 209 |
+
cursor: pointer;
|
| 210 |
+
}
|
| 211 |
+
.stable-inline {
|
| 212 |
+
display: flex;
|
| 213 |
+
gap: 10px;
|
| 214 |
+
align-items: center;
|
| 215 |
+
}
|
| 216 |
+
@media (max-width: 1200px) {
|
| 217 |
+
.stable-signer-root {
|
| 218 |
+
flex-direction: column;
|
| 219 |
+
}
|
| 220 |
+
}
|
| 221 |
+
`;
|
| 222 |
+
document.head.appendChild(style);
|
| 223 |
+
}
|
| 224 |
+
|
| 225 |
+
export default class StableSignerPlugin extends ControlWavePlugin {
|
| 226 |
+
constructor() {
|
| 227 |
+
super({
|
| 228 |
+
id: 'stable-signer',
|
| 229 |
+
name: 'StableSigner',
|
| 230 |
+
version: '1.0.0',
|
| 231 |
+
author: 'StableSigner',
|
| 232 |
+
description: 'Prompt/Text → Gloss → Pose Video',
|
| 233 |
+
order: 25,
|
| 234 |
+
needsViser: false
|
| 235 |
+
});
|
| 236 |
+
this.state = {
|
| 237 |
+
status: 'Idle',
|
| 238 |
+
lastVideo: null
|
| 239 |
+
};
|
| 240 |
+
this.currentVideoObjectUrl = null;
|
| 241 |
+
}
|
| 242 |
+
|
| 243 |
+
async render(container) {
|
| 244 |
+
ensureStyles();
|
| 245 |
+
this.container = container;
|
| 246 |
+
container.classList.add('tab-content', 'active');
|
| 247 |
+
container.style.display = 'flex';
|
| 248 |
+
container.innerHTML = this.renderTemplate();
|
| 249 |
+
this.cacheElements(container);
|
| 250 |
+
this.attachEvents();
|
| 251 |
+
this.updateStatus('Idle');
|
| 252 |
+
await this.refreshRecentVideos();
|
| 253 |
+
}
|
| 254 |
+
|
| 255 |
+
renderTemplate() {
|
| 256 |
+
return `
|
| 257 |
+
<div class="stable-signer-root">
|
| 258 |
+
<div class="stable-signer-left">
|
| 259 |
+
<div class="stable-video-frame">
|
| 260 |
+
<video id="stable-video" controls playsinline loop muted></video>
|
| 261 |
+
<div id="stable-video-placeholder" class="stable-video-placeholder">
|
| 262 |
+
生成的 pose 视频将显示在这里
|
| 263 |
+
</div>
|
| 264 |
+
</div>
|
| 265 |
+
<div class="stable-video-controls">
|
| 266 |
+
<select id="stable-video-select">
|
| 267 |
+
<option value="">选择最近生成的视频</option>
|
| 268 |
+
</select>
|
| 269 |
+
<button id="stable-video-refresh" class="btn secondary">刷新</button>
|
| 270 |
+
</div>
|
| 271 |
+
<div class="stable-meta" id="stable-video-meta">
|
| 272 |
+
等待生成视频...
|
| 273 |
+
</div>
|
| 274 |
+
</div>
|
| 275 |
+
<div class="stable-signer-right">
|
| 276 |
+
<div class="stable-control-header">
|
| 277 |
+
<button id="stable-generate" class="btn primary">生成 Pose Video</button>
|
| 278 |
+
<span class="stable-status-chip" id="stable-status">Idle</span>
|
| 279 |
+
</div>
|
| 280 |
+
<div class="stable-form-row">
|
| 281 |
+
<div class="form-group">
|
| 282 |
+
<label>Prompt (可选)</label>
|
| 283 |
+
<textarea id="stable-prompt" placeholder="描述你想要的动作或指令..."></textarea>
|
| 284 |
+
</div>
|
| 285 |
+
<div class="form-group">
|
| 286 |
+
<label>Text / Context</label>
|
| 287 |
+
<textarea id="stable-text" placeholder="输入完整的句子或上下文"></textarea>
|
| 288 |
+
</div>
|
| 289 |
+
</div>
|
| 290 |
+
<div class="form-group">
|
| 291 |
+
<label>Gloss 序列(自动生成,可手动编辑)</label>
|
| 292 |
+
<textarea id="stable-gloss" placeholder="示例:YOU WANT DRINK WATER"></textarea>
|
| 293 |
+
<div class="form-group" style="margin-top:8px;font-size:13px;color:#475569;">
|
| 294 |
+
<div>示例:</div>
|
| 295 |
+
<div>1. HELLO WORLD</div>
|
| 296 |
+
<div>2. YOU WANT DRINK WATER</div>
|
| 297 |
+
<div>3. TODAY WEATHER NICE</div>
|
| 298 |
+
<div>4. I GO SCHOOL LATER</div>
|
| 299 |
+
</div>
|
| 300 |
+
</div>
|
| 301 |
+
<div class="form-group">
|
| 302 |
+
<label>复用已有视频(路径或文件名,可选)</label>
|
| 303 |
+
<input id="stable-existing-video" type="text" placeholder="如:generated_pose_video/EXAMPLE.mp4">
|
| 304 |
+
</div>
|
| 305 |
+
<details class="stable-advanced">
|
| 306 |
+
<summary>高级设置</summary>
|
| 307 |
+
<div class="stable-advanced-grid">
|
| 308 |
+
<div class="form-group">
|
| 309 |
+
<label>FPS</label>
|
| 310 |
+
<input id="stable-fps" type="number" min="5" max="60" value="30">
|
| 311 |
+
</div>
|
| 312 |
+
<div class="form-group">
|
| 313 |
+
<label>宽度</label>
|
| 314 |
+
<input id="stable-width" type="number" min="256" max="1024" value="480">
|
| 315 |
+
</div>
|
| 316 |
+
<div class="form-group">
|
| 317 |
+
<label>高度</label>
|
| 318 |
+
<input id="stable-height" type="number" min="256" max="1024" value="480">
|
| 319 |
+
</div>
|
| 320 |
+
<div class="form-group">
|
| 321 |
+
<label>Smoothing</label>
|
| 322 |
+
<select id="stable-smoothing">
|
| 323 |
+
<option value="none">None</option>
|
| 324 |
+
<option value="fade">Fade</option>
|
| 325 |
+
<option value="blend">Blend</option>
|
| 326 |
+
<option value="pause">Pause</option>
|
| 327 |
+
</select>
|
| 328 |
+
</div>
|
| 329 |
+
<div class="form-group">
|
| 330 |
+
<label>Smoothing Frames</label>
|
| 331 |
+
<input id="stable-smoothing-frames" type="number" min="0" max="60" value="5">
|
| 332 |
+
</div>
|
| 333 |
+
<div class="form-group">
|
| 334 |
+
<label>NPZ Interp Frames</label>
|
| 335 |
+
<input id="stable-npz" type="number" min="0" max="60" value="0">
|
| 336 |
+
</div>
|
| 337 |
+
<div class="form-group">
|
| 338 |
+
<label>Scale X</label>
|
| 339 |
+
<input id="stable-scale-x" type="number" step="0.1" value="1.5">
|
| 340 |
+
</div>
|
| 341 |
+
<div class="form-group">
|
| 342 |
+
<label>Scale Y</label>
|
| 343 |
+
<input id="stable-scale-y" type="number" step="0.1" value="1.5">
|
| 344 |
+
</div>
|
| 345 |
+
<div class="form-group">
|
| 346 |
+
<label>Draw Style</label>
|
| 347 |
+
<select id="stable-draw-style">
|
| 348 |
+
<option value="controlnext">ControlNeXt</option>
|
| 349 |
+
<option value="openpose">OpenPose</option>
|
| 350 |
+
</select>
|
| 351 |
+
</div>
|
| 352 |
+
<div class="form-group">
|
| 353 |
+
<label>Max Candidates</label>
|
| 354 |
+
<input id="stable-max-candidates" type="number" min="0" value="10">
|
| 355 |
+
</div>
|
| 356 |
+
<div class="form-group">
|
| 357 |
+
<label>Max New Tokens</label>
|
| 358 |
+
<input id="stable-max-new" type="number" min="8" max="256" value="64">
|
| 359 |
+
</div>
|
| 360 |
+
<div class="form-group">
|
| 361 |
+
<label>参考图像路径 (可选)</label>
|
| 362 |
+
<input id="stable-ref-image" type="text" placeholder="ref_img_dict/example.png">
|
| 363 |
+
</div>
|
| 364 |
+
<label class="stable-switch">
|
| 365 |
+
<input type="checkbox" id="stable-normalize" checked>
|
| 366 |
+
归一化姿态
|
| 367 |
+
</label>
|
| 368 |
+
<label class="stable-switch">
|
| 369 |
+
<input type="checkbox" id="stable-hide-torso">
|
| 370 |
+
隐藏躯干线
|
| 371 |
+
</label>
|
| 372 |
+
</div>
|
| 373 |
+
</details>
|
| 374 |
+
<div class="stable-logs">
|
| 375 |
+
<label>日志输出</label>
|
| 376 |
+
<pre id="stable-logs">(等待任务...)</pre>
|
| 377 |
+
</div>
|
| 378 |
+
</div>
|
| 379 |
+
</div>
|
| 380 |
+
`;
|
| 381 |
+
}
|
| 382 |
+
|
| 383 |
+
cacheElements(container) {
|
| 384 |
+
this.videoEl = container.querySelector('#stable-video');
|
| 385 |
+
this.videoPlaceholder = container.querySelector('#stable-video-placeholder');
|
| 386 |
+
this.videoSelect = container.querySelector('#stable-video-select');
|
| 387 |
+
this.videoRefreshBtn = container.querySelector('#stable-video-refresh');
|
| 388 |
+
this.videoMeta = container.querySelector('#stable-video-meta');
|
| 389 |
+
this.generateBtn = container.querySelector('#stable-generate');
|
| 390 |
+
this.statusChip = container.querySelector('#stable-status');
|
| 391 |
+
this.promptInput = container.querySelector('#stable-prompt');
|
| 392 |
+
this.textInput = container.querySelector('#stable-text');
|
| 393 |
+
this.glossInput = container.querySelector('#stable-gloss');
|
| 394 |
+
this.existingInput = container.querySelector('#stable-existing-video');
|
| 395 |
+
this.fpsInput = container.querySelector('#stable-fps');
|
| 396 |
+
this.widthInput = container.querySelector('#stable-width');
|
| 397 |
+
this.heightInput = container.querySelector('#stable-height');
|
| 398 |
+
this.smoothingSelect = container.querySelector('#stable-smoothing');
|
| 399 |
+
this.smoothingFramesInput = container.querySelector('#stable-smoothing-frames');
|
| 400 |
+
this.npzInput = container.querySelector('#stable-npz');
|
| 401 |
+
this.scaleXInput = container.querySelector('#stable-scale-x');
|
| 402 |
+
this.scaleYInput = container.querySelector('#stable-scale-y');
|
| 403 |
+
this.drawStyleSelect = container.querySelector('#stable-draw-style');
|
| 404 |
+
this.maxCandidatesInput = container.querySelector('#stable-max-candidates');
|
| 405 |
+
this.maxNewTokensInput = container.querySelector('#stable-max-new');
|
| 406 |
+
this.refImageInput = container.querySelector('#stable-ref-image');
|
| 407 |
+
this.normalizeCheckbox = container.querySelector('#stable-normalize');
|
| 408 |
+
this.hideTorsoCheckbox = container.querySelector('#stable-hide-torso');
|
| 409 |
+
this.logsPre = container.querySelector('#stable-logs');
|
| 410 |
+
if (this.videoEl) {
|
| 411 |
+
this.videoEl.style.display = 'none';
|
| 412 |
+
}
|
| 413 |
+
}
|
| 414 |
+
|
| 415 |
+
attachEvents() {
|
| 416 |
+
this.generateBtn.addEventListener('click', () => this.handleGenerate());
|
| 417 |
+
this.videoRefreshBtn.addEventListener('click', () => this.refreshRecentVideos());
|
| 418 |
+
this.videoSelect.addEventListener('change', () => this.handleRecentSelection());
|
| 419 |
+
|
| 420 |
+
window.addEventListener('websocket-connected', () => {
|
| 421 |
+
this.updateStatus('WebSocket connected');
|
| 422 |
+
});
|
| 423 |
+
|
| 424 |
+
this.glossInput.addEventListener('input', () => {
|
| 425 |
+
const { selectionStart, selectionEnd, value } = this.glossInput;
|
| 426 |
+
const upper = value.toUpperCase();
|
| 427 |
+
if (upper !== value) {
|
| 428 |
+
this.glossInput.value = upper;
|
| 429 |
+
this.glossInput.setSelectionRange(selectionStart, selectionEnd);
|
| 430 |
+
}
|
| 431 |
+
});
|
| 432 |
+
}
|
| 433 |
+
|
| 434 |
+
collectPayload() {
|
| 435 |
+
const glossValue = (this.glossInput.value || '').toUpperCase().replace(/\s+/g, ' ').trim();
|
| 436 |
+
return {
|
| 437 |
+
prompt: this.promptInput.value,
|
| 438 |
+
text: this.textInput.value,
|
| 439 |
+
gloss: glossValue,
|
| 440 |
+
existingVideo: this.existingInput.value,
|
| 441 |
+
fps: toInt(this.fpsInput.value, 30),
|
| 442 |
+
width: toInt(this.widthInput.value, 480),
|
| 443 |
+
height: toInt(this.heightInput.value, 480),
|
| 444 |
+
smoothing: this.smoothingSelect.value,
|
| 445 |
+
smoothingFrames: toInt(this.smoothingFramesInput.value, 5),
|
| 446 |
+
npzInterpolation: toInt(this.npzInput.value, 0),
|
| 447 |
+
scaleX: toFloat(this.scaleXInput.value, 1.5),
|
| 448 |
+
scaleY: toFloat(this.scaleYInput.value, 1.5),
|
| 449 |
+
drawStyle: this.drawStyleSelect.value,
|
| 450 |
+
maxCandidates: toInt(this.maxCandidatesInput.value, 10),
|
| 451 |
+
maxNewTokens: toInt(this.maxNewTokensInput.value, 64),
|
| 452 |
+
refImagePath: this.refImageInput.value,
|
| 453 |
+
normalizePose: this.normalizeCheckbox.checked,
|
| 454 |
+
hideTorsoLines: this.hideTorsoCheckbox.checked
|
| 455 |
+
};
|
| 456 |
+
}
|
| 457 |
+
|
| 458 |
+
async handleGenerate() {
|
| 459 |
+
if (!window.controlWaveWebSocket || !window.controlWaveWebSocket.sendRequest) {
|
| 460 |
+
this.updateStatus('WebSocket 未就绪');
|
| 461 |
+
return;
|
| 462 |
+
}
|
| 463 |
+
const payload = this.collectPayload();
|
| 464 |
+
this.setLoading(true);
|
| 465 |
+
this.updateStatus('Running...');
|
| 466 |
+
try {
|
| 467 |
+
const response = await window.controlWaveWebSocket.sendRequest(this.id, {
|
| 468 |
+
action: 'generate_pose',
|
| 469 |
+
data: payload
|
| 470 |
+
});
|
| 471 |
+
console.log('[StableSigner] generation payload', response);
|
| 472 |
+
const normalizedStatus = typeof response.status === 'string' ? response.status.toLowerCase() : '';
|
| 473 |
+
const inferredSuccess = normalizedStatus === 'success' || (!!response.video_url && response.generated !== undefined);
|
| 474 |
+
if (inferredSuccess) {
|
| 475 |
+
if (response.gloss) {
|
| 476 |
+
this.glossInput.value = response.gloss;
|
| 477 |
+
}
|
| 478 |
+
if (response.video_url) {
|
| 479 |
+
await this.updateVideo(response.video_url, response.video_path);
|
| 480 |
+
}
|
| 481 |
+
if (response.logs) {
|
| 482 |
+
this.logsPre.textContent = response.logs;
|
| 483 |
+
}
|
| 484 |
+
this.updateStatus(response.generated ? 'Generation completed' : 'Reused existing video');
|
| 485 |
+
try {
|
| 486 |
+
await this.refreshRecentVideos();
|
| 487 |
+
} catch (err) {
|
| 488 |
+
console.warn('[StableSigner] refresh failed', err);
|
| 489 |
+
}
|
| 490 |
+
} else {
|
| 491 |
+
console.error('[StableSigner] backend returned error', response);
|
| 492 |
+
this.updateStatus('Error');
|
| 493 |
+
this.logsPre.textContent = response.logs
|
| 494 |
+
|| response.message
|
| 495 |
+
|| response.error
|
| 496 |
+
|| normalizedStatus
|
| 497 |
+
|| 'Unknown error';
|
| 498 |
+
}
|
| 499 |
+
} catch (error) {
|
| 500 |
+
this.updateStatus('Error');
|
| 501 |
+
console.error('[StableSigner] request failure', error);
|
| 502 |
+
this.logsPre.textContent = (error && error.message) ? error.message : 'Request failed';
|
| 503 |
+
} finally {
|
| 504 |
+
this.setLoading(false);
|
| 505 |
+
}
|
| 506 |
+
}
|
| 507 |
+
|
| 508 |
+
async updateVideo(url, path) {
|
| 509 |
+
if (!url || !this.videoEl) return;
|
| 510 |
+
const absoluteUrl = url.startsWith('http') ? url : `${window.location.origin}${url}`;
|
| 511 |
+
const hasQuery = absoluteUrl.includes('?');
|
| 512 |
+
const fetchUrl = `${absoluteUrl}${hasQuery ? '&' : '?'}t=${Date.now()}`;
|
| 513 |
+
|
| 514 |
+
const resetVideoEl = () => {
|
| 515 |
+
this.videoEl.onloadeddata = null;
|
| 516 |
+
this.videoEl.onerror = null;
|
| 517 |
+
this.videoEl.pause();
|
| 518 |
+
this.videoEl.removeAttribute('src');
|
| 519 |
+
this.videoEl.load();
|
| 520 |
+
};
|
| 521 |
+
|
| 522 |
+
this.videoPlaceholder.style.display = 'flex';
|
| 523 |
+
this.videoPlaceholder.textContent = '正在加载视频…';
|
| 524 |
+
this.videoEl.style.display = 'none';
|
| 525 |
+
resetVideoEl();
|
| 526 |
+
|
| 527 |
+
if (this.currentVideoObjectUrl) {
|
| 528 |
+
URL.revokeObjectURL(this.currentVideoObjectUrl);
|
| 529 |
+
this.currentVideoObjectUrl = null;
|
| 530 |
+
}
|
| 531 |
+
|
| 532 |
+
try {
|
| 533 |
+
const response = await fetch(fetchUrl, { cache: 'no-store' });
|
| 534 |
+
if (!response.ok) {
|
| 535 |
+
throw new Error(`HTTP ${response.status}`);
|
| 536 |
+
}
|
| 537 |
+
|
| 538 |
+
const blob = await response.blob();
|
| 539 |
+
const objectUrl = URL.createObjectURL(blob);
|
| 540 |
+
this.currentVideoObjectUrl = objectUrl;
|
| 541 |
+
|
| 542 |
+
this.videoEl.onloadeddata = () => {
|
| 543 |
+
this.videoEl.onloadeddata = null;
|
| 544 |
+
this.videoEl.onerror = null;
|
| 545 |
+
this.videoPlaceholder.style.display = 'none';
|
| 546 |
+
this.videoEl.style.display = 'block';
|
| 547 |
+
const playPromise = this.videoEl.play();
|
| 548 |
+
if (playPromise && typeof playPromise.catch === 'function') {
|
| 549 |
+
playPromise.catch(() => {});
|
| 550 |
+
}
|
| 551 |
+
this.videoMeta.textContent = `视频: ${path || absoluteUrl}`;
|
| 552 |
+
};
|
| 553 |
+
|
| 554 |
+
this.videoEl.onerror = () => {
|
| 555 |
+
this.videoEl.onloadeddata = null;
|
| 556 |
+
this.videoEl.onerror = null;
|
| 557 |
+
this.videoPlaceholder.style.display = 'flex';
|
| 558 |
+
this.videoPlaceholder.textContent = '视频加载失败';
|
| 559 |
+
const mediaError = this.videoEl.error;
|
| 560 |
+
console.error('[StableSigner] video load error', mediaError ? {
|
| 561 |
+
code: mediaError.code,
|
| 562 |
+
message: mediaError.message
|
| 563 |
+
} : 'unknown');
|
| 564 |
+
};
|
| 565 |
+
|
| 566 |
+
this.videoEl.src = objectUrl;
|
| 567 |
+
this.videoEl.load();
|
| 568 |
+
} catch (error) {
|
| 569 |
+
resetVideoEl();
|
| 570 |
+
this.videoPlaceholder.style.display = 'flex';
|
| 571 |
+
this.videoPlaceholder.textContent = '视频加载失败';
|
| 572 |
+
console.error('[StableSigner] video fetch failed', error);
|
| 573 |
+
}
|
| 574 |
+
}
|
| 575 |
+
|
| 576 |
+
async refreshRecentVideos() {
|
| 577 |
+
if (!window.controlWaveWebSocket || !window.controlWaveWebSocket.sendRequest) {
|
| 578 |
+
this.updateStatus('等待 WebSocket...');
|
| 579 |
+
return;
|
| 580 |
+
}
|
| 581 |
+
try {
|
| 582 |
+
const response = await window.controlWaveWebSocket.sendRequest(this.id, {
|
| 583 |
+
action: 'list_recent_videos'
|
| 584 |
+
});
|
| 585 |
+
this.populateRecentVideos(response.videos || []);
|
| 586 |
+
} catch (error) {
|
| 587 |
+
this.videoMeta.textContent = `无法刷新视频列表: ${error.message}`;
|
| 588 |
+
}
|
| 589 |
+
}
|
| 590 |
+
|
| 591 |
+
populateRecentVideos(videos) {
|
| 592 |
+
this.videoSelect.innerHTML = '<option value="">选择最近生成的视频</option>';
|
| 593 |
+
videos.forEach(video => {
|
| 594 |
+
const option = document.createElement('option');
|
| 595 |
+
option.value = video.url;
|
| 596 |
+
option.dataset.path = video.path;
|
| 597 |
+
option.dataset.size = video.size_mb;
|
| 598 |
+
option.textContent = `${video.name} (${video.size_mb} MB)`;
|
| 599 |
+
this.videoSelect.appendChild(option);
|
| 600 |
+
});
|
| 601 |
+
}
|
| 602 |
+
|
| 603 |
+
async handleRecentSelection() {
|
| 604 |
+
const option = this.videoSelect.selectedOptions[0];
|
| 605 |
+
if (!option || !option.value) {
|
| 606 |
+
return;
|
| 607 |
+
}
|
| 608 |
+
this.videoMeta.textContent = `${option.dataset.path} • ${option.dataset.size} MB`;
|
| 609 |
+
await this.updateVideo(option.value, option.dataset.path);
|
| 610 |
+
}
|
| 611 |
+
|
| 612 |
+
setLoading(isLoading) {
|
| 613 |
+
this.generateBtn.disabled = isLoading;
|
| 614 |
+
this.generateBtn.textContent = isLoading ? '生成中...' : '生成 Pose Video';
|
| 615 |
+
}
|
| 616 |
+
|
| 617 |
+
updateStatus(text) {
|
| 618 |
+
this.statusChip.textContent = text;
|
| 619 |
+
}
|
| 620 |
+
}
|
viser_backend.py
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
StableSigner plugin backend
|
| 4 |
+
Handles prompt/text -> gloss -> pose video generation for the ControlWorld panel.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import contextlib
|
| 10 |
+
import io
|
| 11 |
+
import threading
|
| 12 |
+
from dataclasses import dataclass
|
| 13 |
+
from datetime import datetime
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
from typing import Any, Dict, List, Optional
|
| 16 |
+
|
| 17 |
+
# ControlWorld provides plugin_base in the parent directory of every plugin
|
| 18 |
+
import sys
|
| 19 |
+
|
| 20 |
+
PLUGIN_DIR = Path(__file__).resolve().parent
|
| 21 |
+
|
| 22 |
+
def _inject_plugin_base_path():
|
| 23 |
+
candidates = [
|
| 24 |
+
PLUGIN_DIR.parent, # actual repo root
|
| 25 |
+
PLUGIN_DIR.parent / "ControlWorld" / "plugins",
|
| 26 |
+
Path(__file__).resolve().parent.parent, # fallback two-level parent
|
| 27 |
+
]
|
| 28 |
+
for candidate in candidates:
|
| 29 |
+
plugin_base_file = candidate / "plugin_base.py"
|
| 30 |
+
if plugin_base_file.exists():
|
| 31 |
+
candidate_str = str(candidate)
|
| 32 |
+
if candidate_str not in sys.path:
|
| 33 |
+
sys.path.append(candidate_str)
|
| 34 |
+
return
|
| 35 |
+
|
| 36 |
+
_inject_plugin_base_path()
|
| 37 |
+
|
| 38 |
+
if str(PLUGIN_DIR) not in sys.path:
|
| 39 |
+
sys.path.append(str(PLUGIN_DIR))
|
| 40 |
+
|
| 41 |
+
from plugin_base import PluginBackendBase # type: ignore # pylint: disable=wrong-import-position
|
| 42 |
+
|
| 43 |
+
# Import local helpers lazily when needed
|
| 44 |
+
from prompt2gloss import build_input as build_prompt_input # type: ignore
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _to_bool(value: Any, default: bool = False) -> bool:
|
| 48 |
+
if isinstance(value, bool):
|
| 49 |
+
return value
|
| 50 |
+
if value is None:
|
| 51 |
+
return default
|
| 52 |
+
if isinstance(value, str):
|
| 53 |
+
return value.strip().lower() in {"1", "true", "yes", "on"}
|
| 54 |
+
return bool(value)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _safe_int(value: Any, default: int) -> int:
|
| 58 |
+
try:
|
| 59 |
+
return int(value)
|
| 60 |
+
except (TypeError, ValueError):
|
| 61 |
+
return default
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _safe_float(value: Any, default: float) -> float:
|
| 65 |
+
try:
|
| 66 |
+
return float(value)
|
| 67 |
+
except (TypeError, ValueError):
|
| 68 |
+
return default
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
@dataclass
|
| 72 |
+
class VideoInfo:
|
| 73 |
+
path: Path
|
| 74 |
+
url: str
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class StableSignerBackend(PluginBackendBase):
|
| 78 |
+
"""Backend logic for StableSigner tab (no Viser visualization required)."""
|
| 79 |
+
|
| 80 |
+
def __init__(self, server):
|
| 81 |
+
super().__init__(server)
|
| 82 |
+
self.name = "stable-signer"
|
| 83 |
+
self.display_name = "StableSigner"
|
| 84 |
+
self.plugin_root = PLUGIN_DIR
|
| 85 |
+
self.web_base_url = f"/plugins/{self.plugin_root.name}"
|
| 86 |
+
self.output_dir = self.plugin_root / "generated_pose_video"
|
| 87 |
+
self.output_dir.mkdir(parents=True, exist_ok=True)
|
| 88 |
+
|
| 89 |
+
self._prompt_tokenizer = None
|
| 90 |
+
self._prompt_model = None
|
| 91 |
+
self._prompt_device = None
|
| 92 |
+
self._prompt_lock = threading.Lock()
|
| 93 |
+
self._torch = None
|
| 94 |
+
self._qa_instances: Dict[int, SignLanguageQA] = {}
|
| 95 |
+
self._generation_lock = threading.Lock()
|
| 96 |
+
|
| 97 |
+
# ------------------------------------------------------------------
|
| 98 |
+
# Lazy loaders
|
| 99 |
+
# ------------------------------------------------------------------
|
| 100 |
+
def _load_prompt_model(self):
|
| 101 |
+
if self._prompt_model is not None:
|
| 102 |
+
return
|
| 103 |
+
|
| 104 |
+
model_dir = self.plugin_root / "prompt2gloss" / "t5_finetuned"
|
| 105 |
+
if not model_dir.exists():
|
| 106 |
+
raise FileNotFoundError(
|
| 107 |
+
f"Prompt2Gloss checkpoint not found at {model_dir}. "
|
| 108 |
+
"Please train or copy the fine-tuned weights."
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
with self._prompt_lock:
|
| 112 |
+
if self._prompt_model is not None:
|
| 113 |
+
return
|
| 114 |
+
|
| 115 |
+
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM # lazy import
|
| 116 |
+
import torch
|
| 117 |
+
|
| 118 |
+
self._prompt_tokenizer = AutoTokenizer.from_pretrained(model_dir)
|
| 119 |
+
self._prompt_model = AutoModelForSeq2SeqLM.from_pretrained(model_dir)
|
| 120 |
+
self._torch = torch
|
| 121 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 122 |
+
self._prompt_device = device
|
| 123 |
+
self._prompt_model.to(device)
|
| 124 |
+
self._prompt_model.eval()
|
| 125 |
+
|
| 126 |
+
def _get_prompt_model(self):
|
| 127 |
+
self._load_prompt_model()
|
| 128 |
+
return self._prompt_tokenizer, self._prompt_model, self._prompt_device, self._torch
|
| 129 |
+
|
| 130 |
+
def _get_qa_system(self, max_candidates: int) -> SignLanguageQA:
|
| 131 |
+
from gloss2pose import SignLanguageQA # type: ignore # local import
|
| 132 |
+
|
| 133 |
+
key = max_candidates if max_candidates >= 0 else 10
|
| 134 |
+
if key not in self._qa_instances:
|
| 135 |
+
self._qa_instances[key] = SignLanguageQA(max_candidates=key)
|
| 136 |
+
return self._qa_instances[key]
|
| 137 |
+
|
| 138 |
+
# ------------------------------------------------------------------
|
| 139 |
+
# Helpers
|
| 140 |
+
# ------------------------------------------------------------------
|
| 141 |
+
def _format_logs(self, buffer: io.StringIO) -> str:
|
| 142 |
+
text = buffer.getvalue().strip()
|
| 143 |
+
return text if text else "(no logs)"
|
| 144 |
+
|
| 145 |
+
def _to_web_url(self, file_path: Path) -> Optional[str]:
|
| 146 |
+
try:
|
| 147 |
+
rel = file_path.relative_to(self.plugin_root)
|
| 148 |
+
return f"{self.web_base_url}/{rel.as_posix()}"
|
| 149 |
+
except ValueError:
|
| 150 |
+
return None
|
| 151 |
+
|
| 152 |
+
def _resolve_existing_video(self, user_value: str) -> Optional[VideoInfo]:
|
| 153 |
+
if not user_value:
|
| 154 |
+
return None
|
| 155 |
+
|
| 156 |
+
candidates = []
|
| 157 |
+
user_path = Path(user_value.strip())
|
| 158 |
+
candidates.append(user_path)
|
| 159 |
+
candidates.append(self.output_dir / user_path.name)
|
| 160 |
+
candidates.append(self.plugin_root / user_path)
|
| 161 |
+
|
| 162 |
+
for candidate in candidates:
|
| 163 |
+
if candidate.exists() and candidate.is_file():
|
| 164 |
+
url = self._to_web_url(candidate)
|
| 165 |
+
if url is None:
|
| 166 |
+
continue
|
| 167 |
+
return VideoInfo(path=candidate, url=url)
|
| 168 |
+
return None
|
| 169 |
+
|
| 170 |
+
def _generate_gloss(self, text: str, prompt: Optional[str], max_new_tokens: int) -> str:
|
| 171 |
+
tokenizer, model, device, torch = self._get_prompt_model()
|
| 172 |
+
prompt_text = prompt.strip() if prompt else text.strip()
|
| 173 |
+
if not prompt_text:
|
| 174 |
+
raise ValueError("Prompt/text input is empty.")
|
| 175 |
+
input_text = build_prompt_input(prompt_text, text)
|
| 176 |
+
encoded = tokenizer(
|
| 177 |
+
input_text,
|
| 178 |
+
return_tensors="pt",
|
| 179 |
+
truncation=True,
|
| 180 |
+
max_length=512,
|
| 181 |
+
).to(device)
|
| 182 |
+
with torch.no_grad():
|
| 183 |
+
outputs = model.generate(
|
| 184 |
+
**encoded,
|
| 185 |
+
max_new_tokens=max_new_tokens,
|
| 186 |
+
num_beams=4,
|
| 187 |
+
length_penalty=1.0,
|
| 188 |
+
early_stopping=True,
|
| 189 |
+
)
|
| 190 |
+
decoded = tokenizer.batch_decode(outputs, skip_special_tokens=True)[0].strip().upper()
|
| 191 |
+
return decoded
|
| 192 |
+
|
| 193 |
+
def _build_output_path(self, gloss_tokens: List[str], draw_style: str) -> Path:
|
| 194 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 195 |
+
slug = "_".join(gloss_tokens[:4]) if gloss_tokens else "gloss"
|
| 196 |
+
suffix = f"_{draw_style}_style" if draw_style else ""
|
| 197 |
+
filename = f"{slug}_{timestamp}{suffix}.mp4"
|
| 198 |
+
return self.output_dir / filename
|
| 199 |
+
|
| 200 |
+
def _list_recent_videos(self, limit: int = 12) -> List[Dict[str, Any]]:
|
| 201 |
+
if not self.output_dir.exists():
|
| 202 |
+
return []
|
| 203 |
+
videos = sorted(
|
| 204 |
+
[p for p in self.output_dir.glob("*.mp4") if p.is_file()],
|
| 205 |
+
key=lambda p: p.stat().st_mtime,
|
| 206 |
+
reverse=True,
|
| 207 |
+
)
|
| 208 |
+
result = []
|
| 209 |
+
for video in videos[:limit]:
|
| 210 |
+
url = self._to_web_url(video)
|
| 211 |
+
if not url:
|
| 212 |
+
continue
|
| 213 |
+
result.append(
|
| 214 |
+
{
|
| 215 |
+
"name": video.name,
|
| 216 |
+
"url": url,
|
| 217 |
+
"path": str(video),
|
| 218 |
+
"updated": datetime.fromtimestamp(video.stat().st_mtime).isoformat(),
|
| 219 |
+
"size_mb": round(video.stat().st_size / (1024 * 1024), 2),
|
| 220 |
+
}
|
| 221 |
+
)
|
| 222 |
+
return result
|
| 223 |
+
|
| 224 |
+
# ------------------------------------------------------------------
|
| 225 |
+
# Message handling
|
| 226 |
+
# ------------------------------------------------------------------
|
| 227 |
+
def handle_message(self, message: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
| 228 |
+
action = message.get("action")
|
| 229 |
+
data = message.get("data", {}) or {}
|
| 230 |
+
|
| 231 |
+
if action == "generate_pose":
|
| 232 |
+
return self.handle_generate_pose(data)
|
| 233 |
+
if action == "list_recent_videos":
|
| 234 |
+
return {"status": "success", "videos": self._list_recent_videos()}
|
| 235 |
+
if action == "probe_video":
|
| 236 |
+
return self.handle_probe_video(data)
|
| 237 |
+
return super().handle_message(message)
|
| 238 |
+
|
| 239 |
+
def handle_probe_video(self, data: Dict[str, Any]) -> Dict[str, Any]:
|
| 240 |
+
candidate = (data.get("path") or "").strip()
|
| 241 |
+
info = self._resolve_existing_video(candidate)
|
| 242 |
+
if info:
|
| 243 |
+
return {
|
| 244 |
+
"status": "success",
|
| 245 |
+
"video": {
|
| 246 |
+
"name": info.path.name,
|
| 247 |
+
"url": info.url,
|
| 248 |
+
"path": str(info.path),
|
| 249 |
+
"size_mb": round(info.path.stat().st_size / (1024 * 1024), 2),
|
| 250 |
+
},
|
| 251 |
+
}
|
| 252 |
+
return {"status": "error", "message": "Video not found or outside plugin directory."}
|
| 253 |
+
|
| 254 |
+
def handle_generate_pose(self, data: Dict[str, Any]) -> Dict[str, Any]:
|
| 255 |
+
if not self._generation_lock.acquire(blocking=False):
|
| 256 |
+
return {"status": "error", "message": "A generation job is already running. Please wait."}
|
| 257 |
+
|
| 258 |
+
try:
|
| 259 |
+
text_input = (data.get("text") or "").strip()
|
| 260 |
+
prompt_input = (data.get("prompt") or "").strip()
|
| 261 |
+
gloss_input = (data.get("gloss") or "").strip()
|
| 262 |
+
max_new_tokens = _safe_int(data.get("maxNewTokens"), 64)
|
| 263 |
+
|
| 264 |
+
# Allow reusing an existing video without regeneration
|
| 265 |
+
reuse_target = (data.get("existingVideo") or "").strip()
|
| 266 |
+
if reuse_target:
|
| 267 |
+
info = self._resolve_existing_video(reuse_target)
|
| 268 |
+
if not info:
|
| 269 |
+
return {"status": "error", "message": "Specified video path/name not found."}
|
| 270 |
+
return {
|
| 271 |
+
"status": "success",
|
| 272 |
+
"gloss": gloss_input.upper(),
|
| 273 |
+
"video_url": info.url,
|
| 274 |
+
"video_path": str(info.path),
|
| 275 |
+
"logs": f"Reused existing video: {info.path.name}",
|
| 276 |
+
"generated": False,
|
| 277 |
+
}
|
| 278 |
+
|
| 279 |
+
if not gloss_input:
|
| 280 |
+
if not text_input:
|
| 281 |
+
return {"status": "error", "message": "Please enter text/prompt or a gloss sequence."}
|
| 282 |
+
gloss_input = self._generate_gloss(text_input, prompt_input, max_new_tokens)
|
| 283 |
+
|
| 284 |
+
gloss_tokens = [token for token in gloss_input.upper().split() if token]
|
| 285 |
+
if not gloss_tokens:
|
| 286 |
+
return {"status": "error", "message": "Gloss string is empty after normalization."}
|
| 287 |
+
|
| 288 |
+
fps = _safe_int(data.get("fps"), 30)
|
| 289 |
+
width = _safe_int(data.get("width"), 480)
|
| 290 |
+
height = _safe_int(data.get("height"), 480)
|
| 291 |
+
smoothing_method = data.get("smoothing", "none") or "none"
|
| 292 |
+
smoothing_frames = _safe_int(data.get("smoothingFrames"), 5)
|
| 293 |
+
npz_interp = _safe_int(data.get("npzInterpolation"), 0)
|
| 294 |
+
scale_x = _safe_float(data.get("scaleX"), 1.5)
|
| 295 |
+
scale_y = _safe_float(data.get("scaleY"), 1.5)
|
| 296 |
+
hide_torso = _to_bool(data.get("hideTorsoLines"), False)
|
| 297 |
+
normalize_pose = _to_bool(data.get("normalizePose"), True)
|
| 298 |
+
draw_style = (data.get("drawStyle") or "controlnext").lower()
|
| 299 |
+
max_candidates = _safe_int(data.get("maxCandidates"), 10)
|
| 300 |
+
ref_image = (data.get("refImagePath") or "").strip() or None
|
| 301 |
+
|
| 302 |
+
qa_system = self._get_qa_system(max_candidates if max_candidates >= 0 else 10)
|
| 303 |
+
output_path = self._build_output_path(gloss_tokens, draw_style)
|
| 304 |
+
|
| 305 |
+
log_buffer = io.StringIO()
|
| 306 |
+
success = False
|
| 307 |
+
with contextlib.redirect_stdout(log_buffer), contextlib.redirect_stderr(log_buffer):
|
| 308 |
+
success = qa_system.generate_video_from_glosses(
|
| 309 |
+
gloss_tokens,
|
| 310 |
+
output_path,
|
| 311 |
+
fps=fps,
|
| 312 |
+
width=width,
|
| 313 |
+
height=height,
|
| 314 |
+
smoothing_frames=smoothing_frames,
|
| 315 |
+
smoothing_method=smoothing_method,
|
| 316 |
+
npz_interpolation_frames=npz_interp,
|
| 317 |
+
scale_x=scale_x,
|
| 318 |
+
scale_y=scale_y,
|
| 319 |
+
hide_torso_lines=hide_torso,
|
| 320 |
+
ref_image_path=ref_image,
|
| 321 |
+
draw_style=draw_style,
|
| 322 |
+
normalize_pose=normalize_pose,
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
logs = self._format_logs(log_buffer)
|
| 326 |
+
|
| 327 |
+
if not success or not output_path.exists():
|
| 328 |
+
return {
|
| 329 |
+
"status": "error",
|
| 330 |
+
"message": "Video generation failed. See logs for details.",
|
| 331 |
+
"logs": logs,
|
| 332 |
+
}
|
| 333 |
+
|
| 334 |
+
url = self._to_web_url(output_path)
|
| 335 |
+
if not url:
|
| 336 |
+
return {
|
| 337 |
+
"status": "error",
|
| 338 |
+
"message": "Video generated but cannot be served (outside plugin directory).",
|
| 339 |
+
"logs": logs,
|
| 340 |
+
}
|
| 341 |
+
|
| 342 |
+
return {
|
| 343 |
+
"status": "success",
|
| 344 |
+
"gloss": " ".join(gloss_tokens),
|
| 345 |
+
"video_url": url,
|
| 346 |
+
"video_path": str(output_path),
|
| 347 |
+
"logs": logs,
|
| 348 |
+
"generated": True,
|
| 349 |
+
"settings": {
|
| 350 |
+
"fps": fps,
|
| 351 |
+
"width": width,
|
| 352 |
+
"height": height,
|
| 353 |
+
"smoothing": smoothing_method,
|
| 354 |
+
"npzInterpolation": npz_interp,
|
| 355 |
+
"drawStyle": draw_style,
|
| 356 |
+
},
|
| 357 |
+
}
|
| 358 |
+
except Exception as exc: # pylint: disable=broad-except
|
| 359 |
+
log = io.StringIO()
|
| 360 |
+
with contextlib.redirect_stdout(log), contextlib.redirect_stderr(log):
|
| 361 |
+
import traceback
|
| 362 |
+
|
| 363 |
+
traceback.print_exc()
|
| 364 |
+
logs = log.getvalue()
|
| 365 |
+
return {"status": "error", "message": str(exc), "logs": logs}
|
| 366 |
+
finally:
|
| 367 |
+
self._generation_lock.release()
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
# Entry point required by ControlWorld's loader
|
| 371 |
+
PluginBackend = StableSignerBackend
|