pluem9 commited on
Commit
f87ae4b
·
1 Parent(s): 31e3978
src/streamlit_app.py CHANGED
@@ -1,111 +1,124 @@
1
  import streamlit as st
2
  import pandas as pd
3
- from io import StringIO
 
 
 
 
4
 
5
- st.set_page_config(page_title="Quiz Generation", layout="wide")
 
 
 
 
 
 
 
 
 
 
6
 
7
  # ---------- CSS ----------
8
  st.markdown("""
9
  <style>
10
- [data-testid="stTextInput"],
11
- [data-testid="stDecoratedTextInput"] { display: none !important; }
12
-
13
  .block-container { max-width: 980px; margin: 2rem auto; }
14
-
15
- .upload-card{
16
- background: var(--secondary-background-color);
17
- border: 1px solid rgba(0,0,0,0.08);
18
- border-radius: 18px;
19
- padding: 28px 24px;
20
- box-shadow: 0 6px 18px rgba(0,0,0,0.08);
21
- }
22
-
23
- .upload-title{
24
- display:flex; gap: 12px; align-items:center; margin-bottom: 8px;
25
- font-weight: 700; font-size: 22px;
26
- }
27
-
28
- div[data-testid="stFileUploaderDropzone"]{
29
- border: 2px dashed rgba(0,0,0,.25);
30
- border-radius: 14px;
31
- padding: 26px;
32
- transition: border-color .2s, background .2s;
33
- }
34
- div[data-testid="stFileUploaderDropzone"]:hover{
35
- border-color: #4f8bf9;
36
- background: rgba(79,139,249,0.06);
37
- }
38
-
39
- .hint{ color: #8a8a8a; font-size: 13px; margin-top: 4px; }
40
- .file-chip{
41
- display:inline-flex; align-items:center; gap:8px;
42
- background: rgba(79,139,249,0.12);
43
- color:#1f4fbf; border-radius: 999px; padding:6px 12px; font-size:13px;
44
- }
45
  </style>
46
  """, unsafe_allow_html=True)
47
 
48
  # ---------- Title ----------
49
  st.markdown("<h1 style='margin:0 0 10px 0;'>Quiz Generation</h1>", unsafe_allow_html=True)
50
- st.caption("อัปโหลดสไลด์/ไฟล์ข้อความ เพื่อสร้างแบบทดสอบอัตโนมัติ")
51
 
52
- # ---------- Upload Card ----------
53
  st.markdown('<div class="upload-title">📘 Upload File</div>', unsafe_allow_html=True)
54
- st.write("")
55
-
56
  uploaded = st.file_uploader(
57
  "ลากไฟล์มาวาง หรือกดเพื่อเลือกไฟล์",
58
  type=["txt", "pdf", "docx", "csv"],
59
  label_visibility="collapsed",
60
  accept_multiple_files=False
61
  )
62
-
63
  st.markdown('<div class="hint">รองรับ .txt .pdf .docx .csv • ขนาดไม่ควรเกิน ~50MB</div>', unsafe_allow_html=True)
64
- st.markdown("</div>", unsafe_allow_html=True)
65
-
66
- # ---------- Session State ----------
67
- if "uploaded_file" not in st.session_state:
68
- st.session_state.uploaded_file = None
69
- if "quiz_generated" not in st.session_state:
70
- st.session_state.quiz_generated = False
71
 
72
- # เก็บไฟล์ไว้ใน state
73
- if uploaded is not None:
74
- st.session_state.uploaded_file = uploaded
75
-
76
- # ---------- Preview & Actions ----------
77
- if st.session_state.uploaded_file:
78
- uploaded = st.session_state.uploaded_file
79
  st.markdown(f'<div class="file-chip">📄 {uploaded.name}</div>', unsafe_allow_html=True)
80
  st.divider()
81
-
82
- if uploaded.type == "text/plain":
83
- text = uploaded.read().decode("utf-8", errors="ignore")
84
- st.subheader("Preview")
85
- st.text_area("เนื้อหาไฟล์", text, height=260, label_visibility="collapsed")
86
-
87
- df = pd.DataFrame([{"Question": "ใครเป็นผู้คิดค้นโทรศัพท์?", "Answer": "Alexander Graham Bell"}])
88
- st.download_button(
89
- "⬇️ ดาวน์โหลดตัวอย่าง Quiz (CSV)",
90
- df.to_csv(index=False).encode("utf-8"),
91
- file_name="quiz_sample.csv",
92
- mime="text/csv"
93
- )
94
-
95
- elif uploaded.type == "text/csv":
96
- df = pd.read_csv(uploaded)
97
- st.subheader("Preview (CSV)")
98
- st.dataframe(df, use_container_width=True)
99
-
100
- else:
101
- st.info("ไฟล์ PDF/DOCX จะอ่านได้หลังจากเพิ่มไลบรารีอ่านไฟล์ (เช่น pdfplumber / python-docx)")
102
 
103
  # ---------- Action ----------
104
- with st.container():
105
- st.write("")
106
- col1, col2 = st.columns([1, 2])
107
- if col1.button("🚀 สร้าง Quiz"):
108
- st.session_state.quiz_generated = True
109
-
110
- if st.session_state.quiz_generated:
111
- st.success("กำลังเตรียมประมวลผล… (ต่อเชื่อม NLP ได้ภายหลัง)") # ใช้ session state แสดงผลต่อเนื่อง
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
  import pandas as pd
3
+ import io
4
+ import os
5
+ import sys
6
+ import csv
7
+ import json
8
 
9
+ # ---------- Setup Import Path ----------
10
+ BASE_DIR = os.path.dirname(__file__)
11
+ UTILS_DIR = os.path.join(BASE_DIR, "src", "utils")
12
+ if UTILS_DIR not in sys.path:
13
+ sys.path.append(UTILS_DIR)
14
+
15
+ from utils.loader import load_to_text
16
+ from utils.qg_baseline import generate_quiz, to_csv_rows
17
+
18
+ # ---------- Page Config ----------
19
+ st.set_page_config(page_title="Quiz Generation", page_icon="🧠", layout="wide")
20
 
21
  # ---------- CSS ----------
22
  st.markdown("""
23
  <style>
24
+ [data-testid="stTextInput"], [data-testid="stDecoratedTextInput"] { display:none!important; }
 
 
25
  .block-container { max-width: 980px; margin: 2rem auto; }
26
+ .upload-title { display:flex; gap:12px; align-items:center; margin-bottom:8px; font-weight:700; font-size:22px; }
27
+ div[data-testid="stFileUploaderDropzone"]{ border:2px dashed rgba(0,0,0,.25); border-radius:14px; padding:26px;
28
+ transition:border-color .2s, background .2s; }
29
+ div[data-testid="stFileUploaderDropzone"]:hover{ border-color:#4f8bf9; background:rgba(79,139,249,0.06); }
30
+ .hint{ color:#8a8a8a; font-size:13px; margin-top:4px; }
31
+ .file-chip{ display:inline-flex; align-items:center; gap:8px; background:rgba(79,139,249,0.12); color:#1f4fbf;
32
+ border-radius:999px; padding:6px 12px; font-size:13px; }
33
+ .kpi { display:grid; grid-template-columns: repeat(3, minmax(0,1fr)); gap:12px; margin:8px 0 4px 0; }
34
+ .kpi .card{ border:1px solid rgba(0,0,0,.08); border-radius:12px; padding:14px 16px; background:var(--secondary-background-color); }
35
+ .kpi .title{ font-size:12px; color:#666; }
36
+ .kpi .value{ font-size:20px; font-weight:700; margin-top:2px; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  </style>
38
  """, unsafe_allow_html=True)
39
 
40
  # ---------- Title ----------
41
  st.markdown("<h1 style='margin:0 0 10px 0;'>Quiz Generation</h1>", unsafe_allow_html=True)
42
+ st.caption("อัปโหลดสไลด์/ไฟล์ข้อความ → ตั้งค่า → กดปุ่มเพื่อสร้างแบบทดสอบอัตโนมัติ")
43
 
44
+ # ---------- Upload ----------
45
  st.markdown('<div class="upload-title">📘 Upload File</div>', unsafe_allow_html=True)
 
 
46
  uploaded = st.file_uploader(
47
  "ลากไฟล์มาวาง หรือกดเพื่อเลือกไฟล์",
48
  type=["txt", "pdf", "docx", "csv"],
49
  label_visibility="collapsed",
50
  accept_multiple_files=False
51
  )
 
52
  st.markdown('<div class="hint">รองรับ .txt .pdf .docx .csv • ขนาดไม่ควรเกิน ~50MB</div>', unsafe_allow_html=True)
 
 
 
 
 
 
 
53
 
54
+ text = ""
55
+ if uploaded:
 
 
 
 
 
56
  st.markdown(f'<div class="file-chip">📄 {uploaded.name}</div>', unsafe_allow_html=True)
57
  st.divider()
58
+ uploaded.seek(0)
59
+ text = load_to_text(uploaded)
60
+
61
+ st.subheader("📄 Preview")
62
+ st.text_area("เนื้อหาไฟล์ (ตัวอย่าง)", text[:5000] if text else "(ไฟล์ไม่มีข้อความอ่านได้)", height=260, label_visibility="collapsed")
63
+ if not text:
64
+ st.info("ไม่พบข้อความที่อ่านได้จากไฟล์ที่อัปโหลด (อาจเป็นสแกนภาพหรือมีการป้องกัน).")
65
+
66
+ # ---------- Options ----------
67
+ st.divider()
68
+ st.subheader("⚙️ Quiz Options")
69
+ col1, col2, col3 = st.columns([1, 1, 2])
70
+ n_questions = col1.slider("จำนวนข้อ", 5, 50, 10)
71
+ q_types = col2.multiselect("ประเภทคำถาม", ["CLOZE", "T/F", "MCQ"], default=["CLOZE", "T/F", "MCQ"])
72
+ seed_value = col2.number_input("Seed (กำหนดให้ผลเหมือนเดิม)", min_value=0, value=42, step=1)
 
 
 
 
 
 
73
 
74
  # ---------- Action ----------
75
+ generate_btn = st.button("🚀 สร้าง Quiz", use_container_width=True, disabled=not uploaded)
76
+
77
+ # ---------- Results Area (ใต้ปุ่ม) ----------
78
+ if generate_btn:
79
+ if not uploaded:
80
+ st.warning("กรุณาอัปโหลดไฟล์ก่อน")
81
+ elif not text:
82
+ st.error("ไม่พบข้อความสำหรับสร้างแบบทดสอบ")
83
+ else:
84
+ with st.spinner("กำลังสร้างคำถาม..."):
85
+ quiz = generate_quiz(text, n_questions, mix=tuple(q_types), seed=seed_value)
86
+ rows = to_csv_rows(quiz)
87
+ df = pd.DataFrame(rows)
88
+
89
+ # KPIs
90
+ counts = df["Type"].value_counts().to_dict() if not df.empty else {}
91
+ k_cloze = counts.get("CLOZE", 0)
92
+ k_tf = counts.get("T/F", 0)
93
+ k_mcq = counts.get("MCQ", 0)
94
+
95
+ st.markdown('<div class="kpi">', unsafe_allow_html=True)
96
+ st.markdown(f'<div class="card"><div class="title">รวมข้อ</div><div class="value">{len(df)}</div></div>', unsafe_allow_html=True)
97
+ st.markdown(f'<div class="card"><div class="title">CLOZE</div><div class="value">{k_cloze}</div></div>', unsafe_allow_html=True)
98
+ 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)
99
+ st.markdown('</div>', unsafe_allow_html=True)
100
+
101
+ # Tabs: ตาราง / CSV / JSON
102
+ tab_table, tab_csv, tab_json = st.tabs(["📋 ตารางคำถาม", "🧾 พรีวิว CSV", "🧩 JSON"])
103
+
104
+ with tab_table:
105
+ st.dataframe(df, use_container_width=True)
106
+
107
+ with tab_csv:
108
+ csv_buf = io.StringIO()
109
+ # ใช้ ; เพื่อให้ Excel (locale ไทย) แยกคอลัมน์อัตโนมัติ + UTF-8 BOM
110
+ df.to_csv(csv_buf, index=False, sep=';', quoting=csv.QUOTE_ALL)
111
+ csv_bytes = csv_buf.getvalue().encode("utf-8-sig")
112
+ st.code(csv_buf.getvalue()[:1000] + ("\n... (ตัดท่อนี้ในการแสดงตัวอย่าง)" if len(csv_buf.getvalue()) > 1000 else ""), language="csv")
113
+ st.download_button("⬇️ ดาวน์โหลด CSV", csv_bytes, file_name="quiz_generated.csv", mime="text/csv", use_container_width=True)
114
+
115
+ with tab_json:
116
+ json_str = json.dumps(rows, ensure_ascii=False, indent=2)
117
+ st.code(json_str[:2000] + ("\n... (ตัดท่อนี้ในการแสดงตัวอย่าง)" if len(json_str) > 2000 else ""), language="json")
118
+ st.download_button(
119
+ "⬇️ ดาวน์โหลด JSON",
120
+ json_str.encode("utf-8"),
121
+ file_name="quiz_generated.json",
122
+ mime="application/json",
123
+ use_container_width=True
124
+ )
src/utils/__pycache__/loader.cpython-313.pyc ADDED
Binary file (7.43 kB). View file
 
src/utils/__pycache__/qg_baseline.cpython-313.pyc ADDED
Binary file (16.6 kB). View file
 
src/utils/extractors.py DELETED
@@ -1,12 +0,0 @@
1
- from pypdf import PdfReader
2
-
3
- def extract_text_from_pdf(file_path):
4
- reader = PdfReader(file_path)
5
- all_text = ""
6
-
7
- for i, page in enumerate(reader.pages):
8
- text = page.extract_text()
9
- if text: # ถ้ามีข้อความในหน้านั้น
10
- all_text += f"\n\n--- Page {i+1} ---\n{text}"
11
-
12
- return all_text.strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
src/utils/loader.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # src/utils/loader.py
2
+ from pypdf import PdfReader
3
+ from docx import Document
4
+ import pandas as pd
5
+ import io
6
+ import re
7
+ import os
8
+
9
+ # ---------------------------------------------
10
+ # 🧩 1. อ่านไฟล์ PDF
11
+ # ---------------------------------------------
12
+ def extract_text_from_pdf(file_path: str) -> str:
13
+ """
14
+ ใช้เมื่อมี path ของไฟล์ PDF จริง (เช่นตอนรันบนเครื่อง)
15
+ """
16
+ reader = PdfReader(file_path)
17
+ all_text = ""
18
+ for i, page in enumerate(reader.pages):
19
+ text = page.extract_text()
20
+ if text:
21
+ all_text += f"\n\n--- Page {i+1} ---\n{text}"
22
+ return all_text.strip()
23
+
24
+
25
+ def extract_text_from_pdf_bytes(file_bytes: bytes) -> str:
26
+ """
27
+ ใช้เมื่อไฟล์มาจาก Streamlit uploader (เป็น bytes)
28
+ """
29
+ reader = PdfReader(io.BytesIO(file_bytes))
30
+ texts = []
31
+ for i, page in enumerate(reader.pages):
32
+ text = page.extract_text()
33
+ if text:
34
+ texts.append(f"--- Page {i+1} ---\n{text}")
35
+ return "\n\n".join(texts).strip()
36
+
37
+ # ---------------------------------------------
38
+ # 🧩 2. อ่านไฟล์ DOCX
39
+ # ---------------------------------------------
40
+ def extract_text_from_docx_bytes(file_bytes: bytes) -> str:
41
+ doc = Document(io.BytesIO(file_bytes))
42
+ paras = [p.text for p in doc.paragraphs if p.text.strip()]
43
+ return "\n".join(paras).strip()
44
+
45
+
46
+ def extract_text_from_docx_path(file_path: str) -> str:
47
+ doc = Document(file_path)
48
+ paras = [p.text for p in doc.paragraphs if p.text.strip()]
49
+ return "\n".join(paras).strip()
50
+
51
+ # ---------------------------------------------
52
+ # 🧩 3. อ่านไฟล์ TXT / CSV
53
+ # ---------------------------------------------
54
+ def extract_text_from_txt_bytes(file_bytes: bytes, encoding="utf-8") -> str:
55
+ try:
56
+ return file_bytes.decode(encoding, errors="ignore")
57
+ except Exception:
58
+ return file_bytes.decode("utf-8", errors="ignore")
59
+
60
+
61
+ def extract_text_from_txt_path(file_path: str, encoding="utf-8") -> str:
62
+ with open(file_path, "r", encoding=encoding, errors="ignore") as f:
63
+ return f.read()
64
+
65
+
66
+ def extract_text_from_csv_bytes(file_bytes: bytes) -> str:
67
+ df = pd.read_csv(io.BytesIO(file_bytes))
68
+ # รวมทุกคอลัมน์ทุกแถวให้เป็นข้อความเดียว (เพื่อสร้าง quiz ภายหลัง)
69
+ lines = []
70
+ for _, row in df.astype(str).iterrows():
71
+ lines.append(" | ".join(row.values))
72
+ return "\n".join(lines)
73
+
74
+
75
+ def extract_text_from_csv_path(file_path: str) -> str:
76
+ df = pd.read_csv(file_path)
77
+ lines = []
78
+ for _, row in df.astype(str).iterrows():
79
+ lines.append(" | ".join(row.values))
80
+ return "\n".join(lines)
81
+
82
+ # ---------------------------------------------
83
+ # 🧩 4. Clean ข้อความ (ตัดช่องว่าง / จัดรูปแบบ)
84
+ # ---------------------------------------------
85
+ def clean_text(text: str) -> str:
86
+ text = re.sub(r'\s+\n', '\n', text) # เว้นวรรคก่อนขึ้นบรรทัด
87
+ text = re.sub(r'\n{3,}', '\n\n', text) # ตัดบรรทัดว่างเกิน 2 บรรทัด
88
+ text = re.sub(r'[ \t]{2,}', ' ', text) # ตัดช่องว่างยาว
89
+ return text.strip()
90
+
91
+ # ---------------------------------------------
92
+ # 🧩 5. ฟังก์ชันรวมหลัก (Auto-detect)
93
+ # ---------------------------------------------
94
+ def load_to_text(uploaded_file) -> str:
95
+ """
96
+ ใช้ใน Streamlit: รับ uploaded_file แล้วคืนข้อความทั้งหมดเป็น string เดียว
97
+ """
98
+ file_bytes = uploaded_file.read()
99
+ name = uploaded_file.name.lower()
100
+ mime = uploaded_file.type or ""
101
+
102
+ if name.endswith(".pdf"):
103
+ text = extract_text_from_pdf_bytes(file_bytes)
104
+ elif name.endswith(".docx"):
105
+ text = extract_text_from_docx_bytes(file_bytes)
106
+ elif name.endswith(".csv"):
107
+ text = extract_text_from_csv_bytes(file_bytes)
108
+ elif name.endswith(".txt") or mime.startswith("text/"):
109
+ text = extract_text_from_txt_bytes(file_bytes)
110
+ else:
111
+ # fallback พยายามอ่านเป็นข้อความ
112
+ try:
113
+ text = extract_text_from_txt_bytes(file_bytes)
114
+ except Exception:
115
+ text = ""
116
+ return clean_text(text)
117
+
118
+
119
+ def load_from_path(file_path: str) -> str:
120
+ """
121
+ ใช้นอก Streamlit (อ่านจาก path ปกติ)
122
+ """
123
+ file_path = str(file_path)
124
+ if not os.path.exists(file_path):
125
+ raise FileNotFoundError(file_path)
126
+
127
+ if file_path.lower().endswith(".pdf"):
128
+ text = extract_text_from_pdf(file_path)
129
+ elif file_path.lower().endswith(".docx"):
130
+ text = extract_text_from_docx_path(file_path)
131
+ elif file_path.lower().endswith(".csv"):
132
+ text = extract_text_from_csv_path(file_path)
133
+ elif file_path.lower().endswith(".txt"):
134
+ text = extract_text_from_txt_path(file_path)
135
+ else:
136
+ text = ""
137
+ return clean_text(text)
src/utils/qg_baseline.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # src/utils/qg_baseline.py
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Question Generation (Baseline) — Thai/EN friendly, seed-able, and with simple QC.
5
+
6
+ Features:
7
+ - split_blocks() : แยกเนื้อหาเป็นบล็อกคล้ายสไลด์ (รองรับ --- Page, หัวข้อ, บรรทัดว่าง)
8
+ - to_sentences() : แยกประโยคแบบ heuristic (ไทย/อังกฤษ), รวม bullet
9
+ - pick_keywords(): เลือกคีย์เวิร์ดสำคัญ (กรอง stopwords ไทย/อังกฤษแบบหยาบ)
10
+ - make_cloze(): เติมคำ (CLOZE) พร้อมตัวลวง 3 ตัว (รวมเป็น 4 ตัวเลือกเสมอ)
11
+ - make_true_false(): กลับค่าตัวเลข/ปี (ถ้ามี) ไม่งั้นใช้ True
12
+ - make_mcq_from_bullets(): “ข้อใดไม่ใช่หัวข้อย่อยในสไลด์นี้?”
13
+ - generate_quiz(): ประกอบทั้งหมด + QC (กรองซ้ำ, จำกัดความยาว, ครอบจำนวนข้อ)
14
+ - to_csv_rows(): ส่งออกในรูปแถวสำหรับ CSV
15
+
16
+ ใช้ random.Random(seed) ภายใน (ไม่ยุ่งกับ global random)
17
+ """
18
+
19
+ from __future__ import annotations
20
+ import re
21
+ import random
22
+ from typing import List, Dict, Optional
23
+ from collections import Counter
24
+
25
+
26
+ # -----------------------------
27
+ # Utilities
28
+ # -----------------------------
29
+ def _rng(seed: Optional[int] = None) -> random.Random:
30
+ """คืนอ็อบเจ็กต์สุ่มเฉพาะตัว (isolated RNG)"""
31
+ return random.Random(seed) if seed is not None else random
32
+
33
+ _TH_STOP = set("""
34
+ การ ของ และ ที่ ใน เป็น ได้ ให้ หรือ จาก ด้วย มี ไป มา ซึ่ง เช่น ค่า ตัว ข้อ ความ จะ ถูก คือ
35
+ ว่า ให้ โดย เมื่อ หาก เพราะ แต่ ยัง จึง กับ อย่าง เช่นนี้ เช่นนั้น อีก ทั้ง นี้ นั้น นี่ เลย ก็ ก็ยัง ยังไง
36
+ ถึง เพราะว่า ดังนั้น แล้ว โดยที่ โดยเฉพาะ โดยรวม ประมาณ อาจ จะ ได้ ไม่ ใช่ ก็ได้ กัน บ้าง จน กระทั่ง ต่อ
37
+ ระหว่าง สำหรับ ตาม ด้วยกัน เท่านั้น เท่านี้ นอกจากนี้ ทั้งหมด บน ใต้ หน้า หลัง ก่อน หลังจาก ต่อไป
38
+ """.split())
39
+
40
+ _EN_STOP = set("""
41
+ the of and to in is are was were be been being a an for with on at by from this that these those as it its
42
+ or if then than not no yes do does did have has had can could should would may might you your we our they them
43
+ itself themselves ourselves themselves he she his her theirs their i me my mine
44
+ """.split())
45
+
46
+ def _normalize_whitespace(s: str) -> str:
47
+ s = re.sub(r'[ \t]+', ' ', s)
48
+ s = re.sub(r'\s*\n\s*', '\n', s)
49
+ return s.strip()
50
+
51
+ def _len_ok(s: str, min_len=12, max_len=280) -> bool:
52
+ L = len(s or "")
53
+ return min_len <= L <= max_len
54
+
55
+ def _uniq_keep_order(items: List[str]) -> List[str]:
56
+ seen = set()
57
+ out = []
58
+ for x in items:
59
+ if x not in seen:
60
+ out.append(x)
61
+ seen.add(x)
62
+ return out
63
+
64
+
65
+ # -----------------------------
66
+ # Block & sentence splitting
67
+ # -----------------------------
68
+ def split_blocks(text: str) -> List[str]:
69
+ """
70
+ แบ่งเป็นบล็อกโดยดูจาก:
71
+ - ตัวแบ่งหน้าแบบ --- Page X ---
72
+ - หัวข้อ/บรรทัดว่างติดกัน
73
+ """
74
+ if not text:
75
+ return []
76
+ # ตัดด้วย "--- Page n ---" ก่อน
77
+ parts = re.split(r'(?im)^---\s*Page\s*\d+\s*---\s*$', text)
78
+ # ถ้าไม่มี page marker ใช้บรรทัดว่างคู่/สาม
79
+ if len(parts) == 1:
80
+ parts = re.split(r'\n{2,}', text)
81
+
82
+ blocks = []
83
+ for p in parts:
84
+ p = _normalize_whitespace(p)
85
+ if p and len(p) > 40:
86
+ blocks.append(p)
87
+ return blocks or [text.strip()]
88
+
89
+
90
+ def to_sentences(block: str) -> List[str]:
91
+ """
92
+ แยกประโยคไทย/อังกฤษแบบง่าย:
93
+ - ตัดตาม . ! ? หรือขึ้นบรรทัดใหม่
94
+ - รวม bullet • -
95
+ - กรองสั้น/ยาวเกินไป
96
+ """
97
+ lines = [ln.strip() for ln in block.splitlines() if ln.strip()]
98
+ # รวม bullet ให้เป็นประโยคเดียว (ช่วย MCQ ภายหลัง)
99
+ bullets = [re.sub(r'^[•\-\*\u2022]\s*', '', ln).strip() for ln in lines if re.match(r'^[•\-\*\u2022]\s*', ln)]
100
+ # แยกประโยคทั่วไป
101
+ raw = re.split(r'(?<=[.!?])\s+|\n+', block)
102
+ sents = [s.strip('•-* \t') for s in raw if _len_ok(s.strip())]
103
+
104
+ # ถ้าไม่มีประโยคเลย เอา bullet มาช่วย
105
+ if not sents and bullets:
106
+ sents = [b for b in bullets if _len_ok(b)]
107
+
108
+ return _uniq_keep_order(sents)
109
+
110
+
111
+ # -----------------------------
112
+ # Keyword extraction (simple)
113
+ # -----------------------------
114
+ def pick_keywords(text: str, topk=30) -> List[str]:
115
+ tokens = re.findall(r'[A-Za-zก-๙0-9\-_/]+', text or "")
116
+ cnt = Counter(w.lower() for w in tokens if len(w) > 2)
117
+ cand = []
118
+ for w, _ in cnt.most_common():
119
+ if w in _TH_STOP or w in _EN_STOP:
120
+ continue
121
+ # กรองที่เป็นตัวเลขยาวเกิน (โทรศัพท์/โค้ดยืด)
122
+ if re.fullmatch(r'\d{1,6}', w) or re.search(r'[A-Za-zก-๙]', w):
123
+ cand.append(w)
124
+ return cand[:topk]
125
+
126
+
127
+ # -----------------------------
128
+ # Question builders
129
+ # -----------------------------
130
+ def _pad_options(opts: List[str], n=4, pad='—') -> List[str]:
131
+ opts = [o if o is not None else '' for o in opts]
132
+ while len(opts) < n:
133
+ opts.append(pad)
134
+ return opts[:n]
135
+
136
+ def _dedup_options(opts: List[str]) -> List[str]:
137
+ # ลบซ้ำแบบไม่แคร์เคส
138
+ seen = set()
139
+ out = []
140
+ for o in opts:
141
+ key = o.strip().lower()
142
+ if key not in seen and key != '':
143
+ out.append(o)
144
+ seen.add(key)
145
+ return out
146
+
147
+ def make_cloze(sentence: str, keywords: List[str], rng: random.Random) -> Dict:
148
+ # เลือกคำที่อยู่ในประโยคจริง ๆ
149
+ present = [k for k in keywords if re.search(rf'(?i)\b{re.escape(k)}\b', sentence)]
150
+ if not present:
151
+ return {}
152
+ answer = rng.choice(present)
153
+ # ปิดคำแบบ case-insensitive
154
+ q = re.sub(rf'(?i)\b{re.escape(answer)}\b', '____', sentence)
155
+ # ตัวลวง: คำอื่นที่มี type ใกล้เคียง (เลขกับเลข / คำกับคำ)
156
+ is_num = bool(re.fullmatch(r'\d+', answer))
157
+ pool = [k for k in keywords if k.lower() != answer.lower() and (bool(re.fullmatch(r'\d+', k)) == is_num)]
158
+ rng.shuffle(pool)
159
+ distractors = _dedup_options(pool)[:3]
160
+ options = [answer] + distractors
161
+ rng.shuffle(options)
162
+ options = _pad_options(options)
163
+ return {
164
+ "type": "CLOZE",
165
+ "question": q,
166
+ "options": options,
167
+ "answer": answer,
168
+ "explanation": ""
169
+ }
170
+
171
+ def make_true_false(sentence: str, rng: random.Random) -> Dict:
172
+ # ถ้ามีตัวเลข ให้กลับค่า (เช่น ปี/จำนวน)
173
+ nums = re.findall(r'\b\d+\b', sentence)
174
+ if nums:
175
+ n = rng.choice(nums)
176
+ # เลือก offset เล็กน้อยเพื่อไม่ให้หลุดกรอบ
177
+ offset = rng.choice([1, 2, 3, 5, 10])
178
+ fake = str(int(n) + offset)
179
+ q = re.sub(rf'\b{re.escape(n)}\b', fake, sentence, count=1)
180
+ return {"type": "T/F", "question": q, "options": ["True", "False"], "answer": "False",
181
+ "explanation": f"ค่าจริงควรเป็น {n}"}
182
+ # ไม่มีตัวเลข → ใช้เป็น True
183
+ return {"type": "T/F", "question": sentence, "options": ["True", "False"], "answer": "True", "explanation": ""}
184
+
185
+ def make_mcq_from_bullets(block: str, keywords: List[str], rng: random.Random) -> List[Dict]:
186
+ # รวบรวม bullet ในบล็อกนี้
187
+ bullets = [re.sub(r'^[•\-\*\u2022]\s*', '', ln).strip()
188
+ for ln in block.splitlines()
189
+ if re.match(r'^[•\-\*\u2022]\s*', ln)]
190
+ out: List[Dict] = []
191
+ if len(bullets) >= 4:
192
+ # “ข้อใดไม่ใช่หัวข้อย่อยในสไลด์นี้?”
193
+ # ตัวลวงมาจาก keywords ที่ไม่ใช่ bullet
194
+ pool = [w for w in pick_keywords(" ".join(keywords), topk=80) if w not in bullets]
195
+ rng.shuffle(pool)
196
+ wrong = pool[:1] or ["(ไม่มี)"]
197
+ # เลือกถูก 3 ข้อจาก bullets
198
+ right = bullets[:3]
199
+ options = right + wrong
200
+ rng.shuffle(options)
201
+ ans = next((o for o in options if o not in bullets), options[0])
202
+ options = _pad_options(options)
203
+ out.append({
204
+ "type": "MCQ",
205
+ "question": "ต่อไปนี้ข้อใด 'ไม่ใช่' หัวข้อย่อยในสไลด์นี้?",
206
+ "options": options,
207
+ "answer": ans,
208
+ "explanation": ""
209
+ })
210
+ return out
211
+
212
+
213
+ # -----------------------------
214
+ # Main generator + QC
215
+ # -----------------------------
216
+ def _question_fingerprint(q: Dict) -> str:
217
+ base = f"{q.get('type','')}|{q.get('question','')}".strip().lower()
218
+ base = re.sub(r'\s+', ' ', base)
219
+ return base
220
+
221
+ def _valid_question(q: Dict) -> bool:
222
+ if not q: return False
223
+ if not _len_ok(q.get("question","")): return False
224
+ opts = q.get("options", [])
225
+ if q["type"] == "T/F":
226
+ return True
227
+ # อย่างน้อย 2 ตัวเลือกไม่ซ้ำ/ไม่ว่าง
228
+ clean = _dedup_options(opts)
229
+ return len(clean) >= 2 and q.get("answer","") != ""
230
+
231
+ def generate_quiz(
232
+ text: str,
233
+ n_questions: int = 10,
234
+ mix: tuple[str, ...] = ("CLOZE", "T/F", "MCQ"),
235
+ seed: Optional[int] = None
236
+ ) -> List[Dict]:
237
+ """
238
+ สร้างชุดคำถามจากข้อความ
239
+ - seed: ตั้งค่าเพื่อให้ผลเดิมซ้ำได้
240
+ """
241
+ rng = _rng(seed)
242
+ blocks = split_blocks(text) or [text]
243
+ global_keywords = pick_keywords(text, topk=80)
244
+
245
+ questions: List[Dict] = []
246
+ seen_fp = set()
247
+
248
+ for b in blocks:
249
+ if len(questions) >= n_questions:
250
+ break
251
+
252
+ sents = to_sentences(b)
253
+ local_kw = _uniq_keep_order(pick_keywords(b, topk=30) + global_keywords)[:80]
254
+
255
+ # MCQ จาก bullets
256
+ if "MCQ" in mix:
257
+ for q in make_mcq_from_bullets(b, local_kw, rng):
258
+ fp = _question_fingerprint(q)
259
+ if fp not in seen_fp and _valid_question(q):
260
+ questions.append(q)
261
+ seen_fp.add(fp)
262
+ if len(questions) >= n_questions: break
263
+
264
+ # สร้าง Cloze + T/F จากประโยค (สุ่มเลือกบางประโยค)
265
+ rng.shuffle(sents)
266
+ for s in sents:
267
+ if len(questions) >= n_questions: break
268
+
269
+ if "CLOZE" in mix and rng.random() < 0.7:
270
+ q = make_cloze(s, local_kw, rng)
271
+ if q and _valid_question(q):
272
+ fp = _question_fingerprint(q)
273
+ if fp not in seen_fp:
274
+ questions.append(q); seen_fp.add(fp)
275
+ if len(questions) >= n_questions: break
276
+
277
+ if "T/F" in mix and len(questions) < n_questions:
278
+ q = make_true_false(s, rng)
279
+ if _valid_question(q):
280
+ fp = _question_fingerprint(q)
281
+ if fp not in seen_fp:
282
+ questions.append(q); seen_fp.add(fp)
283
+
284
+ # ตัดให้พอดีจำนวน
285
+ return questions[:n_questions]
286
+
287
+
288
+ # -----------------------------
289
+ # Export helpers
290
+ # -----------------------------
291
+ def to_csv_rows(quiz: List[Dict]) -> List[Dict]:
292
+ rows = []
293
+ for i, q in enumerate(quiz, 1):
294
+ opts = q.get("options", [])
295
+ opts = _pad_options(opts)
296
+ rows.append({
297
+ "No": i,
298
+ "Type": q.get("type",""),
299
+ "Question": q.get("question",""),
300
+ "OptionA": opts[0],
301
+ "OptionB": opts[1],
302
+ "OptionC": opts[2],
303
+ "OptionD": opts[3],
304
+ "Answer": q.get("answer",""),
305
+ "Explanation": q.get("explanation",""),
306
+ })
307
+ return rows