diff --git a/requirements.txt b/requirements.txt index 369c5ee..f7d0279 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,6 +3,10 @@ # Maliyet modülü (rag/pricing, rag/providers/deepseek, rag/costlog): # SIFIR harici bağımlılık — yalnız Python stdlib (urllib, json). # +# Kaynak derleyici (src/ingest — Faz 0): +pymupdf>=1.27 # native PDF parse (metin blok + koordinat) +pdfplumber>=0.11 # tablo tespiti (Faz 0.3c) + # İndirme araçları (eba_dl/, scratch scraper'lar) için: requests>=2.32 gdown>=5.0 diff --git a/src/ingest/__init__.py b/src/ingest/__init__.py new file mode 100644 index 0000000..814356c --- /dev/null +++ b/src/ingest/__init__.py @@ -0,0 +1,8 @@ +"""Kaynak derleyici: PDF/görsel → yapılandırılmış, atıflanabilir öğeler. + +Faz 0 (veri hijyeni): pdf_parse (metin blokları + koordinat), sonra tablo, +yasaklı-sayfa izolasyonu, metadata, curriculum graph. Bkz. Obsidian [[plan]]. +""" +from .pdf_parse import Block, Page, ParsedDoc, parse_pdf + +__all__ = ["Block", "Page", "ParsedDoc", "parse_pdf"] diff --git a/src/ingest/pdf_parse.py b/src/ingest/pdf_parse.py new file mode 100644 index 0000000..25a900b --- /dev/null +++ b/src/ingest/pdf_parse.py @@ -0,0 +1,98 @@ +"""Faz 0.3a — Native PDF parse (PyMuPDF). + +Amaç: PDF'yi LLM'ye vermeden, deterministik olarak sayfa → **metin blokları + +koordinat (bbox) + sayfa no** çıkarmak. Her iddia sonra sayfa/bbox'a bağlanacağı +için koordinat baştan tutulur (atıf/provenance). Okuma sırası + blok tipi = 0.3b, +tablo = 0.3c ayrı adımlar. + +Kullanım: + from src.ingest import parse_pdf + doc = parse_pdf("data/lise/12/biyoloji/kitap.pdf") + print(doc.page_count, doc.pages[0].blocks[0].text) +""" +from __future__ import annotations +import json +import os +from dataclasses import dataclass, asdict, field + +import fitz # PyMuPDF + + +@dataclass +class Block: + """Bir sayfadaki metin bloğu + koordinatı (atıf için).""" + page: int # 1-indeksli sayfa no + bbox: tuple[float, float, float, float] # (x0, y0, x1, y1) + text: str + block_no: int # PyMuPDF'in sayfa-içi blok sırası (kaba okuma sırası) + + +@dataclass +class Page: + number: int # 1-indeksli + width: float + height: float + blocks: list[Block] = field(default_factory=list) + + @property + def text(self) -> str: + return "\n".join(b.text for b in self.blocks) + + +@dataclass +class ParsedDoc: + source_path: str + page_count: int + pages: list[Page] = field(default_factory=list) + + @property + def text(self) -> str: + return "\n\n".join(p.text for p in self.pages) + + +def parse_pdf(path: str) -> ParsedDoc: + """PDF'yi sayfa → metin blokları + bbox olarak ayrıştır. Görsel bloklar atlanır + (tip 1); onlar Faz 5 multimodal'da ayrı ele alınır.""" + if not os.path.exists(path): + raise FileNotFoundError(path) + doc = fitz.open(path) + try: + pages: list[Page] = [] + for i, page in enumerate(doc): + rect = page.rect + blocks: list[Block] = [] + # get_text("blocks"): (x0,y0,x1,y1, "text", block_no, block_type) + # block_type 0 = metin, 1 = görsel. Sıralama kabaca yukarıdan aşağı. + for b in page.get_text("blocks"): + x0, y0, x1, y1, text, block_no, block_type = b[:7] + if block_type != 0: + continue + text = (text or "").strip() + if not text: + continue + blocks.append(Block(page=i + 1, bbox=(x0, y0, x1, y1), + text=text, block_no=int(block_no))) + pages.append(Page(number=i + 1, width=rect.width, + height=rect.height, blocks=blocks)) + return ParsedDoc(source_path=path, page_count=doc.page_count, pages=pages) + finally: + doc.close() + + +def to_json(doc: ParsedDoc) -> str: + """Normalize JSON (Faz 0.5 kanonik şemanın çekirdeği).""" + return json.dumps({ + "source_path": doc.source_path, + "page_count": doc.page_count, + "pages": [ + {"number": p.number, "width": p.width, "height": p.height, + "blocks": [asdict(b) for b in p.blocks]} + for p in doc.pages + ], + }, ensure_ascii=False) + + +def save_json(doc: ParsedDoc, out_path: str) -> None: + os.makedirs(os.path.dirname(out_path) or ".", exist_ok=True) + with open(out_path, "w", encoding="utf-8") as f: + f.write(to_json(doc)) diff --git a/tests/integration/test_pdf_parse.py b/tests/integration/test_pdf_parse.py new file mode 100644 index 0000000..22d5cb7 --- /dev/null +++ b/tests/integration/test_pdf_parse.py @@ -0,0 +1,43 @@ +"""Faz 0.3a integration testi — 12-bio kitabını gerçek veri üzerinde parse et. + +Veri (`data/`) git-ignored ve büyük olduğundan, yoksa test ATLANIR (temiz +checkout'ta kırılmaz). Veri varsa: 187 sayfa + metin bütünlüğü doğrulanır. +""" +import os +import unittest + +from src.ingest import parse_pdf + +BOOK = os.path.join("data", "lise", "12", "biyoloji", "kitap.pdf") + + +@unittest.skipUnless(os.path.exists(BOOK), f"veri yok: {BOOK} (indirilmemiş)") +class PdfParse12BioTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.doc = parse_pdf(BOOK) + + def test_page_count_187(self): + self.assertEqual(self.doc.page_count, 187) + self.assertEqual(len(self.doc.pages), 187) + + def test_has_nonempty_text(self): + # Kitabın büyük çoğunluğu metin içermeli + with_text = sum(1 for p in self.doc.pages if p.text.strip()) + self.assertGreater(with_text, 150, "çok az sayfada metin var — parse şüpheli") + + def test_blocks_have_valid_bbox(self): + # İlk metinli sayfada bbox tutarlı olmalı (atıf için şart) + page = next(p for p in self.doc.pages if p.blocks) + b = page.blocks[0] + x0, y0, x1, y1 = b.bbox + self.assertLess(x0, x1) + self.assertLess(y0, y1) + self.assertEqual(b.page, page.number) + + def test_total_text_substantial(self): + self.assertGreater(len(self.doc.text), 50_000, "toplam metin beklenenden az") + + +if __name__ == "__main__": + unittest.main()