File size: 13,523 Bytes
9381502
 
 
 
 
 
 
 
 
87b5875
9381502
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87b5875
9381502
 
 
 
 
 
 
 
 
87b5875
9381502
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87b5875
9381502
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import json
import re
from collections import Counter, defaultdict
from pathlib import Path
from statistics import median
from typing import Any

from cert_study_app.services.question_type_metadata_service import is_visual_question_type, normalize_question_type

ISSUE_WEIGHTS = {
    "missing_stem": 18,
    "short_stem": 8,
    "missing_answer": 10,
    "missing_options": 8,
    "option_label_gap": 8,
    "answer_not_in_options": 8,
    "duplicate_raw_text": 10,
    "number_gap": 12,
    "number_duplicate": 12,
    "page_regression": 10,
    "chunk_too_short": 8,
    "chunk_too_long": 6,
    "answer_leaked_to_stem": 8,
    "embedded_next_question": 14,
    "image_missing": 6,
}


def default_quality_report_path(output_json: str | Path) -> str:
    path = Path(output_json)
    return path.with_name(f"{path.stem}.quality.json").as_posix()


def load_parsed_questions(json_path: str | Path) -> list[dict[str, Any]]:
    with Path(json_path).open("r", encoding="utf-8") as f:
        data = json.load(f)
    if isinstance(data, dict) and isinstance(data.get("questions"), list):
        data = data["questions"]
    if not isinstance(data, list):
        raise ValueError("parsed JSON must be a list or an object with a questions list")
    return [item for item in data if isinstance(item, dict)]


def build_parse_quality_report(
    json_path: str | Path,
    *,
    output_path: str | Path | None = None,
    expected_count: int | None = None,
) -> dict[str, Any]:
    questions = load_parsed_questions(json_path)
    issues_by_index: dict[int, list[dict[str, Any]]] = defaultdict(list)

    numbers = [_as_int(_first_present(item, "number", "question_number")) for item in questions]
    pages = [_as_int(item.get("page")) for item in questions]
    raw_fingerprints: dict[str, list[int]] = defaultdict(list)
    chunk_lengths = []

    for index, item in enumerate(questions):
        raw_text = _text(item.get("raw_text") or item.get("ocr_text") or item.get("stem") or item.get("question"))
        stem = _text(item.get("stem") or item.get("question") or item.get("q_text"))
        answer = item.get("answer")
        options = _normal_options(item.get("options"))
        question_type = normalize_question_type(item.get("question_type") or "mcq")
        raw_fingerprints[_fingerprint(raw_text)].append(index)
        chunk_lengths.append(len(raw_text))

        if not stem:
            _add_issue(issues_by_index, index, "missing_stem", "๋ฌธ์ œ ๋ณธ๋ฌธ์ด ๋น„์–ด ์žˆ์Šต๋‹ˆ๋‹ค.")
        elif len(stem) < 30:
            _add_issue(issues_by_index, index, "short_stem", "๋ฌธ์ œ ๋ณธ๋ฌธ์ด ๋„ˆ๋ฌด ์งง์Šต๋‹ˆ๋‹ค.", length=len(stem))
        if not _has_answer(answer):
            _add_issue(issues_by_index, index, "missing_answer", "์ •๋‹ต์ด ๋น„์–ด ์žˆ์Šต๋‹ˆ๋‹ค.")
        if not is_visual_question_type(question_type) and len(options) < 2:
            _add_issue(issues_by_index, index, "missing_options", "๊ฐ๊ด€์‹/์„ ํƒํ˜•์œผ๋กœ ๋ณด์ด์ง€๋งŒ ๋ณด๊ธฐ๊ฐ€ 2๊ฐœ ๋ฏธ๋งŒ์ž…๋‹ˆ๋‹ค.", option_count=len(options))
        if len(options) >= 2:
            expected_labels = [chr(ord("A") + offset) for offset in range(len(options))]
            labels = [label for label, _body in options]
            if labels != expected_labels:
                _add_issue(
                    issues_by_index,
                    index,
                    "option_label_gap",
                    "๋ณด๊ธฐ ๋ผ๋ฒจ์ด A๋ถ€ํ„ฐ ์—ฐ์†๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.",
                    labels=labels,
                    expected=expected_labels,
                )
            if _answer_labels(answer) and not set(_answer_labels(answer)).issubset(set(labels)):
                _add_issue(
                    issues_by_index,
                    index,
                    "answer_not_in_options",
                    "์ •๋‹ต ๋ผ๋ฒจ์ด ๋ณด๊ธฐ ๋ผ๋ฒจ ์•ˆ์— ์—†์Šต๋‹ˆ๋‹ค.",
                    answer_labels=_answer_labels(answer),
                    option_labels=labels,
                )
        if re.search(r"(?im)^\s*(?:Answer|์ •๋‹ต)\s*:", stem):
            _add_issue(issues_by_index, index, "answer_leaked_to_stem", "๋ณธ๋ฌธ์— ์ •๋‹ต ๋ผ์ธ์ด ์„ž์—ฌ ์žˆ์Šต๋‹ˆ๋‹ค.")
        if re.search(r"(?m)\n\s*\d{1,3}\s*[.)]\s+\S+", stem):
            _add_issue(issues_by_index, index, "embedded_next_question", "์ฒญํฌ ์•ˆ์— ๋‹ค์Œ ๋ฌธ์ œ ์‹œ์ž‘์ฒ˜๋Ÿผ ๋ณด์ด๋Š” ์ค„์ด ์žˆ์Šต๋‹ˆ๋‹ค.")
        if is_visual_question_type(question_type) and item.get("image_path") and not Path(str(item.get("image_path"))).exists():
            _add_issue(issues_by_index, index, "image_missing", "์ด๋ฏธ์ง€ ๊ธฐ๋ฐ˜ ๋ฌธ์ œ์˜ ์›๋ฌธ ์ด๋ฏธ์ง€ ํŒŒ์ผ์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.")

    nonzero_numbers = [number for number in numbers if number is not None]
    duplicates = [number for number, count in Counter(nonzero_numbers).items() if count > 1]
    if duplicates:
        for index, number in enumerate(numbers):
            if number in duplicates:
                _add_issue(issues_by_index, index, "number_duplicate", "๋ฌธ์ œ ๋ฒˆํ˜ธ๊ฐ€ ์ค‘๋ณต๋˜์—ˆ์Šต๋‹ˆ๋‹ค.", number=number)

    gaps = _number_gaps(nonzero_numbers)
    if gaps:
        gap_numbers = set()
        for start, end in gaps:
            gap_numbers.update({start - 1, end + 1})
        for index, number in enumerate(numbers):
            if number in gap_numbers:
                _add_issue(issues_by_index, index, "number_gap", "๋ฌธ์ œ ๋ฒˆํ˜ธ ์—ฐ์†์„ฑ์ด ๊นจ์ง„ ์ง€์  ๊ทผ์ฒ˜์ž…๋‹ˆ๋‹ค.", gaps=gaps[:10])

    previous_page = None
    for index, page in enumerate(pages):
        if page is None:
            continue
        if previous_page is not None and page < previous_page:
            _add_issue(issues_by_index, index, "page_regression", "ํŽ˜์ด์ง€ ๋ฒˆํ˜ธ๊ฐ€ ์ด์ „ ๋ฌธํ•ญ๋ณด๋‹ค ์ž‘์Šต๋‹ˆ๋‹ค.", previous_page=previous_page, page=page)
        previous_page = page

    repeated_fingerprints = {fp: indexes for fp, indexes in raw_fingerprints.items() if fp and len(indexes) > 1}
    for indexes in repeated_fingerprints.values():
        for index in indexes:
            _add_issue(issues_by_index, index, "duplicate_raw_text", "๊ฐ™์€ ์›๋ฌธ ์ฒญํฌ๊ฐ€ ์ค‘๋ณต ํŒŒ์‹ฑ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.", duplicate_indexes=indexes)

    length_stats = _length_stats(chunk_lengths)
    short_cutoff = 50
    long_cutoff = max(2500, int((length_stats.get("median") or 0) * 4))
    for index, length in enumerate(chunk_lengths):
        if length and length < short_cutoff:
            _add_issue(issues_by_index, index, "chunk_too_short", "์›๋ฌธ ์ฒญํฌ๊ฐ€ ๋„ˆ๋ฌด ์งง์Šต๋‹ˆ๋‹ค.", length=length)
        elif long_cutoff and length > long_cutoff:
            _add_issue(issues_by_index, index, "chunk_too_long", "์›๋ฌธ ์ฒญํฌ๊ฐ€ ๋น„์ •์ƒ์ ์œผ๋กœ ๊น๋‹ˆ๋‹ค.", length=length, cutoff=long_cutoff)

    issue_counts = Counter(issue["code"] for issues in issues_by_index.values() for issue in issues)
    total_penalty = sum(ISSUE_WEIGHTS.get(code, 5) * count for code, count in issue_counts.items())
    count_penalty = 0
    if expected_count is not None and expected_count >= 0:
        count_delta = abs(len(questions) - expected_count)
        count_penalty = min(20, count_delta * 2)
    score = max(0, min(100, 100 - total_penalty - count_penalty))

    samples = []
    for index, issues in sorted(issues_by_index.items(), key=lambda row: (-_issue_weight_sum(row[1]), row[0]))[:30]:
        item = questions[index]
        samples.append(
            {
                "index": index,
                "number": _first_present(item, "number", "question_number"),
                "page": item.get("page"),
                "question_type": item.get("question_type"),
                "issues": issues,
                "stem_preview": _preview(item.get("stem") or item.get("question") or ""),
                "raw_preview": _preview(item.get("raw_text") or item.get("ocr_text") or ""),
            }
        )

    report = {
        "schema_version": 1,
        "source_json": Path(json_path).as_posix(),
        "score": score,
        "status": _status_for_score(score, issue_counts),
        "question_count": len(questions),
        "expected_count": expected_count,
        "issue_counts": dict(sorted(issue_counts.items())),
        "question_issues": [
            {
                "index": index,
                "number": _first_present(questions[index], "number", "question_number"),
                "page": questions[index].get("page"),
                "issues": issues,
            }
            for index, issues in sorted(issues_by_index.items())
        ],
        "metrics": {
            "missing_answer": issue_counts.get("missing_answer", 0),
            "missing_options": issue_counts.get("missing_options", 0),
            "needs_review_estimate": len(issues_by_index),
            "numbers": {
                "first": min(nonzero_numbers) if nonzero_numbers else None,
                "last": max(nonzero_numbers) if nonzero_numbers else None,
                "duplicates": duplicates[:30],
                "gaps": gaps[:30],
            },
            "pages": {
                "first": next((page for page in pages if page is not None), None),
                "last": next((page for page in reversed(pages) if page is not None), None),
                "regressions": issue_counts.get("page_regression", 0),
            },
            "chunk_lengths": length_stats,
        },
        "samples": samples,
    }

    if output_path:
        Path(output_path).parent.mkdir(parents=True, exist_ok=True)
        Path(output_path).write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
    return report


def summarize_quality_report(report: dict[str, Any]) -> str:
    counts = report.get("issue_counts") or {}
    top = ", ".join(f"{key} {value}" for key, value in sorted(counts.items(), key=lambda row: (-row[1], row[0]))[:4])
    return f"ํ’ˆ์งˆ ์ ์ˆ˜ {report.get('score', 0)}์  ยท {report.get('question_count', 0)}๋ฌธํ•ญ" + (f" ยท {top}" if top else "")


def _add_issue(target: dict[int, list[dict[str, Any]]], index: int, code: str, message: str, **details: Any) -> None:
    target[index].append({"code": code, "message": message, "severity": _severity(code), "details": details})


def _severity(code: str) -> str:
    weight = ISSUE_WEIGHTS.get(code, 5)
    if weight >= 12:
        return "high"
    if weight >= 8:
        return "medium"
    return "low"


def _issue_weight_sum(issues: list[dict[str, Any]]) -> int:
    return sum(ISSUE_WEIGHTS.get(str(issue.get("code")), 5) for issue in issues)


def _text(value: Any) -> str:
    return str(value or "").strip()


def _first_present(item: dict[str, Any], *keys: str) -> Any:
    for key in keys:
        if item.get(key) not in {None, ""}:
            return item.get(key)
    return None


def _as_int(value: Any) -> int | None:
    try:
        return int(value)
    except Exception:
        return None


def _normal_options(raw: Any) -> list[tuple[str, str]]:
    if isinstance(raw, dict):
        rows = [(str(key).strip().upper(), str(value).strip()) for key, value in raw.items()]
    elif isinstance(raw, list):
        rows = []
        for index, value in enumerate(raw):
            text = str(value or "").strip()
            match = re.match(r"^([A-Za-z])[\.\)]\s*(.+)$", text, re.S)
            if match:
                rows.append((match.group(1).upper(), match.group(2).strip()))
            else:
                rows.append((chr(ord("A") + index), text))
    else:
        rows = []
    return [(label, body) for label, body in rows if label or body]


def _has_answer(value: Any) -> bool:
    if isinstance(value, list):
        return bool(value)
    if isinstance(value, dict):
        return bool(value)
    text = str(value or "").strip()
    return bool(text and text not in {"[]", "{}"})


def _answer_labels(value: Any) -> list[str]:
    if isinstance(value, list):
        text = " ".join(str(item) for item in value)
    elif isinstance(value, dict):
        text = " ".join(str(item) for item in value.values())
    else:
        text = str(value or "")
    text = text.upper()
    if re.fullmatch(r"[A-H]{2,8}", text.strip()):
        return list(text.strip())
    labels = []
    for token in re.findall(r"\b[A-H]\b|\b[1-8]\b", text):
        labels.append(chr(ord("A") + int(token) - 1) if token.isdigit() else token)
    return labels


def _fingerprint(text: str) -> str:
    normalized = re.sub(r"\s+", " ", text or "").strip().lower()
    if len(normalized) < 80:
        return ""
    return normalized[:500]


def _number_gaps(numbers: list[int]) -> list[tuple[int, int]]:
    if len(numbers) < 2:
        return []
    unique_sorted = sorted(set(numbers))
    gaps = []
    for previous, current in zip(unique_sorted, unique_sorted[1:]):
        if current > previous + 1:
            gaps.append((previous + 1, current - 1))
    return gaps


def _length_stats(lengths: list[int]) -> dict[str, Any]:
    if not lengths:
        return {"min": 0, "median": 0, "max": 0}
    return {"min": min(lengths), "median": int(median(lengths)), "max": max(lengths)}


def _preview(value: Any, limit: int = 220) -> str:
    text = re.sub(r"\s+", " ", str(value or "")).strip()
    return text[:limit]


def _status_for_score(score: int, issue_counts: Counter) -> str:
    if issue_counts.get("number_gap") or issue_counts.get("embedded_next_question"):
        return "needs_chunk_review"
    if score >= 85:
        return "pass"
    if score >= 65:
        return "needs_sampling"
    return "needs_reparse"