StableSigner / index.js
FangSen9000
Add semantic text-to-gloss option
a16e5a2
Raw History Blame Contribute Delete
84.5 kB
import { ControlWavePlugin } from '../plugin-loader.js';
const STYLE_ID = 'stable-signer-plugin-style';
const toInt = (value, fallback) => {
const parsed = parseInt(value, 10);
return Number.isNaN(parsed) ? fallback : parsed;
};
const toFloat = (value, fallback) => {
const parsed = parseFloat(value);
return Number.isNaN(parsed) ? fallback : parsed;
};
const normalizePromptText = (raw) => {
if (!raw) return "";
const text = raw.trim();
const doubleQuoted = text.match(/"([^"]{2,})"/);
if (doubleQuoted) {
return doubleQuoted[1].trim();
}
const singleQuoted = text.match(/'([^']{2,})'/);
if (singleQuoted) {
return singleQuoted[1].trim();
}
const forClause = text.match(/\bfor\s+([^?!.]+)[?!.]?$/i);
if (forClause && forClause[1].trim().length > 0) {
return forClause[1].trim();
}
return text;
};
function ensureStyles() {
if (document.getElementById(STYLE_ID)) {
return;
}
const style = document.createElement('style');
style.id = STYLE_ID;
style.textContent = `
.stable-signer-root {
display: grid;
grid-template-columns: minmax(0, 1.5fr) minmax(0, 1fr);
align-items: start;
gap: 20px;
width: 100%;
height: 100%;
padding: 20px;
box-sizing: border-box;
}
.stable-signer-left-col {
display: flex;
flex-direction: column;
gap: 20px;
min-width: 0;
width: 100%;
justify-self: stretch;
}
.stable-signer-panel {
background: #fff;
border-radius: 12px;
box-shadow: 0 4px 16px rgba(15, 23, 42, 0.08);
padding: 20px;
display: flex;
flex-direction: column;
}
.stable-signer-left {
min-width: 0;
align-self: start;
width: 100%;
}
.stable-signer-right {
min-width: 0;
}
.stable-signer-bottom {
min-width: 0;
width: 100%;
}
.stable-text-playground {
grid-column: 1 / -1;
min-width: 0;
}
.stable-text-playground .stable-reading-area {
min-height: 180px;
font-size: 16px;
line-height: 1.65;
}
.stable-text-playground-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 10px;
}
.stable-text-playground-title h3 {
margin: 0;
font-size: 16px;
color: #0f172a;
}
.stable-playground-actions {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 10px;
flex-wrap: wrap;
}
.stable-playground-actions label {
display: inline-flex;
align-items: center;
gap: 6px;
margin: 0;
font-size: 13px;
font-weight: 600;
color: #334155;
}
.stable-playground-actions input {
width: auto;
margin: 0;
}
.stable-playground-actions button {
padding: 6px 10px;
white-space: nowrap;
}
.stable-video-frame {
position: relative;
width: 100%;
padding-top: 56.25%;
background: #0f172a;
border-radius: 10px;
overflow: hidden;
}
.stable-selected-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 12px;
font-size: 13px;
color: #0f172a;
}
.stable-selected-row strong {
font-weight: 700;
}
.stable-selected-row span {
color: #334155;
}
.stable-refine-grid {
margin-top: 12px;
display: flex;
flex-direction: column;
gap: 12px;
}
.stable-output-section {
margin-top: 12px;
display: flex;
flex-direction: column;
gap: 12px;
}
.stable-output-section h4 {
margin: 8px 0 0;
font-size: 14px;
color: #0f172a;
}
.stable-video-frame video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
object-fit: contain;
background: #0f172a;
}
.stable-video-placeholder {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
color: #94a3b8;
font-size: 15px;
text-align: center;
padding: 20px;
}
.stable-video-controls {
margin-top: 15px;
display: flex;
gap: 10px;
align-items: center;
}
.stable-video-controls select,
.stable-video-controls button {
flex: 1;
}
.stable-meta {
font-family: "JetBrains Mono", "Fira Code", monospace;
background: #0f172a;
color: #e2e8f0;
padding: 12px;
border-radius: 8px;
margin-top: 15px;
min-height: 60px;
font-size: 13px;
}
.stable-control-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 15px;
}
.stable-control-actions {
display: flex;
gap: 10px;
flex: 1;
}
.stable-control-actions button {
flex: 1;
}
.stable-translation-options {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-top: 8px;
font-size: 13px;
color: #334155;
}
.stable-translation-options label {
display: inline-flex;
align-items: center;
gap: 6px;
margin: 0;
font-weight: 600;
}
.stable-translation-options input {
width: auto;
margin: 0;
}
.stable-translation-options button {
white-space: nowrap;
padding: 6px 10px;
}
.stable-status-chip {
font-size: 13px;
padding: 6px 12px;
border-radius: 999px;
background: #e2e8f0;
color: #0f172a;
}
.stable-form-row {
display: flex;
gap: 12px;
margin-bottom: 15px;
}
.stable-form-row .form-group {
flex: 1;
}
.form-group label {
font-size: 13px;
font-weight: 600;
display: block;
margin-bottom: 6px;
color: #0f172a;
}
.form-group textarea,
.form-group input,
.form-group select {
width: 100%;
padding: 10px 12px;
border: 1px solid #cbd5f5;
border-radius: 8px;
font-size: 14px;
transition: border-color 0.2s, box-shadow 0.2s;
}
.form-group textarea {
min-height: 110px;
resize: vertical;
}
.form-group input:focus,
.form-group textarea:focus,
.form-group select:focus {
outline: none;
border-color: #6366f1;
box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
}
details.stable-advanced {
margin-top: 10px;
border: 1px solid #cbd5f5;
border-radius: 10px;
padding: 12px;
}
details.stable-advanced summary {
cursor: pointer;
font-weight: 600;
color: #1d4ed8;
}
.stable-advanced-grid {
margin-top: 12px;
display: flex;
flex-wrap: wrap;
gap: 12px;
}
.stable-advanced-grid .form-group,
.stable-advanced-grid .stable-switch {
flex: 1 1 calc(50% - 12px);
min-width: 180px;
}
.stable-switch {
display: flex;
align-items: center;
gap: 8px;
font-size: 13px;
}
.stable-switch input {
width: auto;
}
.stable-logs {
margin-top: 18px;
}
.stable-logs pre {
background: #0f172a;
color: #cbd5f5;
border-radius: 8px;
padding: 14px;
font-size: 12px;
max-height: 220px;
overflow: auto;
width: 100%;
max-width: 100%;
white-space: pre-wrap;
word-break: break-word;
overflow-wrap: anywhere;
}
.btn.primary {
background: linear-gradient(120deg, #6366f1, #8b5cf6);
border: none;
color: #fff;
border-radius: 10px;
padding: 10px 18px;
font-weight: 600;
cursor: pointer;
transition: transform 0.15s ease, box-shadow 0.2s ease;
}
.btn.primary:disabled {
opacity: 0.6;
cursor: not-allowed;
box-shadow: none;
}
.btn.primary:not(:disabled):hover {
transform: translateY(-2px);
box-shadow: 0 10px 20px rgba(99, 102, 241, 0.2);
}
.btn.secondary {
background: #e2e8f0;
border: none;
color: #0f172a;
border-radius: 8px;
padding: 8px 14px;
font-weight: 600;
cursor: pointer;
}
.stable-inline {
display: flex;
gap: 10px;
align-items: center;
}
.stable-hint {
margin-top: 6px;
font-size: 12px;
color: #475569;
}
.stable-reading-area {
min-height: 120px;
border: 1px solid #cbd5f5;
border-radius: 8px;
padding: 12px;
background: #f8fafc;
color: #0f172a;
line-height: 1.55;
font-size: 14px;
user-select: text;
}
.stable-reading-area:focus {
outline: none;
border-color: #6366f1;
box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
}
.stable-dialogue-area {
min-height: 360px;
border: 1px solid #d7b98a;
border-radius: 10px;
padding: 18px;
background:
linear-gradient(135deg, rgba(255, 255, 255, 0.58), rgba(255, 248, 236, 0.2)),
repeating-linear-gradient(90deg, #f5e3c4 0, #f5e3c4 18px, #efd6ad 19px, #efd6ad 36px);
color: #2f2417;
line-height: 1.62;
font-size: 15px;
user-select: text;
box-shadow: inset 0 1px 0 rgba(255,255,255,0.55);
}
.stable-dialogue-turn {
max-width: 82%;
margin: 12px 0;
padding: 14px 16px;
border-radius: 12px;
box-shadow: 0 4px 12px rgba(74, 53, 28, 0.12);
white-space: normal;
}
.stable-dialogue-turn.question {
margin-left: auto;
background: rgba(255, 255, 255, 0.82);
border: 1px solid rgba(185, 139, 73, 0.38);
}
.stable-dialogue-turn.answer {
margin-right: auto;
background: rgba(255, 250, 240, 0.9);
border: 1px solid rgba(161, 113, 48, 0.42);
}
.stable-dialogue-speaker {
display: inline-block;
margin-bottom: 8px;
padding: 3px 8px;
border-radius: 999px;
background: #8b5e2e;
color: #fff8ed;
font-size: 12px;
font-weight: 700;
}
.stable-dialogue-turn p {
margin: 8px 0;
}
.stable-dialogue-turn ul {
margin: 8px 0 8px 20px;
padding: 0;
}
.stable-dialogue-turn li {
margin: 4px 0;
}
.stable-selection-popover {
position: fixed;
right: 22px;
bottom: 22px;
z-index: 9999;
display: none;
width: min(380px, calc(100vw - 44px));
border-radius: 12px;
background: #0f172a;
color: #e2e8f0;
box-shadow: 0 18px 40px rgba(15, 23, 42, 0.35);
overflow: hidden;
}
.stable-selection-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
padding: 10px 12px;
border-bottom: 1px solid rgba(148, 163, 184, 0.25);
font-size: 13px;
font-weight: 700;
}
.stable-selection-header button,
.stable-selection-actions button {
border: none;
border-radius: 8px;
padding: 7px 10px;
font-size: 12px;
font-weight: 700;
cursor: pointer;
background: #e2e8f0;
color: #0f172a;
}
.stable-selection-body {
padding: 12px;
display: flex;
flex-direction: column;
gap: 10px;
}
.stable-selection-text {
max-height: 66px;
overflow: auto;
color: #cbd5e1;
font-size: 12px;
line-height: 1.45;
border-left: 3px solid #6366f1;
padding-left: 8px;
}
.stable-mini-video-frame {
position: relative;
width: 100%;
aspect-ratio: 1 / 1;
background: #020617;
border-radius: 8px;
overflow: hidden;
}
.stable-mini-video-frame video,
.stable-mini-video-frame canvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
object-fit: contain;
background: #020617;
}
.stable-mini-video-frame canvas {
display: none;
}
.stable-mini-placeholder {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
color: #94a3b8;
font-size: 13px;
text-align: center;
padding: 16px;
}
.stable-selection-status {
min-height: 18px;
color: #cbd5e1;
font-size: 12px;
overflow-wrap: anywhere;
}
.stable-selection-actions {
display: flex;
gap: 8px;
}
.stable-selection-actions button {
flex: 1;
}
@media (max-width: 1200px) {
.stable-signer-root {
grid-template-columns: 1fr;
}
}
`;
document.head.appendChild(style);
}
export default class StableSignerPlugin extends ControlWavePlugin {
constructor() {
super({
id: 'stable-signer',
name: 'StableSigner',
version: '1.0.0',
author: 'StableSigner',
description: 'Prompt/Text → Gloss → Pose Video',
order: 25,
needsViser: false
});
this.state = {
status: 'Idle',
lastVideo: null
};
this.currentVideoObjectUrl = null;
this.refineVideoObjectUrl = null;
this.selectedPosePath = null;
this.refineJobId = null;
this.refineLogCursor = 0;
this.refinePollingTimer = null;
}
async render(container) {
ensureStyles();
this.container = container;
container.classList.add('tab-content', 'active');
container.style.display = 'flex';
container.innerHTML = this.renderTemplate();
this.cacheElements(container);
this.attachEvents();
this.updateStatus('Idle');
await this.refreshRecentVideos();
await this.refreshStage1Videos();
await this.refreshStage2Videos();
}
renderTemplate() {
return `
<div class="stable-signer-root">
<div class="stable-signer-left-col">
<div class="stable-signer-left stable-signer-panel">
<div class="stable-video-frame">
<video id="stable-video" controls playsinline loop muted></video>
<div id="stable-video-placeholder" class="stable-video-placeholder">
Generated pose video will appear here
</div>
</div>
<div class="stable-video-controls">
<select id="stable-video-select">
<option value="">Select recently generated video</option>
</select>
<button id="stable-video-refresh" class="btn secondary">Refresh</button>
</div>
<div class="stable-meta" id="stable-video-meta">
Waiting for generated video...
</div>
</div>
<div class="stable-signer-bottom stable-signer-panel">
<div class="stable-control-header">
<h3 style="margin:0;font-size:16px;">Render / Refine Output</h3>
<span class="stable-status-chip">Preview</span>
</div>
<div class="stable-selected-row">
<div>
<strong>Chosen Pose Video:</strong>
<span id="stable-selected-name">None</span>
</div>
<button id="stable-generate-refine" class="btn primary">Generate Refine Video</button>
</div>
<div class="stable-refine-grid">
<div class="stable-form-row">
<div class="form-group">
<label>Ref image path</label>
<input id="stable-refine-ref-image" type="text" placeholder="ref_img_dict/man.jpg">
</div>
<div class="form-group">
<label>GPU (optional)</label>
<input id="stable-refine-gpu" type="text" placeholder="auto">
</div>
</div>
<div class="stable-form-row">
<div class="form-group">
<label>Ref CFG</label>
<input id="stable-refine-ref-cfg" type="number" step="0.1" value="2.5">
</div>
<div class="form-group">
<label>Pose CFG</label>
<input id="stable-refine-pose-cfg" type="number" step="0.1" value="1.5">
</div>
</div>
<div class="stable-form-row">
<div class="form-group">
<label>Stage1 output dir</label>
<input id="stable-refine-stage1-out" type="text" value="generated_sign_video">
</div>
<div class="form-group">
<label>Stage2 output dir</label>
<input id="stable-refine-stage2-out" type="text" value="generated_sign_video_refine">
</div>
</div>
</div>
<div class="stable-output-section">
<h4>Stage 1 Output (generated_sign_video)</h4>
<div class="stable-video-controls">
<select id="stable-stage1-select">
<option value="">Select stage1 output video</option>
</select>
<button id="stable-stage1-refresh" class="btn secondary">Refresh</button>
</div>
<h4>Stage 2 Output (generated_sign_video_refine)</h4>
<div class="stable-video-controls">
<select id="stable-stage2-select">
<option value="">Select stage2 output video</option>
</select>
<button id="stable-stage2-refresh" class="btn secondary">Refresh</button>
</div>
<div class="stable-video-frame" style="padding-top: 56.25%;">
<video id="stable-output-video" controls playsinline loop muted></video>
<div id="stable-output-placeholder" class="stable-video-placeholder">
Rendered/refined video will appear here
</div>
</div>
<div class="stable-meta" id="stable-output-meta">
Waiting for refine output...
</div>
</div>
<div class="stable-logs">
<label>Render / Refine logs</label>
<pre id="stable-refine-logs">(waiting for refine...)</pre>
</div>
</div>
</div>
<div class="stable-signer-right stable-signer-panel">
<div class="stable-control-header">
<div class="stable-control-actions">
<button id="stable-prewarm" class="btn secondary">Prewarm</button>
<button id="stable-translate" class="btn secondary">Text → Available Gloss</button>
<button id="stable-semantic-demo" class="btn secondary">Semantic Demo</button>
</div>
<span class="stable-status-chip" id="stable-status">Idle</span>
</div>
<div class="form-group">
<label>Prompt / Text</label>
<textarea id="stable-prompt-text" placeholder="Describe the action or context; the system will translate it to gloss."></textarea>
<div class="stable-hint">Input text auto-translates and fills the uppercase gloss field below (still editable).</div>
<div class="stable-translation-options">
<label><input type="checkbox" id="stable-semantic-gloss"> Semantic constrained gloss</label>
<span>Uses conservative synonym fallback; output remains limited to available poses.</span>
</div>
<div class="form-group" style="margin-top:8px;font-size:13px;color:#475569;">
<div>Prompt samples (picked from the latest prompt2gloss eval logs with strongest gloss matches):</div>
<div>1. Can you provide instruction on the sign language for &ldquo;You&rsquo;re going to hit it just a little more behind.&rdquo;?</div>
<div>2. Can you show me how &ldquo;Then what I like to do is go on with my fiber pliable paste.&rdquo; appears in sign language?</div>
<div>3. How is &ldquo;A baby snake might shed every week to an adult snake that might shed once a year so it really varies as to how often they&rsquo;re going to shed their skin because it depends on how much they are growing.&rdquo; signed?</div>
<div>4. How would you express &ldquo;You check the pressure of the tires and to change tire pressures every time you come in, depending on track conditions, the track continues to change every single time you go out there.&rdquo; in sign language?</div>
<div style="margin-top:6px;">Text samples (same sentences without the meta question):</div>
<div>1. You&rsquo;re going to hit it just a little more behind.</div>
<div>2. Then what I like to do is go on with my fiber pliable paste.</div>
<div>3. A baby snake might shed every week to an adult snake that might shed once a year so it really varies as to how often they&rsquo;re going to shed their skin because it depends on how much they are growing.</div>
<div>4. &ldquo;You check the pressure of the tires and to change tire pressures every time you come in, depending on track conditions, the track continues to change every single time you go out there.&rdquo;</div>
<div style="margin-top:6px;">Ground-truth gloss samples (for reference):</div>
<div>1. <strong>TO HIT A MORE BEHIND</strong></div>
<div>2. <strong>THEN WHAT I LIKE TO GO ON WITH MY</strong></div>
<div>3. <strong>A BABY SNAKE EVERY WEEK TO ADULT THAT ONCE YEAR REALLY HOW OFTEN THEIR SKIN BECAUSE ON MUCH THEY</strong></div>
<div>4. <strong>YOU CHECK PRESSURE AND TO CHANGE EVERY TIME COME IN ON SINGLE GO OUT THERE</strong></div>
</div>
</div>
<div class="form-group" style="margin-top:4px;">
<button id="stable-generate" class="btn primary" style="width:100%;">Generate Pose Video</button>
</div>
<div class="form-group">
<label>Gloss sequence (auto generated, editable)</label>
<textarea id="stable-gloss" placeholder="Example: I NEED HELP PLEASE"></textarea>
<div class="form-group" style="margin-top:8px;font-size:13px;color:#475569;">
<div>Examples:</div>
<div>1. HELLO WORLD</div>
<div>2. I NEED HELP PLEASE</div>
<div>3. TODAY WEATHER NICE</div>
<div>4. I GO SCHOOL LATER</div>
</div>
</div>
<div class="form-group">
<label>Reuse existing video (path or filename, optional)</label>
<input id="stable-existing-video" type="text" placeholder="e.g., generated_pose_video/EXAMPLE.mp4">
</div>
<details class="stable-advanced">
<summary>Advanced Settings</summary>
<div class="stable-advanced-grid">
<div class="form-group">
<label>FPS</label>
<input id="stable-fps" type="number" min="5" max="60" value="25">
</div>
<div class="form-group">
<label>Width</label>
<input id="stable-width" type="number" min="256" max="1024" value="512">
</div>
<div class="form-group">
<label>Height</label>
<input id="stable-height" type="number" min="256" max="1024" value="512">
</div>
<div class="form-group">
<label>Smoothing</label>
<select id="stable-smoothing">
<option value="none">None</option>
<option value="fade">Fade</option>
<option value="blend">Blend</option>
<option value="pause">Pause</option>
</select>
</div>
<div class="form-group">
<label>Smoothing Frames</label>
<input id="stable-smoothing-frames" type="number" min="0" max="60" value="0">
</div>
<div class="form-group">
<label>NPZ Interp Frames</label>
<input id="stable-npz" type="number" min="0" max="60" value="20">
</div>
<div class="form-group">
<label>Scale X</label>
<input id="stable-scale-x" type="number" step="0.1" value="1.4">
</div>
<div class="form-group">
<label>Scale Y</label>
<input id="stable-scale-y" type="number" step="0.1" value="1.5">
</div>
<div class="form-group">
<label>Draw Style</label>
<select id="stable-draw-style">
<option value="openpose">OpenPose</option>
<option value="controlnext">ControlNeXt</option>
</select>
</div>
<div class="form-group">
<label>Draw Confidence Threshold</label>
<input id="stable-draw-threshold" type="number" min="0" max="1" step="0.05" value="0.6">
</div>
<div class="form-group">
<label>Max Candidates</label>
<input id="stable-max-candidates" type="number" min="0" value="10">
</div>
<div class="form-group">
<label>Max New Tokens</label>
<input id="stable-max-new" type="number" min="8" max="256" value="64">
</div>
<div class="form-group">
<label>Reference image path (optional)</label>
<input id="stable-ref-image" type="text" placeholder="ref_img_dict/example.png">
</div>
<label class="stable-switch">
<input type="checkbox" id="stable-normalize" checked>
Normalize pose
</label>
<label class="stable-switch">
<input type="checkbox" id="stable-hide-torso">
Hide torso lines
</label>
</div>
</details>
<div class="stable-logs">
<label>Log output</label>
<pre id="stable-logs">(waiting for task...)</pre>
</div>
</div>
<div class="stable-text-playground stable-signer-panel">
<div class="stable-text-playground-title">
<h3>Selection Translation Playground</h3>
<div class="stable-playground-actions">
<label><input type="checkbox" id="stable-selection-semantic-gloss" checked> Semantic gloss</label>
<button id="stable-selection-semantic-demo" type="button" class="btn secondary">Semantic Demo</button>
<span class="stable-status-chip">Select text to translate</span>
</div>
</div>
<div id="stable-selection-template" class="stable-reading-area stable-dialogue-area" tabindex="0" contenteditable="true">
<div class="stable-dialogue-turn question">
<span class="stable-dialogue-speaker">User</span>
<p>Do native signers have difficulty reading written text?</p>
</div>
<div class="stable-dialogue-turn answer">
<span class="stable-dialogue-speaker">Assistant</span>
<p>Yes. This is a well-studied phenomenon. Deaf people whose first language is a sign language often do face difficulty when reading written language. The reason is not cognitive ability. It is a matter of linguistics and language acquisition. Written language is essentially a visual encoding of spoken language. Hearing children already have years of spoken-language immersion before reading; deaf children whose first language is ASL, CSL, or another sign language often approach English or Chinese as a second language, and one without accessible spoken-language support. Empirical work in the United States, including Gallaudet-related longitudinal research, has often found deaf high-school graduates around a fourth-grade median English reading level. Reports in mainland China similarly show delays in written Chinese, especially with function words, passive constructions, complex clauses, metaphor, idioms, and forms that depend on spoken-language and pragmatic experience. There is large variation: early sign-language exposure and bilingual education, sign language as L1 and written language as L2, generally produce much better reading outcomes. This is a core motivation for SLP and SLT: text-to-sign generation addresses a real accessibility gap in news, public notices, medical instructions, and educational materials.</p>
</div>
<div class="stable-dialogue-turn question">
<span class="stable-dialogue-speaker">User</span>
<p>But why do they not just learn text? Their parents usually know English text. In theory, should they not learn text first rather than sign language?</p>
</div>
<div class="stable-dialogue-turn answer">
<span class="stable-dialogue-speaker">Assistant</span>
<p>That intuition is natural, but it depends on a false premise. Parents knowing text does not mean a child can acquire text from them. Writing is not acquired directly; it is a second-order system built on top of an already acquired natural language. Hearing children do not learn text first. They acquire spoken language from age zero to five, then school teaches them to map that known language onto symbols. Deaf children often lack full access to that underlying natural language. You cannot skip language and teach writing directly. The critical-period literature, including work by Mayberry and Newport, shows that early complete language input is crucial; language deprivation can permanently harm later language, second-language learning, and reading. Sign language is not a competitor to reading. It is the foundation for reading. Parents also cannot provide rich language immersion through print: writing apple and pointing to an apple is sparse, slow, and abstract compared with real-time language in daily life. History already tried suppressing sign language through oralism, especially after the 1880 Milan Conference, and the results were disastrous. The correct causal chain is this: deaf children do not read poorly because they learned sign language. Deaf children with early access to a full sign language often learn written language better; those deprived of sign language and forced to rely on incomplete speech or print usually have the worst text outcomes. For SLP and SLT, automatic text-to-sign generation is not a lazy compromise. It provides information through an accessible natural-language modality.</p>
</div>
</div>
<div id="stable-selection-popover" class="stable-selection-popover">
<div class="stable-selection-header">
<span>Sign Translation</span>
<button id="stable-selection-close" type="button">Close</button>
</div>
<div class="stable-selection-body">
<div id="stable-selection-text" class="stable-selection-text"></div>
<div class="stable-mini-video-frame">
<video id="stable-selection-video" controls playsinline loop muted></video>
<canvas id="stable-selection-canvas" width="512" height="512"></canvas>
<div id="stable-selection-placeholder" class="stable-mini-placeholder">Select English text to generate a sign pose video.</div>
</div>
<div id="stable-selection-status" class="stable-selection-status">Waiting for selection...</div>
<div class="stable-selection-actions">
<button id="stable-selection-translate" type="button">Regenerate</button>
</div>
</div>
</div>
<div class="stable-hint">This is the browser-plugin style test area: select any text, then the floating skeleton signer appears at the bottom-right.</div>
</div>
</div>
`;
}
cacheElements(container) {
this.videoEl = container.querySelector('#stable-video');
this.videoPlaceholder = container.querySelector('#stable-video-placeholder');
this.videoSelect = container.querySelector('#stable-video-select');
this.videoRefreshBtn = container.querySelector('#stable-video-refresh');
this.videoMeta = container.querySelector('#stable-video-meta');
this.selectedName = container.querySelector('#stable-selected-name');
this.generateRefineBtn = container.querySelector('#stable-generate-refine');
this.refineRefImageInput = container.querySelector('#stable-refine-ref-image');
this.refineGpuInput = container.querySelector('#stable-refine-gpu');
this.refineRefCfgInput = container.querySelector('#stable-refine-ref-cfg');
this.refinePoseCfgInput = container.querySelector('#stable-refine-pose-cfg');
this.refineStage1OutInput = container.querySelector('#stable-refine-stage1-out');
this.refineStage2OutInput = container.querySelector('#stable-refine-stage2-out');
this.stage1Select = container.querySelector('#stable-stage1-select');
this.stage1RefreshBtn = container.querySelector('#stable-stage1-refresh');
this.stage2Select = container.querySelector('#stable-stage2-select');
this.stage2RefreshBtn = container.querySelector('#stable-stage2-refresh');
this.outputVideoEl = container.querySelector('#stable-output-video');
this.outputPlaceholder = container.querySelector('#stable-output-placeholder');
this.outputMeta = container.querySelector('#stable-output-meta');
this.refineLogsPre = container.querySelector('#stable-refine-logs');
this.prewarmBtn = container.querySelector('#stable-prewarm');
this.translateBtn = container.querySelector('#stable-translate');
this.semanticDemoBtn = container.querySelector('#stable-semantic-demo');
this.semanticGlossCheckbox = container.querySelector('#stable-semantic-gloss');
this.selectionSemanticCheckbox = container.querySelector('#stable-selection-semantic-gloss');
this.selectionSemanticDemoBtn = container.querySelector('#stable-selection-semantic-demo');
this.selectionTemplate = container.querySelector('#stable-selection-template');
this.selectionPopover = container.querySelector('#stable-selection-popover');
this.selectionTranslateBtn = container.querySelector('#stable-selection-translate');
this.selectionCloseBtn = container.querySelector('#stable-selection-close');
this.selectionTextEl = container.querySelector('#stable-selection-text');
this.selectionVideoEl = container.querySelector('#stable-selection-video');
this.selectionCanvas = container.querySelector('#stable-selection-canvas');
this.selectionCanvasCtx = this.selectionCanvas ? this.selectionCanvas.getContext('2d') : null;
this.selectionHasFrame = false;
this.selectionPlaceholder = container.querySelector('#stable-selection-placeholder');
this.selectionStatus = container.querySelector('#stable-selection-status');
this.selectedTemplateText = '';
this.selectionGenerationTimer = null;
this.selectionGenerationInFlight = false;
this.selectionStreamPollingTimer = null;
this.selectionStreamCursor = 0;
this.selectionStreamFrameQueue = [];
this.selectionStreamPlaybackTimer = null;
this.selectionStreamPlaybackFps = 25;
this.selectionPendingFinalVideoUrl = null;
this.lastGeneratedSelection = '';
this.generateBtn = container.querySelector('#stable-generate');
this.statusChip = container.querySelector('#stable-status');
this.promptTextInput = container.querySelector('#stable-prompt-text');
this.glossInput = container.querySelector('#stable-gloss');
this.existingInput = container.querySelector('#stable-existing-video');
this.fpsInput = container.querySelector('#stable-fps');
this.widthInput = container.querySelector('#stable-width');
this.heightInput = container.querySelector('#stable-height');
this.smoothingSelect = container.querySelector('#stable-smoothing');
this.smoothingFramesInput = container.querySelector('#stable-smoothing-frames');
this.npzInput = container.querySelector('#stable-npz');
this.scaleXInput = container.querySelector('#stable-scale-x');
this.scaleYInput = container.querySelector('#stable-scale-y');
this.drawStyleSelect = container.querySelector('#stable-draw-style');
this.drawThresholdInput = container.querySelector('#stable-draw-threshold');
this.maxCandidatesInput = container.querySelector('#stable-max-candidates');
this.maxNewTokensInput = container.querySelector('#stable-max-new');
this.refImageInput = container.querySelector('#stable-ref-image');
this.normalizeCheckbox = container.querySelector('#stable-normalize');
this.hideTorsoCheckbox = container.querySelector('#stable-hide-torso');
this.logsPre = container.querySelector('#stable-logs');
if (this.videoEl) {
this.videoEl.style.display = 'none';
}
if (this.outputVideoEl) {
this.outputVideoEl.style.display = 'none';
}
}
attachEvents() {
this.prewarmBtn.addEventListener('click', () => this.handlePrewarm());
this.translateBtn.addEventListener('click', () => this.handleTranslate());
if (this.semanticDemoBtn) {
this.semanticDemoBtn.addEventListener('click', () => this.handleSemanticDemo());
}
this.generateBtn.addEventListener('click', () => this.handleGenerate());
this.videoRefreshBtn.addEventListener('click', () => this.refreshRecentVideos());
this.videoSelect.addEventListener('change', () => this.handleRecentSelection());
this.generateRefineBtn.addEventListener('click', () => this.handleGenerateRefine());
this.stage1RefreshBtn.addEventListener('click', () => this.refreshStage1Videos());
this.stage2RefreshBtn.addEventListener('click', () => this.refreshStage2Videos());
this.stage1Select.addEventListener('change', () => this.handleStage1Selection());
this.stage2Select.addEventListener('change', () => this.handleStage2Selection());
if (this.selectionTemplate) {
this.selectionTemplate.addEventListener('mouseup', () => this.handleTemplateSelection());
this.selectionTemplate.addEventListener('keyup', () => this.handleTemplateSelection());
}
if (this.selectionSemanticDemoBtn) {
this.selectionSemanticDemoBtn.addEventListener('click', () => this.handleSelectionSemanticDemo());
}
if (this.selectionTranslateBtn) {
this.selectionTranslateBtn.addEventListener('click', () => this.handleSelectedTextGenerate(true));
}
if (this.selectionCloseBtn) {
this.selectionCloseBtn.addEventListener('click', () => this.hideSelectionPopover());
}
window.addEventListener('websocket-connected', () => {
this.updateStatus('WebSocket connected');
});
this.glossInput.addEventListener('input', () => {
const { selectionStart, selectionEnd, value } = this.glossInput;
const upper = value.toUpperCase();
if (upper !== value) {
this.glossInput.value = upper;
this.glossInput.setSelectionRange(selectionStart, selectionEnd);
}
});
}
collectPayload() {
const glossValue = (this.glossInput.value || '').toUpperCase().replace(/\s+/g, ' ').trim();
const promptText = (this.promptTextInput.value || '').trim();
return {
prompt: promptText,
text: promptText,
gloss: glossValue,
existingVideo: this.existingInput.value,
fps: toInt(this.fpsInput.value, 25),
width: toInt(this.widthInput.value, 512),
height: toInt(this.heightInput.value, 512),
smoothing: this.smoothingSelect.value,
smoothingFrames: toInt(this.smoothingFramesInput.value, 0),
npzInterpolation: toInt(this.npzInput.value, 20),
scaleX: toFloat(this.scaleXInput.value, 1.4),
scaleY: toFloat(this.scaleYInput.value, 1.5),
drawStyle: this.drawStyleSelect.value,
drawConfidenceThreshold: toFloat(this.drawThresholdInput.value, 0.6),
maxCandidates: toInt(this.maxCandidatesInput.value, 10),
maxNewTokens: toInt(this.maxNewTokensInput.value, 64),
refImagePath: this.refImageInput.value,
normalizePose: this.normalizeCheckbox.checked,
hideTorsoLines: this.hideTorsoCheckbox.checked,
translationMode: this.semanticGlossCheckbox && this.semanticGlossCheckbox.checked ? 'semantic' : 'text2gloss',
useSemantic: !!(this.semanticGlossCheckbox && this.semanticGlossCheckbox.checked)
};
}
async handleGenerate() {
if (!window.controlWaveWebSocket || !window.controlWaveWebSocket.sendRequest) {
this.updateStatus('WebSocket not ready');
return;
}
const payload = this.collectPayload();
if (!payload.gloss && !payload.text) {
this.updateStatus('Enter Prompt/Text or Gloss');
this.logsPre.textContent = 'Prompt/Text or Gloss cannot be empty';
return;
}
if (!payload.gloss && payload.text) {
try {
await this.handleTranslate(true);
payload.gloss = (this.glossInput.value || '').trim();
} catch (error) {
console.error('[StableSigner] auto translation failed', error);
this.updateStatus('Gloss translation failed');
this.logsPre.textContent = (error && error.message) ? error.message : 'Prompt → Gloss translation failed';
return;
}
}
this.setLoading(true);
this.updateStatus('Running...');
try {
const response = await window.controlWaveWebSocket.sendRequest(this.id, {
action: 'generate_pose',
data: payload
});
console.log('[StableSigner] generation payload', response);
const normalizedStatus = typeof response.status === 'string' ? response.status.toLowerCase() : '';
const inferredSuccess = normalizedStatus === 'success' || (!!response.video_url && response.generated !== undefined);
if (inferredSuccess) {
if (response.gloss) {
this.glossInput.value = response.gloss;
}
if (response.video_url) {
await this.updateVideo(response.video_url, response.video_path);
}
if (response.logs) {
this.logsPre.textContent = response.logs;
}
this.updateStatus(response.generated ? 'Generation completed' : 'Reused existing video');
try {
await this.refreshRecentVideos();
} catch (err) {
console.warn('[StableSigner] refresh failed', err);
}
} else {
console.error('[StableSigner] backend returned error', response);
this.updateStatus('Error');
this.logsPre.textContent = response.logs
|| response.message
|| response.error
|| normalizedStatus
|| 'Unknown error';
}
} catch (error) {
this.updateStatus('Error');
console.error('[StableSigner] request failure', error);
this.logsPre.textContent = (error && error.message) ? error.message : 'Request failed';
} finally {
this.setLoading(false);
}
}
async handlePrewarm() {
if (!window.controlWaveWebSocket || !window.controlWaveWebSocket.sendRequest) {
this.updateStatus('WebSocket not ready');
return;
}
this.updateStatus('Prewarming...');
this.setPrewarmLoading(true);
try {
const response = await window.controlWaveWebSocket.sendRequest(this.id, {
action: 'prewarm',
data: {}
});
const message = response.message || 'Prewarm completed';
const logs = response.logs || response.details || message;
this.logsPre.textContent = logs;
this.updateStatus('Prewarm completed');
} catch (error) {
console.error('[StableSigner] prewarm failed', error);
this.logsPre.textContent = (error && error.message) ? error.message : 'Prewarm failed';
this.updateStatus('Prewarm failed');
} finally {
this.setPrewarmLoading(false);
}
}
async handleTranslate(isAuto = false) {
const promptTextRaw = (this.promptTextInput.value || '').trim();
const maxTokens = toInt(this.maxNewTokensInput.value, 64);
if (!promptTextRaw) {
if (!isAuto) {
this.updateStatus('Prompt/Text is empty');
this.logsPre.textContent = 'Please enter a Prompt or Text to translate';
}
throw new Error('Prompt/Text is empty');
}
const normalizedPrompt = normalizePromptText(promptTextRaw);
if (!isAuto) {
this.updateStatus('Translating...');
this.setTranslateLoading(true);
}
try {
const result = await this.translatePromptToGloss(normalizedPrompt, maxTokens, promptTextRaw);
const gloss = typeof result === 'string' ? result : result.gloss;
this.glossInput.value = gloss;
if (!isAuto) {
this.updateStatus('Gloss translation completed');
const semantic = result.semantic && result.semantic.length > 0
? `\nSemantic fallback: ${result.semantic.map(([src, dst]) => `${src}→${dst}`).join(', ')}`
: '';
const dropped = result.dropped && result.dropped.length > 0
? `\nDropped: ${result.dropped.join(', ')}`
: '';
this.logsPre.textContent = `Translation result: ${gloss}\nMode: ${result.mode || 'rule'}${semantic}${dropped}`;
}
return gloss;
} finally {
if (!isAuto) {
this.setTranslateLoading(false);
}
}
}
async translatePromptToGloss(promptText, maxNewTokens, originalPrompt = null) {
if (!promptText) {
throw new Error('Prompt/Text is empty');
}
const payloadPrompt = originalPrompt || promptText;
const useSemantic = !!(this.semanticGlossCheckbox && this.semanticGlossCheckbox.checked);
const response = await window.controlWaveWebSocket.sendRequest(this.id, {
action: 'text_to_gloss',
data: {
text: promptText,
prompt: payloadPrompt,
maxNewTokens,
mode: useSemantic ? 'semantic' : 'rule',
useSemantic
}
});
if (!response || response.status !== 'success' || !response.gloss) {
throw new Error(response?.message || 'Gloss translation failed');
}
if (response.dropped && response.dropped.length > 0) {
console.info('[StableSigner] dropped non-renderable text tokens', response.dropped);
}
return response;
}
handleSemanticDemo() {
if (this.semanticGlossCheckbox) {
this.semanticGlossCheckbox.checked = true;
}
this.promptTextInput.value = 'Could you aid me? I bought a mobile and go home later.';
this.handleTranslate(false).catch((error) => {
this.updateStatus('Semantic demo failed');
this.logsPre.textContent = (error && error.message) ? error.message : 'Semantic demo failed';
});
}
handleSelectionSemanticDemo() {
if (this.selectionSemanticCheckbox) {
this.selectionSemanticCheckbox.checked = true;
}
const demoText = 'Could you aid me? I bought a mobile and go home later.';
if (this.selectionTemplate) {
this.selectionTemplate.innerHTML = `<div class="stable-dialogue-turn question"><span class="stable-dialogue-speaker">User</span><p>${demoText}</p></div>`;
}
this.selectedTemplateText = demoText;
this.lastGeneratedSelection = '';
if (this.selectionTextEl) {
this.selectionTextEl.textContent = demoText;
}
if (this.selectionPopover) {
this.selectionPopover.style.display = 'block';
}
this.handleSelectedTextGenerate(true);
}
handleTemplateSelection() {
if (!this.selectionTemplate || !this.selectionPopover) return;
const selection = window.getSelection();
const selectedText = selection ? selection.toString().replace(/\s+/g, ' ').trim() : '';
if (!selectedText || selectedText.length < 2) {
return;
}
const range = selection.rangeCount > 0 ? selection.getRangeAt(0) : null;
if (!range || !this.selectionTemplate.contains(range.commonAncestorContainer)) {
return;
}
this.selectedTemplateText = selectedText;
if (this.selectionTextEl) {
this.selectionTextEl.textContent = selectedText;
}
if (this.selectionStatus) {
this.selectionStatus.textContent = 'Preparing translation...';
}
if (this.selectionPopover) {
this.selectionPopover.style.display = 'block';
}
if (this.selectionGenerationTimer) {
clearTimeout(this.selectionGenerationTimer);
}
this.selectionGenerationTimer = setTimeout(() => this.handleSelectedTextGenerate(false), 450);
}
hideSelectionPopover() {
if (this.selectionGenerationTimer) {
clearTimeout(this.selectionGenerationTimer);
this.selectionGenerationTimer = null;
}
this.stopSelectionStreamPlayback();
this.selectionPendingFinalVideoUrl = null;
if (this.selectionPopover) {
this.selectionPopover.style.display = 'none';
}
}
async handleSelectedTextGenerate(force = false) {
const text = (this.selectedTemplateText || '').trim();
if (!text || this.selectionGenerationInFlight) return;
if (!force && text === this.lastGeneratedSelection) return;
this.selectionGenerationInFlight = true;
this.lastGeneratedSelection = text;
this.promptTextInput.value = text;
this.glossInput.value = '';
this.stopSelectionStreamPlayback();
this.selectionStreamFrameQueue = [];
this.selectionStreamCursor = 0;
this.selectionPendingFinalVideoUrl = null;
this.logsPre.textContent = 'Selected text:\n' + text + '\n\nStreaming pose preview...';
if (this.selectionStatus) {
this.selectionStatus.textContent = 'Preparing pose preview...';
}
if (this.selectionPlaceholder && !this.selectionHasFrame) {
this.selectionPlaceholder.style.display = 'none';
}
if (this.selectionVideoEl) {
this.selectionVideoEl.style.display = 'none';
this.selectionVideoEl.removeAttribute('src');
this.selectionVideoEl.load();
}
try {
await this.handleGenerateStream();
} catch (error) {
if (this.selectionStatus) {
this.selectionStatus.textContent = (error && error.message) ? error.message : 'Stream failed';
}
this.selectionGenerationInFlight = false;
}
}
async handleGenerateStream() {
if (!window.controlWaveWebSocket || !window.controlWaveWebSocket.sendRequest) {
throw new Error('WebSocket not ready');
}
const payload = this.collectPayload();
const selectionUseSemantic = !!(this.selectionSemanticCheckbox && this.selectionSemanticCheckbox.checked);
payload.translationMode = selectionUseSemantic ? 'semantic' : 'text2gloss';
payload.useSemantic = selectionUseSemantic;
payload.maxNewTokens = Math.min(toInt(this.maxNewTokensInput.value, 64), 18);
payload.maxCandidates = Math.min(toInt(this.maxCandidatesInput.value, 10), 3);
const response = await window.controlWaveWebSocket.sendRequest(this.id, {
action: 'generate_pose_stream',
data: payload
});
if (!response || response.status !== 'running' || !response.job_id) {
throw new Error(response?.message || 'Stream generation failed');
}
if (response.gloss) {
this.glossInput.value = response.gloss;
}
this.selectionStreamCursor = 0;
this.selectionStreamFrameQueue = [];
this.selectionPendingFinalVideoUrl = null;
this.selectionStreamPlaybackFps = toInt(response.fps, toInt(this.fpsInput.value, 25));
this.startSelectionStreamPlayback();
if (this.selectionStreamPollingTimer) {
clearTimeout(this.selectionStreamPollingTimer);
}
this.pollPoseStream(response.job_id);
}
startSelectionStreamPlayback() {
this.stopSelectionStreamPlayback();
const fps = Math.max(5, Math.min(60, this.selectionStreamPlaybackFps || 30));
const intervalMs = Math.max(16, Math.round(1000 / fps));
this.selectionStreamPlaybackTimer = setInterval(() => {
if (this.selectionStreamFrameQueue && this.selectionStreamFrameQueue.length > 0) {
const next = this.selectionStreamFrameQueue.shift();
if (next && next.image) {
this.drawStreamFrameToCanvas(next.image);
}
return;
}
if (this.selectionPendingFinalVideoUrl) {
const finalUrl = this.selectionPendingFinalVideoUrl;
this.selectionPendingFinalVideoUrl = null;
this.showSelectionFinalVideo(finalUrl);
}
}, intervalMs);
}
stopSelectionStreamPlayback() {
if (this.selectionStreamPlaybackTimer) {
clearInterval(this.selectionStreamPlaybackTimer);
this.selectionStreamPlaybackTimer = null;
}
}
async showSelectionFinalVideo(url) {
if (!url || !this.selectionVideoEl) return;
const absoluteUrl = url.startsWith('http') ? url : `${window.location.origin}${url}`;
const hasQuery = absoluteUrl.includes('?');
const fetchUrl = `${absoluteUrl}${hasQuery ? '&' : '?'}t=${Date.now()}`;
this.stopSelectionStreamPlayback();
this.selectionStreamFrameQueue = [];
this.selectionPendingFinalVideoUrl = null;
this.selectionVideoEl.pause();
this.selectionVideoEl.src = fetchUrl;
this.selectionVideoEl.style.display = 'block';
this.selectionVideoEl.load();
try {
await this.selectionVideoEl.play();
} catch (error) {
// Keep controls available even if autoplay is blocked.
}
if (this.selectionCanvas) {
this.selectionCanvas.style.display = 'none';
}
if (this.selectionPlaceholder) {
this.selectionPlaceholder.style.display = 'none';
}
}
drawStreamFrameToCanvas(dataUrl) {
const image = new Image();
image.onload = () => {
if (!this.selectionCanvas || !this.selectionCanvasCtx) return;
if (this.selectionCanvas.width !== image.naturalWidth) {
this.selectionCanvas.width = image.naturalWidth;
}
if (this.selectionCanvas.height !== image.naturalHeight) {
this.selectionCanvas.height = image.naturalHeight;
}
this.selectionCanvasCtx.drawImage(image, 0, 0, this.selectionCanvas.width, this.selectionCanvas.height);
this.selectionCanvas.style.display = 'block';
if (this.selectionVideoEl) {
this.selectionVideoEl.style.display = 'none';
}
this.selectionHasFrame = true;
if (this.selectionPlaceholder) {
this.selectionPlaceholder.style.display = 'none';
}
};
image.src = dataUrl;
}
async pollPoseStream(jobId) {
try {
const response = await window.controlWaveWebSocket.sendRequest(this.id, {
action: 'get_pose_stream_status',
data: {
jobId,
cursor: this.selectionStreamCursor
}
});
if (!response || response.status === 'error') {
throw new Error(response?.message || 'Stream polling failed');
}
const frames = response.frames || [];
if (frames.length > 0) {
this.selectionStreamFrameQueue.push(...frames.filter(frame => frame && frame.image));
if (this.selectionPlaceholder) {
this.selectionPlaceholder.style.display = 'none';
}
this.selectionStreamCursor = response.cursor || (this.selectionStreamCursor + frames.length);
}
if (this.selectionStatus) {
const total = response.total_frames ? ` / ${response.total_frames}` : '';
this.selectionStatus.textContent = `Gloss: ${(response.gloss || this.glossInput.value || '').trim()} · ${response.frame_count || this.selectionStreamCursor}${total} frames`;
}
if (response.status === 'running') {
this.selectionStreamPollingTimer = setTimeout(() => this.pollPoseStream(jobId), 120);
return;
}
this.selectionGenerationInFlight = false;
if (response.logs) {
this.logsPre.textContent = response.logs;
}
if (response.video_url) {
await this.updateVideo(response.video_url, response.video_path);
await this.refreshRecentVideos();
if (this.selectionStreamFrameQueue.length > 0) {
this.selectionPendingFinalVideoUrl = response.video_url;
} else {
await this.showSelectionFinalVideo(response.video_url);
}
}
if (this.selectionStatus && response.status === 'success') {
this.selectionStatus.textContent = `Gloss: ${(response.gloss || this.glossInput.value || '').trim()} · completed`;
}
} catch (error) {
// Keep the last displayed frame. Short polling gaps should not be visible to users.
if (this.selectionGenerationInFlight) {
this.selectionStreamPollingTimer = setTimeout(() => this.pollPoseStream(jobId), 500);
}
}
}
async updateVideo(url, path) {
if (!url || !this.videoEl) return;
const absoluteUrl = url.startsWith('http') ? url : `${window.location.origin}${url}`;
const hasQuery = absoluteUrl.includes('?');
const fetchUrl = `${absoluteUrl}${hasQuery ? '&' : '?'}t=${Date.now()}`;
if (path) {
this.setSelectedPose(path);
} else {
this.updateSelectedLabel(absoluteUrl);
}
const resetVideoEl = () => {
this.videoEl.onloadeddata = null;
this.videoEl.onerror = null;
this.videoEl.pause();
this.videoEl.removeAttribute('src');
this.videoEl.load();
};
this.videoPlaceholder.style.display = 'flex';
this.videoPlaceholder.textContent = 'Loading video…';
this.videoEl.style.display = 'none';
resetVideoEl();
if (this.currentVideoObjectUrl) {
URL.revokeObjectURL(this.currentVideoObjectUrl);
this.currentVideoObjectUrl = null;
}
try {
const response = await fetch(fetchUrl, { cache: 'no-store' });
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const blob = await response.blob();
const objectUrl = URL.createObjectURL(blob);
this.currentVideoObjectUrl = objectUrl;
this.videoEl.onloadeddata = () => {
this.videoEl.onloadeddata = null;
this.videoEl.onerror = null;
this.videoPlaceholder.style.display = 'none';
this.videoEl.style.display = 'block';
const playPromise = this.videoEl.play();
if (playPromise && typeof playPromise.catch === 'function') {
playPromise.catch(() => {});
}
this.videoMeta.textContent = `Video: ${path || absoluteUrl}`;
};
this.videoEl.onerror = () => {
this.videoEl.onloadeddata = null;
this.videoEl.onerror = null;
this.videoPlaceholder.style.display = 'flex';
this.videoPlaceholder.textContent = 'Video load failed';
const mediaError = this.videoEl.error;
console.error('[StableSigner] video load error', mediaError ? {
code: mediaError.code,
message: mediaError.message
} : 'unknown');
};
this.videoEl.src = objectUrl;
this.videoEl.load();
if (this.selectionVideoEl && this.selectionPopover && this.selectionPopover.style.display !== 'none') {
this.selectionVideoEl.pause();
this.selectionVideoEl.src = objectUrl;
this.selectionVideoEl.style.display = 'block';
this.selectionVideoEl.load();
if (this.selectionPlaceholder) {
this.selectionPlaceholder.style.display = 'none';
}
const miniPlayPromise = this.selectionVideoEl.play();
if (miniPlayPromise && typeof miniPlayPromise.catch === 'function') {
miniPlayPromise.catch(() => {});
}
}
} catch (error) {
resetVideoEl();
this.videoPlaceholder.style.display = 'flex';
this.videoPlaceholder.textContent = 'Video load failed';
console.error('[StableSigner] video fetch failed', error);
}
}
async refreshRecentVideos() {
if (!window.controlWaveWebSocket || !window.controlWaveWebSocket.sendRequest) {
this.updateStatus('Waiting for WebSocket...');
return;
}
try {
const response = await window.controlWaveWebSocket.sendRequest(this.id, {
action: 'list_recent_videos'
});
this.populateRecentVideos(response.videos || []);
} catch (error) {
this.videoMeta.textContent = `Failed to refresh video list: ${error.message}`;
}
}
async refreshStage1Videos() {
if (!window.controlWaveWebSocket || !window.controlWaveWebSocket.sendRequest) {
this.updateStatus('Waiting for WebSocket...');
return;
}
try {
const response = await window.controlWaveWebSocket.sendRequest(this.id, {
action: 'list_sign_videos'
});
this.populateStage1Videos(response.videos || []);
} catch (error) {
this.outputMeta.textContent = `Failed to refresh stage1 list: ${error.message}`;
}
}
async refreshStage2Videos() {
if (!window.controlWaveWebSocket || !window.controlWaveWebSocket.sendRequest) {
this.updateStatus('Waiting for WebSocket...');
return;
}
try {
const response = await window.controlWaveWebSocket.sendRequest(this.id, {
action: 'list_refine_videos'
});
this.populateStage2Videos(response.videos || []);
} catch (error) {
this.outputMeta.textContent = `Failed to refresh stage2 list: ${error.message}`;
}
}
populateRecentVideos(videos) {
this.videoSelect.innerHTML = '<option value="">Select recently generated video</option>';
videos.forEach(video => {
const option = document.createElement('option');
option.value = video.url;
option.dataset.path = video.path;
option.dataset.size = video.size_mb;
option.textContent = `${video.name} (${video.size_mb} MB)`;
this.videoSelect.appendChild(option);
});
}
populateStage1Videos(videos) {
this.stage1Select.innerHTML = '<option value="">Select stage1 output video</option>';
videos.forEach(video => {
const option = document.createElement('option');
option.value = video.url;
option.dataset.path = video.path;
option.dataset.size = video.size_mb;
option.textContent = `${video.name} (${video.size_mb} MB)`;
this.stage1Select.appendChild(option);
});
}
populateStage2Videos(videos) {
this.stage2Select.innerHTML = '<option value="">Select stage2 output video</option>';
videos.forEach(video => {
const option = document.createElement('option');
option.value = video.url;
option.dataset.path = video.path;
option.dataset.size = video.size_mb;
option.textContent = `${video.name} (${video.size_mb} MB)`;
this.stage2Select.appendChild(option);
});
}
async handleRecentSelection() {
const option = this.videoSelect.selectedOptions[0];
if (!option || !option.value) {
return;
}
this.setSelectedPose(option.dataset.path || option.value);
this.videoMeta.textContent = `${option.dataset.path} • ${option.dataset.size} MB`;
await this.updateVideo(option.value, option.dataset.path);
}
async handleStage1Selection() {
const option = this.stage1Select.selectedOptions[0];
if (!option || !option.value) {
return;
}
this.outputMeta.textContent = `${option.dataset.path} • ${option.dataset.size} MB`;
await this.updateOutputVideo(option.value, option.dataset.path);
}
async handleStage2Selection() {
const option = this.stage2Select.selectedOptions[0];
if (!option || !option.value) {
return;
}
this.outputMeta.textContent = `${option.dataset.path} • ${option.dataset.size} MB`;
await this.updateOutputVideo(option.value, option.dataset.path);
}
updateSelectedLabel(pathOrUrl) {
if (!this.selectedName) return;
if (!pathOrUrl) {
this.selectedName.textContent = 'None';
return;
}
const clean = String(pathOrUrl).split('?')[0];
const parts = clean.split('/');
this.selectedName.textContent = parts[parts.length - 1] || clean;
}
setSelectedPose(pathOrUrl) {
this.selectedPosePath = pathOrUrl;
this.updateSelectedLabel(pathOrUrl);
}
collectRefinePayload() {
return {
poseVideoPath: this.selectedPosePath,
refImagePath: (this.refineRefImageInput.value || this.refImageInput.value || '').trim(),
refCfg: toFloat(this.refineRefCfgInput.value, 2.5),
poseCfg: toFloat(this.refinePoseCfgInput.value, 1.5),
stage1Out: (this.refineStage1OutInput.value || '').trim(),
stage2Out: (this.refineStage2OutInput.value || '').trim(),
gpu: (this.refineGpuInput.value || '').trim(),
};
}
async handleGenerateRefine() {
if (!window.controlWaveWebSocket || !window.controlWaveWebSocket.sendRequest) {
this.updateStatus('WebSocket not ready');
return;
}
const payload = this.collectRefinePayload();
if (!payload.poseVideoPath) {
this.updateStatus('Choose a pose video first');
this.refineLogsPre.textContent = 'Please select a pose video from the list above.';
return;
}
if (this.refineJobId) {
this.updateStatus('Refine already running');
return;
}
this.setRefineLoading(true);
this.updateStatus('Refine running...');
this.refineLogsPre.textContent = 'Starting refine...\n';
try {
const response = await window.controlWaveWebSocket.sendRequest(this.id, {
action: 'generate_refine',
data: payload
});
const status = typeof response.status === 'string' ? response.status.toLowerCase() : '';
if (status === 'running' && response.job_id) {
this.refineJobId = response.job_id;
this.refineLogCursor = 0;
this.startRefineLogPolling();
return;
}
if (status === 'success') {
if (response.logs) {
this.refineLogsPre.textContent = response.logs;
}
if (response.stage2_video_url) {
await this.updateOutputVideo(response.stage2_video_url, response.stage2_video_path);
} else if (response.stage1_video_url) {
await this.updateOutputVideo(response.stage1_video_url, response.stage1_video_path);
}
await Promise.all([this.refreshStage1Videos(), this.refreshStage2Videos()]);
this.updateStatus('Refine completed');
} else {
this.updateStatus('Refine failed');
this.refineLogsPre.textContent = response.message || response.error || response.logs || 'Refine failed';
}
} catch (error) {
this.updateStatus('Refine failed');
this.refineLogsPre.textContent = (error && error.message) ? error.message : 'Refine request failed';
}
this.setRefineLoading(false);
}
startRefineLogPolling() {
this.stopRefineLogPolling();
this.pollRefineStatus();
this.refinePollingTimer = setInterval(() => {
this.pollRefineStatus();
}, 1200);
}
stopRefineLogPolling() {
if (this.refinePollingTimer) {
clearInterval(this.refinePollingTimer);
this.refinePollingTimer = null;
}
}
async pollRefineStatus() {
if (!this.refineJobId) {
return;
}
try {
const response = await window.controlWaveWebSocket.sendRequest(this.id, {
action: 'get_refine_status',
data: {
job_id: this.refineJobId,
last_index: this.refineLogCursor
}
});
if (response.status !== 'success') {
throw new Error(response.message || 'Failed to fetch refine status');
}
if (Array.isArray(response.logs) && response.logs.length > 0) {
this.appendRefineLogs(response.logs);
}
if (typeof response.next_index === 'number') {
this.refineLogCursor = response.next_index;
} else if (response.logs) {
this.refineLogCursor += response.logs.length;
}
const jobStatus = response.job_status;
if (jobStatus === 'success' && response.result) {
const result = response.result;
if (result.stage2_video_url) {
await this.updateOutputVideo(result.stage2_video_url, result.stage2_video_path);
} else if (result.stage1_video_url) {
await this.updateOutputVideo(result.stage1_video_url, result.stage1_video_path);
}
await Promise.all([this.refreshStage1Videos(), this.refreshStage2Videos()]);
this.updateStatus('Refine completed');
this.finishRefineJob();
} else if (jobStatus === 'error') {
const errMsg = response.error_message || 'Refine failed';
this.updateStatus(`Refine failed: ${errMsg}`);
this.finishRefineJob();
} else if (jobStatus === 'running') {
this.updateStatus('Refine running...');
}
} catch (error) {
this.updateStatus(`Refine polling failed: ${error.message}`);
this.finishRefineJob();
}
}
appendRefineLogs(newLines) {
if (!this.refineLogsPre || !newLines) {
return;
}
const text = Array.isArray(newLines) ? newLines.join('\n') : newLines;
if (!text) {
return;
}
if (!this.refineLogsPre.textContent || this.refineLogsPre.textContent === '(waiting for refine...)') {
this.refineLogsPre.textContent = '';
}
if (this.refineLogsPre.textContent && !this.refineLogsPre.textContent.endsWith('\n')) {
this.refineLogsPre.textContent += '\n';
}
this.refineLogsPre.textContent += text + '\n';
this.refineLogsPre.scrollTop = this.refineLogsPre.scrollHeight;
}
finishRefineJob() {
this.stopRefineLogPolling();
this.refineJobId = null;
this.setRefineLoading(false);
}
async updateOutputVideo(url, path) {
if (!url || !this.outputVideoEl) return;
const absoluteUrl = url.startsWith('http') ? url : `${window.location.origin}${url}`;
const hasQuery = absoluteUrl.includes('?');
const fetchUrl = `${absoluteUrl}${hasQuery ? '&' : '?'}t=${Date.now()}`;
const resetVideoEl = () => {
this.outputVideoEl.onloadeddata = null;
this.outputVideoEl.onerror = null;
this.outputVideoEl.pause();
this.outputVideoEl.removeAttribute('src');
this.outputVideoEl.load();
};
this.outputPlaceholder.style.display = 'flex';
this.outputPlaceholder.textContent = 'Loading video…';
this.outputVideoEl.style.display = 'none';
resetVideoEl();
if (this.refineVideoObjectUrl) {
URL.revokeObjectURL(this.refineVideoObjectUrl);
this.refineVideoObjectUrl = null;
}
try {
const response = await fetch(fetchUrl, { cache: 'no-store' });
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const blob = await response.blob();
const objectUrl = URL.createObjectURL(blob);
this.refineVideoObjectUrl = objectUrl;
this.outputVideoEl.onloadeddata = () => {
this.outputVideoEl.onloadeddata = null;
this.outputVideoEl.onerror = null;
this.outputPlaceholder.style.display = 'none';
this.outputVideoEl.style.display = 'block';
const playPromise = this.outputVideoEl.play();
if (playPromise && typeof playPromise.catch === 'function') {
playPromise.catch(() => {});
}
this.outputMeta.textContent = `Video: ${path || absoluteUrl}`;
};
this.outputVideoEl.onerror = () => {
this.outputVideoEl.onloadeddata = null;
this.outputVideoEl.onerror = null;
this.outputPlaceholder.style.display = 'flex';
this.outputPlaceholder.textContent = 'Video load failed';
const mediaError = this.outputVideoEl.error;
console.error('[StableSigner] output video load error', mediaError ? {
code: mediaError.code,
message: mediaError.message
} : 'unknown');
};
this.outputVideoEl.src = objectUrl;
this.outputVideoEl.load();
} catch (error) {
resetVideoEl();
this.outputPlaceholder.style.display = 'flex';
this.outputPlaceholder.textContent = 'Video load failed';
console.error('[StableSigner] output video fetch failed', error);
}
}
setRefineLoading(isLoading) {
if (!this.generateRefineBtn) return;
this.generateRefineBtn.disabled = isLoading;
this.generateRefineBtn.textContent = isLoading ? 'Generating...' : 'Generate Refine Video';
}
setLoading(isLoading) {
this.generateBtn.disabled = isLoading;
this.generateBtn.textContent = isLoading ? 'Generating...' : 'Generate Pose Video';
}
setPrewarmLoading(isLoading) {
if (!this.prewarmBtn) return;
this.prewarmBtn.disabled = isLoading;
this.prewarmBtn.textContent = isLoading ? 'Prewarming...' : 'Prewarm';
}
setTranslateLoading(isLoading) {
if (!this.translateBtn) return;
this.translateBtn.disabled = isLoading;
this.translateBtn.textContent = isLoading ? 'Translating...' : 'Translate Prompt → Gloss';
}
updateStatus(text) {
this.statusChip.textContent = text;
}
}