File size: 2,310 Bytes
63a5856
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import openai

def translate_text(text, target_language, api_key):
    # Step 1: Direct Translation
    prompt1 = f"Translate the following text to {target_language} literally, without omitting any information:\n\n{text}"
    direct_translation = openai_api(prompt1, api_key)

    # Step 2: Idiomatic Translation
    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}"
    idiomatic_translation = openai_api(prompt2, api_key)

    # Step 3: Comparison and Error Reporting (Simplified)
    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}"
    comparison_result = openai_api(prompt3, api_key)
    
    return direct_translation, idiomatic_translation, comparison_result


def openai_api(prompt, key):
    openai.api_key = key
    try:
        completion = openai.chat.completions.create(
            model="gpt-4o",  # or gpt-3.5-turbo
            messages=[{"role": "user", "content": prompt}]
        )
        return completion.choices[0].message.content
    except Exception as e:
        return f"An error occurred: {e}"


with gr.Blocks() as demo:
    gr.Markdown("## 萬國翻譯機")

    with gr.Row():
        text_input = gr.Textbox(label="原文", placeholder="輸入要翻譯的文字")
        target_language = gr.Dropdown(choices=["English", "French", "Spanish", "Japanese", "Chinese (Simplified)", "Chinese (Traditional)"], label="目標語言")  # Added more language choices

    api_key_input = gr.Textbox(label="OpenAI API 金鑰", type="password")

    with gr.Row():
        translate_button = gr.Button("翻譯")
        
    with gr.Row():
        direct_translation_output = gr.Textbox(label="直譯結果")
        idiomatic_translation_output = gr.Textbox(label="意譯結果")

    comparison_output = gr.Textbox(label="比對結果")

    translate_button.click(
        translate_text,
        inputs=[text_input, target_language, api_key_input],
        outputs=[direct_translation_output, idiomatic_translation_output, comparison_output]
    )

demo.launch()