Native PDF parse (Faz 0.3a)
Browse files at this commit0a32e96b7dd5989a2723c8c4acce04780686a594Parent: ab28d6f- feat
- native PDF parse (Faz 0.3a)
4 changed files +153 -0
- requirements.txt +4 -0
- src/ingest/__init__.py +8 -0
- src/ingest/pdf_parse.py +98 -0
- tests/integration/test_pdf_parse.py +43 -0
requirements.txtmodified+4 -0
| @@ -3,6 +3,10 @@ | ||
| 3 | 3 | # Maliyet modülü (rag/pricing, rag/providers/deepseek, rag/costlog): |
| 4 | 4 | # SIFIR harici bağımlılık — yalnız Python stdlib (urllib, json). |
| 5 | 5 | # |
| 6 | +# Kaynak derleyici (src/ingest — Faz 0): | |
| 7 | +pymupdf>=1.27 # native PDF parse (metin blok + koordinat) | |
| 8 | +pdfplumber>=0.11 # tablo tespiti (Faz 0.3c) | |
| 9 | + | |
| 6 | 10 | # İndirme araçları (eba_dl/, scratch scraper'lar) için: |
| 7 | 11 | requests>=2.32 |
| 8 | 12 | gdown>=5.0 |
src/ingest/__init__.pyadded+8 -0
| @@ -0,0 +1,8 @@ | ||
| 1 | +"""Kaynak derleyici: PDF/görsel → yapılandırılmış, atıflanabilir öğeler. | |
| 2 | + | |
| 3 | +Faz 0 (veri hijyeni): pdf_parse (metin blokları + koordinat), sonra tablo, | |
| 4 | +yasaklı-sayfa izolasyonu, metadata, curriculum graph. Bkz. Obsidian [[plan]]. | |
| 5 | +""" | |
| 6 | +from .pdf_parse import Block, Page, ParsedDoc, parse_pdf | |
| 7 | + | |
| 8 | +__all__ = ["Block", "Page", "ParsedDoc", "parse_pdf"] |
src/ingest/pdf_parse.pyadded+98 -0
| @@ -0,0 +1,98 @@ | ||
| 1 | +"""Faz 0.3a — Native PDF parse (PyMuPDF). | |
| 2 | + | |
| 3 | +Amaç: PDF'yi LLM'ye vermeden, deterministik olarak sayfa → **metin blokları + | |
| 4 | +koordinat (bbox) + sayfa no** çıkarmak. Her iddia sonra sayfa/bbox'a bağlanacağı | |
| 5 | +için koordinat baştan tutulur (atıf/provenance). Okuma sırası + blok tipi = 0.3b, | |
| 6 | +tablo = 0.3c ayrı adımlar. | |
| 7 | + | |
| 8 | +Kullanım: | |
| 9 | + from src.ingest import parse_pdf | |
| 10 | + doc = parse_pdf("data/lise/12/biyoloji/kitap.pdf") | |
| 11 | + print(doc.page_count, doc.pages[0].blocks[0].text) | |
| 12 | +""" | |
| 13 | +from __future__ import annotations | |
| 14 | +import json | |
| 15 | +import os | |
| 16 | +from dataclasses import dataclass, asdict, field | |
| 17 | + | |
| 18 | +import fitz # PyMuPDF | |
| 19 | + | |
| 20 | + | |
| 21 | +@dataclass | |
| 22 | +class Block: | |
| 23 | + """Bir sayfadaki metin bloğu + koordinatı (atıf için).""" | |
| 24 | + page: int # 1-indeksli sayfa no | |
| 25 | + bbox: tuple[float, float, float, float] # (x0, y0, x1, y1) | |
| 26 | + text: str | |
| 27 | + block_no: int # PyMuPDF'in sayfa-içi blok sırası (kaba okuma sırası) | |
| 28 | + | |
| 29 | + | |
| 30 | +@dataclass | |
| 31 | +class Page: | |
| 32 | + number: int # 1-indeksli | |
| 33 | + width: float | |
| 34 | + height: float | |
| 35 | + blocks: list[Block] = field(default_factory=list) | |
| 36 | + | |
| 37 | + @property | |
| 38 | + def text(self) -> str: | |
| 39 | + return "\n".join(b.text for b in self.blocks) | |
| 40 | + | |
| 41 | + | |
| 42 | +@dataclass | |
| 43 | +class ParsedDoc: | |
| 44 | + source_path: str | |
| 45 | + page_count: int | |
| 46 | + pages: list[Page] = field(default_factory=list) | |
| 47 | + | |
| 48 | + @property | |
| 49 | + def text(self) -> str: | |
| 50 | + return "\n\n".join(p.text for p in self.pages) | |
| 51 | + | |
| 52 | + | |
| 53 | +def parse_pdf(path: str) -> ParsedDoc: | |
| 54 | + """PDF'yi sayfa → metin blokları + bbox olarak ayrıştır. Görsel bloklar atlanır | |
| 55 | + (tip 1); onlar Faz 5 multimodal'da ayrı ele alınır.""" | |
| 56 | + if not os.path.exists(path): | |
| 57 | + raise FileNotFoundError(path) | |
| 58 | + doc = fitz.open(path) | |
| 59 | + try: | |
| 60 | + pages: list[Page] = [] | |
| 61 | + for i, page in enumerate(doc): | |
| 62 | + rect = page.rect | |
| 63 | + blocks: list[Block] = [] | |
| 64 | + # get_text("blocks"): (x0,y0,x1,y1, "text", block_no, block_type) | |
| 65 | + # block_type 0 = metin, 1 = görsel. Sıralama kabaca yukarıdan aşağı. | |
| 66 | + for b in page.get_text("blocks"): | |
| 67 | + x0, y0, x1, y1, text, block_no, block_type = b[:7] | |
| 68 | + if block_type != 0: | |
| 69 | + continue | |
| 70 | + text = (text or "").strip() | |
| 71 | + if not text: | |
| 72 | + continue | |
| 73 | + blocks.append(Block(page=i + 1, bbox=(x0, y0, x1, y1), | |
| 74 | + text=text, block_no=int(block_no))) | |
| 75 | + pages.append(Page(number=i + 1, width=rect.width, | |
| 76 | + height=rect.height, blocks=blocks)) | |
| 77 | + return ParsedDoc(source_path=path, page_count=doc.page_count, pages=pages) | |
| 78 | + finally: | |
| 79 | + doc.close() | |
| 80 | + | |
| 81 | + | |
| 82 | +def to_json(doc: ParsedDoc) -> str: | |
| 83 | + """Normalize JSON (Faz 0.5 kanonik şemanın çekirdeği).""" | |
| 84 | + return json.dumps({ | |
| 85 | + "source_path": doc.source_path, | |
| 86 | + "page_count": doc.page_count, | |
| 87 | + "pages": [ | |
| 88 | + {"number": p.number, "width": p.width, "height": p.height, | |
| 89 | + "blocks": [asdict(b) for b in p.blocks]} | |
| 90 | + for p in doc.pages | |
| 91 | + ], | |
| 92 | + }, ensure_ascii=False) | |
| 93 | + | |
| 94 | + | |
| 95 | +def save_json(doc: ParsedDoc, out_path: str) -> None: | |
| 96 | + os.makedirs(os.path.dirname(out_path) or ".", exist_ok=True) | |
| 97 | + with open(out_path, "w", encoding="utf-8") as f: | |
| 98 | + f.write(to_json(doc)) |
tests/integration/test_pdf_parse.pyadded+43 -0
| @@ -0,0 +1,43 @@ | ||
| 1 | +"""Faz 0.3a integration testi — 12-bio kitabını gerçek veri üzerinde parse et. | |
| 2 | + | |
| 3 | +Veri (`data/`) git-ignored ve büyük olduğundan, yoksa test ATLANIR (temiz | |
| 4 | +checkout'ta kırılmaz). Veri varsa: 187 sayfa + metin bütünlüğü doğrulanır. | |
| 5 | +""" | |
| 6 | +import os | |
| 7 | +import unittest | |
| 8 | + | |
| 9 | +from src.ingest import parse_pdf | |
| 10 | + | |
| 11 | +BOOK = os.path.join("data", "lise", "12", "biyoloji", "kitap.pdf") | |
| 12 | + | |
| 13 | + | |
| 14 | +@unittest.skipUnless(os.path.exists(BOOK), f"veri yok: {BOOK} (indirilmemiş)") | |
| 15 | +class PdfParse12BioTests(unittest.TestCase): | |
| 16 | + @classmethod | |
| 17 | + def setUpClass(cls): | |
| 18 | + cls.doc = parse_pdf(BOOK) | |
| 19 | + | |
| 20 | + def test_page_count_187(self): | |
| 21 | + self.assertEqual(self.doc.page_count, 187) | |
| 22 | + self.assertEqual(len(self.doc.pages), 187) | |
| 23 | + | |
| 24 | + def test_has_nonempty_text(self): | |
| 25 | + # Kitabın büyük çoğunluğu metin içermeli | |
| 26 | + with_text = sum(1 for p in self.doc.pages if p.text.strip()) | |
| 27 | + self.assertGreater(with_text, 150, "çok az sayfada metin var — parse şüpheli") | |
| 28 | + | |
| 29 | + def test_blocks_have_valid_bbox(self): | |
| 30 | + # İlk metinli sayfada bbox tutarlı olmalı (atıf için şart) | |
| 31 | + page = next(p for p in self.doc.pages if p.blocks) | |
| 32 | + b = page.blocks[0] | |
| 33 | + x0, y0, x1, y1 = b.bbox | |
| 34 | + self.assertLess(x0, x1) | |
| 35 | + self.assertLess(y0, y1) | |
| 36 | + self.assertEqual(b.page, page.number) | |
| 37 | + | |
| 38 | + def test_total_text_substantial(self): | |
| 39 | + self.assertGreater(len(self.doc.text), 50_000, "toplam metin beklenenden az") | |
| 40 | + | |
| 41 | + | |
| 42 | +if __name__ == "__main__": | |
| 43 | + unittest.main() |