FangSen9000 commited on
Commit
98cf86d
·
1 Parent(s): 806c397

Add streaming text-to-pose preview

Browse files
index.js CHANGED
@@ -74,6 +74,27 @@ function ensureStyles() {
74
  min-width: 0;
75
  width: 100%;
76
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  .stable-video-frame {
78
  position: relative;
79
  width: 100%;
@@ -298,6 +319,168 @@ function ensureStyles() {
298
  font-size: 12px;
299
  color: #475569;
300
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
301
  @media (max-width: 1200px) {
302
  .stable-signer-root {
303
  grid-template-columns: 1fr;
@@ -444,7 +627,7 @@ export default class StableSignerPlugin extends ControlWavePlugin {
444
  <div class="stable-control-header">
445
  <div class="stable-control-actions">
446
  <button id="stable-prewarm" class="btn secondary">Prewarm</button>
447
- <button id="stable-translate" class="btn secondary">Translate Prompt → Gloss</button>
448
  </div>
449
  <span class="stable-status-chip" id="stable-status">Idle</span>
450
  </div>
@@ -566,6 +749,49 @@ export default class StableSignerPlugin extends ControlWavePlugin {
566
  <pre id="stable-logs">(waiting for task...)</pre>
567
  </div>
568
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
569
  </div>
570
  `;
571
  }
@@ -594,6 +820,23 @@ export default class StableSignerPlugin extends ControlWavePlugin {
594
  this.refineLogsPre = container.querySelector('#stable-refine-logs');
595
  this.prewarmBtn = container.querySelector('#stable-prewarm');
596
  this.translateBtn = container.querySelector('#stable-translate');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
597
  this.generateBtn = container.querySelector('#stable-generate');
598
  this.statusChip = container.querySelector('#stable-status');
599
  this.promptTextInput = container.querySelector('#stable-prompt-text');
@@ -634,6 +877,16 @@ export default class StableSignerPlugin extends ControlWavePlugin {
634
  this.stage2RefreshBtn.addEventListener('click', () => this.refreshStage2Videos());
635
  this.stage1Select.addEventListener('change', () => this.handleStage1Selection());
636
  this.stage2Select.addEventListener('change', () => this.handleStage2Selection());
 
 
 
 
 
 
 
 
 
 
637
 
638
  window.addEventListener('websocket-connected', () => {
639
  this.updateStatus('WebSocket connected');
@@ -671,7 +924,8 @@ export default class StableSignerPlugin extends ControlWavePlugin {
671
  maxNewTokens: toInt(this.maxNewTokensInput.value, 64),
672
  refImagePath: this.refImageInput.value,
673
  normalizePose: this.normalizeCheckbox.checked,
674
- hideTorsoLines: this.hideTorsoCheckbox.checked
 
675
  };
676
  }
677
 
@@ -802,7 +1056,7 @@ export default class StableSignerPlugin extends ControlWavePlugin {
802
  }
803
  const payloadPrompt = originalPrompt || promptText;
804
  const response = await window.controlWaveWebSocket.sendRequest(this.id, {
805
- action: 'prompt_to_gloss',
806
  data: {
807
  text: promptText,
808
  prompt: payloadPrompt,
@@ -812,9 +1066,173 @@ export default class StableSignerPlugin extends ControlWavePlugin {
812
  if (!response || response.status !== 'success' || !response.gloss) {
813
  throw new Error(response?.message || 'Gloss translation failed');
814
  }
 
 
 
815
  return response.gloss;
816
  }
817
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
818
  async updateVideo(url, path) {
819
  if (!url || !this.videoEl) return;
820
  const absoluteUrl = url.startsWith('http') ? url : `${window.location.origin}${url}`;
@@ -880,6 +1298,20 @@ export default class StableSignerPlugin extends ControlWavePlugin {
880
 
881
  this.videoEl.src = objectUrl;
882
  this.videoEl.load();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
883
  } catch (error) {
884
  resetVideoEl();
885
  this.videoPlaceholder.style.display = 'flex';
 
74
  min-width: 0;
75
  width: 100%;
76
  }
77
+ .stable-text-playground {
78
+ grid-column: 1 / -1;
79
+ min-width: 0;
80
+ }
81
+ .stable-text-playground .stable-reading-area {
82
+ min-height: 180px;
83
+ font-size: 16px;
84
+ line-height: 1.65;
85
+ }
86
+ .stable-text-playground-title {
87
+ display: flex;
88
+ align-items: center;
89
+ justify-content: space-between;
90
+ gap: 12px;
91
+ margin-bottom: 10px;
92
+ }
93
+ .stable-text-playground-title h3 {
94
+ margin: 0;
95
+ font-size: 16px;
96
+ color: #0f172a;
97
+ }
98
  .stable-video-frame {
99
  position: relative;
100
  width: 100%;
 
319
  font-size: 12px;
320
  color: #475569;
321
  }
322
+ .stable-reading-area {
323
+ min-height: 120px;
324
+ border: 1px solid #cbd5f5;
325
+ border-radius: 8px;
326
+ padding: 12px;
327
+ background: #f8fafc;
328
+ color: #0f172a;
329
+ line-height: 1.55;
330
+ font-size: 14px;
331
+ user-select: text;
332
+ }
333
+ .stable-reading-area:focus {
334
+ outline: none;
335
+ border-color: #6366f1;
336
+ box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
337
+ }
338
+
339
+ .stable-dialogue-area {
340
+ min-height: 360px;
341
+ border: 1px solid #d7b98a;
342
+ border-radius: 10px;
343
+ padding: 18px;
344
+ background:
345
+ linear-gradient(135deg, rgba(255, 255, 255, 0.58), rgba(255, 248, 236, 0.2)),
346
+ repeating-linear-gradient(90deg, #f5e3c4 0, #f5e3c4 18px, #efd6ad 19px, #efd6ad 36px);
347
+ color: #2f2417;
348
+ line-height: 1.62;
349
+ font-size: 15px;
350
+ user-select: text;
351
+ box-shadow: inset 0 1px 0 rgba(255,255,255,0.55);
352
+ }
353
+ .stable-dialogue-turn {
354
+ max-width: 82%;
355
+ margin: 12px 0;
356
+ padding: 14px 16px;
357
+ border-radius: 12px;
358
+ box-shadow: 0 4px 12px rgba(74, 53, 28, 0.12);
359
+ white-space: normal;
360
+ }
361
+ .stable-dialogue-turn.question {
362
+ margin-left: auto;
363
+ background: rgba(255, 255, 255, 0.82);
364
+ border: 1px solid rgba(185, 139, 73, 0.38);
365
+ }
366
+ .stable-dialogue-turn.answer {
367
+ margin-right: auto;
368
+ background: rgba(255, 250, 240, 0.9);
369
+ border: 1px solid rgba(161, 113, 48, 0.42);
370
+ }
371
+ .stable-dialogue-speaker {
372
+ display: inline-block;
373
+ margin-bottom: 8px;
374
+ padding: 3px 8px;
375
+ border-radius: 999px;
376
+ background: #8b5e2e;
377
+ color: #fff8ed;
378
+ font-size: 12px;
379
+ font-weight: 700;
380
+ }
381
+ .stable-dialogue-turn p {
382
+ margin: 8px 0;
383
+ }
384
+ .stable-dialogue-turn ul {
385
+ margin: 8px 0 8px 20px;
386
+ padding: 0;
387
+ }
388
+ .stable-dialogue-turn li {
389
+ margin: 4px 0;
390
+ }
391
+ .stable-selection-popover {
392
+ position: fixed;
393
+ right: 22px;
394
+ bottom: 22px;
395
+ z-index: 9999;
396
+ display: none;
397
+ width: min(380px, calc(100vw - 44px));
398
+ border-radius: 12px;
399
+ background: #0f172a;
400
+ color: #e2e8f0;
401
+ box-shadow: 0 18px 40px rgba(15, 23, 42, 0.35);
402
+ overflow: hidden;
403
+ }
404
+ .stable-selection-header {
405
+ display: flex;
406
+ align-items: center;
407
+ justify-content: space-between;
408
+ gap: 10px;
409
+ padding: 10px 12px;
410
+ border-bottom: 1px solid rgba(148, 163, 184, 0.25);
411
+ font-size: 13px;
412
+ font-weight: 700;
413
+ }
414
+ .stable-selection-header button,
415
+ .stable-selection-actions button {
416
+ border: none;
417
+ border-radius: 8px;
418
+ padding: 7px 10px;
419
+ font-size: 12px;
420
+ font-weight: 700;
421
+ cursor: pointer;
422
+ background: #e2e8f0;
423
+ color: #0f172a;
424
+ }
425
+ .stable-selection-body {
426
+ padding: 12px;
427
+ display: flex;
428
+ flex-direction: column;
429
+ gap: 10px;
430
+ }
431
+ .stable-selection-text {
432
+ max-height: 66px;
433
+ overflow: auto;
434
+ color: #cbd5e1;
435
+ font-size: 12px;
436
+ line-height: 1.45;
437
+ border-left: 3px solid #6366f1;
438
+ padding-left: 8px;
439
+ }
440
+ .stable-mini-video-frame {
441
+ position: relative;
442
+ width: 100%;
443
+ aspect-ratio: 1 / 1;
444
+ background: #020617;
445
+ border-radius: 8px;
446
+ overflow: hidden;
447
+ }
448
+ .stable-mini-video-frame video,
449
+ .stable-mini-video-frame canvas {
450
+ position: absolute;
451
+ inset: 0;
452
+ width: 100%;
453
+ height: 100%;
454
+ object-fit: contain;
455
+ background: #020617;
456
+ }
457
+ .stable-mini-video-frame canvas {
458
+ display: none;
459
+ }
460
+ .stable-mini-placeholder {
461
+ position: absolute;
462
+ inset: 0;
463
+ display: flex;
464
+ align-items: center;
465
+ justify-content: center;
466
+ color: #94a3b8;
467
+ font-size: 13px;
468
+ text-align: center;
469
+ padding: 16px;
470
+ }
471
+ .stable-selection-status {
472
+ min-height: 18px;
473
+ color: #cbd5e1;
474
+ font-size: 12px;
475
+ overflow-wrap: anywhere;
476
+ }
477
+ .stable-selection-actions {
478
+ display: flex;
479
+ gap: 8px;
480
+ }
481
+ .stable-selection-actions button {
482
+ flex: 1;
483
+ }
484
  @media (max-width: 1200px) {
485
  .stable-signer-root {
486
  grid-template-columns: 1fr;
 
627
  <div class="stable-control-header">
628
  <div class="stable-control-actions">
629
  <button id="stable-prewarm" class="btn secondary">Prewarm</button>
630
+ <button id="stable-translate" class="btn secondary">Text → Available Gloss</button>
631
  </div>
632
  <span class="stable-status-chip" id="stable-status">Idle</span>
633
  </div>
 
749
  <pre id="stable-logs">(waiting for task...)</pre>
750
  </div>
751
  </div>
752
+ <div class="stable-text-playground stable-signer-panel">
753
+ <div class="stable-text-playground-title">
754
+ <h3>Selection Translation Playground</h3>
755
+ <span class="stable-status-chip">Select text to translate</span>
756
+ </div>
757
+ <div id="stable-selection-template" class="stable-reading-area stable-dialogue-area" tabindex="0" contenteditable="true">
758
+ <div class="stable-dialogue-turn question">
759
+ <span class="stable-dialogue-speaker">User</span>
760
+ <p>Do native signers have difficulty reading written text?</p>
761
+ </div>
762
+ <div class="stable-dialogue-turn answer">
763
+ <span class="stable-dialogue-speaker">Assistant</span>
764
+ <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>
765
+ </div>
766
+ <div class="stable-dialogue-turn question">
767
+ <span class="stable-dialogue-speaker">User</span>
768
+ <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>
769
+ </div>
770
+ <div class="stable-dialogue-turn answer">
771
+ <span class="stable-dialogue-speaker">Assistant</span>
772
+ <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>
773
+ </div>
774
+ </div>
775
+ <div id="stable-selection-popover" class="stable-selection-popover">
776
+ <div class="stable-selection-header">
777
+ <span>Sign Translation</span>
778
+ <button id="stable-selection-close" type="button">Close</button>
779
+ </div>
780
+ <div class="stable-selection-body">
781
+ <div id="stable-selection-text" class="stable-selection-text"></div>
782
+ <div class="stable-mini-video-frame">
783
+ <video id="stable-selection-video" controls playsinline loop muted></video>
784
+ <canvas id="stable-selection-canvas" width="512" height="512"></canvas>
785
+ <div id="stable-selection-placeholder" class="stable-mini-placeholder">Select English text to generate a sign pose video.</div>
786
+ </div>
787
+ <div id="stable-selection-status" class="stable-selection-status">Waiting for selection...</div>
788
+ <div class="stable-selection-actions">
789
+ <button id="stable-selection-translate" type="button">Regenerate</button>
790
+ </div>
791
+ </div>
792
+ </div>
793
+ <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>
794
+ </div>
795
  </div>
796
  `;
797
  }
 
820
  this.refineLogsPre = container.querySelector('#stable-refine-logs');
821
  this.prewarmBtn = container.querySelector('#stable-prewarm');
822
  this.translateBtn = container.querySelector('#stable-translate');
823
+ this.selectionTemplate = container.querySelector('#stable-selection-template');
824
+ this.selectionPopover = container.querySelector('#stable-selection-popover');
825
+ this.selectionTranslateBtn = container.querySelector('#stable-selection-translate');
826
+ this.selectionCloseBtn = container.querySelector('#stable-selection-close');
827
+ this.selectionTextEl = container.querySelector('#stable-selection-text');
828
+ this.selectionVideoEl = container.querySelector('#stable-selection-video');
829
+ this.selectionCanvas = container.querySelector('#stable-selection-canvas');
830
+ this.selectionCanvasCtx = this.selectionCanvas ? this.selectionCanvas.getContext('2d') : null;
831
+ this.selectionHasFrame = false;
832
+ this.selectionPlaceholder = container.querySelector('#stable-selection-placeholder');
833
+ this.selectionStatus = container.querySelector('#stable-selection-status');
834
+ this.selectedTemplateText = '';
835
+ this.selectionGenerationTimer = null;
836
+ this.selectionGenerationInFlight = false;
837
+ this.selectionStreamPollingTimer = null;
838
+ this.selectionStreamCursor = 0;
839
+ this.lastGeneratedSelection = '';
840
  this.generateBtn = container.querySelector('#stable-generate');
841
  this.statusChip = container.querySelector('#stable-status');
842
  this.promptTextInput = container.querySelector('#stable-prompt-text');
 
877
  this.stage2RefreshBtn.addEventListener('click', () => this.refreshStage2Videos());
878
  this.stage1Select.addEventListener('change', () => this.handleStage1Selection());
879
  this.stage2Select.addEventListener('change', () => this.handleStage2Selection());
880
+ if (this.selectionTemplate) {
881
+ this.selectionTemplate.addEventListener('mouseup', () => this.handleTemplateSelection());
882
+ this.selectionTemplate.addEventListener('keyup', () => this.handleTemplateSelection());
883
+ }
884
+ if (this.selectionTranslateBtn) {
885
+ this.selectionTranslateBtn.addEventListener('click', () => this.handleSelectedTextGenerate(true));
886
+ }
887
+ if (this.selectionCloseBtn) {
888
+ this.selectionCloseBtn.addEventListener('click', () => this.hideSelectionPopover());
889
+ }
890
 
891
  window.addEventListener('websocket-connected', () => {
892
  this.updateStatus('WebSocket connected');
 
924
  maxNewTokens: toInt(this.maxNewTokensInput.value, 64),
925
  refImagePath: this.refImageInput.value,
926
  normalizePose: this.normalizeCheckbox.checked,
927
+ hideTorsoLines: this.hideTorsoCheckbox.checked,
928
+ translationMode: 'text2gloss'
929
  };
930
  }
931
 
 
1056
  }
1057
  const payloadPrompt = originalPrompt || promptText;
1058
  const response = await window.controlWaveWebSocket.sendRequest(this.id, {
1059
+ action: 'text_to_gloss',
1060
  data: {
1061
  text: promptText,
1062
  prompt: payloadPrompt,
 
1066
  if (!response || response.status !== 'success' || !response.gloss) {
1067
  throw new Error(response?.message || 'Gloss translation failed');
1068
  }
1069
+ if (response.dropped && response.dropped.length > 0) {
1070
+ console.info('[StableSigner] dropped non-renderable text tokens', response.dropped);
1071
+ }
1072
  return response.gloss;
1073
  }
1074
 
1075
+ handleTemplateSelection() {
1076
+ if (!this.selectionTemplate || !this.selectionPopover) return;
1077
+ const selection = window.getSelection();
1078
+ const selectedText = selection ? selection.toString().replace(/\s+/g, ' ').trim() : '';
1079
+ if (!selectedText || selectedText.length < 2) {
1080
+ return;
1081
+ }
1082
+ const range = selection.rangeCount > 0 ? selection.getRangeAt(0) : null;
1083
+ if (!range || !this.selectionTemplate.contains(range.commonAncestorContainer)) {
1084
+ return;
1085
+ }
1086
+ this.selectedTemplateText = selectedText;
1087
+ if (this.selectionTextEl) {
1088
+ this.selectionTextEl.textContent = selectedText;
1089
+ }
1090
+ if (this.selectionStatus) {
1091
+ this.selectionStatus.textContent = 'Preparing translation...';
1092
+ }
1093
+ if (this.selectionPopover) {
1094
+ this.selectionPopover.style.display = 'block';
1095
+ }
1096
+ if (this.selectionGenerationTimer) {
1097
+ clearTimeout(this.selectionGenerationTimer);
1098
+ }
1099
+ this.selectionGenerationTimer = setTimeout(() => this.handleSelectedTextGenerate(false), 450);
1100
+ }
1101
+
1102
+ hideSelectionPopover() {
1103
+ if (this.selectionGenerationTimer) {
1104
+ clearTimeout(this.selectionGenerationTimer);
1105
+ this.selectionGenerationTimer = null;
1106
+ }
1107
+ if (this.selectionPopover) {
1108
+ this.selectionPopover.style.display = 'none';
1109
+ }
1110
+ }
1111
+
1112
+ async handleSelectedTextGenerate(force = false) {
1113
+ const text = (this.selectedTemplateText || '').trim();
1114
+ if (!text || this.selectionGenerationInFlight) return;
1115
+ if (!force && text === this.lastGeneratedSelection) return;
1116
+ this.selectionGenerationInFlight = true;
1117
+ this.lastGeneratedSelection = text;
1118
+ this.promptTextInput.value = text;
1119
+ this.glossInput.value = '';
1120
+ this.logsPre.textContent = 'Selected text:\n' + text + '\n\nStreaming pose preview...';
1121
+ if (this.selectionStatus) {
1122
+ this.selectionStatus.textContent = 'Preparing pose preview...';
1123
+ }
1124
+ if (this.selectionPlaceholder && !this.selectionHasFrame) {
1125
+ this.selectionPlaceholder.style.display = 'none';
1126
+ }
1127
+ if (this.selectionVideoEl) {
1128
+ this.selectionVideoEl.style.display = 'none';
1129
+ this.selectionVideoEl.removeAttribute('src');
1130
+ this.selectionVideoEl.load();
1131
+ }
1132
+ try {
1133
+ await this.handleGenerateStream();
1134
+ } catch (error) {
1135
+ if (this.selectionStatus) {
1136
+ this.selectionStatus.textContent = (error && error.message) ? error.message : 'Stream failed';
1137
+ }
1138
+ this.selectionGenerationInFlight = false;
1139
+ }
1140
+ }
1141
+
1142
+ async handleGenerateStream() {
1143
+ if (!window.controlWaveWebSocket || !window.controlWaveWebSocket.sendRequest) {
1144
+ throw new Error('WebSocket not ready');
1145
+ }
1146
+ const payload = this.collectPayload();
1147
+ payload.maxNewTokens = Math.min(toInt(this.maxNewTokensInput.value, 64), 18);
1148
+ payload.maxCandidates = Math.min(toInt(this.maxCandidatesInput.value, 10), 3);
1149
+ const response = await window.controlWaveWebSocket.sendRequest(this.id, {
1150
+ action: 'generate_pose_stream',
1151
+ data: payload
1152
+ });
1153
+ if (!response || response.status !== 'running' || !response.job_id) {
1154
+ throw new Error(response?.message || 'Stream generation failed');
1155
+ }
1156
+ if (response.gloss) {
1157
+ this.glossInput.value = response.gloss;
1158
+ }
1159
+ this.selectionStreamCursor = 0;
1160
+ if (this.selectionStreamPollingTimer) {
1161
+ clearTimeout(this.selectionStreamPollingTimer);
1162
+ }
1163
+ this.pollPoseStream(response.job_id);
1164
+ }
1165
+
1166
+ drawStreamFrameToCanvas(dataUrl) {
1167
+ const image = new Image();
1168
+ image.onload = () => {
1169
+ if (!this.selectionCanvas || !this.selectionCanvasCtx) return;
1170
+ if (this.selectionCanvas.width !== image.naturalWidth) {
1171
+ this.selectionCanvas.width = image.naturalWidth;
1172
+ }
1173
+ if (this.selectionCanvas.height !== image.naturalHeight) {
1174
+ this.selectionCanvas.height = image.naturalHeight;
1175
+ }
1176
+ this.selectionCanvasCtx.drawImage(image, 0, 0, this.selectionCanvas.width, this.selectionCanvas.height);
1177
+ this.selectionCanvas.style.display = 'block';
1178
+ this.selectionHasFrame = true;
1179
+ if (this.selectionPlaceholder) {
1180
+ this.selectionPlaceholder.style.display = 'none';
1181
+ }
1182
+ };
1183
+ image.src = dataUrl;
1184
+ }
1185
+
1186
+ async pollPoseStream(jobId) {
1187
+ try {
1188
+ const response = await window.controlWaveWebSocket.sendRequest(this.id, {
1189
+ action: 'get_pose_stream_status',
1190
+ data: {
1191
+ jobId,
1192
+ cursor: this.selectionStreamCursor
1193
+ }
1194
+ });
1195
+ if (!response || response.status === 'error') {
1196
+ throw new Error(response?.message || 'Stream polling failed');
1197
+ }
1198
+ const frames = response.frames || [];
1199
+ if (frames.length > 0) {
1200
+ const latest = frames[frames.length - 1];
1201
+ if (this.selectionCanvas && this.selectionCanvasCtx && latest.image) {
1202
+ this.drawStreamFrameToCanvas(latest.image);
1203
+ }
1204
+ if (this.selectionPlaceholder) {
1205
+ this.selectionPlaceholder.style.display = 'none';
1206
+ }
1207
+ this.selectionStreamCursor = response.cursor || (this.selectionStreamCursor + frames.length);
1208
+ }
1209
+ if (this.selectionStatus) {
1210
+ const total = response.total_frames ? ` / ${response.total_frames}` : '';
1211
+ this.selectionStatus.textContent = `Gloss: ${(response.gloss || this.glossInput.value || '').trim()} · ${response.frame_count || this.selectionStreamCursor}${total} frames`;
1212
+ }
1213
+ if (response.status === 'running') {
1214
+ this.selectionStreamPollingTimer = setTimeout(() => this.pollPoseStream(jobId), 180);
1215
+ return;
1216
+ }
1217
+ this.selectionGenerationInFlight = false;
1218
+ if (response.logs) {
1219
+ this.logsPre.textContent = response.logs;
1220
+ }
1221
+ if (response.video_url) {
1222
+ await this.updateVideo(response.video_url, response.video_path);
1223
+ await this.refreshRecentVideos();
1224
+ }
1225
+ if (this.selectionStatus && response.status === 'success') {
1226
+ this.selectionStatus.textContent = `Gloss: ${(response.gloss || this.glossInput.value || '').trim()} · completed`;
1227
+ }
1228
+ } catch (error) {
1229
+ // Keep the last displayed frame. Short polling gaps should not be visible to users.
1230
+ if (this.selectionGenerationInFlight) {
1231
+ this.selectionStreamPollingTimer = setTimeout(() => this.pollPoseStream(jobId), 500);
1232
+ }
1233
+ }
1234
+ }
1235
+
1236
  async updateVideo(url, path) {
1237
  if (!url || !this.videoEl) return;
1238
  const absoluteUrl = url.startsWith('http') ? url : `${window.location.origin}${url}`;
 
1298
 
1299
  this.videoEl.src = objectUrl;
1300
  this.videoEl.load();
1301
+
1302
+ if (this.selectionVideoEl && this.selectionPopover && this.selectionPopover.style.display !== 'none') {
1303
+ this.selectionVideoEl.pause();
1304
+ this.selectionVideoEl.src = objectUrl;
1305
+ this.selectionVideoEl.style.display = 'block';
1306
+ this.selectionVideoEl.load();
1307
+ if (this.selectionPlaceholder) {
1308
+ this.selectionPlaceholder.style.display = 'none';
1309
+ }
1310
+ const miniPlayPromise = this.selectionVideoEl.play();
1311
+ if (miniPlayPromise && typeof miniPlayPromise.catch === 'function') {
1312
+ miniPlayPromise.catch(() => {});
1313
+ }
1314
+ }
1315
  } catch (error) {
1316
  resetVideoEl();
1317
  this.videoPlaceholder.style.display = 'flex';
pipeline01_text2gloss.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Constrained English text -> available gloss translation for StableSigner.
3
+
4
+ This is the browser-panel fallback path: it only emits gloss tokens that exist
5
+ in the local pose dictionary, so gloss2pose can render the result immediately.
6
+ It is intentionally conservative and can later be replaced by a trained
7
+ text-to-gloss model with the same public functions.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import json
14
+ import re
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+ from typing import Dict, Iterable, List, Optional, Sequence, Set, Tuple
18
+
19
+
20
+ BASE_DIR = Path(__file__).resolve().parent
21
+ DEFAULT_POSE_DICT = BASE_DIR / "pose_dict" / "WLASL_train.json"
22
+
23
+
24
+ STOP_WORDS = {
25
+ "A",
26
+ "AN",
27
+ "THE",
28
+ "AM",
29
+ "ARE",
30
+ "IS",
31
+ "WAS",
32
+ "WERE",
33
+ "BE",
34
+ "BEEN",
35
+ "BEING",
36
+ "DO",
37
+ "DOES",
38
+ "DID",
39
+ "TO",
40
+ "OF",
41
+ "FOR",
42
+ "WITH",
43
+ "AND",
44
+ "OR",
45
+ "BUT",
46
+ "THAT",
47
+ "THIS",
48
+ "THESE",
49
+ "THOSE",
50
+ "IT",
51
+ "ITS",
52
+ "JUST",
53
+ "VERY",
54
+ "REALLY",
55
+ }
56
+
57
+
58
+ LEMMA_OVERRIDES = {
59
+ "ME": "I",
60
+ "MINE": "MY",
61
+ "MYSELF": "I",
62
+ "YOURSELF": "YOU",
63
+ "YOUR": "YOU",
64
+ "YOURS": "YOU",
65
+ "HIS": "HE",
66
+ "HIM": "HE",
67
+ "HER": "SHE",
68
+ "HERS": "SHE",
69
+ "THEIR": "THEY",
70
+ "THEM": "THEY",
71
+ "OUR": "WE",
72
+ "US": "WE",
73
+ "WENT": "GO",
74
+ "GONE": "GO",
75
+ "GOING": "GO",
76
+ "CAME": "COME",
77
+ "COMING": "COME",
78
+ "MADE": "MAKE",
79
+ "MAKING": "MAKE",
80
+ "SAID": "SAY",
81
+ "SAYING": "SAY",
82
+ "SAW": "SEE",
83
+ "SEEN": "SEE",
84
+ "SEEING": "SEE",
85
+ "LOOKING": "LOOK",
86
+ "LIKED": "LIKE",
87
+ "LIKES": "LIKE",
88
+ "WANTED": "WANT",
89
+ "WANTS": "WANT",
90
+ "NEEDED": "NEED",
91
+ "NEEDS": "NEED",
92
+ "HELPED": "HELP",
93
+ "HELPS": "HELP",
94
+ "LEARNED": "LEARN",
95
+ "LEARNING": "LEARN",
96
+ "SIGNED": "SIGN",
97
+ "SIGNING": "SIGN",
98
+ "THANKS": "THANK",
99
+ }
100
+
101
+
102
+ PHRASE_MAP = {
103
+ "GOOD MORNING": ["GOOD", "MORNING"],
104
+ "GOOD AFTERNOON": ["GOOD", "AFTERNOON"],
105
+ "GOOD NIGHT": ["GOOD", "NIGHT"],
106
+ "THANK YOU": ["THANK", "YOU"],
107
+ "SIGN LANGUAGE": ["SIGN", "LANGUAGE"],
108
+ }
109
+
110
+
111
+ @dataclass
112
+ class TextToGlossResult:
113
+ gloss: str
114
+ tokens: List[str]
115
+ matched: List[Tuple[str, str]]
116
+ dropped: List[str]
117
+
118
+
119
+ def load_available_glosses(path: Path | str = DEFAULT_POSE_DICT) -> Set[str]:
120
+ """Load uppercase gloss vocabulary from WLASL-style pose dictionary JSON."""
121
+ pose_path = Path(path)
122
+ with pose_path.open("r", encoding="utf-8") as handle:
123
+ data = json.load(handle)
124
+ glosses = set()
125
+ for item in data:
126
+ gloss = str(item.get("gloss", "")).strip().upper()
127
+ if gloss:
128
+ glosses.add(gloss)
129
+ return glosses
130
+
131
+
132
+ def tokenize_english(text: str) -> List[str]:
133
+ text = text.replace("'", "")
134
+ return [token.upper() for token in re.findall(r"[A-Za-z0-9]+", text)]
135
+
136
+
137
+ def _simple_lemma(token: str) -> List[str]:
138
+ candidates = [token]
139
+ if token in LEMMA_OVERRIDES:
140
+ candidates.append(LEMMA_OVERRIDES[token])
141
+ if len(token) > 4 and token.endswith("IES"):
142
+ candidates.append(token[:-3] + "Y")
143
+ if len(token) > 4 and token.endswith("ING"):
144
+ candidates.append(token[:-3])
145
+ if len(token) > 5:
146
+ candidates.append(token[:-4])
147
+ if len(token) > 3 and token.endswith("ED"):
148
+ candidates.append(token[:-2])
149
+ candidates.append(token[:-1])
150
+ if len(token) > 3 and token.endswith("ES"):
151
+ candidates.append(token[:-2])
152
+ if len(token) > 2 and token.endswith("S"):
153
+ candidates.append(token[:-1])
154
+
155
+ deduped = []
156
+ seen = set()
157
+ for candidate in candidates:
158
+ if candidate and candidate not in seen:
159
+ deduped.append(candidate)
160
+ seen.add(candidate)
161
+ return deduped
162
+
163
+
164
+ def _best_vocab_match(token: str, vocab: Set[str]) -> Optional[str]:
165
+ for candidate in _simple_lemma(token):
166
+ if candidate in vocab:
167
+ return candidate
168
+ return None
169
+
170
+
171
+ def _apply_phrase_map(tokens: Sequence[str], vocab: Set[str]) -> Tuple[List[str], List[Tuple[str, str]]]:
172
+ output: List[str] = []
173
+ matched: List[Tuple[str, str]] = []
174
+ i = 0
175
+ while i < len(tokens):
176
+ consumed = False
177
+ for phrase, gloss_tokens in PHRASE_MAP.items():
178
+ phrase_tokens = phrase.split()
179
+ if list(tokens[i : i + len(phrase_tokens)]) != phrase_tokens:
180
+ continue
181
+ available = [gloss for gloss in gloss_tokens if gloss in vocab]
182
+ if available:
183
+ output.extend(available)
184
+ matched.append((phrase, " ".join(available)))
185
+ i += len(phrase_tokens)
186
+ consumed = True
187
+ break
188
+ if not consumed:
189
+ output.append(tokens[i])
190
+ i += 1
191
+ return output, matched
192
+
193
+
194
+ def translate_text_to_gloss(
195
+ text: str,
196
+ vocab: Optional[Iterable[str]] = None,
197
+ max_tokens: int = 64,
198
+ ) -> TextToGlossResult:
199
+ """Translate English text into a renderable uppercase gloss sequence."""
200
+ vocab_set = {item.upper() for item in vocab} if vocab is not None else load_available_glosses()
201
+ raw_tokens = tokenize_english(text)
202
+ phrase_tokens, phrase_matches = _apply_phrase_map(raw_tokens, vocab_set)
203
+
204
+ gloss_tokens: List[str] = []
205
+ matched: List[Tuple[str, str]] = list(phrase_matches)
206
+ dropped: List[str] = []
207
+
208
+ for token in phrase_tokens:
209
+ if len(gloss_tokens) >= max_tokens:
210
+ break
211
+ if token in STOP_WORDS:
212
+ dropped.append(token)
213
+ continue
214
+ gloss = _best_vocab_match(token, vocab_set)
215
+ if gloss:
216
+ gloss_tokens.append(gloss)
217
+ if token != gloss:
218
+ matched.append((token, gloss))
219
+ else:
220
+ dropped.append(token)
221
+
222
+ return TextToGlossResult(
223
+ gloss=" ".join(gloss_tokens),
224
+ tokens=gloss_tokens,
225
+ matched=matched,
226
+ dropped=dropped,
227
+ )
228
+
229
+
230
+ def main() -> None:
231
+ parser = argparse.ArgumentParser(description="Constrained English text to StableSigner gloss.")
232
+ parser.add_argument("text", help="English text to translate.")
233
+ parser.add_argument("--pose-dict", default=str(DEFAULT_POSE_DICT), help="WLASL-style pose dictionary JSON.")
234
+ parser.add_argument("--max-tokens", type=int, default=64)
235
+ parser.add_argument("--json", action="store_true", help="Print structured JSON instead of only gloss.")
236
+ args = parser.parse_args()
237
+
238
+ vocab = load_available_glosses(args.pose_dict)
239
+ result = translate_text_to_gloss(args.text, vocab=vocab, max_tokens=args.max_tokens)
240
+ if args.json:
241
+ print(
242
+ json.dumps(
243
+ {
244
+ "gloss": result.gloss,
245
+ "tokens": result.tokens,
246
+ "matched": result.matched,
247
+ "dropped": result.dropped,
248
+ },
249
+ ensure_ascii=True,
250
+ indent=2,
251
+ )
252
+ )
253
+ else:
254
+ print(result.gloss)
255
+
256
+
257
+ if __name__ == "__main__":
258
+ main()
pipeline02_gloss2pose.py CHANGED
@@ -653,6 +653,409 @@ class SignLanguageQA:
653
 
654
  return filtered
655
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
656
  def normalize_pose_data(self, npz_data, reference_point='neck', scale_by='shoulders',
657
  target_shoulder_width=0.35, target_shoulder_y=0.45):
658
  """
@@ -961,7 +1364,10 @@ class SignLanguageQA:
961
  def generate_video_from_glosses(self, gloss_list, output_path, fps=30, width=480, height=480,
962
  smoothing_frames=5, smoothing_method='none', npz_interpolation_frames=0,
963
  scale_x=1.0, scale_y=1.0, hide_torso_lines=False, ref_image_path=None,
964
- draw_style='controlnext', normalize_pose=True, draw_conf_threshold=0.6):
 
 
 
965
  """Generate video from gloss list with optional progressive scaling and head alignment
966
 
967
  Args:
@@ -983,6 +1389,19 @@ class SignLanguageQA:
983
  all_pose_frames = []
984
  all_npz_data = [] # Store NPZ data for interpolation
985
  video_info = []
 
 
 
 
 
 
 
 
 
 
 
 
 
986
 
987
  for gloss in gloss_list:
988
  matched_videos = self.find_gloss_videos(gloss)
@@ -1054,6 +1473,17 @@ class SignLanguageQA:
1054
  if normalize_pose:
1055
  npz_data = self.normalize_pose_data(npz_data, reference_point='neck', scale_by='shoulders')
1056
 
 
 
 
 
 
 
 
 
 
 
 
1057
  # Store NPZ data for potential interpolation
1058
  all_npz_data.append(npz_data)
1059
 
@@ -1077,6 +1507,7 @@ class SignLanguageQA:
1077
  )
1078
  if pose_frame is not None:
1079
  gloss_frames.append(pose_frame)
 
1080
 
1081
  if gloss_frames:
1082
  all_pose_frames.append(gloss_frames)
@@ -1096,7 +1527,7 @@ class SignLanguageQA:
1096
 
1097
  # Apply NPZ interpolation if requested
1098
  if npz_interpolation_frames > 0 and len(all_pose_frames) > 1:
1099
- print(f"🔄 Applying NPZ interpolation with {npz_interpolation_frames} frames...")
1100
  interpolated_pose_frames = []
1101
 
1102
  for i in range(len(all_pose_frames)):
@@ -1117,7 +1548,7 @@ class SignLanguageQA:
1117
  interpolated_npz_frames = interpolate_pose_npz(
1118
  npz1, npz2,
1119
  num_frames=npz_interpolation_frames,
1120
- method='catmull-rom',
1121
  frame1_num=end_frame1,
1122
  frame2_num=start_frame2
1123
  )
@@ -1146,6 +1577,7 @@ class SignLanguageQA:
1146
  )
1147
  if pose_frame is not None:
1148
  interpolated_pose_frames.append(pose_frame)
 
1149
 
1150
  print(f" ✅ Added {npz_interpolation_frames} interpolated frames between '{video_info[i]['gloss']}' and '{video_info[i+1]['gloss']}'")
1151
 
@@ -1160,6 +1592,18 @@ class SignLanguageQA:
1160
  for group in all_pose_frames:
1161
  final_frames.extend(group)
1162
 
 
 
 
 
 
 
 
 
 
 
 
 
1163
  # Write video using FFmpeg directly for better compatibility
1164
  print("💾 Writing video file...")
1165
 
@@ -1444,7 +1888,7 @@ class SignLanguageQA:
1444
  smoothing_frames = int(input("Pause frames [default 10]: ").strip() or "10")
1445
  elif smooth_choice == '5':
1446
  npz_interpolation_frames = int(input("NPZ interpolation frames [default 10]: ").strip() or "10")
1447
- print(f"📊 Using Catmull-Rom spline interpolation for smooth transitions")
1448
 
1449
  # Generate output filename
1450
  suffix = f"_{smoothing_method}" if smoothing_method != 'none' else ""
@@ -1506,6 +1950,10 @@ def main():
1506
  help='Smoothing frames (default: 5)')
1507
  parser.add_argument('--npz-interpolation', type=int, default=0,
1508
  help='Number of NPZ interpolation frames between glosses (default: 0)')
 
 
 
 
1509
  parser.add_argument('--scale-x', type=float, default=1.4,
1510
  help='Progressive X-axis scaling factor (default: 1.4)')
1511
  parser.add_argument('--scale-y', type=float, default=1.5,
@@ -1522,6 +1970,12 @@ def main():
1522
  help='Normalize pose data to standard coordinate system. This ensures different videos are in the same coordinate space, reducing inconsistency from different video sources. (default: true)')
1523
  parser.add_argument('--max-candidates', type=int, default=10,
1524
  help='Maximum number of NPZ candidates evaluated per gloss (default: 10, set 0 for unlimited)')
 
 
 
 
 
 
1525
 
1526
  args = parser.parse_args()
1527
 
@@ -1562,12 +2016,23 @@ def main():
1562
  else:
1563
  print(f"⚠️ Pose normalization disabled")
1564
 
 
 
 
 
 
 
 
 
 
1565
  success = qa_system.generate_video_from_glosses(
1566
  gloss_list, output_file, args.fps, args.width, args.height,
1567
  args.smoothing_frames, args.smoothing, args.npz_interpolation,
1568
  args.scale_x, args.scale_y, args.hide_torso_lines == 'true',
1569
  args.ref_image_path, args.draw_style, args.normalize_pose == 'true',
1570
- args.draw_threshold
 
 
1571
  )
1572
 
1573
  if not success:
 
653
 
654
  return filtered
655
 
656
+ def _is_valid_point(self, point):
657
+ return point is not None and len(point) >= 2 and point[0] > 0 and point[1] > 0
658
+
659
+ def _face_points_and_mask(self, faces):
660
+ if faces is None:
661
+ return None, None, None
662
+ if faces.ndim == 3:
663
+ if faces.shape[0] == 0:
664
+ return None, None, None
665
+ points = faces[0]
666
+ owner = 0
667
+ else:
668
+ points = faces
669
+ owner = None
670
+ if points is None or len(points) == 0:
671
+ return None, None, None
672
+ mask = (points[:, 0] > 0) & (points[:, 1] > 0)
673
+ if np.count_nonzero(mask) < 4:
674
+ return None, None, None
675
+ return points, mask, owner
676
+
677
+ def _face_scale(self, points, mask):
678
+ valid = points[mask, :2]
679
+ if len(valid) < 4:
680
+ return None
681
+ min_xy = np.min(valid, axis=0)
682
+ max_xy = np.max(valid, axis=0)
683
+ scale = np.linalg.norm(max_xy - min_xy)
684
+ return scale if scale > 1e-6 else None
685
+
686
+ def _translate_nearest_hand_to_wrist_delta(self, frame_data, original_wrists, wrist_deltas):
687
+ hands = frame_data.get('hands', None)
688
+ if hands is None:
689
+ return
690
+
691
+ def choose_delta(root):
692
+ candidates = []
693
+ for wrist_name, wrist in original_wrists.items():
694
+ if self._is_valid_point(wrist):
695
+ candidates.append((np.linalg.norm(root[:2] - wrist[:2]), wrist_deltas[wrist_name]))
696
+ if not candidates:
697
+ return None
698
+ return min(candidates, key=lambda item: item[0])[1]
699
+
700
+ if hands.ndim == 3:
701
+ for hand_idx in range(hands.shape[0]):
702
+ root = hands[hand_idx, 0]
703
+ if not self._is_valid_point(root):
704
+ continue
705
+ delta = choose_delta(root)
706
+ if delta is not None:
707
+ valid = (hands[hand_idx, :, 0] > 0) & (hands[hand_idx, :, 1] > 0)
708
+ hands[hand_idx, valid, :2] += delta
709
+ elif hands.ndim == 2 and len(hands) > 0:
710
+ root = hands[0]
711
+ if self._is_valid_point(root):
712
+ delta = choose_delta(root)
713
+ if delta is not None:
714
+ valid = (hands[:, 0] > 0) & (hands[:, 1] > 0)
715
+ hands[valid, :2] += delta
716
+
717
+ hands[..., 0] = np.clip(hands[..., 0], 0.0, 1.0)
718
+ hands[..., 1] = np.clip(hands[..., 1], 0.0, 1.0)
719
+ frame_data['hands'] = hands
720
+
721
+ def build_signer_template(self, npz_data, start_frame=1, end_frame=None):
722
+ """Build a fixed signer template from a clip.
723
+
724
+ The template stores median body keypoints, first-signer bone lengths, and
725
+ face center/scale. It is intentionally conservative: torso/head/shoulders
726
+ remain stable, while arms can later inherit directions from each word.
727
+ """
728
+ total_frames = self.get_total_frames(npz_data)
729
+ if total_frames == 0:
730
+ return None
731
+ if end_frame is None:
732
+ end_frame = total_frames
733
+ start_frame = max(1, start_frame)
734
+ end_frame = min(total_frames, end_frame)
735
+
736
+ body_samples = []
737
+ face_centers = []
738
+ face_scales = []
739
+ for frame_num in range(start_frame, end_frame + 1):
740
+ frame_data = self.get_frame_data(npz_data, frame_num)
741
+ if not frame_data:
742
+ continue
743
+ bodies = frame_data.get('bodies', None)
744
+ if bodies is not None and len(bodies) >= 18:
745
+ body_samples.append(bodies[:, :2].copy())
746
+ faces = frame_data.get('faces', None)
747
+ if faces is not None:
748
+ points, mask, _owner = self._face_points_and_mask(faces)
749
+ if points is not None:
750
+ face_centers.append(np.mean(points[mask, :2], axis=0))
751
+ scale = self._face_scale(points, mask)
752
+ if scale is not None:
753
+ face_scales.append(scale)
754
+
755
+ if not body_samples:
756
+ return None
757
+
758
+ stack = np.stack(body_samples, axis=0)
759
+ valid = (stack[..., 0] > 0) & (stack[..., 1] > 0)
760
+ template_body = np.zeros((18, 2), dtype=np.float32)
761
+ for j in range(18):
762
+ m = valid[:, j]
763
+ if np.any(m):
764
+ template_body[j] = np.median(stack[m, j, :2], axis=0)
765
+
766
+ body_bones = [
767
+ (1, 0), (1, 2), (2, 3), (3, 4),
768
+ (1, 5), (5, 6), (6, 7),
769
+ (1, 8), (8, 9), (9, 10),
770
+ (1, 11), (11, 12), (12, 13),
771
+ (0, 14), (0, 15), (14, 16), (15, 17),
772
+ ]
773
+ lengths = {}
774
+ for parent, child in body_bones:
775
+ if self._is_valid_point(template_body[parent]) and self._is_valid_point(template_body[child]):
776
+ length = float(np.linalg.norm(template_body[child] - template_body[parent]))
777
+ if 0.002 < length < 0.8:
778
+ lengths[(parent, child)] = length
779
+
780
+ template = {
781
+ 'body': template_body,
782
+ 'lengths': lengths,
783
+ 'face_center': np.median(face_centers, axis=0).astype(np.float32) if face_centers else None,
784
+ 'face_scale': float(np.median(face_scales)) if face_scales else None,
785
+ }
786
+ print(" 🧍 First-signer template built")
787
+ print(f" Body template joints: {np.count_nonzero((template_body[:, 0] > 0) & (template_body[:, 1] > 0))}/18")
788
+ if template['face_center'] is not None:
789
+ print(f" Face center: ({template['face_center'][0]:.3f}, {template['face_center'][1]:.3f})")
790
+ return template
791
+
792
+ def _retarget_arm_to_template(self, bodies, template_body, lengths, shoulder_idx, elbow_idx, wrist_idx):
793
+ out = template_body.copy()
794
+ shoulder = template_body[shoulder_idx]
795
+ if not self._is_valid_point(shoulder):
796
+ return out
797
+
798
+ def direction(a, b, fallback):
799
+ if self._is_valid_point(a) and self._is_valid_point(b):
800
+ v = b[:2] - a[:2]
801
+ n = np.linalg.norm(v)
802
+ if n > 1e-6:
803
+ return v / n
804
+ if self._is_valid_point(fallback[0]) and self._is_valid_point(fallback[1]):
805
+ v = fallback[1] - fallback[0]
806
+ n = np.linalg.norm(v)
807
+ if n > 1e-6:
808
+ return v / n
809
+ return np.array([0.0, 1.0], dtype=np.float32)
810
+
811
+ upper_dir = direction(bodies[shoulder_idx], bodies[elbow_idx], (template_body[shoulder_idx], template_body[elbow_idx]))
812
+ lower_dir = direction(bodies[elbow_idx], bodies[wrist_idx], (template_body[elbow_idx], template_body[wrist_idx]))
813
+ upper_len = lengths.get((shoulder_idx, elbow_idx), np.linalg.norm(template_body[elbow_idx] - template_body[shoulder_idx]))
814
+ lower_len = lengths.get((elbow_idx, wrist_idx), np.linalg.norm(template_body[wrist_idx] - template_body[elbow_idx]))
815
+ out[elbow_idx] = shoulder + upper_dir * upper_len
816
+ out[wrist_idx] = out[elbow_idx] + lower_dir * lower_len
817
+ return out
818
+
819
+ def retarget_pose_data_to_first_signer(self, npz_data, template, start_frame=1, end_frame=None, face_mode='retarget'):
820
+ """Retarget a clip to the first signer's skeleton while preserving arm/hand motion.
821
+
822
+ Torso/head/shoulders/hips use the first signer template. Elbow/wrist use
823
+ the current clip's arm directions with first-signer bone lengths. Hands
824
+ are translated by wrist deltas. Face local shape may come from the clip,
825
+ but its center/scale is aligned to the first signer.
826
+ """
827
+ if template is None or template.get('body') is None:
828
+ return npz_data
829
+ total_frames = self.get_total_frames(npz_data)
830
+ if total_frames == 0:
831
+ return npz_data
832
+ if end_frame is None:
833
+ end_frame = total_frames
834
+ start_frame = max(1, start_frame)
835
+ end_frame = min(total_frames, end_frame)
836
+
837
+ template_body = template['body']
838
+ lengths = template.get('lengths', {})
839
+ face_center = template.get('face_center')
840
+ face_scale = template.get('face_scale')
841
+
842
+ print(" 🧍 Retargeting clip to first signer template")
843
+ for frame_num in range(start_frame, end_frame + 1):
844
+ frame_key = f"frame_{frame_num:08d}"
845
+ bodies_key = f"{frame_key}_bodies"
846
+ if bodies_key not in npz_data or npz_data[bodies_key] is None:
847
+ continue
848
+ bodies = npz_data[bodies_key].copy()
849
+ if len(bodies) < 18:
850
+ continue
851
+ original_wrists = {
852
+ 'right': bodies[4, :2].copy() if len(bodies) > 4 else None,
853
+ 'left': bodies[7, :2].copy() if len(bodies) > 7 else None,
854
+ }
855
+
856
+ new_body_xy = template_body.copy()
857
+ right_arm = self._retarget_arm_to_template(bodies, template_body, lengths, 2, 3, 4)
858
+ left_arm = self._retarget_arm_to_template(bodies, template_body, lengths, 5, 6, 7)
859
+ new_body_xy[[3, 4]] = right_arm[[3, 4]]
860
+ new_body_xy[[6, 7]] = left_arm[[6, 7]]
861
+
862
+ new_bodies = bodies.copy()
863
+ valid_template = (new_body_xy[:, 0] > 0) & (new_body_xy[:, 1] > 0)
864
+ new_bodies[valid_template, :2] = new_body_xy[valid_template]
865
+ new_bodies[:, 0] = np.clip(new_bodies[:, 0], 0.0, 1.0)
866
+ new_bodies[:, 1] = np.clip(new_bodies[:, 1], 0.0, 1.0)
867
+ npz_data[bodies_key] = new_bodies
868
+
869
+ wrist_deltas = {
870
+ 'right': new_bodies[4, :2] - original_wrists['right'] if original_wrists['right'] is not None and len(new_bodies) > 4 else np.zeros(2),
871
+ 'left': new_bodies[7, :2] - original_wrists['left'] if original_wrists['left'] is not None and len(new_bodies) > 7 else np.zeros(2),
872
+ }
873
+ frame_data = self.get_frame_data(npz_data, frame_num)
874
+ if frame_data:
875
+ self._translate_nearest_hand_to_wrist_delta(frame_data, original_wrists, wrist_deltas)
876
+ hands_key = f"{frame_key}_hands"
877
+ if hands_key in npz_data and 'hands' in frame_data:
878
+ npz_data[hands_key] = frame_data['hands']
879
+
880
+ faces_key = f"{frame_key}_faces"
881
+ if face_mode != 'none' and face_center is not None and faces_key in npz_data and npz_data[faces_key] is not None:
882
+ faces = npz_data[faces_key].copy()
883
+ points, mask, owner = self._face_points_and_mask(faces)
884
+ if points is not None:
885
+ current_center = np.mean(points[mask, :2], axis=0)
886
+ scaled_points = points.copy()
887
+ if face_scale is not None:
888
+ current_scale = self._face_scale(points, mask)
889
+ if current_scale is not None and current_scale > 1e-6:
890
+ scaled_points[mask, :2] = current_center + (points[mask, :2] - current_center) * (face_scale / current_scale)
891
+ shifted_center = np.mean(scaled_points[mask, :2], axis=0)
892
+ scaled_points[mask, :2] += face_center - shifted_center
893
+ if owner is None:
894
+ faces = scaled_points
895
+ else:
896
+ faces[owner] = scaled_points
897
+ faces[..., 0] = np.clip(faces[..., 0], 0.0, 1.0)
898
+ faces[..., 1] = np.clip(faces[..., 1], 0.0, 1.0)
899
+ npz_data[faces_key] = faces
900
+
901
+ return npz_data
902
+
903
+ def stabilize_pose_data(self, npz_data, start_frame=1, end_frame=None, body_smoothing_alpha=0.75):
904
+ """Stabilize a pose clip with fixed body bone lengths and fixed face scale."""
905
+ total_frames = self.get_total_frames(npz_data)
906
+ if total_frames == 0:
907
+ return npz_data
908
+ if end_frame is None:
909
+ end_frame = total_frames
910
+ start_frame = max(1, start_frame)
911
+ end_frame = min(total_frames, end_frame)
912
+ if start_frame > end_frame:
913
+ return npz_data
914
+
915
+ body_bones = [
916
+ (1, 0),
917
+ (1, 2), (2, 3), (3, 4),
918
+ (1, 5), (5, 6), (6, 7),
919
+ (1, 8), (8, 9), (9, 10),
920
+ (1, 11), (11, 12), (12, 13),
921
+ (0, 14), (0, 15), (14, 16), (15, 17),
922
+ ]
923
+
924
+ bone_lengths = {bone: [] for bone in body_bones}
925
+ face_scales = []
926
+
927
+ for frame_num in range(start_frame, end_frame + 1):
928
+ frame_data = self.get_frame_data(npz_data, frame_num)
929
+ if not frame_data or 'bodies' not in frame_data:
930
+ continue
931
+ bodies = frame_data['bodies']
932
+ if bodies is not None:
933
+ for parent, child in body_bones:
934
+ if parent < len(bodies) and child < len(bodies):
935
+ if self._is_valid_point(bodies[parent]) and self._is_valid_point(bodies[child]):
936
+ length = np.linalg.norm(bodies[child, :2] - bodies[parent, :2])
937
+ if 0.002 < length < 0.8:
938
+ bone_lengths[(parent, child)].append(length)
939
+
940
+ faces = frame_data.get('faces', None)
941
+ if faces is not None:
942
+ points, mask, _owner = self._face_points_and_mask(faces)
943
+ if points is not None:
944
+ scale = self._face_scale(points, mask)
945
+ if scale is not None and 0.002 < scale < 0.8:
946
+ face_scales.append(scale)
947
+
948
+ median_lengths = {
949
+ bone: float(np.median(lengths))
950
+ for bone, lengths in bone_lengths.items()
951
+ if lengths
952
+ }
953
+ median_face_scale = float(np.median(face_scales)) if face_scales else None
954
+
955
+ if not median_lengths and median_face_scale is None:
956
+ print(" ⚠️ Skeleton stabilization skipped: insufficient valid body/face data")
957
+ return npz_data
958
+
959
+ print(" 🦴 Skeleton stabilization enabled")
960
+ if median_lengths:
961
+ print(f" Fixed body bones: {len(median_lengths)}")
962
+ if median_face_scale is not None:
963
+ print(f" Fixed face scale: {median_face_scale:.3f}")
964
+
965
+ for frame_num in range(start_frame, end_frame + 1):
966
+ frame_key = f"frame_{frame_num:08d}"
967
+ bodies_key = f"{frame_key}_bodies"
968
+ if bodies_key in npz_data and npz_data[bodies_key] is not None:
969
+ bodies = npz_data[bodies_key].copy()
970
+ original_wrists = {
971
+ 'right': bodies[4, :2].copy() if len(bodies) > 4 else None,
972
+ 'left': bodies[7, :2].copy() if len(bodies) > 7 else None,
973
+ }
974
+
975
+ for parent, child in body_bones:
976
+ target_len = median_lengths.get((parent, child))
977
+ if target_len is None or parent >= len(bodies) or child >= len(bodies):
978
+ continue
979
+ if not self._is_valid_point(bodies[parent]) or not self._is_valid_point(bodies[child]):
980
+ continue
981
+ direction = bodies[child, :2] - bodies[parent, :2]
982
+ current_len = np.linalg.norm(direction)
983
+ if current_len <= 1e-6:
984
+ continue
985
+ bodies[child, :2] = bodies[parent, :2] + direction / current_len * target_len
986
+
987
+ bodies[:, 0] = np.clip(bodies[:, 0], 0.0, 1.0)
988
+ bodies[:, 1] = np.clip(bodies[:, 1], 0.0, 1.0)
989
+ npz_data[bodies_key] = bodies
990
+
991
+ wrist_deltas = {
992
+ 'right': bodies[4, :2] - original_wrists['right'] if original_wrists['right'] is not None and len(bodies) > 4 else np.zeros(2),
993
+ 'left': bodies[7, :2] - original_wrists['left'] if original_wrists['left'] is not None and len(bodies) > 7 else np.zeros(2),
994
+ }
995
+ frame_data = self.get_frame_data(npz_data, frame_num)
996
+ if frame_data:
997
+ self._translate_nearest_hand_to_wrist_delta(frame_data, original_wrists, wrist_deltas)
998
+ hands_key = f"{frame_key}_hands"
999
+ if hands_key in npz_data and 'hands' in frame_data:
1000
+ npz_data[hands_key] = frame_data['hands']
1001
+
1002
+ faces_key = f"{frame_key}_faces"
1003
+ if median_face_scale is not None and faces_key in npz_data and npz_data[faces_key] is not None:
1004
+ faces = npz_data[faces_key].copy()
1005
+ points, mask, owner = self._face_points_and_mask(faces)
1006
+ if points is not None:
1007
+ current_scale = self._face_scale(points, mask)
1008
+ if current_scale is not None and current_scale > 1e-6:
1009
+ center = np.mean(points[mask, :2], axis=0)
1010
+ scaled_points = points.copy()
1011
+ scaled_points[mask, :2] = center + (points[mask, :2] - center) * (median_face_scale / current_scale)
1012
+ if owner is None:
1013
+ faces = scaled_points
1014
+ else:
1015
+ faces[owner] = scaled_points
1016
+ faces[..., 0] = np.clip(faces[..., 0], 0.0, 1.0)
1017
+ faces[..., 1] = np.clip(faces[..., 1], 0.0, 1.0)
1018
+ npz_data[faces_key] = faces
1019
+
1020
+ previous_bodies = None
1021
+ for frame_num in range(start_frame, end_frame + 1):
1022
+ frame_key = f"frame_{frame_num:08d}"
1023
+ bodies_key = f"{frame_key}_bodies"
1024
+ if bodies_key not in npz_data or npz_data[bodies_key] is None:
1025
+ continue
1026
+ bodies = npz_data[bodies_key].copy()
1027
+ if previous_bodies is not None and previous_bodies.shape == bodies.shape:
1028
+ original_wrists = {
1029
+ 'right': bodies[4, :2].copy() if len(bodies) > 4 else None,
1030
+ 'left': bodies[7, :2].copy() if len(bodies) > 7 else None,
1031
+ }
1032
+ valid = (
1033
+ (bodies[:, 0] > 0) & (bodies[:, 1] > 0) &
1034
+ (previous_bodies[:, 0] > 0) & (previous_bodies[:, 1] > 0)
1035
+ )
1036
+ bodies[valid, :2] = (
1037
+ body_smoothing_alpha * bodies[valid, :2] +
1038
+ (1.0 - body_smoothing_alpha) * previous_bodies[valid, :2]
1039
+ )
1040
+ bodies[:, 0] = np.clip(bodies[:, 0], 0.0, 1.0)
1041
+ bodies[:, 1] = np.clip(bodies[:, 1], 0.0, 1.0)
1042
+ npz_data[bodies_key] = bodies
1043
+
1044
+ wrist_deltas = {
1045
+ 'right': bodies[4, :2] - original_wrists['right'] if original_wrists['right'] is not None and len(bodies) > 4 else np.zeros(2),
1046
+ 'left': bodies[7, :2] - original_wrists['left'] if original_wrists['left'] is not None and len(bodies) > 7 else np.zeros(2),
1047
+ }
1048
+ frame_data = self.get_frame_data(npz_data, frame_num)
1049
+ if frame_data:
1050
+ self._translate_nearest_hand_to_wrist_delta(frame_data, original_wrists, wrist_deltas)
1051
+ hands_key = f"{frame_key}_hands"
1052
+ if hands_key in npz_data and 'hands' in frame_data:
1053
+ npz_data[hands_key] = frame_data['hands']
1054
+
1055
+ previous_bodies = bodies.copy()
1056
+
1057
+ return npz_data
1058
+
1059
  def normalize_pose_data(self, npz_data, reference_point='neck', scale_by='shoulders',
1060
  target_shoulder_width=0.35, target_shoulder_y=0.45):
1061
  """
 
1364
  def generate_video_from_glosses(self, gloss_list, output_path, fps=30, width=480, height=480,
1365
  smoothing_frames=5, smoothing_method='none', npz_interpolation_frames=0,
1366
  scale_x=1.0, scale_y=1.0, hide_torso_lines=False, ref_image_path=None,
1367
+ draw_style='controlnext', normalize_pose=True, draw_conf_threshold=0.6,
1368
+ stabilize_skeleton=False, npz_interpolation_method='body-anchor',
1369
+ retarget_to_first_signer=True, retarget_face_mode='retarget',
1370
+ frame_callback=None):
1371
  """Generate video from gloss list with optional progressive scaling and head alignment
1372
 
1373
  Args:
 
1389
  all_pose_frames = []
1390
  all_npz_data = [] # Store NPZ data for interpolation
1391
  video_info = []
1392
+ first_signer_template = None
1393
+ streamed_frame_count = 0
1394
+
1395
+ def emit_stream_frame(frame, total_frames=None):
1396
+ nonlocal streamed_frame_count
1397
+ if frame_callback is None or frame is None:
1398
+ return
1399
+ try:
1400
+ frame_callback(streamed_frame_count, frame, total_frames or 0)
1401
+ streamed_frame_count += 1
1402
+ except Exception as cb_err:
1403
+ print(f"⚠️ Frame callback failed at {streamed_frame_count}: {cb_err}")
1404
+
1405
 
1406
  for gloss in gloss_list:
1407
  matched_videos = self.find_gloss_videos(gloss)
 
1473
  if normalize_pose:
1474
  npz_data = self.normalize_pose_data(npz_data, reference_point='neck', scale_by='shoulders')
1475
 
1476
+ if stabilize_skeleton:
1477
+ npz_data = self.stabilize_pose_data(npz_data, start_frame=start_frame, end_frame=end_frame)
1478
+
1479
+ if retarget_to_first_signer:
1480
+ if first_signer_template is None:
1481
+ first_signer_template = self.build_signer_template(npz_data, start_frame=start_frame, end_frame=end_frame)
1482
+ npz_data = self.retarget_pose_data_to_first_signer(
1483
+ npz_data, first_signer_template, start_frame=start_frame, end_frame=end_frame,
1484
+ face_mode=retarget_face_mode
1485
+ )
1486
+
1487
  # Store NPZ data for potential interpolation
1488
  all_npz_data.append(npz_data)
1489
 
 
1507
  )
1508
  if pose_frame is not None:
1509
  gloss_frames.append(pose_frame)
1510
+ emit_stream_frame(pose_frame)
1511
 
1512
  if gloss_frames:
1513
  all_pose_frames.append(gloss_frames)
 
1527
 
1528
  # Apply NPZ interpolation if requested
1529
  if npz_interpolation_frames > 0 and len(all_pose_frames) > 1:
1530
+ print(f"🔄 Applying NPZ interpolation with {npz_interpolation_frames} frames ({npz_interpolation_method})...")
1531
  interpolated_pose_frames = []
1532
 
1533
  for i in range(len(all_pose_frames)):
 
1548
  interpolated_npz_frames = interpolate_pose_npz(
1549
  npz1, npz2,
1550
  num_frames=npz_interpolation_frames,
1551
+ method=npz_interpolation_method,
1552
  frame1_num=end_frame1,
1553
  frame2_num=start_frame2
1554
  )
 
1577
  )
1578
  if pose_frame is not None:
1579
  interpolated_pose_frames.append(pose_frame)
1580
+ emit_stream_frame(pose_frame)
1581
 
1582
  print(f" ✅ Added {npz_interpolation_frames} interpolated frames between '{video_info[i]['gloss']}' and '{video_info[i+1]['gloss']}'")
1583
 
 
1592
  for group in all_pose_frames:
1593
  final_frames.extend(group)
1594
 
1595
+ # Push preview frames before final video encoding, so the browser can play immediately.
1596
+ if frame_callback is not None and streamed_frame_count == 0:
1597
+ print("📡 Streaming preview frames...")
1598
+ total_preview_frames = len(final_frames)
1599
+ for stream_idx, stream_frame in enumerate(final_frames):
1600
+ try:
1601
+ frame_callback(stream_idx, stream_frame, total_preview_frames)
1602
+ streamed_frame_count += 1
1603
+ except Exception as cb_err:
1604
+ print(f"⚠️ Frame callback failed at {stream_idx}: {cb_err}")
1605
+ break
1606
+
1607
  # Write video using FFmpeg directly for better compatibility
1608
  print("💾 Writing video file...")
1609
 
 
1888
  smoothing_frames = int(input("Pause frames [default 10]: ").strip() or "10")
1889
  elif smooth_choice == '5':
1890
  npz_interpolation_frames = int(input("NPZ interpolation frames [default 10]: ").strip() or "10")
1891
+ print(f"📊 Using body-anchor NPZ interpolation for smooth transitions")
1892
 
1893
  # Generate output filename
1894
  suffix = f"_{smoothing_method}" if smoothing_method != 'none' else ""
 
1950
  help='Smoothing frames (default: 5)')
1951
  parser.add_argument('--npz-interpolation', type=int, default=0,
1952
  help='Number of NPZ interpolation frames between glosses (default: 0)')
1953
+ parser.add_argument('--npz-interpolation-method',
1954
+ choices=['body-anchor', 'catmull-rom', 'linear', 'cubic'],
1955
+ default='body-anchor',
1956
+ help='NPZ transition method. body-anchor keeps hand/face local shapes and only retargets them to interpolated wrists/neck. (default: body-anchor)')
1957
  parser.add_argument('--scale-x', type=float, default=1.4,
1958
  help='Progressive X-axis scaling factor (default: 1.4)')
1959
  parser.add_argument('--scale-y', type=float, default=1.5,
 
1970
  help='Normalize pose data to standard coordinate system. This ensures different videos are in the same coordinate space, reducing inconsistency from different video sources. (default: true)')
1971
  parser.add_argument('--max-candidates', type=int, default=10,
1972
  help='Maximum number of NPZ candidates evaluated per gloss (default: 10, set 0 for unlimited)')
1973
+ parser.add_argument('--stabilize-skeleton', type=str, choices=['true', 'false'], default='false',
1974
+ help='Stabilize body bone lengths and face scale before rendering (default: false)')
1975
+ parser.add_argument('--retarget-to-first-signer', type=str, choices=['true', 'false'], default='true',
1976
+ help='Retarget every gloss clip to the first selected signer skeleton. Only arms/hands change across words. (default: true)')
1977
+ parser.add_argument('--retarget-face-mode', choices=['retarget', 'none'], default='retarget',
1978
+ help='Face handling when retargeting: retarget keeps local face shape but aligns center/scale to first signer; none leaves face unchanged. (default: retarget)')
1979
 
1980
  args = parser.parse_args()
1981
 
 
2016
  else:
2017
  print(f"⚠️ Pose normalization disabled")
2018
 
2019
+ if args.stabilize_skeleton == 'true':
2020
+ print(f"🦴 Skeleton stabilization enabled")
2021
+
2022
+ if args.npz_interpolation > 0:
2023
+ print(f"🔄 NPZ interpolation method: {args.npz_interpolation_method}")
2024
+
2025
+ if args.retarget_to_first_signer == 'true':
2026
+ print(f"🧍 Retargeting all glosses to first signer skeleton (face={args.retarget_face_mode})")
2027
+
2028
  success = qa_system.generate_video_from_glosses(
2029
  gloss_list, output_file, args.fps, args.width, args.height,
2030
  args.smoothing_frames, args.smoothing, args.npz_interpolation,
2031
  args.scale_x, args.scale_y, args.hide_torso_lines == 'true',
2032
  args.ref_image_path, args.draw_style, args.normalize_pose == 'true',
2033
+ args.draw_threshold, args.stabilize_skeleton == 'true',
2034
+ args.npz_interpolation_method,
2035
+ args.retarget_to_first_signer == 'true', args.retarget_face_mode
2036
  )
2037
 
2038
  if not success:
templates/selection_translation_template.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ User: Do native signers have difficulty reading written text?
2
+
3
+ Assistant: Yes. This is a well-studied phenomenon. The reason is not cognitive ability, but linguistics and acquisition history. Written language encodes spoken language; many deaf readers approach English or Chinese as a second language without accessible spoken-language support.
4
+
5
+ User: But why do they not just learn text first if their parents know English text?
6
+
7
+ Assistant: Writing is not acquired directly. It is built on top of an already acquired natural language. Sign language is not a competitor to reading; it is often the foundation for reading.
utils/npz_interpolation.py CHANGED
@@ -81,6 +81,141 @@ def catmull_rom_spline(p0, p1, p2, p3, num_points, tension=0.5):
81
  return np.array(points)
82
 
83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  def interpolate_pose_npz(npz1_data, npz2_data, num_frames=10, method='catmull-rom', frame1_num=None, frame2_num=None):
85
  """
86
  Interpolate between two pose NPZ data structures
@@ -200,7 +335,35 @@ def interpolate_pose_npz(npz1_data, npz2_data, num_frames=10, method='catmull-ro
200
  data1 = npz1_data[key1]
201
  data2 = npz2_data[key2]
202
 
203
- if method == 'linear':
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
204
  # Simple linear interpolation with easing
205
  t_eased = ease_in_out_cubic(t)
206
  interpolated = data1 * (1 - t_eased) + data2 * t_eased
 
81
  return np.array(points)
82
 
83
 
84
+
85
+ BODY_TREE = [
86
+ (1, 2), (2, 3), (3, 4),
87
+ (1, 5), (5, 6), (6, 7),
88
+ (1, 8), (8, 9), (9, 10),
89
+ (1, 11), (11, 12), (12, 13),
90
+ (1, 0), (0, 14), (14, 16), (0, 15), (15, 17),
91
+ ]
92
+
93
+
94
+ def _valid_xy(points):
95
+ return points is not None and points.shape[-1] >= 2
96
+
97
+
98
+ def _point_valid(point):
99
+ return point is not None and len(point) >= 2 and point[0] > 0 and point[1] > 0
100
+
101
+
102
+ def _canonicalize_body(body, body_a, body_b, blend=0.9):
103
+ if body is None or body.shape[0] < 18:
104
+ return body
105
+ rec = body.copy()
106
+ rec[1, :2] = body[1, :2]
107
+ for parent, child in BODY_TREE:
108
+ if parent >= len(body) or child >= len(body):
109
+ continue
110
+ if not (_point_valid(body[parent]) and _point_valid(body[child])):
111
+ continue
112
+ lengths = []
113
+ for ref in (body_a, body_b):
114
+ if ref is not None and parent < len(ref) and child < len(ref):
115
+ if _point_valid(ref[parent]) and _point_valid(ref[child]):
116
+ length = np.linalg.norm(ref[child, :2] - ref[parent, :2])
117
+ if 0.002 < length < 0.8:
118
+ lengths.append(length)
119
+ if not lengths:
120
+ continue
121
+ target_len = float(np.median(lengths))
122
+ direction = body[child, :2] - body[parent, :2]
123
+ current_len = np.linalg.norm(direction)
124
+ if current_len <= 1e-6:
125
+ continue
126
+ rec[child, :2] = rec[parent, :2] + direction / current_len * target_len
127
+ out = body.copy()
128
+ out[:, :2] = body[:, :2] * (1.0 - blend) + rec[:, :2] * blend
129
+ out[:, 0] = np.clip(out[:, 0], 0.0, 1.0)
130
+ out[:, 1] = np.clip(out[:, 1], 0.0, 1.0)
131
+ return out
132
+
133
+
134
+ def _attach_hands_to_body(hands_a, hands_b, body_a, body_b, body_t, alpha):
135
+ if hands_a is None and hands_b is None:
136
+ return None
137
+ if hands_a is None:
138
+ hands_a = hands_b
139
+ body_a = body_b
140
+ if hands_b is None:
141
+ hands_b = hands_a
142
+ body_b = body_a
143
+ if hands_a is None or hands_b is None or hands_a.shape != hands_b.shape:
144
+ return hands_a if alpha < 0.5 else hands_b
145
+
146
+ out_a = np.array(hands_a, copy=True)
147
+ out_b = np.array(hands_b, copy=True)
148
+ wrist_ids = [4, 7]
149
+
150
+ def attach(src_hands, src_body):
151
+ attached = np.array(src_hands, copy=True)
152
+ if src_body is None or body_t is None or len(src_body) <= 7 or len(body_t) <= 7:
153
+ return attached
154
+ if src_hands.ndim == 3:
155
+ for hand_idx in range(src_hands.shape[0]):
156
+ root = src_hands[hand_idx, 0]
157
+ if not _point_valid(root):
158
+ continue
159
+ choices = []
160
+ for wid in wrist_ids:
161
+ if _point_valid(src_body[wid]) and _point_valid(body_t[wid]):
162
+ choices.append((np.linalg.norm(root[:2] - src_body[wid, :2]), wid))
163
+ if not choices:
164
+ continue
165
+ wid = min(choices, key=lambda item: item[0])[1]
166
+ delta = body_t[wid, :2] - src_body[wid, :2]
167
+ valid = (attached[hand_idx, :, 0] > 0) & (attached[hand_idx, :, 1] > 0)
168
+ attached[hand_idx, valid, :2] += delta
169
+ elif src_hands.ndim == 2 and len(src_hands) > 0:
170
+ root = src_hands[0]
171
+ choices = []
172
+ for wid in wrist_ids:
173
+ if _point_valid(root) and _point_valid(src_body[wid]) and _point_valid(body_t[wid]):
174
+ choices.append((np.linalg.norm(root[:2] - src_body[wid, :2]), wid))
175
+ if choices:
176
+ wid = min(choices, key=lambda item: item[0])[1]
177
+ delta = body_t[wid, :2] - src_body[wid, :2]
178
+ valid = (attached[:, 0] > 0) & (attached[:, 1] > 0)
179
+ attached[valid, :2] += delta
180
+ attached[..., 0] = np.clip(attached[..., 0], 0.0, 1.0)
181
+ attached[..., 1] = np.clip(attached[..., 1], 0.0, 1.0)
182
+ return attached
183
+
184
+ a = attach(out_a, body_a)
185
+ b = attach(out_b, body_b)
186
+ out = a * (1.0 - alpha) + b * alpha
187
+ return out
188
+
189
+
190
+ def _attach_faces_to_body(face_a, face_b, body_a, body_b, body_t, alpha):
191
+ if face_a is None and face_b is None:
192
+ return None
193
+ if face_a is None:
194
+ face_a = face_b
195
+ body_a = body_b
196
+ if face_b is None:
197
+ face_b = face_a
198
+ body_b = body_a
199
+ if face_a is None or face_b is None or face_a.shape != face_b.shape:
200
+ return face_a if alpha < 0.5 else face_b
201
+
202
+ def attach(src_face, src_body):
203
+ attached = np.array(src_face, copy=True)
204
+ if src_body is None or body_t is None or len(src_body) <= 1 or len(body_t) <= 1:
205
+ return attached
206
+ if not (_point_valid(src_body[1]) and _point_valid(body_t[1])):
207
+ return attached
208
+ delta = body_t[1, :2] - src_body[1, :2]
209
+ valid = (attached[..., 0] > 0) & (attached[..., 1] > 0)
210
+ attached[..., :2][valid] += delta
211
+ attached[..., 0] = np.clip(attached[..., 0], 0.0, 1.0)
212
+ attached[..., 1] = np.clip(attached[..., 1], 0.0, 1.0)
213
+ return attached
214
+
215
+ a = attach(face_a, body_a)
216
+ b = attach(face_b, body_b)
217
+ return a * (1.0 - alpha) + b * alpha
218
+
219
  def interpolate_pose_npz(npz1_data, npz2_data, num_frames=10, method='catmull-rom', frame1_num=None, frame2_num=None):
220
  """
221
  Interpolate between two pose NPZ data structures
 
335
  data1 = npz1_data[key1]
336
  data2 = npz2_data[key2]
337
 
338
+ if method == 'body-anchor':
339
+ t_eased = ease_in_out_sine(t)
340
+ if component == 'bodies':
341
+ prev_key = f"{prev_frame_key1}_{component}"
342
+ next_key = f"{next_frame_key2}_{component}"
343
+ p0 = npz1_data.get(prev_key, data1)
344
+ p1 = data1
345
+ p2 = data2
346
+ p3 = npz2_data.get(next_key, data2)
347
+ interpolated = catmull_rom_spline(p0, p1, p2, p3, num_frames)[i]
348
+ interpolated = _canonicalize_body(interpolated, data1, data2, blend=0.9)
349
+ elif component == 'hands':
350
+ body1 = npz1_data.get(f"frame_{frame_num1}_bodies")
351
+ body2 = npz2_data.get(f"frame_{frame_num2}_bodies")
352
+ body_key = f"frame_{i+1:08d}_bodies"
353
+ body_t = interpolated_data.get(body_key)
354
+ interpolated = _attach_hands_to_body(data1, data2, body1, body2, body_t, t_eased)
355
+ elif component == 'faces':
356
+ body1 = npz1_data.get(f"frame_{frame_num1}_bodies")
357
+ body2 = npz2_data.get(f"frame_{frame_num2}_bodies")
358
+ body_key = f"frame_{i+1:08d}_bodies"
359
+ body_t = interpolated_data.get(body_key)
360
+ interpolated = _attach_faces_to_body(data1, data2, body1, body2, body_t, t_eased)
361
+ elif component.endswith('_scores'):
362
+ interpolated = data1 * (1 - t_eased) + data2 * t_eased
363
+ else:
364
+ interpolated = data1 * (1 - t_eased) + data2 * t_eased
365
+
366
+ elif method == 'linear':
367
  # Simple linear interpolation with easing
368
  t_eased = ease_in_out_cubic(t)
369
  interpolated = data1 * (1 - t_eased) + data2 * t_eased
viser_backend.py CHANGED
@@ -6,6 +6,7 @@ Handles prompt/text -> gloss -> pose video generation for the ControlWorld panel
6
 
7
  from __future__ import annotations
8
 
 
9
  import contextlib
10
  import io
11
  import os
@@ -18,6 +19,8 @@ from datetime import datetime
18
  from pathlib import Path
19
  from typing import Any, Dict, List, Optional
20
 
 
 
21
  # ControlWorld provides plugin_base in the parent directory of every plugin
22
  import sys
23
 
@@ -46,6 +49,7 @@ from plugin_base import PluginBackendBase # type: ignore # pylint: disable=wro
46
 
47
  # Import local helpers lazily when needed
48
  from prompt2gloss import build_input as build_prompt_input # type: ignore
 
49
 
50
 
51
  def _to_bool(value: Any, default: bool = False) -> bool:
@@ -96,6 +100,8 @@ class StableSignerBackend(PluginBackendBase):
96
 
97
  self._refine_jobs: Dict[str, Dict[str, Any]] = {}
98
  self._refine_jobs_lock = threading.Lock()
 
 
99
 
100
  self._prompt_tokenizer = None
101
  self._prompt_model = None
@@ -104,6 +110,7 @@ class StableSignerBackend(PluginBackendBase):
104
  self._torch = None
105
  self._qa_instances: Dict[int, SignLanguageQA] = {}
106
  self._generation_lock = threading.Lock()
 
107
 
108
  # ------------------------------------------------------------------
109
  # Lazy loaders
@@ -146,6 +153,11 @@ class StableSignerBackend(PluginBackendBase):
146
  self._qa_instances[key] = SignLanguageQA(max_candidates=key)
147
  return self._qa_instances[key]
148
 
 
 
 
 
 
149
  # ------------------------------------------------------------------
150
  # Helpers
151
  # ------------------------------------------------------------------
@@ -201,6 +213,19 @@ class StableSignerBackend(PluginBackendBase):
201
  decoded = tokenizer.batch_decode(outputs, skip_special_tokens=True)[0].strip().upper()
202
  return decoded
203
 
 
 
 
 
 
 
 
 
 
 
 
 
 
204
  def _build_output_path(self, gloss_tokens: List[str], draw_style: str) -> Path:
205
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
206
  slug = "_".join(gloss_tokens[:4]) if gloss_tokens else "gloss"
@@ -265,6 +290,10 @@ class StableSignerBackend(PluginBackendBase):
265
 
266
  if action == "generate_pose":
267
  return self.handle_generate_pose(data)
 
 
 
 
268
  if action == "list_recent_videos":
269
  return {"status": "success", "videos": self._list_recent_videos()}
270
  if action == "list_sign_videos":
@@ -279,6 +308,8 @@ class StableSignerBackend(PluginBackendBase):
279
  return self.handle_probe_video(data)
280
  if action == "prompt_to_gloss":
281
  return self.handle_prompt_to_gloss(data)
 
 
282
  if action == "prewarm":
283
  return self.handle_prewarm(data)
284
  return super().handle_message(message)
@@ -309,6 +340,23 @@ class StableSignerBackend(PluginBackendBase):
309
  except Exception as exc: # pylint: disable=broad-except
310
  return {"status": "error", "message": str(exc)}
311
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
312
  def handle_prewarm(self, data: Dict[str, Any]) -> Dict[str, Any]:
313
  candidate_counts = data.get("candidateCounts")
314
  if isinstance(candidate_counts, list):
@@ -353,6 +401,178 @@ class StableSignerBackend(PluginBackendBase):
353
  "logs": logs or "(no logs)",
354
  }
355
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
356
  def handle_generate_pose(self, data: Dict[str, Any]) -> Dict[str, Any]:
357
  if not self._generation_lock.acquire(blocking=False):
358
  return {"status": "error", "message": "A generation job is already running. Please wait."}
@@ -382,7 +602,12 @@ class StableSignerBackend(PluginBackendBase):
382
  if not gloss_input:
383
  if not text_input:
384
  return {"status": "error", "message": "Please enter Prompt/Text or a gloss sequence."}
385
- gloss_input = self._generate_gloss(text_input, prompt_input, max_new_tokens)
 
 
 
 
 
386
 
387
  gloss_tokens = [token for token in gloss_input.upper().split() if token]
388
  if not gloss_tokens:
 
6
 
7
  from __future__ import annotations
8
 
9
+ import base64
10
  import contextlib
11
  import io
12
  import os
 
19
  from pathlib import Path
20
  from typing import Any, Dict, List, Optional
21
 
22
+ import cv2
23
+
24
  # ControlWorld provides plugin_base in the parent directory of every plugin
25
  import sys
26
 
 
49
 
50
  # Import local helpers lazily when needed
51
  from prompt2gloss import build_input as build_prompt_input # type: ignore
52
+ from pipeline01_text2gloss import load_available_glosses, translate_text_to_gloss # type: ignore
53
 
54
 
55
  def _to_bool(value: Any, default: bool = False) -> bool:
 
100
 
101
  self._refine_jobs: Dict[str, Dict[str, Any]] = {}
102
  self._refine_jobs_lock = threading.Lock()
103
+ self._pose_stream_jobs: Dict[str, Dict[str, Any]] = {}
104
+ self._pose_stream_jobs_lock = threading.Lock()
105
 
106
  self._prompt_tokenizer = None
107
  self._prompt_model = None
 
110
  self._torch = None
111
  self._qa_instances: Dict[int, SignLanguageQA] = {}
112
  self._generation_lock = threading.Lock()
113
+ self._available_glosses = None
114
 
115
  # ------------------------------------------------------------------
116
  # Lazy loaders
 
153
  self._qa_instances[key] = SignLanguageQA(max_candidates=key)
154
  return self._qa_instances[key]
155
 
156
+ def _get_available_glosses(self):
157
+ if self._available_glosses is None:
158
+ self._available_glosses = load_available_glosses(self.plugin_root / "pose_dict" / "WLASL_train.json")
159
+ return self._available_glosses
160
+
161
  # ------------------------------------------------------------------
162
  # Helpers
163
  # ------------------------------------------------------------------
 
213
  decoded = tokenizer.batch_decode(outputs, skip_special_tokens=True)[0].strip().upper()
214
  return decoded
215
 
216
+ def _generate_constrained_text_gloss(self, text: str, max_tokens: int) -> Dict[str, Any]:
217
+ result = translate_text_to_gloss(
218
+ text,
219
+ vocab=self._get_available_glosses(),
220
+ max_tokens=max_tokens,
221
+ )
222
+ return {
223
+ "gloss": result.gloss,
224
+ "tokens": result.tokens,
225
+ "matched": result.matched,
226
+ "dropped": result.dropped,
227
+ }
228
+
229
  def _build_output_path(self, gloss_tokens: List[str], draw_style: str) -> Path:
230
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
231
  slug = "_".join(gloss_tokens[:4]) if gloss_tokens else "gloss"
 
290
 
291
  if action == "generate_pose":
292
  return self.handle_generate_pose(data)
293
+ if action == "generate_pose_stream":
294
+ return self.handle_generate_pose_stream(data)
295
+ if action == "get_pose_stream_status":
296
+ return self.handle_get_pose_stream_status(data)
297
  if action == "list_recent_videos":
298
  return {"status": "success", "videos": self._list_recent_videos()}
299
  if action == "list_sign_videos":
 
308
  return self.handle_probe_video(data)
309
  if action == "prompt_to_gloss":
310
  return self.handle_prompt_to_gloss(data)
311
+ if action == "text_to_gloss":
312
+ return self.handle_text_to_gloss(data)
313
  if action == "prewarm":
314
  return self.handle_prewarm(data)
315
  return super().handle_message(message)
 
340
  except Exception as exc: # pylint: disable=broad-except
341
  return {"status": "error", "message": str(exc)}
342
 
343
+ def handle_text_to_gloss(self, data: Dict[str, Any]) -> Dict[str, Any]:
344
+ text = (data.get("text") or data.get("prompt") or "").strip()
345
+ if not text:
346
+ return {"status": "error", "message": "Text is empty."}
347
+ max_tokens = _safe_int(data.get("maxNewTokens"), 64)
348
+ try:
349
+ result = self._generate_constrained_text_gloss(text, max_tokens)
350
+ if not result["gloss"]:
351
+ return {
352
+ "status": "error",
353
+ "message": "No renderable gloss tokens found in the current pose vocabulary.",
354
+ **result,
355
+ }
356
+ return {"status": "success", **result}
357
+ except Exception as exc: # pylint: disable=broad-except
358
+ return {"status": "error", "message": str(exc)}
359
+
360
  def handle_prewarm(self, data: Dict[str, Any]) -> Dict[str, Any]:
361
  candidate_counts = data.get("candidateCounts")
362
  if isinstance(candidate_counts, list):
 
401
  "logs": logs or "(no logs)",
402
  }
403
 
404
+ def _encode_stream_frame(self, frame, quality: int = 72) -> Optional[str]:
405
+ try:
406
+ frame_bgr = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
407
+ ok, encoded = cv2.imencode(".jpg", frame_bgr, [int(cv2.IMWRITE_JPEG_QUALITY), quality])
408
+ if not ok:
409
+ return None
410
+ return "data:image/jpeg;base64," + base64.b64encode(encoded.tobytes()).decode("ascii")
411
+ except Exception:
412
+ return None
413
+
414
+ def _create_pose_stream_job(self, gloss: str, output_path: Path) -> Dict[str, Any]:
415
+ job_id = f"pose_stream_{int(time.time() * 1000)}_{uuid.uuid4().hex[:6]}"
416
+ job = {
417
+ "id": job_id,
418
+ "status": "running",
419
+ "created_at": time.time(),
420
+ "updated_at": time.time(),
421
+ "gloss": gloss,
422
+ "output_path": str(output_path),
423
+ "video_url": None,
424
+ "video_path": None,
425
+ "frames": [],
426
+ "total_frames": None,
427
+ "logs": "",
428
+ "error": None,
429
+ }
430
+ with self._pose_stream_jobs_lock:
431
+ self._pose_stream_jobs[job_id] = job
432
+ return job
433
+
434
+ def _append_pose_stream_frame(self, job_id: str, frame_idx: int, frame, total_frames: int):
435
+ data_url = self._encode_stream_frame(frame)
436
+ if not data_url:
437
+ return
438
+ with self._pose_stream_jobs_lock:
439
+ job = self._pose_stream_jobs.get(job_id)
440
+ if not job:
441
+ return
442
+ job["frames"].append({"index": frame_idx, "image": data_url})
443
+ job["total_frames"] = total_frames
444
+ job["updated_at"] = time.time()
445
+
446
+ def _execute_pose_stream_job(self, job_id: str, qa_system, gloss_tokens: List[str], output_path: Path, settings: Dict[str, Any]):
447
+ log_buffer = io.StringIO()
448
+ try:
449
+ def frame_callback(frame_idx, frame, total_frames):
450
+ self._append_pose_stream_frame(job_id, frame_idx, frame, total_frames)
451
+
452
+ with contextlib.redirect_stdout(log_buffer), contextlib.redirect_stderr(log_buffer):
453
+ success = qa_system.generate_video_from_glosses(
454
+ gloss_tokens,
455
+ output_path,
456
+ fps=settings["fps"],
457
+ width=settings["width"],
458
+ height=settings["height"],
459
+ smoothing_frames=settings["smoothing_frames"],
460
+ smoothing_method=settings["smoothing_method"],
461
+ npz_interpolation_frames=settings["npz_interp"],
462
+ scale_x=settings["scale_x"],
463
+ scale_y=settings["scale_y"],
464
+ hide_torso_lines=settings["hide_torso"],
465
+ ref_image_path=settings["ref_image"],
466
+ draw_style=settings["draw_style"],
467
+ normalize_pose=settings["normalize_pose"],
468
+ draw_conf_threshold=settings["draw_threshold"],
469
+ frame_callback=frame_callback,
470
+ )
471
+ logs = self._format_logs(log_buffer)
472
+ with self._pose_stream_jobs_lock:
473
+ job = self._pose_stream_jobs.get(job_id)
474
+ if not job:
475
+ return
476
+ job["logs"] = logs
477
+ if success and output_path.exists():
478
+ job["status"] = "success"
479
+ job["video_path"] = str(output_path)
480
+ job["video_url"] = self._to_web_url(output_path)
481
+ else:
482
+ job["status"] = "error"
483
+ job["error"] = "Video generation failed."
484
+ job["updated_at"] = time.time()
485
+ except Exception as exc: # pylint: disable=broad-except
486
+ with self._pose_stream_jobs_lock:
487
+ job = self._pose_stream_jobs.get(job_id)
488
+ if job:
489
+ job["status"] = "error"
490
+ job["error"] = str(exc)
491
+ job["logs"] = log_buffer.getvalue()
492
+ job["updated_at"] = time.time()
493
+ finally:
494
+ self._generation_lock.release()
495
+
496
+ def handle_generate_pose_stream(self, data: Dict[str, Any]) -> Dict[str, Any]:
497
+ if not self._generation_lock.acquire(blocking=False):
498
+ return {"status": "error", "message": "A generation job is already running. Please wait."}
499
+
500
+ try:
501
+ prompt_input_raw = (data.get("prompt") or "").strip()
502
+ text_input = (data.get("text") or prompt_input_raw).strip()
503
+ prompt_input = prompt_input_raw or text_input
504
+ gloss_input = (data.get("gloss") or "").strip()
505
+ max_new_tokens = _safe_int(data.get("maxNewTokens"), 64)
506
+ if not gloss_input:
507
+ if not text_input:
508
+ self._generation_lock.release()
509
+ return {"status": "error", "message": "Please enter Prompt/Text or a gloss sequence."}
510
+ translation_mode = (data.get("translationMode") or "text2gloss").strip().lower()
511
+ if translation_mode == "prompt2gloss":
512
+ gloss_input = self._generate_gloss(text_input, prompt_input, max_new_tokens)
513
+ else:
514
+ gloss_input = self._generate_constrained_text_gloss(text_input, max_new_tokens)["gloss"]
515
+
516
+ gloss_tokens = [token for token in gloss_input.upper().split() if token]
517
+ if not gloss_tokens:
518
+ self._generation_lock.release()
519
+ return {"status": "error", "message": "Gloss string is empty after normalization."}
520
+
521
+ settings = {
522
+ "fps": _safe_int(data.get("fps"), 30),
523
+ "width": _safe_int(data.get("width"), 512),
524
+ "height": _safe_int(data.get("height"), 512),
525
+ "smoothing_method": data.get("smoothing", "none") or "none",
526
+ "smoothing_frames": _safe_int(data.get("smoothingFrames"), 0),
527
+ "npz_interp": _safe_int(data.get("npzInterpolation"), 20),
528
+ "scale_x": _safe_float(data.get("scaleX"), 1.4),
529
+ "scale_y": _safe_float(data.get("scaleY"), 1.5),
530
+ "hide_torso": _to_bool(data.get("hideTorsoLines"), False),
531
+ "normalize_pose": _to_bool(data.get("normalizePose"), True),
532
+ "draw_style": (data.get("drawStyle") or "openpose").lower(),
533
+ "draw_threshold": _safe_float(data.get("drawConfidenceThreshold"), 0.6),
534
+ "ref_image": (data.get("refImagePath") or "").strip() or None,
535
+ }
536
+ max_candidates = _safe_int(data.get("maxCandidates"), 10)
537
+ qa_system = self._get_qa_system(max_candidates if max_candidates >= 0 else 10)
538
+ output_path = self._build_output_path(gloss_tokens, settings["draw_style"])
539
+ job = self._create_pose_stream_job(" ".join(gloss_tokens), output_path)
540
+ thread = threading.Thread(
541
+ target=self._execute_pose_stream_job,
542
+ args=(job["id"], qa_system, gloss_tokens, output_path, settings),
543
+ name=f"stable-pose-stream-{job['id']}",
544
+ daemon=True,
545
+ )
546
+ thread.start()
547
+ return {"status": "running", "job_id": job["id"], "gloss": " ".join(gloss_tokens), "fps": settings["fps"]}
548
+ except Exception as exc: # pylint: disable=broad-except
549
+ self._generation_lock.release()
550
+ return {"status": "error", "message": str(exc)}
551
+
552
+ def handle_get_pose_stream_status(self, data: Dict[str, Any]) -> Dict[str, Any]:
553
+ job_id = (data.get("jobId") or data.get("job_id") or "").strip()
554
+ cursor = _safe_int(data.get("cursor"), 0)
555
+ if not job_id:
556
+ return {"status": "error", "message": "jobId is required."}
557
+ with self._pose_stream_jobs_lock:
558
+ job = self._pose_stream_jobs.get(job_id)
559
+ if not job:
560
+ return {"status": "error", "message": "Stream job not found."}
561
+ frames = job["frames"][cursor:]
562
+ return {
563
+ "status": job["status"],
564
+ "job_id": job_id,
565
+ "gloss": job["gloss"],
566
+ "frames": frames,
567
+ "cursor": cursor + len(frames),
568
+ "frame_count": len(job["frames"]),
569
+ "total_frames": job.get("total_frames"),
570
+ "video_url": job.get("video_url"),
571
+ "video_path": job.get("video_path"),
572
+ "logs": job.get("logs") if job["status"] != "running" else "",
573
+ "message": job.get("error"),
574
+ }
575
+
576
  def handle_generate_pose(self, data: Dict[str, Any]) -> Dict[str, Any]:
577
  if not self._generation_lock.acquire(blocking=False):
578
  return {"status": "error", "message": "A generation job is already running. Please wait."}
 
602
  if not gloss_input:
603
  if not text_input:
604
  return {"status": "error", "message": "Please enter Prompt/Text or a gloss sequence."}
605
+ translation_mode = (data.get("translationMode") or "text2gloss").strip().lower()
606
+ if translation_mode == "prompt2gloss":
607
+ gloss_input = self._generate_gloss(text_input, prompt_input, max_new_tokens)
608
+ else:
609
+ gloss_result = self._generate_constrained_text_gloss(text_input, max_new_tokens)
610
+ gloss_input = gloss_result["gloss"]
611
 
612
  gloss_tokens = [token for token in gloss_input.upper().split() if token]
613
  if not gloss_tokens: