File size: 6,656 Bytes
49f6272
 
 
 
 
 
 
5d2ba88
 
 
78c73e4
 
 
5d2ba88
78c73e4
 
 
 
 
 
49f6272
 
 
 
 
 
5d2ba88
49f6272
 
 
 
 
 
 
78c73e4
49f6272
5d2ba88
 
 
 
 
49f6272
78c73e4
 
 
 
 
 
 
 
49f6272
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78c73e4
 
 
49f6272
 
78c73e4
 
 
49f6272
 
 
78c73e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49f6272
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78c73e4
49f6272
 
 
78c73e4
 
 
 
49f6272
 
 
 
 
 
 
 
78c73e4
 
 
 
 
49f6272
 
78c73e4
 
 
5d2ba88
 
 
 
 
49f6272
 
 
 
78c73e4
 
 
 
 
 
49f6272
78c73e4
 
 
 
 
 
 
 
 
 
 
 
 
 
49f6272
78c73e4
 
 
5d2ba88
78c73e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49f6272
 
 
 
 
 
78c73e4
49f6272
 
 
 
 
78c73e4
49f6272
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
import csv
import hashlib
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, List, Optional


RETRIEVAL_SCHEMA_VERSION = "question-answer-v1"


REQUIRED_COLUMNS = {
    "id",
    "question",
    "answer",
    "source_id",
    "category_id",
    "difficulty",
    "flash",
    "is_deleted",
}


@dataclass(frozen=True)
class QuestionRecord:
    question_id: int
    question: str
    answer: str = ""
    source_id: Optional[int] = None
    category_id: Optional[int] = None
    chapter_id: Optional[int] = None
    difficulty: Optional[int] = None
    flash: bool = False
    event_seerah: bool = False
    updated_at: str = ""
    is_deleted: bool = False

    @property
    def retrieval_text(self) -> str:
        """Text used by dense retrieval, BM25, and reranking."""
        return f"Question: {self.question}\nAnswer: {self.answer}"

    def metadata(self) -> Dict[str, object]:
        return {
            "question_id": self.question_id,
            "source_id": self.source_id,
            "category_id": self.category_id,
            "difficulty": self.difficulty,
            "flash": self.flash,
            "is_deleted": self.is_deleted,
        }


@dataclass(frozen=True)
class ParsedQuestions:
    records: List[QuestionRecord]
    source_sha256: str
    invalid_count: int
    deleted_count: int


class QuizCsvValidationError(ValueError):
    pass


def _text(value: object) -> str:
    text = str(value or "").strip()
    return "" if text.lower() == "null" else text


def _required_positive_int(value: object, field: str, row_number: int) -> int:
    text = _text(value)
    if not text:
        raise QuizCsvValidationError(f"Row {row_number}: {field} is required.")
    try:
        numeric = float(text)
    except ValueError as exc:
        raise QuizCsvValidationError(
            f"Row {row_number}: {field} is not an integer."
        ) from exc
    if not numeric.is_integer():
        raise QuizCsvValidationError(
            f"Row {row_number}: {field} is not an integer."
        )
    parsed = int(numeric)
    if parsed <= 0:
        raise QuizCsvValidationError(
            f"Row {row_number}: {field} must be positive."
        )
    return parsed


def _optional_positive_int(
    value: object,
    field: str,
    row_number: int,
) -> Optional[int]:
    text = _text(value)
    if not text:
        return None
    return _required_positive_int(text, field, row_number)


def _boolean(value: object, field: str, row_number: int) -> bool:
    text = _text(value).lower()
    if text in {"1", "true", "t", "yes", "y"}:
        return True
    if text in {"0", "false", "f", "no", "n", ""}:
        return False
    raise QuizCsvValidationError(
        f"Row {row_number}: {field} is not a boolean."
    )


def file_sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def parse_questions_csv(path: Path) -> ParsedQuestions:
    if not path.is_file() or path.stat().st_size <= 0:
        raise QuizCsvValidationError("Quiz CSV is missing or empty.")

    records: List[QuestionRecord] = []
    seen_ids = set()
    invalid_count = 0
    deleted_count = 0

    with path.open("r", encoding="utf-8-sig", newline="") as handle:
        reader = csv.DictReader(handle)
        fieldnames = {
            str(name or "").strip()
            for name in (reader.fieldnames or [])
        }
        missing = sorted(REQUIRED_COLUMNS - fieldnames)
        if missing:
            raise QuizCsvValidationError(
                "Quiz CSV is missing required columns: " + ", ".join(missing)
            )

        for row_number, raw in enumerate(reader, start=2):
            try:
                question_id = _required_positive_int(
                    raw.get("id"),
                    "id",
                    row_number,
                )
                question = _text(raw.get("question"))
                if not question:
                    raise QuizCsvValidationError(
                        f"Row {row_number}: question is blank."
                    )
                answer = _text(raw.get("answer"))
                if not answer:
                    raise QuizCsvValidationError(
                        f"Row {row_number}: answer is blank."
                    )
                if question_id in seen_ids:
                    raise QuizCsvValidationError(
                        f"Row {row_number}: duplicate id {question_id}."
                    )

                is_deleted = _boolean(
                    raw.get("is_deleted"),
                    "is_deleted",
                    row_number,
                )
                seen_ids.add(question_id)
                if is_deleted:
                    deleted_count += 1
                    continue

                difficulty = _optional_positive_int(
                    raw.get("difficulty"),
                    "difficulty",
                    row_number,
                )
                if difficulty is not None and difficulty not in {1, 2, 3}:
                    raise QuizCsvValidationError(
                        f"Row {row_number}: difficulty must be 1, 2, or 3."
                    )

                records.append(
                    QuestionRecord(
                        question_id=question_id,
                        question=question,
                        answer=answer,
                        source_id=_optional_positive_int(
                            raw.get("source_id"),
                            "source_id",
                            row_number,
                        ),
                        category_id=_optional_positive_int(
                            raw.get("category_id"),
                            "category_id",
                            row_number,
                        ),
                        difficulty=difficulty,
                        flash=_boolean(
                            raw.get("flash"),
                            "flash",
                            row_number,
                        ),
                        is_deleted=False,
                    )
                )
            except QuizCsvValidationError:
                invalid_count += 1
                raise

    if not records:
        raise QuizCsvValidationError("Quiz CSV contains no active questions.")

    return ParsedQuestions(
        records=records,
        source_sha256=file_sha256(path),
        invalid_count=invalid_count,
        deleted_count=deleted_count,
    )