Spaces:
Running
Running
Update app.py
Browse files23 unmodified lines2425262728293031323334353637383940414243444546474849505152532 unmodified lines56575859606162636465666768697071727374757677787980818283848586878889909192933 unmodified lines9798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671686 unmodified lines17517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634723 unmodified lines["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 = {"์ด", "๊ฐ", "์", "๋", "์", "๋ฅผ", "ํ๋ค", "์๋ค", "์ ๋ง", "์ง์ง"}# =========================================================# G2P ๋ฐ ์ฌ์ ๋ชจ๋# =========================================================g2p = Noneif G2p:try:g2p = G2p()except Exception:g2p = None@lru_cache(maxsize=5000)def cached_g2p(text):2 unmodified linesexcept: 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 == "์ํ ๋ง (๋จ์ด๋ณ ๋๊ธฐ - ๊ณผ๋ํ ์ฐ์ ๋ฐฉ์ง)":return "".join(cached_g2p(w) if w.strip() else w for w in re.split(r'(\s+)', text))return textclass 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.pattern3 unmodified linesfor 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)# =========================================================# ์ ํธ ๋ฐ ์ซ์ ์๏ฟฝ๏ฟฝ๏ฟฝ# =========================================================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):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] += 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()6 unmodified linesreturn "".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# =========================================================# ์ฌ์ ๊ด๋ฆฌ 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}"# =========================================================# 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; }"""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('๋ณต์ฌ ์๋ฃ!'); } }"# =========================================================# UI ๊ตฌ์ฑ# =========================================================with gr.Blocks(theme="default", css=custom_css) as iface:gr.Markdown("## ๐๏ธ ๋๋ง์ TTS ์ ์ฒ๋ฆฌ ๋ณํ๊ธฐ")# ---------------------------------------------------------# 1. ์ปค์คํ ๋ก๊ทธ์ธ ํ๋ฉด# ---------------------------------------------------------with gr.Column(visible=True) as login_view:gr.Markdown("### ๐ ์ฌ์ฉ์ ์ํด ๋ก๊ทธ์ธํด ์ฃผ์ธ์.")with gr.Row():in_id = gr.Textbox(label="์์ด๋", placeholder="์์ด๋๋ฅผ ์ ๋ ฅํ์ธ์")in_pw = gr.Textbox(label="๋น๋ฐ๋ฒํธ", placeholder="๋น๋ฐ๋ฒํธ๋ฅผ ์ ๋ ฅํ์ธ์", type="password")btn_login = gr.Button("๐ ์ ์ํ๊ธฐ", variant="primary")login_msg = gr.Textbox(label="์๋ฆผ", interactive=False)# ---------------------------------------------------------# 2. ๋ฉ์ธ ์ฑ ํ๋ฉด# ---------------------------------------------------------with gr.Column(visible=False) as main_view: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("โ๏ธ ๊ด๋ฆฌ์ ์ ์ฉ ๊ณ ๊ธ ์ค์ ", open=False, visible=False) as admin_acc: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)# ---------------------------------------------------------# 3. ๋ก๊ทธ์ธ ์ฒ๋ฆฌ ๋ก์ง (์์ธ ๋ถ์ ๋๋ฒ๊น + ์ํฐํค ์ถ๊ฐ)# ---------------------------------------------------------def check_login(user_id, user_pw):secret_str = os.getenv("AUTH_USERS")users_dict = {"a": "1", "User1": "1111"}sys_status = "๊ธฐ๋ณธ ์์๊ณ์ ์๋ ์ค (a/1 ๋๋ User1/1111)"if secret_str:try:users_dict = json.loads(secret_str)sys_status = "ํ๊น ํ์ด์ค ์ํฌ๋ฆฟ ์ ์ ์ฐ๊ฒฐ๋จ"except Exception as e:sys_status = f"๐จ ํ๊น ํ์ด์ค ์ํฌ๋ฆฟ JSON ์์ฑ ์๋ฌ (๋ฐ์ดํ๋ ์ผํ ํ์ธ ์๋ง): {e}"# ๊ณต๋ฐฑ ์ ๊ฑฐ ๋ฐ ์๋ฌธ์ ๋ณํlower_users_dict = {str(k).strip().lower(): str(v).strip() for k, v in users_dict.items()}input_id_lower = str(user_id or "").strip().lower()input_pw = str(user_pw or "").strip()if lower_users_dict.get(input_id_lower) == input_pw:is_admin = (input_id_lower == "a")return gr.update(visible=False), gr.update(visible=True), "โ ๋ก๊ทธ์ธ ์ฑ๊ณต!", gr.update(visible=is_admin)else:err_msg = f"โ ์ ์ ์คํจ.\n[์ ๋ ฅํ ์์ด๋]: '{input_id_lower}'\n[ํ์ฌ ์์คํ ์ํ]: {sys_status}"return gr.update(visible=True), gr.update(visible=False), err_msg, gr.update(visible=False)# ๋ฒํผ ํด๋ฆญ ๋ฐ ์ํฐํค ์น๋ฉด ๋ฐ๋ก ๋ก๊ทธ์ธ ๋๋๋ก ์ค์ btn_login.click(fn=check_login, inputs=[in_id, in_pw], outputs=[login_view, main_view, login_msg, admin_acc])in_pw.submit(fn=check_login, inputs=[in_id, in_pw], outputs=[login_view, main_view, login_msg, admin_acc])iface.load(None, js=js_sync)if __name__ == "__main__":iface.launch()23 unmodified lines2425262728293031323334353637382 unmodified lines41424344454647484950515253545556575859606162636465663 unmodified lines7071727374757677787980818283848586878889909192939495969798991006 unmodified lines10710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219323 unmodified lines["26FW", "์ด์ญ์ก ์ํ๋๋ธ์ "], ["26 FW", "์ด์ญ์ก ์ํ๋๋ธ์ "],["26F/W", "์ด์ญ์ก ์ํ๋๋ธ์ "], ["26 F/W", "์ด์ญ์ก ์ํ๋๋ธ์ "],["55", "์ค์ค"], ["55์ฌ์ด์ฆ", "์ค์ค ์ธ์ด์ฆ"], ["55 ์ฌ์ด์ฆ", "์ค์ค ์ธ์ด์ฆ"],["100%", "๋ฐฑ ํผ์ผํธ"], ["100 %", "๋ฐฑ ํผ์ผํธ"], ["100ํ๋ก", "๋ฐฑ ํ๋ก"],["59,900์", "์ค๋ง ๊ตฌ์ฒ๊ตฌ๋ฐฑ ์"], ["3๊ฐ์", "์ผ๊ฐ์"], ["1+1", "์ํ๋ฌ์ค์"]]BLOCK_WORDS = {"์ด", "๊ฐ", "์", "๋", "์", "๋ฅผ", "ํ๋ค", "์๋ค", "์ ๋ง", "์ง์ง"}# =========================================================# G2P ๋ฐ ์ฌ์ ๋ชจ๋# =========================================================g2p = G2p() if G2p else None@lru_cache(maxsize=5000)def cached_g2p(text):2 unmodified linesexcept: return textdef apply_g2p(text, mode):if not text or 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.dict_map, self.pattern = {}, Noneif not os.path.exists(self.path):with open(self.path, "w", encoding="utf-8") as f: json.dump({"items": []}, f)self.reload()def reload(self):try: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}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 Nonedef get_map(self): self.reload(); return self.dict_mapdef get_pattern(self): self.reload(); return self.pattern3 unmodified linesfor 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()with open(self.path, "w", encoding="utf-8") as f: json.dump({"items": [[k, v] for k, v in base.items()]}, f, ensure_ascii=False, indent=2)self.reload()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)# =========================================================# ์ ํธ ์์ง# =========================================================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 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 textdef 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': "์ํ๋๋ธ์ "}.items(): text = re.sub(p, r, text)return textdef replace_dict_and_transform(text, ai_mode):d, p = dict_store.get_map(), dict_store.get_pattern()6 unmodified linesreturn "".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์", "์์", "", ""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; 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;">\1</span>', rh)return ft, f'<div id="prompter_output_div" style="font-size:{font_size}px;">{rh}</div>', f"๊ธธ์ด: {len(ft)}์", "์๋ฃ", input_text, ftdef add_and_update(w, p, ci, am, ab, sp, fs):w, p = (w or "").strip(), (p or "").strip()if not w or len(w)==1 or w in BLOCK_WORDS: return "๋จ์ด ์ค๋ฅ", *process_text(ci, am, ab, sp, fs)dict_store.add(w, p)return "์ ์ฅ ์๋ฃ", *process_text(ci, am, ab, sp, fs)def get_file(): return dict_path if os.path.exists(dict_path) else Nonedef upload_file(fp):with open(fp, "r", encoding="utf-8") as f: dict_store.save_pairs([[k, v] for i in json.load(f)["items"] for k, v in (i.items() if isinstance(i, dict) else [i])], False)return "๋ณต๊ตฌ ์๋ฃ!"# =========================================================# UI ๊ตฌ์ฑ# =========================================================with gr.Blocks(theme="default") as iface:# 1. ๋ก๊ทธ์ธ ๋ทฐwith gr.Column(visible=True) as login_view:gr.Markdown("### ๐ ์ฌ์ฉ์ ์ํด ๋ก๊ทธ์ธํด ์ฃผ์ธ์.")in_id = gr.Textbox(label="์์ด๋ (์๋ฌธ์๋ก ์ ๋ ฅํด๋ ๋ฉ๋๋ค)")in_pw = gr.Textbox(label="๋น๋ฐ๋ฒํธ", type="password")btn_login = gr.Button("๐ ์ ์ํ๊ธฐ", variant="primary")login_msg = gr.Textbox(label="์ํ ์๋ฆผ์ฐฝ")# 2. ๋ฉ์ธ ๋ทฐwith gr.Column(visible=False) as main_view: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๏ธโฃ ์๋ณธ ํ ์คํธ", lines=10)auto_b = gr.Checkbox(label="๐ ๋ฌธ์ฅ ๋ ์๋ ์ค๋ฐ๊ฟ")smart_p = gr.Checkbox(label="โฑ๏ธ ํธํก์ ( / ) ์ถ๊ฐ")fs = gr.Slider(16, 40, 22, step=2, label="๐ ๊ธ์ ํฌ๊ธฐ")with gr.Accordion("โ๏ธ ๊ด๋ฆฌ์ ์ค์ ", open=False, visible=False) as admin_acc:ai_m = gr.Radio(["๋๊ธฐ (์๋ ์ฌ์ ๋ง ์ ์ฉ)", "์ํ ๋ง (๋จ์ด๋ณ ๋๊ธฐ)", "๋งค์ด ๋ง (๋ฌธ์ฅ ํต์งธ๋ก)"], value="๋๊ธฐ (์๋ ์ฌ์ ๋ง ์ ์ฉ)")btn_conv = gr.Button("โจ ๋ณํํ๊ธฐ", variant="primary")with gr.Column():out_html = gr.HTML('<div id="prompter_output_div" style="height:300px; overflow-y:auto; border:1px solid #ccc; padding:10px;">๊ฒฐ๊ณผ์ฐฝ</div>')out_txt = gr.Textbox(lines=5, label="๋ณต์ฌ์ฉ ํ ์คํธ")cnt = gr.Textbox(label="์ํ")mk_col = gr.Textbox(label="๋ง์ปค")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])with gr.Tab("๐ฅ ๋ฐฑ์ /์กฐํ"):dl_btn = gr.DownloadButton("๐ฅ ๋ฐฑ์ ํ๊ธฐ")dl_btn.click(get_file, None, dl_btn)up_file = gr.File(label="์ ๋ก๋")up_stat = gr.Textbox(label="์ํ")up_file.upload(upload_file, up_file, up_stat)# 3. ๋ก๊ทธ์ธ ์ฒ๋ฆฌ (ํ๋์ฝ๋ฉ - 100% ์๋)def check_login(uid, upw):uid = str(uid).strip().lower()upw = str(upw).strip()# [์ฌ๊ธฐ์ ์์ด๋/๋น๋ฐ๋ฒํธ ํ์ธ!]# a / 1 ๋๋ user1 / 1111 ์ด๋ฉด ํต๊ณผif (uid == "a" and upw == "1") or (uid == "user1" and upw == "1111"):is_admin = (uid == "a")return gr.update(visible=False), gr.update(visible=True), "โ ์ฑ๊ณต", gr.update(visible=is_admin)else:return gr.update(visible=True), gr.update(visible=False), f"โ ์คํจ (์ ๋ ฅ๋ ์์ด๋: {uid}, ๋น๋ฒ: {upw})", gr.update(visible=False)btn_login.click(check_login, [in_id, in_pw], [login_view, main_view, login_msg, admin_acc])in_pw.submit(check_login, [in_id, in_pw], [login_view, main_view, login_msg, admin_acc])if __name__ == "__main__":iface.launch()
app.py+63-217