easyadaptor's picture
Update app.py
fcfdebd verified
Raw History Blame
5.89 kB
import gradio as gr
import json
import os
import difflib
import shutil
try:
from g2pk import G2p
except ImportError:
G2p = None
print("G2P λͺ¨λΈ λ‘œλ”© 쀑...")
try:
if G2p:
g2p = G2p()
else:
g2p = None
except Exception as e:
print(f"G2P λ‘œλ”© μ‹€νŒ¨: {e}")
g2p = None
dict_path = "custom_dict.json"
# μ—λŸ¬ λ°©μ§€λ₯Ό μœ„ν•΄ μ‹œμž‘ μ‹œ 빈 사전 파일 보μž₯
if not os.path.exists(dict_path):
with open(dict_path, "w", encoding="utf-8") as f:
json.dump({"items":[], "meta": {"count": 0}}, f)
def load_dict():
flat_dict = {}
try:
with open(dict_path, "r", encoding="utf-8") as f:
data = json.load(f)
for item in data.get("items",[]):
if len(item) == 2:
flat_dict[item[0]] = item[1]
except Exception as e:
print(f"사전 λ‘œλ”© μ—λŸ¬: {e}")
return flat_dict
def process_text(input_text):
if not input_text or not input_text.strip():
return "", "", "μž…λ ₯ κΈ€μž 수: 0자"
char_count = f"μž…λ ₯ κΈ€μž 수: {len(input_text)}자"
processed = input_text
# 1. μ‚¬μš©μž μ§€μ • 사전 μΉ˜ν™˜
flat_dict = load_dict()
for word, pronun in flat_dict.items():
processed = processed.replace(word, pronun)
final_text = processed
# 2. G2P μžλ™ 발음 λ³€ν™˜ 적용
if g2p is not None:
try:
final_text = g2p(processed)
except Exception as e:
print(f"G2P μ—λŸ¬: {e}")
# 3. ν˜•κ΄‘νŽœ 효과 (HTML)
seq = difflib.SequenceMatcher(None, input_text, final_text)
html_parts =[]
for tag, i1, i2, j1, j2 in seq.get_opcodes():
chunk = final_text[j1:j2].replace('\n', '<br>')
if tag == 'equal':
html_parts.append(chunk)
elif tag in ['replace', 'insert']:
html_parts.append(f'<span style="background-color: #ffe066; font-weight: bold; padding: 2px; border-radius: 3px;">{chunk}</span>')
html_output = f'<div style="line-height:1.6; font-size:16px; padding:10px; border:1px solid #ddd; border-radius:5px; background-color:#f9f9f9;">{"".join(html_parts)}</div>'
return final_text, html_output, char_count
def clear_all():
return "", "", "", "μž…λ ₯ κΈ€μž 수: 0자"
def add_dict(word, pronun):
if not word or not pronun:
return "⚠️ 단어/λ¬Έμž₯κ³Ό λ°œμŒμ„ λͺ¨λ‘ μž…λ ₯ν•˜μ„Έμš”."
try:
with open(dict_path, "r", encoding="utf-8") as f:
j_struct = json.load(f)
except:
j_struct = {"items":[], "meta": {"count": 0}}
found = False
for item in j_struct.get("items",[]):
if item[0] == word:
item[1] = pronun
found = True
break
if not found:
j_struct["items"].append([word, pronun])
try:
with open(dict_path, "w", encoding="utf-8") as f:
json.dump(j_struct, f, ensure_ascii=False, indent=2)
return f"βœ… '{word}' -> '{pronun}' μ €μž₯ μ™„λ£Œ!"
except Exception as e:
return f"❌ μ €μž₯ μ‹€νŒ¨: {e}"
def get_file():
return dict_path if os.path.exists(dict_path) else None
def upload_file(file_path):
if file_path is not None:
shutil.copy(file_path, dict_path)
return "βœ… 볡ꡬ μ™„λ£Œ! 사전을 μ •μƒμ μœΌλ‘œ μ‚¬μš©ν•  수 μžˆμŠ΅λ‹ˆλ‹€."
return "⚠️ 파일이 μ—†μŠ΅λ‹ˆλ‹€."
# UI ν™”λ©΄ ꡬ성
with gr.Blocks(theme="default") as iface:
gr.Markdown("## πŸŽ™οΈ λ‚˜λ§Œμ˜ TTS μ „μ²˜λ¦¬ λ³€ν™˜κΈ° (였λ₯˜ μ™„λ²½ ν•΄κ²°λ³Έ)")
with gr.Tabs():
with gr.Tab("πŸŽ™οΈ 메인 ν™”λ©΄"):
with gr.Row():
with gr.Column():
input_text = gr.Textbox(lines=8, label="1️⃣ 원본 ν…μŠ€νŠΈ μž…λ ₯")
char_count = gr.Textbox(label="κΈ€μž 수 확인", value="μž…λ ₯ κΈ€μž 수: 0자", interactive=False)
with gr.Row():
btn_conv = gr.Button("✨ λ³€ν™˜ν•˜κΈ°", variant="primary")
btn_clr = gr.Button("πŸ—‘οΈ λŒ€λ³Έ μ΄ˆκΈ°ν™”", variant="stop")
with gr.Column():
# 우츑 상단 볡사 λ²„νŠΌ ν™œμ„±ν™”
output_text = gr.Textbox(lines=8, label="2️⃣ λ³€ν™˜λœ ν…μŠ€νŠΈ (우츑 상단 πŸ“‹ μ•„μ΄μ½˜ 클릭 μ‹œ 볡사)", show_copy_button=True)
output_html = gr.HTML(label="πŸ” 변경점 확인")
# api_name=False 속성 μΆ”κ°€λ‘œ 먹톡 버그 μ™„λ²½ 차단!
btn_conv.click(fn=process_text, inputs=[input_text], outputs=[output_text, output_html, char_count], api_name=False)
btn_clr.click(fn=clear_all, outputs=[input_text, output_text, output_html, char_count], api_name=False)
gr.Markdown("---")
with gr.Row():
nw = gr.Textbox(label="κΈ°μ‘΄ 단어 λ˜λŠ” λ¬Έμž₯")
np = gr.Textbox(label="μ›ν•˜λŠ” 발음")
btn_add = gr.Button("πŸ’Ύ 사전에 μΆ”κ°€", variant="primary")
status = gr.Textbox(label="μ €μž₯ μƒνƒœ κ²°κ³Όμ°½", interactive=False)
btn_add.click(fn=add_dict, inputs=[nw, np], outputs=[status], api_name=False)
with gr.Tab("πŸ“₯ λ°±μ—…/볡ꡬ"):
dl_btn = gr.DownloadButton("πŸ“₯ 1. ν˜„μž¬ 사전 λ°±μ—…ν•˜κΈ° (PC λ‹€μš΄λ‘œλ“œ)")
dl_btn.click(fn=get_file, outputs=[dl_btn], api_name=False)
gr.Markdown("---")
up_file = gr.File(label="πŸ“€ 2. λ°±μ—… 파일 λ³΅κ΅¬ν•˜κΈ° (μ—…λ‘œλ“œ)", type="filepath")
up_stat = gr.Textbox(label="볡ꡬ μƒνƒœ κ²°κ³Όμ°½", interactive=False)
up_file.upload(fn=upload_file, inputs=[up_file], outputs=[up_stat], api_name=False)
if __name__ == "__main__":
iface.launch()