"""Context Optimizer — strategy-agnostic cleanup of expanded graph bundles, run once before any AssemblyStrategy sees them. Owns exactly two concerns: deduplication and noise reduction. Does NOT know what question type is being generated for — that's the Assembler's job (see context_assembler.py). Splitting these two responsibilities keeps each one simple and means no individual strategy has to reimplement deduplication. """ from dataclasses import dataclass, field from typing import Optional from app.services.graph_repository import GraphElement, GraphRelationship @dataclass class ElementBundle: """A retrieved chunk plus its connected graph elements (already expanded via GraphRepository.expand), before or after optimization.""" chunk_id: str chunk_content: str section_title: Optional[str] page_number: Optional[int] document_title: str elements: list[tuple[GraphElement, GraphRelationship]] = field(default_factory=list) def optimize_bundles(bundles: list[ElementBundle]) -> list[ElementBundle]: """Deduplicate elements sharing the same id or visual_hash across ALL bundles in one result set (the same diagram reached via two different paragraphs should never be scored, attached, or sent to generation twice), and drop near-empty OCR/caption noise.""" seen_ids: set[str] = set() seen_hashes: set[str] = set() optimized: list[ElementBundle] = [] for bundle in bundles: kept: list[tuple[GraphElement, GraphRelationship]] = [] for element, relationship in bundle.elements: if element.id in seen_ids: continue if element.visual_hash and element.visual_hash in seen_hashes: continue seen_ids.add(element.id) if element.visual_hash: seen_hashes.add(element.visual_hash) # Noise reduction: drop OCR text that's just a stray character or # two (common on low-quality diagram crops) — not useful context. if element.ocr_text and len(element.ocr_text.strip()) < 3: element.ocr_text = None # Collapse a caption that's identical to the semantic_description # (redundant — the description already says it, more fully). if element.caption and element.semantic_description and element.caption.strip() == element.semantic_description.strip(): element.caption = None kept.append((element, relationship)) optimized.append(ElementBundle( chunk_id=bundle.chunk_id, chunk_content=bundle.chunk_content, section_title=bundle.section_title, page_number=bundle.page_number, document_title=bundle.document_title, elements=kept, )) return optimized