Spaces:
Paused

MathematicsApps / question_intake.py
jobinv's picture
Upload 23 files
f8aaa7d verified
Raw History Blame Contribute Delete
15.3 kB
"""Multi-format question ingestion and a reusable local question bank."""
from __future__ import annotations
from datetime import datetime, timezone
from hashlib import sha256
from io import BytesIO
import json
import os
from pathlib import Path
import re
import subprocess
from threading import Lock
from typing import Any
from PIL import Image
from evaluator import run_ocr
from question_visualizer import infer_visual_payload
APP_DIR = Path(__file__).resolve().parent
BANK_PATH = Path(os.getenv("M1_QUESTION_BANK_PATH", APP_DIR / "data" / "user_question_bank.json"))
BASELINE_REFERENCE_COUNT = 149
MAX_TEXT_CHARS = 400_000
MAX_QUESTION_CHARS = 30_000
_BANK_LOCK = Lock()
_WHISPER_MODEL: Any = None
SUPPORTED_EXTENSIONS = {
".txt", ".md", ".json", ".pdf", ".docx", ".doc",
".png", ".jpg", ".jpeg", ".webp", ".bmp", ".tif", ".tiff",
".wav", ".mp3", ".m4a", ".mp4", ".ogg", ".flac", ".webm",
}
IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".webp", ".bmp", ".tif", ".tiff"}
AUDIO_EXTENSIONS = {".wav", ".mp3", ".m4a", ".mp4", ".ogg", ".flac", ".webm"}
def _file_path(value: Any) -> Path | None:
if value is None:
return None
if isinstance(value, (str, Path)):
path = Path(value)
else:
path = Path(getattr(value, "name", ""))
return path if path.is_file() else None
def _clean_text(text: str) -> str:
text = str(text or "").replace("\x00", "").replace("\r\n", "\n").replace("\r", "\n")
text = re.sub(r"[ \t]+", " ", text)
text = re.sub(r"\n{4,}", "\n\n\n", text)
return text.strip()[:MAX_TEXT_CHARS]
def _extract_pdf(path: Path) -> tuple[str, str]:
pages: list[str] = []
try:
from pypdf import PdfReader
reader = PdfReader(str(path))
pages = [(page.extract_text() or "").strip() for page in reader.pages]
except Exception as exc:
return "", f"PDF reader failed ({type(exc).__name__})."
readable = sum(len(page) for page in pages)
if readable >= 80:
return _clean_text("\n\n".join(page for page in pages if page)), f"Read {len(pages)} PDF page(s)."
# Scanned paper fallback: render a limited number of pages and run the same
# local OCR used for handwritten learner submissions.
ocr_pages: list[str] = []
try:
import fitz
document = fitz.open(str(path))
for page_index in range(min(len(document), 40)):
pixmap = document[page_index].get_pixmap(matrix=fitz.Matrix(2, 2), alpha=False)
image = Image.open(BytesIO(pixmap.tobytes("png"))).convert("RGB")
text, _ = run_ocr(image)
if text:
ocr_pages.append(text)
document.close()
except Exception as exc:
return _clean_text("\n\n".join(pages)), f"Scanned-PDF OCR failed ({type(exc).__name__})."
return _clean_text("\n\n".join(ocr_pages)), f"OCR processed {len(ocr_pages)} scanned PDF page(s)."
def _extract_docx(path: Path) -> tuple[str, str]:
try:
from docx import Document
document = Document(str(path))
blocks = [paragraph.text for paragraph in document.paragraphs if paragraph.text.strip()]
for table in document.tables:
for row in table.rows:
text = " | ".join(cell.text.strip() for cell in row.cells if cell.text.strip())
if text:
blocks.append(text)
return _clean_text("\n".join(blocks)), f"Read {len(blocks)} Word text block(s)."
except Exception as exc:
return "", f"Word reader failed ({type(exc).__name__})."
def _extract_doc(path: Path) -> tuple[str, str]:
try:
result = subprocess.run(
["antiword", str(path)], capture_output=True, check=False, timeout=40,
)
text = result.stdout.decode("utf-8", errors="replace")
if result.returncode == 0 and text.strip():
return _clean_text(text), "Read legacy Word document."
return "", "The legacy .doc file could not be read; resave it as .docx."
except Exception as exc:
return "", f"Legacy Word reader failed ({type(exc).__name__})."
def _extract_image(path: Path) -> tuple[str, str]:
try:
image = Image.open(path).convert("RGB")
text, status = run_ocr(image)
return _clean_text(text), status
except Exception as exc:
return "", f"Image OCR failed ({type(exc).__name__})."
def transcribe_audio(path: Path) -> tuple[str, str]:
"""Transcribe audio through a configured API or a lazy local Whisper model."""
if os.getenv("OPENAI_API_KEY"):
try:
from openai import OpenAI
with path.open("rb") as audio_file:
result = OpenAI().audio.transcriptions.create(
model=os.getenv("TRANSCRIPTION_MODEL", "gpt-4o-mini-transcribe"),
file=audio_file,
)
text = getattr(result, "text", "") or str(result)
return _clean_text(text), "Audio transcribed with the configured speech service."
except Exception as exc:
api_note = f"Configured speech service failed ({type(exc).__name__}); trying local transcription."
else:
api_note = ""
global _WHISPER_MODEL
try:
from faster_whisper import WhisperModel
if _WHISPER_MODEL is None:
_WHISPER_MODEL = WhisperModel(
os.getenv("LOCAL_WHISPER_MODEL", "tiny.en"), device="cpu", compute_type="int8"
)
segments, _ = _WHISPER_MODEL.transcribe(str(path), beam_size=3, vad_filter=True)
text = " ".join(segment.text.strip() for segment in segments if segment.text.strip())
status = "Audio transcribed locally with Whisper."
if api_note:
status = api_note + " " + status
return _clean_text(text), status
except Exception as exc:
return "", (api_note + " " if api_note else "") + f"Audio transcription failed ({type(exc).__name__})."
def extract_source(path: Path) -> tuple[str, str]:
extension = path.suffix.lower()
if extension not in SUPPORTED_EXTENSIONS:
return "", f"Unsupported file type: {extension or 'unknown'}."
if extension in {".txt", ".md"}:
try:
return _clean_text(path.read_text(encoding="utf-8", errors="replace")), "Read text file."
except Exception as exc:
return "", f"Text reader failed ({type(exc).__name__})."
if extension == ".json":
try:
content = json.loads(path.read_text(encoding="utf-8"))
if isinstance(content, list) and any(isinstance(item, dict) and item.get("prompt") for item in content):
questions = [
f"Question {index}. {item['prompt']}"
for index, item in enumerate(content, 1)
if isinstance(item, dict) and item.get("prompt")
]
return _clean_text("\n\n".join(questions)), f"Read {len(questions)} question-bank record(s)."
return _clean_text(json.dumps(content, ensure_ascii=False)), "Read JSON text."
except Exception as exc:
return "", f"JSON reader failed ({type(exc).__name__})."
if extension == ".pdf":
return _extract_pdf(path)
if extension == ".docx":
return _extract_docx(path)
if extension == ".doc":
return _extract_doc(path)
if extension in IMAGE_EXTENSIONS:
return _extract_image(path)
return transcribe_audio(path)
QUESTION_MARKER = re.compile(
r"(?mi)^(?P<marker>\s*(?:(?:question|ques|q)\s*)?\d{1,3}\s*[.):-]\s*)"
)
def split_questions(text: str, mode: str = "Automatically split numbered questions") -> list[str]:
clean = _clean_text(text)
if not clean:
return []
if mode == "Keep as one question":
return [clean[:MAX_QUESTION_CHARS]]
matches = list(QUESTION_MARKER.finditer(clean))
if len(matches) >= 2:
questions: list[str] = []
if clean[: matches[0].start()].strip():
prefix = clean[: matches[0].start()].strip()
else:
prefix = ""
for index, match in enumerate(matches):
end = matches[index + 1].start() if index + 1 < len(matches) else len(clean)
block = clean[match.start():end].strip()
if prefix and index == 0:
block = prefix + "\n\n" + block
if len(block) >= 15:
questions.append(block[:MAX_QUESTION_CHARS])
return questions
return [clean[:MAX_QUESTION_CHARS]]
def _load_bank_unlocked() -> list[dict[str, Any]]:
if not BANK_PATH.is_file():
return []
try:
content = json.loads(BANK_PATH.read_text(encoding="utf-8"))
return content if isinstance(content, list) else []
except (OSError, json.JSONDecodeError):
return []
def load_bank() -> list[dict[str, Any]]:
with _BANK_LOCK:
return _load_bank_unlocked()
def _save_bank_unlocked(records: list[dict[str, Any]]) -> None:
BANK_PATH.parent.mkdir(parents=True, exist_ok=True)
temporary = BANK_PATH.with_suffix(".tmp")
temporary.write_text(json.dumps(records, indent=2, ensure_ascii=False), encoding="utf-8")
os.replace(temporary, BANK_PATH)
def _topic_from_scene(scene: str) -> str:
return {
"vertical": "Vertical motion / falling masses",
"collision": "Collision / momentum",
"train": "Train / speed-time motion",
"beam": "Beam / moments",
"friction": "Friction on a plane",
"connected": "Connected particles / pulley",
"vectors": "Vector motion",
"equilibrium": "Equilibrium / strings",
}.get(scene, "Mechanics")
def ingest_question_sources(
typed_text: str,
files: list[Any] | Any,
audio: Any,
title_prefix: str,
topic_hint: str,
split_mode: str,
) -> dict[str, Any]:
chunks: list[tuple[str, str]] = []
notes: list[str] = []
if _clean_text(typed_text):
chunks.append((_clean_text(typed_text), "typed text"))
notes.append("Typed question text received.")
file_values = files if isinstance(files, list) else ([files] if files else [])
for value in file_values:
path = _file_path(value)
if path is None:
notes.append("One uploaded file was unavailable.")
continue
text, note = extract_source(path)
notes.append(f"{path.name}: {note}")
if text:
chunks.append((text, path.name))
audio_path = _file_path(audio)
if audio_path is not None and not any(_file_path(value) == audio_path for value in file_values):
text, note = transcribe_audio(audio_path)
notes.append(f"{audio_path.name}: {note}")
if text:
chunks.append((text, audio_path.name))
if not chunks:
return {
"added": 0,
"duplicates": 0,
"status": "## No question was added\n\nType a question, upload a supported file, or record a spoken question.",
"extracted_text": "\n".join(notes),
"records": load_bank(),
"selected_id": None,
"visual_payload": None,
}
candidates: list[tuple[str, str]] = []
for text, source in chunks:
for question in split_questions(text, split_mode):
candidates.append((question, source))
with _BANK_LOCK:
records = _load_bank_unlocked()
known = {record.get("content_hash") for record in records}
added_records: list[dict[str, Any]] = []
duplicates = 0
timestamp = datetime.now(timezone.utc).isoformat(timespec="seconds")
for index, (question_text, source) in enumerate(candidates, 1):
normalised = " ".join(question_text.lower().split())
content_hash = sha256(normalised.encode("utf-8")).hexdigest()
if content_hash in known:
duplicates += 1
continue
label = str(title_prefix or "Imported M1 question").strip()[:80]
if len(candidates) > 1:
label = f"{label} {index}"
visual = infer_visual_payload(question_text, topic_hint, label)
record = {
"id": "USR-" + content_hash[:12].upper(),
"title": label,
"topic": _topic_from_scene(visual["scene"]),
"source": source,
"created_at": timestamp,
"prompt": question_text,
"content_hash": content_hash,
"visual_payload": visual,
}
records.append(record)
added_records.append(record)
known.add(content_hash)
if added_records:
_save_bank_unlocked(records)
selected = added_records[-1] if added_records else (records[-1] if records else None)
status = (
f"## Added {len(added_records)} new question{'s' if len(added_records) != 1 else ''}\n\n"
f"Skipped **{duplicates}** duplicate{'s' if duplicates != 1 else ''}. "
f"The bank now contains **{BASELINE_REFERENCE_COUNT} mapped reference questions + {len(records)} user-added questions**."
)
extraction_preview = "\n\n---\n\n".join(text for text, _ in chunks)[:20_000]
if notes:
extraction_preview += "\n\n### Intake report\n\n" + "\n".join(f"- {note}" for note in notes)
return {
"added": len(added_records),
"duplicates": duplicates,
"status": status,
"extracted_text": extraction_preview,
"records": records,
"selected_id": selected.get("id") if selected else None,
"visual_payload": selected.get("visual_payload") if selected else None,
}
def bank_choices(records: list[dict[str, Any]] | None = None) -> list[tuple[str, str]]:
records = records if records is not None else load_bank()
return [
(f"{record.get('title', 'Imported question')} · {record.get('topic', 'Mechanics')}", record.get("id", ""))
for record in reversed(records)
]
def bank_summary_markdown(records: list[dict[str, Any]] | None = None) -> str:
records = records if records is not None else load_bank()
lines = [
f"### Reusable question bank · {BASELINE_REFERENCE_COUNT} mapped references + {len(records)} user additions",
"",
]
if not records:
lines.append("No user-added questions yet. Add one above to create its editable concept model.")
return "\n".join(lines)
lines.extend(["| Recent question | Concept | Source |", "|---|---|---|"])
for record in reversed(records[-8:]):
title = str(record.get("title", "Imported question")).replace("|", "\\|")
topic = str(record.get("topic", "Mechanics")).replace("|", "\\|")
source = str(record.get("source", "upload")).replace("|", "\\|")
lines.append(f"| {title} | {topic} | {source} |")
return "\n".join(lines)
def load_bank_record(record_id: str | None) -> dict[str, Any] | None:
if not record_id:
return None
return next((record for record in load_bank() if record.get("id") == record_id), None)
def export_bank_file() -> str:
with _BANK_LOCK:
records = _load_bank_unlocked()
_save_bank_unlocked(records)
return str(BANK_PATH)