import gradio as gr import srt import re # 處理並預覽 b.srt 和 c.txt 檔案,同時生成 a.txt 檔案 def process_and_preview_files(b_srt_file, c_txt_file): try: # 讀取 b.srt 檔案內容 with open(b_srt_file.name, 'r', encoding='utf-8') as f: b_srt_content = f.read() # 讀取 c.txt 檔案內容 with open(c_txt_file.name, 'r', encoding='utf-8') as f: c_txt_content = f.read() # 解析 b.srt 檔案 srt_entries = list(srt.parse(b_srt_content)) # 解析 c.txt 檔案 txt_entries = [] lines = c_txt_content.split("\n") current_speaker = None for line in lines: # 判斷是否是新的講者 if re.match(r'^[^\[]+', line): current_speaker = line.strip() # 匹配對話內容 match = re.match(r'(\[\d{2}:\d{2}\]) (.+)', line) if match and current_speaker: time_str, dialogue = match.groups() txt_entries.append((current_speaker, time_str.strip('[]'), dialogue)) # 整理 a.txt 檔案格式 output_lines = [] for index, srt_entry in enumerate(srt_entries): # 解析 timedelta 時間戳,轉換為小時、分鐘、秒 start_seconds = int(srt_entry.start.total_seconds()) end_seconds = int(srt_entry.end.total_seconds()) start_hours = start_seconds // 3600 start_minutes = (start_seconds % 3600) // 60 start_seconds = start_seconds % 60 end_hours = end_seconds // 3600 end_minutes = (end_seconds % 3600) // 60 end_seconds = end_seconds % 60 # 格式化 a.txt 所需的時間 start_time = f"00;{start_hours:02d};{start_minutes:02d};{start_seconds:02d};00" end_time = f"00;{end_hours:02d};{end_minutes:02d};{end_seconds:02d};00" if index < len(txt_entries): speaker, _, dialogue = txt_entries[index] output_lines.append(f"{start_time} - {end_time}") output_lines.append(speaker) output_lines.append(dialogue) output_lines.append("") a_txt_content = "\n".join(output_lines) # 保存 a.txt 檔案 a_txt_file_path = "/tmp/a.txt" with open(a_txt_file_path, 'w', encoding='utf-8') as f: f.write(a_txt_content) # 返回預覽和下載路徑 b_preview = f"預覽 b.srt 檔案內容:\n\n{b_srt_content[:500]}...\n\n" c_preview = f"預覽 c.txt 檔案內容:\n\n{c_txt_content[:500]}...\n\n" a_preview = f"預覽 a.txt 檔案內容:\n\n{a_txt_content[:500]}...\n\n" return b_preview, c_preview, a_preview, a_txt_file_path except Exception as e: return f"Error reading files: {str(e)}", f"Error reading files: {str(e)}", f"Error reading files: {str(e)}", None # 建立 Gradio 介面 interface = gr.Interface( fn=process_and_preview_files, inputs=[gr.File(label="上傳 srt 檔案"), gr.File(label="上傳 Goodtape含Speaker txt 檔案")], outputs=[ gr.Textbox(label="srt 檔案預覽"), gr.Textbox(label="txt 檔案預覽"), gr.Textbox(label="合併 txt 檔案預覽"), gr.File(label="下載 合併txt 檔案") ], title="SRT 和 TXT 檔案合併工具", description="上傳 srt 檔案t 和 Goodtape含Speaker txt 檔案,將它們整理成 Premiere 的 txt 格式並提供下載,同時可以預覽檔案的內容。" ) # 運行介面 interface.launch()