Spaces:
Paused

File size: 15,258 Bytes
f8aaa7d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
"""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)