Spaces:
Build error

File size: 6,348 Bytes
7e8cd1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
"""Context compressor: builds a compact context window under strict token caps.

Improvements (Phase 3.2, 3.3, 3.5):
  - Deduplicates near-identical chunks (n-gram similarity > 0.95 within same
    document) — keeps the higher-scored chunk only.
  - Uses actual token_count from DB instead of char-based estimate when available.
  - Hard cap at MAX_CONTEXT_TOKENS (6000) to protect against context overflow
    even when callers pass larger limits.

Dedup complexity:
  - Chunks are bucketed by document_id first.
  - Within each bucket, exact-content hashes are checked O(1) before
    computing n-gram similarity, eliminating the inner loop for true duplicates.
  - N-gram sets are pre-computed once per chunk (not once per comparison pair),
    reducing recomputation.
  - Worst-case remains O(k²) per document bucket where k = chunks per document,
    but k is typically 2–5 in practice.
"""
from __future__ import annotations

import hashlib
from typing import Optional

from app.config import get_settings
from app.services.retrieval import RetrievedChunk

# Hard cap on context tokens regardless of what caller requests
_MAX_CONTEXT_TOKENS = 6000

# Cosine similarity threshold for near-duplicate chunk removal
_DEDUP_SIMILARITY_THRESHOLD = 0.95

# Only use first N chars for n-gram dedup to avoid tokenizing huge chunks
_DEDUP_CONTENT_LIMIT = 1000


def _ngrams(text: str, n: int = 4) -> set[str]:
    """Return set of char n-grams from text (whitespace removed)."""
    t = text.replace(" ", "")
    if len(t) < n:
        return set()
    return {t[i:i + n] for i in range(len(t) - n + 1)}


def _jaccard(sa: set[str], sb: set[str]) -> float:
    if not sa or not sb:
        return 0.0
    union = len(sa | sb)
    return len(sa & sb) / union if union else 0.0


def _content_hash(content: str) -> str:
    """MD5 of first 1000 chars — fast exact-duplicate detection."""
    return hashlib.md5(content[:_DEDUP_CONTENT_LIMIT].encode("utf-8")).hexdigest()


def _deduplicate(chunks: list[RetrievedChunk]) -> list[RetrievedChunk]:
    """Remove near-identical chunks within the same document.

    Algorithm (O(k²) per document bucket, k typically 2-5):
      1. Exact-content hash check (O(1)) — removes true duplicates immediately.
      2. N-gram sets pre-computed once per chunk, not per comparison pair.
      3. Jaccard similarity on truncated content (first 1000 chars) only.
    """
    # Pre-compute n-gram sets and content hashes once per chunk
    hashes: dict[str, str] = {}
    ngram_sets: dict[str, set[str]] = {}
    for chunk in chunks:
        cid = chunk.id
        snippet = chunk.content[:_DEDUP_CONTENT_LIMIT] if chunk.content else ""
        hashes[cid] = _content_hash(snippet)
        ngram_sets[cid] = _ngrams(snippet)

    # Bucket by document_id to scope comparisons
    by_doc: dict[str, list[RetrievedChunk]] = {}
    for chunk in chunks:
        by_doc.setdefault(chunk.document_id, []).append(chunk)

    kept_ids: set[str] = set()
    result: list[RetrievedChunk] = []

    for chunk in chunks:  # preserve original ranking order
        if chunk.id in kept_ids:
            continue

        doc_bucket = by_doc.get(chunk.document_id, [])
        is_dup = False

        for kept_chunk in doc_bucket:
            if kept_chunk.id not in kept_ids:
                continue  # not kept yet — skip
            if kept_chunk.id == chunk.id:
                continue

            # Fast path: same content hash → exact duplicate
            if hashes[chunk.id] == hashes[kept_chunk.id]:
                is_dup = True
                break

            # Slow path: n-gram similarity
            if _jaccard(ngram_sets[chunk.id], ngram_sets[kept_chunk.id]) > _DEDUP_SIMILARITY_THRESHOLD:
                is_dup = True
                break

        if not is_dup:
            result.append(chunk)
            kept_ids.add(chunk.id)

    return result


class ContextCompressorService:
    """Builds a compact context window under strict token caps."""

    def __init__(self) -> None:
        settings = get_settings()
        self._chars_per_token = max(1, settings.CHARS_PER_TOKEN)

    def _token_count(self, chunk: RetrievedChunk) -> int:
        """Return actual token count from DB if available, else estimate from chars."""
        if chunk.token_count and chunk.token_count > 0:
            return chunk.token_count
        return max(1, len(chunk.content) // self._chars_per_token)

    def compress(
        self,
        *,
        chunks: list[RetrievedChunk],
        max_context_tokens: int,
        max_chunks: int,
    ) -> list[RetrievedChunk]:
        if not chunks:
            return []

        # Apply hard cap regardless of caller's request
        effective_max_tokens = min(max_context_tokens, _MAX_CONTEXT_TOKENS)
        effective_max_chunks = max(1, max_chunks)

        # Deduplicate near-identical chunks first (keeps highest-scored)
        deduped = _deduplicate(chunks)

        selected: list[RetrievedChunk] = []
        used_tokens = 0

        for chunk in deduped[: effective_max_chunks * 3]:
            if len(selected) >= effective_max_chunks:
                break

            content = chunk.content.strip()
            if not content:
                continue

            chunk_tokens = self._token_count(chunk)

            if used_tokens + chunk_tokens > effective_max_tokens:
                remaining_tokens = max(0, effective_max_tokens - used_tokens)
                remaining_chars = remaining_tokens * self._chars_per_token
                if remaining_chars < 80:
                    break
                # Trim content to fit remaining budget
                trimmed = content[:remaining_chars]
                selected.append(
                    RetrievedChunk(
                        id=chunk.id,
                        content=trimmed,
                        section_title=chunk.section_title,
                        page_number=chunk.page_number,
                        document_id=chunk.document_id,
                        document_title=chunk.document_title,
                        similarity=chunk.similarity,
                        token_count=remaining_tokens,
                    )
                )
                break

            selected.append(chunk)
            used_tokens += chunk_tokens

        return selected