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/analyze.py ADDED
@@ -0,0 +1,408 @@
1
+ """Build a ``Report``: group chunks by document, align, size, check, measure coverage."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from collections.abc import Iterable, Mapping, Sequence
7
+ from typing import Any
8
+
9
+ from .adapters import is_scored_pair, to_chunk, to_sources
10
+ from .align import Aligner
11
+ from .checks import check_chunk, duplicate_issues
12
+ from .models import Chunk, ChunkResult, DocumentResult, Issue, Report, SourceDocument
13
+ from .tokenizers import as_counter
14
+
15
+ UNASSIGNED = "(chunks without a matching source)"
16
+ COLOR_MODES = ("chunk", "size", "issues", "score")
17
+ THEMES = ("auto", "light", "dark")
18
+ MAX_COLOR_KEYS = 4
19
+ _SKIP_COLOR_KEYS = {"start_index", "split_idx_start", "_split_overlap", "token_count", "id", "embedding", "orig_elements"}
20
+
21
+
22
+ def analyze(
23
+ chunks: Iterable[Any],
24
+ source: Any = None,
25
+ *,
26
+ sources: Any = None,
27
+ framework: str | None = None,
28
+ token_counter: Any = None,
29
+ size_unit: str | None = None,
30
+ max_tokens: int | None = None,
31
+ min_tokens: int | None = None,
32
+ title: str = "Chunking report",
33
+ scores: Any = None,
34
+ query: str | None = None,
35
+ color_by: str | None = None,
36
+ color_metadata: str | Sequence[str] | None = None,
37
+ theme: str = "auto",
38
+ ) -> Report:
39
+ """Analyze chunks and return a ``Report`` (render it with ``render_html``).
40
+
41
+ Args:
42
+ chunks: chunks from any chunker: strings, dicts, or LangChain, LlamaIndex,
43
+ Haystack, Chonkie, Docling or Unstructured objects. A list of lists is
44
+ read as one list of chunks per document, paired with ``sources`` by position.
45
+ source: the text of a single document that every chunk comes from.
46
+ sources: several documents: ``{id: text}``, or a list of strings, dicts or
47
+ framework documents. Chunks are matched to them by their document id.
48
+ framework: skip auto-detection (``"langchain"``, ``"llamaindex"``, ...).
49
+ token_counter: ``callable(str) -> int`` or a tokenizer object. Default: characters.
50
+ size_unit: label for sizes; defaults to ``"tokens"`` with a counter, else ``"chars"``.
51
+ max_tokens / min_tokens: size limits; chunks outside them are flagged.
52
+ title: report title.
53
+ scores: retrieval scores, to see what a query retrieves: a list aligned with
54
+ the chunks, or a mapping from chunk position (int) or chunk id (str) to score.
55
+ Scored inputs also work directly: ``(chunk, score)`` tuples, LlamaIndex
56
+ ``NodeWithScore``, Haystack documents with ``score``, dicts with ``"score"``.
57
+ query: the query the scores belong to, shown in the report.
58
+ color_by: initial colouring: ``chunk``, ``size``, ``issues``, ``score`` or
59
+ ``meta:<key>``. Every colouring can be switched in the report.
60
+ color_metadata: metadata key(s) offered as colourings (default: picked automatically).
61
+ theme: ``auto`` (follow the system), ``light`` or ``dark``.
62
+ """
63
+ if theme not in THEMES:
64
+ raise ValueError(f"theme must be one of {', '.join(THEMES)}")
65
+ if source is not None and sources is not None:
66
+ raise ValueError("Pass either source (one document) or sources (several), not both")
67
+ if isinstance(chunks, (str, Mapping)):
68
+ raise TypeError("chunks must be a list of chunks, not a single string or dict")
69
+
70
+ groups, frameworks = _read_chunks(chunks, framework)
71
+ if scores is not None:
72
+ _apply_scores(groups, scores)
73
+ source_docs = to_sources([source] if source is not None and not isinstance(source, str) else source) if source is not None else None
74
+ if source_docs is None and sources is not None:
75
+ source_docs = to_sources(sources)
76
+
77
+ pairs = _pair(groups, source_docs, single=source is not None)
78
+
79
+ counter = as_counter(token_counter)
80
+ unit = size_unit or ("tokens" if token_counter is not None else "chars")
81
+ documents = [_document(doc_id, title_, text, doc_chunks, counter, unit, max_tokens, min_tokens) for doc_id, title_, text, doc_chunks in pairs]
82
+ report = Report(
83
+ title=title,
84
+ documents=documents,
85
+ size_unit=unit,
86
+ max_size=max_tokens,
87
+ min_size=min_tokens,
88
+ frameworks=frameworks,
89
+ query=query,
90
+ theme=theme,
91
+ )
92
+ _rank(report)
93
+ report.color_metadata = _color_keys(report, color_metadata)
94
+ report.color_by = _initial_color(report, color_by)
95
+ return report
96
+
97
+
98
+ def compare(
99
+ runs: Mapping[str, Iterable[Any]],
100
+ source: Any = None,
101
+ *,
102
+ sources: Any = None,
103
+ title: str = "Chunking comparison",
104
+ **options: Any,
105
+ ) -> Report:
106
+ """Analyze several chunkings of the same documents in one report.
107
+
108
+ ``runs`` maps a label to the chunks of one run, for example
109
+ ``{"500 / 50": chunks_a, "1000 / 100": chunks_b}``. Other arguments are the
110
+ same as ``analyze``, except ``scores``, which maps run labels to that run's
111
+ scores. Each document gets a Compare tab with the chunk map of every run,
112
+ on the same scale.
113
+ """
114
+ if not isinstance(runs, Mapping) or not runs:
115
+ raise ValueError("runs must be a non-empty mapping {label: chunks}")
116
+ if sources is not None and not isinstance(sources, (str, Mapping, Sequence)):
117
+ sources = list(sources) # a generator would be used up by the first run
118
+ run_scores = options.pop("scores", None)
119
+ if run_scores is not None and (not isinstance(run_scores, Mapping) or not set(map(str, run_scores)) <= set(map(str, runs))):
120
+ raise ValueError("compare: scores must map run labels to that run's scores, e.g. {'500 / 50': [...]}")
121
+ run_scores = {str(label): value for label, value in (run_scores or {}).items()}
122
+ results = [
123
+ (str(label), analyze(chunks, source, sources=sources, title=title, scores=run_scores.get(str(label)), **options))
124
+ for label, chunks in runs.items()
125
+ ]
126
+ first = results[0][1]
127
+ documents = []
128
+ frameworks: dict[str, None] = {}
129
+ keys: dict[str, None] = {}
130
+ for label, result in results:
131
+ for doc in result.documents:
132
+ doc.run = label
133
+ documents.append(doc)
134
+ frameworks.update(dict.fromkeys(result.frameworks))
135
+ keys.update(dict.fromkeys(result.color_metadata))
136
+ merged = Report(
137
+ title=title,
138
+ documents=documents,
139
+ size_unit=first.size_unit,
140
+ max_size=first.max_size,
141
+ min_size=first.min_size,
142
+ frameworks=list(frameworks),
143
+ query=first.query,
144
+ theme=first.theme,
145
+ runs=[label for label, _ in results],
146
+ color_metadata=list(keys)[:MAX_COLOR_KEYS],
147
+ )
148
+ merged.color_by = _initial_color(merged, options.get("color_by"))
149
+ return merged
150
+
151
+
152
+ # ── Scores and colourings ─────────────────────────────────────────────────────
153
+
154
+
155
+ def _apply_scores(groups: list[list[Chunk]] | list[Chunk], scores: Any) -> None:
156
+ flat: list[Chunk] = [c for group in groups for c in group] if groups and isinstance(groups[0], list) else list(groups) # type: ignore[union-attr]
157
+ if isinstance(scores, Mapping):
158
+ by_id = {chunk.id: chunk for chunk in flat if chunk.id is not None}
159
+ for key, value in scores.items():
160
+ if isinstance(key, int) and not isinstance(key, bool):
161
+ if not 0 <= key < len(flat):
162
+ raise ValueError(f"scores: chunk position {key} is out of range (0-{len(flat) - 1})")
163
+ target = flat[key]
164
+ elif str(key) in by_id:
165
+ target = by_id[str(key)]
166
+ else:
167
+ raise ValueError(f"scores: no chunk has the id {key!r}")
168
+ target.score = None if value is None else float(value)
169
+ return
170
+ values = list(scores)
171
+ if len(values) != len(flat):
172
+ raise ValueError(f"scores has {len(values)} values but there are {len(flat)} chunks; use a mapping for a subset")
173
+ for chunk, value in zip(flat, values):
174
+ chunk.score = None if value is None else float(value)
175
+
176
+
177
+ def _rank(report: Report) -> None:
178
+ scored = [chunk for chunk in report.chunks if chunk.score is not None]
179
+ for rank, chunk in enumerate(sorted(scored, key=lambda c: c.score, reverse=True), start=1): # type: ignore[arg-type, return-value]
180
+ chunk.rank = rank
181
+
182
+
183
+ def meta_value(value: Any) -> str | None:
184
+ """A metadata value as a category label, or None if it cannot be one."""
185
+ if isinstance(value, bool) or isinstance(value, (str, int, float)):
186
+ text = str(value)
187
+ return text if text else None
188
+ if isinstance(value, (list, tuple)) and value and all(isinstance(v, (str, int, float)) for v in value):
189
+ return " > ".join(str(v) for v in value)
190
+ return None
191
+
192
+
193
+ def _color_keys(report: Report, requested: str | Sequence[str] | None) -> list[str]:
194
+ if requested is not None:
195
+ return [requested] if isinstance(requested, str) else list(requested)
196
+ chunks = report.chunks
197
+ if not chunks:
198
+ return []
199
+ candidates = []
200
+ keys: dict[str, None] = {}
201
+ for chunk in chunks:
202
+ keys.update(dict.fromkeys(chunk.chunk.metadata))
203
+ for key in keys:
204
+ if key in _SKIP_COLOR_KEYS or key.startswith("_"):
205
+ continue
206
+ values = [meta_value(chunk.chunk.metadata.get(key)) for chunk in chunks]
207
+ present = [v for v in values if v is not None]
208
+ if len(present) < len(chunks) / 2:
209
+ continue
210
+ distinct = len(set(present))
211
+ varies = any(len({meta_value(c.chunk.metadata.get(key)) for c in doc.chunks} - {None}) > 1 for doc in report.documents)
212
+ if distinct < 2 or not varies or distinct == len(chunks) > 8: # constant, or a unique id per chunk
213
+ continue
214
+ candidates.append((distinct, key))
215
+ return [key for _, key in sorted(candidates)[:MAX_COLOR_KEYS]]
216
+
217
+
218
+ def _initial_color(report: Report, requested: str | None) -> str:
219
+ if requested is None:
220
+ return "score" if any(chunk.score is not None for chunk in report.chunks) else "chunk"
221
+ if requested in COLOR_MODES:
222
+ return requested
223
+ if requested.startswith("meta:"):
224
+ key = requested[5:]
225
+ if key not in report.color_metadata:
226
+ report.color_metadata = [key, *report.color_metadata][:MAX_COLOR_KEYS]
227
+ return requested
228
+ raise ValueError(f"color_by must be one of {', '.join(COLOR_MODES)} or meta:<key>")
229
+
230
+
231
+ # ── Grouping ──────────────────────────────────────────────────────────────────
232
+
233
+
234
+ def _is_group(obj: Any) -> bool:
235
+ return isinstance(obj, (list, tuple)) and not is_scored_pair(obj)
236
+
237
+
238
+ def _read_chunks(chunks: Iterable[Any], framework: str | None) -> tuple[list[list[Chunk]] | list[Chunk], list[str]]:
239
+ items = list(chunks)
240
+ used: dict[str, None] = {}
241
+
242
+ def convert(obj: Any) -> Chunk:
243
+ chunk, name = to_chunk(obj, framework)
244
+ used[name] = None
245
+ return chunk
246
+
247
+ if items and all(_is_group(item) for item in items):
248
+ return [[convert(obj) for obj in group] for group in items], list(used)
249
+ return [convert(obj) for obj in items], list(used)
250
+
251
+
252
+ def _pair(
253
+ groups: list[list[Chunk]] | list[Chunk],
254
+ sources: list[SourceDocument] | None,
255
+ single: bool,
256
+ ) -> list[tuple[str, str, str | None, list[Chunk]]]:
257
+ """Return ``(id, title, text, chunks)`` per document."""
258
+ nested = bool(groups) and isinstance(groups[0], list)
259
+
260
+ if nested:
261
+ nested_groups: list[list[Chunk]] = groups # type: ignore[assignment]
262
+ if sources is None:
263
+ return [(f"document {i + 1}", f"document {i + 1}", None, group) for i, group in enumerate(nested_groups)]
264
+ if len(sources) != len(nested_groups):
265
+ raise ValueError(f"Got {len(nested_groups)} lists of chunks but {len(sources)} source documents; they are paired by position")
266
+ return [(doc.id, doc.title or doc.id, doc.text, group) for doc, group in zip(sources, nested_groups)]
267
+
268
+ flat: list[Chunk] = groups # type: ignore[assignment]
269
+ if sources is None:
270
+ order: dict[str, list[Chunk]] = {}
271
+ for chunk in flat:
272
+ order.setdefault(chunk.doc_id or "document", []).append(chunk)
273
+ return [(key, key, None, members) for key, members in order.items()] or [("document", "document", None, [])]
274
+
275
+ if single or len(sources) == 1 and all(chunk.doc_id is None for chunk in flat):
276
+ doc = sources[0]
277
+ return [(doc.id, doc.title or doc.id, doc.text, flat)]
278
+
279
+ by_id = {doc.id: doc for doc in sources}
280
+ by_name: dict[str, SourceDocument | None] = {}
281
+ for doc in sources:
282
+ name = os.path.basename(doc.id)
283
+ by_name[name] = None if name in by_name else doc # ambiguous names match nothing
284
+
285
+ assigned: dict[str, list[Chunk]] = {doc.id: [] for doc in sources}
286
+ unassigned: list[Chunk] = []
287
+ for chunk in flat:
288
+ key = chunk.doc_id
289
+ doc = None
290
+ if key is not None:
291
+ doc = by_id.get(key) or by_name.get(os.path.basename(key))
292
+ if doc is None:
293
+ unassigned.append(chunk)
294
+ else:
295
+ assigned[doc.id].append(chunk)
296
+
297
+ pairs = [(doc.id, doc.title or doc.id, doc.text, assigned[doc.id]) for doc in sources]
298
+ if unassigned:
299
+ pairs.append((UNASSIGNED, UNASSIGNED, None, unassigned))
300
+ return pairs
301
+
302
+
303
+ # ── One document ──────────────────────────────────────────────────────────────
304
+
305
+
306
+ def _document(
307
+ doc_id: str,
308
+ title: str,
309
+ text: str | None,
310
+ chunks: list[Chunk],
311
+ counter: Any,
312
+ unit: str,
313
+ max_size: int | None,
314
+ min_size: int | None,
315
+ ) -> DocumentResult:
316
+ aligner = Aligner(text) if text is not None else None
317
+ results: list[ChunkResult] = []
318
+ for index, chunk in enumerate(chunks):
319
+ size = counter(chunk.text)
320
+ if aligner is None:
321
+ result = ChunkResult(index, chunk, size, len(chunk.text), "no_source", offsets_provided=chunk.start is not None, score=chunk.score)
322
+ else:
323
+ found = aligner.align(chunk)
324
+ result = ChunkResult(
325
+ index,
326
+ chunk,
327
+ size,
328
+ len(chunk.text),
329
+ found.status,
330
+ found.start,
331
+ found.end,
332
+ found.ratio,
333
+ found.offsets_provided,
334
+ score=chunk.score,
335
+ )
336
+ result.issues = check_chunk(result, text, unit, max_size, min_size)
337
+ results.append(result)
338
+
339
+ for issue in duplicate_issues(results):
340
+ results[issue.chunk].issues.append(issue) # type: ignore[index]
341
+
342
+ doc = DocumentResult(id=doc_id, title=title, text=text, chunks=results)
343
+ if text is None:
344
+ reason = "they could not be matched to a source document" if doc_id == UNASSIGNED else "no source text was given"
345
+ doc.issues.append(Issue("no_source", "info", f"These chunks are listed but not placed: {reason}. Pass source= or sources= to see them in context."))
346
+ return doc
347
+ if not results:
348
+ doc.issues.append(Issue("no_chunks", "warning", "This document produced no chunks: none of its text will be retrievable."))
349
+
350
+ _coverage(doc)
351
+ return doc
352
+
353
+
354
+ def segments(doc: DocumentResult) -> list[tuple[int, int, tuple[int, ...]]]:
355
+ """Split the source into runs covered by the same set of chunks: ``(start, end, chunk indexes)``."""
356
+ if doc.text is None:
357
+ return []
358
+ length = len(doc.text)
359
+ events: dict[int, list[tuple[int, int]]] = {}
360
+ for chunk in doc.chunks:
361
+ if chunk.located and chunk.end > chunk.start: # type: ignore[operator]
362
+ events.setdefault(chunk.start, []).append((1, chunk.index)) # type: ignore[arg-type]
363
+ events.setdefault(chunk.end, []).append((-1, chunk.index)) # type: ignore[arg-type]
364
+ boundaries = sorted({0, length, *events})
365
+ active: dict[int, int] = {}
366
+ runs = []
367
+ for left, right in zip(boundaries, boundaries[1:]):
368
+ for delta, index in events.get(left, []):
369
+ active[index] = active.get(index, 0) + delta
370
+ if active[index] == 0:
371
+ del active[index]
372
+ if right > left:
373
+ runs.append((left, right, tuple(sorted(active))))
374
+ return runs
375
+
376
+
377
+ def _coverage(doc: DocumentResult) -> None:
378
+ text = doc.text or ""
379
+ total = len(text) - sum(1 for char in text if char.isspace())
380
+ uncovered = 0
381
+ gaps: list[tuple[int, int]] = []
382
+ overlaps: list[tuple[int, int]] = []
383
+ for start, end, active in segments(doc):
384
+ if not active:
385
+ solid = sum(1 for char in text[start:end] if not char.isspace())
386
+ if solid:
387
+ uncovered += solid
388
+ _extend(gaps, start, end)
389
+ elif len(active) > 1:
390
+ _extend(overlaps, start, end)
391
+ doc.gaps, doc.overlaps = gaps, overlaps
392
+ doc.coverage = 1.0 if total == 0 else (total - uncovered) / total
393
+ if gaps:
394
+ doc.issues.append(
395
+ Issue(
396
+ "gaps",
397
+ "warning",
398
+ f"{uncovered} non-whitespace characters in {len(gaps)} place(s) are not in any chunk, so they cannot be retrieved. "
399
+ "This is expected only if your chunker deliberately drops text (headings kept as metadata, boilerplate).",
400
+ )
401
+ )
402
+
403
+
404
+ def _extend(runs: list[tuple[int, int]], start: int, end: int) -> None:
405
+ if runs and runs[-1][1] == start:
406
+ runs[-1] = (runs[-1][0], end)
407
+ else:
408
+ runs.append((start, end))
chunkscope/api.py ADDED
@@ -0,0 +1,44 @@
1
+ """One-call entry points."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import webbrowser
6
+ from collections.abc import Iterable
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from .analyze import analyze
11
+ from .models import Report
12
+ from .render import render_html
13
+
14
+ DEFAULT_OUTPUT = "chunkscope-report.html"
15
+
16
+
17
+ def save(result: Report, output: str | Path = DEFAULT_OUTPUT, open_browser: bool = False) -> Path:
18
+ """Write a report to an HTML file and return its path."""
19
+ path = Path(output).expanduser()
20
+ if path.parent and not path.parent.exists():
21
+ path.parent.mkdir(parents=True, exist_ok=True)
22
+ path.write_text(render_html(result), encoding="utf-8")
23
+ if open_browser:
24
+ webbrowser.open(path.resolve().as_uri())
25
+ return path
26
+
27
+
28
+ def report(
29
+ chunks: Iterable[Any],
30
+ source: Any = None,
31
+ *,
32
+ output: str | Path = DEFAULT_OUTPUT,
33
+ open_browser: bool = False,
34
+ **options: Any,
35
+ ) -> Report:
36
+ """Analyze chunks, write the HTML report, and return the ``Report``.
37
+
38
+ Takes the same arguments as ``chunkscope.analyze`` (``sources``,
39
+ ``framework``, ``token_counter``, ``max_tokens``, ``min_tokens``, ``title``)
40
+ plus ``output`` (file path) and ``open_browser``.
41
+ """
42
+ result = analyze(chunks, source, **options)
43
+ save(result, output, open_browser)
44
+ return result
chunkscope/checks.py ADDED
@@ -0,0 +1,155 @@
1
+ """Boundary-quality checks.
2
+
3
+ Each check looks for one common chunking bug and explains it in plain words.
4
+ Checks that need to know where the chunk sits in the source only run on
5
+ located chunks.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+
12
+ from .align import normalize
13
+ from .models import ChunkResult, Issue
14
+
15
+ _HEADING = re.compile(r"^#{1,6}\s+\S")
16
+ _FENCE = re.compile(r"^\s*(```|~~~)")
17
+ _TABLE_SEPARATOR = re.compile(r"^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)*\|?\s*$")
18
+ _SENTENCE_END = set(".!?:;…)]}\"'`|*>")
19
+
20
+
21
+ def check_chunk(result: ChunkResult, source: str | None, unit: str, max_size: int | None, min_size: int | None) -> list[Issue]:
22
+ issues: list[Issue] = []
23
+ text = result.chunk.text
24
+ index = result.index
25
+
26
+ def add(code: str, severity: str, message: str) -> None:
27
+ issues.append(Issue(code, severity, message, index)) # type: ignore[arg-type]
28
+
29
+ if not text.strip():
30
+ add("empty", "error", "Empty chunk: it has no text to embed.")
31
+ return issues
32
+
33
+ if max_size is not None and result.size > max_size:
34
+ add("over_limit", "error", f"{result.size} {unit}, over the limit of {max_size}. Embedding models truncate the rest.")
35
+ if min_size is not None and result.size < min_size:
36
+ add("under_limit", "warning", f"Only {result.size} {unit}, under the minimum of {min_size}. Tiny chunks carry little meaning.")
37
+
38
+ if source is not None:
39
+ if result.status == "unmatched":
40
+ found = f" (only {result.match_ratio:.0%} of it matched)" if result.match_ratio else ""
41
+ add("unmatched", "warning", f"Not found in the source text{found}, so it cannot be placed.")
42
+ elif result.status == "partial":
43
+ add(
44
+ "partial",
45
+ "info",
46
+ f"Only {result.match_ratio:.0%} of the text was found in the source: the chunker transformed it "
47
+ "(added headers or context, cleaned markup) or the source differs.",
48
+ )
49
+ if result.offsets_provided and result.status != "unmatched" and _mismatch(result):
50
+ add("offset_mismatch", "warning", "The chunk's own offsets do not match the source; it was located by search instead.")
51
+
52
+ lines = [line for line in text.splitlines() if line.strip()]
53
+ if sum(1 for line in lines if _FENCE.match(line)) % 2:
54
+ add("split_code_block", "warning", "Cuts a code block: the opening or closing ``` fence is in another chunk.")
55
+ if lines and all(_HEADING.match(line) for line in lines):
56
+ add("heading_only", "warning", "Contains only a heading: its content ended up in another chunk.")
57
+
58
+ if source is not None and result.located:
59
+ issues.extend(_boundary_issues(result, source, lines))
60
+ return issues
61
+
62
+
63
+ def _mismatch(result: ChunkResult) -> bool:
64
+ chunk = result.chunk
65
+ return chunk.start != result.start or (chunk.end is not None and chunk.end != result.end)
66
+
67
+
68
+ def _boundary_issues(result: ChunkResult, source: str, lines: list[str]) -> list[Issue]:
69
+ issues: list[Issue] = []
70
+ start, end = result.start, result.end
71
+ assert start is not None and end is not None
72
+
73
+ def add(code: str, severity: str, message: str) -> None:
74
+ issues.append(Issue(code, severity, message, result.index)) # type: ignore[arg-type]
75
+
76
+ # A partial match has approximate boundaries (only some pieces were found),
77
+ # so word and sentence cuts would be false positives there.
78
+ exact = result.status in ("exact", "normalized")
79
+ if exact and 0 < start < len(source) and source[start - 1].isalnum() and source[start].isalnum():
80
+ add("starts_mid_word", "warning", "Starts in the middle of a word.")
81
+ cut_word = exact and 0 < end < len(source) and source[end - 1].isalnum() and source[end].isalnum()
82
+ if cut_word:
83
+ add("ends_mid_word", "warning", "Ends in the middle of a word.")
84
+ elif exact and lines and end < len(source):
85
+ last = lines[-1].rstrip()
86
+ newline = source.find("\n", end)
87
+ rest_of_line = source[end : newline if newline >= 0 else len(source)]
88
+ if last and last[-1] not in _SENTENCE_END and rest_of_line.strip():
89
+ add("ends_mid_sentence", "info", "Ends in the middle of a sentence.")
90
+
91
+ if lines and _is_table_row(lines[0]) and not (len(lines) > 1 and _TABLE_SEPARATOR.match(lines[1])):
92
+ previous = _neighbour_line(source, start, -1)
93
+ if previous is not None and _is_table_row(previous):
94
+ add("starts_in_table", "warning", "Starts inside a table: these rows are separated from the table header.")
95
+ if lines and _is_table_row(lines[-1]):
96
+ following = _neighbour_line(source, end, +1)
97
+ if following is not None and _is_table_row(following):
98
+ add("ends_in_table", "warning", "Ends inside a table: the table continues in the next chunk.")
99
+ return issues
100
+
101
+
102
+ def _is_table_row(line: str) -> bool:
103
+ stripped = line.strip()
104
+ return stripped.startswith("|") and stripped.count("|") >= 2
105
+
106
+
107
+ def _neighbour_line(source: str, position: int, direction: int) -> str | None:
108
+ """The nearest non-blank line before (``-1``) or after (``+1``) a position.
109
+
110
+ If the position is in the middle of a line, that line is the neighbour.
111
+ Works with indices only, so large documents are not copied.
112
+ """
113
+ if direction < 0:
114
+ line_start = source.rfind("\n", 0, position) + 1
115
+ if source[line_start:position].strip():
116
+ return source[line_start:position]
117
+ end = line_start - 1 # the newline before the current line
118
+ while end > 0:
119
+ begin = source.rfind("\n", 0, end) + 1
120
+ line = source[begin:end]
121
+ if line.strip():
122
+ return line
123
+ end = begin - 1
124
+ return None
125
+ line_end = source.find("\n", position)
126
+ if line_end < 0:
127
+ line_end = len(source)
128
+ if source[position:line_end].strip():
129
+ return source[position:line_end]
130
+ begin = line_end + 1
131
+ while begin < len(source):
132
+ end = source.find("\n", begin)
133
+ if end < 0:
134
+ end = len(source)
135
+ line = source[begin:end]
136
+ if line.strip():
137
+ return line
138
+ begin = end + 1
139
+ return None
140
+
141
+
142
+ def duplicate_issues(results: list[ChunkResult]) -> list[Issue]:
143
+ seen: dict[str, int] = {}
144
+ issues = []
145
+ for result in results:
146
+ key = normalize(result.chunk.text)
147
+ if not key:
148
+ continue
149
+ if key in seen:
150
+ issues.append(
151
+ Issue("duplicate", "info", f"Same text as chunk #{seen[key]}: it will be embedded and retrieved twice.", result.index)
152
+ )
153
+ else:
154
+ seen[key] = result.index
155
+ return issues