chunkscope 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- chunkscope/__init__.py +31 -0
- chunkscope/__main__.py +3 -0
- chunkscope/adapters.py +378 -0
- chunkscope/align.py +189 -0
- chunkscope/analyze.py +408 -0
- chunkscope/api.py +44 -0
- chunkscope/checks.py +155 -0
- chunkscope/cli.py +143 -0
- chunkscope/colors.py +181 -0
- chunkscope/models.py +152 -0
- chunkscope/py.typed +0 -0
- chunkscope/render.py +710 -0
- chunkscope/tokenizers.py +108 -0
- chunkscope-0.2.0.dist-info/METADATA +227 -0
- chunkscope-0.2.0.dist-info/RECORD +18 -0
- chunkscope-0.2.0.dist-info/WHEEL +4 -0
- chunkscope-0.2.0.dist-info/entry_points.txt +2 -0
- chunkscope-0.2.0.dist-info/licenses/LICENSE +21 -0
chunkscope/__init__.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""chunkscope: see how your RAG chunking splits your documents.
|
|
2
|
+
|
|
3
|
+
import chunkscope
|
|
4
|
+
chunkscope.report(chunks, source=text) # writes chunkscope-report.html
|
|
5
|
+
|
|
6
|
+
Works with plain strings and dicts, and with LangChain, LlamaIndex, Haystack,
|
|
7
|
+
Chonkie, Docling and Unstructured chunks. Everything runs locally; the report
|
|
8
|
+
is a single offline HTML file.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
__version__ = "0.2.0"
|
|
12
|
+
|
|
13
|
+
from .analyze import analyze, compare # noqa: E402
|
|
14
|
+
from .api import report, save # noqa: E402
|
|
15
|
+
from .models import Chunk, ChunkResult, DocumentResult, Issue, Report, SourceDocument # noqa: E402
|
|
16
|
+
from .render import render_html # noqa: E402
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"Chunk",
|
|
20
|
+
"ChunkResult",
|
|
21
|
+
"DocumentResult",
|
|
22
|
+
"Issue",
|
|
23
|
+
"Report",
|
|
24
|
+
"SourceDocument",
|
|
25
|
+
"__version__",
|
|
26
|
+
"analyze",
|
|
27
|
+
"compare",
|
|
28
|
+
"render_html",
|
|
29
|
+
"report",
|
|
30
|
+
"save",
|
|
31
|
+
]
|
chunkscope/__main__.py
ADDED
chunkscope/adapters.py
ADDED
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
"""Turn chunks and source documents from any framework into the generic model.
|
|
2
|
+
|
|
3
|
+
Detection uses duck typing: chunkscope never imports LangChain, LlamaIndex,
|
|
4
|
+
Haystack, Chonkie, Docling or Unstructured, so it adds no dependency and does
|
|
5
|
+
not break when one of them is missing. Pass ``framework=`` to skip detection.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Callable, Iterable, Mapping
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from .models import Chunk, SourceDocument
|
|
14
|
+
|
|
15
|
+
FRAMEWORKS = (
|
|
16
|
+
"text",
|
|
17
|
+
"dict",
|
|
18
|
+
"langchain",
|
|
19
|
+
"llamaindex",
|
|
20
|
+
"haystack",
|
|
21
|
+
"chonkie",
|
|
22
|
+
"docling",
|
|
23
|
+
"unstructured",
|
|
24
|
+
"generic",
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
_TEXT_KEYS = ("text", "content", "page_content", "chunk", "body")
|
|
28
|
+
_START_KEYS = ("start", "start_index", "start_char_idx", "start_char", "split_idx_start", "char_start")
|
|
29
|
+
_END_KEYS = ("end", "end_index", "end_char_idx", "end_char", "split_idx_end", "char_end")
|
|
30
|
+
_DOC_KEYS = ("doc_id", "document_id", "source_id", "ref_doc_id", "doc", "document", "source", "file", "filename")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
# ── Detection ─────────────────────────────────────────────────────────────────
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def detect(obj: Any) -> str:
|
|
37
|
+
"""Return the name of the framework an object most likely comes from."""
|
|
38
|
+
if isinstance(obj, str):
|
|
39
|
+
return "text"
|
|
40
|
+
if isinstance(obj, Mapping):
|
|
41
|
+
return "dict"
|
|
42
|
+
if hasattr(obj, "page_content") and hasattr(obj, "metadata"):
|
|
43
|
+
return "langchain"
|
|
44
|
+
if hasattr(obj, "start_char_idx") or (hasattr(obj, "get_content") and hasattr(obj, "node_id")):
|
|
45
|
+
return "llamaindex"
|
|
46
|
+
if hasattr(obj, "content") and hasattr(obj, "meta"):
|
|
47
|
+
return "haystack"
|
|
48
|
+
if hasattr(obj, "text") and hasattr(obj, "start_index") and hasattr(obj, "end_index"):
|
|
49
|
+
return "chonkie"
|
|
50
|
+
meta = getattr(obj, "meta", None)
|
|
51
|
+
if hasattr(obj, "text") and meta is not None and (hasattr(meta, "doc_items") or hasattr(meta, "headings")):
|
|
52
|
+
return "docling"
|
|
53
|
+
metadata = getattr(obj, "metadata", None)
|
|
54
|
+
if hasattr(obj, "text") and metadata is not None and hasattr(metadata, "to_dict"):
|
|
55
|
+
return "unstructured"
|
|
56
|
+
if hasattr(obj, "text"):
|
|
57
|
+
return "generic"
|
|
58
|
+
raise TypeError(
|
|
59
|
+
f"chunkscope cannot read a chunk of type {type(obj).__name__!r}. "
|
|
60
|
+
"Pass strings, dicts with a 'text' key, or objects from a supported framework "
|
|
61
|
+
f"({', '.join(FRAMEWORKS)})."
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
# ── Chunk adapters ────────────────────────────────────────────────────────────
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def is_scored_pair(obj: Any) -> bool:
|
|
69
|
+
"""``(chunk, score)``, as returned by LangChain's similarity_search_with_score."""
|
|
70
|
+
return (
|
|
71
|
+
isinstance(obj, tuple)
|
|
72
|
+
and len(obj) == 2
|
|
73
|
+
and isinstance(obj[1], (int, float))
|
|
74
|
+
and not isinstance(obj[1], bool)
|
|
75
|
+
and not isinstance(obj[0], (int, float))
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def unwrap_score(obj: Any) -> tuple[Any, float | None]:
|
|
80
|
+
"""Separate a retrieval score from the chunk object that carries it."""
|
|
81
|
+
if is_scored_pair(obj):
|
|
82
|
+
return obj[0], float(obj[1])
|
|
83
|
+
if not isinstance(obj, (str, Mapping)) and hasattr(obj, "node") and hasattr(obj, "score"): # LlamaIndex NodeWithScore
|
|
84
|
+
score = obj.score
|
|
85
|
+
return obj.node, float(score) if score is not None else None
|
|
86
|
+
return obj, None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def to_chunk(obj: Any, framework: str | None = None) -> tuple[Chunk, str]:
|
|
90
|
+
"""Convert one chunk object. Returns the chunk and the framework name used."""
|
|
91
|
+
obj, score = unwrap_score(obj)
|
|
92
|
+
chunk, name = _convert(obj, framework)
|
|
93
|
+
if score is not None:
|
|
94
|
+
chunk.score = score
|
|
95
|
+
return chunk, name
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _convert(obj: Any, framework: str | None) -> tuple[Chunk, str]:
|
|
99
|
+
name = framework or detect(obj)
|
|
100
|
+
try:
|
|
101
|
+
adapter = _CHUNK_ADAPTERS[name]
|
|
102
|
+
except KeyError:
|
|
103
|
+
raise ValueError(f"Unknown framework {name!r}; expected one of {', '.join(FRAMEWORKS)}") from None
|
|
104
|
+
chunk = adapter(obj)
|
|
105
|
+
if not isinstance(chunk.text, str):
|
|
106
|
+
raise TypeError(f"Chunk text must be a string, got {type(chunk.text).__name__}")
|
|
107
|
+
return chunk, name
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _from_text(obj: str) -> Chunk:
|
|
111
|
+
return Chunk(text=obj)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _from_dict(obj: Mapping[str, Any]) -> Chunk:
|
|
115
|
+
text = _first(obj, _TEXT_KEYS)
|
|
116
|
+
if text is None:
|
|
117
|
+
raise ValueError(f"Chunk dict has no text; expected one of the keys {', '.join(_TEXT_KEYS)}")
|
|
118
|
+
metadata = dict(obj.get("metadata") or obj.get("meta") or {})
|
|
119
|
+
known = set(_TEXT_KEYS) | set(_START_KEYS) | set(_END_KEYS) | {"id", "parent_id", "metadata", "meta", "score"} | set(_DOC_KEYS)
|
|
120
|
+
metadata.update({k: v for k, v in obj.items() if k not in known})
|
|
121
|
+
doc = _first(obj, _DOC_KEYS)
|
|
122
|
+
if doc is None:
|
|
123
|
+
doc = _first(metadata, ("source", "file_name", "filename", "file_path"))
|
|
124
|
+
return Chunk(
|
|
125
|
+
text=text,
|
|
126
|
+
start=_int_or_none(_first(obj, _START_KEYS)),
|
|
127
|
+
end=_int_or_none(_first(obj, _END_KEYS)),
|
|
128
|
+
id=_str_or_none(obj.get("id")),
|
|
129
|
+
parent_id=_str_or_none(obj.get("parent_id")),
|
|
130
|
+
doc_id=_str_or_none(doc),
|
|
131
|
+
metadata=metadata,
|
|
132
|
+
score=_float_or_none(obj.get("score")),
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def langchain_key(metadata: Mapping[str, Any]) -> str | None:
|
|
137
|
+
"""LangChain documents are identified by ``source`` (+ ``page`` for per-page loaders)."""
|
|
138
|
+
source = metadata.get("source")
|
|
139
|
+
if source is None:
|
|
140
|
+
return None
|
|
141
|
+
if metadata.get("page") is not None:
|
|
142
|
+
return f"{source}#page={metadata['page']}"
|
|
143
|
+
return str(source)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _from_langchain(obj: Any) -> Chunk:
|
|
147
|
+
metadata = dict(obj.metadata or {})
|
|
148
|
+
start = _int_or_none(metadata.get("start_index"))
|
|
149
|
+
return Chunk(
|
|
150
|
+
text=obj.page_content,
|
|
151
|
+
start=start,
|
|
152
|
+
end=start + len(obj.page_content) if start is not None else None,
|
|
153
|
+
id=_str_or_none(getattr(obj, "id", None)),
|
|
154
|
+
doc_id=langchain_key(metadata),
|
|
155
|
+
metadata=metadata,
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _from_llamaindex(obj: Any) -> Chunk:
|
|
160
|
+
text = obj.get_content() if hasattr(obj, "get_content") else obj.text
|
|
161
|
+
parent = None
|
|
162
|
+
relationships = getattr(obj, "relationships", None) or {}
|
|
163
|
+
for relation, info in relationships.items():
|
|
164
|
+
if "PARENT" in str(relation).upper():
|
|
165
|
+
parent = getattr(info, "node_id", None)
|
|
166
|
+
return Chunk(
|
|
167
|
+
text=text if isinstance(text, str) else str(text),
|
|
168
|
+
start=_int_or_none(getattr(obj, "start_char_idx", None)),
|
|
169
|
+
end=_int_or_none(getattr(obj, "end_char_idx", None)),
|
|
170
|
+
id=_str_or_none(getattr(obj, "node_id", None)),
|
|
171
|
+
parent_id=_str_or_none(parent),
|
|
172
|
+
doc_id=_str_or_none(_safe_attr(obj, "ref_doc_id")),
|
|
173
|
+
metadata=dict(getattr(obj, "metadata", None) or {}),
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _from_haystack(obj: Any) -> Chunk:
|
|
178
|
+
meta = dict(obj.meta or {})
|
|
179
|
+
start = _int_or_none(meta.get("split_idx_start"))
|
|
180
|
+
text = obj.content or ""
|
|
181
|
+
return Chunk(
|
|
182
|
+
text=text,
|
|
183
|
+
start=start,
|
|
184
|
+
end=start + len(text) if start is not None else None,
|
|
185
|
+
id=_str_or_none(getattr(obj, "id", None)),
|
|
186
|
+
doc_id=_str_or_none(meta.get("source_id")),
|
|
187
|
+
metadata=meta,
|
|
188
|
+
score=_float_or_none(getattr(obj, "score", None)),
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _from_chonkie(obj: Any) -> Chunk:
|
|
193
|
+
extra = getattr(obj, "metadata", None)
|
|
194
|
+
metadata: dict[str, Any] = dict(extra) if isinstance(extra, Mapping) else {}
|
|
195
|
+
for name in ("token_count", "level", "sentences", "context"):
|
|
196
|
+
value = getattr(obj, name, None)
|
|
197
|
+
if value is not None and not callable(value):
|
|
198
|
+
metadata[name] = len(value) if name == "sentences" and isinstance(value, list) else value
|
|
199
|
+
return Chunk(
|
|
200
|
+
text=obj.text,
|
|
201
|
+
start=_int_or_none(obj.start_index),
|
|
202
|
+
end=_int_or_none(obj.end_index),
|
|
203
|
+
id=_str_or_none(getattr(obj, "id", None)),
|
|
204
|
+
metadata=metadata,
|
|
205
|
+
)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _from_docling(obj: Any) -> Chunk:
|
|
209
|
+
meta = obj.meta
|
|
210
|
+
metadata: dict[str, Any] = {}
|
|
211
|
+
headings = getattr(meta, "headings", None)
|
|
212
|
+
if headings:
|
|
213
|
+
metadata["headings"] = list(headings)
|
|
214
|
+
pages: set[int] = set()
|
|
215
|
+
for item in getattr(meta, "doc_items", None) or []:
|
|
216
|
+
for prov in getattr(item, "prov", None) or []:
|
|
217
|
+
page = getattr(prov, "page_no", None)
|
|
218
|
+
if page is not None:
|
|
219
|
+
pages.add(page)
|
|
220
|
+
if pages:
|
|
221
|
+
metadata["pages"] = sorted(pages)
|
|
222
|
+
origin = getattr(meta, "origin", None)
|
|
223
|
+
filename = getattr(origin, "filename", None) if origin is not None else None
|
|
224
|
+
if filename:
|
|
225
|
+
metadata["filename"] = filename
|
|
226
|
+
return Chunk(text=obj.text, doc_id=_str_or_none(filename), metadata=metadata)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _from_unstructured(obj: Any) -> Chunk:
|
|
230
|
+
metadata = obj.metadata.to_dict() if hasattr(obj.metadata, "to_dict") else dict(obj.metadata)
|
|
231
|
+
metadata.pop("orig_elements", None) # large, serialized originals
|
|
232
|
+
category = getattr(obj, "category", None)
|
|
233
|
+
if category:
|
|
234
|
+
metadata["category"] = category
|
|
235
|
+
return Chunk(
|
|
236
|
+
text=obj.text,
|
|
237
|
+
id=_str_or_none(getattr(obj, "id", None)),
|
|
238
|
+
doc_id=_str_or_none(metadata.get("filename") or metadata.get("file_directory")),
|
|
239
|
+
metadata=metadata,
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _from_generic(obj: Any) -> Chunk:
|
|
244
|
+
metadata = getattr(obj, "metadata", None) or getattr(obj, "meta", None) or {}
|
|
245
|
+
metadata = dict(metadata) if isinstance(metadata, Mapping) else {}
|
|
246
|
+
return Chunk(
|
|
247
|
+
text=obj.text,
|
|
248
|
+
start=_int_or_none(_first_attr(obj, _START_KEYS)),
|
|
249
|
+
end=_int_or_none(_first_attr(obj, _END_KEYS)),
|
|
250
|
+
id=_str_or_none(getattr(obj, "id", None)),
|
|
251
|
+
parent_id=_str_or_none(getattr(obj, "parent_id", None)),
|
|
252
|
+
doc_id=_str_or_none(_first_attr(obj, _DOC_KEYS)),
|
|
253
|
+
metadata=metadata,
|
|
254
|
+
score=_float_or_none(getattr(obj, "score", None)),
|
|
255
|
+
)
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
_CHUNK_ADAPTERS: dict[str, Callable[[Any], Chunk]] = {
|
|
259
|
+
"text": _from_text,
|
|
260
|
+
"dict": _from_dict,
|
|
261
|
+
"langchain": _from_langchain,
|
|
262
|
+
"llamaindex": _from_llamaindex,
|
|
263
|
+
"haystack": _from_haystack,
|
|
264
|
+
"chonkie": _from_chonkie,
|
|
265
|
+
"docling": _from_docling,
|
|
266
|
+
"unstructured": _from_unstructured,
|
|
267
|
+
"generic": _from_generic,
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
# ── Source documents ──────────────────────────────────────────────────────────
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def to_sources(sources: Any) -> list[SourceDocument]:
|
|
275
|
+
"""Normalize the ``sources`` argument.
|
|
276
|
+
|
|
277
|
+
Accepts a mapping ``{id: text}``, or an iterable of strings, dicts
|
|
278
|
+
(``{"id", "text", "title"}``) or framework documents (LangChain, LlamaIndex,
|
|
279
|
+
Haystack), whose ids match the ``doc_id`` of the chunks split from them.
|
|
280
|
+
"""
|
|
281
|
+
if isinstance(sources, str):
|
|
282
|
+
return [SourceDocument(id="document", text=sources)]
|
|
283
|
+
if isinstance(sources, Mapping):
|
|
284
|
+
return [SourceDocument(id=str(key), text=_as_text(value, key)) for key, value in sources.items()]
|
|
285
|
+
if not isinstance(sources, Iterable):
|
|
286
|
+
raise TypeError("sources must be a string, a mapping {id: text} or a list of documents")
|
|
287
|
+
|
|
288
|
+
documents = []
|
|
289
|
+
for position, obj in enumerate(sources):
|
|
290
|
+
documents.append(_to_source(obj, position))
|
|
291
|
+
return documents
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def _to_source(obj: Any, position: int) -> SourceDocument:
|
|
295
|
+
fallback = f"document {position + 1}"
|
|
296
|
+
if isinstance(obj, str):
|
|
297
|
+
return SourceDocument(id=fallback, text=obj)
|
|
298
|
+
if isinstance(obj, Mapping):
|
|
299
|
+
text = _first(obj, _TEXT_KEYS)
|
|
300
|
+
if text is None:
|
|
301
|
+
raise ValueError(f"Source dict #{position} has no text; expected one of {', '.join(_TEXT_KEYS)}")
|
|
302
|
+
doc = _first(obj, ("id", *_DOC_KEYS))
|
|
303
|
+
return SourceDocument(id=str(doc) if doc is not None else fallback, text=text, title=_str_or_none(obj.get("title")))
|
|
304
|
+
if hasattr(obj, "page_content"): # LangChain Document
|
|
305
|
+
key = langchain_key(obj.metadata or {})
|
|
306
|
+
return SourceDocument(id=key or fallback, text=obj.page_content, title=key)
|
|
307
|
+
if hasattr(obj, "get_content") and hasattr(obj, "node_id"): # LlamaIndex Document
|
|
308
|
+
title = (getattr(obj, "metadata", None) or {}).get("file_name")
|
|
309
|
+
return SourceDocument(id=str(obj.node_id), text=obj.get_content(), title=title)
|
|
310
|
+
if hasattr(obj, "content") and hasattr(obj, "meta"): # Haystack Document
|
|
311
|
+
title = (obj.meta or {}).get("file_path") or (obj.meta or {}).get("name")
|
|
312
|
+
return SourceDocument(id=str(obj.id), text=obj.content or "", title=title)
|
|
313
|
+
if hasattr(obj, "text"):
|
|
314
|
+
doc = _first_attr(obj, ("id", *_DOC_KEYS))
|
|
315
|
+
return SourceDocument(id=str(doc) if doc is not None else fallback, text=obj.text)
|
|
316
|
+
raise TypeError(f"chunkscope cannot read a source document of type {type(obj).__name__!r}")
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _as_text(value: Any, key: Any) -> str:
|
|
320
|
+
if isinstance(value, str):
|
|
321
|
+
return value
|
|
322
|
+
if hasattr(value, "page_content"):
|
|
323
|
+
return value.page_content
|
|
324
|
+
if hasattr(value, "get_content"):
|
|
325
|
+
return value.get_content()
|
|
326
|
+
if hasattr(value, "content"):
|
|
327
|
+
return value.content or ""
|
|
328
|
+
if hasattr(value, "text"):
|
|
329
|
+
return value.text
|
|
330
|
+
raise TypeError(f"Source {key!r} is not text (got {type(value).__name__})")
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
# ── Helpers ───────────────────────────────────────────────────────────────────
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def _first(mapping: Mapping[str, Any], keys: Iterable[str]) -> Any:
|
|
337
|
+
for key in keys:
|
|
338
|
+
value = mapping.get(key)
|
|
339
|
+
if value is not None:
|
|
340
|
+
return value
|
|
341
|
+
return None
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def _first_attr(obj: Any, names: Iterable[str]) -> Any:
|
|
345
|
+
for name in names:
|
|
346
|
+
value = _safe_attr(obj, name)
|
|
347
|
+
if value is not None and not callable(value):
|
|
348
|
+
return value
|
|
349
|
+
return None
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def _safe_attr(obj: Any, name: str) -> Any:
|
|
353
|
+
try:
|
|
354
|
+
return getattr(obj, name, None)
|
|
355
|
+
except Exception: # some frameworks compute attributes and may raise
|
|
356
|
+
return None
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def _int_or_none(value: Any) -> int | None:
|
|
360
|
+
if value is None or isinstance(value, bool):
|
|
361
|
+
return None
|
|
362
|
+
try:
|
|
363
|
+
return int(value)
|
|
364
|
+
except (TypeError, ValueError):
|
|
365
|
+
return None
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def _float_or_none(value: Any) -> float | None:
|
|
369
|
+
if value is None or isinstance(value, bool):
|
|
370
|
+
return None
|
|
371
|
+
try:
|
|
372
|
+
return float(value)
|
|
373
|
+
except (TypeError, ValueError):
|
|
374
|
+
return None
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def _str_or_none(value: Any) -> str | None:
|
|
378
|
+
return None if value is None else str(value)
|
chunkscope/align.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
"""Locate chunks inside their source text.
|
|
2
|
+
|
|
3
|
+
Chunks arrive at one of three fidelity levels:
|
|
4
|
+
|
|
5
|
+
1. with character offsets that match the source -> ``exact``;
|
|
6
|
+
2. with text only (or wrong offsets) -> chunkscope searches the source:
|
|
7
|
+
exact substring, then whitespace-insensitive (``normalized``), then
|
|
8
|
+
piece by piece (``partial``) for chunks whose text was transformed
|
|
9
|
+
(added context headers, repeated table headers, cleaned markup...);
|
|
10
|
+
3. text that cannot be found -> ``unmatched``: listed and measured, never placed.
|
|
11
|
+
|
|
12
|
+
Chunks are assumed to be roughly in document order. The search starts from
|
|
13
|
+
the previous chunk's start, so overlapping chunks and repeated text land on
|
|
14
|
+
the right occurrence, and falls back to the whole document otherwise.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
from bisect import bisect_left
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
|
|
22
|
+
from .models import AlignStatus, Chunk
|
|
23
|
+
|
|
24
|
+
PARTIAL_THRESHOLD = 0.5 # share of a chunk's text that must be found for "partial"
|
|
25
|
+
_MIN_PIECE_ALNUM = 4 # pieces with fewer letters/digits ("|---|", "```") are too generic
|
|
26
|
+
_WINDOW = 48 # piece length for chunks without useful line breaks
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class Alignment:
|
|
31
|
+
status: AlignStatus
|
|
32
|
+
start: int | None = None
|
|
33
|
+
end: int | None = None
|
|
34
|
+
ratio: float = 0.0 # share of the chunk's text found in the source
|
|
35
|
+
offsets_provided: bool = False
|
|
36
|
+
offsets_mismatch: bool = False # offsets were given but did not match the source
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class _Normalized:
|
|
40
|
+
"""The source with whitespace runs collapsed, mapped back to original offsets."""
|
|
41
|
+
|
|
42
|
+
def __init__(self, text: str) -> None:
|
|
43
|
+
chars: list[str] = []
|
|
44
|
+
positions: list[int] = []
|
|
45
|
+
for index, char in enumerate(text):
|
|
46
|
+
if char.isspace():
|
|
47
|
+
if chars and chars[-1] == " ":
|
|
48
|
+
continue
|
|
49
|
+
char = " "
|
|
50
|
+
chars.append(char)
|
|
51
|
+
positions.append(index)
|
|
52
|
+
self.text = "".join(chars)
|
|
53
|
+
self.positions = positions
|
|
54
|
+
|
|
55
|
+
def find(self, needle: str, start: int = 0, end: int | None = None) -> tuple[int, int] | None:
|
|
56
|
+
"""Find a normalized needle; ``start``/``end`` are offsets in the original text."""
|
|
57
|
+
if not needle:
|
|
58
|
+
return None
|
|
59
|
+
lo = bisect_left(self.positions, start)
|
|
60
|
+
hi = len(self.text) if end is None else bisect_left(self.positions, end)
|
|
61
|
+
found = self.text.find(needle, lo, hi)
|
|
62
|
+
if found < 0:
|
|
63
|
+
return None
|
|
64
|
+
return self.positions[found], self.positions[found + len(needle) - 1] + 1
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def normalize(text: str) -> str:
|
|
68
|
+
return " ".join(text.split())
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class Aligner:
|
|
72
|
+
"""Aligns the chunks of one document, in order."""
|
|
73
|
+
|
|
74
|
+
def __init__(self, source: str) -> None:
|
|
75
|
+
self.source = source
|
|
76
|
+
self._normalized: _Normalized | None = None
|
|
77
|
+
self.cursor = 0
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def normalized(self) -> _Normalized:
|
|
81
|
+
if self._normalized is None:
|
|
82
|
+
self._normalized = _Normalized(self.source)
|
|
83
|
+
return self._normalized
|
|
84
|
+
|
|
85
|
+
def align(self, chunk: Chunk) -> Alignment:
|
|
86
|
+
result = self._align(chunk)
|
|
87
|
+
if result.start is not None:
|
|
88
|
+
self.cursor = result.start + 1
|
|
89
|
+
return result
|
|
90
|
+
|
|
91
|
+
def _align(self, chunk: Chunk) -> Alignment:
|
|
92
|
+
text = chunk.text
|
|
93
|
+
provided = chunk.start is not None
|
|
94
|
+
if not text.strip():
|
|
95
|
+
return Alignment("unmatched", offsets_provided=provided)
|
|
96
|
+
|
|
97
|
+
if provided:
|
|
98
|
+
start = chunk.start
|
|
99
|
+
end = chunk.end if chunk.end is not None else start + len(text)
|
|
100
|
+
if 0 <= start <= end <= len(self.source):
|
|
101
|
+
window = self.source[start:end]
|
|
102
|
+
if window == text:
|
|
103
|
+
return Alignment("exact", start, end, 1.0, offsets_provided=True)
|
|
104
|
+
if normalize(window) == normalize(text):
|
|
105
|
+
return Alignment("normalized", start, end, 1.0, offsets_provided=True)
|
|
106
|
+
|
|
107
|
+
found = self._search(text)
|
|
108
|
+
found.offsets_provided = provided
|
|
109
|
+
found.offsets_mismatch = provided
|
|
110
|
+
return found
|
|
111
|
+
|
|
112
|
+
def _search(self, text: str) -> Alignment:
|
|
113
|
+
for origin in dict.fromkeys((self.cursor, 0)):
|
|
114
|
+
position = self.source.find(text, origin)
|
|
115
|
+
if position >= 0:
|
|
116
|
+
return Alignment("exact", position, position + len(text), 1.0)
|
|
117
|
+
|
|
118
|
+
needle = normalize(text)
|
|
119
|
+
for origin in dict.fromkeys((self.cursor, 0)):
|
|
120
|
+
span = self.normalized.find(needle, origin)
|
|
121
|
+
if span:
|
|
122
|
+
return Alignment("normalized", span[0], span[1], 1.0)
|
|
123
|
+
|
|
124
|
+
# Prefer a match after the previous chunk (document order); search the
|
|
125
|
+
# whole document only if that fails, so text repeated earlier (such as a
|
|
126
|
+
# table header the chunker copied) does not pull the span backwards.
|
|
127
|
+
best = Alignment("unmatched")
|
|
128
|
+
for origin in dict.fromkeys((self.cursor, 0)):
|
|
129
|
+
candidate = self._partial(text, origin)
|
|
130
|
+
if candidate.status == "partial":
|
|
131
|
+
return candidate
|
|
132
|
+
if candidate.ratio > best.ratio:
|
|
133
|
+
best = candidate
|
|
134
|
+
return best
|
|
135
|
+
|
|
136
|
+
def _partial(self, text: str, origin: int) -> Alignment:
|
|
137
|
+
pieces = _pieces(text)
|
|
138
|
+
total = sum(len(piece) for piece in pieces)
|
|
139
|
+
if not total:
|
|
140
|
+
return Alignment("unmatched")
|
|
141
|
+
|
|
142
|
+
limit = 2 * len(text) + 200 # how far the matched pieces may spread
|
|
143
|
+
first = last = None
|
|
144
|
+
matched = 0
|
|
145
|
+
copied = 0 # pieces found elsewhere in the source, such as a repeated table header
|
|
146
|
+
position = origin
|
|
147
|
+
for piece in pieces:
|
|
148
|
+
window_end = None if first is None else min(len(self.source), first + limit)
|
|
149
|
+
span = self._find_piece(piece, position, window_end)
|
|
150
|
+
if span is None:
|
|
151
|
+
if self._find_piece(piece, 0, None) is not None:
|
|
152
|
+
copied += len(piece)
|
|
153
|
+
continue
|
|
154
|
+
if first is None:
|
|
155
|
+
first = span[0]
|
|
156
|
+
last = span[1]
|
|
157
|
+
position = span[1]
|
|
158
|
+
matched += len(piece)
|
|
159
|
+
|
|
160
|
+
# Copied text counts as "from the source" for the decision, but only the
|
|
161
|
+
# contiguous matched pieces are highlighted and reported as the ratio.
|
|
162
|
+
ratio = matched / total
|
|
163
|
+
if first is None or (matched + copied) / total < PARTIAL_THRESHOLD:
|
|
164
|
+
return Alignment("unmatched", ratio=ratio)
|
|
165
|
+
return Alignment("partial", first, last, ratio)
|
|
166
|
+
|
|
167
|
+
def _find_piece(self, piece: str, start: int, end: int | None) -> tuple[int, int] | None:
|
|
168
|
+
position = self.source.find(piece, start, end if end is not None else len(self.source))
|
|
169
|
+
if position >= 0:
|
|
170
|
+
return position, position + len(piece)
|
|
171
|
+
return self.normalized.find(normalize(piece), start, end)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _pieces(text: str) -> list[str]:
|
|
175
|
+
"""Lines of the chunk; long lines are cut into windows so a partial match is still found."""
|
|
176
|
+
pieces: list[str] = []
|
|
177
|
+
for line in text.splitlines():
|
|
178
|
+
line = normalize(line)
|
|
179
|
+
if len(line) > 2 * _WINDOW:
|
|
180
|
+
pieces.extend(line[i : i + _WINDOW].strip() for i in range(0, len(line), _WINDOW))
|
|
181
|
+
else:
|
|
182
|
+
pieces.append(line)
|
|
183
|
+
return [piece for piece in pieces if sum(c.isalnum() for c in piece) >= _MIN_PIECE_ALNUM]
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def align_chunks(source: str, chunks: list[Chunk]) -> list[Alignment]:
|
|
187
|
+
"""Align every chunk of one document, in order."""
|
|
188
|
+
aligner = Aligner(source)
|
|
189
|
+
return [aligner.align(chunk) for chunk in chunks]
|