Spaces:
Running
Running
Update app.py
Browse files3 unmodified lines456789102 unmodified lines1314151516171816171819202122252324252627282930313233343536373839404142434445464748495051525354555657582728293031323334353637383940596061626364656667686970717273747576777879808182424344454647838485868788498990919293515253545556575859606162949596979899100101102103104105106656610710810911011171727374757677781121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521538315415515686878815715890159160161929316216316495969798991001651661671021031041051681691701071081091711721731121131141151161741751761771191781791211221231241251801811821831271281291301841851861321331341351361371381391401411421431441871881891461471901911921931941951961501511521531541551561571581591601611971981992002012022032042052062072082092102112122132142152162172182192201631641651661671681691701711721731741751761771781791801811821831841851861871882212222231911921931941951962241971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282262272282292312322302312342352362372382392402412422432442452462472482492502512522532542552562572582592602612622322332342352362372652662382392402412422432442682452462472482492502512526 unmodified lines2592602612822832842852622632642872652662902912922932672682692962972982992702712722731 unmodified line27527627730730830931027827928028128228328431531631731828528628728828929029132332429229329429529629729833033133233333433533633733833934034134234334434534634734834935035135235329930030130218 unmodified lines3213223233783793243253263823273283296 unmodified lines3363373383953963393403413423433443453463983994004014024034044054063473483493503514103523533543554144153564163574183583593604223613624254264273633643653663673683693704333713723733743 unmodified linesimport difflibimport shutilimport reimport html
try: from g2pk import G2p2 unmodified lines
print("G2P ๋ชจ๋ธ ๋ก๋ฉ ์ค...")try: if G2p: g2p = G2p() else: g2p = None g2p = G2p() if G2p else Noneexcept Exception as e: print(f"G2P ๋ก๋ฉ ์คํจ: {e}") g2p = None
dict_path = "custom_dict.json"
AUTO_MERGE_WORDS = [["GS๋ง์ด์ต", "์ง์์ค๋ง์ด์ต"],["GS ๋ง์ด์ต", "์ง์์ค๋ง์ด์ต"],["GS์ต", "์ง์์ค์ต"],["GS ์ต", "์ง์์ค์ต"],["26SS", "์ด์ญ์ก ์์ค์์ค"],["26 SS", "์ด์ญ์ก ์์ค์์ค"],["26S/S", "์ด์ญ์ก ์์ค์์ค"],["26 S/S", "์ด์ญ์ก ์์ค์์ค"],["55", "์ค์ค"],["55์ฌ์ด์ฆ", "์ค์ค ์ธ์ด์ฆ"],["55 ์ฌ์ด์ฆ", "์ค์ค ์ธ์ด์ฆ"],["66", "์ต์ก"],["66์ฌ์ด์ฆ", "์ต์ก ์ธ์ด์ฆ"],["66 ์ฌ์ด์ฆ", "์ต์ก ์ธ์ด์ฆ"],["77", "์น ์น "],["77์ฌ์ด์ฆ", "์น ์น ์ธ์ด์ฆ"],["77 ์ฌ์ด์ฆ", "์น ์น ์ธ์ด์ฆ"],["88", "ํํ"],["88์ฌ์ด์ฆ", "ํํ ์ธ์ด์ฆ"],["88 ์ฌ์ด์ฆ", "ํํ ์ธ์ด์ฆ"],["100%", "๋ฐฑํ๋ก"],["100 %", "๋ฐฑํ๋ก"],["100ํ๋ก", "๋ฐฑํ๋ก"],["59,900์", "์ค๋ง ๊ตฌ์ฒ๊ตฌ๋ฐฑ ์"],["59,900 ์", "์ค๋ง ๊ตฌ์ฒ๊ตฌ๋ฐฑ ์"],["59900์", "์ค๋ง ๊ตฌ์ฒ๊ตฌ๋ฐฑ ์"],["59900 ์", "์ค๋ง ๊ตฌ์ฒ๊ตฌ๋ฐฑ ์"],["5๋ง 9์ฒ 9๋ฐฑ ์", "์ค๋ง ๊ตฌ์ฒ๊ตฌ๋ฐฑ ์"],["3๊ฐ์", "์ผ๊ฐ์"],["3 ๊ฐ์", "์ผ๊ฐ์"],["1๋ง์๋", "๋ง์๋"],["1๋ง ์๋", "๋ง์๋"],["1๋ง ์ ๋", "๋ง์๋"],["1๋ง์ ๋", "๋ง์๋"]]# ==========================================# 1. ์ฝ์ด ๋ฐ์ดํฐ ๋ฐ ์ค์ ์ฌ์ ๊ด๋ฆฌ ์์ง# ==========================================AUTO_MERGE_WORDS = [ ["GS๋ง์ด์ต", "์ง์์ค๋ง์ด์ต"],["GS ๋ง์ด์ต", "์ง์์ค๋ง์ด์ต"],["GS์ต", "์ง์์ค์ต"],["GS ์ต", "์ง์์ค์ต"], ["26SS", "์ด์ญ์ก ์์ค์์ค"],["26 SS", "์ด์ญ์ก ์์ค์์ค"],["26S/S", "์ด์ญ์ก ์์ค์์ค"],["26 S/S", "์ด์ญ์ก ์์ค์์ค"], ["55", "์ค์ค"],["55์ฌ์ด์ฆ", "์ค์ค ์ธ์ด์ฆ"],["55 ์ฌ์ด์ฆ", "์ค์ค ์ธ์ด์ฆ"], ["66", "์ต์ก"],["66์ฌ์ด์ฆ", "์ต์ก ์ธ์ด์ฆ"],["66 ์ฌ์ด์ฆ", "์ต์ก ์ธ์ด์ฆ"], ["77", "์น ์น "],["77์ฌ์ด์ฆ", "์น ์น ์ธ์ด์ฆ"],["77 ์ฌ์ด์ฆ", "์น ์น ์ธ์ด์ฆ"], ["88", "ํํ"],["88์ฌ์ด์ฆ", "ํํ ์ธ์ด์ฆ"],["88 ์ฌ์ด์ฆ", "ํํ ์ธ์ด์ฆ"], ["100%", "๋ฐฑํ๋ก"],["100 %", "๋ฐฑํ๋ก"],["100ํ๋ก", "๋ฐฑํ๋ก"], ["59,900์", "์ค๋ง ๊ตฌ์ฒ๊ตฌ๋ฐฑ ์"],["59,900 ์", "์ค๋ง ๊ตฌ์ฒ๊ตฌ๋ฐฑ ์"],["59900์", "์ค๋ง ๊ตฌ์ฒ๊ตฌ๋ฐฑ ์"],["59900 ์", "์ค๋ง ๊ตฌ์ฒ๊ตฌ๋ฐฑ ์"], ["5๋ง 9์ฒ 9๋ฐฑ ์", "์ค๋ง ๊ตฌ์ฒ๊ตฌ๋ฐฑ ์"],["3๊ฐ์", "์ผ๊ฐ์"],["3 ๊ฐ์", "์ผ๊ฐ์"], ["1๋ง์๋", "๋ง์๋"],["1๋ง ์๋", "๋ง์๋"],["1๋ง ์ ๋", "๋ง์๋"],["1๋ง์ ๋", "๋ง์๋"]]
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 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
def perform_auto_recovery_and_merge(): if not os.path.exists(dict_path): with open(dict_path, "w", encoding="utf-8") as f: json.dump({"items":[], "meta": {"count": 0}}, f) try: with open(dict_path, "r", encoding="utf-8") as f: existing_data = json.load(f) except: existing_data = {"items":[], "meta": {"count": 0}} dict_map = {item[0].strip(): item[1].strip() for item in existing_data.get("items",[]) if len(item) == 2} for w in AUTO_MERGE_WORDS: dict_map[w[0]] = w[1] 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) 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) 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()
perform_auto_recovery_and_merge() 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 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 def add(self, word, pronun): self.save_pairs({word: pronun}, overwrite=False)
def get_raw_json_str(self): self.reload() return json.dumps({"items": self.dict_map}, ensure_ascii=False, indent=4)
dict_store = DictStore(dict_path, AUTO_MERGE_WORDS)
# ==========================================# 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 == "์ํ ๋ง (๋จ์ด๋ณ ๋๊ธฐ - ๊ณผ๋ํ ์ฐ์ ๋ฐฉ์ง)": 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 "".join(g2p(w) if w.strip() else w for w in re.split(r'(\s+)', text)) return text
def number_to_korean(num_str): num_str = 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] for i in range(0, len(str_n), 4): chunk, chunk_res = str_n[i:i+4], [] 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
def apply_smart_regex(text): if not text: return text text = re.sub(r'\b1\s*๋ง\s*์\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) 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>'
def process_text(input_text, ai_mode, auto_break, smart_pause, font_size): if not input_text or not input_text.strip(): return "", "", "๊ณต๋ฐฑ ํฌํจ: 0์ / ๊ณต๋ฐฑ ์ ์ธ: 0์", "ํ์๋ ๋ง์ปค(@@)๊ฐ ์์ต๋๋ค." return "", initial_html_template.format(size=font_size, content=""), "๊ณต๋ฐฑ ํฌํจ: 0์ / ๊ณต๋ฐฑ ์ ์ธ: 0์", "ํ์๋ ๋ง์ปค(@@)๊ฐ ์์ต๋๋ค." clean_text = input_text.replace('\r', '') len_with_spaces = len(clean_text) len_without_spaces = len(clean_text.replace(' ', '').replace('\n', '')) char_count = f"๊ณต๋ฐฑ ํฌํจ: {len_with_spaces}์ / ๊ณต๋ฐฑ ์ ์ธ: {len_without_spaces}์" char_count = f"๊ณต๋ฐฑ ํฌํจ: {len(clean_text)}์ / ๊ณต๋ฐฑ ์ ์ธ: {len(clean_text.replace(' ', '').replace(chr(10), ''))}์" flat_dict = load_dict() text_for_processing = apply_smart_regex(input_text) flat_dict, pattern = dict_store.get_map_and_pattern() if not flat_dict: final_text = apply_g2p(input_text, ai_mode) if not flat_dict or not pattern: final_text = apply_g2p(text_for_processing, ai_mode) else: sorted_keys = sorted(flat_dict.keys(), key=len, reverse=True) pattern = re.compile("|".join(map(re.escape, sorted_keys))) parts =[] last_end = 0 for match in pattern.finditer(input_text): parts, last_end = [], 0 for match in pattern.finditer(text_for_processing): start, end = match.span() chunk = input_text[last_end:start] if chunk: parts.append(apply_g2p(chunk, ai_mode)) matched_word = match.group() parts.append(flat_dict[matched_word]) if chunk := text_for_processing[last_end:start]: parts.append(apply_g2p(chunk, ai_mode)) parts.append(flat_dict[match.group()]) last_end = end tail = input_text[last_end:] if tail: parts.append(apply_g2p(tail, ai_mode)) if tail := text_for_processing[last_end:]: parts.append(apply_g2p(tail, ai_mode)) final_text = "".join(parts)
if smart_pause: final_text = re.sub(r',\s*', ', / ', final_text)
if auto_break: final_text = final_text.replace(". ", ".\n\n").replace("? ", "?\n\n") 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)
seq = difflib.SequenceMatcher(None, input_text, final_text) html_parts =[] html_parts = [] for tag, i1, i2, j1, j2 in seq.get_opcodes(): chunk = final_text[j1:j2].replace('\n', '<br>') if tag == 'equal': html_parts.append(chunk) elif tag in['replace', 'insert']: html_parts.append(f'<span style="background-color: #ffe066; font-weight: bold; padding: 2px; border-radius: 3px; color: #000;">{chunk}</span>') 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>') 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>' 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) markers = re.findall(r'[^\s]*@@[^\s]*', input_text) unique_markers =[] for m in markers: clean_m = m.strip('.,!?\n') if clean_m and clean_m not in unique_markers: unique_markers.append(clean_m) if unique_markers: marker_result = " / ".join(unique_markers) else: marker_result = "ํ์๋ ๋ง์ปค(@@)๊ฐ ์์ต๋๋ค."
return final_text, html_output, char_count, marker_result 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 "ํ์๋ ๋ง์ปค(@@)๊ฐ ์์ต๋๋ค."
def clear_all(): return "", "", "", "๊ณต๋ฐฑ ํฌํจ: 0์ / ๊ณต๋ฐฑ ์ ์ธ: 0์", "ํ์๋ ๋ง์ปค(@@)๊ฐ ์์ต๋๋ค."def clear_all(font_size=22): return "", "", initial_html_template.format(size=font_size, content=""), "๊ณต๋ฐฑ ํฌํจ: 0์ / ๊ณต๋ฐฑ ์ ์ธ: 0์", "ํ์๋ ๋ง์ปค(@@)๊ฐ ์์ต๋๋ค."
# ==========================================# 3. UI ์ฐ๋ ์ฌ์ ๊ด๋ฆฌ API# ==========================================def add_and_update(word, pronun, current_input, ai_mode, auto_break, smart_pause, font_size): if not word or not pronun: return "โ ๏ธ ๊ธฐ์กด ๋จ์ด์ ์ํ๋ ๋ฐ์์ ๋ชจ๋ ์
๋ ฅํ์ธ์.", gr.update(), gr.update(), gr.update(), gr.update() word = word.strip() pronun = pronun.strip() if len(word) == 1: error_msg = f"๐ซ [๋ฑ๋ก ์คํจ] '{word}'์ฒ๋ผ 1๊ธ์๋ง ๋ฑ๋กํ๋ฉด ์๋ณธ์ด ํผ์๋ฉ๋๋ค! 2๊ธ์ ์ด์์ผ๋ก ๋ฑ๋กํด์ฃผ์ธ์." if current_input and current_input.strip(): final_text, html_output, char_count, marker_result = process_text(current_input, ai_mode, auto_break, smart_pause, font_size) return error_msg, final_text, html_output, char_count, marker_result return error_msg, "", "", "๊ณต๋ฐฑ ํฌํจ: 0์ / ๊ณต๋ฐฑ ์ ์ธ: 0์", "ํ์๋ ๋ง์ปค(@@)๊ฐ ์์ต๋๋ค." 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 ) 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: 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, "", "", "๊ณต๋ฐฑ ํฌํจ: 0์ / ๊ณต๋ฐฑ ์ ์ธ: 0์", "ํ์๋ ๋ง์ปค(@@)๊ฐ ์์ต๋๋ค." return msg, *preview
def load_current_json_to_text(): try: with open(dict_path, "r", encoding="utf-8") as f: data = json.load(f) dict_map = {item[0]: item[1] for item in data.get("items",[]) if len(item) == 2} pretty_json = json.dumps({"items": dict_map}, ensure_ascii=False, indent=4) return pretty_json, "โ
ํ์ฌ ์ฌ์ ์ ์ฑ๊ณต์ ์ผ๋ก ๋ถ๋ฌ์์ต๋๋ค! ์ด์ํ ๋จ์ด๋ฅผ ์ฐพ์ ์ง์ฐ๊ฑฐ๋ ์์ ํด๋ณด์ธ์." return dict_store.get_raw_json_str(), "โ
ํ์ฌ ์ฌ์ ์ ์ฑ๊ณต์ ์ผ๋ก ๋ถ๋ฌ์์ต๋๋ค! ์ด์ํ ๋จ์ด๋ฅผ ์ฐพ์ ์ง์ฐ๊ฑฐ๋ ์์ ํด๋ณด์ธ์." except Exception as e: return "", f"โ ๋ถ๋ฌ์ค๊ธฐ ์คํจ: {e}"
def overwrite_json_text(json_string): if not json_string or not json_string.strip(): return "โ ๏ธ ๋ด์ฉ์ ์
๋ ฅํด์ฃผ์ธ์." try: new_data = json.loads(json_string) if "items" not in new_data: return "โ ๏ธ ์ฌ๋ฐ๋ฅธ ์ฌ์ ํ์์ด ์๋๋๋ค. ('items' ํค๊ฐ ์์ต๋๋ค)" new_items =[] if isinstance(new_data["items"], dict): for k, v in new_data["items"].items(): new_items.append([k.strip(), v.strip()]) elif isinstance(new_data["items"], list): for item in new_data["items"]: if len(item) == 2: new_items.append([item[0].strip(), item[1].strip()])
final_data = {"items": new_items, "meta": {"count": len(new_items)}} with open(dict_path, "w", encoding="utf-8") as f: json.dump(final_data, f, ensure_ascii=False, indent=2) return f"๐จ[๋ฎ์ด์ฐ๊ธฐ ์๋ฃ] ์์ ํ ๋ด์ฉ({len(new_items)}๊ฐ)์ผ๋ก ์ฌ์ ์ ์๋ฒฝํ ๊ต์ฒดํ์ต๋๋ค!" except Exception as e: return f"โ JSON ํ์ฑ ์๋ฌ (๋ฐ์ดํ๋ ์ผํ๊ฐ ๋น ์ก๋์ง ํ์ธํ์ธ์): {e}"
def apply_json_text(json_string): if not json_string or not json_string.strip(): return "โ ๏ธ ๋ด์ฉ์ ์
๋ ฅํด์ฃผ์ธ์."def process_json_input(json_string, overwrite): if not json_string or not json_string.strip(): return "โ ๏ธ ๋ด์ฉ์ ์
๋ ฅํด์ฃผ์ธ์." try: new_data = json.loads(json_string) if "items" not in new_data: return "โ ๏ธ ์ฌ๋ฐ๋ฅธ ์ฌ์ ํ์์ด ์๋๋๋ค." if "items" not in new_data: return "โ ๏ธ ์ฌ๋ฐ๋ฅธ ์ฌ์ ํ์์ด ์๋๋๋ค. ('items' ํค๊ฐ ์์ต๋๋ค)" 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) return f"โ
๊ธฐ์กด ๋จ์ด๋ฅผ ์ ์งํ๋ฉฐ ์ฑ๊ณต์ ์ผ๋ก ํ๋ฌ์ค(+) ํ์ต๋๋ค!" except Exception as e: return f"โ JSON ํ์ฑ ์๋ฌ: {e}"
def get_file(): return dict_path if os.path.exists(dict_path) else None 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}"
def upload_file(file_path): if file_path is not None: shutil.copy(file_path, dict_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) return "โ
ํ์ผ ๋ณต๊ตฌ ์๋ฃ!" return "โ ๏ธ ํ์ผ์ด ์์ต๋๋ค." except Exception as e: return f"โ ๋ณต๊ตฌ ์คํจ: {e}"
# ==========================================# 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; let isSyncing2 = false; let isSyncing3 = false; let isSyncing1 = false, isSyncing2 = false, isSyncing3 = false; document.addEventListener('scroll', function(e) { let target = e.target; let ta1 = document.querySelector('#input_text_area textarea'); let ta2 = document.querySelector('#output_text_area textarea'); let div3 = document.getElementById('prompter_output_div');
let ta1 = document.querySelector('#input_text_area textarea'), ta2 = document.querySelector('#output_text_area textarea'), 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 = """(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;}"""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; }"
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, elem_id="prompter_html_wrap") output_html = gr.HTML(value=initial_html_template.format(size=22, content=""), 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, 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_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_conv.click(fn=process_text, inputs=[input_text, ai_mode, auto_break, smart_pause, font_size], outputs=[output_text, output_html, char_count, marker_collection], api_name=False) btn_clr.click(fn=clear_all, outputs=[input_text, output_text, output_html, char_count, marker_collection], api_name=False) btn_copy.click(fn=None, inputs=[output_text], outputs=None, js="(text) => { if(text) { navigator.clipboard.writeText(text); alert('โ
๋ณต์ฌ ์๋ฃ!'); } }", api_name=False) font_size.change(fn=process_text, inputs=[input_text, ai_mode, auto_break, smart_pause, font_size], outputs=[output_text, output_html, char_count, marker_collection], api_name=False) ai_mode.change(fn=process_text, inputs=[input_text, ai_mode, auto_break, smart_pause, font_size], outputs=[output_text, output_html, char_count, marker_collection], api_name=False) auto_break.change(fn=process_text, inputs=[input_text, ai_mode, auto_break, smart_pause, font_size], outputs=[output_text, output_html, char_count, marker_collection], api_name=False) smart_pause.change(fn=process_text, inputs=[input_text, ai_mode, auto_break, smart_pause, font_size], outputs=[output_text, output_html, char_count, marker_collection], api_name=False) btn_add.click(fn=add_and_update, inputs=[nw, np, input_text, ai_mode, auto_break, smart_pause, font_size], outputs=[status, output_text, output_html, char_count, marker_collection], api_name=False) btn_clear_dict_inputs.click(fn=lambda: ("", ""), outputs=[nw, np], api_name=False) 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])
with gr.Tab("๐ฅ ์๋ ๋ฐฑ์
/์กฐํ/์์ (๋๋ ๋ฑ๋ก)"): dl_btn = gr.DownloadButton("๐ฅ 1. ํ์ฌ ์์ฑ๋ ์ฌ์ ๋ฐฑ์
ํ๊ธฐ (PC ๋ค์ด๋ก๋)") dl_btn.click(fn=get_file, outputs=[dl_btn], api_name=False) dl_btn.click(fn=lambda: dict_path if os.path.exists(dict_path) else None, outputs=[dl_btn]) 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], 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) 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])
gr.Markdown("---") gr.Markdown("### ๐ค 3. ๋ฐฑ์
ํ์ผ๋ก ๋ฎ์ด์ฐ๊ธฐ (โป ์ฃผ์: ๊ธฐ์กด ๋จ์ด ์ด๊ธฐํ๋จ)") up_file = gr.File(label="๋ฐฑ์
ํ์ผ ์
๋ก๋", type="filepath") up_stat = gr.Textbox(label="ํ์ผ ๋ณต๊ตฌ ์ํ ๊ฒฐ๊ณผ์ฐฝ", interactive=False) up_file.upload(fn=upload_file, inputs=[up_file], outputs=[up_stat], api_name=False) up_file.upload(fn=upload_file, inputs=[up_file], outputs=[up_stat])
iface.load(None, js=script_js)
app.py+216-278