import os import openai import gradio as gr from dotenv import load_dotenv # 환경 변수 로드 load_dotenv() # OpenAI API 키를 환경 변수에서 가져오기 openai.api_key = os.getenv("OPENAI_API_KEY") def translate_to_korean(english_text): """ 입력된 영어 텍스트를 한국어로 번역하는 함수 """ system_message = ( "You are an assistant that translates English text to Korean. " "Ensure that the translation adheres to the following guidelines:\n\n" "1. Prioritize natural and fluent Korean over literal translations.\n" "2. Maintain grammatical accuracy:\n" " - Prefer active voice over passive voice.\n" " - Minimize the use of pronouns.\n" " - Prefer verbs and adjectives over nominalizations.\n" " - Use simple present or present perfect tense instead of present continuous.\n" " - Maintain Subject-Object-Verb order.\n" " - Avoid using expressions like \"~었어요\".\n" "3. Ensure a natural flow that matches the context of the subject.\n" "4. Choose vocabulary that is appropriate for the topic and situation.\n" "5. Reflect emotional nuances to create empathetic expressions.\n" "6. Maintain a balance between literal and free translation.\n" "7. Avoid repeating topic keywords.\n" "8. Ensure the translation does not appear to be written by AI.\n" ) try: response = openai.ChatCompletion.create( model="gpt-4o-mini", # 모델 ID messages=[ {"role": "system", "content": system_message}, {"role": "user", "content": english_text}, ], max_tokens=1000, # 필요한 경우 조정 temperature=0.3, # 창의성 조절 top_p=1.0, # 확률 분포 조절 ) korean_text = response.choices[0].message['content'].strip() return korean_text except Exception as e: return f"오류가 발생했습니다: {str(e)}" # Gradio 인터페이스 구성 with gr.Blocks() as iface: gr.Markdown("# 영어-한국어 번역기") gr.Markdown("GPT-4o-mini 모델을 사용하여 영어 텍스트를 한국어로 번역합니다. 번역 시 자연스럽고 매끄러운 한국어로 제공됩니다.") with gr.Row(): with gr.Column(): english_input = gr.Textbox( lines=10, placeholder="번역할 영어 텍스트를 입력하세요...", label="영어 텍스트" ) with gr.Column(): korean_output = gr.Textbox( lines=10, label="한국어 번역" ) translate_button = gr.Button("번역하기") translate_button.click( fn=translate_to_korean, inputs=english_input, outputs=korean_output ) gr.Examples( examples=[ "Hello, how are you?", "This is a test sentence for translation.", "OpenAI provides powerful language models." ], inputs=english_input, outputs=korean_output ) if __name__ == "__main__": iface.launch()