John Liao
Update app.py
84f2202 verified
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()