chopdiff
chopdiff is a small library of tools I’ve developed to make it easier to do fairly
complex transformations of text documents, especially for LLM applications, where you
want to manipulate text, Markdown, and HTML documents in a clean way.
Basically, it lets you parse, diff, and transform text at the level of words, sentences,
paragraphs, and “chunks” (paragraphs grouped in an HTML tag like a <div>). It aims to
have minimal dependencies.
At its core is FlexDoc, an in-memory data structure that consolidates several views of
a document. The document model lives in the separately published
flexdoc package
(PyPI), which chopdiff builds on:
- Markdown block structure: headings, lists, tables, code, blockquotes, …
- Markdown inline structure: links and other inline elements
- Language structure: paragraphs, sentences, words, and the spacing between them
- Document structure: section hierarchy and TOC
Every unit is anchored back to the original text by exact character offset, so nothing
is copied and nothing drifts.
Markdown parsers give you a block/inline tree but not sentences, sizes, or rollups; NLP
tools give you sentences but not Markdown structure or exact source mapping.
FlexDoc is both: good for textual analysis of a fixed document (spans, sizes,
sections, link rollups) and as an editable model you can modify in place and then
reassemble into a clean, normalized new document.
See
flexdoc’s docs/flexdoc-spec.md
for the definitive FlexDoc design.
Example use cases:
Filter diffs: Diff two documents and only accept changes that fit a specific
filter. For example, you can ask an LLM to edit a transcript, only inserting paragraph
breaks but enforcing that the LLM can’t do anything except insert whitespace.
Or let it only edit punctuation, whitespace, and lemma variants of words.
Or only change one word at a time (e.g. for spell checking).
Backfill information: Match edited text against a previous version of a document
(using a word-level LCS diff), then pull information from one doc to another.
For example, say you have a timestamped transcript and an edited summary.
You can then backfill timestamps of each paragraph into the edited text.
Windowed transforms: Walk through a large document N paragraphs, N sentences, or N
tokens at a time, processing the results with an LLM call, then “stitching together”
the results, even if the chunks overlap.
Installation
Drop the extras if you don’t want the dependency on simplemma (it’s about 70MB).
Full deps:
# Using uv (recommended)
uv add chopdiff[extras]
# Using poetry
poetry add chopdiff -E extras
# Using pip
pip install chopdiff[extras]
Basic deps:
# Using uv (recommended)
uv add chopdiff
# Using poetry
poetry add chopdiff
# Using pip
pip install chopdiff
Comparison to Alternatives
There are full-blown Markdown and HTML parsing libs (such as
Marko and
BeautifulSoup) but these tend
to focus specifically on fully parsing documents as parse trees.
On the other end of the spectrum, there are NLP libraries (like
spaCy) that do more expensive, full language
parsing and sentence segmentation.
This is a lightweight alternative to those approaches when you are just focusing on
processing text, don’t want a big dependency (like a full XML parser or NLP toolkit) and
also want source-referenced text analysis.
Parsed blocks and sentences carry offsets back to the input text, while reassemble()
produces a normalized editable text form rather than a byte-for-byte copy of every
original blank line and leading/trailing space.
Note you may wish to also use this in conjunction with a Markdown parser or
auto-formatter, as it can make documents and diffs more readable.
You may wish to use flowmark for this alongside
chopdiff.
Overview
More on what’s here:
The FlexDoc class (from the flexdoc package)
allows parsing of documents into sentences and paragraphs.
By default, this uses only regex heuristics for speed and simplicity, but optionally
you can use a sentence splitter of your choice, like Spacy.
Tokenization using “wordtoks” (flexdoc.docs.wordtoks) that lets you measure size and
extract subdocs via arbitrary units of paragraphs, sentences, words, chars, or tokens,
with mappings between each, e.g. mapping sentence 3 of paragraph 2 to its
corresponding character or token offset.
The tokenization is simple but flexible, including whitespace (sentence or paragraph
breaks) and HTML tags as single tokens.
It also maintains exact offsets of each token in the original document text.
Word-level diffs (flexdoc.docs.token_diffs) that don’t work at the line level (like
usual git-style diffs) but rather treat whitespace, sentence, and paragraph breaks as
individual tokens. It performs LCS-style token-based diffs with
cydifflib, which is significantly faster
than Python’s built-in difflib.
Filtering of these text-based diffs based
on specific criteria.
For example, only adding or removing words, only changing whitespace, only changing
word lemmas, etc.
The TokenMapping class (flexdoc.docs.token_mapping) offers word-based mappings
between docs, allowing you to find what part of one doc corresponds with another as
token-index mappings.
search_tokens (flexdoc.docs.search_tokens) provides a simple way to search back
and forth among the tokens of a document.
That is, you can seek forward or backward to any desired token (HTML tag, word,
punctuation, or sentence or paragraph break matching a predicate) from any given
position.
Lightweight “chunking” of documents by wrapping paragraphs in <div>s to indicate
chunks. TextNode offers simple recursive parsing
around <div> tags.
This is not a general HTML parser, but rather a way to chunk documents into named
pieces. Unlike more complex parsers, the TextNode parser operates on character
offsets, so maintains the original document exactly and allows exact reassembly if
desired.
The word-based token mapping allows
transformation of documents via
sliding windows, transforming text (e.g. via an LLM call one window at a time, with
overlapping windows), then re-stitching the results back together with best
alignments.
All this is done very simply in memory, and with only regex or basic Markdown parsing to
keep things simple and with few dependencies.
chopdiff has no heavier dependencies like full XML or BeautifulSoup parsing or Spacy
or nltk for sentence splitting (though you can use these as custom sentence parsers if
you like).
Examples
Here are a couple examples to illustrate how all this works, with verbose logging to see
the output. See the examples/ directory.
Inserting Paragraph Breaks
This is an example of diff filtering (see
insert_para_breaks.py for full code):
import argparse
import logging
from textwrap import dedent
import openai
from flowmark import fill_text
from flexdoc import FlexDoc
from chopdiff.transforms import changes_whitespace, filtered_transform, WINDOW_2K_WORDTOKS
def llm_insert_para_breaks(input_text: str) -> str:
"""
Call OpenAI to insert paragraph breaks on a chunk of text.
Note there is no guarantee this might not make other
non-whitespace changes.
"""
client = openai.OpenAI()
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a careful and precise editor."},
{
"role": "user",
"content": dedent(
f"""
Break the following text into paragraphs.
Original text:
{input_text}
Formatted text:
"""
),
},
],
temperature=0.0,
)
return response.choices[0].message.content or ""
def insert_paragraph_breaks(text: str) -> str:
# Create a FlexDoc from the input text
doc = FlexDoc.from_text(text)
print(f"Input document: {doc.size_summary()}")
# Define the transformation function.
# Note in this case we run the LLM on strings, but you could also work directly
# on the FlexDoc if appropriate.
def transform(doc: FlexDoc) -> FlexDoc:
return FlexDoc.from_text(llm_insert_para_breaks(doc.reassemble()))
# Apply the transformation with windowing and filtering.
#
# This will walk along the document in approximately 2K "wordtok" chunks
# (~1000 words) and apply the transformation to each chunk. Chunks can
# slightly overlap to make this more robust.
#
# The change on each chunk will then be filtered to only include whitespace
# changes.
#
# Finally each change will be "stitched back" to form the original document,
# by looking for the right alignment of words between the original and the
# transformed chunk.
#
# (Turn on logging to see these details.)
result_doc = filtered_transform(
doc, transform, windowing=WINDOW_2K_WORDTOKS, diff_filter=changes_whitespace
)
print(f"Output document: {result_doc.size_summary()}")
# Return the transformed text
return result_doc.reassemble()
Running this shows how it works.
Note GPT-4o-mini makes a typo correction, even though it wasn’t requested.
But the diff filter enforces that the output exactly contains only paragraph breaks: