"""정제된 문항 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 = "" # 절대 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()