FangSen9000 commited on
Commit
806c397
·
1 Parent(s): 71f4e02

Update StableSigner refine flow and UI

Browse files
One-to-All-Animation/input_cache/ref_man_driven_ref_man_vid_HELLO_WORLD_20260214_204402_openpose_style_ref_2.5_pose_1.5_align_pose_h_608_w_608_fps_30.0/pose.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8732c6a915c280c222658122fac6a57623525fd9098fbd175d1040b7eadc0597
3
+ size 97652
One-to-All-Animation/video-generation/infer_refine.sh CHANGED
File without changes
__pycache__/gloss2pose.cpython-311.pyc CHANGED
Binary files a/__pycache__/gloss2pose.cpython-311.pyc and b/__pycache__/gloss2pose.cpython-311.pyc differ
 
__pycache__/pipeline02_gloss2pose.cpython-311.pyc ADDED
Binary file (72.7 kB). View file
 
__pycache__/viser_backend.cpython-311.pyc CHANGED
Binary files a/__pycache__/viser_backend.cpython-311.pyc and b/__pycache__/viser_backend.cpython-311.pyc differ
 
generated_pose_video/HELLO_WORLD_20260214_204402_openpose_style.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f5420aec22ff8da2a6e0a9a276262d1c40fed000b2c49e947617a87628664846
3
+ size 351247
generated_sign_video/{ref_man_vid_HELLO_GOOD_MORNING_20251215_142658_openpose_style_ref_2.5_pose_1.5-裁剪旋转-20260212-154852_square.mp4 → 2026-02-14_ref_2.5_pose_1.5/ref_man_vid_HELLO_GOOD_MORNING_20251215_142658_openpose_style_ref_2.5_pose_1.5-裁剪旋转-20260212-154852_square.mp4} RENAMED
File without changes
generated_sign_video/2026-02-14_ref_2.5_pose_1.5/ref_man_vid_HELLO_WORLD_20260214_204402_openpose_style_ref_2.5_pose_1.5.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6da91613ccd2cb30ba050a7c60c3aaf3b721de5e3794c6dcb677ec53f7a88c74
3
+ size 833697
generated_sign_video/2026-02-14_ref_2.5_pose_1.5/ref_man_vid_HELLO_WORLD_20260214_204402_openpose_style_ref_2.5_pose_1.5_pred.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d7aa35988de470c29eddf5a0e468a64438162a2d345feffc28baea061473cd25
3
+ size 498668
gloss2pose.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """Compatibility shim for legacy imports."""
2
+
3
+ from pipeline02_gloss2pose import SignLanguageQA # type: ignore
4
+
5
+ __all__ = ["SignLanguageQA"]
index.js CHANGED
@@ -37,15 +37,24 @@ function ensureStyles() {
37
  style.id = STYLE_ID;
38
  style.textContent = `
39
  .stable-signer-root {
40
- display: flex;
 
 
41
  gap: 20px;
42
  width: 100%;
43
  height: 100%;
44
  padding: 20px;
45
  box-sizing: border-box;
46
  }
47
- .stable-signer-left,
48
- .stable-signer-right {
 
 
 
 
 
 
 
49
  background: #fff;
50
  border-radius: 12px;
51
  box-shadow: 0 4px 16px rgba(15, 23, 42, 0.08);
@@ -54,10 +63,16 @@ function ensureStyles() {
54
  flex-direction: column;
55
  }
56
  .stable-signer-left {
57
- flex: 1.2;
 
 
58
  }
59
  .stable-signer-right {
60
- flex: 1;
 
 
 
 
61
  }
62
  .stable-video-frame {
63
  position: relative;
@@ -67,6 +82,38 @@ function ensureStyles() {
67
  border-radius: 10px;
68
  overflow: hidden;
69
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  .stable-video-frame video {
71
  position: absolute;
72
  top: 0;
@@ -253,7 +300,7 @@ function ensureStyles() {
253
  }
254
  @media (max-width: 1200px) {
255
  .stable-signer-root {
256
- flex-direction: column;
257
  }
258
  }
259
  `;
@@ -276,6 +323,11 @@ export default class StableSignerPlugin extends ControlWavePlugin {
276
  lastVideo: null
277
  };
278
  this.currentVideoObjectUrl = null;
 
 
 
 
 
279
  }
280
 
281
  async render(container) {
@@ -288,29 +340,107 @@ export default class StableSignerPlugin extends ControlWavePlugin {
288
  this.attachEvents();
289
  this.updateStatus('Idle');
290
  await this.refreshRecentVideos();
 
 
291
  }
292
 
293
  renderTemplate() {
294
  return `
295
  <div class="stable-signer-root">
296
- <div class="stable-signer-left">
297
- <div class="stable-video-frame">
298
- <video id="stable-video" controls playsinline loop muted></video>
299
- <div id="stable-video-placeholder" class="stable-video-placeholder">
300
- Generated pose video will appear here
 
 
 
 
 
 
 
 
 
 
 
301
  </div>
302
  </div>
303
- <div class="stable-video-controls">
304
- <select id="stable-video-select">
305
- <option value="">Select recently generated video</option>
306
- </select>
307
- <button id="stable-video-refresh" class="btn secondary">Refresh</button>
308
- </div>
309
- <div class="stable-meta" id="stable-video-meta">
310
- Waiting for generated video...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
311
  </div>
312
  </div>
313
- <div class="stable-signer-right">
314
  <div class="stable-control-header">
315
  <div class="stable-control-actions">
316
  <button id="stable-prewarm" class="btn secondary">Prewarm</button>
@@ -446,6 +576,22 @@ export default class StableSignerPlugin extends ControlWavePlugin {
446
  this.videoSelect = container.querySelector('#stable-video-select');
447
  this.videoRefreshBtn = container.querySelector('#stable-video-refresh');
448
  this.videoMeta = container.querySelector('#stable-video-meta');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
449
  this.prewarmBtn = container.querySelector('#stable-prewarm');
450
  this.translateBtn = container.querySelector('#stable-translate');
451
  this.generateBtn = container.querySelector('#stable-generate');
@@ -472,6 +618,9 @@ export default class StableSignerPlugin extends ControlWavePlugin {
472
  if (this.videoEl) {
473
  this.videoEl.style.display = 'none';
474
  }
 
 
 
475
  }
476
 
477
  attachEvents() {
@@ -480,6 +629,11 @@ export default class StableSignerPlugin extends ControlWavePlugin {
480
  this.generateBtn.addEventListener('click', () => this.handleGenerate());
481
  this.videoRefreshBtn.addEventListener('click', () => this.refreshRecentVideos());
482
  this.videoSelect.addEventListener('change', () => this.handleRecentSelection());
 
 
 
 
 
483
 
484
  window.addEventListener('websocket-connected', () => {
485
  this.updateStatus('WebSocket connected');
@@ -666,6 +820,11 @@ export default class StableSignerPlugin extends ControlWavePlugin {
666
  const absoluteUrl = url.startsWith('http') ? url : `${window.location.origin}${url}`;
667
  const hasQuery = absoluteUrl.includes('?');
668
  const fetchUrl = `${absoluteUrl}${hasQuery ? '&' : '?'}t=${Date.now()}`;
 
 
 
 
 
669
 
670
  const resetVideoEl = () => {
671
  this.videoEl.onloadeddata = null;
@@ -744,6 +903,36 @@ export default class StableSignerPlugin extends ControlWavePlugin {
744
  }
745
  }
746
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
747
  populateRecentVideos(videos) {
748
  this.videoSelect.innerHTML = '<option value="">Select recently generated video</option>';
749
  videos.forEach(video => {
@@ -756,15 +945,299 @@ export default class StableSignerPlugin extends ControlWavePlugin {
756
  });
757
  }
758
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
759
  async handleRecentSelection() {
760
  const option = this.videoSelect.selectedOptions[0];
761
  if (!option || !option.value) {
762
  return;
763
  }
 
764
  this.videoMeta.textContent = `${option.dataset.path} • ${option.dataset.size} MB`;
765
  await this.updateVideo(option.value, option.dataset.path);
766
  }
767
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
768
  setLoading(isLoading) {
769
  this.generateBtn.disabled = isLoading;
770
  this.generateBtn.textContent = isLoading ? 'Generating...' : 'Generate Pose Video';
 
37
  style.id = STYLE_ID;
38
  style.textContent = `
39
  .stable-signer-root {
40
+ display: grid;
41
+ grid-template-columns: minmax(0, 1.5fr) minmax(0, 1fr);
42
+ align-items: start;
43
  gap: 20px;
44
  width: 100%;
45
  height: 100%;
46
  padding: 20px;
47
  box-sizing: border-box;
48
  }
49
+ .stable-signer-left-col {
50
+ display: flex;
51
+ flex-direction: column;
52
+ gap: 20px;
53
+ min-width: 0;
54
+ width: 100%;
55
+ justify-self: stretch;
56
+ }
57
+ .stable-signer-panel {
58
  background: #fff;
59
  border-radius: 12px;
60
  box-shadow: 0 4px 16px rgba(15, 23, 42, 0.08);
 
63
  flex-direction: column;
64
  }
65
  .stable-signer-left {
66
+ min-width: 0;
67
+ align-self: start;
68
+ width: 100%;
69
  }
70
  .stable-signer-right {
71
+ min-width: 0;
72
+ }
73
+ .stable-signer-bottom {
74
+ min-width: 0;
75
+ width: 100%;
76
  }
77
  .stable-video-frame {
78
  position: relative;
 
82
  border-radius: 10px;
83
  overflow: hidden;
84
  }
85
+ .stable-selected-row {
86
+ display: flex;
87
+ align-items: center;
88
+ justify-content: space-between;
89
+ gap: 12px;
90
+ margin-bottom: 12px;
91
+ font-size: 13px;
92
+ color: #0f172a;
93
+ }
94
+ .stable-selected-row strong {
95
+ font-weight: 700;
96
+ }
97
+ .stable-selected-row span {
98
+ color: #334155;
99
+ }
100
+ .stable-refine-grid {
101
+ margin-top: 12px;
102
+ display: flex;
103
+ flex-direction: column;
104
+ gap: 12px;
105
+ }
106
+ .stable-output-section {
107
+ margin-top: 12px;
108
+ display: flex;
109
+ flex-direction: column;
110
+ gap: 12px;
111
+ }
112
+ .stable-output-section h4 {
113
+ margin: 8px 0 0;
114
+ font-size: 14px;
115
+ color: #0f172a;
116
+ }
117
  .stable-video-frame video {
118
  position: absolute;
119
  top: 0;
 
300
  }
301
  @media (max-width: 1200px) {
302
  .stable-signer-root {
303
+ grid-template-columns: 1fr;
304
  }
305
  }
306
  `;
 
323
  lastVideo: null
324
  };
325
  this.currentVideoObjectUrl = null;
326
+ this.refineVideoObjectUrl = null;
327
+ this.selectedPosePath = null;
328
+ this.refineJobId = null;
329
+ this.refineLogCursor = 0;
330
+ this.refinePollingTimer = null;
331
  }
332
 
333
  async render(container) {
 
340
  this.attachEvents();
341
  this.updateStatus('Idle');
342
  await this.refreshRecentVideos();
343
+ await this.refreshStage1Videos();
344
+ await this.refreshStage2Videos();
345
  }
346
 
347
  renderTemplate() {
348
  return `
349
  <div class="stable-signer-root">
350
+ <div class="stable-signer-left-col">
351
+ <div class="stable-signer-left stable-signer-panel">
352
+ <div class="stable-video-frame">
353
+ <video id="stable-video" controls playsinline loop muted></video>
354
+ <div id="stable-video-placeholder" class="stable-video-placeholder">
355
+ Generated pose video will appear here
356
+ </div>
357
+ </div>
358
+ <div class="stable-video-controls">
359
+ <select id="stable-video-select">
360
+ <option value="">Select recently generated video</option>
361
+ </select>
362
+ <button id="stable-video-refresh" class="btn secondary">Refresh</button>
363
+ </div>
364
+ <div class="stable-meta" id="stable-video-meta">
365
+ Waiting for generated video...
366
  </div>
367
  </div>
368
+ <div class="stable-signer-bottom stable-signer-panel">
369
+ <div class="stable-control-header">
370
+ <h3 style="margin:0;font-size:16px;">Render / Refine Output</h3>
371
+ <span class="stable-status-chip">Preview</span>
372
+ </div>
373
+ <div class="stable-selected-row">
374
+ <div>
375
+ <strong>Chosen Pose Video:</strong>
376
+ <span id="stable-selected-name">None</span>
377
+ </div>
378
+ <button id="stable-generate-refine" class="btn primary">Generate Refine Video</button>
379
+ </div>
380
+ <div class="stable-refine-grid">
381
+ <div class="stable-form-row">
382
+ <div class="form-group">
383
+ <label>Ref image path</label>
384
+ <input id="stable-refine-ref-image" type="text" placeholder="ref_img_dict/man.jpg">
385
+ </div>
386
+ <div class="form-group">
387
+ <label>GPU (optional)</label>
388
+ <input id="stable-refine-gpu" type="text" placeholder="auto">
389
+ </div>
390
+ </div>
391
+ <div class="stable-form-row">
392
+ <div class="form-group">
393
+ <label>Ref CFG</label>
394
+ <input id="stable-refine-ref-cfg" type="number" step="0.1" value="2.5">
395
+ </div>
396
+ <div class="form-group">
397
+ <label>Pose CFG</label>
398
+ <input id="stable-refine-pose-cfg" type="number" step="0.1" value="1.5">
399
+ </div>
400
+ </div>
401
+ <div class="stable-form-row">
402
+ <div class="form-group">
403
+ <label>Stage1 output dir</label>
404
+ <input id="stable-refine-stage1-out" type="text" value="generated_sign_video">
405
+ </div>
406
+ <div class="form-group">
407
+ <label>Stage2 output dir</label>
408
+ <input id="stable-refine-stage2-out" type="text" value="generated_sign_video_refine">
409
+ </div>
410
+ </div>
411
+ </div>
412
+ <div class="stable-output-section">
413
+ <h4>Stage 1 Output (generated_sign_video)</h4>
414
+ <div class="stable-video-controls">
415
+ <select id="stable-stage1-select">
416
+ <option value="">Select stage1 output video</option>
417
+ </select>
418
+ <button id="stable-stage1-refresh" class="btn secondary">Refresh</button>
419
+ </div>
420
+ <h4>Stage 2 Output (generated_sign_video_refine)</h4>
421
+ <div class="stable-video-controls">
422
+ <select id="stable-stage2-select">
423
+ <option value="">Select stage2 output video</option>
424
+ </select>
425
+ <button id="stable-stage2-refresh" class="btn secondary">Refresh</button>
426
+ </div>
427
+ <div class="stable-video-frame" style="padding-top: 56.25%;">
428
+ <video id="stable-output-video" controls playsinline loop muted></video>
429
+ <div id="stable-output-placeholder" class="stable-video-placeholder">
430
+ Rendered/refined video will appear here
431
+ </div>
432
+ </div>
433
+ <div class="stable-meta" id="stable-output-meta">
434
+ Waiting for refine output...
435
+ </div>
436
+ </div>
437
+ <div class="stable-logs">
438
+ <label>Render / Refine logs</label>
439
+ <pre id="stable-refine-logs">(waiting for refine...)</pre>
440
+ </div>
441
  </div>
442
  </div>
443
+ <div class="stable-signer-right stable-signer-panel">
444
  <div class="stable-control-header">
445
  <div class="stable-control-actions">
446
  <button id="stable-prewarm" class="btn secondary">Prewarm</button>
 
576
  this.videoSelect = container.querySelector('#stable-video-select');
577
  this.videoRefreshBtn = container.querySelector('#stable-video-refresh');
578
  this.videoMeta = container.querySelector('#stable-video-meta');
579
+ this.selectedName = container.querySelector('#stable-selected-name');
580
+ this.generateRefineBtn = container.querySelector('#stable-generate-refine');
581
+ this.refineRefImageInput = container.querySelector('#stable-refine-ref-image');
582
+ this.refineGpuInput = container.querySelector('#stable-refine-gpu');
583
+ this.refineRefCfgInput = container.querySelector('#stable-refine-ref-cfg');
584
+ this.refinePoseCfgInput = container.querySelector('#stable-refine-pose-cfg');
585
+ this.refineStage1OutInput = container.querySelector('#stable-refine-stage1-out');
586
+ this.refineStage2OutInput = container.querySelector('#stable-refine-stage2-out');
587
+ this.stage1Select = container.querySelector('#stable-stage1-select');
588
+ this.stage1RefreshBtn = container.querySelector('#stable-stage1-refresh');
589
+ this.stage2Select = container.querySelector('#stable-stage2-select');
590
+ this.stage2RefreshBtn = container.querySelector('#stable-stage2-refresh');
591
+ this.outputVideoEl = container.querySelector('#stable-output-video');
592
+ this.outputPlaceholder = container.querySelector('#stable-output-placeholder');
593
+ this.outputMeta = container.querySelector('#stable-output-meta');
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');
 
618
  if (this.videoEl) {
619
  this.videoEl.style.display = 'none';
620
  }
621
+ if (this.outputVideoEl) {
622
+ this.outputVideoEl.style.display = 'none';
623
+ }
624
  }
625
 
626
  attachEvents() {
 
629
  this.generateBtn.addEventListener('click', () => this.handleGenerate());
630
  this.videoRefreshBtn.addEventListener('click', () => this.refreshRecentVideos());
631
  this.videoSelect.addEventListener('change', () => this.handleRecentSelection());
632
+ this.generateRefineBtn.addEventListener('click', () => this.handleGenerateRefine());
633
+ this.stage1RefreshBtn.addEventListener('click', () => this.refreshStage1Videos());
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');
 
820
  const absoluteUrl = url.startsWith('http') ? url : `${window.location.origin}${url}`;
821
  const hasQuery = absoluteUrl.includes('?');
822
  const fetchUrl = `${absoluteUrl}${hasQuery ? '&' : '?'}t=${Date.now()}`;
823
+ if (path) {
824
+ this.setSelectedPose(path);
825
+ } else {
826
+ this.updateSelectedLabel(absoluteUrl);
827
+ }
828
 
829
  const resetVideoEl = () => {
830
  this.videoEl.onloadeddata = null;
 
903
  }
904
  }
905
 
906
+ async refreshStage1Videos() {
907
+ if (!window.controlWaveWebSocket || !window.controlWaveWebSocket.sendRequest) {
908
+ this.updateStatus('Waiting for WebSocket...');
909
+ return;
910
+ }
911
+ try {
912
+ const response = await window.controlWaveWebSocket.sendRequest(this.id, {
913
+ action: 'list_sign_videos'
914
+ });
915
+ this.populateStage1Videos(response.videos || []);
916
+ } catch (error) {
917
+ this.outputMeta.textContent = `Failed to refresh stage1 list: ${error.message}`;
918
+ }
919
+ }
920
+
921
+ async refreshStage2Videos() {
922
+ if (!window.controlWaveWebSocket || !window.controlWaveWebSocket.sendRequest) {
923
+ this.updateStatus('Waiting for WebSocket...');
924
+ return;
925
+ }
926
+ try {
927
+ const response = await window.controlWaveWebSocket.sendRequest(this.id, {
928
+ action: 'list_refine_videos'
929
+ });
930
+ this.populateStage2Videos(response.videos || []);
931
+ } catch (error) {
932
+ this.outputMeta.textContent = `Failed to refresh stage2 list: ${error.message}`;
933
+ }
934
+ }
935
+
936
  populateRecentVideos(videos) {
937
  this.videoSelect.innerHTML = '<option value="">Select recently generated video</option>';
938
  videos.forEach(video => {
 
945
  });
946
  }
947
 
948
+ populateStage1Videos(videos) {
949
+ this.stage1Select.innerHTML = '<option value="">Select stage1 output video</option>';
950
+ videos.forEach(video => {
951
+ const option = document.createElement('option');
952
+ option.value = video.url;
953
+ option.dataset.path = video.path;
954
+ option.dataset.size = video.size_mb;
955
+ option.textContent = `${video.name} (${video.size_mb} MB)`;
956
+ this.stage1Select.appendChild(option);
957
+ });
958
+ }
959
+
960
+ populateStage2Videos(videos) {
961
+ this.stage2Select.innerHTML = '<option value="">Select stage2 output video</option>';
962
+ videos.forEach(video => {
963
+ const option = document.createElement('option');
964
+ option.value = video.url;
965
+ option.dataset.path = video.path;
966
+ option.dataset.size = video.size_mb;
967
+ option.textContent = `${video.name} (${video.size_mb} MB)`;
968
+ this.stage2Select.appendChild(option);
969
+ });
970
+ }
971
+
972
  async handleRecentSelection() {
973
  const option = this.videoSelect.selectedOptions[0];
974
  if (!option || !option.value) {
975
  return;
976
  }
977
+ this.setSelectedPose(option.dataset.path || option.value);
978
  this.videoMeta.textContent = `${option.dataset.path} • ${option.dataset.size} MB`;
979
  await this.updateVideo(option.value, option.dataset.path);
980
  }
981
 
982
+ async handleStage1Selection() {
983
+ const option = this.stage1Select.selectedOptions[0];
984
+ if (!option || !option.value) {
985
+ return;
986
+ }
987
+ this.outputMeta.textContent = `${option.dataset.path} • ${option.dataset.size} MB`;
988
+ await this.updateOutputVideo(option.value, option.dataset.path);
989
+ }
990
+
991
+ async handleStage2Selection() {
992
+ const option = this.stage2Select.selectedOptions[0];
993
+ if (!option || !option.value) {
994
+ return;
995
+ }
996
+ this.outputMeta.textContent = `${option.dataset.path} • ${option.dataset.size} MB`;
997
+ await this.updateOutputVideo(option.value, option.dataset.path);
998
+ }
999
+
1000
+ updateSelectedLabel(pathOrUrl) {
1001
+ if (!this.selectedName) return;
1002
+ if (!pathOrUrl) {
1003
+ this.selectedName.textContent = 'None';
1004
+ return;
1005
+ }
1006
+ const clean = String(pathOrUrl).split('?')[0];
1007
+ const parts = clean.split('/');
1008
+ this.selectedName.textContent = parts[parts.length - 1] || clean;
1009
+ }
1010
+
1011
+ setSelectedPose(pathOrUrl) {
1012
+ this.selectedPosePath = pathOrUrl;
1013
+ this.updateSelectedLabel(pathOrUrl);
1014
+ }
1015
+
1016
+ collectRefinePayload() {
1017
+ return {
1018
+ poseVideoPath: this.selectedPosePath,
1019
+ refImagePath: (this.refineRefImageInput.value || this.refImageInput.value || '').trim(),
1020
+ refCfg: toFloat(this.refineRefCfgInput.value, 2.5),
1021
+ poseCfg: toFloat(this.refinePoseCfgInput.value, 1.5),
1022
+ stage1Out: (this.refineStage1OutInput.value || '').trim(),
1023
+ stage2Out: (this.refineStage2OutInput.value || '').trim(),
1024
+ gpu: (this.refineGpuInput.value || '').trim(),
1025
+ };
1026
+ }
1027
+
1028
+ async handleGenerateRefine() {
1029
+ if (!window.controlWaveWebSocket || !window.controlWaveWebSocket.sendRequest) {
1030
+ this.updateStatus('WebSocket not ready');
1031
+ return;
1032
+ }
1033
+ const payload = this.collectRefinePayload();
1034
+ if (!payload.poseVideoPath) {
1035
+ this.updateStatus('Choose a pose video first');
1036
+ this.refineLogsPre.textContent = 'Please select a pose video from the list above.';
1037
+ return;
1038
+ }
1039
+ if (this.refineJobId) {
1040
+ this.updateStatus('Refine already running');
1041
+ return;
1042
+ }
1043
+ this.setRefineLoading(true);
1044
+ this.updateStatus('Refine running...');
1045
+ this.refineLogsPre.textContent = 'Starting refine...\n';
1046
+ try {
1047
+ const response = await window.controlWaveWebSocket.sendRequest(this.id, {
1048
+ action: 'generate_refine',
1049
+ data: payload
1050
+ });
1051
+ const status = typeof response.status === 'string' ? response.status.toLowerCase() : '';
1052
+ if (status === 'running' && response.job_id) {
1053
+ this.refineJobId = response.job_id;
1054
+ this.refineLogCursor = 0;
1055
+ this.startRefineLogPolling();
1056
+ return;
1057
+ }
1058
+ if (status === 'success') {
1059
+ if (response.logs) {
1060
+ this.refineLogsPre.textContent = response.logs;
1061
+ }
1062
+ if (response.stage2_video_url) {
1063
+ await this.updateOutputVideo(response.stage2_video_url, response.stage2_video_path);
1064
+ } else if (response.stage1_video_url) {
1065
+ await this.updateOutputVideo(response.stage1_video_url, response.stage1_video_path);
1066
+ }
1067
+ await Promise.all([this.refreshStage1Videos(), this.refreshStage2Videos()]);
1068
+ this.updateStatus('Refine completed');
1069
+ } else {
1070
+ this.updateStatus('Refine failed');
1071
+ this.refineLogsPre.textContent = response.message || response.error || response.logs || 'Refine failed';
1072
+ }
1073
+ } catch (error) {
1074
+ this.updateStatus('Refine failed');
1075
+ this.refineLogsPre.textContent = (error && error.message) ? error.message : 'Refine request failed';
1076
+ }
1077
+ this.setRefineLoading(false);
1078
+ }
1079
+
1080
+ startRefineLogPolling() {
1081
+ this.stopRefineLogPolling();
1082
+ this.pollRefineStatus();
1083
+ this.refinePollingTimer = setInterval(() => {
1084
+ this.pollRefineStatus();
1085
+ }, 1200);
1086
+ }
1087
+
1088
+ stopRefineLogPolling() {
1089
+ if (this.refinePollingTimer) {
1090
+ clearInterval(this.refinePollingTimer);
1091
+ this.refinePollingTimer = null;
1092
+ }
1093
+ }
1094
+
1095
+ async pollRefineStatus() {
1096
+ if (!this.refineJobId) {
1097
+ return;
1098
+ }
1099
+ try {
1100
+ const response = await window.controlWaveWebSocket.sendRequest(this.id, {
1101
+ action: 'get_refine_status',
1102
+ data: {
1103
+ job_id: this.refineJobId,
1104
+ last_index: this.refineLogCursor
1105
+ }
1106
+ });
1107
+ if (response.status !== 'success') {
1108
+ throw new Error(response.message || 'Failed to fetch refine status');
1109
+ }
1110
+ if (Array.isArray(response.logs) && response.logs.length > 0) {
1111
+ this.appendRefineLogs(response.logs);
1112
+ }
1113
+ if (typeof response.next_index === 'number') {
1114
+ this.refineLogCursor = response.next_index;
1115
+ } else if (response.logs) {
1116
+ this.refineLogCursor += response.logs.length;
1117
+ }
1118
+
1119
+ const jobStatus = response.job_status;
1120
+ if (jobStatus === 'success' && response.result) {
1121
+ const result = response.result;
1122
+ if (result.stage2_video_url) {
1123
+ await this.updateOutputVideo(result.stage2_video_url, result.stage2_video_path);
1124
+ } else if (result.stage1_video_url) {
1125
+ await this.updateOutputVideo(result.stage1_video_url, result.stage1_video_path);
1126
+ }
1127
+ await Promise.all([this.refreshStage1Videos(), this.refreshStage2Videos()]);
1128
+ this.updateStatus('Refine completed');
1129
+ this.finishRefineJob();
1130
+ } else if (jobStatus === 'error') {
1131
+ const errMsg = response.error_message || 'Refine failed';
1132
+ this.updateStatus(`Refine failed: ${errMsg}`);
1133
+ this.finishRefineJob();
1134
+ } else if (jobStatus === 'running') {
1135
+ this.updateStatus('Refine running...');
1136
+ }
1137
+ } catch (error) {
1138
+ this.updateStatus(`Refine polling failed: ${error.message}`);
1139
+ this.finishRefineJob();
1140
+ }
1141
+ }
1142
+
1143
+ appendRefineLogs(newLines) {
1144
+ if (!this.refineLogsPre || !newLines) {
1145
+ return;
1146
+ }
1147
+ const text = Array.isArray(newLines) ? newLines.join('\n') : newLines;
1148
+ if (!text) {
1149
+ return;
1150
+ }
1151
+ if (!this.refineLogsPre.textContent || this.refineLogsPre.textContent === '(waiting for refine...)') {
1152
+ this.refineLogsPre.textContent = '';
1153
+ }
1154
+ if (this.refineLogsPre.textContent && !this.refineLogsPre.textContent.endsWith('\n')) {
1155
+ this.refineLogsPre.textContent += '\n';
1156
+ }
1157
+ this.refineLogsPre.textContent += text + '\n';
1158
+ this.refineLogsPre.scrollTop = this.refineLogsPre.scrollHeight;
1159
+ }
1160
+
1161
+ finishRefineJob() {
1162
+ this.stopRefineLogPolling();
1163
+ this.refineJobId = null;
1164
+ this.setRefineLoading(false);
1165
+ }
1166
+
1167
+ async updateOutputVideo(url, path) {
1168
+ if (!url || !this.outputVideoEl) return;
1169
+ const absoluteUrl = url.startsWith('http') ? url : `${window.location.origin}${url}`;
1170
+ const hasQuery = absoluteUrl.includes('?');
1171
+ const fetchUrl = `${absoluteUrl}${hasQuery ? '&' : '?'}t=${Date.now()}`;
1172
+
1173
+ const resetVideoEl = () => {
1174
+ this.outputVideoEl.onloadeddata = null;
1175
+ this.outputVideoEl.onerror = null;
1176
+ this.outputVideoEl.pause();
1177
+ this.outputVideoEl.removeAttribute('src');
1178
+ this.outputVideoEl.load();
1179
+ };
1180
+
1181
+ this.outputPlaceholder.style.display = 'flex';
1182
+ this.outputPlaceholder.textContent = 'Loading video…';
1183
+ this.outputVideoEl.style.display = 'none';
1184
+ resetVideoEl();
1185
+
1186
+ if (this.refineVideoObjectUrl) {
1187
+ URL.revokeObjectURL(this.refineVideoObjectUrl);
1188
+ this.refineVideoObjectUrl = null;
1189
+ }
1190
+
1191
+ try {
1192
+ const response = await fetch(fetchUrl, { cache: 'no-store' });
1193
+ if (!response.ok) {
1194
+ throw new Error(`HTTP ${response.status}`);
1195
+ }
1196
+
1197
+ const blob = await response.blob();
1198
+ const objectUrl = URL.createObjectURL(blob);
1199
+ this.refineVideoObjectUrl = objectUrl;
1200
+
1201
+ this.outputVideoEl.onloadeddata = () => {
1202
+ this.outputVideoEl.onloadeddata = null;
1203
+ this.outputVideoEl.onerror = null;
1204
+ this.outputPlaceholder.style.display = 'none';
1205
+ this.outputVideoEl.style.display = 'block';
1206
+ const playPromise = this.outputVideoEl.play();
1207
+ if (playPromise && typeof playPromise.catch === 'function') {
1208
+ playPromise.catch(() => {});
1209
+ }
1210
+ this.outputMeta.textContent = `Video: ${path || absoluteUrl}`;
1211
+ };
1212
+
1213
+ this.outputVideoEl.onerror = () => {
1214
+ this.outputVideoEl.onloadeddata = null;
1215
+ this.outputVideoEl.onerror = null;
1216
+ this.outputPlaceholder.style.display = 'flex';
1217
+ this.outputPlaceholder.textContent = 'Video load failed';
1218
+ const mediaError = this.outputVideoEl.error;
1219
+ console.error('[StableSigner] output video load error', mediaError ? {
1220
+ code: mediaError.code,
1221
+ message: mediaError.message
1222
+ } : 'unknown');
1223
+ };
1224
+
1225
+ this.outputVideoEl.src = objectUrl;
1226
+ this.outputVideoEl.load();
1227
+ } catch (error) {
1228
+ resetVideoEl();
1229
+ this.outputPlaceholder.style.display = 'flex';
1230
+ this.outputPlaceholder.textContent = 'Video load failed';
1231
+ console.error('[StableSigner] output video fetch failed', error);
1232
+ }
1233
+ }
1234
+
1235
+ setRefineLoading(isLoading) {
1236
+ if (!this.generateRefineBtn) return;
1237
+ this.generateRefineBtn.disabled = isLoading;
1238
+ this.generateRefineBtn.textContent = isLoading ? 'Generating...' : 'Generate Refine Video';
1239
+ }
1240
+
1241
  setLoading(isLoading) {
1242
  this.generateBtn.disabled = isLoading;
1243
  this.generateBtn.textContent = isLoading ? 'Generating...' : 'Generate Pose Video';
pipeline03_pose2video.sh CHANGED
@@ -104,6 +104,22 @@ run_stage1() {
104
  )
105
  }
106
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  resolve_stage1_output() {
108
  local pose_base ref_base stage1_pattern stage1_video
109
  pose_base="$(basename "${POSE_VIDEO}")"
@@ -111,8 +127,9 @@ resolve_stage1_output() {
111
  ref_base="$(basename "${REF_IMAGE}")"
112
  ref_base="${ref_base%.*}"
113
 
114
- stage1_pattern="${STAGE1_OUT_DIR}"/*_ref_${REF_CFG}_pose_${POSE_CFG}/"ref_${ref_base}_vid_${pose_base}_ref_${REF_CFG}_pose_${POSE_CFG}.mp4"
115
- stage1_video="$(ls -t ${stage1_pattern} 2>/dev/null | head -n 1 || true)"
 
116
  if [[ -z "${stage1_video}" ]]; then
117
  echo "Stage1 output not found. Pattern: ${stage1_pattern}" >&2
118
  exit 1
@@ -136,12 +153,23 @@ run_stage2() {
136
  }
137
 
138
  if [[ "${STAGE2_ONLY}" -ne 1 ]]; then
139
- run_stage1
140
- if [[ "${STAGE1_ONLY}" -eq 1 ]]; then
141
- echo "Done (stage1 only)."
142
- exit 0
 
 
 
 
 
 
 
 
 
 
 
 
143
  fi
144
- STAGE2_INPUT="$(resolve_stage1_output)"
145
  fi
146
 
147
  run_stage2 "${STAGE2_INPUT}"
 
104
  )
105
  }
106
 
107
+ find_stage1_output() {
108
+ local pose_base ref_base stage1_pattern stage1_video
109
+ pose_base="$(basename "${POSE_VIDEO}")"
110
+ pose_base="${pose_base%.*}"
111
+ ref_base="$(basename "${REF_IMAGE}")"
112
+ ref_base="${ref_base%.*}"
113
+
114
+ stage1_pattern="${STAGE1_OUT_DIR}"/*_ref_${REF_CFG}_pose_${POSE_CFG}/"ref_${ref_base}_vid_${pose_base}_ref_${REF_CFG}_pose_${POSE_CFG}"*.mp4
115
+ stage1_square="${STAGE1_OUT_DIR}"/*_ref_${REF_CFG}_pose_${POSE_CFG}/"ref_${ref_base}_vid_${pose_base}_ref_${REF_CFG}_pose_${POSE_CFG}"*square*.mp4
116
+ stage1_video="$(ls -t ${stage1_square} 2>/dev/null | head -n 1 || true)"
117
+ if [[ -z "${stage1_video}" ]]; then
118
+ stage1_video="$(ls -t ${stage1_pattern} 2>/dev/null | head -n 1 || true)"
119
+ fi
120
+ echo "${stage1_video}"
121
+ }
122
+
123
  resolve_stage1_output() {
124
  local pose_base ref_base stage1_pattern stage1_video
125
  pose_base="$(basename "${POSE_VIDEO}")"
 
127
  ref_base="$(basename "${REF_IMAGE}")"
128
  ref_base="${ref_base%.*}"
129
 
130
+ stage1_pattern="${STAGE1_OUT_DIR}"/*_ref_${REF_CFG}_pose_${POSE_CFG}/"ref_${ref_base}_vid_${pose_base}_ref_${REF_CFG}_pose_${POSE_CFG}"*.mp4
131
+ stage1_square="${STAGE1_OUT_DIR}"/*_ref_${REF_CFG}_pose_${POSE_CFG}/"ref_${ref_base}_vid_${pose_base}_ref_${REF_CFG}_pose_${POSE_CFG}"*square*.mp4
132
+ stage1_video="$(find_stage1_output)"
133
  if [[ -z "${stage1_video}" ]]; then
134
  echo "Stage1 output not found. Pattern: ${stage1_pattern}" >&2
135
  exit 1
 
153
  }
154
 
155
  if [[ "${STAGE2_ONLY}" -ne 1 ]]; then
156
+ existing_stage1="$(find_stage1_output)"
157
+ if [[ -n "${existing_stage1}" ]]; then
158
+ echo "Stage1 output found for this pose/ref. Skipping stage1 and jumping to stage2."
159
+ echo "Stage2 will use: ${existing_stage1}"
160
+ if [[ "${STAGE1_ONLY}" -eq 1 ]]; then
161
+ echo "Stage1-only requested; skipping stage1 because output already exists."
162
+ exit 0
163
+ fi
164
+ STAGE2_INPUT="${existing_stage1}"
165
+ else
166
+ run_stage1
167
+ if [[ "${STAGE1_ONLY}" -eq 1 ]]; then
168
+ echo "Done (stage1 only)."
169
+ exit 0
170
+ fi
171
+ STAGE2_INPUT="$(resolve_stage1_output)"
172
  fi
 
173
  fi
174
 
175
  run_stage2 "${STAGE2_INPUT}"
prompt2gloss/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (335 Bytes). View file
 
prompt2gloss/__pycache__/prompt2gloss.cpython-311.pyc ADDED
Binary file (4.5 kB). View file
 
viser_backend.py CHANGED
@@ -8,7 +8,11 @@ from __future__ import annotations
8
 
9
  import contextlib
10
  import io
 
 
11
  import threading
 
 
12
  from dataclasses import dataclass
13
  from datetime import datetime
14
  from pathlib import Path
@@ -85,6 +89,13 @@ class StableSignerBackend(PluginBackendBase):
85
  self.web_base_url = f"/plugins/{self.plugin_root.name}"
86
  self.output_dir = self.plugin_root / "generated_pose_video"
87
  self.output_dir.mkdir(parents=True, exist_ok=True)
 
 
 
 
 
 
 
88
 
89
  self._prompt_tokenizer = None
90
  self._prompt_model = None
@@ -221,6 +232,30 @@ class StableSignerBackend(PluginBackendBase):
221
  )
222
  return result
223
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
  # ------------------------------------------------------------------
225
  # Message handling
226
  # ------------------------------------------------------------------
@@ -232,6 +267,14 @@ class StableSignerBackend(PluginBackendBase):
232
  return self.handle_generate_pose(data)
233
  if action == "list_recent_videos":
234
  return {"status": "success", "videos": self._list_recent_videos()}
 
 
 
 
 
 
 
 
235
  if action == "probe_video":
236
  return self.handle_probe_video(data)
237
  if action == "prompt_to_gloss":
@@ -429,6 +472,250 @@ class StableSignerBackend(PluginBackendBase):
429
  finally:
430
  self._generation_lock.release()
431
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
432
 
433
  # Entry point required by ControlWorld's loader
434
  PluginBackend = StableSignerBackend
 
8
 
9
  import contextlib
10
  import io
11
+ import os
12
+ import subprocess
13
  import threading
14
+ import time
15
+ import uuid
16
  from dataclasses import dataclass
17
  from datetime import datetime
18
  from pathlib import Path
 
89
  self.web_base_url = f"/plugins/{self.plugin_root.name}"
90
  self.output_dir = self.plugin_root / "generated_pose_video"
91
  self.output_dir.mkdir(parents=True, exist_ok=True)
92
+ self.sign_output_dir = self.plugin_root / "generated_sign_video"
93
+ self.sign_output_dir.mkdir(parents=True, exist_ok=True)
94
+ self.refine_output_dir = self.plugin_root / "generated_sign_video_refine"
95
+ self.refine_output_dir.mkdir(parents=True, exist_ok=True)
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
 
232
  )
233
  return result
234
 
235
+ def _list_recent_videos_in_dir(self, base_dir: Path, limit: int = 12, recursive: bool = False) -> List[Dict[str, Any]]:
236
+ if not base_dir.exists():
237
+ return []
238
+ if recursive:
239
+ candidates = [p for p in base_dir.rglob("*.mp4") if p.is_file()]
240
+ else:
241
+ candidates = [p for p in base_dir.glob("*.mp4") if p.is_file()]
242
+ videos = sorted(candidates, key=lambda p: p.stat().st_mtime, reverse=True)
243
+ result = []
244
+ for video in videos[:limit]:
245
+ url = self._to_web_url(video)
246
+ if not url:
247
+ continue
248
+ result.append(
249
+ {
250
+ "name": video.name,
251
+ "url": url,
252
+ "path": str(video),
253
+ "updated": datetime.fromtimestamp(video.stat().st_mtime).isoformat(),
254
+ "size_mb": round(video.stat().st_size / (1024 * 1024), 2),
255
+ }
256
+ )
257
+ return result
258
+
259
  # ------------------------------------------------------------------
260
  # Message handling
261
  # ------------------------------------------------------------------
 
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":
271
+ return {"status": "success", "videos": self._list_recent_videos_in_dir(self.sign_output_dir, recursive=True)}
272
+ if action == "list_refine_videos":
273
+ return {"status": "success", "videos": self._list_recent_videos_in_dir(self.refine_output_dir, recursive=True)}
274
+ if action == "generate_refine":
275
+ return self.handle_generate_refine(data)
276
+ if action == "get_refine_status":
277
+ return self.handle_get_refine_status(data)
278
  if action == "probe_video":
279
  return self.handle_probe_video(data)
280
  if action == "prompt_to_gloss":
 
472
  finally:
473
  self._generation_lock.release()
474
 
475
+ def handle_generate_refine(self, data: Dict[str, Any]) -> Dict[str, Any]:
476
+ if not self._generation_lock.acquire(blocking=False):
477
+ return {"status": "error", "message": "A generation job is already running. Please wait."}
478
+
479
+ try:
480
+ pose_video_raw = (data.get("poseVideoPath") or "").strip()
481
+ if not pose_video_raw:
482
+ self._generation_lock.release()
483
+ return {"status": "error", "message": "Pose video path is required."}
484
+
485
+ pose_path = Path(pose_video_raw)
486
+ if not pose_path.is_file():
487
+ info = self._resolve_existing_video(pose_video_raw)
488
+ if not info:
489
+ self._generation_lock.release()
490
+ return {"status": "error", "message": "Pose video not found."}
491
+ pose_path = info.path
492
+
493
+ ref_image_raw = (data.get("refImagePath") or "").strip()
494
+ if ref_image_raw:
495
+ ref_path = Path(ref_image_raw)
496
+ if not ref_path.is_absolute():
497
+ ref_path = (self.plugin_root / ref_path).resolve()
498
+ else:
499
+ ref_path = self.plugin_root / "ref_img_dict" / "man.jpg"
500
+ if not ref_path.exists():
501
+ self._generation_lock.release()
502
+ return {"status": "error", "message": f"Reference image not found: {ref_path}"}
503
+
504
+ ref_cfg = _safe_float(data.get("refCfg"), 2.5)
505
+ pose_cfg = _safe_float(data.get("poseCfg"), 1.5)
506
+
507
+ stage1_out_raw = (data.get("stage1Out") or "").strip()
508
+ stage2_out_raw = (data.get("stage2Out") or "").strip()
509
+
510
+ stage1_out = self._resolve_output_dir(stage1_out_raw, self.sign_output_dir)
511
+ stage2_out = self._resolve_output_dir(stage2_out_raw, self.refine_output_dir)
512
+
513
+ gpu_id = (data.get("gpu") or "").strip()
514
+
515
+ script_path = self.plugin_root / "pipeline03_pose2video.sh"
516
+ if not script_path.exists():
517
+ self._generation_lock.release()
518
+ return {"status": "error", "message": f"Pipeline script not found: {script_path}"}
519
+
520
+ cmd = [
521
+ "bash",
522
+ str(script_path),
523
+ "--pose-video",
524
+ str(pose_path),
525
+ "--ref-image",
526
+ str(ref_path),
527
+ "--stage1-out",
528
+ str(stage1_out),
529
+ "--stage2-out",
530
+ str(stage2_out),
531
+ "--ref-cfg",
532
+ str(ref_cfg),
533
+ "--pose-cfg",
534
+ str(pose_cfg),
535
+ ]
536
+ if gpu_id:
537
+ cmd.extend(["--gpu", gpu_id])
538
+
539
+ job = self._create_refine_job(
540
+ pose_path=str(pose_path),
541
+ ref_path=str(ref_path),
542
+ stage1_out=str(stage1_out),
543
+ stage2_out=str(stage2_out),
544
+ )
545
+ self._append_refine_log(job["id"], f"🧩 Pose video: {pose_path}")
546
+ self._append_refine_log(job["id"], f"🖼️ Ref image: {ref_path}")
547
+ self._append_refine_log(job["id"], f"📦 Stage1 out: {stage1_out}")
548
+ self._append_refine_log(job["id"], f"📦 Stage2 out: {stage2_out}")
549
+ if gpu_id:
550
+ self._append_refine_log(job["id"], f"🎯 GPU: {gpu_id}")
551
+ self._append_refine_log(job["id"], f"🚀 Command: {' '.join(cmd)}")
552
+
553
+ thread = threading.Thread(
554
+ target=self._execute_refine_job,
555
+ args=(job["id"], cmd),
556
+ name=f"stable-refine-{job['id']}",
557
+ daemon=True,
558
+ )
559
+ job["thread"] = thread
560
+ thread.start()
561
+
562
+ return {"status": "running", "job_id": job["id"], "message": "Refine job started."}
563
+ except Exception as exc: # pylint: disable=broad-except
564
+ self._generation_lock.release()
565
+ log = io.StringIO()
566
+ with contextlib.redirect_stdout(log), contextlib.redirect_stderr(log):
567
+ import traceback
568
+
569
+ traceback.print_exc()
570
+ logs = log.getvalue()
571
+ return {"status": "error", "message": str(exc), "logs": logs}
572
+
573
+ def _resolve_output_dir(self, raw_value: str, fallback: Path) -> Path:
574
+ if not raw_value:
575
+ target = fallback
576
+ else:
577
+ candidate = Path(raw_value)
578
+ if not candidate.is_absolute():
579
+ candidate = (self.plugin_root / candidate).resolve()
580
+ target = candidate
581
+ try:
582
+ target.relative_to(self.plugin_root)
583
+ except ValueError as exc:
584
+ raise ValueError(f"Output dir must be inside plugin root: {target}") from exc
585
+ target.mkdir(parents=True, exist_ok=True)
586
+ return target
587
+
588
+ def _pick_latest_video(self, base_dir: Path) -> Optional[Path]:
589
+ if not base_dir.exists():
590
+ return None
591
+ videos = sorted(
592
+ [p for p in base_dir.rglob("*.mp4") if p.is_file()],
593
+ key=lambda p: p.stat().st_mtime,
594
+ reverse=True,
595
+ )
596
+ return videos[0] if videos else None
597
+
598
+ def _create_refine_job(self, pose_path: str, ref_path: str, stage1_out: str, stage2_out: str) -> Dict[str, Any]:
599
+ job_id = f"refine_{int(time.time() * 1000)}_{uuid.uuid4().hex[:6]}"
600
+ job = {
601
+ "id": job_id,
602
+ "pose_path": pose_path,
603
+ "ref_path": ref_path,
604
+ "stage1_out": stage1_out,
605
+ "stage2_out": stage2_out,
606
+ "status": "running",
607
+ "created_at": time.time(),
608
+ "updated_at": time.time(),
609
+ "logs": [],
610
+ "result": None,
611
+ "error": None,
612
+ "thread": None,
613
+ }
614
+ with self._refine_jobs_lock:
615
+ self._refine_jobs[job_id] = job
616
+ return job
617
+
618
+ def _get_refine_job(self, job_id: str) -> Optional[Dict[str, Any]]:
619
+ with self._refine_jobs_lock:
620
+ return self._refine_jobs.get(job_id)
621
+
622
+ def _append_refine_log(self, job_id: str, line: str):
623
+ if not line:
624
+ return
625
+ job = self._get_refine_job(job_id)
626
+ if not job:
627
+ return
628
+ job["logs"].append(line.rstrip())
629
+ job["updated_at"] = time.time()
630
+ if len(job["logs"]) > 2000:
631
+ job["logs"] = job["logs"][-2000:]
632
+
633
+ def _finalize_refine_job(self, job_id: str, status: str, *, result: Optional[Dict[str, Any]] = None, error: Optional[str] = None):
634
+ job = self._get_refine_job(job_id)
635
+ if not job:
636
+ return
637
+ job["status"] = status
638
+ job["result"] = result
639
+ job["error"] = error
640
+ job["finished_at"] = time.time()
641
+ job["updated_at"] = job["finished_at"]
642
+
643
+ def _execute_refine_job(self, job_id: str, cmd: List[str]):
644
+ try:
645
+ env = os.environ.copy()
646
+ env["PYTHONUNBUFFERED"] = "1"
647
+ process = subprocess.Popen(
648
+ cmd,
649
+ cwd=str(self.plugin_root),
650
+ stdout=subprocess.PIPE,
651
+ stderr=subprocess.STDOUT,
652
+ text=True,
653
+ bufsize=1,
654
+ env=env,
655
+ )
656
+ if process.stdout:
657
+ for line in iter(process.stdout.readline, ''):
658
+ if line:
659
+ self._append_refine_log(job_id, line.rstrip())
660
+ returncode = process.wait()
661
+ if returncode != 0:
662
+ self._append_refine_log(job_id, f"❌ Refine failed (exit={returncode})")
663
+ self._finalize_refine_job(job_id, "error", error=f"Exit code {returncode}")
664
+ return
665
+
666
+ job = self._get_refine_job(job_id)
667
+ stage1_video = self._pick_latest_video(Path(job["stage1_out"])) if job else None
668
+ stage2_video = self._pick_latest_video(Path(job["stage2_out"])) if job else None
669
+
670
+ result: Dict[str, Any] = {}
671
+ if stage1_video:
672
+ result["stage1_video_path"] = str(stage1_video)
673
+ result["stage1_video_url"] = self._to_web_url(stage1_video)
674
+ if stage2_video:
675
+ result["stage2_video_path"] = str(stage2_video)
676
+ result["stage2_video_url"] = self._to_web_url(stage2_video)
677
+
678
+ self._append_refine_log(job_id, "✅ Refine completed")
679
+ self._finalize_refine_job(job_id, "success", result=result)
680
+ except Exception as exc: # pylint: disable=broad-except
681
+ self._append_refine_log(job_id, f"❌ Refine error: {exc}")
682
+ self._finalize_refine_job(job_id, "error", error=str(exc))
683
+ finally:
684
+ if self._generation_lock.locked():
685
+ self._generation_lock.release()
686
+
687
+ def handle_get_refine_status(self, data: Dict[str, Any]) -> Dict[str, Any]:
688
+ job_id = data.get("job_id")
689
+ if not job_id:
690
+ return {"status": "error", "message": "Missing job_id"}
691
+ job = self._get_refine_job(job_id)
692
+ if not job:
693
+ return {"status": "error", "message": f"Job not found: {job_id}"}
694
+
695
+ last_index = data.get("last_index", 0)
696
+ try:
697
+ last_index = int(last_index)
698
+ if last_index < 0:
699
+ last_index = 0
700
+ except (TypeError, ValueError):
701
+ last_index = 0
702
+
703
+ logs = job["logs"][last_index:]
704
+ response: Dict[str, Any] = {
705
+ "status": "success",
706
+ "job_id": job_id,
707
+ "job_status": job["status"],
708
+ "logs": logs,
709
+ "next_index": last_index + len(logs),
710
+ "finished": job["status"] in ("success", "error"),
711
+ "started_at": job.get("created_at"),
712
+ }
713
+ if job["status"] == "success" and job.get("result"):
714
+ response["result"] = job["result"]
715
+ elif job["status"] == "error":
716
+ response["error_message"] = job.get("error") or "Refine failed"
717
+ return response
718
+
719
 
720
  # Entry point required by ControlWorld's loader
721
  PluginBackend = StableSignerBackend