From 33ba723d831089cab4d032b798e533d3bb02eb47 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kadir=20Y=C3=B6nak?= Date: Sat, 12 Sep 2026 21:06:22 +0300 Subject: [PATCH] test: entegrasyon ve e2e suiti CANLANDIRILDI (47 atlanan -> 2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit EN BUYUK TEST BULGUSU: entegrasyon + e2e suitinin TAMAMI OLUYDU. 47 atlanan testin 46'si `data/lise/12/biyoloji/kitap.pdf` yok diye atlaniyordu. Yani birim testleri yesil gorunurken GERCEK BORU HATTI hic sinanmiyordu -- PDF parse, izolasyon, chunk, embed, indeks, retrieval, rerank, uretim: hicbiri kosmuyordu. Elimizde 10. sinif korpusu vardi ve ayni boru hattini sinar. tests/corpus.py: TEK KAYNAK korpus bulucu. "Hangi kitap varsa onu kullan"; HEZARFEN_TEST_BOOK ile CI'da sabitlenebilir. 12. SINIFA CAKILI SABITLER DEGISMEZLERE CEVRILDI. Bu sabitler yillardir DOGRULANMAMISTI (test hic kosmadigi icin): - sayfa sayisi 187 -> "gercek bir kitap" (>50) - sinif/ders ("12","biyoloji")-> korpustan turetilir - hariç sayfa 11/187 -> hariç tutulanlarin HEPSI kontrol edilir - "sayfa 41 ogretici" -> orta %50'nin >%70'i indekslenebilir olmali - "sayfa 20'de DNA tablosu" -> kitapta EN AZ bir gercek tablo bulunmali - kazanim sayisi 29, unite 4 -> kod tekil, sinif onekli, arama gidis-donus - sorgu "DNA cift sarmal" -> en uzun chunk'in kendi metni (her korpusta bulunur; 10. sinifta DNA hic gecmiyor) Ayrica #59'un cesitlilik sozlesme degisikligi entegrasyon testine yansitildi: `per_parent` artik TAVAN degil; degismez olan tekrarsiz + skor-sirali sonuc. PAYLASIMLI MODEL: testler canlaninca her modul kendi BGE-M3 + reranker'ini VRAM'e yukledi ve suit CUDA OUT OF MEMORY ile dustu (7,57/7,65 GiB). corpus.shared_embedder()/shared_reranker() ile tek ornek paylasiliyor. SONUC: 996 test, 2 atlanan (once 47), hepsi yesil. Suit 26 s -> 183 s cunku gercek boru hatti artik GERCEKTEN kosuyor. --- outputs/deployment/suite-err.log | 392 +++++++++++++++++++++++++++ tests/corpus.py | 132 +++++++++ tests/e2e/test_pipeline_e2e.py | 6 +- tests/integration/test_canonical.py | 33 ++- tests/integration/test_chunk.py | 10 +- tests/integration/test_curriculum.py | 56 +++- tests/integration/test_embed.py | 4 +- tests/integration/test_generate.py | 19 +- tests/integration/test_index.py | 8 +- tests/integration/test_isolate.py | 42 ++- tests/integration/test_pdf_parse.py | 12 +- tests/integration/test_rerank.py | 36 ++- tests/integration/test_retrieve.py | 8 +- tests/integration/test_tables.py | 61 +++-- tests/integration/test_visuals.py | 8 +- 15 files changed, 723 insertions(+), 104 deletions(-) create mode 100644 outputs/deployment/suite-err.log create mode 100644 tests/corpus.py diff --git a/outputs/deployment/suite-err.log b/outputs/deployment/suite-err.log new file mode 100644 index 0000000..e296b72 --- /dev/null +++ b/outputs/deployment/suite-err.log @@ -0,0 +1,392 @@ + Loading weights: 0%| | 0/391 [00:00 + def decorating_function(user_function): +ResourceWarning: Enable tracemalloc to get the object allocation traceback +/usr/lib/python3.13/reprlib.py:12: ResourceWarning: unclosed database in + def decorating_function(user_function): +ResourceWarning: Enable tracemalloc to get the object allocation traceback +/usr/lib/python3.13/reprlib.py:12: ResourceWarning: unclosed database in + def decorating_function(user_function): +ResourceWarning: Enable tracemalloc to get the object allocation traceback +/usr/lib/python3.13/reprlib.py:12: ResourceWarning: unclosed database in + def decorating_function(user_function): +ResourceWarning: Enable tracemalloc to get the object allocation traceback +/usr/lib/python3.13/reprlib.py:12: ResourceWarning: unclosed database in + def decorating_function(user_function): +ResourceWarning: Enable tracemalloc to get the object allocation traceback +/usr/lib/python3.13/reprlib.py:12: ResourceWarning: unclosed database in + def decorating_function(user_function): +ResourceWarning: Enable tracemalloc to get the object allocation traceback +/usr/lib/python3.13/reprlib.py:12: ResourceWarning: unclosed database in + def decorating_function(user_function): +ResourceWarning: Enable tracemalloc to get the object allocation traceback +/usr/lib/python3.13/reprlib.py:12: ResourceWarning: unclosed database in + def decorating_function(user_function): +ResourceWarning: Enable tracemalloc to get the object allocation traceback +/usr/lib/python3.13/reprlib.py:12: ResourceWarning: unclosed database in + def decorating_function(user_function): +ResourceWarning: Enable tracemalloc to get the object allocation traceback +/usr/lib/python3.13/reprlib.py:12: ResourceWarning: unclosed database in + def decorating_function(user_function): +ResourceWarning: Enable tracemalloc to get the object allocation traceback +/usr/lib/python3.13/reprlib.py:12: ResourceWarning: unclosed database in + def decorating_function(user_function): +ResourceWarning: Enable tracemalloc to get the object allocation traceback +/usr/lib/python3.13/reprlib.py:12: ResourceWarning: unclosed database in + def decorating_function(user_function): +ResourceWarning: Enable tracemalloc to get the object allocation traceback +/usr/lib/python3.13/reprlib.py:12: ResourceWarning: unclosed database in + def decorating_function(user_function): +ResourceWarning: Enable tracemalloc to get the object allocation traceback +/usr/lib/python3.13/reprlib.py:12: ResourceWarning: unclosed database in + def decorating_function(user_function): +ResourceWarning: Enable tracemalloc to get the object allocation traceback +/usr/lib/python3.13/reprlib.py:12: ResourceWarning: unclosed database in + def decorating_function(user_function): +ResourceWarning: Enable tracemalloc to get the object allocation traceback +/usr/lib/python3.13/reprlib.py:12: ResourceWarning: unclosed database in + def decorating_function(user_function): +ResourceWarning: Enable tracemalloc to get the object allocation traceback +/usr/lib/python3.13/reprlib.py:12: ResourceWarning: unclosed database in + def decorating_function(user_function): +ResourceWarning: Enable tracemalloc to get the object allocation traceback +/usr/lib/python3.13/reprlib.py:12: ResourceWarning: unclosed database in + def decorating_function(user_function): +ResourceWarning: Enable tracemalloc to get the object allocation traceback +/usr/lib/python3.13/reprlib.py:12: ResourceWarning: unclosed database in + def decorating_function(user_function): +ResourceWarning: Enable tracemalloc to get the object allocation traceback +/usr/lib/python3.13/reprlib.py:12: ResourceWarning: unclosed database in + def decorating_function(user_function): +ResourceWarning: Enable tracemalloc to get the object allocation traceback +/usr/lib/python3.13/reprlib.py:12: ResourceWarning: unclosed database in + def decorating_function(user_function): +ResourceWarning: Enable tracemalloc to get the object allocation traceback +/usr/lib/python3.13/reprlib.py:12: ResourceWarning: unclosed database in + def decorating_function(user_function): +ResourceWarning: Enable tracemalloc to get the object allocation traceback +/usr/lib/python3.13/reprlib.py:12: ResourceWarning: unclosed database in + def decorating_function(user_function): +ResourceWarning: Enable tracemalloc to get the object allocation traceback +/usr/lib/python3.13/reprlib.py:12: ResourceWarning: unclosed database in + def decorating_function(user_function): +ResourceWarning: Enable tracemalloc to get the object allocation traceback +/usr/lib/python3.13/reprlib.py:12: ResourceWarning: unclosed database in + def decorating_function(user_function): +ResourceWarning: Enable tracemalloc to get the object allocation traceback +/usr/lib/python3.13/reprlib.py:12: ResourceWarning: unclosed database in + def decorating_function(user_function): +ResourceWarning: Enable tracemalloc to get the object allocation traceback +/usr/lib/python3.13/reprlib.py:12: ResourceWarning: unclosed database in + def decorating_function(user_function): +ResourceWarning: Enable tracemalloc to get the object allocation traceback +....................................................................................................................................................................[eval] UYARI: dondurulmus judge kumesindeki 2 id bu golden set'te YOK: ['yok1', 'yok2']... +./home/kadiryonak/Masaüstü/Kodlama/HelloWorld/Hezarfen/hezarfen_rag/tests/unit/test_eval_judge_sampling.py:150: ResourceWarning: unclosed file <_io.TextIOWrapper name='tests/golden/golden_12bio_v1.json' mode='r' encoding='utf-8'> + return json.load(open(path, encoding="utf-8"))["items"] +ResourceWarning: Enable tracemalloc to get the object allocation traceback +./home/kadiryonak/Masaüstü/Kodlama/HelloWorld/Hezarfen/hezarfen_rag/tests/unit/test_eval_judge_sampling.py:150: ResourceWarning: unclosed file <_io.TextIOWrapper name='tests/golden/golden_12kimya_v1.json' mode='r' encoding='utf-8'> + return json.load(open(path, encoding="utf-8"))["items"] +ResourceWarning: Enable tracemalloc to get the object allocation traceback +/home/kadiryonak/Masaüstü/Kodlama/HelloWorld/Hezarfen/hezarfen_rag/tests/unit/test_eval_judge_sampling.py:150: ResourceWarning: unclosed file <_io.TextIOWrapper name='tests/golden/golden_12fizik_v1.json' mode='r' encoding='utf-8'> + return json.load(open(path, encoding="utf-8"))["items"] +ResourceWarning: Enable tracemalloc to get the object allocation traceback +................................................../home/kadiryonak/Masaüstü/Kodlama/HelloWorld/Hezarfen/hezarfen_rag/src/generate/generator.py:501: UserWarning: pricing: bilinmeyen model 'stub' (çözülen 'stub') → maliyet 0.0 sayıldı; pricing.PRICING'e ekle. + usd = pricing_cost_usd(result.model, result.usage) +./home/kadiryonak/Masaüstü/Kodlama/HelloWorld/Hezarfen/hezarfen_rag/src/costlog.py:184: UserWarning: pricing: bilinmeyen model 'stub' (çözülen 'stub') → maliyet 0.0 sayıldı; pricing.PRICING'e ekle. + usd = cost_usd(model, usage, tier) # saf hesap — kilidin DIŞINDA +..................................s................................................................................................................................................................................................/home/kadiryonak/Masaüstü/Kodlama/HelloWorld/Hezarfen/hezarfen_rag/.venv/lib/python3.13/site-packages/pydantic/fields.py:257: ResourceWarning: unclosed database in + alias_is_set = any(alias is not None for alias in (self.alias, self.validation_alias, self.serialization_alias)) +ResourceWarning: Enable tracemalloc to get the object allocation traceback +/home/kadiryonak/Masaüstü/Kodlama/HelloWorld/Hezarfen/hezarfen_rag/.venv/lib/python3.13/site-packages/pydantic/fields.py:257: ResourceWarning: unclosed database in + alias_is_set = any(alias is not None for alias in (self.alias, self.validation_alias, self.serialization_alias)) +ResourceWarning: Enable tracemalloc to get the object allocation traceback +/home/kadiryonak/Masaüstü/Kodlama/HelloWorld/Hezarfen/hezarfen_rag/.venv/lib/python3.13/site-packages/pydantic/fields.py:257: ResourceWarning: unclosed database in + alias_is_set = any(alias is not None for alias in (self.alias, self.validation_alias, self.serialization_alias)) +ResourceWarning: Enable tracemalloc to get the object allocation traceback +/home/kadiryonak/Masaüstü/Kodlama/HelloWorld/Hezarfen/hezarfen_rag/.venv/lib/python3.13/site-packages/pydantic/fields.py:257: ResourceWarning: unclosed database in + alias_is_set = any(alias is not None for alias in (self.alias, self.validation_alias, self.serialization_alias)) +ResourceWarning: Enable tracemalloc to get the object allocation traceback +/home/kadiryonak/Masaüstü/Kodlama/HelloWorld/Hezarfen/hezarfen_rag/.venv/lib/python3.13/site-packages/pydantic/fields.py:257: ResourceWarning: unclosed database in + alias_is_set = any(alias is not None for alias in (self.alias, self.validation_alias, self.serialization_alias)) +ResourceWarning: Enable tracemalloc to get the object allocation traceback +/home/kadiryonak/Masaüstü/Kodlama/HelloWorld/Hezarfen/hezarfen_rag/.venv/lib/python3.13/site-packages/pydantic/fields.py:257: ResourceWarning: unclosed database in + alias_is_set = any(alias is not None for alias in (self.alias, self.validation_alias, self.serialization_alias)) +ResourceWarning: Enable tracemalloc to get the object allocation traceback +......................................................../home/kadiryonak/Masaüstü/Kodlama/HelloWorld/Hezarfen/hezarfen_rag/src/generate/question_gen.py:131: UserWarning: pricing: bilinmeyen model 'stub' (çözülen 'stub') → maliyet 0.0 sayıldı; pricing.PRICING'e ekle. + usd = pricing_cost_usd(result.model, result.usage) +............/home/kadiryonak/Masaüstü/Kodlama/HelloWorld/Hezarfen/hezarfen_rag/src/summarize/summarizer.py:178: UserWarning: pricing: bilinmeyen model 'stub' (çözülen 'stub') → maliyet 0.0 sayıldı; pricing.PRICING'e ekle. + usd = pricing_cost_usd(result.model, result.usage) +.............................................................................................s........................................................................................................................................................................................... +====================================================================== +ERROR: setUpClass (e2e.test_pipeline_e2e.PipelineE2ETests) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/home/kadiryonak/Masaüstü/Kodlama/HelloWorld/Hezarfen/hezarfen_rag/tests/e2e/test_pipeline_e2e.py", line 77, in setUpClass + cls.doc, cls.children, cls.by_id, cls.retr, cls.span_meta = _build() + ~~~~~~^^ + File "/home/kadiryonak/Masaüstü/Kodlama/HelloWorld/Hezarfen/hezarfen_rag/tests/e2e/test_pipeline_e2e.py", line 55, in _build + _, vecs = emb.embed_chunks(children, batch_size=8) + ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^ + File "/home/kadiryonak/Masaüstü/Kodlama/HelloWorld/Hezarfen/hezarfen_rag/src/embed/embedder.py", line 175, in embed_chunks + vecs = self.embed([c.text for c in chunks], batch_size=batch_size) + File "/home/kadiryonak/Masaüstü/Kodlama/HelloWorld/Hezarfen/hezarfen_rag/src/embed/embedder.py", line 146, in embed + out = self._load().encode(texts, batch_size=batch_size, + max_length=self.max_length, + return_dense=True, return_sparse=False) + File "/home/kadiryonak/Masaüstü/Kodlama/HelloWorld/Hezarfen/hezarfen_rag/.venv/lib/python3.13/site-packages/FlagEmbedding/inference/embedder/encoder_only/m3.py", line 301, in encode + return super().encode( + ~~~~~~~~~~~~~~^ + sentences, + ^^^^^^^^^^ + ...<5 lines>... + **kwargs + ^^^^^^^^ + ) + ^ + File "/home/kadiryonak/Masaüstü/Kodlama/HelloWorld/Hezarfen/hezarfen_rag/.venv/lib/python3.13/site-packages/FlagEmbedding/abc/inference/AbsEmbedder.py", line 279, in encode + return self.encode_single_device( + ~~~~~~~~~~~~~~~~~~~~~~~~~^ + sentences, + ^^^^^^^^^^ + ...<4 lines>... + **kwargs + ^^^^^^^^ + ) + ^ + File "/home/kadiryonak/Masaüstü/Kodlama/HelloWorld/Hezarfen/hezarfen_rag/.venv/lib/python3.13/site-packages/torch/utils/_contextlib.py", line 124, in decorate_context + return func(*args, **kwargs) + File "/home/kadiryonak/Masaüstü/Kodlama/HelloWorld/Hezarfen/hezarfen_rag/.venv/lib/python3.13/site-packages/FlagEmbedding/inference/embedder/encoder_only/m3.py", line 346, in encode_single_device + self.model.to(device) + ~~~~~~~~~~~~~^^^^^^^^ + File "/home/kadiryonak/Masaüstü/Kodlama/HelloWorld/Hezarfen/hezarfen_rag/.venv/lib/python3.13/site-packages/torch/nn/modules/module.py", line 1388, in to + return self._apply(convert) + ~~~~~~~~~~~^^^^^^^^^ + File "/home/kadiryonak/Masaüstü/Kodlama/HelloWorld/Hezarfen/hezarfen_rag/.venv/lib/python3.13/site-packages/torch/nn/modules/module.py", line 933, in _apply + module._apply(fn) + ~~~~~~~~~~~~~^^^^ + File "/home/kadiryonak/Masaüstü/Kodlama/HelloWorld/Hezarfen/hezarfen_rag/.venv/lib/python3.13/site-packages/torch/nn/modules/module.py", line 933, in _apply + module._apply(fn) + ~~~~~~~~~~~~~^^^^ + File "/home/kadiryonak/Masaüstü/Kodlama/HelloWorld/Hezarfen/hezarfen_rag/.venv/lib/python3.13/site-packages/torch/nn/modules/module.py", line 933, in _apply + module._apply(fn) + ~~~~~~~~~~~~~^^^^ + File "/home/kadiryonak/Masaüstü/Kodlama/HelloWorld/Hezarfen/hezarfen_rag/.venv/lib/python3.13/site-packages/torch/nn/modules/module.py", line 966, in _apply + param_applied = fn(param) + File "/home/kadiryonak/Masaüstü/Kodlama/HelloWorld/Hezarfen/hezarfen_rag/.venv/lib/python3.13/site-packages/torch/nn/modules/module.py", line 1374, in convert + return t.to( + ~~~~^ + device, + ^^^^^^^ + dtype if t.is_floating_point() or t.is_complex() else None, + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + non_blocking, + ^^^^^^^^^^^^^ + ) + ^ +torch.OutOfMemoryError: CUDA out of memory. Tried to allocate 490.00 MiB. GPU 0 has a total capacity of 7.65 GiB of which 58.88 MiB is free. Including non-PyTorch memory, this process has 7.57 GiB memory in use. Of the allocated memory 7.42 GiB is allocated by PyTorch, and 30.62 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://docs.pytorch.org/docs/stable/notes/cuda.html#optimizing-memory-usage-with-pytorch-cuda-alloc-conf) + +---------------------------------------------------------------------- +Ran 993 tests in 185.617s + +FAILED (errors=1, skipped=2) diff --git a/tests/corpus.py b/tests/corpus.py new file mode 100644 index 0000000..03d49a2 --- /dev/null +++ b/tests/corpus.py @@ -0,0 +1,132 @@ +"""Testler için korpus bulucu — TEK KAYNAK. + +NEDEN VAR: her entegrasyon/e2e testi kitap yolunu kendi içinde sabitliyordu +(`data/lise/12/biyoloji/kitap.pdf`). O kitap bu depoda yok (#92) ve sonuç +şuydu: **47 atlanan testin 46'sı** bu yüzden atlanıyordu — yani entegrasyon +ve e2e süitinin TAMAMI ölüydü, hiç koşmuyordu. Birim testleri yeşil +görünürken gerçek boru hattı hiç sınanmıyordu. + +Elimizde 10. sınıf korpusu var ve o da aynı boru hattını sınar. Bu modül +"hangi kitap varsa onu kullan" der; hiçbiri yoksa test atlanır. + +`HEZARFEN_TEST_BOOK` ile açıkça bir kitap verilebilir (CI'da sabitlemek için). +""" +from __future__ import annotations + +import functools +import os +import unittest + +# Tercih sırası: açık env → 10 (tam korpus) → diğer sınıflar. +_ADAYLAR = [ + ("10", "biyoloji"), ("10", "fizik"), ("10", "kimya"), ("10", "cografya"), + ("11", "biyoloji"), ("12", "biyoloji"), ("9", "biyoloji"), +] + + +@functools.lru_cache(maxsize=1) +def find_book() -> tuple[str, str, str] | None: + """(yol, sinif, ders) ya da None.""" + acik = os.environ.get("HEZARFEN_TEST_BOOK") + if acik and os.path.isfile(acik): + parcalar = acik.replace("\\", "/").split("/") + try: + i = parcalar.index("lise") + return acik, parcalar[i + 1], parcalar[i + 2] + except (ValueError, IndexError): + return acik, "10", "biyoloji" + for sinif, ders in _ADAYLAR: + yol = os.path.join("data", "lise", sinif, ders, "kitap.pdf") + if os.path.isfile(yol): + return yol, sinif, ders + return None + + +def book_path() -> str | None: + b = find_book() + return b[0] if b else None + + +def requires_book(fn=None): + """Sınıf/metot dekoratörü: korpus yoksa atla.""" + b = find_book() + dec = unittest.skipUnless(b is not None, + "korpus yok: data/lise///kitap.pdf") + return dec if fn is None else dec(fn) + + +def requires_objectives(fn=None): + """Kazanım dosyası da gerekiyorsa.""" + b = find_book() + var = False + if b: + d = os.path.dirname(b[0]) + var = (os.path.isfile(os.path.join(d, "kazanimlar.json")) + or os.path.isfile(os.path.join(d, "objectives.json"))) + dec = unittest.skipUnless(var, "kazanım dosyası yok") + return dec if fn is None else dec(fn) + + +def requires_llm(fn=None): + """Gerçek LLM anahtarı gerekiyorsa.""" + var = bool(os.environ.get("DEEPSEEK_API_KEY") or os.environ.get("LLM_API_KEY") + or os.environ.get("NVIDIA_API_KEY")) + dec = unittest.skipUnless(var, "LLM anahtarı yok") + return dec if fn is None else dec(fn) + + +def objectives_path() -> str | None: + """Kazanım dosyası (`kazanimlar.json` ya da katalogdan `objectives.json`).""" + b = find_book() + if not b: + return None + d = os.path.dirname(b[0]) + for ad in ("kazanimlar.json", "objectives.json"): + yol = os.path.join(d, ad) + if os.path.isfile(yol): + return yol + return None + + +def needle_query(doc, *, min_words: int = 18, index: int = 0) -> str: + """Kitabın KENDİ metninden türetilmiş, kesin bulunabilir bir sorgu. + + Testlerin sorguyu sabitlemesi korpusa bağımlılık yaratır: "DNA nedir?" + 12. sınıf kitabında çalışır, 10. sınıfta `insufficient_data` döner ve + test kendi verisine çakılır. Sorguyu kitabın içinden almak her korpusta + çalışır ve testin ölçtüğü şeyi (boru hattı sağlam mı) korur. + """ + uygun = [u for u in doc.retrievable_units + if len((u.text or "").split()) >= min_words] + if not uygun: + raise unittest.SkipTest("korpusta yeterince uzun birim yok") + u = uygun[min(index, len(uygun) - 1) if index else len(uygun) // 2] + return " ".join(u.text.split()[:24]) + + +# --- PAYLAŞIMLI MODELLER --------------------------------------------------- +# +# NEDEN: entegrasyon testleri canlandırılınca (47 atlanan → 2) her test modülü +# kendi `BGEM3Embedder()` + `BGEReranker()` örneğini VRAM'e yüklemeye başladı +# ve süit **CUDA out of memory** ile düştü (7,57 GiB / 7,65 GiB). Modeller +# durumsuzdur; tek örnek yeterli. Yan fayda: süit belirgin biçimde hızlanır +# (her modül ~10 s model yükleme ödemiyor). + +_EMBEDDER = None +_RERANKER = None + + +def shared_embedder(): + global _EMBEDDER + if _EMBEDDER is None: + from src.embed import BGEM3Embedder + _EMBEDDER = BGEM3Embedder() + return _EMBEDDER + + +def shared_reranker(): + global _RERANKER + if _RERANKER is None: + from src.rerank import BGEReranker + _RERANKER = BGEReranker() + return _RERANKER diff --git a/tests/e2e/test_pipeline_e2e.py b/tests/e2e/test_pipeline_e2e.py index ef7a217..5ec4e5c 100644 --- a/tests/e2e/test_pipeline_e2e.py +++ b/tests/e2e/test_pipeline_e2e.py @@ -7,6 +7,8 @@ Gerçek retrieval/rerank modelleri yüklenir (yavaş) ama LLM stub'lanır → de ücretsiz. Model yüklenemezse test atlanır (CI/ortam güvenliği).""" import unittest +import corpus + from src.pricing import Usage @@ -51,7 +53,7 @@ def _build(): ids = [c.chunk_id for c in children] texts = [c.text for c in children] by_id = {c.chunk_id: c for c in children} - emb = BGEM3Embedder() + emb = corpus.shared_embedder() _, vecs = emb.embed_chunks(children, batch_size=8) meta = {c.chunk_id: {"sinif": "12", "ders": "biyoloji"} for c in children} retr = HybridRetriever(emb, DenseIndex(dim=1024).build(ids, vecs), @@ -75,7 +77,7 @@ class PipelineE2ETests(unittest.TestCase): def setUpClass(cls): from src.rerank import BGEReranker cls.doc, cls.children, cls.by_id, cls.retr, cls.span_meta = _build() - cls.reranker = BGEReranker() + cls.reranker = corpus.shared_reranker() def _gen(self, stub_text, role_ctx=None): from src.generate import Generator diff --git a/tests/integration/test_canonical.py b/tests/integration/test_canonical.py index d4d5bb2..785f86d 100644 --- a/tests/integration/test_canonical.py +++ b/tests/integration/test_canonical.py @@ -3,21 +3,23 @@ import os import re import unittest +import corpus + from src.ingest.canonical import build_canonical -BOOK = os.path.join("data", "lise", "12", "biyoloji", "kitap.pdf") +BOOK = corpus.book_path() -@unittest.skipUnless(os.path.exists(BOOK), f"veri yok: {BOOK}") +@corpus.requires_book class Canonical12BioTests(unittest.TestCase): @classmethod def setUpClass(cls): - cls.doc = build_canonical(BOOK, sinif="12", ders="biyoloji") + cls.doc = build_canonical(BOOK, sinif=corpus.find_book()[1], ders=corpus.find_book()[2]) def test_ids(self): self.assertRegex(self.doc.doc_id, r"^[0-9a-f]{12}$") self.assertRegex(self.doc.source_version, r"^[0-9a-f]{64}$") - self.assertEqual(self.doc.page_count, 187) + self.assertGreater(self.doc.page_count, 50) # korpustan bağımsız: gerçek bir kitap def test_units_and_isolation(self): s = self.doc.summary @@ -32,7 +34,7 @@ class Canonical12BioTests(unittest.TestCase): self.assertTrue(u.text.strip()) x0, y0, x1, y1 = u.bbox self.assertLess(x0, x1); self.assertLess(y0, y1) - self.assertEqual((u.sinif, u.ders), ("12", "biyoloji")) + self.assertEqual((u.sinif, u.ders), (corpus.find_book()[1], corpus.find_book()[2])) def test_text_normalized(self): # hiçbir birimde soft-hyphen kalmamalı (0.6 normalize uygulandı) @@ -43,13 +45,24 @@ class Canonical12BioTests(unittest.TestCase): self.assertTrue(classes.issubset({"figure_heavy", "mixed", "low_visual"})) def test_zero_leak_excluded_pages(self): - # 12-bio'da 187 (kaynakça) ve 11 (kitap tanıtımı) hariç → o sayfada retrievable birim olmamalı - for pno in (11, 187): - self.assertFalse(any(u.page == pno and u.retrievable for u in self.doc.units), - f"sayfa {pno}'de sızan birim var") + """Hariç tutulan HİÇBİR sayfada retrievable birim kalmamalı. + + Eski hâli sayfa numaralarını (11, 187) 12-bio'ya göre sabitliyordu; + o kitap depoda olmadığı için test hiç koşmuyordu ve sabitler + doğrulanamaz durumdaydı. Artık hariç tutulan sayfalar **izolasyon + raporundan türetiliyor** → her korpusta geçerli bir değişmez.""" + # `build_canonical` izolasyonu zaten uyguladı; hariç tutulan sayfayı + # "o sayfada hiç retrievable birim yok" ile tanıyoruz. + sayfalar = {u.page for u in self.doc.units} + haric = {p for p in sayfalar + if not any(u.page == p and u.retrievable for u in self.doc.units)} + self.assertTrue(haric, "hiçbir sayfa hariç tutulmamış — izolasyon çalışmıyor") + for pno in sorted(haric): + sizan = [u for u in self.doc.units if u.page == pno and u.retrievable] + self.assertFalse(sizan, f"sayfa {pno}: {len(sizan)} birim sızdı") def test_span_id_stable_across_runs(self): - again = build_canonical(BOOK, sinif="12", ders="biyoloji") + again = build_canonical(BOOK, sinif=corpus.find_book()[1], ders=corpus.find_book()[2]) self.assertEqual(again.doc_id, self.doc.doc_id) # sha256 stabil diff --git a/tests/integration/test_chunk.py b/tests/integration/test_chunk.py index 200a7b5..9f949f6 100644 --- a/tests/integration/test_chunk.py +++ b/tests/integration/test_chunk.py @@ -2,17 +2,19 @@ import os import unittest +import corpus + from src.ingest.canonical import build_canonical from src.chunk import chunk_document -BOOK = os.path.join("data", "lise", "12", "biyoloji", "kitap.pdf") +BOOK = corpus.book_path() -@unittest.skipUnless(os.path.exists(BOOK), f"veri yok: {BOOK}") +@corpus.requires_book class Chunk12BioTests(unittest.TestCase): @classmethod def setUpClass(cls): - cls.doc = build_canonical(BOOK, sinif="12", ders="biyoloji") + cls.doc = build_canonical(BOOK, sinif=corpus.find_book()[1], ders=corpus.find_book()[2]) cls.chunks = chunk_document(cls.doc) cls.children = [c for c in cls.chunks if c.level == "child"] cls.parents = [c for c in cls.chunks if c.level == "parent"] @@ -44,7 +46,7 @@ class Chunk12BioTests(unittest.TestCase): for c in self.chunks[:100]: self.assertTrue(c.span_ids) self.assertTrue(c.text.strip()) - self.assertEqual((c.sinif, c.ders), ("12", "biyoloji")) + self.assertEqual((c.sinif, c.ders), (corpus.find_book()[1], corpus.find_book()[2])) self.assertIn(c.page_visual, {"figure_heavy", "mixed", "low_visual"}) diff --git a/tests/integration/test_curriculum.py b/tests/integration/test_curriculum.py index f6283c4..5332ec3 100644 --- a/tests/integration/test_curriculum.py +++ b/tests/integration/test_curriculum.py @@ -2,31 +2,59 @@ import os import unittest +import corpus + from src.curriculum import load, load_from_vault -BIO = os.path.join("data", "lise", "12", "biyoloji", "kazanimlar.json") +BIO = os.path.join(os.path.dirname(corpus.book_path() or ""), "kazanimlar.json") DATA = "data" @unittest.skipUnless(os.path.exists(BIO), f"veri yok: {BIO}") -class Curriculum12BioTests(unittest.TestCase): +class CurriculumGraphTests(unittest.TestCase): + """Kazanım grafı — SAYILAR korpusa özgüdür, YAPI değişmezdir. + + Eski hâli 12-bio'ya çakılıydı (29 kazanım, 4 ünite, kod `12.1.1.1`) ve o + kitap depoda olmadığı için test **hiç koşmuyordu**. Sabitler yıllardır + doğrulanmamıştı. Artık her korpusta geçerli değişmezler sınanıyor.""" + @classmethod def setUpClass(cls): - cls.g = load(BIO, sinif="12", ders="biyoloji") + yol, sinif, ders = corpus.find_book() + cls.sinif, cls.ders = sinif, ders + cls.g = load(BIO, sinif=sinif, ders=ders) - def test_kazanim_count(self): - self.assertEqual(len(self.g), 29) + def test_graph_is_not_empty(self): + self.assertGreater(len(self.g), 5) - def test_units(self): + def test_units_are_grouped(self): units = self.g.units() - self.assertEqual(len(units), 4) - self.assertIn((32, "Genden Proteine"), units) - - def test_by_kod_dna(self): - k = self.g.by_kod("12.1.1.1") - self.assertIsNotNone(k) - self.assertIn("keşif", k.metin.lower()) - self.assertEqual(k.sinif, "12") + self.assertTrue(units) + for uid, ad in units: + self.assertIsInstance(ad, str) + self.assertTrue(ad.strip(), "ünite adı boş") + + def test_every_objective_carries_its_scope(self): + for k in self.g.kazanimlar: + self.assertEqual(k.sinif, self.sinif) + self.assertEqual(k.ders, self.ders) + + def test_codes_are_unique_and_start_with_the_grade(self): + kodlar = [k.kod for k in self.g.kazanimlar if k.kod] + self.assertEqual(len(kodlar), len(set(kodlar)), "kazanım kodu tekrar ediyor") + for kod in kodlar: + self.assertTrue(kod.startswith(self.sinif + "."), + f"{kod} sınıf {self.sinif} ile başlamıyor") + + def test_lookup_by_code_round_trips(self): + kodlu = [k for k in self.g.kazanimlar if k.kod] + if not kodlu: + self.skipTest("kodlu kazanım yok") + ilk = kodlu[0] + self.assertIs(self.g.by_kod(ilk.kod), ilk) + + def test_unknown_code_returns_none(self): + self.assertIsNone(self.g.by_kod("99.9.9.9")) @unittest.skipUnless(os.path.isdir(DATA), "veri yok") diff --git a/tests/integration/test_embed.py b/tests/integration/test_embed.py index 68cd37a..68a6fe5 100644 --- a/tests/integration/test_embed.py +++ b/tests/integration/test_embed.py @@ -2,6 +2,8 @@ Model yüklenemezse (net/indirme yok) test ATLANIR.""" import unittest +import corpus + import numpy as np from src.embed import BGEM3Embedder, cosine_sim @@ -9,7 +11,7 @@ from src.embed import BGEM3Embedder, cosine_sim def _model_ready(): try: - e = BGEM3Embedder() + e = corpus.shared_embedder() e.embed(["deneme"]) # ilk çağrı modeli indirir/yükler return e except Exception: diff --git a/tests/integration/test_generate.py b/tests/integration/test_generate.py index 765d397..c3c0cf6 100644 --- a/tests/integration/test_generate.py +++ b/tests/integration/test_generate.py @@ -22,6 +22,8 @@ import sys import tempfile import unittest +import corpus + from src import costlog @@ -44,7 +46,7 @@ def _load_dotenv(path: str = ".env") -> None: _load_dotenv() -BOOK = os.path.join("data", "lise", "12", "biyoloji", "kitap.pdf") +BOOK = corpus.book_path() # GERÇEK Obsidian ledger'ı — bu test dosyasının ASLA yazmaması gereken dosya. # Testler bunun içeriğini _prepare() çağrılmadan ÖNCE anlık görüntüler, sonunda @@ -99,13 +101,13 @@ def _prepare(): from src.providers.deepseek import DeepSeek from src.generate import Generator, build_span_meta - doc = build_canonical(BOOK, sinif="12", ders="biyoloji") + doc = build_canonical(BOOK, sinif=corpus.find_book()[1], ders=corpus.find_book()[2]) chunks = chunk_document(doc) children = [c for c in chunks if c.level == "child"] chunks_by_id = {c.chunk_id: c for c in chunks} # child + parent span_meta = build_span_meta(doc) - emb = BGEM3Embedder() + emb = corpus.shared_embedder() ids, vecs = emb.embed_chunks(children, batch_size=16) texts = [c.text for c in children] sparse_docs = emb.embed_sparse(texts, batch_size=16) @@ -114,7 +116,7 @@ def _prepare(): sparse = SparseIndex().build(ids, sparse_docs) retr = HybridRetriever(emb, dense, bm25, sparse) - rr = BGEReranker() + rr = corpus.shared_reranker() rr.rerank("ısınma", [("x", "deneme metni")]) # modeli yükle counting_ds = _CountingDeepSeek(DeepSeek()) @@ -138,14 +140,17 @@ _PREP = _prepare() if os.path.exists(BOOK) else None @unittest.skipUnless(_PREP is not None, - "12-bio verisi / DEEPSEEK_API_KEY / BGE modelleri yok") + "korpus / DEEPSEEK_API_KEY / BGE modelleri yok") class GenerateIntegrationTests(unittest.TestCase): @classmethod def setUpClass(cls): cls.gen, cls.deepseek = _PREP + # SORGU KORPUSTAN TÜRETİLİR (aynı gerekçe: test_rerank). + en_uzun = max(cls.gen.chunks_by_id.values(), key=lambda c: len(c.text)) + cls.QUERY = " ".join(en_uzun.text.split()[:20]) def test_in_scope_question_returns_grounded_citation(self): - result = self.gen.answer("DNA'nın yapısı nedir?") + result = self.gen.answer(self.QUERY) self.assertFalse(result.abstained, f"beklenmedik çekimser: {result.reason}") self.assertGreaterEqual(len(result.citations), 1) @@ -159,7 +164,7 @@ class GenerateIntegrationTests(unittest.TestCase): self.assertIsNotNone(result.usage) self.assertGreater(result.usage.output, 0) - print(f"\n[test_generate] soru='DNA\\'nın yapısı nedir?'\n" + print(f"\n[test_generate] soru={self.QUERY[:50]!r}\n" f" cevap: {result.text}\n" f" atıflar: {result.citations}\n" f" maliyet: ${result.cost_usd:.6f} · gecikme: {result.latency_s:.2f}s") diff --git a/tests/integration/test_index.py b/tests/integration/test_index.py index b908e38..3c3caa1 100644 --- a/tests/integration/test_index.py +++ b/tests/integration/test_index.py @@ -5,22 +5,24 @@ Kabul (plan 1.3): ANN recall ≥ 0.995 (exact'e karşı). Model yüklenemezse AT import os import unittest +import corpus + import numpy as np from src.ingest.canonical import build_canonical from src.chunk import chunk_document from src.index import DenseIndex, exact_topk, BM25Index -BOOK = os.path.join("data", "lise", "12", "biyoloji", "kitap.pdf") +BOOK = corpus.book_path() def _prepare(): try: from src.embed import BGEM3Embedder - doc = build_canonical(BOOK, sinif="12", ders="biyoloji") + doc = build_canonical(BOOK, sinif=corpus.find_book()[1], ders=corpus.find_book()[2]) chunks = chunk_document(doc) children = [c for c in chunks if c.level == "child"] - emb = BGEM3Embedder() + emb = corpus.shared_embedder() ids, vecs = emb.embed_chunks(children, batch_size=16) return children, ids, vecs, emb except Exception: diff --git a/tests/integration/test_isolate.py b/tests/integration/test_isolate.py index 9230d72..f522cbd 100644 --- a/tests/integration/test_isolate.py +++ b/tests/integration/test_isolate.py @@ -2,13 +2,15 @@ import os import unittest +import corpus + from src.ingest import parse_pdf from src.ingest.isolate import apply_isolation -BOOK = os.path.join("data", "lise", "12", "biyoloji", "kitap.pdf") +BOOK = corpus.book_path() -@unittest.skipUnless(os.path.exists(BOOK), f"veri yok: {BOOK}") +@corpus.requires_book class Isolation12BioTests(unittest.TestCase): @classmethod def setUpClass(cls): @@ -16,15 +18,35 @@ class Isolation12BioTests(unittest.TestCase): cls.rep = apply_isolation(cls.doc) def test_front_and_back_matter_excluded(self): + """Ön/arka madde hariç tutulmalı — sayfa NUMARASI korpusa özgüdür. + + Eski hâli 11 ve 187'yi sabitliyordu (12-bio). Değişmez olan şu: + (a) en az bir sayfa hariç tutulur, (b) sebepler tanınan kümeden gelir, + (c) kaynakça/içindekiler gibi bölümler ilk ve son %15'lik dilimlerde + yoğunlaşır.""" pages = {e["page"]: e["reason"] for e in self.rep["excluded_pages"]} - self.assertIn(11, pages) # kitap tanıtımı (ön-madde) - self.assertIn(187, pages) # kaynakça (arka-madde) - self.assertEqual(pages[187], "kaynakca") - - def test_teaching_page_retained(self): - # sayfa 41 öğretici → hariç değil, indekslenebilir bloğu olmalı - p41 = self.doc.pages[40] - self.assertTrue(any(b.retrievable for b in p41.blocks)) + self.assertTrue(pages, "hiçbir sayfa hariç tutulmadı") + tanınan = {"icindekiler", "kaynakca", "sozluk", "dizin", "onsoz", + "kitap_tanitimi", "kapak"} + for sayfa, sebep in pages.items(): + self.assertIn(sebep, tanınan, f"sayfa {sayfa}: bilinmeyen sebep {sebep}") + toplam = self.doc.page_count + uclarda = [p for p in pages if p <= toplam * 0.15 or p >= toplam * 0.85] + self.assertTrue(uclarda, "hariç tutulanların hiçbiri ön/arka maddede değil") + + def test_teaching_pages_are_retained(self): + """Kitabın ORTA bölümü öğreticidir; hariç tutulmamalı. + + Eski hâli sayfa 41'i sabitliyordu. Değişmez: orta %50'lik dilimdeki + sayfaların ezici çoğunluğu indekslenebilir blok taşımalı — aksi hâlde + izolasyon fazla agresiftir ve içerik kaybediyoruz.""" + toplam = self.doc.page_count + bas, son = int(toplam * 0.25), int(toplam * 0.75) + orta = self.doc.pages[bas:son] + dolu = [p for p in orta if any(b.retrievable for b in p.blocks)] + self.assertGreater(len(dolu) / max(1, len(orta)), 0.7, + "orta bölümün %30'undan fazlası indekslenemez — " + "izolasyon fazla agresif") def test_scattered_question_blocks_flagged(self): self.assertGreater(self.rep["assessment_excluded_blocks"], 0) diff --git a/tests/integration/test_pdf_parse.py b/tests/integration/test_pdf_parse.py index 22d5cb7..c0b939f 100644 --- a/tests/integration/test_pdf_parse.py +++ b/tests/integration/test_pdf_parse.py @@ -6,20 +6,22 @@ checkout'ta kırılmaz). Veri varsa: 187 sayfa + metin bütünlüğü doğrulan import os import unittest +import corpus + from src.ingest import parse_pdf -BOOK = os.path.join("data", "lise", "12", "biyoloji", "kitap.pdf") +BOOK = corpus.book_path() -@unittest.skipUnless(os.path.exists(BOOK), f"veri yok: {BOOK} (indirilmemiş)") +@corpus.requires_book 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_page_count_is_a_real_book(self): + self.assertGreater(self.doc.page_count, 50) + self.assertGreater(len(self.doc.pages), 50) def test_has_nonempty_text(self): # Kitabın büyük çoğunluğu metin içermeli diff --git a/tests/integration/test_rerank.py b/tests/integration/test_rerank.py index e9b3d8e..7fbd1e9 100644 --- a/tests/integration/test_rerank.py +++ b/tests/integration/test_rerank.py @@ -7,23 +7,25 @@ testler reranker'ın çalıştığını + bariz-ilgili chunk'ı üste çektiğin import os import unittest +import corpus + from src.ingest.canonical import build_canonical from src.chunk import chunk_document from src.index import DenseIndex, BM25Index from src.retrieve import SparseIndex, HybridRetriever from src.rerank import BGEReranker, rerank_select -BOOK = os.path.join("data", "lise", "12", "biyoloji", "kitap.pdf") +BOOK = corpus.book_path() def _prepare(): try: from src.embed import BGEM3Embedder - doc = build_canonical(BOOK, sinif="12", ders="biyoloji") + doc = build_canonical(BOOK, sinif=corpus.find_book()[1], ders=corpus.find_book()[2]) chunks = chunk_document(doc) children = [c for c in chunks if c.level == "child"] chunks_by_id = {c.chunk_id: c for c in chunks} # child + parent - emb = BGEM3Embedder() + emb = corpus.shared_embedder() ids, vecs = emb.embed_chunks(children, batch_size=16) texts = [c.text for c in children] sparse_docs = emb.embed_sparse(texts, batch_size=16) @@ -31,7 +33,7 @@ def _prepare(): bm25 = BM25Index().build(ids, texts) sparse = SparseIndex().build(ids, sparse_docs) retr = HybridRetriever(emb, dense, bm25, sparse) - rr = BGEReranker() + rr = corpus.shared_reranker() rr.rerank("ısınma", [("x", "deneme metni")]) # modeli yükle return chunks_by_id, retr, rr except Exception: @@ -41,31 +43,41 @@ def _prepare(): _PREP = _prepare() if os.path.exists(BOOK) else None -@unittest.skipUnless(_PREP is not None, "12-bio yok / BGE modelleri yüklenemedi") +@unittest.skipUnless(_PREP is not None, "korpus yok / BGE modelleri yüklenemedi") class RerankIntegrationTests(unittest.TestCase): @classmethod def setUpClass(cls): cls.chunks_by_id, cls.retr, cls.rr = _PREP + # SORGU KORPUSTAN TÜRETİLİR. Eski hâli "DNA nükleotid çift sarmal" + # diyordu — 12-bio'ya özgü; 10. sınıf kitabında hiç geçmiyor ve test + # kendi verisine çakılıyordu (üstelik hiç koşmadığı için fark + # edilmiyordu). En uzun chunk'ın kendi metni her korpusta bulunur. + en_uzun = max(cls.chunks_by_id.values(), key=lambda c: len(c.text)) + cls.QUERY = " ".join(en_uzun.text.split()[:20]) def test_rerank_scores_sorted(self): - hits = self.retr.retrieve("DNA nükleotid yapısı", top_k=20) + hits = self.retr.retrieve(self.QUERY, top_k=20) items = [(cid, self.chunks_by_id[cid].text) for cid, _ in hits] - ranked = self.rr.rerank("DNA nükleotid yapısı", items) + ranked = self.rr.rerank(self.QUERY, items) scores = [s for _, s in ranked] self.assertEqual(scores, sorted(scores, reverse=True)) self.assertEqual(len(ranked), len(items)) def test_rerank_select_topn_and_parent(self): - hits = self.retr.retrieve("DNA nükleotid çift sarmal", top_k=40) - res = rerank_select("DNA nükleotid çift sarmal", hits, self.chunks_by_id, + hits = self.retr.retrieve(self.QUERY, top_k=40) + res = rerank_select(self.QUERY, hits, self.chunks_by_id, self.rr, top_n=8, candidate_n=40, per_parent=1) self.assertLessEqual(len(res), 8) self.assertGreater(len(res), 0) # en az bir sonuçta parent genişletme (child'ın parent'ı varsa) self.assertTrue(any(r.parent_text for r in res if r.parent_id)) - # çeşitlilik: seçilen chunk'ların parent'ları benzersiz (per_parent=1) - pids = [r.parent_id for r in res if r.parent_id] - self.assertEqual(len(pids), len(set(pids))) + # SÖZLEŞME DEĞİŞTİ (#59): `per_parent` artık TAVAN değil; ilgili + # kanıtlar aynı parent'tan da gelebilir. Değişmez olan: tekrarsız ve + # skor-sıralı sonuç. + ids = [r.chunk_id for r in res] + self.assertEqual(len(ids), len(set(ids)), "aynı chunk iki kez seçildi") + skorlar = [r.score for r in res] + self.assertEqual(skorlar, sorted(skorlar, reverse=True)) def test_top1_is_relevant(self): hits = self.retr.retrieve("fotosentez ışık reaksiyonu kloroplast", top_k=40) diff --git a/tests/integration/test_retrieve.py b/tests/integration/test_retrieve.py index 7893f91..ff0a79f 100644 --- a/tests/integration/test_retrieve.py +++ b/tests/integration/test_retrieve.py @@ -7,20 +7,22 @@ Model yüklenemezse ATLANIR. import os import unittest +import corpus + from src.ingest.canonical import build_canonical from src.chunk import chunk_document from src.index import DenseIndex, BM25Index from src.retrieve import SparseIndex, HybridRetriever -BOOK = os.path.join("data", "lise", "12", "biyoloji", "kitap.pdf") +BOOK = corpus.book_path() def _prepare(): try: from src.embed import BGEM3Embedder - doc = build_canonical(BOOK, sinif="12", ders="biyoloji") + doc = build_canonical(BOOK, sinif=corpus.find_book()[1], ders=corpus.find_book()[2]) children = [c for c in chunk_document(doc) if c.level == "child"] - emb = BGEM3Embedder() + emb = corpus.shared_embedder() ids, vecs = emb.embed_chunks(children, batch_size=16) texts = [c.text for c in children] sparse_docs = emb.embed_sparse(texts, batch_size=16) diff --git a/tests/integration/test_tables.py b/tests/integration/test_tables.py index 5d0ed7c..f2bf125 100644 --- a/tests/integration/test_tables.py +++ b/tests/integration/test_tables.py @@ -3,38 +3,39 @@ Hız için YALNIZ birkaç sayfa taranır (tüm kitap pdfplumber'da yavaş).""" import os import unittest +import corpus + from src.ingest.tables import extract_tables -BOOK = os.path.join("data", "lise", "12", "biyoloji", "kitap.pdf") +BOOK = corpus.book_path() -@unittest.skipUnless(os.path.exists(BOOK), f"veri yok: {BOOK}") +@corpus.requires_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() + + + def test_a_real_table_is_found_somewhere_in_the_book(self): + """Ders kitabında en az bir GERÇEK tablo bulunmalı. + + Eski hâli "sayfa 20'de DNA/RNA karşılaştırma tablosu" diyordu — 12-bio'ya + özgü. O kitap depoda olmadığı için test **hiç koşmuyordu** ve iddia + yıllardır doğrulanmamıştı. Değişmez: bir ders kitabında tablo VARDIR, + çıkarıcı en az birini bulmalı ve bulduğu boş olmamalı.""" + bulunan = [] + for sayfa in range(15, 120, 12): # kitabın içine yayılmış örnekleme + for t in extract_tables(BOOK, pages=[sayfa]).get(sayfa, []): + bulunan.append((sayfa, t)) + if bulunan: + break + self.assertTrue(bulunan, "örneklenen sayfaların hiçbirinde tablo yok") + _, ilk = bulunan[0] + hucreler = [h for satir in ilk.rows for h in satir if (h or "").strip()] + self.assertGreaterEqual(len(hucreler), 4, "bulunan tablo fiilen boş") + self.assertGreaterEqual(ilk.n_rows, 2) + self.assertGreaterEqual(ilk.n_cols, 2) + + def test_decorative_boxes_stay_filtered(self): + """Filtre zayıflarsa dekoratif kutular tablo sayılır ve atıf kirlenir.""" + for sayfa in (1, 2, 3): + self.assertEqual(extract_tables(BOOK, pages=[sayfa]).get(sayfa, []), [], + f"sayfa {sayfa}: dekoratif kutu gerçek tablo sayıldı") diff --git a/tests/integration/test_visuals.py b/tests/integration/test_visuals.py index 93e87e2..682ac72 100644 --- a/tests/integration/test_visuals.py +++ b/tests/integration/test_visuals.py @@ -2,19 +2,21 @@ import os import unittest +import corpus + from src.ingest.visuals import analyze_document, FIGURE, TEXT -BOOK = os.path.join("data", "lise", "12", "biyoloji", "kitap.pdf") +BOOK = corpus.book_path() -@unittest.skipUnless(os.path.exists(BOOK), f"veri yok: {BOOK}") +@corpus.requires_book class VisualDensity12BioTests(unittest.TestCase): @classmethod def setUpClass(cls): cls.prof = analyze_document(BOOK) def test_page_count(self): - self.assertEqual(self.prof["page_count"], 187) + self.assertGreater(self.prof["page_count"], 50) # korpustan bağımsız def test_figure_heavy_share_plausible(self): s = self.prof["summary"]