Spaces:
Running

math-tutor / scripts /06_load_supabase.py
seongui2030
deploy 2026-12-03 20:26
b146445
Raw History Blame Contribute Delete
15 kB
"""์ •์ œ๋œ ๋ฌธํ•ญ JSONL -> Supabase `questions` ํ…Œ์ด๋ธ” ์ ์žฌ (Load ๋‹จ๊ณ„).
ETL(Extract, Transform, Load) ์˜ ๋งˆ์ง€๋ง‰ ๋‹จ๊ณ„์ž…๋‹ˆ๋‹ค. 04_normalize_aihub.py ๊ฐ€ ๋งŒ๋“  aihub_A.jsonl ์„ DB ์— ๋„ฃ์Šต๋‹ˆ๋‹ค.
ํ‘œ์ค€ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋งŒ ์‚ฌ์šฉํ•˜๋ฏ€๋กœ pip ์„ค์น˜๊ฐ€ ํ•„์š” ์—†์Šต๋‹ˆ๋‹ค.
์ ‘์† ์ •๋ณด๋Š” ํŒŒ์ผ์— ์ ์ง€ ์•Š๊ณ  'ํ™˜๊ฒฝ๋ณ€์ˆ˜'๋กœ๋งŒ ๋ฐ›์Šต๋‹ˆ๋‹ค. (PowerShell ์ฐฝ์„ ๋‹ซ์œผ๋ฉด ์‚ฌ๋ผ์ง‘๋‹ˆ๋‹ค)
$env:SUPABASE_URL = "https://xxxxxxxx.supabase.co"
$env:SUPABASE_SERVICE_KEY = "<service_role ๋˜๋Š” Secret key>" # ์ ˆ๋Œ€ GitHub ์— ์˜ฌ๋ฆฌ์ง€ ๋งˆ์„ธ์š”
์‚ฌ์šฉ๋ฒ•
# 1) ๋จผ์ € ์‹œํ—˜ (๋„คํŠธ์›Œํฌ ์‚ฌ์šฉ ์•ˆ ํ•จ: ํ˜•์‹ ๊ฒ€์‚ฌ์™€ ๊ฐœ์ˆ˜๋งŒ ํ™•์ธ)
python scripts\\06_load_supabase.py --file data\\aihub_normalized\\aihub_A.jsonl --dry-run
# 2) ์†Œ๋Ÿ‰ ์ ์žฌ
python scripts\\06_load_supabase.py --file data\\aihub_normalized\\aihub_A.jsonl --limit 50
# 3) ์ „์ฒด ์ ์žฌ
python scripts\\06_load_supabase.py --file data\\aihub_normalized\\aihub_A.jsonl
๊ฐ™์€ ํŒŒ์ผ์„ ๋‹ค์‹œ ์˜ฌ๋ ค๋„ ์•ˆ์ „ํ•ฉ๋‹ˆ๋‹ค.
๊ธฐ๋ณธ(insert-only) : ์ด๋ฏธ ์žˆ๋Š” ๋ฌธํ•ญ(source+source_ref ๊ฐ€ ๊ฐ™์€ ๊ฒƒ)์€ ๊ฑด๋“œ๋ฆฌ์ง€ ์•Š๊ณ  ์ƒˆ ๋ฌธํ•ญ๋งŒ ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค.
--refresh : ์ด๋ฏธ ์žˆ๋Š” ๋ฌธํ•ญ์˜ '๋‚ด์šฉ'(๋ฌธ์ œยท์„ ํƒ์ง€ยท์ •๋‹ตยท๋‹จ์› ๋“ฑ)๋งŒ ๊ฐฑ์‹ ํ•ฉ๋‹ˆ๋‹ค.
๊ฒ€์ˆ˜ ๊ฒฐ๊ณผ(verified, status, rights_status, solution_md, intent, figure_path)๋Š” ์ ˆ๋Œ€ ๋ฎ์–ด์“ฐ์ง€ ์•Š์Šต๋‹ˆ๋‹ค.
--refresh --with-solution : ์œ„ ๋‚ด์šฉ + ํ•ด์„ค(solution_md)๋„ ๊ฐฑ์‹  (EBSi ํ•ด์„ค ์›๋ณธ ๋Œ€์กฐ ์ˆ˜์ • ๋ฐ˜์˜์šฉ).
"""
from __future__ import annotations
import argparse
import base64
import json
import os
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from collections import Counter
from pathlib import Path
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
TABLE = "questions"
QTYPES = {"multiple_choice", "short_answer"}
DIFFS = {"low", "mid", "high"}
GRADES = {"e3", "e4", "e5", "e6", "m1", "m2", "m3", "h1", "h2", "h3"}
RIGHTS = {"unreviewed", "cleared", "restricted"}
# ์‹ ๊ทœ ์ ์žฌ ๋•Œ ๋ณด๋‚ด๋Š” ์—ด (ํ‘œ์˜ ์—ด ์ด๋ฆ„๊ณผ ๊ฐ™์Œ)
ALL_COLS = ("source", "source_ref", "source_meta", "rights_status", "grade_code", "unit_id", "difficulty", "score",
"qtype", "stem_md", "choices", "figure_description", "figure_path", "answer", "accepted_answers",
"solution_md", "intent", "verified", "verify_note", "status")
# --refresh ๋•Œ ๋ณด๋‚ด๋Š” ์—ด: ๋‚ด์šฉ๋งŒ. ๊ฒ€์ˆ˜ยท๊ฒŒ์‹œ ์ƒํƒœ์™€ ํ•ด์„ค์€ ๋ณด๋‚ด์ง€ ์•Š์•„ ๊ธฐ์กด ๊ฐ’์ด ์œ ์ง€๋จ
CONTENT_COLS = ("source", "source_ref", "source_meta", "grade_code", "unit_id", "difficulty", "qtype", "stem_md",
"choices", "figure_description", "answer", "accepted_answers")
# 005/006 SQL ๋กœ ์ถ”๊ฐ€๋˜๋Š” ์—ด (EBSi ๋“ฑ). ํŒŒ์ผ์˜ ํ–‰์— ์ด ์—ด์ด ์žˆ์„ ๋•Œ๋งŒ ๋ณด๋ƒ„ -> 005ยท006 ์„ ๋จผ์ € ์‹คํ–‰ํ•ด์•ผ ํ•จ
EXTRA_COLS = ("exam_year", "exam_month", "exam_number", "search_text", "figure_text", "item_image_path",
"figure_paths", "embedding", "embedding_model")
def clean_str(v):
"""PostgreSQL ์€ ๊ธ€์ž ์† NUL(\\u0000)์„ ์ €์žฅํ•˜์ง€ ๋ชปํ•˜๋ฏ€๋กœ ์ œ๊ฑฐ."""
if isinstance(v, str):
return v.replace("\u0000", "")
if isinstance(v, list):
return [clean_str(x) for x in v]
if isinstance(v, dict):
return {k: clean_str(x) for k, x in v.items()}
return v
def validate(row: dict) -> str | None:
"""DB ์ œ์•ฝ(CHECK)์— ๊ฑธ๋ฆด ํ–‰์„ ๋ฏธ๋ฆฌ ์ฐพ์•„ ์ด์œ ๋ฅผ ๋Œ๋ ค์ค€๋‹ค. ๋ฌธ์ œ ์—†์œผ๋ฉด None."""
if not row.get("source") or not row.get("source_ref"):
return "source/source_ref ์—†์Œ"
if row.get("qtype") not in QTYPES:
return f"qtype ์ด์ƒ: {row.get('qtype')!r}"
if row.get("grade_code") not in GRADES:
return f"grade_code ์ด์ƒ: {row.get('grade_code')!r}"
if row.get("difficulty") is not None and row["difficulty"] not in DIFFS:
return f"difficulty ์ด์ƒ: {row['difficulty']!r}"
if row.get("rights_status", "unreviewed") not in RIGHTS:
return f"rights_status ์ด์ƒ: {row.get('rights_status')!r}"
if not str(row.get("stem_md") or "").strip():
return "๋ฌธ์ œ ๋ณธ๋ฌธ(stem_md) ์—†์Œ"
if not str(row.get("answer") or "").strip():
return "์ •๋‹ต(answer) ์—†์Œ"
if row["qtype"] == "multiple_choice" and len(row.get("choices") or []) < 2:
return "๊ฐ๊ด€์‹์ธ๋ฐ ์„ ํƒ์ง€๊ฐ€ 2๊ฐœ ๋ฏธ๋งŒ"
if row.get("status", "draft") == "published":
return "published ์ƒํƒœ๋Š” ์ ์žฌ ์Šคํฌ๋ฆฝํŠธ์—์„œ ์˜ฌ๋ฆฌ์ง€ ์•Š์Œ (๊ฒ€์ฆยท์ด์šฉํ—ˆ๋ฝ ํ™•์ธ ํ›„ ๋”ฐ๋กœ ๊ฒŒ์‹œ)"
return None
def read_rows(paths: list[Path], limit: int | None):
n = 0
for p in paths:
with p.open(encoding="utf-8") as f:
for ln, line in enumerate(f, 1):
line = line.strip()
if not line:
continue
try:
yield p, ln, json.loads(line)
except json.JSONDecodeError:
yield p, ln, None
n += 1
if limit and n >= limit:
return
def check_key(key: str) -> None:
"""๊ณต๊ฐœ์šฉ(anon/publishable) ํ‚ค๋ฅผ ์‹ค์ˆ˜๋กœ ๋„ฃ์—ˆ๋Š”์ง€ ํ™•์ธ."""
if key.startswith("sb_publishable_"):
sys.exit("[์ค‘๋‹จ] publishable ํ‚ค์ž…๋‹ˆ๋‹ค. Secret key ๋˜๋Š” service_role ํ‚ค๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. (Settings > API Keys)")
if key.count(".") == 2: # ์˜ˆ์ „ ๋ฐฉ์‹ JWT ํ‚ค: ๊ฐ€์šด๋ฐ ์กฐ๊ฐ์—์„œ role ์„ ์ฝ๋Š”๋‹ค
try:
mid = key.split(".")[1]
role = json.loads(base64.urlsafe_b64decode(mid + "=" * (-len(mid) % 4))).get("role")
if role != "service_role":
sys.exit(f"[์ค‘๋‹จ] ์ด ํ‚ค์˜ role ์ด '{role}' ์ž…๋‹ˆ๋‹ค. service_role ํ‚ค๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค.")
except (ValueError, KeyError):
pass
class Client:
def __init__(self, url: str, key: str):
self.base = url.rstrip("/") + "/rest/v1"
self.key = key
def _headers(self, extra: dict | None = None) -> dict:
h = {"apikey": self.key, "Content-Type": "application/json"}
if self.key.count(".") == 2: # ์˜ˆ์ „ JWT ํ‚ค๋งŒ Authorization ์— ๊ฐ™์ด ๋ณด๋‚ธ๋‹ค (์ƒˆ Secret key ๋Š” apikey ๋งŒ)
h["Authorization"] = f"Bearer {self.key}"
h.update(extra or {})
return h
def post_rows(self, rows: list[dict], refresh: bool, retries: int = 3) -> None:
prefer = "resolution=merge-duplicates,return=minimal" if refresh else "resolution=ignore-duplicates,return=minimal"
qs = urllib.parse.urlencode({"on_conflict": "source,source_ref"})
req_url = f"{self.base}/{TABLE}?{qs}"
data = json.dumps(rows, ensure_ascii=False).encode("utf-8")
for attempt in range(1, retries + 1):
req = urllib.request.Request(req_url, data=data, method="POST", headers=self._headers({"Prefer": prefer}))
try:
with urllib.request.urlopen(req, timeout=60):
return
except urllib.error.HTTPError as e:
body = e.read().decode("utf-8", "replace")[:600]
if e.code in (429, 500, 502, 503, 504) and attempt < retries:
time.sleep(2 * attempt)
continue
raise RuntimeError(f"HTTP {e.code}: {body}") from None
except (urllib.error.URLError, TimeoutError) as e:
if attempt < retries:
time.sleep(2 * attempt)
continue
raise RuntimeError(f"์—ฐ๊ฒฐ ์‹คํŒจ: {e}") from None
def count(self, source: str) -> int | None:
qs = urllib.parse.urlencode({"select": "id", "source": f"eq.{source}"})
req = urllib.request.Request(f"{self.base}/{TABLE}?{qs}", method="GET",
headers=self._headers({"Prefer": "count=exact", "Range": "0-0"}))
try:
with urllib.request.urlopen(req, timeout=60) as r:
cr = r.headers.get("Content-Range", "")
return int(cr.split("/")[-1]) if "/" in cr and cr.split("/")[-1].isdigit() else None
except Exception:
return None
def main() -> None:
ap = argparse.ArgumentParser(description="์ •์ œ JSONL -> Supabase questions ์ ์žฌ")
ap.add_argument("--file", type=Path, nargs="+", required=True, help="์ ์žฌํ•  JSONL (์˜ˆ: aihub_A.jsonl)")
ap.add_argument("--dry-run", action="store_true", help="๋„คํŠธ์›Œํฌ ์—†์ด ํ˜•์‹ ๊ฒ€์‚ฌ์™€ ๊ฐœ์ˆ˜๋งŒ ํ™•์ธ")
ap.add_argument("--refresh", action="store_true", help="์ด๋ฏธ ์žˆ๋Š” ๋ฌธํ•ญ์˜ ๋‚ด์šฉ๋งŒ ๊ฐฑ์‹  (๊ฒ€์ˆ˜ ๊ฒฐ๊ณผ๋Š” ๋ณด์กด)")
ap.add_argument("--with-solution", action="store_true",
help="--refresh ์™€ ํ•จ๊ป˜: ํ•ด์„ค(solution_md)๋„ ๊ฐฑ์‹  (๊ฒ€์ˆ˜ยท๊ฒŒ์‹œ ์ƒํƒœ๋Š” ๊ทธ๋Œ€๋กœ ๋ณด์กด)")
ap.add_argument("--limit", type=int, help="์•ž์—์„œ ์ด ๊ฐœ์ˆ˜๋งŒ ์ฒ˜๋ฆฌ")
ap.add_argument("--batch", type=int, default=200, help="ํ•œ ๋ฒˆ์— ๋ณด๋‚ด๋Š” ํ–‰ ์ˆ˜ (๊ธฐ๋ณธ 200)")
ap.add_argument("--failed-out", type=Path, default=Path("load_failed.jsonl"), help="์‹คํŒจํ•œ ํ–‰์„ ์ €์žฅํ•  ํŒŒ์ผ")
a = ap.parse_args()
for p in a.file:
if not p.exists():
sys.exit(f"[์ค‘๋‹จ] ํŒŒ์ผ์ด ์—†์Šต๋‹ˆ๋‹ค: {p}")
if a.with_solution and not a.refresh:
sys.exit("[์ค‘๋‹จ] --with-solution ์€ --refresh ์™€ ํ•จ๊ป˜ ์“ฐ์„ธ์š”")
cols = (CONTENT_COLS + (("solution_md",) if a.with_solution else ())) if a.refresh else ALL_COLS
good: list[dict] = []
bad: list[dict] = []
why = Counter()
seen: set[tuple] = set()
dup = 0
extra_cols: tuple | None = None
for p, ln, row in read_rows(a.file, a.limit):
if row is None:
why["JSON ํ•ด์„ ์‹คํŒจ"] += 1
bad.append({"file": str(p), "line": ln, "reason": "JSON ํ•ด์„ ์‹คํŒจ"})
continue
row = clean_str(row)
row.setdefault("rights_status", "unreviewed")
row.setdefault("status", "draft")
r = validate(row)
if r:
why[r] += 1
bad.append({"file": str(p), "line": ln, "source_ref": row.get("source_ref"), "reason": r})
continue
k = (row["source"], row["source_ref"])
if k in seen:
dup += 1
continue
seen.add(k)
row["choices"] = row.get("choices") or []
row["accepted_answers"] = row.get("accepted_answers") or []
row["source_meta"] = row.get("source_meta") or {}
if "figure_paths" in row:
row["figure_paths"] = row.get("figure_paths") or []
extra = tuple(c for c in EXTRA_COLS if c in row)
if extra_cols is None:
extra_cols = extra
elif extra != extra_cols:
why["์ถ”๊ฐ€ ์—ด ๊ตฌ์„ฑ์ด ๋‹ค๋ฅธ ํ–‰๊ณผ ๋‹ค๋ฆ„"] += 1
bad.append({"file": str(p), "line": ln, "source_ref": row.get("source_ref"), "reason": "์ถ”๊ฐ€ ์—ด ๊ตฌ์„ฑ ๋ถˆ์ผ์น˜"})
continue
good.append({c: row.get(c) for c in cols + extra_cols}) # ๋ชจ๋“  ํ–‰์ด ๊ฐ™์€ ์—ด์„ ๊ฐ€์ง€๋„๋ก (PostgREST ์š”๊ตฌ์‚ฌํ•ญ)
by_grade = Counter(r.get("grade_code") for r in good)
by_diff = Counter(r.get("difficulty") for r in good)
sources = sorted({r["source"] for r in good})
print(f"์ฝ์Œ: ์ ์žฌ ๋Œ€์ƒ {len(good)}๊ฐœ / ์ œ์™ธ {len(bad)}๊ฐœ / ํŒŒ์ผ ์•ˆ ์ค‘๋ณต {dup}๊ฐœ")
print(f" ์ถœ์ฒ˜: {sources} ํ•™๋…„: {dict(by_grade)} ๋‚œ์ด๋„: {dict(by_diff)}")
if extra_cols:
print(f" ์ถ”๊ฐ€ ์—ด(005/006 SQL ํ•„์š”): {', '.join(extra_cols)}")
if "embedding" in extra_cols:
dims = {len(str(r['embedding']).strip('[]').split(',')) for r in good if r.get('embedding')}
print(f" ์ž„๋ฒ ๋”ฉ ์ฐจ์›: {sorted(dims)} (006 SQL ์˜ vector(1024) ์™€ ๊ฐ™์•„์•ผ ํ•จ)")
if a.batch > 50:
print(" โ€ป ์ž„๋ฒ ๋”ฉ์ด ์žˆ์–ด ํ•œ ์ค„์ด ํฝ๋‹ˆ๋‹ค. --batch 50 ์ดํ•˜๋ฅผ ๊ถŒ์žฅํ•ฉ๋‹ˆ๋‹ค.")
for k, v in why.most_common():
print(f" ์ œ์™ธ ์ด์œ  - {k}: {v}")
if bad:
with a.failed_out.open("w", encoding="utf-8") as f:
for b in bad:
f.write(json.dumps(b, ensure_ascii=False) + "\n")
print(f" ์ œ์™ธ๋œ ํ–‰ ๋ชฉ๋ก: {a.failed_out}")
if a.dry_run:
print("[dry-run] ๋„คํŠธ์›Œํฌ๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค. ์ด์ƒ์ด ์—†์œผ๋ฉด --dry-run ์„ ๋นผ๊ณ  ์‹คํ–‰ํ•˜์„ธ์š”.")
return
if not good:
sys.exit("[์ค‘๋‹จ] ์ ์žฌํ•  ํ–‰์ด ์—†์Šต๋‹ˆ๋‹ค.")
url, key = os.environ.get("SUPABASE_URL", "").strip(), os.environ.get("SUPABASE_SERVICE_KEY", "").strip()
if not url or not key:
sys.exit("[์ค‘๋‹จ] ํ™˜๊ฒฝ๋ณ€์ˆ˜ SUPABASE_URL, SUPABASE_SERVICE_KEY ๋ฅผ ๋จผ์ € ์„ค์ •ํ•˜์„ธ์š”. (ํŒŒ์ผ ๋งจ ์œ„ ์„ค๋ช… ์ฐธ๊ณ )")
if not (url.startswith("https://") or url.startswith("http://127.0.0.1") or url.startswith("http://localhost")):
sys.exit("[์ค‘๋‹จ] SUPABASE_URL ์€ https://<ํ”„๋กœ์ ํŠธ>.supabase.co ํ˜•์‹์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.")
check_key(key)
cli = Client(url, key)
src = sources[0] if len(sources) == 1 else None
before = cli.count(src) if src else None
print(f"์ ์žฌ ์ „ DB ์˜ {src or 'ํ•ด๋‹น'} ๋ฌธํ•ญ ์ˆ˜: {before if before is not None else 'ํ™•์ธ ๋ชป ํ•จ'}")
sent = failed = 0
fails: list[dict] = []
for i in range(0, len(good), a.batch):
chunk = good[i:i + a.batch]
try:
cli.post_rows(chunk, a.refresh)
sent += len(chunk)
except RuntimeError as e:
# ๋ฌถ์Œ์ด ์‹คํŒจํ•˜๋ฉด ํ•œ ์ค„์”ฉ ๋‹ค์‹œ ๋ณด๋‚ด ๋ฌธ์ œ ํ–‰๋งŒ ๊ณจ๋ผ๋‚ธ๋‹ค
print(f" ๋ฌถ์Œ {i + 1}~{i + len(chunk)} ์‹คํŒจ -> ํ•œ ์ค„์”ฉ ์žฌ์‹œ๋„ ({str(e)[:120]})")
for r in chunk:
try:
cli.post_rows([r], a.refresh, retries=2)
sent += 1
except RuntimeError as e2:
failed += 1
fails.append({"source_ref": r.get("source_ref"), "error": str(e2)[:300]})
print(f" ... {min(i + a.batch, len(good))}/{len(good)} ์ „์†ก")
if fails:
with a.failed_out.open("a", encoding="utf-8") as f:
for x in fails:
f.write(json.dumps(x, ensure_ascii=False) + "\n")
after = cli.count(src) if src else None
print(f"์™„๋ฃŒ: ์ „์†ก ์„ฑ๊ณต {sent}๊ฐœ / ์‹คํŒจ {failed}๊ฐœ")
print(f"์ ์žฌ ํ›„ DB ์˜ {src or 'ํ•ด๋‹น'} ๋ฌธํ•ญ ์ˆ˜: {after if after is not None else 'ํ™•์ธ ๋ชป ํ•จ'}"
+ (f" (์ด๋ฒˆ์— ์ƒˆ๋กœ ๋Š˜์–ด๋‚œ ์ˆ˜ {after - before})" if before is not None and after is not None else ""))
if not a.refresh:
print("โ€ป ๊ธฐ๋ณธ ๋ชจ๋“œ๋Š” ์ด๋ฏธ ์žˆ๋Š” ๋ฌธํ•ญ์„ ๊ฑด๋“œ๋ฆฌ์ง€ ์•Š์Šต๋‹ˆ๋‹ค. '์ „์†ก ์„ฑ๊ณต'์ด ์ƒˆ๋กœ ๋Š˜์–ด๋‚œ ์ˆ˜๋ณด๋‹ค ํด ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.")
if failed:
print(f"์‹คํŒจํ•œ ํ–‰: {a.failed_out} (์ด ํŒŒ์ผ์„ ๋ณด๋‚ด ์ฃผ์‹œ๋ฉด ์›์ธ์„ ๋ด…๋‹ˆ๋‹ค)")
if __name__ == "__main__":
main()