Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
1120 lines (1048 loc) · 51.3 KB
/
Copy pathapp.py
File metadata and controls
1120 lines (1048 loc) · 51.3 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
"""PowerTokens Video Studio; run with Python 3.9+ / tkinter."""
import base64
import ctypes
from ctypes import wintypes
import json
import os
from pathlib import Path
import queue
import threading
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import uuid
import webbrowser
from i18n import (LANGUAGES, LANGUAGE_NAMES, get_language, is_zh, load_settings, save_language,
save_setting, set_language, t)
from studio_ui import (APP_NAME, VERSION, subtitle, promotion_text, FONT, WHITE, INK, LINE, ACCENT, LOGO_FILE,
apply_theme, label, heading, card, Columns, Flow, ScrollPage, text_area,
load_image, header_logo_file)
from input_helpers import parse_keys, infer_prompt
from batch_ui import BatchTab
from compare_ui import CompareTab
from models import (DEFAULT_MODEL_ID, list_models, get_model, resolve_model_id, snap_params,
format_adjust_notice, model_allows_first_frame, allowed_media_types)
from frame_util import encode_local_image_as_data_url
from wan_core import (Client, DATA_DIR, PRICE_CHECKED_DATE, UTM, current_prices, list_prices,
TaskError, atomic_json, estimate_cost, fingerprint, payload)
OFFICIAL_KEY_URL = 'https://powertokens.ai/zh-Hans/api-keys?' + UTM
OFFICIAL_KEY_URL_EN = 'https://powertokens.ai/api-keys?' + UTM
KEY_QUOTA_TIP_URL = 'https://powertokens.ai/zh-Hans/api-keys?utm_source=videostudio&utm_medium=app&utm_campaign=video-studio'
KEY_QUOTA_TIP_URL_EN = 'https://powertokens.ai/api-keys?utm_source=videostudio&utm_medium=app&utm_campaign=video-studio'
def key_quota_tip_url():
return KEY_QUOTA_TIP_URL if is_zh() else KEY_QUOTA_TIP_URL_EN
def official_key_url():
return OFFICIAL_KEY_URL if is_zh() else OFFICIAL_KEY_URL_EN
def protect(raw, decrypt=False):
"""Windows DPAPI: saved secrets are bound to the current Windows account."""
if os.name != 'nt':
raise RuntimeError(t('remember_windows_only'))
class Blob(ctypes.Structure):
_fields_ = [('size', wintypes.DWORD), ('data', ctypes.POINTER(ctypes.c_ubyte))]
buf = ctypes.create_string_buffer(raw)
source = Blob(len(raw), ctypes.cast(buf, ctypes.POINTER(ctypes.c_ubyte)))
result = Blob()
crypt = ctypes.WinDLL('crypt32', use_last_error=True)
fn = crypt.CryptUnprotectData if decrypt else crypt.CryptProtectData
fn.argtypes = [ctypes.POINTER(Blob), ctypes.c_void_p, ctypes.c_void_p,
ctypes.c_void_p, ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(Blob)]
fn.restype = wintypes.BOOL
if not fn(ctypes.byref(source), None, None, None, None, 1, ctypes.byref(result)):
raise ctypes.WinError(ctypes.get_last_error())
try:
return ctypes.string_at(result.data, result.size)
finally:
kernel = ctypes.WinDLL('kernel32', use_last_error=True)
kernel.LocalFree.argtypes = [ctypes.c_void_p]
kernel.LocalFree.restype = ctypes.c_void_p
kernel.LocalFree(result.data)
class App:
def __init__(self, root):
self.root = root
self.keys, self.records = [], {}
self.events = queue.Queue()
self.stop = threading.Event()
self.busy = False
self.prompt_timer = None
self.scale = apply_theme(root)
root.title('%s · v%s' % (APP_NAME, VERSION))
# Keep image references on the instance; a missing logo must never stop the app.
self.icon_image = load_image(LOGO_FILE)
self.logo_image = load_image(header_logo_file(self.scale))
if self.icon_image is not None:
try:
root.iconphoto(True, self.icon_image)
except tk.TclError:
pass
width = min(int(1280 * self.scale), root.winfo_screenwidth() - 60)
height = min(int(920 * self.scale), root.winfo_screenheight() - 90)
root.geometry('%dx%d' % (width, height))
root.minsize(min(860, width), min(620, height))
self.build_ui()
self.load_keys()
self.refresh_history()
root.after(150, self.drain)
root.protocol('WM_DELETE_WINDOW', self.close)
def build_ui(self):
"""Build every widget in the current language; rebuilt in place by switch_language()."""
root = self.root
shell = self.shell = ttk.Frame(root, style='Page.TFrame')
shell.pack(fill='both', expand=True)
header = ttk.Frame(shell, padding=(28, 20, 28, 20))
header.pack(fill='x')
# Keep the long name on its own line on smaller displays.
brand = ttk.Frame(header)
brand.pack(fill='x')
if self.logo_image is not None:
self.logo_label = ttk.Label(brand, image=self.logo_image)
self.logo_label.pack(side='left', padx=(0, 12))
ttk.Label(brand, text=APP_NAME, style='Brand.TLabel').pack(side='left')
# 中文 / English switch, top right. Applies immediately (the window is rebuilt in place).
switch = ttk.Frame(brand)
switch.pack(side='right')
self.lang_buttons = {}
for code in LANGUAGES:
button = ttk.Button(switch, text=LANGUAGE_NAMES[code], takefocus=0,
style='LangActive.TButton' if code == get_language() else 'Lang.TButton',
command=lambda code=code: self.switch_language(code))
button.pack(side='left')
self.lang_buttons[code] = button
self.help_tips_btn = ttk.Button(switch, text=t('onboard_help'), style='Link.TButton',
command=self.show_onboarding)
self.help_tips_btn.pack(side='left', padx=(12, 0))
header_row = ttk.Frame(header)
header_row.pack(fill='x', pady=(8, 0))
ttk.Label(header_row, text=subtitle(), style='Muted.TLabel').pack(side='left')
self.key_badge = tk.StringVar(value=t('badge_no_key'))
ttk.Button(header_row, text=t('header_get_key'), style='Link.TButton',
command=self.open_official_keys).pack(side='right')
ttk.Label(header_row, textvariable=self.key_badge, style='Badge.TLabel').pack(side='right', padx=12)
tabs = ttk.Notebook(shell)
tabs.pack(fill='both', expand=True)
pages = [ScrollPage(tabs) for _ in range(5)]
for page, name in zip(pages, ('tab_generate', 'tab_compare', 'tab_batch', 'tab_history', 'tab_keys')):
tabs.add(page, text=t(name))
self.tabs, self.pages = tabs, pages
self.build_create(pages[0].body)
self.compare = CompareTab(self, pages[1].body)
self.batch = BatchTab(self, pages[2].body)
self.build_history(pages[3].body)
self.build_keys(pages[4].body)
self.status = tk.StringVar(value=t('status_ready'))
label(shell, variable=self.status, style='Page.TLabel').pack(fill='x', padx=28, pady=(8, 12))
def switch_language(self, lang):
"""Switch the UI language now and remember it in settings.json."""
if lang == get_language():
return
if self.busy:
# Widgets are in use by a running task: remember the choice for the next start.
try:
save_language(lang)
except OSError:
pass
messagebox.showinfo(t('lang_saved_title'), t('lang_saved_busy'))
return
state = self.capture_state()
try:
set_language(lang, persist=True)
except OSError:
set_language(lang) # Still switch for this session if the settings file is not writable.
if self.prompt_timer:
self.root.after_cancel(self.prompt_timer)
self.prompt_timer = None
self.shell.destroy()
for name in ('promo_label', 'cost'): # Rebuilt below; update_cost() must not touch the old ones.
self.__dict__.pop(name, None)
self.build_ui()
self.restore_state(state)
def capture_state(self):
return dict(
tab=self.tabs.index('current'), prompt=self.prompt.get('1.0', 'end-1c'),
auto=self.auto_prompt.get(), model=getattr(self, 'model_id', tk.StringVar(value=DEFAULT_MODEL_ID)).get(),
duration=self.duration.get(), resolution=self.resolution.get(),
ratio=self.ratio.get(), output=self.output.get(), seed=self.seed.get(),
media={kind: var.get() for kind, var in self.media.items()}, log=self.log.get('1.0', 'end-1c'),
key_input=self.key_input.get(), show_key=self.show_key.get(), remember=self.remember.get(),
key_selection=self.key_list.curselection(), task_id=self.task_id.get(),
video_link=self.video_link.get(), batch=self.batch.export_state(),
compare=self.compare.export_state() if hasattr(self, 'compare') else {})
def restore_state(self, state):
self.auto_prompt.set(state['auto'])
self.prompt.insert('1.0', state['prompt'])
self.prompt.edit_modified(False)
if 'model' in state and hasattr(self, 'model_id'):
try:
mid = resolve_model_id(state['model'])
except KeyError:
mid = DEFAULT_MODEL_ID
self.model_id.set(mid)
self._sync_model_widgets(preserve=True)
for name in ('duration', 'resolution', 'ratio', 'output', 'seed', 'key_input', 'task_id', 'video_link'):
if name in state:
getattr(self, name).set(state[name])
for kind, value in state['media'].items():
if kind in self.media:
self.media[kind].set(value)
ff = (state.get('media') or {}).get('first_frame', '')
self._ff_local_name = None
if ff.startswith('data:image/'):
self._ff_syncing_url = True
self._ff_url_var.set('')
self._ff_syncing_url = False
elif ff:
self._ff_syncing_url = True
self._ff_url_var.set(ff)
self._ff_syncing_url = False
self._refresh_first_frame_ui()
self.show_key.set(state['show_key'])
self.key_entry.configure(show='' if state['show_key'] else '•')
self.remember.set(state['remember'])
if state['log']:
self.log.configure(state='normal')
self.log.insert('end', state['log'])
self.log.configure(state='disabled')
self.sync_keys()
if state['key_selection'] and state['key_selection'][0] < len(self.keys):
self.key_list.selection_clear(0, 'end')
self.key_list.selection_set(state['key_selection'][0])
if state['auto'] and state['prompt'].strip():
self.apply_prompt()
elif not state['auto']:
self.prompt_hint.set(t('hint_off'))
self.batch.restore_state(state['batch'])
if hasattr(self, 'compare'):
self.compare.import_state(state.get('compare') or {})
self.update_cost()
self.refresh_history()
self.status.set(t('status_idle') if self.keys else t('status_ready'))
self.tabs.select(state['tab'])
def _onboarding_pending(self):
return not bool(load_settings().get('onboarding_dismissed'))
def _build_onboarding(self, parent, force=False):
if self.onboard_card is not None:
try:
self.onboard_card.destroy()
except tk.TclError:
pass
self.onboard_card = None
if not force and not self._onboarding_pending():
return
box = card(parent, t('onboard_title'))
self.onboard_card = box
for key in ('onboard_step1', 'onboard_step2', 'onboard_step3'):
label(box, t(key)).pack(fill='x', pady=(0, 4))
actions = Flow(box)
actions.pack(fill='x', pady=(8, 0))
ttk.Button(actions, text=t('onboard_goto_keys'), command=self._onboard_goto_keys)
ttk.Button(actions, text=t('onboard_get_key'), style='Link.TButton', command=self._onboard_open_signup)
ttk.Button(actions, text=t('onboard_dismiss'), command=self.dismiss_onboarding)
actions.schedule()
def show_onboarding(self):
host = getattr(self, '_create_frame', None)
if host is None:
return
self._build_onboarding(host, force=True)
card = self.onboard_card
if card is None:
return
try:
siblings = [c for c in host.winfo_children() if c is not card]
card.pack_forget()
if siblings:
card.pack(fill='x', pady=(0, 12), before=siblings[0])
else:
card.pack(fill='x', pady=(0, 12))
except tk.TclError:
pass
try:
self.tabs.select(0)
except tk.TclError:
pass
def dismiss_onboarding(self):
save_setting('onboarding_dismissed', True)
if self.onboard_card is not None:
try:
self.onboard_card.destroy()
except tk.TclError:
pass
self.onboard_card = None
def _onboard_goto_keys(self):
try:
self.tabs.select(4) # API Key is last tab
except tk.TclError:
pass
def _onboard_open_signup(self):
import webbrowser
webbrowser.open(t('onboard_signup_url'))
def build_create(self, frame):
self._create_frame = frame
self.onboard_card = None
self._build_onboarding(frame)
heading(frame, t('gen_title'), t('gen_desc'))
columns = Columns(frame, self.scale)
columns.pack(fill='x')
prompt_box = card(columns.left, t('prompt_card'))
self.prompt = text_area(prompt_box, height=2, undo=True)
self.prompt.pack(fill='x', pady=(0, 4))
self.auto_prompt = tk.BooleanVar(value=True)
self.prompt_hint = tk.StringVar(value=t('prompt_hint_default'))
ttk.Checkbutton(prompt_box, text=t('auto_detect'), variable=self.auto_prompt,
command=self.apply_prompt).pack(anchor='w')
label(prompt_box, variable=self.prompt_hint).pack(fill='x', pady=(2, 0))
self.prompt.bind('<<Modified>>', self.prompt_changed)
self.prompt.edit_modified(False)
self._build_first_frame_card(columns.left)
params = card(columns.left, t('params_card'))
self.model_id = tk.StringVar(value=DEFAULT_MODEL_ID)
self.model_label = tk.StringVar()
model_row = ttk.Frame(params)
model_row.pack(fill='x', pady=(0, 4))
ttk.Label(model_row, text=t('param_model'), style='Muted.TLabel').pack(anchor='w', pady=(0, 6))
self.model_combo = ttk.Combobox(model_row, textvariable=self.model_label, state='readonly', width=28)
self.model_combo.pack(fill='x')
desc_row = ttk.Frame(model_row)
desc_row.pack(fill='x', pady=(4, 0))
self.model_desc = tk.StringVar()
self.model_desc_full = tk.StringVar()
self._model_details_open = False
label(desc_row, variable=self.model_desc).pack(side='left', fill='x', expand=True)
self.model_details_btn = ttk.Button(desc_row, text=t('model_details'), style='Link.TButton',
command=self._toggle_model_details)
self.model_details_btn.pack(side='right', padx=(8, 0))
self.model_desc_full_label = label(model_row, variable=self.model_desc_full)
self.model_desc_full_label.pack(fill='x', pady=(4, 0))
self.model_desc_full_label.pack_forget()
self.model_adjust = tk.StringVar()
self.model_adjust_label = label(model_row, variable=self.model_adjust, style='Badge.TLabel')
self.model_adjust_label.pack(fill='x', pady=(6, 0))
self.model_adjust_label.pack_forget()
self._model_labels = {}
self._refresh_model_combo()
self.model_combo.bind('<<ComboboxSelected>>', lambda *_: self._on_model_picked())
row = ttk.Frame(params)
row.pack(fill='x')
self.duration, self.resolution, self.ratio = tk.StringVar(value='5'), tk.StringVar(value='720p'), tk.StringVar(value='16:9')
self.duration_spin = self.resolution_combo = self.ratio_combo = None
for index, (name, var, kind) in enumerate([
(t('param_duration'), self.duration, 'duration'),
(t('param_resolution'), self.resolution, 'resolution'),
(t('param_ratio'), self.ratio, 'ratio')]):
row.columnconfigure(index, weight=1, uniform='params')
field = ttk.Frame(row)
field.grid(row=0, column=index, sticky='ew', padx=(0, 12 if index < 2 else 0))
ttk.Label(field, text=name, style='Muted.TLabel').pack(anchor='w', pady=(0, 6))
if kind == 'duration':
widget = ttk.Spinbox(field, from_=2, to=30, textvariable=var, width=6)
self.duration_spin = widget
else:
widget = ttk.Combobox(field, textvariable=var, values=('720p', '1080p') if kind == 'resolution' else ('16:9', '9:16', '1:1'),
state='readonly', width=6)
if kind == 'resolution':
self.resolution_combo = widget
else:
self.ratio_combo = widget
widget.pack(fill='x')
var.trace_add('write', lambda *_: self.update_cost())
self.cost = tk.StringVar()
label(params, variable=self.cost).pack(fill='x', pady=(4, 0))
self._sync_model_widgets()
self.update_cost()
actions = Flow(params)
actions.pack(fill='x', pady=(6, 0))
self.generate_btn = ttk.Button(actions, text=t('generate_btn'), style='Accent.TButton', command=self.generate)
self.stop_btn = ttk.Button(actions, text=t('stop_btn'), command=self.stop_wait, state='disabled')
actions.schedule()
self.bar = ttk.Progressbar(params, mode='indeterminate')
# Right column: current config + save folder + collapsed advanced
current = card(columns.right, t('current_card'))
self.current_model_badge = tk.StringVar()
label(current, variable=self.current_model_badge, style='Badge.TLabel').pack(fill='x')
label(current, t('current_saved')).pack(fill='x', pady=(10, 0))
self._update_current_model_badge()
self.advanced_open = tk.BooleanVar(value=False)
adv_card = card(columns.right, t('media_card'))
self.advanced_toggle_btn = ttk.Button(adv_card, text=t('advanced_show'), style='Link.TButton',
command=self._toggle_advanced)
self.advanced_toggle_btn.pack(anchor='w')
self.advanced_body = ttk.Frame(adv_card)
label(self.advanced_body, t('media_card_desc')).pack(fill='x', pady=(0, 8))
if not hasattr(self, 'media') or 'first_frame' not in getattr(self, 'media', {}):
# first_frame StringVar is created in _build_first_frame_card (left column).
self.media = getattr(self, 'media', {})
self.media.setdefault('first_frame', tk.StringVar())
for kind in ('last_frame', 'reference_image', 'reference_video', 'reference_audio'):
ttk.Label(self.advanced_body, text=t('media_' + kind), style='Muted.TLabel').pack(anchor='w', pady=(0, 4))
var = tk.StringVar()
ttk.Entry(self.advanced_body, textvariable=var, width=12).pack(fill='x', pady=(0, 8))
self.media[kind] = var
ttk.Label(self.advanced_body, text=t('seed_label'), style='Muted.TLabel').pack(anchor='w', pady=(0, 4))
self.seed = tk.StringVar()
ttk.Entry(self.advanced_body, textvariable=self.seed, width=12).pack(fill='x')
# Collapsed by default so Generate stays on the first screen.
save_box = card(columns.right, t('save_card'))
ttk.Label(save_box, text=t('output_folder'), style='Muted.TLabel').pack(anchor='w', pady=(0, 6))
row = ttk.Frame(save_box)
row.pack(fill='x')
self.output = tk.StringVar(value=str(Path.home() / 'Videos' / 'PowerTokensVideoStudio'))
ttk.Entry(row, textvariable=self.output, width=12).pack(side='left', fill='x', expand=True)
ttk.Button(row, text=t('browse'), command=self.choose_folder).pack(side='left', padx=(10, 0))
label(save_box, t('cloud_note')).pack(fill='x', pady=(6, 0))
logs = card(frame, t('progress_card'))
self.log = text_area(logs, height=2, state='disabled')
self.log.pack(fill='x')
def _toggle_advanced(self):
if self.advanced_open.get():
self.advanced_body.pack_forget()
self.advanced_open.set(False)
self.advanced_toggle_btn.configure(text=t('advanced_show'))
else:
self.advanced_body.pack(fill='x', pady=(8, 0))
self.advanced_open.set(True)
self.advanced_toggle_btn.configure(text=t('advanced_hide'))
def _build_first_frame_card(self, parent):
"""Primary I2V control under the prompt (local upload first, URL secondary)."""
self.ff_card = card(parent, t('first_frame_label'))
self.ff_tip = label(self.ff_card, t('first_frame_tip'))
self.ff_tip.pack(fill='x', pady=(0, 8))
self.ff_unsupported = label(self.ff_card, t('first_frame_unsupported'))
self.ff_unsupported.pack(fill='x', pady=(0, 4))
self.ff_unsupported.pack_forget()
self.ff_controls = ttk.Frame(self.ff_card)
self.ff_controls.pack(fill='x')
row = ttk.Frame(self.ff_controls)
row.pack(fill='x')
self.ff_pick_btn = ttk.Button(row, text=t('first_frame_pick'), command=self._choose_first_frame)
self.ff_pick_btn.pack(side='left')
self.ff_clear_btn = ttk.Button(row, text=t('first_frame_remove'), style='Link.TButton',
command=self._clear_first_frame)
self.ff_clear_btn.pack(side='left', padx=(8, 0))
self.ff_info = tk.StringVar(value='')
self.ff_info_label = label(self.ff_controls, variable=self.ff_info)
self.ff_info_label.pack(fill='x', pady=(6, 0))
self.ff_info_label.pack_forget()
self.ff_url_open = tk.BooleanVar(value=False)
self.ff_url_toggle = ttk.Button(self.ff_controls, text=t('first_frame_url_summary'),
style='Link.TButton', command=self._toggle_ff_url)
self.ff_url_toggle.pack(anchor='w', pady=(8, 0))
self.ff_url_body = ttk.Frame(self.ff_controls)
self.media = getattr(self, 'media', {})
self.media['first_frame'] = tk.StringVar()
self._ff_local_name = None
self._ff_url_var = tk.StringVar()
self._ff_syncing_url = False
ttk.Entry(self.ff_url_body, textvariable=self._ff_url_var, width=12).pack(fill='x')
self._ff_url_var.trace_add('write', lambda *_: self._on_ff_url_typed())
self.ff_wan_note = label(self.ff_controls, t('first_frame_wan_note'), style='Badge.TLabel')
self.ff_wan_note.pack(fill='x', pady=(8, 0))
self.ff_wan_note.pack_forget()
self._refresh_first_frame_ui()
def _toggle_ff_url(self):
if self.ff_url_open.get():
self.ff_url_body.pack_forget()
self.ff_url_open.set(False)
self.ff_url_toggle.configure(text=t('first_frame_url_summary'))
else:
self.ff_url_body.pack(fill='x', pady=(4, 0), after=self.ff_url_toggle)
self.ff_url_open.set(True)
self.ff_url_toggle.configure(text=t('first_frame_url_hide'))
def _on_ff_url_typed(self):
if self._ff_syncing_url:
return
url = self._ff_url_var.get().strip()
self._ff_local_name = None
self.media['first_frame'].set(url)
self._refresh_first_frame_ui()
def _choose_first_frame(self):
path = filedialog.askopenfilename(
title=t('first_frame_pick'),
filetypes=[
(t('media_first_frame'), '*.jpg *.jpeg *.png *.webp *.gif *.bmp'),
('*', '*.*'),
])
if not path:
return
try:
data_url = encode_local_image_as_data_url(path)
except TaskError as exc:
messagebox.showerror(t('check_input'), str(exc))
return
except Exception as exc:
messagebox.showerror(t('check_input'), str(exc))
return
self._ff_local_name = Path(path).name
self._ff_syncing_url = True
self._ff_url_var.set('')
self._ff_syncing_url = False
self.media['first_frame'].set(data_url)
self._refresh_first_frame_ui()
def _clear_first_frame(self):
self._ff_local_name = None
self._ff_syncing_url = True
self._ff_url_var.set('')
self._ff_syncing_url = False
self.media['first_frame'].set('')
self._refresh_first_frame_ui()
def _refresh_first_frame_ui(self):
if not hasattr(self, 'ff_controls'):
return
try:
spec = get_model(self.model_id.get())
except Exception:
return
ok = model_allows_first_frame(spec)
value = (self.media.get('first_frame').get() if self.media.get('first_frame') else '').strip()
if ok:
self.ff_unsupported.pack_forget()
if not self.ff_tip.winfo_manager():
self.ff_tip.pack(fill='x', pady=(0, 8), before=self.ff_controls)
if not self.ff_controls.winfo_manager():
self.ff_controls.pack(fill='x')
else:
self.ff_tip.pack_forget()
self.ff_controls.pack_forget()
if not self.ff_unsupported.winfo_manager():
self.ff_unsupported.pack(fill='x', pady=(0, 4))
if value.startswith('data:image/'):
info = t('first_frame_local_fmt', self._ff_local_name) if self._ff_local_name else t('first_frame_embedded')
self.ff_info.set(info)
if not self.ff_info_label.winfo_manager():
self.ff_info_label.pack(fill='x', pady=(6, 0), after=self.ff_pick_btn.master)
self.ff_clear_btn.configure(state='normal')
elif value:
self.ff_info.set(value if len(value) < 64 else value[:61] + '…')
if not self.ff_info_label.winfo_manager():
self.ff_info_label.pack(fill='x', pady=(6, 0), after=self.ff_pick_btn.master)
self.ff_clear_btn.configure(state='normal')
# Keep URL details open when a non-data URL is present.
if not value.startswith('data:') and not self.ff_url_open.get():
self._toggle_ff_url()
if not self._ff_url_var.get().strip() and not value.startswith('data:'):
self._ff_syncing_url = True
self._ff_url_var.set(value)
self._ff_syncing_url = False
else:
self.ff_info.set('')
self.ff_info_label.pack_forget()
self.ff_clear_btn.configure(state='disabled')
show_wan = ok and value.startswith('data:image/') and spec.family == 'wan'
if show_wan:
if not self.ff_wan_note.winfo_manager():
self.ff_wan_note.pack(fill='x', pady=(8, 0))
else:
self.ff_wan_note.pack_forget()
def _collect_generate_media(self):
"""Build media list for the current model; skip types the family rejects."""
spec = get_model(self.model_id.get())
allowed = set(allowed_media_types(spec.family))
items = []
for kind, var in self.media.items():
url = var.get().strip()
if not url or kind not in allowed:
continue
items.append({'type': kind, 'url': url})
return items
def _toggle_model_details(self):
self._model_details_open = not getattr(self, '_model_details_open', False)
if self._model_details_open:
self.model_desc_full_label.pack(fill='x', pady=(4, 0))
self.model_details_btn.configure(text=t('model_details_hide'))
else:
self.model_desc_full_label.pack_forget()
self.model_details_btn.configure(text=t('model_details'))
def build_history(self, frame):
heading(frame, t('history_title'), t('history_desc'))
table_card = card(frame, t('history_card'), t('history_card_desc'))
table = ttk.Frame(table_card)
table.pack(fill='both', expand=True)
table.rowconfigure(0, weight=1)
table.columnconfigure(0, weight=1)
self.tree = ttk.Treeview(table, columns=('time', 'task', 'state', 'key'), show='headings', selectmode='extended', height=8)
for column, name, width in [('time', 'col_created', 155), ('task', 'col_task', 350), ('state', 'col_state', 230), ('key', 'col_key', 90)]:
self.tree.heading(column, text=t(name))
self.tree.column(column, width=width, minwidth=60)
self.tree.grid(row=0, column=0, sticky='nsew')
sy = ttk.Scrollbar(table, command=self.tree.yview)
sy.grid(row=0, column=1, sticky='ns')
sx = ttk.Scrollbar(table, orient='horizontal', command=self.tree.xview)
sx.grid(row=1, column=0, sticky='ew')
self.tree.configure(yscrollcommand=sy.set, xscrollcommand=sx.set)
self.tree.bind('<Control-c>', self.copy_selected_task_ids)
self.tree.bind('<Control-a>', self.select_all_task_rows)
row = Flow(table_card)
row.pack(fill='x', pady=(10, 0))
self.resume_btn = ttk.Button(row, text=t('resume_selected'), style='Accent.TButton', command=self.resume_selected)
ttk.Button(row, text=t('refresh'), command=self.refresh_history)
ttk.Button(row, text=t('copy_selected_ids'), command=self.copy_selected_task_ids)
ttk.Button(row, text=t('copy_all_ids'), command=self.copy_all_task_ids)
ttk.Button(row, text=t('open_folder'), command=self.open_folder)
row.schedule()
box = card(frame, t('manual_card'), t('manual_card_desc'))
row = ttk.Frame(box)
row.pack(fill='x')
self.task_id = tk.StringVar()
ttk.Entry(row, textvariable=self.task_id, width=12).pack(side='left', fill='x', expand=True)
self.manual_btn = ttk.Button(row, text=t('manual_btn'), command=self.resume_manual)
self.manual_btn.pack(side='left', padx=(10, 0))
link_box = card(frame, t('link_card'), t('link_card_desc'))
row = ttk.Frame(link_box)
row.pack(fill='x')
self.video_link = tk.StringVar()
ttk.Entry(row, textvariable=self.video_link, width=12).pack(side='left', fill='x', expand=True)
self.link_btn = ttk.Button(row, text=t('link_btn'), command=self.resume_from_link)
self.link_btn.pack(side='left', padx=(10, 0))
label(frame, t('history_footer'), style='Page.TLabel').pack(fill='x')
def build_keys(self, frame):
heading(frame, t('keys_title'), t('keys_desc'))
columns = Columns(frame, self.scale)
columns.pack(fill='x')
add = card(columns.left, t('add_card'), t('add_card_desc'))
self.key_input = tk.StringVar()
key_row = ttk.Frame(add)
key_row.pack(fill='x', pady=(0, 10))
self.key_entry = ttk.Entry(key_row, textvariable=self.key_input, show='•', width=12)
self.key_entry.pack(side='left', fill='x', expand=True)
self.show_key = tk.BooleanVar(value=False)
ttk.Checkbutton(key_row, text=t('show_key'), variable=self.show_key,
command=lambda: self.key_entry.configure(show='' if self.show_key.get() else '•')).pack(side='left', padx=(10, 0))
self.key_entry.bind('<Return>', lambda event: self.add_keys())
label(add, t('paste_hint')).pack(fill='x', pady=(0, 12))
ttk.Button(add, text=t('add_btn'), style='Accent.TButton', command=self.add_keys).pack(anchor='w')
pool = card(columns.left, t('pool_card'), t('pool_card_desc'))
self.key_count = tk.StringVar(value=t('key_count', 0, count=0))
label(pool, variable=self.key_count, style='Badge.TLabel').pack(anchor='w', pady=(0, 8))
# Tip sits under the pool header so it wraps inside the card and stays visible.
self.key_quota_tip = label(pool, t('key_quota_tip'), style='Badge.TLabel')
self.key_quota_tip.pack(fill='x', pady=(0, 4))
self.key_quota_tip.bind('<Button-1>', lambda *_: self.open_key_quota_tip())
try:
self.key_quota_tip.configure(cursor='hand2')
except tk.TclError:
pass
self.key_quota_btn = ttk.Button(pool, text=t('key_quota_tip_btn'), style='Link.TButton',
command=self.open_key_quota_tip)
self.key_quota_btn.pack(anchor='w', pady=(0, 12))
list_row = ttk.Frame(pool)
list_row.pack(fill='x')
self.key_list = tk.Listbox(list_row, height=8, width=1, exportselection=False, font=(FONT, 11),
background=WHITE, foreground=INK, relief='flat', borderwidth=0,
highlightthickness=1, highlightbackground=LINE, highlightcolor=ACCENT,
selectbackground='#e3f3ed', selectforeground='#236a5e', activestyle='none')
self.key_list.pack(side='left', fill='x', expand=True)
scroll = ttk.Scrollbar(list_row, command=self.key_list.yview)
scroll.pack(side='right', fill='y')
self.key_list.configure(yscrollcommand=scroll.set)
ttk.Button(pool, text=t('remove_key'), command=self.remove_key).pack(anchor='w', pady=(12, 0))
label(pool, t('pool_note')).pack(fill='x', pady=(10, 0))
get = card(columns.right, t('get_card'), t('get_card_desc'))
self.promo_label = label(get, promotion_text(), style='Badge.TLabel')
self.get_key_btn = ttk.Button(get, text=t('get_btn'), style='Accent.TButton', command=self.open_official_keys)
self.get_key_btn.pack(fill='x')
self.refresh_promo()
label(get, t('get_note')).pack(fill='x', pady=(12, 0))
save = card(columns.right, t('local_card'))
self.remember = tk.BooleanVar(value=False)
ttk.Checkbutton(save, text=t('remember'), variable=self.remember, command=self.save_keys).pack(anchor='w')
label(save, t('dpapi_badge'), style='Badge.TLabel').pack(anchor='w', pady=(10, 14))
label(save, t('remember_note')).pack(fill='x')
ttk.Separator(save).pack(fill='x', pady=16)
label(save, t('no_repeat_note')).pack(fill='x')
def prompt_changed(self, event=None):
if not self.prompt.edit_modified():
return
self.prompt.edit_modified(False)
if self.prompt_timer:
self.root.after_cancel(self.prompt_timer)
self.prompt_timer = self.root.after(400, self.apply_prompt)
def apply_prompt(self):
self.prompt_timer = None
if not self.auto_prompt.get():
self.prompt_hint.set(t('hint_off'))
return {'warnings': []}
result = infer_prompt(self.prompt.get('1.0', 'end'))
hints = []
if result['duration'] is not None:
self.duration.set(str(result['duration']))
hints.append(t('hint_seconds', result['duration']))
if result['ratio'] is not None:
self.ratio.set(result['ratio'])
hints.append(result['ratio'])
if result['warnings']:
self.prompt_hint.set(t('warning_sep').join(result['warnings']))
elif hints:
# e.g. "已识别:16 秒 · 16:9" plus "时长根据分镜时间轴推断…" when inferred from shot ranges.
self.prompt_hint.set(t('hint_detected') + ' · '.join(hints) +
''.join(t('hint_note_sep') + n for n in result.get('notes', [])))
else:
self.prompt_hint.set(t('hint_none'))
return result
def refresh_promo(self):
"""Show the campaign badge only while the discount runs; hides itself after PROMO_END_DATE."""
if not hasattr(self, 'promo_label'):
return
text = promotion_text()
if text:
self.promo_label.configure(text=text)
if not self.promo_label.winfo_manager():
self.promo_label.pack(fill='x', pady=(0, 16), before=self.get_key_btn)
else:
self.promo_label.pack_forget()
def _refresh_model_combo(self):
self._model_labels = {}
labels = []
for spec in list_models():
label_text = spec.label()
pct = spec.discount_percent()
if pct:
label_text = '%s (-%s%%)' % (label_text, pct)
self._model_labels[label_text] = spec.id
labels.append(label_text)
self.model_combo.configure(values=labels)
current = get_model(self.model_id.get())
current_label = current.label()
pct = current.discount_percent()
if pct:
current_label = '%s (-%s%%)' % (current_label, pct)
self.model_label.set(current_label)
self._update_model_description()
def _on_model_picked(self):
mid = self._model_labels.get(self.model_label.get(), DEFAULT_MODEL_ID)
self.model_id.set(mid)
self._sync_model_widgets()
self.update_cost()
def _sync_model_widgets(self, preserve=False):
spec = get_model(self.model_id.get())
if self.duration_spin is not None:
self.duration_spin.configure(from_=spec.durations[0], to=spec.durations[-1])
if self.resolution_combo is not None:
self.resolution_combo.configure(values=spec.resolutions)
if self.ratio_combo is not None:
self.ratio_combo.configure(values=spec.ratios)
changes = []
if not preserve:
try:
old_duration = int(self.duration.get())
except (TypeError, ValueError):
old_duration = self.duration.get()
old_resolution = self.resolution.get()
old_ratio = self.ratio.get()
new_duration, new_resolution, new_ratio, changes = snap_params(
spec, old_duration, old_resolution, old_ratio)
if str(self.duration.get()) != str(new_duration):
self.duration.set(str(new_duration))
if self.resolution.get() != new_resolution:
self.resolution.set(new_resolution)
if self.ratio.get() != new_ratio:
self.ratio.set(new_ratio)
self._show_model_adjust(changes)
else:
self._show_model_adjust([])
self._update_current_model_badge()
self._update_model_description()
self._refresh_first_frame_ui()
def _show_model_adjust(self, changes):
if not hasattr(self, 'model_adjust'):
return
if changes:
spec = get_model(self.model_id.get())
self.model_adjust.set(format_adjust_notice(spec, changes))
if not self.model_adjust_label.winfo_manager():
self.model_adjust_label.pack(fill='x', pady=(6, 0))
else:
self.model_adjust.set('')
self.model_adjust_label.pack_forget()
def _update_model_description(self):
if not hasattr(self, 'model_desc'):
return
spec = get_model(self.model_id.get())
self.model_desc.set(spec.summary())
if hasattr(self, 'model_desc_full'):
self.model_desc_full.set(spec.description())
def _update_current_model_badge(self):
if not hasattr(self, 'current_model_badge'):
return
spec = get_model(self.model_id.get())
self.current_model_badge.set(t('current_model_fmt', spec.label(), spec.id))
def update_cost(self):
if not hasattr(self, 'cost'):
return
self.refresh_promo() # Also catches the end date passing while the app stays open.
try:
mid = self.model_id.get() if hasattr(self, 'model_id') else DEFAULT_MODEL_ID
resolution = self.resolution.get()
value = estimate_cost(self.duration.get(), resolution, model_id=mid)
prices = current_prices(model_id=mid)
text = t('cost_estimate', PRICE_CHECKED_DATE, value, prices[resolution])
regular = list_prices(model_id=mid)
if resolution in regular:
text += t('cost_regular', regular[resolution])
self.cost.set(text + t('cost_tail'))
except (ValueError, KeyError, TaskError):
self.cost.set(t('cost_invalid'))
def open_key_quota_tip(self):
url = key_quota_tip_url()
try:
if not webbrowser.open(url):
messagebox.showinfo(t('official_site'), url)
except OSError:
messagebox.showinfo(t('official_site'), url)
def open_official_keys(self):
try:
if not webbrowser.open(official_key_url()):
messagebox.showinfo(t('official_site'), official_key_url())
except OSError:
messagebox.showinfo(t('official_site'), official_key_url())
def choose_folder(self):
folder = filedialog.askdirectory()
if folder:
self.output.set(folder)
def sync_keys(self):
self.key_list.delete(0, 'end')
for i, key in enumerate(self.keys):
self.key_list.insert('end', '%d. ****%s' % (i + 1, key[-4:]))
self.key_count.set(t('key_count', len(self.keys), count=len(self.keys)))
self.key_badge.set(t('badge_keys', len(self.keys), count=len(self.keys)) if self.keys else t('badge_no_key'))
if self.keys:
self.key_list.selection_set(0)
def add_keys(self):
try:
keys = parse_keys(self.key_input.get())
except ValueError as exc:
messagebox.showerror(t('key_format_title'), str(exc))
return
self.keys = list(dict.fromkeys(self.keys + keys))
self.key_input.set('')
self.status.set(t('keys_added_status', len(self.keys), count=len(self.keys)))
self.sync_keys()
self.save_keys()
def remove_key(self):
selected = self.key_list.curselection()
if selected:
self.keys.pop(selected[0])
self.sync_keys()
self.save_keys()
def save_keys(self):
path = DATA_DIR / 'keys.json'
try:
if self.remember.get():
encrypted = protect(json.dumps(self.keys).encode())
atomic_json(path, {'dpapi': base64.b64encode(encrypted).decode()})
else:
path.unlink(missing_ok=True)
except Exception:
self.remember.set(False)
messagebox.showerror(t('save_failed_title'), t('save_failed_body'))
def load_keys(self):
path = DATA_DIR / 'keys.json'
if path.exists():
try:
encrypted = base64.b64decode(json.loads(path.read_text(encoding='utf-8'))['dpapi'])
self.keys = json.loads(protect(encrypted, decrypt=True))
self.remember.set(True)
except Exception:
messagebox.showwarning(t('load_failed_title'), t('load_failed_body'))
self.sync_keys()
def selected_key(self):
if not self.keys:
raise TaskError(t('need_key'))
selected = self.key_list.curselection()
return self.keys[selected[0] if selected else 0]
def new_output(self):
folder = Path(self.output.get().strip()).expanduser()
folder.mkdir(parents=True, exist_ok=True)
# Validate write access before making a chargeable request.
test = folder / ('.write-test-' + uuid.uuid4().hex)
test.touch()
test.unlink()
return str(folder / ('wan_' + uuid.uuid4().hex[:12] + '.mp4'))
def generate(self):
if self.busy:
return
try:
if not self.keys:
raise TaskError(t('need_key'))
recognized = self.apply_prompt()
if recognized['warnings']:
raise TaskError(t('warning_sep').join(recognized['warnings']))
request = payload(self.prompt.get('1.0', 'end'), self.duration.get(), self.resolution.get(),
self.ratio.get(), self._collect_generate_media(),
self.seed.get(), model=self.model_id.get())
output = self.new_output()
except Exception as exc:
messagebox.showerror(t('check_input'), str(exc))
return
keys = list(self.keys)
self.launch(lambda client: client.submit(keys, request, output))
def resume_selected(self):
if self.busy:
return
selected = self.tree.selection()
if not selected:
messagebox.showinfo(t('select_task_title'), t('select_task_body'))
return
record = self.records[selected[0]]
try:
if not record.get('task_id'):
raise TaskError(t('record_no_id'))
key = next((k for k in self.keys if fingerprint(k) == record.get('key_hash')), None)
if not key:
raise TaskError(t('need_original_key') + record.get('key_hint', ''))
output = record['output']
if Path(output).exists():
output = self.new_output()
self.launch(lambda client: client.resume(key, record['task_id'], output, record))
except Exception as exc:
messagebox.showerror(t('cannot_resume'), str(exc))
def resume_manual(self):
if self.busy:
return
try:
from wan_core import task_url
task = self.task_id.get().strip()
task_url(task)
key, output = self.selected_key(), self.new_output()
self.launch(lambda client: client.resume(key, task, output))
except Exception as exc:
messagebox.showerror(t('check_input'), str(exc))
def resume_from_link(self):
if self.busy:
return
selected = self.tree.selection()
if not selected:
messagebox.showinfo(t('select_task_title'), t('select_download_body'))
return
try:
record = self.records[selected[0]]
key = next((k for k in self.keys if fingerprint(k) == record.get('key_hash')), None)
if not key:
raise TaskError(t('need_original_key') + record.get('key_hint', ''))
link = self.video_link.get().strip()
if not link:
raise TaskError(t('need_link'))
output = record['output']
if Path(output).exists():
output = self.new_output()
self.launch(lambda client: client.resume_download_url(key, record['task_id'], output, link, record))
except Exception as exc:
messagebox.showerror(t('link_failed_title'), str(exc))
def launch(self, operation, prefer_tab=None):
self.busy = True
self.stop.clear()
for button in (self.generate_btn, self.resume_btn, self.manual_btn, self.link_btn):
button.configure(state='disabled')
self.stop_btn.configure(state='normal')
self.batch.set_busy(True)
if hasattr(self, 'compare'):
self.compare.set_busy(True)
if not self.bar.winfo_manager():
self.bar.pack(fill='x', pady=(8, 0))
self.bar.start(12)
tab_map = {'generate': 0, 'compare': 1, 'batch': 2, 'history': 3, 'keys': 4}
self.tabs.select(tab_map.get(prefer_tab, 0))