Spaces:
Running
Running
Update app.py
Browse files17 unmodified lines1819202122238 unmodified lines323334353637166 unmodified lines20420520620720820919 unmodified lines22923023123223323410 unmodified lines24524624724824925025125225325425525625725825926026126226326426526626726810 unmodified lines27928028128228328428528628728828929029129229329429529629729829930030130230330430530614 unmodified lines32132232332432532632732832933033133233333433533633733833934096 unmodified lines4374384394404414424431 unmodified line44544644744844945045145245345422 unmodified lines4774784794804814824838 unmodified lines49249349449549649749838 unmodified lines53753853954054154254317 unmodified lines56156256356456556656756856957057112 unmodified lines58458558658758858959059159259326 unmodified lines62062162262362462562666 unmodified lines69369469569669769855 unmodified lines7547557567577587597603 unmodified lines7647657667677687697705 unmodified lines77677777877978078178278378478578678778878979079179279315 unmodified lines80981081181281381481517 unmodified lines# - λ²νΌ νμ κ°μ scaleΒ·sizeλ‘ ν΅μΌ. μ΄κΈ°ν λ²νΌμ λ§μ§λ§ μλ¦¬λ‘ λ³΅μ.# ============================================================================# ---------- G2P μλ μ ν (g2pk β g2pk2 β g2pkk) ----------g2p = NoneG2P_BACKEND = "μμ"8 unmodified linesprint(f"G2P {_mod} λ‘λ© μ€ν¨: {_e}")dict_path = "custom_dict.json"ADMIN_ID = os.environ.get("ADMIN_ID", "admin")ADMIN_PW = os.environ.get("ADMIN_PW", "admin1234")GUEST_ID = os.environ.get("GUEST_ID", "guest")166 unmodified linesmsg = "λ‘컬 μ μ₯ μλ£ (HF_TOKEN μμ β μ¬μμ μ μ μ€ κ°λ₯)"return f"{msg} Β· νμ¬ μ¬μ {len(dict_map)}κ°"def perform_startup_recovery():dict_map = _read_local_dict()remote_ok = True19 unmodified linesif hf_api and remote_ok:_push_remote()perform_startup_recovery()def load_dict(user_temp_dict=None):10 unmodified lines[v150] 1κΈμ μμ«μ ν€λ λ¨μ΄ κ²½κ³(boundary)λ₯Ό κ°μ ν΄μ'CLASS' κ°μ λ¨μ΄ μ€κ°μμ μ€νλμ§ μκ² νλ€.[v152] μμ νκΈ ν€λ μ’μΈ‘μ νκΈμ΄ μ€λ©΄ λ§€μΉ κΈμ§ β 'μμ€'κ°'ν΄λ¦¬μμ€ν°' κ°μ ν©μ±μ΄ μ€κ°μμ μ€νλμ§ μλλ‘. μ°μΈ‘ κ²½κ³λλμ§ μλλ€ (μ‘°μ¬ 'μμ€λ/μμ€κ°' λ±μ κ·Έλλ‘ μ‘νμΌ νκΈ° λλ¬Έ)."""ordered = sorted(keys, key=lambda x: -len(x.replace(" ", "")))if not ordered:return None, []pats = []for k in ordered:if len(k) == 1 and re.match(r'^[A-Za-z0-9_]$', k):# 1κΈμ μμ«μ: μ’μ° alphanumeric/underscoreκ° μ€λ©΄ λ§€μΉ μ ν¨pats.append(rf'(?<![A-Za-z0-9_]){re.escape(k)}(?![A-Za-z0-9_])')else:body = r'\s*'.join(map(re.escape, k.split(" ")))# [v152] 곡백 μ κ±° ν μ λΆ νκΈμ΄λ©΄ μ’μΈ‘μ νκΈμ΄ μ€λ©΄ μ λ¨if re.match(r'^[κ°-ν£]+$', k.replace(" ", "")):pats.append(rf'(?<![κ°-ν£]){body}')else:pats.append(body)return re.compile("|".join(f"({p})" for p in pats)), ordereddef get_engine(flat_dict):sig = hash(tuple(sorted(flat_dict.items())))10 unmodified linesshields.add(v)else:phase2[k] = vp1_pat, p1_keys = _build_pattern(phase1.keys())p2_pat, p2_keys = _build_pattern(phase2.keys())sh_pat, _ = _build_pattern(shields)_ENGINE_CACHE.update({"sig": sig, "phase1": phase1, "phase2": phase2,"p1_pat": p1_pat, "p1_keys": p1_keys,"p2_pat": p2_pat, "p2_keys": p2_keys, "sh_pat": sh_pat})return _ENGINE_CACHEdef _sub_phase1(text, eng):if not eng["p1_pat"]:return textreturn eng["p1_pat"].sub(lambda m: eng["phase1"][eng["p1_keys"][m.lastindex - 1]], text)def _segments_phase2(text, eng):if not eng["p2_pat"] or not text:return [(False, text)] if text else []segs, last = [], 0for m in eng["p2_pat"].finditer(text):s, e = m.span()if s > last:segs.append((False, text[last:s]))segs.append((True, eng["phase2"][eng["p2_keys"][m.lastindex - 1]]))last = eif last < len(text):segs.append((False, text[last:]))14 unmodified linesres.append(apply_g2p(chunk[last:], mode))return "".join(res)def convert_text(text, mode, flat_dict):"""μλ¬Έ λΉκ³΅λ°± λ¬Έμμ΄ λ³ν μ ν λμΌμ± μ μ§.μΈν λ³νλ μ¬μ Β·μ«μΒ·λ¬Έμ₯λΆνΈ νΈν‘ λ§μ»€λ‘λ§ λ§λ€μ΄μ§λ€."""eng = get_engine(flat_dict)t = _sub_phase1(text, eng)out = []for fixed, chunk in _segments_phase2(t, eng):if fixed:out.append(chunk)continuechunk = apply_smart_regex(chunk)for fixed2, c2 in _segments_phase2(chunk, eng):out.append(c2 if fixed2 else _g2p_shielded(c2, mode, eng))return "".join(out)# ---------- G2P λͺ¨λ ----------def apply_g2p(text, mode):96 unmodified linestext = re.sub(r'β¦\s*', 'β¦ / ', text)return textdef process_text(input_text, ai_mode, auto_break, smart_pause, font_size, user_temp_dict):if not input_text or not input_text.strip():return "", f'<div id="prompter_label_space">πΊ ν둬νν° λ·°</div><div id="prompter_output_div" style="font-size:{font_size}px;"></div>', \"곡백 ν¬ν¨: 0μ / 곡백 μ μΈ: 0μ", "νμλ λ§μ»€(@@)κ° μμ΅λλ€."1 unmodified linechar_count = f"곡백 ν¬ν¨: {len(input_text)}μ / 곡백 μ μΈ: {len(input_text.replace(' ', '').replace(chr(10), ''))}μ"flat_dict = load_dict(user_temp_dict)if not flat_dict:final_text = apply_g2p(apply_smart_regex(input_text), ai_mode)else:final_text = convert_text(input_text, ai_mode, flat_dict)if smart_pause:final_text = _join_breath_marks(final_text)22 unmodified linesdef get_file():return dict_path if os.path.exists(dict_path) else Nonedef add_and_update(word, pronun, user_role, current_input, ai_mode, auto_break, smart_pause, font_size, user_temp_dict):if not word or not pronun:return "β οΈ λ¨μ΄μ λ°μμ μ λ ₯νμΈμ.", gr.update(), gr.update(), gr.update(), gr.update(), user_temp_dictword, pronun = word.strip(), pronun.strip()8 unmodified linesuser_temp_dict[word] = pronunstatus_msg = f"π€ [κ²μ€νΈ] '{word}' -> '{pronun}' μμ μ μ₯ μλ£! (μλ‘κ³ μΉ¨ μ μ΄κΈ°ν - μꡬ λ±λ‘μ μ΄λλ―Όμκ² μμ²)"if current_input.strip():ft, ho, cc, mr = process_text(current_input, ai_mode, auto_break, smart_pause, font_size, user_temp_dict)return status_msg, ft, ho, cc, mr, user_temp_dictreturn status_msg, gr.update(), gr.update(), gr.update(), gr.update(), user_temp_dict38 unmodified linesexcept Exception as e:return f"β μλ¬: {e}", user_temp_dictdef update_dict_entry(old_word, new_pronun, user_role, current_input, ai_mode, auto_break, smart_pause, font_size, user_temp_dict):"""λ¨μ΄μ₯ νλͺ© μμ β key(λ¨μ΄) μλ³μκ° κ·Έλλ‘μΈ λμ value(λ°μ)λ§ κ΅μ²΄."""if not old_word:return "β οΈ λ¨Όμ λ¨μ΄λ₯Ό μ ννμΈμ.", gr.update(), gr.update(), gr.update(), gr.update(), update_choices(), user_temp_dict17 unmodified linesuser_temp_dict[old_word] = new_pronunstatus_msg = f"π€ [κ²μ€νΈ μμ ] '{old_word}' : '{old_value}' β '{new_pronun}' (μλ‘κ³ μΉ¨ μ μ΄κΈ°ν)"if current_input.strip():ft, ho, cc, mr = process_text(current_input, ai_mode, auto_break, smart_pause, font_size, user_temp_dict)return status_msg, ft, ho, cc, mr, update_choices(), user_temp_dictreturn status_msg, gr.update(), gr.update(), gr.update(), gr.update(), update_choices(), user_temp_dictdef delete_dict_entry(old_word, user_role, current_input, ai_mode, auto_break, smart_pause, font_size, user_temp_dict):"""λ¨μ΄μ₯ νλͺ©μμ ν μ€λ§ μμ . ADMIN_IDΒ·μ΄λλ―Όμ΄λ©΄ μλ² μ μ₯μ, κ²μ€νΈλ©΄ μμ μ¬μ ."""if not old_word:return "β οΈ λ¨Όμ λ¨μ΄λ₯Ό μ ννμΈμ.", gr.update(), gr.update(), gr.update(), gr.update(), update_choices(), user_temp_dict12 unmodified linesold_value = user_temp_dict.pop(old_word)status_msg = f"ποΈ [κ²μ€νΈ μμ ] '{old_word}' : '{old_value}' (μλ‘κ³ μΉ¨ μ μ΄κΈ°ν)"if current_input.strip():ft, ho, cc, mr = process_text(current_input, ai_mode, auto_break, smart_pause, font_size, user_temp_dict)return status_msg, ft, ho, cc, mr, update_choices(), user_temp_dictreturn status_msg, gr.update(), gr.update(), gr.update(), gr.update(), update_choices(), user_temp_dictdef update_choices():"""λλ‘λ€μ΄μ νμ¬ μλ² μ¬μ μ ν€λ€μ μνλ²³μμΌλ‘ λ ΈμΆ."""d = _read_local_dict()26 unmodified linesreturn gr.update(visible=True), gr.update(visible=False), "none", "β μμ΄λ λλ λΉλ°λ²νΈκ° νλ Έμ΅λλ€.", ""def perform_logout():return gr.update(visible=True), gr.update(visible=False), "none", "", "", "", {}def handle_page_load(current_role):if current_role in ["admin", "guest"]:66 unmodified lineswith gr.Blocks(**_BLOCKS_KW) as iface:user_role = gr.State("none")user_temp_dict = gr.State(lambda: {})with gr.Column(visible=True, elem_classes="login-box") as login_screen:gr.Markdown("### π μμ€ν λ‘κ·ΈμΈ")login_id = gr.Textbox(label="μμ΄λ")55 unmodified linesbtn_delete_entry = gr.Button("ποΈ μ ν λ¨μ΄ μμ ", variant="stop")btn_refresh_choices = gr.Button("π λͺ©λ‘ μλ‘κ³ μΉ¨", variant="secondary")proc_inputs = [input_text, ai_mode, auto_break, smart_pause, font_size, user_temp_dict]proc_outputs = [output_text, output_html, char_count, marker_collection]btn_insert_marker.click(fn=None, inputs=[input_text], outputs=[input_text], js=insert_marker_js, api_name=False)3 unmodified linesbtn_copy.click(fn=None, inputs=[output_text], outputs=None, js="(t) => { if(t) { navigator.clipboard.writeText(t); alert('β λ³΅μ¬ μλ£!'); } }", api_name=False)btn_add.click(fn=add_and_update,inputs=[nw, np, user_role, input_text, ai_mode, auto_break, smart_pause, font_size, user_temp_dict],outputs=[status, output_text, output_html, char_count, marker_collection, user_temp_dict], api_name=False)btn_add.click(fn=lambda: gr.update(choices=sorted(_read_local_dict().keys())), outputs=[dict_keys_dd], api_name=False)btn_clear_dict_inputs.click(fn=lambda: ("", ""), outputs=[nw, np], api_name=False)5 unmodified lines)btn_update_entry.click(fn=update_dict_entry,inputs=[dict_keys_dd, edit_pron, user_role, input_text, ai_mode, auto_break, smart_pause, font_size, user_temp_dict],outputs=[status, output_text, output_html, char_count, marker_collection, dict_keys_dd, user_temp_dict], api_name=False,)btn_delete_entry.click(fn=delete_dict_entry,inputs=[dict_keys_dd, user_role, input_text, ai_mode, auto_break, smart_pause, font_size, user_temp_dict],outputs=[status, output_text, output_html, char_count, marker_collection, dict_keys_dd, user_temp_dict], api_name=False,)btn_refresh_choices.click(fn=update_choices, outputs=[dict_keys_dd], api_name=False,)iface.load(fn=update_choices, outputs=[dict_keys_dd], api_name=False)for evt in [font_size.change, ai_mode.change, auto_break.change, smart_pause.change]:evt(fn=process_text, inputs=proc_inputs, outputs=proc_outputs, api_name=False)with gr.Tab("π₯ μλ λ°±μ /μ‘°ν/μμ "):15 unmodified linesup_stat = gr.Textbox(label="μν κ²°κ³Όμ°½", interactive=False)up_file.upload(fn=upload_file, inputs=[up_file, user_role, user_temp_dict], outputs=[up_stat, user_temp_dict], api_name=False)login_btn.click(fn=verify_login, inputs=[login_id, login_pw], outputs=[login_screen, main_app, user_role, login_msg, login_pw], api_name=False)btn_logout.click(fn=perform_logout, inputs=[], outputs=[login_screen, main_app, user_role, login_msg, login_id, login_pw, user_temp_dict], api_name=False)iface.load(fn=handle_page_load, inputs=[user_role], outputs=[login_screen, main_app, user_role, login_msg, login_id, login_pw], js=script_js)if __name__ == "__main__":17 unmodified lines18192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858 unmodified lines949596979899100166 unmodified lines26726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935019 unmodified lines37037137237337437537637737837938038138238338438538638738838939039139210 unmodified lines40340440540640740840941041141241341441541641741841942042142242342442542642742842943043110 unmodified lines44244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948014 unmodified lines49549649749849950050150250350450550650750850951051151251351451551651751851952052196 unmodified lines6186196206216226236241 unmodified line62662762862963063163263363463563663763822 unmodified lines6616626636646656666678 unmodified lines67667767867968068168238 unmodified lines72172272372472572672717 unmodified lines74574674774874975075175275375475512 unmodified lines76876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682726 unmodified lines85485585685785885986066 unmodified lines92792892993093193293355 unmodified lines9899909919929939949959969979989991000100110021003100410051006100710081009101010113 unmodified lines10151016101710181019102010215 unmodified lines1027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106115 unmodified lines107710781079108010811082108317 unmodified lines# - λ²νΌ νμ κ°μ scaleΒ·sizeλ‘ ν΅μΌ. μ΄κΈ°ν λ²νΌμ λ§μ§λ§ μλ¦¬λ‘ λ³΅μ.# ============================================================================# ---------- [v154] ννμ κ²½κ³ μΈμ (A+B νμ΄λΈλ¦¬λ) ----------# B: Kiwi(κ²½λ ννμ λΆμκΈ°, μμ ν ) β μμΌλ©΄ μ‘°μ¬/μ΄λ―Έ κ²½κ³λ₯Ό μ λ° νλ³# A: Kiwiκ° μκ±°λ λ‘λ μ€ν¨ μ μ‘°μ¬ μ λ―Έμ¬ λ¦¬μ€νΈλ‘ ν΄λ°± (μμ‘΄μ± 0, μ±μ μ λ μ μ£½μ)_kiwi = None_KIWI_OK = None # None=μμ§ μλ μ ν¨ / True / Falsedef _load_kiwi():global _kiwi, _KIWI_OKif _KIWI_OK is None:try:from kiwipiepy import Kiwi_kiwi = Kiwi()_KIWI_OK = Trueprint("[ννμ λΆμκΈ°] Kiwi λ‘λ μλ£ β μ‘°μ¬/μ΄λ―Έ κ²½κ³ νλ³ μ¬μ©")except Exception as e:_KIWI_OK = Falseprint(f"[ννμ λΆμκΈ°] Kiwi λ‘λ μ€ν¨({e}) β μ‘°μ¬ λ¦¬μ€νΈ κ·μΉμΌλ‘ ν΄λ°±")return _kiwi# A ν΄λ°±μ©: μ΄μ λ€μ λΆλ νκ΅μ΄ μ‘°μ¬Β·λ³΄μ‘°μ¬Β·μ΄λ―Έ (κΈΈμ΄ λ΄λ¦Όμ°¨μ β κΈ΄ κ² λ¨Όμ )_PARTICLE_SUFFIXES = sorted(set(["μΌλ‘λΆν°", "λ‘λΆν°", "μμ", "μκ²", "νν ", "κΉμ§", "보λ€", "μ²λΌ", "κ°μ΄","λ§νΌ", "μ‘°μ°¨", "λ§μ ", "νκ³ ", "μ΄λ", "μ΄λΌ", "μ λλ€", "μ΄μ§λ§", "λκΉ","λλ°", "λ", "μ", "μ΄", "κ°", "μ", "λ₯Ό", "μ", "μ", "λ", "λ§","κ³Ό", "μ", "λ‘", "μΌ", "μΌ", "μ", "κ»", "λ"]), key=lambda x: -len(x))class _MorphBoundary:"""νμ¬ ν μ€νΈ κΈ°μ€ ννμ κ²½κ³ β ν€ λ§€μΉ μμΉ λ€κ° 'μ‘°μ¬/μ΄λ―Έμ μμ'μΈμ§ νλ³."""def __init__(self, text):self.text = text or ""self._kiwi = _load_kiwi()self._starts = {} # position -> tag (Kiwi ν ν° μμμ )if self._kiwi is not None:try:for tok in self._kiwi.tokenize(self.text):st = int(tok.start) if tok.start is not None else Noneif st is not None and st not in self._starts:self._starts[st] = tok.tagexcept Exception:self._kiwi = None@staticmethoddef _is_particle_tag(tag):# J*: μ‘°μ¬ / E*: μ΄λ―Έ / VCPΒ·VCN: 'μ΄λ€Β·μλλ€' λ₯ (μ: μμ€μ λλ€)return tag.startswith("J") or tag.startswith("E") or tag in ("VCP", "VCN")def allow_after(self, e):"""ν€ λ§€μΉμ΄ λλ μμΉ e λ€μ μ‘°μ¬/μ΄λ―Έ(μ ννμ)κ° μ΄μ΄μ§λ©΄ True."""if e is None or e >= len(self.text):return Truenxt = self.text[e]if not ('κ°' <= nxt <= 'ν£'): # 곡백·문μ₯λΆνΈΒ·λ β λ 립 λ¨μ΄return Trueif self._kiwi is not None and self._starts:tag = self._starts.get(e)if tag is not None:return self._is_particle_tag(tag)return False # νκΈ μ°μμΈλ° ννμ κ²½κ³ μμ β ν©μ±μ΄# ν΄λ°± A: μ‘°μ¬ μ λ―Έμ¬λ‘ μμνλμ§ (Kiwi μμ λλ§)return any(self.text[e:].startswith(p) for p in _PARTICLE_SUFFIXES)# ---------- G2P μλ μ ν (g2pk β g2pk2 β g2pkk) ----------g2p = NoneG2P_BACKEND = "μμ"8 unmodified linesprint(f"G2P {_mod} λ‘λ© μ€ν¨: {_e}")dict_path = "custom_dict.json"whitelist_path = "custom_whitelist.json" # [v153] μμΈ λ¨μ΄(μΉν κΈμ§) μ μ₯μADMIN_ID = os.environ.get("ADMIN_ID", "admin")ADMIN_PW = os.environ.get("ADMIN_PW", "admin1234")GUEST_ID = os.environ.get("GUEST_ID", "guest")166 unmodified linesmsg = "λ‘컬 μ μ₯ μλ£ (HF_TOKEN μμ β μ¬μμ μ μ μ€ κ°λ₯)"return f"{msg} Β· νμ¬ μ¬μ {len(dict_map)}κ°"# ---------- [v153] νμ΄νΈλ¦¬μ€νΈ I/O + λ§μ€νΉ ----------def _read_local_whitelist():try:with open(whitelist_path, "r", encoding="utf-8") as f:data = json.load(f)return sorted({str(x).strip() for x in data.get("items", []) if str(x).strip()},key=lambda x: -len(x))except Exception:return []def _write_local_whitelist(wl_list):items = sorted({s.strip() for s in wl_list if s and s.strip()}, key=lambda x: -len(x))payload = {"items": items, "meta": {"app_title": "VoiceScript AI whitelist","app_version": "153.0", "count": len(items)}}tmp_path = whitelist_path + ".tmp"with open(tmp_path, "w", encoding="utf-8") as f:json.dump(payload, f, ensure_ascii=False, indent=2)if os.path.exists(whitelist_path):os.replace(whitelist_path, whitelist_path + ".bak")os.replace(tmp_path, whitelist_path)def _push_remote_whitelist():if not hf_api:return "λ‘컬 μ μ₯λ§ λ¨ (μ¬μμ μ μ μ€ κ°λ₯ - HF_TOKEN μ€μ νμ)"try:hf_api.upload_file(path_or_fileobj=whitelist_path, path_in_repo="custom_whitelist.json",repo_id=dict_repo_id, repo_type="dataset",commit_message="update pronunciation whitelist")return "μꡬ μ μ₯ μλ£"except Exception as e:return f"μ격 μ μ₯ μ€ν¨({e}) - λ‘μ»¬λ§ μ μ₯λ¨"def save_whitelist(wl_list):_write_local_whitelist(wl_list)if hf_api:def _bg_push():try:msg = _push_remote_whitelist()print(f"[νμ΄νΈλ¦¬μ€νΈ μ격 μ μ₯] {msg}")except Exception as e:print(f"[νμ΄νΈλ¦¬μ€νΈ μ격 μ μ₯ μ€ν¨] {e}")threading.Thread(target=_bg_push, daemon=True).start()msg = "μ μ₯ μλ£ (μ격 λκΈ°νλ λ°±κ·ΈλΌμ΄λ μ§ν μ€)"else:msg = "λ‘컬 μ μ₯ μλ£ (HF_TOKEN μμ)"items = _read_local_whitelist()return f"{msg} Β· νμ¬ μμΈ λ¨μ΄ {len(items)}κ°", items_WL_TOKEN_FMT = "\x00WL{}\x00"def _mask_whitelist(text, wl_terms):"""νμ΄νΈλ¦¬μ€νΈ λ¨μ΄λ€μ μμ ν ν°μΌλ‘ μΉν. (masked_text, token_map) λ°ν."""if not text or not wl_terms:return text, {}# κΈ΄ κ²λΆν° λ§€μΉ (κ²ΉμΉ¨ λ°©μ§)ordered = sorted({w for w in wl_terms if w}, key=lambda x: -len(x))token_map = {}for idx, term in enumerate(ordered):token = _WL_TOKEN_FMT.format(idx)if term in text:text = text.replace(term, token)token_map[token] = termreturn text, token_mapdef _unmask_whitelist(text, token_map):if not token_map:return textfor token, term in token_map.items():text = text.replace(token, term)return textdef load_whitelist(user_temp_wl=None):base = list(_read_local_whitelist())if user_temp_wl:base.extend([str(x).strip() for x in user_temp_wl if str(x).strip()])# μ€λ³΅ μ κ±° + κΈ΄ μreturn sorted(set(base), key=lambda x: -len(x))def perform_startup_recovery():dict_map = _read_local_dict()remote_ok = True19 unmodified linesif hf_api and remote_ok:_push_remote()# [v153] νμ΄νΈλ¦¬μ€νΈλ μ격μμ 볡μ μλ (μμΌλ©΄ 무μ)wl_local = _read_local_whitelist()if hf_api:try:remote_wl_path = hf_hub_download(repo_id=dict_repo_id, repo_type="dataset",filename="custom_whitelist.json", token=HF_TOKEN)with open(remote_wl_path, "r", encoding="utf-8") as f:remote_wl = json.load(f)merged = set(wl_local) | {str(x).strip() for x in remote_wl.get("items", []) if str(x).strip()}_write_local_whitelist(list(merged))except Exception as e:is_404 = getattr(getattr(e, "response", None), "status_code", None) == 404if is_404:print("[νμ΄νΈλ¦¬μ€νΈ] μ격μ νμΌ μμ β μ΅μ΄ λΆν ")else:print(f"[νμ΄νΈλ¦¬μ€νΈ] μ격 볡μ μ€ν¨({e}) - λ‘컬 보νΈ")perform_startup_recovery()def load_dict(user_temp_dict=None):10 unmodified lines[v150] 1κΈμ μμ«μ ν€λ λ¨μ΄ κ²½κ³(boundary)λ₯Ό κ°μ ν΄μ'CLASS' κ°μ λ¨μ΄ μ€κ°μμ μ€νλμ§ μκ² νλ€.[v152] μμ νκΈ ν€λ μ’μΈ‘μ νκΈμ΄ μ€λ©΄ λ§€μΉ κΈμ§ β 'μμ€'κ°'ν΄λ¦¬μμ€ν°' κ°μ ν©μ±μ΄ μ€κ°μμ μ€νλμ§ μλλ‘.[v154] μμ νκΈ ν€λ guarded=True β μ€μ λ§€μΉ μ ννμ κ²½κ³(μ‘°μ¬/μ΄λ―Έ μ¬λΆ, Kiwi λλ μ‘°μ¬ λ¦¬μ€νΈ ν΄λ°±)λ₯Ό νμΈν΄'μμ€μ»¬λ μ΄ν°/μμ€νλ μ/μ μ΄μ¨μ°' κ°μ ν©μ±μ΄ μ€νμ λ§λλ€."""ordered = sorted(keys, key=lambda x: -len(x.replace(" ", "")))if not ordered:return None, [], []pats, guarded = [], []for k in ordered:if len(k) == 1 and re.match(r'^[A-Za-z0-9_]$', k):# 1κΈμ μμ«μ: μ’μ° alphanumeric/underscoreκ° μ€λ©΄ λ§€μΉ μ ν¨pats.append(rf'(?<![A-Za-z0-9_]){re.escape(k)}(?![A-Za-z0-9_])')guarded.append(False)else:body = r'\s*'.join(map(re.escape, k.split(" ")))# [v152] 곡백 μ κ±° ν μ λΆ νκΈμ΄λ©΄ μ’μΈ‘μ νκΈμ΄ μ€λ©΄ μ λ¨if re.match(r'^[κ°-ν£]+$', k.replace(" ", "")):pats.append(rf'(?<![κ°-ν£]){body}')guarded.append(True)else:pats.append(body)guarded.append(False)return re.compile("|".join(f"({p})" for p in pats)), ordered, guardeddef get_engine(flat_dict):sig = hash(tuple(sorted(flat_dict.items())))10 unmodified linesshields.add(v)else:phase2[k] = vp1_pat, p1_keys, p1_guard = _build_pattern(phase1.keys())p2_pat, p2_keys, p2_guard = _build_pattern(phase2.keys())sh_pat, _, _ = _build_pattern(shields)_ENGINE_CACHE.update({"sig": sig, "phase1": phase1, "phase2": phase2,"p1_pat": p1_pat, "p1_keys": p1_keys,"p2_pat": p2_pat, "p2_keys": p2_keys, "sh_pat": sh_pat,"p1_guard": p1_guard, "p2_guard": p2_guard})return _ENGINE_CACHEdef _sub_phase1(text, eng, boundary=None):if not eng["p1_pat"]:return textguard = eng.get("p1_guard", []) or []def _repl(m):gi = m.lastindex - 1if guard[gi] and boundary is not None and not boundary.allow_after(m.end()):return m.group() # ν©μ±μ΄ λ΄λΆ β μ μ§return eng["phase1"][eng["p1_keys"][gi]]return eng["p1_pat"].sub(_repl, text)def _segments_phase2(text, eng, boundary=None):if not eng["p2_pat"] or not text:return [(False, text)] if text else []guard = eng.get("p2_guard", []) or []segs, last = [], 0for m in eng["p2_pat"].finditer(text):s, e = m.span()gi = m.lastindex - 1if guard[gi] and boundary is not None and not boundary.allow_after(e):continue # ν©μ±μ΄ λ΄λΆ β μ΄ λ§€μΉ κ±΄λλ (μλ¬Έ μ μ§)if s > last:segs.append((False, text[last:s]))segs.append((True, eng["phase2"][eng["p2_keys"][gi]]))last = eif last < len(text):segs.append((False, text[last:]))14 unmodified linesres.append(apply_g2p(chunk[last:], mode))return "".join(res)def convert_text(text, mode, flat_dict, whitelist=None):"""μλ¬Έ λΉκ³΅λ°± λ¬Έμμ΄ λ³ν μ ν λμΌμ± μ μ§.μΈν λ³νλ μ¬μ Β·μ«μΒ·λ¬Έμ₯λΆνΈ νΈν‘ λ§μ»€λ‘λ§ λ§λ€μ΄μ§λ€.[v153] whitelistμ ν¬ν¨λ λ¨μ΄λ μ΄λ€ μ¬μ ν€κ° μμ λ€μ΄μμ΄λμΉν λμμμ μμ ν μ μΈλλ€."""text, wl_map = _mask_whitelist(text, whitelist or [])eng = get_engine(flat_dict)t = _sub_phase1(text, eng, _MorphBoundary(text))out = []b2 = _MorphBoundary(t)for fixed, chunk in _segments_phase2(t, eng, b2):if fixed:out.append(chunk)continuechunk = apply_smart_regex(chunk)# [v154] 2μ°¨ λ§€μΉλ μ‘°κ° λ¨μ ννμ κ°λ μ μ© β 1μ°¨μμ κ±°μ λ# ν©μ±μ΄(μμ€μ»¬λ μ΄ν° λ±)κ° μ΄ λ£¨νμμ μ¬μ€νλλ κ² λ°©μ§.b_chunk = _MorphBoundary(chunk)for fixed2, c2 in _segments_phase2(chunk, eng, b_chunk):out.append(c2 if fixed2 else _g2p_shielded(c2, mode, eng))return _unmask_whitelist("".join(out), wl_map)# ---------- G2P λͺ¨λ ----------def apply_g2p(text, mode):96 unmodified linestext = re.sub(r'β¦\s*', 'β¦ / ', text)return textdef process_text(input_text, ai_mode, auto_break, smart_pause, font_size, user_temp_dict, user_temp_wl=None):if not input_text or not input_text.strip():return "", f'<div id="prompter_label_space">πΊ ν둬νν° λ·°</div><div id="prompter_output_div" style="font-size:{font_size}px;"></div>', \"곡백 ν¬ν¨: 0μ / 곡백 μ μΈ: 0μ", "νμλ λ§μ»€(@@)κ° μμ΅λλ€."1 unmodified linechar_count = f"곡백 ν¬ν¨: {len(input_text)}μ / 곡백 μ μΈ: {len(input_text.replace(' ', '').replace(chr(10), ''))}μ"flat_dict = load_dict(user_temp_dict)whitelist = load_whitelist(user_temp_wl)if not flat_dict:# μ¬μ μ μλλΌλ νμ΄νΈλ¦¬μ€νΈλ μ€λ§νΈ μ κ·μ/G2Pμμ 보νΈλμ΄μΌ ν¨masked, wl_map = _mask_whitelist(input_text, whitelist)final_text = _unmask_whitelist(apply_g2p(apply_smart_regex(masked), ai_mode), wl_map)else:final_text = convert_text(input_text, ai_mode, flat_dict, whitelist)if smart_pause:final_text = _join_breath_marks(final_text)22 unmodified linesdef get_file():return dict_path if os.path.exists(dict_path) else Nonedef add_and_update(word, pronun, user_role, current_input, ai_mode, auto_break, smart_pause, font_size, user_temp_dict, user_temp_wl=None):if not word or not pronun:return "β οΈ λ¨μ΄μ λ°μμ μ λ ₯νμΈμ.", gr.update(), gr.update(), gr.update(), gr.update(), user_temp_dictword, pronun = word.strip(), pronun.strip()8 unmodified linesuser_temp_dict[word] = pronunstatus_msg = f"π€ [κ²μ€νΈ] '{word}' -> '{pronun}' μμ μ μ₯ μλ£! (μλ‘κ³ μΉ¨ μ μ΄κΈ°ν - μꡬ λ±λ‘μ μ΄λλ―Όμκ² μμ²)"if current_input.strip():ft, ho, cc, mr = process_text(current_input, ai_mode, auto_break, smart_pause, font_size, user_temp_dict, user_temp_wl)return status_msg, ft, ho, cc, mr, user_temp_dictreturn status_msg, gr.update(), gr.update(), gr.update(), gr.update(), user_temp_dict38 unmodified linesexcept Exception as e:return f"β μλ¬: {e}", user_temp_dictdef update_dict_entry(old_word, new_pronun, user_role, current_input, ai_mode, auto_break, smart_pause, font_size, user_temp_dict, user_temp_wl=None):"""λ¨μ΄μ₯ νλͺ© μμ β key(λ¨μ΄) μλ³μκ° κ·Έλλ‘μΈ λμ value(λ°μ)λ§ κ΅μ²΄."""if not old_word:return "β οΈ λ¨Όμ λ¨μ΄λ₯Ό μ ννμΈμ.", gr.update(), gr.update(), gr.update(), gr.update(), update_choices(), user_temp_dict17 unmodified linesuser_temp_dict[old_word] = new_pronunstatus_msg = f"π€ [κ²μ€νΈ μμ ] '{old_word}' : '{old_value}' β '{new_pronun}' (μλ‘κ³ μΉ¨ μ μ΄κΈ°ν)"if current_input.strip():ft, ho, cc, mr = process_text(current_input, ai_mode, auto_break, smart_pause, font_size, user_temp_dict, user_temp_wl)return status_msg, ft, ho, cc, mr, update_choices(), user_temp_dictreturn status_msg, gr.update(), gr.update(), gr.update(), gr.update(), update_choices(), user_temp_dictdef delete_dict_entry(old_word, user_role, current_input, ai_mode, auto_break, smart_pause, font_size, user_temp_dict, user_temp_wl=None):"""λ¨μ΄μ₯ νλͺ©μμ ν μ€λ§ μμ . ADMIN_IDΒ·μ΄λλ―Όμ΄λ©΄ μλ² μ μ₯μ, κ²μ€νΈλ©΄ μμ μ¬μ ."""if not old_word:return "β οΈ λ¨Όμ λ¨μ΄λ₯Ό μ ννμΈμ.", gr.update(), gr.update(), gr.update(), gr.update(), update_choices(), user_temp_dict12 unmodified linesold_value = user_temp_dict.pop(old_word)status_msg = f"ποΈ [κ²μ€νΈ μμ ] '{old_word}' : '{old_value}' (μλ‘κ³ μΉ¨ μ μ΄κΈ°ν)"if current_input.strip():ft, ho, cc, mr = process_text(current_input, ai_mode, auto_break, smart_pause, font_size, user_temp_dict, user_temp_wl)return status_msg, ft, ho, cc, mr, update_choices(), user_temp_dictreturn status_msg, gr.update(), gr.update(), gr.update(), gr.update(), update_choices(), user_temp_dict# ---------- [v153] νμ΄νΈλ¦¬μ€νΈ UI νΈλ€λ¬ ----------def add_whitelist_entry(term, user_role, current_input, ai_mode, auto_break, smart_pause, font_size, user_temp_dict, user_temp_wl):term = (term or "").strip()if not term:return "β οΈ μμΈ λ¨μ΄λ₯Ό μ λ ₯νμΈμ.", gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), user_temp_wlif user_role == "admin":wl = _read_local_whitelist()if term in wl:status_msg = f"βΉοΈ μ΄λ―Έ μμΈ λͺ©λ‘μ μμ: '{term}'"else:wl.append(term)msg, _ = save_whitelist(wl)status_msg = f"π [μ΄λλ―Ό] μμΈ λ¨μ΄ μΆκ°: '{term}' ({msg})"else:if term in user_temp_wl:status_msg = f"βΉοΈ μ΄λ―Έ μμ μμΈ λͺ©λ‘μ μμ: '{term}'"else:user_temp_wl.append(term)status_msg = f"π€ [κ²μ€νΈ] μμ μμΈ μΆκ°: '{term}' (μλ‘κ³ μΉ¨ μ μ΄κΈ°ν)"dd_update = gr.update(choices=list(_read_local_whitelist()))if current_input.strip():ft, ho, cc, mr = process_text(current_input, ai_mode, auto_break, smart_pause, font_size, user_temp_dict, user_temp_wl)return status_msg, ft, ho, cc, mr, dd_update, user_temp_wlreturn status_msg, gr.update(), gr.update(), gr.update(), gr.update(), dd_update, user_temp_wldef delete_whitelist_entry(term, user_role, current_input, ai_mode, auto_break, smart_pause, font_size, user_temp_dict, user_temp_wl):term = (term or "").strip()if not term:return "β οΈ μμ ν μμΈ λ¨μ΄λ₯Ό μ ννμΈμ.", gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), user_temp_wlif user_role == "admin":wl = _read_local_whitelist()if term not in wl:return f"π« μμΈ λͺ©λ‘μ '{term}' κ° μμ΅λλ€.", gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), user_temp_wlwl = [x for x in wl if x != term]msg, _ = save_whitelist(wl)status_msg = f"ποΈ [μμΈ μμ ] '{term}' ({msg})"else:if term not in user_temp_wl:return f"π« μμ μμΈ λͺ©λ‘μ '{term}' κ° μμ΅λλ€.", gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), user_temp_wluser_temp_wl = [x for x in user_temp_wl if x != term]status_msg = f"ποΈ [κ²μ€νΈ μμΈ μμ ] '{term}' (μλ‘κ³ μΉ¨ μ μ΄κΈ°ν)"dd_update = gr.update(choices=list(_read_local_whitelist()), value=None)if current_input.strip():ft, ho, cc, mr = process_text(current_input, ai_mode, auto_break, smart_pause, font_size, user_temp_dict, user_temp_wl)return status_msg, ft, ho, cc, mr, dd_update, user_temp_wlreturn status_msg, gr.update(), gr.update(), gr.update(), gr.update(), dd_update, user_temp_wldef refresh_whitelist_choices():return gr.update(choices=list(_read_local_whitelist()))def update_choices():"""λλ‘λ€μ΄μ νμ¬ μλ² μ¬μ μ ν€λ€μ μνλ²³μμΌλ‘ λ ΈμΆ."""d = _read_local_dict()26 unmodified linesreturn gr.update(visible=True), gr.update(visible=False), "none", "β μμ΄λ λλ λΉλ°λ²νΈκ° νλ Έμ΅λλ€.", ""def perform_logout():return gr.update(visible=True), gr.update(visible=False), "none", "", "", "", {}, []def handle_page_load(current_role):if current_role in ["admin", "guest"]:66 unmodified lineswith gr.Blocks(**_BLOCKS_KW) as iface:user_role = gr.State("none")user_temp_dict = gr.State(lambda: {})user_temp_wl = gr.State(lambda: []) # [v153] κ²μ€νΈ μμ νμ΄νΈλ¦¬μ€νΈwith gr.Column(visible=True, elem_classes="login-box") as login_screen:gr.Markdown("### π μμ€ν λ‘κ·ΈμΈ")login_id = gr.Textbox(label="μμ΄λ")55 unmodified linesbtn_delete_entry = gr.Button("ποΈ μ ν λ¨μ΄ μμ ", variant="stop")btn_refresh_choices = gr.Button("π λͺ©λ‘ μλ‘κ³ μΉ¨", variant="secondary")# [v153] μμΈ λ¨μ΄(νμ΄νΈλ¦¬μ€νΈ) β μ¬μ μΉνμμ μ μΈν μ΄μ /ν©μ±μ΄with gr.Accordion("π‘οΈ μμΈ λ¨μ΄(νμ΄νΈλ¦¬μ€νΈ) (v153)", open=False):gr.Markdown("**λ¨μ΄μ₯ μΉνμμ μμ ν μ μΈν λ¨μ΄**λ₯Ό λ±λ‘ν©λλ€. ""μ: `μμ€μ»¬λ μ΄ν°`, `μμ€νλ μ`, `ν΄λ¦¬μμ€ν°` μ²λΌ μ¬μ μ `μμ€βμ€λͺ°`μ΄ μμ΄λ ""μ΄ λ¨μ΄λ€μ μλ¬Έ κ·Έλλ‘ μ μ§λ©λλ€. **μ νν μΌμΉνλ λ¬Έμμ΄**λ‘ λ±λ‘νμΈμ ""(λ¬Έμμ΄ λΆλΆμΌμΉ λ°©μμ΄λΌ `μμ€μ»¬λ μ΄ν°`λ‘ λ±λ‘νλ©΄ `μμ€μ»¬λ μ΄ν°λ/μμ€μ»¬λ μ΄ν°λ₯Ό`λ ν¨κ» 보νΈλ©λλ€).")with gr.Row():wl_input = gr.Textbox(label="μμΈλ‘ μ§μ ν λ¨μ΄(μ΄μ )", placeholder="μ: μμ€μ»¬λ μ΄ν°")wl_keys_dd = gr.Dropdown(choices=[], label="λ±λ‘λ μμΈ λ¨μ΄ μ ν", interactive=True)with gr.Row():btn_add_wl = gr.Button("β μμΈ μΆκ°", variant="primary")btn_del_wl = gr.Button("ποΈ μ ν μμΈ μμ ", variant="stop")btn_refresh_wl = gr.Button("π μμΈ λͺ©λ‘ μλ‘κ³ μΉ¨", variant="secondary")proc_inputs = [input_text, ai_mode, auto_break, smart_pause, font_size, user_temp_dict, user_temp_wl]proc_outputs = [output_text, output_html, char_count, marker_collection]btn_insert_marker.click(fn=None, inputs=[input_text], outputs=[input_text], js=insert_marker_js, api_name=False)3 unmodified linesbtn_copy.click(fn=None, inputs=[output_text], outputs=None, js="(t) => { if(t) { navigator.clipboard.writeText(t); alert('β λ³΅μ¬ μλ£!'); } }", api_name=False)btn_add.click(fn=add_and_update,inputs=[nw, np, user_role, input_text, ai_mode, auto_break, smart_pause, font_size, user_temp_dict, user_temp_wl],outputs=[status, output_text, output_html, char_count, marker_collection, user_temp_dict], api_name=False)btn_add.click(fn=lambda: gr.update(choices=sorted(_read_local_dict().keys())), outputs=[dict_keys_dd], api_name=False)btn_clear_dict_inputs.click(fn=lambda: ("", ""), outputs=[nw, np], api_name=False)5 unmodified lines)btn_update_entry.click(fn=update_dict_entry,inputs=[dict_keys_dd, edit_pron, user_role, input_text, ai_mode, auto_break, smart_pause, font_size, user_temp_dict, user_temp_wl],outputs=[status, output_text, output_html, char_count, marker_collection, dict_keys_dd, user_temp_dict], api_name=False,)btn_delete_entry.click(fn=delete_dict_entry,inputs=[dict_keys_dd, user_role, input_text, ai_mode, auto_break, smart_pause, font_size, user_temp_dict, user_temp_wl],outputs=[status, output_text, output_html, char_count, marker_collection, dict_keys_dd, user_temp_dict], api_name=False,)btn_refresh_choices.click(fn=update_choices, outputs=[dict_keys_dd], api_name=False,)iface.load(fn=update_choices, outputs=[dict_keys_dd], api_name=False)# [v153] νμ΄νΈλ¦¬μ€νΈ νΈλ€λ¬ λ°μΈλ©btn_add_wl.click(fn=add_whitelist_entry,inputs=[wl_input, user_role, input_text, ai_mode, auto_break, smart_pause, font_size, user_temp_dict, user_temp_wl],outputs=[status, output_text, output_html, char_count, marker_collection, wl_keys_dd, user_temp_wl],api_name=False,)btn_add_wl.click(fn=lambda: "", outputs=[wl_input], api_name=False) # μ λ ₯μΉΈ λΉμ°κΈ°btn_del_wl.click(fn=delete_whitelist_entry,inputs=[wl_keys_dd, user_role, input_text, ai_mode, auto_break, smart_pause, font_size, user_temp_dict, user_temp_wl],outputs=[status, output_text, output_html, char_count, marker_collection, wl_keys_dd, user_temp_wl],api_name=False,)btn_refresh_wl.click(fn=refresh_whitelist_choices, outputs=[wl_keys_dd], api_name=False)iface.load(fn=refresh_whitelist_choices, outputs=[wl_keys_dd], api_name=False)for evt in [font_size.change, ai_mode.change, auto_break.change, smart_pause.change]:evt(fn=process_text, inputs=proc_inputs, outputs=proc_outputs, api_name=False)with gr.Tab("π₯ μλ λ°±μ /μ‘°ν/μμ "):15 unmodified linesup_stat = gr.Textbox(label="μν κ²°κ³Όμ°½", interactive=False)up_file.upload(fn=upload_file, inputs=[up_file, user_role, user_temp_dict], outputs=[up_stat, user_temp_dict], api_name=False)login_btn.click(fn=verify_login, inputs=[login_id, login_pw], outputs=[login_screen, main_app, user_role, login_msg, login_pw], api_name=False)btn_logout.click(fn=perform_logout, inputs=[], outputs=[login_screen, main_app, user_role, login_msg, login_id, login_pw, user_temp_dict, user_temp_wl], api_name=False)iface.load(fn=handle_page_load, inputs=[user_role], outputs=[login_screen, main_app, user_role, login_msg, login_id, login_pw], js=script_js)if __name__ == "__main__":
app.py+302-34