Spaces:
Running
Running
Update app.py
Browse files39 unmodified lines40414243434445464 unmodified lines51525354555657585954555657586263646566675960616269707172736364657677786667818283848568697071724 unmodified lines777879808182839798991001011021031041051061071081091101111121131141151161171181198485868788899091124125126127128129130131929394959613513613713813914014114297989910014414510110214714814915015115215310310410510610710815810911016016116216316416516616716816917017117217311111211311411511611717611817811912018018112112212312418518612512618818919019119219319419512712812913013119920013213313420320420520620720820921021121221321421521621721813513613713813914014122422522622722822923023123223323423523623714214314414514614714824314915015115215324824915415515615715825425525625725825926026126226326426526626726826927015916016116216316416516616727327427527627727827928028128228328428528628728828929029116816917017117217317417517629429529629729829930030130230330430530630730830931031131231331431531631731817732032132217817932432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038118018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921038738838921121221321439239321521621721821939622022139822222340140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647722447948048148248348448548648748822522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930049049130130230330430530630730830931031131231331431531631731831932032132232339 unmodified linesBLOCK_WORDS = {"์ด", "๊ฐ", "์", "๋", "์", "๋ฅผ", "ํ๋ค", "์๋ค", "์ ๋ง", "์ง์ง"}
# =========================================================# G2P# G2P ๋ฐ ์ฌ์ ๋ชจ๋# =========================================================g2p = Noneif G2p:4 unmodified lines
@lru_cache(maxsize=5000)def cached_g2p(text): if g2p is None or not text: return text try: return g2p(text) except Exception: return text if g2p is None or not text: return text try: return g2p(text) except: return text
def apply_g2p(text, mode): if not text: return text if g2p is None or mode == "๋๊ธฐ (์๋ ์ฌ์ ๋ง ์ ์ฉ)": return text if mode == "๋งค์ด ๋ง (๋ฌธ์ฅ ํต์งธ๋ก - ์์ฐ์ค๋ฌ์ด ์ฐ์)": return cached_g2p(text) if not text: return text if g2p is None or mode == "๋๊ธฐ (์๋ ์ฌ์ ๋ง ์ ์ฉ)": return text if mode == "๋งค์ด ๋ง (๋ฌธ์ฅ ํต์งธ๋ก - ์์ฐ์ค๋ฌ์ด ์ฐ์)": return cached_g2p(text) if mode == "์ํ ๋ง (๋จ์ด๋ณ ๋๊ธฐ - ๊ณผ๋ํ ์ฐ์ ๋ฐฉ์ง)": words = re.split(r'(\s+)', text) out = [] for w in words: out.append(cached_g2p(w) if w.strip() else w) return "".join(out) return "".join(cached_g2p(w) if w.strip() else w for w in re.split(r'(\s+)', text)) return text
# =========================================================# ์ฌ์ ์บ์ ํด๋์ค# =========================================================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.path, self.auto_words = path, auto_words self.mtime, self.dict_map, self.pattern = None, {}, None self.ensure_file() self.reload(force=True)
4 unmodified lines
def reload(self, force=False): self.ensure_file() try: current_mtime = os.path.getmtime(self.path) except: current_mtime = None if not force and self.mtime == current_mtime: return 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": [], "meta": {"count": 0}}
d = {} for item in data.get("items", []): if isinstance(item, list) and len(item) == 2: k = str(item[0]).strip() v = str(item[1]).strip() if k: d[k] = v
for k, v in self.auto_words: d[k.strip()] = v.strip()
with open(self.path, "r", encoding="utf-8") as f: data = json.load(f) except: data = {"items": []} d = {str(i[0]).strip(): str(i[1]).strip() for i in data.get("items", []) if isinstance(i, list) and len(i) == 2 and str(i[0]).strip()} for k, v in self.auto_words: d[k.strip()] = v.strip() self.dict_map = d self.pattern = re.compile("|".join(map(re.escape, sorted(d.keys(), key=len, reverse=True)))) if d else None self.mtime = current_mtime
def get_map(self): self.reload() return self.dict_map
def get_pattern(self): self.reload() return self.pattern
def get_map(self): self.reload(); return self.dict_map def get_pattern(self): self.reload(); return self.pattern def save_pairs(self, pairs, merge=False): self.reload() base = dict(self.dict_map) if merge else {} for item in pairs: if isinstance(item, list) and len(item) == 2: k = str(item[0]).strip() v = str(item[1]).strip() if k: base[k] = v for k, v in self.auto_words: base[k.strip()] = v.strip()
for i in pairs: if isinstance(i, list) and len(i) == 2 and str(i[0]).strip(): base[str(i[0]).strip()] = str(i[1]).strip() for k, v in self.auto_words: base[k.strip()] = v.strip() final_items = [[k, v] for k, v in base.items()] with open(self.path, "w", encoding="utf-8") as f: json.dump({"items": final_items, "meta": {"count": len(final_items)}}, f, ensure_ascii=False, indent=2) with open(self.path, "w", encoding="utf-8") as f: json.dump({"items": final_items}, f, ensure_ascii=False, indent=2) self.reload(force=True)
def add(self, word, pronun): self.save_pairs([[word, pronun]], merge=True)
def export_text(self): self.reload() return json.dumps({"items": self.dict_map}, ensure_ascii=False, indent=4) def add(self, word, pronun): self.save_pairs([[word, pronun]], merge=True) def export_text(self): self.reload(); return json.dumps({"items": self.dict_map}, ensure_ascii=False, indent=4)
dict_store = DictStore(dict_path, AUTO_MERGE_WORDS)
# =========================================================# ์ ํธ ๋ฐ ์ซ์/๋จ์ ์์ง# ์ ํธ ๋ฐ ์ซ์ ์์ง# =========================================================def normalize_text(text): return (text or "").replace("\r\n", "\n").replace("\r", "\n")
def safe_html(text): return html.escape(text).replace("\n", "<br>")
def build_count_text(original_text, final_text): o = normalize_text(original_text) f = normalize_text(final_text) o_ws = len(o) o_nws = len(o.replace(" ", "").replace("\n", "")) f_ws = len(f) f_nws = len(f.replace(" ", "").replace("\n", "")) return f"์๋ณธ ๊ณต๋ฐฑ ํฌํจ: {o_ws}์ / ๊ณต๋ฐฑ ์ ์ธ: {o_nws}์\n๋ณํ ํ ๊ณต๋ฐฑ ํฌํจ: {f_ws}์ / ๊ณต๋ฐฑ ์ ์ธ: {f_nws}์"def normalize_text(text): return (text or "").replace("\r\n", "\n").replace("\r", "\n")def safe_html(text): return html.escape(text).replace("\n", "<br>")def build_count_text(o, f): o, f = normalize_text(o), normalize_text(f) return f"์๋ณธ ๊ณต๋ฐฑ ํฌํจ: {len(o)}์ / ๊ณต๋ฐฑ ์ ์ธ: {len(o.replace(' ', '').replace(chr(10), ''))}์\n๋ณํ ํ ๊ณต๋ฐฑ ํฌํจ: {len(f)}์ / ๊ณต๋ฐฑ ์ ์ธ: {len(f.replace(' ', '').replace(chr(10), ''))}์"
def extract_markers(text): markers = re.findall(r'[^\s]*@@[^\s]*', text or "") seen = [] for m in markers: for m in re.findall(r'[^\s]*@@[^\s]*', text or ""): m = m.strip(".,!?\n ") if m and m not in seen: seen.append(m) if m and m not in seen: seen.append(m) return " / ".join(seen) if seen else "ํ์๋ ๋ง์ปค(@@)๊ฐ ์์ต๋๋ค."
def protect_tokens(text): protected = {} idx = 0 protected, idx = {}, [0] def repl(m): nonlocal idx key = f"__P{idx}__" protected[key] = m.group(0) idx += 1 return key patterns = [r'https?://\S+', r'\b\S+@\S+\.\S+\b', r'\b\d{2,4}-\d{3,4}-\d{4}\b', r'[^\s]*@@[^\s]*'] for p in patterns: text = re.sub(p, repl, text) k = f"__P{idx[0]}__"; protected[k] = m.group(0); idx[0] += 1; return k for p in [r'https?://\S+', r'\b\S+@\S+\.\S+\b', r'\b\d{2,4}-\d{3,4}-\d{4}\b', r'[^\s]*@@[^\s]*']: text = re.sub(p, repl, text) return text, protected
def restore_tokens(text, protected): for k, v in protected.items(): text = text.replace(k, v) for k, v in protected.items(): text = text.replace(k, v) return text
DIGITS = ["์", "์ผ", "์ด", "์ผ", "์ฌ", "์ค", "์ก", "์น ", "ํ", "๊ตฌ"]SMALL_UNITS = ["์ฒ", "๋ฐฑ", "์ญ", ""]LARGE_UNITS = ["", "๋ง", "์ต", "์กฐ"]NATIVE_1_20 = {1: "ํ", 2: "๋", 3: "์ธ", 4: "๋ค", 5: "๋ค์ฏ", 6: "์ฌ์ฏ", 7: "์ผ๊ณฑ", 8: "์ฌ๋", 9: "์ํ", 10: "์ด", 11: "์ดํ", 12: "์ด๋", 13: "์ด์ธ", 14: "์ด๋ค", 15: "์ด๋ค์ฏ", 16: "์ด์ฌ์ฏ", 17: "์ด์ผ๊ณฑ", 18: "์ด์ฌ๋", 19: "์ด์ํ", 20: "์ค๋ฌด"}
def read_four_digits(n): s = str(n).zfill(4) parts = [] for i, ch in enumerate(s): d = int(ch) if d == 0: continue unit = SMALL_UNITS[i] if d == 1 and unit: parts.append(unit) else: parts.append(DIGITS[d] + unit) return "".join(parts)
DIGITS, SMALL_UNITS, LARGE_UNITS = ["์", "์ผ", "์ด", "์ผ", "์ฌ", "์ค", "์ก", "์น ", "ํ", "๊ตฌ"], ["์ฒ", "๋ฐฑ", "์ญ", ""], ["", "๋ง", "์ต", "์กฐ"]def read_four_digits(n): return "".join(SMALL_UNITS[i] if d==1 and SMALL_UNITS[i] else DIGITS[d]+SMALL_UNITS[i] for i, d in enumerate(map(int, str(n).zfill(4))) if d!=0)def number_to_korean(n): try: n = int(str(n).replace(",", "")) except: return str(n) if n == 0: return "์" s = str(n) groups = [] while s: groups.insert(0, s[-4:]) s = s[:-4] result = [] total = len(groups) for i, g in enumerate(groups): gi = int(g) if gi == 0: continue read = read_four_digits(gi) large = LARGE_UNITS[total - i - 1] if read == "์ผ" and large: result.append(large) else: result.append(read + large) return " ".join(result).strip() groups = [s[max(0, i-4):i] for i in range(len(s), 0, -4)][::-1] return " ".join(large if (read := read_four_digits(int(g))) == "์ผ" and large else read + large for i, g in enumerate(groups) if int(g) != 0 for large in [LARGE_UNITS[len(groups) - i - 1]]).strip()
def counter_to_korean(n, unit): try: n = int(str(n).replace(",", "")) except: return str(n) if unit in {"๊ฐ", "ํฉ", "์ธํธ", "๋ณ", "ํฌ", "๋งค"} and 1 <= n <= 20: return NATIVE_1_20[n] return {1:"ํ", 2:"๋", 3:"์ธ", 4:"๋ค", 5:"๋ค์ฏ", 6:"์ฌ์ฏ", 7:"์ผ๊ณฑ", 8:"์ฌ๋", 9:"์ํ", 10:"์ด", 11:"์ดํ", 12:"์ด๋", 13:"์ด์ธ", 14:"์ด๋ค", 15:"์ด๋ค์ฏ", 16:"์ด์ฌ์ฏ", 17:"์ด์ผ๊ณฑ", 18:"์ด์ฌ๋", 19:"์ด์ํ", 20:"์ค๋ฌด"}[n] return number_to_korean(n)
def apply_rules(text): if not text: return text fixed = {r'\b1\+1\b': "์ํ๋ฌ์ค์", r'\b2\+1\b': "ํฌํ๋ฌ์ค์", r'\bSS\b': "์์ค์์ค", r'\bFW\b': "์ํ๋๋ธ์ ", r'\bS/S\b': "์์ค์์ค", r'\bF/W\b': "์ํ๋๋ธ์ ", r'\bUV\b': "์ ๋ธ์ด", r'\bLED\b': "์์ด๋", r'\bVIP\b': "๋ธ์ด์์ดํผ", r'\bA/S\b': "์์ด์์ค", r'\bAS\b': "์์ด์์ค"} for p, r in fixed.items(): text = re.sub(p, r, text) for p, r in {r'\b1\+1\b': "์ํ๋ฌ์ค์", r'\b2\+1\b': "ํฌํ๋ฌ์ค์", r'\bS/S\b': "์์ค์์ค", r'\bF/W\b': "์ํ๋๋ธ์ ", r'\bSS\b': "์์ค์์ค", r'\bFW\b': "์ํ๋๋ธ์ ", r'\bUV\b': "์ ๋ธ์ด", r'\bLED\b': "์์ด๋", r'\bVIP\b': "๋ธ์ด์์ดํผ", r'\bA/S\b': "์์ด์์ค", r'\bAS\b': "์์ด์์ค"}.items(): text = re.sub(p, r, text) text = re.sub(r'\b(\d{2})\s*(SS|S/S)\b', lambda m: f"{number_to_korean(m.group(1))} ์์ค์์ค", text) text = re.sub(r'\b(\d{2})\s*(FW|F/W)\b', lambda m: f"{number_to_korean(m.group(1))} ์ํ๋๋ธ์ ", text) text = re.sub(r'(\d+)\s*%', lambda m: f"{number_to_korean(m.group(1))} ํผ์ผํธ", text) text = re.sub(r'(\d{1,3}(?:,\d{3})+|\d+)\s*์', lambda m: f"{number_to_korean(m.group(1))} ์", text) size_map = {"55": "์ค์ค", "66": "์ก์ก", "77": "์น ์น ", "88": "ํํ"} text = re.sub(r'\b(55|66|77|88)\s*์ฌ์ด์ฆ\b', lambda m: f"{size_map[m.group(1)]} ์ธ์ด์ฆ", text) def unit_repl(m): num, unit = m.group(1), m.group(2) if unit in {"๊ฐ", "ํฉ", "์ธํธ", "๋ณ", "ํฌ", "๋งค"}: return f"{counter_to_korean(num, unit)} {unit}" if unit == "๊ฐ์": return f"{number_to_korean(num)}๊ฐ์" unit_map = {"๋
": "๋
", "์ข
": "์ข
", "๋ถ": "๋ถ", "์ด": "์ด", "์๊ฐ": "์๊ฐ", "ml": "๋ฐ๋ฆฌ๋ฆฌํฐ", "mL": "๋ฐ๋ฆฌ๋ฆฌํฐ", "ML": "๋ฐ๋ฆฌ๋ฆฌํฐ", "L": "๋ฆฌํฐ", "kg": "ํฌ๋ก๊ทธ๋จ", "g": "๊ทธ๋จ", "cm": "์ผํฐ๋ฏธํฐ", "mm": "๋ฐ๋ฆฌ๋ฏธํฐ"} return f"{number_to_korean(num)} {unit_map.get(unit, unit)}" text = re.sub(r'(\d+)\s*(๊ฐ์|๋
|๊ฐ|์ข
|ํฉ|์ธํธ|๋ณ|ํฌ|๋งค|๋ถ|์ด|์๊ฐ|ml|mL|ML|L|kg|g|cm|mm)\b', unit_repl, text) return text
def transform_chunk(chunk, ai_mode): if not chunk: return chunk if re.fullmatch(r'__P\d+__', chunk): return chunk chunk = apply_rules(chunk) chunk = apply_g2p(chunk, ai_mode) return chunk text = re.sub(r'\b(55|66|77|88)\s*์ฌ์ด์ฆ\b', lambda m: f"{dict(zip(['55','66','77','88'],['์ค์ค','์ก์ก','์น ์น ','ํํ']))[m.group(1)]} ์ธ์ด์ฆ", text) def ur(m): n, u = m.group(1), m.group(2) if u in {"๊ฐ", "ํฉ", "์ธํธ", "๋ณ", "ํฌ", "๋งค"}: return f"{counter_to_korean(n, u)} {u}" if u == "๊ฐ์": return f"{number_to_korean(n)}๊ฐ์" return f"{number_to_korean(n)} {{'๋
':'๋
','์ข
':'์ข
','๋ถ':'๋ถ','์ด':'์ด','์๊ฐ':'์๊ฐ','ml':'๋ฐ๋ฆฌ๋ฆฌํฐ','mL':'๋ฐ๋ฆฌ๋ฆฌํฐ','ML':'๋ฐ๋ฆฌ๋ฆฌํฐ','L':'๋ฆฌํฐ','kg':'ํฌ๋ก๊ทธ๋จ','g':'๊ทธ๋จ','cm':'์ผํฐ๋ฏธํฐ','mm':'๋ฐ๋ฆฌ๋ฏธํฐ'}}.get(u, u)" return re.sub(r'(\d+)\s*(๊ฐ์|๋
|๊ฐ|์ข
|ํฉ|์ธํธ|๋ณ|ํฌ|๋งค|๋ถ|์ด|์๊ฐ|ml|mL|ML|L|kg|g|cm|mm)\b', ur, text)
def replace_dict_and_transform(text, ai_mode): flat_dict = dict_store.get_map() pattern = dict_store.get_pattern() if not flat_dict or pattern is None: parts = re.split(r'(__P\d+__)', text) return "".join(transform_chunk(p, ai_mode) for p in parts if p is not None) parts = [] last_end = 0 for match in pattern.finditer(text): start, end = match.span() if start > last_end: before = text[last_end:start] before_parts = re.split(r'(__P\d+__)', before) parts.extend(transform_chunk(p, ai_mode) for p in before_parts if p is not None) parts.append(flat_dict.get(match.group(0), match.group(0))) last_end = end if last_end < len(text): tail = text[last_end:] tail_parts = re.split(r'(__P\d+__)', tail) parts.extend(transform_chunk(p, ai_mode) for p in tail_parts if p is not None) d, p = dict_store.get_map(), dict_store.get_pattern() if not d or not p: return "".join(apply_g2p(apply_rules(c), ai_mode) if not re.fullmatch(r'__P\d+__', c) else c for c in re.split(r'(__P\d+__)', text) if c) parts, last = [], 0 for m in p.finditer(text): if m.start() > last: parts.extend(apply_g2p(apply_rules(c), ai_mode) if not re.fullmatch(r'__P\d+__', c) else c for c in re.split(r'(__P\d+__)', text[last:m.start()]) if c) parts.append(d.get(m.group(0), m.group(0))); last = m.end() if last < len(text): parts.extend(apply_g2p(apply_rules(c), ai_mode) if not re.fullmatch(r'__P\d+__', c) else c for c in re.split(r'(__P\d+__)', text[last:]) if c) return "".join(parts)
def apply_pause_and_break(text, auto_break, smart_pause): if smart_pause: text = re.sub(r',\s*', ', / ', text) text = re.sub(r'\s(๊ทธ๋ฆฌ๊ณ |ํ์ง๋ง|๊ทธ๋์|ํนํ|๋ํ|๋ค๋ง)\s', r' / \1 ', text) text = re.sub(r'\s*/\s*/\s*', ' / ', text) if auto_break: text = re.sub(r'([.?!])\s+', r'\1\n\n', text) text = re.sub(r',\s*/\s*', ',\n', text) text = re.sub(r'\n{3,}', '\n\n', text) return text.strip()
def render_html(original_text, final_text, font_size): if len(original_text) + len(final_text) > 45000: raw_html = safe_html(final_text) else: seq = difflib.SequenceMatcher(None, original_text, final_text) html_parts = [] for tag, i1, i2, j1, j2 in seq.get_opcodes(): chunk = safe_html(final_text[j1:j2]) 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) return f'<div id="prompter_label_space">๐บ ํ๋กฌํํฐ ๋ทฐ (๋ณ๊ฒฝ์ ํ์ธ)</div><div id="prompter_output_div" style="font-size:{font_size}px;">{raw_html}</div>'
def process_text(input_text, ai_mode, auto_break, smart_pause, font_size): input_text = normalize_text(input_text) if 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์", "๋ง์ปค ์์", "", "" if not (input_text := normalize_text(input_text)).strip(): return "", f'<div id="prompter_output_div" style="font-size:{font_size}px;"></div>', "์๋ณธ 0์ / ๋ณํ 0์", "๋ง์ปค ์์", "", "" try: protected_text, protected_map = protect_tokens(input_text) final_text = replace_dict_and_transform(protected_text, ai_mode) final_text = restore_tokens(final_text, protected_map) final_text = apply_pause_and_break(final_text, auto_break, smart_pause) html_output = render_html(input_text, final_text, font_size) char_count = build_count_text(input_text, final_text) marker_result = extract_markers(input_text) return final_text, html_output, char_count, marker_result, input_text, final_text except Exception as e: fallback = input_text return fallback, f'<div id="prompter_output_div" style="font-size:{font_size}px;">์ค๋ฅ: {e}</div>', build_count_text(input_text, fallback), f"์ค๋ฅ ๋ฐ์", input_text, fallback
def rerender_only(original_text, final_text, font_size): return render_html(original_text or "", final_text or "", font_size)
def clear_all(): return "", "", '<div id="prompter_label_space">๐บ ํ๋กฌํํฐ ๋ทฐ</div><div id="prompter_output_div" style="font-size:22px;"></div>', "์๋ณธ 0์ / ๋ณํ 0์", "๋ง์ปค ์์", "", ""
# =========================================================# ์ฌ์ ๊ด๋ฆฌ API# =========================================================def validate_word(word): word = (word or "").strip() if not word: return False, "โ ๏ธ ๋จ์ด๋ฅผ ์
๋ ฅํ์ธ์." if len(word) == 1: return False, "๐ซ 1๊ธ์๋ ๋ฑ๋ก ๋ถ๊ฐ." if word in BLOCK_WORDS: return False, "๐ซ ๋ฒ์ฉ ๋จ์ด ๋ฑ๋ก ๋ถ๊ฐ." return True, ""
def add_and_update(word, pronun, current_input, ai_mode, auto_break, smart_pause, font_size): word, pronun = (word or "").strip(), (pronun or "").strip() if not word or not pronun: return "โ ๏ธ ๋ชจ๋ ์
๋ ฅํ์ธ์.", *process_text(current_input, ai_mode, auto_break, smart_pause, font_size) ok, msg = validate_word(word) if not ok: return msg, *process_text(current_input, ai_mode, auto_break, smart_pause, font_size) dict_store.add(word, pronun) return f"โ
'{word}' ์ ์ฅ ์๋ฃ!", *process_text(current_input, ai_mode, auto_break, smart_pause, font_size)
def load_current_json_to_text(): return dict_store.export_text(), "โ
์ฌ์ ์ ๋ถ๋ฌ์์ต๋๋ค!"
def apply_json_text(json_string): data = json.loads(json_string) pairs = [[k, v] for item in data["items"] for k, v in (item.items() if isinstance(data["items"], dict) else [item])] dict_store.save_pairs(pairs, merge=True) return "โ
ํ๋ฌ์ค ์๋ฃ!"
def overwrite_json_text(json_string): data = json.loads(json_string) pairs = [[k, v] for item in data["items"] for k, v in (item.items() if isinstance(data["items"], dict) else [item])] dict_store.save_pairs(pairs, merge=False) return "๐จ ๋ฎ์ด์ฐ๊ธฐ ์๋ฃ!"
def get_file(): return dict_path if os.path.exists(dict_path) else Nonedef upload_file(file_path): with open(file_path, "r", encoding="utf-8") as f: data = json.load(f) pairs = [[k, v] for item in data["items"] for k, v in (item.items() if isinstance(data["items"], dict) else [item])] dict_store.save_pairs(pairs, merge=False) return "โ
ํ์ผ ๋ณต๊ตฌ ์๋ฃ!" pt, pm = protect_tokens(input_text) ft = restore_tokens(replace_dict_and_transform(pt, ai_mode), pm) if smart_pause: ft = re.sub(r'\s*/\s*/\s*', ' / ', re.sub(r'\s(๊ทธ๋ฆฌ๊ณ |ํ์ง๋ง|๊ทธ๋์|ํนํ|๋ํ|๋ค๋ง)\s', r' / \1 ', re.sub(r',\s*', ', / ', ft))) if auto_break: ft = re.sub(r',\s*/\s*', ',\n', re.sub(r'([.?!])\s+', r'\1\n\n', ft)) ft = re.sub(r'\n{3,}', '\n\n', ft.strip()) rh = safe_html(ft) if len(input_text)+len(ft)>45000 else "".join(safe_html(ft[j1:j2]) if t=="equal" else f'<span style="background-color:#ffe066; font-weight:bold; color:#000;">{safe_html(ft[j1:j2])}</span>' for t, i1, i2, j1, j2 in difflib.SequenceMatcher(None, input_text, ft).get_opcodes()) rh = re.sub(r'([^\s<]*@@[^\s<]*)', r'<span style="background-color:#ff4d4d; color:white; padding:2px;">\1</span>', rh) return ft, f'<div id="prompter_output_div" style="font-size:{font_size}px;">{rh}</div>', build_count_text(input_text, ft), extract_markers(input_text), input_text, ft except Exception as e: return input_text, f'<div id="prompter_output_div">์ค๋ฅ: {e}</div>', "์ค๋ฅ", "์ค๋ฅ", input_text, input_text
def validate_word(w): w = (w or "").strip() return (False, "๋จ์ด ์
๋ ฅ ์๋ง") if not w else (False, "1๊ธ์ ๋ถ๊ฐ") if len(w)==1 else (False, "๋ฒ์ฉ๋จ์ด ๋ถ๊ฐ") if w in BLOCK_WORDS else (True, "")
def add_and_update(w, p, ci, am, ab, sp, fs): w, p = (w or "").strip(), (p or "").strip() ok, msg = validate_word(w) if not w or not p or not ok: return msg if not ok else "๋ชจ๋ ์
๋ ฅ ์๋ง", *process_text(ci, am, ab, sp, fs) dict_store.add(w, p) return f"โ
'{w}' ์ ์ฅ๋จ!", *process_text(ci, am, ab, sp, fs)
def r_html(o, f, fs): return process_text(o, "๋๊ธฐ (์๋ ์ฌ์ ๋ง ์ ์ฉ)", False, False, fs)[1]def load_json(): return dict_store.export_text(), "๋ถ๋ฌ์ด!"def app_json(j): dict_store.save_pairs([[k, v] for i in json.loads(j)["items"] for k, v in (i.items() if isinstance(json.loads(j)["items"], dict) else [i])], True); return "ํ๋ฌ์ค ์๋ฃ!"def over_json(j): dict_store.save_pairs([[k, v] for i in json.loads(j)["items"] for k, v in (i.items() if isinstance(json.loads(j)["items"], dict) else [i])], False); return "๋ฎ์ด์ฐ๊ธฐ ์๋ฃ!"
# =========================================================# CSS / JS# =========================================================custom_css = """#prompter_html_wrap, #prompter_html_wrap .prose { width: 100% !important; max-width: 100% !important; margin: 0 !important; padding: 0 !important; text-align: left !important; }#input_text_area textarea, #output_text_area textarea, #prompter_output_div { font-family: sans-serif !important; }#input_text_area textarea, #prompter_output_div { height: 500px !important; overflow-y: auto !important; padding: 16px !important; line-height: 1.8 !important; white-space: pre-wrap !important; }#prompter_html_wrap { width: 100% !important; margin: 0 !important; }#input_text_area textarea, #output_text_area textarea, #prompter_output_div { font-family: sans-serif !important; height: 500px !important; overflow-y: auto !important; padding: 16px !important; line-height: 1.8 !important; white-space: pre-wrap !important; }#prompter_output_div { background-color: #333 !important; color: #fff !important; border-radius: 8px !important; }"""script_js = "function() { setTimeout(()=> { let t1=document.querySelector('#input_text_area textarea'); if(t1) t1.style.fontSize='22px'; let t2=document.querySelector('#output_text_area textarea'); if(t2){ t2.style.fontSize='22px'; t2.style.lineHeight='1.8';} }, 500); }"insert_marker_js = "(t) => { let ta = document.querySelector('#input_text_area textarea'); if (!ta) return t; let s = ta.selectionStart, e = ta.selectionEnd, val = ta.value; ta.value = val.substring(0, s) + '@@' + val.substring(e); ta.dispatchEvent(new Event('input', { bubbles: true })); ta.selectionStart = ta.selectionEnd = s + 2; ta.focus(); return ta.value; }"js_sync = "() => { setTimeout(()=> { let t1=document.querySelector('#input_text_area textarea'); if(t1) t1.style.fontSize='22px'; let t2=document.querySelector('#output_text_area textarea'); if(t2){ t2.style.fontSize='22px'; t2.style.lineHeight='1.8';} }, 500); }"js_marker = "(t) => { let ta = document.querySelector('#input_text_area textarea'); if (!ta) return t; let s = ta.selectionStart, e = ta.selectionEnd, v = ta.value; ta.value = v.substring(0, s) + '@@' + v.substring(e); ta.dispatchEvent(new Event('input', { bubbles: true })); ta.selectionStart = ta.selectionEnd = s + 2; ta.focus(); return ta.value; }"js_copy = "(t) => { if(t){ navigator.clipboard.writeText(t); alert('๋ณต์ฌ ์๋ฃ!'); } }"
# =========================================================# UI ๊ตฌ์ฑ# UI ๊ตฌ์ฑ (์๋ฌ์๋ ์ปค์คํ
๋ก๊ทธ์ธ ํฌํจ)# =========================================================# โ
์๋ฌ์ ์์ธ์ด์๋ ssr=False ์ ๊ฑฐ ์๋ฃwith gr.Blocks(theme="default", css=custom_css) as iface: gr.Markdown("## ๐๏ธ ๋๋ง์ TTS ์ ์ฒ๋ฆฌ ๋ณํ๊ธฐ") last_o = gr.State("") last_f = gr.State("")
with gr.Tabs(): with gr.Tab("๐๏ฟฝ๏ฟฝ ๋ฉ์ธ ํ๋ฉด"): with gr.Row(): with gr.Column(): input_text = gr.Textbox(label="1๏ธโฃ ์๋ณธ ํ
์คํธ", elem_id="input_text_area") with gr.Group(): auto_break = gr.Checkbox(label="๐ ๋ฌธ์ฅ ๋ ์๋ ์ค๋ฐ๊ฟ", value=False) smart_pause = gr.Checkbox(label="โฑ๏ธ ํธํก์ ( / ) ์ถ๊ฐ", value=False) btn_marker = gr.Button("๐จ ๋ง์ปค(@@) ์ฝ์
", size="sm") font_size = gr.Slider(minimum=16, maximum=40, value=22, step=2, label="๐ ๊ธ์ ํฌ๊ธฐ") # ๐ก ๊ด๋ฆฌ์ ์ ์ฉ ์์ฝ๋์ธ (๊ธฐ๋ณธ ์จ๊น) with gr.Accordion("โ๏ธ ๊ด๋ฆฌ์ ์ ์ฉ ๊ณ ๊ธ ์ค์ ", open=False, visible=False) as admin_accordion: ai_mode = gr.Radio(["๋๊ธฐ (์๋ ์ฌ์ ๋ง ์ ์ฉ)", "์ํ ๋ง (๋จ์ด๋ณ ๋๊ธฐ - ๊ณผ๋ํ ์ฐ์ ๋ฐฉ์ง)", "๋งค์ด ๋ง (๋ฌธ์ฅ ํต์งธ๋ก - ์์ฐ์ค๋ฌ์ด ์ฐ์)"], value="๋๊ธฐ (์๋ ์ฌ์ ๋ง ์ ์ฉ)", label="๐ค AI ๊ฐ๋")
char_count = gr.Textbox(label="๊ธ์ ์", interactive=False) with gr.Row(): btn_conv = gr.Button("โจ ๋ณํํ๊ธฐ", variant="primary") btn_copy = gr.Button("๐ ๋ณต์ฌ", variant="secondary") btn_clr = gr.Button("๐๏ธ ์ด๊ธฐํ", variant="stop")
with gr.Column(): output_html = gr.HTML('<div id="prompter_output_div"></div>', 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_col = gr.Textbox(label="๐จ ์์ ํ์ ๋จ์ด (@@)", interactive=False)
gr.Markdown("---") with gr.Row(): nw = gr.Textbox(label="๊ธฐ์กด ๋จ์ด (2๊ธ์ ์ด์)") np = gr.Textbox(label="์ํ๋ ๋ฐ์") btn_add = gr.Button("๐พ ์ ์ฅ ํ ์ฆ์ ๋ณํ", variant="primary") status = gr.Textbox(label="์ํ", interactive=False)
# ์ด๋ฒคํธ ์ฐ๊ฒฐ btn_marker.click(None, input_text, input_text, js=insert_marker_js).then(process_text, [input_text, ai_mode, auto_break, smart_pause, font_size], [output_text, output_html, char_count, marker_col, last_o, last_f]) btn_conv.click(process_text, [input_text, ai_mode, auto_break, smart_pause, font_size], [output_text, output_html, char_count, marker_col, last_o, last_f]) btn_clr.click(clear_all, None, [input_text, output_text, output_html, char_count, marker_col, last_o, last_f]) btn_copy.click(None, output_text, None, js="(t) => { if(t){ navigator.clipboard.writeText(t); alert('๋ณต์ฌ ์๋ฃ!'); } }") font_size.change(rerender_only, [last_o, last_f, font_size], output_html) for comp in [ai_mode, auto_break, smart_pause]: comp.change(process_text, [input_text, ai_mode, auto_break, smart_pause, font_size], [output_text, output_html, char_count, marker_col, last_o, last_f]) btn_add.click(add_and_update, [nw, np, input_text, ai_mode, auto_break, smart_pause, font_size], [status, output_text, output_html, char_count, marker_col, last_o, last_f])
with gr.Tab("๐ฅ ๋ฐฑ์
/์กฐํ"): dl_btn = gr.DownloadButton("๐ฅ ๋ฐฑ์
ํ๊ธฐ") dl_btn.click(get_file, None, dl_btn) btn_load = gr.Button("๐ ๋จ์ด ๋ถ๋ฌ์ค๊ธฐ") json_in = gr.Textbox(lines=10, label="๋ฐ์ดํฐ") btn_apply = gr.Button("๐ ๊ธฐ์กด์ ํ๋ฌ์ค") btn_over = gr.Button("๐จ ์์ ํ ๋ฎ์ด์ฐ๊ธฐ") json_stat = gr.Textbox(label="์ํ") btn_load.click(load_current_json_to_text, None, [json_in, json_stat]) btn_apply.click(apply_json_text, json_in, json_stat) btn_over.click(overwrite_json_text, json_in, json_stat) up_file = gr.File(label="๋ฐฑ์
ํ์ผ ์
๋ก๋") up_stat = gr.Textbox(label="์ํ") up_file.upload(upload_file, up_file, up_stat)
# ๐ก ์ ์ํ ์์ด๋๊ฐ 'a'์ผ ๋๋ง ๊ด๋ฆฌ์ ๋ฉ๋ด๋ฅผ ๋ณด์ฌ์ฃผ๋ ํจ์ def check_admin(request: gr.Request): if request and request.username == "a": return gr.update(visible=True) return gr.update(visible=False)
iface.load(check_admin, None, admin_accordion) iface.load(None, js=script_js)
if __name__ == "__main__": import os import json auth_list = [] hf_secrets = os.getenv("AUTH_USERS") if hf_secrets: try: secrets_dict = json.loads(hf_secrets) auth_list = [(k, v) for k, v in secrets_dict.items()] except Exception as e: print(f"์ํฌ๋ฆฟ ์๋ฌ: {e}") # ์ํฌ๋ฆฟ์ด ์์ผ๋ฉด ์์๋ก a/1, User1/1111 ์ ์ฉ if not auth_list: auth_list = [("a", "1"), ("User1", "1111")] # --------------------------------------------------------- # 1. ์ปค์คํ
๋ก๊ทธ์ธ ํ๋ฉด (์๋ฌ ๋ฐฉ์ง 100%) # --------------------------------------------------------- with gr.Column(visible=True) as login_view: gr.Markdown("### ๐ ์ฌ์ฉ์ ์ํด ๋ก๊ทธ์ธํด ์ฃผ์ธ์.") with gr.Row(): in_id = gr.Textbox(label="์์ด๋", placeholder="์์ด๋๋ฅผ ์
๋ ฅํ์ธ์") in_pw = gr.Textbox(label="๋น๋ฐ๋ฒํธ", placeholder="๋น๋ฐ๋ฒํธ๋ฅผ ์
๋ ฅํ์ธ์", type="password") btn_login = gr.Button("๐ ์ ์ํ๊ธฐ", variant="primary") login_msg = gr.Textbox(label="์๋ฆผ", interactive=False)
# --------------------------------------------------------- # 2. ๋ฉ์ธ ์ฑ ํ๋ฉด (๋ก๊ทธ์ธ ์ฑ๊ณต ์ ๋ณด์) # --------------------------------------------------------- with gr.Column(visible=False) as main_view: last_o, last_f = gr.State(""), gr.State("") with gr.Tabs(): with gr.Tab("๐๏ธ ๋ฉ์ธ ํ๋ฉด"): with gr.Row(): with gr.Column(): in_txt = gr.Textbox(label="1๏ธโฃ ์๋ณธ ํ
์คํธ", elem_id="input_text_area") with gr.Group(): auto_b = gr.Checkbox(label="๐ ๋ฌธ์ฅ ๋ ์๋ ์ค๋ฐ๊ฟ", value=False) smart_p = gr.Checkbox(label="โฑ๏ธ ํธํก์ ( / ) ์ถ๊ฐ", value=False) btn_mk = gr.Button("๐จ ๋ง์ปค(@@) ์ฝ์
", size="sm") fs = gr.Slider(16, 40, 22, step=2, label="๐ ๊ธ์ ํฌ๊ธฐ") # ๊ด๋ฆฌ์ ์ ์ฉ ์์ฝ๋์ธ (๊ธฐ๋ณธ ์จ๊น) with gr.Accordion("โ๏ธ ๊ด๋ฆฌ์ ์ ์ฉ ๊ณ ๊ธ ์ค์ ", open=False, visible=False) as admin_acc: ai_m = gr.Radio(["๋๊ธฐ (์๋ ์ฌ์ ๋ง ์ ์ฉ)", "์ํ ๋ง (๋จ์ด๋ณ ๋๊ธฐ)", "๋งค์ด ๋ง (๋ฌธ์ฅ ํต์งธ๋ก)"], value="๋๊ธฐ (์๋ ์ฌ์ ๋ง ์ ์ฉ)", label="๐ค AI ๊ฐ๋")
cnt = gr.Textbox(label="๊ธ์ ์", interactive=False) with gr.Row(): btn_conv = gr.Button("โจ ๋ณํํ๊ธฐ", variant="primary") btn_cp = gr.Button("๐ ๋ณต์ฌ", variant="secondary") btn_clr = gr.Button("๐๏ธ ์ด๊ธฐํ", variant="stop")
with gr.Column(): out_html = gr.HTML('<div id="prompter_output_div"></div>', elem_id="prompter_html_wrap") with gr.Accordion("๐ ์์ ํ
์คํธ ๊ฒฐ๊ณผ (๋ณต์ฌ์ฉ)", open=False): out_txt = gr.Textbox(lines=8, show_label=False, show_copy_button=True, elem_id="output_text_area") mk_col = gr.Textbox(label="๐จ ์์ ํ์ ๋จ์ด (@@)", interactive=False)
gr.Markdown("---") with gr.Row(): nw, np = gr.Textbox(label="๊ธฐ์กด ๋จ์ด (2๊ธ์ ์ด์)"), gr.Textbox(label="์ํ๋ ๋ฐ์") btn_add = gr.Button("๐พ ์ ์ฅ ํ ์ฆ์ ๋ณํ", variant="primary") stat = gr.Textbox(label="์ํ", interactive=False)
# ์ด๋ฒคํธ ์ฐ๊ฒฐ btn_mk.click(None, in_txt, in_txt, js=js_marker).then(process_text, [in_txt, ai_m, auto_b, smart_p, fs], [out_txt, out_html, cnt, mk_col, last_o, last_f]) btn_conv.click(process_text, [in_txt, ai_m, auto_b, smart_p, fs], [out_txt, out_html, cnt, mk_col, last_o, last_f]) btn_clr.click(lambda: ("","",'<div id="prompter_output_div"></div>',"","","",""), None, [in_txt, out_txt, out_html, cnt, mk_col, last_o, last_f]) btn_cp.click(None, out_txt, None, js=js_copy) fs.change(r_html, [last_o, last_f, fs], out_html) for c in [ai_m, auto_b, smart_p]: c.change(process_text, [in_txt, ai_m, auto_b, smart_p, fs], [out_txt, out_html, cnt, mk_col, last_o, last_f]) btn_add.click(add_and_update, [nw, np, in_txt, ai_m, auto_b, smart_p, fs], [stat, out_txt, out_html, cnt, mk_col, last_o, last_f])
with gr.Tab("๐ฅ ๋ฐฑ์
/์กฐํ"): dl_btn = gr.DownloadButton("๐ฅ ๋ฐฑ์
ํ๊ธฐ") dl_btn.click(get_file, None, dl_btn) json_in, j_stat = gr.Textbox(lines=10, label="๋ฐ์ดํฐ"), gr.Textbox(label="์ํ") with gr.Row(): btn_ld, btn_ap, btn_ov = gr.Button("๐ ๋ถ๋ฌ์ค๊ธฐ"), gr.Button("๐ ํ๋ฌ์ค"), gr.Button("๐จ ๋ฎ์ด์ฐ๊ธฐ") btn_ld.click(load_json, None, [json_in, j_stat]) btn_ap.click(app_json, json_in, j_stat) btn_ov.click(over_json, json_in, j_stat)
# --------------------------------------------------------- # 3. ๋ก๊ทธ์ธ ์ฒ๋ฆฌ ๋ก์ง # --------------------------------------------------------- def check_login(user_id, user_pw): # 1. ํ๊น
ํ์ด์ค ์ํฌ๋ฆฟ์์ ๋น๋ฐ๋ฒํธ ๋ฐ์ดํฐ ๋ถ๋ฌ์ค๊ธฐ secret_str = os.getenv("AUTH_USERS") users_dict = {"a": "1", "User1": "1111"} # ๊ธฐ๋ณธ๊ฐ # โ
์๋ฌ ๋ฐฉ์ง: server_name="0.0.0.0" ์ต์
์ ์ง iface.launch(auth=auth_list, server_name="0.0.0.0") if secret_str: try: users_dict = json.loads(secret_str) except: pass # 2. ๋น๋ฒ ํ์ธ if users_dict.get(user_id) == user_pw: # ์ฑ๊ณต! (๋ง์ฝ ์์ด๋๊ฐ a ๋ผ๋ฉด ๊ด๋ฆฌ์ ๋ฉ๋ด ๋ณด์ฌ์ฃผ๊ธฐ) is_admin = (user_id == "a") return gr.update(visible=False), gr.update(visible=True), "โ
๋ก๊ทธ์ธ ์ฑ๊ณต!", gr.update(visible=is_admin) else: return gr.update(visible=True), gr.update(visible=False), "โ ์์ด๋ ๋๋ ๋น๋ฐ๋ฒํธ๊ฐ ํ๋ ธ์ต๋๋ค.", gr.update(visible=False)
btn_login.click( fn=check_login, inputs=[in_id, in_pw], outputs=[login_view, main_view, login_msg, admin_acc] )
iface.load(None, js=js_sync)
# ํด ์คํ (Gradio ๊ธฐ๋ณธ auth ๊ธฐ๋ฅ์ ๊บผ๋ - ์๋ฌ ์์ ์ฐจ๋จ)if __name__ == "__main__": iface.launch()app.py+188-356