"""문항·단원 불러오기. 두 가지 방식을 지원합니다. local : DB 에 넣은 것과 같은 적재 파일에서 읽음 (기본값, 키·인터넷 불필요) AI Hub 보정본(aihub_A_fixed.jsonl, 없으면 aihub_A.jsonl) + EBSi 고1·고2·고3(data/ebsi/load/ebsi_h*.jsonl) + AI Hub B 그림 문항(aihub_B_sel.jsonl, 있을 때). LOCAL_QUESTIONS 로 바꿀 수 있음. supabase : questions 표에서 읽음 (환경변수 SUPABASE_URL, SUPABASE_SERVICE_KEY 필요, 서버에서만 사용) 어느 쪽이든 '어떤 문항을 학생에게 보여 줄지'는 여기서 정합니다. teacher 모드 : status 가 draft 또는 published 인 문항 모두 student 모드 : status 가 published 이고 rights_status 가 cleared 인 문항만 """ from __future__ import annotations import json import os import urllib.parse import urllib.request from pathlib import Path ROOT = Path(__file__).resolve().parents[1] _AIHUB = ROOT / "data" / "aihub_normalized" _AIHUB_A = _AIHUB / "aihub_A_fixed.jsonl" if (_AIHUB / "aihub_A_fixed.jsonl").exists() else _AIHUB / "aihub_A.jsonl" DEFAULT_LOCAL = ",".join(str(p) for p in [_AIHUB_A, _AIHUB / "aihub_B_sel.jsonl", *(ROOT / "data" / "ebsi" / "load" / f"ebsi_h{g}.jsonl" for g in (1, 2, 3))] if p == _AIHUB_A or p.exists()) UNITS_YAML = ROOT / "configs" / "curriculum_units.yaml" COLUMNS = ("id,source,source_ref,grade_code,unit_id,difficulty,qtype,stem_md,choices," "figure_description,figure_path,answer,accepted_answers,solution_md,status,rights_status,source_meta") # 005 SQL 을 실행한 DB 에서만 있는 열 (EBSi 그림). 환경변수 SUPABASE_EBSI_COLUMNS=on 이면 함께 읽음 EBSI_COLUMNS = ",figure_paths,item_image_path" def _finish(row: dict) -> dict: """엔진이 쓰는 형태로 맞춘다 (answer_display 는 source_meta 에 들어 있음).""" row = dict(row) row["id"] = str(row.get("id") or row.get("source_ref")) meta = row.get("source_meta") or {} if isinstance(meta, str): try: meta = json.loads(meta) except ValueError: meta = {} row["answer_display"] = meta.get("answer_display_md") or row.get("answer") if isinstance(row.get("choices"), str): row["choices"] = json.loads(row["choices"]) # 그림: 문제 그림 목록(figure_paths, 없으면 figure_path 하나), 문항 전체 이미지(표·조립제법 등 B등급), 해설 그림 figs = row.get("figure_paths") if isinstance(figs, str): figs = [x.strip().strip('"') for x in figs.strip("{}").split(",") if x.strip()] row["figure_paths"] = list(figs or ([row["figure_path"]] if row.get("figure_path") else [])) row["show_item_image"] = bool(meta.get("show_item_image")) row["solution_figure_paths"] = list(meta.get("solution_figure_paths") or []) return row def _visible(row: dict, mode: str) -> bool: status = row.get("status", "draft") if mode == "teacher": return status in ("draft", "published") return status == "published" and row.get("rights_status") == "cleared" visible_for = _visible # 외부에서 쓰는 이름: visible_for(row, "teacher"|"student") def load_local(path: Path | None = None, mode: str = "teacher") -> list[dict]: """LOCAL_QUESTIONS 는 파일 하나 또는 쉼표로 여러 개 (예: AI Hub + EBSi 고1·고2 를 함께 시험)""" spec = str(path or os.environ.get("LOCAL_QUESTIONS") or DEFAULT_LOCAL) out = [] for one in [s.strip() for s in spec.split(",") if s.strip()]: p = Path(one) if not p.is_absolute() and not p.exists(): p = ROOT / one if not p.exists(): raise FileNotFoundError(f"문항 파일이 없습니다: {p}") with p.open(encoding="utf-8") as f: for line in f: if line.strip(): r = _finish(json.loads(line)) if _visible(r, mode): out.append(r) return out def load_supabase(mode: str = "teacher", page: int = 1000) -> list[dict]: url = os.environ.get("SUPABASE_URL", "").rstrip("/") key = os.environ.get("SUPABASE_SERVICE_KEY", "") if not url or not key: raise RuntimeError("SUPABASE_URL 과 SUPABASE_SERVICE_KEY 환경변수가 필요합니다.") headers = {"apikey": key} if key.startswith("eyJ"): # 예전 방식(JWT) 키만 Authorization 도 필요 headers["Authorization"] = f"Bearer {key}" if mode == "teacher": flt = "status=in.(draft,published)" else: flt = "status=eq.published&rights_status=eq.cleared" rows, start = [], 0 while True: cols = COLUMNS + (EBSI_COLUMNS if os.environ.get("SUPABASE_EBSI_COLUMNS") == "on" else "") q = f"{url}/rest/v1/questions?select={urllib.parse.quote(cols, safe=',')}&{flt}&order=id" req = urllib.request.Request(q, headers=dict(headers, Range=f"{start}-{start + page - 1}", **{"Range-Unit": "items"})) with urllib.request.urlopen(req, timeout=60) as resp: batch = json.loads(resp.read().decode("utf-8")) rows += [_finish(r) for r in batch] if len(batch) < page: return rows start += page def load_questions(mode: str = "teacher", source: str | None = None) -> list[dict]: source = source or os.environ.get("DATA_SOURCE", "local") return load_supabase(mode) if source == "supabase" else load_local(mode=mode) def _yaml() -> dict: import yaml return yaml.safe_load(UNITS_YAML.read_text(encoding="utf-8")) def load_units(with_questions: set | None = None) -> list[dict]: """시범 단원(pilot) + 문항이 있는 단원. [{'id','name','level','areas'}...] with_questions: 문항이 들어 있는 단원 id 모음. EBSi 고2·고3(수학Ⅰ·Ⅱ, 확률과 통계)처럼 pilot 이 아니어도 문항이 있으면 카드가 생긴다. (AI Hub 만 있을 때는 비시범 단원 문항이 0개라 화면이 지금과 같음)""" extra = set(with_questions or ()) return [{"id": u["id"], "name": u["name"], "level": u["level"], "areas": list(u.get("areas") or [])} for u in _yaml()["units"] if u.get("pilot") or u["id"] in extra] _UNIT_NAMES: dict | None = None def unit_names() -> dict[str, str]: """{'U20': '순열과 조합', ...} 대시보드용 (한 번 읽어 둠)""" global _UNIT_NAMES if _UNIT_NAMES is None: _UNIT_NAMES = {u["id"]: u["name"] for u in _yaml()["units"]} return _UNIT_NAMES def load_areas() -> list[dict]: """영역 카드용. [{'id','name'}...] (sort_order 순)""" return [{"id": a["id"], "name": a["name"]} for a in sorted(_yaml()["areas"], key=lambda a: a["sort_order"])]