Spaces:
Running

File size: 36,224 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
"""AI Hub ์ˆ˜ํ•™ ๋ผ๋ฒจ๋ง zip(TL_*, VL_*) -> ์ •์ œ๋œ ๋ฌธํ•ญ JSONL.

ETL(Extract, Transform, Load: ๊บผ๋‚ด์„œ -> ๊ณ ์ณ์„œ -> DB์— ๋„ฃ๋Š” ๊ณผ์ •) ์ค‘ ์•ž์˜ ๋‘ ๋‹จ๊ณ„(Extract, Transform)์ž…๋‹ˆ๋‹ค.
Supabase ์ ์žฌ(Load)๋Š” ๋‹ค์Œ ๋‹จ๊ณ„์—์„œ ์ด JSONL ์„ ์ฝ์–ด ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค.

์‚ฌ์šฉ๋ฒ• (์ €์žฅ์†Œ ๋ฃจํŠธ์—์„œ)
    python scripts/04_normalize_aihub.py --root "D:\\์ˆ˜ํ•™" --out data/aihub_normalized
    python scripts/04_normalize_aihub.py --root "D:\\์ˆ˜ํ•™" --out data/aihub_normalized --limit 500   # ๋ง›๋ณด๊ธฐ

์ž…๋ ฅ  : --root ์•„๋ž˜์˜ TL_*.zip, VL_*.zip (์••์ถ•์„ ํ’€์ง€ ์•Š๊ณ  zip ์•ˆ์˜ JSON ์„ ๋ฐ”๋กœ ์ฝ์Šต๋‹ˆ๋‹ค)
์ถœ๋ ฅ  : --out ํด๋”
    aihub_A.jsonl     ํ…์ŠคํŠธ๋กœ ์™„๋น„๋œ ๋ฌธํ•ญ (ํ‘œ๋Š” ํ‘œ ํ˜•์‹ ๊ธ€์ž๋กœ ๋ฐ”๊ฟ” ํฌํ•จ)         <- ๋ฐ”๋กœ ์“ธ ์ˆ˜ ์žˆ๋Š” ํ’€
    aihub_B.jsonl     ๊ทธ๋ฆผ์ด ํ•„์š”ํ•œ ๋ฌธํ•ญ (์›์ฒœ ์ด๋ฏธ์ง€์—์„œ ์ž˜๋ผ ์“ธ ๋•Œ๊นŒ์ง€ ๋ณด๋ฅ˜)
    aihub_C.jsonl     ๊ฒ€์ˆ˜๊ฐ€ ํ•„์š”ํ•œ ๋ฌธํ•ญ (๊ธ€์ž ๊นจ์ง, ์ •๋‹ตยท์„ ํƒ์ง€ ๋ˆ„๋ฝ ๋“ฑ; ์ด์œ ๊ฐ€ reasons ์— ์žˆ์Œ)
    normalize_report.txt   ๋ฌด์—‡์„ ์–ผ๋งˆ๋‚˜ ๊ณ ์ณค๋Š”์ง€ / ๋“ฑ๊ธ‰ / ์ด์œ ๋ณ„ ๊ฐœ์ˆ˜
    coverage_after.csv     ๋‹จ์› x ๋‚œ์ด๋„๋ณ„ ๋ฌธํ•ญ ์ˆ˜ (A, A+B)
    tables_failed.jsonl    ํ‘œ๋ฅผ ๋ชป ๋ฐ”๊พผ ์›๋ณธ (์žˆ์„ ๋•Œ๋งŒ) - ์ด ํŒŒ์ผ์„ ๋ณด๋‚ด ์ฃผ์‹œ๋ฉด ๋ณ€ํ™˜ ๊ทœ์น™์„ ๊ณ ์นฉ๋‹ˆ๋‹ค

๋“ฑ๊ธ‰ (3.2ํŒ ์กฐ์‚ฌ์˜ ์ •์˜๋ฅผ ์ด์–ด๋ฐ›๋˜, 'ํ•ด์„ค'์€ ๋‚˜์ค‘์— ์ƒˆ๋กœ ๋งŒ๋“ค ๊ฒƒ์ด๋ฏ€๋กœ ๋”ฐ๋กœ ์ทจ๊ธ‰)
    A : ๋ฌธํ•ญ ๋ณธ๋ฌธยท์„ ํƒ์ง€ยท์ •๋‹ต์ด ๊ธ€์ž๋กœ ์™„๋น„. ํ‘œ๋Š” ํ‘œ ํ˜•์‹ ๊ธ€์ž๋กœ ๋ฐ”๊ฟ” ๋„ฃ์Œ.
    B : A ์ด์ง€๋งŒ ๋ฌธํ•ญ์ด๋‚˜ ์„ ํƒ์ง€์— ๊ทธ๋ฆผ์ด ํ•„์š”ํ•จ (๊ทธ๋ฆผ ์œ„์น˜๋Š” source_meta.figure_boxes)
    C : ๋ฌธํ•ญ ๋ณธ๋ฌธ์ด ์—†์Œ / ์ •๋‹ต์„ ๋ชป ์ฝ์Œ / ๊ฐ๊ด€์‹ ์„ ํƒ์ง€ 5๊ฐœ๊ฐ€ ์•ˆ ๋งž์Œ / ๋ฌธํ•ญยท์„ ํƒ์ง€ยท์ •๋‹ต์ด ๊นจ์ง / ํ‘œ ๋ณ€ํ™˜ ์‹คํŒจ
ํ•ด์„ค์€ ๋“ฑ๊ธ‰๊ณผ ๋ณ„๊ฐœ์ž…๋‹ˆ๋‹ค.
    ํ•ด์„ค์ด ์—†๊ฑฐ๋‚˜, ๊ธ€์ž๊ฐ€ ๊นจ์กŒ๊ฑฐ๋‚˜, ๊ทธ๋ฆผ์ด ํ•„์š”ํ•˜๋ฉด solution_md ๋ฅผ ๋น„์šฐ๊ณ (null) ํ”Œ๋ž˜๊ทธ๋ฅผ ๋‚จ๊น๋‹ˆ๋‹ค.
    (๊นจ์ง„ ํ•ด์„ค์„ ํ•™์ƒ์—๊ฒŒ ๋ณด์—ฌ ์ฃผ์ง€ ์•Š๊ธฐ ์œ„ํ•ด์„œ์ด๋ฉฐ, ์›๋ณธ์€ source_meta.solution_raw_broken ์— ๋ณด๊ด€)
    ์ดํ›„ ๋‹จ๊ณ„์—์„œ ํ•ด์„ค์„ ์ƒˆ๋กœ ์ƒ์„ฑํ•˜๊ณ  ์ •๋‹ต๊ณผ ๋Œ€์กฐํ•ด ์ฑ„์›๋‹ˆ๋‹ค.

๊ณ ์น˜๋Š” ๊ฒƒ(์ „๋ถ€ source_meta.flags ์— ๊ธฐ๋ก)
    HTML ๊ป๋ฐ๊ธฐ(<div>, <span class="math-inline">) ์ œ๊ฑฐ, ์—”ํ‹ฐํ‹ฐ(&lt;) ๋ณต์›, ```html ์ฝ”๋“œ ์šธํƒ€๋ฆฌ ์ œ๊ฑฐ,
    ํ‘œ(<table>, Mathpix ์‹ <div class="table_tabular">) -> ๋งˆํฌ๋‹ค์šด ํ‘œ(๋ณ‘ํ•ฉ ์นธ์ด ์žˆ์œผ๋ฉด ์ •๋ฆฌ๋œ HTML ํ‘œ),
    '์ด๋‹ค$. $A$' ๊ฐ™์€ ๊ตฌ๋ถ„์ž ์ดํƒˆ, '0. 9455' ์†Œ์ˆ˜์  ๋’ค ๊ณต๋ฐฑ,
    ์ˆ˜์‹ ๋ฐ–์˜ < > ๋Š” &lt; &gt; ๋กœ, ์ˆ˜์‹ ์•ˆ์˜ < > ๋Š” \\lt \\gt ๋กœ (ํ™”๋ฉด์—์„œ ํƒœ๊ทธ๋กœ ์˜ค์ธ๋˜์–ด ๊ธ€์ž๊ฐ€ ์‚ฌ๋ผ์ง€๋Š” ๊ฒƒ ๋ฐฉ์ง€)

์•ˆ ๊ณ ์น˜๋Š” ๊ฒƒ: ์ˆ˜์‹ ์† ๊ธ€์ž ๊นจ์ง($..$0, fโ‘ก ๋“ฑ) - ์–ต์ง€๋กœ ๋ณต๊ตฌํ•˜์ง€ ์•Š๊ณ  C(๋ฌธํ•ญ ์ชฝ) ๋˜๋Š” ํ•ด์„ค ์žฌ์ƒ์„ฑ(ํ•ด์„ค ์ชฝ)์œผ๋กœ ๋ณด๋ƒ…๋‹ˆ๋‹ค.
"""
from __future__ import annotations

import argparse
import csv
import html
import json
import re
import sys
import zipfile
from collections import Counter, defaultdict
from dataclasses import dataclass, field
from html.parser import HTMLParser
from pathlib import Path
from typing import Any

if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")

ROOT = Path(__file__).resolve().parents[1]
PATTERNS = ("TL_*.zip", "VL_*.zip")

GRADE_CODE = {
    ("์ค‘ํ•™๊ต", "1ํ•™๋…„"): "m1", ("์ค‘ํ•™๊ต", "2ํ•™๋…„"): "m2", ("์ค‘ํ•™๊ต", "3ํ•™๋…„"): "m3",
    ("๊ณ ๋“ฑํ•™๊ต", "1ํ•™๋…„"): "h1",
}
DIFF_CODE = {"ํ•˜": "low", "์ค‘": "mid", "์ƒ": "high"}
QTYPE = {"๊ฐ๊ด€์‹": "multiple_choice", "์ฃผ๊ด€์‹": "short_answer"}
CIRCLED = "โ‘ โ‘กโ‘ขโ‘ฃโ‘ค"

# ---- 3.2ํŒ ์กฐ์‚ฌ์—์„œ ๊ฒ€์ฆํ•œ ์†์ƒ ํƒ์ง€ ๊ทœ์น™ (๊ทธ๋Œ€๋กœ ์ด์–ด๋ฐ›์Œ) ----
GLUED_DIGIT = re.compile(r"(?<=[A-Za-z0-9)\]}])\$\d")
CIRCLED_AFTER_LETTER = re.compile(r"(?<![\\A-Za-z])[A-Za-z][โ‘ โ‘กโ‘ขโ‘ฃโ‘คโ‘ฅโ‘ฆโ‘งโ‘จโ‘ฉ]")
CIRCLED_AFTER_SYMBOL = re.compile(r"[0-9)\]}=^][โ‘ โ‘กโ‘ขโ‘ฃโ‘คโ‘ฅโ‘ฆโ‘งโ‘จโ‘ฉ](?!\s*\\end)")
DAMAGE_CHECKS = (("glued_digit", GLUED_DIGIT), ("circled_after_letter", CIRCLED_AFTER_LETTER),
                 ("circled_after_symbol", CIRCLED_AFTER_SYMBOL))

CODE_RE = re.compile(r"\[([^\]]+)\]")
MATH_SPAN = re.compile(r"\$[^$]*\$|\\\[.*?\\\]", re.DOTALL)
HANGUL = re.compile(r"[๊ฐ€-ํžฃ]")
# ์ˆ˜์‹ ์† "q<p$" ๊ฐ™์€ ๋ถ€๋“ฑํ˜ธ๋ฅผ ํƒœ๊ทธ๋กœ ์˜ค์ธํ•˜์ง€ ์•Š๋„๋ก, ์•„๋Š” ํƒœ๊ทธ ์ด๋ฆ„ ๋ฐ”๋กœ ๋’ค๊ฐ€ ๊ณต๋ฐฑยท>ยท/ ์ธ ๊ฒฝ์šฐ๋งŒ HTML ๋กœ ๋ณธ๋‹ค
KNOWN_TAGS = ("table|thead|tbody|tfoot|tr|td|th|caption|colgroup|col|span|div|br|p|html|head|body|style|script|"
              "title|meta|b|i|u|strong|em|sub|sup|h[1-6]|ul|ol|li|center|font")
HTML_TAG = re.compile(rf"</?(?:{KNOWN_TAGS})(?=[\s>/])", re.IGNORECASE)
NOT_A_TAG = re.compile(rf"<(?!/?(?:{KNOWN_TAGS})(?=[\s>/])|!--|!DOCTYPE)", re.IGNORECASE)
HTML_TABLE = re.compile(r"<table\b|table_tabular|<tr\b|<td\b", re.IGNORECASE)
ENTITY = re.compile(r"&(?:lt|gt|amp|quot|apos|nbsp|#\d+|#x[0-9a-fA-F]+);")
FENCE = re.compile(r"^\s*```[a-zA-Z]*\s*$", re.MULTILINE)
DELIM_FIX = re.compile(r"([๊ฐ€-ํžฃ])\$([.,])\s+\$")          # '์ด๋‹ค$. $A$๋Š”' -> '์ด๋‹ค. $A$๋Š”'
DECIMAL_SPACE = re.compile(r"(?<=\d)\. (?=\d)")             # '0. 9455' -> '0.9455'
MATH_SPLIT = re.compile(r"(\$\$.*?\$\$|\$[^$]*\$|\\\[.*?\\\])", re.DOTALL)
TEXT_CLASSES = ("๋ฌธํ•ญ(ํ…์ŠคํŠธ)", "์ •๋‹ต(ํ…์ŠคํŠธ)", "์˜ค๋‹ต(ํ…์ŠคํŠธ)", "ํ•ด์„ค(ํ…์ŠคํŠธ)")
IMAGE_CLASSES = ("๋ฌธํ•ญ(์ด๋ฏธ์ง€)", "์ •๋‹ต(์ด๋ฏธ์ง€)", "์˜ค๋‹ต(์ด๋ฏธ์ง€)", "ํ•ด์„ค(์ด๋ฏธ์ง€)")


# ================================================================ HTML -> ๊ธ€์ž
VOID = {"br", "hr", "img", "meta", "link", "input", "col", "area", "base", "wbr"}
BLOCK = {"div", "p", "tr", "li", "ul", "ol", "h1", "h2", "h3", "h4", "h5", "h6", "center", "caption", "body", "html"}
DROP = {"style", "script", "head", "title"}


class Node:
    __slots__ = ("tag", "attrs", "kids")

    def __init__(self, tag: str, attrs: list | None = None):
        self.tag = tag
        self.attrs = {k: (v or "") for k, v in (attrs or [])}
        self.kids: list[Node | str] = []


class _Builder(HTMLParser):
    def __init__(self) -> None:
        super().__init__(convert_charrefs=True)
        self.root = Node("#root")
        self.stack = [self.root]

    def handle_starttag(self, tag, attrs):
        n = Node(tag, attrs)
        self.stack[-1].kids.append(n)
        if tag not in VOID:
            self.stack.append(n)

    def handle_startendtag(self, tag, attrs):
        self.stack[-1].kids.append(Node(tag, attrs))

    def handle_endtag(self, tag):
        for i in range(len(self.stack) - 1, 0, -1):
            if self.stack[i].tag == tag:
                del self.stack[i:]
                return

    def handle_data(self, data):
        self.stack[-1].kids.append(data)


def parse_html(s: str) -> Node:
    b = _Builder()
    b.feed(NOT_A_TAG.sub("&lt;", s))    # ํƒœ๊ทธ๊ฐ€ ์•„๋‹Œ '<' ๋Š” ๊ธ€์ž๋กœ ์ง€ํ‚จ๋‹ค
    b.close()
    return b.root


def has_tag(n: Node, tag: str) -> bool:
    return any(isinstance(k, Node) and (k.tag == tag or has_tag(k, tag)) for k in n.kids)


def find_rows(n: Node) -> list[Node]:
    rows = []
    for k in n.kids:
        if isinstance(k, Node):
            if k.tag == "tr":
                rows.append(k)
            elif k.tag != "table":      # ํ‘œ ์•ˆ์˜ ํ‘œ๋Š” ๋”ฐ๋ผ๊ฐ€์ง€ ์•Š์Œ
                rows.extend(find_rows(k))
    return rows


def esc_pipes(cell: str) -> str:
    """๋งˆํฌ๋‹ค์šด ํ‘œ ์นธ ์•ˆ์˜ '|' ์ฒ˜๋ฆฌ: ์ˆ˜์‹ ์†์€ \\vert, ๊ทธ ๋ฐ–์€ \\|"""
    out = []
    for part in MATH_SPLIT.split(cell):
        out.append(part.replace("|", "\\vert ") if MATH_SPLIT.fullmatch(part) else part.replace("|", "\\|"))
    return "".join(out)


def cell_text(n: Node, stats: Counter) -> str:
    return re.sub(r"\s+", " ", render_children(n, stats)).strip()


def grid_to_md(grid: list[list[str]], spans: bool, stats: Counter, spans_info: list[list[tuple[int, int]]]) -> str:
    width = max(len(r) for r in grid)
    if spans:      # ๋ณ‘ํ•ฉ ์นธ์ด ์žˆ์œผ๋ฉด ๋งˆํฌ๋‹ค์šด ํ‘œ๋กœ ๋ชป ๋‚˜ํƒ€๋‚ด๋ฏ€๋กœ ์ •๋ฆฌ๋œ HTML ํ‘œ(ํƒœ๊ทธ๋Š” table/tr/td/th, ์†์„ฑ์€ ๋ณ‘ํ•ฉ๋งŒ)
        stats["tables_html_fallback"] += 1
        lines = ["<table>"]
        for r, info in zip(grid, spans_info):
            tds = []
            for text, (cs, rs) in zip(r, info):
                attr = (f' colspan="{cs}"' if cs > 1 else "") + (f' rowspan="{rs}"' if rs > 1 else "")
                tds.append(f"<td{attr}>{html.escape(text, quote=False)}</td>")
            lines.append("<tr>" + "".join(tds) + "</tr>")
        lines.append("</table>")
        return "\n".join(lines)
    stats["tables_md"] += 1
    rows = [r + [""] * (width - len(r)) for r in grid]
    md = ["| " + " | ".join(esc_pipes(c) for c in rows[0]) + " |", "|" + " --- |" * width]
    md += ["| " + " | ".join(esc_pipes(c) for c in r) + " |" for r in rows[1:]]
    return "\n".join(md)


def table_to_md(n: Node, stats: Counter) -> str:
    rows = find_rows(n)
    grid, info, spans = [], [], False
    for tr in rows:
        cells = [k for k in tr.kids if isinstance(k, Node) and k.tag in ("td", "th")]
        if not cells:
            continue
        grid.append([cell_text(c, stats) for c in cells])
        row_info = []
        for c in cells:
            try:
                cs, rs = int(c.attrs.get("colspan", 1) or 1), int(c.attrs.get("rowspan", 1) or 1)
            except ValueError:
                cs = rs = 1
            row_info.append((cs, rs))
            spans = spans or cs > 1 or rs > 1
        info.append(row_info)
    if not grid:
        stats["tables_failed"] += 1
        return "[[TABLE_FAILED]]"
    return grid_to_md(grid, spans, stats, info)


def grid_div_to_md(n: Node, stats: Counter) -> str:
    """<table> ํƒœ๊ทธ๊ฐ€ ์—†๋Š” div ๊ฒฉ์ž: ์ž์‹ = ํ–‰, ์†์ž = ์นธ ์ด๋ผ๊ณ  ๋ณด๊ณ  ์ฝ๋Š”๋‹ค (์ฝ๊ธฐ ์‹คํŒจ ์‹œ ์‹คํŒจ๋กœ ๊ธฐ๋ก)."""
    rows = [k for k in n.kids if isinstance(k, Node)]
    grid = []
    for r in rows:
        cells = [k for k in r.kids if isinstance(k, Node)]
        if cells:
            grid.append([cell_text(c, stats) for c in cells])
    if len(grid) < 1 or max(len(r) for r in grid) < 1:
        stats["tables_failed"] += 1
        return "[[TABLE_FAILED]]"
    stats["tables_div_grid"] += 1
    return grid_to_md(grid, False, stats, [])


def render_children(n: Node, stats: Counter) -> str:
    return "".join(k if isinstance(k, str) else render_el(k, stats) for k in n.kids)


def render_el(n: Node, stats: Counter) -> str:
    t = n.tag
    if t in DROP:
        return ""
    if t == "br":
        return "\n"
    if t == "table":
        stats["tables_found"] += 1
        return "\n\n" + table_to_md(n, stats) + "\n\n"
    cls = n.attrs.get("class", "")
    if t == "div" and "table_tabular" in cls and not has_tag(n, "table"):
        stats["tables_found"] += 1
        return "\n\n" + grid_div_to_md(n, stats) + "\n\n"
    inner = render_children(n, stats)
    if t == "span" and "math-block" in cls:
        body = inner.strip()
        for d in ("$$", "$"):          # ์ด๋ฏธ ๋‹ฌ๋Ÿฌ๋กœ ๊ฐ์‹ธ์ ธ ์žˆ์œผ๋ฉด ๋ฒ—๊ธฐ๊ณ  ์•„๋ž˜์—์„œ $$ ๋กœ ๋‹ค์‹œ ๊ฐ์‹ผ๋‹ค
            if len(body) > 2 * len(d) and body.startswith(d) and body.endswith(d):
                body = body[len(d):-len(d)].strip()
                break
        return "\n$$" + body + "$$\n" if body else ""
    if t in BLOCK:
        return "\n" + inner + "\n"
    return inner


# ================================================================ ๊ธ€์ž ๋‹ค๋“ฌ๊ธฐ
@dataclass
class Cleaned:
    text: str
    has_table: bool = False
    table_failed: bool = False
    html_cleaned: bool = False
    notes: set = field(default_factory=set)


def tidy(s: str, notes: set) -> str:
    s = s.replace("\u00a0", " ").replace("\u200b", "")
    s = re.sub(r"[ \t]+", " ", s)
    s = re.sub(r" *\n *", "\n", s)
    s = re.sub(r"\n{3,}", "\n\n", s).strip()
    s2 = DELIM_FIX.sub(r"\1\2 $", s)
    if s2 != s:
        notes.add("delimiter_fixed")
        s = s2

    def dec(m: re.Match) -> str:
        text, j = m.string, m.start()
        while j > 0 and text[j - 1].isdigit():
            j -= 1
        return m.group(0) if (j == 0 or text[j - 1] == "\n") else "."   # ์ค„ ๋งจ ์•ž '1. 2๋ฒˆ' ์€ ๋ฒˆํ˜ธ๋ผ์„œ ๋‘ 

    s2 = DECIMAL_SPACE.sub(dec, s)
    if s2 != s:
        notes.add("decimal_space_fixed")
        s = s2
    return s


def clean_box(raw: str, stats: Counter) -> Cleaned:
    out = Cleaned(text="")
    s = FENCE.sub("", raw or "")
    if s != (raw or ""):
        out.notes.add("code_fence_removed")
    if HTML_TAG.search(s):
        out.html_cleaned = True
        out.has_table = bool(HTML_TABLE.search(s))
        before = stats["tables_failed"]
        s = render_children(parse_html(s), stats)
        if "[[TABLE_FAILED]]" in s or stats["tables_failed"] > before:
            out.table_failed = True
    elif ENTITY.search(s):
        s = html.unescape(s)
        out.notes.add("entity_unescaped")
    out.text = tidy(s, out.notes)
    return out


def finalize_md(s: str) -> str:
    """์ €์žฅ ์ง์ „: ์ˆ˜์‹ ๋ฐ– < > ๋Š” &lt; &gt; ๋กœ, ์ˆ˜์‹ ์•ˆ์€ \\lt \\gt ๋กœ (ํ™”๋ฉด์—์„œ ํƒœ๊ทธ๋กœ ์˜ค์ธ๋˜์ง€ ์•Š๊ฒŒ)."""
    out = []
    for part in MATH_SPLIT.split(s):
        if MATH_SPLIT.fullmatch(part):
            out.append(part.replace("<", "\\lt ").replace(">", "\\gt "))
        else:
            out.append(re.sub(r"</?(?:table|tr|td|th)\b[^>]*>", lambda m: m.group(0), part)
                       if part.lstrip().startswith("<table>") else part.replace("<", "&lt;").replace(">", "&gt;"))
    return "".join(out)


def finalize_with_tables(s: str) -> str:
    """์ •๋ฆฌ๋œ HTML ํ‘œ(<table>...</table>)๋Š” ๊ทธ๋Œ€๋กœ ๋‘๊ณ  ๊ทธ ๋ฐ–์˜ ๊ธ€์ž๋งŒ finalize_md ๋กœ ์ฒ˜๋ฆฌ."""
    pieces = re.split(r"(<table>.*?</table>)", s, flags=re.DOTALL)
    return "".join(p if p.startswith("<table>") else finalize_md(p) for p in pieces)


def is_pure_math(text: str) -> bool:
    rest = MATH_SPAN.sub("", text)
    return len(HANGUL.findall(rest)) < 5


def damage_of(text: str) -> list[str]:
    return [name for name, rx in DAMAGE_CHECKS if rx.search(text)]


# ================================================================ ๋ฌธํ•ญ ํ•œ ๊ฐœ ์ •์ œ
@dataclass
class Item:
    cls: str
    kind: str            # text / formula / figure / table
    text: str
    y: float
    x: float
    bbox: list
    table_failed: bool = False


def bbox_of(box: dict) -> list[float]:
    try:
        tv = box.get("Type_value")
        v = tv[0] if tv and isinstance(tv[0], (list, tuple)) else tv
        return [float(v[0]), float(v[1]), float(v[2]), float(v[3])]
    except Exception:
        return [0.0, 0.0, 0.0, 0.0]


def join_pieces(pieces: list[str]) -> str:
    """์ƒ์ž ์กฐ๊ฐ๋“ค์„ ์ด์–ด ๋ถ™์ž„: ํ‘œ์‹œ ์ˆ˜์‹($$, \\[ )๊ณผ ํ‘œ๋Š” ์ค„์„ ๋ฐ”๊พธ๊ณ , ๋ฌธ์žฅ ์กฐ๊ฐ์€ ๊ณต๋ฐฑ์œผ๋กœ ์ž‡๋Š”๋‹ค."""
    out = ""
    for p in pieces:
        p = p.strip()
        if not p:
            continue
        if not out:
            out = p
        elif (p.startswith(("$$", "\\[", "|", "<table")) or out.endswith(("$$", "\\]", "</table>"))
              or out.rsplit("\n", 1)[-1].lstrip().startswith("|")):          # ํ‘œ ๋ฐ”๋กœ ๋’ค ๋ฌธ์žฅ์€ ์ƒˆ ๋ฌธ๋‹จ์œผ๋กœ(ํ‘œ ์ค„์— ๋ถ™์œผ๋ฉด ์‚ฌ๋ผ์ง)
            after_table = out.endswith("</table>") or out.rsplit("\n", 1)[-1].lstrip().startswith("|")
            out += "\n\n" + p if (p.startswith(("|", "<table")) or after_table) else "\n" + p
        else:
            out += " " + p
    return out


def split_marked(text: str) -> dict[str, str]:
    """'โ‘ก 5 โ‘ข 7' -> {'โ‘ก': '5', 'โ‘ข': '7'} (๋™๊ทธ๋ผ๋ฏธ ์ˆซ์ž ๊ธฐ์ค€์œผ๋กœ ์ชผ๊ฐฌ)"""
    ms = list(re.finditer(f"[{CIRCLED}]", text))
    res: dict[str, list[str]] = {}
    for i, m in enumerate(ms):
        end = ms[i + 1].start() if i + 1 < len(ms) else len(text)
        res.setdefault(m.group(0), []).append(text[m.end():end].strip())
    return {k: v for k, v in ((d, vs) for d, vs in res.items())} and {k: "\u0000".join(v) for k, v in res.items()}


def strip_dollars(s: str) -> str:
    s = re.sub(r"\\text\s*\{([^{}]*)\}", r"\1", s)
    s = s.replace("$", "").replace("\\,", "").replace("\\;", "").replace("\\!", "")
    return re.sub(r"\s+", " ", s).strip().rstrip(".").strip()


def load_unit_map(path: Path) -> dict[str, dict[str, dict[str, str]]]:
    """{"2022": {2022์ฝ”๋“œ: ํ–‰}, "2015": {2015์ฝ”๋“œ: ํ–‰}}  - ๋‘ ๊ต์œก๊ณผ์ •์˜ ์ฝ”๋“œ๊ฐ€ ๊ฐ™์€ ๊ธ€์ž์—ฌ๋„ ๋œป์ด ๋‹ค๋ฅผ ์ˆ˜ ์žˆ์–ด ๋”ฐ๋กœ ๋ณด๊ด€"""
    if not path.exists():
        return {}
    with path.open(encoding="utf-8-sig", newline="") as f:
        rows = list(csv.DictReader(f))
    return {"2022": {r["code_2022_primary"]: r for r in rows if r.get("code_2022_primary")},
            "2015": {r["code_2015_primary"]: r for r in rows if r.get("code_2015_primary")}}


def normalize_one(data: dict, origin: dict, unit_map: dict, stats: Counter, html_dump: list | None = None):
    raw = data.get("raw_data_info") or {}
    src = data.get("source_data_info") or {}
    ref = str(src.get("source_data_name") or "").strip()
    gcode = GRADE_CODE.get((raw.get("school"), raw.get("grade")))
    if not ref or not gcode:
        stats["skipped_no_ref_or_grade"] += 1
        return None
    diff_txt, ptype_txt = str(src.get("level_of_difficulty")), str(src.get("types_of_problems"))
    qtype = QTYPE.get(ptype_txt)

    s2015 = " / ".join(x.strip() for x in src.get("2015_achievement_standard", []) or [] if x.strip())
    s2022 = " / ".join(x.strip() for x in src.get("2022_achievement_standard", []) or [] if x.strip())
    codes = CODE_RE.findall(s2015)
    codes22 = CODE_RE.findall(s2022)
    # 2022 ๊ฐœ์ • ๊ต์œก๊ณผ์ • ๊ธฐ์ค€์„ ์šฐ์„  ์‚ฌ์šฉํ•˜๊ณ , 2022 ์ฝ”๋“œ๊ฐ€ ๋น„์—ˆ๊ฑฐ๋‚˜ ํ‘œ์— ์—†์„ ๋•Œ๋งŒ 2015 ์ฝ”๋“œ๋กœ ๋ณด์ถฉํ•œ๋‹ค
    um, unit_basis = None, None
    if codes22 and unit_map.get("2022", {}).get(codes22[0]):
        um, unit_basis = unit_map["2022"][codes22[0]], "2022"
    elif codes and unit_map.get("2015", {}).get(codes[0]):
        um, unit_basis = unit_map["2015"][codes[0]], "2015_fallback"

    classes: dict[str, list] = {}
    for block in data.get("learning_data_info", []) or []:
        classes.setdefault(str(block.get("class_name")), []).extend(block.get("class_info_list", []) or [])

    flags: set[str] = set()
    reasons: list[str] = []
    local = Counter()

    def items_of(*names: str) -> list[Item]:
        res = []
        for cn in names:
            for b in classes.get(cn, []):
                rawt = str(b.get("text_description", "") or "")
                c = clean_box(rawt, local)
                if c.html_cleaned or c.notes:
                    flags.update(c.notes)
                    if c.html_cleaned:
                        flags.add("html_cleaned")
                if c.has_table:
                    flags.add("table_rendered")
                    if html_dump is not None and (HTML_TABLE.search(rawt)):
                        html_dump.append({"source_ref": ref, "class": cn, "raw": rawt, "converted": c.text})
                if cn.endswith("(์ด๋ฏธ์ง€)"):
                    kind = "table" if c.has_table else ("formula" if is_pure_math(c.text) else "figure")
                else:
                    kind = "text"
                bb = bbox_of(b)
                res.append(Item(cn, kind, c.text, bb[1], bb[0], bb, c.table_failed))
        return sorted(res, key=lambda it: (it.y, it.x))

    # ---- ๋ฌธํ•ญ ๋ณธ๋ฌธ
    stem_items = items_of("๋ฌธํ•ญ(ํ…์ŠคํŠธ)", "๋ฌธํ•ญ(์ด๋ฏธ์ง€)")
    has_stem_text = bool(classes.get("๋ฌธํ•ญ(ํ…์ŠคํŠธ)")) and any(i.kind == "text" and i.text for i in stem_items)
    if not has_stem_text:
        reasons.append("no_stem_text")
    stem_vis = [i for i in stem_items if i.kind != "figure"]
    stem_figs = [i for i in stem_items if i.kind == "figure"]
    stem_raw = join_pieces([i.text for i in stem_vis])
    if re.search(r"(?:๋ฌผ์Œ|์งˆ๋ฌธ)์—\s*๋‹ตํ•˜์‹œ์˜ค\.?\s*$", stem_raw.strip()):      # ๋ฌป๋Š” ๋ฌธ์žฅ ์—†์ด ๋๋‚จ -> ์งˆ๋ฌธ์ด ๋น ์ง„ ๋ฌธํ•ญ
        reasons.append("stem_incomplete")

    # ---- ์ •๋‹ต / ์„ ํƒ์ง€
    ans_items = items_of("์ •๋‹ต(ํ…์ŠคํŠธ)", "์ •๋‹ต(์ด๋ฏธ์ง€)")
    wrong_items = items_of("์˜ค๋‹ต(ํ…์ŠคํŠธ)", "์˜ค๋‹ต(์ด๋ฏธ์ง€)")
    choice_items = sorted(ans_items + wrong_items, key=lambda it: (it.y, it.x))
    choice_figs = [i for i in choice_items if i.kind == "figure"]
    if any(i.table_failed for i in stem_items + choice_items):
        reasons.append("table_convert_failed")
    if not ans_items:
        reasons.append("no_answer")

    choices: list[str] = []
    answer = ""
    answer_display = ""
    accepted: list[str] = []
    # ๊ฐ๊ด€์‹์ด๋ผ๊ณ  ์ ํ˜€ ์žˆ์ง€๋งŒ ์˜ค๋‹ต ์ƒ์ž๊ฐ€ ์—†๊ณ  ์ •๋‹ต์—๋„ โ‘ ~โ‘ค ๊ฐ€ ์—†์œผ๋ฉด(์˜ˆ: ์ •๋‹ต์ด 'ใ‰ ') ๋‹จ๋‹ตํ˜•์œผ๋กœ ์ทจ๊ธ‰
    if (qtype == "multiple_choice" and ans_items and not wrong_items
            and not any(c in CIRCLED for it in ans_items for c in it.text)):
        qtype = "short_answer"
        flags.add("mc_without_choices")
    if qtype == "multiple_choice":
        merged: dict[str, str] = {}
        conflict = False
        for it in choice_items:
            if it.kind == "figure":      # ๊ทธ๋ฆผ ์„ ํƒ์ง€: ์„ค๋ช…๋ฌธ ์† ๋ฒˆํ˜ธ๋ฅผ ์ชผ๊ฐœ์ง€ ์•Š๊ณ  ๋งจ ์•ž ๋ฒˆํ˜ธ๋งŒ ์“ด๋‹ค
                for dd in re.findall(rf"([{CIRCLED}])\s*(?:์ด๋ฏธ์ง€|๊ทธ๋ฆผ)", it.text) or re.findall(rf"^\s*([{CIRCLED}])", it.text):
                    merged.setdefault(dd, "(๊ทธ๋ฆผ)")
                    flags.add("choices_are_figures")
                continue
            for d, txt in split_marked(it.text).items():
                for one in txt.split("\u0000"):
                    if d in merged and merged[d] != one:
                        conflict = True
                    merged.setdefault(d, one)
        # ์ •๋‹ต ์ƒ์ž์—๋งŒ ๋ฒˆํ˜ธ๊ฐ€ ๋น ์ง„ ๊ฒฝ์šฐ: ๋ฒˆํ˜ธ๊ฐ€ ๋ถ™์€ ์„ ํƒ์ง€๊ฐ€ 4๊ฐœ์ด๊ณ  ๋ฒˆํ˜ธ ์—†๋Š” ์ •๋‹ต ์ƒ์ž๊ฐ€ 1๊ฐœ๋ฉด, ๋น ์ง„ ๋ฒˆํ˜ธ๊ฐ€ ์ •๋‹ต์ด๋‹ค
        inferred = None
        plain = [it for it in ans_items if it.kind != "figure"]
        if (not conflict and len(plain) == 1 and not any(c in CIRCLED for c in plain[0].text)
                and len([d for d in CIRCLED if d not in merged]) == 1 and plain[0].text.strip()):
            inferred = next(d for d in CIRCLED if d not in merged)
            merged[inferred] = plain[0].text.strip()
            flags.add("answer_marker_inferred")
        if conflict:
            reasons.append("choice_conflict")
        if all(d in merged and merged[d] for d in CIRCLED):
            choices = [f"{d} {merged[d]}" for d in CIRCLED]
        else:
            reasons.append("choices_incomplete")
        ans_digits = []
        for it in ans_items:
            if it.kind == "figure":
                ans_digits += (re.findall(rf"([{CIRCLED}])\s*(?:์ด๋ฏธ์ง€|๊ทธ๋ฆผ)", it.text)
                               or re.findall(rf"^\s*([{CIRCLED}])", it.text))[:1]
            else:
                ans_digits += [c for c in it.text if c in CIRCLED]
        ans_unique = sorted(set(ans_digits))
        multi_ask = bool(re.search(r"๋ชจ๋‘|๋‘\s*๊ฐœ|2\s*๊ฐœ|์„ธ\s*๊ฐœ|3\s*๊ฐœ", stem_raw))
        if inferred:
            answer = str(CIRCLED.index(inferred) + 1)
            answer_display = inferred
        elif len(ans_unique) == 1:
            answer = str(CIRCLED.index(ans_unique[0]) + 1)
            answer_display = ans_unique[0]
        elif len(ans_unique) >= 2 and multi_ask:
            # ๋ณต์ˆ˜ ์ •๋‹ต: '1,4' ์ฒ˜๋Ÿผ ์‰ผํ‘œ๋กœ ์ด์€ ๋ฒˆํ˜ธ (์ฑ„์ ์€ ์ง‘ํ•ฉ ๋น„๊ต๋กœ ํ•ด์•ผ ํ•จ)
            answer = ",".join(str(CIRCLED.index(d) + 1) for d in ans_unique)
            answer_display = " ".join(ans_unique)
            flags.add("multi_answer")
        elif ans_items:
            reasons.append("answer_unparsed" if not ans_unique else "answer_ambiguous")
    elif qtype == "short_answer":
        pieces = [i.text for i in ans_items if i.kind != "figure"]
        if any(i.kind == "figure" for i in ans_items):
            reasons.append("answer_is_figure")
        answer_display = join_pieces(pieces)
        answer = strip_dollars(answer_display)
        if not answer and ans_items:
            reasons.append("answer_unparsed")
        accepted = [a for a in dict.fromkeys([answer, answer.replace(" ", "")]) if a]
    else:
        reasons.append("unknown_problem_type")

    # ---- ํ•ด์„ค
    sol_items = items_of("ํ•ด์„ค(ํ…์ŠคํŠธ)", "ํ•ด์„ค(์ด๋ฏธ์ง€)")
    sol_vis = [i for i in sol_items if i.kind != "figure"]
    sol_figs = [i for i in sol_items if i.kind == "figure"]
    sol_raw = join_pieces([i.text for i in sol_vis])
    if any(i.table_failed for i in sol_items):
        flags.add("solution_table_failed")

    # ---- ๊ธ€์ž ๊นจ์ง (๋ฌธํ•ญยท์„ ํƒ์ง€ยท์ •๋‹ต / ํ•ด์„ค์„ ๋”ฐ๋กœ ๋ณธ๋‹ค)
    dmg_main: set[str] = set()
    for i in stem_vis:
        dmg_main.update(damage_of(i.text))
    for it in choice_items:     # ์„ ํƒ์ง€๋Š” ๋™๊ทธ๋ผ๋ฏธ ์ˆซ์ž๋ฅผ ๋–ผ๊ณ  ์กฐ๊ฐ๋ณ„๋กœ ๊ฒ€์‚ฌ (์ •์ƒ์ ์ธ '1โ‘ข' ์˜คํƒ ๋ฐฉ์ง€)
        if it.kind == "figure":
            continue
        for txt in split_marked(it.text).values():
            for one in txt.split("\u0000"):
                dmg_main.update(damage_of(one))
        if qtype == "short_answer" and it in ans_items:
            dmg_main.update(damage_of(it.text))
    if dmg_main:
        reasons.append("broken_math_in_stem_or_choice:" + ",".join(sorted(dmg_main)))
    dmg_sol = set(damage_of(sol_raw))

    solution_md = None
    if not sol_raw:
        flags.add("solution_missing")
    elif dmg_sol:
        flags.add("solution_broken")
    else:
        solution_md = finalize_with_tables(sol_raw)
    if sol_figs:
        flags.add("solution_needs_figure")
        solution_md = None      # ๊ทธ๋ฆผ์ด ์žˆ์–ด์•ผ ์ดํ•ด๋˜๋Š” ํ•ด์„ค์€ ํ•™์ƒ์—๊ฒŒ ๊ทธ๋Œ€๋กœ ๋ณด์ด์ง€ ์•Š๊ณ , ์ƒˆ๋กœ ๋งŒ๋“ค ๋•Œ๊นŒ์ง€ ๋น„์›Œ ๋‘”๋‹ค

    # ---- ๋“ฑ๊ธ‰
    if reasons:
        tier = "C"
    elif stem_figs or choice_figs:
        tier = "B"
    else:
        tier = "A"
    if unit_basis == "2015_fallback":
        flags.add("unit_by_2015_fallback")
    if um is None:
        flags.add("unit_unmapped")
    elif um.get("confidence") and um["confidence"] != "high":
        flags.add("unit_medium_confidence")

    fig_boxes = [{"class": i.cls, "bbox": i.bbox, "description": i.text[:300]} for i in stem_figs + choice_figs]
    fig_desc = " / ".join(i.text for i in stem_figs + choice_figs) or None
    stats.update(local)

    meta = {
        "dataset": "aihub-71859", "split": origin.get("split"), "zip": origin.get("zip"), "json": origin.get("json"),
        "school": raw.get("school"), "grade_text": raw.get("grade"), "semester": raw.get("semester"),
        "publisher": raw.get("publisher"), "revision_year": raw.get("revision_year"),
        "standard_2015": s2015, "standard_2022": s2022, "unit_code_2015": codes[0] if codes else None,
        "unit_code_2022": codes22[0] if codes22 else None, "unit_basis": unit_basis,
        "unit_confidence": (um or {}).get("confidence"), "difficulty_text": diff_txt, "problem_type_text": ptype_txt,
        "tier": tier, "reasons": reasons, "flags": sorted(flags),
        "needs_figure": bool(stem_figs or choice_figs), "figure_boxes": fig_boxes,
        "answer_display_md": finalize_with_tables(answer_display) if answer_display else None,
        "solution_raw_broken": finalize_with_tables(sol_raw) if (sol_raw and solution_md is None) else None,
    }
    row = {
        "source": "aihub", "source_ref": ref, "source_meta": meta, "rights_status": "unreviewed",
        "grade_code": gcode, "unit_id": (um or {}).get("unit_id"), "difficulty": DIFF_CODE.get(diff_txt), "score": None,
        "qtype": qtype, "stem_md": finalize_with_tables(stem_raw), "choices": choices, "figure_description": fig_desc,
        "figure_path": None, "answer": answer, "accepted_answers": accepted, "solution_md": solution_md, "intent": None,
        "verified": False, "verify_note": None, "status": "draft",
    }
    return row, tier


# ================================================================ ์ž…์ถœ๋ ฅ
def read_json(raw: bytes) -> dict | None:
    for enc in ("utf-8-sig", "utf-8", "cp949"):
        try:
            return json.loads(raw.decode(enc))
        except Exception:
            continue
    return None


def iter_label_files(root: Path, limit: int | None):
    n = 0
    zips = sorted({p for pat in PATTERNS for p in root.rglob(pat)})
    for zpath in zips:
        split = "training" if zpath.name.upper().startswith("TL_") else "validation"
        with zipfile.ZipFile(zpath) as zf:
            for info in zf.infolist():
                if info.is_dir() or not info.filename.lower().endswith(".json"):
                    continue
                data = read_json(zf.read(info))
                yield data, {"split": split, "zip": zpath.name, "json": info.filename}
                n += 1
                if limit and n >= limit:
                    return
    if not zips:       # zip ์ด ์—†์œผ๋ฉด ํ’€์–ด ๋‘” JSON ํด๋”๋กœ ๋ณด๊ณ  ์ฝ๋Š”๋‹ค (์‹œํ—˜์šฉ)
        for jp in sorted(root.rglob("*.json")):
            yield read_json(jp.read_bytes()), {"split": "loose", "zip": None, "json": jp.name}
            n += 1
            if limit and n >= limit:
                return


def load_all_units(path: Path) -> list[tuple[str, str]]:
    if not path.exists():
        return []
    text = path.read_text(encoding="utf-8")
    ids = re.findall(r"^\s*-\s*id:\s*([UM]\d+)", text, re.M)
    names = re.findall(r'^\s*name:\s*"([^"]+)"', text, re.M)
    return list(zip(ids, names)) if ids and len(ids) == len(names) else []


def main() -> None:
    ap = argparse.ArgumentParser(description="AI Hub ๋ผ๋ฒจ๋ง zip -> ์ •์ œ JSONL")
    ap.add_argument("--root", type=Path, required=True, help="TL_*/VL_* zip ์ด ์žˆ๋Š” ํด๋” (์˜ˆ: D:\\์ˆ˜ํ•™)")
    ap.add_argument("--out", type=Path, default=ROOT / "data" / "aihub_normalized")
    ap.add_argument("--unit-map", type=Path, default=ROOT / "configs" / "standard_unit_map.csv")
    ap.add_argument("--units-yaml", type=Path, default=ROOT / "configs" / "curriculum_units.yaml")
    ap.add_argument("--limit", type=int, help="๋ง›๋ณด๊ธฐ: ์•ž์—์„œ ์ด ๊ฐœ์ˆ˜๋งŒ ์ฒ˜๋ฆฌ")
    ap.add_argument("--inspect", nargs="+", metavar="SOURCE_REF", help="๋ฌธํ•ญ ์ด๋ฆ„(์˜ˆ: S3_์ค‘๋“ฑ_1_000005)์˜ ์›๋ณธ ์ƒ์ž ๊ตฌ์กฐ๋ฅผ ์ถœ๋ ฅํ•˜๊ณ  ๋๋ƒ„")
    ap.add_argument("--dump-tables", type=int, default=0, help="ํ‘œ๊ฐ€ ๋“  ์›๋ณธ N๊ฐœ๋ฅผ tables_dump.jsonl ๋กœ ์ €์žฅ(๋ณ€ํ™˜ ํ™•์ธ์šฉ)")
    a = ap.parse_args()

    if a.inspect:
        want = set(a.inspect)
        for data, origin in iter_label_files(a.root, None):
            nm = str(((data or {}).get("source_data_info") or {}).get("source_data_name") or "")
            if nm in want:
                print("=" * 70, "\n", nm, origin["zip"])
                for blk in data.get("learning_data_info", []) or []:
                    for b in blk.get("class_info_list", []) or []:
                        print(f"[{blk.get('class_name')}] bbox={bbox_of(b)}  {str(b.get('text_description'))[:160]!r}")
                want.discard(nm)
                if not want:
                    break
        if want:
            print("์ฐพ์ง€ ๋ชปํ•จ:", sorted(want))
        return

    unit_map = load_unit_map(a.unit_map)
    if unit_map and not unit_map.get("2022"):
        print(f"[๊ฒฝ๊ณ ] {a.unit_map} ์— code_2022_primary ์—ด์ด ์—†์Šต๋‹ˆ๋‹ค. ์ƒˆ standard_unit_map.csv ๋กœ ๋ฎ์–ด์“ฐ์„ธ์š”. "
              "(์ง€๊ธˆ์€ ๋ชจ๋“  ๋ฌธํ•ญ์ด 2015 ์ฝ”๋“œ๋กœ๋งŒ ๋‹จ์›์ด ์ •ํ•ด์ง‘๋‹ˆ๋‹ค)")
    if not unit_map:
        print(f"[์•Œ๋ฆผ] {a.unit_map} ๋ฅผ ์ฝ์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค. ๋ชจ๋“  ๋ฌธํ•ญ์˜ unit_id ๊ฐ€ ๋น„๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.")
    a.out.mkdir(parents=True, exist_ok=True)

    stats, tier_count = Counter(), Counter()
    reason_count, flag_count = Counter(), Counter()
    seen: dict[str, str] = {}
    dups = 0
    matrix: dict[tuple[str, str], Counter] = defaultdict(Counter)
    dump: list = [] if a.dump_tables else None
    failed_tables: list = []
    files = {t: (a.out / f"aihub_{t}.jsonl").open("w", encoding="utf-8") for t in ("A", "B", "C")}
    total = 0
    try:
        for data, origin in iter_label_files(a.root, a.limit):
            total += 1
            if total % 2000 == 0:
                print(f"  ... {total}๊ฐœ ์ฒ˜๋ฆฌ")
            if not isinstance(data, dict):
                stats["json_parse_fail"] += 1
                continue
            res = normalize_one(data, origin, unit_map, stats, dump)
            if res is None:
                continue
            row, tier = res
            ref = row["source_ref"]
            if ref in seen:
                dups += 1
                continue
            seen[ref] = origin["zip"] or origin["json"]
            tier_count[tier] += 1
            for r in row["source_meta"]["reasons"]:
                reason_count[r.split(":")[0] + (":" + r.split(":")[1] if ":" in r else "")] += 1
            for fl in row["source_meta"]["flags"]:
                flag_count[fl] += 1
            if "table_convert_failed" in row["source_meta"]["reasons"]:
                failed_tables.append({"source_ref": ref})
            matrix[(row["unit_id"] or "?", row["difficulty"] or "?")][tier] += 1
            files[tier].write(json.dumps(row, ensure_ascii=False) + "\n")
    finally:
        for f in files.values():
            f.close()

    if dump:
        with (a.out / "tables_dump.jsonl").open("w", encoding="utf-8") as f:
            for d in dump[: a.dump_tables]:
                f.write(json.dumps(d, ensure_ascii=False) + "\n")
    if stats["tables_failed"]:
        with (a.out / "tables_failed.jsonl").open("w", encoding="utf-8") as f:
            for d in (dump or []):
                if "[[TABLE_FAILED]]" in d["converted"]:
                    f.write(json.dumps(d, ensure_ascii=False) + "\n")

    # ์ปค๋ฒ„๋ฆฌ์ง€ ํ‘œ
    diff_order = ("low", "mid", "high")
    rows = []
    unit_names = {u: n for u, n in load_all_units(a.units_yaml)}
    units = sorted({u for u, _ in matrix} | set(unit_names), key=lambda u: (u[0] != "U", u))
    for u in units:
        r = {"unit_id": u, "unit_name": unit_names.get(u, ""), }
        for d in diff_order:
            c = matrix.get((u, d), Counter())
            r[f"A_{d}"], r[f"usable_{d}"] = c["A"], c["A"] + c["B"]
        rows.append(r)
    with (a.out / "coverage_after.csv").open("w", encoding="utf-8-sig", newline="") as f:
        w = csv.DictWriter(f, fieldnames=["unit_id", "unit_name", "A_low", "A_mid", "A_high",
                                          "usable_low", "usable_mid", "usable_high"])
        w.writeheader()
        w.writerows(rows)

    n_out = sum(tier_count.values())
    total_ok = n_out
    L = [f"AI Hub ์ •์ œ ๊ฒฐ๊ณผ  (์ฝ์€ JSON {total}๊ฐœ, ์ค‘๋ณต source_ref {dups}๊ฐœ ์ œ์™ธ, ์ถœ๋ ฅ {n_out}๊ฐœ)",
         f"๋“ฑ๊ธ‰: A {tier_count['A']} | B {tier_count['B']} | C {tier_count['C']}",
         f"  - A+B(์‚ฌ์šฉ ๊ฐ€๋Šฅ ํ›„๋ณด) {tier_count['A'] + tier_count['B']}๊ฐœ / ๋ฐ”๋กœ ์“ธ ์ˆ˜ ์žˆ๋Š” A {tier_count['A']}๊ฐœ"]
    L.append("C ๊ฐ€ ๋œ ์ด์œ (ํ•œ ๋ฌธํ•ญ์— ์ด์œ ๊ฐ€ ์—ฌ๋Ÿฌ ๊ฐœ์ผ ์ˆ˜ ์žˆ์Œ):")
    L += [f"  - {k}: {v}" for k, v in reason_count.most_common()] or ["  (์—†์Œ)"]
    L.append("๊ณ ์นœ ๊ฒƒ / ํ‘œ์‹œํ•œ ๊ฒƒ (๋ฌธํ•ญ ์ˆ˜):")
    L += [f"  - {k}: {v}" for k, v in flag_count.most_common()] or ["  (์—†์Œ)"]
    L.append(f"ํ‘œ ๋ณ€ํ™˜: ์ฐพ์€ ํ‘œ {stats['tables_found']}๊ฐœ -> ๋งˆํฌ๋‹ค์šด ํ‘œ {stats['tables_md']}, "
             f"div ๊ฒฉ์ž {stats['tables_div_grid']}, ๋ณ‘ํ•ฉ ์นธ์ด๋ผ HTML ํ‘œ {stats['tables_html_fallback']}, ์‹คํŒจ {stats['tables_failed']}")
    if stats["json_parse_fail"] or stats["skipped_no_ref_or_grade"]:
        L.append(f"๊ฑด๋„ˆ๋œ€: JSON ํ•ด์„ ์‹คํŒจ {stats['json_parse_fail']}, ์ด๋ฆ„ยทํ•™๋…„ ์ •๋ณด ์—†์Œ {stats['skipped_no_ref_or_grade']}")
    no_unit = 0
    unmapped = flag_count["unit_unmapped"]
    L.append(f"๋‹จ์› ๋งคํ•‘: 2022 ๊ธฐ์ค€ {total_ok - flag_count['unit_by_2015_fallback'] - unmapped}๊ฐœ, 2015 ์ฝ”๋“œ๋กœ ๋ณด์ถฉ {flag_count['unit_by_2015_fallback']}๊ฐœ, "
             f"๋งคํ•‘ ์‹คํŒจ {unmapped}๊ฐœ, ์‹ ๋ขฐ๋„ ๋‚ฎ์Œ(๊ฒ€ํ†  ํ•„์š”) {flag_count['unit_medium_confidence']}๊ฐœ")
    (a.out / "normalize_report.txt").write_text("\n".join(L) + "\n", encoding="utf-8")
    print("\n".join(L))
    print(f"[์ €์žฅ] {a.out}")


if __name__ == "__main__":
    main()