Spaces:
Running
Running
Update app.py
Browse files208 unmodified lines20921021121221321421512 unmodified lines228229230231232233234235236237238213 unmodified lines45245345445545645745845949 unmodified lines509510511512513514144 unmodified lines6596606616626636646 unmodified lines671672673674675676677208 unmodified linesprint("[사전] 원격에 아직 사전 파일 없음 — 최초 부팅으로 처리")else:remote_ok = Falseprint(f"[사전] 원격 복원 실패({e}) - 로컬 사전 보호")for w in AUTO_MERGE_WORDS:dict_map.setdefault(w[0], w[1]) # 사용자값 절대 안 덮어쓰기_write_local_dict(dict_map)12 unmodified lines_ENGINE_CACHE = {"sig": None}def _build_pattern(keys):r"""키 길이 내림차순 정렬 후 공백을 \s* 로 바꾼 유연 패턴. 그룹번호→키."""ordered = sorted(keys, key=lambda x: -len(x.replace(" ", "")))if not ordered:return None, []pats = [r'\s*'.join(map(re.escape, k.split(" "))) for k in ordered]return re.compile("|".join(f"({p})" for p in pats)), ordereddef get_engine(flat_dict):213 unmodified linesif not word or not pronun:return "⚠️ 단어와 발음을 입력하세요.", gr.update(), gr.update(), gr.update(), gr.update(), user_temp_dictword, pronun = word.strip(), pronun.strip()if len(word) == 1:return "🚫 [등록 실패] 1글자는 등록할 수 없습니다.", gr.update(), gr.update(), gr.update(), gr.update(), user_temp_dictif user_role == "admin":dict_map = _read_local_dict()49 unmodified linesexcept Exception as e:return f"❌ 에러: {e}", user_temp_dictdef upload_file(file_path, user_role, user_temp_dict):if file_path is None:return "⚠️ 파일이 없습니다.", user_temp_dict144 unmodified linesbtn_clear_dict_inputs = gr.Button("🧹 입력칸 비우기", variant="secondary")status = gr.Textbox(label="저장 상태", interactive=False)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]6 unmodified linesbtn_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_clear_dict_inputs.click(fn=lambda: ("", ""), outputs=[nw, np], 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("📥 수동 백업/조회/수정"):208 unmodified lines20921021121221321421512 unmodified lines228229230231232233234235236237238239240241242243244245246247213 unmodified lines46146246346446546646749 unmodified lines517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578144 unmodified lines7237247257267277287297307317327337347357367377387396 unmodified lines746747748749750751752753754755756757758759760761762763764765766767768769770771772773208 unmodified linesprint("[사전] 원격에 아직 사전 파일 없음 — 최초 부팅으로 처리")else:remote_ok = Falseprint(f"[사전] 원측 복원 실패({e}) - 로컬 사전 보호")for w in AUTO_MERGE_WORDS:dict_map.setdefault(w[0], w[1]) # 사용자값 절대 안 덮어쓰기_write_local_dict(dict_map)12 unmodified lines_ENGINE_CACHE = {"sig": None}def _build_pattern(keys):r"""키 길이 내림차순 정렬 후 공백을 \s* 로 바꾼 유연 패턴. 그룹번호→키.[v150] 1글자 영숫자 키는 단어 경계(boundary)를 강제해서'CLASS' 같은 단어 중간에서 오탐되지 않게 한다.2글자 이상 한국어 키는 부분 매칭 위험이 거의 없으므로 기존 \s* 정책을 유지."""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:pats.append(r'\s*'.join(map(re.escape, k.split(" "))))return re.compile("|".join(f"({p})" for p in pats)), ordereddef get_engine(flat_dict):213 unmodified linesif not word or not pronun:return "⚠️ 단어와 발음을 입력하세요.", gr.update(), gr.update(), gr.update(), gr.update(), user_temp_dictword, pronun = word.strip(), pronun.strip()# [v150] 1글자 키 허용 — 경계는 _build_pattern에서 처리if user_role == "admin":dict_map = _read_local_dict()49 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_dictold_word = old_word.strip()new_pronun = (new_pronun or "").strip()if not new_pronun:return "⚠️ 새 발음을 입력하세요.", gr.update(), gr.update(), gr.update(), gr.update(), update_choices(), user_temp_dictif user_role == "admin":dict_map = _read_local_dict()if old_word not in dict_map:return f"🚫 단어장에 '{old_word}' 가 없습니다.", gr.update(), gr.update(), gr.update(), gr.update(), update_choices(), user_temp_dictold_value = dict_map[old_word]dict_map[old_word] = new_pronunsync_msg = save_dict(dict_map)status_msg = f"👑 [수정] '{old_word}' : '{old_value}' ➜ '{new_pronun}' ({sync_msg})"else:if old_word not in user_temp_dict:return f"🚫 임시 단어장에 '{old_word}' 가 없습니다.", gr.update(), gr.update(), gr.update(), gr.update(), update_choices(), user_temp_dictold_value = user_temp_dict[old_word]user_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_dictold_word = old_word.strip()if user_role == "admin":dict_map = _read_local_dict()if old_word not in dict_map:return f"🚫 단어장에 '{old_word}' 가 없습니다.", gr.update(), gr.update(), gr.update(), gr.update(), update_choices(), user_temp_dictold_value = dict_map.pop(old_word)sync_msg = save_dict(dict_map)status_msg = f"🗑️ [삭제] '{old_word}' : '{old_value}' ({sync_msg})"else:if old_word not in user_temp_dict:return f"🚫 임시 단어장에 '{old_word}' 가 없습니다.", gr.update(), gr.update(), gr.update(), gr.update(), update_choices(), user_temp_dictold_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()return gr.update(choices=sorted(d.keys()))def upload_file(file_path, user_role, user_temp_dict):if file_path is None:return "⚠️ 파일이 없습니다.", user_temp_dict144 unmodified linesbtn_clear_dict_inputs = gr.Button("🧹 입력칸 비우기", variant="secondary")status = gr.Textbox(label="저장 상태", interactive=False)# [v151] 등록된 단어 중 잘못 등록한 것을 골라 수정/삭제with gr.Accordion("✂️ 단어장 항목 수정/삭제 (v151)", open=False):gr.Markdown("단어 선택 시 현재 발음이 자동으로 채워집니다. 새 발음을 입력하고 [✏️ 발음 수정], 완전히 지울 때는 [🗑️ 삭제]를 누르세요.")with gr.Row():dict_keys_dd = gr.Dropdown(choices=[], label="등록된 단어 선택", interactive=True)edit_pron = gr.Textbox(label="새 발음 (수정 시)")with gr.Row():btn_update_entry = gr.Button("✏️ 발음 수정", variant="primary")btn_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]6 unmodified linesbtn_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)# [v151] 수정/삭제 핸들러 — 선택 변경 시 기존 발음을 프리필dict_keys_dd.change(fn=lambda key: _read_local_dict().get(key, "") if key else "",inputs=[dict_keys_dd], outputs=[edit_pron], api_name=False,)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("📥 수동 백업/조회/수정"):
app.py+101-5