hlyangster commited on
Commit
6dcee9d
·
verified ·
1 Parent(s): afbf047

Update core.py

Browse files
Files changed (1) hide show
  1. core.py +131 -40
core.py CHANGED
@@ -16,18 +16,54 @@ def parse_srt(srt_path):
16
  print(f"解析字幕檔案錯誤: {e}")
17
  return None
18
 
19
- # 預處理逐字稿
20
  def preprocess_transcript(transcript):
21
- # 移除 SSML 標籤
22
  transcript = re.sub(r'<[^>]*?>', '', transcript)
 
23
  # 移除多個連續空格
24
  transcript = re.sub(r'\s+', ' ', transcript)
25
- # 移除所有換行符號
26
- transcript = transcript.replace('\n','')
 
 
27
  # 移除文字前後的空白
28
  transcript = transcript.strip()
29
  return transcript
30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  def process_files(api_key, test_transcript_file, test_srt_file, batch_size):
32
  # 1. 配置 Gemini API
33
  try:
@@ -48,67 +84,122 @@ def process_files(api_key, test_transcript_file, test_srt_file, batch_size):
48
  if not os.path.exists(test_srt_file):
49
  return f"錯誤: 找不到口語稿檔案: {test_srt_file},請確認您已上傳該檔案", None, None
50
  else:
51
- srt_data = parse_srt(test_srt_file)
52
- if srt_data is None:
53
  return "錯誤: 解析口語稿檔案失敗,請確認檔案內容", None, None
54
 
 
 
 
55
  # 儲存所有報告
56
  all_reports = []
57
  keys = list(srt_data.keys()) # 取得編號
58
 
 
 
 
59
  # 處理每個批次
60
- for i in range(0, len(keys), batch_size):
61
- batch_keys = keys[i:i + batch_size]
62
- batch_data = {key: srt_data[key] for key in batch_keys} # 取得該批次的資料
63
- subtitle_content = "\n".join([f"編號{index}:{data['text']}" for index, data in batch_data.items()])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  prompt = (
65
- "請扮演一位專業的文字編輯,比對以下字幕檔和逐字稿,並以逐字稿的內容為準,修正字幕檔中因語音轉文字造成的錯別字、漏字、多字、詞語誤用等問題,請勿修改語氣和修辭,必須嚴格保持原始字幕的時間戳和斷句結構,不要拆分或合併任何段落,不要新增或移除任何字幕段落,直接輸出修正後的字幕檔。\n"
66
- "接著,請將**當前批次**所有修改的內容整理成一個修改清單,並放在所有字幕內容之後。\n"
67
- "請使用以下格式輸出修改清單: \n"
68
- "編號: 原文: 修正後\n"
69
- "請使用 `<<<分隔符號>>>` 來分隔字幕與修改清單。\n"
70
- "請按照以下步驟進行:\n"
71
- "1. 比對字幕檔和逐字稿。\n"
72
- "2. 以逐字稿���內容為準,修正字幕檔中因語音轉文字造成的錯別字、漏字、多字和詞語誤用、以及標點符號漏缺等問題。\n"
73
- "3. 必須嚴格保持原始字幕的時間戳和斷句結構,不要拆分或合併任何段落,不要新增或移除任何字幕段落,直接輸出修正後的字幕檔。\n"
74
- "4. 讀取整份逐字稿時,請忽略SSML標籤,直接比對文字與標點符號,請勿修改任何語義。\n"
75
- "字幕檔內容:\n"
76
- f"{subtitle_content}\n\n"
77
- "逐字稿內容:\n"
78
- f"{transcript_content}\n\n"
79
- )
 
 
 
 
 
 
 
 
 
 
80
  try:
81
  response = model.generate_content(prompt)
82
  corrected_subtitle = response.text
83
- print(f"第 {i // batch_size + 1} 批次 Gemini 模型的回應:")
84
  print(corrected_subtitle)
85
 
86
  # 使用 re.split 分割字幕和報告
87
  parts = re.split(r'<<<分隔符號>>>', corrected_subtitle, maxsplit=1) # 只分割一次
88
- corrected_lines = parts[0].split('\n') # 取得字幕文字
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  report = ""
90
  if len(parts) > 1:
91
  report = parts[1] # 取得修改清單文字
92
  report_lines = report.strip().split('\n')
93
  all_reports.extend(report_lines)
94
 
95
- for line in corrected_lines:
96
- match = re.match(r'編號(\d+):(.*)', line)
97
- if match:
98
- index = int(match.group(1))
99
- corrected_text = match.group(2).strip()
100
- srt_data[index]['text'] = corrected_text
101
  except Exception as e:
102
- return f"第 {i // batch_size + 1} 批次修正過程失敗:{e}", None, None
 
 
 
 
 
103
 
104
  # 寫回 SRT 檔案
105
  new_subs = []
106
- for index, data in srt_data.items():
107
- time_str = data['time']
108
- start_str, end_str = time_str.split(" --> ")
109
- start = pysrt.srtitem.SubRipTime.from_string(start_str)
110
- end = pysrt.srtitem.SubRipTime.from_string(end_str)
111
- new_subs.append(pysrt.SubRipItem(index=index, start=start, end=end, text=data['text']))
112
 
113
  # 將 new_subs 轉換為 SubRipFile 物件
114
  new_srt = pysrt.SubRipFile(items=new_subs)
 
16
  print(f"解析字幕檔案錯誤: {e}")
17
  return None
18
 
19
+ # 改進的預處理逐字稿函數
20
  def preprocess_transcript(transcript):
21
+ # 移除 SSML 標籤
22
  transcript = re.sub(r'<[^>]*?>', '', transcript)
23
+
24
  # 移除多個連續空格
25
  transcript = re.sub(r'\s+', ' ', transcript)
26
+
27
+ # 將連續多個換行替換為單個分隔符(而不是完全移除)
28
+ transcript = re.sub(r'\n+', ' | ', transcript)
29
+
30
  # 移除文字前後的空白
31
  transcript = transcript.strip()
32
  return transcript
33
 
34
+ # 驗證SRT結構
35
+ def validate_srt(original_srt, modified_srt):
36
+ """
37
+ 驗證修改後的SRT是否保留了原始SRT的基本結構
38
+
39
+ Args:
40
+ original_srt: 原始SRT數據
41
+ modified_srt: 修改後的SRT數據
42
+
43
+ Returns:
44
+ (bool, str): (是否有效, 錯誤信息)
45
+ """
46
+ # 檢查編號完整性
47
+ if set(original_srt.keys()) != set(modified_srt.keys()):
48
+ missing = set(original_srt.keys()) - set(modified_srt.keys())
49
+ extra = set(modified_srt.keys()) - set(original_srt.keys())
50
+ return False, f"編號不匹配: 缺少 {missing}, 多出 {extra}"
51
+
52
+ # 檢查時間戳保持不變
53
+ for idx in original_srt:
54
+ if original_srt[idx]['time'] != modified_srt[idx]['time']:
55
+ return False, f"編號 {idx} 的時間戳被修改"
56
+
57
+ # 檢查文字長度變化不太大(防止大規模刪減或添加)
58
+ for idx in original_srt:
59
+ orig_len = len(original_srt[idx]['text'])
60
+ mod_len = len(modified_srt[idx]['text'])
61
+ # 允許30%的文字長度變化
62
+ if abs(orig_len - mod_len) / max(1, orig_len) > 0.3:
63
+ return False, f"編號 {idx} 的文字長度變化過大: 原 {orig_len}, 現 {mod_len}"
64
+
65
+ return True, "驗證通過"
66
+
67
  def process_files(api_key, test_transcript_file, test_srt_file, batch_size):
68
  # 1. 配置 Gemini API
69
  try:
 
84
  if not os.path.exists(test_srt_file):
85
  return f"錯誤: 找不到口語稿檔案: {test_srt_file},請確認您已上傳該檔案", None, None
86
  else:
87
+ original_srt_data = parse_srt(test_srt_file)
88
+ if original_srt_data is None:
89
  return "錯誤: 解析口語稿檔案失敗,請確認檔案內容", None, None
90
 
91
+ # 創建工作副本
92
+ srt_data = original_srt_data.copy()
93
+
94
  # 儲存所有報告
95
  all_reports = []
96
  keys = list(srt_data.keys()) # 取得編號
97
 
98
+ # 使用重疊批次而非固定批次
99
+ overlap = max(2, batch_size // 4) # 25% 的重疊
100
+
101
  # 處理每個批次
102
+ for i in range(0, len(keys), batch_size - overlap):
103
+ end_idx = min(i + batch_size, len(keys))
104
+ batch_keys = keys[i:end_idx]
105
+
106
+ # 確保前一批次的最後部分有重疊
107
+ context_start = max(0, i - overlap)
108
+ context_keys = keys[context_start:i] if i > 0 else []
109
+
110
+ # 準備本批次處理的數據
111
+ batch_with_context = context_keys + batch_keys
112
+ context_batch_data = {key: srt_data[key] for key in batch_with_context}
113
+
114
+ # 在提示中標記哪些是實際需要處理的部分(非上下文)
115
+ subtitle_lines = []
116
+ for key in batch_with_context:
117
+ prefix = "處理→ " if key in batch_keys else "上下文: "
118
+ subtitle_lines.append(f"{prefix}編號{key}:{context_batch_data[key]['text']}")
119
+
120
+ subtitle_content = "\n".join(subtitle_lines)
121
+
122
  prompt = (
123
+ "請扮演一位專業的文字編輯,比對以下字幕檔和逐字稿,並以逐字稿的內容為準,修正字幕檔中因語音轉文字造成的錯別字、漏字、多字、詞語誤用等問題,請勿修改語氣和修辭。\n"
124
+
125
+ "【重要規則】:\n"
126
+ "1. 只修正標記有「處理→」的字幕行,標記為「上下文:」的行僅供參考\n"
127
+ "2. 必須嚴格保持原始字幕的時間戳和斷句結構\n"
128
+ "3. 不允許合併任何字幕行,每個編號必須獨立輸出\n"
129
+ "4. 不允許拆分任何字幕行\n"
130
+ "5. 不要新增或移除任何字幕段落\n"
131
+ "6. 即使對於很長的字幕行,也必須完整處理,不能忽略任何部分\n"
132
+ "7. 逐字稿中的 '|' 符號代表可能的段落分隔,請參考但不必完全依照\n"
133
+
134
+ "請使用以下格式輸出每個字幕行:\n"
135
+ "編號X:修正後的文字\n"
136
+
137
+ "接著,請將**當前批次**所有修改的內容整理成一個修改清單,並放在所有字幕內容之後。\n"
138
+ "請使用以下格式輸出修改清單: \n"
139
+ "編號: 原文: 修正後\n"
140
+ "請使用 `<<<分隔符號>>>` 來分隔字幕與修改清單。\n"
141
+
142
+ "字幕檔內容:\n"
143
+ f"{subtitle_content}\n\n"
144
+ "逐字稿內容:\n"
145
+ f"{transcript_content}\n\n"
146
+ )
147
+
148
  try:
149
  response = model.generate_content(prompt)
150
  corrected_subtitle = response.text
151
+ print(f"第 {i // (batch_size - overlap) + 1} 批次 Gemini 模型的回應:")
152
  print(corrected_subtitle)
153
 
154
  # 使用 re.split 分割字幕和報告
155
  parts = re.split(r'<<<分隔符號>>>', corrected_subtitle, maxsplit=1) # 只分割一次
156
+
157
+ # 改進的字幕解析方法
158
+ corrected_lines = parts[0].strip().split('\n')
159
+
160
+ # 建立一個映射表來追踪已處理的編號
161
+ processed_indices = set()
162
+
163
+ for line in corrected_lines:
164
+ # 確保只處理「處理→」標記的編號字幕行
165
+ match = re.match(r'(?:處理→ )?編號(\d+):(.*)', line)
166
+ if match:
167
+ index = int(match.group(1))
168
+ corrected_text = match.group(2).strip()
169
+
170
+ # 確保此編號在當前批次中且需要處理
171
+ if index in batch_keys:
172
+ srt_data[index]['text'] = corrected_text
173
+ processed_indices.add(index)
174
+
175
+ # 檢查是否所有批次中的編號都被處理了
176
+ for index in batch_keys:
177
+ if index not in processed_indices:
178
+ print(f"警告:編號 {index} 在AI處理後丟失,保持原始字幕內容")
179
+
180
+ # 處理報告部分
181
  report = ""
182
  if len(parts) > 1:
183
  report = parts[1] # 取得修改清單文字
184
  report_lines = report.strip().split('\n')
185
  all_reports.extend(report_lines)
186
 
 
 
 
 
 
 
187
  except Exception as e:
188
+ return f"第 {i // (batch_size - overlap) + 1} 批次修正過程失敗:{e}", None, None
189
+
190
+ # 驗證修改後的SRT結構
191
+ is_valid, error_msg = validate_srt(original_srt_data, srt_data)
192
+ if not is_valid:
193
+ return f"SRT結構驗證失敗: {error_msg}", None, None
194
 
195
  # 寫回 SRT 檔案
196
  new_subs = []
197
+ for index, data in sorted(srt_data.items()): # 確保按編號順序排序
198
+ time_str = data['time']
199
+ start_str, end_str = time_str.split(" --> ")
200
+ start = pysrt.srtitem.SubRipTime.from_string(start_str)
201
+ end = pysrt.srtitem.SubRipTime.from_string(end_str)
202
+ new_subs.append(pysrt.SubRipItem(index=index, start=start, end=end, text=data['text']))
203
 
204
  # 將 new_subs 轉換為 SubRipFile 物件
205
  new_srt = pysrt.SubRipFile(items=new_subs)