Spaces:
Runtime error
Runtime error
File size: 12,860 Bytes
cb7eb15 fb7b386 e83b154 fb7b386 e83b154 fb7b386 53a1a66 fb7b386 e83b154 fb7b386 e83b154 fb7b386 e83b154 fb7b386 e83b154 fb7b386 e83b154 fb7b386 e83b154 fb7b386 e83b154 fb7b386 e83b154 fb7b386 e83b154 fb7b386 e83b154 fb7b386 e83b154 fb7b386 e83b154 fb7b386 e83b154 |
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 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 |
import os
import json
import tempfile
import gradio as gr
import openai
from transformers import pipeline
# =========================
# π§ μ€μ
# =========================
openai.api_key = os.environ.get("OPENAI_API_KEY")
# Hugging Face λ²μ νμ΄νλΌμΈ (μλ°©ν₯ ν¬ν¨)
translator_ko_to_en = pipeline("translation", model="Helsinki-NLP/opus-mt-ko-en")
translator_ko_to_de = pipeline("translation", model="Helsinki-NLP/opus-mt-ko-de")
translator_en_to_ko = pipeline("translation", model="Helsinki-NLP/opus-mt-en-ko")
translator_de_to_ko = pipeline("translation", model="Helsinki-NLP/opus-mt-de-ko")
# =========================
# π§ μ νΈ: OpenAI νΈμΆ
# =========================
def gpt(messages, temperature=0.7, model="gpt-4"):
"""λ¨μΌ ChatCompletion λνΌ"""
resp = openai.ChatCompletion.create(
model=model,
messages=messages,
temperature=temperature
)
return resp.choices[0].message["content"].strip()
# =========================
# π§© ν΅μ¬ λ‘μ§
# =========================
def make_variants(input_text, source_lang, target_lang, direct_translation):
"""
μ§μμ κΈ°μ€μΌλ‘ μμ΄λ―Όμ΄ μμ°μ€λ½κ² μ°λ λ³ν λ²μ 2κ°λ₯Ό μΆκ°λ‘ μμ± (μ΄ 3κ°)
"""
sys_msg = "You are a bilingual translator who produces concise, natural alternatives."
user_msg = f"""
[μλ¬Έ] ({source_lang}): {input_text}
[μ§μ] ({target_lang}): {direct_translation}
μ μ§μμ κΈ°μ€μΌλ‘, {target_lang} μμ΄λ―Όμ΄ μ€μ λ‘ λ§μ΄ μ°λ μμ°μ€λ¬μ΄ λ³ν 2κ°μ§λ₯Ό λ§λ€μ΄μ€.
- λ§₯λ½: μΌμ λν κΈ°μ€
- κ° λ³νμ 1λ¬Έμ₯
- κ³Όμ₯/μ¬λμ κ³Όνμ§ μκ²
- μΆλ ₯ νμ:
1) λ³νA: ...
2) λ³νB: ...
"""
out = gpt([{"role":"system","content":sys_msg},{"role":"user","content":user_msg}], temperature=0.6)
# κ°λ¨ νμ±
variants = [direct_translation]
for line in out.splitlines():
line = line.strip()
if line.startswith("1)") or line.lower().startswith("λ³νa"):
variants.append(line.split(":",1)[1].strip() if ":" in line else line)
elif line.startswith("2)") or line.lower().startswith("λ³νb"):
variants.append(line.split(":",1)[1].strip() if ":" in line else line)
# fallback
return variants[:3] if len(variants)>=3 else (variants + ["", ""])[:3]
def back_translate_list(variants, source_lang, target_lang):
"""κ° λ³ν λ²μμ λͺ¨κ΅μ΄λ‘ μλ²μνμ¬ λΉκ΅ ν
μ΄λΈμ© λ°μ΄ν° μμ±"""
back_list = []
for v in variants:
if not v:
back_list.append("")
continue
if source_lang == "νκ΅μ΄" and target_lang == "μμ΄":
back_ = translator_en_to_ko(v)[0]["translation_text"]
elif source_lang == "νκ΅μ΄" and target_lang == "λ
μΌμ΄":
back_ = translator_de_to_ko(v)[0]["translation_text"]
else:
back_ = "(μλ²μ λ―Έμ§μ)"
back_list.append(back_)
return back_list
def build_explanations(input_text, variants, source_lang, target_lang):
"""νν/λ¬Έλ²/λ¨μ΄/λ¬Έν μ€λͺ
μ μΉμ
λ³ λ§ν¬λ€μ΄μΌλ‘ μμ±"""
best = variants[0] if variants else ""
sys_msg = "You are a concise yet friendly language tutor who explains in Korean with clear headings and bullet points."
user_msg = f"""
λ€μ ννμ λν΄ νκ΅μ΄λ‘ μ€λͺ
ν΄μ€. κ°κ²°νμ§λ§ ν΅μ¬μ λΉ μ§μμ΄.
[μλ¬Έ] ({source_lang}): {input_text}
[λν λ²μ] ({target_lang}): {best}
[λ€λ₯Έ λ³ν λ²μλ€]: {variants[1:]}
μλ μΉμ
μ λͺ©μ κ·Έλλ‘ μ¬μ©ν΄:
## νν μ€λͺ
- μ΄λ€ μν©/κ΄κ³μμ μ°λμ§, λμμ€(격μ/μΉκ·Όκ°)
## λ¬Έλ² ν¬μΈνΈ
- ν΅μ¬ λ¬Έλ² μμ 2~3κ° (μ‘°μ¬/μ μΉμ¬, μμ , μ΄μ λ±)
- κ°λ¨ μλ¬Έ κ° 1κ°
## λ¨μ΄/νν μ€λͺ
- μ΄λ €μΈ μ μλ λ¨μ΄/ꡬμ 3κ°: μλ―Έ + μ§§μ μλ¬Έ
## λ¬Ένμ μ°¨μ΄
- νκ΅μ΄μ λμ μΈμ΄ μ¬μ΄μ κΈ°λ/μμ/κ΄μ΅ μ°¨μ΄ 2~3κ°μ§
"""
return gpt([{"role":"system","content":sys_msg},{"role":"user","content":user_msg}], temperature=0.5)
def build_pronunciation(input_text, variants, source_lang, target_lang):
"""λ°μ κ°μ΄λ(ν
μ€νΈ). IPA/κ°μΈ/λ¦¬λ¬ ν¬μΈνΈ"""
best = variants[0] if variants else ""
sys_msg = "You provide compact pronunciation guides (IPA-ish, stress, rhythm)."
user_msg = f"""
λ€μ λ λ¬Έμ₯μ λν λ°μ κ°μ΄λλ₯Ό νκ΅μ΄λ‘ κ°λ¨ν μ μ΄μ€.
[μλ¬Έ] ({source_lang}): {input_text}
[λν λ²μ] ({target_lang}): {best}
νμ:
- μλ¬Έ: (κ°λ₯νλ©΄ κ°λ¨ IPA/νκΈνκΈ°) + κ°μΈ/λ¦¬λ¬ ν¬μΈνΈ
- λ²μ: (IPA/κ°μΈ) + μμ°μ€λ¬μ΄ μ΅μ ν
"""
return gpt([{"role":"system","content":sys_msg},{"role":"user","content":user_msg}], temperature=0.4)
def build_roleplay(input_text, variants, target_lang):
"""격μ/μΉκ·Ό 2κ°μ§ ν€μ μ§§μ Role Play"""
best = variants[0] if variants else ""
sys_msg = "You create short, practical role-play dialogues for language learners."
user_msg = f"""
λ€μ ννμ νμ©ν μ§§μ λν 2κ°μ§λ₯Ό λ§λ€μ΄μ€. κ° λνλ 6~8 ν΄.
- ν€1: 격μ(μ§μ₯/곡μ μΈ μν©)
- ν€2: μΉκ·Ό(μΉκ΅¬/κ°λ²Όμ΄ μν©)
- λμ μΈμ΄: {target_lang}
- λν ν νκ΅μ΄ μμ½ ν μ€
νν: "{best}"
"""
return gpt([{"role":"system","content":sys_msg},{"role":"user","content":user_msg}], temperature=0.7)
def suggest_resources(input_text, target_lang):
"""νμ΅ μλ£ μΆμ²: μ νλΈ/κ²μ ν€μλ"""
sys_msg = "You suggest search keywords for YouTube and web to find usage contexts."
user_msg = f"""
μλ ννμ μ€μ λ§₯λ½μμ λ³Ό μ μλ μλ£λ₯Ό μ°ΎκΈ° μν κ²μ ν€μλλ₯Ό μ μν΄μ€.
- μΈμ΄: {target_lang}
- 5~7κ° ν€μλ, λ°μ΄ν μμ΄, ν μ€μ νλ
νν: {input_text}
"""
out = gpt([{"role":"system","content":sys_msg},{"role":"user","content":user_msg}], temperature=0.5)
# ν΄λ¦ κ°λ₯ν κ²μ URL λ¬Έμμ΄ μμ±
items = [s.strip("-β’ ").strip() for s in out.splitlines() if s.strip()]
md_lines = []
base = "https://www.youtube.com/results?search_query="
for k in items:
url = base + k.replace(" ", "+")
md_lines.append(f"- [{k}]({url})")
return "\n".join(md_lines)
# =========================
# π λ©μΈ ν¨μ (Gradioμ μ°κ²°)
# =========================
def run_pipeline(input_text, source_lang, target_lang, favorites_state):
if not input_text.strip():
return (
"", [], None, "", "", "", favorites_state, gr.update(visible=False), None
)
# 1) κΈ°λ³Έ λ²μ
if source_lang == "νκ΅μ΄" and target_lang == "μμ΄":
direct = translator_ko_to_en(input_text)[0]['translation_text']
elif source_lang == "νκ΅μ΄" and target_lang == "λ
μΌμ΄":
direct = translator_ko_to_de(input_text)[0]['translation_text']
else:
return (
input_text, ["(μ§μλμ§ μλ μΈμ΄μμ
λλ€.)"], None, "(μ§μλμ§ μλ μΈμ΄μ)", "", "", favorites_state, gr.update(visible=False), None
)
# 2) λ³ν 3κ°μ§
variants = make_variants(input_text, source_lang, target_lang, direct)
# 3) μλ²μ ν
μ΄λΈ λ°μ΄ν°
backs = back_translate_list(variants, source_lang, target_lang)
back_table = {
"λ²μ(Variant)": variants,
"μλ²μ(λͺ¨κ΅μ΄)": backs
}
# 4) μ€λͺ
μΉμ
explanations_md = build_explanations(input_text, variants, source_lang, target_lang)
# 5) λ°μ κ°μ΄λ
pron_md = build_pronunciation(input_text, variants, source_lang, target_lang)
# 6) Role Play
roleplay_md = build_roleplay(input_text, variants, target_lang)
# 7) μλ£ μΆμ²
resources_md = suggest_resources(input_text, target_lang)
# 8) μ¦κ²¨μ°ΎκΈ° μΉ΄λ(νμ¬ κ²°κ³Ό)
current_card = {
"μλ¬Έ": input_text,
"λν λ²μ": variants[0],
"λ€λ₯Έ λ³ν": variants[1:],
"μλ²μ": backs,
"μ€λͺ
": explanations_md,
"λ°μ": pron_md,
"role_play": roleplay_md
}
# λ€μ΄λ‘λ νμΌμ Save λ²νΌ ν΄λ¦ μ μμ±νλλ‘ νλ―λ‘ μ¬κΈ°μλ None
return (
input_text,
variants,
back_table,
explanations_md,
pron_md,
roleplay_md,
favorites_state,
gr.update(visible=True),
resources_md
)
def save_to_favorites(input_text, variants, backs, explanations_md, pron_md, roleplay_md, favorites_state):
if favorites_state is None:
favorites_state = []
entry = {
"μλ¬Έ": input_text,
"λ³νλ²μ": variants,
"μλ²μ": backs,
"μ€λͺ
": explanations_md,
"λ°μ": pron_md,
"role_play": roleplay_md
}
favorites_state.append(entry)
return favorites_state, f"μ μ₯ μλ£! (μ΄ {len(favorites_state)}건)"
def export_favorites(favorites_state):
if not favorites_state:
return None
fd, path = tempfile.mkstemp(suffix=".json")
with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump(favorites_state, f, ensure_ascii=False, indent=2)
return path
def load_sample(sample_text):
return gr.update(value=sample_text)
# =========================
# ποΈ Gradio UI
# =========================
with gr.Blocks(title="π λ¬Έν κ° νν λΉκ΅ + λ¬Έλ² & μ΄ν λμ°λ―Έ (νμ₯ν)") as demo:
gr.Markdown("## π λ¬Έν κ° νν λΉκ΅ + λ¬Έλ² & μ΄ν λμ°λ―Έ\nμ
λ ₯ν ννμ κΈ°λ°μΌλ‘ **μμ°μ€λ¬μ΄ λ²μ 3κ°μ§, μλ²μ λΉκ΅, λ¬Έλ²/λ¬Έν μ€λͺ
, Role Play, λ°μ κ°μ΄λ**κΉμ§ ν λ²μ!")
with gr.Row():
with gr.Column(scale=5):
input_text = gr.Textbox(label="λΉκ΅ν λ¬Έμ₯ μ
λ ₯", placeholder="μ: κ³ μνμ΄!", lines=2)
with gr.Row():
src_dd = gr.Dropdown(["νκ΅μ΄"], label="λͺ¨κ΅μ΄ μ ν", value="νκ΅μ΄")
tgt_dd = gr.Dropdown(["μμ΄", "λ
μΌμ΄"], label="λΉκ΅ μΈμ΄ μ ν", value="μμ΄")
with gr.Accordion("μν λ¬Έμ₯ λΆλ¬μ€κΈ°", open=False):
gr.Markdown("- μν©λ³λ‘ λ°λ‘ ν
μ€νΈν΄λ³΄μΈμ.")
with gr.Row():
b1 = gr.Button("μΉκ΅¬ μλ‘: κ³ μνμ΄!")
b2 = gr.Button("κ²©λ €: μκ³ λ§μμ΄, μ λ§ κ³ λ§μ.")
b3 = gr.Button("μ
무: μ€λ μΌμ νμΈ λΆνλ립λλ€.")
submit = gr.Button("π Submit", variant="primary")
with gr.Column(scale=7):
tabs = gr.Tabs()
with tabs:
with gr.Tab("κ²°κ³Ό μμ½"):
orig_out = gr.Textbox(label="μλ¬Έ", interactive=False)
variants_out = gr.HighlightedText(
label="λ²μ 3κ°μ§ (μ§μ + μμ°μ€λ¬μ΄ λ³ν)",
combine_adjacent=True
)
resources_md = gr.Markdown(visible=False)
with gr.Tab("μλ°©ν₯ λΉκ΅"):
back_table = gr.Dataframe(headers=["λ²μ(Variant)", "μλ²μ(λͺ¨κ΅μ΄)"], interactive=False)
with gr.Tab("μ€λͺ
"):
explain_out = gr.Markdown()
with gr.Tab("λ°μ κ°μ΄λ"):
pron_out = gr.Markdown()
with gr.Tab("Role Play"):
role_out = gr.Markdown()
with gr.Tab("μ¦κ²¨μ°ΎκΈ°"):
fav_state = gr.State([])
save_btn = gr.Button("β νμ¬ κ²°κ³Ό μ μ₯")
save_status = gr.Markdown("")
export_btn = gr.Button("β¬οΈ μ¦κ²¨μ°ΎκΈ° JSON λ΄λ³΄λ΄κΈ°")
export_file = gr.File(label="λ€μ΄λ‘λ νμΌ")
# ---------- μ΄λ²€νΈ λ°μΈλ© ----------
submit.click(
fn=run_pipeline,
inputs=[input_text, src_dd, tgt_dd, fav_state],
outputs=[orig_out, variants_out, back_table, explain_out, pron_out, role_out, fav_state, resources_md, resources_md],
)
# μν λ²νΌ
b1.click(fn=load_sample, inputs=None, outputs=input_text, _js=None, kwargs={"sample_text":"κ³ μνμ΄!"})
b2.click(fn=load_sample, inputs=None, outputs=input_text, kwargs={"sample_text":"μκ³ λ§μμ΄, μ λ§ κ³ λ§μ."})
b3.click(fn=load_sample, inputs=None, outputs=input_text, kwargs={"sample_text":"μ€λ μΌμ νμΈ λΆνλ립λλ€."})
# μ¦κ²¨μ°ΎκΈ° μ μ₯
save_btn.click(
fn=save_to_favorites,
inputs=[orig_out, variants_out, back_table, explain_out, pron_out, role_out, fav_state],
outputs=[fav_state, save_status]
)
# λ΄λ³΄λ΄κΈ°
export_btn.click(fn=export_favorites, inputs=[fav_state], outputs=[export_file])
demo.launch()
|