Repository navigation
Expand file tree
/
Copy pathpanels.js
More file actions
2022 lines (1859 loc) · 70 KB
/
Copy pathpanels.js
File metadata and controls
2022 lines (1859 loc) · 70 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Center workspace controller: Tabs + Image (t2i) + Video (t2v/i2v) + 3D World (Lyra 2.0) + Post + Gallery.
import { $, $$, h, esc, fmtDur, fmtNum, fmtGB, setText, toast, withBusy, snapFrames, clamp } from './dom.js';
import { icon, trajDiagram } from './icons.js';
import { S, on, emit, colab, modelById, modelsOfKind, workerOf, saveCustomModel } from './store.js';
import { local, remote, resolveRemote, srcFromGallery } from './api.js';
import { pickFromGallery, openABCompare, openCinemaShowcase } from './overlays.js';
import {
LYRA_ASPECT,
VIDEO_RESOLUTIONS,
DIRECTION_LABEL,
LYRA_FPS,
LYRA_DURATION_PRESETS,
VIDEO_PROMPT_PRESETS,
KIND_LABEL,
CINEMA_CAMERA_RIGS,
GOD_TIER_MOVIE_SCENES,
expandCinemaMasterPrompt,
} from './defaults.js';
import { bindDropzone, bindRanges, renderTaskResults, renderMediaTile } from './cards.js';
import * as A from './actions.js';
export function initPanels({ refreshGallery, refreshAll }) {
initTabs();
initImagePanel({ refreshAll });
initVideoPanel({ refreshAll });
initWorldPanel({ refreshAll });
initPostPanel({ refreshGallery, refreshAll });
initGalleryPanel({ refreshGallery });
// Bind global dice buttons for random seed inputs
$$('[data-dice]').forEach((btn) => {
btn.addEventListener('click', () => {
const id = btn.dataset.dice;
const input = document.getElementById(id);
if (!input) return;
if (Number(input.value) === -1 || id === 'worldSeed') {
input.value = String(Math.floor(Math.random() * 2147483647));
} else {
input.value = '-1';
}
input.dispatchEvent(new Event('input', { bubbles: true }));
});
});
}
/* =========================================================
SHARED: INLINE HUGGINGFACE MODEL REGISTRATION & CARD RENDERING
========================================================= */
function parseHfSpec(raw, fallbackKind = 't2i') {
let s = (raw || '').trim();
if (!s) return null;
s = s.replace(/^https?:\/\/huggingface\.co\//i, '').replace(/\/+$/, '');
let repo = s;
let subfolder = '';
const treeMatch = s.match(/^([^/]+\/[^/]+)\/(?:tree|blob)\/[^/]+\/(.+)$/i);
if (treeMatch) {
repo = treeMatch[1];
subfolder = treeMatch[2];
} else {
const parts = s.split('/');
if (parts.length >= 2) {
repo = `${parts[0]}/${parts[1]}`;
if (parts.length > 2) subfolder = parts.slice(2).join('/');
}
}
const lower = `${repo}/${subfolder}`.toLowerCase();
let kind = fallbackKind;
if (lower.includes('breeze') || lower.includes('tts') || lower.includes('voice') || lower.includes('cosyvoice')) kind = 'tts';
else if (lower.includes('lyra')) kind = 'lyra';
else if (lower.includes('i2v')) kind = 'i2v';
else if (lower.includes('t2v') || lower.includes('wan') || lower.includes('hunyuanvideo') || lower.includes('ltx') || lower.includes('minimax') || lower.includ
8000
es('cogvideo')) {
kind = fallbackKind === 't2i' ? 't2i' : 't2v';
} else if (lower.includes('flux') || lower.includes('qwen-image') || lower.includes('z-image') || lower.includes('sdxl') || lower.includes('stable-diffusion') || lower.includes('kolors')) {
kind = 't2i';
}
const baseName = repo.split('/').pop() || repo;
const id = (subfolder ? `${baseName}-${subfolder}` : baseName)
.toLowerCase()
.replace(/[^a-z0-9._-]+/g, '-');
const featured_hybrid = /minimax|hybrid|fl2va/i.test(lower);
const isTts = kind === 'tts' || id === 'breeze-tts-2';
return {
id,
repo,
subfolder: subfolder || undefined,
name: subfolder ? `${baseName} (${subfolder})` : baseName,
kind,
zero_vram: isTts,
also_t2i: fallbackKind === 't2i' && kind !== 't2i',
featured_hybrid,
builtin: false,
status: isTts ? 'downloaded' : 'available',
size_gb: isTts ? 2.8 : (kind === 't2i' ? 24.0 : 32.0),
storage_tier: isTts ? 'drive' : 'ramdisk',
description: isTts
? `0显存云盘常驻语音合成 · ${repo}`
: `自定义接入 HuggingFace 模型 · ${repo}${subfolder ? '/' + subfolder : ''}`,
defaults: kind === 't2i'
? { width: 2048, height: 1152, steps: 8, guidance: 3.5 }
: { width: 832, height: 480, num_frames: 81, fps: 16, steps: 24, guidance: 5.0 },
};
}
export async function addCustomHfModel(rawInput, defaultKind = 't2i', { refreshAll } = {}) {
const spec = parseHfSpec(rawInput, defaultKind);
if (!spec) {
toast('请输入 HuggingFace 模型仓库地址(如 black-forest-labs/FLUX.1-schnell)', 'warn');
return null;
}
let registered = spec;
if (S.connected) {
try {
const m = await remote('/models', {
body: { repo: rawInput.trim(), kind: defaultKind },
silent: true,
});
if (m && m.id) {
registered = { ...spec, ...m, also_t2i: spec.also_t2i || m.kind === 't2i' };
if (registered.status === 'available') {
remote(`/models/${encodeURIComponent(registered.id)}/download`, { method: 'POST', silent: true }).catch(() => {});
}
}
} catch {
// Fallback to local registration so UI always works immediately
}
}
saveCustomModel(registered);
const idx = S.models.findIndex((x) => x.id === registered.id);
if (idx >= 0) S.models[idx] = { ...S.models[idx], ...registered };
else S.models.unshift(registered);
emit('models', S.models);
toast(`已添加并选中模型:「${registered.name}」`, 'success');
if (refreshAll && S.connected) refreshAll();
return registered;
}
function modelStatusMeta(m) {
if (m.kind === 'tts' || m.id === 'breeze-tts-2' || m.zero_vram) {
return { label: '0显存 · 云盘常驻', tone: 'green' };
}
const w = workerOf(m.id);
const activeJob = S.jobs.find(
(j) => j.model_id === m.id && (j.status === 'running' || j.status === 'queued') && ['download', 'load', 'setup'].includes(j.task),
);
if (activeJob) {
const pct = activeJob.progress ? ` ${Math.round(activeJob.progress * 100)}%` : '';
return { label: `${activeJob.task === 'download' ? '拉取中' : '加载中'}${pct}`, tone: 'amber' };
}
if (w && w.state === 'on_gpu') return { label: 'GPU 常驻', tone: 'green' };
if (w && w.state === 'offloaded') return { label: '内存盘待命', tone: 'cyan' };
if (m.status === 'loaded') return { label: 'GPU 常驻', tone: 'green' };
if (m.status === 'downloaded') return { label: '内存盘就绪', tone: 'cyan' };
if (m.storage_tier === 'ramdisk') return { label: '内存盘就绪', tone: 'cyan' };
return { label: '云端就绪', tone: 'blue' };
}
function renderModelSelectorCards(container, models, selectedId, onSelect) {
if (!container) return;
container.innerHTML = '';
models.forEach((m) => {
const isSel = m.id === selectedId;
const isZeroVram = m.kind === 'tts' || m.id === 'breeze-tts-2' || m.zero_vram;
const st = modelStatusMeta(m);
const kindTag = m.kind === 'lyra' ? '3D 世界长片' : (KIND_LABEL[m.kind] || m.kind.toUpperCase());
const card = h(
'button',
{
type: 'button',
class: 'mcard' + (isSel ? ' on' : '') + (m.featured_hybrid ? ' is-hybrid' : ''),
'data-model-id': m.id,
onclick: () => onSelect(m),
},
h('div', { class: 'mcard-top' },
h('div', { class: 'mcard-title-wrap' },
h('span', { class: 'mcard-check', html: isSel ? icon('check') : '' }),
h('span', { class: 'mcard-name', title: m.name || m.id }, m.name || m.id),
),
h('span', { class: 'badge mcard-status', 'data-tone': st.tone }, st.label),
),
h('div', { class: 'mcard-meta' },
m.featured_hybrid ? h('span', { class: 'mcard-pill hybrid' }, '⚡ 音视频同生') : null,
isZeroVram ? h('span', { class: 'mcard-pill zero-vram' }, '☁️ 0显存 · 云盘常驻') : null,
h('span', { class: 'mcard-pill' }, kindTag),
m.size_gb ? h('span', { class: 'mcard-size' }, fmtGB(m.size_gb)) : null,
isSel ? h('span', { class: 'mcard-active-lbl' }, '✓ 当前使用') : null,
),
m.description ? h('div', { class: 'mcard-desc' }, m.description) : null,
);
container.append(card);
});
}
function renderCinemaCamBar(container, activeCamId, onSelect) {
if (!container) return;
container.innerHTML = '';
CINEMA_CAMERA_RIGS.forEach((rig) => {
const isOn = rig.id === activeCamId;
container.append(
h(
'button',
{
type: 'button',
class: 'chip cinema-cam-pill' + (isOn ? ' on' : ''),
title: `${rig.name}\n光学规格:${rig.spec}`,
onclick: () => onSelect(rig),
},
rig.name,
),
);
});
}
function applyCinemaRigSuffix(prompt, rigId) {
const clean = (prompt || '').trim();
if (!clean) return '';
const rig = CINEMA_CAMERA_RIGS.find((r) => r.id === rigId) || CINEMA_CAMERA_RIGS[0];
if (!rig || !rig.suffix) return clean;
// Avoid duplicating if the prompt already includes the camera signature
if (clean.includes('ARRI Alexa') || clean.includes('Sony Venice') || clean.includes('Panavision') || clean.includes(rig.suffix.slice(0, 28))) {
return clean;
}
return `${clean}${rig.suffix}`;
}
/* =========================================================
TABS & INDICATOR
========================================================= */
function initTabs() {
const indicator = $('#tabIndicator');
const tabBtns = $$('#tabs .tab');
const panels = $$('#panels .panel');
function updateIndicator() {
const active = $('#tabs .tab.on');
if (!active || !indicator) return;
indicator.style.left = `${active.offsetLeft}px`;
indicator.style.width = `${active.offsetWidth}px`;
}
function setTab(name) {
if (!name) return;
S.tab = name;
tabBtns.forEach((b) => b.classList.toggle('on', b.dataset.tab === name));
panels.forEach((p) => p.classList.toggle('on', p.dataset.panel === name));
requestAnimationFrame(updateIndicator);
}
tabBtns.forEach((btn) => {
btn.addEventListener('click', () => emit('tab', btn.dataset.tab));
});
on('tab', setTab);
window.addEventListener('resize', updateIndicator);
setTab(S.tab || 'image');
setTimeout(updateIndicator, 60);
}
/* =========================================================
PANEL 1: IMAGE (T2I) — 3-STEP STREAMLINED WORKFLOW
========================================================= */
function initImagePanel({ refreshAll }) {
const modelCardsWrap = $('#t2iModelCards');
const toggleAddBtn = $('#t2iToggleAdd');
const addBox = $('#t2iAddBox');
const addInput = $('#t2iAddInput');
const addBtn = $('#t2iAddBtn');
const expandPromptBtn = $('#t2iExpandPrompt');
const dicePromptBtn = $('#t2iDicePrompt');
const cinemaCamWrap = $('#t2iCinemaCam');
const promptEl = $('#t2iPrompt');
const charsEl = $('#t2iChars');
const clearBtn = $('#t2iClear');
const negEl = $('#t2iNeg');
const stylesWrap = $('#t2iStyles');
const scenesWrap = $('#t2iScenes');
const aspectsWrap = $('#t2iAspects');
const modelSel = $('#t2iModel');
const countWrap = $('#t2iCount');
const countInput = $('#t2iCount input');
const seedInput = $('#t2iSeed');
const stepsInput = $('#t2iSteps');
const metaEl = $('#t2iMeta');
const runBtn = $('#t2iRun');
const resultsEl = $('#t2iResults');
const resultsHint = $('#t2iResultsHint');
let activeStyleId = null;
let activeSceneId = null;
let activeCamId = 'iwai_soft'; // Default: 🌸 岩井俊二·黄金逆光柔焦 (ARRI Alexa 65 + 85mm f/1.2L)
let selectedModelId = 'qwen-image-2.1-turbo';
let activeAspect = (S.presets.aspect_presets && S.presets.aspect_presets[0]) || { id: '16:9', name: '16:9 横屏 2K', width: 2752, height: 1536 };
function getScenePresets() {
// Always prioritize the 8 God-Tier Movie Scenes
const remoteScenes = S.presets.scene_presets || [];
const seen = new Set(GOD_TIER_MOVIE_SCENES.map((s) => s.id));
const extra = remoteScenes.filter((s) => s && s.id && !seen.has(s.id));
return [...GOD_TIER_MOVIE_SCENES, ...extra];
}
function getImageModels() {
const list = modelsOfKind('t2i');
// Ensure minimax-h3-hybrid is always selectable for hybrid image generation too
const pc = modelById('minimax-h3-hybrid');
if (pc && !list.some((m) => m.id === pc.id)) {
list.push(pc);
}
return list;
}
function selectImageModel(mOrId, { focusPrompt = false, announce = false } = {}) {
const id = typeof mOrId === 'string' ? mOrId : mOrId?.id;
if (!id) return;
selectedModelId = id;
if (modelSel) modelSel.value = id;
const m = modelById(id);
if (m?.defaults?.steps && stepsInput) {
stepsInput.value = String(m.defaults.steps);
}
syncModels();
if (announce && m) {
toast(`已选择生图模型:${m.name},输入一句话提示词即可生成`, 'info', { timeout: 2200 });
}
if (focusPrompt) {
setTimeout(() => promptEl?.focus(), 60);
}
}
// Toggle inline "+ 添加生图模型" box
toggleAddBtn?.addEventListener('click', () => {
if (!addBox) return;
addBox.hidden = !addBox.hidden;
if (!addBox.hidden) setTimeout(() => addInput?.focus(), 50);
});
async function handleAddImageModel(rawVal) {
const val = (rawVal ?? addInput?.value ?? '').trim();
const added = await addCustomHfModel(val, 't2i', { refreshAll });
if (added) {
if (addInput) addInput.value = '';
if (addBox) addBox.hidden = true;
selectImageModel(added.id, { focusPrompt: true });
}
}
addBtn?.addEventListener('click', () => withBusy(addBtn, () => handleAddImageModel()));
addInput?.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
withBusy(addBtn, () => handleAddImageModel());
}
});
$$('[data-hf-t2i]').forEach((chip) => {
chip.addEventListener('click', () => {
const repo = chip.dataset.hfT2i;
if (addInput) addInput.value = repo;
withBusy(chip, () => handleAddImageModel(repo));
});
});
// ✨ 电影级扩写 button
expandPromptBtn?.addEventListener('click', () => {
if (!promptEl) return;
const expanded = expandCinemaMasterPrompt(promptEl.value, activeCamId, false);
promptEl.value = expanded;
updateChars();
updateMeta();
const rig = CINEMA_CAMERA_RIGS.find((r) => r.id === activeCamId) || CINEMA_CAMERA_RIGS[0];
toast(`✨ 已为您扩写为「${rig.short}」大师级唯美电影提示词`, 'success', { timeout: 2200 });
promptEl.focus();
});
// Random scene prompt button
dicePromptBtn?.addEventListener('click', () => {
const scenes = getScenePresets();
if (!scenes.length || !promptEl) return;
const pick = scenes[Math.floor(Math.random() * scenes.length)];
activeSceneId = pick.id;
promptEl.value = pick.prompt;
updateChars();
renderPresets();
updateMeta();
toast(`🎬 已填入电影级片段:${pick.name}`, 'info', { timeout: 1800 });
promptEl.focus();
});
function updateChars() {
if (charsEl && promptEl) charsEl.textContent = String(promptEl.value.length);
}
promptEl?.addEventListener('input', () => {
updateChars();
updateMeta();
});
clearBtn?.addEventListener('click', () => {
if (!promptEl) return;
promptEl.value = '';
activeSceneId = null;
renderPresets();
updateChars();
updateMeta();
promptEl.focus();
});
// Stepper for batch count
$$('button[data-d]', countWrap).forEach((btn) => {
btn.addEventListener('click', () => {
if (!countInput) return;
const d = Number(btn.dataset.d) || 0;
countInput.value = String(clamp((Number(countInput.value) || 1) + d, 1, 8));
updateMeta();
});
});
countInput?.addEventListener('input', updateMeta);
stepsInput?.addEventListener('input', updateMeta);
modelSel?.addEventListener('change', () => {
selectImageModel(modelSel.value);
});
function renderPresets() {
renderCinemaCamBar(cinemaCamWrap, activeCamId, (rig) => {
activeCamId = rig.id;
renderPresets();
updateMeta();
toast(`🎥 已切换电影摄影机:${rig.name}`, 'info', { timeout: 1800 });
});
const styles = S.presets.t2i_styles || [];
if (stylesWrap) {
stylesWrap.innerHTML = '';
styles.forEach((st) => {
stylesWrap.append(
h('button', {
class: 'chip' + (activeStyleId === st.id ? ' on' : ''),
type: 'button',
onclick: () => {
activeStyleId = activeStyleId === st.id ? null : st.id;
renderPresets();
updateMeta();
},
}, st.name),
);
});
}
const scenes = getScenePresets();
if (scenesWrap) {
scenesWrap.innerHTML = '';
scenes.forEach((sc) => {
scenesWrap.append(
h('button', {
class: 'chip scene-movie-chip' + (activeSceneId === sc.id ? ' on' : ''),
type: 'button',
title: sc.prompt,
onclick: () => {
activeSceneId = sc.id;
if (promptEl) {
promptEl.value = sc.prompt;
updateChars();
}
renderPresets();
updateMeta();
},
}, sc.name),
);
});
}
const aspects = [...(S.presets.aspect_presets || []), LYRA_ASPECT];
if (aspectsWrap) {
aspectsWrap.innerHTML = '';
aspects.forEach((a) => {
const maxSide = 16;
const ratio = a.width / a.height;
const bw = ratio >= 1 ? maxSide : Math.max(7, Math.round(maxSide * ratio));
const bh = ratio >= 1 ? Math.max(7, Math.round(maxSide / ratio)) : maxSide;
aspectsWrap.append(
h('button', {
class: 'aspect' + (activeAspect.id === a.id ? ' on' : ''),
type: 'button',
onclick: () => {
activeAspect = a;
renderPresets();
updateMeta();
},
},
h('span', { class: 'aspect-box' }, h('i', { style: { width: `${bw}px`, height: `${bh}px` } })),
h('span', { class: 'aspect-txt' },
h('b', {}, a.name),
h('span', {}, `${a.width}×${a.height}`))),
);
});
}
}
function syncModels() {
const list = getImageModels();
if (!list.some((m) => m.id === selectedModelId) && list.length) {
selectedModelId = list[0].id;
}
if (modelSel) {
modelSel.innerHTML = '';
list.forEach((m) => {
modelSel.append(h('option', { value: m.id }, m.name || m.id));
});
modelSel.value = selectedModelId;
}
renderModelSelectorCards(modelCardsWrap, list, selectedModelId, (m) => {
selectImageModel(m.id, { focusPrompt: true, announce: true });
});
updateMeta();
}
function updateMeta() {
if (!metaEl) return;
const m = modelById(selectedModelId) || getImageModels()[0];
const rig = CINEMA_CAMERA_RIGS.find((r) => r.id === activeCamId) || CINEMA_CAMERA_RIGS[0];
const count = clamp(Number(countInput?.value) || 1, 1, 8);
const steps = Number(stepsInput?.value) || 8;
const st = (S.presets.t2i_styles || []).find((x) => x.id === activeStyleId);
const parts = [
`<span>模型 <b>${esc(m?.name || selectedModelId)}</b></span>`,
`<span>摄影机 <b>${esc(rig.short)}</b></span>`,
`<span>尺寸 <b>${activeAspect.width}×${activeAspect.height}</b> · <b>${count} 张</b></span>`,
];
if (st) parts.push(`<span>风格 <b>${esc(st.name)}</b></span>`);
if (!S.connected) {
parts.push(`<span class="warn">${icon('alert')}提交时如未连接 GPU 将自动引导连接</span>`);
}
metaEl.innerHTML = parts.join('');
}
async function submitT2i() {
let rawPrompt = (promptEl?.value || '').trim();
if (!rawPrompt) {
toast('请先在步骤 ② 输入一句话画面描述,或点击下方电影片段芯片', 'warn', {
actionText: '🎲 随机填入并生成',
onAction: () => {
dicePromptBtn?.click();
if (promptEl?.value.trim()) submitT2i();
},
});
promptEl?.focus();
return;
}
if (!S.connected) {
toast('当前尚未连接 Colab 云端 GPU,请点击左侧「一键启动并连接」', 'warn', {
actionText: '🚀 立即启动 GPU',
onAction: () => $('#btnStart')?.click(),
});
return;
}
const st = (S.presets.t2i_styles || []).find((x) => x.id === activeStyleId);
const withStyle = st ? `${rawPrompt}${st.suffix}` : rawPrompt;
const finalPrompt = applyCinemaRigSuffix(withStyle, activeCamId);
const neg = (negEl?.value || '').trim();
const count = clamp(Number(countInput?.value) || 1, 1, 8);
const steps = clamp(Number(stepsInput?.value) || 8, 1, 100);
const seed = Number(seedInput?.value ?? -1);
const modelId = selectedModelId || modelSel?.value || 'qwen-image-2.1-turbo';
await withBusy(runBtn, async () => {
try {
await remote('/jobs', {
body: {
model_id: modelId,
task: 't2i',
params: {
prompt: finalPrompt,
negative_prompt: neg || undefined,
width: activeAspect.width,
height: activeAspect.height,
steps,
seed,
count,
},
},
errTitle: '提交生图任务失败',
});
const m = modelById(modelId);
toast(`已提交生图任务(${m?.name || modelId})`, 'success', { timeout: 2000 });
emit('poll:fast');
refreshAll();
} catch {}
});
}
runBtn?.addEventListener('click', submitT2i);
function renderResults() {
const t2iJobs = S.jobs.filter((j) => j.task === 't2i');
if (resultsHint) {
resultsHint.textContent = t2iJobs.length ? `共 ${t2iJobs.length} 次生成任务` : '生成完成后悬停图片可一键「做成 3D 世界」或「图生视频」';
}
renderTaskResults(resultsEl, ['t2i'], {
emptyIcon: 'sparkles',
emptyTitle: '还没有生图记录',
emptySub: '① 选择生图模型 → ② 输入一句话描述 → ③ 点击「⚡ 立即生成图片」即可出图',
});
}
on('presets', renderPresets);
on('models', syncModels);
on('state', () => {
syncModels();
updateMeta();
});
on('jobs', () => {
syncModels();
renderResults();
});
on('gallery', renderResults);
on('model:select', (m) => {
if (!m) return;
if (m.kind === 't2i' || m.also_t2i) {
selectImageModel(m.id, { focusPrompt: true });
}
});
on('run:image', submitT2i);
renderPresets();
syncModels();
updateChars();
renderResults();
}
/* =========================================================
PANEL 2: VIDEO (T2V / I2V / LYRA) — 3-STEP STREAMLINED WORKFLOW
========================================================= */
function initVideoPanel({ refreshAll }) {
const modelCardsWrap = $('#vidModelCards');
const toggleAddBtn = $('#vidToggleAdd');
const addBox = $('#vidAddBox');
const addInput = $('#vidAddInput');
const addBtn = $('#vidAddBtn');
const expandPromptBtn = $('#vidExpandPrompt');
const dicePromptBtn = $('#vidDicePrompt');
const cinemaCamWrap = $('#vidCinemaCam');
const clearBtn = $('#vidClear');
const charsEl = $('#vidChars');
const scenesWrap = $('#vidScenes');
const optRefDetails = $('#vidOptRefDetails');
const dropEl = $('#vidDrop');
const promptEl = $('#vidPrompt');
const negEl = $('#vidNeg');
const modelSel = $('#vidModel');
const resSel = $('#vidRes');
const framesInput = $('#vidFrames');
const fpsInput = $('#vidFps');
const stepsInput = $('#vidSteps');
const guidanceInput = $('#vidGuidance');
const seedInput = $('#vidSeed');
const metaEl = $('#vidMeta');
const runBtn = $('#vidRun');
const resultsEl = $('#vidResults');
let vidSource = null;
let activeVidSceneId = null;
let activeVidCamId = 'iwai_soft'; // Default: 🌸 岩井俊二·黄金逆光柔焦 (ARRI Alexa 65 + 85mm f/1.2L)
let selectedModelId = 'minimax-h3-hybrid';
function getVideoModels() {
const list = modelsOfKind('t2v', 'i2v', 'lyra', 'tts');
// Sort so minimax-h3-hybrid is always first
return list.slice().sort((a, b) => {
if (a.id === 'minimax-h3-hybrid') return -1;
if (b.id === 'minimax-h3-hybrid') return 1;
if (a.featured_hybrid && !b.featured_hybrid) return -1;
if (!a.featured_hybrid && b.featured_hybrid) return 1;
return 0;
});
}
function selectVideoModel(mOrId, { focusPrompt = false, announce = false } = {}) {
const id = typeof mOrId === 'string' ? mOrId : mOrId?.id;
if (!id) return;
selectedModelId = id;
if (modelSel) modelSel.value = id;
const m = modelById(id);
if (m?.defaults) {
if (m.defaults.steps && stepsInput) stepsInput.value = String(m.defaults.steps);
if (m.defaults.fps && fpsInput) fpsInput.value = String(m.defaults.fps);
if (m.defaults.num_frames && framesInput) framesInput.value = String(m.defaults.num_frames);
if (m.defaults.guidance != null && guidanceInput) guidanceInput.value = String(m.defaults.guidance);
}
syncModels();
if (announce && m) {
toast(`已选择视频模型:${m.name},输入一句话提示词即可生成视频`, 'info', { timeout: 2200 });
}
if (focusPrompt) {
setTimeout(() => promptEl?.focus(), 60);
}
}
// Toggle inline "+ 添加视频模型" box
toggleAddBtn?.addEventListener('click', () => {
if (!addBox) return;
addBox.hidden = !addBox.hidden;
if (!addBox.hidden) setTimeout(() => addInput?.focus(), 50);
});
async function handleAddVideoModel(rawVal) {
const val = (rawVal ?? addInput?.value ?? '').trim();
const added = await addCustomHfModel(val, 't2v', { refreshAll });
if (added) {
if (addInput) addInput.value = '';
if (addBox) addBox.hidden = true;
selectVideoModel(added.id, { focusPrompt: true });
}
}
addBtn?.addEventListener('click', () => withBusy(addBtn, () => handleAddVideoModel()));
addInput?.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
withBusy(addBtn, () => handleAddVideoModel());
}
});
$$('[data-hf-vid]').forEach((chip) => {
chip.addEventListener('click', () => {
const repo = chip.dataset.hfVid;
if (addInput) addInput.value = repo;
withBusy(chip, () => handleAddVideoModel(repo));
});
});
function updateChars() {
if (charsEl && promptEl) charsEl.textContent = String(promptEl.value.length);
}
promptEl?.addEventListener('input', () => {
updateChars();
updateMeta();
});
clearBtn?.addEventListener('click', () => {
if (!promptEl) return;
promptEl.value = '';
activeVidSceneId = null;
renderVideoPresets();
updateChars();
updateMeta();
promptEl.focus();
});
// ✨ 电影级扩写 button
expandPromptBtn?.addEventListener('click', () => {
if (!promptEl) return;
const expanded = expandCinemaMasterPrompt(promptEl.value, activeVidCamId, true);
promptEl.value = expanded;
updateChars();
updateMeta();
const rig = CINEMA_CAMERA_RIGS.find((r) => r.id === activeVidCamId) || CINEMA_CAMERA_RIGS[0];
toast(`✨ 已为您扩写为「${rig.short}」大师级电影运镜提示词`, 'success', { timeout: 2200 });
promptEl.focus();
});
dicePromptBtn?.addEventListener('click', () => {
const presets = VIDEO_PROMPT_PRESETS || [];
if (!presets.length || !promptEl) return;
const pick = presets[Math.floor(Math.random() * presets.length)];
activeVidSceneId = pick.id;
promptEl.value = pick.prompt;
updateChars();
renderVideoPresets();
updateMeta();
toast(`🎬 已填入电影级片段:${pick.name}`, 'info', { timeout: 1800 });
promptEl.focus();
});
function renderVideoPresets() {
renderCinemaCamBar(cinemaCamWrap, activeVidCamId, (rig) => {
activeVidCamId = rig.id;
renderVideoPresets();
updateMeta();
toast(`🎥 已切换电影摄影机:${rig.name}`, 'info', { timeout: 1800 });
});
if (!scenesWrap) return;
scenesWrap.innerHTML = '';
(VIDEO_PROMPT_PRESETS || []).forEach((sc) => {
scenesWrap.append(
h('button', {
class: 'chip scene-movie-chip' + (activeVidSceneId === sc.id ? ' on' : ''),
type: 'button',
title: sc.prompt,
onclick: () => {
activeVidSceneId = sc.id;
if (promptEl) {
promptEl.value = sc.prompt;
updateChars();
}
renderVideoPresets();
updateMeta();
},
}, sc.name),
);
});
}
const dz = dropEl ? bindDropzone(dropEl, {
onChange: (src) => {
vidSource = src;
if (src && optRefDetails) optRefDetails.open = true;
syncModels();
updateMeta();
},
}) : null;
on('use:video', (src) => {
if (optRefDetails) optRefDetails.open = true;
dz?.set(src);
if (src?.meta?.prompt && promptEl && !promptEl.value.trim()) {
promptEl.value = src.meta.prompt;
updateChars();
}
});
if (resSel) {
resSel.innerHTML = '';
VIDEO_RESOLUTIONS.forEach((r) => {
resSel.append(h('option', { value: r.id }, r.name));
});
}
modelSel?.addEventListener('change', () => {
selectVideoModel(modelSel.value);
});
function syncModels() {
const list = getVideoModels();
if (!list.some((m) => m.id === selectedModelId) && list.length) {
selectedModelId = list[0].id;
}
if (modelSel) {
CE2A
modelSel.innerHTML = '';
list.forEach((m) => {
modelSel.append(h('option', { value: m.id }, `${m.name || m.id} (${m.kind.toUpperCase()})`));
});
modelSel.value = selectedModelId;
}
renderModelSelectorCards(modelCardsWrap, list, selectedModelId, (m) => {
selectVideoModel(m.id, { focusPrompt: true, announce: true });
});
updateMeta();
}
function updateMeta() {
if (!metaEl) return;
const m = modelById(selectedModelId) || getVideoModels()[0];
const rig = CINEMA_CAMERA_RIGS.find((r) => r.id === activeVidCamId) || CINEMA_CAMERA_RIGS[0];
const resObj = VIDEO_RESOLUTIONS.find((r) => r.id === resSel?.value) || VIDEO_RESOLUTIONS[0];
const frames = Number(framesInput?.value) || 81;
const fps = Number(fpsInput?.value) || 24;
const isTts = m?.kind === 'tts' || m?.id === 'breeze-tts-2';
const dur = m?.kind === 'lyra' ? '30.1' : (frames / Math.max(1, fps)).toFixed(1);
const modeTxt = isTts
? 'Breeze-TTS-2 语音合成 (0显存 · 云盘常驻)'
: (m?.kind === 'lyra'
? 'Lyra 2.0 3D 长片直出'
: (vidSource ? '图生视频 (I2V)' : '一句话文生视频 (T2V)'));
const parts = [
`<span>模型 <b>${esc(m?.name || selectedModelId)}</b></span>`,
isTts ? `<span>模式 <b>${modeTxt}</b></span>` : `<span>摄影机 <b>${esc(rig.short)}</b></span>`,
isTts
? `<span>引擎 <b>Google Drive 云盘常驻 · 0 GPU 显存占用</b></span>`
: `<span>规格 <b>${resObj.width}×${resObj.height} · ~${dur}s</b></span>`,
];
if (!S.connected) {
parts.push(`<span class="warn">${icon('alert')}提交时如未连接 GPU 将自动引导连接</span>`);
}
metaEl.innerHTML = parts.join('');
}
[resSel, framesInput, fpsInput, stepsInput, guidanceInput].forEach((el) => {
el?.addEventListener('input', updateMeta);
el?.addEventListener('change', updateMeta);
});
async function submitVideo() {
const prompt = (promptEl?.value || '').trim();
if (!prompt && !vidSource) {
toast('请先在步骤 ② 输入一句话视频提示词,或点击下方快速芯片', 'warn', {
actionText: '🎲 随机填入并生成',
onAction: () => {
dicePromptBtn?.click();
if (promptEl?.value.trim()) submitVideo();
},
});
promptEl?.focus();
return;
}
if (!S.connected) {
toast('当前尚未连接 Colab 云端 GPU,请点击左侧「一键启动并连接」', 'warn', {
actionText: '🚀 立即启动 GPU',
onAction: () => $('#btnStart')?.click(),
});
return;
}
const modelId = selectedModelId || modelSel?.value || 'minimax-h3-hybrid';
const resObj = VIDEO_RESOLUTIONS.find((r) => r.id === resSel?.value) || VIDEO_RESOLUTIONS[0];
const numFrames = clamp(Number(framesInput?.value) || 81, 9, 721);
const fps = clamp(Number(fpsInput?.value) || 24, 8, 60);
const steps = clamp(Number(stepsInput?.value) || 8, 1, 100);
const guidance = Number(guidanceInput?.value ?? 1.0);
const seed = Number(seedInput?.value ?? -1);
const neg = (negEl?.value || '').trim();
await withBusy(runBtn, async () => {
try {
let imagePath;
if (vidSource) {
imagePath = await resolveRemote(vidSource);
}
const m = modelById(modelId);
const finalVideoPrompt = applyCinemaRigSuffix(prompt, activeVidCamId);
if (m?.kind === 'tts' || modelId === 'breeze-tts-2') {
await remote('/jobs', {
body: {
model_id: modelId || 'breeze-tts-2',
task: 'tts',
params: {
prompt,
text: prompt,
seed: seed < 0 ? 42 : seed,
},
},
errTitle: '提交 Breeze-TTS-2 语音生成任务失败',
});
toast('已提交 Breeze-TTS-2 语音合成任务(0显存 · 云盘常驻)', 'success', { timeout: 2000 });
} else if (m?.kind === 'lyra' || modelId === 'lyra-2') {
await remote('/jobs', {
body: {
model_id: 'lyra-2',
task: 'lyra',
params: {
scene: finalVideoPrompt,
prompt: finalVideoPrompt,
image_path: imagePath,
mode: 'flythrough',
frames: 481,
zoom_out_frames: 241,
zoom_in_frames: 241,
steps: 4,
dmd: true,
seed: seed < 0 ? 42 : seed,
},
},
errTitle: '提交 Lyra 2.0 3D 视频任务失败',
});
toast('已提交 Lyra 2.0 3D 长片视频任务', 'success', { timeout: 2000 });
} else {
const task = vidSource ? 'i2v' : 't2v';
await remote('/jobs', {
body: {
model_id: modelId,
task,
params: {
prompt: finalVideoPrompt,
negative_prompt: neg || undefined,
width: resObj.width,
height: resObj.height,
num_frames: numFrames,
fps,
steps,
guidance,
seed,
image_path: imagePath,
},
},
errTitle: '提交视频任务失败',
});
toast(`已提交视频生成任务(${m?.name || modelId})`, 'success', { timeout: 2000 });
}
emit('poll:fast');
refreshAll();
} catch {}
});
}
runBtn?.addEventListener('click', submitVideo);
function renderResults() {
renderTaskResults(resultsEl, ['t2v', 'i2v', 'lyra', 'tts'], {
emptyIcon: 'film',
emptyTitle: '还没有视频/语音生成记录',
emptySub: '① 选择模型 → ② 输入一句话提示词或台词 → ③ 点击「🎬 立即生成视频」即可直出',