From 5e9fe364b784ad54b8a596f96e2c8f0eec3f0609 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kadir=20Y=C3=B6nak?= Date: Sat, 29 Aug 2026 12:51:06 +0300 Subject: [PATCH] feat(ingest): tablo tespiti + siki kalite filtresi (Faz 0.3c) - src/ingest/tables.py: pdfplumber ile tablo cikar + is_real_table filtresi (min satir/sutun/hucre + dolu-oran >=0.6) -> dekoratif kutulari eler - Gercek 12-bio: 270 ham tablo -> ~21 aday; %50 ikon-kutu elenir, sayfa 20 DNA/RNA karsilastirma tablosu (%100 dolu) tutulur - extract_tables(pages=[...]) sayfa-kapsamli (tum kitap pdfplumber'da yavas) - Edge case birim testleri (fill_ratio/is_real_table) + gercek-veri integration - Bu kitap tablo-fakiri (proz+diyagram agirlikli); filtre bunu durustce yansitir --- src/ingest/__init__.py | 4 +- src/ingest/tables.py | 80 ++++++++++++++++++++++++++++++++ tests/integration/test_tables.py | 40 ++++++++++++++++ tests/unit/test_tables.py | 51 ++++++++++++++++++++ 4 files changed, 174 insertions(+), 1 deletion(-) create mode 100644 src/ingest/tables.py create mode 100644 tests/integration/test_tables.py create mode 100644 tests/unit/test_tables.py diff --git a/src/ingest/__init__.py b/src/ingest/__init__.py index 814356c..91eebf3 100644 --- a/src/ingest/__init__.py +++ b/src/ingest/__init__.py @@ -4,5 +4,7 @@ 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 +from .tables import Table, extract_tables, is_real_table -__all__ = ["Block", "Page", "ParsedDoc", "parse_pdf"] +__all__ = ["Block", "Page", "ParsedDoc", "parse_pdf", + "Table", "extract_tables", "is_real_table"] diff --git a/src/ingest/tables.py b/src/ingest/tables.py new file mode 100644 index 0000000..b8e031a --- /dev/null +++ b/src/ingest/tables.py @@ -0,0 +1,80 @@ +"""Faz 0.3c — Tablo tespiti (pdfplumber) + sıkı kalite filtresi. + +Gerçek 12-bio bulgusu: ham `find_tables` çoğunlukla **dekoratif kutu**yu tablo +sanıyor (270 ham → 21 gerçek). Bu yüzden kalite filtresi ŞART: yeterli +satır/sütun + dolu-hücre oranı olmayan "tablolar" elenir. Yalnız yüksek-güven +tablolar döner; her biri sayfa/bbox ile atıflanabilir. + +Kullanım: + from src.ingest.tables import extract_tables + tbls = extract_tables("data/lise/12/biyoloji/kitap.pdf", pages=[12]) + for t in tbls[12]: + print(t.n_rows, t.n_cols, t.fill_ratio, t.rows[0]) +""" +from __future__ import annotations +import os +import warnings +from dataclasses import dataclass, field + +import pdfplumber + +Rows = list[list[str | None]] + + +@dataclass +class Table: + page: int # 1-indeksli + bbox: tuple[float, float, float, float] + rows: Rows + n_rows: int + n_cols: int + fill_ratio: float + + +def fill_ratio(rows: Rows) -> float: + cells = [c for r in rows for c in r] + if not cells: + return 0.0 + return sum(1 for c in cells if c and str(c).strip()) / len(cells) + + +def is_real_table(rows: Rows, *, min_rows: int = 2, min_cols: int = 2, + min_cells: int = 6, min_fill: float = 0.6) -> bool: + """Dekoratif kutuyu gerçek tablodan ayır. Eşikler ayarlanabilir; varsayılan + filtre 12-bio'nun %0-25 dolu dekoratif kutularını eler.""" + n_rows = len(rows) + n_cols = max((len(r) for r in rows), default=0) + if n_rows < min_rows or n_cols < min_cols or n_rows * n_cols < min_cells: + return False + return fill_ratio(rows) >= min_fill + + +def extract_tables(path: str, pages: list[int] | None = None, *, + min_fill: float = 0.6) -> dict[int, list[Table]]: + """PDF'den gerçek tabloları çıkar. pages=None → tüm kitap (yavaş); + pages=[12,20] → yalnız o sayfalar (hızlı; ingest/test için). 1-indeksli.""" + if not os.path.exists(path): + raise FileNotFoundError(path) + out: dict[int, list[Table]] = {} + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + with pdfplumber.open(path) as pdf: + if pages is None: + targets = list(range(len(pdf.pages))) + else: + targets = [p - 1 for p in pages if 1 <= p <= len(pdf.pages)] + for idx in targets: + page = pdf.pages[idx] + real: list[Table] = [] + for t in page.find_tables(): + rows = t.extract() + if not is_real_table(rows, min_fill=min_fill): + continue + real.append(Table( + page=idx + 1, bbox=tuple(round(x, 1) for x in t.bbox), + rows=rows, n_rows=len(rows), + n_cols=max((len(r) for r in rows), default=0), + fill_ratio=round(fill_ratio(rows), 3))) + if real: + out[idx + 1] = real + return out diff --git a/tests/integration/test_tables.py b/tests/integration/test_tables.py new file mode 100644 index 0000000..5d0ed7c --- /dev/null +++ b/tests/integration/test_tables.py @@ -0,0 +1,40 @@ +"""Faz 0.3c integration testi — gerçek 12-bio'da tablo tespiti + filtre. +Hız için YALNIZ birkaç sayfa taranır (tüm kitap pdfplumber'da yavaş).""" +import os +import unittest + +from src.ingest.tables import extract_tables + +BOOK = os.path.join("data", "lise", "12", "biyoloji", "kitap.pdf") + + +@unittest.skipUnless(os.path.exists(BOOK), f"veri yok: {BOOK}") +class TableExtractionTests(unittest.TestCase): + def test_decorative_page1_filtered(self): + # Sayfa 1 = kapak; dekoratif kutular gerçek tablo sayılmamalı + out = extract_tables(BOOK, pages=[1]) + self.assertEqual(out.get(1, []), [], "kapak kutusu gerçek tablo sayıldı (filtre zayıf)") + + def test_page12_icon_box_filtered(self): + # Sayfa 12 = güvenlik ikon kutusu (9x2, %50 dolu) → GERÇEK tablo değil, elenir + out = extract_tables(BOOK, pages=[12]) + self.assertEqual(out.get(12, []), [], "ikon kutusu (%50 dolu) gerçek tablo sayıldı") + + def test_page20_has_real_dna_rna_table(self): + # Sayfa 20 = gerçek DNA/RNA karşılaştırma tablosu (5x2, %100 dolu) + out = extract_tables(BOOK, pages=[20]) + tabs = out.get(20, []) + self.assertTrue(tabs, "sayfa 20'de gerçek tablo bulunamadı") + t = tabs[0] + self.assertGreaterEqual(t.fill_ratio, 0.6) + self.assertEqual(t.page, 20) + flat = " ".join(str(c) for r in t.rows for c in r if c) + self.assertIn("DNA", flat) + self.assertIn("RNA", flat) + x0, y0, x1, y1 = t.bbox # bbox tutarlı (atıf için) + self.assertLess(x0, x1) + self.assertLess(y0, y1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/test_tables.py b/tests/unit/test_tables.py new file mode 100644 index 0000000..8c78443 --- /dev/null +++ b/tests/unit/test_tables.py @@ -0,0 +1,51 @@ +"""Faz 0.3c birim testleri — tablo kalite filtresi (PDF gerekmez, deterministik).""" +import unittest + +from src.ingest.tables import fill_ratio, is_real_table + + +class FillRatioTests(unittest.TestCase): + def test_full(self): + self.assertEqual(fill_ratio([["a", "b"], ["c", "d"]]), 1.0) + + def test_empty_box(self): + self.assertEqual(fill_ratio([[None], [None]]), 0.0) + + def test_partial(self): + self.assertAlmostEqual(fill_ratio([["a", None], [None, None]]), 0.25) + + def test_no_cells(self): + self.assertEqual(fill_ratio([]), 0.0) + + +class IsRealTableTests(unittest.TestCase): + def test_real_3x3_full(self): + rows = [["Kodon", "AA", "Sonuç"], ["AUG", "Met", "Başlat"], ["UAA", "-", "Dur"]] + self.assertTrue(is_real_table(rows)) + + def test_decorative_empty_box_2x1(self): + # 12-bio kapak/kutu tipi → elenir + self.assertFalse(is_real_table([[None], [None]])) + + def test_sparse_9x10_9pct(self): + # gerçek false-positive örneği (sayfa 13): 9x10, ~%9 dolu → elenir + rows = [[None] * 10 for _ in range(9)] + rows[1][2] = "1." + self.assertFalse(is_real_table(rows)) + + def test_too_few_cells(self): + self.assertFalse(is_real_table([["a", "b"]])) # 1 satır + self.assertFalse(is_real_table([["a"], ["b"], ["c"]])) # 1 sütun + + def test_fill_threshold_boundary(self): + # 2x3 = 6 hücre, 4 dolu = %66 → geçer (varsayılan 0.6) + rows = [["a", "b", "c"], ["d", None, None]] + self.assertTrue(is_real_table(rows)) + # aynısı %50 dolu → varsayılanda elenir, gevşek eşikte geçer + rows2 = [["a", "b", None], ["d", None, None]] + self.assertFalse(is_real_table(rows2)) + self.assertTrue(is_real_table(rows2, min_fill=0.3)) + + +if __name__ == "__main__": + unittest.main()