Spaces:
Sleeping
Sleeping
중복답변 가능 버전
Browse filesFiles changed (21)
- app.py+217-38
- db.py+30-16
- ingest.py+245-79
- models.py+61-19
- templates/quiz.html+517-248
- adaptive_parser_monitor.py → 삭제용/adaptive_parser_monitor.pyRenamed
- adative_parser_watchdog.py → 삭제용/adative_parser_watchdog.pyRenamed
- analyze_parser_log_ai.py → 삭제용/analyze_parser_log_ai.pyRenamed
- append_questions.py → 삭제용/append_questions.pyRenamed
- check_db.py → 삭제용/check_db.pyRenamed
- classify.py → 삭제용/classify.pyRenamed
- deploy_to_spaces.py → 삭제용/deploy_to_spaces.pyRenamed
- llm_extract.py → 삭제용/llm_extract.pyRenamed
- llm_parse.py → 삭제용/llm_parse.pyRenamed
- ocr_test_light.py → 삭제용/ocr_test_light.pyRenamed
- parse_pipeline.py → 삭제용/parse_pipeline.pyRenamed
- pdf_parser.py → 삭제용/pdf_parser.pyRenamed
- pdf_parser_adaptive.py → 삭제용/pdf_parser_adaptive.pyRenamed
- schemas.py → 삭제용/schemas.pyRenamed
- seed.py → 삭제용/seed.pyRenamed
- similarity.py → 삭제용/similarity.pyRenamed
123459 unmodified lines151617181920212223242526273 unmodified lines31323334353637383940414243444546476 unmodified lines54555657585919 unmodified lines79808182838415 unmodified lines1001011021031041051061071081091101111121131141151161171181191201211221231241251261271281 unmodified line1301311321331341351361371381391401411421431441451461474 unmodified lines1521531541551561571581591601611623 unmodified lines16616716816917017117217317417517617717817918018118218318426 unmodified lines21121221321421521621727 unmodified lines24524624724824925025113 unmodified lines265266267268269# ==============================================# app.py — CBT + REVIEW(⭐) + WRONG + 통합 노트 + OCR Parser (확정 안정 전체 버전)# ==============================================import os9 unmodified linestry:from pdf_parser_adaptive import parse_pdf as _parse_pdfexcept:_parse_pdf = Noneload_dotenv()app = Flask(__name__)init_db()BASE_DIR = os.path.abspath(os.path.dirname(__file__))DATA_DIR = os.path.join(BASE_DIR, "data")UPLOAD_DIR = os.path.join(DATA_DIR, "uploads")3 unmodified linesDEFAULT_USER = "default"def normalize_options(raw):if not raw:return []try:if isinstance(raw, dict):return [f"{k}. {v}" for k, v in sorted(raw.items(), key=lambda kv: kv[0])]if isinstance(raw, list):return rawexcept:passreturn []6 unmodified linesreturn out_json@app.route("/")def home():return render_template("index.html")19 unmodified linesreturn jsonify({"ok": True})@app.route("/admin/upload", methods=["GET", "POST"])def upload_pdf():if request.method == "GET":15 unmodified linesreturn jsonify({"ok": False, "error": str(e)}), 500@app.route("/api/question", methods=["GET"])def api_question():qid = request.args.get("id")db = SessionLocal()try:q = db.query(Question).filter(Question.id == int(qid)).first() if qid \else db.query(Question).order_by(Question.id.asc()).first()if not q:return jsonify({"error": "문제 없음"}), 404total = db.query(Question).count()return jsonify({"id": q.id,"question": q.stem,"options": normalize_options(q.get_options()),"answer": q.answer,"explanation": q.explanation,"total": total})finally:db.close()@app.route("/api/answer", methods=["POST"])def api_answer():data = request.get_json(force=True) or {}1 unmodified linechosen = data.get("chosen")user_id = str(data.get("user_id", DEFAULT_USER))if not qid or not chosen:return jsonify({"error": "question_id 또는 chosen 누락"}), 400db = SessionLocal()try:q = db.query(Question).filter(Question.id == int(qid)).first()correct = (str(chosen).upper() == str(q.answer).upper())db.add(Attempt(user_id=user_id,question_id=q.id,chosen=str(chosen),correct=bool(correct),note_type="wrong" if not correct else None))4 unmodified linesdb.close()@app.route("/api/next", methods=["GET"])def api_next():current_id = int(request.args.get("current_id", 1))db = SessionLocal()try:nxt = (db.query(Question).filter(Question.id > current_id)3 unmodified linesif not nxt:return jsonify({"end": True})total = db.query(Question).count()return jsonify({"id": nxt.id,"question": nxt.stem,"options": normalize_options(nxt.get_options()),"answer": nxt.answer,"explanation": nxt.explanation,"total": total})finally:db.close()@app.route("/api/review_add", methods=["POST"])def review_add():data = request.get_json(force=True) or {}26 unmodified linesdb.close()# ✅ 오답 + 복습 통합 조회@app.route("/api/wrong_review", methods=["GET"])def wrong_review():user_id = request.args.get("user_id", DEFAULT_USER)27 unmodified linesdb.close()# ✅ 오답에서 제거 (복습에서도 제거)@app.route("/api/wrong_remove", methods=["POST"])def wrong_remove():data = request.get_json(force=True) or {}13 unmodified linesif __name__ == "__main__":print("[INFO] http://127.0.0.1:5000 실행 중")app.run(host="0.0.0.0", port=5000, debug=True)123459 unmodified lines1516171819202122232425262728293 unmodified lines33343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384856 unmodified lines929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721819 unmodified lines23823924024124224324424524615 unmodified lines2622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942951 unmodified line2972982993003013023033043053063073083093103113123133143153163173183194 unmodified lines3243253263273283293303313323333343353363373383393403413423433443453 unmodified lines34935035135235335435535635735835936036136226 unmodified lines38939039139239339439527 unmodified lines42342442542642742842913 unmodified lines443444445446447448# ==============================================# app.py — CBT + REVIEW(⭐) + WRONG + 통합 노트 + OCR Parser (최적화 + 자동 DB화 완성본)# ==============================================import os9 unmodified linestry:from pdf_parser_adaptive import parse_pdf as _parse_pdfexcept Exception:_parse_pdf = Noneload_dotenv()app = Flask(__name__)# -----------------------------# Paths# -----------------------------BASE_DIR = os.path.abspath(os.path.dirname(__file__))DATA_DIR = os.path.join(BASE_DIR, "data")UPLOAD_DIR = os.path.join(DATA_DIR, "uploads")3 unmodified linesDEFAULT_USER = "default"# -----------------------------# DB init (패치/구버전 모두 호환)# -----------------------------try:init_db(apply_light_migrations=True)except TypeError:init_db()# -----------------------------# Utils# -----------------------------def normalize_options(raw):"""어떤 형태로 저장되어 있어도 "표시용 문자열 리스트"로 변환.- 표준: [{"key":"A","text":"..."}] -> ["A. ...", ...]- 레거시: {"A":"..."} -> ["A. ...", ...]- 레거시: ["...","..."] -> 그대로"""if not raw:return []# 표준: list[dict]if isinstance(raw, list) and raw and isinstance(raw[0], dict):out = []for o in raw:k = str(o.get("key", "")).strip()t = str(o.get("text", "")).strip()if k and t:out.append(f"{k}. {t}")elif t:out.append(t)elif k:out.append(k)return out# 레거시: dictif isinstance(raw, dict):try:return [f"{k}. {v}" for k, v in sorted(raw.items(), key=lambda kv: kv[0])]except Exception:return [str(raw)]# 레거시: list[str]if isinstance(raw, list):return [str(x) for x in raw]return []6 unmodified linesreturn out_jsondef first_question(db):"""첫 문제 선택:- page_no/q_no_on_page/global_no 컬럼이 있으면 PDF 순서로- 없으면 id로"""q = db.query(Question)if hasattr(Question, "page_no") and hasattr(Question, "q_no_on_page"):return q.order_by(Question.page_no.asc().nulls_last(),Question.q_no_on_page.asc().nulls_last(),Question.id.asc()).first()if hasattr(Question, "global_no"):return q.order_by(Question.global_no.asc().nulls_last(),Question.id.asc()).first()return q.order_by(Question.id.asc()).first()def api_payload(db, q: Question):"""기존 프론트 호환 필드 유지 + 신규 필드(있으면)만 추가"""total = db.query(Question).count()payload = {"id": q.id,"question": q.stem,"options": normalize_options(q.get_options()),"answer": q.answer, # 레거시 유지"explanation": q.explanation,"total": total,}# 신규(모델이 지원할 때만)if hasattr(q, "get_answer_keys"):payload["answer_keys"] = q.get_answer_keys()if hasattr(q, "get_answer_steps"):payload["answer_steps"] = q.get_answer_steps()if hasattr(q, "get_images"):payload["images"] = q.get_images()# 순서 메타(있을 때만)if hasattr(q, "page_no"):payload["page_no"] = q.page_noif hasattr(q, "q_no_on_page"):payload["q_no_on_page"] = q.q_no_on_pageif hasattr(q, "global_no"):payload["global_no"] = q.global_noreturn payloaddef is_correct(q: Question, chosen):"""최소 변경으로 정답 판정 개선:- models.py에 get_answer_keys/get_answer_steps 있으면 그걸 우선 사용- 없으면 레거시 answer(string)로 비교"""# chosen 표준화 (string/list 모두 허용)if isinstance(chosen, list):chosen_list = [str(x).strip().upper() for x in chosen if str(x).strip()]else:s = str(chosen).strip()if "," in s:chosen_list = [x.strip().upper() for x in s.split(",") if x.strip()]else:chosen_list = [s.upper()] if s else []# Steps 우선if hasattr(q, "get_answer_steps"):ans_steps = [str(x).strip().upper() for x in (q.get_answer_steps() or [])]if ans_steps:return chosen_list == ans_steps # 순서/중복까지 동일# 복수정답(중복 포함) 우선if hasattr(q, "get_answer_keys"):ans_keys = [str(x).strip().upper() for x in (q.get_answer_keys() or [])]if ans_keys:from collections import Counterreturn Counter(chosen_list) == Counter(ans_keys)# 레거시 단일 비교return str(chosen).strip().upper() == str(q.answer or "").strip().upper()def auto_ingest_json_if_empty(json_path="data/questions.json", source_name="az104_dump"):"""✅ 서버 시작 시 자동 DB화:- DB에 문제가 0개면 json_path를 자동 ingest- DB 삭제 후 재실행해도 자동으로 다시 쌓임"""# JSON 존재 확인abs_json = json_path if os.path.isabs(json_path) else os.path.join(BASE_DIR, json_path)if not os.path.exists(abs_json):print(f"[WARN] JSON not found: {abs_json}")returndb = SessionLocal()try:n = db.query(Question).count()finally:db.close()if n > 0:print(f"[INFO] DB already has {n} questions. skip auto ingest.")returnprint(f"[INFO] AUTO INGEST start: {abs_json}")inserted = ingest_questions(abs_json, source_name=source_name)print(f"[INFO] AUTO INGEST done: inserted={inserted}")# ✅ 여기서 자동 ingest 실행 (원하는 경로: data/questions.json)auto_ingest_json_if_empty("data/questions.json", "az104_dump")# -----------------------------# Pages# -----------------------------@app.route("/")def home():return render_template("index.html")19 unmodified linesreturn jsonify({"ok": True})# -----------------------------# Admin: upload pdf -> parse -> ingest# -----------------------------@app.route("/admin/upload", methods=["GET", "POST"])def upload_pdf():if request.method == "GET":15 unmodified linesreturn jsonify({"ok": False, "error": str(e)}), 500# -----------------------------# API: question# - ✅ id 없거나/없는 id면 첫 문제 fallback (DB 삭제 후 404 방지)# -----------------------------@app.route("/api/question", methods=["GET"])def api_question():qid = request.args.get("id", type=int)db = SessionLocal()try:q = Noneif qid:q = db.query(Question).filter(Question.id == qid).first()if not q:q = first_question(db)if not q:return jsonify({"error": "문제 없음"}), 404return jsonify(api_payload(db, q))finally:db.close()# -----------------------------# API: answer# - ✅ chosen list/string 둘 다 허용 + (가능하면) 복수/순서 정답 판정# -----------------------------@app.route("/api/answer", methods=["POST"])def api_answer():data = request.get_json(force=True) or {}1 unmodified linechosen = data.get("chosen")user_id = str(data.get("user_id", DEFAULT_USER))if not qid or chosen is None:return jsonify({"error": "question_id 또는 chosen 누락"}), 400db = SessionLocal()try:q = db.query(Question).filter(Question.id == int(qid)).first()if not q:return jsonify({"error": "해당 문제 없음"}), 404correct = is_correct(q, chosen)chosen_store = json.dumps(chosen, ensure_ascii=False) if isinstance(chosen, list) else str(chosen)db.add(Attempt(user_id=user_id,question_id=q.id,chosen=chosen_store,correct=bool(correct),note_type="wrong" if not correct else None))4 unmodified linesdb.close()# -----------------------------# API: next# - ✅ 최소 수정: current_id 없으면 첫 문제# - (PDF 순서 next까지 완전 구현은 코드가 길어져서, 여기선 레거시 id-next 유지)# -----------------------------@app.route("/api/next", methods=["GET"])def api_next():current_id = request.args.get("current_id", type=int, default=None)db = SessionLocal()try:if not current_id:q = first_question(db)if not q:return jsonify({"end": True})return jsonify(api_payload(db, q))nxt = (db.query(Question).filter(Question.id > current_id)3 unmodified linesif not nxt:return jsonify({"end": True})return jsonify(api_payload(db, nxt))finally:db.close()# -----------------------------# Review add/remove# -----------------------------@app.route("/api/review_add", methods=["POST"])def review_add():data = request.get_json(force=True) or {}26 unmodified linesdb.close()# ✅ 오답 + 복습 통합 조회 (기존 그대로 유지)@app.route("/api/wrong_review", methods=["GET"])def wrong_review():user_id = request.args.get("user_id", DEFAULT_USER)27 unmodified linesdb.close()# ✅ 오답에서 제거 (기존 그대로 유지)@app.route("/api/wrong_remove", methods=["POST"])def wrong_remove():data = request.get_json(force=True) or {}13 unmodified linesif __name__ == "__main__":port = int(os.getenv("PORT", 7860))print(f"[INFO] 서버 시작: 0.0.0.0:{port} (HF/로컬 공통)")app.run(host="0.0.0.0", port=port, debug=False)
123452 unmodified lines8910111213141516171819202122232425262728293031322 unmodified lines35363738394041424344454647484950515253545556575859606162636465666768# ==============================================# db.py (v2025-final)# ==============================================import os2 unmodified linesfrom sqlalchemy.orm import sessionmaker, declarative_base# ----------------------------------------------# 경로 설정# ----------------------------------------------DATA_DIR = Path("data")DATA_DIR.mkdir(parents=True, exist_ok=True)DB_PATH = DATA_DIR / "questions.db"DATABASE_URL = f"sqlite:///{DB_PATH.as_posix()}"# ----------------------------------------------# SQLAlchemy Engine# ----------------------------------------------engine = create_engine(DATABASE_URL,connect_args={"check_same_thread": False},echo=False, # 필요하면 .env 로 True/False 변경 가능future=True)# ----------------------------------------------# Session# ----------------------------------------------SessionLocal = sessionmaker(autocommit=False,2 unmodified lines)# ----------------------------------------------# Base (ORM 공통)# ----------------------------------------------Base = declarative_base()# ----------------------------------------------# DB 초기화# ----------------------------------------------def init_db():from models import Question, Attempt # Base 로 묶인 모델 불러오기Base.metadata.create_all(bind=engine)print(f"\n[INFO] ✅ Database Initialized: {DB_PATH}")print("──────────────────────────────────────────────")inspector = inspect(engine)for table in inspector.get_table_names():print(f"\n📘 Table: {table}")for col in inspector.get_columns(table):print(f" • {col['name']:<18} {str(col['type'])}")print("──────────────────────────────────────────────\n")# ----------------------------------------------# 요청 단위 DB 세션# ----------------------------------------------def get_db():db = SessionLocal()try:yield dbfinally:db.close()123452 unmodified lines8910111213141516171819202122232425262728293031323334352 unmodified lines383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182# ==============================================# db.py# ==============================================import os2 unmodified linesfrom sqlalchemy.orm import sessionmaker, declarative_base# ----------------------------------------------# 1. 경로 및 DB 설정# ----------------------------------------------BASE_DIR = Path(__file__).resolve().parentDATA_DIR = BASE_DIR / "data"DATA_DIR.mkdir(parents=True, exist_ok=True)DB_PATH = DATA_DIR / "questions.db"DATABASE_URL = f"sqlite:///{DB_PATH.as_posix()}"# ----------------------------------------------# 2. SQLAlchemy Engine 생성# ----------------------------------------------# check_same_thread=False: SQLite를 멀티 스레드 환경(FastAPI 등)에서 쓸 때 필수engine = create_engine(DATABASE_URL,connect_args={"check_same_thread": False},echo=False, # SQL 로그가 필요하면 True로 변경future=True)# ----------------------------------------------# 3. Session 설정# ----------------------------------------------SessionLocal = sessionmaker(autocommit=False,2 unmodified lines)# ----------------------------------------------# 4. Base 모델 (ORM 공통 부모)# ----------------------------------------------Base = declarative_base()# ----------------------------------------------# 5. DB 초기화 함수 (테이블 생성 및 확인)# ----------------------------------------------def init_db():# 모델들을 여기서 import 해야 Base.metadata에 등록됨# (순환 참조 방지를 위해 함수 내부 import 권장)from models import Question, Attempt# 테이블 생성 (이미 있으면 무시함)Base.metadata.create_all(bind=engine)print(f"\n[INFO] ✅ Database Connected: {DB_PATH}")print("──────────────────────────────────────────────")# 생성된 테이블 구조 확인 (디버깅용)inspector = inspect(engine)table_names = inspector.get_table_names()if not table_names:print("⚠️ No tables found. Did you define classes in models.py?")for table in table_names:print(f"📘 Table: {table}")for col in inspector.get_columns(table):# 컬럼명, 타입 출력print(f" • {col['name']:<15} {str(col['type'])}")print("──────────────────────────────────────────────\n")# ----------------------------------------------# 6. Dependency (FastAPI 등에서 사용)# ----------------------------------------------def get_db():db = SessionLocal()try:yield dbfinally:db.close()
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181194 unmodified lines124125126127128129130131132133134135136137# ==============================================# ingest.py (v2025-UNIVERSAL)# OCR JSON + 수동 JSON + Case Study JSON 완전 호환# ==============================================import jsonfrom db import SessionLocal, init_dbfrom models import Questiondef normalize(item: dict):"""서로 다른 JSON 스키마를 하나의 표준 Question 구조로 정규화한다."""# 1) 문제(Stem)stem = (item.get("stem")or item.get("question")or item.get("q_text")or "").strip()# 2) 해설explanation = item.get("explanation", "").strip()# 3) 정답answer_raw = item.get("answer", "")answer = (json.dumps(answer_raw, ensure_ascii=False)if isinstance(answer_raw, list)else str(answer_raw).strip())# 4) 보기 (list → dict 자동 변환)opts = item.get("options", {})if isinstance(opts, list): # ["opt1","opt2",...]options = {chr(65 + i): opt for i, opt in enumerate(opts)}elif isinstance(opts, dict):options = optselse:options = {}# 5) Topic / Subtopic → category/subcategory 매핑category = item.get("category") or item.get("topic") or Nonesubcategory = item.get("subcategory") or item.get("subtopic") or None# 6) OCR 기반 JSON 호환 필드page = item.get("page")qtype = item.get("question_type", "MCQ")code = item.get("code", "")# 7) 순서형 / 매칭형 문제도 그대로 pass (DB에서 JSON 형태로 저장)sequence = (json.dumps(item.get("sequence"), ensure_ascii=False)if isinstance(item.get("sequence"), list)else None)pairs = (json.dumps(item.get("pairs"), ensure_ascii=False)if isinstance(item.get("pairs"), dict)else None)return {"stem": stem,"explanation": explanation,"answer": answer,"options": options,"category": category,"subcategory": subcategory,"page": page,"question_type": qtype,"code": code,"sequence": sequence,"pairs": pairs,}def ingest_questions(json_path: str, source_name: str = "imported"):"""다양한 형태의 JSON 문제 파일을 DB에 넣는 통합 ingest 함수."""init_db()db = SessionLocal()count = 0try:with open(json_path, "r", encoding="utf-8") as f:data = json.load(f)# Case Study 형태: {"questions":[...]} 지원if isinstance(data, dict) and "questions" in data:data = data["questions"]for raw in data:if not isinstance(raw, dict):continueqn = normalize(raw)q = Question(page=qn["page"],stem=qn["stem"],explanation=qn["explanation"],answer=qn["answer"],question_type=qn["question_type"],category=qn["category"],subcategory=qn["subcategory"],source=source_name,code=qn["code"],sequence=qn["sequence"],pairs=qn["pairs"],)q.set_options(qn["options"])db.add(q)count += 14 unmodified linesexcept Exception as e:db.rollback()print(f"[ERROR] DB 적재 중 오류 발생 → {e}")raise efinally:db.close()if __name__ == "__main__":# 네가 실제로 둔 경로에 맞게 수정# 예: data/json/questions.json 에 있으면path = "data/json/questions.json"ingest_questions(path, "az104_dump")1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822834 unmodified lines288289290291292293294295296297298299300301302303# ==============================================# ingest.py (v2025-UNIVERSAL-COMPAT)# ✅ 현재 db.py/init_db() (인자 없음)와 100% 호환# ✅ 기존 questions 테이블 스키마( options_json / answer / pairs / sequence ) 기준으로 안전 동작# ✅ 확장 모델( set_answer_keys / set_answer_steps / set_images / page_no 등 )이 있으면 자동 활용# ✅ options는 항상 [{"key","text"}] 형태로 저장 → 웹 표기 안정화# ✅ Steps/복수/중복 정답:# - 확장 모델이면 answer_json/answer_steps_json에 저장# - 구버전이면 answer="A,B" / sequence=["E","B","C"] 로 fallback# ✅ rebuild_db=True: DB 파일 삭제 후 재생성# ==============================================import jsonimport osfrom typing import Any, Dict, Listfrom db import SessionLocal, init_db, DB_PATHfrom models import Question# -----------------------------# Helpers# -----------------------------def _to_list_answer_keys(v: Any) -> List[str]:"""정답 입력을 key 리스트로 정규화.- ["A","C"] -> ["A","C"]- "A" -> ["A"]- "A,C" -> ["A","C"]- "BE" -> ["B","E"] (전부 대문자 알파벳일 때만)- dict(steps 텍스트) -> [] (steps에서 처리)"""if v is None:return []if isinstance(v, list):return [str(x).strip() for x in v if str(x).strip()]if isinstance(v, dict):return []s = str(v).strip()if not s:return []if "," in s:return [x.strip() for x in s.split(",") if x.strip()]if len(s) >= 2 and s.isalpha() and s.upper() == s:return list(s)return [s]def _normalize_options(opts: Any) -> List[Dict[str, str]]:"""options를 항상 표준 리스트 형태로:[{"key":"A","text":"..."}, ...]지원:- list[str]- dict{key:text}- list[dict] (이미 key/text)"""if not opts:return []# list[dict]if isinstance(opts, list) and opts and all(isinstance(x, dict) for x in opts):out = []for o in opts:k = str(o.get("key", "")).strip()t = str(o.get("text", "")).strip()if k or t:out.append({"key": k, "text": t})return out# list[str]if isinstance(opts, list):return [{"key": chr(65 + i), "text": str(opt).strip()} for i, opt in enumerate(opts)]# dict{key:text}if isinstance(opts, dict):return [{"key": str(k).strip(), "text": str(v).strip()} for k, v in opts.items()]return []def _infer_steps_answer_keys(item: Dict[str, Any], options_std: List[Dict[str, str]]) -> List[str]:"""Steps 정답을 key 리스트로 뽑는다.우선순위:1) answer_steps(list)2) sequence(list)3) answer가 {"1":"텍스트", "2":"텍스트"} 형태면 options text 매칭으로 key 추정"""if isinstance(item.get("answer_steps"), list):return [str(x).strip() for x in item["answer_steps"] if str(x).strip()]if isinstance(item.get("sequence"), list):return [str(x).strip() for x in item["sequence"] if str(x).strip()]ans = item.get("answer")if isinstance(ans, dict) and all(str(k).isdigit() for k in ans.keys()):text_to_key = {}for o in options_std:t = (o.get("text") or "").strip()if t and t not in text_to_key:text_to_key[t] = (o.get("key") or "").strip()keys = []for i in sorted(int(x) for x in ans.keys()):t = str(ans.get(str(i), "")).strip()keys.append(text_to_key.get(t, "__UNKNOWN__"))return keysreturn []def _load_json(json_path: str) -> List[Dict[str, Any]]:with open(json_path, "r", encoding="utf-8") as f:data = json.load(f)# Case Study: {"questions":[...]}if isinstance(data, dict) and "questions" in data:data = data["questions"]if not isinstance(data, list):raise ValueError("JSON root must be a list (or dict with 'questions').")# dict 아닌 것 제거return [x for x in data if isinstance(x, dict)]def _normalize_item(item: Dict[str, Any]) -> Dict[str, Any]:# stemstem = (item.get("stem") or item.get("question") or item.get("q_text") or "")stem = str(stem).strip()explanation = str(item.get("explanation") or "").strip()qtype = item.get("question_type", "MCQ")code = item.get("code", "")category = item.get("category") or item.get("topic") or Nonesubcategory = item.get("subcategory") or item.get("subtopic") or None# options 표준화options_std = _normalize_options(item.get("options"))# 정렬키 (있으면)source_pages = item.get("source_pages")page_no = source_pages[0] if isinstance(source_pages, list) and source_pages else Nonepage_legacy = item.get("page")q_no_on_page = item.get("q_no_on_page")global_no = item.get("global_no") or item.get("question_id")# 이미지images = item.get("images") or item.get("image_urls") or []if not isinstance(images, list):images = []# steps 정답answer_steps = _infer_steps_answer_keys(item, options_std)# 일반 정답 key들answer_keys = []if not answer_steps:if isinstance(item.get("answer_keys"), list):answer_keys = [str(x).strip() for x in item["answer_keys"] if str(x).strip()]else:answer_keys = _to_list_answer_keys(item.get("answer"))return {"stem": stem,"explanation": explanation,"question_type": qtype,"category": category,"subcategory": subcategory,"code": code,"options_std": options_std,"page": page_legacy,"page_no": page_no,"q_no_on_page": q_no_on_page,"global_no": global_no,"answer_keys": answer_keys,"answer_steps": answer_steps,# 레거시 유지"pairs": item.get("pairs"),"sequence": item.get("sequence"),"images": images,"raw_answer": item.get("answer"),}# -----------------------------# Ingest# -----------------------------def ingest_questions(json_path: str, source_name: str = "imported", rebuild_db: bool = False) -> int:"""✅ 현재 db.py/init_db()와 호환되는 통합 ingest- rebuild_db=True: DB 파일 삭제 후 init_db()로 새로 생성"""json_path = str(json_path)if rebuild_db and DB_PATH.exists():DB_PATH.unlink()print(f"[INFO] 🧹 Deleted DB: {DB_PATH}")# ✅ 현재 db.py는 인자 없는 init_db()만 지원init_db()rows = _load_json(json_path)db = SessionLocal()try:count = 0for raw in rows:qn = _normalize_item(raw)q = Question(page=qn["page"],stem=qn["stem"],explanation=qn["explanation"],question_type=qn["question_type"],category=qn["category"],subcategory=qn["subcategory"],source=source_name,code=qn["code"],)# (확장 모델이면) 정렬키 저장if hasattr(q, "page_no"):q.page_no = qn["page_no"]if hasattr(q, "q_no_on_page"):q.q_no_on_page = qn["q_no_on_page"]if hasattr(q, "global_no"):q.global_no = qn["global_no"]# ✅ options는 표준 list[dict]로 저장 (web 표시 안정화)q.set_options(qn["options_std"])# ✅ Steps 정답 처리if qn["answer_steps"]:if hasattr(q, "set_answer_steps"):q.set_answer_steps(qn["answer_steps"])q.answer = "" # 확장 컬럼 쓰는 경우 레거시 비워도 OKelse:# 구버전 fallback: sequence에 steps key 리스트 저장q.sequence = json.dumps(qn["answer_steps"], ensure_ascii=False)q.answer = "" # steps는 answer 문자열 비교가 의미 없음else:# ✅ 일반 정답(복수/중복 포함)if qn["answer_keys"]:if hasattr(q, "set_answer_keys"):q.set_answer_keys(qn["answer_keys"])q.answer = ""else:# 구버전 fallback: answer="A,B,C" (중복도 그대로)q.answer = ",".join(qn["answer_keys"])else:# 정답이 애매하면 원본 유지q.answer = str(qn["raw_answer"] or "").strip()# 레거시 pairs/sequence 유지(있으면)if qn["sequence"] is not None:q.sequence = json.dumps(qn["sequence"], ensure_ascii=False) if isinstance(qn["sequence"], list) else qn["sequence"]if qn["pairs"] is not None:q.pairs = json.dumps(qn["pairs"], ensure_ascii=False) if isinstance(qn["pairs"], (dict, list)) else qn["pairs"]# ✅ images 저장(확장 모델이면)if hasattr(q, "set_images"):q.set_images(qn["images"])db.add(q)count += 14 unmodified linesexcept Exception as e:db.rollback()print(f"[ERROR] DB 적재 중 오류 발생 → {e}")raisefinally:db.close()if __name__ == "__main__":# 너가 말한 실제 경로: data/questions.jsonpath = os.getenv("QUESTIONS_JSON", "data/questions.json")source = os.getenv("SOURCE_NAME", "az104_dump")rebuild = os.getenv("REBUILD_DB", "0") == "1"ingest_questions(path, source_name=source, rebuild_db=rebuild)
5 unmodified lines6789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354557 unmodified lines636465666768697071727374757677787980818283845 unmodified linesfrom sqlalchemy.orm import relationshipimport jsonfrom db import Base # ✅ Base 는 db.py 의 Base 를 사용# ----------------------------------------------# Question# ----------------------------------------------class Question(Base):__tablename__ = "questions"id = Column(Integer, primary_key=True, autoincrement=True)stem = Column(Text, nullable=False)answer = Column(String(255))explanation = Column(Text)question_type = Column(String(50), default="MCQ")page = Column(Integer)category = Column(String(100))subcategory = Column(String(100))code = Column(Text)source = Column(String(255))# JSON 문자열 저장options_json = Column(Text)pairs = Column(Text)sequence = Column(Text)# 보기 저장def set_options(self, options):try:self.options_json = (json.dumps(options, ensure_ascii=False)if isinstance(options, (list, dict))else options)except Exception:self.options_json = "[]"# 보기 가져오기def get_options(self):try:return json.loads(self.options_json) if self.options_json else []except:return []def get_pairs(self):try:return json.loads(self.pairs) if self.pairs else {}7 unmodified linesreturn []def __repr__(self):return f"<Question id={self.id} type={self.question_type}>"# ----------------------------------------------# Attempt# ----------------------------------------------class Attempt(Base):__tablename__ = "attempts"id = Column(Integer, primary_key=True, autoincrement=True)user_id = Column(String(100), nullable=False, default="guest")question_id = Column(Integer, ForeignKey("questions.id"))chosen = Column(String(10))correct = Column(Boolean, default=False)note_type = Column(String(20), default="wrong")question = relationship("Question", backref="attempts")def __repr__(self):return f"<Attempt q={self.question_id}, user={self.user_id}, correct={self.correct}>"5 unmodified lines6789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384857 unmodified lines939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251265 unmodified linesfrom sqlalchemy.orm import relationshipimport json# db.py에서 생성한 Base 객체를 가져옵니다.from db import Base# ----------------------------------------------# Question 모델# ----------------------------------------------class Question(Base):__tablename__ = "questions"id = Column(Integer, primary_key=True, autoincrement=True)# 문제 질문 (기존 이름 유지)stem = Column(Text, nullable=False)# 정답 (단순 리스트로 변경되어도 "A", "B" 또는 "1", "2" 같은 인덱스 키 저장)answer = Column(String(255))# 해설explanation = Column(Text)# 문제 유형 (MCQ: 객관식)question_type = Column(String(50), default="MCQ")# 메타 데이터page = Column(Integer)category = Column(String(100))subcategory = Column(String(100))code = Column(Text)source = Column(String(255))# -------------------------------------------------------# [데이터 구조 변경 핵심]# 기존: [{"key": "A", "text": "내용"}]# 변경: ["내용1", "내용2", "내용3"] (단순 문자열 리스트)# -------------------------------------------------------options_json = Column(Text, default="[]")pairs = Column(Text, default="{}")sequence = Column(Text, default="[]")# -------------------------------------------------------# Helper Methods (JSON 직렬화/역직렬화)# -------------------------------------------------------def set_options(self, options):"""리스트 데이터를 받아 JSON 문자열로 변환하여 저장합니다.Input 예시: ["EC2", "S3", "Lambda"]"""try:if options is None:self.options_json = "[]"elif isinstance(options, (list, dict)):# ensure_ascii=False: 한글 깨짐 방지self.options_json = json.dumps(options, ensure_ascii=False)else:# 문자열로 들어오면 그대로 저장 시도 혹은 리스트로 감싸기self.options_json = json.dumps([str(options)], ensure_ascii=False)except Exception as e:print(f"Error setting options: {e}")self.options_json = "[]"def get_options(self):"""저장된 JSON 문자열을 파이썬 리스트로 반환합니다.Return 예시: ["EC2", "S3", "Lambda"]"""try:if not self.options_json:return []return json.loads(self.options_json)except Exception:return []# (추가) pairs, sequence 처리도 동일한 방식으로 안정성 확보def get_pairs(self):try:return json.loads(self.pairs) if self.pairs else {}7 unmodified linesreturn []def __repr__(self):return f"<Question id={self.id} type={self.question_type} stem={self.stem[:20]}...>"# ----------------------------------------------# Attempt 모델 (사용자 풀이 기록)# ----------------------------------------------class Attempt(Base):__tablename__ = "attempts"id = Column(Integer, primary_key=True, autoincrement=True)# 사용자 ID (로그인 기능이 없다면 guest 혹은 브라우저 지문 등 사용)user_id = Column(String(100), nullable=False, default="guest")# 문제 ID (FK)question_id = Column(Integer, ForeignKey("questions.id"))# 사용자가 선택한 답 (프론트엔드에서 생성한 Key: "A", "B", "1" 등)chosen = Column(String(10))# 정답 여부correct = Column(Boolean, default=False)# 오답 노트 유형 (wrong: 틀림, bookmark: 중요 표시 등)note_type = Column(String(20), default="wrong")# 관계 설정 (Attempt.question 으로 문제 정보 접근 가능)question = relationship("Question", backref="attempts")def __repr__(self):return f"<Attempt q={self.question_id}, user={self.user_id}, correct={self.correct}>"
13 unmodified lines1415161718192 unmodified lines22232425262728293031323334353637383940413 unmodified lines4546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143213 unmodified lines--bad: #d12929;--card: #fff;--muted: #6b7280;}body {margin: 0;2 unmodified linespadding: 24px;display: flex;justify-content: center;}.wrap { width: 100%; max-width: 900px; }.topbar {display: flex; align-items: center; justify-content: space-between;margin-bottom: 16px; gap: 12px; flex-wrap: wrap;}.progress { color: var(--muted); font-size: 14px; }.jump-box {display: flex; align-items: center; gap: 8px;}.jump-box input {width: 70px; padding: 6px 10px; border: 1px solid #e5e7eb;border-radius: 8px; font-size: 14px; text-align: center;}.jump-box button {padding: 6px 12px; border: 1px solid #e5e7eb; border-radius: 8px;background: #fff; cursor: pointer; font-size: 13px;3 unmodified linesbackground: var(--brand); color: #fff; border-color: var(--brand);}.pill {font-size: 12px; padding: 6px 10px; border-radius: 999px;background: #f3f4f6; color: #374151;}.card {background: var(--card); border-radius: 14px; padding: 22px;box-shadow: 0 8px 24px rgba(0,0,0,.08);min-height: 260px;}.qid { font-size: 13px; color: var(--muted); margin-bottom: 6px; }.qtext { font-size: 18px; line-height: 1.5; margin: 0 0 14px; }.options { display: grid; gap: 10px; margin-top: 14px; }.opt {display: flex; align-items: center; gap: 10px; padding: 12px 14px;border: 1px solid #e5e7eb; border-radius: 10px; cursor: pointer; background: #fff;transition: background .15s, border-color .15s;}.opt:hover { background: #f0f6ff; border-color: #d1e3ff; }.opt.selected { background: #f0f6ff; border-color: var(--brand); }.opt.correct { border-color: #b8e3c1; background: #effaf2; }.opt.wrong { border-color: #f1b7b7; background: #fff1f1; }.opt.disabled { cursor: not-allowed; opacity: 0.7; }.opt input { accent-color: var(--brand); }.exp {display: none; margin-top: 14px; padding: 12px 14px; border-left: 5px solid var(--brand);background: #eef6ff; border-radius: 8px;}.exp.show { display: block; }.exp .title { margin: 0 0 6px; font-weight: 700; }.exp .ok { color: var(--ok); }.exp .bad { color: var(--bad); }.nav {margin-top: 18px; display: flex; align-items: center; gap: 14px;background: #fff; border-radius: 14px; box-shadow: 0 8px 24px rgba(0,0,0,.08);padding: 16px 18px;}.nav-group {display: flex; gap: 8px;}.spacer { flex: 1; }button.btn {border: 0; padding: 10px 18px; border-radius: 10px; color: #fff; background: var(--brand);cursor: pointer; font-weight: 600;transition: background .15s;}button.btn:hover { background: var(--brand-dark); }button.outline {background: #fff; color: #111827; border: 1px solid #e5e7eb;}button.bookmark { background: var(--warn); color: #1f2937; }button[disabled] { opacity: .5; cursor: not-allowed; }.loading {text-align: center;padding: 40px;color: var(--muted);}</style></head><body><div class="wrap"><div class="topbar"><div class="pill">CBT • 단일문제 모드</div><div class="jump-box"><span style="font-size: 13px; color: var(--muted);">문제 이동:</span><input type="number" id="jumpInput" placeholder="번호" min="1" /><button id="jumpBtn">이동</button></div><div class="progress" id="progress">문제 0 / 0</div></div><div class="card"><div id="loading" class="loading">문제를 불러오는 중...</div><div id="qContainer" style="display: none;"><div class="qid" id="qid"></div><h2 class="qtext" id="qtext"></h2><div class="options" id="options"></div><div class="exp" id="exp"></div></div></div><div class="nav"><button class="btn outline" id="homeBtn">🏠 홈</button><div class="nav-group"><button class="btn outline" id="prevBtn">← 이전</button><button class="btn outline" id="skipBtn">다음 →</button></div><div class="spacer"></div><button class="btn" id="submitBtn" disabled>정답 확인</button><button class="btn" id="nextBtn" style="display: none;">정답 후 다음 →</button><button class="btn bookmark" id="bmBtn">⭐ 복습</button></div></div><script>let currentQuestion = null;let selectedOption = null;let answered = false;const qidEl = document.getElementById("qid");const qtextEl = document.getElementById("qtext");const optsEl = document.getElementById("options");const expEl = document.getElementById("exp");const progressEl = document.getElementById("progress");const submitBtn = document.getElementById("submitBtn");const nextBtn = document.getElementById("nextBtn");const skipBtn = document.getElementById("skipBtn");const prevBtn = document.getElementById("prevBtn");const homeBtn = document.getElementById("homeBtn");const bmBtn = document.getElementById("bmBtn");const jumpInput = document.getElementById("jumpInput");const jumpBtn = document.getElementById("jumpBtn");const loadingEl = document.getElementById("loading");const qContainer = document.getElementById("qContainer");// localStorage에서 마지막 문제 번호 가져오기function getLastQuestionId() {return parseInt(localStorage.getItem("lastQuestionId")) || null;}// localStorage에 현재 문제 번호 저장function saveLastQuestionId(id) {localStorage.setItem("lastQuestionId", id);}// 문제 불러오기async function loadQuestion(questionId = null) {loadingEl.style.display = "block";qContainer.style.display = "none";try {const url = questionId ? `/api/question?id=${questionId}` : '/api/question';const res = await fetch(url);const data = await res.json();if (data.error) {loadingEl.textContent = "❌ " + data.error;return;}currentQuestion = data;render(data);saveLastQuestionId(data.id); // 문제 번호 저장loadingEl.style.display = "none";qContainer.style.display = "block";} catch (err) {loadingEl.textContent = "❌ 문제를 불러오지 못했습니다.";console.error(err);}}// 문제 렌더링function render(q) {progressEl.textContent = `문제 ${q.id} / ${q.total}`;qidEl.textContent = `ID ${q.id}`;qtextEl.textContent = q.question;optsEl.innerHTML = "";expEl.classList.remove("show");expEl.innerHTML = "";// 입력창 최대값 설정jumpInput.max = q.total;jumpInput.placeholder = `1-${q.total}`;// 초기화selectedOption = null;answered = false;submitBtn.disabled = true;submitBtn.style.display = "block";nextBtn.style.display = "none";skipBtn.style.display = "block";(q.options || []).forEach(opt => {const label = document.createElement("label");label.className = "opt";const input = document.createElement("input");input.type = "radio";input.name = `q${q.id}`;input.value = opt;input.addEventListener("change", () => onSelect(opt, label));label.appendChild(input);label.append(opt);optsEl.appendChild(label);});}// 선택function onSelect(chosen, labelEl) {if (answered) return;// 모든 선택 해제document.querySelectorAll('.opt').forEach(opt => {opt.classList.remove("selected");});// 새 선택labelEl.classList.add("selected");selectedOption = chosen.charAt(0); // "A. Berlin" -> "A"submitBtn.disabled = false;}// 정답 확인submitBtn.addEventListener("click", async () => {if (!selectedOption || answered) return;try {const res = await fetch("/api/answer", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({question_id: currentQuestion.id,chosen: selectedOption,user_id: "default"})});const result = await res.json();answered = true;// 정답/오답 표시document.querySelectorAll('.opt').forEach(opt => {opt.classList.add("disabled");const optLetter = opt.textContent.charAt(0);if (optLetter === result.answer) {opt.classList.add("correct");} else if (optLetter === selectedOption && !result.correct) {opt.classList.add("wrong");}});// 해설 표시showExplanation(result);submitBtn.style.display = "none";nextBtn.style.display = "block";skipBtn.style.display = "none";} catch (err) {console.error(err);alert("채점 중 오류가 발생했습니다.");}});// 해설 표시function showExplanation(result) {expEl.classList.add("show");const isCorrect = result.correct;expEl.innerHTML = `<div class="title ${isCorrect ? 'ok':'bad'}">${isCorrect ? "✅ 정답입니다!" : "❌ 오답입니다. 정답: " + result.answer}</div><div>${result.explanation || "해설이 없습니다."}</div>`;}// 다음 문제nextBtn.addEventListener("click", async () => {try {const res = await fetch(`/api/next?current_id=${currentQuestion.id}`);const data = await res.json();if (data.end) {alert("마지막 문제입니다!");return;}currentQuestion = data;render(data);saveLastQuestionId(data.id); // 문제 번호 저장} catch (err) {console.error(err);alert("다음 문제를 불러오는데 실패했습니다.");}});// 이전 문제prevBtn.addEventListener("click", async () => {if (!currentQuestion || currentQuestion.id <= 1) {alert("첫 번째 문제입니다!");return;}try {const prevId = currentQuestion.id - 1;await loadQuestion(prevId);} catch (err) {console.error(err);alert("이전 문제를 불러오는데 실패했습니다.");}});// 홈으로 이동homeBtn.addEventListener("click", () => {window.location.href = "/";});// 건너뛰기 (답 확인 없이 다음 문제)skipBtn.addEventListener("click", async () => {try {const res = await fetch(`/api/next?current_id=${currentQuestion.id}`);const data = await res.json();if (data.end) {alert("마지막 문제입니다!");return;}currentQuestion = data;render(data);saveLastQuestionId(data.id);} catch (err) {console.error(err);alert("다음 문제를 불러오는데 실패했습니다.");}});// 문제 번호로 이동jumpBtn.addEventListener("click", async () => {const targetId = parseInt(jumpInput.value);if (!targetId || targetId < 1) {alert("올바른 문제 번호를 입력하세요.");return;}if (currentQuestion && targetId > currentQuestion.total) {alert(`문제 번호는 1부터 ${currentQuestion.total}까지입니다.`);return;}await loadQuestion(targetId);jumpInput.value = "";});// Enter 키로 문제 이동jumpInput.addEventListener("keypress", (e) => {if (e.key === "Enter") {jumpBtn.click();}});// 복습 추가bmBtn.addEventListener("click", async () => {if (!currentQuestion) return;try {const res = await fetch("/api/review_add", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({question_id: currentQuestion.id,user_id: "default"})});const data = await res.json();alert(data.message);} catch (err) {console.error(err);alert("복습노트 추가 중 오류가 발생했습니다.");}});// 키보드 단축키window.addEventListener("keydown", e => {if (e.key === "Enter" && !submitBtn.disabled && submitBtn.style.display !== "none") {submitBtn.click();}if (e.key === "ArrowRight" && nextBtn.style.display !== "none") {nextBtn.click();}if (e.key === "ArrowLeft") {prevBtn.click();}});// 페이지 로드시 마지막 문제 또는 첫 문제const lastId = getLastQuestionId();if (lastId) {loadQuestion(lastId);} else {loadQuestion();}</script></body></html>13 unmodified lines141516171819202 unmodified lines23242526272829303132333435363738394041424344453 unmodified lines49505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070113 unmodified lines--bad: #d12929;--card: #fff;--muted: #6b7280;--text: #1f2937;}body {margin: 0;2 unmodified linespadding: 24px;display: flex;justify-content: center;color: var(--text);}.wrap { width: 100%; max-width: 900px; }/* Topbar */.topbar {display: flex; align-items: center; justify-content: space-between;margin-bottom: 16px; gap: 12px; flex-wrap: wrap;}.progress { color: var(--muted); font-size: 14px; font-weight: 500; }.jump-box { display: flex; align-items: center; gap: 8px; }.jump-box input {width: 60px; padding: 6px 10px; border: 1px solid #e5e7eb;border-radius: 8px; font-size: 14px; text-align: center;outline: none;}.jump-box input:focus { border-color: var(--brand); }.jump-box button {padding: 6px 12px; border: 1px solid #e5e7eb; border-radius: 8px;background: #fff; cursor: pointer; font-size: 13px;3 unmodified linesbackground: var(--brand); color: #fff; border-color: var(--brand);}.pill {font-size: 12px; padding: 6px 12px; border-radius: 999px;background: #e0e7ff; color: var(--brand-dark); font-weight: 600;}/* Card */.card {background: var(--card); border-radius: 16px; padding: 28px;box-shadow: 0 10px 30px rgba(0,0,0,.06);min-height: 300px; position: relative;}/* Fade Animation */.fade-in { animation: fadeIn 0.3s ease-out; }@keyframes fadeIn {from { opacity: 0; transform: translateY(5px); }to { opacity: 1; transform: translateY(0); }}.qid { font-size: 13px; color: var(--muted); margin-bottom: 8px; font-weight: 600; }.qtext { font-size: 19px; line-height: 1.55; margin: 0 0 20px; font-weight: 700; word-break: keep-all; }/* Options */.options { display: grid; gap: 12px; margin-top: 16px; }.opt {display: flex; align-items: flex-start; gap: 12px; padding: 14px 16px;border: 2px solid #e5e7eb; border-radius: 12px; cursor: pointer; background: #fff;transition: all .2s; position: relative;}.opt:hover:not(.disabled) { background: #f8fafc; border-color: #cbd5e1; }.opt.selected { background: #eff6ff; border-color: var(--brand); box-shadow: 0 0 0 1px var(--brand); }.opt.correct { border-color: var(--ok); background: #f0fdf4; }.opt.wrong { border-color: var(--bad); background: #fef2f2; }.opt.disabled { cursor: default; opacity: 0.8; pointer-events: none; }/* Input Custom Style */.opt input { margin-top: 4px; accent-color: var(--brand); cursor: pointer; }.opt-key {font-size: 12px; font-weight: 700; color: var(--muted);min-width: 20px; margin-top: 3px;}/* Explanation */.exp {display: none; margin-top: 20px; padding: 16px;border-left: 5px solid var(--brand);background: #f0f9ff; border-radius: 8px;line-height: 1.6;}.exp.show { display: block; animation: fadeIn 0.3s; }.exp .title { margin: 0 0 8px; font-weight: 700; font-size: 16px; display: flex; align-items: center; gap: 6px; }.exp .ok { color: var(--ok); }.exp .bad { color: var(--bad); }/* Navigation */.nav {margin-top: 20px; display: flex; align-items: center; gap: 12px;background: #fff; border-radius: 16px; box-shadow: 0 10px 30px rgba(0,0,0,.06);padding: 16px 20px; flex-wrap: wrap;}.nav-group { display: flex; gap: 8px; }.spacer { flex: 1; }button.btn {border: 0; padding: 12px 20px; border-radius: 10px; color: #fff; background: var(--brand);cursor: pointer; font-weight: 600; font-size: 15px;transition: background .15s, transform .05s;}button.btn:active { transform: scale(0.98); }button.btn:hover:not([disabled]) { background: var(--brand-dark); }button.outline {background: #fff; color: #374151; border: 1px solid #d1d5db;}button.outline:hover { background: #f9fafb; border-color: #9ca3af; }button.bookmark { background: #fffbeb; color: #92400e; border: 1px solid #fcd34d; }button.bookmark:hover { background: #fef3c7; }button[disabled] { opacity: .5; cursor: not-allowed; background: #9ca3af; }.loading { text-align: center; padding: 60px 0; color: var(--muted); font-size: 15px; }/* Toast Notification */#toast-container {position: fixed; bottom: 24px; left: 50%; transform: translateX(-50%);z-index: 1000; display: flex; flex-direction: column; gap: 10px; pointer-events: none;}.toast {background: #1f2937; color: #fff; padding: 12px 24px; border-radius: 50px;font-size: 14px; opacity: 0; transform: translateY(20px);transition: all 0.3s; box-shadow: 0 4px 12px rgba(0,0,0,0.15);}.toast.show { opacity: 1; transform: translateY(0); }/* Multi-answer hint */.multi-hint {margin-top: 10px;font-size: 13px;color: var(--muted);display: none;}.multi-hint.show { display: block; }/* Mobile Responsive */@media (max-width: 640px) {body { padding: 12px; padding-bottom: 80px; }.topbar { flex-direction: column; align-items: stretch; gap: 10px; }.jump-box { justify-content: space-between; }.jump-box input { width: 100%; flex:1; }.card { padding: 20px; }.qtext { font-size: 17px; }.nav {flex-direction: column; gap: 10px; padding: 12px 16px;position: fixed; bottom: 0; left: 0; right: 0;border-radius: 20px 20px 0 0; box-shadow: 0 -4px 20px rgba(0,0,0,0.08);z-index: 50;}.nav-group { width: 100%; display: grid; grid-template-columns: 1fr 1fr; }button.btn { width: 100%; padding: 12px; }.spacer { display: none; }#homeBtn, #bmBtn { display: none; }}</style></head><body><div class="wrap"><div class="topbar"><div class="pill">AZ-104 CBT 연습</div><div class="spacer" style="flex:1"></div><div class="progress" id="progress">문제 - / -</div><div class="jump-box"><input type="number" id="jumpInput" placeholder="No." min="1" /><button id="jumpBtn">이동</button></div></div><div class="card"><div id="loading" class="loading"><svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" style="animation: spin 1s linear infinite; margin-bottom: 10px; display:block; margin: 0 auto 10px;"><path d="M12 2V6" stroke="currentColor" stroke-width="2" stroke-linecap="round"/><path d="M12 18V22" stroke="currentColor" stroke-width="2" stroke-linecap="round"/><path d="M4.93 4.93L7.76 7.76" stroke="currentColor" stroke-width="2" stroke-linecap="round"/><path d="M16.24 16.24L19.07 19.07" stroke="currentColor" stroke-width="2" stroke-linecap="round"/><path d="M2 12H6" stroke="currentColor" stroke-width="2" stroke-linecap="round"/><path d="M18 12H22" stroke="currentColor" stroke-width="2" stroke-linecap="round"/><path d="M4.93 19.07L7.76 16.24" stroke="currentColor" stroke-width="2" stroke-linecap="round"/><path d="M16.24 7.76L19.07 4.93" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg><style>@keyframes spin { 100% { transform: rotate(360deg); } }</style>문제를 불러오는 중...</div><div id="qContainer" style="display: none;"><div class="qid" id="qid"></div><h2 class="qtext" id="qtext"></h2><!-- ✅ 멀티/스텝 힌트 --><div id="multiHint" class="multi-hint"></div><div class="options" id="options"></div><div class="exp" id="exp"></div></div></div><div class="nav"><button class="btn outline" id="homeBtn" title="홈으로">🏠</button><div class="nav-group"><button class="btn outline" id="prevBtn">← 이전</button><button class="btn outline" id="skipBtn">스킵 →</button></div><div class="spacer"></div><button class="btn" id="submitBtn" disabled>정답 확인 (Enter)</button><button class="btn" id="nextBtn" style="display: none;">다음 문제 →</button><button class="btn bookmark" id="bmBtn">⭐ 복습 저장</button></div></div><div id="toast-container"></div><script>/* --- Global State --- */let currentQuestion = null;let answered = false;// ✅ 단일/복수/스텝에 따라 UI/채점 모드// mode: "single" | "multi" | "steps"let answerMode = "single";// ✅ 선택값// single: string("A")// multi/steps: array(["A","C"]) / array(["E","B","C"])let selected = null;/* --- Elements --- */const els = {qid: document.getElementById("qid"),qtext: document.getElementById("qtext"),opts: document.getElementById("options"),exp: document.getElementById("exp"),progress: document.getElementById("progress"),submitBtn: document.getElementById("submitBtn"),nextBtn: document.getElementById("nextBtn"),skipBtn: document.getElementById("skipBtn"),prevBtn: document.getElementById("prevBtn"),homeBtn: document.getElementById("homeBtn"),bmBtn: document.getElementById("bmBtn"),jumpInput: document.getElementById("jumpInput"),jumpBtn: document.getElementById("jumpBtn"),loading: document.getElementById("loading"),qContainer: document.getElementById("qContainer"),toastContainer: document.getElementById("toast-container"),multiHint: document.getElementById("multiHint"),};/* --- Utils --- */function showToast(message) {const toast = document.createElement("div");toast.className = "toast";toast.textContent = message;els.toastContainer.appendChild(toast);void toast.offsetWidth;toast.classList.add("show");setTimeout(() => {toast.classList.remove("show");setTimeout(() => toast.remove(), 300);}, 2500);}function getLastQuestionId() {return parseInt(localStorage.getItem("lastQuestionId")) || null;}function saveLastQuestionId(id) {localStorage.setItem("lastQuestionId", id);}function setLoading(isLoading) {els.loading.style.display = isLoading ? "block" : "none";els.qContainer.style.display = isLoading ? "none" : "block";}function toKey(opt) {// opt: "A. text" / "2-D. text" 형태const s = String(opt || "").trim();if (!s) return "";// 첫 토큰을 key로: "A." / "2-D." / "B)" 등const first = s.split(/\s+/)[0];return first.replace(/[.)]$/, "").trim();}function inferModeFromQuestion(q) {// ✅ Steps 우선 (백엔드가 answer_steps 내려주면 확정)if (Array.isArray(q.answer_steps) && q.answer_steps.length) return "steps";// ✅ 멀티: answer_keys가 2개 이상이거나 answer 문자열에 쉼표가 있으면if (Array.isArray(q.answer_keys) && q.answer_keys.length >= 2) return "multi";if (typeof q.answer === "string" && q.answer.includes(",")) return "multi";return "single";}function setHint(mode) {els.multiHint.classList.remove("show");els.multiHint.textContent = "";if (mode === "multi") {els.multiHint.textContent = "💡 복수 정답 문제입니다. 정답을 여러 개 선택한 뒤 제출하세요.";els.multiHint.classList.add("show");} else if (mode === "steps") {els.multiHint.textContent = "💡 순서(단계) 문제입니다. 정답을 순서대로 클릭하세요. (다시 클릭하면 마지막 선택이 취소됩니다)";els.multiHint.classList.add("show");}}function resetState() {selected = null;answered = false;els.submitBtn.disabled = true;els.submitBtn.style.display = "block";els.nextBtn.style.display = "none";els.skipBtn.style.display = "block";els.exp.classList.remove("show");els.exp.innerHTML = "";els.opts.innerHTML = "";}function updateSubmitEnabled() {if (answerMode === "single") {els.submitBtn.disabled = !selected;} else {els.submitBtn.disabled = !(Array.isArray(selected) && selected.length > 0);}}// steps 모드: 선택 순서 표시(옵션 우측 상단 배지 대신, 간단히 selected 클래스로만 유지)function toggleSelectedClass(labelEl, on) {if (on) labelEl.classList.add("selected");else labelEl.classList.remove("selected");}function clearAllSelectedClass() {document.querySelectorAll(".opt").forEach(el => el.classList.remove("selected"));}function getSelectedArray() {if (!Array.isArray(selected)) return [];return selected.slice();}/* --- Core Logic --- */async function loadQuestion(questionId = null) {setLoading(true);try {const url = questionId ? `/api/question?id=${questionId}` : "/api/question";const res = await fetch(url);if (!res.ok) throw new Error("네트워크 응답 오류");const data = await res.json();if (data.error) {els.loading.innerHTML = `<span style="color:var(--bad)">⚠️ ${data.error}</span>`;return;}currentQuestion = data;render(data);saveLastQuestionId(data.id);setLoading(false);} catch (err) {els.loading.innerHTML = `<span style="color:var(--bad)">⚠️ 문제를 불러오지 못했습니다.<br><small>${err.message}</small></span>`;console.error(err);}}function render(q) {els.qContainer.classList.remove("fade-in");void els.qContainer.offsetWidth;els.qContainer.classList.add("fade-in");els.progress.textContent = `문제 ${q.id} / ${q.total}`;els.qid.textContent = `Question ID: ${q.id}`;els.qtext.textContent = q.question;els.jumpInput.max = q.total;els.jumpInput.placeholder = `Total ${q.total}`;resetState();// ✅ 모드 판별 + 힌트answerMode = inferModeFromQuestion(q);setHint(answerMode);// ✅ 옵션 렌더(q.options || []).forEach((opt, index) => {const line = (typeof opt === "string") ? opt : `${opt.key}. ${opt.text}`;const key = toKey(line);let text = line.replace(/^[^\s]+[\s]*/, ""); // 첫 토큰 제거 후 나머지// "A. xxx" 같은 경우 앞에 "A." 제거가 덜 될 수 있어 보정text = text.replace(/^[A-Z]\s*[\.\)]\s*/, "");const label = document.createElement("label");label.className = "opt";label.dataset.key = key;label.dataset.idx = index + 1;const input = document.createElement("input");input.name = `q${q.id}`;// ✅ single=radio, multi/steps=checkbox (steps도 체크박스를 쓰되, 클릭 순서로 배열 관리)input.type = (answerMode === "single") ? "radio" : "checkbox";input.value = key;// 클릭/변경 이벤트 통합 처리input.addEventListener("change", (e) => onSelect(key, label, e.target.checked));const keySpan = document.createElement("div");keySpan.className = "opt-key";keySpan.textContent = key + ".";const textSpan = document.createElement("div");textSpan.style.flex = "1";textSpan.textContent = text;label.appendChild(input);label.appendChild(keySpan);label.appendChild(textSpan);els.opts.appendChild(label);// label 클릭해도 토글되게(모바일 체감 좋음)label.addEventListener("click", (e) => {if (answered) return;// input 자체 클릭은 기본 동작에 맡기고, label 영역 클릭만 보정if (e.target.tagName !== "INPUT") input.click();});});}function onSelect(key, labelEl, checked) {if (answered) return;if (answerMode === "single") {// 기존 동작 유지document.querySelectorAll(".opt").forEach(opt => opt.classList.remove("selected"));labelEl.classList.add("selected");selected = key;updateSubmitEnabled();return;}// multi / steps: 배열로 관리if (!Array.isArray(selected)) selected = [];if (answerMode === "multi") {// checkbox 그대로 반영if (checked) {if (!selected.includes(key)) selected.push(key);toggleSelectedClass(labelEl, true);} else {selected = selected.filter(x => x !== key);toggleSelectedClass(labelEl, false);}updateSubmitEnabled();return;}// steps: 클릭 순서가 중요// 규칙: 체크되면 push, 해제되면 "마지막 요소"일 때만 pop 허용(사용자 실수 방지)if (checked) {if (!selected.includes(key)) selected.push(key);toggleSelectedClass(labelEl, true);} else {// 마지막만 취소 허용const last = selected[selected.length - 1];if (last === key) {selected.pop();toggleSelectedClass(labelEl, false);} else {// 되돌리고 안내const input = labelEl.querySelector("input");if (input) input.checked = true;showToast("순서 문제는 마지막 선택만 취소할 수 있어요.");}}updateSubmitEnabled();}// 정답 제출els.submitBtn.addEventListener("click", async () => {if (answered) return;// 선택 값 만들기let chosenPayload = null;if (answerMode === "single") {if (!selected) return;chosenPayload = selected;} else {const arr = getSelectedArray();if (!arr.length) return;chosenPayload = arr.length === 1 ? arr[0] : arr; // 백엔드 호환(1개면 string)}els.submitBtn.disabled = true;try {const res = await fetch("/api/answer", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({question_id: currentQuestion.id,chosen: chosenPayload,user_id: "default"})});const result = await res.json();answered = true;// 정답키/steps키를 받을 수 있으면 우선 사용// - 최적화 app.py: answer_keys / answer_steps를 내려줄 수 있음const answerKeys = Array.isArray(currentQuestion.answer_keys) ? currentQuestion.answer_keys.map(String) : [];const answerSteps = Array.isArray(currentQuestion.answer_steps) ? currentQuestion.answer_steps.map(String) : [];// 서버가 answer를 "A,B"로 주는 구버전이면 파싱const legacyKeys = (typeof result.answer === "string" && result.answer.includes(","))? result.answer.split(",").map(x => x.trim()).filter(Boolean): [];// 채점용 정답 리스트 결정let correctList = [];if (answerMode === "steps" && answerSteps.length) correctList = answerSteps;else if (answerMode !== "single" && answerKeys.length) correctList = answerKeys;else if (legacyKeys.length) correctList = legacyKeys;else if (typeof result.answer === "string" && result.answer) correctList = [result.answer];// 스타일 적용document.querySelectorAll(".opt").forEach(optEl => {optEl.classList.add("disabled");const optKey = optEl.dataset.key;// correctList에 있으면 correct 표기 (멀티면 여러개)if (correctList.includes(optKey)) {optEl.classList.add("correct");}// 오답 표기: 선택했는데 correctList에 없으면 wrongif (answerMode === "single") {if (optKey === selected && !result.correct && !correctList.includes(optKey)) {optEl.classList.add("wrong");}} else {const selArr = Array.isArray(selected) ? selected : [];if (selArr.includes(optKey) && !result.correct && !correctList.includes(optKey)) {optEl.classList.add("wrong");}}});showExplanation(result, correctList);els.submitBtn.style.display = "none";els.nextBtn.style.display = "block";els.skipBtn.style.display = "none";els.nextBtn.focus();} catch (err) {console.error(err);showToast("❌ 채점 중 오류가 발생했습니다.");els.submitBtn.disabled = false;}});function showExplanation(result, correctList) {els.exp.classList.add("show");const isCorrect = !!result.correct;const correctText = correctList.length ? correctList.join(", ") : (result.answer || "(정답 정보 없음)");const extra =(answerMode === "multi") ? `<div style="margin-top:6px;color:var(--muted);font-size:13px">선택: ${Array.isArray(selected) ? selected.join(", ") : selected}</div>` :(answerMode === "steps") ? `<div style="margin-top:6px;color:var(--muted);font-size:13px">선택(순서): ${Array.isArray(selected) ? selected.join(" → ") : selected}</div>` :"";els.exp.innerHTML = `<div class="title ${isCorrect ? 'ok':'bad'}">${isCorrect ? "✅ 정답입니다!" : "❌ 오답! 정답은 " + correctText + " 입니다."}</div>${extra}<div>${result.explanation || "해설 정보가 없습니다."}</div>`;}// 다음/이전/스킵async function moveQuestion(direction) {if (!currentQuestion) return;if (direction === "prev") {if (currentQuestion.id <= 1) { showToast("첫 번째 문제입니다."); return; }await loadQuestion(currentQuestion.id - 1);return;}try {const res = await fetch(`/api/next?current_id=${currentQuestion.id}`);const data = await res.json();if (data.end) { showToast("🎉 마지막 문제입니다!"); return; }currentQuestion = data;render(data);saveLastQuestionId(data.id);} catch (err) {showToast("❌ 이동 실패");}}els.nextBtn.addEventListener("click", () => moveQuestion("next"));els.skipBtn.addEventListener("click", () => moveQuestion("next"));els.prevBtn.addEventListener("click", () => moveQuestion("prev"));// 북마크els.bmBtn.addEventListener("click", async () => {if (!currentQuestion) return;try {const res = await fetch("/api/review_add", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ question_id: currentQuestion.id, user_id: "default" })});const data = await res.json();showToast("⭐ " + (data.message || "복습 노트에 저장되었습니다."));} catch (err) {showToast("❌ 저장 실패");}});// 점프function jumpTo() {const targetId = parseInt(els.jumpInput.value);if (!targetId || targetId < 1) { showToast("⚠️ 올바른 번호를 입력하세요."); return; }if (currentQuestion && targetId > currentQuestion.total) { showToast(`⚠️ 1 ~ ${currentQuestion.total} 사이만 가능합니다.`); return; }loadQuestion(targetId);els.jumpInput.value = "";}els.jumpBtn.addEventListener("click", jumpTo);els.jumpInput.addEventListener("keypress", (e) => { if (e.key === "Enter") jumpTo(); });els.homeBtn.addEventListener("click", () => window.location.href = "/");// 키보드 단축키window.addEventListener("keydown", e => {if (document.activeElement.tagName === "INPUT") return;const key = e.key.toUpperCase();// 선택지 선택(1~4 / A~D) — 멀티/스텝에서도 "토글"로 동작if (!answered) {const keyMap = { "1":"A", "2":"B", "3":"C", "4":"D", "A":"A", "B":"B", "C":"C", "D":"D" };if (keyMap[key]) {const targetKey = keyMap[key];const targetLabel = document.querySelector(`.opt[data-key="${targetKey}"]`);if (targetLabel) {const input = targetLabel.querySelector("input");if (input) input.click();}}}// 제출/다음 (Enter)if (e.key === "Enter") {if (!els.submitBtn.disabled && els.submitBtn.style.display !== "none") {els.submitBtn.click();} else if (els.nextBtn.style.display !== "none") {els.nextBtn.click();}}// 이동 (좌우)if (e.key === "ArrowRight") {if (els.nextBtn.style.display !== "none") els.nextBtn.click();}if (e.key === "ArrowLeft") {els.prevBtn.click();}});// 초기 실행const lastId = getLastQuestionId();loadQuestion(lastId || undefined);</script></body></html>
app.py+217-38
db.py+30-16
ingest.py+245-79
models.py+61-19
templates/quiz.html+517-248
adaptive_parser_monitor.py → 삭제용/adaptive_parser_monitor.pyRenamed
adative_parser_watchdog.py → 삭제용/adative_parser_watchdog.pyRenamed
analyze_parser_log_ai.py → 삭제용/analyze_parser_log_ai.pyRenamed
append_questions.py → 삭제용/append_questions.pyRenamed
check_db.py → 삭제용/check_db.pyRenamed
classify.py → 삭제용/classify.pyRenamed
deploy_to_spaces.py → 삭제용/deploy_to_spaces.pyRenamed
llm_extract.py → 삭제용/llm_extract.pyRenamed
llm_parse.py → 삭제용/llm_parse.pyRenamed
ocr_test_light.py → 삭제용/ocr_test_light.pyRenamed
parse_pipeline.py → 삭제용/parse_pipeline.pyRenamed
pdf_parser.py → 삭제용/pdf_parser.pyRenamed
pdf_parser_adaptive.py → 삭제용/pdf_parser_adaptive.pyRenamed
schemas.py → 삭제용/schemas.pyRenamed
seed.py → 삭제용/seed.pyRenamed
similarity.py → 삭제용/similarity.pyRenamed