Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import subprocess
|
| 2 |
+
import sys
|
| 3 |
+
import os
|
| 4 |
+
from pydub import AudioSegment
|
| 5 |
+
try:
|
| 6 |
+
import openai
|
| 7 |
+
except ImportError:
|
| 8 |
+
subprocess.check_call([sys.executable, "-m", "pip", "install", "openai"])
|
| 9 |
+
import openai # Import the library after installing it
|
| 10 |
+
|
| 11 |
+
import gradio as gr
|
| 12 |
+
|
| 13 |
+
def setup_gradio_interface():
|
| 14 |
+
with gr.Blocks() as demo:
|
| 15 |
+
# 大標題:透過 HTML 實現置中與加大
|
| 16 |
+
gr.Markdown(
|
| 17 |
+
"""
|
| 18 |
+
<h1 style="text-align: center; font-size: 36px; color: #333;">萬國語言翻譯機</h1>
|
| 19 |
+
""",
|
| 20 |
+
elem_id="title"
|
| 21 |
+
)
|
| 22 |
+
api_key_input = gr.Textbox(label="第一步:請輸入OpenAI API金鑰", placeholder="OpenAI API Key")
|
| 23 |
+
txt_input = gr.Textbox(label="第二步:請輸入原文")
|
| 24 |
+
drop_input = gr.Dropdown(
|
| 25 |
+
label="第三步:選擇語系",
|
| 26 |
+
choices=["English", "Chinese", "French", "Spanish", "Japanese", "German"],
|
| 27 |
+
value="English" # 預設值
|
| 28 |
+
)
|
| 29 |
+
submit_button = gr.Button("第四步:開始翻譯")
|
| 30 |
+
txt_output = gr.Textbox(label="第五步:語言翻譯結果")
|
| 31 |
+
|
| 32 |
+
def openai_api(input_text, lang, key):
|
| 33 |
+
openai.api_key = key
|
| 34 |
+
prompt = f"Please translate the following text to {lang}:\n{input_text}"
|
| 35 |
+
completion = openai.chat.completions.create(
|
| 36 |
+
model="gpt-4o",
|
| 37 |
+
messages=[{"role": "user", "content": prompt}]
|
| 38 |
+
)
|
| 39 |
+
return completion.choices[0].message.content
|
| 40 |
+
|
| 41 |
+
submit_button.click(
|
| 42 |
+
openai_api,
|
| 43 |
+
inputs=[txt_input, drop_input, api_key_input],
|
| 44 |
+
outputs=[txt_output]
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
return demo
|
| 48 |
+
|
| 49 |
+
# Run the interface
|
| 50 |
+
if __name__ == "__main__":
|
| 51 |
+
demo = setup_gradio_interface()
|
| 52 |
+
demo.launch()
|