hlyangster commited on
Commit
84c7e84
·
verified ·
1 Parent(s): 6c50ec3

Update app.py

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