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/cli.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""Command line: ``chunkscope report chunks.jsonl --source doc.md``.
|
|
2
|
+
|
|
3
|
+
Chunk files are JSON Lines (one chunk object per line) or a JSON list. Each
|
|
4
|
+
chunk needs a text field (``text``, ``content`` or ``page_content``) and may
|
|
5
|
+
have offsets (``start``/``end``), an ``id``, ``metadata`` and a document id
|
|
6
|
+
(``doc_id`` or ``source``) that matches a source file name.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
import json
|
|
13
|
+
import sys
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from . import __version__
|
|
18
|
+
from .analyze import analyze, compare
|
|
19
|
+
from .api import DEFAULT_OUTPUT, save
|
|
20
|
+
from .tokenizers import from_spec
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def main(argv: list[str] | None = None) -> int:
|
|
24
|
+
parser = _parser()
|
|
25
|
+
args = parser.parse_args(argv)
|
|
26
|
+
if args.command not in ("report", "compare"):
|
|
27
|
+
parser.print_help()
|
|
28
|
+
return 2
|
|
29
|
+
try:
|
|
30
|
+
return _report(args)
|
|
31
|
+
except (OSError, ValueError, TypeError, ImportError) as error:
|
|
32
|
+
print(f"chunkscope: error: {error}", file=sys.stderr)
|
|
33
|
+
return 1
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _parser() -> argparse.ArgumentParser:
|
|
37
|
+
parser = argparse.ArgumentParser(prog="chunkscope", description="Visualize RAG chunking as an offline HTML report.")
|
|
38
|
+
parser.add_argument("--version", action="version", version=f"chunkscope {__version__}")
|
|
39
|
+
commands = parser.add_subparsers(dest="command")
|
|
40
|
+
report = commands.add_parser("report", help="build an HTML report from a chunks file")
|
|
41
|
+
report.add_argument("chunks", type=Path, help="chunks as JSON Lines (.jsonl) or a JSON list (.json)")
|
|
42
|
+
_common(report)
|
|
43
|
+
compare_cmd = commands.add_parser("compare", help="compare several chunkings of the same documents")
|
|
44
|
+
compare_cmd.add_argument("chunks", type=Path, nargs="+", help="one chunks file per run; the file name is the run label")
|
|
45
|
+
_common(compare_cmd)
|
|
46
|
+
return parser
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _common(report: argparse.ArgumentParser) -> None:
|
|
50
|
+
report.add_argument("-s", "--source", type=Path, action="append", default=[], help="source document (repeat for several)")
|
|
51
|
+
report.add_argument("--source-dir", type=Path, help="directory where the chunks' doc_id / source paths are found")
|
|
52
|
+
report.add_argument("-o", "--output", type=Path, default=Path(DEFAULT_OUTPUT), help=f"output file (default: {DEFAULT_OUTPUT})")
|
|
53
|
+
report.add_argument("--title", default="Chunking report")
|
|
54
|
+
report.add_argument("--tokenizer", default="chars", help="chars (default), words, tiktoken:<encoding>, hf:<model>")
|
|
55
|
+
report.add_argument("--max-tokens", type=int, help="flag chunks larger than this")
|
|
56
|
+
report.add_argument("--min-tokens", type=int, help="flag chunks smaller than this")
|
|
57
|
+
report.add_argument("--fail-on", choices=("error", "warning"), help="exit with status 3 if issues of this severity (or worse) exist")
|
|
58
|
+
report.add_argument("--color-by", help="initial colouring: chunk, size, issues, score or meta:<key> (switchable in the report)")
|
|
59
|
+
report.add_argument("--theme", choices=("auto", "light", "dark"), default="auto")
|
|
60
|
+
report.add_argument("--query", help="the query that produced the chunks' \"score\" values")
|
|
61
|
+
report.add_argument("--open", action="store_true", help="open the report in the browser")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _report(args: argparse.Namespace) -> int:
|
|
65
|
+
files = args.chunks if isinstance(args.chunks, list) else [args.chunks]
|
|
66
|
+
runs = {path.stem: _read_chunks(path) for path in files}
|
|
67
|
+
if len(runs) != len(files):
|
|
68
|
+
raise ValueError("compare: give each chunks file a different name; the file name is the run label")
|
|
69
|
+
every_chunk = [chunk for chunks in runs.values() for chunk in chunks]
|
|
70
|
+
sources: dict[str, str] | None = None
|
|
71
|
+
if args.source:
|
|
72
|
+
sources = {str(path): path.read_text(encoding="utf-8") for path in args.source}
|
|
73
|
+
if args.source_dir:
|
|
74
|
+
sources = dict(sources or {})
|
|
75
|
+
sources.update(_read_source_dir(args.source_dir, every_chunk))
|
|
76
|
+
|
|
77
|
+
counter, unit = from_spec(args.tokenizer)
|
|
78
|
+
options = dict(
|
|
79
|
+
sources=sources,
|
|
80
|
+
token_counter=counter,
|
|
81
|
+
size_unit=unit,
|
|
82
|
+
max_tokens=args.max_tokens,
|
|
83
|
+
min_tokens=args.min_tokens,
|
|
84
|
+
title=args.title,
|
|
85
|
+
query=args.query,
|
|
86
|
+
color_by=args.color_by,
|
|
87
|
+
theme=args.theme,
|
|
88
|
+
)
|
|
89
|
+
if args.command == "compare":
|
|
90
|
+
result = compare(runs, **options)
|
|
91
|
+
else:
|
|
92
|
+
result = analyze(next(iter(runs.values())), **options)
|
|
93
|
+
path = save(result, args.output, open_browser=args.open)
|
|
94
|
+
summary = result.summary()
|
|
95
|
+
print(
|
|
96
|
+
f"{path}: {summary['documents']} document(s), {summary['chunks']} chunks, "
|
|
97
|
+
f"{summary['errors']} error(s), {summary['warnings']} warning(s)"
|
|
98
|
+
)
|
|
99
|
+
if args.fail_on == "error" and summary["errors"]:
|
|
100
|
+
return 3
|
|
101
|
+
if args.fail_on == "warning" and (summary["errors"] or summary["warnings"]):
|
|
102
|
+
return 3
|
|
103
|
+
return 0
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _read_chunks(path: Path) -> list[Any]:
|
|
107
|
+
text = path.read_text(encoding="utf-8")
|
|
108
|
+
stripped = text.lstrip()
|
|
109
|
+
if stripped.startswith("["):
|
|
110
|
+
data = json.loads(text)
|
|
111
|
+
if not isinstance(data, list):
|
|
112
|
+
raise ValueError(f"{path}: expected a JSON list of chunks")
|
|
113
|
+
return data
|
|
114
|
+
chunks = []
|
|
115
|
+
for number, line in enumerate(text.splitlines(), start=1):
|
|
116
|
+
if not line.strip():
|
|
117
|
+
continue
|
|
118
|
+
try:
|
|
119
|
+
chunks.append(json.loads(line))
|
|
120
|
+
except json.JSONDecodeError as error:
|
|
121
|
+
raise ValueError(f"{path}:{number}: invalid JSON ({error.msg})") from None
|
|
122
|
+
return chunks
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _read_source_dir(directory: Path, chunks: list[Any]) -> dict[str, str]:
|
|
126
|
+
"""Read the source files that the chunks refer to, relative to ``directory``."""
|
|
127
|
+
if not directory.is_dir():
|
|
128
|
+
raise ValueError(f"{directory} is not a directory")
|
|
129
|
+
root = directory.resolve()
|
|
130
|
+
found: dict[str, str] = {}
|
|
131
|
+
for chunk in chunks:
|
|
132
|
+
if not isinstance(chunk, dict):
|
|
133
|
+
continue
|
|
134
|
+
meta = chunk.get("metadata") or {}
|
|
135
|
+
key = chunk.get("doc_id") or chunk.get("source") or meta.get("source")
|
|
136
|
+
if not key or key in found:
|
|
137
|
+
continue
|
|
138
|
+
path = (root / str(key)).resolve()
|
|
139
|
+
if root not in path.parents and path != root: # never read outside the directory
|
|
140
|
+
continue
|
|
141
|
+
if path.is_file():
|
|
142
|
+
found[str(key)] = path.read_text(encoding="utf-8")
|
|
143
|
+
return found
|
chunkscope/colors.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
"""Colourings for the source view and the chunk map.
|
|
2
|
+
|
|
3
|
+
Every chunk carries one CSS class per colouring (``k1 z3 v2 r4 m0x2``), and
|
|
4
|
+
the page switches between them by changing ``body[data-color]``. Nothing is
|
|
5
|
+
recomputed in the browser, so switching is instant and works offline.
|
|
6
|
+
|
|
7
|
+
Colour rules (from a validated palette):
|
|
8
|
+
- chunk: four alternating hues, only to tell neighbours apart;
|
|
9
|
+
- size and score: one hue each, light to dark (blue for size, orange for score);
|
|
10
|
+
- issues: the status colours, always paired with an icon and a label;
|
|
11
|
+
- metadata: eight categorical hues in fixed order; further values fold into "other".
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import html
|
|
17
|
+
from collections import Counter
|
|
18
|
+
|
|
19
|
+
from .analyze import meta_value
|
|
20
|
+
from .models import ChunkResult, Report
|
|
21
|
+
|
|
22
|
+
e = html.escape
|
|
23
|
+
|
|
24
|
+
CATEGORICAL = ("#257de0", "#f47230", "#00b894", "#f2a600", "#ee7fac", "#008a17", "#6a4ce2", "#ec4647")
|
|
25
|
+
OTHER = "#9a9a9a"
|
|
26
|
+
BLUE_SOLID = ("#b6d5f8", "#84b9f3", "#519ced", "#257de0", "#1757ac")
|
|
27
|
+
ORANGE_SOLID = ("#fcd3bd", "#f9ae86", "#f68b54", "#f47230", "#b9501b")
|
|
28
|
+
SEQ_ALPHA = (0.08, 0.16, 0.26, 0.38, 0.52)
|
|
29
|
+
CRITICAL, WARNING, INFO = "#dc3c3d", "#fbb315", "#8a94a6"
|
|
30
|
+
STEPS = 5
|
|
31
|
+
_LABEL_LIMIT = 48
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _rgba(hex_color: str, alpha: float) -> str:
|
|
35
|
+
red, green, blue = (int(hex_color[i : i + 2], 16) for i in (1, 3, 5))
|
|
36
|
+
return f"rgba({red},{green},{blue},{alpha})"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _bucket(value: float, low: float, high: float) -> int:
|
|
40
|
+
if high <= low:
|
|
41
|
+
return STEPS - 1
|
|
42
|
+
return max(0, min(STEPS - 1, int((value - low) / (high - low) * STEPS)))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class Palette:
|
|
46
|
+
def __init__(self, report: Report) -> None:
|
|
47
|
+
self.report = report
|
|
48
|
+
chunks = report.chunks
|
|
49
|
+
sizes = [c.size for c in chunks]
|
|
50
|
+
self.size_top = report.max_size or (max(sizes) if sizes else 0)
|
|
51
|
+
scores = [c.score for c in chunks if c.score is not None]
|
|
52
|
+
self.score_range = (min(scores), max(scores)) if scores else None
|
|
53
|
+
self.keys = list(report.color_metadata)
|
|
54
|
+
self.categories: list[dict[str, int]] = []
|
|
55
|
+
self.counts: list[Counter[str]] = []
|
|
56
|
+
for key in self.keys:
|
|
57
|
+
counter: Counter[str] = Counter()
|
|
58
|
+
for chunk in chunks:
|
|
59
|
+
value = meta_value(chunk.chunk.metadata.get(key))
|
|
60
|
+
if value is not None:
|
|
61
|
+
counter[value] += 1
|
|
62
|
+
# The most frequent values get a hue (at most eight), in order of first appearance.
|
|
63
|
+
kept = {value for value, _ in counter.most_common(len(CATEGORICAL))}
|
|
64
|
+
ordered = [value for value in counter if value in kept] # Counter keeps insertion order
|
|
65
|
+
self.categories.append({value: index for index, value in enumerate(ordered)})
|
|
66
|
+
self.counts.append(counter)
|
|
67
|
+
|
|
68
|
+
# ── Per chunk ──────────────────────────────────────────────────────────
|
|
69
|
+
|
|
70
|
+
def classes(self, chunk: ChunkResult) -> str:
|
|
71
|
+
names = [f"k{chunk.index % 4}"]
|
|
72
|
+
if self.report.max_size is not None and chunk.size > self.report.max_size:
|
|
73
|
+
names.append("zx")
|
|
74
|
+
else:
|
|
75
|
+
names.append(f"z{_bucket(chunk.size, 0, self.size_top)}")
|
|
76
|
+
severities = {issue.severity for issue in chunk.issues}
|
|
77
|
+
names.append("v3" if "error" in severities else "v2" if "warning" in severities else "v1" if severities else "v0")
|
|
78
|
+
if chunk.score is None or self.score_range is None:
|
|
79
|
+
names.append("rn")
|
|
80
|
+
else:
|
|
81
|
+
names.append(f"r{_bucket(chunk.score, *self.score_range)}")
|
|
82
|
+
for number, key in enumerate(self.keys):
|
|
83
|
+
value = meta_value(chunk.chunk.metadata.get(key))
|
|
84
|
+
if value is None:
|
|
85
|
+
names.append(f"m{number}n")
|
|
86
|
+
else:
|
|
87
|
+
names.append(f"m{number}x{self.categories[number].get(value, len(CATEGORICAL))}")
|
|
88
|
+
return " ".join(names)
|
|
89
|
+
|
|
90
|
+
# ── Modes and legends ──────────────────────────────────────────────────
|
|
91
|
+
|
|
92
|
+
def modes(self) -> list[tuple[str, str]]:
|
|
93
|
+
modes = [("chunk", "Chunk"), ("size", f"Size ({self.report.size_unit})"), ("issues", "Issues")]
|
|
94
|
+
if self.score_range is not None:
|
|
95
|
+
modes.append(("score", "Retrieval score"))
|
|
96
|
+
modes.extend((f"m{number}", f"Metadata: {key}") for number, key in enumerate(self.keys))
|
|
97
|
+
return modes
|
|
98
|
+
|
|
99
|
+
def initial(self) -> str:
|
|
100
|
+
wanted = self.report.color_by
|
|
101
|
+
if wanted.startswith("meta:") and wanted[5:] in self.keys:
|
|
102
|
+
return f"m{self.keys.index(wanted[5:])}"
|
|
103
|
+
if wanted == "score" and self.score_range is None:
|
|
104
|
+
return "chunk"
|
|
105
|
+
return wanted if wanted in ("chunk", "size", "issues", "score") else "chunk"
|
|
106
|
+
|
|
107
|
+
def legends(self) -> str:
|
|
108
|
+
unit = self.report.size_unit
|
|
109
|
+
parts = [
|
|
110
|
+
'<span class="lg lg-chunk"><i class="sw k0"></i><i class="sw k1"></i><i class="sw k2"></i><i class="sw k3"></i>'
|
|
111
|
+
"alternating colours tell neighbouring chunks apart</span>"
|
|
112
|
+
]
|
|
113
|
+
steps = "".join(f'<i class="sw" style="background:{color}"></i>' for color in BLUE_SOLID)
|
|
114
|
+
limit = self.report.max_size
|
|
115
|
+
over = f'<i class="sw" style="background:{CRITICAL}"></i>✕ over {limit}' if limit else ""
|
|
116
|
+
parts.append(f'<span class="lg lg-size">0 {steps} {self.size_top} {e(unit)} {over}</span>')
|
|
117
|
+
parts.append(
|
|
118
|
+
'<span class="lg lg-issues"><i class="sw sw-line"></i>no issues'
|
|
119
|
+
f'<i class="sw" style="background:{INFO}"></i>ℹ info'
|
|
120
|
+
f'<i class="sw" style="background:{WARNING}"></i>▲ warning'
|
|
121
|
+
f'<i class="sw" style="background:{CRITICAL}"></i>✕ error</span>'
|
|
122
|
+
)
|
|
123
|
+
if self.score_range is not None:
|
|
124
|
+
low, high = self.score_range
|
|
125
|
+
steps = "".join(f'<i class="sw" style="background:{color}"></i>' for color in ORANGE_SOLID)
|
|
126
|
+
parts.append(f'<span class="lg lg-score">{low:.3g} {steps} {high:.3g} · <i class="sw sw-line"></i>not scored</span>')
|
|
127
|
+
for number, key in enumerate(self.keys):
|
|
128
|
+
items = []
|
|
129
|
+
for value, index in self.categories[number].items():
|
|
130
|
+
label = value if len(value) <= _LABEL_LIMIT else value[: _LABEL_LIMIT - 1] + "…"
|
|
131
|
+
items.append(f'<span class="lgi"><i class="sw" style="background:{CATEGORICAL[index]}"></i>{e(label)} <small>{self.counts[number][value]}</small></span>')
|
|
132
|
+
rest = len(self.counts[number]) - len(self.categories[number])
|
|
133
|
+
if rest > 0:
|
|
134
|
+
items.append(f'<span class="lgi"><i class="sw" style="background:{OTHER}"></i>{rest} other value{"s" if rest != 1 else ""}</span>')
|
|
135
|
+
items.append('<span class="lgi"><i class="sw sw-line"></i>missing</span>')
|
|
136
|
+
parts.append(f'<span class="lg lg-m{number}">{"".join(items)}</span>')
|
|
137
|
+
return "".join(parts)
|
|
138
|
+
|
|
139
|
+
# ── CSS ────────────────────────────────────────────────────────────────
|
|
140
|
+
|
|
141
|
+
def css(self) -> str:
|
|
142
|
+
rules: list[str] = []
|
|
143
|
+
|
|
144
|
+
def rule(mode: str, cls: str, color: str | None, tint: str | None = None) -> None:
|
|
145
|
+
sel = f'body[data-color="{mode}"]'
|
|
146
|
+
if color is None: # "no value": faint underline only
|
|
147
|
+
rules.append(f"{sel} .seg.{cls}{{background-color:transparent;box-shadow:inset 0 -1px var(--line)}}")
|
|
148
|
+
rules.append(f"{sel} .cmb.{cls}{{background:var(--line)}}")
|
|
149
|
+
return
|
|
150
|
+
rules.append(f"{sel} .seg.{cls}{{background-color:{tint or _rgba(color, .2)};box-shadow:inset 0 -2px {color}}}")
|
|
151
|
+
rules.append(f"{sel} .cmb.{cls}{{background:{color}}}")
|
|
152
|
+
|
|
153
|
+
for index in range(4):
|
|
154
|
+
rules.append(f'body[data-color="chunk"] .seg.k{index}{{background-color:var(--k{index});box-shadow:inset 0 -2px var(--k{index}b)}}')
|
|
155
|
+
rules.append(f'body[data-color="chunk"] .cmb.k{index}{{background:var(--k{index}b)}}')
|
|
156
|
+
# Overlaps in chunk mode: both chunks' colours, stronger than a normal tint,
|
|
157
|
+
# as two bands with each chunk's underline above and below.
|
|
158
|
+
for first in range(4):
|
|
159
|
+
for second in range(4):
|
|
160
|
+
rules.append(
|
|
161
|
+
f'body[data-color="chunk"] .seg.ov.k{first}.o{second}{{background-color:transparent;'
|
|
162
|
+
f"background-image:linear-gradient(to bottom,var(--k{first}s) 0 50%,var(--k{second}s) 50% 100%);"
|
|
163
|
+
f"box-shadow:inset 0 3px var(--k{first}b),inset 0 -3px var(--k{second}b)}}"
|
|
164
|
+
)
|
|
165
|
+
for step in range(STEPS):
|
|
166
|
+
rule("size", f"z{step}", BLUE_SOLID[step], _rgba("#257de0", SEQ_ALPHA[step]))
|
|
167
|
+
rule("score", f"r{step}", ORANGE_SOLID[step], _rgba("#f47230", SEQ_ALPHA[step]))
|
|
168
|
+
rule("size", "zx", CRITICAL, _rgba(CRITICAL, .3))
|
|
169
|
+
rule("score", "rn", None)
|
|
170
|
+
rules.append('body[data-color="score"] .seg.rn{color:var(--muted)}')
|
|
171
|
+
rule("issues", "v0", None)
|
|
172
|
+
rule("issues", "v1", INFO, _rgba(INFO, .25))
|
|
173
|
+
rule("issues", "v2", WARNING, _rgba(WARNING, .32))
|
|
174
|
+
rule("issues", "v3", CRITICAL, _rgba(CRITICAL, .28))
|
|
175
|
+
for number in range(len(self.keys)):
|
|
176
|
+
for index, color in enumerate((*CATEGORICAL, OTHER)):
|
|
177
|
+
rule(f"m{number}", f"m{number}x{index}", color, _rgba(color, .2))
|
|
178
|
+
rule(f"m{number}", f"m{number}n", None)
|
|
179
|
+
modes = [mode for mode, _ in self.modes()]
|
|
180
|
+
rules.extend(f'body[data-color="{mode}"] .lg-{mode}{{display:flex}}' for mode in modes)
|
|
181
|
+
return "".join(rules)
|
chunkscope/models.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"""Data model shared by every module.
|
|
2
|
+
|
|
3
|
+
``Chunk`` is the generic contract: whatever chunker or framework produced the
|
|
4
|
+
chunks, adapters turn them into ``Chunk`` objects before anything else happens.
|
|
5
|
+
Only ``text`` is required; every other field improves what the report can show.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from typing import Any, Literal
|
|
12
|
+
|
|
13
|
+
AlignStatus = Literal["exact", "normalized", "partial", "unmatched", "no_source"]
|
|
14
|
+
Severity = Literal["error", "warning", "info"]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass
|
|
18
|
+
class Chunk:
|
|
19
|
+
"""One chunk, independent of the framework that produced it.
|
|
20
|
+
|
|
21
|
+
``start``/``end`` are character offsets into the source text (``end`` is
|
|
22
|
+
exclusive). When they are missing, chunkscope locates the chunk itself.
|
|
23
|
+
``doc_id`` says which source document the chunk came from.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
text: str
|
|
27
|
+
start: int | None = None
|
|
28
|
+
end: int | None = None
|
|
29
|
+
id: str | None = None
|
|
30
|
+
parent_id: str | None = None
|
|
31
|
+
doc_id: str | None = None
|
|
32
|
+
metadata: dict[str, Any] = field(default_factory=dict)
|
|
33
|
+
score: float | None = None # retrieval score, if the chunk came from a search
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass
|
|
37
|
+
class SourceDocument:
|
|
38
|
+
"""The text a chunker received, before splitting."""
|
|
39
|
+
|
|
40
|
+
id: str
|
|
41
|
+
text: str
|
|
42
|
+
title: str | None = None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class Issue:
|
|
47
|
+
"""A problem or observation found by the checks."""
|
|
48
|
+
|
|
49
|
+
code: str
|
|
50
|
+
severity: Severity
|
|
51
|
+
message: str
|
|
52
|
+
chunk: int | None = None # index of the chunk inside its document, if any
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass
|
|
56
|
+
class ChunkResult:
|
|
57
|
+
"""A chunk after alignment, sizing and checks."""
|
|
58
|
+
|
|
59
|
+
index: int
|
|
60
|
+
chunk: Chunk
|
|
61
|
+
size: int
|
|
62
|
+
chars: int
|
|
63
|
+
status: AlignStatus
|
|
64
|
+
start: int | None = None
|
|
65
|
+
end: int | None = None
|
|
66
|
+
match_ratio: float = 0.0
|
|
67
|
+
offsets_provided: bool = False
|
|
68
|
+
issues: list[Issue] = field(default_factory=list)
|
|
69
|
+
score: float | None = None
|
|
70
|
+
rank: int | None = None # 1 = best retrieval score in the report
|
|
71
|
+
|
|
72
|
+
@property
|
|
73
|
+
def located(self) -> bool:
|
|
74
|
+
return self.start is not None and self.end is not None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@dataclass
|
|
78
|
+
class DocumentResult:
|
|
79
|
+
id: str
|
|
80
|
+
title: str
|
|
81
|
+
text: str | None
|
|
82
|
+
chunks: list[ChunkResult]
|
|
83
|
+
issues: list[Issue] = field(default_factory=list) # document-level issues only
|
|
84
|
+
gaps: list[tuple[int, int]] = field(default_factory=list)
|
|
85
|
+
overlaps: list[tuple[int, int]] = field(default_factory=list)
|
|
86
|
+
coverage: float | None = None # share of non-whitespace source chars inside a chunk
|
|
87
|
+
run: str | None = None # which chunking run (see chunkscope.compare)
|
|
88
|
+
|
|
89
|
+
@property
|
|
90
|
+
def all_issues(self) -> list[Issue]:
|
|
91
|
+
found = list(self.issues)
|
|
92
|
+
for chunk in self.chunks:
|
|
93
|
+
found.extend(chunk.issues)
|
|
94
|
+
return found
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@dataclass
|
|
98
|
+
class Report:
|
|
99
|
+
title: str
|
|
100
|
+
documents: list[DocumentResult]
|
|
101
|
+
size_unit: str
|
|
102
|
+
max_size: int | None = None
|
|
103
|
+
min_size: int | None = None
|
|
104
|
+
frameworks: list[str] = field(default_factory=list)
|
|
105
|
+
query: str | None = None
|
|
106
|
+
color_by: str = "chunk" # default colouring in the report: chunk, size, issues, score, meta:<key>
|
|
107
|
+
color_metadata: list[str] = field(default_factory=list) # metadata keys offered as colourings
|
|
108
|
+
theme: str = "auto" # auto, light or dark
|
|
109
|
+
runs: list[str] = field(default_factory=list)
|
|
110
|
+
|
|
111
|
+
@property
|
|
112
|
+
def chunks(self) -> list[ChunkResult]:
|
|
113
|
+
return [chunk for doc in self.documents for chunk in doc.chunks]
|
|
114
|
+
|
|
115
|
+
@property
|
|
116
|
+
def issues(self) -> list[Issue]:
|
|
117
|
+
return [issue for doc in self.documents for issue in doc.all_issues]
|
|
118
|
+
|
|
119
|
+
def summary(self) -> dict[str, Any]:
|
|
120
|
+
"""Headline numbers, handy for tests, CI gates and logging."""
|
|
121
|
+
sizes = sorted(chunk.size for chunk in self.chunks)
|
|
122
|
+
counts = {"error": 0, "warning": 0, "info": 0}
|
|
123
|
+
for issue in self.issues:
|
|
124
|
+
counts[issue.severity] += 1
|
|
125
|
+
coverages = [doc.coverage for doc in self.documents if doc.coverage is not None]
|
|
126
|
+
return {
|
|
127
|
+
"documents": len(self.documents),
|
|
128
|
+
"chunks": len(sizes),
|
|
129
|
+
"size_unit": self.size_unit,
|
|
130
|
+
"min_size": sizes[0] if sizes else 0,
|
|
131
|
+
"median_size": _median(sizes),
|
|
132
|
+
"max_size": sizes[-1] if sizes else 0,
|
|
133
|
+
"over_limit": sum(s > self.max_size for s in sizes) if self.max_size else 0,
|
|
134
|
+
"errors": counts["error"],
|
|
135
|
+
"warnings": counts["warning"],
|
|
136
|
+
"infos": counts["info"],
|
|
137
|
+
"coverage": min(coverages) if coverages else None,
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
def _repr_html_(self) -> str: # Jupyter display
|
|
141
|
+
from .render import render_notebook
|
|
142
|
+
|
|
143
|
+
return render_notebook(self)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _median(sorted_values: list[int]) -> float:
|
|
147
|
+
if not sorted_values:
|
|
148
|
+
return 0
|
|
149
|
+
middle = len(sorted_values) // 2
|
|
150
|
+
if len(sorted_values) % 2:
|
|
151
|
+
return sorted_values[middle]
|
|
152
|
+
return (sorted_values[middle - 1] + sorted_values[middle]) / 2
|
chunkscope/py.typed
ADDED
|
File without changes
|