Spaces:
Running
Running
Update app.py
Browse files1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114121 unmodified lineimport jsonimport osimport difflibimport reimport 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"AUTO_MERGE_WORDS = [["GS๋ง์ด์ต", "์ง์์ค๋ง์ด์ต"], ["GS ๋ง์ด์ต", "์ง์์ค๋ง์ด์ต"],["GS์ต", "์ง์์ค์ต"], ["GS ์ต", "์ง์์ค์ต"],["26SS", "์ด์ญ์ก ์์ค์์ค"], ["26 SS", "์ด์ญ์ก ์์ค์์ค"],["26S/S", "์ด์ญ์ก ์์ค์์ค"], ["26 S/S", "์ด์ญ์ก ์์ค์์ค"],["26FW", "์ด์ญ์ก ์ํ๋๋ธ์ "], ["26 FW", "์ด์ญ์ก ์ํ๋๋ธ์ "],["26F/W", "์ด์ญ์ก ์ํ๋๋ธ์ "], ["26 F/W", "์ด์ญ์ก ์ํ๋๋ธ์ "],["55", "์ค์ค"], ["55์ฌ์ด์ฆ", "์ค์ค ์ธ์ด์ฆ"], ["55 ์ฌ์ด์ฆ", "์ค์ค ์ธ์ด์ฆ"],["66", "์ก์ก"], ["66์ฌ์ด์ฆ", "์ก์ก ์ธ์ด์ฆ"], ["66 ์ฌ์ด์ฆ", "์ก์ก ์ธ์ด์ฆ"],["77", "์น ์น "], ["77์ฌ์ด์ฆ", "์น ์น ์ธ์ด์ฆ"], ["77 ์ฌ์ด์ฆ", "์น ์น ์ธ์ด์ฆ"],["88", "ํํ"], ["88์ฌ์ด์ฆ", "ํํ ์ธ์ด์ฆ"], ["88 ์ฌ์ด์ฆ", "ํํ ์ธ์ด์ฆ"],["100%", "๋ฐฑ ํผ์ผํธ"], ["100 %", "๋ฐฑ ํผ์ผํธ"], ["100ํ๋ก", "๋ฐฑ ํ๋ก"],["59,900์", "์ค๋ง ๊ตฌ์ฒ๊ตฌ๋ฐฑ ์"], ["59,900 ์", "์ค๋ง ๊ตฌ์ฒ๊ตฌ๋ฐฑ ์"],["59900์", "์ค๋ง ๊ตฌ์ฒ๊ตฌ๋ฐฑ ์"], ["59900 ์", "์ค๋ง ๊ตฌ์ฒ๊ตฌ๋ฐฑ ์"],["3๊ฐ์", "์ผ๊ฐ์"], ["3 ๊ฐ์", "์ผ๊ฐ์"],["1๋ง์๋", "๋ง์๋"], ["1๋ง ์๋", "๋ง์๋"], ["1๋ง ์ ๋", "๋ง์๋"],["1+1", "์ํ๋ฌ์ค์"], ["2+1", "ํฌํ๋ฌ์ค์"],["S/S", "์์ค์์ค"], ["F/W", "์ํ๋๋ธ์ "], ["FW", "์ํ๋๋ธ์ "], ["SS", "์์ค์์ค"],["UV", "์ ๋ธ์ด"], ["LED", "์์ด๋"], ["VIP", "๋ธ์ด์์ดํผ"], ["A/S", "์์ด์์ค"]]BLOCK_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):seen = []for m in re.findall(r'[^\s]*@@[^\s]*', text or ""):m = m.strip(".,!?\n ")if m and m not in seen: seen.append(m)return " / ".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():with gr.Tab("๐๏ธ ๋ฉ์ธ ํ๋ฉด"):with gr.Row():with gr.Column():in_txt = gr.Textbox(label="1๏ธโฃ ์๋ณธ ํ ์คํธ", elem_id="input_text_area")with gr.Group():auto_b = gr.Checkbox(label="๐ ๋ฌธ์ฅ ๋ ์๋ ์ค๋ฐ๊ฟ", value=False)smart_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 ๊ฐ๋")cnt = gr.Textbox(label="๊ธ์ ์", interactive=False)with gr.Row():btn_conv = gr.Button("โจ ๋ณํํ๊ธฐ", variant="primary")btn_cp = gr.Button("๐ ๋ณต์ฌ", variant="secondary")btn_clr = gr.Button("๐๏ธ ์ด๊ธฐํ", variant="stop")with gr.Column():out_html = gr.HTML('<div id="prompter_output_div"></div>', elem_id="prompter_html_wrap")with gr.Accordion("๐ ์์ ํ ์คํธ ๊ฒฐ๊ณผ (๋ณต์ฌ์ฉ)", open=False):out_txt = gr.Textbox(lines=8, show_label=False, show_copy_button=True, elem_id="output_text_area")mk_col = gr.Textbox(label="๐จ ์์ ํ์ ๋จ์ด (@@)", interactive=False)gr.Markdown("---")with gr.Row():nw, np = gr.Textbox(label="๊ธฐ์กด ๋จ์ด (2๊ธ์ ์ด์)"), gr.Textbox(label="์ํ๋ ๋ฐ์")btn_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])btn_cp.click(None, out_txt, None, js=js_copy)fs.change(r_html, [last_o, last_f, fs], out_html)for c in [ai_m, auto_b, smart_p]: c.change(process_text, [in_txt, ai_m, auto_b, smart_p, fs], [out_txt, out_html, cnt, mk_col, last_o, last_f])btn_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)iface.load(None, js=js_sync)if __name__ == "__main__":iface.launch()1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374381 unmodified lineimport jsonimport osimport difflibimport shutilimport retry:from g2pk import G2pexcept ImportError:G2p = Noneprint("G2P ๋ชจ๋ธ ๋ก๋ฉ ์ค...")try:if G2p:g2p = G2p()else:g2p = Noneexcept Exception as e:print(f"G2P ๋ก๋ฉ ์คํจ: {e}")g2p = Nonedict_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_itemsexisting_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:passreturn flat_dictdef apply_g2p(text, mode):if g2p is None or mode == "๋๊ธฐ (์๋ ์ฌ์ ๋ง ์ ์ฉ)":return textif mode == "๋งค์ด ๋ง (๋ฌธ์ฅ ํต์งธ๋ก - ์์ฐ์ค๋ฌ์ด ์ฐ์)":try: return g2p(text)except: return textif 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 textdef 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 = 0for 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 = endtail = 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', '<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; color: #000;">{chunk}</span>')raw_html = "".join(html_parts)raw_html = re.sub(r'([^\s<]*@@[^\s<]*)', r'<span style="background-color: #ff4d4d; color: white; font-weight: bold; padding: 2px 6px; border-radius: 4px; box-shadow: 0 0 5px #ff4d4d;">\1</span>', raw_html)html_output = f'<div id="prompter_label_space">๐บ ํ๋กฌํํฐ ๋ทฐ (๋ณ๊ฒฝ์ ํ์ธ)</div><div id="prompter_output_div" style="font-size:{font_size}px;">{raw_html}</div>'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_resultdef 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_resultreturn 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 = Falsefor item in j_struct.get("items",[]):if item[0].strip() == word:item[1] = pronunfound = Truebreakif 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_resultreturn 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_itemsexisting_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 Nonedef 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 = '<div id="prompter_label_space">๐บ ํ๋กฌํํฐ ๋ทฐ (๋ณ๊ฒฝ์ ํ์ธ)</div><div id="prompter_output_div" style="font-size:22px;"></div>'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()
app.py+383-357