Spaces:
Sleeping

File size: 45,665 Bytes
6c00a1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224e295
6c00a1f
 
224e295
6c00a1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd58eb7
 
 
224e295
6c00a1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224e295
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c00a1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab76de4
6c00a1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224e295
6c00a1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd58eb7
 
 
 
 
6c00a1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224e295
6c00a1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224e295
6c00a1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab76de4
fd58eb7
6c00a1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd58eb7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc77534
 
 
 
 
 
 
 
 
 
 
 
 
 
6c00a1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc77534
 
 
 
6c00a1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd58eb7
6c00a1f
 
 
 
 
 
 
fd58eb7
6c00a1f
fd58eb7
 
 
 
 
 
 
 
 
 
 
 
6c00a1f
 
 
fd58eb7
6c00a1f
224e295
 
 
fd58eb7
224e295
 
 
fd58eb7
224e295
fd58eb7
 
 
224e295
 
 
 
 
fd58eb7
224e295
 
 
 
fd58eb7
224e295
 
 
6c00a1f
 
 
 
 
fd58eb7
6c00a1f
 
 
 
 
 
 
fd58eb7
6c00a1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd58eb7
6c00a1f
 
 
 
 
 
 
fd58eb7
dc77534
fd58eb7
 
 
 
 
 
 
 
 
 
 
6c00a1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224e295
 
 
6c00a1f
224e295
 
fd58eb7
224e295
fd58eb7
224e295
 
 
 
 
 
fd58eb7
 
 
224e295
 
 
 
fd58eb7
 
224e295
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd58eb7
224e295
 
 
 
 
 
5b579e9
 
 
 
224e295
 
 
 
 
6c00a1f
224e295
6c00a1f
fd58eb7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc77534
fd58eb7
 
 
dc77534
 
 
 
 
 
 
 
 
fd58eb7
6c00a1f
 
5b579e9
6c00a1f
 
 
 
 
 
 
 
 
5b579e9
6c00a1f
 
 
dc77534
 
 
6c00a1f
 
224e295
 
 
 
 
 
fd58eb7
 
 
 
224e295
 
 
 
 
 
 
 
fd58eb7
224e295
 
6c00a1f
 
 
 
 
5b579e9
fd58eb7
dc77534
fd58eb7
 
6c00a1f
 
 
dc77534
 
 
 
6c00a1f
 
 
 
 
 
 
 
 
 
224e295
 
 
6c00a1f
 
 
 
5b579e9
 
 
 
 
6c00a1f
 
 
 
fd58eb7
 
dc77534
 
 
 
 
 
 
6c00a1f
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
import sys
import subprocess
import os
import shutil
import time
import json
import requests
import zipfile
import queue
import re
import threading
import glob
import traceback
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor, as_completed
from difflib import SequenceMatcher

# ==========================================
# 0. 环境自动修复
# ==========================================
def install_package(package, pip_name=None):
    pip_name = pip_name or package
    try:
        __import__(package)
    except ImportError:
        print(f"📦 正在自动安装缺失库: {pip_name} ...")
        subprocess.check_call([sys.executable, "-m", "pip", "install", pip_name])

install_package("moviepy", "moviepy==1.0.3") 
install_package("whisper", "openai-whisper")
install_package("opencc", "opencc-python-reimplemented") 
install_package("PIL", "Pillow") 

import gradio as gr
import opencc
from moviepy.editor import VideoFileClip, AudioFileClip, vfx

# ================= 配置区域 =================

# 视频生成的 API Key
YUNWU_API_KEY = "sk-crO3d0vpI1gKZRxwhgJ5TfyGKrvKAydummPmuPFmR5Obkbm8"

# Whisper Key
WHISPER_API_KEY = "sk-swiXot5QTrrJQ5zu8oBiIpPAQLfB9SLM6te6LH4rLP9l771m"

MERCHANT_BASE_URL = "https://yunwu.ai" 

# 核心模型配置
SORA_MODEL = "sora-2-all"        # 模型名称
VIDEO_SIZE = "720p"              # 分辨率
VIDEO_DURATION = 15              # 时长
ORIENTATION = "landscape"        # 横屏

TEXT_MODEL = "gemini-3-pro-preview-thinking"
WHISPER_MODEL = "whisper-1" 
SEGMENTS_PER_VIDEO = 15          # 15个短句对应15秒视频
VIDEOS_PER_BATCH = 10            

TASKS_ROOT_DIR = "tasks_data" 

# 🔥🔥 极限并发 (测试期建议改小) 🔥🔥
VIDEO_WORKERS = 5           
LLM_WORKERS = 5            
RENDER_PARALLELISM = 4       # 渲染线程保持4以防爆内存

# 全局渲染锁
GLOBAL_RENDER_LOCK = threading.Lock()

FORCE_STYLE_PREFIX = (
    "A sacred Tibetan Thangka painting style on aged cotton canvas. "
    "Rich mineral pigment colors (ground lapis lazuli, malachite, cinnabar, gold lines). "
    "Solemn deities, flat perspective with divine aura. "
)

FORCE_MOTION_BOOSTER = (
    " , (EXTREME VISUAL VELOCITY: hard cuts every second, stroboscopic editing style, "
    "hyper-lapse speed, visual explosion, distinct unrelated scenes, frantic energy, "
    "kaleidoscope effect, elements constantly morphing and breaking, no continuity), "
)

FORCE_STYLE_SUFFIX = (
    " , highly detailed Thangka line work (Goujin), traditional cloth texture, masterpiece, "
    "bright lighting, bright scene, well-lit."
)

FORCE_NEGATIVE_PROMPT = (
    " --no child, children, kid, baby, toddler, minor, schoolboy, schoolgirl, young boy, young girl, "
    "slow motion, static, still image, frozen, continuity, smooth transition, "
    "photorealistic, realistic, 3d render, cgi, blurry, deformed, modern, watermark, dark, dim, shadows, night."
)

DEFAULT_GEN_SYSTEM = """你是一位专门制作【极速快闪蒙太奇】视频的唐卡艺术导演。
你的任务是将输入的 **文案段落**(每段包含15个短句),批量转化为 **对应数量的独立视频** 的提示词。

【输入格式】
你将收到类似这样的输入:
Video 1 Segments: [0-1s]... [1-2s]... [14-15s]...
Video 2 Segments: ...
...

【输出目标格式 (JSON List)】
必须返回一个包含对应数量对象的 JSON 列表,每个对象对应一个 15秒视频。
格式示例:
[
  {"id": 1, "prompt": "(0s-1s) Scene A --HARD CUT TO--> (1s-2s) Scene B..."},
  ...
]

【绝对铁律】
1. **必须返回与输入数量一致的 Prompt**。
2. 每个 Prompt 内部必须包含 15 个硬切画面。
3. 风格必须是高燃、快速、唐卡视觉。
4. 🚫 **严禁出现任何儿童相关词汇**:禁止使用 'child', 'kid', 'baby', 'boy', 'girl', 'student' 等词汇。涉及人物时,必须使用 'adult', 'man', 'woman', 'figure', 'deity' (神灵) 等成年或神话描述。
"""

# ================= 核心工具函数 =================

# SRT 解析函数
def parse_time_str(time_str):
    try:
        hours, minutes, seconds = time_str.split(':')
        seconds, milliseconds = seconds.split(',')
        return int(hours) * 3600 + int(minutes) * 60 + int(seconds) + int(milliseconds) / 1000.0
    except:
        return 0.0

def parse_srt_to_whisper_data(srt_path):
    if not os.path.exists(srt_path): return None
    try:
        with open(srt_path, 'r', encoding='utf-8') as f:
            content = f.read()
        segments = []
        full_text_list = []
        pattern = re.compile(r'(\d+)\n(\d{2}:\d{2}:\d{2},\d{3}) --> (\d{2}:\d{2}:\d{2},\d{3})\n((?:(?!\n\n).)*)', re.DOTALL)
        matches = pattern.findall(content)
        for match in matches:
            index, start_str, end_str, text_block = match
            text = text_block.replace('\n', ' ').strip()
            start_time = parse_time_str(start_str)
            end_time = parse_time_str(end_str)
            segments.append({
                "id": int(index) - 1,
                "seek": 0,
                "start": start_time,
                "end": end_time,
                "text": text
            })
            full_text_list.append(text)
        return {
            "text": " ".join(full_text_list),
            "segments": segments,
            "language": "zh" 
        }
    except Exception as e:
        print(f"SRT Parse Error: {e}")
        return None

def strict_text_splitter(text):
    chunks = []
    current_chunk = ""
    valid_count = 0
    punctuations = set(",。!?;:、,.;:!?\n\t ")
    for char in text:
        current_chunk += char
        if char not in punctuations: valid_count += 1
        should_cut = False
        if 15 <= valid_count <= 25:
            if char in punctuations: should_cut = True
        if valid_count > 25: should_cut = True
        if should_cut:
            if current_chunk.strip(): chunks.append(current_chunk.strip())
            current_chunk = ""
            valid_count = 0
    if current_chunk.strip(): chunks.append(current_chunk.strip())
    if len(chunks) > 1 and len(chunks[-1]) < 8:
        last_short = chunks.pop()
        chunks[-1] += last_short
    return chunks

def normalize_text(text):
    return re.sub(r"[^\w]", "", text)

def format_timestamp(seconds):
    millis = int((seconds - int(seconds)) * 1000)
    seconds = int(seconds)
    minutes = seconds // 60
    hours = minutes // 60
    minutes %= 60
    seconds %= 60
    return f"{hours:02d}:{minutes:02d}:{seconds:02d},{millis:03d}"

def generate_srt_file(subtitle_data, output_path):
    with open(output_path, 'w', encoding='utf-8') as f:
        for i, sub in enumerate(subtitle_data):
            start_str = format_timestamp(sub['start'])
            end_str = format_timestamp(sub['end'])
            text = sub['text']
            f.write(f"{i+1}\n{start_str} --> {end_str}\n{text}\n\n")
    return output_path

def align_transcript_with_truth(truth_text_raw, whisper_segments, logger_func):
    logger_func("🔄 正在执行【字幕真理修正】...")
    try:
        cc = opencc.OpenCC('s2t')
        truth_text_trad = cc.convert(truth_text_raw)
    except:
        truth_text_trad = truth_text_raw 
    truth_clean = truth_text_trad.replace("\n", "")
    corrected_segments = []
    truth_cursor = 0
    for i, seg in enumerate(whisper_segments):
        whisper_text = seg['text']
        if not whisper_text.strip(): continue
        search_window = len(whisper_text) + 20 
        search_area = truth_clean[truth_cursor : truth_cursor + search_window]
        matcher = SequenceMatcher(None, whisper_text, search_area)
        match = matcher.find_longest_match(0, len(whisper_text), 0, len(search_area))
        if match.size > 1:
            current_text_len = match.b + match.size
            final_len = max(len(whisper_text), current_text_len)
        else:
            final_len = len(whisper_text)
        if truth_cursor + final_len > len(truth_clean):
            final_len = len(truth_clean) - truth_cursor
        corrected_text = truth_clean[truth_cursor : truth_cursor + final_len]
        truth_cursor += final_len
        corrected_segments.append({"start": seg['start'], "end": seg['end'], "text": corrected_text})
        if truth_cursor >= len(truth_clean): break
    return corrected_segments

def calculate_video_durations_from_whisper(text_segments, whisper_segments, total_audio_duration, logger_func):
    logger_func("⚓ 正在执行锚点纠偏对齐 (V8.9 Anti-Drift)...")
    if not whisper_segments:
        lengths = [len("".join(seg)) for seg in text_segments]
        total_len = sum(lengths)
        return [max(5.0, (l/total_len)*total_audio_duration) for l in lengths]

    source_full_text = ""
    group_char_ranges = []
    current_char_idx = 0
    for seg_list in text_segments:
        group_text = normalize_text("".join(seg_list))
        length = len(group_text)
        group_char_ranges.append((current_char_idx, current_char_idx + length))
        source_full_text += group_text
        current_char_idx += length

    char_time_map = {}
    whisper_full_text = ""
    w_cursor = 0
    for seg in whisper_segments:
        seg_text = normalize_text(seg['text'])
        if not seg_text: continue
        start_t = seg['start']
        end_t = seg['end']
        duration = end_t - start_t
        seg_len = len(seg_text)
        seg_start_idx = w_cursor
        for i in range(seg_len):
            t = start_t + (i / seg_len) * duration
            char_time_map[seg_start_idx + i] = t
        whisper_full_text += seg_text
        w_cursor += seg_len

    matcher = SequenceMatcher(None, source_full_text, whisper_full_text)
    source_to_whisper_index = {}
    for tag, i1, i2, j1, j2 in matcher.get_opcodes():
        if tag == 'equal':
            for k in range(i2 - i1):
                source_to_whisper_index[i1 + k] = j1 + k
        elif tag == 'replace':
            s_len = i2 - i1
            w_len = j2 - j1
            for k in range(s_len):
                w_idx = j1 + int((k / s_len) * w_len)
                source_to_whisper_index[i1 + k] = min(w_idx, j2 - 1)

    cut_points = []
    last_valid_time = 0.0
    for i, (start_char, end_char) in enumerate(group_char_ranges):
        found_time = None
        for offset in range(min(5, end_char - start_char)):
            target = start_char + offset
            if target in source_to_whisper_index:
                w_idx = source_to_whisper_index[target]
                if w_idx in char_time_map:
                    found_time = char_time_map[w_idx]
                    break
        if found_time is not None:
            if found_time < last_valid_time: found_time = last_valid_time
            cut_points.append(found_time)
            last_valid_time = found_time
        else:
            cut_points.append(last_valid_time)
    cut_points.append(total_audio_duration)

    video_durations = []
    for i in range(len(text_segments)):
        t_start = cut_points[i]
        t_end = cut_points[i+1]
        dur = t_end - t_start
        final_dur = max(2.0, dur)
        video_durations.append(final_dur)
        logger_func(f"⚓ [Group {i+1}] 锚点: {t_start:.2f}s -> {t_end:.2f}s (时长: {final_dur:.2f}s)")
    return video_durations

# ================= Agent 类 =================

class DirectorAgent:
    def __init__(self):
        self.headers = {"Authorization": f"Bearer {YUNWU_API_KEY}", "Content-Type": "application/json"}
    
    def rewrite_failed_prompt(self, old_prompt, level):
        if level == 1: 
            system_instruction = (
                "The previous video prompt triggered a SAFETY FILTER. "
                "Your task: REWRITE the prompt to be 100% SAFE. "
                "1. REMOVE ALL references to human figures, bodies, or children. "
                "2. Focus ONLY on objects, scenery, architecture, or abstract energy. "
                "3. Keep the visual style but change the subject to something neutral."
            )
        else: 
            system_instruction = (
                "Prompt FAILED multiple times due to safety or errors. "
                "REWRITE as EXTREMELY CONCISE, ABSTRACT, and ARTISTIC. "
                "Use fewer than 10 words. No humans. Just pure visual atmosphere."
            )
        
        payload = {"model": TEXT_MODEL, "messages": [{"role": "system", "content": system_instruction}, {"role": "user", "content": f"Failed Prompt: {old_prompt}"}]}
        try:
            resp = requests.post(f"{MERCHANT_BASE_URL}/v1/chat/completions", headers=self.headers, json=payload, timeout=60)
            if resp.status_code == 200: return resp.json()['choices'][0]['message']['content'].strip()
        except: pass
        return old_prompt 

    def generate_batch_prompts(self, batch_data, system_prompt):
        user_msg = f"Generate prompts for {len(batch_data)} videos:\n\n"
        for i, group in enumerate(batch_data):
            video_text = " | ".join([f"({s}s) {txt}" for s, txt in enumerate(group)])
            user_msg += f"Video {i+1} Segments: {video_text}\n"
        payload = {"model": TEXT_MODEL, "messages": [{"role": "system", "content": system_prompt}, {"role": "user", "content": user_msg}], "response_format": {"type": "json_object"}}
        for _ in range(3): 
            try:
                resp = requests.post(f"{MERCHANT_BASE_URL}/v1/chat/completions", headers=self.headers, json=payload, timeout=120)
                if resp.status_code == 200:
                    content = resp.json()['choices'][0]['message']['content']
                    if "```json" in content: content = content.split("```json")[1].split("```")[0]
                    elif "```" in content: content = content.split("```")[1].split("```")[0]
                    data = json.loads(content)
                    if isinstance(data, dict):
                        for v in data.values():
                            if isinstance(v, list): return v
                    if isinstance(data, list): return data
            except: time.sleep(1)
        return [{"prompt": f"Fallback prompt {i}"} for i in range(len(batch_data))]

class AudioAgent:
    def __init__(self):
        self.headers = {"Authorization": f"Bearer {WHISPER_API_KEY}"} 
    
    def compress_audio(self, input_path, logger_func, force=False):
        if not force and os.path.getsize(input_path) < 24 * 1024 * 1024: return input_path
        prefix = "🔊 [强压模式]" if force else "📦 [普通压缩]"
        logger_func(f"{prefix} 正在压缩音频: {os.path.basename(input_path)}...")
        output_path = input_path.rsplit('.', 1)[0] + f"_compressed_{int(time.time())}.mp3"
        try:
            bitrate = "16k" if force else "32k"
            subprocess.run(["ffmpeg", "-y", "-i", input_path, "-ar", "16000", "-ac", "1", "-b:a", bitrate, output_path], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            return output_path
        except: return input_path

    def _execute_transcribe(self, file_path, max_attempts, logger_func):
        url = "https://api.apimart.ai/v1/audio/transcriptions"
        for attempt in range(max_attempts):
            try:
                logger_func(f"🎙️ Whisper (Apimart) 识别中 ({attempt+1}/{max_attempts})...")
                with open(file_path, "rb") as f:
                    files = {"file": (os.path.basename(file_path), f, "audio/mp3")}
                    data = {"model": "whisper-1", "language": "zh", "response_format": "verbose_json"}
                    resp = requests.post(url, headers=self.headers, files=files, data=data, timeout=600)
                if resp.status_code == 200:
                    res_json = resp.json()
                    if 'words' in res_json or 'segments' in res_json: return res_json
                logger_func(f"⚠️ 识别失败 (HTTP {resp.status_code}),重试中...")
                time.sleep(3)
            except Exception as e:
                logger_func(f"⚠️ 请求异常: {e}")
                time.sleep(3)
        return None

    def transcribe_audio_with_retry(self, audio_path, logger_func):
        logger_func("🎙️ [Phase 1] 首次识别尝试...")
        initial_path = self.compress_audio(audio_path, logger_func, force=False)
        res = self._execute_transcribe(initial_path, 5, logger_func)
        if res: return res

        logger_func("⚠️ [Phase 1] 失败,启动 [Phase 2] 极限压缩重试...")
        compressed_path = self.compress_audio(audio_path, logger_func, force=True)
        res = self._execute_transcribe(compressed_path, 5, logger_func)
        if res: return res
        
        logger_func("❌ Whisper 最终失败,将使用纯字数比例分配。")
        return None

class VideoAgent:
    def __init__(self, director_instance=None):
        self.headers = {"Authorization": f"Bearer {YUNWU_API_KEY}", "Content-Type": "application/json"} 
        self.director = director_instance
     
    def worker_task(self, prompt, global_video_idx, log_queue, save_dir):
        save_path = os.path.join(save_dir, f"clip_{global_video_idx+1:04d}.mp4")
        
        # 🔥🔥 断点续传核心逻辑 🔥🔥
        if os.path.exists(save_path) and os.path.getsize(save_path) > 1000: 
            log_queue.put(f"⏭️ [跳过] 视频{global_video_idx+1} 已存在,直接复用。")
            return save_path
        
        current_prompt_core = prompt
        
        for rewrite_cycle in range(3):
            if rewrite_cycle > 0:
                log_queue.put(f"♻️ [视频{global_video_idx+1}] 第 {rewrite_cycle} 次触发安全改写...")
                try: 
                    new_core = self.director.rewrite_failed_prompt(current_prompt_core, rewrite_cycle)
                    current_prompt_core = new_core if new_core else current_prompt_core
                except: pass
            
            final_prompt = (f"{FORCE_STYLE_PREFIX} {current_prompt_core} {FORCE_MOTION_BOOSTER} {FORCE_STYLE_SUFFIX} {FORCE_NEGATIVE_PROMPT}")
            final_prompt = re.sub(r'\s+', ' ', final_prompt).replace(", ,", ",").replace("..", ".")
            
            for attempt in range(5):
                try:
                    payload = {
                        "images": [],
                        "model": SORA_MODEL,
                        "orientation": ORIENTATION,
                        "prompt": final_prompt,
                        "size": VIDEO_SIZE,
                        "duration": VIDEO_DURATION,  
                        "watermark": False,
                        "private": True
                    }
                    
                    req = requests.post(f"{MERCHANT_BASE_URL}/v1/video/create", headers=self.headers, json=payload, timeout=60)
                    
                    if req.status_code != 200: 
                        log_queue.put(f"⚠️ [API Error {req.status_code}] {req.text[:100]}")
                        if req.status_code == 400: break 
                        time.sleep(2); continue
                    
                    task_id = req.json().get("id")
                    if not task_id: continue
                    
                    log_queue.put(f"⏳ [ID:{task_id}] 视频{global_video_idx+1} 生成中 (Cycle {rewrite_cycle})...")
                    start_time = time.time()
                    
                    while True:
                        if time.time() - start_time > 600: break 
                        status_resp = requests.get(f"{MERCHANT_BASE_URL}/v1/videos/{task_id}", headers=self.headers, timeout=30)
                        if status_resp.status_code == 200:
                            status = status_resp.json().get("status")
                            if status == "completed":
                                video_url = status_resp.json().get("video_url")
                                if video_url:
                                    with open(save_path, "wb") as f: f.write(requests.get(video_url, timeout=120).content)
                                    log_queue.put(f"⬇️ 视频{global_video_idx+1} 下载完成")
                                    return save_path
                            elif status == "failed": break 
                            time.sleep(3)
                        else: time.sleep(3)
                except Exception as e: 
                    log_queue.put(f"⚠️ 生成异常: {e}")
                    time.sleep(3)
                    
        log_queue.put(f"❌ 视频{global_video_idx+1} 彻底失败 (已尝试 3个Prompt版本 x 5次网络请求)")
        return None

# ================= 渲染核心 =================

def render_atomic_group_final(group_id, vid_path, target_duration, global_start, logger_func, output_filename):
    logger_func(f"🟫 [Group {group_id}] 渲染中 (时长:{target_duration:.1f}s)...")
    try:
        raw_clip = VideoFileClip(vid_path)
        if target_duration < 0.5: target_duration = 0.5 
        speed_factor = raw_clip.duration / target_duration
        video_clip = raw_clip.fx(vfx.speedx, factor=speed_factor)
        video_clip.write_videofile(output_filename, fps=24, codec="libx264", audio=False, threads=2, preset='ultrafast', ffmpeg_params=["-crf", "26"], logger=None)
        video_clip.close(); raw_clip.close()
        return True
    except Exception as e:
        logger_func(f"❌ [Group {group_id}] 渲染失败: {e}")
        return False

def align_and_edit_videos_production(video_files, audio_path, text_segments, whisper_result, full_truth_text, logger_func, output_zip_path):
    logger_func(f"🏭 启动 V9.2 生产线 (Sora版)...")
    try: ac = AudioFileClip(audio_path); total_audio = ac.duration; ac.close()
    except: return False

    final_subtitle_data = []
    srt_path = output_zip_path.replace(".zip", ".srt")
    if whisper_result and 'segments' in whisper_result:
        final_subtitle_data = align_transcript_with_truth(full_truth_text, whisper_result['segments'], logger_func)
        logger_func(f"📝 生成SRT: {os.path.basename(srt_path)}")
        generate_srt_file(final_subtitle_data, srt_path)

    if whisper_result and 'segments' in whisper_result:
        segment_durations = calculate_video_durations_from_whisper(text_segments, whisper_result['segments'], total_audio, logger_func)
    else:
        logger_func(f"⚠️ Whisper 最终失败,使用字数比例分配 (总长: {total_audio:.1f}s)")
        lengths = [len("".join(s)) for s in text_segments]
        total_len = sum(lengths)
        segment_durations = [(l/total_len)*total_audio for l in lengths]

    video_files = sorted(video_files)
    total_items = min(len(video_files), len(segment_durations))
    
    temp_dir = os.path.dirname(output_zip_path); chunk_dir = os.path.join(temp_dir, "chunks_temp"); os.makedirs(chunk_dir, exist_ok=True)
    global_cursor = 0.0; group_configs = [] 
    
    for i in range(total_items):
        target_d = segment_durations[i]
        group_configs.append({'id': i + 1, 'vid': video_files[i], 'dur': target_d, 'start': global_cursor, 'out': os.path.join(chunk_dir, f"part_{i+1:04d}.mp4")})
        global_cursor += target_d

    completed_count = 0
    with ThreadPoolExecutor(max_workers=RENDER_PARALLELISM) as renderer:
        future_map = {renderer.submit(render_atomic_group_final, cfg['id'], cfg['vid'], cfg['dur'], cfg['start'], logger_func, cfg['out']): cfg['id'] for cfg in group_configs}
        for f in as_completed(future_map): 
            if f.result(): completed_count += 1

    logger_func("🔗 最终拼接...")
    list_file_path = os.path.join(chunk_dir, "concat_list.txt"); temp_silent_full = os.path.join(chunk_dir, "full_silent.mp4"); final_mp4_path = output_zip_path.replace(".zip", ".mp4")
    valid_chunks = sorted([os.path.join(chunk_dir, f) for f in os.listdir(chunk_dir) if f.startswith("part_") and f.endswith(".mp4")])
    with open(list_file_path, "w", encoding="utf-8") as f:
        for p in valid_chunks: f.write(f"file '{os.path.abspath(p)}'\n")
            
    try:
        subprocess.run(["ffmpeg", "-y", "-f", "concat", "-safe", "0", "-i", list_file_path, "-c", "copy", temp_silent_full], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
        logger_func("🎵 注入音频...")
        subprocess.run(["ffmpeg", "-y", "-i", temp_silent_full, "-i", audio_path, "-c:v", "copy", "-c:a", "aac", "-map", "0:v:0", "-map", "1:a:0", "-shortest", final_mp4_path], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
        shutil.rmtree(chunk_dir, ignore_errors=True)
        
        logger_func("📦 打包 ZIP...")
        with zipfile.ZipFile(output_zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
            zf.write(final_mp4_path, os.path.basename(final_mp4_path))
            if os.path.exists(srt_path): zf.write(srt_path, os.path.basename(srt_path))
        return True
    except Exception as e:
        logger_func(f"❌ 拼接/打包失败: {e}")
        return False

def create_zip_package(file_paths, output_dir):
    timestamp = int(time.time()); zip_path = os.path.join(output_dir, f"Backup_Raw_{timestamp}.zip")
    with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
        for file in file_paths:
            if file and os.path.exists(file): zf.write(file, os.path.basename(file))
    return zip_path

# ================= V15 Task Manager & Data Persistence =================

class TaskManager:
    def __init__(self, root_dir=TASKS_ROOT_DIR):
        self.root_dir = root_dir
        os.makedirs(self.root_dir, exist_ok=True)

    def create_task(self, original_filename="project"):
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        clean_name = os.path.splitext(original_filename)[0]
        clean_name = re.sub(r'[\\/*?:"<>|]', "", clean_name)
        
        task_id = f"{clean_name}_{timestamp}"
        task_dir = os.path.join(self.root_dir, task_id)
        os.makedirs(task_dir, exist_ok=True)
        
        with open(os.path.join(task_dir, "log.txt"), "w", encoding="utf-8") as f:
            f.write(f"[{datetime.now().strftime('%H:%M:%S')}] 任务创建成功: {task_id}\n")
        
        self.update_status(task_id, "running", progress=0)
        return task_id, task_dir

    def save_task_config(self, task_id, config_data):
        """保存任务配置,用于断点续传"""
        config_path = os.path.join(self.root_dir, task_id, "task_config.json")
        try:
            with open(config_path, "w", encoding="utf-8") as f:
                json.dump(config_data, f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"Config Save Error: {e}")

    def load_task_config(self, task_id):
        """读取任务配置"""
        config_path = os.path.join(self.root_dir, task_id, "task_config.json")
        if os.path.exists(config_path):
            try:
                with open(config_path, "r", encoding="utf-8") as f:
                    return json.load(f)
            except: return None
        return None

    # 🔥🔥 新增删除方法 🔥🔥
    def delete_task(self, task_id):
        """删除单个任务及其所有文件"""
        if not task_id: return False, "未选择任务"
        task_dir = os.path.join(self.root_dir, task_id)
        try:
            if os.path.exists(task_dir):
                shutil.rmtree(task_dir)
                return True, f"✅ 任务 {task_id} 已物理删除"
            else:
                return False, f"❌ 任务 {task_id} 不存在"
        except Exception as e:
            return False, f"❌ 删除失败: {e}"

    def log(self, task_id, message):
        timestamp = datetime.now().strftime('%H:%M:%S')
        log_line = f"[{timestamp}] {message}\n"
        log_path = os.path.join(self.root_dir, task_id, "log.txt")
        try:
            with open(log_path, "a", encoding="utf-8") as f:
                f.write(log_line)
        except: pass
        print(f"[{task_id}] {message}") 

    def update_status(self, task_id, status, result_path=None, progress=0):
        status_path = os.path.join(self.root_dir, task_id, "status.json")
        data = {
            "status": status,
            "last_update": time.time(),
            "progress": progress,
            "result": result_path
        }
        try:
            with open(status_path, "w", encoding="utf-8") as f:
                json.dump(data, f)
        except: pass

    def get_task_info(self, task_id):
        task_dir = os.path.join(self.root_dir, task_id)
        if not os.path.exists(task_dir): return None
        
        log_content = ""
        try:
            with open(os.path.join(task_dir, "log.txt"), "r", encoding="utf-8") as f:
                log_content = f.read()
        except: log_content = "日志读取中..."
        
        status_data = {}
        try:
            with open(os.path.join(task_dir, "status.json"), "r", encoding="utf-8") as f:
                status_data = json.load(f)
        except: status_data = {"status": "unknown"}

        return {
            "id": task_id,
            "log": log_content,
            "status": status_data.get("status"),
            "result": status_data.get("result")
        }

    def list_tasks(self):
        tasks = []
        if not os.path.exists(self.root_dir): return []
        for d in os.listdir(self.root_dir):
            full_path = os.path.join(self.root_dir, d)
            if os.path.isdir(full_path):
                tasks.append(d)
        tasks.sort(key=lambda x: os.path.getmtime(os.path.join(self.root_dir, x)), reverse=True)
        return tasks

    def clear_all_tasks(self):
        try:
            shutil.rmtree(self.root_dir)
            os.makedirs(self.root_dir, exist_ok=True)
            return True, "✅ 存储已清空,所有历史任务已删除。"
        except Exception as e:
            return False, f"❌ 清空失败: {e}"

task_manager = TaskManager()

# --- 日志适配器 ---
class LogQueueAdapter:
    def __init__(self, task_manager, task_id):
        self.tm = task_manager
        self.tid = task_id
    def put(self, message):
        self.tm.log(self.tid, message)
    def get(self): return None 
    def empty(self): return True

# ----------------- 后台工作线程 -----------------
def background_worker(task_id, full_text, audio_path, system_prompt, original_filename, local_srt_path, is_resume=False):
    task_dir = os.path.join(task_manager.root_dir, task_id)
    logger = LogQueueAdapter(task_manager, task_id)

    def log_wrapper(msg):
        task_manager.log(task_id, msg)

    try:
        log_wrapper("🚀 任务启动/恢复中...")
        local_audio_path = os.path.join(task_dir, "original_audio.mp3")
        
        # 如果是新任务,保存现场;如果是恢复,不需要复制音频(假设已存在)
        if not is_resume:
            shutil.copy(audio_path, local_audio_path)
            # 🔥 保存任务配置,用于后续恢复
            config_data = {
                "full_text": full_text,
                "system_prompt": system_prompt,
                "original_filename": original_filename,
                "local_srt_path": local_srt_path
            }
            task_manager.save_task_config(task_id, config_data)
        
        zip_basename = task_id 
        if original_filename:
            zip_basename = os.path.splitext(original_filename)[0]
        
        # 优先读取本地 SRT 并内部转为 Whisper JSON
        whisper_result = None
        if local_srt_path and os.path.exists(local_srt_path):
            log_wrapper(f"📂 读取 SRT: {os.path.basename(local_srt_path)}")
            whisper_result = parse_srt_to_whisper_data(local_srt_path)
            
            if whisper_result:
                log_wrapper("✅ SRT 解析成功。")
                if not full_text.strip():
                    if 'text' in whisper_result:
                        full_text = whisper_result['text']
                        log_wrapper("📄 从 SRT 中自动拼接了全文文案。")
            else:
                log_wrapper(f"❌ SRT 解析失败,将尝试使用 API。")
                whisper_result = None

        if whisper_result is None:
            log_wrapper("🎙️ 正在调用 Whisper API...")
            audio_agent = AudioAgent()
            whisper_result = audio_agent.transcribe_audio_with_retry(local_audio_path, log_wrapper)
        
        if not full_text.strip():
            log_wrapper("❌ 错误:无法获取文案。")
            task_manager.update_status(task_id, "failed")
            return

        raw_segments = strict_text_splitter(full_text)
        video_text_groups = [] 
        for i in range(0, len(raw_segments), SEGMENTS_PER_VIDEO): video_text_groups.append(raw_segments[i : i + SEGMENTS_PER_VIDEO])
        total_videos = len(video_text_groups)
        
        log_wrapper(f"📄 共 {len(raw_segments)} 小节,{total_videos} 个视频任务。")
        
        director = DirectorAgent(); cameraman = VideoAgent(director_instance=director)
        llm_batches = []; video_futures = []
        video_executor = ThreadPoolExecutor(max_workers=VIDEO_WORKERS)
        
        for i in range(0, total_videos, VIDEOS_PER_BATCH): llm_batches.append(video_text_groups[i : i + VIDEOS_PER_BATCH])
        
        log_wrapper(f"🧠 开始并发生成与渲染...")
        with ThreadPoolExecutor(max_workers=LLM_WORKERS) as llm_executor:
            llm_future_map = {llm_executor.submit(director.generate_batch_prompts, batch, system_prompt): b_idx for b_idx, batch in enumerate(llm_batches)}
            for future in as_completed(llm_future_map):
                b_idx = llm_future_map[future]
                try:
                    prompts = future.result(); start_id = b_idx * VIDEOS_PER_BATCH
                    for i, p_obj in enumerate(prompts):
                        p_text = p_obj.get("prompt", "") if isinstance(p_obj, dict) else str(p_obj)
                        gid = start_id + i
                        if gid < total_videos: 
                            future_task = video_executor.submit(cameraman.worker_task, p_text, gid, logger, task_dir)
                            video_futures.append((gid, future_task))
                            
                    log_wrapper(f"⚡ Batch {b_idx+1} Prompt OK")
                except Exception as e:
                    log_wrapper(f"⚠️ Batch Error: {e}")

        log_wrapper("⏳ 等待所有视频素材就绪...")
        while True:
            done_count = sum(1 for _, f in video_futures if f.done())
            if done_count >= len(video_futures): break
            time.sleep(2)

        video_paths = [None] * total_videos
        for idx, f in video_futures:
            try: video_paths[idx] = f.result()
            except Exception as e: log_wrapper(f"❌ 视频 {idx+1} 线程崩溃: {str(e)}")
        
        valid_videos = [v for v in video_paths if v]
        log_wrapper(f"🎬 素材下载完毕 ({len(valid_videos)}/{total_videos})")
        
        if len(valid_videos) > 0:
            output_zip = os.path.join(task_dir, f"{zip_basename}.zip")
            
            log_wrapper("🔒 正在申请全局渲染锁...")
            with GLOBAL_RENDER_LOCK:
                log_wrapper("🟢 获得渲染锁,开始最终合成...")
                success = align_and_edit_videos_production(valid_videos, local_audio_path, video_text_groups[:len(valid_videos)], whisper_result, full_text, log_wrapper, output_zip)
                log_wrapper("⚪ 渲染结束,释放锁。")
            
            if success:
                log_wrapper("🎉🎉🎉 打包成功!")
                
                # 🔥🔥🔥 生成成功后,自动清理原片以释放空间 🔥🔥🔥
                log_wrapper("🧹 正在执行自动清理:删除中间视频文件以释放磁盘空间...")
                cleaned_count = 0
                for v_path in valid_videos:
                    if v_path and os.path.exists(v_path):
                        try:
                            os.remove(v_path)
                            cleaned_count += 1
                        except: pass
                
                log_wrapper(f"✅ 清理完成,已删除 {cleaned_count} 个临时视频片段。")
                
                task_manager.update_status(task_id, "completed", result_path=output_zip)
            else:
                log_wrapper("⚠️ 拼接失败,打包原始素材")
                bk_zip = create_zip_package(valid_videos, task_dir)
                task_manager.update_status(task_id, "failed", result_path=bk_zip)
        else:
            log_wrapper("❌ 无视频生成 (请检查上方日志)")
            task_manager.update_status(task_id, "failed")

    except Exception as e:
        log_wrapper(f"💥 致命错误: {traceback.format_exc()}")
        task_manager.update_status(task_id, "error")

# ================= 交互层 =================

def submit_batch_tasks(sys_prompt, *file_lists):
    tasks_to_launch = []
    skipped_info = []
    
    for i, uploaded_files in enumerate(file_lists):
        window_name = f"窗口 #{i+1}"
        if not uploaded_files: continue
            
        txt_file = None; audio_file = None; srt_file = None
        audio_exts = ['.mp3', '.wav', '.m4a', '.flac', '.aac', '.ogg', '.wma']
        
        for file_obj in uploaded_files:
            if not file_obj: continue
            filename = file_obj.name
            ext = os.path.splitext(filename)[1].lower()
            if ext == '.txt': txt_file = file_obj
            elif ext == '.srt': srt_file = file_obj
            elif ext in audio_exts: audio_file = file_obj
            else:
                if ext == '.mp4': audio_file = file_obj

        if txt_file and audio_file and srt_file:
            tasks_to_launch.append({
                "txt": txt_file, "audio": audio_file, "srt": srt_file, "index": i + 1
            })
        else:
            missing = []
            if not txt_file: missing.append("文案")
            if not audio_file: missing.append("音频")
            if not srt_file: missing.append("字幕")
            skipped_info.append(f"{window_name} (缺失: {', '.join(missing)})")

    if not tasks_to_launch:
        return "⚠️ 未检测到任何有效任务。\n(请确保至少有一个窗口包含了完整的 TXT+MP3+SRT)", None

    started_ids = []
    for task in tasks_to_launch:
        try:
            with open(task['txt'].name, 'r', encoding='utf-8') as f:
                final_text = f.read()
            original_fname = os.path.basename(task['txt'].name)
            
            task_id, _ = task_manager.create_task(original_fname)
            
            t = threading.Thread(
                target=background_worker, 
                args=(task_id, final_text, task['audio'].name, sys_prompt, original_fname, task['srt'].name, False)
            )
            t.start()
            started_ids.append(task_id)
        except Exception as e:
            skipped_info.append(f"窗口 #{task['index']} 启动报错: {str(e)}")

    if not started_ids:
        err_msg = "❌ 所有任务启动失败,请检查以下错误信息:\n" + "\n".join(skipped_info)
        return err_msg, None

    msg_lines = [f"🚀 成功启动 {len(started_ids)} 个任务!"]
    msg_lines.append(f"ID: {', '.join(started_ids)}")
    if skipped_info:
        msg_lines.append("\n⚠️ 以下窗口因文件不全或错误被跳过:")
        msg_lines.extend(skipped_info)
    
    return "\n".join(msg_lines), started_ids[0]

def resume_task_entry(task_id):
    """断点续传入口函数"""
    if not task_id: return "未选择任务"
    
    config = task_manager.load_task_config(task_id)
    if not config: return f"❌ 任务 {task_id} 缺少配置文件,无法恢复。"
    
    task_dir = os.path.join(task_manager.root_dir, task_id)
    local_audio = os.path.join(task_dir, "original_audio.mp3")
    if not os.path.exists(local_audio): return "❌ 原始音频文件已丢失,无法恢复。"
    
    t = threading.Thread(
        target=background_worker,
        args=(
            task_id, 
            config.get("full_text"), 
            local_audio, 
            config.get("system_prompt"), 
            config.get("original_filename"), 
            config.get("local_srt_path"),
            True 
        )
    )
    t.start()
    return f"🚀 任务 {task_id} 已恢复运行!"

# 🔥🔥 删除单个任务交互函数 🔥🔥
def handle_delete_single_task(task_id):
    success, msg = task_manager.delete_task(task_id)
    # 删除后更新列表
    new_list = task_manager.list_tasks()
    new_val = new_list[0] if new_list else None
    return msg, gr.update(choices=new_list, value=new_val), "", None, "当前状态: 已删除"

def refresh_task_list():
    tasks = task_manager.list_tasks()
    return gr.update(choices=tasks, value=tasks[0] if tasks else None)

def get_task_details(task_id):
    if not task_id: return "请选择任务", None, None
    info = task_manager.get_task_info(task_id)
    if not info: return "任务不存在", None, None
    return info['log'], info['result'], f"当前状态: {info['status']}"

def handle_clear_storage():
    success, msg = task_manager.clear_all_tasks()
    return msg, gr.update(choices=[], value=None)

# ================= UI 构建 =================

with gr.Blocks(title="Veo V16 Final (Single Delete)") as demo:
    gr.Markdown("## 🎬 Veo V16 Final (Resume + AutoClean + ManualDelete)")
    gr.Markdown("🌟 **特性**:断点续传、自动清理原片、手动删除单任务释放空间")
    
    with gr.Tabs():
        with gr.Tab("🚀 批量提交任务"):
            gr.Markdown("### 批量上传区域 (每格需包含: txt + mp3 + srt)")
            sys_prompt = gr.Textbox(label="System Prompt", value=DEFAULT_GEN_SYSTEM, lines=3, visible=False)
            
            all_file_inputs = [] 
            with gr.Column():
                for row_idx in range(5): 
                    with gr.Row():      
                        for col_idx in range(4): 
                            i = row_idx * 4 + col_idx 
                            f_input = gr.File(
                                label=f"任务 #{i+1}", 
                                file_count="multiple", 
                                height=100,
                                min_width=100
                            )
                            all_file_inputs.append(f_input)
            
            submit_btn = gr.Button("🔥 立即启动有效任务", variant="primary")
            submit_result = gr.Textbox(label="提交结果", lines=5)
            new_task_id_storage = gr.State()

        with gr.Tab("📺 任务监控"):
            with gr.Row():
                with gr.Column(scale=1):
                    refresh_list_btn = gr.Button("🔄 刷新任务列表")
                    task_dropdown = gr.Dropdown(label="选择历史任务", choices=[], interactive=True, allow_custom_value=True)
                    
                    resume_btn = gr.Button("🔄 恢复/重试选中任务", variant="secondary")
                    resume_msg = gr.Label("")
                    
                    status_display = gr.Label("当前状态: 准备就绪")
                    download_file = gr.File(label="下载成品 (ZIP)")
                    
                    # 🔥🔥 新增删除按钮 🔥🔥
                    delete_single_btn = gr.Button("🗑️ 删除当前任务 (释放空间)", variant="secondary")
                    delete_msg = gr.Label("")
                    
                    gr.Markdown("---")
                    clear_btn = gr.Button("🗑️ 危险:清空所有任务数据", variant="stop")
                    clear_msg = gr.Label("")
                    
                with gr.Column(scale=3):
                    log_monitor = gr.Textbox(label="运行日志 (自动刷新)", lines=25, max_lines=25)
                    auto_timer = gr.Timer(2) 

    # --- 事件绑定 ---
    submit_btn.click(
        submit_batch_tasks, 
        inputs=[sys_prompt] + all_file_inputs, 
        outputs=[submit_result, new_task_id_storage]
    )

    def auto_select_new_task(new_id):
        all_tasks = task_manager.list_tasks()
        if new_id:
            if new_id not in all_tasks:
                all_tasks.insert(0, new_id)
            return gr.update(choices=all_tasks, value=new_id)
        return gr.update(choices=all_tasks, value=all_tasks[0] if all_tasks else None)
    
    submit_btn.click(auto_select_new_task, new_task_id_storage, task_dropdown)
    refresh_list_btn.click(refresh_task_list, outputs=task_dropdown)

    resume_btn.click(resume_task_entry, inputs=task_dropdown, outputs=resume_msg)

    # 🔥 绑定删除按钮 🔥
    delete_single_btn.click(
        handle_delete_single_task, 
        inputs=task_dropdown, 
        outputs=[delete_msg, task_dropdown, log_monitor, download_file, status_display]
    )

    auto_timer.tick(get_task_details, inputs=[task_dropdown], outputs=[log_monitor, download_file, status_display])
    task_dropdown.change(get_task_details, inputs=[task_dropdown], outputs=[log_monitor, download_file, status_display])
    
    clear_btn.click(handle_clear_storage, outputs=[clear_msg, task_dropdown])
    
    demo.load(refresh_task_list, outputs=task_dropdown)

if __name__ == "__main__":
    demo.queue().launch(server_name="0.0.0.0", inbrowser=True)