Spaces:
Running

File size: 46,879 Bytes
b146445
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
r"""EBSi ์ •๋‹ต ๋ฐ ํ•ด์„ค PDF -> ๋ฌธํ•ญ๋ณ„ ์ •๋‹ต + ํ•ด์„ค(LaTeX)  (3๋‹จ๊ณ„, ๋ฌด๋ฃŒ)

* ์ •๋‹ตํ‘œ(1ํŽ˜์ด์ง€ 5์นธ x 6์ค„ ๊ฒฉ์ž)๋ฅผ ์ฝ์–ด 1~21๋ฒˆ ๋ณด๊ธฐ ๋ฒˆํ˜ธ, 22~30๋ฒˆ ๋‹จ๋‹ต ์ˆซ์ž๋ฅผ ์–ป๋Š”๋‹ค.
  ๋‹จ๋‹ต ์ˆซ์ž๋Š” ์ˆ˜์‹ ๊ธ€๊ผด ์ฝ”๋“œ(๋ณ€ํ™˜ํ‘œ๋กœ ์ˆซ์žํ™”) ๋˜๋Š” ์ผ๋ฐ˜ ์ˆซ์ž. ์ •๋‹ต์ด ๋ฒˆํ˜ธ๋ณด๋‹ค ์กฐ๊ธˆ ์•„๋ž˜์ธ ์‹œํ—˜,
  ๋ฒˆํ˜ธ๋งŒ ๊ธฐ์šธ์ž„์ฒด์ธ ์‹œํ—˜, ์˜† ๋‹จ ํ•ด์„ค์ด ๊ฐ™์€ ์ค„์— ์žˆ๋Š” ์‹œํ—˜๋„ ์ฒ˜๋ฆฌํ•œ๋‹ค. (28ํšŒ ๋ชจ๋‘ 30/30 ํ™•์ธ)
  2021_11 ์˜ โ‘ ~โ‘ค ๋Š” pdfplumber ๊ฐ€ ๋ชป ์ฝ์–ด์„œ pypdfium2 ๋กœ ๋ณด์ถฉํ•œ๋‹ค (answer_source="table_pdfium").
* ํ•ด์„ค์€ "N. [์ถœ์ œ์˜๋„]" ๋กœ ์‹œ์ž‘ํ•˜๋Š” ๋ฌธํ•ญ ๋‹จ์œ„๋กœ ๋‚˜๋ˆˆ๋‹ค. (3๋‹จ ํŽธ์ง‘: ํŽ˜์ด์ง€ -> ๋‹จ -> ์œ„์—์„œ ์•„๋ž˜)
  ๊ฐ ๋ฌธํ•ญ ํ•ด์„ค์„ 12_ebsi_latex.py ์™€ ๊ฐ™์€ ๋ฐฉ์‹์œผ๋กœ LaTeX ๋กœ ๋ณต์›ํ•œ๋‹ค.
* ๊ฐ๊ด€์‹ ๋Œ€์กฐ(์ฐธ๊ณ ์šฉ): ํ•ด์„ค์€ ๋ณดํ†ต ๋ณด๊ธฐ ๋ฒˆํ˜ธ ์—†์ด ๊ฐ’์œผ๋กœ ๋๋‚˜๋ฏ€๋กœ, ํ•ด์„ค ๋งจ ๋ โ‘ ~โ‘ค ๊ฐ€ ์—†์œผ๋ฉด
  ๋งˆ์ง€๋ง‰ ์ˆ˜์‹์˜ ๋งˆ์ง€๋ง‰ '=' ๋’ค ๊ฐ’์„ 2๋‹จ๊ณ„ ๋ณด๊ธฐ(data/ebsi/latex)์™€ ๋น„๊ตํ•œ๋‹ค.
  answer_check = ok / mismatch / no_choice_in_explanation / n/a(๋‹จ๋‹ต). ์ฑ„์  ๊ธฐ์ค€์€ ํ•ญ์ƒ ์ •๋‹ตํ‘œ.

์‚ฌ์šฉ ์˜ˆ (PowerShell)
    python scripts\13_ebsi_solution.py --dir data\ebsi\h1 --out data\ebsi\solutions
    python scripts\13_ebsi_solution.py --pdf data\ebsi\h1\2022_09_hs1_solution.pdf --show 1 22
"""
from __future__ import annotations
import argparse, importlib.util, json, re, statistics, sys
from collections import Counter
from pathlib import Path

import pdfplumber
sys.path.insert(0, str(Path(__file__).resolve().parent))
import ebsi_tables as TBL

HERE = Path(__file__).resolve().parent
CIRC = "โ‘ โ‘กโ‘ขโ‘ฃโ‘ค"


def _load(name, fname):
    spec = importlib.util.spec_from_file_location(name, HERE / fname)
    m = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(m)
    return m


LX = _load("ebsi_latex", "12_ebsi_latex.py")
PUA_DIGIT = {k: v["latex"] for k, v in LX.PUA_MAP.items() if v.get("kind") == "digit" and v["latex"].isdigit()}


def isdig(c):
    t = c["text"]
    return t.isascii() and t.isdigit()


# ------------------------------------------------------------ ์ •๋‹ตํ‘œ
def _cy(c):
    return (c["top"] + c["bottom"]) / 2


def _kind(c):
    t = c["text"]
    return "circ" if t in CIRC else "asc" if isdig(c) else "pua" if f"{ord(t[0]):04X}" in PUA_DIGIT else None


def _toks_of(cs):
    """๊ธ€์ž -> ํ† ํฐ. ๊ฐ™์€ ์ค„(์ค‘์‹ฌ ์ฐจ 3pt ์ด๋‚ด)์—์„œ ๋ฐ”๋กœ ์ด์–ด์ง€๋Š” ๊ฐ™์€ ์ข…๋ฅ˜ ์ˆซ์ž๋Š” ํ•œ ๋ฉ์–ด๋ฆฌ."""
    toks = []
    for c in sorted(cs, key=lambda c: (round(_cy(c)), c["x0"])):
        k = _kind(c)
        if k is None:
            continue
        last = toks[-1] if toks else None
        prev = last["cs"][-1] if last else None
        if (last and k == last["kind"] != "circ" and abs(_cy(c) - last["cy"]) < 3
                # ๋ฒˆํ˜ธ '29' + ์ •๋‹ต '126' ๋ถ„๋ฆฌ: ๊ธ€๊ผดยทํฌ๊ธฐยท๊ธฐ์šธ์ž„(๋ฒˆํ˜ธ๋งŒ ๊ธฐ์šธ์ธ ์‹œํ—˜ ์žˆ์Œ)์ด ๊ฐ™์•„์•ผ ๋ฌถ์Œ
                and c["fontname"] == prev["fontname"] and abs(c["size"] - prev["size"]) < 0.3
                and abs(c["matrix"][2] - prev["matrix"][2]) < 0.01
                and c["x0"] > last["cs"][-1]["x0"] + 1 and c["x0"] - last["cs"][-1]["x1"] < 3):   # ๊ธ€์ž ์ƒ์ž๋Š” ๊ฒน์น  ์ˆ˜ ์žˆ์Œ
            last["cs"].append(c)
        else:
            toks.append({"kind": k, "cs": [c], "cy": _cy(c)})
    for t in toks:
        t["x0"], t["x1"] = t["cs"][0]["x0"], t["cs"][-1]["x1"]
    return toks


def _tok_value(t):
    if t["kind"] == "circ":
        return {"kind": "choice", "value": CIRC.index(t["cs"][0]["text"]) + 1}
    if t["kind"] == "pua":
        return {"kind": "integer", "value": int("".join(PUA_DIGIT[f"{ord(c['text'][0]):04X}"] for c in t["cs"]))}
    return {"kind": "integer", "value": int("".join(c["text"] for c in t["cs"]))}


# 2021_11 ์ •๋‹ตํ‘œ์˜ โ‘ ~โ‘ค๋Š” pdfminer(pdfplumber)๊ฐ€ ๊ธ€์ž๋ฅผ ์•„์˜ˆ ๋ฒ„๋ฆฌ๊ณ , pdfium ์€ ํ•œ์ž๋กœ ์ž˜๋ชป ์ฝ๋Š”๋‹ค.
# (ํ™”๋ฉด ๋ Œ๋”๋ง๊ณผ ๋Œ€์กฐํ•ด ํ™•์ธํ•œ ๋Œ€์‘. ์ฝ”๋“œ ์ˆœ์„œ๋„ โ‘ ->โ‘ค ์ˆœ)
PDFIUM_CIRC_FIX = {"ๆฆ•": "โ‘ ", "ๆถŒ": "โ‘ก", "ๆนง": "โ‘ข", "ๆบถ": "โ‘ฃ", "็†”": "โ‘ค"}


def pdfium_extra_chars(path: Path):
    """pdfplumber ๊ฐ€ ๋ชป ์ฝ์€ ์ •๋‹ตํ‘œ ๋ณด๊ธฐ ๋ฒˆํ˜ธ๋ฅผ pypdfium2(pdfplumber ์„ค์น˜ ์‹œ ํ•จ๊ป˜ ๊น”๋ฆผ)๋กœ ๋ณด์ถฉ."""
    import pypdfium2 as pdfium
    doc = pdfium.PdfDocument(str(path))
    try:
        pg = doc[0]
        H = pg.get_height()
        tp = pg.get_textpage()
        out = []
        for i in range(tp.count_chars()):
            t = tp.get_text_range(i, 1)
            if t in CIRC or t in PDFIUM_CIRC_FIX:
                l, b, r, top = tp.get_charbox(i)
                out.append({"text": PDFIUM_CIRC_FIX.get(t, t), "x0": l, "x1": r, "top": H - top, "bottom": H - b,
                            "fontname": "pdfium", "size": 0, "matrix": (0, 0, 0, 0, 0, 0), "pdfium": True})
        return out
    finally:
        doc.close()


def parse_answers(pdf: pdfplumber.PDF, extra_chars=None):
    """1ํŽ˜์ด์ง€ ์ •๋‹ตํ‘œ(5์นธ x 6์ค„, ์นธ๋งˆ๋‹ค [๋ฒˆํ˜ธ][์ •๋‹ต])๋ฅผ ๊ธ€์ž ์œ„์น˜๋กœ ์ฝ๋Š”๋‹ค.
    1) '1 2 3 4 5' ๊ฐ€ ์ฐจ๋ก€๋กœ ๋‚˜์˜ค๋Š” ์ค„์„ ์ฐพ์•„ ์นธ์˜ x ์œ„์น˜(๋ฒˆํ˜ธ ์˜ค๋ฅธ์ชฝ ๋)์™€ ๊ฐ„๊ฒฉ์„ ์–ป๋Š”๋‹ค.
    2) ํ‘œ์˜ x ๋ฒ”์œ„ ๋ฐ– ๊ธ€์ž(์˜† ๋‹จ ํ•ด์„ค)๋Š” ๋ฒ„๋ฆฐ๋‹ค.
    3) ๋ฒˆํ˜ธ ํ† ํฐ = ์นธ ์œ„์น˜์— ์˜ค๋ฅธ์ชฝ ๋์ด ๋งž๋Š” ASCII ์ˆซ์ž. ๋ฒˆํ˜ธ๋Š” 1,2,...,30 ์ˆœ์„œ๋กœ๋งŒ ๋ฐ›์•„๋“ค์ธ๋‹ค.
    4) ์ •๋‹ต = ๊ฐ™์€ ์นธ(๋ฒˆํ˜ธ ์˜ค๋ฅธ์ชฝ ~ ๋‹ค์Œ ์นธ ์‹œ์ž‘) ์•ˆ์—์„œ ์„ธ๋กœ ์ค‘์‹ฌ์ด ๊ฐ€๊นŒ์šด(9pt) ์ฒซ ํ† ํฐ.
       ์ •๋‹ต ์ค„์ด ๋ฒˆํ˜ธ ์ค„๋ณด๋‹ค ์กฐ๊ธˆ ์•„๋ž˜์— ์žˆ๋Š” ์‹œํ—˜(2021_11 ๋“ฑ)๋„ ์ค‘์‹ฌ ๊ธฐ์ค€์ด๋ผ ์žกํžŒ๋‹ค."""
    p = pdf.pages[0]
    allc = [c for c in p.chars if c["text"].strip() and _kind(c)]
    if extra_chars:   # pdfplumber ๊ธ€์ž์™€ ๊ฒน์น˜์ง€ ์•Š๋Š” ๊ฒƒ๋งŒ
        allc += [e for e in extra_chars
                 if not any(abs(c["x0"] - e["x0"]) < 2 and abs(_cy(c) - _cy(e)) < 2 for c in allc)]
    toks = _toks_of(allc)
    # 1) ๊ธฐ์ค€ ์ค„ ์ฐพ๊ธฐ
    head = None
    for t in toks:
        if t["kind"] != "asc" or "".join(c["text"] for c in t["cs"]) != "1":
            continue
        row = sorted([u for u in toks if u["kind"] == "asc" and abs(u["cy"] - t["cy"]) < 3 and u["x0"] >= t["x0"]],
                     key=lambda u: u["x0"])
        nums = ["".join(c["text"] for c in u["cs"]) for u in row]
        if nums[:5] == ["1", "2", "3", "4", "5"]:
            head = row[:5]
            break
    if head is None:
        return {}, "์ •๋‹ตํ‘œ ์œ„์น˜๋ฅผ ๋ชป ์ฐพ์Œ"
    M = [(u["x0"] + u["x1"]) / 2 for u in head]  # ๋ฒˆํ˜ธ ์นธ ๊ฐ€์šด๋ฐ (๋ฒˆํ˜ธ๋Š” ๊ฐ€์šด๋ฐ ์ •๋ ฌ)
    R = [u["x1"] for u in head]
    pitch = (M[4] - M[0]) / 4
    y0 = head[0]["cy"] - 8
    x_lo, x_hi = head[0]["x0"] - pitch * 0.4, R[4] + pitch * 0.8
    box = [t for t in toks if x_lo <= t["x0"] <= x_hi and t["cy"] >= y0]

    def col(t):   # ๋ฒˆํ˜ธ ์นธ์ด๋ฉด ์นธ ๋ฒˆํ˜ธ, ์•„๋‹ˆ๋ฉด None
        if t["kind"] != "asc":
            return None
        mid = (t["x0"] + t["x1"]) / 2
        for j, m in enumerate(M):
            if abs(mid - m) < 3.5:
                return j
        return None

    # 3) ๋ฒˆํ˜ธ ํ† ํฐ์„ ์ˆœ์„œ๋Œ€๋กœ
    numbers, want = {}, 1
    for t in sorted(box, key=lambda t: (round(t["cy"] / 4), t["x0"])):
        j = col(t)
        if j is None or want > 30:
            continue
        v = int("".join(c["text"] for c in t["cs"]))
        if v == want and j == (want - 1) % 5:
            numbers[v] = t
            want += 1
    # 4) ์ •๋‹ต ์ง์ง“๊ธฐ
    used = {id(t) for t in numbers.values()}
    ans = {}
    for n, nt in numbers.items():
        j = (n - 1) % 5
        right = R[j] + pitch - (R[0] - head[0]["x0"]) - 2   # ๋‹ค์Œ ์นธ ๋ฒˆํ˜ธ ์‹œ์ž‘ ์ง์ „
        cand = [t for t in box if id(t) not in used and nt["x1"] - 1 <= t["x0"] < right
                and abs(t["cy"] - nt["cy"]) < 9 and col(t) is None]
        if cand:
            a = min(cand, key=lambda t: (abs(t["cy"] - nt["cy"]) > 3, t["x0"]))
            ans[n] = _tok_value(a)
            ans[n]["source"] = "table_pdfium" if a["cs"][0].get("pdfium") else "table"
            used.add(id(a))
    err = None if len(numbers) == 30 else f"์ •๋‹ตํ‘œ ๋ฒˆํ˜ธ {len(numbers)}/30๊ฐœ๋งŒ ์ฐพ์Œ"
    return ans, err


# ------------------------------------------------------------ ๊ณ 3 ์„ ํƒ๊ณผ๋ชฉ ๊ตฌ๊ฐ„ (๊ต์œก์ฒญ ํ˜•์‹)
# ๊ณ 3 ํ•ด์„ค์€ ๊ณตํ†ต(1~22) ๋’ค์— [ํ™•๋ฅ ๊ณผ ํ†ต๊ณ„] [๋ฏธ์ ๋ถ„] [๊ธฐํ•˜] ๊ตฌ๊ฐ„์ด ์ฐจ๋ก€๋กœ ์žˆ๊ณ , ๊ตฌ๊ฐ„๋งˆ๋‹ค 23~30๋ฒˆ ์ •๋‹ตํ‘œ๊ฐ€ ๋”ฐ๋กœ ์žˆ๋‹ค.
# ์ด ์•ฑ์€ ํ™•๋ฅ ๊ณผ ํ†ต๊ณ„๋งŒ ์“ด๋‹ค: ํ™•ํ†ต ๊ตฌ๊ฐ„ ์ •๋‹ตํ‘œ๋กœ 23~30 ์ •๋‹ต์„ ์ฝ๊ณ , ๋ฏธ์ ๋ถ„ยท๊ธฐํ•˜ ๊ตฌ๊ฐ„๋ถ€ํ„ฐ๋Š” ํ•ด์„ค์—์„œ ๋บ€๋‹ค.
SUBJ = (("ํ™•ํ†ต", ("[ํ™•๋ฅ ๊ณผ", "ํ™•๋ฅ ๊ณผ")), ("๋ฏธ์ ๋ถ„", ("[๋ฏธ์ ๋ถ„",)), ("๊ธฐํ•˜", ("[๊ธฐํ•˜",)))
PUA_DIG_CH = {chr(int(k, 16)): v for k, v in PUA_DIGIT.items()}     # ์ˆ˜์‹ ๊ธ€๊ผด ์ˆซ์ž ๊ธ€์ž -> '0'~'9'
PUA_DIG_CH |= {chr(0x24F5 + i): CIRC[i] for i in range(5)}   # โ“ต~โ“น(์ด์ค‘ ์› ์ˆซ์ž, 2024_06 ๊ณ 3 ์ •๋‹ตํ‘œ) -> โ‘ ~โ‘ค


def section_headers(pdf):
    """์„ ํƒ๊ณผ๋ชฉ ๊ตฌ๊ฐ„ ๋จธ๋ฆฌ ์œ„์น˜. '[ํ™•๋ฅ ๊ณผ ํ†ต๊ณ„]'(3ยท4ยท5ยท10์›”) ๋˜๋Š” 'ํ™•๋ฅ ๊ณผ ํ†ต๊ณ„ ์ •๋‹ต'(7์›”).
    ๋ฏธ์ ๋ถ„ยท๊ธฐํ•˜๋Š” '[๋ฏธ์ ๋ถ„]' '[๊ธฐํ•˜]' ๋˜๋Š” '๋ฏธ์ ๋ถ„ ์ •๋‹ต' '๊ธฐํ•˜ ์ •๋‹ต'."""
    out = []
    for pi, p in enumerate(pdf.pages):
        ws = p.extract_words()
        for j, w in enumerate(ws):
            t = w["text"]
            nxt = " ".join(x["text"] for x in ws[j + 1:j + 3])
            name = None
            if t.startswith("[์„ ํƒ"):                 # ํ‰๊ฐ€์› ํ˜•์‹ '[์„ ํƒ: ํ™•๋ฅ ๊ณผ ํ†ต๊ณ„]' '[์„ ํƒ: ๋ฏธ์ ๋ถ„]' '[์„ ํƒ: ๊ธฐํ•˜]'
                t = "[" + nxt.split()[0] if nxt else t
            if t.startswith("[ํ™•๋ฅ ๊ณผ") or (t == "ํ™•๋ฅ ๊ณผ" and nxt.startswith("ํ†ต๊ณ„")):
                name = "ํ™•ํ†ต"
            elif t.startswith("[๋ฏธ์ ๋ถ„") or (t == "๋ฏธ์ ๋ถ„" and nxt.startswith("์ •๋‹ต")):
                name = "๋ฏธ์ ๋ถ„"
            elif t.startswith("[๊ธฐํ•˜") or (t == "๊ธฐํ•˜" and nxt.startswith("์ •๋‹ต")):
                name = "๊ธฐํ•˜"
            if name and not any(h["name"] == name for h in out):
                out.append({"name": name, "page": pi, "x": w["x0"], "x1": w["x1"], "top": w["top"]})
    return out


def select_of(pdf, exam: str):
    """๊ณ 3 ํ•ด์„ค์˜ ์„ ํƒ๊ณผ๋ชฉ ๊ตฌ๊ฐ„ ์ •๋ณด: {"skip": ํ™•ํ†ต ๋จธ๋ฆฌ, "cut": ๋‹ค์Œ ์„ ํƒ๊ณผ๋ชฉ ๋จธ๋ฆฌ} (์—†์œผ๋ฉด None). 13ยท14 ๊ฐ€ ๊ฐ™์ด ์”€."""
    if not exam.endswith("_hs3"):
        return None
    hd = {h["name"]: h for h in section_headers(pdf)}
    if "ํ™•ํ†ต" not in hd:
        return None
    t = hd["ํ™•ํ†ต"]
    later = [h for k, h in hd.items() if k != "ํ™•ํ†ต" and (h["page"], h["x"], h["top"]) > (t["page"], t["x"], t["top"])]
    return {"skip": t, "cut": min(later, key=lambda h: (h["page"], h["x"], h["top"])) if later else None}


def parse_select_answers(pdf, hdr):
    """ํ™•ํ†ต ๋จธ๋ฆฌ ์•„๋ž˜ ์ •๋‹ตํ‘œ '23 โ‘ข 24 โ‘ฃ โ€ฆ 29 55 30 97' (์ˆซ์ž๊ฐ€ ์ˆ˜์‹ ๊ธ€๊ผด ์ „์šฉ ์ฝ”๋“œ์ผ ์ˆ˜ ์žˆ์Œ, '29288' ์ฒ˜๋Ÿผ ๋ถ™๊ธฐ๋„ ํ•จ)."""
    p = pdf.pages[hdr["page"]]
    cx = (hdr["x"] + hdr["x1"]) / 2
    ws = [w for w in p.extract_words() if hdr["top"] + 3 < w["top"] < hdr["top"] + 60 and abs((w["x0"] + w["x1"]) / 2 - cx) < 190]
    return pair_answers(ws, r"(2[3-9]|30)\.?", range(23, 31), "table_select")


def pair_answers(ws, num_pat, wanted, source, max_gap=60):
    """๋ฒˆํ˜ธ ๋‹จ์–ด(num_pat) ์™€ ๊ฐ™์€ ์ค„ ์˜ค๋ฅธ์ชฝ ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ๊ฐ’(โ‘ ~โ‘ค ๋˜๋Š” ์ˆซ์ž)์„ ์ง์ง“๋Š”๋‹ค.
    '29288' '01.โ‘ก' ์ฒ˜๋Ÿผ ๋ฒˆํ˜ธ์™€ ๊ฐ’์ด ํ•œ ๋‹จ์–ด์ธ ๊ฒƒ๋„ ๋ฐ›๋Š”๋‹ค. ๊ฐ’์ด ์—†๋Š” ๋ฒˆํ˜ธ ๋‹จ์–ด(๋ฌธํ•ญ ์‹œ์ž‘ '28. [์ถœ์ œ์˜๋„]')๋Š” ๋ฌด์‹œ.
    ๊ฐ™์€ ๋ฒˆํ˜ธ๊ฐ€ ์—ฌ๋Ÿฟ์ด๋ฉด ๊ฐ’์ด ์žˆ๋Š” ๊ฒƒ ์ค‘ ์œ„์ชฝ ์ฒซ ๊ฒƒ."""
    # ์ค„(์„ธ๋กœ 4pt ์•ˆ) ๋‹จ์œ„๋กœ ์™ผ์ชฝ๋ถ€ํ„ฐ ์ฝ์œผ๋ฉฐ '๋ฒˆํ˜ธ โ†’ ๊ฐ’' ์„ ์ฐจ๋ก€๋กœ ๋ฐ›๋Š”๋‹ค. ๋ฒˆํ˜ธ๋Š” wanted ์ˆœ์„œ๋Œ€๋กœ๋งŒ.
    # (๊ฐ’ '25' ๊ฐ€ ๋ฒˆํ˜ธ์ฒ˜๋Ÿผ ๋ณด์—ฌ๋„ ์ˆœ์„œ์ƒ ๊ฐ’ ์ž๋ฆฌ์ด๋ฉด ๊ฐ’: 2021_07 '29 25 30 51')
    toks = []
    for w in ws:
        w["t"] = "".join(PUA_DIG_CH.get(ch, ch) for ch in w["text"])
        if re.fullmatch(r"[โ‘ โ‘กโ‘ขโ‘ฃโ‘ค]|\d+\.?(?:[โ‘ โ‘กโ‘ขโ‘ฃโ‘ค]|\d+)?", w["t"]):
            toks.append(w)
    toks.sort(key=lambda w: w["top"])
    lines = []
    for w in toks:
        if lines and abs(w["top"] - lines[-1][0]["top"]) < 4:
            lines[-1].append(w)
        else:
            lines.append([w])
    order = list(wanted)
    ans, k, pend = {}, 0, None
    for line in lines:
        pend = None
        for w in sorted(line, key=lambda w: w["x0"]):
            if pend is not None:                      # ๊ฐ’ ์ž๋ฆฌ
                pn, px = pend
                pend = None
                if re.fullmatch(r"[โ‘ โ‘กโ‘ขโ‘ฃโ‘ค]|\d+", w["t"]) and w["x0"] < px + max_gap:
                    v = w["t"]
                    ans[pn] = ({"kind": "choice", "value": CIRC.index(v) + 1} if v in CIRC
                               else {"kind": "integer", "value": int(v)}) | {"source": source}
                    k += 1
                    continue
                k += 1                                # ๊ฐ’์ด ๊ธ€์ž๋กœ ์•ˆ ๋‚˜์˜จ ์นธ(โ‘ ~โ‘ค ๋ˆ„๋ฝ): ๊ฑด๋„ˆ๋›ฐ๊ณ  ์ด ๋‹จ์–ด๋ฅผ ๋ฒˆํ˜ธ๋กœ ๋‹ค์‹œ ๋ด„
            if k >= len(order):
                break
            m = re.fullmatch(num_pat + r"([โ‘ โ‘กโ‘ขโ‘ฃโ‘ค]|\d*)", w["t"])
            if not m or int(m.group(1)) != order[k]:
                continue
            if m.group(2):                            # '29288' '01.โ‘ก'
                v = m.group(2)
                ans[order[k]] = ({"kind": "choice", "value": CIRC.index(v) + 1} if v in CIRC
                                 else {"kind": "integer", "value": int(v)}) | {"source": source}
                k += 1
            else:
                pend = (order[k], w["x1"])
    return ans


def pdfium_list_answers(path: Path, wanted):
    """pdfplumber ๊ฐ€ โ‘ ~โ‘ค๋ฅผ ๋ชป ์ฝ๋Š” ํ•ด์„ค(2024_06 ๊ณ 3 ๋“ฑ): pdfium ๊ธ€์ž๋กœ 'NN. โ‘ฃ' ๋ชฉ๋ก์„ ๋‹ค์‹œ ์ฝ๋Š”๋‹ค.
    ๋ฒˆํ˜ธ๊ฐ€ ์ฐจ๋ก€๋กœ(1์”ฉ ์ฆ๊ฐ€) ์ด์–ด์ง€๋Š” ๊ตฌ๊ฐ„๋งŒ ๋ฐ›๋Š”๋‹ค(๋ณธ๋ฌธ ์† '23. ์ถœ์ œ์˜๋„' ๋“ฑ ์˜ค์ธ ๋ฐฉ์ง€)."""
    import pypdfium2 as pdfium
    doc = pdfium.PdfDocument(str(path))
    lo = min(wanted)
    for i in range(len(doc)):
        t = "".join(PUA_DIG_CH.get(ch, ch) for ch in doc[i].get_textpage().get_text_range())
        found = {}
        for m in re.finditer(r"(?<!\d)(\d{2})\.\s*([โ‘ โ‘กโ‘ขโ‘ฃโ‘ค]|\d+)", t):
            n = int(m.group(1))
            if n in wanted and n not in found and (n == lo or n - 1 in found):
                v = m.group(2)
                found[n] = ({"kind": "choice", "value": CIRC.index(v) + 1} if v in CIRC else {"kind": "integer", "value": int(v)}) \
                    | {"source": "table_pdfium"}
        if len(found) >= len(wanted) - 1:
            return found
    return {}


def parse_list_answers(pdf):
    """ํ‰๊ฐ€์› ํ˜•์‹ 1์ชฝ ์ •๋‹ต ๋ชฉ๋ก '01. โ‘ฃ 02. โ‘ค โ€ฆ 16. 2 โ€ฆ 22. 61' (01~22). ๋ฒˆํ˜ธ ๋‹จ์–ด ์˜ค๋ฅธ์ชฝ ๊ฐ™์€ ์ค„์˜ ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ๊ฐ’.
    '01.โ‘ก' ์ฒ˜๋Ÿผ ๋ถ™์€ ๋‹จ์–ด๋„ ๋ฐ›๋Š”๋‹ค. ๋ฌธํ•ญ ์‹œ์ž‘ '16. ์ถœ์ œ์˜๋„' ๋Š” ๊ฐ’์ด ์•„๋‹ˆ์–ด์„œ ๊ฑธ๋ฆฌ์ง€ ์•Š์Œ."""
    return pair_answers(pdf.pages[0].extract_words(), r"(\d{2})\.", range(1, 23), "table_list", max_gap=30)


# ------------------------------------------------------------ ํ•ด์„ค ๋‚˜๋ˆ„๊ธฐ
START = re.compile(r"(\d{1,2})\.(?:\[์ถœ์ œ|์ถœ์ œ์˜๋„)")   # ํ‰๊ฐ€์› ๊ณ 3 ํ•ด์„ค์€ 'N. ์ถœ์ œ์˜๋„ :'


def _lines(chars, tol=1.5):
    """๊ณต๋ฐฑ ์•„๋‹Œ ๊ธ€์ž๋ฅผ ๊ฐ™์€ top(ยฑtol)๋ผ๋ฆฌ ์ค„๋กœ ๋ฌถ๋Š”๋‹ค. ์ค„ ์•ˆ์€ x ์ˆœ์„œ."""
    cs = sorted((c for c in chars if c["text"].strip()), key=lambda c: (c["top"], c["x0"]))
    lines = []
    for c in cs:
        if lines and abs(c["top"] - lines[-1][0]["top"]) <= tol:
            lines[-1].append(c)
        else:
            lines.append([c])
    return [sorted(l, key=lambda c: c["x0"]) for l in lines]


WORD_NUM = re.compile(r"^\d{1,2}\.$")


def find_starts(pdf):
    """'N. [์ถœ์ œ์˜๋„]' ํ‘œ์ง€ ์ฐพ๊ธฐ. ๋‘ ๋ฐฉ์‹์„ ํ•ฉ์นœ๋‹ค.
    1) ๋‹จ์–ด ๋ฐฉ์‹: '7.' ๋‹ค์Œ ๋‹จ์–ด๊ฐ€ '[์ถœ์ œโ€ฆ' (๊ธ€๊ผด์ด ๋‹ฌ๋ผ top ์ด 1.5pt ๋„˜๊ฒŒ ์–ด๊ธ‹๋‚˜๋„ ๋จ)
    2) ๊ธ€์ž ๋ฐฉ์‹: ๊ฐ™์€ top ์˜ ๊ธ€์ž๋งŒ ์ด์–ด 'N.[์ถœ์ œ'. extract_words ๊ฐ€ ๋จธ๋ฆฌ์ค„๊ณผ ๋ฐ”๋กœ ์•„๋žซ์ค„์„
       ์„ž์–ด ๋ฒ„๋ฆฌ๋Š” ๊ฒฝ์šฐ(2024_10 5๋ฒˆ: '5. ์ฃผ[์ถœ์–ด์ œ์ง„์˜...')๋ฅผ ์žก๋Š”๋‹ค.
    ๋‹จ์–ด ๋ฐฉ์‹ ๊ฒฐ๊ณผ๋ฅผ ์šฐ์„ ํ•˜๊ณ , ๊ฑฐ๊ธฐ์„œ ๋น ์ง„ ๋ฒˆํ˜ธ๋งŒ ๊ธ€์ž ๋ฐฉ์‹์œผ๋กœ ๋ณด์ถฉ."""
    found = {}
    for pi, p in enumerate(pdf.pages):
        ws = p.extract_words()
        for j, w in enumerate(ws[:-1]):
            if WORD_NUM.match(w["text"]) and ws[j + 1]["text"].startswith(("[์ถœ์ œ", "์ถœ์ œ์˜๋„")) and abs(ws[j + 1]["top"] - w["top"]) < 3:
                found.setdefault(int(w["text"][:-1]), {"page": pi, "x": w["x0"], "top": w["top"], "n": int(w["text"][:-1])})
    for s in _find_starts_chars(pdf):
        found.setdefault(s["n"], s)
    return list(found.values())


def _find_starts_chars(pdf):
    out = []
    for pi, p in enumerate(pdf.pages):
        for line in _lines(p.chars):
            s = "".join(c["text"] for c in line)
            for m in START.finditer(s):
                c0 = line[m.start(1)]
                if m.start(1) > 0 and line[m.start(1) - 1]["text"].isdigit():
                    continue            # '123.[์ถœ์ œ' ๊ฐ™์€ ์˜ค์ธ ๋ฐฉ์ง€
                out.append({"page": pi, "x": c0["x0"], "top": c0["top"], "n": int(m.group(1))})
    return out


def header_bottom(p, default=None):
    """ํŽ˜์ด์ง€ ๋จธ๋ฆฌ๋ง์˜ ์•„๋ž˜ ๋. ๋จธ๋ฆฌ๋ง = '์ •๋‹ต ๋ฐ ํ•ด์„ค' ์ค„ + ๊ทธ ์•„๋ž˜ 25pt ์•ˆ์˜ 'โ€ฆํ•™๋ ฅํ‰๊ฐ€' ์ค„.
    (1ํŽ˜์ด์ง€ ๋ณธ๋ฌธ ์•ˆ๋‚ด๋ฌธ 'โ€ป ๋ณธ ์ „๊ตญ์—ฐํ•ฉํ•™๋ ฅํ‰๊ฐ€๋Š”โ€ฆ' ์€ ๋จธ๋ฆฌ๋ง์ด ์•„๋‹˜) ๋ชป ์ฐพ์œผ๋ฉด ๊ธฐ๋ณธ๊ฐ’.
    ๊ธฐ๋ณธ๊ฐ’: A3(๊ฐ€๋กœ 841) 152, A4(๊ฐ€๋กœ 595) 115 โ€” A4 ๋ณธ๋ฌธ์€ 120 ๋ถ€ํ„ฐ๋ผ 152 ๋กœ ์ž๋ฅด๋ฉด ๋‹จ๋งˆ๋‹ค ์ฒซ 2~3์ค„์ด
    ์‚ฌ๋ผ์กŒ์Œ (2020_11 ํ•ด์„ค 18๋ฒˆ '์  P์˜ ์ขŒํ‘œ๋Š” (2/3,4)โ€ฆ', 20๋ฒˆ ๋จธ๋ฆฌ ์ค„; 2021_03ยท2022_11ยท2024_10 ๋„ ๊ฐ™์Œ)."""
    if default is None:
        default = 152 if p.width > 700 else 115
    lines = [(l, "".join(c["text"] for c in l)) for l in _lines([c for c in p.chars if c["top"] < 170], tol=3)]
    title = [l for l, s in lines if "์ •๋‹ต๋ฐํ•ด์„ค" in s]
    if not title:
        # ์ œ๋ชฉ ์ค„์ด ์—†๋Š” ์ชฝ: ๋จธ๋ฆฌ๋ง ์•„๋ž˜ ๊ฐ€๋กœ ๊ตฌ๋ถ„์„ (์ชฝ ๋„ˆ๋น„ 60% ์ด์ƒ, 130pt ์œ„)์ด ์žˆ์œผ๋ฉด ๊ทธ ๋ฐ”๋กœ ์•„๋ž˜๋ถ€ํ„ฐ ๋ณธ๋ฌธ.
        # (2021_06_hs3 ํ•ด์„ค: 2์ชฝ๋ถ€ํ„ฐ ์„ ์ด 85pt, ๋ณธ๋ฌธ ์ฒซ ์ค„์ด 99pt ๋ผ 115 ๋กœ ์ž๋ฅด๋ฉด ๋‹จ๋งˆ๋‹ค ์ฒซ ์ค„์ด ์‚ฌ๋ผ์กŒ์Œ
        #  โ€” 5๋ฒˆ g'(1)=โ€ฆ, 11ยท13ยท15๋ฒˆ ๋จธ๋ฆฌ ์ค„)
        rules = [l["top"] for l in p.lines if l["top"] < 130 and (l["x1"] - l["x0"]) > p.width * 0.6]
        if rules:
            return min(default, max(rules) + 2)
        # ์ œ๋ชฉ ์ค„๋„ ๊ตฌ๋ถ„์„ ๋„ ์—†๋Š” A4 ์ชฝ: ๋ณธ๋ฌธ ์ฒซ ์ค„์ด 99pt ๋ถ€๊ทผ์ด๋ผ 115 ๋กœ ์ž๋ฅด๋ฉด ๋‹จ๋งˆ๋‹ค ์ฒซ ์ค„์ด ์‚ฌ๋ผ์กŒ์Œ
        # (2025_05_hs3 15ยท21ยท27ยท30๋ฒˆ ๋จธ๋ฆฌ ์ค„, 2025_06ยท2025_09 3๋ฒˆ ๋จธ๋ฆฌ, 2022_09ยท2024_09 ์ฒซ ์ค„ ๋“ฑ).
        # 85 ์œ„์—๋Š” ์‹œํ—˜ ์ œ๋ชฉ๋งŒ ์žˆ๊ณ , 85~115 ์˜ '์ตœ๊ทผ ์ˆ˜์ •์ผ'ยท'โ–  [๊ณตํ†ตโ€ฆ]' ๊ฐ™์€ ๋จธ๋ฆฌ ๊ธ€์€ ์ฒซ ๋ฌธํ•ญ๋ณด๋‹ค ์•ž์ด๋ผ ๋ฒ„๋ ค์ง.
        if p.width <= 700:
            return 85
        return default
    t0 = min(c["top"] for c in title[0])
    bot = max(max(c["bottom"] for c in l) for l, s in lines
              if ("์ •๋‹ต๋ฐํ•ด์„ค" in s or "ํ•™๋ ฅํ‰๊ฐ€" in s) and min(c["top"] for c in l) < t0 + 25)
    return bot + 2


def column_lefts(starts):
    xs = sorted(s["x"] for s in starts)
    cols = []
    for x in xs:
        if cols and abs(x - cols[-1][-1]) < 12:
            cols[-1].append(x)
        else:
            cols.append([x])
    return [min(c) for c in cols]


def col_of(x, lefts):
    k = 0
    for i, l in enumerate(lefts):
        if x >= l - 6:
            k = i
    return k


def _in_any(cx, cy, boxes, pad=0.5):
    return any(b[0] + pad <= cx <= b[2] - pad and b[1] + pad <= cy <= b[3] - pad for b in boxes)


def split_solutions(pdf, drop_figure_labels: bool = True, select=None):
    """drop_figure_labels: ๊ทธ๋ฆผ(์ด๋ฏธ์ง€) ์œ„์— ๊ฒน์ณ ์“ด ๋ผ๋ฒจ ๊ธ€์ž(๊ผญ์ง“์  A, ์ถ• xยทy, ์› ์•ˆ์˜ ์‹ ๋“ฑ)๋Š” ๋ณธ๋ฌธ์—์„œ ๋บ€๋‹ค.
    (2020_06 ํ•ด์„ค 6๋ฒˆ: ์ด๋ฏธ์ง€ ๋‘ ์žฅ ์œ„์— '-2xยฒ, xยณ+1, A, D' ๋ผ๋ฒจ์ด ๊ธ€์ž๋กœ ์˜ฌ๋ผ๊ฐ€ ๋ณธ๋ฌธ ์•ž์— ์„ž์˜€์Œ)
    ํ™”๋ฉด ๋Œ€์กฐ์šฉ ์ž˜๋ผ๋‚ด๊ธฐ(14_ebsi_review.py)๋Š” ๊ทธ๋ฆผ ๋ฒ”์œ„๋ฅผ ๋ณด๋ ค๊ณ  False ๋กœ ๋ถ€๋ฅธ๋‹ค."""
    starts = find_starts(pdf)
    if not starts:
        return {}, "ํ•ด์„ค ์‹œ์ž‘ ํ‘œ์ง€๋ฅผ ๋ชป ์ฐพ์Œ"
    lefts = column_lefts(starts)
    for s in starts:
        s["col"] = col_of(s["x"], lefts)
    # ๊ณ 3 ์„ ํƒ๊ณผ๋ชฉ: select = {"skip": ํ™•ํ†ต ๋จธ๋ฆฌ(์ •๋‹ตํ‘œ ๊ตฌ์—ญ), "cut": ๋ฏธ์ ๋ถ„/๊ธฐํ•˜ ๋จธ๋ฆฌ(์—ฌ๊ธฐ๋ถ€ํ„ฐ ํ•ด์„ค์—์„œ ๋บŒ)}
    select = select or {}
    cut = select.get("cut")
    cut_key = (cut["page"], col_of(cut["x"], lefts), cut["top"] - 2) if cut else None
    skip = select.get("skip")
    if cut_key:
        starts = [s for s in starts if (s["page"], s["col"], s["top"]) < cut_key]
    skip_zone = None
    if skip:
        sc = col_of(skip["x"], lefts)
        below = [s["top"] for s in starts if s["page"] == skip["page"] and s["col"] == sc and s["top"] > skip["top"]]
        skip_zone = (skip["page"], sc, skip["top"] - 2, min(below) - 2 if below else skip["top"] + 60)
    starts.sort(key=lambda s: (s["page"], s["col"], s["top"]))
    out: dict[int, dict] = {s["n"]: {"segs": {}} for s in starts}
    for pi, p in enumerate(pdf.pages):
        body_bot = p.height * 0.91
        # ์ชฝ ๋ฒˆํ˜ธ(์•„๋ž˜์ชฝ ๊ฐ€์šด๋ฐ์˜ ํฐ ์ˆซ์ž, 13pt ์ด์ƒ)๊ฐ€ 91% ์„ ๋ณด๋‹ค ์œ„์— ์žˆ์œผ๋ฉด ๊ทธ ์œ„๊นŒ์ง€๋งŒ ๋ณธ๋ฌธ.
        # (A4 ํŒ ์ชฝ ๋ฒˆํ˜ธ๋Š” 753pt ์— ์žˆ์–ด ๋ณธ๋ฌธ 'โ€ฆ์ •๋ฆฌํ•˜๋ฉด y=โ€ฆ์ด๋‹ค. 1 ์ด๋ฅผ ใ‰ก์—โ€ฆ' ์ฒ˜๋Ÿผ ์„ž์˜€์Œ: 2021_06 ํ•ด์„ค 13๋ฒˆ)
        pn = [c for c in p.chars if c["text"].isdigit() and c["top"] > p.height * 0.85 and c["size"] >= 13
              and abs((c["x0"] + c["x1"]) / 2 - p.width / 2) < 40]
        if pn:
            body_bot = min(body_bot, min(c["top"] for c in pn) - 1)
        head = header_bottom(p)
        pst = [s for s in starts if s["page"] == pi]
        figs = []
        if drop_figure_labels:
            for im in p.images:
                box = (im["x0"], im["top"], im["x1"], im["bottom"])
                # ์ด๋ฏธ์ง€ ์•ˆ์— ํ•œ๊ธ€์ด 4์ž ์ด์ƒ์ด๋ฉด ๋ณธ๋ฌธ ์œ„์— ๊ฑธ์นœ ์ด๋ฏธ์ง€(๋ฐฐ๊ฒฝยท์ƒ์ž)๋กœ ๋ณด๊ณ  ๊ฑด๋“œ๋ฆฌ์ง€ ์•Š์Œ.
                # (2020_03 12๋ฒˆ ๋ณธ๋ฌธ, 14๋ฒˆ ๋ฌธํ•ญ ๋ฒˆํ˜ธ๊ฐ€ ์ง€์›Œ์กŒ๋˜ ๋ฌธ์ œ) ๊ทธ๋ฆผ ๋ผ๋ฒจ์€ ๊ฑฐ์˜ ํ•œ๊ธ€์ด ์•„๋‹˜.
                hang = sum(1 for c in p.chars if _hangul(c["text"])
                           and _in_any((c["x0"] + c["x1"]) / 2, (c["top"] + c["bottom"]) / 2, [box]))
                if hang < 4:
                    # ์˜์—ญ์„ ๋„“ํžˆ์ง€ ์•Š์Œ: 8pt ๋„“ํžˆ๋ฉด ๊ทธ๋ฆผ ์˜† ๋ณธ๋ฌธ์˜ ์ฒจ์žยท๋ถ„์ž๊นŒ์ง€ ์ง€์›Œ์กŒ์Œ(2024_09 9ยท17ยท21๋ฒˆ).
                    # ๊ฒฝ๊ณ„์— ๊ฑธ์นœ ๋ผ๋ฒจ ์กฐ๊ฐ(') )' ๋“ฑ)์€ ํ™”๋ฉด ๋Œ€์กฐ์—์„œ ์ฒ˜๋ฆฌ.
                    figs.append(box)
        hrows: dict[int, list[float]] = {}      # ๋‹จ๋ณ„ ํ•œ๊ธ€ ๊ธ€์ž ๋†’์ด (์˜† ๋‹จ ์ค„์€ ๋ณด์ง€ ์•Š์Œ)
        if figs:
            for c in p.chars:
                if _hangul(c["text"]):
                    hrows.setdefault(col_of(c["x0"], lefts), []).append((c["top"] + c["bottom"]) / 2)
            for v in hrows.values():
                v.sort()

        def hangul_row(cy, col, tol=2):
            import bisect
            rows = hrows.get(col, [])
            i = bisect.bisect_left(rows, cy - tol)
            return i < len(rows) and rows[i] <= cy + tol

        def in_fig_band(c, cy, col):
            """๊ทธ๋ฆผ๊ณผ ๊ฐ™์€ ๋†’์ด ๋ฒ”์œ„(๊ฐ™์€ ๋‹จ)์— ์žˆ๋Š” ๋ผ๋ฒจ: ๊ทธ๋ฆผ ์œ„ 'y=g(x)', ์˜† 'A' ์ฒ˜๋Ÿผ ์ด๋ฏธ์ง€ ์ƒ์ž ๋ฐ–์— ๋ถ™์€ ๊ฒƒ.
            ๋ณธ๋ฌธ ๋ณดํ˜ธ: ํ•œ๊ธ€ ์ค„ ยฑ7pt(์ฒจ์žยท๋ถ„์žยท๋ถ„๋ชจ ๋†’์ด) ์•ˆ์˜ ๊ธ€์ž๋Š” ์ œ์™ธํ•˜์ง€ ์•Š์Œ."""
            cx = (c["x0"] + c["x1"]) / 2
            for b in figs:
                # ๊ทธ๋ฆผ์˜ ๋‹จ์€ ๊ฐ€์šด๋ฐ x ๋กœ ํŒ์ • (์™ผ์ชฝ ๋์œผ๋กœ ํ•˜๋ฉด ์˜† ๋‹จ ๊ฒฝ๊ณ„์— ๊ฑธ์นœ ๊ทธ๋ฆผ์ด ์ด ๋‹จ ๊ฒƒ์œผ๋กœ ์žกํ˜€
                # ๊ทธ ๋†’์ด์˜ ์ˆ˜์‹ ์ค„์ด ๋ผ๋ฒจ๋กœ ์ง€์›Œ์กŒ์Œ: 2022_07_hs3 11๋ฒˆ 'b-a=4 โ‹ฏใ‰ ', 20๋ฒˆ ๋ ๊ณ„์‚ฐ)
                if b[1] <= cy <= b[3] and col_of((b[0] + b[2]) / 2, lefts) == col and not hangul_row(cy, col, 7):
                    return True
            return False
        for c in p.chars:
            if not c["text"].strip():
                continue
            cy = (c["top"] + c["bottom"]) / 2
            if cy > body_bot or cy < head:
                continue
            col = col_of(c["x0"], lefts)
            if cut_key and (pi, col, cy) >= cut_key:
                continue        # ๋ฏธ์ ๋ถ„ยท๊ธฐํ•˜ ๊ตฌ๊ฐ„
            if skip_zone and pi == skip_zone[0] and col == skip_zone[1] and skip_zone[2] <= cy < skip_zone[3]:
                continue        # ํ™•ํ†ต ๋จธ๋ฆฌยท์ •๋‹ตํ‘œ
            if figs and ((_in_any((c["x0"] + c["x1"]) / 2, cy, figs) and not hangul_row(cy, col))
                         or in_fig_band(c, cy, col)):
                continue        # ๊ทธ๋ฆผ ๋ผ๋ฒจ (๊ฐ™์€ ๋‹จยท๊ฐ™์€ ๋†’์ด์— ํ•œ๊ธ€์ด ์žˆ์œผ๋ฉด ๋ณธ๋ฌธ ์ค„์ด๋ผ ๋‚จ๊น€: 2023_06 27๋ฒˆ 'โ‘  nโ‰ค5์ธ ๊ฒฝ์šฐ')
            same = [s for s in pst if s["col"] == col and s["top"] <= cy + 6]
            if same:
                owner = same[-1]
            else:
                prev = [s for s in starts if (s["page"], s["col"]) < (pi, col)]
                if not prev:
                    continue            # ์ฒซ ๋ฌธํ•ญ๋ณด๋‹ค ์•ž(์ •๋‹ตํ‘œ ๋“ฑ)
                owner = prev[-1]
            # ๋ฌธํ•ญ ๋ฒˆํ˜ธ ๊ธ€์ž ์ž์ฒด๋Š” ์ œ์™ธ
            out[owner["n"]]["segs"].setdefault((pi, col), []).append(c)
    return out, None


def _hangul(ch: str) -> bool:
    return bool(ch) and "๊ฐ€" <= ch <= "ํžฃ"


def render_solution(segs, ctx):
    """๋‹จ/ํŽ˜์ด์ง€ ์กฐ๊ฐ์„ ์ด์–ด ๋ถ™์ธ๋‹ค. ์กฐ๊ฐ ๊ฒฝ๊ณ„(๋‹จ ๋ = ๊ฝ‰ ์ฐฌ ์ค„)๋„ ํ•œ๊ธ€-ํ•œ๊ธ€์ด๋ฉด ์ค„๋ฐ”๊ฟˆ ํ‘œ์ง€."""
    out = ""
    for key in sorted(segs):
        t = LX.render_question(segs[key], ctx, mark_breaks=True)
        if not t:
            continue
        if out:
            out += LX.LINE_BREAK if (_hangul(out[-1]) and _hangul(t[0])) else " "
        out += t
    return out


# ------------------------------------------------------------ ์ค„๋ฐ”๊ฟˆ ์ž๋ฆฌ: ๋ถ™์ผ๊นŒ, ๋„์šธ๊นŒ
# ๋ถ™์ธ ํ˜•ํƒœ๊ฐ€ ์ž๋ฃŒ์— ์—†์„ ๋•Œ๋งŒ ์“ฐ๋Š” '๋’ท์กฐ๊ฐ์ด ์กฐ์‚ฌยท์–ด๋ฏธ๋ฟ' ๋ชฉ๋ก.
# 'ํ•˜๋ฉด/ํ•˜๊ณ /ํ•˜์—ฌ' ๋Š” ๋„ฃ์ง€ ์•Š์Œ: '~๋ผ ํ•˜๋ฉด', '~์•ผ ํ•˜๊ณ ' ์ฒ˜๋Ÿผ ๋„์–ด ์“ฐ๋Š” ๊ฒฝ์šฐ๊ฐ€ ํ”ํ•จ.
JOSA = {"์„", "๋ฅผ", "์ด", "๊ฐ€", "์€", "๋Š”", "์˜", "์—", "๋„", "์™€", "๊ณผ", "๋กœ", "์œผ๋กœ", "์—์„œ", "์ด๋‹ค", "๋‹ค",
        "์ด๊ณ ", "์ด๋ฏ€๋กœ", "๋ฏ€๋กœ", "์ด๋ฉด", "๋ฉด", "๋ถ€ํ„ฐ", "๊นŒ์ง€", "๋งŒ", "๊ณ ", "๋ฉฐ", "๋ผ", "์ด๋ผ"}
UNITS = ("๊ฐ€์ง€", "๊ฐœ", "๋ฐฐ", "๋ฒˆ", "๋ช…", "์งธ", "๋งŒํผ", "์‹œ๊ฐ„", "๋“ฑ๋ถ„", "์ž๋ฆฌ", "์žฅ", "ํšŒ", "์ธต", "cm", "m")
_PUNCT = ".,)]}ยทโ€ฆ:;!?'\""


def _strip(w: str) -> str:
    return w.rstrip(_PUNCT)


def word_counts(texts):
    """์ค„ ์•ˆ์ชฝ(์ค„๋ฐ”๊ฟˆ ํ‘œ์ง€๊ฐ€ ์—†๋Š”) ์–ด์ ˆ ๋นˆ๋„. ๋ ๋ฌธ์žฅ๋ถ€ํ˜ธ๋ฅผ ๋—€ ํ˜•ํƒœ๋„ ํ•จ๊ป˜ ์„ผ๋‹ค."""
    c = Counter()
    for t in texts:
        for w in t.split(" "):
            if not w or LX.LINE_BREAK in w:
                continue
            c[w] += 1
            s = _strip(w)
            if s != w:
                c[s] += 1
    return c


def resolve_breaks(text: str, counts: Counter) -> str:
    """'์•ž์–ด์ ˆ<ํ‘œ์ง€>๋’ท์–ด์ ˆ' -> ๋ถ™์ธ ํ˜•ํƒœ๊ฐ€ ์ž๋ฃŒ์— ์žˆ๊ณ  ๋’ท์กฐ๊ฐ๋ณด๋‹ค ํ”ํ•˜๋ฉด ๋ถ™์ž„, ์•„๋‹ˆ๋ฉด ๊ณต๋ฐฑ.
    ๋ถ™์ธ ํ˜•ํƒœ๊ฐ€ ์ž๋ฃŒ์— ์—†์„ ๋•Œ๋Š” ๋’ท์กฐ๊ฐ์ด ์กฐ์‚ฌยท์–ด๋ฏธ๋ฟ์ด๋ฉด ๋ถ™์ž„."""
    def decide(m):
        a, b = m.group(1), m.group(2)
        a_word = a.rsplit("$", 1)[-1] if "$" in a else a      # ์ˆ˜์‹ ๋’ค์— ๋ถ™์€ ํ•œ๊ธ€๋งŒ ๋น„๊ต
        if not a_word:      # ์•ž์ด ์ˆ˜์‹์œผ๋กœ ๋๋‚จ: ๋’ท์กฐ๊ฐ์ด ์กฐ์‚ฌ์ผ ๋•Œ๋งŒ ๋ถ™์ž„ ('$\angle BAC$|๋ฅผ'), ์•„๋‹ˆ๋ฉด ์ƒˆ ๋ง('๋”ฐ๋ผ์„œ')
            # ์ˆซ์ž๋กœ ๋๋‚˜๋Š” ์ˆ˜์‹ ๋’ค์˜ ๋‹จ์œ„ ๋ช…์‚ฌ๋„ ๋ถ™์ž„ ('$2$|๊ฐ€์ง€', '$13$|๊ฐœ์”ฉ', '$\frac{1}{3}$|๋ฐฐ')
            numeric = re.search(r"[0-9}]\$$", a) is not None
            if _strip(b) in JOSA or (numeric and _strip(b).startswith(UNITS)):
                return a + b
            return a + " " + b
        joined = _strip(a_word + b)
        cj, cb, ca = counts[joined], counts[_strip(b)], counts[_strip(a_word.lstrip("([{'\""))]
        # ๋ถ™์ด๋Š” ๊ฒฝ์šฐ:
        #  - ๋’ท์กฐ๊ฐ์ด ์กฐ์‚ฌยท์–ด๋ฏธ (๋‹จ๋… ๋‹จ์–ด๊ฐ€ ๋  ์ˆ˜ ์—†์Œ; '์ด' ๋Š” ์ง€์‹œ์–ด์ผ ์ˆ˜ ์žˆ์–ด ์ œ์™ธ)
        #  - ๋ถ™์ธ ํ˜•ํƒœ๊ฐ€ ๋’ท์กฐ๊ฐ ๋‹จ๋…๋ณด๋‹ค ํ”ํ•จ
        #  - ์•ž์กฐ๊ฐ์ด ๋‹จ๋…์œผ๋กœ ๋‚˜์˜จ ์ ์ด ์—†๊ณ  ๋ถ™์ธ ํ˜•ํƒœ๋Š” ์žˆ์Œ ('๋‚˜์—ด|ํ•˜๋ฉด', '๊ผญ์ง“|์ ์˜')
        #  - ์•ž๋’ค ์กฐ๊ฐ ๋ชจ๋‘ ๋‹จ๋…์œผ๋กœ ๋‚˜์˜จ ์ ์ด ์—†์Œ ('์ง€|๋‚˜๊ฒŒ', '๋”ฐ|๋ผ๊ฐ€์•ผ')
        #  (๋’ค ๋‘ ๊ทœ์น™์€ ์•ž์กฐ๊ฐ์ด ์กฐ์‚ฌ๋กœ ๋๋‚˜๋ฉด ์“ฐ์ง€ ์•Š์Œ: '[๊ทธ๋ฆผ9]์˜|๊ฒฝ์šฐ๊ฐ€', '์ขŒ๋ณ€๊ณผ|์šฐ๋ณ€์˜' ๋Š” ๋„์–ด ์”€.
        #   ๋งˆ์ง€๋ง‰ ๊ทœ์น™์€ ์•ž์กฐ๊ฐ์ด ์„ธ ๊ธ€์ž ์ดํ•˜์ธ ์กฐ๊ฐ์ผ ๋•Œ๋งŒ)
        a_core = _strip(a_word.lstrip("([{'\""))
        a_josa_end = a_core[-1:] in "์˜๋กœ๊ณผ์™€์„๋ฅผ์€๋Š”์—๊ฐ€๋„"
        if ((_strip(b) in JOSA and _strip(b) != "์ด") or cj > cb or (cj == 0 and _strip(b) in JOSA)
                or (not a_josa_end and ca == 0 and cj > 0)
                or (not a_josa_end and len(a_core) <= 3 and ca == 0 and cb == 0)
                # ์•ž์กฐ๊ฐ์ด ํ•œ ๊ธ€์ž์ด๊ณ  ๋ถ™์ธ ํ˜•ํƒœ๊ฐ€ ์ž๋ฃŒ์— 3๋ฒˆ ์ด์ƒ ('๋„“์ด๋ฅผ ๊ตฌ|ํ•˜๋Š”': 'ํ•˜๋Š”' ๋‹จ๋…๋„ ํ”ํ•ด ๋„์–ด์กŒ์Œ)
                or (len(a_core) == 1 and cj >= 3)):
            return a + b
        return a + " " + b
    pat = re.compile(r"(\S*)" + LX.LINE_BREAK + r"([^\s" + LX.LINE_BREAK + r"]*)")
    while LX.LINE_BREAK in text:
        new = pat.sub(decide, text, count=1)
        if new == text:
            text = text.replace(LX.LINE_BREAK, " ")
            break
        text = new
    return text



def _norm(s: str) -> str:
    s = s.replace("$", "").replace("\\left", "").replace("\\right", "").replace("\\,", "")
    s = re.sub(r"\s+", "", s)
    s = re.sub(r"[.,ใ€‚]+$", "", s)
    return s


def explanation_choice(text: str, choices: list[str] | None):
    """ํ•ด์„ค์ด ๊ฐ€๋ฆฌํ‚ค๋Š” ๋ณด๊ธฐ ๋ฒˆํ˜ธ์™€ ๊ทธ ๊ทผ๊ฑฐ.
    1) ํ•ด์„ค ๋งจ ๋(๋งˆ์ง€๋ง‰ 20์ž)์— โ‘ ~โ‘ค๊ฐ€ ์žˆ์œผ๋ฉด ๊ทธ๊ฒƒ ('circle')
    2) ์•„๋‹ˆ๋ฉด ๋งˆ์ง€๋ง‰ ์ˆ˜์‹์˜ ๋งˆ์ง€๋ง‰ '=' ๋’ค ๊ฐ’์ด ๋ณด๊ธฐ ์ค‘ ์ •ํ™•ํžˆ ํ•˜๋‚˜์™€ ๊ฐ™์œผ๋ฉด ๊ทธ ๋ฒˆํ˜ธ ('value')"""
    tail = text.rstrip()[-20:]
    circ = [ch for ch in tail if ch in CIRC]
    if circ:
        return CIRC.index(circ[-1]) + 1, "circle"
    if not choices or len(choices) != 5:
        return None, None
    maths = re.findall(r"\$([^$]+)\$", text)
    if not maths:
        return None, None
    last = maths[-1].split("=")[-1]
    hit = [i + 1 for i, c in enumerate(choices) if _norm(c) and _norm(c) == _norm(last)]
    if len(hit) == 1:
        return hit[0], "value"
    return None, None


def load_choices(latex_dir: Path | None, exam: str):
    f = latex_dir / f"{exam}.jsonl" if latex_dir else None
    if not f or not f.exists():
        return {}
    out = {}
    with open(f, encoding="utf-8") as fh:
        for line in fh:
            q = json.loads(line)
            out[q["number"]] = q.get("choices")
    return out


def inject_missing_glyphs(pdf, path: Path):
    """pdfplumber ๊ฐ€ ๋ฒ„๋ฆฌ๋Š” ๊ธ€์ž(configs/ebsi_missing_glyphs.json: 2021_11 ํ•ด์„ค์˜ ใ‰ ~ใ‰ฃยทใ„ฑใ„ดใ„ทยทโ…ฐ~โ…ถยทโˆˆยทโ€ฒยท| 99๊ฐœ)๋ฅผ
    ํŽ˜์ด์ง€ ๊ธ€์ž ๋ชฉ๋ก์— ๋ผ์›Œ ๋„ฃ๋Š”๋‹ค. ๋†’์ดยทํฌ๊ธฐ๋Š” ๊ฐ™์€ ์ค„ ์™ผ์ชฝ ์ด์›ƒ ๊ธ€์ž(๊ฐ€๋กœ์„  ์ œ์™ธ)๋ฅผ ๋”ฐ๋ฅด๊ณ (์ฒจ์ž ์˜คํŒ ๋ฐฉ์ง€),
    ๊ธ€๊ผด์€ ๊ธ€ ๊ธฐํ˜ธ(ใ‰ ยทใ„ฑยทโ…ฐ ๋“ฑ)๋ฉด ํ•œ๊ธ€ ๋ณธ๋ฌธ ๊ธ€๊ผด, ์ˆ˜์‹ ๊ธฐํ˜ธ(โ€ฒยท|ยทโˆˆ)๋ฉด ์ด์›ƒ ๊ธ€๊ผด."""
    f = HERE.parent / "configs" / "ebsi_missing_glyphs.json"
    if not f.exists():
        return 0
    rows = json.loads(f.read_text(encoding="utf-8")).get(path.name, [])
    texty = set("ใ‰ ใ‰กใ‰ขใ‰ฃใ‰คใ„ฑใ„ดใ„ทใ„นโ…ฐโ…ฑโ…ฒโ…ณโ…ดโ…ตโ…ถ")
    for r in rows:
        p = pdf.pages[r["page"]]
        orig = [c for c in p.chars if not c.get("missing_glyph")]
        body = [c for c in orig if _hangul(c["text"])]
        bsize = statistics.median([c["size"] for c in body]) if body else 8.0
        bfont = Counter(c["fontname"] for c in body).most_common(1)[0][0] if body else "missing"
        nb = [c for c in orig if c["text"].strip() and c["text"] != "๎ญ" and r["x0"] - 15 <= c["x1"] <= r["x0"] + 1
              and c["top"] < r["bottom"] and c["bottom"] > r["top"]]
        if nb:
            n = max(nb, key=lambda c: c["x1"])
            top, bot, size = n["top"], n["bottom"], n["size"]
        else:
            cy = (r["top"] + r["bottom"]) / 2
            top, bot, size, n = cy - bsize / 2, cy + bsize / 2, bsize, None
        font = bfont if r["text"] in texty or n is None else n["fontname"]
        p.chars.append({"text": r["text"], "x0": r["x0"], "x1": r["x1"], "top": top, "bottom": bot,
                        "size": size, "fontname": font, "matrix": (1, 0, 0, 1, 0, 0), "upright": True,
                        "doctop": top, "missing_glyph": True})
    return len(rows)


def process_pdf(path: Path, latex_dir: Path | None = None):
    exam = path.name.replace("_solution.pdf", "")
    problems = []
    choices = load_choices(latex_dir, exam)
    with pdfplumber.open(path) as pdf:
        LX.set_eq_fonts(pdf)          # ์ต๋ช… ๊ธ€๊ผด(CIDFont+Fn) PDF ์˜ ์ˆ˜์‹ ๊ธ€๊ผด ํŒ์ •
        inject_missing_glyphs(pdf, path)
        ans, err1 = parse_answers(pdf)
        if len(ans) < 30:     # ๊ธ€์ž๋ฅผ ๋ชป ์ฝ์€ ์นธ์ด ์žˆ์œผ๋ฉด pdfium ์œผ๋กœ ํ•œ ๋ฒˆ ๋”
            ans, err1 = parse_answers(pdf, pdfium_extra_chars(path))
        select = None
        if exam.endswith("_hs3"):
            if len([k for k in ans if k <= 22]) < 22:        # ํ‰๊ฐ€์› ํ˜•์‹: 1์ชฝ '01. โ‘ฃ โ€ฆ' ๋ชฉ๋ก
                ans = parse_list_answers(pdf) | {k: v for k, v in ans.items() if k <= 22}
            hd = {h["name"]: h for h in section_headers(pdf)}
            if "ํ™•ํ†ต" in hd:
                t = hd["ํ™•ํ†ต"]
                later = [h for k, h in hd.items() if k != "ํ™•ํ†ต" and (h["page"], h["x"], h["top"]) > (t["page"], t["x"], t["top"])]
                select = {"skip": t, "cut": min(later, key=lambda h: (h["page"], h["x"], h["top"])) if later else None}
                sel = parse_select_answers(pdf, t)
                ans = {k: v for k, v in ans.items() if k <= 22} | sel
            # pdfplumber ๊ฐ€ โ‘ ~โ‘ค๋ฅผ ๋ชป ์ฝ์€ ์นธ: pdfium ๊ธ€์ž๋กœ ๋ณด์ถฉ (๋นˆ ์นธ๋งŒ)
            for rng in (range(1, 23), range(23, 31)):
                if any(k not in ans for k in rng):
                    ans = pdfium_list_answers(path, rng) | ans
            ans = {k: v for k, v in ans.items() if 1 <= k <= 30}
            err1 = None if len(ans) == 30 else f"์ •๋‹ตํ‘œ {len(ans)}/30 (๊ณตํ†ต+ํ™•ํ†ต)"
        # ์›๋ณธ ์ด๋ฏธ์ง€๋กœ ํ™•์ธํ•œ ์ •๋‹ต ๋ณด์ • (์ •๋‹ตํ‘œ ๊ธ€์ž๊ฐ€ ๊นจ์ง„ ํŒ: 2021_11ยท2023_11 ๊ณ 3 ์€ ์ชฝ ๊ทธ๋ฆผ + OCR ๊ธ€์ž ์ธต)
        ao = ANSWER_OVERRIDES.get(exam, {})
        if ao:
            ans = {k: v for k, v in ans.items()} | ao
            err1 = None if len(ans) >= 30 else err1
        sol, err2 = split_solutions(pdf, select=select)
        for n in range(1, 31):
            ctx = LX.Ctx()
            segs = sol.get(n, {}).get("segs", {})
            text = render_solution(segs, ctx) if segs else ""
            # '( โ…ฐ )' -> '(โ…ฐ)' (2021_11 ์€ ๊ด„ํ˜ธ์™€ ๋กœ๋งˆ์ˆซ์ž ์‚ฌ์ด์— ๊ณต๋ฐฑ ๊ธ€์ž๊ฐ€ ์žˆ์Œ)
            text = re.sub(r"\(\s*([โ…ฐโ…ฑโ…ฒโ…ณโ…ดโ…ตโ…ถโ…ทโ…ธโ…นโ… โ…กโ…ขโ…ฃโ…คโ…ฅโ…ฆโ…งโ…จโ…ฉ]+)\s*\)", r"(\1)", text)
            # '(โ…ฐ$)n = 2$' -> '(โ…ฐ) $n = 2$' (๋‹ซ๋Š” ๊ด„ํ˜ธ๊ฐ€ ์ˆ˜์‹์— ๋ถ™์–ด ๋“ค์–ด๊ฐ„ ๊ฒฝ์šฐ: 2020_09_hs2 ๋“ฑ)
            text = re.sub(r"\(([โ…ฐโ…ฑโ…ฒโ…ณโ…ดโ…ตโ…ถโ…ทโ…ธโ…นโ… โ…กโ…ขโ…ฃโ…คโ…ฅโ…ฆโ…งโ…จโ…ฉ]+)\$\)", r"(\1) $", text)
            # ์˜๋ฌธ i ๋กœ ์“ด ๋กœ๋งˆ์ˆซ์ž๊ฐ€ ์ˆ˜์‹ ๋งจ ์•ž์— ๋ถ™์€ ๊ฒฝ์šฐ: '$(i)a > 0$' -> '(โ…ฐ) $a > 0$', '$(i i)$' -> '(โ…ฑ)'
            # (2022_06_hs2 ํ•ด์„ค 21ยท30๋ฒˆ)
            ROM = {"i": "โ…ฐ", "i i": "โ…ฑ", "i i i": "โ…ฒ", "i v": "โ…ณ", "v": "โ…ด"}
            text = re.sub(r"\$\((i i i|i i|i v|i|v)\)\$", lambda g: "(" + ROM[g.group(1)] + ")", text)
            text = re.sub(r"\$\((i i i|i i|i v|i|v)\)(?=[^$])", lambda g: "(" + ROM[g.group(1)] + ") $", text)
            # '(โ…ฐ) , (โ…ฑ) ์—' -> '(โ…ฐ), (โ…ฑ)์—'
            text = re.sub(r"\(([โ…ฐโ…ฑโ…ฒโ…ณโ…ดโ…ตโ…ถโ…ทโ…ธโ…นโ… โ…กโ…ขโ…ฃโ…คโ…ฅโ…ฆโ…งโ…จโ…ฉ]+)\) (?=[,์—])", r"(\1)", text)
            # '(โ…ฐ) $\sim($โ…ฒ)์—' -> '(โ…ฐ) $\sim$ (โ…ฒ)์—' (2024_09_hs2ยท2025_09_hs2)
            text = re.sub(r"\$\\sim\(\$([โ…ฐโ…ฑโ…ฒโ…ณโ…ดโ…ตโ…ถโ…ทโ…ธโ…นโ… โ…กโ…ขโ…ฃโ…คโ…ฅโ…ฆโ…งโ…จโ…ฉ]+)\)", r"$\\sim$ (\1)", text)
            # '$A \cap B$=$\{ 5,9 \}$' -> '$A \cap B = \{ 5,9 \}$' (2025_03_hs2)
            text = re.sub(r"(?<=[^)\s])\$=\$(?=[^(])", " = ", text)
            # ์ˆ˜์‹ ์•ˆ 'โ‰ฆ'ยท'โ‰ง' -> '\le'ยท'\ge' (2025_03_hs2 26๋ฒˆ)
            text = text.replace("โ‰ฆ", r" \le ").replace("โ‰ง", r" \ge ")
            text = TBL.convert_tables(text)    # ์ฆ๊ฐํ‘œยท๋ถ€ํ˜ธํ‘œ -> array (์นธ ์ˆ˜๊ฐ€ ๋งž์„ ๋•Œ๋งŒ)
            # ๋นˆ์นธ '(๊ฐ€)' ๊ด„ํ˜ธ๊ฐ€ ์ˆ˜์‹ ๊ฒฝ๊ณ„์™€ ์„ž์ž„ -> \boxed{(๊ฐ€)} (12 ๋ฌธ์ œ ๋ณธ๋ฌธ๊ณผ ๊ฐ™์€ ๊ทœ์น™; '์ฆ‰, (๊ฐ€$)= - \frac{1}{n}$')
            text = re.sub(r"\(\$([๊ฐ€๋‚˜๋‹ค๋ผ๋งˆ])\$\)", r"\\boxed{(\1)}", text)
            text = re.sub(r"\(\$([๊ฐ€๋‚˜๋‹ค๋ผ๋งˆ])\)", r"\\boxed{(\1)}$", text)
            text = re.sub(r"\(([๊ฐ€๋‚˜๋‹ค๋ผ๋งˆ])\$\)", r"$\\boxed{(\1)}", text)
            reasons = list(ctx.reasons)
            a = ans.get(n)
            if a is None:
                reasons.append("์ •๋‹ตํ‘œ์—์„œ ์ •๋‹ต์„ ๋ชป ์ฝ์Œ")
            if not text:
                reasons.append("ํ•ด์„ค์„ ๋ชป ์ฐพ์Œ")
            if "$$" in text or re.search(r"\?[0-9A-F]{4}", text):
                reasons.append("ํ•ด์„ค ์ˆ˜์‹ ๋ณ€ํ™˜ ์ ๊ฒ€ ํ•„์š”")
            problems.append({
                "exam": exam, "number": n,
                "answer_kind": a["kind"] if a else None,
                "answer": a["value"] if a else None,
                "answer_source": a.get("source") if a else None,
                "explanation_choice": None,
                "explanation_choice_by": None,
                "explanation_latex": text,          # ์ค„๋ฐ”๊ฟˆ ํ‘œ์ง€ ํฌํ•จ (finalize ์—์„œ ์ •๋ฆฌ)
                "answer_check": "n/a",
                "needs_review": bool(reasons),
                "review_reasons": reasons,
                "_choices": choices.get(n),
            })
        errs = [e for e in (err1, err2) if e]
    return problems, errs


REVIEW_DIR = Path("data/ebsi/review")


def _load_answer_overrides():
    """data/ebsi/review/answer_overrides.jsonl: {exam, number, kind(choice|integer), value, note}. ๋‚˜์ค‘ ์ค„ ์šฐ์„ ."""
    f = Path(__file__).resolve().parents[1] / "data/ebsi/review/answer_overrides.jsonl"
    out: dict[str, dict] = {}
    if f.exists():
        for line in open(f, encoding="utf-8"):
            if line.strip():
                r = json.loads(line)
                out.setdefault(r["exam"], {})[r["number"]] = {"kind": r["kind"], "value": r["value"], "source": "manual"}
    return out


ANSWER_OVERRIDES = _load_answer_overrides()


def load_overrides(review_dir: Path = REVIEW_DIR):
    """ํ™”๋ฉด ๋Œ€์กฐ๋กœ ์‚ฌ๋žŒ์ด ๊ณ ์นœ ํ•ด์„ค: {(exam, number): explanation_latex}. ๋‚˜์ค‘ ์ค„์ด ์•ž ์ค„์„ ๋ฎ์Œ."""
    f = review_dir / "solution_overrides.jsonl"
    out = {}
    if f.exists():
        for line in open(f, encoding="utf-8"):
            if line.strip():
                r = json.loads(line)
                out[(r["exam"], r["number"])] = r["explanation_latex"]
    return out


def load_review(review_dir: Path = REVIEW_DIR):
    """ํ™”๋ฉด ๋Œ€์กฐ ๊ธฐ๋ก: {(exam, number): {"status": "verified"|"fixed", "date": ..., "note": ...}}"""
    f = review_dir / "solution_review.jsonl"
    out = {}
    if f.exists():
        for line in open(f, encoding="utf-8"):
            if line.strip():
                r = json.loads(line)
                out[(r["exam"], r["number"])] = r
    return out


def finalize(q: dict, counts: Counter, overrides=None, review=None):
    """์ค„๋ฐ”๊ฟˆ ํ‘œ์ง€ ์ •๋ฆฌ -> (์žˆ์œผ๋ฉด) ์‚ฌ๋žŒ์ด ๊ณ ์นœ ํ•ด์„ค๋กœ ๊ต์ฒด -> ๊ฐ๊ด€์‹ ๋Œ€์กฐ."""
    q["explanation_latex"] = resolve_breaks(q["explanation_latex"], counts)
    key = (q["exam"], q["number"])
    q["explanation_source"] = "auto"
    if overrides and key in overrides:
        q["explanation_latex"] = overrides[key]
        q["explanation_source"] = "manual"
        q["review_reasons"] = []            # ์ž๋™ ๋ณ€ํ™˜ ๊ฒฝ๊ณ ๋Š” ์‚ฌ๋žŒ์ด ๊ณ ์นœ ๋ณธ๋ฌธ์—๋Š” ํ•ด๋‹น ์—†์Œ
    rv = (review or {}).get(key)
    q["visual_check"] = rv["status"] if rv else None      # ์›๋ณธ ํ™”๋ฉด ๋Œ€์กฐ ์—ฌ๋ถ€ (None = ์•„์ง)
    if rv and rv.get("text_sha"):
        import hashlib
        now = hashlib.sha1(" ".join(q["explanation_latex"].split()).encode("utf-8")).hexdigest()[:12]
        if now != rv["text_sha"]:
            q["visual_check"] = "stale"     # ๋Œ€์กฐ ๋’ค ๊ทœ์น™์ด ๋ฐ”๋€Œ์–ด ํ…์ŠคํŠธ๊ฐ€ ๋‹ฌ๋ผ์ง -> ๋‹ค์‹œ ๋Œ€์กฐํ•ด์•ผ ํ•จ
    q["needs_review"] = bool(q["review_reasons"]) or q["visual_check"] in (None, "stale")
    exp_choice, exp_how = explanation_choice(q["explanation_latex"], q.pop("_choices"))
    q["explanation_choice"], q["explanation_choice_by"] = exp_choice, exp_how
    if q["answer_kind"] == "choice":
        q["answer_check"] = ("no_choice_in_explanation" if exp_choice is None
                             else "ok" if exp_choice == q["answer"] else "mismatch")
    elif q["answer_kind"] == "integer":
        # ๋‹จ๋‹ต: ํ•ด์„ค ๋งˆ์ง€๋ง‰ ์ˆ˜์‹์˜ ๋งˆ์ง€๋ง‰ '=' ๋’ค ๊ฐ’์ด ์ •๋‹ต ์ •์ˆ˜์™€ ๊ฐ™์€์ง€
        v = explanation_value(q["explanation_latex"])
        q["explanation_value"] = v
        q["answer_check"] = "no_value_in_explanation" if v is None else "ok" if v == q["answer"] else "mismatch"


def explanation_value(text: str):
    """ํ•ด์„ค ๋์˜ ๊ฐ’(์ •์ˆ˜)์„ ์ฐพ๋Š”๋‹ค: ๋งˆ์ง€๋ง‰ ์ˆ˜์‹๋ถ€ํ„ฐ ๊ฑฐ์Šฌ๋Ÿฌ ์˜ฌ๋ผ๊ฐ€๋ฉฐ '= ์ •์ˆ˜' ๋กœ ๋๋‚˜๋Š” ์ฒซ ์ˆ˜์‹."""
    maths = re.findall(r"\$([^$]+)\$", text)
    for m in reversed(maths[-3:]):
        last = _norm(m.split("=")[-1])
        if re.fullmatch(r"-?\d+", last):
            return int(last)
    return None


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--pdf", type=Path)
    ap.add_argument("--dir", type=Path)
    ap.add_argument("--out", type=Path, default=Path("data/ebsi/solutions"))
    ap.add_argument("--latex-dir", type=Path, default=Path("data/ebsi/latex"),
                    help="2๋‹จ๊ณ„ ๊ฒฐ๊ณผ(๋ณด๊ธฐ ๋‚ด์šฉ). ํ•ด์„ค ๋งˆ์ง€๋ง‰ ๊ฐ’๊ณผ ๋ณด๊ธฐ๋ฅผ ๋Œ€์กฐํ•  ๋•Œ ์”€")
    ap.add_argument("--show", nargs="*", type=int)
    a = ap.parse_args()
    pdfs = [a.pdf] if a.pdf else sorted(a.dir.glob("*_solution.pdf")) if a.dir else []
    if not pdfs:
        sys.exit("์ฒ˜๋ฆฌํ•  PDF ๊ฐ€ ์—†์–ด์š” (--pdf ๋˜๋Š” --dir)")
    a.out.mkdir(parents=True, exist_ok=True)
    tot = rev = mism = noans = vis_tot = 0
    why = Counter()
    mismatches, nochoice = [], []
    done = [(pdf, *process_pdf(pdf, a.latex_dir)) for pdf in pdfs]
    # ์ค„๋ฐ”๊ฟˆ ํŒ์ •์šฉ ์–ด์ ˆ ๋นˆ๋„: ์ด๋ฒˆ ํ•ด์„ค ์ „๋ถ€ + 2๋‹จ๊ณ„ ๋ฌธ์ œ ๋ณธ๋ฌธ/๋ณด๊ธฐ
    corpus = [q["explanation_latex"] for _, items, _ in done for q in items]
    # ๊ฐ™์€ ํ•™๋…„ ๋ฌธ์ œ ๋ณธ๋ฌธ๋งŒ (๋‹ค๋ฅธ ํ•™๋…„ ํŒŒ์ผ์ด ๋Š˜์–ด๋‚˜๋ฉด ๋นˆ๋„๊ฐ€ ๋ฐ”๋€Œ์–ด ์ด๋ฏธ ๋Œ€์กฐํ•œ ํ•ด์„ค์˜ ์ค„๋ฐ”๊ฟˆ์ด ๋‹ฌ๋ผ์กŒ์Œ: 2024_03_hs1 11๋ฒˆ)
    grades = {p.name.split("_solution")[0].rsplit("_hs", 1)[-1] for p in pdfs}
    for f in sorted(x for x in a.latex_dir.glob("*.jsonl") if x.stem.rsplit("_hs", 1)[-1] in grades) \
            if a.latex_dir and a.latex_dir.exists() else []:
        for line in open(f, encoding="utf-8"):
            q = json.loads(line)
            corpus.append(q.get("stem_latex", ""))
            corpus.extend(q.get("choices") or [])
    counts = word_counts(corpus)
    overrides, review = load_overrides(), load_review()
    for pdf, items, errs in done:
        for q in items:
            finalize(q, counts, overrides, review)
        exam = items[0]["exam"]
        with open(a.out / f"{exam}.jsonl", "w", encoding="utf-8") as f:
            for q in items:
                f.write(json.dumps(q, ensure_ascii=False) + "\n")
        got = sum(q["answer"] is not None for q in items)
        mm = sum(q["answer_check"] == "mismatch" for q in items)
        r = sum(bool(q["review_reasons"]) for q in items)
        vis = sum(q["visual_check"] in ("verified", "fixed") for q in items)
        stale = [q["number"] for q in items if q["visual_check"] == "stale"]
        if stale:
            errs = list(errs) + [f"๋Œ€์กฐ ๋’ค ํ…์ŠคํŠธ ๋ฐ”๋€œ(์žฌ๋Œ€์กฐ ํ•„์š”): {stale}"]
        vis_tot += vis
        tot += len(items); rev += r; mism += mm; noans += 30 - got
        for q in items:
            why.update(q["review_reasons"])
            if q["answer_check"] == "mismatch":
                mismatches.append(q)
            elif q["answer_check"] in ("no_choice_in_explanation", "no_value_in_explanation"):
                nochoice.append(q)
        print(f"{exam}: ์ •๋‹ต {got}/30, ์ž๋™๊ฒฝ๊ณ  {r}, ํ™”๋ฉด๋Œ€์กฐ {vis}/30, ๋ณด๊ธฐ๋ฒˆํ˜ธ ๋ถˆ์ผ์น˜ {mm} {'; '.join(errs)}")
        if a.show:
            for q in items:
                if q["number"] in a.show:
                    print(f"\n[{exam} {q['number']}๋ฒˆ] ์ •๋‹ต={q['answer']} ({q['answer_kind']}) ๊ฒ€์ฆ={q['answer_check']}\n{q['explanation_latex'][:600]}")
    print(f"\n์ „์ฒด {tot}๋ฌธํ•ญ: ์ •๋‹ต ๋ชป ์ฝ์Œ {noans}, ์ž๋™๊ฒฝ๊ณ  {rev}, ํ™”๋ฉด๋Œ€์กฐ ์™„๋ฃŒ {vis_tot}/{tot}, ๋ณด๊ธฐ๋ฒˆํ˜ธ ๋ถˆ์ผ์น˜ {mism}")
    for k, v in why.most_common():
        print(f"  - {k}: {v}")
    okc = sum(1 for f in [a.out / f"{p.name.replace('_solution.pdf', '')}.jsonl" for p in pdfs]
              for line in open(f, encoding="utf-8") if json.loads(line)["answer_check"] == "ok")
    print(f"\n[์ •๋‹ตโ†”ํ•ด์„ค ๋Œ€์กฐ] ์ผ์น˜ {okc} / ๋ถˆ์ผ์น˜ {len(mismatches)} / ์ž๋™ ๋Œ€์กฐ ๋ถˆ๊ฐ€ {len(nochoice)} (ํ™”๋ฉด ๋Œ€์กฐ๋กœ ํ™•์ธ)")
    print("  ๊ฐ๊ด€์‹: ํ•ด์„ค ๋ โ‘ ~โ‘ค ๋˜๋Š” ๋งˆ์ง€๋ง‰ '=' ๋’ค ๊ฐ’์ด ๋ณด๊ธฐ ํ•˜๋‚˜์™€ ๊ฐ™์„ ๋•Œ / ๋‹จ๋‹ต: ๋งˆ์ง€๋ง‰ '= ์ •์ˆ˜' ๊ฐ€ ์ •๋‹ต๊ณผ ๊ฐ™์„ ๋•Œ")
    for q in mismatches:
        tail = q["explanation_latex"][-80:].replace("\n", " ")
        if q["answer_kind"] == "choice":
            got = f"์ •๋‹ตํ‘œ {CIRC[q['answer'] - 1]} / ํ•ด์„ค {CIRC[q['explanation_choice'] - 1]}({q['explanation_choice_by']})"
        else:
            got = f"์ •๋‹ตํ‘œ {q['answer']} / ํ•ด์„ค {q.get('explanation_value')}"
        print(f"  ๋ถˆ์ผ์น˜ {q['exam']} {q['number']:>2}๋ฒˆ: {got}  โ€ฆ{tail}")
    by_exam = Counter(q["exam"] for q in nochoice)
    if nochoice:
        print("  ์ž๋™ ๋Œ€์กฐ ๋ถˆ๊ฐ€(์‹œํ—˜๋ณ„): " + ", ".join(f"{k} {v}" for k, v in sorted(by_exam.items())))


if __name__ == "__main__":
    main()