import os import sys import io import csv import json import re import random from typing import List, Dict, Optional import traceback import streamlit as st import pandas as pd from dotenv import load_dotenv load_dotenv() st.write("DEBUG ANTHROPIC_MODEL:", os.getenv("ANTHROPIC_MODEL")) st.write("DEBUG ANTHROPIC_API_KEY exists:", bool(os.getenv("ANTHROPIC_API_KEY"))) LLM_AVAILABLE = False generate_quiz_llm = None llm_error = None try: from utils.utils_quiz_llm import generate_quiz_llm # type: ignore LLM_AVAILABLE = True except Exception as e: LLM_AVAILABLE = False llm_error = str(e) # ========= Paths / Imports ========= BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # .../src UTILS_DIR = os.path.join(BASE_DIR, "utils") # .../src/utils if BASE_DIR not in sys.path: sys.path.append(BASE_DIR) # ---- Baseline (ของเดิม) ---- from utils.loader import load_to_text from utils.qg_baseline import ( generate_quiz as generate_quiz_baseline, to_csv_rows as to_csv_rows_baseline, ) def mcq_to_baseline_rows( questions, q_types=None, default_type="MCQ", seed: Optional[int] = None, ): """ แปลง list ของคำถามให้กลายเป็นรูปแบบเดียวกับ baseline (No, Type, Question, OptionA..D, Answer, Explanation) """ # 1) เคสที่ engine (เช่น LLM) สร้าง type/question/options/answer มาให้ครบแล้ว # -> ไม่ต้องดัดรูปแบบคำถาม แค่จัด options ให้ครบ 4 ตัว แล้วส่งเข้า to_csv_rows_baseline if questions and all(isinstance(q, dict) and "type" in q for q in questions): quiz = [] for q in questions: q_type = str(q.get("type", default_type)).upper() stem = str(q.get("question", "")) ans = str(q.get("answer", "")) opts = [ str(o) for o in q.get("options", []) if isinstance(o, (str, int, float)) and str(o).strip() ] # ให้มี answer อยู่ใน options ด้วย if ans and all(ans.lower() != o.lower() for o in opts): opts.insert(0, ans) if not opts and ans: opts = [ans] # pad ตัวเลือกให้ครบ 4 while len(opts) < 4: opts.append("—") opts = opts[:4] quiz.append({ "type": q_type, "question": stem, "options": opts, "answer": ans, "explanation": str(q.get("explanation", "") or ""), }) return to_csv_rows_baseline(quiz) # 2) เคสเก่า ๆ (เช่น TF-IDF / MiniLM) ที่ยังให้มาแค่ question/answer/options # ตรงนี้จะดัดจาก MCQ ตาม q_types (ถ้ายังอยากใช้ logic เดิมก็ใส่ต่อจากตรงนี้ได้) # ถ้าไม่อยากดัดอะไรเลย สามารถให้กลับไปเป็น MCQ ล้วน ๆ แบบนี้: quiz = [] for q in questions: stem = str(q.get("question", "")) ans = str(q.get("answer", "")) opts = [ str(o) for o in q.get("options", []) if isinstance(o, (str, int, float)) and str(o).strip() ] if ans and all(ans.lower() != o.lower() for o in opts): opts.insert(0, ans) if not opts and ans: opts = [ans] while len(opts) < 4: opts.append("—") opts = opts[:4] quiz.append({ "type": default_type, "question": stem, "options": opts, "answer": ans, "explanation": "", }) return to_csv_rows_baseline(quiz) # ---- Smart TF-IDF ---- SMART_AVAILABLE = False generate_quiz_smart: Optional[callable] = None smart_error: Optional[str] = None try: from utils.utils_quiz_quality import generate_quiz as generate_quiz_smart # type: ignore SMART_AVAILABLE = True except Exception as e: SMART_AVAILABLE = False smart_error = str(e) # ---- Smart AI (MiniLM) ---- AI_AVAILABLE = False generate_quiz_ai: Optional[callable] = None ai_error: Optional[str] = None try: from utils.utils_quiz_embedding import generate_quiz as generate_quiz_ai # type: ignore AI_AVAILABLE = True except Exception as e: AI_AVAILABLE = False ai_error = f"{e}\n{traceback.format_exc()}" # ---- LLM (Claude 3) ---- LLM_AVAILABLE = False generate_quiz_llm = None # type: ignore llm_error: Optional[str] = None try: from utils.utils_quiz_llm import generate_quiz_llm # type: ignore LLM_AVAILABLE = True except Exception as e: LLM_AVAILABLE = False llm_error = str(e) # ========= Page Config / CSS ========= st.set_page_config(page_title="Quiz Generation", page_icon="🧠", layout="wide") st.markdown(""" """, unsafe_allow_html=True) # ========= Helpers ========= def text_to_slides(txt: str) -> List[str]: if not txt: return [] parts = [p.strip() for p in txt.split("\n\n") if p.strip()] if len(parts) <= 2: import re parts = re.split(r"(?:^|\n)(?:Slide|สไลด์)\s*\d*[::-]?", txt, flags=re.IGNORECASE) parts = [p.strip() for p in parts if p and p.strip()] return [p if len(p) <= 5000 else p[:5000] for p in parts] def render_outputs(df: pd.DataFrame, rows: List[Dict], qc_info: Optional[Dict] = None) -> None: counts = df["Type"].value_counts().to_dict() if not df.empty else {} k_cloze = counts.get("CLOZE", 0) k_tf = counts.get("T/F", 0) k_mcq = counts.get("MCQ", 0) st.markdown('
', unsafe_allow_html=True) st.markdown(f'
รวมข้อ
{len(df)}
', unsafe_allow_html=True) st.markdown(f'
CLOZE
{k_cloze}
', unsafe_allow_html=True) st.markdown(f'
T/F • MCQ
{k_tf} • {k_mcq}
', unsafe_allow_html=True) st.markdown('
', unsafe_allow_html=True) if qc_info is not None: st.info(f"QC report: {qc_info}") tab_table, tab_csv, tab_json = st.tabs(["📋 ตารางคำถาม", "🧾 พรีวิว CSV", "🧩 JSON"]) with tab_table: st.dataframe(df, use_container_width=True) with tab_csv: csv_buf = io.StringIO() df.to_csv(csv_buf, index=False, sep=";", quoting=csv.QUOTE_ALL) csv_str = csv_buf.getvalue() st.code(csv_str[:1000] + ("\n... (ตัดท่อนี้ในการแสดงตัวอย่าง)" if len(csv_str) > 1000 else ""), language="csv") st.download_button("⬇️ ดาวน์โหลด CSV", csv_str.encode("utf-8-sig"), file_name="quiz_generated.csv", mime="text/csv", use_container_width=True) with tab_json: json_str = json.dumps(rows, ensure_ascii=False, indent=2) st.code(json_str[:2000] + ("\n... (ตัดท่อนี้ในการแสดงตัวอย่าง)" if len(json_str) > 2000 else ""), language="json") st.download_button("⬇️ ดาวน์โหลด JSON", json_str.encode("utf-8"), file_name="quiz_generated.json", mime="application/json", use_container_width=True) # ========= UI ========= st.markdown("

Quiz Generation

", unsafe_allow_html=True) st.caption("อัปโหลดสไลด์หรือไฟล์ข้อความ → ตั้งค่า → เลือก Engine → กดปุ่มเพื่อสร้าง Quiz อัตโนมัติ") st.markdown('
📘 Upload File
', unsafe_allow_html=True) uploaded = st.file_uploader("ลากไฟล์มาวาง หรือกดเพื่อเลือกไฟล์", type=["txt", "pdf", "docx", "csv"], label_visibility="collapsed", accept_multiple_files=False) st.markdown('
รองรับ .txt .pdf .docx .csv • ขนาดไม่ควรเกิน ~50MB
', unsafe_allow_html=True) text = "" if uploaded: st.markdown(f'
📄 {uploaded.name}
', unsafe_allow_html=True) st.divider() uploaded.seek(0) text = load_to_text(uploaded) st.subheader("📄 Preview") st.text_area("เนื้อหาไฟล์ (ตัวอย่าง)", text[:5000] if text else "(ไฟล์ไม่มีข้อความอ่านได้)", height=260, label_visibility="collapsed") if not text: st.info("ไม่พบข้อความที่อ่านได้จากไฟล์ที่อัปโหลด (อาจเป็นสแกนภาพหรือไฟล์ถูกล็อก).") st.divider() st.subheader("⚙️ Quiz Options") col1, col2, col3 = st.columns([1, 1, 2]) # ---------- ENGINE SELECT ---------- engine_choices = ["Baseline"] if SMART_AVAILABLE: engine_choices += ["Smart (TF-IDF)"] if AI_AVAILABLE: engine_choices += ["Smart AI (MiniLM)"] if LLM_AVAILABLE: engine_choices += ["LLM (Claude 3)"] engine = col1.selectbox("Engine", engine_choices, index=0, key="engine_select") n_questions = col1.slider("จำนวนข้อ", 5, 50, 10) q_types = col2.multiselect("ประเภทคำถาม", ["CLOZE", "T/F", "MCQ"], default=["CLOZE", "T/F", "MCQ"]) seed_value = col2.number_input("Seed (ผลลัพธ์คงที่)", min_value=0, value=42, step=1) if engine.startswith("Smart"): level = col3.selectbox("Difficulty", ["easy", "medium", "hard"], index=1) if "AI" in engine: st.markdown('Smart AI (MiniLM) engine: sentence embedding', unsafe_allow_html=True) else: st.markdown('Smart TF-IDF engine: weighted keywords + QC', unsafe_allow_html=True) else: level = None st.markdown('Baseline engine', unsafe_allow_html=True) # ---------- WARNINGS ---------- if not SMART_AVAILABLE and smart_error: st.warning(f"⚠️ Smart (TF-IDF) engine โหลดไม่สำเร็จ: {smart_error}") if not AI_AVAILABLE and ai_error: st.warning(f"⚠️ Smart AI (MiniLM) engine โหลดไม่สำเร็จ: {ai_error}") if not LLM_AVAILABLE and llm_error: st.warning(f"⚠️ LLM (Claude 3) engine โหลดไม่สำเร็จ: {llm_error}") generate_btn = st.button("🚀 สร้าง Quiz", use_container_width=True, disabled=not uploaded) # ========= Generate ========= if generate_btn: if not uploaded: st.warning("กรุณาอัปโหลดไฟล์ก่อน") elif not text: st.error("ไม่พบข้อความสำหรับสร้างแบบทดสอบ") else: slides = text_to_slides(text) if not slides: st.error("ไม่สามารถแยกสไลด์จากไฟล์ได้") else: if engine == "Smart (TF-IDF)" and SMART_AVAILABLE and generate_quiz_smart: with st.spinner("กำลังสร้างคำถามด้วย Smart TF-IDF engine…"): out = generate_quiz_smart( slides, n_questions=n_questions, level=level, seed=seed_value, q_types=q_types, ) rows = mcq_to_baseline_rows( out.get("questions", []), q_types=q_types, default_type="MCQ", seed=seed_value, ) df = pd.DataFrame(rows) render_outputs(df, rows, qc_info=out.get("qc_report", {})) elif engine == "Smart AI (MiniLM)" and AI_AVAILABLE and generate_quiz_ai: with st.spinner("กำลังสร้างคำถามด้วย Smart AI (MiniLM) engine…"): out = generate_quiz_ai( slides, n_questions=n_questions, level=level, seed=seed_value, q_types=q_types, ) rows = mcq_to_baseline_rows( out.get("questions", []), q_types=q_types, default_type="MCQ", seed=seed_value, ) df = pd.DataFrame(rows) render_outputs(df, rows, qc_info=out.get("qc_report", {})) elif engine == "LLM (Claude 3)" and LLM_AVAILABLE and generate_quiz_llm: try: with st.spinner("กำลังสร้างคำถามด้วย LLM (Claude 3)…"): out = generate_quiz_llm( slides, n_questions=n_questions, level=level, seed=seed_value, q_types=q_types, ) rows = mcq_to_baseline_rows( out.get("questions", []), q_types=q_types, default_type="MCQ", seed=seed_value, ) df = pd.DataFrame(rows) except Exception as e: st.error(f"LLM (Claude 3) มีปัญหา: {e}") rows = [] df = pd.DataFrame() else: render_outputs(df, rows, qc_info=out.get("qc_report", {})) else: with st.spinner("กำลังสร้างคำถามด้วย Baseline engine…"): quiz = generate_quiz_baseline( text, n_questions, mix=tuple(q_types), seed=seed_value, ) rows = to_csv_rows_baseline(quiz) df = pd.DataFrame(rows) render_outputs(df, rows)