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', '
')
if tag == 'equal':
html_parts.append(chunk)
elif tag in ['replace', 'insert']:
html_parts.append(f'{chunk}')
html_output = f'
{"".join(html_parts)}
'
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()