File size: 2,532 Bytes
962b14c
 
 
 
 
 
 
 
 
84f2202
 
 
 
 
 
d83632f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import subprocess
import sys

try:
    import pptx
except ImportError:
    subprocess.check_call([sys.executable, "-m", "pip", "install", "python-pptx"])
    import pptx  # Import the library after installing it

try:
    import openai
except ImportError:
    subprocess.check_call([sys.executable, "-m", "pip", "install", "openai"])
    import openai  # Import the library after installing it

from pptx import Presentation
import openai

def translate_text(text, apikey):
    openai.api_key = apikey
    completion = openai.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": "請把字串「"+text+"」翻譯成為英文,不需要有其他多餘的說明"}]
        )
    return completion.choices[0].message.content

def translate_pptx(file, key):
    prs = Presentation(file.name)
    for slide in prs.slides:
        for shape in slide.shapes:
            if shape.has_text_frame:
                for paragraph in shape.text_frame.paragraphs:
                    original_text = ''.join(run.text for run in paragraph.runs)
                    translated_text = translate_text(original_text, key)
                    for run in paragraph.runs:
                        run.text = translated_text

    # Save the modified presentation to a new file
    output_file_path = "translated_presentation.pptx"
    prs.save(output_file_path)
    return output_file_path

def setup_gradio_interface():
    with gr.Blocks() as demo:
        gr.Markdown("## PowerPoint Translator")
        gr.Markdown("Upload your PowerPoint presentation in Chinese, and download it translated into English.")
        with gr.Row():
            file_input = gr.File(label="Upload PPTX file")
            api_key_input = gr.Textbox(label="Enter OpenAI API Key", placeholder="OpenAI API Key")
            submit_button = gr.Button("Translate")
        file_output = gr.File(label="Download Translated Presentation")

        def translate_and_download(file):
            if file is not None:
                output_path = translate_pptx(file, key)
                return output_path

        submit_button.click(
            translate_and_download,
            inputs=[file_input, api_key_input],
            outputs=file_output
        )

    return demo

# First, try importing gradio. If it fails, attempt to install it.
try:
    import gradio as gr
except ImportError:
    import sys
    import gradio as gr

# Run the interface
if __name__ == "__main__":
    demo = setup_gradio_interface()
    demo.launch()