File size: 1,861 Bytes
8bf184a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import subprocess
import sys
import os
from pydub import AudioSegment
try:
    import openai
except ImportError:
    subprocess.check_call([sys.executable, "-m", "pip", "install", "openai"])
    import openai  # Import the library after installing it

import gradio as gr

def setup_gradio_interface():
    with gr.Blocks() as demo:
        # 大標題:透過 HTML 實現置中與加大
          gr.Markdown(
                  """
                  <h1 style="text-align: center; font-size: 36px; color: #333;">萬國語言翻譯機</h1>
                  """,
                  elem_id="title"
          )
          api_key_input = gr.Textbox(label="第一步:請輸入OpenAI API金鑰", placeholder="OpenAI API Key")
          txt_input = gr.Textbox(label="第二步:請輸入原文")
          drop_input = gr.Dropdown(
                label="第三步:選擇語系",
                choices=["English", "Chinese", "French", "Spanish", "Japanese", "German"],
                value="English"  # 預設值
          )
          submit_button = gr.Button("第四步:開始翻譯")
          txt_output = gr.Textbox(label="第五步:語言翻譯結果")

          def openai_api(input_text, lang, key):
             openai.api_key = key
             prompt = f"Please translate the following text to {lang}:\n{input_text}"
             completion = openai.chat.completions.create(
                model="gpt-4o",
                messages=[{"role": "user", "content": prompt}]
                )
             return completion.choices[0].message.content

          submit_button.click(
                  openai_api,
                  inputs=[txt_input, drop_input, api_key_input],
                  outputs=[txt_output]
          )

    return demo

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