Spaces:
Running
Running
File size: 14,986 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 | """์ ์ ๋ ๋ฌธํญ 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()
|