Spaces:
Running

math-tutor / scripts /21_aihub_fix.py
seongui2030
deploy 2026-12-03 20:26
b146445
Raw History Blame Contribute Delete
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()