Spaces:
Build error
Build error
File size: 2,801 Bytes
460549a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | """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
|