File size: 30,207 Bytes
9c84f9d
 
3dfc93b
9c84f9d
 
 
 
 
 
 
 
 
 
 
 
 
3dfc93b
9c84f9d
 
 
 
 
 
 
3dfc93b
9c84f9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3dfc93b
9c84f9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3dfc93b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c84f9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3dfc93b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c84f9d
3dfc93b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c84f9d
 
 
 
 
 
 
 
 
 
3dfc93b
 
9c84f9d
3dfc93b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c84f9d
3dfc93b
 
 
 
 
 
9c84f9d
 
3dfc93b
9c84f9d
 
3dfc93b
9c84f9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""multi_step ํŒŒ์ดํ”„๋ผ์ธ์˜ rule ์Šคํ… ๊ตฌํ˜„์ฒด.

`multi_step.py` ๊ฐ€ 518์ค„์ด๋ผ (`.agents/rules/code-style.md` ์˜ 400์ค„ ๊ถŒ์žฅ์„ ์„
๋„˜์–ด) ๋ฃฐ ๊ตฌํ˜„๋งŒ ๋”ฐ๋กœ ๋ฝ‘์•„๋ƒˆ๋‹ค. vocabulary/post_process/correction_filter ๋Š”
๋™์ž‘์„ ๋ฐ”๊พธ์ง€ ์•Š๊ณ  `MultiStepPipeline._apply_*` ๋ฉ”์„œ๋“œ์—์„œ ๊ทธ๋Œ€๋กœ ์˜ฎ๊ฒจ์˜จ
๊ฒƒ์ด๋‹ค โ€” ์ˆœ์ˆ˜ ํ…์ŠคํŠธ ๋ณ€ํ™˜ ๋กœ์ง์ด๋ผ `self` ์ƒํƒœ๊ฐ€ ํ•„์š” ์—†๋‹ค(`apply_vocabulary`
๋งŒ ์˜ˆ์™ธ โ€” ๋ฐ์ดํ„ฐ์…‹์—์„œ ๋กœ๋“œํ•œ ์–ดํœ˜ ์บ์‹œ๋ฅผ ์ธ์ž๋กœ ๋ฐ›๊ณ  ๊ฐฑ์‹ ๋œ ์บ์‹œ๋ฅผ ๋˜๋Œ๋ ค์ค€๋‹ค).

`apply_judge_decisions`/`apply_change_rate_guard` ๋Š” v24 ๊ณ„์—ด ํฌํŒ… ๋‹จ๊ณ„(ยง5-F)์—์„œ
์ถ”๊ฐ€๋๋‹ค. ์ „์ž๋Š” `EvalSample.artifacts` ๋ฅผ ์ฝ์–ด์•ผ ํ•ด์„œ(judge ์Šคํ…์˜ ๊ตฌ์กฐํ™” ๊ฒฐ์ •,
self-consistency ์˜ corrections ๋ชฉ๋ก) `sample` ์„ ์ธ์ž๋กœ ๋ฐ›๋Š”๋‹ค โ€” ๋‹ค๋ฅธ rule
ํ•จ์ˆ˜๋“ค๊ณผ ์‹œ๊ทธ๋‹ˆ์ฒ˜๊ฐ€ ๋‹ค๋ฅธ ์œ ์ผํ•œ ์ด์œ ๋‹ค.
"""

from __future__ import annotations

import difflib
import logging
import re
from pathlib import Path
from typing import TYPE_CHECKING, Any

from solar_eval.models.sample import EvalSample
from solar_eval.pipelines.errors import KnowledgeAssetError
from solar_eval.pipelines.pipeline import ResourceRef, relative_posix

if TYPE_CHECKING:
    from solar_eval.core.dataset_loader import DatasetLoader

logger = logging.getLogger(__name__)


def apply_vocabulary(
    text: str,
    config: dict[str, Any],
    vocabulary: list[dict[str, str]] | None,
    dataset_loader: DatasetLoader | None,
    config_dir: Path | None = None,
) -> tuple[str, list[dict[str, str]] | None]:
    """`vocabulary_sub`/`vocabulary_reapply` rule_type ๊ตฌํ˜„.

    ํ˜ธ์ถœ์ž(`VocabularyStep`)๊ฐ€ run ์ˆ˜๋ช… ์บ์‹œ๋ฅผ ๋“ค๊ณ  ์žˆ์œผ๋ฏ€๋กœ, ์ตœ์ดˆ ํ˜ธ์ถœ ์‹œ ๋กœ๋“œํ•œ
    ์–ดํœ˜ ๋ชฉ๋ก์„ ๋ฐ˜ํ™˜๊ฐ’์œผ๋กœ ๋˜๋Œ๋ ค์ค˜ ์บ์‹œ๋กœ ์ €์žฅํ•˜๊ฒŒ ํ•œ๋‹ค.

    Args:
        config_dir: ๋ ˆํฌ์˜ config ์ •๋ณธ ๋””๋ ‰ํ† ๋ฆฌ(`03-evaluation`). ์น˜ํ™˜ ์‚ฌ์ „์€
            ๋ฐ์ดํ„ฐ๊ฐ€ ์•„๋‹ˆ๋ผ **์„ค์ •**์ด๋ผ(๋ฐ”๋€Œ๋ฉด ๊ฐ™์€ ๋ฌธ์ œ๋ฅผ ๋‹ค๋ฅด๊ฒŒ ํ‘ผ๋‹ค) ์—ฌ๊ธฐ๋ฅผ
            ๋จผ์ € ์ฐพ๋Š”๋‹ค. ๋ฐ์ดํ„ฐ ๋ฃจํŠธ ๊ธฐ์ค€ ๋ ˆ๊ฑฐ์‹œ ์„ ์–ธ๋„ ๊ณ„์† ์ง€์›ํ•œ๋‹ค.

    Returns:
        (์น˜ํ™˜๋œ text, ๊ฐฑ์‹ ๋œ vocabulary ์บ์‹œ) ํŠœํ”Œ.

    Raises:
        KnowledgeAssetError: `vocab_dataset` ์„ ์„ ์–ธํ–ˆ๋Š”๋ฐ ๋ชป ์ฝ์„ ๋•Œ.
    """
    if vocabulary is None:
        vocabulary = _load_vocabulary(config, dataset_loader, config_dir)

    for row in vocabulary:
        wrong = row.get("wrong", row.get("before", ""))
        correct = row.get("correct", row.get("after", ""))
        if wrong and correct:
            text = text.replace(wrong, correct)

    return text, vocabulary


def _load_vocabulary(
    config: dict[str, Any],
    dataset_loader: DatasetLoader | None,
    config_dir: Path | None,
) -> list[dict[str, str]]:
    """์น˜ํ™˜ ์‚ฌ์ „์„ ๋กœ๋“œํ•œ๋‹ค โ€” config ์ •๋ณธ ์šฐ์„ , ๋ฐ์ดํ„ฐ ๋ฃจํŠธ ํด๋ฐฑ.

    ์„ ์–ธ์ด ์—†์œผ๋ฉด ๋นˆ ๋ชฉ๋ก(์ •์ƒ์ ์ธ no-op)์ด๊ณ , ์„ ์–ธํ–ˆ๋Š”๋ฐ ๋ชป ์ฝ์œผ๋ฉด ์˜ˆ์™ธ๋‹ค.
    """
    vocab_path = config.get("vocab_dataset", "")
    if not vocab_path:
        return []

    searched: list[str] = []

    # 1. config ์ •๋ณธ (๋ ˆํฌ์˜ 03-evaluation/) โ€” ์น˜ํ™˜ ์‚ฌ์ „์€ ์„ค์ •์ด๋‹ค.
    if config_dir is not None:
        candidate = _config_candidate(config_dir, vocab_path)
        searched.append(str(candidate))
        if candidate.is_file() and dataset_loader is not None:
            return dataset_loader.load_csv(str(config_dir), vocab_path, source="local")

    # 2. ๋ ˆ๊ฑฐ์‹œ ์„ ์–ธ (repo/source ๋กœ ๋ฐ์ดํ„ฐ ๋ฃจํŠธ๋‚˜ HF ๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋Š” ๊ฒฝ์šฐ)
    repo = config.get("repo", "")
    source = config.get("source", "huggingface")
    if dataset_loader is not None:
        searched.append(f"{source}:{repo}/{vocab_path}" if repo else f"{source}:{vocab_path}")
        try:
            return dataset_loader.load_csv(repo, vocab_path, source=source)
        except Exception as e:  # noqa: BLE001 โ€” ์›์ธ์„ KnowledgeAssetError ์— ์‹ค์–ด ๋‹ค์‹œ ๋˜์ง„๋‹ค
            logger.debug("vocabulary load failed (%s): %s", vocab_path, e)
    else:
        searched.append("(dataset_loader ์—†์Œ)")

    raise KnowledgeAssetError(vocab_path, searched)


def _config_candidate(config_dir: Path | str, rel: str) -> Path:
    """config ์ •๋ณธ ๊ธฐ์ค€ ์ž์‚ฐ ๊ฒฝ๋กœ โ€” ๋กœ๋”(`_load_vocabulary`)์™€ ์Šค๋ƒ…์ƒท ํ•ด์„์ด ๊ณต์œ ํ•œ๋‹ค.

    config ์ž์‚ฐ์€ config_dir **์•ˆ**์— ์žˆ์–ด์•ผ ํ•œ๋‹ค: `../` ๋‚˜ ๋ฐ–์„ ๊ฐ€๋ฆฌํ‚ค๋Š” ์‹ฌ๋ณผ๋ฆญ ๋งํฌ๋กœ ํ’€๋ฆฌ๋Š”
    ํŒŒ์ผ์€ ์ปค๋ฐ‹์œผ๋กœ ๋ณต์›๋˜์ง€ ์•Š๊ณ (dirty ๋ฒ”์œ„ ๋ฐ–), ์Šค๋ƒ…์ƒท ๋ผ๋ฒจ์ด ๊ธฐ๊ณ„๋งˆ๋‹ค ๋‹ค๋ฅธ ์ ˆ๋Œ€๊ฒฝ๋กœ๊ฐ€ ๋œ๋‹ค.
    ๊ทธ๋Ÿฐ ํŒŒ์ผ์ด ์‹ค์ œ๋กœ ์žˆ์œผ๋ฉด ์“ฐ์ง€ ์•Š๊ณ  `KnowledgeAssetError` ๋กœ ๊ฑฐ๋ถ€ํ•œ๋‹ค(๋กœ๋”ยท์Šค๋ƒ…์ƒท ๊ณตํ†ต).
    ์—†์œผ๋ฉด ๊ฒฝ๋กœ๋งŒ ๋Œ๋ ค์ค€๋‹ค โ€” ํ˜ธ์ถœ์ž๊ฐ€ ๋ ˆ๊ฑฐ์‹œ ์„ ์–ธ์œผ๋กœ ๋„˜์–ด๊ฐ€๊ฑฐ๋‚˜ ๊ฐ™์€ ์˜ค๋ฅ˜๋ฅผ ๋‚ธ๋‹ค.

    Raises:
        KnowledgeAssetError: ํ›„๋ณด ํŒŒ์ผ์ด ์žˆ๋Š”๋ฐ ์‹ค์ œ ์œ„์น˜๊ฐ€ config_dir ๋ฐ–์ผ ๋•Œ.
    """
    candidate = Path(config_dir) / rel
    if candidate.is_file():
        resolved = candidate.resolve()
        root = Path(config_dir).resolve()
        if not resolved.is_relative_to(root):
            raise KnowledgeAssetError(
                rel, [f"{candidate} โ†’ {resolved} (config_dir {root} ๋ฐ– โ€” config ์ž์‚ฐ์€ ๊ทธ ์•ˆ์—)"]
            )
    return candidate


def resolve_vocabulary_path(
    config: dict[str, Any],
    dataset_loader: DatasetLoader | None,
    config_dir: Path | None,
) -> ResourceRef | None:
    """์น˜ํ™˜ ์‚ฌ์ „ ์„ ์–ธ์„ **์ฝ์ง€ ์•Š๊ณ ** ์–ด๋А ํŒŒ์ผ์ธ์ง€๋กœ ํ‘ผ๋‹ค (run.json ์Šค๋ƒ…์ƒท์˜ `resources`).

    `_load_vocabulary` ์™€ ๊ฐ™์€ ์ˆœ์„œ๋ฅผ ๋”ฐ๋ฅธ๋‹ค: config ์ •๋ณธ โ†’ ๋ ˆ๊ฑฐ์‹œ ์„ ์–ธ(repo/source).
    ๋ ˆ๊ฑฐ์‹œ `local` ์€ ๋กœ๋”์˜ ๊ฒฝ๋กœ ๊ทœ์น™(`DatasetLoader._resolve_local_path`)์„ ๊ทธ๋Œ€๋กœ ์“ฐ๊ณ 
    ๋ผ๋ฒจ์€ ๋ฐ์ดํ„ฐ ๋ฃจํŠธ ์ƒ๋Œ€(`data:`), ์›๊ฒฉ(`huggingface` ๋“ฑ)์€ ๋„คํŠธ์›Œํฌ๋ฅผ ํƒ€์ง€ ์•Š๊ณ 
    ์„ ์–ธ๋งŒ์œผ๋กœ `hf:<repo>/<path>`(path None)๋ฅผ ๋‚ธ๋‹ค.

    Returns:
        ์„ ์–ธ์ด ์—†์œผ๋ฉด None(์ •์ƒ์ ์ธ no-op).

    Raises:
        KnowledgeAssetError: ์„ ์–ธํ–ˆ๋Š”๋ฐ ๋กœ์ปฌ์—์„œ ์ฐพ์„ ์ˆ˜ ์—†์„ ๋•Œ โ€” ๋กœ๋”๊ฐ€ run ๋„์ค‘์— ๋‚ผ
            ์˜ค๋ฅ˜๋ฅผ run ์‹œ์ž‘ ์ „์œผ๋กœ ์•ž๋‹น๊ธด๋‹ค.
    """
    vocab_path = config.get("vocab_dataset", "")
    if not vocab_path:
        return None
    searched: list[str] = []
    if config_dir is not None:
        candidate = _config_candidate(config_dir, vocab_path)
        searched.append(str(candidate))
        if candidate.is_file() and dataset_loader is not None:
            return ResourceRef("config", relative_posix(candidate, config_dir), candidate)
    if dataset_loader is None:
        searched.append("(dataset_loader ์—†์Œ)")
        raise KnowledgeAssetError(vocab_path, searched)
    repo = config.get("repo", "")
    source = config.get("source", "huggingface")
    if source != "local":
        if not repo:
            # repo ์—†๋Š” ์›๊ฒฉ ์„ ์–ธ์€ ๋กœ๋”๊ฐ€ run ๋„์ค‘ ๋‹ค์šด๋กœ๋“œ์— ์‹คํŒจํ•œ๋‹ค(prod_251231 ์˜ ์˜› ์‚ฌ๊ณ ) โ€”
            # ์Šค๋ƒ…์ƒท์ด null ๋กœ ๋„˜๊ธฐ์ง€ ์•Š๊ณ  ์‹œ์ž‘ ์ „์— ๊ฐ™์€ ์˜ค๋ฅ˜๋กœ ์ฃฝ์ธ๋‹ค.
            searched.append(f"{source}:{vocab_path}")
            raise KnowledgeAssetError(vocab_path, searched)
        return ResourceRef("hf", f"{repo}/{vocab_path}", None)
    local = dataset_loader._resolve_local_path(repo, vocab_path)
    searched.append(str(local))
    if not local.is_file():
        raise KnowledgeAssetError(vocab_path, searched)
    return ResourceRef("data", relative_posix(local, dataset_loader.base_dir), local)


def apply_pronoun_postprocess(text: str, replacements: dict[str, str]) -> str:
    """๋Œ€๋ช…์‚ฌ/์งํ•จ ์น˜ํ™˜ + ํ•œ๊ตญ์–ด ์กฐ์‚ฌ ๊ต์ •.

    ๋‹จ์–ด๋ฅผ ์น˜ํ™˜ํ•  ๋•Œ(์˜ˆ: "์ด์žฌ๋ช… ๋Œ€ํ‘œ" โ†’ "์ด์žฌ๋ช… ๋Œ€ํ†ต๋ น") ๋’ค๋”ฐ๋ฅด๋Š” ์กฐ์‚ฌ๋„
    ์ƒˆ ๋‹จ์–ด์˜ ๋ฐ›์นจ์— ๋งž์ถฐ ๋ฐ”๊ฟ”์•ผ ํ•œ๋‹ค.
    """
    # ๋ชจ์Œ์œผ๋กœ ๋๋‚˜๋Š” ์กฐ์‚ฌ โ†’ ์ž์Œ์œผ๋กœ ๋๋‚˜๋Š” ๋‹จ์–ด ๋’ค์— ๋ถ™๋Š” ๋Œ€์‘ ์กฐ์‚ฌ
    correction_map = {
        "๋Š”": "์€",
        "๊ฐ€": "์ด",
        "๋ฅผ": "์„",
        "์™€": "๊ณผ",
        "๋กœ": "์œผ๋กœ",
        "์—ฌ": "์ด์—ฌ",
        "๋ผ": "์ด๋ผ",
        "๋ž‘": "์ด๋ž‘",
        "๋‹ค": "์ด๋‹ค",
        "์˜€๋‹ค": "์ด์—ˆ๋‹ค",
        "๋ผ๋ฉด": "์ด๋ผ๋ฉด",
        "๋ผ์„œ": "์ด๋ผ์„œ",
        "๋กœ๋ถ€ํ„ฐ": "์œผ๋กœ๋ถ€ํ„ฐ",
    }
    all_particles = (
        list(correction_map.keys()) + list(correction_map.values()) + ["๋งŒ", "๋„", "๊ป˜์„œ"]
    )
    particle_pattern = "|".join(re.escape(p) for p in sorted(all_particles, key=len, reverse=True))

    for old, new in replacements.items():
        regex = re.compile(f"({re.escape(old)})({particle_pattern})?")

        def replacer(m: re.Match, new_word: str = new) -> str:
            particle = m.group(2)
            if particle:
                return new_word + correction_map.get(particle, particle)
            return new_word

        text = regex.sub(replacer, text)
    return text


def apply_currency_compact(text: str) -> str:
    """ํ†ตํ™” ํ‘œํ˜„์—์„œ ์ˆซ์ž์™€ ๋‹จ์œ„ ์‚ฌ์ด ๊ณต๋ฐฑ์„ ์ œ๊ฑฐํ•œ๋‹ค."""
    _unit = r"(์›|๋ช…|๊ฐœ|๋Œ€|์œ„์•ˆ|๋‹ฌ๋Ÿฌ|์œ ๋กœ|์—”|ํ†ค|๊ถŒ|๊ฑด|ํšŒ|์žฅ|๋งˆ๋ฆฌ|๊ทธ๋ฃจ|์†ก์ด|ํ•„)"
    _tail = r"(?=[\s.,!?()\"\'๊ฐ€-ํžฃ]|$)"
    # "3์–ต 5000๋งŒ ์›" โ†’ "3์–ต5000๋งŒ์›"
    text = re.sub(
        r"(\d+(?:\.\d+)?)(๋งŒ|์–ต|์กฐ)\s*(\d+)\s*" + _unit + _tail,
        r"\1\2\3\4",
        text,
    )
    # "3์–ต ์›" โ†’ "3์–ต์›"
    text = re.sub(
        r"(\d+(?:\.\d+)?)(๋งŒ|์–ต|์กฐ)\s*" + _unit + _tail,
        r"\1\2\3",
        text,
    )
    return text


def apply_comma_removal(text: str) -> str:
    """์ˆซ์ž ์‚ฌ์ด์˜ ์ฒœ๋‹จ์œ„ ์ฝค๋งˆ๋ฅผ ์ œ๊ฑฐํ•œ๋‹ค (1,000 โ†’ 1000)."""
    return re.sub(r"(?<=\d),(?=\d)", "", text)


def apply_correction_filter(text: str, config: dict[str, Any], original: str = "") -> str:
    """Filter corrections by comparing with original text.

    Keeps only 'safe' corrections (spacing changes, small character diffs).
    Reverts larger changes that are likely unnecessary expression substitutions.

    Config options:
        max_char_diff: Maximum character differences to allow (default: 2)
        allow_spacing: Keep spacing-only changes (default: true)
    """
    from solar_eval.evaluators.scoring import compute_lcs

    if not original:
        return text

    max_cd = config.get("max_char_diff", 2)
    allow_spacing = config.get("allow_spacing", True)

    orig_tokens = original.split()
    pred_tokens = text.split()

    if orig_tokens == pred_tokens:
        return text

    lcs_pairs = compute_lcs(orig_tokens, pred_tokens)

    def is_safe(o_text: str, c_text: str) -> bool:
        if allow_spacing and o_text.replace(" ", "") == c_text.replace(" ", ""):
            return True
        if abs(len(o_text) - len(c_text)) <= 1:
            d = sum(1 for a, b in zip(o_text, c_text) if a != b)
            d += abs(len(o_text) - len(c_text))
            if d <= max_cd:
                return True
        return False

    result_tokens: list[str] = []
    prev_orig = -1
    prev_pred = -1

    for oi, pi in lcs_pairs:
        orig_gap = orig_tokens[prev_orig + 1 : oi]
        pred_gap = pred_tokens[prev_pred + 1 : pi]
        if orig_gap or pred_gap:
            o_text = " ".join(orig_gap)
            p_text = " ".join(pred_gap)
            if o_text == p_text or is_safe(o_text, p_text):
                result_tokens.extend(pred_gap)
            else:
                result_tokens.extend(orig_gap)
        result_tokens.append(orig_tokens[oi])
        prev_orig = oi
        prev_pred = pi

    orig_tail = orig_tokens[prev_orig + 1 :]
    pred_tail = pred_tokens[prev_pred + 1 :]
    if orig_tail or pred_tail:
        o_text = " ".join(orig_tail)
        p_text = " ".join(pred_tail)
        if o_text == p_text or is_safe(o_text, p_text):
            result_tokens.extend(pred_tail)
        else:
            result_tokens.extend(orig_tail)

    return " ".join(result_tokens)


def apply_judge_decisions(text: str, config: dict[str, Any], sample: EvalSample) -> str:
    """`tool_calling_judge` ์˜ verdict="revert" ํŒ์ •์„ ํ…์ŠคํŠธ์— ๋˜๋Œ๋ฆฐ๋‹ค.

    `judge_step`(๊ธฐ๋ณธ "tool_calling_judge")์˜ ํŒ์ • ๋ชฉ๋ก๊ณผ `corrections_step`
    (๊ธฐ๋ณธ "basic_correction")์˜ corrections ๋ชฉ๋ก์„ `sample.artifacts` ์—์„œ ์ฝ๋Š”๋‹ค
    โ€” ์ด ๋‘ artifact ๋Š” ๊ฐ๊ฐ `pipelines/judge.py::run_tool_calling_judge` ์™€
    `MultiStepPipeline` ์˜ self-consistency ๊ฒฝ๋กœ๊ฐ€ ์ฑ„์šด๋‹ค. ์–ด๋А ํ•œ์ชฝ์ด๋ผ๋„ ๋น„์–ด
    ์žˆ์œผ๋ฉด(judge ์Šคํ…์ด ์—†์—ˆ๊ฑฐ๋‚˜ corrections ๊ฐ€ ํ•˜๋‚˜๋„ ์—†์—ˆ๋˜ ๊ฒฝ์šฐ) ์กฐ์šฉํžˆ
    ์›๋ฌธ(text)์„ ๊ทธ๋Œ€๋กœ ๋Œ๋ ค์ค€๋‹ค โ€” revert ํ•  ๋Œ€์ƒ ์ž์ฒด๊ฐ€ ์—†๋Š” ์ •์ƒ ์ƒํƒœ๋‹ค.

    HF ๊ตฌํ˜„(`huggingface/pipelines_v24.py::apply_judge_decisions_for_bulk`)์„
    ํฌํŒ…. bulk ๋‹จ์œ„์˜€๋˜ ์›๋ณธ๊ณผ ๋‹ฌ๋ฆฌ ์—ฌ๊ธฐ์„œ๋Š” ๋ฌธ์„œ ์ „์ฒด text ์— ์ ์šฉํ•œ๋‹ค
    (ยง5-F ์„ค๊ณ„ ๊ฒฐ์ • โ€” ์ด ์—”์ง„์€ tool_calling_judge/basic_correction ์„ ์ด๋ฏธ
    ๋ฌธ์„œ ๋‹จ์œ„๋กœ ์ฒ˜๋ฆฌํ•˜๋ฏ€๋กœ bulk ์ •๋ ฌ ๋ฌธ์ œ ์ž์ฒด๊ฐ€ ์—†๋‹ค).
    """
    judge_step = config.get("judge_step", "tool_calling_judge")
    corrections_step = config.get("corrections_step", "basic_correction")
    decisions = sample.artifacts.get("judge_decisions", {}).get(judge_step, [])
    corrections = sample.artifacts.get("corrections", {}).get(corrections_step, [])
    if not decisions or not corrections:
        return text

    revert_pairs: list[tuple[str, str]] = []
    for d in decisions:
        if not isinstance(d, dict) or d.get("verdict") != "revert":
            continue
        idx = d.get("correction_index")
        if not isinstance(idx, int) or idx < 0 or idx >= len(corrections):
            continue
        entry = corrections[idx]
        if not isinstance(entry, dict):
            continue
        corrected = str(entry.get("corrected", ""))
        original = str(entry.get("original", ""))
        if corrected and original and corrected != original:
            revert_pairs.append((corrected, original))

    # ๊ธด ๊ฒƒ๋ถ€ํ„ฐ ๋˜๋Œ๋ ค์•ผ ์งง์€ ๊ต์ •์ด ๊ธด ๊ต์ •์˜ ๋ถ€๋ถ„ ๋ฌธ์ž์—ด์ผ ๋•Œ ์ž˜๋ชป ๋˜๋Œ๋ฆฌ์ง€ ์•Š๋Š”๋‹ค.
    revert_pairs.sort(key=lambda p: -len(p[0]))
    for corrected, original in revert_pairs:
        if corrected in text:
            text = text.replace(corrected, original, 1)
    return text


def apply_change_rate_guard(text: str, original: str, config: dict[str, Any]) -> str:
    """์›๋ฌธ ๋Œ€๋น„ ํ† ํฐ ๋ณ€๊ฒฝ ๋น„์œจ์ด `max_change_rate` ๋ฅผ ๋„˜์œผ๋ฉด ์›๋ฌธ์œผ๋กœ ๋˜๋Œ๋ฆฌ๋Š” ์•ˆ์ „๋ง.

    v17 ์ธ์‚ฌ์ดํŠธ ๋ฌธ์„œ(`insights/260504_solar-pro2_essentials.md`)๊ฐ€ "change_rate_guard
    (rule, bulk-level safety net, max_change_rate: 0.45)" ๋ผ๊ณ ๋งŒ ์„ค๋ช…ํ•˜๊ณ , ์‹ค์ œ
    ๊ตฌํ˜„์€ HF ์•„์นด์ด๋ธŒ(`huggingface/pipelines.py`/`pipelines_v24.py`) ์–ด๋””์—๋„ ์—†๋‹ค
    (๋ ˆํฌ ์ „์ฒด ๊ฒ€์ƒ‰์œผ๋กœ ํ™•์ธ). ๊ทธ๋ž˜์„œ ์ด ํ•จ์ˆ˜๋Š” ๊ทธ ์„ค๋ช…๋งŒ ๋ณด๊ณ  ์ƒˆ๋กœ ์ž‘์„ฑํ•œ ๊ฒƒ์ด๋‹ค
    โ€” v17 ์ˆ˜์น˜ ์žฌํ˜„์„ ์•ฝ์†ํ•˜์ง€ ์•Š๋Š”๋‹ค๋Š” ์ „์ œ๋กœ ํฌํŒ… ๋Œ€์ƒ์— ํฌํ•จ๋๋‹ค
    (`.agents/01-plans/harness/2026-08-09-chosun-proofread-evalsample-migration.md` ยง9-3).

    ๋ณ€๊ฒฝ ๋น„์œจ์€ `evaluators/scoring.compute_lcs` ๋กœ ์›๋ฌธยทํ˜„์žฌ ํ…์ŠคํŠธ์˜ ํ† ํฐ ๋‹จ์œ„
    LCS ๋ฅผ ๊ตฌํ•ด `1 - |LCS| / |์›๋ฌธ ํ† ํฐ|` ์œผ๋กœ ์ •์˜ํ•œ๋‹ค โ€” ์ด ํ”„๋กœ์ ํŠธ์˜ ๋‹ค๋ฅธ ๋ชจ๋“ 
    ๊ต์—ด diff ๋กœ์ง(`compute_proofread_metrics`, `apply_correction_filter`)๊ณผ ๊ฐ™์€
    ์ฒ™๋„๋ฅผ ์“ด๋‹ค.
    """
    from solar_eval.evaluators.scoring import compute_lcs

    max_rate = config.get("max_change_rate", 0.45)
    orig_tokens = original.split()
    if not orig_tokens:
        return text

    text_tokens = text.split()
    lcs_pairs = compute_lcs(orig_tokens, text_tokens)
    change_rate = 1 - (len(lcs_pairs) / len(orig_tokens))

    if change_rate > max_rate:
        logger.warning(
            "[change_rate_guard] change_rate=%.3f > max=%.3f, reverting to original",
            change_rate,
            max_rate,
        )
        return original
    return text


_UNIT_SYMBOLS = {
    "mmยฒ": "ใŽŸ",
    "cmยฒ": "ใŽ ",
    "kmยฒ": "ใŽข",
    "mยฒ": "ใŽก",
    "mm": "ใŽœ",
    "cm": "ใŽ",
    "km": "ใŽž",
    "mg": "ใŽŽ",
    "kg": "ใŽ",
    "ml": "ใŽ–",
    "dl": "ใŽ—",
    "cc": "ใ„",
}
# ์ˆซ์ž(๊ณต๋ฐฑ ํ•˜๋‚˜๊นŒ์ง€ ํ—ˆ์šฉ) ๋ฐ”๋กœ ๋’ค์— ์˜ค๊ณ  ๋’ค์— ์˜๋ฌธ์ž๊ฐ€ ์ด์–ด์ง€์ง€ ์•Š๋Š” ๋‹จ์œ„๋งŒ ๋ฐ”๊พผ๋‹ค. ์˜ˆ์ „์—๋Š” ๊ธ€์ž์—ด ์–ด๋””์„œ๋‚˜ ๋ฐ”๊ฟ”
# `Grammy`ยท`Programme`ยท`Baccalaureate`ยท`Nadler`ยท๋ฉ”์ผ ์ฃผ์†Œ์˜ mmยทccยทdl ๊นŒ์ง€ ใŽœยทใ„ยทใŽ— ๋กœ ๋ง๊ฐ€๋œจ๋ ธ๋‹ค(2026-10-20 ํ˜„์—… ์‚ฌ๋ก€ ๋น„๊ต).
_UNIT_RE = re.compile(
    r"(?<=\d)(\s?)("
    + "|".join(sorted(map(re.escape, _UNIT_SYMBOLS), key=len, reverse=True))
    + r")(?![A-Za-z])"
)


def apply_unit_unicode(text: str) -> str:
    """์ˆซ์ž ๋’ค ๋‹จ์œ„ ํ…์ŠคํŠธ๋ฅผ ์œ ๋‹ˆ์ฝ”๋“œ ๊ฒฐํ•ฉ ๋ฌธ์ž๋กœ ๋ณ€ํ™˜ํ•œ๋‹ค(`10mm`โ†’`10ใŽœ`, `5 kg`โ†’`5 ใŽ`)."""
    return _UNIT_RE.sub(lambda m: m.group(1) + _UNIT_SYMBOLS[m.group(2)], text)


_QUOTE_KINDS = (("'โ€˜โ€™", "โ€˜", "โ€™"), ('"โ€œโ€', "โ€œ", "โ€"))
_CLOSES_AFTER = ".,!?;%โ€ฆโ€™โ€"
# ์•ž ๊ธ€์ž๋งŒ์œผ๋กœ๋Š” ์—ฌ๋‹ซ์ด๋ฅผ ์ •ํ•  ์ˆ˜ ์—†๋Š” ๊ธฐํ˜ธ: ๊ฐ™์€ ์ค„์— ์—ด๋ฆฐ ๋”ฐ์˜ดํ‘œ๊ฐ€ ์žˆ๊ฑฐ๋‚˜ ๋’ค๊ฐ€ ๊ณต๋ฐฑยท์ค„ ๋์ด๋ฉด ๋‹ซ๋Š” ์ชฝ, ์•„๋‹ˆ๋ฉด ์—ฌ๋Š” ์ชฝ.
# `โ€˜AA-โ€™`ยท`โ€˜์†ก๋„๋Š”~โ€™`ยท`โ€˜๊ฐœ(็Šฌ)โ€™` ์€ ๋‹ซ๊ณ , ์ธํ„ฐ๋ทฐ ์งˆ๋ฌธ ๋จธ๋ฆฌ `-โ€˜๊ฝƒโ€™`ยท`[์ธํ„ฐ๋ทฐ]โ€œ๋”ฅ ๋ฆฌ๋”ฉโ€` ์€ ์—ฐ๋‹ค.
_AMBIGUOUS_BEFORE = "-+~)]}>ใ€ใ€"


def apply_quote_direction(text: str, original: str = "") -> str:
    """๋‘ฅ๊ทผ ๋”ฐ์˜ดํ‘œ์˜ ์—ฌ๋‹ซ์ด ๋ฐฉํ–ฅ์„ ์•ž ๊ธ€์ž์™€ ๊ฐ™์€ ์ค„์˜ ์ง์œผ๋กœ ๋‹ค์‹œ ์ •ํ•œ๋‹ค.

    FT ๊ต์—ด ๋ชจ๋ธ์ด ๊ณง์€ ๋”ฐ์˜ดํ‘œ(')๋ฅผ ์กฐ์„ ์ผ๋ณด ํ‘œ๊ธฐ์ธ ๋‘ฅ๊ทผ ๋”ฐ์˜ดํ‘œ๋กœ ๋ฐ”๊พธ๋ฉด์„œ ์—ฌ๋Š” ์ž๋ฆฌ์— ๋‹ซ๋Š” ๋”ฐ์˜ดํ‘œ(โ€™)๋ฅผ ๋„ฃ๊ฑฐ๋‚˜ ํ•œ์ชฝ๋งŒ ๋ฐ”๊พธ๋Š”
    ์‚ฌ๊ณ ๋ฅผ ๋‚ธ๋‹ค(2026-10-21 FT ์•ฝ์  ๋ถ„์„: ์ •๋‹ต ๋ฐ– ์˜ค๊ต์ •์˜ ์•ฝ 1/4). ๋‘ฅ๊ทผ ๋”ฐ์˜ดํ‘œ๊ฐ€ ์žˆ๋Š” ์ค„์—์„œ๋งŒ ๊ทธ ์ค„์˜ ๊ฐ™์€ ์ข…๋ฅ˜ ๋”ฐ์˜ดํ‘œ๋ฅผ
    ๋ชจ๋‘ ๋‘ฅ๊ทผ ๋”ฐ์˜ดํ‘œ๋กœ ๋งž์ถ”๊ณ , ๊ธ€์žยท์ˆซ์žยท๋‹ซ๋Š” ๋ฌธ์žฅ๋ถ€ํ˜ธ ๋’ค๋ฉด ๋‹ซ๋Š”(โ€™ โ€), ๊ทธ ๋ฐ–(์ค„ ์ฒ˜์Œยท๊ณต๋ฐฑยท`โ—‡`ยท`โ–ถ` ๊ฐ™์€ ๋จธ๋ฆฌ ๊ธฐํ˜ธยท์—ฌ๋Š” ๊ด„ํ˜ธยท
    ์—ฌ๋Š” ๋”ฐ์˜ดํ‘œ ๋’ค)์€ ์—ฌ๋Š”(โ€˜ โ€œ) ์ชฝ์œผ๋กœ ๋‘”๋‹ค. `-`ยท`+`ยท`~` ๋’ค๋Š” ๊ฐ™์€ ์ค„์— ์—ด๋ฆฐ ๋”ฐ์˜ดํ‘œ๊ฐ€ ์žˆ๊ฑฐ๋‚˜ ๋’ค๊ฐ€ ๊ณต๋ฐฑยท์ค„ ๋์ผ ๋•Œ๋งŒ ๋‹ซ๋Š”๋‹ค.
    ์—ด๋ฆฐ ์ž‘์€๋”ฐ์˜ดํ‘œ ๋’ค ์ˆซ์ž์— ๋ถ™์€ ํ”„๋ผ์ž„(โ€ฒ)์€ FT ๊ฐ€ ๋‹ซ๋Š” ๋”ฐ์˜ดํ‘œ๋ฅผ ๋ฐ”๊พผ ๊ฒƒ์ด๋ผ โ€™ ๋กœ ๋˜๋Œ๋ฆฐ๋‹ค(`โ€˜ํ•˜์•ผ๋ถ€์‚ฌ2โ€ฒ๊ฐ€`). ๋‹จ ์—ฌ๋Š”
    ๋”ฐ์˜ดํ‘œ๋ถ€ํ„ฐ ๊ทธ ํ”„๋ผ์ž„๊นŒ์ง€๊ฐ€ `original` ์— ๊ทธ๋Œ€๋กœ ์žˆ์œผ๋ฉด ๋‘”๋‹ค - ์กฐ์„ ์ผ๋ณด ์›๋ฌธยท๊ฒŒ์žฌ๋ณธ์—๋Š” `โ€˜์ถ˜์ฒœ์‚ฌ์ด๋กœ248โ€ฒ` ๊ฐ™์€ ํ‘œ๊ธฐ๊ฐ€
    ์žˆ๊ณ  ๊ต์—ด์ž๋„ ๊ณ ์น˜์ง€ ์•Š๋Š”๋‹ค(2026-10-27 ๊ธฐ์‚ฌ ์…‹ ํ™•์ธ).
    ๋‘ฅ๊ทผ ๋”ฐ์˜ดํ‘œ๊ฐ€ ์—†๋Š” ์ค„์˜ ๊ณง์€ ๋”ฐ์˜ดํ‘œ๋Š” ๊ฑด๋“œ๋ฆฌ์ง€ ์•Š๋Š”๋‹ค.
    """
    lines = []
    for line in text.split("\n"):
        chars = list(line)
        for kinds, opening, closing in _QUOTE_KINDS:
            if opening not in line and closing not in line:
                continue
            # ์•„์ง ๋‹ซํžˆ์ง€ ์•Š์€ ์—ฌ๋Š” ๋”ฐ์˜ดํ‘œ ์ž๋ฆฌ(๊ฒน๋”ฐ์˜ดํ‘œ `โ€˜โ€ฆ(โ€˜โ€ฆโ€™)โ€™` ์˜ ๋ฐ”๊นฅ์ชฝ์„ ์žƒ์ง€ ์•Š๋„๋ก)
            opened: list[int] = []
            for i, ch in enumerate(chars):
                prev = chars[i - 1] if i else ""
                nxt = chars[i + 1] if i + 1 < len(chars) else ""
                if ch == "โ€ฒ" and opening == "โ€˜":
                    if opened and prev.isdigit() and not (nxt.isdigit() or nxt == "โ€ณ"):
                        # ์—ฌ๋Š” ๋”ฐ์˜ดํ‘œ ๊ธ€์ž๋Š” ์›๋ฌธ๊ณผ ๋‹ค๋ฅผ ์ˆ˜ ์žˆ์–ด(`โ€™1988KY26โ€ฒ`) ์•ˆ์ชฝ ๊ธ€์ž + ํ”„๋ผ์ž„์œผ๋กœ ์›๋ฌธ์„ ์ฐพ๋Š”๋‹ค.
                        inner = "".join(chars[opened.pop() + 1 : i + 1])
                        chars[i] = ch if inner in original else closing
                    continue
                if ch not in kinds:
                    continue
                if prev and prev in _AMBIGUOUS_BEFORE:
                    closes = bool(opened) or not nxt or nxt.isspace()
                else:
                    closes = bool(prev) and (prev.isalnum() or prev in _CLOSES_AFTER)
                chars[i] = closing if closes else opening
                if closes:
                    if opened:
                        opened.pop()
                else:
                    opened.append(i)
        lines.append("".join(chars))
    return "\n".join(lines)


# ๋”ฐ์˜ดํ‘œ ๊ธ€์ž๋ฅผ ์ข…๋ฅ˜๋ณ„ ๋Œ€ํ‘œ ๊ธ€์ž๋กœ ์ ‘์–ด, ๋”ฐ์˜ดํ‘œ ๋ชจ์–‘๋งŒ ๋‹ค๋ฅธ ์ž๋ฆฌ๋ฅผ ๊ฐ™์€ ๊ธ€์ž๋กœ ์ •๋ ฌํ•œ๋‹ค(โ€ฒ โ€ณ ๋Š” FT ๊ฐ€ ๋‹ซ๋Š” ๋”ฐ์˜ดํ‘œ ๋Œ€์‹  ๋„ฃ๋Š”๋‹ค).
_QUOTE_FOLD = str.maketrans({"โ€˜": "'", "โ€™": "'", "โ€ฒ": "'", "โ€œ": '"', "โ€": '"', "โ€ณ": '"'})


def apply_quote_preserve(text: str, original: str) -> str:
    """์›๋ฌธ์— ์žˆ๋˜ ๋”ฐ์˜ดํ‘œ ๊ธ€์ž๋ฅผ ์›๋ฌธ ๋ชจ์–‘ ๊ทธ๋Œ€๋กœ ๋˜๋Œ๋ฆฐ๋‹ค.

    ์กฐ์„ ์ผ๋ณด ๊ต์—ด์ž๋Š” ๋”ฐ์˜ดํ‘œ ๋ชจ์–‘(๊ณง์€ยท๋‘ฅ๊ทผยท์—ฌ๋‹ซ์ดยทํ”„๋ผ์ž„)์„ ๊ณ ์น˜์ง€ ์•Š๋Š”๋‹ค - ๊ธฐ์‚ฌ ์…‹ 508 ยท ์ผ๋ฐ˜ ๋ฌธ๋‹จ 541 ์˜ ์›๋ฌธ โ†’ ์ •๋‹ต์—์„œ
    ๋”ฐ์˜ดํ‘œ ๊ธ€์ž๋งŒ ๋ฐ”๋€ ์ž๋ฆฌ๋Š” 0 ์ด๋‹ค. ๋ฐ˜๋ฉด FT ๋Š” ๊ณง์€ ๋”ฐ์˜ดํ‘œ๋ฅผ ๋‘ฅ๊ทผ ๋”ฐ์˜ดํ‘œ๋กœ ๋ฐ”๊พธ๊ณ  ๋ฐฉํ–ฅยทํ”„๋ผ์ž„ ์‚ฌ๊ณ ๋ฅผ ๋‚ด์„œ, FT+Opus ์ถœ๋ ฅ์—๋Š”
    ๋”ฐ์˜ดํ‘œ๋งŒ ๋ฐ”๋€ ์ž๋ฆฌ๊ฐ€ ๊ธฐ์‚ฌ ์…‹ 508ํŽธ ์ค‘ 78ํŽธ์—์„œ 246๊ณณ ์žˆ์—ˆ๋‹ค(2026-10-27). ๋”ฐ์˜ดํ‘œ๋ฅผ ์ข…๋ฅ˜๋ณ„๋กœ ์ ‘์€ ๊ธ€์ž์—ด๋ผ๋ฆฌ ์ •๋ ฌํ•ด ์›๋ฌธ๊ณผ ๋งž๋ฌผ๋ฆฌ๋Š”
    ๋”ฐ์˜ดํ‘œ ์ž๋ฆฌ๋งŒ ์›๋ฌธ ๊ธ€์ž๋กœ ๋Œ๋ฆฐ๋‹ค. ์˜† ๊ธ€์ž ๊ต์ •(`โ€˜ํ•˜์•ผ๋ถ€์‚ฌ2ํ˜ธโ€ฒ`์˜ `ํ˜ธ` ์‚ญ์ œ)์€ ๋‚จ๊ณ , ์›๋ฌธ์— ์—†๋˜ ๋”ฐ์˜ดํ‘œ๋Š” ๊ทธ๋Œ€๋กœ ๋‘”๋‹ค.
    ๊ธ€์ž ์ •๋ ฌ์€ ์ค„ ๋‹จ์œ„๋กœ ๋จผ์ € ์ง์„ ์ง€์€ ๋’ค ๋ฐ”๋€ ์ค„ ๋ฌถ์Œ ์•ˆ์—์„œ๋งŒ ํ•œ๋‹ค(๊ธฐ์‚ฌ ์ „์ฒด๋ฅผ ๊ธ€์ž๋กœ ์ •๋ ฌํ•˜๋ฉด ๊ธด ๊ธฐ์‚ฌ์—์„œ 1์ดˆ ๊ฐ€๊นŒ์ด ๊ฑธ๋ฆฐ๋‹ค).
    """
    if not original or text == original:
        return text
    orig_lines, text_lines = original.split("\n"), text.split("\n")
    out_lines = list(text_lines)
    matcher = difflib.SequenceMatcher(
        None,
        [line.translate(_QUOTE_FOLD) for line in orig_lines],
        [line.translate(_QUOTE_FOLD) for line in text_lines],
        autojunk=False,
    )
    for op, i1, i2, j1, j2 in matcher.get_opcodes():
        if op == "equal":
            # ์ ‘์€ ์ค„์ด ๊ฐ™์œผ๋ฉด ๋”ฐ์˜ดํ‘œ ๊ธ€์ž๋งŒ ๋‹ค๋ฅด๋‹ค - ์›๋ฌธ ์ค„ ๊ทธ๋Œ€๋กœ.
            out_lines[j1:j2] = orig_lines[i1:i2]
        elif op == "replace":
            block = _restore_quotes("\n".join(text_lines[j1:j2]), "\n".join(orig_lines[i1:i2]))
            out_lines[j1:j2] = block.split("\n")
    return "\n".join(out_lines)


def _restore_quotes(text: str, original: str) -> str:
    out = list(text)
    matcher = difflib.SequenceMatcher(
        None, original.translate(_QUOTE_FOLD), text.translate(_QUOTE_FOLD), autojunk=False
    )
    for i, j, size in matcher.get_matching_blocks():
        for k in range(size):
            if original[i + k] != text[j + k] and original[i + k] in "'\"โ€˜โ€™โ€œโ€โ€ฒโ€ณ":
                out[j + k] = original[i + k]
    return "".join(out)


def load_compound_whitelist(config: dict[str, Any], config_dir: Path | None) -> set[str]:
    """๋ณตํ•ฉ์–ด ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ(ํƒญ ๊ตฌ๋ถ„ ``ํ‘œ์ œ์–ด\\t๋นˆ๋„``)๋ฅผ ๋กœ๋“œํ•œ๋‹ค.

    ์„ ์–ธ์ด ์—†์œผ๋ฉด ๋นˆ set(์ •์ƒ์ ์ธ no-op)์ด๊ณ , ์„ ์–ธํ–ˆ๋Š”๋ฐ ๋ชป ์ฝ์œผ๋ฉด ์˜ˆ์™ธ๋‹ค โ€”
    `KnowledgeAssetError` ๊ณ„์•ฝ(`errors.py`)์„ ์น˜ํ™˜ ์‚ฌ์ „๊ณผ ๋™์ผํ•˜๊ฒŒ ๋”ฐ๋ฅธ๋‹ค.
    ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ๋Š” ์‚ฌ๋žŒ์ด ํŽธ์ง‘ํ•˜๋Š” ์ง€์‹ ์ž์‚ฐ์ด๋ผ config ์ •๋ณธ(`03-evaluation/`)
    ๊ธฐ์ค€ ์ƒ๋Œ€๊ฒฝ๋กœ๋งŒ ์ง€์›ํ•œ๋‹ค.
    """
    ref = resolve_whitelist_path(config, config_dir)
    if ref is None:
        return set()
    if ref.path is None:  # config ์ž์‚ฐ๋งŒ ์ง€์›ํ•˜๋ฏ€๋กœ ์˜ค์ง€ ์•Š๋Š”๋‹ค โ€” ์˜จ๋‹ค๋ฉด ํ•ด์„ ๊ทœ์น™์ด ๋ฐ”๋€ ๊ฒƒ
        raise KnowledgeAssetError(ref.rel, [ref.label])
    entries: set[str] = set()
    for line in ref.path.read_text(encoding="utf-8").splitlines():
        form = line.split("\t")[0].strip()
        if form:
            entries.add(form)
    return entries


def resolve_whitelist_path(config: dict[str, Any], config_dir: Path | None) -> ResourceRef | None:
    """๋ณตํ•ฉ์–ด ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ ์„ ์–ธ์„ ํŒŒ์ผ๋กœ ํ‘ผ๋‹ค โ€” ๋กœ๋”(`load_compound_whitelist`)์™€ ์Šค๋ƒ…์ƒท์ด ๊ณต์œ .

    Returns:
        ์„ ์–ธ์ด ์—†์œผ๋ฉด None.

    Raises:
        KnowledgeAssetError: ์„ ์–ธํ–ˆ๋Š”๋ฐ config ์ •๋ณธ์— ํŒŒ์ผ์ด ์—†์„ ๋•Œ(๋˜๋Š” config_dir ์ด ์—†์„ ๋•Œ).
    """
    wl_path = config.get("whitelist_path", "")
    if not wl_path:
        return None
    searched: list[str] = []
    if config_dir is not None:
        candidate = _config_candidate(config_dir, wl_path)
        searched.append(str(candidate))
        if candidate.is_file():
            return ResourceRef("config", relative_posix(candidate, config_dir), candidate)
    else:
        searched.append("(config_dir ์—†์Œ)")
    raise KnowledgeAssetError(wl_path, searched)


def _has_whitelist_prefix(joined: str, split_at: int, whitelist: set[str]) -> bool:
    """๊ฒฐํ•ฉํ˜•์˜ ์ ‘๋‘(๋ถ„๋ฆฌ์  ๋„ˆ๋จธ ~ ์ „์ฒด)๊ฐ€ ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ ํ‘œ์ œ์–ด์ธ์ง€.

    ์กฐ์‚ฌยท์–ด๋ฏธ๊ฐ€ ๋ถ™์€ ์–ด์ ˆ("์‚ผ์„ฑ"+"์ „์ž๋Š”")๋„ ํ‘œ์ œ์–ด("์‚ผ์„ฑ์ „์ž")๋กœ ์žก๊ธฐ ์œ„ํ•ด
    ์ •ํ™• ์ผ์น˜๊ฐ€ ์•„๋‹ˆ๋ผ ์ ‘๋‘ ์ผ์น˜๋ฅผ ๋ณธ๋‹ค. ๋ถ„๋ฆฌ์ (`split_at`) ์•ˆ์ชฝ์—์„œ ๋๋‚˜๋Š”
    ์ ‘๋‘๋Š” ์ฒซ ์–ด์ ˆ๋งŒ์œผ๋กœ ์„ฑ๋ฆฝํ•˜๋ฏ€๋กœ ํ›„๋ณด์—์„œ ๋บ€๋‹ค.
    """
    return any(joined[:k] in whitelist for k in range(split_at + 1, len(joined) + 1))


def apply_compound_whitelist_restore(text: str, original: str, whitelist: set[str]) -> str:
    """`compound_whitelist_restore` rule_type ๊ตฌํ˜„ (v19/v32 ๊ณ„๋ณด์˜ ํ˜„ ์—”์ง„ ํฌํŒ…).

    ํŒŒ์ดํ”„๋ผ์ธ(FTยทstep1/2/3)์ด ๊ฐˆ๋ผ๋†“์€ ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ ๋ณตํ•ฉ์–ด๋ฅผ ๋‹ค์‹œ ๋ถ™์ธ๋‹ค.
    ์ธ์ ‘ ์–ด์ ˆ ์Œ์˜ ๊ฒฐํ•ฉ์ด (1) ํ™”์ดํŠธ๋ฆฌ์ŠคํŠธ ํ‘œ์ œ์–ด๋ฅผ ์ ‘๋‘๋กœ ๊ฐ–๊ณ  โ€” ๋ถ„๋ฆฌ์ ์ด
    ํ‘œ์ œ์–ด ์•ˆ์ชฝ โ€” (2) ์›๋ฌธ์— ๊ทธ๋Œ€๋กœ ์กด์žฌํ•  ๋•Œ๋งŒ ๋ถ™์ธ๋‹ค. ์กฐ๊ฑด (2) ๋•Œ๋ฌธ์— ์ด
    ๋ฃฐ์€ ํŒŒ์ดํ”„๋ผ์ธ์ด ๋งŒ๋“  ๋ถ„๋ฆฌ๋ฅผ ๋˜๋Œ๋ฆด ๋ฟ, ์ƒˆ ๊ต์ •์„ ๋งŒ๋“ค์ง€ ์•Š๋Š”๋‹ค.

    2026-09-02 ์žฌ์ƒ ์‹ค์ธก(combo ์ฒด์ธ ์ถœ๋ ฅ ์œ„): paragraph +2.91 f1
    (redundant 408โ†’342), ci-v0 +0.43, ci-v2/ci-v1/yul-ryul ๋ฌด๋ณ€ํ™”.
    """
    if not whitelist:
        return text

    restored_lines: list[str] = []
    for line in text.split("\n"):
        tokens = line.split()
        out: list[str] = []
        i = 0
        while i < len(tokens):
            if i + 1 < len(tokens):
                joined = tokens[i] + tokens[i + 1]
                if joined in original and _has_whitelist_prefix(joined, len(tokens[i]), whitelist):
                    out.append(joined)
                    i += 2
                    continue
            out.append(tokens[i])
            i += 1
        restored_lines.append(" ".join(out))
    return "\n".join(restored_lines)


#: ์œจ/๋ฅ  ์ •๊ทœํ™”๊ฐ€ "๋ช…์‚ฌ + ์กฐ์‚ฌ" ๋ฌธ๋งฅ์œผ๋กœ ์ธ์ •ํ•˜๋Š” ์–ด์ ˆ ๊ผฌ๋ฆฌ(ํ•œ๊ธ€ ์ž”์—ฌ) ๋ชฉ๋ก.
#: ์ด ๋ชฉ๋ก ๋ฐ–์˜ ํ•œ๊ธ€์ด ์ด์–ด์ง€๋ฉด(์˜ˆ: ์ธ๋ช… '๊น€์œจํฌ๊ฐ€'์˜ 'ํฌ๊ฐ€') ๊ฑด๋“œ๋ฆฌ์ง€ ์•Š๋Š”๋‹ค.
_YUL_RYUL_JOSA = frozenset(
    {
        "์€",
        "๋Š”",
        "์ด",
        "๊ฐ€",
        "์„",
        "๋ฅผ",
        "์˜",
        "์—",
        "๋„",
        "๋งŒ",
        "๊ณผ",
        "์™€",
        "๋กœ",
        "์œผ๋กœ",
        "๋ณด๋‹ค",
        "๋ถ€ํ„ฐ",
        "๊นŒ์ง€",
        "์กฐ์ฐจ",
        "๋งˆ์ €",
        "๋ฐ–์—",
        "์ฒ˜๋Ÿผ",
        "๋Œ€๋กœ",
        "๋งŒํผ",
        "๋ฟ",
        "๋‚˜",
        "์ด๋‚˜",
        "๋ž€",
        "์ด๋ž€",
        "๋ผ",
        "์ด๋ผ",
        "๋ผ๊ณ ",
        "์ด๋ผ๊ณ ",
        "๋ผ๋Š”",
        "์ด๋ผ๋Š”",
        "๋ผ๋ฉฐ",
        "์ด๋ผ๋ฉฐ",
        "๋ฉฐ",
        "์ด๋ฉฐ",
        "๊ณ ",
        "์ด๊ณ ",
        "๋‹ค",
        "์ด๋‹ค",
        "์ž…๋‹ˆ๋‹ค",
        "์—์„œ",
        "์—๊ฒŒ",
        "์—๋Š”",
        "์—๋„",
        "์—์„œ๋Š”",
        "์—์„œ๋„",
        "๋กœ๋Š”",
        "์œผ๋กœ๋Š”",
        "๋กœ๋„",
        "์œผ๋กœ๋„",
        "๋กœ์„œ",
        "์œผ๋กœ์„œ",
        "๋กœ์จ",
        "์œผ๋กœ์จ",
        "์™€์˜",
        "๊ณผ์˜",
        "๊ณผ๋Š”",
        "์™€๋Š”",
        "์€์š”",
        "์š”",
        "๋Œ€๋น„",
    }
)


def apply_yul_ryul_normalize(text: str, exceptions: tuple[str, ...] = ()) -> str:
    """`yul_ryul_normalize` rule_type ๊ตฌํ˜„ โ€” ์œจ/๋ฅ  ๋ฐ›์นจ ๊ทœ์น™์˜ ๊ฒฐ์ •๋ก ์  ์ ์šฉ.

    ํ•œ๊ธ€ ๋งž์ถค๋ฒ• ์ œ11ํ•ญ: ์•ž ์Œ์ ˆ์— ๋ฐ›์นจ์ด ์—†๊ฑฐ๋‚˜ ใ„ด ๋ฐ›์นจ์ด๋ฉด '์œจ'(๋น„์œจยทํ™˜์œจยท
    ์ „ํ™˜์œจ), ๊ทธ ์™ธ ๋ฐ›์นจ์ด๋ฉด '๋ฅ '(๋ฒ•๋ฅ ยทํ™•๋ฅ ยท์ถœ์„๋ฅ ). ๋ฐ›์นจ์€ ์œ ๋‹ˆ์ฝ”๋“œ ์—ฐ์‚ฐ์œผ๋กœ
    ํŒ์ •๋˜๋ฏ€๋กœ LLM ์—†์ด ์ตœ์ข… ํ…์ŠคํŠธ์—์„œ ๊ฐ•์ œํ•  ์ˆ˜ ์žˆ๋‹ค.

    ์ธ๋ช… ์˜คํƒ ๋ฐฉ์ง€ 2์ค‘ ๊ฐ€๋“œ:
    1. ์–ด์ ˆ ๊ผฌ๋ฆฌ ๊ฒ€์‚ฌ โ€” ์œจ/๋ฅ  ๋’ค์˜ ํ•œ๊ธ€ ์ž”์—ฌ๊ฐ€ ์กฐ์‚ฌ ๋ชฉ๋ก(`_YUL_RYUL_JOSA`)์—
       ์—†์œผ๋ฉด ์ ‘๋ฏธ์‚ฌ ์šฉ๋ฒ•์ด ์•„๋‹Œ ๊ฒƒ์œผ๋กœ ๋ณด๊ณ  ๊ฑด๋„ˆ๋›ด๋‹ค (์žฌ์ƒ ์‹ค์ธก์˜ ์œ ์ผํ•œ ์˜คํƒ
       '๊น€์œจํฌ๊ฐ€'โ†’'๊น€๋ฅ ํฌ๊ฐ€' ๊ฐ€ ์—ฌ๊ธฐ์„œ ๊ฑธ๋Ÿฌ์ง„๋‹ค).
    2. `exceptions` โ€” ์–ด์ ˆ์— ํฌํ•จ๋˜๋ฉด ๋ฌด์กฐ๊ฑด ๊ฑด๋„ˆ๋›ฐ๋Š” ๋ฌธ์ž์—ด ๋ชฉ๋ก (์œจ/๋ฅ ๋กœ
       ๋๋‚˜๋Š” ์ธ๋ช… '๊น€์„์œจ' ๋ฅ˜๋ฅผ ์œ„ํ•œ ํ›…. ๊ธฐ๋ณธ ๋น„์–ด ์žˆ์Œ).

    2026-09-02 ์žฌ์ƒ ์‹ค์ธก(v33/combo ์ถœ๋ ฅ ์œ„, ์กฐ์‚ฌ ๊ฐ€๋“œ ํฌํ•จ): yul-ryul ๋†“์นจ 2๊ฑด
    ์ „๋Ÿ‰ ํšŒ์ˆ˜(+3.07), ci-v2 +0.59, ci-v1 +0.53, paragraphยทci-v0 ๋ณ€๊ฒฝ 0๊ฑด.
    """
    out = list(text)
    n = len(text)
    for i, ch in enumerate(text):
        if ch not in ("์œจ", "๋ฅ "):
            continue
        prev = text[i - 1] if i > 0 else ""
        if not ("๊ฐ€" <= prev <= "ํžฃ"):
            continue
        jong = (ord(prev) - 0xAC00) % 28
        want = "์œจ" if jong in (0, 4) else "๋ฅ "  # ๋ฐ›์นจ ์—†์Œ(0)/ใ„ด(4) โ†’ ์œจ
        if want == ch:
            continue

        j = i + 1
        while j < n and not text[j].isspace():
            j += 1
        residue = "".join(c for c in text[i + 1 : j] if "๊ฐ€" <= c <= "ํžฃ")
        if residue and residue not in _YUL_RYUL_JOSA:
            continue

        if exceptions:
            k = i
            while k > 0 and not text[k - 1].isspace():
                k -= 1
            token = text[k:j]
            if any(e in token for e in exceptions):
                continue

        out[i] = want
    return "".join(out)