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()