Jiangxz commited on
Commit
06047fb
·
verified ·
1 Parent(s): 939d22a

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +311 -0
  2. requirements.txt +4 -0
app.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # 財政部財政資訊中心 江信宗
3
+
4
+ import gradio as gr
5
+ import tempfile
6
+ import subprocess
7
+ from groq import Groq
8
+ from zhconv_rs import zhconv
9
+ from datetime import timedelta
10
+ import os
11
+ from pathlib import Path
12
+
13
+ def check_ffmpeg():
14
+ try:
15
+ subprocess.run(["ffmpeg", "-version"], check=True, capture_output=True, text=True)
16
+ print("FFmpeg is installed and working.")
17
+ except subprocess.CalledProcessError:
18
+ print("Error: FFmpeg is not installed or not working properly.")
19
+ except FileNotFoundError:
20
+ print("Error: FFmpeg is not installed or not in the system PATH.")
21
+
22
+ def format_time(seconds):
23
+ td = timedelta(seconds=seconds)
24
+ hours, remainder = divmod(td.seconds, 3600)
25
+ minutes, seconds = divmod(remainder, 60)
26
+ milliseconds = round(td.microseconds / 1000)
27
+ return f"{hours:02d}:{minutes:02d}:{seconds:02d},{milliseconds:03d}"
28
+
29
+ def json_to_srt(segments):
30
+ srt_lines = []
31
+ for i, item in enumerate(segments, 1):
32
+ start_time = format_time(item['start'])
33
+ end_time = format_time(item['end'])
34
+ text = zhconv(item['text'], "zh-tw")
35
+ srt_lines.append(f"{i}\n{start_time} --> {end_time}\n{text}\n")
36
+ return "\n".join(srt_lines)
37
+
38
+ def validate_and_convert(file, Language, api_key):
39
+ gr.Info("檔案上傳完成,開始轉換......")
40
+ try:
41
+ if not api_key:
42
+ os.remove(file.name)
43
+ gr.Warning("請輸入正確的 API Key!!")
44
+ return f"請輸入正確的 API Key!!"
45
+ if api_key == os.getenv("SPACE_ID"):
46
+ api_key = os.getenv("YOUR_API_KEY")
47
+ except Exception as e:
48
+ gr.Warning("請輸入正確的 API Key!!")
49
+ return f"請輸入正確的 API Key!!"
50
+ MAX_FILE_SIZE = 200 * 1024 * 1024 # 200MB
51
+ ALLOWED_EXTENSIONS = ['mp3', 'mp4', 'mpeg', 'm4a', 'wav', 'ogg', 'flac', 'webm', 'mpga']
52
+ if file is None:
53
+ return None, None, "沒有選擇文件", None, None
54
+ try:
55
+ file_path = Path(file.name)
56
+ if not file_path.exists():
57
+ return None, None, f"找不到上傳的檔案:{file.name}", None, None
58
+ file_extension = file_path.suffix[1:].lower()
59
+ if file_extension not in ALLOWED_EXTENSIONS:
60
+ return None, None, f"不支援的檔案類型!請上傳以下格式之一的檔案:{', '.join(ALLOWED_EXTENSIONS)}", None, None
61
+ file_size = file_path.stat().st_size
62
+ if file_size > MAX_FILE_SIZE:
63
+ return None, None, "檔案已超過200MB限制,請上傳較小的檔案。", None, None
64
+ show_info = file_size > 50 * 1024 * 1024
65
+ return convert_to_mp3(file, Language, api_key, show_info)
66
+ except Exception as e:
67
+ return None, None, f"檔案處理錯誤:{str(e)}", None, None
68
+
69
+ def convert_to_mp3(file, Language, api_key, show_info):
70
+ temp_dir = tempfile.gettempdir()
71
+ input_path = file.name
72
+ output_path = os.path.join(temp_dir, "output.mp3")
73
+ command = f"ffmpeg -i \"{input_path}\" -acodec libmp3lame -b:a 48k -y \"{output_path}\""
74
+ try:
75
+ if show_info:
76
+ gr.Info("開始轉換為音檔,請稍候......")
77
+ result = subprocess.run(command, shell=True, check=True, capture_output=True, text=True)
78
+ if os.path.exists(output_path):
79
+ file_size = os.path.getsize(output_path)
80
+ if file_size > 25 * 1024 * 1024:
81
+ return None, None, "轉譯限制:MP3檔案大小不得超過25MB!", None, None
82
+ if file_size > 5 * 1024 * 1024:
83
+ show_info = True
84
+ size_info = f"MP3 檔案大小: {file_size / 1024:.2f} KB"
85
+ transcription, transcription_text = transcribe_audio(output_path, Language, api_key, show_info)
86
+ if isinstance(transcription, list):
87
+ if show_info:
88
+ gr.Info("開始產製SRT字幕檔......")
89
+ srt_content = json_to_srt(transcription)
90
+ srt_file = create_srt_file(srt_content)
91
+ return file, output_path, size_info, transcription_text, srt_file
92
+ else:
93
+ return file, output_path, size_info, transcription, None
94
+ else:
95
+ return None, None, "轉換失敗:輸出文件不存在", None, None
96
+ except subprocess.CalledProcessError as e:
97
+ error_message = f"轉換失敗:{str(e)}"
98
+ return None, None, error_message, None, None
99
+
100
+ def summarize_article(trans_text, api_key):
101
+ try:
102
+ if not api_key:
103
+ api_key = os.getenv("YOUR_API_KEY")
104
+ client = Groq(api_key=api_key)
105
+ response = client.chat.completions.create(
106
+ model="llama-3.1-70b-versatile",
107
+ messages=[
108
+ {"role": "system", "content": """
109
+ 你是一個精通繁體中文和臺灣用語的中文編輯。
110
+ 使用者會提供給你一段逐字稿,請協助我檢查錯字、修正標點符號的使用,盡可能保持原意不變、保留內容細節(例如故事、提到的數字和案例)的情況下,提供優化中文排版後所有的逐字稿內容。
111
+
112
+ ## 限制
113
+ 提供時請分成數個段落,並替這段落下個合適的標題,並依照以下限制輸出。而且無論如何,都要提供所有的逐字稿內容,請不要擅自刪減或總結成段落!
114
+
115
+ ### 中文錯字修正範例
116
+ 1. 「罰還」改成「罰緩」
117
+ 2. 「巧巧」改成「悄悄」
118
+ 3. 「辯試」改成「辨識」
119
+ 4. 「規護」改成「歸戶」
120
+ 5. 「披頭」改成「劈頭」
121
+ 6. 「查器」改成「查緝」
122
+
123
+ ### 中文排版&標點符號的使用原則
124
+ 1. 一律使用全形符號,例如用「」做引號,而不是 “”;用 "," 做為逗號,而不是 ","。
125
+ 2. 省略號是……(兩個英文省略號),不是。。。,也不是......(六個點)
126
+ 3. 中文與英文或數字之間需要增加半形空格。正確用法:「Apple 課程人數已經超過 2000 人了。」;錯誤用法:「Apple課程人數已經超過2000人了。」
127
+ 4. 遇到完整的英文整句、特殊名詞,其內容使用半形標點。正確用法:「賈伯斯說過:"Stay hungry, stay foolish."」;錯誤用法:「賈伯斯說過:"Stay hungry,stay foolish。”」
128
+ 5. 一律在中英文之間增加空格
129
+ 6. 在中文與數字之間增加空格
130
+ 7. 在數字與單位之間增加空格
131
+ 8. 全形標點與其他字符之間不加空格。
132
+
133
+ ### 其他限制
134
+ - 請注意,直接輸出結果給我,不需要有開頭招呼。
135
+ - 無論如何,都要提供所有的逐字稿內容,請不要擅自刪減或總結成段落!
136
+
137
+ ## 輸出格式
138
+ **{總結後的段落重點}**
139
+
140
+ {文字段落內容}
141
+
142
+ **{總結後的段落重點}**
143
+
144
+ {文字段落內容}
145
+ """},
146
+ {"role": "user", "content": trans_text}
147
+ ],
148
+ temperature=0.2
149
+ )
150
+ return response.choices[0].message.content
151
+ except Exception as e:
152
+ return f"總結失敗:{str(e)}"
153
+
154
+ def transcribe_audio(filename, Language, api_key, show_info):
155
+ try:
156
+ if not api_key:
157
+ api_key = os.getenv("YOUR_API_KEY")
158
+ if show_info:
159
+ gr.Info("開始轉譯,請稍候......")
160
+ client = Groq(api_key=api_key)
161
+ language_dict = {"繁體中文": "zh", "English": "en", "German": "de", "Spanish": "es", "Russian": "ru", "Korean": "ko", "French": "fr", "Japanese": "ja", "Portuguese": "pt", "Turkish": "tr", "Polish": "pl", "Catalan": "ca", "Dutch": "nl", "Arabic": "ar", "Swedish": "sv", "Italian": "it", "Indonesian": "id", "Hindi": "hi", "Finnish": "fi", "Vietnamese": "vi", "Hebrew": "he", "Ukrainian": "uk", "Greek": "el", "Malay": "ms", "Czech": "cs", "Romanian": "ro", "Danish": "da", "Hungarian": "hu", "Tamil": "ta", "Norwegian": "no", "Thai": "th", "Urdu": "ur", "Croatian": "hr", "Bulgarian": "bg", "Lithuanian": "lt", "Latin": "la", "Maori": "mi", "Malayalam": "ml", "Welsh": "cy", "Slovak": "sk", "Telugu": "te", "Persian": "fa", "Latvian": "lv", "Bengali": "bn", "Serbian": "sr", "Azerbaijani": "az", "Slovenian": "sl", "Kannada": "kn", "Estonian": "et", "Macedonian": "mk", "Breton": "br", "Basque": "eu", "Icelandic": "is", "Armenian": "hy", "Nepali": "ne", "Mongolian": "mn", "Bosnian": "bs", "Kazakh": "kk", "Albanian": "sq", "Swahili": "sw", "Galician": "gl", "Marathi": "mr", "Punjabi": "pa", "Sinhala": "si", "Khmer": "km", "Shona": "sn", "Yoruba": "yo", "Somali": "so", "Afrikaans": "af", "Occitan": "oc", "Georgian": "ka", "Belarusian": "be", "Tajik": "tg", "Sindhi": "sd", "Gujarati": "gu", "Amharic": "am", "Yiddish": "yi", "Lao": "lo", "Uzbek": "uz", "Faroese": "fo", "Haitian creole": "ht", "Pashto": "ps", "Turkmen": "tk", "Nynorsk": "nn", "Maltese": "mt", "Sanskrit": "sa", "Luxembourgish": "lb", "Myanmar": "my", "Tibetan": "bo", "Tagalog": "tl", "Malagasy": "mg", "Assamese": "as", "Tatar": "tt", "Hawaiian": "haw", "Lingala": "ln", "Hausa": "ha", "Bashkir": "ba", "Javanese": "jw", "Sundanese": "su"}
162
+ selected_language = language_dict.get(Language)
163
+ selected_model = "distil-whisper-large-v3-en" if Language == "English" else "whisper-large-v3"
164
+ with open(filename, "rb") as file:
165
+ transcription = client.audio.transcriptions.create(
166
+ file=(filename, file.read()),
167
+ model=selected_model,
168
+ response_format="verbose_json",
169
+ language=selected_language,
170
+ temperature=0.0
171
+ )
172
+ if Language == "English":
173
+ summary = transcription.text
174
+ else:
175
+ full_text = zhconv(transcription.text, "zh-tw")
176
+ if show_info:
177
+ chunks = [full_text[i:i+1000] for i in range(0, len(full_text), 1000)]
178
+ summaries = []
179
+ for i, chunk in enumerate(chunks):
180
+ gr.Info(f"正在處理第 {i+1}/{len(chunks)} 部分...")
181
+ chunk_summary = summarize_article(chunk, api_key)
182
+ summaries.append(chunk_summary.strip())
183
+ summary = "\n\n".join(summaries)
184
+ else:
185
+ summary = summarize_article(full_text, api_key)
186
+ return transcription.segments, summary.strip()
187
+ except Exception as e:
188
+ return f"轉譯失敗:{str(e)}"
189
+
190
+ def create_srt_file(srt_content):
191
+ with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".srt", encoding="utf-8") as temp_file:
192
+ temp_file.write(srt_content)
193
+ return temp_file.name
194
+
195
+ def clear_inputs():
196
+ return None, None, None, None, None
197
+
198
+ custom_css = """
199
+ .center-aligned {
200
+ text-align: center !important;
201
+ color: #ff4081;
202
+ text-shadow: 2px 2px 4px rgba(0,0,0,0.1);
203
+ margin-bottom: 0 !important;
204
+ }
205
+ .gr-input, .gr-box, .gr-dropdown {
206
+ border-radius: 10px !important;
207
+ border: 2px solid #ff4081 !important;
208
+ margin: 0 !important;
209
+ }
210
+ .gr-input:focus, .gr-box:focus, .gr-dropdown:focus {
211
+ border-color: #f50057 !important;
212
+ box-shadow: 0 0 0 2px rgba(245,0,87,0.2) !important;
213
+ }
214
+ .file-background {
215
+ background-color: #B7E0FF !important;
216
+ padding: 15px !important;
217
+ border-radius: 10px !important;
218
+ margin: 0 !important;
219
+ height: auto;
220
+ }
221
+ .api-background {
222
+ background-color: #FFCFB3 !important;
223
+ padding: 15px !important;
224
+ border-radius: 10px !important;
225
+ margin: 0 !important;
226
+ }
227
+ .script-background {
228
+ background-color: #FEF9D9 !important;
229
+ padding: 15px !important;
230
+ border-radius: 10px !important;
231
+ margin: 0 !important;
232
+ }
233
+ .script-background textarea {
234
+ font-size: 18px !important;
235
+ background-color: #ffffff;
236
+ border: 1px solid #f0f8ff;
237
+ border-radius: 8px;
238
+ }
239
+ .srt-background {
240
+ background-color: #FFF4B5 !important;
241
+ padding: 5px !important;
242
+ border-radius: 10px !important;
243
+ margin: 0 !important;
244
+ }
245
+ .text-background {
246
+ padding: 5px !important;
247
+ border-radius: 10px !important;
248
+ border: 2px solid #B7E0FF !important;
249
+ margin: 0 !important;
250
+ }
251
+ .clear-button {
252
+ border-radius: 10px !important;
253
+ background-color: #333333 !important;
254
+ color: white !important;
255
+ font-weight: bold !important;
256
+ transition: all 0.3s ease !important;
257
+ }
258
+ .clear-button:hover {
259
+ background-color: #000000 !important;
260
+ transform: scale(1.05);
261
+ }
262
+ """
263
+
264
+ with gr.Blocks(theme=gr.themes.Monochrome(), css=custom_css) as demo:
265
+ gr.Markdown("""
266
+ # 📝 凊彩歐北寫 - 財政部財政資訊中心 🎵
267
+ > ### **※ 玩轉聲音魅力,開拓更多可能性,自動生成 Note-taking Record,系統布署:江信宗,LLM:<a href="https://huggingface.co/openai/whisper-large-v3" style="color: black;">Whisper large-v3</a>。**<br>依據 <a href="https://www.youtube.com/static?template=terms&hl=zh-Hant" style="color: black;">YouTube 的服務條款(ToS)</a>,請自行明確取得 YouTube 著作權人授權後再上傳影片進行轉譯!
268
+ """, elem_classes="center-aligned")
269
+ with gr.Row():
270
+ file_input = gr.File(
271
+ label="上傳影片或音訊檔",
272
+ file_count="single",
273
+ elem_classes="file-background"
274
+ )
275
+ with gr.Column():
276
+ api_key_input = gr.Textbox(label="輸入您的 API Key", type="password", placeholder="API authentication key", elem_classes="api-background")
277
+ Language = gr.Dropdown(
278
+ choices = ["繁體中文","English","Japanese","Korean","German","French","Spanish","Arabic","Italian","Portuguese","Thai","Vietnamese","Malay","Indonesian","Hindi","Bengali","Russian"],
279
+ value="繁體中文",
280
+ label="媒體檔之音訊語言",
281
+ interactive=True,
282
+ elem_classes="api-background"
283
+ )
284
+ output_audio = gr.Audio(label="轉換後的 MP3", type="filepath", elem_classes="script-background")
285
+ with gr.Row():
286
+ srt_file_output = gr.File(label="下載 SRT 字幕檔", elem_classes="srt-background")
287
+ output_text = gr.Textbox(label="音訊檔案大小", elem_classes="script-background")
288
+ clear_button = gr.Button("清除", elem_classes="clear-button")
289
+ gr.HTML(
290
+ """
291
+ <span style="font-size: 20px; color: black; font-weight:bold;">歡迎將轉譯結果製作為</span><a href="https://huggingface.co/spaces/Jiangxz/Generated_Podcast" style="font-size: 20px; color: red; font-weight:bold;">財資歐北共 Podcast</a><span style="font-size: 20px; color: black;"> ,</span><span style="font-size: 20px; color: black;">而重點總結及RAG知識問答推薦使用 </span><a href="https://notebooklm.google.com" style="font-size: 20px; color: red;">Google NotebookLM</a><span style="font-size: 20px; color: black;"> 更佳。</span>
292
+ """
293
+ )
294
+ transcription_text = gr.Markdown(label="語音轉譯結果", elem_classes="text-background")
295
+ file_input.upload(
296
+ fn=validate_and_convert,
297
+ inputs=[file_input, Language, api_key_input],
298
+ outputs=[file_input, output_audio, output_text, transcription_text, srt_file_output]
299
+ )
300
+ clear_button.click(
301
+ fn=clear_inputs,
302
+ inputs=[],
303
+ outputs=[file_input, output_audio, output_text, transcription_text, srt_file_output]
304
+ )
305
+
306
+ if __name__ == "__main__":
307
+ check_ffmpeg()
308
+ if "SPACE_ID" in os.environ:
309
+ demo.queue().launch()
310
+ else:
311
+ demo.queue().launch(share=True, show_api=False)
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ gradio
2
+ groq
3
+ opencc-python-reimplemented
4
+ zhconv_rs