Spaces:
Running
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">) ์ ๊ฑฐ, ์ํฐํฐ(<) ๋ณต์, ```html ์ฝ๋ ์ธํ๋ฆฌ ์ ๊ฑฐ,
ํ(<table>, Mathpix ์ <div class="table_tabular">) -> ๋งํฌ๋ค์ด ํ(๋ณํฉ ์นธ์ด ์์ผ๋ฉด ์ ๋ฆฌ๋ HTML ํ),
'์ด๋ค$. $A$' ๊ฐ์ ๊ตฌ๋ถ์ ์ดํ, '0. 9455' ์์์ ๋ค ๊ณต๋ฐฑ,
์์ ๋ฐ์ < > ๋ < > ๋ก, ์์ ์์ < > ๋ \\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("<", 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 ๋ก (ํ๋ฉด์์ ํ๊ทธ๋ก ์ค์ธ๋์ง ์๊ฒ)."""
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("<", "<").replace(">", ">"))
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()
|