Faz 5 multimodal VLM captioning iskeleti (sağlayıcı-bağımsız, zarif degradasyon) — Refs #23
Browse files at this commitd6fb062fef2ab3b96991fc89ad777840c0880aceParent: 814fe5f- feat
- Faz 5 multimodal VLM captioning iskeleti (sağlayıcı-bağımsız, zarif degradasyon) — Refs #23
4 changed files +273 -2
- src/ingest/canonical.py +15 -2
- src/ingest/visual_caption.py +81 -0
- src/providers/vlm.py +96 -0
- tests/unit/test_vlm.py +81 -0
src/ingest/canonical.pymodified+15 -2
| @@ -96,11 +96,15 @@ def units_from_parsed(doc: ParsedDoc, *, doc_id: str, sinif: str, ders: str, | |||
| 96 | 96 | ||
| 97 | 97 | ||
| 98 | def build_canonical(path: str, sinif: str, ders: str, *, | 98 | def build_canonical(path: str, sinif: str, ders: str, *, |
| 99 | - kaynak_turu: str = "ders_kitabi", ocr: bool = False) -> CanonicalDoc: | 99 | + kaynak_turu: str = "ders_kitabi", ocr: bool = False, |
| 100 | + vlm: bool = False, captioner=None) -> CanonicalDoc: | ||
| 100 | """PDF → kanonik doküman (parse + izolasyon + normalize + görsel sınıfı + metadata). | 101 | """PDF → kanonik doküman (parse + izolasyon + normalize + görsel sınıfı + metadata). |
| 101 | 102 | ||
| 102 | `ocr=True` (Faz 0.8): text-layer'ı boş taranmış/görüntü sayfalar Tesseract ile | 103 | `ocr=True` (Faz 0.8): text-layer'ı boş taranmış/görüntü sayfalar Tesseract ile |
| 103 | - OCR edilir (bkz. pdf_parse.parse_pdf). Varsayılan KAPALI.""" | 104 | + OCR edilir (bkz. pdf_parse.parse_pdf). Varsayılan KAPALI. |
| 105 | + `vlm=True` (Faz 5, #23): figure_heavy sayfalar VLM ile captionlanıp | ||
| 106 | + `kind="gorsel_aciklama"` birim olarak eklenir (bkz. visual_caption.py; captioner | ||
| 107 | + verilmezse env'den VLMCaptioner denenir, kullanılamıyorsa zarifçe atlanır).""" | ||
| 104 | if not os.path.exists(path): | 108 | if not os.path.exists(path): |
| 105 | raise FileNotFoundError(path) | 109 | raise FileNotFoundError(path) |
| 106 | full = file_sha256(path) | 110 | full = file_sha256(path) |
| @@ -111,6 +115,15 @@ def build_canonical(path: str, sinif: str, ders: str, *, | |||
| 111 | page_visual = {pv.page: pv.klass for pv in vis["pages"]} | 115 | page_visual = {pv.page: pv.klass for pv in vis["pages"]} |
| 112 | units = units_from_parsed(parsed, doc_id=doc_id, sinif=sinif, ders=ders, | 116 | units = units_from_parsed(parsed, doc_id=doc_id, sinif=sinif, ders=ders, |
| 113 | kaynak_turu=kaynak_turu, page_visual=page_visual) | 117 | kaynak_turu=kaynak_turu, page_visual=page_visual) |
| 118 | + if vlm: | ||
| 119 | + from .visual_caption import caption_visual_units, merge_visual_units | ||
| 120 | + if captioner is None: | ||
| 121 | + from ..providers.vlm import VLMCaptioner | ||
| 122 | + captioner = VLMCaptioner() | ||
| 123 | + vunits = caption_visual_units(path, doc_id=doc_id, sinif=sinif, ders=ders, | ||
| 124 | + kaynak_turu=kaynak_turu, page_visual=page_visual, | ||
| 125 | + captioner=captioner) | ||
| 126 | + units = merge_visual_units(units, vunits) | ||
| 114 | return CanonicalDoc(source_path=path, doc_id=doc_id, source_version=full, | 127 | return CanonicalDoc(source_path=path, doc_id=doc_id, source_version=full, |
| 115 | sinif=sinif, ders=ders, kaynak_turu=kaynak_turu, | 128 | sinif=sinif, ders=ders, kaynak_turu=kaynak_turu, |
| 116 | page_count=parsed.page_count, units=units) | 129 | page_count=parsed.page_count, units=units) |
src/ingest/visual_caption.pyadded+81 -0
| @@ -0,0 +1,81 @@ | |||
| 1 | +"""Faz 5 (#23) — görsel içerik captioning ingest pass. | ||
| 2 | + | ||
| 3 | +`analyze_document` (visuals.py) figure_heavy işaretlediği sayfalar VLM ile Türkçe | ||
| 4 | +betimlenir → `kind="gorsel_aciklama"` CanonicalUnit (gerçek span_id: sayfa+bbox). | ||
| 5 | +Böylece görsel içerik mevcut metin boru hattında (embed→retrieve→rerank→generate→ | ||
| 6 | +özet) aranır/özetlenir + atıf gerçek görsele çözülür. OCR (gömülü metin) ile | ||
| 7 | +tamamlayıcıdır: OCR yazıyı, captioning ŞEKLİ/DİYAGRAMI kurtarır. | ||
| 8 | + | ||
| 9 | +Zarif degradasyon: captioner yoksa/kullanılamıyorsa boş liste (çağıran metinle devam). | ||
| 10 | +Maliyet: yalnız figure_heavy sayfa başına 1 VLM çağrısı (default-off, `build_canonical(vlm=True)`). | ||
| 11 | +""" | ||
| 12 | +from __future__ import annotations | ||
| 13 | + | ||
| 14 | +import fitz | ||
| 15 | + | ||
| 16 | +from .canonical import CanonicalUnit, make_span_id | ||
| 17 | +from ..text import normalize | ||
| 18 | + | ||
| 19 | +VISUAL_KIND = "gorsel_aciklama" | ||
| 20 | +_VISUAL_BLOCK_NO = 8000 # görsel-birim blok no (metin bloklarıyla çakışmaz) | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +def target_visual_pages(page_visual: dict[int, str], | ||
| 24 | + classes: tuple[str, ...] = ("figure_heavy",)) -> list[int]: | ||
| 25 | + """Captionlanacak sayfalar (varsayılan: yalnız figure_heavy — maliyet sınırı).""" | ||
| 26 | + return sorted(p for p, k in page_visual.items() if k in classes) | ||
| 27 | + | ||
| 28 | + | ||
| 29 | +def merge_visual_units(text_units: list[CanonicalUnit], | ||
| 30 | + visual_units: list[CanonicalUnit]) -> list[CanonicalUnit]: | ||
| 31 | + """Görsel-birimleri, her birini KENDİ sayfasının son metin biriminden SONRA | ||
| 32 | + yerleştirerek okuma sırasını korur (saf fonksiyon — VLM'siz test edilebilir). | ||
| 33 | + Metin biriminin olmadığı görsel-sayfaların birimleri sona eklenir.""" | ||
| 34 | + if not visual_units: | ||
| 35 | + return text_units | ||
| 36 | + vby: dict[int, list[CanonicalUnit]] = {} | ||
| 37 | + for v in visual_units: | ||
| 38 | + vby.setdefault(v.page, []).append(v) | ||
| 39 | + merged: list[CanonicalUnit] = [] | ||
| 40 | + for i, u in enumerate(text_units): | ||
| 41 | + merged.append(u) | ||
| 42 | + next_page = text_units[i + 1].page if i + 1 < len(text_units) else None | ||
| 43 | + if u.page != next_page and u.page in vby: | ||
| 44 | + merged.extend(vby.pop(u.page)) | ||
| 45 | + for p in sorted(vby): # metinsiz görsel-sayfalar | ||
| 46 | + merged.extend(vby[p]) | ||
| 47 | + return merged | ||
| 48 | + | ||
| 49 | + | ||
| 50 | +def caption_visual_units(path: str, *, doc_id: str, sinif: str, ders: str, | ||
| 51 | + kaynak_turu: str, page_visual: dict[int, str], captioner, | ||
| 52 | + classes: tuple[str, ...] = ("figure_heavy",), | ||
| 53 | + dpi: int = 200) -> list[CanonicalUnit]: | ||
| 54 | + """figure_heavy sayfaları VLM ile captionlar → CanonicalUnit listesi. | ||
| 55 | + captioner None/kullanılamaz ise boş liste (zarif degradasyon).""" | ||
| 56 | + if captioner is None or not captioner.available(): | ||
| 57 | + return [] | ||
| 58 | + targets = set(target_visual_pages(page_visual, classes)) | ||
| 59 | + if not targets: | ||
| 60 | + return [] | ||
| 61 | + out: list[CanonicalUnit] = [] | ||
| 62 | + doc = fitz.open(path) | ||
| 63 | + try: | ||
| 64 | + for page in doc: | ||
| 65 | + pno = page.number + 1 | ||
| 66 | + if pno not in targets: | ||
| 67 | + continue | ||
| 68 | + pix = page.get_pixmap(matrix=fitz.Matrix(dpi / 72, dpi / 72)) | ||
| 69 | + text = normalize(captioner.caption(pix.tobytes("png"))) | ||
| 70 | + if not text: | ||
| 71 | + continue | ||
| 72 | + rect = page.rect | ||
| 73 | + out.append(CanonicalUnit( | ||
| 74 | + span_id=make_span_id(doc_id, pno, _VISUAL_BLOCK_NO), | ||
| 75 | + doc_id=doc_id, sinif=sinif, ders=ders, kaynak_turu=kaynak_turu, | ||
| 76 | + page=pno, bbox=(0.0, 0.0, rect.width, rect.height), | ||
| 77 | + block_no=_VISUAL_BLOCK_NO, kind=VISUAL_KIND, text=text, | ||
| 78 | + page_visual=page_visual.get(pno, "figure_heavy"), retrieval_disi=False)) | ||
| 79 | + finally: | ||
| 80 | + doc.close() | ||
| 81 | + return out | ||
src/providers/vlm.pyadded+96 -0
| @@ -0,0 +1,96 @@ | |||
| 1 | +"""VLM (görme-dil) sağlayıcı — görsel içerik captioning (Faz 5, #23). | ||
| 2 | + | ||
| 3 | +Sağlayıcı-BAĞIMSIZ: OpenAI-uyumlu `/chat/completions` (mesajda `image_url` data-URI | ||
| 4 | +bloğu) konuşan HERHANGİ bir VLM API'sine bağlanır — base_url/model/key env'den: | ||
| 5 | + VLM_BASE_URL (ör. https://openrouter.ai/api/v1, .../gemini OpenAI-compat, https://api.openai.com/v1) | ||
| 6 | + VLM_MODEL (ör. google/gemini-2.0-flash, gpt-4o-mini, qwen/qwen2-vl-72b-instruct) | ||
| 7 | + VLM_API_KEY | ||
| 8 | + | ||
| 9 | +Karar (Kadir 2026-09-06): yerel VLM DEĞİL, API. Sağlayıcı seçimi env ile; kod aynı. | ||
| 10 | + | ||
| 11 | +Zarif degradasyon (OCR deseniyle aynı): key/base/model yoksa `available()` False, | ||
| 12 | +`caption()` "" döner (çağıran görsel-birim üretmeden devam eder). Gerçek HTTP çağrısı | ||
| 13 | +yalnız `caption()` çağrılınca yapılır — anahtarsız import + test edilebilir. | ||
| 14 | + | ||
| 15 | +Dönen maliyet: `caption_with_usage()` (text, Usage) verir → pricing.cost_usd ile $ hesaplanır. | ||
| 16 | +""" | ||
| 17 | +from __future__ import annotations | ||
| 18 | + | ||
| 19 | +import base64 | ||
| 20 | +import json | ||
| 21 | +import os | ||
| 22 | +import time | ||
| 23 | +import urllib.request | ||
| 24 | +from dataclasses import dataclass, field | ||
| 25 | + | ||
| 26 | +from ..pricing import Usage | ||
| 27 | + | ||
| 28 | +# Türkçe, öğretim-odaklı captioning yönergesi (görsel içerikten METİN çıkarımı). | ||
| 29 | +DEFAULT_CAPTION_PROMPT = ( | ||
| 30 | + "Bu bir ders kitabı sayfasındaki görsel içeriktir (şema, diyagram, grafik, " | ||
| 31 | + "resim, tablo veya sanat eseri olabilir). Görselin ÖĞRETİCİ içeriğini Türkçe, " | ||
| 32 | + "nesnel ve ayrıntılı biçimde betimle: ne gösteriyor, hangi kavramı/olayı " | ||
| 33 | + "anlatıyor, üzerindeki etiket/başlık/sayılar neler. Görselde OLMAYAN bilgi " | ||
| 34 | + "UYDURMA. Yalnız betimlemeyi yaz, ön söz ekleme." | ||
| 35 | +) | ||
| 36 | + | ||
| 37 | + | ||
| 38 | +@dataclass | ||
| 39 | +class CaptionResult: | ||
| 40 | + text: str | ||
| 41 | + usage: Usage | ||
| 42 | + model: str | ||
| 43 | + latency_s: float = 0.0 | ||
| 44 | + raw: dict = field(default_factory=dict) | ||
| 45 | + | ||
| 46 | + | ||
| 47 | +class VLMCaptioner: | ||
| 48 | + def __init__(self, model: str | None = None, base_url: str | None = None, | ||
| 49 | + api_key: str | None = None, timeout: float = 120.0): | ||
| 50 | + self.model = model or os.environ.get("VLM_MODEL") | ||
| 51 | + base = base_url or os.environ.get("VLM_BASE_URL") | ||
| 52 | + self.base_url = base.rstrip("/") if base else None | ||
| 53 | + self.timeout = timeout | ||
| 54 | + self._api_key = api_key or os.environ.get("VLM_API_KEY") | ||
| 55 | + | ||
| 56 | + def available(self) -> bool: | ||
| 57 | + """Gerçek çağrı yapılabilir mi (key + base + model tanımlı).""" | ||
| 58 | + return bool(self._api_key and self.base_url and self.model) | ||
| 59 | + | ||
| 60 | + def caption_with_usage(self, image_png: bytes, *, prompt: str = DEFAULT_CAPTION_PROMPT, | ||
| 61 | + max_tokens: int = 512, temperature: float = 0.2) -> CaptionResult: | ||
| 62 | + """PNG baytlarını VLM'e gönderip Türkçe betim + token kullanımı döndürür. | ||
| 63 | + Kullanılamıyorsa/çağrı patlarsa boş CaptionResult (zarif degradasyon).""" | ||
| 64 | + if not self.available(): | ||
| 65 | + return CaptionResult(text="", usage=Usage(), model=self.model or "", raw={}) | ||
| 66 | + try: | ||
| 67 | + b64 = base64.b64encode(image_png).decode("ascii") | ||
| 68 | + data_uri = f"data:image/png;base64,{b64}" | ||
| 69 | + payload = { | ||
| 70 | + "model": self.model, | ||
| 71 | + "messages": [{"role": "user", "content": [ | ||
| 72 | + {"type": "text", "text": prompt}, | ||
| 73 | + {"type": "image_url", "image_url": {"url": data_uri}}, | ||
| 74 | + ]}], | ||
| 75 | + "max_tokens": max_tokens, "temperature": temperature, "stream": False, | ||
| 76 | + } | ||
| 77 | + req = urllib.request.Request( | ||
| 78 | + f"{self.base_url}/chat/completions", | ||
| 79 | + data=json.dumps(payload).encode("utf-8"), | ||
| 80 | + headers={"Content-Type": "application/json", | ||
| 81 | + "Authorization": f"Bearer {self._api_key}"}, | ||
| 82 | + method="POST") | ||
| 83 | + t0 = time.time() | ||
| 84 | + with urllib.request.urlopen(req, timeout=self.timeout) as resp: | ||
| 85 | + data = json.loads(resp.read().decode("utf-8")) | ||
| 86 | + latency = time.time() - t0 | ||
| 87 | + text = (data["choices"][0]["message"]["content"] or "").strip() | ||
| 88 | + usage = Usage.from_api(data.get("usage", {})) | ||
| 89 | + return CaptionResult(text=text, usage=usage, model=self.model, | ||
| 90 | + latency_s=latency, raw=data) | ||
| 91 | + except Exception: | ||
| 92 | + return CaptionResult(text="", usage=Usage(), model=self.model or "", raw={}) | ||
| 93 | + | ||
| 94 | + def caption(self, image_png: bytes, **kw) -> str: | ||
| 95 | + """Yalnız betim metni (maliyet gerekmezse).""" | ||
| 96 | + return self.caption_with_usage(image_png, **kw).text | ||
tests/unit/test_vlm.pyadded+81 -0
| @@ -0,0 +1,81 @@ | |||
| 1 | +"""Faz 5 (#23) birim testleri — VLM captioning (hermetik: gerçek API gerektirmez). | ||
| 2 | + | ||
| 3 | +Sağlayıcı-bağımsız istemci + zarif degradasyon + saf yardımcılar | ||
| 4 | +(target_visual_pages, merge_visual_units). Gerçek VLM çağrısı DEMO'da (key gelince).""" | ||
| 5 | +import unittest | ||
| 6 | + | ||
| 7 | +from src.providers.vlm import VLMCaptioner | ||
| 8 | +from src.ingest.canonical import CanonicalUnit | ||
| 9 | +from src.ingest.visual_caption import (VISUAL_KIND, target_visual_pages, | ||
| 10 | + merge_visual_units, caption_visual_units) | ||
| 11 | + | ||
| 12 | + | ||
| 13 | +def _u(page, block_no, kind="paragraph", text="metin"): | ||
| 14 | + return CanonicalUnit( | ||
| 15 | + span_id=f"doc#{page}.{block_no}", doc_id="doc", sinif="12", ders="biyoloji", | ||
| 16 | + kaynak_turu="ders_kitabi", page=page, bbox=(0, 0, 400, 560), block_no=block_no, | ||
| 17 | + kind=kind, text=text, page_visual="mixed", retrieval_disi=False) | ||
| 18 | + | ||
| 19 | + | ||
| 20 | +class AvailabilityTests(unittest.TestCase): | ||
| 21 | + def test_unavailable_without_config(self): | ||
| 22 | + c = VLMCaptioner(model=None, base_url=None, api_key=None) | ||
| 23 | + self.assertFalse(c.available()) | ||
| 24 | + self.assertEqual(c.caption(b"\x89PNG..."), "") # HTTP yapmaz | ||
| 25 | + r = c.caption_with_usage(b"\x89PNG...") | ||
| 26 | + self.assertEqual(r.text, "") | ||
| 27 | + self.assertEqual(r.usage.total, 0) # boş Usage | ||
| 28 | + | ||
| 29 | + def test_available_with_full_config(self): | ||
| 30 | + c = VLMCaptioner(model="m", base_url="https://x/v1", api_key="k") | ||
| 31 | + self.assertTrue(c.available()) | ||
| 32 | + | ||
| 33 | + def test_partial_config_unavailable(self): | ||
| 34 | + self.assertFalse(VLMCaptioner(model="m", base_url="https://x/v1", api_key=None).available()) | ||
| 35 | + self.assertFalse(VLMCaptioner(model=None, base_url="https://x/v1", api_key="k").available()) | ||
| 36 | + | ||
| 37 | + | ||
| 38 | +class TargetPagesTests(unittest.TestCase): | ||
| 39 | + def test_only_figure_heavy(self): | ||
| 40 | + pv = {1: "low_visual", 2: "figure_heavy", 3: "mixed", 4: "figure_heavy"} | ||
| 41 | + self.assertEqual(target_visual_pages(pv), [2, 4]) | ||
| 42 | + | ||
| 43 | + def test_custom_classes(self): | ||
| 44 | + pv = {1: "low_visual", 2: "figure_heavy", 3: "mixed"} | ||
| 45 | + self.assertEqual(target_visual_pages(pv, ("figure_heavy", "mixed")), [2, 3]) | ||
| 46 | + | ||
| 47 | + | ||
| 48 | +class MergeTests(unittest.TestCase): | ||
| 49 | + def test_inserts_after_page_last_text_unit(self): | ||
| 50 | + text = [_u(1, 0), _u(1, 1), _u(2, 0)] | ||
| 51 | + vis = [_u(1, 8000, VISUAL_KIND, "gorsel1")] | ||
| 52 | + merged = merge_visual_units(text, vis) | ||
| 53 | + # sayfa 1'in son metin biriminden (block 1) SONRA, sayfa 2'den ÖNCE | ||
| 54 | + self.assertEqual([(u.page, u.block_no) for u in merged], | ||
| 55 | + [(1, 0), (1, 1), (1, 8000), (2, 0)]) | ||
| 56 | + | ||
| 57 | + def test_textless_visual_page_appended_end(self): | ||
| 58 | + text = [_u(1, 0)] | ||
| 59 | + vis = [_u(5, 8000, VISUAL_KIND, "gorsel5")] # sayfa 5'te metin yok | ||
| 60 | + merged = merge_visual_units(text, vis) | ||
| 61 | + self.assertEqual([(u.page, u.block_no) for u in merged], [(1, 0), (5, 8000)]) | ||
| 62 | + | ||
| 63 | + def test_empty_visuals_unchanged(self): | ||
| 64 | + text = [_u(1, 0), _u(1, 1)] | ||
| 65 | + self.assertIs(merge_visual_units(text, []), text) | ||
| 66 | + | ||
| 67 | + | ||
| 68 | +class GracefulCaptionPassTests(unittest.TestCase): | ||
| 69 | + def test_unavailable_captioner_no_units(self): | ||
| 70 | + # captioner None → boş; kullanılamaz captioner → boş (dosyaya bile dokunmaz) | ||
| 71 | + self.assertEqual(caption_visual_units( | ||
| 72 | + "yok.pdf", doc_id="d", sinif="12", ders="biyoloji", kaynak_turu="ders_kitabi", | ||
| 73 | + page_visual={1: "figure_heavy"}, captioner=None), []) | ||
| 74 | + c = VLMCaptioner(model=None, base_url=None, api_key=None) | ||
| 75 | + self.assertEqual(caption_visual_units( | ||
| 76 | + "yok.pdf", doc_id="d", sinif="12", ders="biyoloji", kaynak_turu="ders_kitabi", | ||
| 77 | + page_visual={1: "figure_heavy"}, captioner=c), []) | ||
| 78 | + | ||
| 79 | + | ||
| 80 | +if __name__ == "__main__": | ||
| 81 | + unittest.main() | ||