Spaces:
Running
Running
Update app.py
Browse files5 unmodified lines678910111213141516171821 unmodified lines4041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091104 unmodified lines1151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372386 unmodified lines24524624724824925025125215 unmodified lines2682692702712722732743 unmodified lines2782792802812822832842852862872882892902912922932945 unmodified linesimport htmlfrom functools import lru_cachetry:from g2pk import G2pexcept ImportError:G2p = None# =========================================================# 1. ๊ธฐ๋ณธ ์ค์ ๋ฐ ๋ฐ์ดํฐ (โ ๊ธฐ์กด ๋จ์ด 100% ์๊ตฌ ๋ณต๊ตฌ ์๋ฃ!)# =========================================================dict_path = "custom_dict.json"21 unmodified linesBLOCK_WORDS = {"์ด", "๊ฐ", "์", "๋", "์", "๋ฅผ", "ํ๋ค", "์๋ค", "์ ๋ง", "์ง์ง"}# =========================================================# 2. G2P ๋ฐ ์ฌ์ ๋ชจ๋# =========================================================g2p = G2p() if G2p else None@lru_cache(maxsize=5000)def cached_g2p(text):if g2p is None or not text: return texttry: return g2p(text)except: return textdef apply_g2p(text, mode):if not text: return textif g2p is None or mode == "๋๊ธฐ (์๋ ์ฌ์ ๋ง ์ ์ฉ)": return textif mode == "๋งค์ด ๋ง (๋ฌธ์ฅ ํต์งธ๋ก - ์์ฐ์ค๋ฌ์ด ์ฐ์)": return cached_g2p(text)return "".join(cached_g2p(w) if w.strip() else w for w in re.split(r'(\s+)', text))class DictStore:def __init__(self, path, auto_words):self.path, self.auto_words = path, auto_wordsself.mtime, self.dict_map, self.pattern = None, {}, Noneself.ensure_file()self.reload(force=True)def ensure_file(self):if not os.path.exists(self.path):with open(self.path, "w", encoding="utf-8") as f:json.dump({"items": [], "meta": {"count": 0}}, f, ensure_ascii=False, indent=2)def reload(self, force=False):self.ensure_file()try: current_mtime = os.path.getmtime(self.path)except: current_mtime = Noneif not force and self.mtime == current_mtime: returntry:with open(self.path, "r", encoding="utf-8") as f: data = json.load(f)except: data = {"items": []}d = {str(i[0]).strip(): str(i[1]).strip() for i in data.get("items", []) if isinstance(i, list) and len(i) == 2 and str(i[0]).strip()}for k, v in self.auto_words: d[k.strip()] = v.strip()self.dict_map = dself.pattern = re.compile("|".join(map(re.escape, sorted(d.keys(), key=len, reverse=True)))) if d else Noneself.mtime = current_mtimedef get_map(self): self.reload(); return self.dict_mapdef get_pattern(self): self.reload(); return self.patterndef save_pairs(self, pairs, merge=False):self.reload()base = dict(self.dict_map) if merge else {}for i in pairs:if isinstance(i, list) and len(i) == 2 and str(i[0]).strip(): base[str(i[0]).strip()] = str(i[1]).strip()for k, v in self.auto_words: base[k.strip()] = v.strip()final_items = [[k, v] for k, v in base.items()]with open(self.path, "w", encoding="utf-8") as f: json.dump({"items": final_items}, f, ensure_ascii=False, indent=2)self.reload(force=True)def add(self, word, pronun): self.save_pairs([[word, pronun]], merge=True)def export_text(self): self.reload(); return json.dumps({"items": self.dict_map}, ensure_ascii=False, indent=4)dict_store = DictStore(dict_path, AUTO_MERGE_WORDS)# =========================================================# 3. ์ ํธ ๋ฐ ํต์ฌ ์์ง# =========================================================def normalize_text(text): return (text or "").replace("\r\n", "\n").replace("\r", "\n")def safe_html(text): return html.escape(text).replace("\n", "<br>")def build_count_text(o, f):o, f = normalize_text(o), normalize_text(f)return f"์๋ณธ ๊ณต๋ฐฑ ํฌํจ: {len(o)}์ / ๊ณต๋ฐฑ ์ ์ธ: {len(o.replace(' ', '').replace(chr(10), ''))}์\n๋ณํ ํ ๊ณต๋ฐฑ ํฌํจ: {len(f)}์ / ๊ณต๋ฐฑ ์ ์ธ: {len(f.replace(' ', '').replace(chr(10), ''))}์"def extract_markers(text):4 unmodified linesreturn " / ".join(seen) if seen else "ํ์๋ ๋ง์ปค(@@)๊ฐ ์์ต๋๋ค."def protect_tokens(text):protected, idx = {}, [0]def repl(m):k = f"__P{idx[0]}__"; protected[k] = m.group(0); idx[0] += 1; return kfor p in [r'https?://\S+', r'\b\S+@\S+\.\S+\b', r'\b\d{2,4}-\d{3,4}-\d{4}\b', r'[^\s]*@@[^\s]*']: text = re.sub(p, repl, text)return text, protecteddef restore_tokens(text, protected):for k, v in protected.items(): text = text.replace(k, v)return textDIGITS, SMALL_UNITS, LARGE_UNITS = ["์", "์ผ", "์ด", "์ผ", "์ฌ", "์ค", "์ก", "์น ", "ํ", "๊ตฌ"], ["์ฒ", "๋ฐฑ", "์ญ", ""], ["", "๋ง", "์ต", "์กฐ"]def read_four_digits(n): return "".join(SMALL_UNITS[i] if d==1 and SMALL_UNITS[i] else DIGITS[d]+SMALL_UNITS[i] for i, d in enumerate(map(int, str(n).zfill(4))) if d!=0)def number_to_korean(n):try: n = int(str(n).replace(",", ""))except: return str(n)if n == 0: return "์"s = str(n)groups = [s[max(0, i-4):i] for i in range(len(s), 0, -4)][::-1]return " ".join(large if (read := read_four_digits(int(g))) == "์ผ" and large else read + large for i, g in enumerate(groups) if int(g) != 0 for large in [LARGE_UNITS[len(groups) - i - 1]]).strip()def counter_to_korean(n, unit):try: n = int(str(n).replace(",", ""))except: return str(n)if unit in {"๊ฐ", "ํฉ", "์ธํธ", "๋ณ", "ํฌ", "๋งค"} and 1 <= n <= 20:return {1:"ํ", 2:"๋", 3:"์ธ", 4:"๋ค", 5:"๋ค์ฏ", 6:"์ฌ์ฏ", 7:"์ผ๊ณฑ", 8:"์ฌ๋", 9:"์ํ", 10:"์ด", 11:"์ดํ", 12:"์ด๋", 13:"์ด์ธ", 14:"์ด๋ค", 15:"์ด๋ค์ฏ", 16:"์ด์ฌ์ฏ", 17:"์ด์ผ๊ณฑ", 18:"์ด์ฌ๋", 19:"์ด์ํ", 20:"์ค๋ฌด"}[n]return number_to_korean(n)def apply_rules(text):if not text: return textfor p, r in {r'\b1\+1\b': "์ํ๋ฌ์ค์", r'\b2\+1\b': "ํฌํ๋ฌ์ค์", r'\bS/S\b': "์์ค์์ค", r'\bF/W\b': "์ํ๋๋ธ์ ", r'\bSS\b': "์์ค์์ค", r'\bFW\b': "์ํ๋๋ธ์ ", r'\bUV\b': "์ ๋ธ์ด", r'\bLED\b': "์์ด๋", r'\bVIP\b': "๋ธ์ด์์ดํผ", r'\bA/S\b': "์์ด์์ค", r'\bAS\b': "์์ด์์ค"}.items(): text = re.sub(p, r, text)text = re.sub(r'\b(\d{2})\s*(SS|S/S)\b', lambda m: f"{number_to_korean(m.group(1))} ์์ค์์ค", text)text = re.sub(r'\b(\d{2})\s*(FW|F/W)\b', lambda m: f"{number_to_korean(m.group(1))} ์ํ๋๋ธ์ ", text)text = re.sub(r'(\d+)\s*%', lambda m: f"{number_to_korean(m.group(1))} ํผ์ผํธ", text)text = re.sub(r'(\d{1,3}(?:,\d{3})+|\d+)\s*์', lambda m: f"{number_to_korean(m.group(1))} ์", text)text = re.sub(r'\b(55|66|77|88)\s*์ฌ์ด์ฆ\b', lambda m: f"{dict(zip(['55','66','77','88'],['์ค์ค','์ก์ก','์น ์น ','ํํ']))[m.group(1)]} ์ธ์ด์ฆ", text)def ur(m):n, u = m.group(1), m.group(2)if u in {"๊ฐ", "ํฉ", "์ธํธ", "๋ณ", "ํฌ", "๋งค"}: return f"{counter_to_korean(n, u)} {u}"if u == "๊ฐ์": return f"{number_to_korean(n)}๊ฐ์"return f"{number_to_korean(n)} {{'๋ ':'๋ ','์ข ':'์ข ','๋ถ':'๋ถ','์ด':'์ด','์๊ฐ':'์๊ฐ','ml':'๋ฐ๋ฆฌ๋ฆฌํฐ','mL':'๋ฐ๋ฆฌ๋ฆฌํฐ','ML':'๋ฐ๋ฆฌ๋ฆฌํฐ','L':'๋ฆฌํฐ','kg':'ํฌ๋ก๊ทธ๋จ','g':'๊ทธ๋จ','cm':'์ผํฐ๋ฏธํฐ','mm':'๋ฐ๋ฆฌ๋ฏธํฐ'}}.get(u, u)"return re.sub(r'(\d+)\s*(๊ฐ์|๋ |๊ฐ|์ข |ํฉ|์ธํธ|๋ณ|ํฌ|๋งค|๋ถ|์ด|์๊ฐ|ml|mL|ML|L|kg|g|cm|mm)\b', ur, text)def replace_dict_and_transform(text, ai_mode):d, p = dict_store.get_map(), dict_store.get_pattern()if not d or not p: return "".join(apply_g2p(apply_rules(c), ai_mode) if not re.fullmatch(r'__P\d+__', c) else c for c in re.split(r'(__P\d+__)', text) if c)parts, last = [], 0for m in p.finditer(text):if m.start() > last: parts.extend(apply_g2p(apply_rules(c), ai_mode) if not re.fullmatch(r'__P\d+__', c) else c for c in re.split(r'(__P\d+__)', text[last:m.start()]) if c)parts.append(d.get(m.group(0), m.group(0))); last = m.end()if last < len(text): parts.extend(apply_g2p(apply_rules(c), ai_mode) if not re.fullmatch(r'__P\d+__', c) else c for c in re.split(r'(__P\d+__)', text[last:]) if c)return "".join(parts)def process_text(input_text, ai_mode, auto_break, smart_pause, font_size):if not (input_text := normalize_text(input_text)).strip(): return "", f'<div id="prompter_output_div" style="font-size:{font_size}px;"></div>', "์๋ณธ 0์ / ๋ณํ 0์", "๋ง์ปค ์์", "", ""try:pt, pm = protect_tokens(input_text)ft = restore_tokens(replace_dict_and_transform(pt, ai_mode), pm)if smart_pause: ft = re.sub(r'\s*/\s*/\s*', ' / ', re.sub(r'\s(๊ทธ๋ฆฌ๊ณ |ํ์ง๋ง|๊ทธ๋์|ํนํ|๋ํ|๋ค๋ง)\s', r' / \1 ', re.sub(r',\s*', ', / ', ft)))if auto_break: ft = re.sub(r',\s*/\s*', ',\n', re.sub(r'([.?!])\s+', r'\1\n\n', ft))ft = re.sub(r'\n{3,}', '\n\n', ft.strip())rh = safe_html(ft) if len(input_text)+len(ft)>45000 else "".join(safe_html(ft[j1:j2]) if t=="equal" else f'<span style="background-color:#ffe066; font-weight:bold; color:#000;">{safe_html(ft[j1:j2])}</span>' for t, i1, i2, j1, j2 in difflib.SequenceMatcher(None, input_text, ft).get_opcodes())rh = re.sub(r'([^\s<]*@@[^\s<]*)', r'<span style="background-color:#ff4d4d; color:white; padding:2px;">\1</span>', rh)return ft, f'<div id="prompter_output_div" style="font-size:{font_size}px;">{rh}</div>', build_count_text(input_text, ft), extract_markers(input_text), input_text, ftexcept Exception as e: return input_text, f'<div id="prompter_output_div">์ค๋ฅ: {e}</div>', "์ค๋ฅ", "์ค๋ฅ", input_text, input_text# =========================================================# 4. ์ฌ์ ๊ด๋ฆฌ ๋ฐ ๊ธฐํ API# =========================================================def validate_word(w):w = (w or "").strip()return (False, "๋จ์ด ์ ๋ ฅ ์๋ง") if not w else (False, "1๊ธ์ ๋ถ๊ฐ") if len(w)==1 else (False, "๋ฒ์ฉ๋จ์ด ๋ถ๊ฐ") if w in BLOCK_WORDS else (True, "")def add_and_update(w, p, ci, am, ab, sp, fs):w, p = (w or "").strip(), (p or "").strip()ok, msg = validate_word(w)if not w or not p or not ok: return msg if not ok else "๋ชจ๋ ์ ๋ ฅ ์๋ง", *process_text(ci, am, ab, sp, fs)dict_store.add(w, p)return f"โ '{w}' ์ ์ฅ๋จ!", *process_text(ci, am, ab, sp, fs)def r_html(o, f, fs): return process_text(o, "๋๊ธฐ (์๋ ์ฌ์ ๋ง ์ ์ฉ)", False, False, fs)[1]def load_json(): return dict_store.export_text(), "๋ถ๋ฌ์ด!"def app_json(j): dict_store.save_pairs([[k, v] for i in json.loads(j)["items"] for k, v in (i.items() if isinstance(json.loads(j)["items"], dict) else [i])], True); return "ํ๋ฌ์ค ์๋ฃ!"def over_json(j): dict_store.save_pairs([[k, v] for i in json.loads(j)["items"] for k, v in (i.items() if isinstance(json.loads(j)["items"], dict) else [i])], False); return "๋ฎ์ด์ฐ๊ธฐ ์๋ฃ!"def get_file(): return dict_path if os.path.exists(dict_path) else Nonedef upload_file(file_path):try:with open(file_path, "r", encoding="utf-8") as f: data = json.load(f)dict_store.save_pairs([[k, v] for i in data["items"] for k, v in (i.items() if isinstance(data["items"], dict) else [i])], False)return "โ ํ์ผ ๋ณต๊ตฌ ์๋ฃ!"except Exception as e: return f"โ ๋ณต๊ตฌ ์คํจ: {e}"# =========================================================# 5. CSS / JS# =========================================================custom_css = """#prompter_html_wrap { width: 100% !important; margin: 0 !important; }#input_text_area textarea, #output_text_area textarea, #prompter_output_div { font-family: sans-serif !important; height: 500px !important; overflow-y: auto !important; padding: 16px !important; line-height: 1.8 !important; white-space: pre-wrap !important; }#prompter_output_div { background-color: #333 !important; color: #fff !important; border-radius: 8px !important; border: 1px solid #555; }"""js_sync = """() => {setTimeout(()=> {let t1=document.querySelector('#input_text_area textarea'); if(t1) t1.style.fontSize='22px';let t2=document.querySelector('#output_text_area textarea'); if(t2){ t2.style.fontSize='22px'; t2.style.lineHeight='1.8';}}, 500);}"""js_marker = "(t) => { let ta = document.querySelector('#input_text_area textarea'); if (!ta) return t; let s = ta.selectionStart, e = ta.selectionEnd, v = ta.value; ta.value = v.substring(0, s) + '@@' + v.substring(e); ta.dispatchEvent(new Event('input', { bubbles: true })); ta.selectionStart = ta.selectionEnd = s + 2; ta.focus(); return ta.value; }"js_copy = "(t) => { if(t){ navigator.clipboard.writeText(t); alert('๋ณต์ฌ ์๋ฃ!'); } }"# =========================================================# 6. UI ๊ตฌ์ฑ (๋ก๊ทธ์ธ ์ ๊ฑฐ, ์ฆ์ ๋ ๋๋ง)# =========================================================with gr.Blocks(theme="default", css=custom_css) as iface:gr.Markdown("## ๐๏ธ ๋๋ง์ TTS ์ ์ฒ๋ฆฌ ๋ณํ๊ธฐ")last_o, last_f = gr.State(""), gr.State("")with gr.Tabs():6 unmodified linessmart_p = gr.Checkbox(label="โฑ๏ธ ํธํก์ ( / ) ์ถ๊ฐ", value=False)btn_mk = gr.Button("๐จ ๋ง์ปค(@@) ์ฝ์ ", size="sm")fs = gr.Slider(16, 40, 22, step=2, label="๐ ๊ธ์ ํฌ๊ธฐ")# ๋๊ตฌ๋ ์ธ ์ ์์ง๋ง ๋์ ๋ ๋๋๋ก ์ ์ด๋with gr.Accordion("โ๏ธ ๊ณ ๊ธ ์ค์ (AI ๋ฐ์ ๋ณํ๊ธฐ)", open=False):ai_m = gr.Radio(["๋๊ธฐ (์๋ ์ฌ์ ๋ง ์ ์ฉ)", "์ํ ๋ง (๋จ์ด๋ณ ๋๊ธฐ)", "๋งค์ด ๋ง (๋ฌธ์ฅ ํต์งธ๋ก)"], value="๋๊ธฐ (์๋ ์ฌ์ ๋ง ์ ์ฉ)", label="๐ค AI ๊ฐ๋")15 unmodified linesbtn_add = gr.Button("๐พ ์ ์ฅ ํ ์ฆ์ ๋ณํ", variant="primary")stat = gr.Textbox(label="์ํ", interactive=False)# ์ด๋ฒคํธ ์ฐ๊ฒฐbtn_mk.click(None, in_txt, in_txt, js=js_marker).then(process_text, [in_txt, ai_m, auto_b, smart_p, fs], [out_txt, out_html, cnt, mk_col, last_o, last_f])btn_conv.click(process_text, [in_txt, ai_m, auto_b, smart_p, fs], [out_txt, out_html, cnt, mk_col, last_o, last_f])btn_clr.click(lambda: ("","",'<div id="prompter_output_div"></div>',"","","",""), None, [in_txt, out_txt, out_html, cnt, mk_col, last_o, last_f])3 unmodified linesbtn_add.click(add_and_update, [nw, np, in_txt, ai_m, auto_b, smart_p, fs], [stat, out_txt, out_html, cnt, mk_col, last_o, last_f])with gr.Tab("๐ฅ ๋ฐฑ์ /์กฐํ"):dl_btn = gr.DownloadButton("๐ฅ ๋ฐฑ์ ํ๊ธฐ")dl_btn.click(get_file, None, dl_btn)json_in, j_stat = gr.Textbox(lines=10, label="๋ฐ์ดํฐ"), gr.Textbox(label="์ํ")with gr.Row():btn_ld, btn_ap, btn_ov = gr.Button("๐ ๋ถ๋ฌ์ค๊ธฐ"), gr.Button("๐ ํ๋ฌ์ค"), gr.Button("๐จ ๋ฎ์ด์ฐ๊ธฐ")btn_ld.click(load_json, None, [json_in, j_stat])btn_ap.click(app_json, json_in, j_stat)btn_ov.click(over_json, json_in, j_stat)up_file = gr.File(label="๋ฐฑ์ ํ์ผ ์ ๋ก๋")up_stat = gr.Textbox(label="์ํ")up_file.upload(upload_file, up_file, up_stat)5 unmodified lines678910111213141516171819202122232421 unmodified lines4647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741754 unmodified lines1801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563576 unmodified lines36436536636736836915 unmodified lines3853863873883893903 unmodified lines3943953963973983994004014024034044054064075 unmodified linesimport htmlfrom functools import lru_cache# โ ํ๊น ํ์ด์ค ํด๋ผ์ฐ๋ ์๊ตฌ ์ ์ฅ์ฉtry:from huggingface_hub import HfApiexcept ImportError:HfApi = Nonetry:from g2pk import G2pexcept ImportError:G2p = None# =========================================================# 1. ๊ธฐ๋ณธ ์ค์ ๋ฐ ๋จ์ด ๋ฐ์ดํฐ# =========================================================dict_path = "custom_dict.json"21 unmodified linesBLOCK_WORDS = {"์ด", "๊ฐ", "์", "๋", "์", "๋ฅผ", "ํ๋ค", "์๋ค", "์ ๋ง", "์ง์ง"}# =========================================================# 2. G2P ๋ฐ ์ฌ์ ์บ์ (ํด๋ผ์ฐ๋ ๋๊ธฐํ ํฌํจ)# =========================================================g2p = Noneif G2p:try:g2p = G2p()except Exception:g2p = None@lru_cache(maxsize=5000)def cached_g2p(text):if g2p is None or not text:return texttry:return g2p(text)except Exception:return textdef apply_g2p(text, mode):if not text: return textif g2p is None or mode == "๋๊ธฐ (์๋ ์ฌ์ ๋ง ์ ์ฉ)": return textif mode == "๋งค์ด ๋ง (๋ฌธ์ฅ ํต์งธ๋ก - ์์ฐ์ค๋ฌ์ด ์ฐ์)": return cached_g2p(text)if mode == "์ํ ๋ง (๋จ์ด๋ณ ๋๊ธฐ - ๊ณผ๋ํ ์ฐ์ ๋ฐฉ์ง)":words = re.split(r'(\s+)', text)out = []for w in words:out.append(cached_g2p(w) if w.strip() else w)return "".join(out)return textclass DictStore:def __init__(self, path, auto_words):self.path = pathself.auto_words = auto_wordsself.mtime = Noneself.dict_map = {}self.pattern = Noneself.ensure_file()self.reload(force=True)def ensure_file(self):if not os.path.exists(self.path):with open(self.path, "w", encoding="utf-8") as f:json.dump({"items": []}, f, ensure_ascii=False, indent=2)def reload(self, force=False):self.ensure_file()try: current_mtime = os.path.getmtime(self.path)except Exception: current_mtime = Noneif not force and self.mtime == current_mtime: returntry:with open(self.path, "r", encoding="utf-8") as f: data = json.load(f)except Exception: data = {"items": []}d = {}for item in data.get("items", []):if isinstance(item, list) and len(item) == 2:k = str(item[0]).strip()v = str(item[1]).strip()if k: d[k] = vfor k, v in self.auto_words:d[k.strip()] = v.strip()self.dict_map = dself.pattern = re.compile("|".join(map(re.escape, sorted(d.keys(), key=len, reverse=True)))) if d else Noneself.mtime = current_mtimedef get_map(self):self.reload()return self.dict_mapdef get_pattern(self):self.reload()return self.patterndef save_pairs(self, pairs, merge=False):self.reload()base = dict(self.dict_map) if merge else {}for item in pairs:if isinstance(item, list) and len(item) == 2:k, v = str(item[0]).strip(), str(item[1]).strip()if k: base[k] = vfor k, v in self.auto_words:base[k.strip()] = v.strip()final_items = [[k, v] for k, v in base.items() if [k, v] not in self.auto_words]with open(self.path, "w", encoding="utf-8") as f:json.dump({"items": final_items}, f, ensure_ascii=False, indent=2)self._sync_to_hub()self.reload(force=True)def _sync_to_hub(self):token = os.environ.get("HF_TOKEN")repo_id = os.environ.get("SPACE_ID")if token and repo_id and HfApi:try:api = HfApi(token=token)api.upload_file(path_or_fileobj=self.path, path_in_repo=self.path, repo_id=repo_id, repo_type="space")print("HF ์๋ ์ ์ฅ ์ฑ๊ณต")except Exception as e:print(f"HF ์๋ ์ ์ฅ ์คํจ: {e}")def add(self, word, pronun):self.save_pairs([[word, pronun]], merge=True)def export_text(self):self.reload()return json.dumps({"items": self.dict_map}, ensure_ascii=False, indent=4)dict_store = DictStore(dict_path, AUTO_MERGE_WORDS)# =========================================================# 3. ํ ์คํธ ๋ณํ ํต์ฌ ์์ง (์์ ํ ์๋ณธ ์ฝ๋)# =========================================================def normalize_text(text):return (text or "").replace("\r\n", "\n").replace("\r", "\n")def safe_html(text):return html.escape(text).replace("\n", "<br>")def build_count_text(original_text, final_text):o, f = normalize_text(original_text), normalize_text(final_text)return f"์๋ณธ ๊ณต๋ฐฑ ํฌํจ: {len(o)}์ / ๊ณต๋ฐฑ ์ ์ธ: {len(o.replace(' ', '').replace(chr(10), ''))}์\n๋ณํ ํ ๊ณต๋ฐฑ ํฌํจ: {len(f)}์ / ๊ณต๋ฐฑ ์ ์ธ: {len(f.replace(' ', '').replace(chr(10), ''))}์"def extract_markers(text):4 unmodified linesreturn " / ".join(seen) if seen else "ํ์๋ ๋ง์ปค(@@)๊ฐ ์์ต๋๋ค."def protect_tokens(text):protected = {}idx = [0]def repl(m):k = f"__P{idx[0]}__"protected[k] = m.group(0)idx[0] += 1return kfor p in [r'https?://\S+', r'\b\S+@\S+\.\S+\b', r'\b\d{2,4}-\d{3,4}-\d{4}\b', r'[^\s]*@@[^\s]*']:text = re.sub(p, repl, text)return text, protecteddef restore_tokens(text, protected):for k, v in protected.items():text = text.replace(k, v)return textDIGITS = ["์", "์ผ", "์ด", "์ผ", "์ฌ", "์ค", "์ก", "์น ", "ํ", "๊ตฌ"]SMALL_UNITS = ["์ฒ", "๋ฐฑ", "์ญ", ""]LARGE_UNITS = ["", "๋ง", "์ต", "์กฐ"]NATIVE_1_20 = {1:"ํ", 2:"๋", 3:"์ธ", 4:"๋ค", 5:"๋ค์ฏ", 6:"์ฌ์ฏ", 7:"์ผ๊ณฑ", 8:"์ฌ๋", 9:"์ํ", 10:"์ด", 11:"์ดํ", 12:"์ด๋", 13:"์ด์ธ", 14:"์ด๋ค", 15:"์ด๋ค์ฏ", 16:"์ด์ฌ์ฏ", 17:"์ด์ผ๊ณฑ", 18:"์ด์ฌ๋", 19:"์ด์ํ", 20:"์ค๋ฌด"}def read_four_digits(n):parts = []for i, d in enumerate(map(int, str(n).zfill(4))):if d == 0: continueparts.append(SMALL_UNITS[i] if d == 1 and SMALL_UNITS[i] else DIGITS[d] + SMALL_UNITS[i])return "".join(parts)def number_to_korean(n):try: n = int(str(n).replace(",", ""))except: return str(n)if n == 0: return "์"s = str(n)groups = [s[max(0, i-4):i] for i in range(len(s), 0, -4)][::-1]result = []for i, g in enumerate(groups):if int(g) == 0: continuer = read_four_digits(int(g))l = LARGE_UNITS[len(groups) - i - 1]result.append(l if r == "์ผ" and l else r + l)return " ".join(result).strip()def counter_to_korean(n, unit):try: n = int(str(n).replace(",", ""))except: return str(n)if unit in {"๊ฐ", "ํฉ", "์ธํธ", "๋ณ", "ํฌ", "๋งค"} and 1 <= n <= 20:return NATIVE_1_20[n]return number_to_korean(n)def apply_rules(text):if not text: return textfixed = {r'\b1\+1\b': "์ํ๋ฌ์ค์", r'\b2\+1\b': "ํฌํ๋ฌ์ค์", r'\bSS\b': "์์ค์์ค", r'\bFW\b': "์ํ๋๋ธ์ ", r'\bS/S\b': "์์ค์์ค", r'\bF/W\b': "์ํ๋๋ธ์ ", r'\bUV\b': "์ ๋ธ์ด", r'\bLED\b': "์์ด๋", r'\bVIP\b': "๋ธ์ด์์ดํผ", r'\bA/S\b': "์์ด์์ค", r'\bAS\b': "์์ด์์ค"}for p, r in fixed.items(): text = re.sub(p, r, text)text = re.sub(r'\b(\d{2})\s*(SS|S/S)\b', lambda m: f"{number_to_korean(m.group(1))} ์์ค์์ค", text)text = re.sub(r'\b(\d{2})\s*(FW|F/W)\b', lambda m: f"{number_to_korean(m.group(1))} ์ํ๋๋ธ์ ", text)text = re.sub(r'(\d+)\s*%', lambda m: f"{number_to_korean(m.group(1))} ํผ์ผํธ", text)text = re.sub(r'(\d{1,3}(?:,\d{3})+|\d+)\s*์', lambda m: f"{number_to_korean(m.group(1))} ์", text)size_map = {"55": "์ค์ค", "66": "์ก์ก", "77": "์น ์น ", "88": "ํํ"}text = re.sub(r'\b(55|66|77|88)\s*์ฌ์ด์ฆ\b', lambda m: f"{size_map[m.group(1)]} ์ธ์ด์ฆ", text)def unit_repl(m):num, unit = m.group(1), m.group(2)if unit in {"๊ฐ", "ํฉ", "์ธํธ", "๋ณ", "ํฌ", "๋งค"}: return f"{counter_to_korean(num, unit)} {unit}"if unit == "๊ฐ์": return f"{number_to_korean(num)}๊ฐ์"unit_map = {"๋ ": "๋ ", "์ข ": "์ข ", "๋ถ": "๋ถ", "์ด": "์ด", "์๊ฐ": "์๊ฐ", "ml": "๋ฐ๋ฆฌ๋ฆฌํฐ", "mL": "๋ฐ๋ฆฌ๋ฆฌํฐ", "ML": "๋ฐ๋ฆฌ๋ฆฌํฐ", "L": "๋ฆฌํฐ", "kg": "ํฌ๋ก๊ทธ๋จ", "g": "๊ทธ๋จ", "cm": "์ผํฐ๋ฏธํฐ", "mm": "๋ฐ๋ฆฌ๋ฏธํฐ"}return f"{number_to_korean(num)} {unit_map.get(unit, unit)}"text = re.sub(r'(\d+)\s*(๊ฐ์|๋ |๊ฐ|์ข |ํฉ|์ธํธ|๋ณ|ํฌ|๋งค|๋ถ|์ด|์๊ฐ|ml|mL|ML|L|kg|g|cm|mm)\b', unit_repl, text)return textdef transform_chunk(chunk, ai_mode):if not chunk: return chunkif re.fullmatch(r'__P\d+__', chunk): return chunkchunk = apply_rules(chunk)chunk = apply_g2p(chunk, ai_mode)return chunkdef replace_dict_and_transform(text, ai_mode):flat_dict = dict_store.get_map()pattern = dict_store.get_pattern()if not flat_dict or pattern is None:parts = re.split(r'(__P\d+__)', text)return "".join(transform_chunk(p, ai_mode) for p in parts if p is not None)parts = []last_end = 0for match in pattern.finditer(text):start, end = match.span()if start > last_end:before = text[last_end:start]before_parts = re.split(r'(__P\d+__)', before)parts.extend(transform_chunk(p, ai_mode) for p in before_parts if p is not None)parts.append(flat_dict.get(match.group(0), match.group(0)))last_end = endif last_end < len(text):tail = text[last_end:]tail_parts = re.split(r'(__P\d+__)', tail)parts.extend(transform_chunk(p, ai_mode) for p in tail_parts if p is not None)return "".join(parts)def process_text(input_text, ai_mode, auto_break, smart_pause, font_size):input_text = normalize_text(input_text)if not input_text.strip():return "", f'<div id="prompter_output_div" style="font-size:{font_size}px;"></div>', "์๋ณธ 0์ / ๋ณํ 0์", "๋ง์ปค ์์", "", ""try:protected_text, protected_map = protect_tokens(input_text)final_text = replace_dict_and_transform(protected_text, ai_mode)final_text = restore_tokens(final_text, protected_map)if smart_pause:final_text = re.sub(r',\s*', ', / ', final_text)final_text = re.sub(r'\s(๊ทธ๋ฆฌ๊ณ |ํ์ง๋ง|๊ทธ๋์|ํนํ|๋ํ|๋ค๋ง)\s', r' / \1 ', final_text)final_text = re.sub(r'\s*/\s*/\s*', ' / ', final_text)if auto_break:final_text = re.sub(r'([.?!])\s+', r'\1\n\n', final_text)final_text = re.sub(r',\s*/\s*', ',\n', final_text)final_text = re.sub(r'\n{3,}', '\n\n', final_text).strip()if len(input_text) + len(final_text) > 45000:raw_html = safe_html(final_text)else:seq = difflib.SequenceMatcher(None, input_text, final_text)html_parts = []for tag, i1, i2, j1, j2 in seq.get_opcodes():chunk = safe_html(final_text[j1:j2])if tag == "equal": html_parts.append(chunk)elif tag in ["replace", "insert"]: html_parts.append(f'<span style="background-color:#ffe066; font-weight:bold; color:#000;">{chunk}</span>')raw_html = "".join(html_parts)raw_html = re.sub(r'([^\s<]*@@[^\s<]*)', r'<span style="background-color:#ff4d4d; color:white; padding:2px;">\1</span>', raw_html)return final_text, f'<div id="prompter_output_div" style="font-size:{font_size}px;">{raw_html}</div>', build_count_text(input_text, final_text), extract_markers(input_text), input_text, final_textexcept Exception as e:return input_text, f'<div id="prompter_output_div">์ค๋ฅ: {e}</div>', "์ค๋ฅ", "์ค๋ฅ", input_text, input_text# =========================================================# 4. ๋ถ๊ฐ ๊ธฐ๋ฅ ๋ฐ UI# =========================================================def validate_word(w):w = (w or "").strip()if not w: return False, "๋จ์ด๋ฅผ ์ ๋ ฅํ์ธ์."if len(w) == 1: return False, "1๊ธ์๋ ๋ถ๊ฐํฉ๋๋ค."if w in BLOCK_WORDS: return False, "๋ฒ์ฉ ๋จ์ด๋ ๋ถ๊ฐํฉ๋๋ค."return True, ""def add_and_update(w, p, ci, am, ab, sp, fs):w, p = (w or "").strip(), (p or "").strip()ok, msg = validate_word(w)if not w or not p or not ok: return msg if not ok else "๋ชจ๋ ์ ๋ ฅํ์ธ์.", *process_text(ci, am, ab, sp, fs)dict_store.add(w, p)return f"โ '{w}' ์ ์ฅ๋จ (ํด๋ผ์ฐ๋ ๋๊ธฐํ ์๋ฃ)", *process_text(ci, am, ab, sp, fs)def r_html(o, f, fs): return process_text(o, "๋๊ธฐ (์๋ ์ฌ์ ๋ง ์ ์ฉ)", False, False, fs)[1]def load_json(): return dict_store.export_text(), "๋ถ๋ฌ์ด!"def app_json(j): dict_store.save_pairs([[k, v] for i in json.loads(j)["items"] for k, v in (i.items() if isinstance(json.loads(j)["items"], dict) else [i])], True); return "ํ๋ฌ์ค ์๋ฃ!"def over_json(j): dict_store.save_pairs([[k, v] for i in json.loads(j)["items"] for k, v in (i.items() if isinstance(json.loads(j)["items"], dict) else [i])], False); return "๋ฎ์ด์ฐ๊ธฐ ์๋ฃ!"def get_file(): return dict_path if os.path.exists(dict_path) else Nonedef upload_file(fp):try:with open(fp, "r", encoding="utf-8") as f: data = json.load(f)dict_store.save_pairs([[k, v] for i in data["items"] for k, v in (i.items() if isinstance(data["items"], dict) else [i])], False)return "โ ํ์ผ ๋ณต๊ตฌ ์๋ฃ!"except Exception as e: return f"โ ๋ณต๊ตฌ ์คํจ: {e}"custom_css = """#prompter_html_wrap { width: 100% !important; margin: 0 !important; }#input_text_area textarea, #output_text_area textarea, #prompter_output_div { font-family: sans-serif !important; height: 500px !important; overflow-y: auto !important; padding: 16px !important; line-height: 1.8 !important; white-space: pre-wrap !important; }#prompter_output_div { background-color: #333 !important; color: #fff !important; border-radius: 8px !important; }"""js_sync = "() => { setTimeout(()=> { let t1=document.querySelector('#input_text_area textarea'); if(t1) t1.style.fontSize='22px'; let t2=document.querySelector('#output_text_area textarea'); if(t2){ t2.style.fontSize='22px'; t2.style.lineHeight='1.8';} }, 500); }"js_marker = "(t) => { let ta = document.querySelector('#input_text_area textarea'); if (!ta) return t; let s = ta.selectionStart, e = ta.selectionEnd, v = ta.value; ta.value = v.substring(0, s) + '@@' + v.substring(e); ta.dispatchEvent(new Event('input', { bubbles: true })); ta.selectionStart = ta.selectionEnd = s + 2; ta.focus(); return ta.value; }"js_copy = "(t) => { if(t){ navigator.clipboard.writeText(t); alert('๋ณต์ฌ ์๋ฃ!'); } }"with gr.Blocks(theme="default", css=custom_css) as iface:gr.Markdown("## ๐๏ธ ๋๋ง์ TTS ์ ์ฒ๋ฆฌ ๋ณํ๊ธฐ")last_o, last_f = gr.State(""), gr.State("")with gr.Tabs():6 unmodified linessmart_p = gr.Checkbox(label="โฑ๏ธ ํธํก์ ( / ) ์ถ๊ฐ", value=False)btn_mk = gr.Button("๐จ ๋ง์ปค(@@) ์ฝ์ ", size="sm")fs = gr.Slider(16, 40, 22, step=2, label="๐ ๊ธ์ ํฌ๊ธฐ")with gr.Accordion("โ๏ธ ๊ณ ๊ธ ์ค์ (AI ๋ฐ์ ๋ณํ๊ธฐ)", open=False):ai_m = gr.Radio(["๋๊ธฐ (์๋ ์ฌ์ ๋ง ์ ์ฉ)", "์ํ ๋ง (๋จ์ด๋ณ ๋๊ธฐ)", "๋งค์ด ๋ง (๋ฌธ์ฅ ํต์งธ๋ก)"], value="๋๊ธฐ (์๋ ์ฌ์ ๋ง ์ ์ฉ)", label="๐ค AI ๊ฐ๋")15 unmodified linesbtn_add = gr.Button("๐พ ์ ์ฅ ํ ์ฆ์ ๋ณํ", variant="primary")stat = gr.Textbox(label="์ํ", interactive=False)btn_mk.click(None, in_txt, in_txt, js=js_marker).then(process_text, [in_txt, ai_m, auto_b, smart_p, fs], [out_txt, out_html, cnt, mk_col, last_o, last_f])btn_conv.click(process_text, [in_txt, ai_m, auto_b, smart_p, fs], [out_txt, out_html, cnt, mk_col, last_o, last_f])btn_clr.click(lambda: ("","",'<div id="prompter_output_div"></div>',"","","",""), None, [in_txt, out_txt, out_html, cnt, mk_col, last_o, last_f])3 unmodified linesbtn_add.click(add_and_update, [nw, np, in_txt, ai_m, auto_b, smart_p, fs], [stat, out_txt, out_html, cnt, mk_col, last_o, last_f])with gr.Tab("๐ฅ ๋ฐฑ์ /์กฐํ"):dl_btn = gr.DownloadButton("๐ฅ ๋ก์ปฌ๋ก ๋ฐฑ์ ํ๊ธฐ")dl_btn.click(get_file, None, dl_btn)json_in, j_stat = gr.Textbox(lines=10, label="๋ฐ์ดํฐ"), gr.Textbox(label="์ํ")with gr.Row():btn_ld, btn_ap, btn_ov = gr.Button("๐ ๋ถ๋ฌ์ค๊ธฐ"), gr.Button("๐ ํ๋ฌ์ค"), gr.Button("๐จ ๋ฎ์ด์ฐ๊ธฐ")btn_ld.click(load_json, None, [json_in, j_stat])btn_ap.click(app_json, json_in, j_stat)btn_ov.click(over_json, json_in, j_stat)up_file = gr.File(label="๋ฐฑ์ ํ์ผ ์ ๋ก๋")up_stat = gr.Textbox(label="์ํ")up_file.upload(upload_file, up_file, up_stat)
app.py+204-91