Spaces:
Running

math-tutor / app /data_source.py
seongui2030
deploy 2026-12-03 20:26
b146445
Raw History Blame Contribute Delete
6.86 kB
"""๋ฌธํ•ญยท๋‹จ์› ๋ถˆ๋Ÿฌ์˜ค๊ธฐ. ๋‘ ๊ฐ€์ง€ ๋ฐฉ์‹์„ ์ง€์›ํ•ฉ๋‹ˆ๋‹ค.
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"])]