Kims12's picture
Update app.py
c5eb776 verified
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()