John Liao commited on
Commit
d83632f
·
verified ·
1 Parent(s): 1922613

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -0
app.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pptx import Presentation
2
+ import openai
3
+
4
+ def translate_text(text, apikey):
5
+ openai.api_key = apikey
6
+ completion = openai.chat.completions.create(
7
+ model="gpt-4o",
8
+ messages=[{"role": "user", "content": "請把字串「"+text+"」翻譯成為英文,不需要有其他多餘的說明"}]
9
+ )
10
+ return completion.choices[0].message.content
11
+
12
+ def translate_pptx(file, key):
13
+ prs = Presentation(file.name)
14
+ for slide in prs.slides:
15
+ for shape in slide.shapes:
16
+ if shape.has_text_frame:
17
+ for paragraph in shape.text_frame.paragraphs:
18
+ original_text = ''.join(run.text for run in paragraph.runs)
19
+ translated_text = translate_text(original_text, key)
20
+ for run in paragraph.runs:
21
+ run.text = translated_text
22
+
23
+ # Save the modified presentation to a new file
24
+ output_file_path = "translated_presentation.pptx"
25
+ prs.save(output_file_path)
26
+ return output_file_path
27
+
28
+ def setup_gradio_interface():
29
+ with gr.Blocks() as demo:
30
+ gr.Markdown("## PowerPoint Translator")
31
+ gr.Markdown("Upload your PowerPoint presentation in Chinese, and download it translated into English.")
32
+ with gr.Row():
33
+ file_input = gr.File(label="Upload PPTX file")
34
+ api_key_input = gr.Textbox(label="Enter OpenAI API Key", placeholder="OpenAI API Key")
35
+ submit_button = gr.Button("Translate")
36
+ file_output = gr.File(label="Download Translated Presentation")
37
+
38
+ def translate_and_download(file):
39
+ if file is not None:
40
+ output_path = translate_pptx(file, key)
41
+ return output_path
42
+
43
+ submit_button.click(
44
+ translate_and_download,
45
+ inputs=[file_input, api_key_input],
46
+ outputs=file_output
47
+ )
48
+
49
+ return demo
50
+
51
+ # First, try importing gradio. If it fails, attempt to install it.
52
+ try:
53
+ import gradio as gr
54
+ except ImportError:
55
+ import sys
56
+ import gradio as gr
57
+
58
+ # Run the interface
59
+ if __name__ == "__main__":
60
+ demo = setup_gradio_interface()
61
+ demo.launch()