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" # ===================================================================== # ★ AI 자동 복구 & 병합 로직 (기존 완벽 유지) ★ # ===================================================================== AUTO_MERGE_WORDS = [["GS마이샵", "지에스마이샵"],["지에스 마이샵", "지에스 마이샵"],["1+1", "원플러스원"],["2+1", "투플러스원"],["F/W", "에프 더블유"],["S/S", "에스 에스"],["VIP", "브이아이피"],["할인가", "하린까"],["특가", "특까"],["최저가", "최저까"],["단독구성", "단독꾸성"],["역대급", "역때끕"],["앱결제", "앱껼제"],["일시불", "일씨불"],["무이자", "무이자"],["매진임박", "매지님박"],["자동주문", "자동주문"],["사은품", "사은품"],["퀄리티를", "퀄리티를"],["디테일이", "디테이리"],["실루엣이", "실루에시"],["커터앤벅", "커터앤벅"],["세르즈블랑코", "세르즈블랑코"],["포머티브", "포머티브"],["빈트릴", "빈트릴"],["레미앤르루", "레미앤르루"],["잭니클라우스", "쟁니클라우스"],["푸마골프", "푸마골프"],["컬럼비아", "컬럼비아"],["에스까다스포츠", "에스까다스포츠"],["에스카다스포츠", "에스까다스포츠"],["쏘울", "쏘울"],["엔니튜드", "엔니튜드"],["라삐아프", "라삐아프"],["모르간", "모르간"],["막스스튜디오", "막쓰스튜디오"],["데일리블루", "데일리블루"],["트라이엄프", "트라이엄프"],["알씨비 폴로클럽", "알씨비 폴로클럽"],["기펠", "기펠"],["샤론느", "샤론느"],["SJ와니", "에스제이와니"],["코어 어센틱", "코어 어센틱"],["르네크루", "르네크루"],["디페", "디페"],["1종", "일종"],["2종", "이종"],["3종", "삼종"],["4종", "사종"],["5종", "오종"],["10종", "십종"],["4in1", "포인원"],["25FW", "이오 에프 더블유"],["25 F/W", "이오 에프 더블유"],["이오 에프떠블유", "이오 에프 더블유"],["26SS", "이십뉵에스에스"],["2026 SS", "이천이십뉵 에스에스"],["SS시즌", "에스에스 시즌"],["셋업", "세덥"],["리버시블", "리버시블"],["맨투맨", "맨투맨"],["윈터팬츠", "윈터팬츠"],["본딩팬츠", "본딩팬츠"],["스윙자켓", "스윙자켓"],["하이브리드", "하이브리드"],["레이어링", "레이어링"],["레이어드", "레이어드"],["숄카라", "숄카라"],["인타샤", "인타샤"],["덕다운패딩", "덕따운패딩"],["덕다운스커트", "덕따운스커트"],["그레이지", "그레이지"],["트윌", "트윌"],["홀가먼트", "홀가먼트"],["플러피", "플러피"],["노르딕", "노르딕"],["울블렌드", "울블렌드"],["라쿤 블렌드", "라쿤 블렌드"],["세이지그린", "세이지그린"],["모브와인", "모브와인"],["크로쉐", "크로셰"],["레이스 퓨징", "레이스 퓨징"],["시어서커", "시어서커"],["핸디 스타일러", "핸디 스타일러"],["아일렛", "아일렛"],["시어 블레이저", "시어 블레이저"],["틸블루", "틸블루"],["에어리", "에어리"],["핀턱", "핀턱"],["슬리브리스", "슬리브리스"],["튤 레이어드", "튤 레이어드"],["쉬폰", "쉬폰"],["잉크블랙", "잉크블랙"],["썸머브라운", "썸머브라운"],["블룸핑크", "블룸핑크"],["미스트블루", "미스트블루"],["르네베이지", "르네베이지"],["썸머카키", "썸머카키"],["인피니티블루", "인피니티블루"],["르네블랙", "르네블랙"],["블룸화이트", "블룸화이트"],["썸머네이비", "썸머네이비"],["블라썸핑크", "블라썸핑크"],["썸머베이지", "썸머베이지"],["딥와인", "딥와인"],["100프로", "백프로"],["100%", "백프로"],["86%", "팔십육프로"],["14%", "십사프로"],["1,499,900원", "백사십구만 구천구백 원"],["169,900원", "십육만 구천구백 원"],["159,900원", "십오만 구천구백 원"],["149,000원", "십사만 구천 원"],["12만 9천 8백 원", "십이만 구천팔백 원"],["10만 9천원", "십만 구천원"],["89,900원", "팔만 구천구백 원"],["79,900원", "칠만 구천구백 원"],["79,900 원", "칠만 구천구백 원"],["6만 9천 9백 원", "육만 구천구백 원"],["69,900원", "육만 구천구백 원"],["69,900 원", "육만 구천구백 원"],["3만 6천원대", "삼만 육천원대"] ] 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 process_text(input_text, use_g2p, auto_break, font_size): if not input_text or not input_text.strip(): return "", "", "입력 글자 수: 0자" char_count = f"입력 글자 수: {len(input_text)}자" flat_dict = load_dict() if not flat_dict: final_text = input_text if use_g2p and g2p is not None: try: final_text = g2p(input_text) except: pass 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: if use_g2p and g2p is not None: try: parts.append(g2p(chunk)) except: parts.append(chunk) else: parts.append(chunk) matched_word = match.group() parts.append(flat_dict[matched_word]) last_end = end tail = input_text[last_end:] if tail: if use_g2p and g2p is not None: try: parts.append(g2p(tail)) except: parts.append(tail) else: parts.append(tail) final_text = "".join(parts) 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}') html_output = f'''
📺 프롬프터 뷰 (변경점 확인)
{"".join(html_parts)}
''' return final_text, html_output, char_count def clear_all(): return "", "", "", "입력 글자 수: 0자" def add_and_update(word, pronun, current_input, use_g2p, auto_break, font_size): if not word or not pronun: return "⚠️ 기존 단어와 원하는 발음을 모두 입력하세요.", gr.update(), gr.update(), gr.update() word = word.strip() pronun = pronun.strip() 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) if current_input and word not in current_input: status_msg = f"⚠️ 사전 저장 완료! 하지만 원본 텍스트에 '{word}'(이)가 없어 화면에 변화가 없습니다." else: 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 = process_text(current_input, use_g2p, auto_break, font_size) return status_msg, final_text, html_output, char_count else: return status_msg, "", "", "입력 글자 수: 0자" 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 "⚠️ 파일이 없습니다." 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 "⚠️ 올바른 사전 형식이 아닙니다. ('items' 키가 없습니다)" 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 item in new_data.get("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"✅ 기존 단어를 유지하며 {len(new_data.get('items',[]))}개의 단어를 성공적으로 플러스(+) 했습니다!" except Exception as e: return f"❌ JSON 파싱 에러: {e}" # ★ 핵심! 들여쓰기 원인(max-width)을 무력화하고 양쪽을 100% 동일하게 세팅하는 완벽 CSS ★ custom_css = """ /* Gradio의 HTML 컴포넌트가 강제로 폭을 좁히고 중앙 정렬하는 악성 기본값을 완벽히 무력화합니다! */ #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 { 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; font-family: inherit !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); } """ 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("**⚙️ 변환 및 화면 설정**") use_g2p = gr.Checkbox(label="🤖 AI 발음 변환 켜기 (연음 처리용)", value=False) auto_break = gr.Checkbox(label="📖 문장 끝에서 자동으로 줄바꿈 하기", value=True) font_size = gr.Slider(minimum=16, maximum=40, value=22, step=2, label="🔍 결과창 글자 크기 조절") char_count = gr.Textbox(label="글자 수 확인", value="입력 글자 수: 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 = '
📺 프롬프터 뷰 (변경점 확인)
' # ★ 변경된 부분: elem_id="prompter_html_wrap" 를 부여해서 Gradio의 강제 중앙정렬/폭제한 속성을 CSS로 무력화합니다! ★ 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") btn_conv.click(fn=process_text, inputs=[input_text, use_g2p, auto_break, font_size], 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) 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, use_g2p, auto_break, font_size], outputs=[output_text, output_html, char_count], api_name=False ).then( fn=None, inputs=[font_size], js="(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'; } " "}" ) auto_break.change(fn=process_text, inputs=[input_text, use_g2p, auto_break, font_size], outputs=[output_text, output_html, char_count], api_name=False) gr.Markdown("---") with gr.Row(): nw = gr.Textbox(label="기존 단어 또는 문장 (★반드시 1번 창에서 복사해오세요★)") 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_add.click( fn=add_and_update, inputs=[nw, np, input_text, use_g2p, auto_break, font_size], outputs=[status, output_text, output_html, char_count], 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. 코드를 복사해서 직접 붙여넣기") json_input = gr.Textbox(lines=10, label="여기에 추출된 JSON 코드를 붙여넣으세요") btn_apply_json = gr.Button("🚀 기존 단어장에 플러스(+) 하기", variant="primary") json_stat = gr.Textbox(label="복구 상태 결과창", interactive=False) btn_apply_json.click(fn=apply_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()