Spaces:
Running
Running
Download scripts/21_aihub_fix.py from lilyjeongwon/math-tutor: direct link, hf CLI and curl.
- Browser
- Download file 11.6 kB
-
https://huggingface.co/spaces/lilyjeongwon/math-tutor/resolve/main/scripts/21_aihub_fix.py
- Command line
-
hf download hf://spaces/lilyjeongwon/math-tutor/scripts/21_aihub_fix.py
-
curl -L -o 21_aihub_fix.py https://huggingface.co/spaces/lilyjeongwon/math-tutor/resolve/main/scripts/21_aihub_fix.py
11.6 kB
| r"""AI Hub ์ ์ ๊ฒฐ๊ณผ(aihub_A.jsonl)์ ์ ๊ฒ ๋ณด์ ์ ์ ์ฉํด DB ๊ฐฑ์ ์ฉ ํ์ผ์ ๋ง๋ ๋ค. (๋น์ฉยท์ธ๋ถ ์ฐ๊ธฐ ์์) | |
| python scripts\21_aihub_fix.py # -> data/aihub_normalized/aihub_A_fixed.jsonl + ์์ฝ | |
| python scripts\21_aihub_fix.py --list sub # ๊ท์น์ผ๋ก ๊ณ ์น ์๋ฌธํญ ๋ฒํธ ๋ชฉ๋ก ๋ณด๊ธฐ | |
| ์ ๋ ฅ | |
| data/aihub_normalized/aihub_A.jsonl 04 ์ ์ ๊ฒฐ๊ณผ (๊ทธ๋๋ก ๋๊ณ ์ฝ๊ธฐ๋ง ํจ) | |
| data/aihub_normalized/review/aihub_overrides.jsonl ๋ฌธํญ๋ณ ์ ๋ณด์ (๋์ค ์ค ์ฐ์ , ํ๋๋ณ ๋ฎ์ด์ฐ๊ธฐ) | |
| {"source_ref", "stem_md"?, "choices"?, "answer"?, "accepted_answers"?, "solution_md"?, | |
| "stem_subs"?: [[old, new]], "choice_set"?: [[๋ฒํธ, ์ ๋ณด๊ธฐ]], | |
| "solution_from_raw"?: true, "solution_subs"?: [[old, new]], | |
| "exclude"?: "์ฌ์ ", "keep_circled"?: true, "note"} | |
| ๋ฎ์ด์ฐ๊ธฐ ํ์ผ์ python tools/review/aihub_ov_all.py ๋ก ๋ค์ ๋ง๋ ๋ค (aihub_ov_batch*.py ์์๋๋ก). | |
| ๊ท์น (๋ณด์ ์ ยทํ๋ฅผ source_meta.fix ์ ๋จ๊น) | |
| R1 ์ง๋ฌธ ๋ ์๋ฌธํญ ๋ฒํธ: ์๋ณธ์ ์ฌ๋ฌ ์๋ฌธํญ์ ํ ๋ฌธํญ์ผ๋ก ์ชผ๊ฐค ๋ ๋จ์ ๋ฒํธ ํ๋ | |
| ("๋ค์์ ๊ณ์ฐํ์์ค. โก $โฆ$", "โก $a=2$ ์ผ ๋ โฆ") -> ๋ฒํธ๋ง ์ง์. ์ง๋ฌธ์ ์๋ฌธ์๊ฐ ๋ฑ ํ๋์ด๊ณ | |
| ์ง์๋ฌธ ๋ฐ๋ก ๋ค๋ ๋งจ ์์ ์์ ๋๋ง. keep_circled ๋ก ๋ ์ ์์. | |
| R2 ์ฃผ๊ด์ ์ ๋ต ์ ์๋ฌธํญ ๋ฒํธ / R3 ์ง๋ฌธ ์ โ ~โค ๋ณด๊ธฐํ ์ฃผ๊ด์ -> ๊ฐ๊ด์ / R4 ์๋ฌธํญ ๋ต ๋ฌถ์ ์ ์ธ | |
| R5 ๋ณด๊ธฐ์ $ ์งยทํ ์กฐ๊ฐ ์ฐ๊บผ๊ธฐ / R6 ์ง๋ฌธ ๋งจ ์ ์๋ณธ ๋ฌธํญ ๋ฒํธ('03 ๋ค์ โฆ') | |
| ์ถ๋ ฅ | |
| data/aihub_normalized/aihub_A_fixed.jsonl exclude ๋ ๋ฌธํญ์ ๋น ์ง -> 07 ๋ก ํด์ญ ์ฒ๋ฆฌ | |
| DB ๋ฐ์ (์ฌ์ฉ์๊ฐ ์ง์ ) | |
| python scripts\06_load_supabase.py --file data\aihub_normalized\aihub_A_fixed.jsonl --refresh --with-solution --dry-run | |
| python scripts\07_retire_missing.py --file data\aihub_normalized\aihub_A_fixed.jsonl (๋ฏธ๋ฆฌ๋ณด๊ธฐ ํ --apply) | |
| """ | |
| from __future__ import annotations | |
| import argparse, json, re | |
| from collections import Counter | |
| from pathlib import Path | |
| ROOT = Path(__file__).resolve().parents[1] | |
| SRC = ROOT / "data/aihub_normalized/aihub_A.jsonl" | |
| OV = ROOT / "data/aihub_normalized/review/aihub_overrides.jsonl" | |
| OUT = ROOT / "data/aihub_normalized/aihub_A_fixed.jsonl" | |
| C = "โ โกโขโฃโคโฅโฆโงโจโฉ" | |
| INSTR = r"(?:์์ค|์ฌ๋ผ|ํ๋ผ|๋ณด์)\s*\.?|\?|\|\s|</table>" | |
| R1_AFTER = re.compile(rf"({INSTR})\s*(\$?)\s*[{C}]\s*(?:\\;|\\,)?\s*") | |
| R1_START = re.compile(rf"^\s*(\$?)\s*[{C}]\s*") | |
| LABEL = re.compile(rf"^\s*[{C}]\s*") | |
| # R6 ์ง๋ฌธ ๋งจ ์์ ์๋ณธ ๋ฌธํญ ๋ฒํธ ('03 ๋ค์์ โฆ', '3-1 ๋ค์ โฆ', '$1-1$ ๋ค์ โฆ') | |
| STEM_NO = re.compile(r"^\s*(?:\d{1,3}(?:-\d)?|\$\d-\d\$)\.?\s+(?=(?:๋ค์|์๋|์|์ค๋ฅธ์ชฝ|์ผ์ชฝ|๊ทธ๋ฆผ|ํ)\S*)") | |
| def load_overrides(): | |
| ov = {} | |
| if OV.exists(): | |
| for line in open(OV, encoding="utf-8"): | |
| if line.strip(): | |
| o = json.loads(line) | |
| ov.setdefault(o["source_ref"], {}).update({k: v for k, v in o.items() if k != "source_ref"}) | |
| return ov | |
| def rule_sub_label(stem: str) -> str | None: | |
| if len(re.findall(f"[{C}]", stem)) != 1: | |
| return None | |
| if R1_AFTER.search(stem): | |
| return R1_AFTER.sub(lambda m: m.group(1).rstrip() + " " + m.group(2), stem, count=1) | |
| if R1_START.match(stem): | |
| return R1_START.sub(lambda m: m.group(1), stem, count=1) | |
| # ์๋ฌธ์๊ฐ ํ๋๋ฟ์ด๊ณ ๋น์นธ '(\text{ โ })'ยท์ฐธ์กฐ 'โ ์์/โ ์โฆ'๊ฐ ์๋๋ฉด ์๋ฌธํญ ๋ฒํธ๋ก ๋ณธ๋ค | |
| m = re.search(rf"[{C}]\s*", stem) | |
| if m and not re.search(rf"\\text\s*\{{\s*[{C}]", stem) and not re.match(r"(์์|์|๊ณผ|์|์|๋ฅผ|๋ฒ|\))", stem[m.end():]): | |
| return (stem[:m.start()].rstrip() + " " + stem[m.end():]).strip() | |
| return None | |
| def safe_sub_label(stem: str) -> str | None: | |
| """rule_sub_label ๊ฒฐ๊ณผ๊ฐ ์์ ๊ฒฝ๊ณ($ ์ง)๋ฅผ ๊นจ๋ฉด ์ฐ์ง ์๋๋ค.""" | |
| new = rule_sub_label(stem) | |
| if new is None or new.count("$") % 2 or new.count("$") != stem.count("$"): | |
| return None | |
| return new | |
| def rule_answer_label(r) -> bool: | |
| """R2: ์ฃผ๊ด์ ์ ๋ต ์์ ์๋ฌธํญ ๋ฒํธ ํ๋๋ฅผ ์ง์ด๋ค ('โข x^{6}' -> 'x^{6}'). ๋ฒํธ๋ง ์๋ ๋ต('โค')์ ๊ทธ๋๋ก.""" | |
| a = str(r.get("answer") or "") | |
| if r["qtype"] != "short_answer" or len(re.findall(f"[{C}]", a)) != 1 or not LABEL.match(a): | |
| return False | |
| rest = LABEL.sub("", a) | |
| if not rest.strip(): | |
| return False | |
| r["answer"] = rest | |
| acc = [LABEL.sub("", x) for x in (r.get("accepted_answers") or [])] | |
| r["accepted_answers"] = [x for x in dict.fromkeys(acc) if x.strip()] | |
| return True | |
| JUNK = re.compile(r"\\end\{array\}|\\text\s*\{|\\\\|(?<![a-zA-Z])\}|\\[ ;,]|\$") | |
| SIMPLE = re.compile(r"^-?[\d.]+(?:\s*[a-zA-Z๊ฐ-ํฃ]{0,3})?$|^-?\\sqrt\{\d+\}$|^-?\d*\s*\\sqrt\{\d+\}$|^-?\\frac\{\d+\}\{\d+\}$" | |
| r"|^[a-z](?:\s*[a-z])?$|^\d+\s*[+-]\s*\d+\s*i$|^[a-z]\s*[a-z]$") | |
| def _choice_broken(c: str) -> bool: | |
| t = re.sub(r"\\[{}$]", "", c) | |
| return bool(t.count("$") % 2 or re.search(r"\$\s*\$|\\[ ;,]\s*[-\d]|\}\s*[-\d+]|\\text\s*\{\s*$", c)) | |
| def rule_choices(r) -> list[str] | None: | |
| """R5: ๋ณด๊ธฐ์ $ ์งยทํ ์กฐ๊ฐ ์ฐ๊บผ๊ธฐ๋ฅผ ๊ฑท์ด ๋ธ๋ค. ๊ฑท์ด ๋ธ ๋ด์ฉ์ด ๋จ์ํ ์ยท์์ผ ๋๋ง ๋ฐ๊พผ๋ค.""" | |
| ch = r.get("choices") or [] | |
| if r["qtype"] != "multiple_choice" or not any(_choice_broken(c) for c in ch): | |
| return None | |
| out = [] | |
| for c in ch: | |
| if not _choice_broken(c): | |
| out.append(c) | |
| continue | |
| lab = c.strip()[0] if c.strip()[:1] in C else "" | |
| body = c.strip()[1:] if lab else c.strip() | |
| clean = re.sub(r"\s+", " ", JUNK.sub(" ", body)).strip().rstrip(".").strip() | |
| if not SIMPLE.match(clean): | |
| return None | |
| mu = re.fullmatch(r"(-?[\d.]+)\s*([๊ฐ-ํฃ]+)", clean) | |
| out.append(f"{lab} ${mu.group(1)}${mu.group(2)}" if mu else f"{lab} ${clean}$") | |
| return out | |
| def _norm(t): | |
| t = re.sub(r"\$|\\left|\\right|\s", "", str(t)) | |
| return t.replace("\\geq", "\\ge").replace("\\leq", "\\le") | |
| def rule_sa_to_mc(r) -> str | None: | |
| """R3: ์ง๋ฌธ ์์ โ โฆ โค ๋ณด๊ธฐ๊ฐ ๋ค์ด ์๋ '์ฃผ๊ด์'์ ๊ฐ๊ด์์ผ๋ก. ์ ๋ต์ ๋ฒํธ๋ก ๋ง์ถ์ง ๋ชปํ๋ฉด None(์ ์ธ ๋์).""" | |
| if r["qtype"] != "short_answer": | |
| return None | |
| s = r["stem_md"] | |
| pos = [s.find(ch) for ch in C[:5]] | |
| if any(p < 0 for p in pos) or pos != sorted(pos) or s.count("โ ") != 1: | |
| return None | |
| head, body = s[:pos[0]].rstrip(), s[pos[0]:] | |
| if not re.search(r"(๊ฒ์|๊ฒ์|๊ฒ๋ง์|๊ฒ๋ผ๋ฆฌ|\?)\s*\??\s*(\(.*\))?\s*$", head): | |
| return None | |
| parts = re.split(f"(?=[{C[:5]}])", body) | |
| choices = [p.strip() for p in parts if p.strip()] | |
| if len(choices) != 5: | |
| return None | |
| a = str(r.get("answer") or "").strip() | |
| m = re.fullmatch(f"[{C[:5]}]", a) | |
| if m: | |
| idx = C.index(a) + 1 | |
| else: | |
| hit = [i + 1 for i, ch in enumerate(choices) if _norm(LABEL.sub("", ch)) == _norm(a)] | |
| if len(hit) != 1: | |
| return "nomatch" | |
| idx = hit[0] | |
| r["stem_md"], r["choices"], r["qtype"] = head, choices, "multiple_choice" | |
| r["answer"], r["accepted_answers"] = str(idx), [] | |
| return "ok" | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--list", choices=["sub"]) | |
| a = ap.parse_args() | |
| ov = load_overrides() | |
| rows = [json.loads(l) for l in open(SRC, encoding="utf-8")] | |
| cnt, out, listed, excluded = Counter(), [], [], [] | |
| for r in rows: | |
| o = ov.get(r["source_ref"], {}) | |
| fix = [] | |
| auto_ex = None | |
| conv = rule_sa_to_mc(r) | |
| if conv == "ok": | |
| fix.append("R3_sa_to_mc"); cnt["R3_sa_to_mc"] += 1 | |
| elif conv == "nomatch": | |
| auto_ex = "R3 ๋ณด๊ธฐํ ์ฃผ๊ด์์ธ๋ฐ ์ ๋ต์ ๋ณด๊ธฐ ๋ฒํธ๋ก ๋ง์ถ์ง ๋ชปํจ" | |
| if r["qtype"] == "short_answer" and (len(re.findall(f"[{C}]", str(r.get("answer")))) >= 2 | |
| or re.search(r"\(1\).*\(2\)", str(r.get("answer")))): | |
| auto_ex = "R4 ์๋ฌธํญ ์ฌ๋ฌ ๊ฐ์ ๋ต์ด ํ ์นธ์ ์์" | |
| if rule_answer_label(r): | |
| fix.append("R2_answer_label"); cnt["R2_answer_label"] += 1 | |
| if not o.get("keep_circled") and conv != "ok": | |
| new = safe_sub_label(r["stem_md"]) | |
| if new is not None: | |
| listed.append((r["source_ref"], r["stem_md"][:90], new[:90])) | |
| r["stem_md"] = new | |
| fix.append("R1_sub_label") | |
| cnt["R1_sub_label"] += 1 | |
| newc = rule_choices(r) | |
| if newc: | |
| r["choices"] = newc | |
| fix.append("R5_choices"); cnt["R5_choices"] += 1 | |
| sol = r.get("solution_md") or "" | |
| if ("R1_sub_label" in fix or "R2_answer_label" in fix) and LABEL.match(sol) and len(re.findall(f"[{C}]", sol)) == 1: | |
| r["solution_md"] = LABEL.sub("", sol) | |
| fix.append("R2b_solution_label"); cnt["R2b_solution_label"] += 1 | |
| for idx, text in o.get("choice_set", []): | |
| r["choices"][idx - 1] = text | |
| fix.append("ov_choice_set"); cnt["ov_choice_set"] += 1 | |
| for old, new in o.get("stem_subs", []): | |
| if r["stem_md"].count(old) != 1: | |
| raise SystemExit(f"{r['source_ref']}: stem_subs '{old}' ๊ฐ {r['stem_md'].count(old)}๊ณณ (1๊ณณ์ด์ด์ผ ํจ)") | |
| r["stem_md"] = r["stem_md"].replace(old, new) | |
| fix.append("ov_stem_subs"); cnt["ov_stem_subs"] += 1 | |
| new_stem = STEM_NO.sub("", r["stem_md"], count=1) | |
| if new_stem != r["stem_md"] and "stem_md" not in o: | |
| r["stem_md"] = new_stem | |
| fix.append("R6_stem_number"); cnt["R6_stem_number"] += 1 | |
| if o.get("solution_from_raw"): | |
| raw = (r.get("source_meta") or {}).get("solution_raw_broken") or "" | |
| for old, new in o.get("solution_subs", []): | |
| if raw.count(old) < 1: | |
| raise SystemExit(f"{r['source_ref']}: solution_subs '{old}' ์์") | |
| raw = raw.replace(old, new) | |
| r["solution_md"] = raw.strip() | |
| fix.append("ov_solution_from_raw"); cnt["ov_solution_from_raw"] += 1 | |
| for k in ("stem_md", "choices", "answer", "accepted_answers", "solution_md"): | |
| if k in o: | |
| r[k] = o[k] | |
| fix.append("ov_" + k) | |
| cnt["ov_" + k] += 1 | |
| if fix: | |
| r["source_meta"] = {**(r.get("source_meta") or {}), "fix": fix, "fix_note": o.get("note", "")} | |
| if o.get("include"): | |
| auto_ex = None | |
| if o.get("exclude") or auto_ex: | |
| cnt["excluded:" + (o.get("exclude") or auto_ex)[:2]] += 1 | |
| excluded.append((r["source_ref"], o.get("exclude") or auto_ex)) | |
| continue | |
| out.append(r) | |
| with open(OUT, "w", encoding="utf-8") as f: | |
| for r in out: | |
| f.write(json.dumps(r, ensure_ascii=False) + "\n") | |
| with open(OUT.with_name("aihub_excluded.jsonl"), "w", encoding="utf-8") as f: | |
| for ref, why in excluded: | |
| f.write(json.dumps({"source_ref": ref, "reason": why}, ensure_ascii=False) + "\n") | |
| nosol = sum(not (r.get("solution_md") or "").strip() for r in out) | |
| print(f"{len(rows)} -> {len(out)}ํ {OUT}") | |
| print("๋ณด์ :", dict(cnt), "| ํด์ค ์์ ๋จ์ ์:", nosol) | |
| if a.list == "sub": | |
| for s in listed: | |
| print(" | ".join(s)) | |
| if __name__ == "__main__": | |
| main() | |