Spaces:
Sleeping

File size: 54,638 Bytes
fc2774d
 
 
 
 
 
 
 
 
 
 
 
 
77d33a1
fc2774d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30f3dab
fc2774d
77d33a1
fc2774d
77d33a1
fc2774d
77d33a1
fc2774d
 
 
 
77d33a1
fc2774d
 
 
 
 
 
 
77d33a1
 
 
 
fc2774d
 
 
 
77d33a1
fc2774d
 
 
30f3dab
fc2774d
 
77d33a1
fc2774d
77d33a1
 
 
 
fc2774d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77d33a1
fc2774d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77d33a1
fc2774d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30f3dab
fc2774d
 
 
 
 
 
 
 
 
 
 
77d33a1
fc2774d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30f3dab
77d33a1
 
 
fc2774d
 
77d33a1
 
 
 
 
 
 
fc2774d
77d33a1
 
 
 
30f3dab
77d33a1
 
 
fc2774d
77d33a1
 
 
 
fc2774d
77d33a1
 
 
 
 
 
 
 
 
30f3dab
77d33a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc2774d
77d33a1
 
 
 
 
 
fc2774d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30f3dab
 
 
fc2774d
 
 
 
 
 
 
 
 
 
 
 
 
77d33a1
fc2774d
 
 
 
77d33a1
fc2774d
 
 
 
 
 
 
 
77d33a1
fc2774d
 
 
 
 
 
 
 
 
 
 
 
 
 
77d33a1
fc2774d
 
 
 
 
 
 
 
 
 
 
 
 
77d33a1
fc2774d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30f3dab
fc2774d
30f3dab
fc2774d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30f3dab
fc2774d
 
30f3dab
fc2774d
 
 
30f3dab
fc2774d
 
 
 
 
 
 
 
30f3dab
fc2774d
30f3dab
fc2774d
 
 
 
 
30f3dab
 
 
fc2774d
 
30f3dab
fc2774d
 
 
30f3dab
 
 
 
 
 
 
 
fc2774d
 
 
 
30f3dab
fc2774d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30f3dab
fc2774d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77d33a1
fc2774d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77d33a1
fc2774d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
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
import copy
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") 
install_package("gradio")

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

# ================= 配置区域 (V24 暴力直链抓取版 - Fixed 403) =================

# FFmpeg 路径配置
import shutil
FFMPEG_PATH = shutil.which("ffmpeg") or "/usr/bin/ffmpeg"

# 1. LLM 配置
LLM_API_KEY = "sk-nkNoclHt8HeZ0FFe7SeCDmIhf9XF0PGrHeCeHyLv6UT5LK5R"
LLM_BASE_URL = "https://yunwu.ai/v1/chat/completions"
TEXT_MODEL = "gemini-3-pro-preview-thinking"

# 2. 视频配置
VIDEO_API_KEY = "zz2026021"
VIDEO_BASE_URL = "http://154.40.59.124:8000/flow/v1/videos"
SORA_MODEL = "veo_3_1-fast-landscape" 

# 3. 语音配置
WHISPER_API_KEY = "sk-swiXot5QTrrJQ5zu8oBiIpPAQLfB9SLM6te6LH4rLP9l771m"

# 任务参数
SEGMENTS_PER_VIDEO = 8
VIDEOS_PER_BATCH = 5
VIDEO_DURATION = 8.0

# 任务存储路径
TASKS_ROOT_DIR = "tasks_data_thangka_v24" 

# 并发设置
VIDEO_WORKERS = 200               
LLM_WORKERS = 100                 
RENDER_PARALLELISM = 4        
DOWNLOAD_SEMAPHORE = threading.Semaphore(100) # 直链模式可以放开并发
GLOBAL_RENDER_LOCK = threading.Lock()

# ================= 提示词工程 =================

FORCE_STYLE_PREFIX = "Thangka style. "
FORCE_MOTION_BOOSTER = " , (FAST MOTION: camera moving forward rapidly, elements transforming, dynamic composition, wind blowing, flying objects, energy flowing, no static scenes), "
FORCE_STYLE_SUFFIX = " , traditional cloth texture, masterpiece."
FORCE_NEGATIVE_PROMPT = " --no static, still image, frozen, slow motion, standing still, paused, photorealistic, realistic, 3d render, cgi, blurry, deformed, watermark."

DEFAULT_GEN_SYSTEM = """你是一位精通“唐卡艺术”与“高速动态视觉”的视频导演。
你的任务是将输入的 **8个文案片段**,严格转化为 **8个对应的时间戳画面描述**。

【输入格式】
你将收到类似这样的输入:
Video 1 Segments: (0.0s) 文案1 | (1.0s) 文案2 | (2.0s) 文案3 | ... | (7.0s) 文案8

【核心任务:1对1 映射 (1.0秒法则)】
你必须生成一个英文 Prompt,严格按照以下时间段:
[0.0s-1.0s] 画面展示 "文案1"
[1.0s-2.0s] 画面展示 "文案2"
[2.0s-3.0s] 画面展示 "文案3"
[3.0s-4.0s] 画面展示 "文案4"
[4.0s-5.0s] 画面展示 "文案5"
[5.0s-6.0s] 画面展示 "文案6"
[6.0s-7.0s] 画面展示 "文案7"
[7.0s-8.0s] 画面展示 "文案8"

【必须遵守的规则】
1. **风格 (Style)**: 必须是 "Thangka style" (唐卡风格)。
2. **运动 (Motion)**: 【重要】每一个 1.0秒的时间段都必须包含 "高速运动" 的描述!
   - 错误示例: "A Buddha sitting on a lotus." (静态,禁止)
   - 正确示例: "A Buddha on a lotus flying rapidly through clouds, golden light exploding outwards." (动态,通过)
3. **二次检查 (Double Check)**: 在生成前,请自我检查:这8个片段是否都是动态的?如果有静态画面,请立即修改为动态。

【输出目标格式 (JSON List)】
返回一个 JSON 列表。
格式示例:
[
  {"id": 1, "prompt": "[0.0s-1.0s] Fast moving visual of Text1 in Thangka style... [1.0s-2.0s] Rapid scene of Text2... [7.0s-8.0s] Dynamic ending of Text8..."},
  ...
]
"""

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

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 verify_video_integrity(file_path):
    if not os.path.exists(file_path): return False
    if os.path.getsize(file_path) < 1024: return False
    try:
        clip = VideoFileClip(file_path)
        duration = clip.duration
        clip.close()
        if duration and duration > 0: return True
        return False
    except:
        return False

# ================= 视频对齐逻辑 =================

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)
        if total_len == 0: return [8.0] * len(text_segments)
        return [max(3.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 {LLM_API_KEY}", "Content-Type": "application/json"}
      
    def rewrite_prompt_for_safety(self, original_prompt, level=1):
        if level == 1:
            sys_msg = (
                "You are a prompt engineer optimizing for video generation compliance."
                "Simplify the following prompt. Keep the core Thangka visual elements but remove complex actions."
                "Make it concise (under 20 words). Remove any potential NSFW, violence, or sensitive keywords."
                "Output ONLY the new English prompt."
            )
        else:
            sys_msg = (
                "EXTREME SAFETY MODE. Rewrite the prompt to describe a STATIC, HOLY object only."
                "Use simple words: 'Lotus', 'Buddha', 'Sky', 'Mountain'."
                "Remove ALL motion verbs. Remove ALL complex adjectives."
                "Ensure 100% compliance with safety policies."
                "Output ONLY the new English prompt."
            )

        payload = {
            "model": TEXT_MODEL,
            "messages": [{"role": "system", "content": sys_msg}, {"role": "user", "content": original_prompt}],
        }
       
        try:
            resp = requests.post(LLM_BASE_URL, headers=self.headers, json=payload, timeout=60)
            if resp.status_code == 200:
                content = resp.json()['choices'][0]['message']['content']
                return content.strip().replace('"', '').replace("'", "")
        except:
            pass
        return "Sacred Thangka patterns floating in the sky, peace and holy."

    def generate_batch_prompts(self, batch_data, system_prompt):
        user_msg = f"Please generate prompts for the following {len(batch_data)} videos:\n\n"
        for i, group in enumerate(batch_data):
            segment_text = ""
            for seg_idx, txt in enumerate(group):
                time_point = seg_idx * 1.0 
                segment_text += f"({time_point:.1f}s) {txt} | "
            
            user_msg += f"Video {i+1} Segments (Strict 1.0s Mapping): {segment_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(LLM_BASE_URL, 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, list): return data
                    if isinstance(data, dict):
                        for v in data.values():
                            if isinstance(v, list): return v
            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_PATH, "-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 Exception as e:
            logger_func(f"⚠️ 音频压缩失败: {e}")
            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

# ================= 视频生成 Agent (核心修改:1:1复刻程序B逻辑+下载修复) =================

class VideoAgent:
    def __init__(self, director_instance=None):
        self.headers = {"Authorization": f"Bearer {VIDEO_API_KEY}", "Content-Type": "application/json"} 
        self.director = director_instance
        self.FINAL_FALLBACK_PROMPT = "A Tibetan high monk meditating in peace, Thangka style."
      
    def _call_api(self, prompt, global_video_idx, log_queue, attempt_tag):
        final_prompt = (f"{FORCE_STYLE_PREFIX} {prompt} {FORCE_MOTION_BOOSTER} {FORCE_STYLE_SUFFIX} {FORCE_NEGATIVE_PROMPT}")
        final_prompt = re.sub(r'\s+', ' ', final_prompt).replace(", ,", ",").replace("..", ".")

        # 1. POST 创建任务
        payload = {
            "prompt": final_prompt,
            "model": SORA_MODEL, 
            "size": "1920x1080",
            "generate_audio": False 
        }

        log_queue.put(f"⏳ [视频{global_video_idx+1}] {attempt_tag} 提交任务...")

        try:
            resp = requests.post(VIDEO_BASE_URL, headers=self.headers, json=payload, timeout=60)
            if resp.status_code != 200:
                log_queue.put(f"⚠️ [API Fail {resp.status_code}] {resp.text}")
                return None
            
            resp_json = resp.json()
            task_id = resp_json.get("id") or resp_json.get("data", {}).get("id") or resp_json.get("task_id")
            
            if not task_id:
                log_queue.put(f"⚠️ 无法解析 Task ID: {resp_json}")
                return None
                
            log_queue.put(f"🔹 ID: {task_id},轮询中...")

            # 2. GET 查询状态 (Strict Program B Logic)
            check_url = f"{VIDEO_BASE_URL}/{task_id}"
            max_retries = 120 # 10分钟超时
            start_time = time.time()
            
            for _ in range(max_retries):
                # Program B uses explicit sleep 3s
                time.sleep(3) 
                elapsed = int(time.time() - start_time)
                if elapsed > 600:
                    log_queue.put(f"⚠️ 任务超时,ID: {task_id}")
                    break

                try:
                    # [核心] 严格按照程序B:添加 detail=true 参数
                    res_status = requests.get(check_url, headers=self.headers, params={"detail": "true"}, timeout=60)
                    
                    if res_status.status_code != 200:
                        continue 

                    status_data = res_status.json()
                    status = str(status_data.get("status") or status_data.get("state") or "").upper()
                    
                    if status in ["SUCCEEDED", "SUCCESS", "COMPLETED"]:
                        # 3. 从 detail 字段直接解析 download_url (参考程序B)
                        detail_info = status_data.get("detail", {})
                        download_link = None
                        
                        if isinstance(detail_info, dict):
                            download_link = detail_info.get("download_url")
                        
                        if not download_link and isinstance(detail_info, str):
                            try:
                                detail_json = json.loads(detail_info)
                                download_link = detail_json.get("download_url")
                            except: pass
                        
                        # 兜底:尝试 /content 重定向
                        if not download_link:
                            log_queue.put(f"⚠️ detail 中未找到链接,尝试探测 /content...")
                            try:
                                content_url = f"{VIDEO_BASE_URL}/{task_id}/content"
                                res_content = requests.get(content_url, headers=self.headers, allow_redirects=False, stream=True, timeout=30)
                                if res_content.status_code in [301, 302, 303, 307, 308]:
                                    download_link = res_content.headers.get('Location')
                                elif res_content.status_code == 200:
                                    download_link = content_url
                            except: pass
                        
                        if download_link:
                            log_queue.put(f"⚡️ [视频{global_video_idx+1}] 捕获直链: ...{download_link[-30:]}")
                            return download_link
                        else:
                            log_queue.put(f"❌ 任务成功但未找到下载链接: {json.dumps(status_data, ensure_ascii=False)[:100]}")
                            return None
                            
                    elif status in ["FAILED", "FAILURE"]:
                        error_msg = status_data.get("detail", "未知错误")
                        log_queue.put(f"❌ 生成失败: {error_msg}")
                        return None
                        
                except Exception as e:
                    pass

            log_queue.put(f"❌ 生成超时")
            return None

        except Exception as e:
            log_queue.put(f"⚠️ API 异常: {e}")
            return None

    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: 
            if verify_video_integrity(save_path):
                log_queue.put(f"⏭️ [跳过] 视频{global_video_idx+1} 已存在且有效。")
                return save_path
            else:
                log_queue.put(f"🗑️ [删除] 视频{global_video_idx+1} 已存在但损坏,重新生成。")
                os.remove(save_path)

        def safe_download_with_limit(url):
            with DOWNLOAD_SEMAPHORE:
                download_attempts = 3
                for d_i in range(download_attempts):
                    try:
                        log_queue.put(f"⬇️ [视频{global_video_idx+1}] 开始下载 (尝试 {d_i+1})...")
                        # 🔥🔥🔥【核心修正】移除 headers 参数!解决 403 问题 🔥🔥🔥
                        # Google Signed URL 不需要 Authorization Header,带了反而会被拒绝。
                        with requests.get(url, stream=True, timeout=600) as r:
                            if r.status_code == 200:
                                with open(save_path, 'wb') as f:
                                    for chunk in r.iter_content(chunk_size=8192): f.write(chunk)
                                if verify_video_integrity(save_path):
                                    return True
                                else:
                                    log_queue.put(f"⚠️ [视频{global_video_idx+1}] 下载文件损毁,准备重试...")
                                    try: os.remove(save_path)
                                    except: pass
                            else:
                                log_queue.put(f"⚠️ 下载拒绝 HTTP {r.status_code}")
                    except Exception as e: 
                        log_queue.put(f"⚠️ 下载异常: {e}")
                    time.sleep(2)
                return False

        current_prompt = prompt
        
        # 阶段 1: 原始 Prompt
        for i in range(3):
            url = self._call_api(current_prompt, global_video_idx, log_queue, f"Round 1-{i+1}")
            if url:
                if safe_download_with_limit(url):
                    log_queue.put(f"✅ [视频{global_video_idx+1}] 成功")
                    return save_path
            time.sleep(2)

        # 阶段 2: 第一次改写
        log_queue.put(f"🛡️ [视频{global_video_idx+1}] 启动一级改写...")
        try:
            current_prompt = self.director.rewrite_prompt_for_safety(prompt, level=1)
            log_queue.put(f"📝 New Prompt L1: {current_prompt[:50]}...")
        except Exception as e:
            log_queue.put(f"⚠️ 改写失败: {e}")

        for i in range(3):
            url = self._call_api(current_prompt, global_video_idx, log_queue, f"Round 2-{i+1}")
            if url and safe_download_with_limit(url):
                log_queue.put(f"✅ [视频{global_video_idx+1}] 一级改写生成成功")
                return save_path
            time.sleep(2)

        # 阶段 3: 第二次改写
        log_queue.put(f"🛡️🛡️ [视频{global_video_idx+1}] 启动二级改写...")
        try:
            current_prompt = self.director.rewrite_prompt_for_safety(prompt, level=2)
            log_queue.put(f"📝 New Prompt L2: {current_prompt[:50]}...")
        except: pass

        for i in range(3):
            url = self._call_api(current_prompt, global_video_idx, log_queue, f"Round 3-{i+1}")
            if url and safe_download_with_limit(url):
                log_queue.put(f"✅ [视频{global_video_idx+1}] 二级改写生成成功")
                return save_path
            time.sleep(2)

        # 阶段 4: 最终兜底
        log_queue.put(f"🧘 [视频{global_video_idx+1}] 使用兜底词...")
        for i in range(2):
            url = self._call_api(self.FINAL_FALLBACK_PROMPT, global_video_idx, log_queue, f"Fallback-{i+1}")
            if url and safe_download_with_limit(url): 
                log_queue.put(f"✅ [视频{global_video_idx+1}] 兜底成功")
                return save_path
            
        log_queue.put(f"❌❌❌ [视频{global_video_idx+1}] 彻底失败")
        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", "28"], logger=None)
        video_clip.close(); raw_clip.close()
        return True
    except Exception as e:
        logger_func(f"❌ [Group {group_id}] 渲染失败: {e}")
        return False

# --- 新增功能:去标点函数 ---
def remove_punctuation(text):
    # 去除中英文常见标点和特殊符号,保留文字和数字
    return re.sub(r"[,。!?;:、,.;:!?\"'«»(){}\[\]\s]", "", text)

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"🏭 启动 V24 生产线 (含硬字幕烧录)...")
    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)
        if total_len == 0: total_len = 1 
        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")])
    
    if not valid_chunks:
        logger_func("❌ 没有有效的视频片段可以拼接")
        return False

    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:
        # 1. 拼接无声视频 (Concat)
        subprocess.run([FFMPEG_PATH, "-y", "-f", "concat", "-safe", "0", "-i", list_file_path, "-c", "copy", temp_silent_full], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
        
        # 2. 准备烧录用的字幕 (去标点)
        burn_srt_path = os.path.join(chunk_dir, "burn_subs.srt")
        burn_subs_data = []
        if final_subtitle_data:
            # 深拷贝一份,以免影响原始SRT
            burn_subs_data = copy.deepcopy(final_subtitle_data)
            for item in burn_subs_data:
                item['text'] = remove_punctuation(item['text'])
            generate_srt_file(burn_subs_data, burn_srt_path)
            logger_func("🔥 字幕处理:标点已移除,准备烧录...")
        else:
            with open(burn_srt_path, 'w') as f: f.write("")

        # 3. 最终渲染:合并音频 + 烧录字幕 (使用 libx264 重编码)
        logger_func("🎵 注入音频并烧录硬字幕 (Rendering)...")
        
        ffmpeg_cmd = [
            FFMPEG_PATH, "-y",
            "-i", temp_silent_full,
            "-i", audio_path
        ]

        # 如果有字幕文件,添加 subtitles 滤镜
        # Fontsize=18, MarginV=25 可根据需要微调
        if os.path.exists(burn_srt_path) and os.path.getsize(burn_srt_path) > 0:
            style = "Fontsize=18,PrimaryColour=&HFFFFFF&,Outline=1,Shadow=0,MarginV=25"
            burn_path_esc = os.path.abspath(burn_srt_path).replace("\\", "/") # 路径处理
            ffmpeg_cmd.extend(["-vf", f"subtitles='{burn_path_esc}':force_style='{style}'"])
        
        ffmpeg_cmd.extend([
            "-c:v", "libx264",     # 必须重编码才能烧录
            "-preset", "fast",     # 编码速度 (veryfast/fast/medium)
            "-crf", "23",          # 画质控制 (18-28, 越小越好)
            "-c:a", "aac",
            "-map", "0:v:0", 
            "-map", "1:a:0", 
            "-shortest", 
            final_mp4_path
        ])

        subprocess.run(ffmpeg_cmd, 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}")
        print(traceback.format_exc())
        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

# ================= 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 save_generated_prompts(self, task_id, prompts):
        prompt_path = os.path.join(self.root_dir, task_id, "generated_prompts.txt")
        try:
            with open(prompt_path, "w", encoding="utf-8") as f:
                for idx, p in enumerate(prompts):
                    p_text = p.get("prompt", "") if isinstance(p, dict) else str(p)
                    f.write(f"--- Video {idx+1} Prompt ---\n{p_text}\n\n")
        except Exception as e: print(f"Prompts 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("🚀 任务启动/恢复中 (V24 - 1:1复刻版)...")
        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]
        
        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() and 'text' in whisper_result:
                    full_text = whisper_result['text']
            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} 个视频任务 ({SEGMENTS_PER_VIDEO}段/视频)。")
        
        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"🧠 开始并发生成 (API并发: {VIDEO_WORKERS}, 下载锁: 100)...")
        
        all_collected_prompts = [None] * total_videos

        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: 
                            all_collected_prompts[gid] = p_text
                            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}")

        valid_collected = [p for p in all_collected_prompts if p]
        task_manager.save_generated_prompts(task_id, valid_collected)
        log_wrapper(f"📝 Prompt 已生成 (共 {len(valid_collected)} 条)")

        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:
            skipped_info.append(f"{window_name} (缺失文件)")

    if not tasks_to_launch: return "⚠️ 未检测到有效任务", 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)}")

    msg = f"🚀 成功启动 {len(started_ids)} 个任务!\nID: {', '.join(started_ids)}"
    if skipped_info: msg += "\n" + "\n".join(skipped_info)
    return msg, 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()
    return msg, gr.update(choices=new_list, value=new_list[0] if new_list else None), "", 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 V24 Thangka Direct") as demo:
    gr.Markdown("## 🎬 Veo V24 Force-Direct Link (8x1.0s Thangka Mode)")
    
    with gr.Tabs():
        with gr.Tab("🚀 批量提交任务"):
            gr.Markdown("### 批量上传区域 (每格需包含: txt + mp3 + srt)")
            sys_prompt = gr.Textbox(label="System Prompt (Auto-Configured)", 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):
                    with gr.Row():
                        log_monitor = gr.Textbox(label="运行日志 (自动刷新)", lines=15, max_lines=15)
                    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 and new_id not in all_tasks: all_tasks.insert(0, new_id)
        return gr.update(choices=all_tasks, value=new_id if new_id else (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__":
    import os
    import socket
    import stat
    import shutil
    
    print(" 检查 FFmpeg...")
    ffmpeg_test = shutil.which("ffmpeg")
    if ffmpeg_test:
        print(f" FFmpeg 找到: {ffmpeg_test}")
        globals()['FFMPEG_PATH'] = ffmpeg_test
    else:
        print("错误: 找不到 FFmpeg")
        print("   请运行: sudo apt-get install ffmpeg")
        print("   或检查 PATH 环境变量")
    
    temp_dirs = ['/tmp/gradio', '/tmp/gradio_temp']
    for temp_dir in temp_dirs:
        try:
            os.makedirs(temp_dir, exist_ok=True)
            os.chmod(temp_dir, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
            print(f"已设置 {temp_dir} 权限")
        except Exception as e:
            print(f"警告: 无法设置 {temp_dir} 权限: {e}")
    
    os.environ['GRADIO_TEMP_DIR'] = '/tmp/gradio_temp'
    
    try:
        hostname = socket.gethostname()
        server_ip = socket.gethostbyname(hostname)
        if server_ip.startswith('127.'):
            import subprocess
            result = subprocess.run(['hostname', '-I'], capture_output=True, text=True)
            server_ip = result.stdout.strip().split()[0] if result.stdout else server_ip
    except:
        server_ip = "127.0.0.1"
    
    print("\n" + "=" * 60)
    print("=" * 60 + "\n")
    
    demo.queue(
        max_size=20,
        default_concurrency_limit=5,
        api_open=True
    ).launch(
        server_name="0.0.0.0",
        server_port=7860,
        inbrowser=False, 
        share=False,        
        max_threads=40,
        max_file_size="500mb",
        show_error=True,
        quiet=False,
        ssl_verify=False,    
        ssl_keyfile=None,        
        ssl_certfile=None,    
        allowed_paths=["/tmp", "./tasks_data_thangka_v24", "."]
    )