-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1978 lines (1616 loc) · 74.1 KB
/
Copy pathapp.py
File metadata and controls
1978 lines (1616 loc) · 74.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from flask import Flask, render_template, jsonify, request, Response, stream_with_context
from flask_cors import CORS
import yt_dlp
import re
import json
from deep_translator import GoogleTranslator
import logging
import threading
import time
import os
import sys
from datetime import datetime, timedelta
app = Flask(__name__)
CORS(app)
# 設定日誌
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# 應用根目錄(支援被 PyInstaller 打包後的 exe 放置目錄)
if getattr(sys, 'frozen', False):
# exe 模式:使用可執行檔所在目錄
BASE_DIR = os.path.dirname(sys.executable)
else:
# 開發模式:使用目前檔案所在目錄
BASE_DIR = os.path.dirname(__file__)
# 快取翻譯結果
translation_cache = {}
# 翻譯進度追蹤(用於多個請求)
translation_progress = {}
# 單字庫文件路徑(與 exe 同層)
WORD_BANK_FILE = os.path.join(BASE_DIR, 'word_banks.json')
# 字幕緩存文件路徑(與 exe 同層)
SUBTITLE_CACHE_FILE = os.path.join(BASE_DIR, 'subtitle_cache.json')
# 翻譯緩存文件路徑(與 exe 同層)
TRANSLATION_CACHE_FILE = os.path.join(BASE_DIR, 'translation_cache.json')
# 用戶資料文件路徑(與 exe 同層)
USER_DATA_FILE = os.path.join(BASE_DIR, 'user_data.json')
# 書籤文件路徑(與 exe 同層)
BOOKMARKS_FILE = os.path.join(BASE_DIR, 'bookmarks.json')
def load_subtitle_cache():
"""載入字幕緩存數據"""
if os.path.exists(SUBTITLE_CACHE_FILE):
try:
with open(SUBTITLE_CACHE_FILE, 'r', encoding='utf-8') as f:
return json.load(f)
except Exception as e:
logger.error(f"[字幕緩存] 載入失敗: {e}")
return {}
return {}
def save_subtitle_cache(cache):
"""保存字幕緩存數據"""
try:
with open(SUBTITLE_CACHE_FILE, 'w', encoding='utf-8') as f:
json.dump(cache, f, ensure_ascii=False, indent=2)
return True
except Exception as e:
logger.error(f"[字幕緩存] 保存失敗: {e}")
return False
def load_translation_cache():
"""載入翻譯緩存數據"""
if translation_cache: # 如果內存中已有緩存,先返回
return translation_cache
if os.path.exists(TRANSLATION_CACHE_FILE):
try:
with open(TRANSLATION_CACHE_FILE, 'r', encoding='utf-8') as f:
cache = json.load(f)
translation_cache.update(cache) # 更新內存緩存
return cache
except Exception as e:
logger.error(f"[翻譯緩存] 載入失敗: {e}")
return {}
return {}
def save_translation_cache():
"""保存翻譯緩存數據"""
try:
with open(TRANSLATION_CACHE_FILE, 'w', encoding='utf-8') as f:
json.dump(translation_cache, f, ensure_ascii=False, indent=2)
return True
except Exception as e:
logger.error(f"[翻譯緩存] 保存失敗: {e}")
return False
def load_word_banks():
"""載入單字庫數據"""
if os.path.exists(WORD_BANK_FILE):
try:
with open(WORD_BANK_FILE, 'r', encoding='utf-8') as f:
return json.load(f)
except Exception as e:
logger.error(f"[單字庫] 載入失敗: {e}")
return {}
return {}
def save_word_banks(word_banks):
"""保存單字庫數據"""
try:
with open(WORD_BANK_FILE, 'w', encoding='utf-8') as f:
json.dump(word_banks, f, ensure_ascii=False, indent=2)
return True
except Exception as e:
logger.error(f"[單字庫] 保存失敗: {e}")
return False
def load_user_data():
"""載入用戶資料數據"""
if os.path.exists(USER_DATA_FILE):
try:
with open(USER_DATA_FILE, 'r', encoding='utf-8') as f:
return json.load(f)
except Exception as e:
logger.error(f"[用戶資料] 載入失敗: {e}")
return {}
return {}
def save_user_data(user_data):
"""保存用戶資料數據"""
try:
with open(USER_DATA_FILE, 'w', encoding='utf-8') as f:
json.dump(user_data, f, ensure_ascii=False, indent=2)
return True
except Exception as e:
logger.error(f"[用戶資料] 保存失敗: {e}")
return False
def load_bookmarks():
"""載入書籤數據"""
if os.path.exists(BOOKMARKS_FILE):
try:
with open(BOOKMARKS_FILE, 'r', encoding='utf-8') as f:
return json.load(f)
except Exception as e:
logger.error(f"[書籤] 載入失敗: {e}")
return {}
return {}
def save_bookmarks(bookmarks):
"""保存書籤數據"""
try:
with open(BOOKMARKS_FILE, 'w', encoding='utf-8') as f:
json.dump(bookmarks, f, ensure_ascii=False, indent=2)
return True
except Exception as e:
logger.error(f"[書籤] 保存失敗: {e}")
return False
def get_user_stats(nickname):
"""獲取用戶學習統計"""
user_data = load_user_data()
if nickname not in user_data:
# 初始化新用戶資料
user_data[nickname] = {
'learning_time': 0, # 學習時間(秒)
'videos_watched': 0, # 觀看的影片數量
'words_added': 0, # 添加的單字數量
'review_sessions': 0, # 複習次數
'review_correct': 0, # 複習正確數量
'review_total': 0, # 複習總數量
'last_active': datetime.now().isoformat(),
'created_at': datetime.now().isoformat()
}
save_user_data(user_data)
return user_data[nickname]
def update_user_stats(nickname, stats_update):
"""更新用戶統計資料"""
user_data = load_user_data()
if nickname not in user_data:
user_data[nickname] = get_user_stats(nickname)
user_data[nickname].update(stats_update)
user_data[nickname]['last_active'] = datetime.now().isoformat()
save_user_data(user_data)
return user_data[nickname]
# 應用啟動時載入翻譯緩存(在所有函數定義之後)
load_translation_cache()
logger.info(f"[翻譯緩存] 已載入 {len(translation_cache)} 條翻譯緩存")
def extract_video_id(url):
"""從 YouTube URL 提取影片 ID"""
patterns = [
r'(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([^&\n?#]+)',
r'youtube\.com\/watch\?.*v=([^&\n?#]+)'
]
for pattern in patterns:
match = re.search(pattern, url)
if match:
return match.group(1)
return None
def get_subtitle_for_lang(subtitle_data, lang_code):
"""獲取指定語言的字幕內容"""
import urllib.request
import time
if not subtitle_data:
return None
subtitle_url = subtitle_data[0]['url']
# 確保使用 SRT 格式(如果不是,修改 URL)
if 'fmt=json3' in subtitle_url or 'fmt=json' in subtitle_url:
subtitle_url = subtitle_url.replace('fmt=json3', 'fmt=srt').replace('fmt=json', 'fmt=srt')
try:
url_start = time.time()
with urllib.request.urlopen(subtitle_url, timeout=30) as response:
subtitle_content = response.read().decode('utf-8')
url_elapsed = time.time() - url_start
logger.info(f"[字幕獲取] {lang_code} 字幕內容獲取成功,耗時 {url_elapsed:.2f} 秒,內容長度: {len(subtitle_content)} 字元")
# 檢查內容格式
if subtitle_content.strip().startswith('{') or subtitle_content.strip().startswith('['):
logger.warning(f"[字幕獲取] {lang_code} 收到 JSON 格式,嘗試轉換...")
import json
json_data = json.loads(subtitle_content)
subtitle_content = convert_json_to_srt(json_data)
logger.info(f"[字幕獲取] {lang_code} JSON 轉換為 SRT 完成")
parsed = parse_subtitle_content(subtitle_content)
logger.info(f"[字幕獲取] {lang_code} 字幕解析完成,解析出 {len(parsed)} 條字幕")
return parsed
except Exception as e:
logger.warning(f"[字幕獲取] {lang_code} 字幕獲取失敗: {e}")
return None
def get_subtitles(video_id):
"""使用 yt-dlp 獲取英文字幕和中文字幕(先檢查緩存)"""
# 先檢查緩存
subtitle_cache = load_subtitle_cache()
if video_id in subtitle_cache:
cached_data = subtitle_cache[video_id]
logger.info(f"[字幕緩存] 找到緩存字幕,video_id: {video_id}")
return cached_data.get('subtitles', None)
import tempfile
import os
url = f'https://www.youtube.com/watch?v={video_id}'
# 創建臨時目錄來存放字幕文件
with tempfile.TemporaryDirectory() as tmpdir:
ydl_opts = {
'writesubtitles': True,
'writeautomaticsub': True,
'subtitleslangs': ['en', 'zh-TW', 'zh-CN', 'en-US', 'en-GB'],
'subtitlesformat': 'srt',
'skip_download': True,
'outtmpl': os.path.join(tmpdir, '%(id)s.%(ext)s'),
'quiet': False,
'no_warnings': False,
}
try:
logger.info(f"[字幕獲取] 開始使用 yt-dlp 獲取影片資訊...")
logger.info(f"[字幕獲取] URL: {url}")
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(url, download=False)
logger.info(f"[字幕獲取] 影片資訊獲取成功")
# 檢查可用的字幕
subtitles = info.get('subtitles', {})
auto_captions = info.get('automatic_captions', {})
logger.info(f"[字幕獲取] 可用字幕語言: {list(subtitles.keys())}")
logger.info(f"[字幕獲取] 可用自動字幕語言: {list(auto_captions.keys())}")
# 尋找英文字幕
en_subtitle_data = None
en_lang = None
for lang_code in ['en', 'en-US', 'en-GB']:
if lang_code in subtitles:
en_subtitle_data = subtitles[lang_code]
en_lang = lang_code
break
elif lang_code in auto_captions:
en_subtitle_data = auto_captions[lang_code]
en_lang = lang_code
break
# 尋找中文字幕(優先繁體,其次簡體)
zh_subtitle_data = None
zh_lang = None
for lang_code in ['zh-TW', 'zh-CN', 'zh-Hant', 'zh-Hans']:
if lang_code in subtitles:
zh_subtitle_data = subtitles[lang_code]
zh_lang = lang_code
break
elif lang_code in auto_captions:
zh_subtitle_data = auto_captions[lang_code]
zh_lang = lang_code
break
if not en_subtitle_data:
logger.warning("[字幕獲取] 找不到英文字幕")
return None
logger.info(f"[字幕獲取] 找到英文字幕: {en_lang}")
if zh_subtitle_data:
logger.info(f"[字幕獲取] 找到中文字幕: {zh_lang}")
else:
logger.info(f"[字幕獲取] 找不到中文字幕,將只返回英文字幕")
# 獲取英文字幕
en_subtitles = get_subtitle_for_lang(en_subtitle_data, en_lang)
if not en_subtitles:
return None
# 獲取中文字幕(如果有的話)
zh_subtitles = None
if zh_subtitle_data:
zh_subtitles = get_subtitle_for_lang(zh_subtitle_data, zh_lang)
# 合併字幕(以英文字幕的時間軸為準,匹配中文字幕)
merged_subtitles = []
zh_dict = {}
# 建立中文字幕的時間索引
if zh_subtitles:
for zh_sub in zh_subtitles:
# 使用開始時間作為鍵
key = round(zh_sub['start'], 2)
zh_dict[key] = zh_sub['english'] # 中文字幕的內容在 'english' 欄位
# 合併字幕
for en_sub in en_subtitles:
merged_sub = {
'start': en_sub['start'],
'end': en_sub['end'],
'english': en_sub['english']
}
# 嘗試匹配中文字幕(允許 0.5 秒的時間差)
en_start = round(en_sub['start'], 2)
matched_zh = None
for key in zh_dict:
if abs(key - en_start) < 0.5:
matched_zh = zh_dict[key]
break
merged_sub['chinese'] = matched_zh if matched_zh else ''
merged_subtitles.append(merged_sub)
logger.info(f"[字幕獲取] 字幕合併完成,共 {len(merged_subtitles)} 條,其中 {sum(1 for s in merged_subtitles if s['chinese'])} 條有中文")
# 保存到緩存
subtitle_cache = load_subtitle_cache()
subtitle_cache[video_id] = {
'subtitles': merged_subtitles,
'cached_at': datetime.now().isoformat()
}
save_subtitle_cache(subtitle_cache)
logger.info(f"[字幕緩存] 已保存字幕到緩存,video_id: {video_id}")
return merged_subtitles
except Exception as e:
logger.error(f"Error getting subtitles: {e}", exc_info=True)
return None
def convert_json_to_srt(json_data):
"""將 YouTube JSON 格式字幕轉換為 SRT 格式"""
import json
srt_lines = []
index = 1
# YouTube JSON 格式:{"events": [{"segs": [{"utf8": "text"}], "tStartMs": 1000, "dDurationMs": 2000}, ...]}
if isinstance(json_data, dict) and 'events' in json_data:
events = json_data['events']
elif isinstance(json_data, list):
events = json_data
else:
logger.warning(f"[字幕轉換] 未知的 JSON 格式")
return ""
for event in events:
if 'segs' not in event or 'tStartMs' not in event:
continue
# 提取文字
text_parts = []
for seg in event.get('segs', []):
if 'utf8' in seg:
text_parts.append(seg['utf8'])
if not text_parts:
continue
text = ' '.join(text_parts).strip()
if not text:
continue
# 時間轉換(毫秒轉秒)
start_ms = event['tStartMs']
duration_ms = event.get('dDurationMs', 0)
end_ms = start_ms + duration_ms
start_sec = start_ms / 1000.0
end_sec = end_ms / 1000.0
# 轉換為 SRT 時間格式
start_h = int(start_sec // 3600)
start_m = int((start_sec % 3600) // 60)
start_s = int(start_sec % 60)
start_ms_remainder = int((start_sec % 1) * 1000)
end_h = int(end_sec // 3600)
end_m = int((end_sec % 3600) // 60)
end_s = int(end_sec % 60)
end_ms_remainder = int((end_sec % 1) * 1000)
time_str = f"{start_h:02d}:{start_m:02d}:{start_s:02d},{start_ms_remainder:03d} --> {end_h:02d}:{end_m:02d}:{end_s:02d},{end_ms_remainder:03d}"
srt_lines.append(f"{index}\n{time_str}\n{text}\n")
index += 1
return '\n'.join(srt_lines)
def parse_subtitle_content(content):
"""解析字幕內容(SRT / VTT 格式),並按句子合併"""
raw_subtitles = []
if not content:
return []
# 以空行分段(同時支援 SRT 及 VTT)
blocks = re.split(r'\n\s*\n', content.strip())
def _parse_timestamp(ts: str):
"""解析單一時間戳,支援 H:MM:SS.mmm / MM:SS.mmm / 逗號或句點"""
ts = ts.strip()
if not ts:
return None
# 拆出毫秒
if ',' in ts:
main, ms = ts.split(',', 1)
elif '.' in ts:
main, ms = ts.split('.', 1)
else:
return None
parts = main.split(':')
if len(parts) == 3:
h, m, s = parts
elif len(parts) == 2:
h, m, s = '0', parts[0], parts[1]
else:
return None
try:
h = int(h)
m = int(m)
s = int(s)
ms_digits = re.sub(r'\D', '', ms)[:3]
ms_val = int(ms_digits.ljust(3, '0')) if ms_digits else 0
except ValueError:
return None
return h * 3600 + m * 60 + s + ms_val / 1000.0
def parse_timecode(line: str):
if '-->' not in line:
return None, None
left, right = line.split('-->', 1)
start = _parse_timestamp(left)
end = _parse_timestamp(right)
return start, end
for block in blocks:
# 拆成行並去除前後空白
lines = [line.strip() for line in block.splitlines() if line.strip()]
if not lines:
continue
# 跳過 WebVTT 標頭
if lines[0].upper().startswith('WEBVTT'):
continue
try:
time_line = None
text_lines = []
start_time = None
end_time = None
# 1) SRT:第一行是序號,第二行是時間軸
if re.fullmatch(r'\d+', lines[0]) and len(lines) >= 2:
time_line = lines[1]
text_lines = lines[2:]
start_time, end_time = parse_timecode(time_line)
# 2) VTT:第一行直接是時間軸
else:
start_time, end_time = parse_timecode(lines[0])
if start_time is not None:
time_line = lines[0]
text_lines = lines[1:]
if time_line is None:
time_line = lines[0]
text_lines = lines[1:]
start_time, end_time = parse_timecode(time_line)
if start_time is None or end_time is None:
continue
text = ' '.join(text_lines).strip()
if text:
raw_subtitles.append({
'start': start_time,
'end': end_time,
'english': text
})
except Exception as e:
logger.warning(f"Error parsing subtitle block: {e}")
continue
# 按句子合併字幕
return merge_subtitles_by_sentence(raw_subtitles)
def count_words(text):
"""計算文字中的單字數量"""
if not text:
return 0
# 匹配單字(字母、連字號、撇號)
words = re.findall(r"[a-zA-Z]+(?:[-'][a-zA-Z]+)*", text)
return len(words)
def merge_subtitles_by_sentence(raw_subtitles):
"""將字幕按句子合併(優先以句點斷句,否則不超過15個單字)"""
if not raw_subtitles:
return []
merged = []
current_sentence = {
'text_parts': [],
'start': None,
'end': None
}
MAX_WORDS_PER_SENTENCE = 15
for sub in raw_subtitles:
text = sub['english'].strip()
if not text:
continue
# 初始化當前句子的開始時間
if current_sentence['start'] is None:
current_sentence['start'] = sub['start']
# 添加文字到當前句子
current_sentence['text_parts'].append(text)
current_sentence['end'] = sub['end']
# 合併當前累積的文字
current_text = ' '.join(current_sentence['text_parts']).strip()
# 優先檢查是否有句點(. ! ?),在句點處斷句
# 使用正則表達式找到最後一個句點位置(考慮引號後面的標點)
# 匹配句點、問號、驚嘆號,可能在引號後面
sentence_end_pattern = r'[.!?]["\']?\s*'
matches = list(re.finditer(sentence_end_pattern, current_text))
if matches:
# 找到最後一個句點位置
last_match = matches[-1]
end_pos = last_match.end()
# 在句點處分割
sentence_text = current_text[:end_pos].strip()
remaining_text = current_text[end_pos:].strip()
# 保存完整的句子
if sentence_text:
merged.append({
'start': current_sentence['start'],
'end': current_sentence['end'],
'english': sentence_text
})
# 如果有剩餘文字,開始新句子
if remaining_text:
current_sentence = {
'text_parts': [remaining_text],
'start': sub['start'],
'end': sub['end']
}
else:
# 重置當前句子
current_sentence = {
'text_parts': [],
'start': None,
'end': None
}
continue
# 如果沒有句點,檢查是否超過15個單字
word_count = count_words(current_text)
# 如果超過15個單字,先保存當前句子
if word_count > MAX_WORDS_PER_SENTENCE:
# 移除最後添加的文字(因為它會讓句子超過15個單字)
last_text = current_sentence['text_parts'].pop()
last_end = current_sentence['end']
sentence_text = ' '.join(current_sentence['text_parts']).strip()
if sentence_text:
merged.append({
'start': current_sentence['start'],
'end': sub['start'], # 使用下一個字幕的開始時間作為結束時間
'english': sentence_text
})
# 開始新句子(使用剛才移除的文字)
current_sentence = {
'text_parts': [last_text],
'start': sub['start'],
'end': last_end
}
# 處理最後一個未完成的句子
if current_sentence['text_parts']:
sentence_text = ' '.join(current_sentence['text_parts']).strip()
if sentence_text:
merged.append({
'start': current_sentence['start'],
'end': current_sentence['end'],
'english': sentence_text
})
logger.info(f"[字幕處理] 原始字幕: {len(raw_subtitles)} 條,合併後: {len(merged)} 條句子")
return merged
def translate_subtitles(subtitles, progress_key=None, update_callback=None):
"""翻譯字幕為中文,支持進度追蹤和實時更新"""
start_time = time.time()
logger.info(f"[翻譯] 開始翻譯 {len(subtitles)} 條字幕")
# 確保翻譯緩存已載入
load_translation_cache()
translator = GoogleTranslator(source='en', target='zh-TW')
translated = []
translated_count = 0
cached_count = 0
needs_save = False
for i, sub in enumerate(subtitles):
english_text = sub['english']
# 檢查快取(內存和持久化)
if english_text in translation_cache:
chinese_text = translation_cache[english_text]
cached_count += 1
else:
try:
chinese_text = translator.translate(english_text)
translation_cache[english_text] = chinese_text
translated_count += 1
needs_save = True # 標記需要保存
# 每翻譯 10 條顯示進度
if translated_count % 10 == 0:
elapsed = time.time() - start_time
logger.info(f"[翻譯] 進度: {i+1}/{len(subtitles)}, 已翻譯 {translated_count} 條, 快取 {cached_count} 條, 耗時 {elapsed:.2f} 秒")
except Exception as e:
logger.warning(f"[翻譯] 翻譯錯誤 (第 {i+1} 條): {e}")
chinese_text = ''
# 構建翻譯結果
translated_item = {
'start': sub['start'],
'end': sub['end'],
'english': english_text,
'chinese': chinese_text
}
translated.append(translated_item)
# 更新進度
if progress_key:
# 確保進度字典存在
if progress_key not in translation_progress:
translation_progress[progress_key] = {
'current': 0,
'total': len(subtitles),
'translated': 0,
'cached': 0,
'elapsed': 0,
'translated_items': []
}
# 更新進度資訊
translation_progress[progress_key].update({
'current': i + 1,
'total': len(subtitles),
'translated': translated_count,
'cached': cached_count,
'elapsed': time.time() - start_time
})
# 存儲已翻譯的字幕(用於實時更新)
translation_progress[progress_key]['translated_items'].append(translated_item)
# 調用更新回調(用於實時顯示)
if update_callback:
update_callback(i, translated_item)
elapsed = time.time() - start_time
logger.info(f"[翻譯] 翻譯完成: 總共 {len(subtitles)} 條, 新翻譯 {translated_count} 條, 快取 {cached_count} 條, 總耗時 {elapsed:.2f} 秒")
# 如果有新翻譯,保存翻譯緩存
if needs_save:
save_translation_cache()
logger.info(f"[翻譯緩存] 已保存 {translated_count} 條新翻譯到緩存")
# 標記完成
if progress_key:
translation_progress[progress_key]['completed'] = True
return translated
@app.route('/')
def index():
"""首頁"""
return render_template('index.html')
@app.route('/api/subtitles/<video_id>')
def get_subtitles_api(video_id):
"""API:獲取字幕(直接從 YouTube 獲取英文和中文字幕,如果沒有中文則啟動翻譯)"""
start_time = time.time()
try:
logger.info(f"[API] ========== 開始處理字幕請求 ==========")
logger.info(f"[API] video_id: {video_id}")
logger.info(f"[API] 時間: {time.strftime('%Y-%m-%d %H:%M:%S')}")
# 獲取英文字幕和中文字幕
logger.info(f"[API] 開始獲取字幕...")
fetch_start = time.time()
subtitles = get_subtitles(video_id)
fetch_elapsed = time.time() - fetch_start
logger.info(f"[API] 獲取字幕完成,耗時 {fetch_elapsed:.2f} 秒")
if not subtitles:
logger.warning(f"[API] 無法獲取字幕,video_id: {video_id}")
return jsonify({
'error': '無法獲取字幕。此影片可能沒有字幕或字幕不可用。'
}), 404
# 檢查是否有中文字幕
has_chinese = sum(1 for s in subtitles if s.get('chinese', ''))
logger.info(f"[API] 字幕統計: 總共 {len(subtitles)} 條,其中 {has_chinese} 條有中文")
# 如果中文字幕少於 10%,啟動翻譯
if has_chinese < len(subtitles) * 0.1:
logger.info(f"[API] 中文字幕不足,啟動翻譯機制...")
progress_key = f"{video_id}_{int(time.time())}"
translation_progress[progress_key] = {
'current': 0,
'total': len(subtitles),
'completed': False,
'translated_items': []
}
# 在背景執行翻譯
def translate_in_background():
def update_callback(index, translated_item):
# 更新原始字幕陣列
if index < len(subtitles):
subtitles[index]['chinese'] = translated_item['chinese']
translated = translate_subtitles(subtitles, progress_key, update_callback)
# 翻譯完成後,更新字幕緩存
subtitle_cache = load_subtitle_cache()
subtitle_cache[video_id] = {
'subtitles': subtitles, # 使用已更新的字幕(包含翻譯)
'cached_at': datetime.now().isoformat()
}
save_subtitle_cache(subtitle_cache)
logger.info(f"[字幕緩存] 翻譯完成後已更新字幕緩存,video_id: {video_id}")
thread = threading.Thread(target=translate_in_background)
thread.daemon = True
thread.start()
return jsonify({
'video_id': video_id,
'subtitles': subtitles,
'needs_translation': True,
'translation_progress_key': progress_key,
'has_chinese': has_chinese,
'total': len(subtitles)
})
else:
total_elapsed = time.time() - start_time
logger.info(f"[API] ========== 處理完成 ==========")
logger.info(f"[API] 總耗時: {total_elapsed:.2f} 秒")
logger.info(f"[API] 返回 {len(subtitles)} 條字幕")
return jsonify({
'video_id': video_id,
'subtitles': subtitles,
'needs_translation': False
})
except Exception as e:
elapsed = time.time() - start_time
logger.error(f"[API] ========== 發生錯誤 ==========")
logger.error(f"[API] 耗時: {elapsed:.2f} 秒")
logger.error(f"[API] 錯誤類型: {type(e).__name__}")
logger.error(f"[API] 錯誤訊息: {str(e)}")
logger.error(f"[API] 錯誤詳情:", exc_info=True)
return jsonify({
'error': f'處理字幕時發生錯誤:{str(e)}'
}), 500
@app.route('/api/translation-progress/<progress_key>')
def get_translation_progress(progress_key):
"""API:獲取翻譯進度和已翻譯的字幕"""
progress = translation_progress.get(progress_key, None)
if progress is None:
return jsonify({'error': '找不到進度資訊'}), 404
# 返回進度和新翻譯的字幕項目
result = {
'current': progress.get('current', 0),
'total': progress.get('total', 0),
'translated': progress.get('translated', 0),
'cached': progress.get('cached', 0),
'elapsed': progress.get('elapsed', 0),
'completed': progress.get('completed', False)
}
# 獲取上次請求後的新翻譯項目
last_index = request.args.get('last_index', 0, type=int)
translated_items = progress.get('translated_items', [])
new_items = translated_items[last_index:] if last_index < len(translated_items) else []
result['new_items'] = new_items
result['last_index'] = len(translated_items)
return jsonify(result)
@app.route('/api/subtitles/<video_id>/update')
def update_subtitles_api(video_id):
"""API:更新字幕(翻譯完成後調用)"""
progress_key = request.args.get('progress_key')
if not progress_key:
return jsonify({'error': '缺少 progress_key 參數'}), 400
progress = translation_progress.get(progress_key)
if not progress or not progress.get('completed'):
return jsonify({'error': '翻譯尚未完成'}), 400
# 重新獲取字幕(此時應該已經翻譯完成)
subtitles = get_subtitles(video_id)
if not subtitles:
return jsonify({'error': '無法獲取字幕'}), 404
return jsonify({
'video_id': video_id,
'subtitles': subtitles,
'needs_translation': False
})
@app.route('/api/word/<path:text>')
def get_word_info(text):
"""API:獲取單字資訊(定義、例句等)"""
import urllib.request
import json as json_lib
try:
logger.info(f"[單字API] 查詢文字: {text}")
# 清理輸入文字
clean_text = text.strip()
if not clean_text:
return jsonify({'error': '文字不能為空'}), 400
# 檢查是否為片語(包含空格)
is_phrase = ' ' in clean_text
# 檢查是否為片語
if is_phrase:
# 作為片語處理(直接翻譯)
try:
translator = GoogleTranslator(source='en', target='zh-TW')
phrase_translation = translator.translate(clean_text)
logger.info(f"[單字API] 片語翻譯成功: {clean_text} -> {phrase_translation}")
result = {
'word': clean_text,
'wordTranslation': phrase_translation,
'phonetic': '',
'meanings': [],
'isPhrase': True
}
logger.info(f"[單字API] 成功處理片語: {clean_text}")
return jsonify(result)
except Exception as e:
logger.warning(f"[單字API] 片語翻譯失敗: {e}")
return jsonify({
'error': '無法獲取此文字的資訊'
}), 404
else:
# 使用 Free Dictionary API(用於單字)
api_url = f'https://api.dictionaryapi.dev/api/v2/entries/en/{clean_text}'
try:
with urllib.request.urlopen(api_url, timeout=10) as response:
data = json_lib.loads(response.read().decode('utf-8'))
if not data or len(data) == 0:
return jsonify({
'error': '找不到此單字的資訊'
}), 404
# 處理第一個結果
entry = data[0]
# 提取音標
phonetic = entry.get('phonetic', '')
if not phonetic and entry.get('phonetics'):
for ph in entry['phonetics']:
if ph.get('text'):
phonetic = ph['text']
break
# 提取詞義和例句
meanings = []
for meaning in entry.get('meanings', []):
part_of_speech = meaning.get('partOfSpeech', '')
definitions = []
for def_item in meaning.get('definitions', [])[:3]: # 最多3個定義
definition_text = def_item.get('definition', '')
example = def_item.get('example', '')
# 翻譯定義為中文
definition_zh = ''
if definition_text:
try:
translator = GoogleTranslator(source='en', target='zh-TW')
definition_zh = translator.translate(definition_text)
logger.info(f"[單字API] 定義翻譯成功: {definition_text[:50]}... -> {definition_zh}")
except Exception as e:
logger.warning(f"[單字API] 翻譯定義失敗: {e}")
definition_zh = '(翻譯失敗,請稍後再試)'
# 翻譯例句為中文(確保所有例句都有翻譯)
example_zh = ''
if example:
try:
translator = GoogleTranslator(source='en', target='zh-TW')
example_zh = translator.translate(example)
logger.info(f"[單字API] 例句翻譯成功: {example} -> {example_zh}")
except Exception as e:
logger.warning(f"[單字API] 翻譯例句失敗: {e}")
# 如果翻譯失敗,至少顯示提示
example_zh = '(翻譯失敗,請稍後再試)'
definitions.append({
'definition': definition_text,