hlyangster commited on
Commit
644f14a
·
verified ·
1 Parent(s): 84c7e84

Create core.py

Browse files
Files changed (1) hide show
  1. core.py +120 -0
core.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # core.py
2
+ !pip install pysrt
3
+
4
+ import google.generativeai as genai
5
+ import pysrt
6
+ import re
7
+ import os
8
+ from google.colab import files
9
+
10
+
11
+ # 解析 SRT 檔案
12
+ def parse_srt(srt_path):
13
+ try:
14
+ subs = pysrt.open(srt_path, encoding='utf-8')
15
+ srt_data = {}
16
+ for sub in subs:
17
+ srt_data[sub.index] = {"time": str(sub.start) + " --> " + str(sub.end), "text": sub.text}
18
+ return srt_data
19
+ except Exception as e:
20
+ print(f"解析字幕檔案錯誤: {e}")
21
+ return None
22
+
23
+ # 預處理逐字稿
24
+ def preprocess_transcript(transcript):
25
+ # 移除 SSML 標籤
26
+ transcript = re.sub(r'<[^>]*?>', '', transcript)
27
+ # 移除多個連續空格
28
+ transcript = re.sub(r'\s+', ' ', transcript)
29
+ # 移除所有換行符號
30
+ transcript = transcript.replace('\n','')
31
+ # 移除文字前後的空白
32
+ transcript = transcript.strip()
33
+ return transcript
34
+
35
+ def process_files(api_key, test_transcript_file, test_srt_file, batch_size):
36
+ # 1. 配置 Gemini API
37
+ try:
38
+ genai.configure(api_key=api_key)
39
+ model = genai.GenerativeModel('gemini-1.5-flash') # 測試金鑰是否正確
40
+ except Exception as e:
41
+ return f"API 金鑰錯誤,請檢查設定: {e}", None, None
42
+
43
+ # 檢查測試用逐字稿檔案是否存在
44
+ if not os.path.exists(test_transcript_file):
45
+ return f"錯誤: 找不到逐字稿檔案: {test_transcript_file},請確認您已上傳該檔案", None, None
46
+ else:
47
+ with open(test_transcript_file, 'r', encoding='utf-8') as f:
48
+ transcript_content = f.read()
49
+ transcript_content = preprocess_transcript(transcript_content)
50
+
51
+ # 檢查測試用 srt 檔案是否存在
52
+ if not os.path.exists(test_srt_file):
53
+ return f"錯誤: 找不到口語稿檔案: {test_srt_file},請確認您已上傳該檔案", None, None
54
+ else:
55
+ srt_data = parse_srt(test_srt_file)
56
+ if srt_data is None:
57
+ return "錯誤: 解析口語稿檔案失敗,請確認檔案內容", None, None
58
+
59
+ # 儲存所有報告
60
+ all_reports = []
61
+ keys = list(srt_data.keys()) # 取得編號
62
+
63
+ # 處理每個批次
64
+ for i in range(0, len(keys), batch_size):
65
+ batch_keys = keys[i:i + batch_size]
66
+ batch_data = {key: srt_data[key] for key in batch_keys} # 取得該批次的資料
67
+ subtitle_content = "\n".join([f"編號{index}:{data['text']}" for index, data in batch_data.items()])
68
+ prompt = (
69
+ "請扮演一位專業的文字編輯,比對以下字幕檔和逐字稿,並以逐字稿的內容為準,修正字幕檔中因語音轉文字造成的錯別字、漏字、多字和詞語誤用等問題,請勿修改語氣和修辭,直接輸出修正後的字幕檔。\n"
70
+ "接著,請將**當前批次**所有修改的內容整理成一個修改清單,並放在所有字幕內容之後。\n"
71
+ "請使用以下格式輸出修改清單: \n"
72
+ "編號: 原文: 修正後\n"
73
+ "請使用 `<<<分隔符號>>>` 來分隔字幕與修改清單。\n"
74
+ "請按照以下步驟進行:\n"
75
+ "1. 比對字幕檔和逐字稿。\n"
76
+ "2. 以逐字稿的內容為準,修正字幕檔中因語音轉文字造成的錯別字、漏字、多字和詞語誤用、以及標點符號漏缺等問題。\n"
77
+ "3. 必須嚴格保持原始字幕的時間戳和斷句結構,不要拆分或合併任何段落,不要新增或移除任何字幕段落,直接輸出修正後的字幕檔。\n"
78
+ "4. 讀取整份逐字稿時,請忽略SSML標籤,直接比對文字與標點符號,請勿修改任何語義。\n"
79
+ "字幕檔內容:\n"
80
+ f"{subtitle_content}\n\n"
81
+ "逐字稿內容:\n"
82
+ f"{transcript_content}\n\n"
83
+ )
84
+ try:
85
+ response = model.generate_content(prompt)
86
+ corrected_subtitle = response.text
87
+ print(f"第 {i // batch_size + 1} 批次 Gemini 模型的回應:")
88
+ print(corrected_subtitle)
89
+
90
+ # 使用 re.split 分割字幕和報告
91
+ parts = re.split(r'<<<分隔符號>>>', corrected_subtitle, maxsplit=1) # 只分割一次
92
+ corrected_lines = parts[0].split('\n') # 取得字幕文字
93
+ report = ""
94
+ if len(parts) > 1:
95
+ report = parts[1] # 取得修改清單文字
96
+ report_lines = report.strip().split('\n')
97
+ all_reports.extend(report_lines)
98
+
99
+ for line in corrected_lines:
100
+ match = re.match(r'編號(\d+):(.*)', line)
101
+ if match:
102
+ index = int(match.group(1))
103
+ corrected_text = match.group(2).strip()
104
+ srt_data[index]['text'] = corrected_text
105
+ except Exception as e:
106
+ return f"第 {i // batch_size + 1} 批次修正過程失敗:{e}", None, None
107
+
108
+ # 寫回 SRT 檔案
109
+ new_subs = []
110
+ for index, data in srt_data.items():
111
+ time_str = data['time']
112
+ start_str, end_str = time_str.split(" --> ")
113
+ start = pysrt.srtitem.SubRipTime.from_string(start_str)
114
+ end = pysrt.srtitem.SubRipTime.from_string(end_str)
115
+ new_subs.append(pysrt.SubRipItem(index=index, start=start, end=end, text=data['text']))
116
+
117
+ # 將 new_subs 轉換為 SubRipFile 物件
118
+ new_srt = pysrt.SubRipFile(items=new_subs)
119
+
120
+ return None, new_srt, all_reports