Zoe0122 commited on
Commit
63a5856
·
verified ·
1 Parent(s): a816fb1

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -0
app.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import openai
3
+
4
+ def translate_text(text, target_language, api_key):
5
+ # Step 1: Direct Translation
6
+ prompt1 = f"Translate the following text to {target_language} literally, without omitting any information:\n\n{text}"
7
+ direct_translation = openai_api(prompt1, api_key)
8
+
9
+ # Step 2: Idiomatic Translation
10
+ prompt2 = f"Translate the following text to {target_language} in a more natural and understandable way, while preserving the original meaning:\n\n{direct_translation}"
11
+ idiomatic_translation = openai_api(prompt2, api_key)
12
+
13
+ # Step 3: Comparison and Error Reporting (Simplified)
14
+ prompt3 = f"Compare the following two translations and list any distortions or omissions of the original meaning:\n\nOriginal Text: {text}\n\nDirect Translation: {direct_translation}\n\nIdiomatic Translation: {idiomatic_translation}"
15
+ comparison_result = openai_api(prompt3, api_key)
16
+
17
+ return direct_translation, idiomatic_translation, comparison_result
18
+
19
+
20
+ def openai_api(prompt, key):
21
+ openai.api_key = key
22
+ try:
23
+ completion = openai.chat.completions.create(
24
+ model="gpt-4o", # or gpt-3.5-turbo
25
+ messages=[{"role": "user", "content": prompt}]
26
+ )
27
+ return completion.choices[0].message.content
28
+ except Exception as e:
29
+ return f"An error occurred: {e}"
30
+
31
+
32
+ with gr.Blocks() as demo:
33
+ gr.Markdown("## 萬國翻譯機")
34
+
35
+ with gr.Row():
36
+ text_input = gr.Textbox(label="原文", placeholder="輸入要翻譯的文字")
37
+ target_language = gr.Dropdown(choices=["English", "French", "Spanish", "Japanese", "Chinese (Simplified)", "Chinese (Traditional)"], label="目標語言") # Added more language choices
38
+
39
+ api_key_input = gr.Textbox(label="OpenAI API 金鑰", type="password")
40
+
41
+ with gr.Row():
42
+ translate_button = gr.Button("翻譯")
43
+
44
+ with gr.Row():
45
+ direct_translation_output = gr.Textbox(label="直譯結果")
46
+ idiomatic_translation_output = gr.Textbox(label="意譯結果")
47
+
48
+ comparison_output = gr.Textbox(label="比對結果")
49
+
50
+ translate_button.click(
51
+ translate_text,
52
+ inputs=[text_input, target_language, api_key_input],
53
+ outputs=[direct_translation_output, idiomatic_translation_output, comparison_output]
54
+ )
55
+
56
+ demo.launch()