Kanonik dokuman semasi + versiyonlu span-id (Faz 0.5)
Browse files at this commit7737e536ae833428da7d9b74148a3c1ef7c94048Parent: 17ec1e9- feat
- kanonik dokuman semasi + versiyonlu span-id (Faz 0.5)
4 changed files +253 -1
- src/ingest/__init__.py +5 -1
- src/ingest/canonical.py +129 -0
- tests/integration/test_canonical.py +57 -0
- tests/unit/test_canonical.py +62 -0
src/ingest/__init__.pymodified+5 -1
| @@ -7,8 +7,12 @@ from .pdf_parse import Block, Page, ParsedDoc, parse_pdf | |||
| 7 | from .tables import Table, extract_tables, is_real_table | 7 | from .tables import Table, extract_tables, is_real_table |
| 8 | from .visuals import PageVisual, analyze_document, page_visual, render_region | 8 | from .visuals import PageVisual, analyze_document, page_visual, render_region |
| 9 | from .isolate import apply_isolation, page_exclusion_reason | 9 | from .isolate import apply_isolation, page_exclusion_reason |
| 10 | +from .canonical import (CanonicalUnit, CanonicalDoc, build_canonical, | ||
| 11 | + units_from_parsed, make_span_id, file_sha256) | ||
| 10 | 12 | ||
| 11 | __all__ = ["Block", "Page", "ParsedDoc", "parse_pdf", | 13 | __all__ = ["Block", "Page", "ParsedDoc", "parse_pdf", |
| 12 | "Table", "extract_tables", "is_real_table", | 14 | "Table", "extract_tables", "is_real_table", |
| 13 | "PageVisual", "analyze_document", "page_visual", "render_region", | 15 | "PageVisual", "analyze_document", "page_visual", "render_region", |
| 14 | - "apply_isolation", "page_exclusion_reason"] | 16 | + "apply_isolation", "page_exclusion_reason", |
| 17 | + "CanonicalUnit", "CanonicalDoc", "build_canonical", | ||
| 18 | + "units_from_parsed", "make_span_id", "file_sha256"] | ||
src/ingest/canonical.pyadded+129 -0
| @@ -0,0 +1,129 @@ | |||
| 1 | +"""Faz 0.5 — Kanonik doküman şeması + metadata. | ||
| 2 | + | ||
| 3 | +parse (0.3a/b) + izolasyon (0.4) + TR-normalize (0.6) + görsel sınıfı (0.3d) tek | ||
| 4 | +**chunk'lanabilir** yapıda birleşir. Her birim **versiyonlu, stabil span-id** taşır | ||
| 5 | +(claim–evidence sözleşmesinin temeli: her iddia sabit kaynak span'ına bağlanacak, | ||
| 6 | +bkz. mimari §0.1 + RES-001). Tablo (0.3c) opsiyonel (pdfplumber yavaş). | ||
| 7 | + | ||
| 8 | +span_id = "<doc_id>#<sayfa>.<blok_no>" · doc_id = dosya sha256'sının ilk 12'si | ||
| 9 | +(kaynak değişirse sha256 → doc_id → span_id değişir = sürümleme). | ||
| 10 | +""" | ||
| 11 | +from __future__ import annotations | ||
| 12 | +import hashlib | ||
| 13 | +import json | ||
| 14 | +import os | ||
| 15 | +from dataclasses import dataclass, asdict, field | ||
| 16 | + | ||
| 17 | +from .pdf_parse import parse_pdf, ParsedDoc | ||
| 18 | +from .isolate import apply_isolation | ||
| 19 | +from .visuals import analyze_document | ||
| 20 | +from ..text import normalize | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +@dataclass | ||
| 24 | +class CanonicalUnit: | ||
| 25 | + span_id: str # versiyonlu, stabil (atıf birimi) | ||
| 26 | + doc_id: str | ||
| 27 | + sinif: str | ||
| 28 | + ders: str | ||
| 29 | + kaynak_turu: str # ders_kitabi / konu_ozeti / defter ... | ||
| 30 | + page: int | ||
| 31 | + bbox: tuple[float, float, float, float] | ||
| 32 | + block_no: int | ||
| 33 | + kind: str # heading/paragraph/list/caption... | ||
| 34 | + text: str # TR-normalize edilmiş | ||
| 35 | + page_visual: str # figure_heavy/mixed/low_visual | ||
| 36 | + retrieval_disi: bool # sızıntı: indekse girmez | ||
| 37 | + | ||
| 38 | + @property | ||
| 39 | + def retrievable(self) -> bool: | ||
| 40 | + return not self.retrieval_disi | ||
| 41 | + | ||
| 42 | + | ||
| 43 | +@dataclass | ||
| 44 | +class CanonicalDoc: | ||
| 45 | + source_path: str | ||
| 46 | + doc_id: str | ||
| 47 | + source_version: str # tam sha256 | ||
| 48 | + sinif: str | ||
| 49 | + ders: str | ||
| 50 | + kaynak_turu: str | ||
| 51 | + page_count: int | ||
| 52 | + units: list[CanonicalUnit] = field(default_factory=list) | ||
| 53 | + | ||
| 54 | + @property | ||
| 55 | + def retrievable_units(self) -> list[CanonicalUnit]: | ||
| 56 | + return [u for u in self.units if u.retrievable] | ||
| 57 | + | ||
| 58 | + @property | ||
| 59 | + def summary(self) -> dict: | ||
| 60 | + return {"total": len(self.units), | ||
| 61 | + "retrievable": len(self.retrievable_units), | ||
| 62 | + "excluded": sum(1 for u in self.units if u.retrieval_disi)} | ||
| 63 | + | ||
| 64 | + | ||
| 65 | +def file_sha256(path: str) -> str: | ||
| 66 | + h = hashlib.sha256() | ||
| 67 | + with open(path, "rb") as f: | ||
| 68 | + for chunk in iter(lambda: f.read(1 << 20), b""): | ||
| 69 | + h.update(chunk) | ||
| 70 | + return h.hexdigest() | ||
| 71 | + | ||
| 72 | + | ||
| 73 | +def make_span_id(doc_id: str, page: int, block_no: int) -> str: | ||
| 74 | + return f"{doc_id}#{page}.{block_no}" | ||
| 75 | + | ||
| 76 | + | ||
| 77 | +def units_from_parsed(doc: ParsedDoc, *, doc_id: str, sinif: str, ders: str, | ||
| 78 | + kaynak_turu: str, page_visual: dict[int, str]) -> list[CanonicalUnit]: | ||
| 79 | + """İzole edilmiş+parse edilmiş dokümandan kanonik birimler (metin normalize edilir). | ||
| 80 | + Saf fonksiyon — sentetik ParsedDoc ile test edilebilir.""" | ||
| 81 | + out: list[CanonicalUnit] = [] | ||
| 82 | + for p in doc.pages: | ||
| 83 | + for b in p.blocks: | ||
| 84 | + if not b.is_body: # header/footer/label indekslenmez | ||
| 85 | + continue | ||
| 86 | + text = normalize(b.text) | ||
| 87 | + if not text: | ||
| 88 | + continue | ||
| 89 | + out.append(CanonicalUnit( | ||
| 90 | + span_id=make_span_id(doc_id, b.page, b.block_no), | ||
| 91 | + doc_id=doc_id, sinif=sinif, ders=ders, kaynak_turu=kaynak_turu, | ||
| 92 | + page=b.page, bbox=b.bbox, block_no=b.block_no, kind=b.kind, | ||
| 93 | + text=text, page_visual=page_visual.get(b.page, "low_visual"), | ||
| 94 | + retrieval_disi=b.retrieval_disi)) | ||
| 95 | + return out | ||
| 96 | + | ||
| 97 | + | ||
| 98 | +def build_canonical(path: str, sinif: str, ders: str, *, | ||
| 99 | + kaynak_turu: str = "ders_kitabi") -> CanonicalDoc: | ||
| 100 | + """PDF → kanonik doküman (parse + izolasyon + normalize + görsel sınıfı + metadata).""" | ||
| 101 | + if not os.path.exists(path): | ||
| 102 | + raise FileNotFoundError(path) | ||
| 103 | + full = file_sha256(path) | ||
| 104 | + doc_id = full[:12] | ||
| 105 | + parsed = parse_pdf(path) | ||
| 106 | + apply_isolation(parsed) # retrieval_disi işaretle | ||
| 107 | + vis = analyze_document(path) | ||
| 108 | + page_visual = {pv.page: pv.klass for pv in vis["pages"]} | ||
| 109 | + units = units_from_parsed(parsed, doc_id=doc_id, sinif=sinif, ders=ders, | ||
| 110 | + kaynak_turu=kaynak_turu, page_visual=page_visual) | ||
| 111 | + return CanonicalDoc(source_path=path, doc_id=doc_id, source_version=full, | ||
| 112 | + sinif=sinif, ders=ders, kaynak_turu=kaynak_turu, | ||
| 113 | + page_count=parsed.page_count, units=units) | ||
| 114 | + | ||
| 115 | + | ||
| 116 | +def to_json(doc: CanonicalDoc) -> str: | ||
| 117 | + return json.dumps({ | ||
| 118 | + "source_path": doc.source_path, "doc_id": doc.doc_id, | ||
| 119 | + "source_version": doc.source_version, "sinif": doc.sinif, "ders": doc.ders, | ||
| 120 | + "kaynak_turu": doc.kaynak_turu, "page_count": doc.page_count, | ||
| 121 | + "summary": doc.summary, | ||
| 122 | + "units": [asdict(u) for u in doc.units], | ||
| 123 | + }, ensure_ascii=False) | ||
| 124 | + | ||
| 125 | + | ||
| 126 | +def save_json(doc: CanonicalDoc, out_path: str) -> None: | ||
| 127 | + os.makedirs(os.path.dirname(out_path) or ".", exist_ok=True) | ||
| 128 | + with open(out_path, "w", encoding="utf-8") as f: | ||
| 129 | + f.write(to_json(doc)) | ||
tests/integration/test_canonical.pyadded+57 -0
| @@ -0,0 +1,57 @@ | |||
| 1 | +"""Faz 0.5 integration testi — 12-bio kanonik doküman (gerçek veri).""" | ||
| 2 | +import os | ||
| 3 | +import re | ||
| 4 | +import unittest | ||
| 5 | + | ||
| 6 | +from src.ingest.canonical import build_canonical | ||
| 7 | + | ||
| 8 | +BOOK = os.path.join("data", "lise", "12", "biyoloji", "kitap.pdf") | ||
| 9 | + | ||
| 10 | + | ||
| 11 | +@unittest.skipUnless(os.path.exists(BOOK), f"veri yok: {BOOK}") | ||
| 12 | +class Canonical12BioTests(unittest.TestCase): | ||
| 13 | + @classmethod | ||
| 14 | + def setUpClass(cls): | ||
| 15 | + cls.doc = build_canonical(BOOK, sinif="12", ders="biyoloji") | ||
| 16 | + | ||
| 17 | + def test_ids(self): | ||
| 18 | + self.assertRegex(self.doc.doc_id, r"^[0-9a-f]{12}$") | ||
| 19 | + self.assertRegex(self.doc.source_version, r"^[0-9a-f]{64}$") | ||
| 20 | + self.assertEqual(self.doc.page_count, 187) | ||
| 21 | + | ||
| 22 | + def test_units_and_isolation(self): | ||
| 23 | + s = self.doc.summary | ||
| 24 | + self.assertGreater(s["total"], 100) | ||
| 25 | + self.assertGreater(s["retrievable"], 0) | ||
| 26 | + self.assertLess(s["retrievable"], s["total"]) # izolasyon bazı birimleri hariç tuttu | ||
| 27 | + self.assertEqual(s["retrievable"] + s["excluded"], s["total"]) | ||
| 28 | + | ||
| 29 | + def test_every_unit_has_provenance(self): | ||
| 30 | + for u in self.doc.units[:200]: | ||
| 31 | + self.assertTrue(u.span_id.startswith(self.doc.doc_id + "#")) | ||
| 32 | + self.assertTrue(u.text.strip()) | ||
| 33 | + x0, y0, x1, y1 = u.bbox | ||
| 34 | + self.assertLess(x0, x1); self.assertLess(y0, y1) | ||
| 35 | + self.assertEqual((u.sinif, u.ders), ("12", "biyoloji")) | ||
| 36 | + | ||
| 37 | + def test_text_normalized(self): | ||
| 38 | + # hiçbir birimde soft-hyphen kalmamalı (0.6 normalize uygulandı) | ||
| 39 | + self.assertFalse(any("\xad" in u.text or "" in u.text for u in self.doc.units)) | ||
| 40 | + | ||
| 41 | + def test_page_visual_classes_valid(self): | ||
| 42 | + classes = {u.page_visual for u in self.doc.units} | ||
| 43 | + self.assertTrue(classes.issubset({"figure_heavy", "mixed", "low_visual"})) | ||
| 44 | + | ||
| 45 | + def test_zero_leak_excluded_pages(self): | ||
| 46 | + # 12-bio'da 187 (kaynakça) ve 11 (kitap tanıtımı) hariç → o sayfada retrievable birim olmamalı | ||
| 47 | + for pno in (11, 187): | ||
| 48 | + self.assertFalse(any(u.page == pno and u.retrievable for u in self.doc.units), | ||
| 49 | + f"sayfa {pno}'de sızan birim var") | ||
| 50 | + | ||
| 51 | + def test_span_id_stable_across_runs(self): | ||
| 52 | + again = build_canonical(BOOK, sinif="12", ders="biyoloji") | ||
| 53 | + self.assertEqual(again.doc_id, self.doc.doc_id) # sha256 stabil | ||
| 54 | + | ||
| 55 | + | ||
| 56 | +if __name__ == "__main__": | ||
| 57 | + unittest.main() | ||
tests/unit/test_canonical.pyadded+62 -0
| @@ -0,0 +1,62 @@ | |||
| 1 | +"""Faz 0.5 birim testleri — kanonik birim üretimi (sentetik, deterministik).""" | ||
| 2 | +import unittest | ||
| 3 | + | ||
| 4 | +from src.ingest.pdf_parse import Block, Page, ParsedDoc, HEADING, PARAGRAPH, HEADER, LABEL | ||
| 5 | +from src.ingest.canonical import make_span_id, units_from_parsed | ||
| 6 | + | ||
| 7 | + | ||
| 8 | +def _b(text, block_no, kind=PARAGRAPH, retrieval_disi=False, page=1): | ||
| 9 | + return Block(page=page, bbox=(10, 20, 300, 40), text=text, block_no=block_no, | ||
| 10 | + kind=kind, retrieval_disi=retrieval_disi) | ||
| 11 | + | ||
| 12 | + | ||
| 13 | +class SpanIdTests(unittest.TestCase): | ||
| 14 | + def test_format(self): | ||
| 15 | + self.assertEqual(make_span_id("abc123def456", 12, 3), "abc123def456#12.3") | ||
| 16 | + | ||
| 17 | + | ||
| 18 | +class UnitsFromParsedTests(unittest.TestCase): | ||
| 19 | + def setUp(self): | ||
| 20 | + p = Page(number=1, width=400, height=560, blocks=[ | ||
| 21 | + _b("1.2 Başlık", 0, HEADING), | ||
| 22 | + _b("DNA çift sarmaldır ve mü\xadhendislik ile değiştirilir.", 1, PARAGRAPH), | ||
| 23 | + _b("2. BÖLÜM", 2, HEADER), # header → hariç | ||
| 24 | + _b("3,4 nm", 3, LABEL), # label → hariç | ||
| 25 | + _b("Ünite Değerlendirme Soruları", 4, PARAGRAPH, retrieval_disi=True), # sızıntı | ||
| 26 | + ]) | ||
| 27 | + self.doc = ParsedDoc(source_path="x.pdf", page_count=1, pages=[p]) | ||
| 28 | + self.units = units_from_parsed( | ||
| 29 | + self.doc, doc_id="d0c1d2e3f4a5", sinif="12", ders="biyoloji", | ||
| 30 | + kaynak_turu="ders_kitabi", page_visual={1: "mixed"}) | ||
| 31 | + | ||
| 32 | + def test_only_body_units(self): | ||
| 33 | + # header ve label hariç → 3 birim (heading + paragraph + değerlendirme) | ||
| 34 | + kinds = [u.kind for u in self.units] | ||
| 35 | + self.assertEqual(len(self.units), 3) | ||
| 36 | + self.assertNotIn(HEADER, kinds) | ||
| 37 | + self.assertNotIn(LABEL, kinds) | ||
| 38 | + | ||
| 39 | + def test_text_normalized(self): | ||
| 40 | + para = next(u for u in self.units if u.block_no == 1) | ||
| 41 | + self.assertIn("mühendislik", para.text) # \xad hece birleşti | ||
| 42 | + self.assertNotIn("\xad", para.text) | ||
| 43 | + | ||
| 44 | + def test_span_id_and_metadata(self): | ||
| 45 | + para = next(u for u in self.units if u.block_no == 1) | ||
| 46 | + self.assertEqual(para.span_id, "d0c1d2e3f4a5#1.1") | ||
| 47 | + self.assertEqual((para.sinif, para.ders, para.kaynak_turu), ("12", "biyoloji", "ders_kitabi")) | ||
| 48 | + self.assertEqual(para.page_visual, "mixed") | ||
| 49 | + | ||
| 50 | + def test_retrieval_disi_carried(self): | ||
| 51 | + excl = next(u for u in self.units if u.block_no == 4) | ||
| 52 | + self.assertTrue(excl.retrieval_disi) | ||
| 53 | + self.assertFalse(excl.retrievable) | ||
| 54 | + # sızan birim retrievable listesinde olmamalı | ||
| 55 | + self.assertNotIn(excl, [u for u in self.units if u.retrievable]) | ||
| 56 | + | ||
| 57 | + def test_retrievable_subset(self): | ||
| 58 | + self.assertEqual(sum(u.retrievable for u in self.units), 2) # heading + paragraph | ||
| 59 | + | ||
| 60 | + | ||
| 61 | +if __name__ == "__main__": | ||
| 62 | + unittest.main() | ||