Spaces:
Running
Running
File size: 6,864 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 | """๋ฌธํญยท๋จ์ ๋ถ๋ฌ์ค๊ธฐ. ๋ ๊ฐ์ง ๋ฐฉ์์ ์ง์ํฉ๋๋ค.
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"])]
|