File size: 16,022 Bytes
f87ae4b 9a64701 f87ae4b 9b23490 9a64701 91391c2 38a8da3 9a64701 d6c4a0f 9a64701 f87ae4b 9a64701 f87ae4b 9a64701 f87ae4b 9b23490 91391c2 9a64701 38a8da3 91391c2 d6c4a0f 9a64701 38a8da3 b8cf762 f87ae4b 9a64701 38a8da3 9a64701 38a8da3 91391c2 38a8da3 9a64701 38a8da3 f06adc7 f87ae4b 38a8da3 f87ae4b 9a64701 f87ae4b 91391c2 f87ae4b 9a64701 91391c2 d6c4a0f 91391c2 d6c4a0f f87ae4b 9a64701 f87ae4b 91391c2 f391007 9a64701 91391c2 9a64701 91391c2 9a64701 91391c2 9a64701 91391c2 d6c4a0f 9a64701 f87ae4b 9a64701 f87ae4b 91391c2 d6c4a0f 3d94eac d6c4a0f 9b23490 9a64701 91391c2 d6c4a0f 3d94eac d6c4a0f 9b23490 91391c2 d6c4a0f 9b23490 d6c4a0f 9b23490 d6c4a0f 91391c2 d6c4a0f 91391c2 d6c4a0f | 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 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 | 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("""
<style>
.block-container { max-width: 980px; margin: 2rem auto; }
.upload-title { display:flex; gap:12px; align-items:center; margin-bottom:8px; font-weight:700; font-size:22px; }
div[data-testid="stFileUploaderDropzone"]{ border:2px dashed rgba(0,0,0,.25); border-radius:14px; padding:26px;
transition:border-color .2s, background .2s; }
div[data-testid="stFileUploaderDropzone"]:hover{ border-color:#4f8bf9; background:rgba(79,139,249,0.06); }
.hint{ color:#8a8a8a; font-size:13px; margin-top:4px; }
.file-chip{ display:inline-flex; align-items:center; gap:8px; background:rgba(79,139,249,0.12); color:#1f4fbf;
border-radius:999px; padding:6px 12px; font-size:13px; }
.kpi { display:grid; grid-template-columns: repeat(3, minmax(0,1fr)); gap:12px; margin:8px 0 4px 0; }
.kpi .card{ border:1px solid rgba(0,0,0,.08); border-radius:12px; padding:14px 16px; background:var(--secondary-background-color); }
.kpi .title{ font-size:12px; color:#666; }
.kpi .value{ font-size:20px; font-weight:700; margin-top:2px; }
.badge{ display:inline-block; padding:3px 8px; border-radius:999px; font-size:12px; border:1px solid rgba(0,0,0,.15); }
</style>
""", 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('<div class="kpi">', unsafe_allow_html=True)
st.markdown(f'<div class="card"><div class="title">รวมข้อ</div><div class="value">{len(df)}</div></div>', unsafe_allow_html=True)
st.markdown(f'<div class="card"><div class="title">CLOZE</div><div class="value">{k_cloze}</div></div>', unsafe_allow_html=True)
st.markdown(f'<div class="card"><div class="title">T/F • MCQ</div><div class="value">{k_tf} • {k_mcq}</div></div>', unsafe_allow_html=True)
st.markdown('</div>', 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("<h1 style='margin:0 0 10px 0;'>Quiz Generation</h1>", unsafe_allow_html=True)
st.caption("อัปโหลดสไลด์หรือไฟล์ข้อความ → ตั้งค่า → เลือก Engine → กดปุ่มเพื่อสร้าง Quiz อัตโนมัติ")
st.markdown('<div class="upload-title">📘 Upload File</div>', unsafe_allow_html=True)
uploaded = st.file_uploader("ลากไฟล์มาวาง หรือกดเพื่อเลือกไฟล์",
type=["txt", "pdf", "docx", "csv"],
label_visibility="collapsed", accept_multiple_files=False)
st.markdown('<div class="hint">รองรับ .txt .pdf .docx .csv • ขนาดไม่ควรเกิน ~50MB</div>', unsafe_allow_html=True)
text = ""
if uploaded:
st.markdown(f'<div class="file-chip">📄 {uploaded.name}</div>', 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('<span class="badge">Smart AI (MiniLM) engine: sentence embedding</span>', unsafe_allow_html=True)
else:
st.markdown('<span class="badge">Smart TF-IDF engine: weighted keywords + QC</span>', unsafe_allow_html=True)
else:
level = None
st.markdown('<span class="badge">Baseline engine</span>', 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) |