File size: 79,976 Bytes
ccfef4b
d501367
 
0e3899e
3ea43ac
f6b99fb
1e0f32b
a70c0d7
9f9e345
8b3a610
9f9e345
8b3a610
 
 
 
 
 
 
 
 
9f9e345
 
 
 
 
 
 
 
 
8ed688a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f9e345
c9f23c6
 
 
 
 
 
 
 
 
 
 
 
5437580
3ce5100
 
a62aeb0
7ac5008
a62aeb0
 
7ac5008
9f9e345
c9f23c6
 
 
 
9f9e345
c9f23c6
 
 
 
 
 
 
 
 
 
 
 
9f9e345
 
 
 
f6b99fb
9f9e345
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c0090b4
 
f6b99fb
 
3ce5100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f9e345
c9f23c6
 
 
 
 
 
 
 
 
 
8b3a610
c9f23c6
 
 
 
 
 
 
 
 
 
cadfa41
c9f23c6
 
 
 
 
 
 
cd6691f
 
 
 
 
3ce5100
 
cd6691f
3ce5100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f409da7
8b3a610
3ce5100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd6691f
 
 
 
3ce5100
cd6691f
3ce5100
cd6691f
3ce5100
 
 
 
 
 
cd6691f
3ce5100
 
 
 
 
 
 
cd6691f
8b3a610
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f409da7
 
 
 
 
 
 
 
 
 
 
 
 
 
8b3a610
 
 
 
 
 
 
 
 
 
 
 
 
 
f409da7
8b3a610
f409da7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9f23c6
 
 
3ce5100
 
 
 
 
f409da7
3ce5100
 
 
f409da7
3ce5100
1e0f32b
 
 
 
 
 
 
 
 
 
 
 
 
cd6691f
c9f23c6
8ed688a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd6691f
3ce5100
cd6691f
 
3ce5100
 
 
cd6691f
8ed688a
 
 
3ce5100
 
 
cd6691f
f409da7
 
8b3a610
cd6691f
 
 
f409da7
8b3a610
8ed688a
cd6691f
8ed688a
c9f23c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f9e345
c9f23c6
 
05fc5be
c9f23c6
9f9e345
c9f23c6
 
 
 
8ed688a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ce5100
cd6691f
3ce5100
cd6691f
3ce5100
8b3a610
 
 
 
 
cd6691f
c9f23c6
20dfe26
7ac5008
c9f23c6
 
 
cadfa41
f6b99fb
9f9e345
c9f23c6
 
3ce5100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9f23c6
05fc5be
 
 
1e0f32b
8ed688a
 
 
3ce5100
 
 
9f9e345
c9f23c6
8ed688a
 
05fc5be
 
 
 
8ed688a
05fc5be
3ce5100
 
 
 
1e0f32b
8ed688a
1e0f32b
3ce5100
1e0f32b
8ed688a
 
c9f23c6
 
 
 
 
 
 
 
 
 
9f9e345
3ce5100
9f9e345
 
c9f23c6
9f9e345
8ed688a
 
 
c9f23c6
 
8ed688a
 
c9f23c6
 
8ed688a
c9f23c6
 
8ed688a
 
 
 
 
 
 
c9f23c6
8ed688a
c9f23c6
 
8ed688a
c9f23c6
 
 
8ed688a
 
 
c9f23c6
 
8ed688a
c9f23c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ed688a
9f9e345
8ed688a
 
 
 
c9f23c6
8ed688a
c9f23c6
8ed688a
 
c9f23c6
 
 
 
8ed688a
 
 
 
c9f23c6
8ed688a
c9f23c6
 
2fae5f2
c9f23c6
 
c0090b4
c9f23c6
 
 
 
c0090b4
cadfa41
c9f23c6
cadfa41
 
c9f23c6
 
 
 
 
 
cadfa41
c0090b4
9f9e345
c0090b4
9f9e345
 
c0090b4
 
c9f23c6
 
 
 
c0090b4
c9f23c6
 
 
 
 
 
c0090b4
f6b99fb
 
9f9e345
f6b99fb
cadfa41
c9f23c6
 
 
 
 
 
9f9e345
 
a62aeb0
f6b99fb
a62aeb0
f6b99fb
 
 
 
c9f23c6
 
f6b99fb
c9f23c6
 
a62aeb0
f6b99fb
 
c9f23c6
 
f6b99fb
cadfa41
 
f6b99fb
 
9f9e345
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62609ce
7404e05
9f9e345
 
 
 
 
 
 
 
8ed688a
c9f23c6
9f9e345
 
 
 
c9f23c6
7ac5008
cd6691f
c9f23c6
8ed688a
 
 
5437580
8ed688a
c9f23c6
 
9f9e345
c9f23c6
9f9e345
5437580
 
f6b99fb
5437580
f6b99fb
c9f23c6
 
 
 
 
414c8d5
 
c9f23c6
cadfa41
414c8d5
 
cadfa41
c9f23c6
 
5437580
3053a9b
 
 
8ed688a
c9f23c6
 
414c8d5
05fc5be
c9f23c6
3ce5100
 
 
 
 
 
 
 
 
a62aeb0
c9f23c6
3ce5100
 
 
c9f23c6
 
3ce5100
 
f409da7
 
 
3ce5100
f409da7
3ce5100
 
 
7ac5008
3ce5100
 
 
 
 
7ac5008
3ce5100
 
a62aeb0
8ed688a
a62aeb0
414c8d5
7864509
7ac5008
c9f23c6
 
 
 
 
 
 
 
 
 
 
cadfa41
a62aeb0
c9f23c6
 
 
 
62609ce
c9f23c6
 
 
 
 
cadfa41
a62aeb0
c9f23c6
 
cadfa41
c9f23c6
a62aeb0
c9f23c6
414c8d5
c9f23c6
 
7ac5008
414c8d5
c9f23c6
 
 
5437580
8ed688a
05fc5be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ed688a
05fc5be
 
 
8ed688a
05fc5be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ed688a
05fc5be
 
 
8ed688a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05fc5be
 
 
 
 
a62aeb0
c9f23c6
 
f879749
c9f23c6
 
414c8d5
a62aeb0
c9f23c6
414c8d5
c9f23c6
 
7ac5008
414c8d5
a62aeb0
c9f23c6
 
a62aeb0
 
 
042c305
a62aeb0
042c305
a62aeb0
042c305
 
773ccf0
8ed688a
773ccf0
218ec5b
 
 
042c305
41c4e1b
9f9e345
10be047
414c8d5
9f9e345
 
 
 
414c8d5
a62aeb0
773ccf0
9f9e345
 
 
5437580
67ad677
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
414c8d5
9f9e345
 
 
c9f23c6
 
 
 
 
 
a62aeb0
7ac5008
8ed688a
a62aeb0
 
 
 
 
 
 
773ccf0
d5de09c
fe5092e
c9f23c6
a62aeb0
 
 
 
 
 
9f9e345
 
 
a62aeb0
 
 
 
c9f23c6
a62aeb0
9f9e345
 
 
a62aeb0
 
 
c9f23c6
a62aeb0
 
 
c9f23c6
a62aeb0
9f9e345
c9f23c6
a62aeb0
9f9e345
a62aeb0
9f9e345
a62aeb0
 
 
 
 
c9f23c6
05fc5be
 
 
 
 
 
 
 
 
 
 
8ed688a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9f23c6
 
a62aeb0
c9f23c6
 
a62aeb0
 
9f9e345
 
8ed688a
9f9e345
05fc5be
a62aeb0
05fc5be
 
 
 
 
 
 
 
8ed688a
05fc5be
 
 
 
8ed688a
05fc5be
 
 
 
 
 
8ed688a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f9e345
c9f23c6
a62aeb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
042c305
8ed688a
218ec5b
0d64641
 
1e0f32b
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
import gradio as gr
import json
import os
import difflib
import re
import html
import threading

# ============================================================================
# VoiceScript-AI v158.3 โ€” ๋‹จ์–ด์žฅ ์ตœ๊ฐ•ํŒ (์™ธ๋ถ€ ํ† ํฌ๋‚˜์ด์ € ๋ฏธ์‚ฌ์šฉ)
# ============================================================================
# [2026-10-19 v158.x ์ด๋ ฅ]
#  - v152: ์ˆœ์ˆ˜ ํ•œ๊ธ€ ํ‚ค ์ขŒ์ธก ๊ฒฝ๊ณ„ ๊ฐ€๋“œ ('ํด๋ฆฌ์—์Šคํ„ฐ' ํ•ฉ์„ฑ์–ด ์˜คํƒ ์ œ๊ฑฐ)
#  - v153: ์˜ˆ์™ธ ๋‹จ์–ด(ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ) UI ์ถ”๊ฐ€
#  - v154: Kiwi ํ˜•ํƒœ์†Œ ๊ฒฝ๊ณ„ ๊ฐ€๋“œ(์กฐ์‚ฌ ๋ฆฌ์ŠคํŠธ ํด๋ฐฑ) โ€” '์—์Šค์ปฌ๋ ˆ์ดํ„ฐ' ๋ณด์กด
#  - v155: ์ž๊ธฐ์น˜ํ™˜(k==v) โ†’ ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ ์ž๋™ ๋ฏธ๋Ÿฌ๋ง
#  - v156: ๊ตฌ๋‘์  ์œ ์—ฐ ๋งค์นญ (๋“ฑ๋ก ํ‚ค์˜ ๋„์–ด์“ฐ๊ธฐ/๋งˆ์นจํ‘œ ์ฐจ์ด ํก์ˆ˜)
#  - v157: ์ž๊ธฐ์น˜ํ™˜โ†”ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ ์–‘๋ฐฉํ–ฅ ๋™๊ธฐํ™”(auto_whitelist.json)
#  - v158: ๋ฐœ์Œ ์˜คํƒ€ ๊ฐ์ง€(์ž์Œ ์ถฉ๋Œ) + ๊ฒน์นจ ๊ฐ์ง€(๊ธฐ์กด ๋‹จ์–ด์žฅ ์‚ญ์ œ ์—†์Œ)
#  - v158.1~3: ๊ทœ์น™-์˜ˆ์™ธ ์ถฉ๋Œ ํšŒ์ˆ˜(์–‘๋ฐฉํ–ฅ ๊ฒน์นจ, ๋ถ€ํŒ… ์‹œ ์ž๋™ ์ •๋ฆฌ)
# [2026-08-29]
#  - ์™ธ๋ถ€ ํ’ˆ์‚ฌ ํ† ํฌ๋‚˜์ด์ € ์˜์กด์„ฑ ์™„์ „ ์ œ๊ฑฐ. ๋„์–ด์ฝ๊ธฐ๋Š” ๋‹จ์–ด์žฅ ๊ธฐ๋ฐ˜ ํ‘œ๊ธฐ ์ •๊ทœํ™”
#    + ๋ฌธ์žฅ๋ถ€ํ˜ธ ํ˜ธํก์ (`, ` ๋’ค์— `/`, ๋ฌธ์žฅ ๋์—์„œ `\n\n`)์œผ๋กœ๋งŒ ๋งŒ๋“ ๋‹ค.
#  - ์ž๋™ ๋ฐœ์Œ ์‚ฌ์ „ 172๊ฐœ (์‚ฌ์šฉ์ž ํ‚ค ๋“ฑ๋ก๊ฐ’ ์šฐ์„  โ€” ๋น„ํŒŒ๊ดด ๋ณ‘ํ•ฉ).
#  - ์˜ค๋””์˜ค ์ƒ์„ฑ ์ฝ”๋“œ(edge-ttsยทgTTSยทAudio ์œ„์ ฏ) ์™„์ „ ์ œ๊ฑฐ โ€” ๋Œ€๋ณธ ๋ณ€ํ™˜ ์ „์šฉ ์•ฑ.
#  - ๋‹จ์–ด์žฅ ์‹ ๊ทœ 60๊ฐœ ์ถ”๊ฐ€(์˜๋ฌธ ์•ฝ์–ดยท์นดํŽ˜ยท์•ฑยท๋‹จ์œ„ยท์‚ฌ์ด์ฆˆยท๊ธฐ๊ฐ„ยท์š”์ผ).
#  - ๋ฒ„ํŠผ ํ–‰์„ ๊ฐ™์€ scaleยทsize๋กœ ํ†ต์ผ. ์ดˆ๊ธฐํ™” ๋ฒ„ํŠผ์„ ๋งˆ์ง€๋ง‰ ์ž๋ฆฌ๋กœ ๋ณต์›.
# ============================================================================

# ---------- [v154] ํ˜•ํƒœ์†Œ ๊ฒฝ๊ณ„ ์ธ์‹ (A+B ํ•˜์ด๋ธŒ๋ฆฌ๋“œ) ----------
# B: Kiwi(๊ฒฝ๋Ÿ‰ ํ˜•ํƒœ์†Œ ๋ถ„์„๊ธฐ, ์ˆœ์ˆ˜ ํœ ) โ€” ์žˆ์œผ๋ฉด ์กฐ์‚ฌ/์–ด๋ฏธ ๊ฒฝ๊ณ„๋ฅผ ์ •๋ฐ€ ํŒ๋ณ„
# A: Kiwi๊ฐ€ ์—†๊ฑฐ๋‚˜ ๋กœ๋“œ ์‹คํŒจ ์‹œ ์กฐ์‚ฌ ์ ‘๋ฏธ์‚ฌ ๋ฆฌ์ŠคํŠธ๋กœ ํด๋ฐฑ (์˜์กด์„ฑ 0, ์•ฑ์€ ์ ˆ๋Œ€ ์•ˆ ์ฃฝ์Œ)
_kiwi = None
_KIWI_OK = None   # None=์•„์ง ์‹œ๋„ ์•ˆ ํ•จ / True / False

def _load_kiwi():
    global _kiwi, _KIWI_OK
    if _KIWI_OK is None:
        try:
            from kiwipiepy import Kiwi
            _kiwi = Kiwi()
            _KIWI_OK = True
            print("[ํ˜•ํƒœ์†Œ ๋ถ„์„๊ธฐ] Kiwi ๋กœ๋“œ ์™„๋ฃŒ โ€” ์กฐ์‚ฌ/์–ด๋ฏธ ๊ฒฝ๊ณ„ ํŒ๋ณ„ ์‚ฌ์šฉ")
        except Exception as e:
            _KIWI_OK = False
            print(f"[ํ˜•ํƒœ์†Œ ๋ถ„์„๊ธฐ] Kiwi ๋กœ๋“œ ์‹คํŒจ({e}) โ€” ์กฐ์‚ฌ ๋ฆฌ์ŠคํŠธ ๊ทœ์น™์œผ๋กœ ํด๋ฐฑ")
    return _kiwi

# A ํด๋ฐฑ์šฉ: ์–ด์ ˆ ๋’ค์— ๋ถ™๋Š” ํ•œ๊ตญ์–ด ์กฐ์‚ฌยท๋ณด์กฐ์‚ฌยท์–ด๋ฏธ (๊ธธ์ด ๋‚ด๋ฆผ์ฐจ์ˆœ โ€” ๊ธด ๊ฒƒ ๋จผ์ €)
_PARTICLE_SUFFIXES = sorted(set([
    "์œผ๋กœ๋ถ€ํ„ฐ", "๋กœ๋ถ€ํ„ฐ", "์—์„œ", "์—๊ฒŒ", "ํ•œํ…Œ", "๊นŒ์ง€", "๋ณด๋‹ค", "์ฒ˜๋Ÿผ", "๊ฐ™์ด",
    "๋งŒํผ", "์กฐ์ฐจ", "๋งˆ์ €", "ํ•˜๊ณ ", "์ด๋‚˜", "์ด๋ผ", "์ž…๋‹ˆ๋‹ค", "์ด์ง€๋งŒ", "๋‹ˆ๊นŒ",
    "๋Š”๋ฐ", "๋Š”", "์€", "์ด", "๊ฐ€", "์„", "๋ฅผ", "์˜", "์—", "๋„", "๋งŒ",
    "๊ณผ", "์™€", "๋กœ", "์œผ", "์•ผ", "์•„", "๊ป˜", "๋ž‘"
]), key=lambda x: -len(x))

class _MorphBoundary:
    """ํ˜„์žฌ ํ…์ŠคํŠธ ๊ธฐ์ค€ ํ˜•ํƒœ์†Œ ๊ฒฝ๊ณ„ โ€” ํ‚ค ๋งค์นญ ์œ„์น˜ ๋’ค๊ฐ€ '์กฐ์‚ฌ/์–ด๋ฏธ์˜ ์‹œ์ž‘'์ธ์ง€ ํŒ๋ณ„."""
    def __init__(self, text):
        self.text = text or ""
        self._kiwi = _load_kiwi()
        self._starts = {}    # position -> tag  (Kiwi ํ† ํฐ ์‹œ์ž‘์ )
        if self._kiwi is not None:
            try:
                for tok in self._kiwi.tokenize(self.text):
                    st = int(tok.start) if tok.start is not None else None
                    if st is not None and st not in self._starts:
                        self._starts[st] = tok.tag
            except Exception:
                self._kiwi = None

    @staticmethod
    def _is_particle_tag(tag):
        # J*: ์กฐ์‚ฌ / E*: ์–ด๋ฏธ / VCPยทVCN: '์ด๋‹คยท์•„๋‹ˆ๋‹ค' ๋ฅ˜ (์˜ˆ: ์—์Šค์ž…๋‹ˆ๋‹ค)
        return tag.startswith("J") or tag.startswith("E") or tag in ("VCP", "VCN")

    def allow_after(self, e):
        """ํ‚ค ๋งค์นญ์ด ๋๋‚œ ์œ„์น˜ e ๋’ค์— ์กฐ์‚ฌ/์–ด๋ฏธ(์ƒˆ ํ˜•ํƒœ์†Œ)๊ฐ€ ์ด์–ด์ง€๋ฉด True."""
        if e is None or e >= len(self.text):
            return True
        nxt = self.text[e]
        if not ('๊ฐ€' <= nxt <= 'ํžฃ'):      # ๊ณต๋ฐฑยท๋ฌธ์žฅ๋ถ€ํ˜ธยท๋ โ†’ ๋…๋ฆฝ ๋‹จ์–ด
            return True
        if self._kiwi is not None and self._starts:
            tag = self._starts.get(e)
            if tag is not None:
                return self._is_particle_tag(tag)
            return False                    # ํ•œ๊ธ€ ์—ฐ์†์ธ๋ฐ ํ˜•ํƒœ์†Œ ๊ฒฝ๊ณ„ ์—†์Œ โ†’ ํ•ฉ์„ฑ์–ด
        # ํด๋ฐฑ A: ์กฐ์‚ฌ ์ ‘๋ฏธ์‚ฌ๋กœ ์‹œ์ž‘ํ•˜๋Š”์ง€ (Kiwi ์—†์„ ๋•Œ๋งŒ)
        return any(self.text[e:].startswith(p) for p in _PARTICLE_SUFFIXES)

# ---------- G2P ์ž๋™ ์„ ํƒ (g2pk โ†’ g2pk2 โ†’ g2pkk) ----------
g2p = None
G2P_BACKEND = "์—†์Œ"
for _mod in ("g2pk", "g2pk2", "g2pkk"):
    try:
        _m = __import__(_mod, fromlist=["G2p"])
        g2p = _m.G2p()
        G2P_BACKEND = _mod
        print(f"G2P ๋กœ๋”ฉ ์™„๋ฃŒ: {_mod}")
        break
    except Exception as _e:
        print(f"G2P {_mod} ๋กœ๋”ฉ ์‹คํŒจ: {_e}")

dict_path = "custom_dict.json"
whitelist_path = "custom_whitelist.json"   # [v153] ์˜ˆ์™ธ ๋‹จ์–ด(์น˜ํ™˜ ๊ธˆ์ง€) โ€” ์‚ฌ์šฉ์ž ์ˆ˜๋™ ๋“ฑ๋ก
auto_wl_path = "auto_whitelist.json"       # [v157] ์‚ฌ์ „ ์ž๊ธฐ์น˜ํ™˜์—์„œ ์ž๋™ ๋ฏธ๋Ÿฌ๋ง๋œ ํ•ญ๋ชฉ (๋™๊ธฐํ™” ๊ด€๋ฆฌ ๋Œ€์ƒ)
ADMIN_ID = os.environ.get("ADMIN_ID", "admin")
ADMIN_PW = os.environ.get("ADMIN_PW", "admin1234")
GUEST_ID = os.environ.get("GUEST_ID", "guest")
GUEST_PW = os.environ.get("GUEST_PW", "guest1234")

# ---------- HF Dataset ์˜๊ตฌ ์ €์žฅ์†Œ (์„ ํƒ) ----------
HF_TOKEN = os.environ.get("HF_TOKEN")
DICT_REPO = os.environ.get("DICT_REPO", "").strip()
hf_api = None
dict_repo_id = None
SYNC_STATE = "๋กœ์ปฌ ์ „์šฉ (HF_TOKEN ๋ฏธ์„ค์ • โ€” Space ์žฌ์‹œ์ž‘ ์‹œ ๋“ฑ๋ก๋ถ„ ์œ ์‹ค!)"
try:
    from huggingface_hub import HfApi, hf_hub_download
    if HF_TOKEN:
        hf_api = HfApi(token=HF_TOKEN)
        dict_repo_id = DICT_REPO or (hf_api.whoami()["name"] + "/voicescript-dict")
        hf_api.create_repo(dict_repo_id, repo_type="dataset", private=True, exist_ok=True)
        SYNC_STATE = f"์˜๊ตฌ ์ €์žฅ์†Œ ์—ฐ๊ฒฐ๋จ: {dict_repo_id}"
except Exception as _e:
    hf_api = None
    SYNC_STATE = f"์˜๊ตฌ ์ €์žฅ์†Œ ์—ฐ๊ฒฐ ์‹คํŒจ({_e}) - ๋กœ์ปฌ ์ €์žฅ๋งŒ ๋™์ž‘"
print(f"[์‚ฌ์ „ ์ €์žฅ์†Œ] {SYNC_STATE}")

# ============================================================================
# AUTO_MERGE_WORDS โ€” ์ž๋™ ๋ฐœ์Œ ์‚ฌ์ „
# ์‚ฌ์šฉ์ž ์‚ฌ์ „์— ๊ฐ™์€ ํ‚ค๊ฐ€ ์ด๋ฏธ ์žˆ์œผ๋ฉด setdefault ๋•๋ถ„์— ๋ฎ์–ด์“ฐ์ง€ ์•Š์Œ.
# ============================================================================
AUTO_MERGE_WORDS = [
    # โ”€โ”€ ์˜๋ฌธ ์•ฝ์–ดยท๋ธŒ๋žœ๋“œ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    ["H&M", "์—์ด์น˜ ์•ค ์— "],
    ["ZARA", "์ž๋ผ"],
    ["UNIQLO", "์œ ๋‹ˆํด๋กœ"],
    ["YouTube", "์œ ํŠœ๋ธŒ"],
    ["Instagram", "์ธ์Šคํƒ€๊ทธ๋žจ"],
    ["iPhone", "์•„์ดํฐ"], ["iOS", "์•„์ด์˜ค์—์Šค"], ["IOS", "์•„์ด์˜ค์—์Šค"],
    ["Android", "์•ˆ๋“œ๋กœ์ด๋“œ"],
    ["Mac", "๋งฅ"], ["MacBook", "๋งฅ๋ถ"],
    ["Windows", "์œˆ๋„์šฐ"],
    ["NAVER", "๋„ค์ด๋ฒ„"], ["DAUM", "๋‹ค์Œ"], ["KAKAO", "์นด์นด์˜ค"],
    ["CJ", "์”จ์ œ์ด"], ["HD", "์—์ด์น˜๋””"], ["LS", "์—˜์—์Šค"],
    ["LG", "์—˜์ง€"], ["SK", "์—์Šค์ผ€์ด"], ["KT", "์ผ€์ดํ‹ฐ"],
    ["26SS", "์ด์‹ญ์œก ์—์Šค์—์Šค"], ["26 SS", "์ด์‹ญ์œก ์—์Šค์—์Šค"],
    ["26S/S", "์ด์‹ญ์œก ์—์Šค์—์Šค"], ["26 S/S", "์ด์‹ญ์œก ์—์Šค์—์Šค"],
    ["25SS", "์ด์‹ญ์˜ค ์—์Šค์—์Šค"], ["25 SS", "์ด์‹ญ์˜ค ์—์Šค์—์Šค"],
    ["FW", "์—ํ”„๋”๋ธ”์œ "], ["SSFW", "์—์Šค์—์Šค ์—ํ”„๋”๋ธ”์œ "],
    ["GS๋งˆ์ด์ƒต", "์ง€์—์Šค๋งˆ์ด์ƒต"], ["GS ๋งˆ์ด์ƒต", "์ง€์—์Šค๋งˆ์ด์ƒต"],
    ["GS์ƒต", "์ง€์—์Šค์ƒต"], ["GS ์ƒต", "์ง€์—์Šค์ƒต"],
    # โ”€โ”€ ์นดํŽ˜ยท์•ฑยท์„œ๋น„์Šค โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    ["์นด์นด์˜คํ†ก", "์นด์นด์˜ค ํ†ก"],
    ["๋ฐฐ๋‹ฌ์˜๋ฏผ์กฑ", "๋ฐฐ๋‹ฌ์˜ ๋ฏผ์กฑ"],
    ["๋‹น๊ทผ๋งˆ์ผ“", "๋‹น๊ทผ ๋งˆ์ผ“"],
    ["ํ† ์Šค", "ํ† ์Šค"], ["์ฟ ํŒก", "์ฟ ํŒก"],
    ["๋„ค์ด๋ฒ„", "๋„ค์ด๋ฒ„"], ["๋‹ค์Œ", "๋‹ค์Œ"], ["์คŒ", "์คŒ"],
    # โ”€โ”€ ์ˆซ์ž+๋‹จ์œ„ ๊ฒฐํ•ฉ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    ["14์ธ์น˜", "์‹ญ์‚ฌ ์ธ์น˜"],
    ["13.3์ธ์น˜", "์‹ญ์‚ผ ์  ์‚ผ ์ธ์น˜"],
    ["15์ธ์น˜", "์‹ญ์˜ค ์ธ์น˜"], ["15.6์ธ์น˜", "์‹ญ์˜ค ์  ์œก ์ธ์น˜"],
    ["32GB", "์‚ผ์‹ญ์ด ๊ธฐ๊ฐ€"], ["64GB", "์œก์‹ญ์‚ฌ ๊ธฐ๊ฐ€"], ["128GB", "๋ฐฑ์ด์‹ญํŒ” ๊ธฐ๊ฐ€"],
    ["256GB", "์ด๋ฐฑ์˜ค์‹ญ์œก ๊ธฐ๊ฐ€"], ["512GB", "์˜ค๋ฐฑ์‹ญ์ด ๊ธฐ๊ฐ€"],
    ["1TB", "์ผ ํ…Œ๋ผ๋ฐ”์ดํŠธ"],
    ["1080p", "์ฒœํŒ”์‹ญ ํ”ผ"], ["4K", "ํฌ ์ผ€์ด"], ["8K", "์—์ž‡ ์ผ€์ด"],
    # โ”€โ”€ ๋‹จ์œ„ ๋ณด์™„ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    ["์ธ์น˜", "์ธ์น˜"], ["์•ผ๋“œ", "์•ผ๋“œ"], ["ํŒŒ์šด๋“œ", "ํŒŒ์šด๋“œ"],
    ["์˜จ์Šค", "์˜จ์Šค"], ["๊ฐค๋Ÿฐ", "๊ฐค๋Ÿฐ"], ["์˜จ๋„", "์˜จ๋„"],
    ["ํ—ฅํƒ€๋ฅด", "ํ—ฅํƒ€๋ฅด"], ["๋ฐ์‹œ๋ฆฌํ„ฐ", "๋ฐ์‹œ๋ฆฌํ„ฐ"], ["๋งˆ์ผ", "๋งˆ์ผ"],
    ["๋…ธํŠธ", "๋…ธํŠธ"],
    ["mm", "๋ฐ€๋ฆฌ๋ฏธํ„ฐ"], ["cm", "์„ผํ‹ฐ๋ฏธํ„ฐ"], ["km", "ํ‚ฌ๋กœ๋ฏธํ„ฐ"],
    ["kg", "ํ‚ฌ๋กœ๊ทธ๋žจ"], ["mg", "๋ฐ€๋ฆฌ๊ทธ๋žจ"], ["ml", "๋ฐ€๋ฆฌ๋ฆฌํ„ฐ"],
    # โ”€โ”€ ์˜๋ฌธ ์˜๋ฅ˜ ์‚ฌ์ด์ฆˆ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    ["XS", "์—‘์Šค์Šค"], ["S", "์—์Šค"], ["M", "์— "], ["L", "์—˜"],
    ["XL", "์—‘์Šค์—˜"], ["XXL", "๋”๋ธ”์—‘์Šค์—˜"],
    ["FREE", "ํ”„๋ฆฌ"], ["ONE SIZE", "์› ์‚ฌ์ด์ฆˆ"],
    # โ”€โ”€ ํ•œ์ˆซ์ž ์‚ฌ์ด์ฆˆ(ํ•œ๊ตญ ์˜๋ฅ˜ ์‚ฌ์ด์ฆˆ) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    ["55์‚ฌ์ด์ฆˆ", "์˜ค์˜ค ์‹ธ์ด์ฆˆ"], ["55 ์‚ฌ์ด์ฆˆ", "์˜ค์˜ค ์‹ธ์ด์ฆˆ"],
    ["66์‚ฌ์ด์ฆˆ", "์œต์œก ์‹ธ์ด์ฆˆ"], ["66 ์‚ฌ์ด์ฆˆ", "์œต์œก ์‹ธ์ด์ฆˆ"],
    ["77์‚ฌ์ด์ฆˆ", "์น ์น  ์‹ธ์ด์ฆˆ"], ["77 ์‚ฌ์ด์ฆˆ", "์น ์น  ์‹ธ์ด์ฆˆ"],
    ["88์‚ฌ์ด์ฆˆ", "ํŒ”ํŒ” ์‹ธ์ด์ฆˆ"], ["88 ์‚ฌ์ด์ฆˆ", "ํŒ”ํŒ” ์‹ธ์ด์ฆˆ"],
    ["95์‚ฌ์ด์ฆˆ", "๊ตฌ์˜ค ์‹ธ์ด์ฆˆ"], ["95 ์‚ฌ์ด์ฆˆ", "๊ตฌ์˜ค ์‹ธ์ด์ฆˆ"],
    ["100์‚ฌ์ด์ฆˆ", "๋ฐฑ ์‹ธ์ด์ฆˆ"], ["100 ์‚ฌ์ด์ฆˆ", "๋ฐฑ ์‹ธ์ด์ฆˆ"],
    ["105์‚ฌ์ด์ฆˆ", "๋ฐฑ์˜ค ์‹ธ์ด์ฆˆ"], ["105 ์‚ฌ์ด์ฆˆ", "๋ฐฑ์˜ค ์‹ธ์ด์ฆˆ"],
    ["110์‚ฌ์ด์ฆˆ", "๋ฐฑ์‹ญ ์‹ธ์ด์ฆˆ"], ["110 ์‚ฌ์ด์ฆˆ", "๋ฐฑ์‹ญ ์‹ธ์ด์ฆˆ"],
    ["๋‹จ๋…์‚ฌ์ด์ฆˆ", "๋‹จ๋… ์‚ฌ์ด์ฆˆ"], ["๋‹จ๋… ์‚ฌ์ด์ฆˆ", "๋‹จ๋… ์‚ฌ์ด์ฆˆ"],
    # โ”€โ”€ %, 100% โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    ["100%", "๋ฐฑํ”„๋กœ"], ["100 %", "๋ฐฑํ”„๋กœ"], ["100ํ”„๋กœ", "๋ฐฑํ”„๋กœ"],
    ["50%", "์˜ค์‹ญํ”„๋กœ"], ["50 %", "์˜ค์‹ญํ”„๋กœ"],
    ["20%", "์ด์‹ญํ”„๋กœ"], ["20 %", "์ด์‹ญํ”„๋กœ"],
    ["30%", "์‚ผ์‹ญํ”„๋กœ"], ["30 %", "์‚ผ์‹ญํ”„๋กœ"],
    ["90%", "๊ตฌ์‹ญํ”„๋กœ"], ["90 %", "๊ตฌ์‹ญํ”„๋กœ"],
    # โ”€โ”€ ๊ฐ€๊ฒฉ (์ฝค๋งˆ ์žˆ๋Š” ๊ฒƒ ์šฐ์„  โ†’ ์ผ๋ฐ˜ ๊ฒƒ ์ฐจํ›„) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    ["99,000์›", "๊ตฌ๋งŒ ๊ตฌ์ฒœ ์›"], ["99,000 ์›", "๊ตฌ๋งŒ ๊ตฌ์ฒœ ์›"],
    ["59,900์›", "์˜ค๋งŒ ๊ตฌ์ฒœ๊ตฌ๋ฐฑ ์›"], ["59,900 ์›", "์˜ค๋งŒ ๊ตฌ์ฒœ๊ตฌ๋ฐฑ ์›"],
    ["49,900์›", "์‚ฌ๋งŒ ๊ตฌ์ฒœ๊ตฌ๋ฐฑ ์›"], ["49,900 ์›", "์‚ฌ๋งŒ ๊ตฌ์ฒœ๊ตฌ๋ฐฑ ์›"],
    ["39,900์›", "์‚ผ๋งŒ ๊ตฌ์ฒœ๊ตฌ๋ฐฑ ์›"], ["39,900 ์›", "์‚ผ๋งŒ ๊ตฌ์ฒœ๊ตฌ๋ฐฑ ์›"],
    ["29,900์›", "์ด๋งŒ ๊ตฌ์ฒœ๊ตฌ๋ฐฑ ์›"], ["29,900 ์›", "์ด๋งŒ ๊ตฌ์ฒœ๊ตฌ๋ฐฑ ์›"],
    ["19,900์›", "์ผ๋งŒ ๊ตฌ์ฒœ๊ตฌ๋ฐฑ ์›"], ["19,900 ์›", "์ผ๋งŒ ๊ตฌ์ฒœ๊ตฌ๋ฐฑ ์›"],
    ["9,900์›", "๊ตฌ์ฒœ๊ตฌ๋ฐฑ ์›"], ["9,900 ์›", "๊ตฌ์ฒœ๊ตฌ๋ฐฑ ์›"],
    ["59,900", "์˜ค๋งŒ ๊ตฌ์ฒœ๊ตฌ๋ฐฑ"], ["49,900", "์‚ฌ๋งŒ ๊ตฌ์ฒœ๊ตฌ๋ฐฑ"],
    ["39,900", "์‚ผ๋งŒ ๊ตฌ์ฒœ๊ตฌ๋ฐฑ"], ["29,900", "์ด๋งŒ ๊ตฌ์ฒœ๊ตฌ๋ฐฑ"],
    # โ”€โ”€ ๊ธฐ๊ฐ„ (์ผ๋ฐ˜ ์ผ/์ฃผ/๋…„) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    ["1์ผ", "ํ•˜๋ฃจ"], ["2์ผ", "์ดํ‹€"], ["3์ผ", "์‚ฌํ˜"],
    ["1์ฃผ", "์ผ์ฃผ"], ["2์ฃผ", "์ด์ฃผ"], ["1๋…„", "์ผ๋…„"],
    ["24์‹œ๊ฐ„", "์ด์‹ญ์‚ฌ ์‹œ๊ฐ„"], ["12์‹œ๊ฐ„", "์‹ญ์ด ์‹œ๊ฐ„"],
    ["3๊ฐœ์›”", "์‚ผ๊ฐœ์›”"], ["3 ๊ฐœ์›”", "์‚ผ๊ฐœ์›”"],
    ["6๊ฐœ์›”", "์œก๊ฐœ์›”"], ["6 ๊ฐœ์›”", "์œก๊ฐœ์›”"],
    ["12๊ฐœ์›”", "์‹ญ์ด๊ฐœ์›”"], ["12 ๊ฐœ์›”", "์‹ญ์ด๊ฐœ์›”"],
    ["24๊ฐœ์›”", "์ด์‹ญ์‚ฌ๊ฐœ์›”"], ["24 ๊ฐœ์›”", "์ด์‹ญ์‚ฌ๊ฐœ์›”"],
    # โ”€โ”€ ์‹œ๊ฐ„ยท์š”์ผ ํ‘œ๊ธฐ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    ["์˜ค์ „", "์˜ค์ „"], ["์˜คํ›„", "์˜คํ›„"],
    ["AM", "์—์ด์— "], ["PM", "ํ”ผ์— "], ["KST", "์ผ€์ด์—์Šคํ‹ฐ"],
    ["์›”์š”์ผ", "์›”์š”์ผ"], ["ํ™”์š”์ผ", "ํ™”์š”์ผ"], ["ํ‰์ผ", "ํ‰์ผ"],
    # โ”€โ”€ ๊ฐ€๊ฒฉ๋Œ€ ํ‘œํ˜„ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    ["1๋งŒ์›๋Œ€", "๋งŒ์›๋•Œ"], ["1๋งŒ ์›๋Œ€", "๋งŒ์›๋•Œ"],
    ["1๋งŒ ์› ๋Œ€", "๋งŒ์›๋•Œ"], ["1๋งŒ์› ๋Œ€", "๋งŒ์›๋•Œ"],
    ["2๋งŒ์›๋Œ€", "์ด๋งŒ์›๋•Œ"], ["2๋งŒ ์›๋Œ€", "์ด๋งŒ์›๋•Œ"],
    ["3๋งŒ์›๋Œ€", "์‚ผ๋งŒ์›๋•Œ"], ["3๋งŒ ์›๋Œ€", "์‚ผ๋งŒ์›๋•Œ"],
    ["5๋งŒ์›๋Œ€", "์˜ค๋งŒ์›๋•Œ"], ["5๋งŒ ์›๋Œ€", "์˜ค๋งŒ์›๋•Œ"],
    # โ”€โ”€ ์ž์ฃผ ํ‹€๋ฆฌ๋Š” ํ•œ๊ตญ์–ด ํ‘œ๊ธฐ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    ["~์ž…๋‹ˆ๋‹ค", "~์Šต๋‹ˆ๋‹ค"], ["์ž…๋‹ˆ๋‹ค", "์ž…๋‹ˆ๋‹ค"],
    ["์˜ˆ์ •์ž…๋‹ˆ๋‹ค", "์˜ˆ์ •์ž…๋‹ˆ๋‹ค"], ["๊ฒฐ๊ณผ์ ์œผ๋กœ", "๊ฒฐ๊ณผ์ ์œผ๋กœ"],
    ["์‚ผ์„ฑ", "์‚ผ์„ฑ"], ["ํ˜„๋Œ€", "ํ˜„๋Œ€"], ["๊ธฐ์•„", "๊ธฐ์•„"],
    ["์ƒํ’ˆ", "์ƒํ’ˆ"], ["์ œํ’ˆ", "์ œํ’ˆ"], ["๊ฐ€๊ฒฉ", "๊ฐ€๊ฒฉ"],
    ["๋ฐฐ์†ก", "๋ฐฐ์†ก"], ["ํ• ์ธ", "ํ• ์ธ"], ["์ด๋ฒคํŠธ", "์ด๋ฒคํŠธ"]
]

# ---------- [v158] ๋“ฑ๋ก ๋ณด์กฐ: ๋ฐœ์Œ ์˜คํƒ€ ๊ฐ์ง€ + ์ค‘๋ณต(์ž˜๋ฆฐ) ํ‚ค ์ž๋™ ์ •๋ฆฌ ----------
def _detect_pronun_typo(word, pronun):
    """[v158] ๋ฐœ์Œ ํ‘œ๊ธฐ์˜ ํ”ํ•œ ์˜คํƒ€๋ฅผ ๊ฐ์ง€ํ•ด ๊ฒฝ๊ณ  ๋ฌธ์ž์—ด ๋ชฉ๋ก์„ ๋ฐ˜ํ™˜.
    1) ์ž์Œ ์ถฉ๋Œ: ํ•œ๊ธ€ ์ข…์„ฑ(๋ฐ›์นจ) ๋ฐ”๋กœ ๋’ค์— ๊ฐ™์€ ์ž์Œ๊ณ„ ์ดˆ์„ฑ์ด ๋ถ™์œผ๋ฉด
       '์ƒต๋น•'๋ฅ˜์˜ ๋ถ€์ž์—ฐ์Šค๋Ÿฌ์šด ๋ฐœ์Œ ํ‘œ๊ธฐ์ผ ๊ฐ€๋Šฅ์„ฑ์ด ๋†’๋‹ค.
    2) ์ž๊ธฐ์น˜ํ™˜: ๋‹จ์–ด์™€ ๋ฐœ์Œ์ด ์™„์ „ํžˆ ๊ฐ™์œผ๋ฉด ๋ฐœ์Œ ์ง€์ • ์˜๋ฏธ๊ฐ€ ์—†๋‹ค(์˜ˆ์™ธ ๋“ฑ๋ก ์ทจ์ง€ ์ œ์™ธ)."""
    warnings = []
    if pronun == word:
        warnings.append("๋‹จ์–ด์™€ ๋ฐœ์Œ์ด ๋˜‘๊ฐ™์Šต๋‹ˆ๋‹ค. ์ด๋Œ€๋กœ ์ €์žฅํ•˜๋ฉด ์ด ๋‹จ์–ด๋Š” ์–ด๋–ค ๋ฐœ์Œ ๋ณ€ํ™˜๋„ ๋ฐ›์ง€ ์•Š์Šต๋‹ˆ๋‹ค(์›๋ฌธ ์œ ์ง€).")
    # ์ข…์„ฑ-์ดˆ์„ฑ ์ž์Œ ์ถฉ๋Œ ์Šค์บ”: ๊ฒน๋ฐ›์นจ ํฌํ•จ ์ข…์„ฑ ๋’ค์— ๋™์ผ ๊ณ„์—ด ์ž์Œ ์ดˆ์„ฑ์ด ์˜ค๋Š” ์กฐํ•ฉ
    _jamO_conflict = [
        ("ใ…‚", "ใ…‚"), ("ใ…‚", "ใ…ƒ"), ("ใ…‚", "ใ…"), ("ใ„ฑ", "ใ„ฑ"), ("ใ„ฑ", "ใ„ฒ"),
        ("ใ„ฑ", "ใ…‹"), ("ใ„ท", "ใ„ท"), ("ใ„ท", "ใ„ธ"), ("ใ„ท", "ใ…Œ"), ("ใ……", "ใ…†"),
        ("ใ„ด", "ใ„ด"), ("ใ…", "ใ…"), ("ใ…‡", "ใ…‡"), ("ใ„น", "ใ„น"), ("ใ…ˆ", "ใ…‰"),
        ("ใ…ˆ", "ใ…Š"), ("ใ…Š", "ใ…Š"), ("ใ…‹", "ใ…‹"), ("ใ…Œ", "ใ…Œ"), ("ใ…", "ใ…"), ("ใ…Ž", "ใ…Ž"),
    ]
    _cho = "ใ„ฑใ„ฒใ„ดใ„ทใ„ธใ„นใ…ใ…‚ใ…ƒใ……ใ…†ใ…‡ใ…ˆใ…‰ใ…Šใ…‹ใ…Œใ…ใ…Ž"
    _jong_map = {  # ์ข…์„ฑ โ†’ ๋Œ€ํ‘œ ์ž์Œ
        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: 'ใ…Ž',
    }
    prev_jong = None
    for ch in pronun:
        if '๊ฐ€' <= ch <= 'ํžฃ':
            offset = ord(ch) - ord('๊ฐ€')
            jong = offset % 28                     # 0=๋ฐ›์นจ ์—†์Œ, 1~27
            cho_idx = offset // (21 * 28)
            if prev_jong is not None and cho_idx < len(_cho):
                cur_cho = _cho[cho_idx]
                cur_jong = _jong_map.get(prev_jong)   # prev_jong: 1~27 ์ธ๋ฑ์Šค โ†’ ๋Œ€ํ‘œ ์ž์Œ ๋ฌธ์ž
                if cur_jong and any(j == cur_jong and c == cur_cho for j, c in _jamO_conflict):
                    ctx = pronun[max(0, pronun.find(ch) - 1):pronun.find(ch) + 2]
                    warnings.append(f"๋ฐœ์Œ์— ๋ถ€์ž์—ฐ์Šค๋Ÿฌ์šด ์ž์Œ ์ถฉ๋Œ์ด ์žˆ์Šต๋‹ˆ๋‹ค: '...{ctx}...' โ€” ์‹ค์ œ ๋‚ญ๋… ๋ฐœ์Œ(์˜ˆ: '๋งˆ์ด์ƒต์ž…๋‹ˆ๋‹ค'โ†’'๋งˆ์ด์ƒค๋น•๋‹ˆ๋‹ค')์ธ์ง€ ๋‹ค์‹œ ํ™•์ธํ•˜์„ธ์š”.")
                    break
            prev_jong = jong if jong > 0 else None
        else:
            prev_jong = None
    return list(dict.fromkeys(warnings))[:2]  # ์ตœ๋Œ€ 2๊ฐœ, ์ค‘๋ณต ์ œ๊ฑฐ

def _find_overlapping_keys(dict_map, new_word):
    """[v158-final] ์ƒˆ ํ‚ค์™€ '๊ฐ™์€ ๋‹จ์–ด์˜ ๋‹ค๋ฅธ ํ‘œ๊ธฐ'๋กœ ๊ฒน์น˜๋Š” ๊ธฐ์กด ํ‚ค๋ฅผ ์ฐพ๋Š”๋‹ค.
    ์ ˆ๋Œ€ ์‚ญ์ œํ•˜์ง€ ์•Š๋Š”๋‹ค โ€” ์—”์ง„์ด ๊ธด ํ‚ค ์šฐ์„  ๋งค์นญ์„ ํ•˜๋ฏ€๋กœ ์šฐ์„ ์ˆœ์œ„๋Š” ์ด๋ฏธ ๋ณด์žฅ๋˜๊ณ ,
    ๊ธฐ์กด์— ๋“ฑ๋ก๋œ ๋‹จ์–ด์žฅ์€ ์–ด๋–ค ๊ฒฝ์šฐ์—๋„ ํ›ผ์†๋˜์ง€ ์•Š์•„์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ(์‚ฌ์šฉ์ž ์š”๊ตฌ).
    - ๊ฒน์นจ ํŒ์ •: ๊ณต๋ฐฑ์„ ๋ฌด์‹œํ•˜๊ณ  ํ•œ์ชฝ์ด ๋‹ค๋ฅธ ์ชฝ์˜ ์ ‘๋‘์–ด(4๊ธ€์ž ์ด์ƒ).
      '์ง€์—์Šค๋งˆ์ด์ƒต์ž…๋‹ˆ๋‹ค' vs '์ง€์—์Šค ๋งˆ์ด์ƒต์ž…๋‹ˆ๋‹ค' (๋„์–ด์“ฐ๊ธฐ ์ฐจ์ด)๋„ ๊ฒน์นจ์œผ๋กœ ๋ณธ๋‹ค.
    ๋ฐ˜ํ™˜: ๊ฒน์น˜๋Š” ๊ธฐ์กด ํ‚ค ๋ชฉ๋ก."""
    def _norm(s):
        return re.sub(r'\s+', '', s or "")
    nw = _norm(new_word)
    if len(nw) < 4:
        return []
    overlaps = []
    for k in dict_map.keys():
        if k == new_word:
            continue
        nk = _norm(k)
        if len(nk) < 4:
            continue
        if nk.startswith(nw) or nw.startswith(nk):
            overlaps.append(k)
    return overlaps

# ---------- ์‚ฌ์ „ I/O ----------
def _read_local_dict():
    try:
        with open(dict_path, "r", encoding="utf-8") as f:
            data = json.load(f)
        return {i[0].strip(): i[1].strip() for i in data.get("items", []) if len(i) == 2}
    except Exception:
        return {}

def _write_local_dict(dict_map):
    items = [[k, v] for k, v in dict_map.items()]
    payload = {"items": items, "meta": {"app_title": "VoiceScript AI", "app_version": "158.3", "count": len(items)}}
    tmp_path = dict_path + ".tmp"
    with open(tmp_path, "w", encoding="utf-8") as f:
        json.dump(payload, f, ensure_ascii=False, indent=2)
    if os.path.exists(dict_path):
        os.replace(dict_path, dict_path + ".bak")
    os.replace(tmp_path, dict_path)

def _push_remote():
    if not hf_api:
        return "๋กœ์ปฌ ์ €์žฅ๋งŒ ๋จ (์žฌ์‹œ์ž‘ ์‹œ ์œ ์‹ค ๊ฐ€๋Šฅ - HF_TOKEN ์„ค์ • ํ•„์š”)"
    try:
        hf_api.upload_file(path_or_fileobj=dict_path, path_in_repo="custom_dict.json",
                           repo_id=dict_repo_id, repo_type="dataset",
                           commit_message="update pronunciation dict")
        return "์˜๊ตฌ ์ €์žฅ ์™„๋ฃŒ"
    except Exception as e:
        return f"์›๊ฒฉ ์ €์žฅ ์‹คํŒจ({e}) - ๋กœ์ปฌ๋งŒ ์ €์žฅ๋จ"

def _self_reference_keys(dict_map):
    """[v155] ์‚ฌ์ „์—์„œ k == v (์ž๊ธฐ์น˜ํ™˜) ์ธ ํ‚ค ๋ชฉ๋ก.
    ์‚ฌ์šฉ์ž๊ฐ€ '์ด ๋‹จ์–ด๋ฅผ ์›๋ฌธ ๊ทธ๋Œ€๋กœ ๋‘๊ณ  ์‹ถ๋‹ค'๋Š” ์˜๋„๋กœ ๋“ฑ๋กํ•œ ํ•ญ๋ชฉ๋“ค."""
    return [k for k, v in (dict_map or {}).items() if k and k == v]

def _read_auto_whitelist():
    """[v157] ์‚ฌ์ „ ์ž๊ธฐ์น˜ํ™˜์—์„œ ์ž๋™ ๋ฏธ๋Ÿฌ๋ง๋œ ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ ๋ชฉ๋ก (๋™๊ธฐํ™” ๊ด€๋ฆฌ ๋Œ€์ƒ)."""
    try:
        with open(auto_wl_path, "r", encoding="utf-8") as f:
            data = json.load(f)
        return {str(x).strip() for x in data.get("items", []) if str(x).strip()}
    except Exception:
        return set()

def _write_auto_whitelist(items_set):
    payload = {"items": sorted(items_set), "meta": {"app_title": "auto whitelist mirror",
                                                     "app_version": "157.0",
                                                     "count": len(items_set)}}
    tmp = auto_wl_path + ".tmp"
    with open(tmp, "w", encoding="utf-8") as f:
        json.dump(payload, f, ensure_ascii=False, indent=2)
    if os.path.exists(auto_wl_path):
        os.replace(auto_wl_path, auto_wl_path + ".bak")
    os.replace(tmp, auto_wl_path)

def _sync_self_refs_to_whitelist(dict_map):
    """[v157] ์‚ฌ์ „์˜ ์ž๊ธฐ์น˜ํ™˜๊ณผ ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ๋ฅผ ์–‘๋ฐฉํ–ฅ ๋™๊ธฐํ™”.
    - ์‚ฌ์ „์— ์ƒˆ๋กœ ์ƒ๊ธด ์ž๊ธฐ์น˜ํ™˜์€ ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ์— ์ถ”๊ฐ€ (v155 ๋™์ž‘)
    - ์‚ฌ์ „์—์„œ ์ž๊ธฐ์น˜ํ™˜์ด ์‚ฌ๋ผ์ง„ ํ•ญ๋ชฉ์€ ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ์—์„œ๋„ ์ œ๊ฑฐ (v157 ์‹ ๊ทœ)
      ๋‹จ, ์‚ฌ์šฉ์ž๊ฐ€ UI๋กœ ์ง์ ‘ ๋“ฑ๋กํ•œ ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ ํ•ญ๋ชฉ์€ ์ ˆ๋Œ€ ๊ฑด๋“œ๋ฆฌ์ง€ ์•Š์Œ
      (auto_whitelist.json ์— ๊ธฐ๋ก๋œ '์ž๋™ ๋ฏธ๋Ÿฌ๋ง ํ”์ '๋งŒ ๊ด€๋ฆฌ ๋Œ€์ƒ).
    [v158] ์•ˆ์ „ ํ•„ํ„ฐ ์ถ”๊ฐ€: '์ž…๋‹ˆ๋‹ค' ๊ฐ™์€ ์ดˆ๋‹จ์ˆœ ์ž๊ธฐ์น˜ํ™˜(๋‚ด์žฅ ์‚ฌ์ „์— ๋™์ผ ํ‘œ๊ธฐ๋กœ
    ๋“ค์–ด์žˆ๋Š” ๊ฒƒ๋“ค)์„ ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ๋กœ ๋ฏธ๋Ÿฌ๋งํ•˜๋ฉด ์›๋ฌธ์˜ ํ”ํ•œ ์–ด๋ฏธ๊นŒ์ง€ ๋งˆ์Šคํ‚น๋˜์–ด
    ๊ทธ ์•ˆ์˜ ๋ชจ๋“  ์‚ฌ์ „ ๊ทœ์น™์ด ๋งค์นญ์„ ์žƒ๋Š”๋‹ค(10/19 ๋ฒ„๊ทธ). ๋”ฐ๋ผ์„œ
    ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ ์ž๋™ ๋“ฑ๋ก์€ '3๊ธ€์ž ์ด์ƒ + ๊ณต๋ฐฑ ํฌํ•จ ๋ฌธ๊ตฌ'๋งŒ ํ—ˆ์šฉํ•œ๋‹ค.
    ๋ฐ˜ํ™˜: (added, removed) ํŠœํ”Œ."""
    try:
        # [v158] ์ž๋™ ๋ฏธ๋Ÿฌ๋ง ์ž๊ฒฉ ํ•„ํ„ฐ: 3๊ธ€์ž ์ด์ƒ(๊ณต๋ฐฑ ์ œ์™ธ)๋งŒ โ€” '์ž…๋‹ˆ๋‹ค','์ƒํ’ˆ'๋ฅ˜ ๋ณดํ˜ธ
        def _eligible(s):
            return len(re.sub(r'\s+', '', s)) >= 4
        current_self_refs = {t for t in _self_reference_keys(dict_map)
                             if _eligible(t) and not _wl_overlaps_rules(t, dict_map)}
        previously_auto = _read_auto_whitelist()   # ์ด์ „์— ์ž๋™ ๋ฏธ๋Ÿฌ๋งํ•œ ๋ชฉ๋ก
        current_wl = set(_read_local_whitelist())

        added   = current_self_refs - current_wl                     # ์ƒˆ๋กœ ๋„ฃ์„ ํ•ญ๋ชฉ
        removed = (previously_auto - current_self_refs) & current_wl # ์‚ฌ์ „์—์„œ ์‚ฌ๋ผ์ง„ ์ž๋™ ํ•ญ๋ชฉ๋งŒ ์ œ๊ฑฐ
        # [v158] ์ž๊ฒฉ์„ ์žƒ์€ ๊ณผ๊ฑฐ ์ž๋™ ํ•ญ๋ชฉ๋„ ํšŒ์ˆ˜ (์˜ˆ: '์ž…๋‹ˆ๋‹ค'๋ฅ˜๊ฐ€ ๊ณผ๊ฑฐ์— ๋“ค์–ด๊ฐ„ ๊ฒฝ์šฐ)
        removed |= (previously_auto - current_self_refs) & current_wl
        removed |= {t for t in previously_auto if t in current_wl and not _eligible(t)}

        if not added and not removed:
            return [], []

        new_wl = (current_wl | added) - removed
        _write_local_whitelist(sorted(new_wl, key=lambda x: -len(x)))
        # ์ž๋™ ๋ฏธ๋Ÿฌ๋ง ํ”์  ๊ฐฑ์‹  = ์ง€๊ธˆ ์‚ฌ์ „์— ์žˆ๋Š” ์ž๊ธฐ์น˜ํ™˜ ์ „๋ถ€
        _write_auto_whitelist(current_self_refs)

        if hf_api:
            def _bg_push_wl():
                try:
                    msg = _push_remote_whitelist()
                    print(f"[v157 ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ ๋™๊ธฐํ™” ์›๊ฒฉ] {msg}")
                except Exception as e:
                    print(f"[v157 ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ ๋™๊ธฐํ™” ์›๊ฒฉ ์‹คํŒจ] {e}")
            threading.Thread(target=_bg_push_wl, daemon=True).start()

        if added:
            print(f"[v157] ์ž๊ธฐ์น˜ํ™˜ โ†’ ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ ์ถ”๊ฐ€ {len(added)}: {sorted(added)}")
        if removed:
            print(f"[v157] ์ž๊ธฐ์น˜ํ™˜ ํ•ด์ œ โ†’ ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ ์ œ๊ฑฐ {len(removed)}: {sorted(removed)}")
        return sorted(added), sorted(removed)
    except Exception as e:
        print(f"[v157] ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ ๋™๊ธฐํ™” ์‹คํŒจ: {e}")
        return [], []

# ํ•˜์œ„ ํ˜ธํ™˜ ๋ณ„์นญ (๊ธฐ์กด ํ˜ธ์ถœ๋ถ€๊ฐ€ ์ด ์ด๋ฆ„์„ ์ฐธ์กฐํ•˜๋ฏ€๋กœ ์œ ์ง€)
def _mirror_self_refs_to_whitelist(dict_map):
    added, _ = _sync_self_refs_to_whitelist(dict_map)
    return added

def _wl_overlaps_rules(term, dict_map):
    """[v158.3] ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ ํ•ญ๋ชฉ์ด ๋ฐœ์Œ ๊ทœ์น™(k!=v, 4๊ธ€์ž+)๊ณผ ๊ฒน์น˜๋Š”์ง€ ์–‘๋ฐฉํ–ฅ ํŒ์ •.
    ๊ฒน์นจ = ๊ณต๋ฐฑ ์ œ๊ฑฐ ํ›„ ํ•œ์ชฝ์ด ๋‹ค๋ฅธ ์ชฝ์˜ ๋ถ€๋ถ„๋ฌธ์ž์—ด. ์ด๋Ÿฐ ํ•ญ๋ชฉ์ด WL์— ์žˆ์œผ๋ฉด
    ์›๋ฌธ์˜ ๊ทธ ๊ตฌ๊ฐ„์ด ๋งˆ์Šคํ‚น๋˜์–ด ํ•ด๋‹น ๊ทœ์น™์ด ์ ˆ๋Œ€ ๋งค์นญ๋˜์ง€ ๋ชปํ•œ๋‹ค."""
    nt = re.sub(r'\s+', '', term or "")
    if len(nt) < 2:
        return False
    for k, v in (dict_map or {}).items():
        if not k or k == v:
            continue
        nk = re.sub(r'\s+', '', k)
        if len(nk) < 4:
            continue
        if nt in nk or nk in nt:
            return True
    return False

def _release_conflicting_wl_terms(dict_map):
    """[v158.1] ๋ฐœ์Œ ๊ทœ์น™(k!=v)์˜ ํ‚ค์™€ ๊ฒน์ณ ๊ทธ ๋งค์นญ์„ ๋ฐฉํ•ดํ•˜๋Š” ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ ํ•ญ๋ชฉ์„
    '์ž๋™ ๋ฏธ๋Ÿฌ๋ง ํ”์ '์— ํ•œํ•ด์„œ ํšŒ์ˆ˜ํ•œ๋‹ค. ์‚ฌ์šฉ์ž๊ฐ€ UI๋กœ ์ง์ ‘ ๋“ฑ๋กํ•œ ์˜ˆ์™ธ๋Š” ๋ณด์กด.
    ๋ฐฐ๊ฒฝ: ์˜ˆ์ „ ์‹ค์ˆ˜๋กœ ๋“ฑ๋ก๋œ ์ž๊ธฐ์น˜ํ™˜ '์ง€์—์Šค ๋งˆ์ด์ƒต'์ด ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ๋กœ ๋ฏธ๋Ÿฌ๋ง๋˜์–ด
    ์žˆ์œผ๋ฉด, ์ƒˆ ๊ทœ์น™ '์ง€์—์Šค ๋งˆ์ด์ƒต์ž…๋‹ˆ๋‹ค -> ์ง€์—์Šค๋งˆ์ด์ƒค๋น•๋‹ˆ๋‹ค'์˜ ํ‚ค๊ฐ€ ์›๋ฌธ์—์„œ
    ๋งˆ์Šคํ‚น๋˜์–ด ๋งค์นญ ๊ธฐํšŒ์กฐ์ฐจ ๋ชป ์–ป๋Š”๋‹ค(10/19 ์‚ฌ์šฉ์ž ๋ฒ„๊ทธ). ์ž๊ธฐ์น˜ํ™˜ ์ž์ฒด๋Š”
    shields๋กœ ๊ณ„์† ๋ณดํ˜ธ๋˜๋ฏ€๋กœ ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ์—์„œ ๋น ์ ธ๋„ ์›๋ฌธ ์œ ์ง€ ๊ธฐ๋Šฅ์€ ์œ ์ง€๋œ๋‹ค.
    ๋ฐ˜ํ™˜: ํšŒ์ˆ˜๋œ ํ•ญ๋ชฉ ๋ชฉ๋ก."""
    try:
        auto = _read_auto_whitelist()
        wl = set(_read_local_whitelist())
        rule_keys = [re.sub(r'\s+', '', k) for k, v in (dict_map or {}).items()
                     if k and k != v and len(re.sub(r'\s+', '', k)) >= 4]
        released = []
        # [v158.2] ํšŒ์ˆ˜ ๋Œ€์ƒ์„ ํ”์  ํŒŒ์ผ์— ์˜์กดํ•˜์ง€ ์•Š๊ฒŒ ํ™•์žฅ โ€” HF Space๋Š” ์žฌ์‹œ์ž‘ ์‹œ
        # auto_whitelist.json์ด ์‚ฌ๋ผ์ง€๋ฏ€๋กœ(๋น„์˜๊ตฌ ๋””์Šคํฌ), ํ”์ ๋งŒ ๋ณด๋ฉด ํšŒ์ˆ˜๊ฐ€ ๋ˆ„๋ฝ๋œ๋‹ค.
        # [v158.3] ๊ฒน์นจ ํŒ์ •์„ ์–‘๋ฐฉํ–ฅ์œผ๋กœ โ€” WL ํ•ญ๋ชฉ์ด ๊ทœ์น™ ํ‚ค๋ณด๋‹ค ๊ธด ๊ฒฝ์šฐ(์˜ˆ:
        # '์•ˆ๋…•ํ•˜์„ธ์š”, ์ง€์—์Šค ๋งˆ์ด์ƒต์ž…๋‹ˆ๋‹ค.')๋„ ๊ทธ ๊ตฌ๊ฐ„์„ ๋งˆ์Šคํ‚นํ•ด ๊ทœ์น™์„ ๋ง‰์œผ๋ฏ€๋กœ ํšŒ์ˆ˜.
        # ๋Œ€์ƒ: (a) ์‚ฌ์ „์— ์ž๊ธฐ์น˜ํ™˜(k==v)์œผ๋กœ ์กด์žฌํ•˜๊ฑฐ๋‚˜ (b) ๊ทœ์น™ ํ‚ค์™€ ๊ฐ™์€ ๋ฌธ์ž์—ด
        # (๋„์–ด์“ฐ๊ธฐ๋งŒ ๋‹ค๋ฆ„)์ธ WL ํ•ญ๋ชฉ โ€” ์ „๋ถ€ ์ž๋™ ๋ฏธ๋Ÿฌ๋ง ์‚ฐ๋ฌผ๋กœ ๊ฐ„์ฃผ. ์ž๊ธฐ์น˜ํ™˜์€
        # shields๊ฐ€ ๊ณ„์† ๋ณดํ˜ธํ•˜๋ฏ€๋กœ ์•ˆ์ „. ์‚ฌ์šฉ์ž ์ˆ˜๋™ ์˜ˆ์™ธ(์‚ฌ์ „์— ์—†๋Š” ํ•ญ๋ชฉ)๋Š” ๋ณด์กด.
        norm_rule_keys = [re.sub(r'\s+', '', k) for k in dict_map
                          if k and dict_map[k] != k and len(re.sub(r'\s+', '', k)) >= 4]
        candidates = set(auto) | {t for t in wl if dict_map.get(t) == t}
        for t in wl:
            if re.sub(r'\s+', '', t) in norm_rule_keys:
                candidates.add(t)
        for t in sorted(candidates, key=lambda x: -len(x)):
            nt = re.sub(r'\s+', '', t)
            if t in wl and nt and any(nt in rk or rk in nt for rk in norm_rule_keys):
                wl.discard(t)
                auto.discard(t)
                released.append(t)
        if released:
            _write_local_whitelist(sorted(wl, key=lambda x: -len(x)))
            _write_auto_whitelist(auto)
            if hf_api:
                def _bg_push_rel():
                    try:
                        msg = _push_remote_whitelist()
                        print(f"[v158.1 ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ ํšŒ์ˆ˜ ์›๊ฒฉ] {msg}")
                    except Exception as e:
                        print(f"[v158.1 ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ ํšŒ์ˆ˜ ์›๊ฒฉ ์‹คํŒจ] {e}")
                threading.Thread(target=_bg_push_rel, daemon=True).start()
            print(f"[v158.1] ์ƒˆ ๊ทœ์น™๊ณผ ์ถฉ๋Œํ•˜๋Š” ์ž๋™ ์˜ˆ์™ธ {len(released)}๊ฐœ ํšŒ์ˆ˜: {released}")
        return released
    except Exception as e:
        print(f"[v158.1] ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ ์ถฉ๋Œ ํšŒ์ˆ˜ ์‹คํŒจ: {e}")
        return []

def save_dict(dict_map):
    _write_local_dict(dict_map)
    _ENGINE_CACHE["sig"] = None
    # [v157] ์‚ฌ์ „ ์ž๊ธฐ์น˜ํ™˜ โ†” ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ ์–‘๋ฐฉํ–ฅ ๋™๊ธฐํ™”
    # - ์ƒˆ ์ž๊ธฐ์น˜ํ™˜: ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ์— ์ถ”๊ฐ€ (v155 ๊ธฐ๋Šฅ ์œ ์ง€)
    # - ๋ฐœ์Œ์ด ๋ฐ”๋€Œ์–ด ๋”๋Š” ์ž๊ธฐ์น˜ํ™˜์ด ์•„๋‹Œ ํ•ญ๋ชฉ: ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ์—์„œ ์ž๋™ ์ œ๊ฑฐ
    #   (์‚ฌ์šฉ์ž๊ฐ€ UI๋กœ ์ง์ ‘ ๋“ฑ๋กํ•œ ์˜ˆ์™ธ ๋‹จ์–ด๋Š” ๊ฑด๋“œ๋ฆฌ์ง€ ์•Š์Œ)
    added_wl, removed_wl = _sync_self_refs_to_whitelist(dict_map)
    released_wl = _release_conflicting_wl_terms(dict_map)   # [v158.1] ๊ทœ์น™-์˜ˆ์™ธ ์ถฉ๋Œ ํ•ด์†Œ
    parts = []
    if added_wl: parts.append(f"์ž๊ธฐ์น˜ํ™˜ {len(added_wl)}๊ฐœ ์˜ˆ์™ธ ์ž๋™ ๋“ฑ๋ก")
    if removed_wl: parts.append(f"๋ฐœ์Œ ์ˆ˜์ •๋œ {len(removed_wl)}๊ฐœ ์˜ˆ์™ธ ์ž๋™ ํ•ด์ œ")
    if released_wl: parts.append(f"์ƒˆ ๊ทœ์น™๊ณผ ์ถฉ๋Œํ•˜๋Š” ์ž๋™ ์˜ˆ์™ธ {len(released_wl)}๊ฐœ ํšŒ์ˆ˜({', '.join(released_wl[:2])}{'...' if len(released_wl) > 2 else ''})")
    wl_note = (" ยท " + ", ".join(parts)) if parts else ""
    # [v152] ์›๊ฒฉ ์—…๋กœ๋“œ๋Š” ์‘๋‹ต์„ ๋ง‰์ง€ ์•Š๋„๋ก ๋ฐฑ๊ทธ๋ผ์šด๋“œ๋กœ ๋ฐ€์–ด๋ƒ„.
    # ์‹คํŒจํ•ด๋„ ๋กœ์ปฌ ์ €์žฅ์€ ์ด๋ฏธ ์™„๋ฃŒ๋œ ์ƒํƒœ โ€” ๋กœ๊ทธ๋กœ๋งŒ ๋‚จ๊ธด๋‹ค.
    if hf_api:
        def _bg_push():
            try:
                msg = _push_remote()
                print(f"[์‚ฌ์ „ ์›๊ฒฉ ์ €์žฅ] {msg}")
            except Exception as e:
                print(f"[์‚ฌ์ „ ์›๊ฒฉ ์ €์žฅ ์‹คํŒจ] {e}")
        threading.Thread(target=_bg_push, daemon=True).start()
        msg = "์ €์žฅ ์™„๋ฃŒ (์›๊ฒฉ ๋™๊ธฐํ™”๋Š” ๋ฐฑ๊ทธ๋ผ์šด๋“œ ์ง„ํ–‰ ์ค‘)"
    else:
        msg = "๋กœ์ปฌ ์ €์žฅ ์™„๋ฃŒ (HF_TOKEN ์—†์Œ โ€” ์žฌ์‹œ์ž‘ ์‹œ ์œ ์‹ค ๊ฐ€๋Šฅ)"
    return f"{msg} ยท ํ˜„์žฌ ์‚ฌ์ „ {len(dict_map)}๊ฐœ{wl_note}"

# ---------- [v153] ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ I/O + ๋งˆ์Šคํ‚น ----------
def _read_local_whitelist():
    try:
        with open(whitelist_path, "r", encoding="utf-8") as f:
            data = json.load(f)
        return sorted({str(x).strip() for x in data.get("items", []) if str(x).strip()},
                      key=lambda x: -len(x))
    except Exception:
        return []

def _write_local_whitelist(wl_list):
    items = sorted({s.strip() for s in wl_list if s and s.strip()}, key=lambda x: -len(x))
    payload = {"items": items, "meta": {"app_title": "VoiceScript AI whitelist",
                                        "app_version": "153.0", "count": len(items)}}
    tmp_path = whitelist_path + ".tmp"
    with open(tmp_path, "w", encoding="utf-8") as f:
        json.dump(payload, f, ensure_ascii=False, indent=2)
    if os.path.exists(whitelist_path):
        os.replace(whitelist_path, whitelist_path + ".bak")
    os.replace(tmp_path, whitelist_path)

def _push_remote_whitelist():
    if not hf_api:
        return "๋กœ์ปฌ ์ €์žฅ๋งŒ ๋จ (์žฌ์‹œ์ž‘ ์‹œ ์œ ์‹ค ๊ฐ€๋Šฅ - HF_TOKEN ์„ค์ • ํ•„์š”)"
    try:
        hf_api.upload_file(path_or_fileobj=whitelist_path, path_in_repo="custom_whitelist.json",
                           repo_id=dict_repo_id, repo_type="dataset",
                           commit_message="update pronunciation whitelist")
        return "์˜๊ตฌ ์ €์žฅ ์™„๋ฃŒ"
    except Exception as e:
        return f"์›๊ฒฉ ์ €์žฅ ์‹คํŒจ({e}) - ๋กœ์ปฌ๋งŒ ์ €์žฅ๋จ"

def save_whitelist(wl_list):
    _write_local_whitelist(wl_list)
    if hf_api:
        def _bg_push():
            try:
                msg = _push_remote_whitelist()
                print(f"[ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ ์›๊ฒฉ ์ €์žฅ] {msg}")
            except Exception as e:
                print(f"[ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ ์›๊ฒฉ ์ €์žฅ ์‹คํŒจ] {e}")
        threading.Thread(target=_bg_push, daemon=True).start()
        msg = "์ €์žฅ ์™„๋ฃŒ (์›๊ฒฉ ๋™๊ธฐํ™”๋Š” ๋ฐฑ๊ทธ๋ผ์šด๋“œ ์ง„ํ–‰ ์ค‘)"
    else:
        msg = "๋กœ์ปฌ ์ €์žฅ ์™„๋ฃŒ (HF_TOKEN ์—†์Œ)"
    items = _read_local_whitelist()
    return f"{msg} ยท ํ˜„์žฌ ์˜ˆ์™ธ ๋‹จ์–ด {len(items)}๊ฐœ", items

_WL_TOKEN_FMT = "\x00WL{}\x00"

def _mask_whitelist(text, wl_terms):
    """ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ ๋‹จ์–ด๋“ค์„ ์ž„์‹œ ํ† ํฐ์œผ๋กœ ์น˜ํ™˜. (masked_text, token_map) ๋ฐ˜ํ™˜."""
    if not text or not wl_terms:
        return text, {}
    # ๊ธด ๊ฒƒ๋ถ€ํ„ฐ ๋งค์นญ (๊ฒน์นจ ๋ฐฉ์ง€)
    ordered = sorted({w for w in wl_terms if w}, key=lambda x: -len(x))
    token_map = {}
    for idx, term in enumerate(ordered):
        token = _WL_TOKEN_FMT.format(idx)
        if term in text:
            text = text.replace(term, token)
            token_map[token] = term
    return text, token_map

def _unmask_whitelist(text, token_map):
    if not token_map:
        return text
    for token, term in token_map.items():
        text = text.replace(token, term)
    return text

def load_whitelist(user_temp_wl=None, user_temp_dict=None):
    """[v158] ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ ์†Œ์Šค:
       1) custom_whitelist.json (์˜๊ตฌ)
       2) ๊ฒŒ์ŠคํŠธ ์ž„์‹œ ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ (user_temp_wl)
       3) ์„œ๋ฒ„ ์‚ฌ์ „ + ๊ฒŒ์ŠคํŠธ ์ž„์‹œ ์‚ฌ์ „์˜ ์ž๊ธฐ์น˜ํ™˜(k==v) ํ•ญ๋ชฉ โ€” ๋‹จ, 3๊ธ€์ž ์ด์ƒ๋งŒ
          ('์ž…๋‹ˆ๋‹ค'๋ฅ˜ ๋‹จ์ˆœ ์ž๊ธฐ์น˜ํ™˜์„ ๋„ฃ์œผ๋ฉด ์›๋ฌธ ์–ด๋ฏธ๊นŒ์ง€ ๋งˆ์Šคํ‚น๋˜์–ด ์‚ฌ์ „ ๊ทœ์น™์ด
          ์ „๋ถ€ ๋ฌด๋ ฅํ™”๋˜๋Š” 10/19 ๋ฒ„๊ทธ์˜ ์žฌ๋ฐœ์„ ๋ง‰๋Š”๋‹ค)
    """
    base = list(_read_local_whitelist())
    if user_temp_wl:
        base.extend([str(x).strip() for x in user_temp_wl if str(x).strip()])
    # [v158] ์•ˆ์ „๋ง๋„ ์ž๊ฒฉ ํ•„ํ„ฐ ์ ์šฉ โ€” 3๊ธ€์ž(๊ณต๋ฐฑ ์ œ์™ธ) ์ด์ƒ๋งŒ ์ž๋™ ์˜ˆ์™ธ๋กœ ์ธ์ •
    def _eligible(s):
        return len(re.sub(r'\s+', '', s)) >= 4
    try:
        server_dict = _read_local_dict()
        base.extend(x for x in _self_reference_keys(server_dict)
                    if _eligible(x) and not _wl_overlaps_rules(x, server_dict))
    except Exception:
        pass
    if user_temp_dict:
        base.extend(x for x in _self_reference_keys(user_temp_dict)
                    if _eligible(x) and not _wl_overlaps_rules(x, user_temp_dict))
    # ์ค‘๋ณต ์ œ๊ฑฐ + ๊ธด ์ˆœ
    return sorted({b.strip() for b in base if b and b.strip()}, key=lambda x: -len(x))

def perform_startup_recovery():
    dict_map = _read_local_dict()
    remote_ok = True
    if hf_api:
        try:
            remote_path = hf_hub_download(repo_id=dict_repo_id, repo_type="dataset",
                                          filename="custom_dict.json", token=HF_TOKEN)
            with open(remote_path, "r", encoding="utf-8") as f:
                remote = json.load(f)
            for i in remote.get("items", []):
                if len(i) == 2:
                    dict_map[i[0].strip()] = i[1].strip()
        except Exception as e:
            is_404 = getattr(getattr(e, "response", None), "status_code", None) == 404
            if is_404:
                print("[์‚ฌ์ „] ์›๊ฒฉ์— ์•„์ง ์‚ฌ์ „ ํŒŒ์ผ ์—†์Œ โ€” ์ตœ์ดˆ ๋ถ€ํŒ…์œผ๋กœ ์ฒ˜๋ฆฌ")
            else:
                remote_ok = False
                print(f"[์‚ฌ์ „] ์›์ธก ๋ณต์› ์‹คํŒจ({e}) - ๋กœ์ปฌ ์‚ฌ์ „ ๋ณดํ˜ธ")
    for w in AUTO_MERGE_WORDS:
        dict_map.setdefault(w[0], w[1])          # ์‚ฌ์šฉ์ž๊ฐ’ ์ ˆ๋Œ€ ์•ˆ ๋ฎ์–ด์“ฐ๊ธฐ
    _write_local_dict(dict_map)
    if hf_api and remote_ok:
        _push_remote()

    # [v153] ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ๋„ ์›๊ฒฉ์—์„œ ๋ณต์› ์‹œ๋„ (์—†์œผ๋ฉด ๋ฌด์‹œ)
    wl_local = _read_local_whitelist()
    if hf_api:
        try:
            remote_wl_path = hf_hub_download(repo_id=dict_repo_id, repo_type="dataset",
                                             filename="custom_whitelist.json", token=HF_TOKEN)
            with open(remote_wl_path, "r", encoding="utf-8") as f:
                remote_wl = json.load(f)
            merged = set(wl_local) | {str(x).strip() for x in remote_wl.get("items", []) if str(x).strip()}
            _write_local_whitelist(list(merged))
        except Exception as e:
            is_404 = getattr(getattr(e, "response", None), "status_code", None) == 404
            if is_404:
                print("[ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ] ์›๊ฒฉ์— ํŒŒ์ผ ์—†์Œ โ€” ์ตœ์ดˆ ๋ถ€ํŒ…")
            else:
                print(f"[ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ] ์›๊ฒฉ ๋ณต์› ์‹คํŒจ({e}) - ๋กœ์ปฌ ๋ณดํ˜ธ")

    # [v157] ๋ถ€ํŒ… ์‹œ ์‚ฌ์ „ ์ž๊ธฐ์น˜ํ™˜ โ†” ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ ์–‘๋ฐฉํ–ฅ ๋™๊ธฐํ™”
    try:
        _sync_self_refs_to_whitelist(dict_map)
    except Exception as e:
        print(f"[v157] ๋ถ€ํŒ… ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ ๋™๊ธฐํ™” ์‹คํŒจ: {e}")
    # [v158.2] ๋ถ€ํŒ… ์‹œ ๊ทœ์น™-์˜ˆ์™ธ ์ถฉ๋Œ ํ•ญ๋ชฉ ํšŒ์ˆ˜ (Space ์žฌ์‹œ์ž‘ ํ›„์—๋„ ์˜ค์—ผ ์ž๋™ ์ •๋ฆฌ)
    try:
        _release_conflicting_wl_terms(dict_map)
    except Exception as e:
        print(f"[v158.2] ๋ถ€ํŒ… ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ ํšŒ์ˆ˜ ์‹คํŒจ: {e}")

perform_startup_recovery()

def load_dict(user_temp_dict=None):
    flat_dict = _read_local_dict()
    if user_temp_dict:
        flat_dict.update({k.strip(): v.strip() for k, v in user_temp_dict.items()})
    return flat_dict

# ---------- 2๋‹จ๊ณ„ ๋งค์นญ ์—”์ง„ (ํ‘œ๊ธฐ ์ •๊ทœํ™” โ†’ ๋ฐœ์Œ ์น˜ํ™˜) ----------
_ENGINE_CACHE = {"sig": None}

# [v156] ์‚ฌ์ „ ํ‚ค๋ฅผ ์›๋ฌธ๊ณผ ๋งค์นญํ•  ๋•Œ ์™„ํ™” ๋Œ€์ƒ์œผ๋กœ ์‚ผ๋Š” ๋ฌธ์ž ํด๋ž˜์Šค.
# ๊ณต๋ฐฑยท๋งˆ์นจํ‘œยท์‰ผํ‘œยท๊ฐ€์šด๋Žƒ์ ยท๋А๋‚Œํ‘œยท๋ฌผ์Œํ‘œยท์ค‘์ ยท๋ง์ค„์ž„ โ€” ๋ชจ๋‘ '์žˆ์–ด๋„/์—†์–ด๋„' ๋งค์นญ.
_PUNCT_FLEX = r'[\s,\.\!\?ยทโ€ขโ€ฆใ€ใ€‚]*'

def _flex_body_pure_hangul(k):
    """[v156] ์ˆœ์ˆ˜ ํ•œ๊ธ€ ํ‚ค์— ๋Œ€ํ•ด '๊ณต๋ฐฑ/๊ตฌ๋‘์  ์œ ์—ฐ' ์ •๊ทœ์‹ ๋ชธํ†ต ์ƒ์„ฑ.
    - ํ‚ค ๋‚ด๋ถ€์˜ ๊ณต๋ฐฑยท๊ตฌ๋‘์ ์€ ์›๋ฌธ์—์„œ ์žˆ์–ด๋„ ์—†์–ด๋„ ๋งค์นญ๋˜๋„๋ก [\\s,.!?...]* ๋กœ ์น˜ํ™˜
    - ํ•œ๊ธ€ ์‚ฌ์ด์—๋Š” ์›๋ฌธ ๊ตฌ๋‘์ (์˜ˆ: ', ')์ด ๋ผ์–ด๋„ ๋งค์นญ๋˜๋„๋ก [\\s,.!?...]* ๋ฅผ ์‚ฝ์ž…
    ์ด๋ ‡๊ฒŒ ํ•˜๋ฉด ์‚ฌ์šฉ์ž๊ฐ€ ๋งˆ์นจํ‘œยท์‰ผํ‘œยท๋„์–ด์“ฐ๊ธฐ๋ฅผ ์–ด๋–ป๊ฒŒ ๋„ฃ๋“  ๋งค์นญ๋จ.
    """
    # ํ‚ค์—์„œ ๊ณต๋ฐฑยท๊ตฌ๋‘์ ์„ ๋ชจ๋‘ ๋ฝ‘์•„๋‚ธ ํ•œ๊ธ€ ์‹œํ€€์Šค
    hangul_only = re.sub(r'[\s,\.\!\?ยทโ€ขโ€ฆใ€ใ€‚]+', '', k)
    if not hangul_only:
        # ํ•œ๊ธ€์ด ์—†์œผ๋ฉด (์ด ํ•จ์ˆ˜๊ฐ€ ํ˜ธ์ถœ๋  ๋ฆฌ ์—†์ง€๋งŒ) ๊ธฐ์กด ๋ฐฉ์‹ ์œ ์ง€
        return r'\s*'.join(map(re.escape, k.split(" ")))
    # ํ•œ ๊ธ€์ž๋งˆ๋‹ค ๋’ค์— ์œ ์—ฐ ๊ตฌ๋‘์  ํด๋ž˜์Šค ์‚ฝ์ž… (๋งˆ์ง€๋ง‰ ๊ธ€์ž ๋’ค์—” ๋ถ™์ด์ง€ ์•Š์Œ)
    parts = []
    for i, ch in enumerate(hangul_only):
        parts.append(re.escape(ch))
        if i < len(hangul_only) - 1:
            parts.append(_PUNCT_FLEX)
    return "".join(parts)

def _build_pattern(keys):
    r"""ํ‚ค ๊ธธ์ด ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌ ํ›„ ๊ณต๋ฐฑ์„ \s* ๋กœ ๋ฐ”๊พผ ์œ ์—ฐ ํŒจํ„ด. ๊ทธ๋ฃน๋ฒˆํ˜ธโ†’ํ‚ค.
    [v150] 1๊ธ€์ž ์˜์ˆซ์ž ํ‚ค๋Š” ๋‹จ์–ด ๊ฒฝ๊ณ„(boundary)๋ฅผ ๊ฐ•์ œํ•ด์„œ
    'CLASS' ๊ฐ™์€ ๋‹จ์–ด ์ค‘๊ฐ„์—์„œ ์˜คํƒ๋˜์ง€ ์•Š๊ฒŒ ํ•œ๋‹ค.
    [v152] ์ˆœ์ˆ˜ ํ•œ๊ธ€ ํ‚ค๋Š” ์ขŒ์ธก์— ํ•œ๊ธ€์ด ์˜ค๋ฉด ๋งค์นญ ๊ธˆ์ง€ โ€” '์—์Šค'๊ฐ€
    'ํด๋ฆฌ์—์Šคํ„ฐ' ๊ฐ™์€ ํ•ฉ์„ฑ์–ด ์ค‘๊ฐ„์—์„œ ์˜คํƒ๋˜์ง€ ์•Š๋„๋ก.
    [v154] ์ˆœ์ˆ˜ ํ•œ๊ธ€ ํ‚ค๋Š” guarded=True โ€” ์‹ค์ œ ๋งค์นญ ์‹œ ํ˜•ํƒœ์†Œ ๊ฒฝ๊ณ„
    (์กฐ์‚ฌ/์–ด๋ฏธ ์—ฌ๋ถ€, Kiwi ๋˜๋Š” ์กฐ์‚ฌ ๋ฆฌ์ŠคํŠธ ํด๋ฐฑ)๋ฅผ ํ™•์ธํ•ด
    '์—์Šค์ปฌ๋ ˆ์ดํ„ฐ/์—์Šคํ”„๋ ˆ์†Œ/์ œ์ด์Šจ์šฐ' ๊ฐ™์€ ํ•ฉ์„ฑ์–ด ์˜คํƒ์„ ๋ง‰๋Š”๋‹ค.
    [v156] ์ˆœ์ˆ˜ ํ•œ๊ธ€ ํ‚ค(๊ณต๋ฐฑยท๊ตฌ๋‘์  ์„ž์—ฌ ์žˆ์–ด๋„ ํ•œ๊ธ€๋งŒ ๋‚จ์œผ๋ฉด ์ˆœ์ˆ˜ ํ•œ๊ธ€๋กœ ์ทจ๊ธ‰)๋Š”
    ์›๋ฌธ์˜ ๊ณต๋ฐฑยท๊ตฌ๋‘์  ํŽธ์ฐจ๋ฅผ ํก์ˆ˜ํ•˜๋„๋ก ์œ ์—ฐ ๋งค์นญ ๋ชธํ†ต์„ ์‚ฌ์šฉํ•œ๋‹ค."""
    ordered = sorted(keys, key=lambda x: -len(x.replace(" ", "")))
    if not ordered:
        return None, [], []
    pats, guarded = [], []
    for k in ordered:
        if len(k) == 1 and re.match(r'^[A-Za-z0-9_]$', k):
            # 1๊ธ€์ž ์˜์ˆซ์ž: ์ขŒ์šฐ alphanumeric/underscore๊ฐ€ ์˜ค๋ฉด ๋งค์นญ ์•ˆ ํ•จ
            pats.append(rf'(?<![A-Za-z0-9_]){re.escape(k)}(?![A-Za-z0-9_])')
            guarded.append(False)
        else:
            # [v156] ๊ณต๋ฐฑยท๊ตฌ๋‘์ ์„ ์ œ๊ฑฐํ–ˆ์„ ๋•Œ ์ˆœ์ˆ˜ ํ•œ๊ธ€์ด๋ฉด ์œ ์—ฐ ๋งค์นญ ๋ชธํ†ต ์‚ฌ์šฉ
            stripped = re.sub(r'[\s,\.\!\?ยทโ€ขโ€ฆใ€ใ€‚]+', '', k)
            if stripped and re.match(r'^[๊ฐ€-ํžฃ]+$', stripped):
                body = _flex_body_pure_hangul(k)
                pats.append(rf'(?<![๊ฐ€-ํžฃ]){body}')
                guarded.append(True)
            else:
                body = r'\s*'.join(map(re.escape, k.split(" ")))
                pats.append(body)
                guarded.append(False)
    return re.compile("|".join(f"({p})" for p in pats)), ordered, guarded

def get_engine(flat_dict):
    sig = hash(tuple(sorted(flat_dict.items())))
    if _ENGINE_CACHE.get("sig") == sig:
        return _ENGINE_CACHE
    phase1, phase2, shields = {}, {}, set()
    for k, v in flat_dict.items():
        if not k:
            continue
        if k == v:
            shields.add(k)
        elif re.sub(r'[\s,\.\!\?ยทโ€ขโ€ฆใ€ใ€‚]+', '', k) == re.sub(r'[\s,\.\!\?ยทโ€ขโ€ฆใ€ใ€‚]+', '', v):
            phase1[k] = v
            shields.add(v)
        else:
            phase2[k] = v
    p1_pat, p1_keys, p1_guard = _build_pattern(phase1.keys())
    p2_pat, p2_keys, p2_guard = _build_pattern(phase2.keys())
    sh_pat, _, _ = _build_pattern(shields)
    _ENGINE_CACHE.update({"sig": sig, "phase1": phase1, "phase2": phase2,
                          "p1_pat": p1_pat, "p1_keys": p1_keys,
                          "p2_pat": p2_pat, "p2_keys": p2_keys, "sh_pat": sh_pat,
                          "p1_guard": p1_guard, "p2_guard": p2_guard})
    return _ENGINE_CACHE

def _sub_phase1(text, eng, boundary=None):
    if not eng["p1_pat"]:
        return text
    guard = eng.get("p1_guard", []) or []
    def _repl(m):
        gi = m.lastindex - 1
        if guard[gi] and boundary is not None and not boundary.allow_after(m.end()):
            return m.group()          # ํ•ฉ์„ฑ์–ด ๋‚ด๋ถ€ โ†’ ์œ ์ง€
        return eng["phase1"][eng["p1_keys"][gi]]
    return eng["p1_pat"].sub(_repl, text)

def _segments_phase2(text, eng, boundary=None):
    if not eng["p2_pat"] or not text:
        return [(False, text)] if text else []
    guard = eng.get("p2_guard", []) or []
    segs, last = [], 0
    for m in eng["p2_pat"].finditer(text):
        s, e = m.span()
        gi = m.lastindex - 1
        if guard[gi] and boundary is not None and not boundary.allow_after(e):
            continue                # ํ•ฉ์„ฑ์–ด ๋‚ด๋ถ€ โ†’ ์ด ๋งค์นญ ๊ฑด๋„ˆ๋œ€ (์›๋ฌธ ์œ ์ง€)
        if s > last:
            segs.append((False, text[last:s]))
        segs.append((True, eng["phase2"][eng["p2_keys"][gi]]))
        last = e
    if last < len(text):
        segs.append((False, text[last:]))
    return segs

def _g2p_shielded(chunk, mode, eng):
    if not chunk:
        return chunk
    if not eng["sh_pat"]:
        return apply_g2p(chunk, mode)
    res, last = [], 0
    for m in eng["sh_pat"].finditer(chunk):
        s, e = m.span()
        if s > last:
            res.append(apply_g2p(chunk[last:s], mode))
        res.append(m.group())
        last = e
    res.append(apply_g2p(chunk[last:], mode))
    return "".join(res)

def convert_text(text, mode, flat_dict, whitelist=None):
    """์›๋ฌธ ๋น„๊ณต๋ฐฑ ๋ฌธ์ž์—ด ๋ณ€ํ™˜ ์ „ํ›„ ๋™์ผ์„ฑ ์œ ์ง€.
    ์™ธํ˜• ๋ณ€ํ™”๋Š” ์‚ฌ์ „ยท์ˆซ์žยท๋ฌธ์žฅ๋ถ€ํ˜ธ ํ˜ธํก ๋งˆ์ปค๋กœ๋งŒ ๋งŒ๋“ค์–ด์ง„๋‹ค.
    [v153] whitelist์— ํฌํ•จ๋œ ๋‹จ์–ด๋Š” ์–ด๋–ค ์‚ฌ์ „ ํ‚ค๊ฐ€ ์•ˆ์— ๋“ค์–ด์žˆ์–ด๋„
    ์น˜ํ™˜ ๋Œ€์ƒ์—์„œ ์™„์ „ํžˆ ์ œ์™ธ๋œ๋‹ค."""
    text, wl_map = _mask_whitelist(text, whitelist or [])
    eng = get_engine(flat_dict)
    t = _sub_phase1(text, eng, _MorphBoundary(text))
    out = []
    b2 = _MorphBoundary(t)
    for fixed, chunk in _segments_phase2(t, eng, b2):
        if fixed:
            out.append(chunk)
            continue
        chunk = apply_smart_regex(chunk)
        # [v154] 2์ฐจ ๋งค์นญ๋„ ์กฐ๊ฐ ๋‹จ์œ„ ํ˜•ํƒœ์†Œ ๊ฐ€๋“œ ์ ์šฉ โ€” 1์ฐจ์—์„œ ๊ฑฐ์ ˆ๋œ
        # ํ•ฉ์„ฑ์–ด(์—์Šค์ปฌ๋ ˆ์ดํ„ฐ ๋“ฑ)๊ฐ€ ์ด ๋ฃจํ”„์—์„œ ์žฌ์˜คํƒ๋˜๋Š” ๊ฒƒ ๋ฐฉ์ง€.
        b_chunk = _MorphBoundary(chunk)
        for fixed2, c2 in _segments_phase2(chunk, eng, b_chunk):
            out.append(c2 if fixed2 else _g2p_shielded(c2, mode, eng))
    return _unmask_whitelist("".join(out), wl_map)

# ---------- G2P ๋ชจ๋“œ ----------
def apply_g2p(text, mode):
    if g2p is None or mode.startswith("๋„๊ธฐ"):
        return text
    if mode.startswith("๋งค์šด ๋ง›"):
        try:
            return g2p(text)
        except Exception:
            return text
    if mode.startswith("์ˆœํ•œ ๋ง›"):
        words = re.split(r'(\s+)', text)
        res = []
        for w in words:
            if w.strip():
                try:
                    res.append(g2p(w))
                except Exception:
                    res.append(w)
            else:
                res.append(w)
        return "".join(res)
    if mode.startswith("์ค‘๊ฐ„ ๋ง›"):
        # ๋ช…์‚ฌ/๊ณ ์œ ์–ด (ํ•œ๊ธ€ 2๊ธ€์ž+) ๋งŒ ๋ณ€ํ™˜, ๋‹จ์ผ ์กฐ์‚ฌยท๋ณด์กฐ์‚ฌยท๊ธฐํ˜ธ๋Š” ๊ฑด๋„ˆ๋œ€
        tokens = re.split(r'([๊ฐ€-ํžฃ]+|[a-zA-Z]+|\d+|[^\w\s]+|\s+)', text)
        particles = {'์ด', '๊ฐ€', '์„', '๋ฅผ', '์—', '๋Š”', '์€', '๋กœ', '์œผ๋กœ', '๊ณ ',
                     '๋„ค', '์–ด', '์š”', '๋‹ค', '์ž…๋‹ˆ๋‹ค', '์Šต๋‹ˆ๋‹ค'}
        res = []
        for t in tokens:
            if not t:
                continue
            if t.isspace() or t in particles or len(t) == 1:
                res.append(t)
            elif re.match(r'^[๊ฐ€-ํžฃ]{2,}$', t):
                try:
                    res.append(g2p(t))
                except Exception:
                    res.append(t)
            else:
                res.append(t)
        return "".join(res)
    return text

# ---------- ์ˆซ์ž/๋‹จ์œ„ ํ•œ๊ตญ์–ด ๋ณ€ํ™˜ ----------
def number_to_korean(num_str):
    num_str = num_str.replace(',', '')
    try:
        n = int(num_str)
    except Exception:
        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'\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": "ํŒ”ํŒ”",
                 "95": "๊ตฌ์˜ค", "100": "๋ฐฑ", "105": "๋ฐฑ์˜ค", "110": "๋ฐฑ์‹ญ"}
    def _size_repl(m):
        k = m.group(1)
        return f"{size_dict[k]} ์‹ธ์ด์ฆˆ" if k in size_dict else m.group(0)
    text = re.sub(r'\b(55|66|77|88|95|100|105|110)\s*์‚ฌ์ด์ฆˆ\b', _size_repl, 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)
    unit_dict = {"mm": "๋ฐ€๋ฆฌ๋ฏธํ„ฐ", "cm": "์„ผํ‹ฐ๋ฏธํ„ฐ", "m": "๋ฏธํ„ฐ", "km": "ํ‚ฌ๋กœ๋ฏธํ„ฐ",
                 "g": "๊ทธ๋žจ", "kg": "ํ‚ฌ๋กœ๊ทธ๋žจ", "ml": "๋ฐ€๋ฆฌ๋ฆฌํ„ฐ", "L": "๋ฆฌํ„ฐ"}
    def _unit_repl(m):
        num_u, u = m.group(1), m.group(2).lower() if m.group(2).lower() != 'l' else 'L'
        return f"{number_to_korean(num_u)} {unit_dict[u]}"
    text = re.sub(r'(\d+)\s*(mm|cm|m|km|g|kg|ml|L)\b', _unit_repl, text, flags=re.IGNORECASE)
    return text

# ---------- ์ฒ˜๋ฆฌ ํ•œ ์ค„์— ๋ชจ์œผ๊ธฐ (ํ˜ธํก์ ๋งŒ ๋ฌธ์žฅ๋ถ€ํ˜ธ ๊ธฐ๋ฐ˜) ----------
def _join_breath_marks(text):
    """์‰ผํ‘œยท๊ฐ€์šด๋Žƒ์ ยท๋ง์ค„์ž„ํ‘œ ๋’ค์— ํ˜ธํก ๋งˆํฌ('/')๋ฅผ ๋„ฃ๊ณ , `@@` ๋งˆ์ปค๋Š” ๋ณด์กดํ•œ๋‹ค."""
    text = re.sub(r'[,ใ€]\s*', ', / ', text)
    text = re.sub(r'[ยทโ€ข]\s*', 'ยท / ', text)
    text = re.sub(r'โ€ฆ\s*', 'โ€ฆ / ', text)
    return text

def process_text(input_text, ai_mode, auto_break, smart_pause, font_size, user_temp_dict, user_temp_wl=None):
    if not input_text or 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์ž", "ํ‘œ์‹œ๋œ ๋งˆ์ปค(@@)๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค."

    char_count = f"๊ณต๋ฐฑ ํฌํ•จ: {len(input_text)}์ž / ๊ณต๋ฐฑ ์ œ์™ธ: {len(input_text.replace(' ', '').replace(chr(10), ''))}์ž"

    flat_dict = load_dict(user_temp_dict)
    whitelist = load_whitelist(user_temp_wl, user_temp_dict)
    if not flat_dict:
        # ์‚ฌ์ „์€ ์—†๋”๋ผ๋„ ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ๋Š” ์Šค๋งˆํŠธ ์ •๊ทœ์‹/G2P์—์„œ ๋ณดํ˜ธ๋˜์–ด์•ผ ํ•จ
        masked, wl_map = _mask_whitelist(input_text, whitelist)
        final_text = _unmask_whitelist(apply_g2p(apply_smart_regex(masked), ai_mode), wl_map)
    else:
        final_text = convert_text(input_text, ai_mode, flat_dict, whitelist)

    if smart_pause:
        final_text = _join_breath_marks(final_text)
    if auto_break:
        final_text = final_text.replace(". ", ".\n\n").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 = 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;">{chunk}</span>')

    raw_html = re.sub(r'([^\s<]*@@[^\s<]*)', r'<span style="background-color: #ff4d4d; color: white;">\1</span>', "".join(html_parts))
    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 = list(dict.fromkeys([m.strip('.,!?\n') for m in markers if m.strip('.,!?\n')]))
    return final_text, html_output, char_count, " / ".join(unique_markers) if unique_markers else "ํ‘œ์‹œ๋œ ๋งˆ์ปค(@@)๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค."

def clear_all():
    return "", "", '<div id="prompter_output_div" style="font-size:22px;"></div>', "๊ณต๋ฐฑ ํฌํ•จ: 0์ž / ๊ณต๋ฐฑ ์ œ์™ธ: 0์ž", "ํ‘œ์‹œ๋œ ๋งˆ์ปค(@@)๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค."

def get_file():
    return dict_path if os.path.exists(dict_path) else None

def add_and_update(word, pronun, user_role, current_input, ai_mode, auto_break, smart_pause, font_size, user_temp_dict, user_temp_wl=None):
    if not word or not pronun:
        return "โš ๏ธ ๋‹จ์–ด์™€ ๋ฐœ์Œ์„ ์ž…๋ ฅํ•˜์„ธ์š”.", gr.update(), gr.update(), gr.update(), gr.update(), user_temp_dict
    word, pronun = word.strip(), pronun.strip()
    # [v150] 1๊ธ€์ž ํ‚ค ํ—ˆ์šฉ โ€” ๊ฒฝ๊ณ„๋Š” _build_pattern์—์„œ ์ฒ˜๋ฆฌ

    # [v158] ๋ฐœ์Œ ์˜คํƒ€ ๊ฐ์ง€ โ€” ๋ฌธ์ œ๊ฐ€ ์žˆ์œผ๋ฉด ์ €์žฅํ•˜์ง€ ์•Š๊ณ  ๋˜๋ฌผ์Œ
    typos = _detect_pronun_typo(word, pronun)
    if typos:
        status_msg = "๐Ÿ›‘ ๋“ฑ๋ก ๋ณด๋ฅ˜: " + " / ".join(typos) + " โ†’ ๋ฐœ์Œ์„ ํ™•์ธ ํ›„ ๋‹ค์‹œ ๋“ฑ๋กํ•˜์„ธ์š”."
        if current_input.strip():
            ft, ho, cc, mr = process_text(current_input, ai_mode, auto_break, smart_pause, font_size, user_temp_dict, user_temp_wl)
            return status_msg, ft, ho, cc, mr, user_temp_dict
        return status_msg, gr.update(), gr.update(), gr.update(), gr.update(), user_temp_dict

    if user_role == "admin":
        dict_map = _read_local_dict()
        # [v158-final] ๊ฒน์น˜๋Š” ๊ธฐ์กด ๊ทœ์น™์„ '๊ฐ์ง€๋งŒ' ํ•œ๋‹ค โ€” ์ ˆ๋Œ€ ์‚ญ์ œํ•˜์ง€ ์•Š์Œ.
        # ์—”์ง„์ด ๊ธด ํ‚ค ์šฐ์„  ๋งค์นญ์ด๋ผ ์šฐ์„ ์ˆœ์œ„๋Š” ๋ณด์žฅ๋˜๋ฉฐ, ๊ธฐ์กด ๋‹จ์–ด์žฅ์€ ์˜จ์ „ํžˆ ๋ณด์กด๋œ๋‹ค.
        overlapping = _find_overlapping_keys(dict_map, word)
        dict_map[word] = pronun
        sync_msg = save_dict(dict_map)
        if overlapping:
            new_len = len(re.sub(r'\s+', '', word))
            longer = [k for k in overlapping if len(re.sub(r'\s+', '', k)) > new_len]
            if longer:
                prune_note = f" ยท โš ๏ธ ๊ธฐ์กด ๊ธด ๊ทœ์น™ '{longer[0]}'๊ฐ€ ์ด ํ‚ค๋ณด๋‹ค ์šฐ์„  ์ ์šฉ๋  ์ˆ˜ ์žˆ์Œ (๊ฒน์น˜๋Š” ๊ตฌ๊ฐ„ ์ฃผ์˜)"
            else:
                prune_note = f" ยท ์œ ์‚ฌ ๊ธฐ์กด ๊ทœ์น™ {len(overlapping)}๊ฐœ ์กด์žฌ (์ƒˆ ๊ทœ์น™์ด ์šฐ์„  ์ ์šฉ๋จ)"
        else:
            prune_note = ""
        status_msg = f"๐Ÿ‘‘ [์–ด๋“œ๋ฏผ] '{word}' -> '{pronun}' ์ €์žฅ!{prune_note} ({sync_msg})"
    else:
        # [v158-final] ๊ฒŒ์ŠคํŠธ ์ž„์‹œ ์‚ฌ์ „๋„ ๋™์ผ โ€” ์‚ญ์ œ ์—†์ด ๊ฐ์ง€๋งŒ
        overlapping = [k for k in user_temp_dict.keys()
                       if k != word and len(re.sub(r'\s+', '', k)) >= 4
                       and (re.sub(r'\s+', '', k).startswith(re.sub(r'\s+', '', word))
                            or re.sub(r'\s+', '', word).startswith(re.sub(r'\s+', '', k)))]
        user_temp_dict[word] = pronun
        prune_note = f" ยท ์œ ์‚ฌ ๊ธฐ์กด ๊ทœ์น™ {len(overlapping)}๊ฐœ ์กด์žฌ (๊ธด ํ‚ค ์šฐ์„  ์ ์šฉ)" if overlapping else ""
        status_msg = f"๐Ÿ‘ค [๊ฒŒ์ŠคํŠธ] '{word}' -> '{pronun}' ์ž„์‹œ ์ €์žฅ ์™„๋ฃŒ!{prune_note} (์ƒˆ๋กœ๊ณ ์นจ ์‹œ ์ดˆ๊ธฐํ™” - ์˜๊ตฌ ๋“ฑ๋ก์€ ์–ด๋“œ๋ฏผ์—๊ฒŒ ์š”์ฒญ)"
    if current_input.strip():
        ft, ho, cc, mr = process_text(current_input, ai_mode, auto_break, smart_pause, font_size, user_temp_dict, user_temp_wl)
        return status_msg, ft, ho, cc, mr, user_temp_dict
    return status_msg, gr.update(), gr.update(), gr.update(), gr.update(), user_temp_dict

def load_current_json_to_text(user_temp_dict):
    try:
        return json.dumps({"items": load_dict(user_temp_dict)}, ensure_ascii=False, indent=4), "โœ… ์‚ฌ์ „์„ ๋ถˆ๋Ÿฌ์™”์Šต๋‹ˆ๋‹ค!"
    except Exception as e:
        return "", f"โŒ ์‹คํŒจ: {e}"

def _parse_items(json_string):
    new_data = json.loads(json_string)
    items = new_data.get("items", [])
    if isinstance(items, dict):
        return {k.strip(): str(v).strip() for k, v in items.items()}
    return {i[0].strip(): i[1].strip() for i in items if len(i) == 2}

def overwrite_json_text(json_string, user_role):
    if user_role != "admin":
        return "๐Ÿšซ [๊ถŒํ•œ ์—†์Œ] ์–ด๋“œ๋ฏผ๋งŒ ๋ฎ์–ด์“ฐ๊ธฐ๊ฐ€ ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค."
    if not json_string.strip():
        return "โš ๏ธ ๋‚ด์šฉ์„ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”."
    try:
        dict_map = _parse_items(json_string)
        sync_msg = save_dict(dict_map)
        return f"๐Ÿ‘‘ [์–ด๋“œ๋ฏผ] ์„œ๋ฒ„ ์‚ฌ์ „์„ ์™„์ „ํžˆ ๊ต์ฒดํ–ˆ์Šต๋‹ˆ๋‹ค! ({sync_msg})"
    except Exception as e:
        return f"โŒ ์—๋Ÿฌ: {e}"

def apply_json_text(json_string, user_role, user_temp_dict):
    if not json_string.strip():
        return "โš ๏ธ ๋‚ด์šฉ์„ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”.", user_temp_dict
    try:
        parsed_items = _parse_items(json_string)
        if user_role == "admin":
            dict_map = _read_local_dict()
            dict_map.update(parsed_items)
            sync_msg = save_dict(dict_map)
            return f"๐Ÿ‘‘ [์–ด๋“œ๋ฏผ] ์„œ๋ฒ„์— ์ถ”๊ฐ€ํ–ˆ์Šต๋‹ˆ๋‹ค! ({sync_msg})", user_temp_dict
        else:
            user_temp_dict.update(parsed_items)
            return "๐Ÿ‘ค [๊ฒŒ์ŠคํŠธ] ์ž„์‹œ ๋‹จ์–ด์žฅ์— ์ถ”๊ฐ€๋˜์—ˆ์Šต๋‹ˆ๋‹ค!", user_temp_dict
    except Exception as e:
        return f"โŒ ์—๋Ÿฌ: {e}", user_temp_dict

def update_dict_entry(old_word, new_pronun, user_role, current_input, ai_mode, auto_break, smart_pause, font_size, user_temp_dict, user_temp_wl=None):
    """๋‹จ์–ด์žฅ ํ•ญ๋ชฉ ์ˆ˜์ • โ€” key(๋‹จ์–ด) ์‹๋ณ„์ž๊ฐ€ ๊ทธ๋Œ€๋กœ์ธ ๋™์•ˆ value(๋ฐœ์Œ)๋งŒ ๊ต์ฒด."""
    if not old_word:
        return "โš ๏ธ ๋จผ์ € ๋‹จ์–ด๋ฅผ ์„ ํƒํ•˜์„ธ์š”.", gr.update(), gr.update(), gr.update(), gr.update(), update_choices(), user_temp_dict
    old_word = old_word.strip()
    new_pronun = (new_pronun or "").strip()
    if not new_pronun:
        return "โš ๏ธ ์ƒˆ ๋ฐœ์Œ์„ ์ž…๋ ฅํ•˜์„ธ์š”.", gr.update(), gr.update(), gr.update(), gr.update(), update_choices(), user_temp_dict

    if user_role == "admin":
        dict_map = _read_local_dict()
        if old_word not in dict_map:
            return f"๐Ÿšซ ๋‹จ์–ด์žฅ์— '{old_word}' ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.", gr.update(), gr.update(), gr.update(), gr.update(), update_choices(), user_temp_dict
        old_value = dict_map[old_word]
        dict_map[old_word] = new_pronun
        sync_msg = save_dict(dict_map)
        status_msg = f"๐Ÿ‘‘ [์ˆ˜์ •] '{old_word}' : '{old_value}' โžœ '{new_pronun}' ({sync_msg})"
    else:
        if old_word not in user_temp_dict:
            return f"๐Ÿšซ ์ž„์‹œ ๋‹จ์–ด์žฅ์— '{old_word}' ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.", gr.update(), gr.update(), gr.update(), gr.update(), update_choices(), user_temp_dict
        old_value = user_temp_dict[old_word]
        user_temp_dict[old_word] = new_pronun
        status_msg = f"๐Ÿ‘ค [๊ฒŒ์ŠคํŠธ ์ˆ˜์ •] '{old_word}' : '{old_value}' โžœ '{new_pronun}' (์ƒˆ๋กœ๊ณ ์นจ ์‹œ ์ดˆ๊ธฐํ™”)"
    if current_input.strip():
        ft, ho, cc, mr = process_text(current_input, ai_mode, auto_break, smart_pause, font_size, user_temp_dict, user_temp_wl)
        return status_msg, ft, ho, cc, mr, update_choices(), user_temp_dict
    return status_msg, gr.update(), gr.update(), gr.update(), gr.update(), update_choices(), user_temp_dict

def delete_dict_entry(old_word, user_role, current_input, ai_mode, auto_break, smart_pause, font_size, user_temp_dict, user_temp_wl=None):
    """๋‹จ์–ด์žฅ ํ•ญ๋ชฉ์—์„œ ํ•œ ์ค„๋งŒ ์‚ญ์ œ. ADMIN_IDยท์–ด๋“œ๋ฏผ์ด๋ฉด ์„œ๋ฒ„ ์ €์žฅ์†Œ, ๊ฒŒ์ŠคํŠธ๋ฉด ์ž„์‹œ ์‚ฌ์ „."""
    if not old_word:
        return "โš ๏ธ ๋จผ์ € ๋‹จ์–ด๋ฅผ ์„ ํƒํ•˜์„ธ์š”.", gr.update(), gr.update(), gr.update(), gr.update(), update_choices(), user_temp_dict
    old_word = old_word.strip()

    if user_role == "admin":
        dict_map = _read_local_dict()
        if old_word not in dict_map:
            return f"๐Ÿšซ ๋‹จ์–ด์žฅ์— '{old_word}' ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.", gr.update(), gr.update(), gr.update(), gr.update(), update_choices(), user_temp_dict
        old_value = dict_map.pop(old_word)
        sync_msg = save_dict(dict_map)
        status_msg = f"๐Ÿ—‘๏ธ [์‚ญ์ œ] '{old_word}' : '{old_value}' ({sync_msg})"
    else:
        if old_word not in user_temp_dict:
            return f"๐Ÿšซ ์ž„์‹œ ๋‹จ์–ด์žฅ์— '{old_word}' ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.", gr.update(), gr.update(), gr.update(), gr.update(), update_choices(), user_temp_dict
        old_value = user_temp_dict.pop(old_word)
        status_msg = f"๐Ÿ—‘๏ธ [๊ฒŒ์ŠคํŠธ ์‚ญ์ œ] '{old_word}' : '{old_value}' (์ƒˆ๋กœ๊ณ ์นจ ์‹œ ์ดˆ๊ธฐํ™”)"
    if current_input.strip():
        ft, ho, cc, mr = process_text(current_input, ai_mode, auto_break, smart_pause, font_size, user_temp_dict, user_temp_wl)
        return status_msg, ft, ho, cc, mr, update_choices(), user_temp_dict
    return status_msg, gr.update(), gr.update(), gr.update(), gr.update(), update_choices(), user_temp_dict

# ---------- [v153] ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ UI ํ•ธ๋“ค๋Ÿฌ ----------
def add_whitelist_entry(term, user_role, current_input, ai_mode, auto_break, smart_pause, font_size, user_temp_dict, user_temp_wl):
    term = (term or "").strip()
    if not term:
        return "โš ๏ธ ์˜ˆ์™ธ ๋‹จ์–ด๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”.", gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), user_temp_wl
    if user_role == "admin":
        wl = _read_local_whitelist()
        if term in wl:
            status_msg = f"โ„น๏ธ ์ด๋ฏธ ์˜ˆ์™ธ ๋ชฉ๋ก์— ์žˆ์Œ: '{term}'"
        else:
            wl.append(term)
            msg, _ = save_whitelist(wl)
            status_msg = f"๐Ÿ‘‘ [์–ด๋“œ๋ฏผ] ์˜ˆ์™ธ ๋‹จ์–ด ์ถ”๊ฐ€: '{term}' ({msg})"
    else:
        if term in user_temp_wl:
            status_msg = f"โ„น๏ธ ์ด๋ฏธ ์ž„์‹œ ์˜ˆ์™ธ ๋ชฉ๋ก์— ์žˆ์Œ: '{term}'"
        else:
            user_temp_wl.append(term)
            status_msg = f"๐Ÿ‘ค [๊ฒŒ์ŠคํŠธ] ์ž„์‹œ ์˜ˆ์™ธ ์ถ”๊ฐ€: '{term}' (์ƒˆ๋กœ๊ณ ์นจ ์‹œ ์ดˆ๊ธฐํ™”)"
    dd_update = gr.update(choices=list(_read_local_whitelist()))
    if current_input.strip():
        ft, ho, cc, mr = process_text(current_input, ai_mode, auto_break, smart_pause, font_size, user_temp_dict, user_temp_wl)
        return status_msg, ft, ho, cc, mr, dd_update, user_temp_wl
    return status_msg, gr.update(), gr.update(), gr.update(), gr.update(), dd_update, user_temp_wl

def delete_whitelist_entry(term, user_role, current_input, ai_mode, auto_break, smart_pause, font_size, user_temp_dict, user_temp_wl):
    term = (term or "").strip()
    if not term:
        return "โš ๏ธ ์‚ญ์ œํ•  ์˜ˆ์™ธ ๋‹จ์–ด๋ฅผ ์„ ํƒํ•˜์„ธ์š”.", gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), user_temp_wl
    if user_role == "admin":
        wl = _read_local_whitelist()
        if term not in wl:
            return f"๐Ÿšซ ์˜ˆ์™ธ ๋ชฉ๋ก์— '{term}' ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.", gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), user_temp_wl
        wl = [x for x in wl if x != term]
        msg, _ = save_whitelist(wl)
        status_msg = f"๐Ÿ—‘๏ธ [์˜ˆ์™ธ ์‚ญ์ œ] '{term}' ({msg})"
    else:
        if term not in user_temp_wl:
            return f"๐Ÿšซ ์ž„์‹œ ์˜ˆ์™ธ ๋ชฉ๋ก์— '{term}' ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.", gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), user_temp_wl
        user_temp_wl = [x for x in user_temp_wl if x != term]
        status_msg = f"๐Ÿ—‘๏ธ [๊ฒŒ์ŠคํŠธ ์˜ˆ์™ธ ์‚ญ์ œ] '{term}' (์ƒˆ๋กœ๊ณ ์นจ ์‹œ ์ดˆ๊ธฐํ™”)"
    dd_update = gr.update(choices=list(_read_local_whitelist()), value=None)
    if current_input.strip():
        ft, ho, cc, mr = process_text(current_input, ai_mode, auto_break, smart_pause, font_size, user_temp_dict, user_temp_wl)
        return status_msg, ft, ho, cc, mr, dd_update, user_temp_wl
    return status_msg, gr.update(), gr.update(), gr.update(), gr.update(), dd_update, user_temp_wl

def refresh_whitelist_choices():
    return gr.update(choices=list(_read_local_whitelist()))

def update_choices():
    """๋“œ๋กญ๋‹ค์šด์— ํ˜„์žฌ ์„œ๋ฒ„ ์‚ฌ์ „์˜ ํ‚ค๋“ค์„ ์•ŒํŒŒ๋ฒณ์ˆœ์œผ๋กœ ๋…ธ์ถœ."""
    d = _read_local_dict()
    return gr.update(choices=sorted(d.keys()))

def upload_file(file_path, user_role, user_temp_dict):
    if file_path is None:
        return "โš ๏ธ ํŒŒ์ผ์ด ์—†์Šต๋‹ˆ๋‹ค.", user_temp_dict
    try:
        with open(file_path, "r", encoding="utf-8") as f:
            uploaded_data = json.load(f)
        parsed_items = {item[0].strip(): item[1].strip() for item in uploaded_data.get("items", []) if len(item) == 2}
        if user_role == "admin":
            dict_map = _read_local_dict()
            dict_map.update(parsed_items)
            sync_msg = save_dict(dict_map)
            return f"๐Ÿ‘‘ [์–ด๋“œ๋ฏผ] ํŒŒ์ผ ๋ฐ์ดํ„ฐ๋ฅผ ์„œ๋ฒ„์— ๋ณ‘ํ•ฉํ–ˆ์Šต๋‹ˆ๋‹ค! ({sync_msg})", user_temp_dict
        else:
            user_temp_dict.update(parsed_items)
            return "๐Ÿ‘ค [๊ฒŒ์ŠคํŠธ] ๋‚ด ์ž„์‹œ ๋‹จ์–ด์žฅ์— ๋ณ‘ํ•ฉ๋˜์—ˆ์Šต๋‹ˆ๋‹ค!", user_temp_dict
    except Exception as e:
        return f"โŒ ์—๋Ÿฌ: {e}", user_temp_dict

def verify_login(uid, upw):
    if uid == ADMIN_ID and upw == ADMIN_PW:
        return gr.update(visible=False), gr.update(visible=True), "admin", "โœ… ๋กœ๊ทธ์ธ ์„ฑ๊ณต (์–ด๋“œ๋ฏผ ๋ชจ๋“œ)", ""
    elif uid == GUEST_ID and upw == GUEST_PW:
        return gr.update(visible=False), gr.update(visible=True), "guest", "โœ… ๋กœ๊ทธ์ธ ์„ฑ๊ณต (๊ฒŒ์ŠคํŠธ ๋ชจ๋“œ)", ""
    else:
        return gr.update(visible=True), gr.update(visible=False), "none", "โŒ ์•„์ด๋”” ๋˜๋Š” ๋น„๋ฐ€๋ฒˆํ˜ธ๊ฐ€ ํ‹€๋ ธ์Šต๋‹ˆ๋‹ค.", ""

def perform_logout():
    return gr.update(visible=True), gr.update(visible=False), "none", "", "", "", {}, []

def handle_page_load(current_role):
    if current_role in ["admin", "guest"]:
        return gr.update(visible=False), gr.update(visible=True), current_role, "", gr.update(), gr.update()
    return gr.update(visible=True), gr.update(visible=False), "none", "", "", ""

# ---------- UI ๋นŒ๋“œ ----------
custom_css = """
#prompter_html_wrap, #prompter_html_wrap .prose { width: 100% !important; text-align: left !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;
}
#prompter_output_div { background-color: #333 !important; color: #fff !important; border-radius: 8px !important; white-space: pre-wrap !important; }
.login-box { max-width: 400px; margin: 100px auto; padding: 30px; border: 1px solid #ddd; border-radius: 10px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
.header-row { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; }
/* ๋ฒ„ํŠผ ํ–‰ 4๊ฐœ ๋™์ผ ํญ (Gradio use_container_width ๋Œ€์‘ CSS ๋ณด๊ฐ•) */
.convert-row { gap: 8px !important; }
.convert-row > button { flex: 1 1 0 !important; min-width: 0 !important; }
"""
script_js = """
function() {
    setTimeout(function() {
        let ta1 = document.querySelector('#input_text_area textarea');
        if(ta1) { ta1.style.fontSize = '22px'; }
        let ta2 = document.querySelector('#output_text_area textarea');
        if(ta2) { ta2.style.fontSize = '22px'; ta2.style.lineHeight = '1.8'; }
    }, 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 = "(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; }"

_mode_choices = ["๋„๊ธฐ (์ˆ˜๋™ ์‚ฌ์ „๋งŒ ์ ์šฉ)", "์ค‘๊ฐ„ ๋ง› (๋ช…์‚ฌ/๊ณ ์œ ์–ด๋งŒ - ์ถ”์ฒœ โญ)",
                 "์ˆœํ•œ ๋ง› (๋‹จ์–ด๋ณ„ ๋Š๊ธฐ)", "๋งค์šด ๋ง› (์ž์—ฐ ์—ฐ์Œ)"]

_GRADIO_MAJOR = int(gr.__version__.split(".")[0])
_BLOCKS_KW = {"theme": "default", "css": custom_css} if _GRADIO_MAJOR < 6 else {}
_LAUNCH_KW = {"theme": "default", "css": custom_css} if _GRADIO_MAJOR >= 6 else {}

with gr.Blocks(**_BLOCKS_KW) as iface:
    user_role = gr.State("none")
    user_temp_dict = gr.State(lambda: {})
    user_temp_wl = gr.State(lambda: [])   # [v153] ๊ฒŒ์ŠคํŠธ ์ž„์‹œ ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ
    with gr.Column(visible=True, elem_classes="login-box") as login_screen:
        gr.Markdown("### ๐Ÿ” ์‹œ์Šคํ…œ ๋กœ๊ทธ์ธ")
        login_id = gr.Textbox(label="์•„์ด๋””")
        login_pw = gr.Textbox(label="๋น„๋ฐ€๋ฒˆํ˜ธ", type="password")
        login_btn = gr.Button("๋กœ๊ทธ์ธ", variant="primary")
        login_msg = gr.Markdown("")
    with gr.Column(visible=False) as main_app:
        with gr.Row(elem_classes="header-row"):
            gr.Markdown("## ๐ŸŽ™๏ธ AI ์Šคํฌ๋ฆฝํ„ฐ ๋ณ€ํ™˜๊ธฐ")
            btn_logout = gr.Button("๐Ÿšช ๋กœ๊ทธ์•„์›ƒ", variant="secondary", size="sm", scale=0, min_width=100)

        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():
                            ai_mode = gr.Radio(choices=_mode_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์ž", interactive=False)

                        # === ๋ณ€ํ™˜ ๋ฒ„ํŠผ ํ–‰ (๋™์ผ scaleยทsize, ์ดˆ๊ธฐํ™”๋Š” ๋งˆ์ง€๋ง‰ ์ž๋ฆฌ) ===
                        with gr.Row(elem_classes="convert-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(value='<div id="prompter_label_space">๐Ÿ“บ ํ”„๋กฌํ”„ํ„ฐ ๋ทฐ</div><div id="prompter_output_div" style="font-size:22px;"></div>', elem_id="prompter_html_wrap")
                        with gr.Accordion("๐Ÿ“‚ ํ…์ŠคํŠธ ๊ฒฐ๊ณผ (ํด๋ฆญํ•˜์—ฌ ํŽผ์น˜๊ธฐ)", open=False):
                            output_text = gr.Textbox(lines=8, show_label=False, elem_id="output_text_area")
                        marker_collection = gr.Textbox(label="๐Ÿšจ ์ˆ˜์ • ํ•„์š” ๋‹จ์–ด (@@)", interactive=False, lines=2)


                gr.Markdown("---")
                gr.Markdown("**๐Ÿ’ก ๋‚˜๋งŒ์˜ ๋ฐœ์Œ ์‚ฌ์ „ ์ถ”๊ฐ€** โ€” ๋‹จ์–ด์žฅ์ด ๊ฐ€์žฅ ํšจ๊ณผ์ ์ธ ๋ฐœ์Œ ๊ต์ • ์ˆ˜๋‹จ์ž…๋‹ˆ๋‹ค.")
                with gr.Row():
                    nw = gr.Textbox(label="๋‹จ์–ด")
                    np = gr.Textbox(label="์›ํ•˜๋Š” ๋ฐœ์Œ")
                    with gr.Column():
                        btn_add = gr.Button("๐Ÿ’พ ์ ์šฉ ๋ฐ ๋ณ€ํ™˜", variant="primary")
                        btn_clear_dict_inputs = gr.Button("๐Ÿงน ์ž…๋ ฅ์นธ ๋น„์šฐ๊ธฐ", variant="secondary")
                status = gr.Textbox(label="์ €์žฅ ์ƒํƒœ", interactive=False)

                # [v151] ๋“ฑ๋ก๋œ ๋‹จ์–ด ์ค‘ ์ž˜๋ชป ๋“ฑ๋กํ•œ ๊ฒƒ์„ ๊ณจ๋ผ ์ˆ˜์ •/์‚ญ์ œ
                with gr.Accordion("โœ‚๏ธ ๋‹จ์–ด์žฅ ํ•ญ๋ชฉ ์ˆ˜์ •/์‚ญ์ œ (v151)", open=False):
                    gr.Markdown("๋‹จ์–ด ์„ ํƒ ์‹œ ํ˜„์žฌ ๋ฐœ์Œ์ด ์ž๋™์œผ๋กœ ์ฑ„์›Œ์ง‘๋‹ˆ๋‹ค. ์ƒˆ ๋ฐœ์Œ์„ ์ž…๋ ฅํ•˜๊ณ  [โœ๏ธ ๋ฐœ์Œ ์ˆ˜์ •], ์™„์ „ํžˆ ์ง€์šธ ๋•Œ๋Š” [๐Ÿ—‘๏ธ ์‚ญ์ œ]๋ฅผ ๋ˆ„๋ฅด์„ธ์š”.")
                    with gr.Row():
                        dict_keys_dd = gr.Dropdown(choices=[], label="๋“ฑ๋ก๋œ ๋‹จ์–ด ์„ ํƒ", interactive=True)
                        edit_pron = gr.Textbox(label="์ƒˆ ๋ฐœ์Œ (์ˆ˜์ • ์‹œ)")
                    with gr.Row():
                        btn_update_entry = gr.Button("โœ๏ธ ๋ฐœ์Œ ์ˆ˜์ •", variant="primary")
                        btn_delete_entry = gr.Button("๐Ÿ—‘๏ธ ์„ ํƒ ๋‹จ์–ด ์‚ญ์ œ", variant="stop")
                        btn_refresh_choices = gr.Button("๐Ÿ”„ ๋ชฉ๋ก ์ƒˆ๋กœ๊ณ ์นจ", variant="secondary")

                # [v153] ์˜ˆ์™ธ ๋‹จ์–ด(ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ) โ€” ์‚ฌ์ „ ์น˜ํ™˜์—์„œ ์ œ์™ธํ•  ์–ด์ ˆ/ํ•ฉ์„ฑ์–ด
                with gr.Accordion("๐Ÿ›ก๏ธ ์˜ˆ์™ธ ๋‹จ์–ด(ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ) (v153)", open=False):
                    gr.Markdown(
                        "**๋‹จ์–ด์žฅ ์น˜ํ™˜์—์„œ ์™„์ „ํžˆ ์ œ์™ธํ•  ๋‹จ์–ด**๋ฅผ ๋“ฑ๋กํ•ฉ๋‹ˆ๋‹ค. "
                        "์˜ˆ: `์—์Šค์ปฌ๋ ˆ์ดํ„ฐ`, `์—์Šคํ”„๋ ˆ์†Œ`, `ํด๋ฆฌ์—์Šคํ„ฐ` ์ฒ˜๋Ÿผ ์‚ฌ์ „์— `์—์Šคโ†’์Šค๋ชฐ`์ด ์žˆ์–ด๋„ "
                        "์ด ๋‹จ์–ด๋“ค์€ ์›๋ฌธ ๊ทธ๋Œ€๋กœ ์œ ์ง€๋ฉ๋‹ˆ๋‹ค. **์ •ํ™•ํžˆ ์ผ์น˜ํ•˜๋Š” ๋ฌธ์ž์—ด**๋กœ ๋“ฑ๋กํ•˜์„ธ์š” "
                        "(๋ฌธ์ž์—ด ๋ถ€๋ถ„์ผ์น˜ ๋ฐฉ์‹์ด๋ผ `์—์Šค์ปฌ๋ ˆ์ดํ„ฐ`๋กœ ๋“ฑ๋กํ•˜๋ฉด `์—์Šค์ปฌ๋ ˆ์ดํ„ฐ๋Š”/์—์Šค์ปฌ๋ ˆ์ดํ„ฐ๋ฅผ`๋„ ํ•จ๊ป˜ ๋ณดํ˜ธ๋ฉ๋‹ˆ๋‹ค)."
                    )
                    with gr.Row():
                        wl_input = gr.Textbox(label="์˜ˆ์™ธ๋กœ ์ง€์ •ํ•  ๋‹จ์–ด(์–ด์ ˆ)", placeholder="์˜ˆ: ์—์Šค์ปฌ๋ ˆ์ดํ„ฐ")
                        wl_keys_dd = gr.Dropdown(choices=[], label="๋“ฑ๋ก๋œ ์˜ˆ์™ธ ๋‹จ์–ด ์„ ํƒ", interactive=True)
                    with gr.Row():
                        btn_add_wl = gr.Button("โž• ์˜ˆ์™ธ ์ถ”๊ฐ€", variant="primary")
                        btn_del_wl = gr.Button("๐Ÿ—‘๏ธ ์„ ํƒ ์˜ˆ์™ธ ์‚ญ์ œ", variant="stop")
                        btn_refresh_wl = gr.Button("๐Ÿ”„ ์˜ˆ์™ธ ๋ชฉ๋ก ์ƒˆ๋กœ๊ณ ์นจ", variant="secondary")

                proc_inputs = [input_text, ai_mode, auto_break, smart_pause, font_size, user_temp_dict, user_temp_wl]
                proc_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=proc_inputs, outputs=proc_outputs, api_name=False)
                btn_conv.click(fn=process_text, inputs=proc_inputs, outputs=proc_outputs, 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="(t) => { if(t) { navigator.clipboard.writeText(t); alert('โœ… ๋ณต์‚ฌ ์™„๋ฃŒ!'); } }", api_name=False)

                btn_add.click(fn=add_and_update,
                               inputs=[nw, np, user_role, input_text, ai_mode, auto_break, smart_pause, font_size, user_temp_dict, user_temp_wl],
                               outputs=[status, output_text, output_html, char_count, marker_collection, user_temp_dict], api_name=False)
                btn_add.click(fn=lambda: gr.update(choices=sorted(_read_local_dict().keys())), outputs=[dict_keys_dd], api_name=False)
                btn_clear_dict_inputs.click(fn=lambda: ("", ""), outputs=[nw, np], api_name=False)

                # [v151] ์ˆ˜์ •/์‚ญ์ œ ํ•ธ๋“ค๋Ÿฌ โ€” ์„ ํƒ ๋ณ€๊ฒฝ ์‹œ ๊ธฐ์กด ๋ฐœ์Œ์„ ํ”„๋ฆฌํ•„
                dict_keys_dd.change(
                    fn=lambda key: _read_local_dict().get(key, "") if key else "",
                    inputs=[dict_keys_dd], outputs=[edit_pron], api_name=False,
                )
                btn_update_entry.click(
                    fn=update_dict_entry,
                    inputs=[dict_keys_dd, edit_pron, user_role, input_text, ai_mode, auto_break, smart_pause, font_size, user_temp_dict, user_temp_wl],
                    outputs=[status, output_text, output_html, char_count, marker_collection, dict_keys_dd, user_temp_dict], api_name=False,
                )
                btn_delete_entry.click(
                    fn=delete_dict_entry,
                    inputs=[dict_keys_dd, user_role, input_text, ai_mode, auto_break, smart_pause, font_size, user_temp_dict, user_temp_wl],
                    outputs=[status, output_text, output_html, char_count, marker_collection, dict_keys_dd, user_temp_dict], api_name=False,
                )
                btn_refresh_choices.click(
                    fn=update_choices, outputs=[dict_keys_dd], api_name=False,
                )
                iface.load(fn=update_choices, outputs=[dict_keys_dd], api_name=False)

                # [v153] ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ ํ•ธ๋“ค๋Ÿฌ ๋ฐ”์ธ๋”ฉ
                btn_add_wl.click(
                    fn=add_whitelist_entry,
                    inputs=[wl_input, user_role, input_text, ai_mode, auto_break, smart_pause, font_size, user_temp_dict, user_temp_wl],
                    outputs=[status, output_text, output_html, char_count, marker_collection, wl_keys_dd, user_temp_wl],
                    api_name=False,
                )
                btn_add_wl.click(fn=lambda: "", outputs=[wl_input], api_name=False)  # ์ž…๋ ฅ์นธ ๋น„์šฐ๊ธฐ
                btn_del_wl.click(
                    fn=delete_whitelist_entry,
                    inputs=[wl_keys_dd, user_role, input_text, ai_mode, auto_break, smart_pause, font_size, user_temp_dict, user_temp_wl],
                    outputs=[status, output_text, output_html, char_count, marker_collection, wl_keys_dd, user_temp_wl],
                    api_name=False,
                )
                btn_refresh_wl.click(fn=refresh_whitelist_choices, outputs=[wl_keys_dd], api_name=False)
                iface.load(fn=refresh_whitelist_choices, outputs=[wl_keys_dd], api_name=False)
                for evt in [font_size.change, ai_mode.change, auto_break.change, smart_pause.change]:
                    evt(fn=process_text, inputs=proc_inputs, outputs=proc_outputs, api_name=False)
            with gr.Tab("๐Ÿ“ฅ ์ˆ˜๋™ ๋ฐฑ์—…/์กฐํšŒ/์ˆ˜์ •"):
                dl_btn = gr.DownloadButton("๐Ÿ“ฅ 1. ์‚ฌ์ „ ๋ฐฑ์—… (PC ๋‹ค์šด๋กœ๋“œ)")
                dl_btn.click(fn=get_file, outputs=[dl_btn], api_name=False)
                gr.Markdown("---")
                btn_load_json = gr.Button("๐Ÿ‘€ 2. ๋“ฑ๋ก๋œ ๋‹จ์–ด์žฅ ๋ถˆ๋Ÿฌ์˜ค๊ธฐ", variant="secondary")
                json_input = gr.Textbox(lines=10, label="ํŽธ์ง‘์ฐฝ")
                with gr.Row():
                    btn_apply_json = gr.Button("๐Ÿš€ ํ”Œ๋Ÿฌ์Šค(+) ํ•˜๊ธฐ", variant="primary")
                    btn_overwrite_json = gr.Button("๐Ÿšจ ์™„์ „ํžˆ ๋ฎ์–ด์“ฐ๊ธฐ (์–ด๋“œ๋ฏผ ์ „์šฉ)", variant="stop")
                json_stat = gr.Textbox(label="์ƒํƒœ ๊ฒฐ๊ณผ์ฐฝ", interactive=False)
                btn_load_json.click(fn=load_current_json_to_text, inputs=[user_temp_dict], outputs=[json_input, json_stat], api_name=False)
                btn_apply_json.click(fn=apply_json_text, inputs=[json_input, user_role, user_temp_dict], outputs=[json_stat, user_temp_dict], api_name=False)
                btn_overwrite_json.click(fn=overwrite_json_text, inputs=[json_input, user_role], outputs=[json_stat], api_name=False)
                gr.Markdown("---")
                with gr.Accordion("๐Ÿ“ค 3. ๋ฐฑ์—… ํŒŒ์ผ๋กœ ์‚ฌ์ „์— ๋ณ‘ํ•ฉํ•˜๊ธฐ", open=False):
                    up_file = gr.File(label="๋ฐฑ์—… ํŒŒ์ผ ์—…๋กœ๋“œ", type="filepath")
                    up_stat = gr.Textbox(label="์ƒํƒœ ๊ฒฐ๊ณผ์ฐฝ", interactive=False)
                    up_file.upload(fn=upload_file, inputs=[up_file, user_role, user_temp_dict], outputs=[up_stat, user_temp_dict], api_name=False)
    login_btn.click(fn=verify_login, inputs=[login_id, login_pw], outputs=[login_screen, main_app, user_role, login_msg, login_pw], api_name=False)
    btn_logout.click(fn=perform_logout, inputs=[], outputs=[login_screen, main_app, user_role, login_msg, login_id, login_pw, user_temp_dict, user_temp_wl], api_name=False)
    iface.load(fn=handle_page_load, inputs=[user_role], outputs=[login_screen, main_app, user_role, login_msg, login_id, login_pw], js=script_js)

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