File size: 23,607 Bytes
ccfef4b
d501367
 
0e3899e
 
3ea43ac
ccfef4b
a70c0d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d501367
 
6870cef
20dfe26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2fae5f2
 
 
 
3d98cb8
 
2fae5f2
 
 
 
 
3d98cb8
 
 
2fae5f2
 
 
6870cef
20dfe26
56a58cf
 
 
 
 
 
 
20dfe26
 
 
 
2fae5f2
a70c0d7
 
 
20dfe26
a70c0d7
 
 
 
 
3d98cb8
a70c0d7
 
 
 
 
3d98cb8
a70c0d7
20dfe26
6870cef
 
 
a088b80
 
 
20dfe26
 
 
 
 
 
e8c9780
a088b80
20dfe26
41c4e1b
86215d7
41c4e1b
 
75abab5
86215d7
 
 
56a58cf
86215d7
 
 
75abab5
 
 
 
 
 
20dfe26
 
56a58cf
20dfe26
6870cef
20dfe26
75abab5
20dfe26
 
 
 
3d98cb8
 
 
75abab5
 
56a58cf
3d98cb8
20dfe26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d98cb8
20dfe26
 
 
 
75abab5
 
56a58cf
20dfe26
3d98cb8
 
 
 
 
 
9a0fa15
3d98cb8
 
20dfe26
3d98cb8
 
 
 
 
 
 
 
9a0fa15
3d98cb8
 
 
 
 
 
 
 
 
 
 
 
 
56a58cf
3d98cb8
 
20dfe26
 
 
 
 
 
 
9a0fa15
20dfe26
 
 
 
 
 
 
 
 
3d98cb8
 
 
 
 
 
 
20dfe26
 
 
 
 
 
 
 
3d98cb8
20dfe26
ce922b6
20dfe26
3d98cb8
 
d558f9a
3d98cb8
 
 
 
 
990e80c
3d98cb8
 
 
 
 
 
 
5cae838
e8c9780
 
 
6ff1b0d
 
53df6b8
6ff1b0d
53df6b8
6ff1b0d
27b32c2
ca1a587
27b32c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41c4e1b
27b32c2
41c4e1b
 
27b32c2
 
 
 
41c4e1b
27b32c2
41c4e1b
 
27b32c2
 
 
 
41c4e1b
27b32c2
41c4e1b
 
27b32c2
 
e8c9780
 
 
41c4e1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5cae838
e8c9780
20dfe26
 
53df6b8
20dfe26
 
5cae838
a088b80
 
3d98cb8
a7965e1
6870cef
41c4e1b
a088b80
41c4e1b
56a58cf
20dfe26
 
 
 
 
 
990e80c
53df6b8
6061b85
d558f9a
75abab5
 
13c3b2f
 
3d98cb8
13c3b2f
3d98cb8
13c3b2f
 
75abab5
13c3b2f
 
 
41c4e1b
75abab5
41c4e1b
75abab5
 
9a0fa15
75abab5
 
 
 
 
9a0fa15
3d98cb8
 
 
9a0fa15
e8c9780
3d98cb8
 
 
 
e8c9780
3d98cb8
20dfe26
3d98cb8
 
 
20dfe26
3d98cb8
20dfe26
9a0fa15
 
 
20dfe26
 
 
 
 
9a0fa15
20dfe26
e8c9780
 
20dfe26
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
import gradio as gr
import json
import os
import difflib
import shutil
import re

try:
    from g2pk import G2p
except ImportError:
    G2p = None

print("G2P ๋ชจ๋ธ ๋กœ๋”ฉ ์ค‘...")
try:
    if G2p:
        g2p = G2p()
    else:
        g2p = None
except 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๋งŒ์› ๋Œ€", "๋งŒ์›๋•Œ"]]

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]
        
    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()

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 apply_g2p(text, mode):
    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 text

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์ž", "ํ‘œ์‹œ๋œ ๋งˆ์ปค(@@)๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค."
    
    # โ˜… ์ •ํ™•ํ•œ ๊ธ€์ž ์ˆ˜ ๊ณ„์‚ฐ ๋กœ์ง
    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}์ž"
    
    flat_dict = load_dict()
    
    if not flat_dict:
        final_text = apply_g2p(input_text, 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):
            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])
            last_end = end
            
        tail = input_text[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 = 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():
        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>')
    
    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>'
    
    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

def clear_all():
    return "", "", "", "๊ณต๋ฐฑ ํฌํ•จ: 0์ž / ๊ณต๋ฐฑ ์ œ์™ธ: 0์ž", "ํ‘œ์‹œ๋œ ๋งˆ์ปค(@@)๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค."

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์ž", "ํ‘œ์‹œ๋œ ๋งˆ์ปค(@@)๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค."
    
    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์ž", "ํ‘œ์‹œ๋œ ๋งˆ์ปค(@@)๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค."

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, "โœ… ํ˜„์žฌ ์‚ฌ์ „์„ ์„ฑ๊ณต์ ์œผ๋กœ ๋ถˆ๋Ÿฌ์™”์Šต๋‹ˆ๋‹ค! ์ด์ƒํ•œ ๋‹จ์–ด๋ฅผ ์ฐพ์•„ ์ง€์šฐ๊ฑฐ๋‚˜ ์ˆ˜์ •ํ•ด๋ณด์„ธ์š”."
    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 "โš ๏ธ ๋‚ด์šฉ์„ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."
    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)
            
        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 file_path is not None:
        shutil.copy(file_path, dict_path)
        return "โœ… ํŒŒ์ผ ๋ณต๊ตฌ ์™„๋ฃŒ!"
    return "โš ๏ธ ํŒŒ์ผ์ด ์—†์Šต๋‹ˆ๋‹ค."

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; }
#input_text_area textarea, #output_text_area textarea, #prompter_output_div { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif !important; letter-spacing: normal !important; word-spacing: normal !important; }
#input_text_area textarea { height: 500px !important; max-height: 500px !important; overflow-y: auto !important; padding: 16px !important; line-height: 1.8 !important; box-sizing: border-box !important; white-space: pre-wrap !important; word-break: break-word !important; }
#prompter_label_space { font-size: 13px !important; color: var(--body-text-color-subdued, #6b7280) !important; margin-bottom: 8px !important; display: block !important; text-align: left !important; font-weight: 400 !important; }
#prompter_output_div { height: 500px !important; max-height: 500px !important; overflow-y: auto !important; padding: 16px !important; line-height: 1.8 !important; box-sizing: border-box !important; background-color: #333 !important; color: #fff !important; border: 1px solid #ddd !important; border-radius: 8px !important; white-space: pre-wrap !important; word-break: break-word !important; text-align: left !important; margin-top: 0 !important; width: 100% !important; max-width: 100% !important; }
"""

script_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'; }
    }

    setTimeout(function() { applyFontSize(22); }, 500);

    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');
        let ta2 = document.querySelector('#output_text_area textarea');
        let div3 = document.getElementById('prompter_output_div');

        if (!ta1 || !div3) return;

        if (target === ta1) {
            if (isSyncing1) { isSyncing1 = false; return; }
            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 (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 (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); }
        }
    }, 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;
}
"""

with gr.Blocks(theme="default", css=custom_css) as iface:
    gr.Markdown("## ๐ŸŽ™๏ธ ๋‚˜๋งŒ์˜ TTS ์ „์ฒ˜๋ฆฌ ๋ณ€ํ™˜๊ธฐ (ํ”„๋กฌํ”„ํ„ฐ ๋ชจ๋“œ)")
    
    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():
                        gr.Markdown("**โš™๏ธ ๋ณ€ํ™˜ ๋ฐ ํ™”๋ฉด ์„ค์ •**")
                        ai_mode = gr.Radio(choices=["๋„๊ธฐ (์ˆ˜๋™ ์‚ฌ์ „๋งŒ ์ ์šฉ)", "์ˆœํ•œ ๋ง› (๋‹จ์–ด๋ณ„ ๋Š๊ธฐ - ๊ณผ๋„ํ•œ ์—ฐ์Œ ๋ฐฉ์ง€)", "๋งค์šด ๋ง› (๋ฌธ์žฅ ํ†ต์งธ๋กœ - ์ž์—ฐ์Šค๋Ÿฌ์šด ์—ฐ์Œ)"], value="๋„๊ธฐ (์ˆ˜๋™ ์‚ฌ์ „๋งŒ ์ ์šฉ)", label="๐Ÿค– AI ๋ฐœ์Œ ๋ณ€ํ™˜ ๊ฐ•๋„ ์„ ํƒ")
                        auto_break = gr.Checkbox(label="๐Ÿ“– ๋ฌธ์žฅ ๋์—์„œ ์ž๋™์œผ๋กœ ์ค„๋ฐ”๊ฟˆ ํ•˜๊ธฐ", value=False)
                        smart_pause = gr.Checkbox(label="โฑ๏ธ ์Šค๋งˆํŠธ ํ”„๋กฌํ”„ํ„ฐ ํ˜ธํก์  ( / ) ์ถ”๊ฐ€ํ•˜๊ธฐ (์‰ผํ‘œ ๋’ค)", value=False)
                        btn_insert_marker = gr.Button("๐Ÿšจ ์ปค์„œ ์œ„์น˜์— ๋งˆ์ปค(@@) ์‚ฝ์ž…ํ•˜๊ธฐ", variant="secondary", size="sm")
                        font_size = gr.Slider(minimum=16, maximum=40, value=22, step=2, label="๐Ÿ” ๊ฒฐ๊ณผ์ฐฝ ๊ธ€์ž ํฌ๊ธฐ ์กฐ์ ˆ")
                    
                    char_count = gr.Textbox(label="๊ธ€์ž ์ˆ˜ ํ™•์ธ", value="๊ณต๋ฐฑ ํฌํ•จ: 0์ž / ๊ณต๋ฐฑ ์ œ์™ธ: 0์ž", 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():
                    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")
                    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("---")
            gr.Markdown("**๐Ÿ’ก ๋‚˜๋งŒ์˜ ๋ฐœ์Œ ์‚ฌ์ „ ์ถ”๊ฐ€** (โ€ป 1๊ธ€์ž ๋‹จ์–ด๋Š” ์›๋ณธ ํ›ผ์†์„ ๋ง‰๊ธฐ ์œ„ํ•ด ๋“ฑ๋ก ๋ถˆ๊ฐ€ํ•ฉ๋‹ˆ๋‹ค!)")
            with gr.Row():
                nw = gr.Textbox(label="๊ธฐ์กด ๋‹จ์–ด ๋˜๋Š” ๋ฌธ์žฅ (2๊ธ€์ž ์ด์ƒ)")
                np = gr.Textbox(label="์›ํ•˜๋Š” ๋ฐœ์Œ")
                with gr.Column(min_width=200):
                    btn_add = gr.Button("๐Ÿ’พ ์‚ฌ์ „์— ์ถ”๊ฐ€ํ•˜๊ณ  ์ฆ‰์‹œ ๋Œ€๋ณธ ๋ณ€ํ™˜ํ•˜๊ธฐ", variant="primary")
                    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_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)

        with gr.Tab("๐Ÿ“ฅ ์ˆ˜๋™ ๋ฐฑ์—…/์กฐํšŒ/์ˆ˜์ • (๋Œ€๋Ÿ‰ ๋“ฑ๋ก)"):
            dl_btn = gr.DownloadButton("๐Ÿ“ฅ 1. ํ˜„์žฌ ์™„์„ฑ๋œ ์‚ฌ์ „ ๋ฐฑ์—…ํ•˜๊ธฐ (PC ๋‹ค์šด๋กœ๋“œ)")
            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")
            
            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)

            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)

    iface.load(None, js=script_js)

if __name__ == "__main__":
    iface.launch()