QuizGen / src /utils /qg_baseline.py
pluem9
demo1
f87ae4b
Raw History Blame Contribute Delete
13.3 kB
# src/utils/qg_baseline.py
# -*- coding: utf-8 -*-
"""
Question Generation (Baseline) — Thai/EN friendly, seed-able, and with simple QC.
Features:
- split_blocks() : แยกเนื้อหาเป็นบล็อกคล้ายสไลด์ (รองรับ --- Page, หัวข้อ, บรรทัดว่าง)
- to_sentences() : แยกประโยคแบบ heuristic (ไทย/อังกฤษ), รวม bullet
- pick_keywords(): เลือกคีย์เวิร์ดสำคัญ (กรอง stopwords ไทย/อังกฤษแบบหยาบ)
- make_cloze(): เติมคำ (CLOZE) พร้อมตัวลวง 3 ตัว (รวมเป็น 4 ตัวเลือกเสมอ)
- make_true_false(): กลับค่าตัวเลข/ปี (ถ้ามี) ไม่งั้นใช้ True
- make_mcq_from_bullets(): “ข้อใดไม่ใช่หัวข้อย่อยในสไลด์นี้?”
- generate_quiz(): ประกอบทั้งหมด + QC (กรองซ้ำ, จำกัดความยาว, ครอบจำนวนข้อ)
- to_csv_rows(): ส่งออกในรูปแถวสำหรับ CSV
ใช้ random.Random(seed) ภายใน (ไม่ยุ่งกับ global random)
"""
from __future__ import annotations
import re
import random
from typing import List, Dict, Optional
from collections import Counter
# -----------------------------
# Utilities
# -----------------------------
def _rng(seed: Optional[int] = None) -> random.Random:
"""คืนอ็อบเจ็กต์สุ่มเฉพาะตัว (isolated RNG)"""
return random.Random(seed) if seed is not None else random
_TH_STOP = set("""
การ ของ และ ที่ ใน เป็น ได้ ให้ หรือ จาก ด้วย มี ไป มา ซึ่ง เช่น ค่า ตัว ข้อ ความ จะ ถูก คือ
ว่า ให้ โดย เมื่อ หาก เพราะ แต่ ยัง จึง กับ อย่าง เช่นนี้ เช่นนั้น อีก ทั้ง นี้ นั้น นี่ เลย ก็ ก็ยัง ยังไง
ถึง เพราะว่า ดังนั้น แล้ว โดยที่ โดยเฉพาะ โดยรวม ประมาณ อาจ จะ ได้ ไม่ ใช่ ก็ได้ กัน บ้าง จน กระทั่ง ต่อ
ระหว่าง สำหรับ ตาม ด้วยกัน เท่านั้น เท่านี้ นอกจากนี้ ทั้งหมด บน ใต้ หน้า หลัง ก่อน หลังจาก ต่อไป
""".split())
_EN_STOP = set("""
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
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
itself themselves ourselves themselves he she his her theirs their i me my mine
""".split())
def _normalize_whitespace(s: str) -> str:
s = re.sub(r'[ \t]+', ' ', s)
s = re.sub(r'\s*\n\s*', '\n', s)
return s.strip()
def _len_ok(s: str, min_len=12, max_len=280) -> bool:
L = len(s or "")
return min_len <= L <= max_len
def _uniq_keep_order(items: List[str]) -> List[str]:
seen = set()
out = []
for x in items:
if x not in seen:
out.append(x)
seen.add(x)
return out
# -----------------------------
# Block & sentence splitting
# -----------------------------
def split_blocks(text: str) -> List[str]:
"""
แบ่งเป็นบล็อกโดยดูจาก:
- ตัวแบ่งหน้าแบบ --- Page X ---
- หัวข้อ/บรรทัดว่างติดกัน
"""
if not text:
return []
# ตัดด้วย "--- Page n ---" ก่อน
parts = re.split(r'(?im)^---\s*Page\s*\d+\s*---\s*$', text)
# ถ้าไม่มี page marker ใช้บรรทัดว่างคู่/สาม
if len(parts) == 1:
parts = re.split(r'\n{2,}', text)
blocks = []
for p in parts:
p = _normalize_whitespace(p)
if p and len(p) > 40:
blocks.append(p)
return blocks or [text.strip()]
def to_sentences(block: str) -> List[str]:
"""
แยกประโยคไทย/อังกฤษแบบง่าย:
- ตัดตาม . ! ? หรือขึ้นบรรทัดใหม่
- รวม bullet • -
- กรองสั้น/ยาวเกินไป
"""
lines = [ln.strip() for ln in block.splitlines() if ln.strip()]
# รวม bullet ให้เป็นประโยคเดียว (ช่วย MCQ ภายหลัง)
bullets = [re.sub(r'^[•\-\*\u2022]\s*', '', ln).strip() for ln in lines if re.match(r'^[•\-\*\u2022]\s*', ln)]
# แยกประโยคทั่วไป
raw = re.split(r'(?<=[.!?])\s+|\n+', block)
sents = [s.strip('•-* \t') for s in raw if _len_ok(s.strip())]
# ถ้าไม่มีประโยคเลย เอา bullet มาช่วย
if not sents and bullets:
sents = [b for b in bullets if _len_ok(b)]
return _uniq_keep_order(sents)
# -----------------------------
# Keyword extraction (simple)
# -----------------------------
def pick_keywords(text: str, topk=30) -> List[str]:
tokens = re.findall(r'[A-Za-zก-๙0-9\-_/]+', text or "")
cnt = Counter(w.lower() for w in tokens if len(w) > 2)
cand = []
for w, _ in cnt.most_common():
if w in _TH_STOP or w in _EN_STOP:
continue
# กรองที่เป็นตัวเลขยาวเกิน (โทรศัพท์/โค้ดยืด)
if re.fullmatch(r'\d{1,6}', w) or re.search(r'[A-Za-zก-๙]', w):
cand.append(w)
return cand[:topk]
# -----------------------------
# Question builders
# -----------------------------
def _pad_options(opts: List[str], n=4, pad='—') -> List[str]:
opts = [o if o is not None else '' for o in opts]
while len(opts) < n:
opts.append(pad)
return opts[:n]
def _dedup_options(opts: List[str]) -> List[str]:
# ลบซ้ำแบบไม่แคร์เคส
seen = set()
out = []
for o in opts:
key = o.strip().lower()
if key not in seen and key != '':
out.append(o)
seen.add(key)
return out
def make_cloze(sentence: str, keywords: List[str], rng: random.Random) -> Dict:
# เลือกคำที่อยู่ในประโยคจริง ๆ
present = [k for k in keywords if re.search(rf'(?i)\b{re.escape(k)}\b', sentence)]
if not present:
return {}
answer = rng.choice(present)
# ปิดคำแบบ case-insensitive
q = re.sub(rf'(?i)\b{re.escape(answer)}\b', '____', sentence)
# ตัวลวง: คำอื่นที่มี type ใกล้เคียง (เลขกับเลข / คำกับคำ)
is_num = bool(re.fullmatch(r'\d+', answer))
pool = [k for k in keywords if k.lower() != answer.lower() and (bool(re.fullmatch(r'\d+', k)) == is_num)]
rng.shuffle(pool)
distractors = _dedup_options(pool)[:3]
options = [answer] + distractors
rng.shuffle(options)
options = _pad_options(options)
return {
"type": "CLOZE",
"question": q,
"options": options,
"answer": answer,
"explanation": ""
}
def make_true_false(sentence: str, rng: random.Random) -> Dict:
# ถ้ามีตัวเลข ให้กลับค่า (เช่น ปี/จำนวน)
nums = re.findall(r'\b\d+\b', sentence)
if nums:
n = rng.choice(nums)
# เลือก offset เล็กน้อยเพื่อไม่ให้หลุดกรอบ
offset = rng.choice([1, 2, 3, 5, 10])
fake = str(int(n) + offset)
q = re.sub(rf'\b{re.escape(n)}\b', fake, sentence, count=1)
return {"type": "T/F", "question": q, "options": ["True", "False"], "answer": "False",
"explanation": f"ค่าจริงควรเป็น {n}"}
# ไม่มีตัวเลข → ใช้เป็น True
return {"type": "T/F", "question": sentence, "options": ["True", "False"], "answer": "True", "explanation": ""}
def make_mcq_from_bullets(block: str, keywords: List[str], rng: random.Random) -> List[Dict]:
# รวบรวม bullet ในบล็อกนี้
bullets = [re.sub(r'^[•\-\*\u2022]\s*', '', ln).strip()
for ln in block.splitlines()
if re.match(r'^[•\-\*\u2022]\s*', ln)]
out: List[Dict] = []
if len(bullets) >= 4:
# “ข้อใดไม่ใช่หัวข้อย่อยในสไลด์นี้?”
# ตัวลวงมาจาก keywords ที่ไม่ใช่ bullet
pool = [w for w in pick_keywords(" ".join(keywords), topk=80) if w not in bullets]
rng.shuffle(pool)
wrong = pool[:1] or ["(ไม่มี)"]
# เลือกถูก 3 ข้อจาก bullets
right = bullets[:3]
options = right + wrong
rng.shuffle(options)
ans = next((o for o in options if o not in bullets), options[0])
options = _pad_options(options)
out.append({
"type": "MCQ",
"question": "ต่อไปนี้ข้อใด 'ไม่ใช่' หัวข้อย่อยในสไลด์นี้?",
"options": options,
"answer": ans,
"explanation": ""
})
return out
# -----------------------------
# Main generator + QC
# -----------------------------
def _question_fingerprint(q: Dict) -> str:
base = f"{q.get('type','')}|{q.get('question','')}".strip().lower()
base = re.sub(r'\s+', ' ', base)
return base
def _valid_question(q: Dict) -> bool:
if not q: return False
if not _len_ok(q.get("question","")): return False
opts = q.get("options", [])
if q["type"] == "T/F":
return True
# อย่างน้อย 2 ตัวเลือกไม่ซ้ำ/ไม่ว่าง
clean = _dedup_options(opts)
return len(clean) >= 2 and q.get("answer","") != ""
def generate_quiz(
text: str,
n_questions: int = 10,
mix: tuple[str, ...] = ("CLOZE", "T/F", "MCQ"),
seed: Optional[int] = None
) -> List[Dict]:
"""
สร้างชุดคำถามจากข้อความ
- seed: ตั้งค่าเพื่อให้ผลเดิมซ้ำได้
"""
rng = _rng(seed)
blocks = split_blocks(text) or [text]
global_keywords = pick_keywords(text, topk=80)
questions: List[Dict] = []
seen_fp = set()
for b in blocks:
if len(questions) >= n_questions:
break
sents = to_sentences(b)
local_kw = _uniq_keep_order(pick_keywords(b, topk=30) + global_keywords)[:80]
# MCQ จาก bullets
if "MCQ" in mix:
for q in make_mcq_from_bullets(b, local_kw, rng):
fp = _question_fingerprint(q)
if fp not in seen_fp and _valid_question(q):
questions.append(q)
seen_fp.add(fp)
if len(questions) >= n_questions: break
# สร้าง Cloze + T/F จากประโยค (สุ่มเลือกบางประโยค)
rng.shuffle(sents)
for s in sents:
if len(questions) >= n_questions: break
if "CLOZE" in mix and rng.random() < 0.7:
q = make_cloze(s, local_kw, rng)
if q and _valid_question(q):
fp = _question_fingerprint(q)
if fp not in seen_fp:
questions.append(q); seen_fp.add(fp)
if len(questions) >= n_questions: break
if "T/F" in mix and len(questions) < n_questions:
q = make_true_false(s, rng)
if _valid_question(q):
fp = _question_fingerprint(q)
if fp not in seen_fp:
questions.append(q); seen_fp.add(fp)
# ตัดให้พอดีจำนวน
return questions[:n_questions]
# -----------------------------
# Export helpers
# -----------------------------
def to_csv_rows(quiz: List[Dict]) -> List[Dict]:
rows = []
for i, q in enumerate(quiz, 1):
opts = q.get("options", [])
opts = _pad_options(opts)
rows.append({
"No": i,
"Type": q.get("type",""),
"Question": q.get("question",""),
"OptionA": opts[0],
"OptionB": opts[1],
"OptionC": opts[2],
"OptionD": opts[3],
"Answer": q.get("answer",""),
"Explanation": q.get("explanation",""),
})
return rows