import gradio as gr
import json
import os
import difflib
import shutil
import re
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"
AUTO_MERGE_WORDS = [["GS마이샵", "지에스마이샵"],["GS 마이샵", "지에스마이샵"],["GS샵", "지에스샵"],["GS 샵", "지에스샵"],["26SS", "이십육 에스에스"],["26 SS", "이십육 에스에스"],["26S/S", "이십육 에스에스"],["26 S/S", "이십육 에스에스"],["55", "오오"],["55사이즈", "오오 싸이즈"],["55 사이즈", "오오 싸이즈"],["66", "융육"],["66사이즈", "융육 싸이즈"],["66 사이즈", "융육 싸이즈"],["77", "칠칠"],["77사이즈", "칠칠 싸이즈"],["77 사이즈", "칠칠 싸이즈"],["88", "팔팔"],["88사이즈", "팔팔 싸이즈"],["88 사이즈", "팔팔 싸이즈"],["100%", "백프로"],["100 %", "백프로"],["100프로", "백프로"],["59,900원", "오만 구천구백 원"],["59,900 원", "오만 구천구백 원"],["59900원", "오만 구천구백 원"],["59900 원", "오만 구천구백 원"],["5만 9천 9백 원", "오만 구천구백 원"],["3개월", "삼개월"],["3 개월", "삼개월"],["1만원대", "만원때"],["1만 원대", "만원때"],["1만 원 대", "만원때"],["1만원 대", "만원때"]]
def perform_auto_recovery_and_merge():
if not os.path.exists(dict_path):
with open(dict_path, "w", encoding="utf-8") as f:
json.dump({"items":[], "meta": {"count": 0}}, f)
try:
with open(dict_path, "r", encoding="utf-8") as f:
existing_data = json.load(f)
except:
existing_data = {"items":[], "meta": {"count": 0}}
dict_map = {item[0].strip(): item[1].strip() for item in existing_data.get("items",[]) if len(item) == 2}
for w in AUTO_MERGE_WORDS:
dict_map[w[0]] = w[1]
merged_items = [[k, v] for k, v in dict_map.items()]
existing_data["items"] = merged_items
existing_data["meta"]["count"] = len(merged_items)
with open(dict_path, "w", encoding="utf-8") as f:
json.dump(existing_data, f, ensure_ascii=False, indent=2)
perform_auto_recovery_and_merge()
def load_dict():
flat_dict = {}
try:
if os.path.exists(dict_path):
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].strip()] = item[1].strip()
except:
pass
return flat_dict
def apply_g2p(text, mode):
if g2p is None or mode == "끄기 (수동 사전만 적용)":
return text
if mode == "매운 맛 (문장 통째로 - 자연스러운 연음)":
try: return g2p(text)
except: return text
if mode == "순한 맛 (단어별 끊기 - 과도한 연음 방지)":
words = re.split(r'(\s+)', text)
res =[]
for w in words:
if w.strip():
try: res.append(g2p(w))
except: res.append(w)
else: res.append(w)
return "".join(res)
return text
def process_text(input_text, ai_mode, auto_break, smart_pause, font_size):
if not input_text or not input_text.strip():
return "", "", "공백 포함: 0자 / 공백 제외: 0자", "표시된 마커(@@)가 없습니다."
# ★ 정확한 글자 수 계산 로직
clean_text = input_text.replace('\r', '')
len_with_spaces = len(clean_text)
len_without_spaces = len(clean_text.replace(' ', '').replace('\n', ''))
char_count = f"공백 포함: {len_with_spaces}자 / 공백 제외: {len_without_spaces}자"
flat_dict = load_dict()
if not flat_dict:
final_text = apply_g2p(input_text, ai_mode)
else:
sorted_keys = sorted(flat_dict.keys(), key=len, reverse=True)
pattern = re.compile("|".join(map(re.escape, sorted_keys)))
parts =[]
last_end = 0
for match in pattern.finditer(input_text):
start, end = match.span()
chunk = input_text[last_end:start]
if chunk: parts.append(apply_g2p(chunk, ai_mode))
matched_word = match.group()
parts.append(flat_dict[matched_word])
last_end = end
tail = input_text[last_end:]
if tail: parts.append(apply_g2p(tail, ai_mode))
final_text = "".join(parts)
if smart_pause:
final_text = re.sub(r',\s*', ', / ', final_text)
if auto_break:
final_text = final_text.replace(". ", ".\n\n").replace("? ", "?\n\n")
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}')
raw_html = "".join(html_parts)
raw_html = re.sub(r'([^\s<]*@@[^\s<]*)', r'\1', raw_html)
html_output = f'
📺 프롬프터 뷰 (변경점 확인)
{raw_html}
'
markers = re.findall(r'[^\s]*@@[^\s]*', input_text)
unique_markers =[]
for m in markers:
clean_m = m.strip('.,!?\n')
if clean_m and clean_m not in unique_markers:
unique_markers.append(clean_m)
if unique_markers:
marker_result = " / ".join(unique_markers)
else:
marker_result = "표시된 마커(@@)가 없습니다."
return final_text, html_output, char_count, marker_result
def clear_all():
return "", "", "", "공백 포함: 0자 / 공백 제외: 0자", "표시된 마커(@@)가 없습니다."
def add_and_update(word, pronun, current_input, ai_mode, auto_break, smart_pause, font_size):
if not word or not pronun:
return "⚠️ 기존 단어와 원하는 발음을 모두 입력하세요.", gr.update(), gr.update(), gr.update(), gr.update()
word = word.strip()
pronun = pronun.strip()
if len(word) == 1:
error_msg = f"🚫 [등록 실패] '{word}'처럼 1글자만 등록하면 원본이 훼손됩니다! 2글자 이상으로 등록해주세요."
if current_input and current_input.strip():
final_text, html_output, char_count, marker_result = process_text(current_input, ai_mode, auto_break, smart_pause, font_size)
return error_msg, final_text, html_output, char_count, marker_result
return error_msg, "", "", "공백 포함: 0자 / 공백 제외: 0자", "표시된 마커(@@)가 없습니다."
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].strip() == 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)
status_msg = f"✅ '{word}' -> '{pronun}' 저장 완료!"
except Exception as e:
status_msg = f"❌ 저장 실패: {e}"
if current_input and current_input.strip():
final_text, html_output, char_count, marker_result = process_text(current_input, ai_mode, auto_break, smart_pause, font_size)
return status_msg, final_text, html_output, char_count, marker_result
return status_msg, "", "", "공백 포함: 0자 / 공백 제외: 0자", "표시된 마커(@@)가 없습니다."
def load_current_json_to_text():
try:
with open(dict_path, "r", encoding="utf-8") as f:
data = json.load(f)
dict_map = {item[0]: item[1] for item in data.get("items",[]) if len(item) == 2}
pretty_json = json.dumps({"items": dict_map}, ensure_ascii=False, indent=4)
return pretty_json, "✅ 현재 사전을 성공적으로 불러왔습니다! 이상한 단어를 찾아 지우거나 수정해보세요."
except Exception as e:
return "", f"❌ 불러오기 실패: {e}"
def overwrite_json_text(json_string):
if not json_string or not json_string.strip():
return "⚠️ 내용을 입력해주세요."
try:
new_data = json.loads(json_string)
if "items" not in new_data:
return "⚠️ 올바른 사전 형식이 아닙니다. ('items' 키가 없습니다)"
new_items =[]
if isinstance(new_data["items"], dict):
for k, v in new_data["items"].items():
new_items.append([k.strip(), v.strip()])
elif isinstance(new_data["items"], list):
for item in new_data["items"]:
if len(item) == 2:
new_items.append([item[0].strip(), item[1].strip()])
final_data = {"items": new_items, "meta": {"count": len(new_items)}}
with open(dict_path, "w", encoding="utf-8") as f:
json.dump(final_data, f, ensure_ascii=False, indent=2)
return f"🚨[덮어쓰기 완료] 수정한 내용({len(new_items)}개)으로 사전을 완벽히 교체했습니다!"
except Exception as e:
return f"❌ JSON 파싱 에러 (따옴표나 쉼표가 빠졌는지 확인하세요): {e}"
def apply_json_text(json_string):
if not json_string or not json_string.strip():
return "⚠️ 내용을 입력해주세요."
try:
new_data = json.loads(json_string)
if "items" not in new_data:
return "⚠️ 올바른 사전 형식이 아닙니다."
try:
with open(dict_path, "r", encoding="utf-8") as f:
existing_data = json.load(f)
except:
existing_data = {"items":[], "meta": {"count": 0}}
dict_map = {item[0].strip(): item[1].strip() for item in existing_data.get("items",[]) if len(item) == 2}
if isinstance(new_data["items"], dict):
for k, v in new_data["items"].items():
dict_map[k.strip()] = v.strip()
elif isinstance(new_data["items"], list):
for item in new_data["items"]:
if len(item) == 2:
dict_map[item[0].strip()] = item[1].strip()
merged_items = [[k, v] for k, v in dict_map.items()]
existing_data["items"] = merged_items
existing_data["meta"]["count"] = len(merged_items)
with open(dict_path, "w", encoding="utf-8") as f:
json.dump(existing_data, f, ensure_ascii=False, indent=2)
return f"✅ 기존 단어를 유지하며 성공적으로 플러스(+) 했습니다!"
except Exception as e:
return f"❌ JSON 파싱 에러: {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 "⚠️ 파일이 없습니다."
custom_css = """
#prompter_html_wrap { width: 100% !important; max-width: 100% !important; margin: 0 !important; padding: 0 !important; }
#prompter_html_wrap .prose { width: 100% !important; max-width: 100% !important; text-align: left !important; margin: 0 !important; }
#input_text_area textarea, #output_text_area textarea, #prompter_output_div { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif !important; letter-spacing: normal !important; word-spacing: normal !important; }
#input_text_area textarea { height: 500px !important; max-height: 500px !important; overflow-y: auto !important; padding: 16px !important; line-height: 1.8 !important; box-sizing: border-box !important; white-space: pre-wrap !important; word-break: break-word !important; }
#prompter_label_space { font-size: 13px !important; color: var(--body-text-color-subdued, #6b7280) !important; margin-bottom: 8px !important; display: block !important; text-align: left !important; font-weight: 400 !important; }
#prompter_output_div { height: 500px !important; max-height: 500px !important; overflow-y: auto !important; padding: 16px !important; line-height: 1.8 !important; box-sizing: border-box !important; background-color: #333 !important; color: #fff !important; border: 1px solid #ddd !important; border-radius: 8px !important; white-space: pre-wrap !important; word-break: break-word !important; text-align: left !important; margin-top: 0 !important; width: 100% !important; max-width: 100% !important; }
"""
script_js = """
function() {
function applyFontSize(size) {
let ta1 = document.querySelector('#input_text_area textarea');
if(ta1) { ta1.style.fontSize = size + 'px'; }
let ta2 = document.querySelector('#output_text_area textarea');
if(ta2) { ta2.style.fontSize = size + 'px'; ta2.style.lineHeight = '1.8'; }
}
setTimeout(function() { applyFontSize(22); }, 500);
let isSyncing1 = false;
let isSyncing2 = false;
let isSyncing3 = false;
document.addEventListener('scroll', function(e) {
let target = e.target;
let ta1 = document.querySelector('#input_text_area textarea');
let ta2 = document.querySelector('#output_text_area textarea');
let div3 = document.getElementById('prompter_output_div');
if (!ta1 || !div3) return;
if (target === ta1) {
if (isSyncing1) { isSyncing1 = false; return; }
if (ta1.scrollHeight - ta1.clientHeight <= 0) return;
isSyncing2 = true; isSyncing3 = true;
let percentage = ta1.scrollTop / (ta1.scrollHeight - ta1.clientHeight);
if (ta2 && ta2.scrollHeight - ta2.clientHeight > 0) { ta2.scrollTop = percentage * (ta2.scrollHeight - ta2.clientHeight); }
if (div3.scrollHeight - div3.clientHeight > 0) { div3.scrollTop = percentage * (div3.scrollHeight - div3.clientHeight); }
}
else if (target === ta2) {
if (isSyncing2) { isSyncing2 = false; return; }
if (ta2 && ta2.scrollHeight - ta2.clientHeight <= 0) return;
isSyncing1 = true; isSyncing3 = true;
let percentage = ta2.scrollTop / (ta2.scrollHeight - ta2.clientHeight);
if (ta1.scrollHeight - ta1.clientHeight > 0) { ta1.scrollTop = percentage * (ta1.scrollHeight - ta1.clientHeight); }
if (div3.scrollHeight - div3.clientHeight > 0) { div3.scrollTop = percentage * (div3.scrollHeight - div3.clientHeight); }
}
else if (target === div3) {
if (isSyncing3) { isSyncing3 = false; return; }
if (div3.scrollHeight - div3.clientHeight <= 0) return;
isSyncing1 = true; isSyncing2 = true;
let percentage = div3.scrollTop / (div3.scrollHeight - div3.clientHeight);
if (ta1.scrollHeight - ta1.clientHeight > 0) { ta1.scrollTop = percentage * (ta1.scrollHeight - ta1.clientHeight); }
if (ta2 && ta2.scrollHeight - ta2.clientHeight > 0) { ta2.scrollTop = percentage * (ta2.scrollHeight - ta2.clientHeight); }
}
}, true);
}
"""
insert_marker_js = """
(current_text) => {
let ta = document.querySelector('#input_text_area textarea');
if (!ta) return current_text;
let start = ta.selectionStart;
let end = ta.selectionEnd;
let text = ta.value;
let before = text.substring(0, start);
let after = text.substring(end, text.length);
let new_text = before + "@@" + after;
ta.value = new_text;
let event = new Event('input', { bubbles: true });
ta.dispatchEvent(event);
ta.selectionStart = ta.selectionEnd = start + 2;
ta.focus();
return new_text;
}
"""
with gr.Blocks(theme="default", css=custom_css) as iface:
gr.Markdown("## 🎙️ 나만의 TTS 전처리 변환기 (프롬프터 모드)")
with gr.Tabs():
with gr.Tab("🎙️ 메인 화면"):
with gr.Row():
with gr.Column():
input_text = gr.Textbox(label="1️⃣ 원본 텍스트 입력", elem_id="input_text_area")
with gr.Group():
gr.Markdown("**⚙️ 변환 및 화면 설정**")
ai_mode = gr.Radio(choices=["끄기 (수동 사전만 적용)", "순한 맛 (단어별 끊기 - 과도한 연음 방지)", "매운 맛 (문장 통째로 - 자연스러운 연음)"], value="끄기 (수동 사전만 적용)", label="🤖 AI 발음 변환 강도 선택")
auto_break = gr.Checkbox(label="📖 문장 끝에서 자동으로 줄바꿈 하기", value=False)
smart_pause = gr.Checkbox(label="⏱️ 스마트 프롬프터 호흡점 ( / ) 추가하기 (쉼표 뒤)", value=False)
btn_insert_marker = gr.Button("🚨 커서 위치에 마커(@@) 삽입하기", variant="secondary", size="sm")
font_size = gr.Slider(minimum=16, maximum=40, value=22, step=2, label="🔍 결과창 글자 크기 조절")
char_count = gr.Textbox(label="글자 수 확인", value="공백 포함: 0자 / 공백 제외: 0자", interactive=False)
with gr.Row():
btn_conv = gr.Button("✨ 변환하기", variant="primary")
btn_copy = gr.Button("📋 변환복사", variant="secondary")
btn_clr = gr.Button("🗑️ 대본 초기화", variant="stop")
with gr.Column():
initial_html = '📺 프롬프터 뷰 (변경점 확인)
'
output_html = gr.HTML(value=initial_html, elem_id="prompter_html_wrap")
with gr.Accordion("📂 순수 텍스트 결과 (복사용) - 클릭해서 펼치기", open=False):
output_text = gr.Textbox(lines=8, show_label=False, show_copy_button=True, elem_id="output_text_area")
marker_collection = gr.Textbox(label="🚨 수정 필요 단어 모아보기 (@@)", interactive=False, lines=2)
gr.Markdown("---")
gr.Markdown("**💡 나만의 발음 사전 추가** (※ 1글자 단어는 원본 훼손을 막기 위해 등록 불가합니다!)")
with gr.Row():
nw = gr.Textbox(label="기존 단어 또는 문장 (2글자 이상)")
np = gr.Textbox(label="원하는 발음")
with gr.Column(min_width=200):
btn_add = gr.Button("💾 사전에 추가하고 즉시 대본 변환하기", variant="primary")
btn_clear_dict_inputs = gr.Button("🧹 단어 입력칸 비우기", variant="secondary")
status = gr.Textbox(label="저장 상태 결과창", interactive=False)
btn_insert_marker.click(fn=None, inputs=[input_text], outputs=[input_text], js=insert_marker_js, api_name=False)
btn_insert_marker.click(fn=process_text, inputs=[input_text, ai_mode, auto_break, smart_pause, font_size], outputs=[output_text, output_html, char_count, marker_collection], api_name=False)
btn_conv.click(fn=process_text, inputs=[input_text, ai_mode, auto_break, smart_pause, font_size], outputs=[output_text, output_html, char_count, marker_collection], api_name=False)
btn_clr.click(fn=clear_all, outputs=[input_text, output_text, output_html, char_count, marker_collection], api_name=False)
btn_copy.click(fn=None, inputs=[output_text], outputs=None, js="(text) => { if(text) { navigator.clipboard.writeText(text); alert('✅ 복사 완료!'); } }", api_name=False)
font_size.change(fn=process_text, inputs=[input_text, ai_mode, auto_break, smart_pause, font_size], outputs=[output_text, output_html, char_count, marker_collection], api_name=False)
ai_mode.change(fn=process_text, inputs=[input_text, ai_mode, auto_break, smart_pause, font_size], outputs=[output_text, output_html, char_count, marker_collection], api_name=False)
auto_break.change(fn=process_text, inputs=[input_text, ai_mode, auto_break, smart_pause, font_size], outputs=[output_text, output_html, char_count, marker_collection], api_name=False)
smart_pause.change(fn=process_text, inputs=[input_text, ai_mode, auto_break, smart_pause, font_size], outputs=[output_text, output_html, char_count, marker_collection], api_name=False)
btn_add.click(fn=add_and_update, inputs=[nw, np, input_text, ai_mode, auto_break, smart_pause, font_size], outputs=[status, output_text, output_html, char_count, marker_collection], api_name=False)
btn_clear_dict_inputs.click(fn=lambda: ("", ""), outputs=[nw, np], 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("---")
gr.Markdown("### 📝 2. 화면에서 직접 사전 조회/수정/삭제하기 (다운로드 불가 환경용)")
with gr.Row():
btn_load_json = gr.Button("👀 1단계: 현재 등록된 모든 단어 불러오기", variant="secondary")
json_input = gr.Textbox(lines=15, label="여기에 단어들이 표시됩니다. 이상한 단어(예: '이': '종')를 찾아 그 줄을 삭제하세요!")
with gr.Row():
btn_apply_json = gr.Button("🚀 2단계: 기존 단어장에 플러스(+) 하기", variant="primary")
btn_overwrite_json = gr.Button("🚨 2단계: 수정한 내용으로 완전히 덮어쓰기 (기존 삭제)", variant="stop")
json_stat = gr.Textbox(label="상태 결과창", interactive=False)
btn_load_json.click(fn=load_current_json_to_text, outputs=[json_input, json_stat], api_name=False)
btn_apply_json.click(fn=apply_json_text, inputs=[json_input], outputs=[json_stat], api_name=False)
btn_overwrite_json.click(fn=overwrite_json_text, inputs=[json_input], outputs=[json_stat], api_name=False)
gr.Markdown("---")
gr.Markdown("### 📤 3. 백업 파일로 덮어쓰기 (※ 주의: 기존 단어 초기화됨)")
up_file = gr.File(label="백업 파일 업로드", type="filepath")
up_stat = gr.Textbox(label="파일 복구 상태 결과창", interactive=False)
up_file.upload(fn=upload_file, inputs=[up_file], outputs=[up_stat], api_name=False)
iface.load(None, js=script_js)
if __name__ == "__main__":
iface.launch()