Tal commited on
Commit
837c1b6
·
1 Parent(s): 453b3b1

initial push

Browse files
Files changed (2) hide show
  1. app.py +67 -0
  2. requirements.txt +4 -0
app.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import srt
3
+ from datetime import timedelta
4
+ import openai
5
+ import os
6
+
7
+ # 配置OpenAI API(用户需要自行添加API密钥)
8
+ openai.api_key = os.getenv('OPENAI_API_KEY')
9
+
10
+ def translate_text(text, target_language):
11
+ client = openai.OpenAI()
12
+ response = client.chat.completions.create(
13
+ model="gpt-4o-mini",
14
+ messages=[
15
+ {"role": "system", "content": f"你是一个专业翻译,请准确将字幕内容翻译成{target_language},保持口语化表达。"},
16
+ {"role": "user", "content": text}
17
+ ]
18
+ )
19
+ return response.choices[0].message.content
20
+
21
+ def process_srt(input_file, target_language):
22
+ with open(input_file.name, 'r', encoding='utf-8') as f:
23
+ subs = list(srt.parse(f.read()))
24
+
25
+ translated_subs = []
26
+ for sub in subs:
27
+ translated_text = translate_text(sub.content, target_language)
28
+ translated_subs.append(srt.Subtitle(
29
+ index=sub.index,
30
+ start=sub.start,
31
+ end=sub.end,
32
+ content=translated_text
33
+ ))
34
+
35
+ return srt.compose(translated_subs)
36
+
37
+ # Gradio界面
38
+ with gr.Blocks() as demo:
39
+ gr.Markdown("## SRT translation")
40
+ with gr.Row():
41
+ input_file = gr.File(label="Upload SRT file", type="filepath")
42
+ target_language = gr.Dropdown(
43
+ choices=["English", "Finnish", "Chinese", "Japanese", "Korean", "German", "French", "Spanish", "Italian", "Arabic", "Russian"],
44
+ label="Chose target language",
45
+ value="Finnish"
46
+ )
47
+ btn = gr.Button("Start Translation", variant="primary", scale=1)
48
+
49
+ with gr.Row():
50
+ preview_text = gr.Textbox(label="Preview", interactive=False)
51
+ output_file = gr.File(label="Download translated file", visible=True)
52
+
53
+ def process_file(file, target_language):
54
+ translated = process_srt(file, target_language)
55
+ output_path = os.path.join(os.getcwd(), "translated.srt")
56
+ with open(output_path, 'w', encoding='utf-8') as f:
57
+ f.write(translated)
58
+ return translated, output_path
59
+
60
+ btn.click(
61
+ fn=process_file,
62
+ inputs=[input_file, target_language],
63
+ outputs=[preview_text, output_file]
64
+ )
65
+
66
+ if __name__ == "__main__":
67
+ demo.launch(server_name="0.0.0.0", server_port=int(os.getenv('PORT', 7860)))
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ gradio>=3.50
2
+ srt>=3.5.0
3
+ openai>=0.28
4
+ python-dotenv>=1.0.0