Spaces:
Running
Running
Update app.py
Browse files12 unmodified lines13141516161718192021222324252324252627287 unmodified lines3637383940414243444546474849505152394041425354555657585960616263646566676869707172737475767778798081828384438687888990919293949544454647484950515253545556575859609798996162101636465666768697071727374751031041057610777787980818211283848586878889909192939495961169798991001011211221021031041051061071081251091101111121131141151161321331171181191201211221231241371251261271281291301311321331341351361371381391401411501511421431441451461541471481491571501511521531541551601561571581621591601611651621631641651661671681681691691701711721731741711751761771781791801741751811821831841851861871881891901911811821921931941951961841851971981992002011871882022032042052062072082092102112122131901912142152162172181931941952191971981992002012022032042052062072082092102112122132142152162172182192202212222212232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612242252262272622632642652662672682692702712722732742752302762772782792802812822832842852862872882892322332342352902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363372382392402412422433383393403412453423432472482493443453466 unmodified lines3533543552622633563573583593603613623632673643653663673683692703703713723733743753761 unmodified line37837938027827928038138238338438538638738828528628738939039139239339439539629229339739839940040140240329940440540640740840941041141241341441541641741841942042142242342442542642742842943018 unmodified lines4494504514523244534544554564574584596 unmodified lines46646746833934034134234334434546947047147247347447547647747834734847948048148248335248448548648748835648949049149249349449549649749836336436549950050150250350450550637150750850951012 unmodified lines
print("G2P ๋ชจ๋ธ ๋ก๋ฉ ์ค...")try: g2p = G2p() if G2p else None if G2p: g2p = G2p() else: g2p = Noneexcept Exception as e: print(f"G2P ๋ก๋ฉ ์คํจ: {e}") g2p = None
dict_path = "custom_dict.json"
# ==========================================# 1. ์ฝ์ด ๋ฐ์ดํฐ ๋ฐ ์ค์ ์ฌ์ ๊ด๋ฆฌ ์์ง# ==========================================AUTO_MERGE_WORDS = [ ["GS๋ง์ด์ต", "์ง์์ค๋ง์ด์ต"],["GS ๋ง์ด์ต", "์ง์์ค๋ง์ด์ต"],["GS์ต", "์ง์์ค์ต"],["GS ์ต", "์ง์์ค์ต"], ["26SS", "์ด์ญ์ก ์์ค์์ค"],["26 SS", "์ด์ญ์ก ์์ค์์ค"],["26S/S", "์ด์ญ์ก ์์ค์์ค"],["26 S/S", "์ด์ญ์ก ์์ค์์ค"],7 unmodified lines ["1๋ง์๋", "๋ง์๋"],["1๋ง ์๋", "๋ง์๋"],["1๋ง ์ ๋", "๋ง์๋"],["1๋ง์ ๋", "๋ง์๋"]]
class DictStore: def __init__(self, path, auto_words): self.path = path self.auto_words = auto_words self.mtime = None self.dict_map = {} self.pattern = None self.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 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)
def reload(self, force=False): try: current_mtime = os.path.getmtime(self.path) except Exception: current_mtime = None if not force and self.mtime == current_mtime: return
try: 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 and str(item[0]).strip(): d[str(item[0]).strip()] = str(item[1]).strip() for k, v in self.auto_words: d[k.strip()] = v.strip()
self.dict_map = d sorted_keys = sorted(d.keys(), key=len, reverse=True) self.pattern = re.compile("|".join(map(re.escape, sorted_keys))) if d else None self.mtime = current_mtime
def get_map_and_pattern(self): self.reload() return self.dict_map, self.pattern
def save_pairs(self, new_pairs_dict, overwrite=False): self.reload() base = {} if overwrite else dict(self.dict_map) for k, v in new_pairs_dict.items(): if str(k).strip(): base[str(k).strip()] = str(v).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, "meta": {"count": len(final_items)}}, f, ensure_ascii=False, indent=2) self.reload(force=True)
def add(self, word, pronun): self.save_pairs({word: pronun}, overwrite=False) 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_items existing_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)
def get_raw_json_str(self): self.reload() return json.dumps({"items": self.dict_map}, ensure_ascii=False, indent=4)perform_auto_recovery_and_merge()
dict_store = DictStore(dict_path, AUTO_MERGE_WORDS)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: pass return flat_dict
# ==========================================# 2. ํ
์คํธ ๋ฐ ๋ฐ์ ๋ณํ ์์ง# ==========================================def apply_g2p(text, mode): if g2p is None or mode == "๋๊ธฐ (์๋ ์ฌ์ ๋ง ์ ์ฉ)": return text if g2p is None or mode == "๋๊ธฐ (์๋ ์ฌ์ ๋ง ์ ์ฉ)": return text if mode == "๋งค์ด ๋ง (๋ฌธ์ฅ ํต์งธ๋ก - ์์ฐ์ค๋ฌ์ด ์ฐ์)": try: return g2p(text) except: return text if mode == "์ํ ๋ง (๋จ์ด๋ณ ๋๊ธฐ - ๊ณผ๋ํ ๏ฟฝ๏ฟฝ๏ฟฝ์ ๋ฐฉ์ง)": return "".join(g2p(w) if w.strip() else w for w in re.split(r'(\s+)', text)) 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 text
# ==========================================# โ
1. ์ค๋งํธ ์ ๊ท์ ๋ก์ง๋ง ์กฐ์ฌ์ค๋ฝ๊ฒ ์ถ๊ฐ โ
# ==========================================def number_to_korean(num_str): num_str = str(num_str).replace(',', '') num_str = num_str.replace(',', '') try: n = int(num_str) except: return num_str if n == 0: return "์" digits, units, large_units = ["", "์ผ", "์ด", "์ผ", "์ฌ", "์ค", "์ก", "์น ", "ํ", "๊ตฌ"], ["", "์ญ", "๋ฐฑ", "์ฒ"], ["", "๋ง", "์ต", "์กฐ"] res, str_n = [], str(n)[::-1] digits = ["", "์ผ", "์ด", "์ผ", "์ฌ", "์ค", "์ก", "์น ", "ํ", "๊ตฌ"] units = ["", "์ญ", "๋ฐฑ", "์ฒ"] large_units = ["", "๋ง", "์ต", "์กฐ"] res = [] str_n = str(n)[::-1] for i in range(0, len(str_n), 4): chunk, chunk_res = str_n[i:i+4], [] chunk = str_n[i:i+4] chunk_res = [] for j, char in enumerate(chunk): d = int(char) if d > 0: word = digits[d] if d > 1 or j == 0 else "" if d == 1 and j == 0 and len(chunk) == 1 and i == 0: word = "์ผ" chunk_res.append(word + units[j]) if chunk_res: res.append("".join(chunk_res[::-1]) + large_units[i//4]) return "".join(res[::-1]) or num_str if chunk_res: res.append("".join(chunk_res[::-1]) + large_units[i//4]) final_str = "".join(res[::-1]) return final_str if final_str else num_str
def apply_smart_regex(text): if not text: return text # ์ ์ฐํ ๋์ด์ฐ๊ธฐ ํจํด text = re.sub(r'\b1\s*๋ง\s*์\s*๋\b', "๋ง์๋", text) text = re.sub(r'\b1\s*๋ง์\s*๋\b', "๋ง์๋", text) text = re.sub(r'\b1\s*๋ง์๋\b', "๋ง์๋", text) text = re.sub(r'(\d+)\s*๊ฐ์\b', lambda m: f"{number_to_korean(m.group(1))}๊ฐ์", text) text = re.sub(r'(\d+)\s*(%|ํ๋ก)\b', lambda m: f"{number_to_korean(m.group(1))}ํ๋ก", text) size_dict = {"55":"์ค์ค", "66":"์ต์ก", "77":"์น ์น ", "88":"ํํ"} text = re.sub(r'\b(55|66|77|88)\s*์ฌ์ด์ฆ\b', lambda m: f"{size_dict[m.group(1)]} ์ธ์ด์ฆ", text) # 12,900์ ๋ฑ ๋ฒ์ฉ ๊ฐ๊ฒฉ text = re.sub(r'(\d{1,3}(?:,\d{3})+|\d+)\s*๋ง\s*์\s*๋\b', lambda m: f"{number_to_korean(m.group(1))}๋ง์๋", text) text = re.sub(r'(\d{1,3}(?:,\d{3})+|\d+)\s*์\b', lambda m: f"{number_to_korean(m.group(1))} ์", text) return text
initial_html_template = '<div id="prompter_label_space">๐บ ํ๋กฌํํฐ ๋ทฐ (๋ณ๊ฒฝ์ ํ์ธ)</div><div id="prompter_output_div" style="font-size:{size}px;">{content}</div>'
# ==========================================# โ
์์
์๋ ์์ ๋ก์ง 100% ๋ณต๊ตฌ โ
# ==========================================def process_text(input_text, ai_mode, auto_break, smart_pause, font_size): if not input_text or not input_text.strip(): return "", initial_html_template.format(size=font_size, content=""), "๊ณต๋ฐฑ ํฌํจ: 0์ / ๊ณต๋ฐฑ ์ ์ธ: 0์", "ํ์๋ ๋ง์ปค(@@)๊ฐ ์์ต๋๋ค." return "", f'<div id="prompter_label_space">๐บ ํ๋กฌํํฐ ๋ทฐ (๋ณ๊ฒฝ์ ํ์ธ)</div><div id="prompter_output_div" style="font-size:{font_size}px;"></div>', "๊ณต๋ฐฑ ํฌํจ: 0์ / ๊ณต๋ฐฑ ์ ์ธ: 0์", "ํ์๋ ๋ง์ปค(@@)๊ฐ ์์ต๋๋ค." clean_text = input_text.replace('\r', '') char_count = f"๊ณต๋ฐฑ ํฌํจ: {len(clean_text)}์ / ๊ณต๋ฐฑ ์ ์ธ: {len(clean_text.replace(' ', '').replace(chr(10), ''))}์" len_with_spaces = len(clean_text) len_without_spaces = len(clean_text.replace(' ', '').replace('\n', '')) char_count = f"๊ณต๋ฐฑ ํฌํจ: {len_with_spaces}์ / ๊ณต๋ฐฑ ์ ์ธ: {len_without_spaces}์" # ์ฌ๊ธฐ์ ๋จผ์ ์ ๊ท์์ ํ ๋ฒ ๋๋ ค์ค๋๋ค (์ด ํ ์ค๋ง ์๋ณธ์ ์ถ๊ฐ) text_for_processing = apply_smart_regex(input_text) flat_dict, pattern = dict_store.get_map_and_pattern() flat_dict = load_dict() if not flat_dict or not pattern: if not flat_dict: final_text = apply_g2p(text_for_processing, ai_mode) else: parts, last_end = [], 0 sorted_keys = sorted(flat_dict.keys(), key=len, reverse=True) pattern = re.compile("|".join(map(re.escape, sorted_keys))) parts = [] last_end = 0 for match in pattern.finditer(text_for_processing): start, end = match.span() if chunk := text_for_processing[last_end:start]: parts.append(apply_g2p(chunk, ai_mode)) parts.append(flat_dict[match.group()]) chunk = text_for_processing[last_end:start] if chunk: parts.append(apply_g2p(chunk, ai_mode)) matched_word = match.group() parts.append(flat_dict[matched_word]) last_end = end if tail := text_for_processing[last_end:]: parts.append(apply_g2p(tail, ai_mode)) tail = text_for_processing[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 = re.sub(r'([.!?])\s+', r'\1\n\n', final_text) 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(): # HTML ๋ ๋๋ง ์๋ฌ ๋ฐฉ์ง (๋ณด์ ์ถ๊ฐ) chunk = html.escape(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>') 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 = 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>', "".join(html_parts)) html_output = initial_html_template.format(size=font_size, content=raw_html) 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>' unique_markers = list(dict.fromkeys(m.strip('.,!?\n') for m in re.findall(r'[^\s]*@@[^\s]*', input_text) if m.strip('.,!?\n'))) return final_text, html_output, char_count, " / ".join(unique_markers) if unique_markers else "ํ์๋ ๋ง์ปค(@@)๊ฐ ์์ต๋๋ค." 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 = "ํ์๋ ๋ง์ปค(@@)๊ฐ ์์ต๋๋ค."
def clear_all(font_size=22): return "", "", initial_html_template.format(size=font_size, content=""), "๊ณต๋ฐฑ ํฌํจ: 0์ / ๊ณต๋ฐฑ ์ ์ธ: 0์", "ํ์๋ ๋ง์ปค(@@)๊ฐ ์์ต๋๋ค." return final_text, html_output, char_count, marker_result
def clear_all(): return "", "", '<div id="prompter_label_space">๐บ ํ๋กฌํํฐ ๋ทฐ (๋ณ๊ฒฝ์ ํ์ธ)</div><div id="prompter_output_div" style="font-size:22px;"></div>', "๊ณต๋ฐฑ ํฌํจ: 0์ / ๊ณต๋ฐฑ ์ ์ธ: 0์", "ํ์๋ ๋ง์ปค(@@)๊ฐ ์์ต๋๋ค."
# ==========================================# 3. UI ์ฐ๋ ์ฌ์ ๊ด๋ฆฌ API# ==========================================def add_and_update(word, pronun, current_input, ai_mode, auto_break, smart_pause, font_size): empty_preview = ( "", initial_html_template.format(size=font_size, content=""), "๊ณต๋ฐฑ ํฌํจ: 0์ / ๊ณต๋ฐฑ ์ ์ธ: 0์", "ํ์๋ ๋ง์ปค(@@)๊ฐ ์์ต๋๋ค." )
if not (word := (word or "").strip()) or not (pronun := (pronun or "").strip()): msg = "โ ๏ธ ๊ธฐ์กด ๋จ์ด์ ์ํ๋ ๋ฐ์์ ๋ชจ๋ ์
๋ ฅํ์ธ์." elif len(word) == 1: msg = f"๐ซ [๋ฑ๋ก ์คํจ] '{word}'์ฒ๋ผ 1๊ธ์๋ง ๋ฑ๋กํ๋ฉด ์๋ณธ์ด ํผ์๋ฉ๋๋ค!" else: try: dict_store.add(word, pronun) msg = f"โ
'{word}' -> '{pronun}' ์ ์ฅ ์๋ฃ!" except Exception as e: msg = f"โ ์ ์ฅ ์คํจ: {e}"
preview = ( process_text(current_input, ai_mode, auto_break, smart_pause, font_size) if current_input and current_input.strip() else empty_preview ) if not word or not pronun: return "โ ๏ธ ๊ธฐ์กด ๋จ์ด์ ์ํ๋ ๋ฐ์์ ๋ชจ๋ ์
๋ ฅํ์ธ์.", gr.update(), gr.update(), gr.update(), gr.update() return msg, *preview 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_result return error_msg, "", f'<div id="prompter_label_space">๐บ ํ๋กฌํํฐ ๋ทฐ (๋ณ๊ฒฝ์ ํ์ธ)</div><div id="prompter_output_div" style="font-size:{font_size}px;"></div>', "๊ณต๋ฐฑ ํฌํจ: 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 = False for item in j_struct.get("items",[]): if item[0].strip() == word: item[1] = pronun found = True break if not found: j_struct["items"].append([word, pronun]) try: j_struct["meta"]["count"] = len(j_struct["items"]) 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_result return status_msg, "", f'<div id="prompter_label_space">๐บ ํ๋กฌํํฐ ๋ทฐ (๋ณ๊ฒฝ์ ํ์ธ)</div><div id="prompter_output_div" style="font-size:{font_size}px;"></div>', "๊ณต๋ฐฑ ํฌํจ: 0์ / ๊ณต๋ฐฑ ์ ์ธ: 0์", "ํ์๋ ๋ง์ปค(@@)๊ฐ ์์ต๋๋ค."
def load_current_json_to_text(): return dict_store.get_raw_json_str(), "โ
ํ์ฌ ์ฌ์ ์ ์ฑ๊ณต์ ์ผ๋ก ๋ถ๋ฌ์์ต๋๋ค! ์ด์ํ ๋จ์ด๋ฅผ ์ฐพ์ ์ง์ฐ๊ฑฐ๋ ์์ ํด๋ณด์ธ์."
def process_json_input(json_string, overwrite): if not json_string or not json_string.strip(): return "โ ๏ธ ๋ด์ฉ์ ์
๋ ฅํด์ฃผ์ธ์." 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' ํค๊ฐ ์์ต๋๋ค)" 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)}} items_dict = new_data["items"] if isinstance(new_data["items"], dict) else {i[0]: i[1] for i in new_data["items"] if len(i)==2} dict_store.save_pairs(items_dict, overwrite=overwrite) return "๐จ[๋ฎ์ด์ฐ๊ธฐ ์๋ฃ] ์์ ํ ๋ด์ฉ์ผ๋ก ์ฌ์ ์ ์๋ฒฝํ ๊ต์ฒดํ์ต๋๋ค!" if overwrite else "โ
๊ธฐ์กด ๋จ์ด๋ฅผ ์ ์งํ๋ฉฐ ์ฑ๊ณต์ ์ผ๋ก ํ๋ฌ์ค(+) ํ์ต๋๋ค!" except Exception as e: return f"โ JSON ํ์ฑ ์๋ฌ (๋ฐ์ดํ๋ ์ผํ๊ฐ ๋น ์ก๋์ง ํ์ธํ์ธ์): {e}" with open(dict_path, "w", encoding="utf-8") as f: json.dump(final_data, f, ensure_ascii=False, indent=2) perform_auto_recovery_and_merge() 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_items existing_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() return f"โ
๊ธฐ์กด ๋จ์ด๋ฅผ ์ ์งํ๋ฉฐ ์ฑ๊ณต์ ์ผ๋ก ํ๋ฌ์ค(+) ํ์ต๋๋ค!" except Exception as e: return f"โ JSON ํ์ฑ ์๋ฌ: {e}"
def get_file(): return dict_path if os.path.exists(dict_path) else None
def upload_file(file_path): if not file_path: return "โ ๏ธ ํ์ผ์ด ์์ต๋๋ค." try: with open(file_path, "r", encoding="utf-8") as f: data = json.load(f) if "items" not in data: return "โ JSON ๊ตฌ์กฐ ์ค๋ฅ ('items' ์์)" items_dict = data["items"] if isinstance(data["items"], dict) else {i[0]: i[1] for i in data["items"] if len(i)==2} dict_store.save_pairs(items_dict, overwrite=True) if file_path is not None: shutil.copy(file_path, dict_path) perform_auto_recovery_and_merge() return "โ
ํ์ผ ๋ณต๊ตฌ ์๋ฃ!" except Exception as e: return f"โ ๋ณต๊ตฌ ์คํจ: {e}" return "โ ๏ธ ํ์ผ์ด ์์ต๋๋ค."
# ==========================================# 4. ํ๋ก ํธ์๋ (CSS, JS, Gradio UI)# ==========================================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; }6 unmodified linesscript_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'; } 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, isSyncing2 = false, isSyncing3 = false; 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'), ta2 = document.querySelector('#output_text_area textarea'), div3 = document.getElementById('prompter_output_div'); 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) {1 unmodified line 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 (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 (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); 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 = "(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; }"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 ์ ์ฒ๋ฆฌ ๋ณํ๊ธฐ (ํ๋กฌํํฐ ๋ชจ๋)")18 unmodified lines 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_template.format(size=22, content=""), elem_id="prompter_html_wrap") 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("---")6 unmodified lines 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).then(process_text, inputs=[input_text, ai_mode, auto_break, smart_pause, font_size], outputs=[output_text, output_html, char_count, marker_collection]) 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]) btn_clr.click(fn=clear_all, inputs=[font_size], outputs=[input_text, output_text, output_html, char_count, marker_collection]) btn_copy.click(fn=None, inputs=[output_text], js="(text) => { if(text) { navigator.clipboard.writeText(text); alert('โ
๋ณต์ฌ ์๋ฃ!'); } }") for evt in [font_size.change, ai_mode.change, auto_break.change, smart_pause.change]: evt(fn=process_text, inputs=[input_text, ai_mode, auto_break, smart_pause, font_size], 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) 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]) btn_clear_dict_inputs.click(fn=lambda: ("", ""), outputs=[nw, np]) 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=lambda: dict_path if os.path.exists(dict_path) else None, outputs=[dl_btn]) 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") 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]) btn_apply_json.click(fn=lambda j: process_json_input(j, False), inputs=[json_input], outputs=[json_stat]) btn_overwrite_json.click(fn=lambda j: process_json_input(j, True), inputs=[json_input], outputs=[json_stat]) 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]) up_file.upload(fn=upload_file, inputs=[up_file], outputs=[up_stat], api_name=False)
iface.load(None, js=script_js)
app.py+307-171