Metadata-Version: 2.5
Name: chunkscope
Version: 0.2.1
Summary: See how your RAG chunking splits your documents: an offline HTML report for any chunker or framework.
Project-URL: Homepage, https://belarif.com/chunkscope
Project-URL: Documentation, https://belarif.com/chunkscope
Project-URL: Repository, https://github.com/spydersy/chunkscope
Project-URL: Issues, https://github.com/spydersy/chunkscope/issues
Project-URL: Changelog, https://github.com/spydersy/chunkscope/blob/main/CHANGELOG.md
Author-email: Achraf Belarif <contact@belarif.com>
License-Expression: MIT
License-File: LICENSE
Keywords: chunking,embeddings,llm,rag,retrieval,text-splitting,visualization
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Text Processing
Classifier: Typing :: Typed
Requires-Python: >=3.10
Provides-Extra: hf
Requires-Dist: tokenizers>=0.15; extra == 'hf'
Provides-Extra: tiktoken
Requires-Dist: tiktoken>=0.5; extra == 'tiktoken'
Description-Content-Type: text/markdown

# chunkscope

**Documentation: [belarif.com/chunkscope](https://belarif.com/chunkscope)**

**See how your RAG chunking splits your documents.** One line in your existing pipeline produces an offline HTML report. The report shows every chunk in place in the source text, where chunks overlap, which text ended up in no chunk, the size distribution, and the boundary bugs that quietly hurt retrieval.

- **Any chunking method:** fixed-size, recursive, sentence, Markdown or heading-aware, semantic, LLM-based, hierarchical, or your own.
- **Any framework, or none:** plain strings and dicts, LangChain, LlamaIndex, Haystack, Chonkie, Docling, Unstructured. Detection is automatic, and chunkscope imports none of them.
- **Any file type:** chunkscope shows the text your chunker actually received (from PDF, DOCX, HTML, Markdown, code…). Many chunking bugs are really extraction bugs, and this makes them visible.
- **Private by design:** the report is one HTML file with no network access (enforced by a Content-Security-Policy), no CDN and no telemetry. Safe for confidential documents.
- **No dependencies:** standard library only. Tokenizers are optional extras.

> Status: alpha (0.2.1). The API may still change. LangChain, LlamaIndex, Haystack and Chonkie are tested against the real libraries; Docling and Unstructured support is based on their documented output and not yet tested against the libraries themselves. Reports of problems are welcome in the [issues](https://github.com/spydersy/chunkscope/issues).

## All methods

| Call | Use it to |
|---|---|
| `chunkscope.report(chunks, source=...)` | analyze and write the HTML report in one call |
| `chunkscope.analyze(chunks, source=...)` | get a `Report` to inspect, test or save later |
| `chunkscope.compare({"a": chunks_a, "b": chunks_b}, source=...)` | compare several chunkings in one report |
| `chunkscope.save(report, "file.html")` | write a `Report` to a file |
| `chunkscope.render_html(report)` | get the page as a string, to serve or store it yourself |
| `report.summary()`, `report.issues` | use the results in code and tests |
| `chunkscope.tokenizers.*` | count sizes like your embedding model (tiktoken, Hugging Face, words) |
| `chunkscope report` / `chunkscope compare` | the same from the command line |

The full guide, with a live example report, is at **[belarif.com/chunkscope](https://belarif.com/chunkscope)**. Every parameter, return value, error and usage is also documented in **[docs/API.md](https://github.com/spydersy/chunkscope/blob/main/docs/API.md)**. How to read and use the HTML report is explained in **[docs/REPORT.md](https://github.com/spydersy/chunkscope/blob/main/docs/REPORT.md)**.

## Install

```bash
pip install chunkscope                 # core, no dependencies
pip install "chunkscope[tiktoken]"     # count sizes with tiktoken
pip install "chunkscope[hf]"           # count sizes with a Hugging Face tokenizer
```

## Quick start

```python
import chunkscope

chunks = my_chunker(text)              # strings, dicts or framework objects
chunkscope.report(chunks, source=text) # writes chunkscope-report.html
```

Open `chunkscope-report.html` in any browser. Pass `open_browser=True` to open it automatically. In Jupyter, `chunkscope.analyze(chunks, source=text)` displays the report inline.

### With a framework

```python
# LangChain: add_start_index=True gives exact offsets
splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50, add_start_index=True)
chunks = splitter.split_documents(docs)
chunkscope.report(chunks, sources=docs)            # chunks are matched to their document

# LlamaIndex
nodes = SentenceSplitter(chunk_size=256).get_nodes_from_documents(documents)
chunkscope.report(nodes, sources=documents)

# Haystack
chunks = DocumentSplitter(split_by="word", split_length=150).run(documents=docs)["documents"]
chunkscope.report(chunks, sources=docs)

# Chonkie: one list of chunks per text, paired with the sources by position
batches = RecursiveChunker(chunk_size=512).chunk_batch(texts)
chunkscope.report(batches, sources=texts)
```

### Count sizes like your embedding model

```python
from chunkscope.tokenizers import huggingface_counter, tiktoken_counter

chunkscope.report(chunks, source=text, token_counter=huggingface_counter("BAAI/bge-small-en-v1.5"), max_tokens=512)
chunkscope.report(chunks, source=text, token_counter=tiktoken_counter("cl100k_base"), max_tokens=8191)
chunkscope.report(chunks, source=text, token_counter=my_model.tokenizer)   # any tokenizer with .encode()
chunkscope.report(chunks, source=text, token_counter=lambda t: len(t.split()))
```

Without a counter, sizes are in characters, and the report says so.

### Command line

```bash
chunkscope report chunks.jsonl --source guide.md --tokenizer tiktoken:cl100k_base --max-tokens 512 --open
chunkscope report chunks.jsonl --source-dir ./docs          # chunks carry doc_id / source paths
chunkscope report chunks.jsonl --source guide.md --fail-on error   # exit code 3 in CI if errors exist
chunkscope report hits.jsonl --source guide.md --query "how fine for espresso?"   # chunks with a "score" field
chunkscope report chunks.jsonl --source guide.md --color-by meta:section --theme dark
```

`chunks.jsonl` holds one chunk per line, for example `{"text": "...", "start": 0, "end": 512, "doc_id": "guide.md", "metadata": {...}}`. Only `text` is required.

## What the report shows

- **Overview:** chunk count, size distribution histogram, limit violations, coverage per document, and issues grouped by type.
- **Source view:** the document with each chunk highlighted in place, a marker where each chunk starts, overlaps striped, and uncovered text in red. Click any text to inspect its chunk.
- **Chunk cards:** text, size, offsets, metadata, alignment status and issues, with a filter to show only problem chunks.

### Checks

| Check | Severity | Meaning |
|---|---|---|
| `over_limit` / `under_limit` | error / warning | chunk is larger than `max_tokens` or smaller than `min_tokens` |
| `empty` | error | chunk has no text |
| `gaps` | warning | source text that is in no chunk, so it cannot be retrieved |
| `split_code_block` | warning | a code fence is opened or closed in another chunk |
| `starts_in_table` / `ends_in_table` | warning | table rows are separated from their header or from the rest of the table |
| `starts_mid_word` / `ends_mid_word` | warning | boundary cuts a word |
| `heading_only` | warning | chunk is just a heading, with its content elsewhere |
| `unmatched` | warning | chunk text cannot be found in the source |
| `offset_mismatch` | warning | the chunk's own offsets point to the wrong text |
| `ends_mid_sentence` | info | boundary falls inside a sentence |
| `partial` | info | the chunker transformed the text (added headers or context); only part of it was found |
| `duplicate` | info | same text as an earlier chunk |

## How chunks are placed

chunkscope works at three fidelity levels, so every chunker works:

1. **Exact:** the chunk carries character offsets that match the source (LangChain `start_index`, LlamaIndex `start_char_idx`, Haystack `split_idx_start`, Chonkie `start_index`).
2. **Aligned:** text only, or wrong offsets. chunkscope searches the source: first an exact match, then a match that ignores whitespace, then a piece-by-piece match for transformed chunks (`partial`).
3. **Unplaced:** text that cannot be found, or no source given. The chunk is still listed, measured and checked.

## Visualization options

Every report lets you switch between these views with the **Colour by** menu, and a **Theme** button toggles automatic, light and dark.

| Colour by | Shows |
|---|---|
| Chunk | alternating colours, to tell neighbouring chunks apart (default) |
| Size | one blue scale from small to large; chunks over `max_tokens` in red |
| Issues | the worst issue of each chunk: info, ▲ warning, ✕ error |
| Retrieval score | one orange scale from low to high score; unscored chunks dimmed |
| Metadata: *key* | one colour per value of a metadata field (section, page, heading…), with a legend; picked automatically or with `color_metadata=` |

Above the source text, the **chunk map** shows the whole document as a strip of bars: one bar per chunk, overlapping chunks on extra rows, gaps in red. Click a bar to jump to its chunk.

### See what a query retrieves

```python
hits = vectorstore.similarity_search_with_score(query, k=len(chunks))   # LangChain: (Document, score) pairs
chunkscope.report(hits, sources=docs, query=query)

nodes = retriever.retrieve(query)                                       # LlamaIndex: NodeWithScore
chunkscope.report(nodes, sources=documents, query=query)

chunkscope.report(chunks, source=text, scores=my_scores, query=query)  # any retriever: one score per chunk
```

The report opens coloured by score, with a ranked table of the best chunks and a "retrieval rank" order for the chunk cards. `scores=` takes a list aligned with the chunks, or a mapping `{position or chunk id: score}` for a subset.

### Compare chunkings

```python
result = chunkscope.compare(
    {"500 / 50": splitter_a.split_documents(docs), "1000 / 100": splitter_b.split_documents(docs)},
    sources=docs,
    max_tokens=512,
)
chunkscope.save(result, "compare.html")
```

The overview gets a table comparing the runs. Every document gets a **Compare runs** tab with the chunk map of each run on the same scale. From the command line: `chunkscope compare small.jsonl large.jsonl --source guide.md` (each file name is a run label).

## Programmatic use

```python
result = chunkscope.analyze(chunks, source=text, max_tokens=512)
result.summary()       # {'chunks': 42, 'median_size': 380, 'over_limit': 2, 'errors': 2, 'coverage': 0.97, ...}
result.issues          # list of Issue(code, severity, message, chunk)
chunkscope.save(result, "report.html")
```

Use it in a test to keep your chunking honest:

```python
def test_chunking_quality():
    summary = chunkscope.analyze(chunk(doc), source=doc, max_tokens=512).summary()
    assert summary["errors"] == 0 and summary["coverage"] > 0.99
```

## Development

```bash
uv venv && uv pip install -e . pytest
pytest -m "not integration"                       # fast unit tests
uv pip install --group integration && pytest      # also run real LangChain, LlamaIndex, Haystack, Chonkie
python examples/quickstart.py                     # writes examples/output/quickstart.html
python examples/demo_site.py                      # the full demo: 7 fictional docs, 3 chunkers, every check
```

Design decisions are recorded in [docs/DESIGN.md](https://github.com/spydersy/chunkscope/blob/main/docs/DESIGN.md).

## License

MIT
