Metadata-Version: 2.4
Name: jubarte-docx
Version: 0.21.0
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Legal Industry
Classifier: Operating System :: MacOS
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
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: Programming Language :: Rust
Classifier: Topic :: Office/Business :: Office Suites
Classifier: Topic :: Text Processing :: Markup :: XML
Classifier: Typing :: Typed
Requires-Dist: mcp>=2.2,<3 ; extra == 'mcp'
Provides-Extra: mcp
License-File: LICENSE
License-File: NOTICE
Summary: Word-faithful DOCX redline engine — compare two Word documents into a tracked-changes document that opens cleanly in Microsoft Word; list, accept, or reject revisions; render DOCX to PDF
Keywords: docx,redline,track-changes,tracked-changes,word,microsoft-word,openxml,ooxml,compare,diff,pdf,docx-to-pdf,markdown,criticmarkup,ai-agents
Author-email: "Jandira Technologies, LLC" <arthur@jandira.tech>
Maintainer-email: "Jandira Technologies, LLC" <arthur@jandira.tech>
License-Expression: Apache-2.0
Requires-Python: >=3.10
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Changelog, https://github.com/jandira-tech/jubarte/blob/main/CHANGELOG.md
Project-URL: Documentation, https://github.com/jandira-tech/jubarte/blob/main/docs/python.md
Project-URL: Homepage, https://github.com/jandira-tech/jubarte
Project-URL: Issues, https://github.com/jandira-tech/jubarte/issues
Project-URL: Repository, https://github.com/jandira-tech/jubarte

<!--
SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC

SPDX-License-Identifier: Apache-2.0
-->

<!-- Generated by scripts/library_readmes.py from README.md and jubarte-python/README.fragment.md for v0.21.0 (README.md sha256 43fc6a04ea82b6d7). Edit those, not this file. -->

> **See every page side by side: [jandira-tech.github.io/neurotic_docx_bench](https://jandira-tech.github.io/neurotic_docx_bench/)**  
> jubarte vs Microsoft Word, docxide-pdf, LibreOffice, PyMuPDF Pro, MiniPdf, rdocx and office2pdf on 808 documents, DOCX to PDF, scored per page.

# jubarte-docx (Python)

[![PyPI](https://img.shields.io/pypi/v/jubarte-docx.svg)](https://pypi.org/project/jubarte-docx/)
[![CI](https://github.com/jandira-tech/jubarte/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/jandira-tech/jubarte/actions/workflows/ci.yml)
[![license](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](https://github.com/jandira-tech/jubarte/blob/v0.21.0/LICENSE)

Word-faithful DOCX **redline** engine: compare two Word documents into a
tracked-changes document that opens cleanly in Microsoft Word; list, accept,
or reject revisions; render DOCX to PDF.

Python bindings (PyO3 + maturin) for the Rust
[`jubarte-redlines`](https://github.com/jandira-tech/jubarte) engine.
Pure compute, no Word/LibreOffice dependency, no network, no temp files —
documents go in and come out as `bytes` (whole DOCX/PDF packages), revision
metadata comes back as parsed records (`get_revisions` → `list[dict]`,
`get_revisions_json` → JSON string), and the GIL is released while the
engine runs.

## Install

```sh
pip install jubarte-docx
# or: uv add jubarte-docx
```

Prebuilt wheels are `abi3` (one wheel per platform, CPython ≥ 3.10).

## Command line

The native `jubarte` binary offers `--keep-nested-comment` on `accept`,
`reject` and `convert --track-changes accept|reject`. These bindings do not
yet dispatch that option or return its kept-thread receipts; use the native
binary when retention is needed.

The distribution is `jubarte-docx`; the import package and the command are
both `jubarte`, as `python-dotenv` ships `dotenv`. PyPI's own `jubarte` is an
unrelated project: `pip install jubarte` and `uvx jubarte` do not install
this engine, and installing both projects in one environment breaks
whichever was installed first. `uvx --from jubarte-docx` runs the command
without installing anything:

```sh
uvx --from jubarte-docx jubarte redline original.docx modified.docx -o redline.docx --author Legal
uvx --from jubarte-docx jubarte changes redline.docx
uvx --from jubarte-docx jubarte accept redline.docx -o clean.docx --kind formatting
uvx --from jubarte-docx jubarte reject redline.docx -o original-again.docx --id r12
uvx --from jubarte-docx jubarte convert redline.docx --revisions word
uvx --from jubarte-docx jubarte read contract.docx
uvx --from jubarte-docx jubarte read contract.docx --json
uvx --from jubarte-docx jubarte edit contract.docx -p p12 --anchor "thirty" --content "sixty" -a NAME
uvx --from jubarte-docx jubarte edit contract.docx --plan plan.json --out-dir review --pdf
uvx --from jubarte-docx jubarte capabilities
uvx --from jubarte-docx jubarte --help
```

`redline` is an alias of `compare`; `python -m jubarte` runs the same
commands. `changes` lists what a document tracks, one change per line with
its short id (`r12`; `--json` for one object per line); `accept` and `reject`
take repeatable `--id` (`r12`, `r1+2`, `header1.r1`),
`--author` and `--kind` to resolve a selection and keep the rest tracked, or
everything when none is given; `read` prints the agent view with the
`<!-- p12 -->` ids edits use (`--json` the snapshot); `edit` and `add` write
`FILE_modified.docx`, or with `--out-dir` the bundle (clean copy, redline,
`patch.diff`, `report.jsonl`, optional PDF/PNG pages); `capabilities`
reports what the build can do (`--json` the manifest). Exit codes: 0
success, 1 error, 2 usage, 3 edit plan refused. Inputs are `.docx`: save a Word
97-2003 `.doc` as `.docx` first.

## Library

```python
from pathlib import Path
from jubarte import (
    compare_documents,
    get_revisions,
    accept_revisions,
    reject_revisions,
    docx_to_pdf,
)

original = Path("original.docx").read_bytes()
modified = Path("modified.docx").read_bytes()

# Word-mode compare → tracked-changes DOCX (w:ins / w:del)
redline = compare_documents(original, modified, author="Reviewer")
Path("redline.docx").write_bytes(redline)

# List revisions (the library's own records; `jubarte changes --json` is the CLI's listing)
for rev in get_revisions(redline):
    print(rev["type"], rev["author"], repr(rev.get("text")))

# Accept / reject every tracked revision, package-wide
clean = accept_revisions(redline)   # ≙ modified content
base = reject_revisions(redline)    # ≙ original content

# Render to PDF (Word-style layout)
Path("redline.pdf").write_bytes(docx_to_pdf(redline))
```

`compare_documents(original, modified, author="Redline", date=None)` stamps
revisions with a fixed epoch date by default so output is deterministic;
pass an ISO-8601 `date` to override. Errors raise
`jubarte.JubarteError`.

Both inputs are admitted under a size budget before anything is inflated
(512 MiB per file and per part, 2 GiB inflated, 10,000 entries, XML depth
256, 4,000,000 XML elements, 2,000,000 characters and elements per compared
side). `input_limits` overrides it key by key, for example
`compare_documents(a, b, input_limits={"max_uncompressed_bytes": 256 << 20})`;
the keys are `max_compressed_bytes`, `max_entries`, `max_part_bytes`,
`max_uncompressed_bytes`, `max_xml_depth`, `max_xml_elements` and
`max_story_units`. A package
past the budget
raises `JubarteError` with `INPUT_LIMIT`, and an unknown key raises
`invalid input limits`. `get_revisions_json` and
`CompareOptions(input_limits=...)` take the same mapping.

`read()` returns a `Document` — an immutable snapshot, path I/O done once, no
operation mutating it or writing files:

```python
from jubarte import read, EditPlan, diff

doc = read("contract.docx")
doc.markdown()    # body and every header/footer/notes story, <!-- pN --> id lines
doc.inspect()     # Snapshot: summary + paragraphs (ids, style, spans, limitations) + tables
doc.sha256()      # the source_sha256 guard an edit plan carries
doc.changes()     # each tracked change, with the id accept/reject and plans take
doc.accept(ids=["r12"])           # or reject(...): resolve a selection,
                                  # keep the rest tracked (no selection = all)
result = doc.render(pdf=True, png_dpi=144)  # Rendered: pdf, pngs, page report
```

The snapshot uses `schema_version: 3`. `changes` lists logical changes:
a change Word wrote as several marks is one entry with its `members`,
and a deletion and an insertion by one author that touch, in either
order, are one `replacement`.
`summary.tables` and `tables[]`
count top-level body tables only; each `index` is the view's `tN`.
Every table has a `nested` array (empty for a leaf), containing its cell tables.
A nested entry has `parent` (for example `t0.row2.cell0`) and no `index`.
A deeper parent includes the cell-local table ordinal, for example
`t0.row2.cell0.t0.row0.cell1`. Paragraph ids and edit-plan schemas are unchanged.

Python nested grids are `Table(index=None, parent=CELL_PATH, nested=(...))`;
top-level grids retain integer indices.

`doc.compare(other, author=...)` is `compare_documents`; `doc.to_pdf()` and
`doc.to_png(dpi=...)` are the one-shot renderers.

An `EditPlan` builds the tracked-changes transaction `doc.edit(plan)` applies —
all-or-nothing: a refused plan raises `EditPlanError` (stable `code`, the
failed operation, every operation's outcome) and produces nothing.
`doc.preview(plan)` resolves and reports without applying:

```python
plan = (
    EditPlan(author="Reviewer")
    .for_document(doc)             # bind to this snapshot; STALE_SOURCE if it changed
    .replace("p3", find="30 days", replacement="45 days", format={"bold": True})
    .comment("p3", text="Check with the client", find="45 days")
    .insert_paragraph("p3", runs=["New sentence."], like="p3")
)
out = doc.edit(plan)               # EditResult: clean, redline, report, diff
```

`replace`, `insert`, `delete`, `comment` and `format_run` edit run text; `insert_paragraph`,
`delete_paragraph`, `format_paragraph`, `merge_paragraphs` and `rewrite` work on
whole paragraphs; `insert_table(paragraph, rows=[[...], ...])` adds a table and
`list_paragraphs([...], kind_of_list="decimal")` (wire kind `list`) numbers
paragraphs; `insert_footnote` adds a footnote after an anchor;
`insert_image` adds a picture paragraph; `page_setup` changes the page size,
orientation and margins;
`resolving(accept={...}, reject={...})` settles existing
tracked changes first. `plan.to_json()` is exactly what `edit --plan` reads.

`diff(old, new)` shows the
changed paragraphs between two documents — or a document and Markdown text —
as `[-old-]{+new+}` marks (`format="critic"` for CriticMarkup). When a side
is a Word document, the comparer writes the changes, and a replacement inside
a paragraph keeps Word Compare's order, the insertion first: `{+new+}[-old-]`.

```python
print(diff(read("v1.docx"), read("v2.docx")))
```

`doc.append(other)` puts `other` after `doc` on a new page and
returns `Appended(document, warnings)`: images, links, headers, styles, lists
and notes come along. Comments are dropped (`COMMENTS_DROPPED` in `warnings`)
unless `comments="carry"`, which brings the comments `other`'s body anchors
with their threads and resolution. `section_break="continuous"` joins on the
same page and `keep_sections=True` keeps `other`'s page setup, headers and
footers.

Before a document goes out, or after an agent edited it:

```python
doc.validate()        # Word-validity findings beyond the schema; () is a pass
fixed = doc.repair()  # Repaired: document, repaired, remaining
doc.audit_tracked(read("original.docx"), author="Reviewer")  # untracked or foreign edits
doc.audit("a11y,structure")  # accessibility, style and structure findings by paragraph id
out = doc.scrub()     # authors as "Author", no rsids, document properties or comments
doc.update_fields()   # PAGEREF, REF, NUMPAGES, SEQ and TOC results from jubarte's layout
```

`from_markdown(text, author=..., track_changes="all")` writes Markdown as a
Word document, CriticMarkup becoming tracked changes and comments, as
`jubarte convert draft.md` does; `reference=` lends a document's styles and
page setup. A change or comment that names no author or date takes `author`
and `date` when you pass them, else the front matter's `author:` and
`last_modified:`/`modified:`/`date:`/`created:`, else `Redline` and the fixed
epoch, so the same Markdown writes the same bytes (the CLI falls back to
`--reference-doc`'s creator and creation time, then `Redline` and now).
`diff_render(a, b, dpi=100)` says which pages of two documents
look different, pixel for pixel, with magenta overlays on the changed pages.

`Document.from_bytes(data)` holds bytes you already have and `to_bytes()`
returns them; `inspect_json()` is the engine's inspect snapshot as JSON text,
unchanged (`inspect()` decodes it). `scrub` takes `author_alias`, `rsids`,
`docprops` and `comments` to choose what goes.

## Also available as

- **Rust crate**: [`jubarte`](https://crates.io/crates/jubarte) (this engine, plus a CLI)
- **npm / WebAssembly**: [`jubarte-wasm`](https://www.npmjs.com/package/jubarte-wasm) (Node and browser builds)
- **MCP server**: `pip install 'jubarte-docx[mcp]'` then `jubarte-mcp --root .` ([setup for Claude Code, Codex and Gemini CLI](https://github.com/jandira-tech/jubarte/blob/main/docs/adoption/mcp.md))

## Text comparisons

```sh
jubarte diff a.docx b.docx --format github
jubarte diff a.docx b.docx --format github -U0 --accept-changes
jubarte diff a.docx b.docx --format word
```

Line views (`github`, `normal`, `context`, `side-by-side`) retain each input’s
tracked marks. Word comparison accepts **all changes in both inputs first**,
then creates fresh CriticMarkup; earlier revision provenance disappears.
`critic` remains a representation of document content with its marks.
Long lines use a 70-character review window; `--full-lines` shows all text.
Text views support DOCX and Markdown and write stdout or an explicit `-o` text
file. CLI help and usage errors come from the shared clap-derived grammar.

## Rendering and fonts

The PDF engine reconstructs Word-oriented layout directly; it does not call
Microsoft Word or LibreOffice.

The documented rendering surface includes:

- tracked changes, and comments as Word's balloons in the markup pane
  (a resolved comment faded, a reply numbered under its thread);
- paragraph/run formatting and advanced line layout;
- CJK and RTL/complex-script text;
- installed and embedded fonts;
- merged, vertically merged, autofit and floating tables;
- DrawingML/VML graphics, text boxes, charts and SmartArt;
- raster and EMF/WMF images;
- headers, footers and floating frames;
- sections, columns, backgrounds and page borders;
- footnotes and selected fields.

Rendering fidelity still depends on fonts and on document features.
WebAssembly has no installed fonts: `docxToPdf` paints with the fonts a
document embeds and the bundled Carlito and Liberation faces, so Chinese,
Japanese or Korean text without an embedded font is not painted (see
[`KNOWN_ISSUES.md`](https://github.com/jandira-tech/jubarte/blob/v0.21.0/KNOWN_ISSUES.md), item 9).

Supplemental font lookup can be configured with:

```sh
export JUBARTE_FONT_DIR=/path/to/jubarte/fonts
export JUBARTE_FONT_INDEX=/path/to/font-index.tsv
```

Set:

```sh
export JUBARTE_FONT_INDEX=off
```

to disable the persistent font index, and:

```sh
export JUBARTE_SYSTEM_FONTS=off
```

to leave the system, Word and cloud-font folders out of the search: a render
then uses the fonts a document embeds, the faces compiled in and
`JUBARTE_FONT_DIR` alone, so it depends on no font the machine happens to
have. These variables, and `jubarte doctor` below, belong to the native
command line and Rust crates; the WebAssembly packages search no folders
and draw with the faces compiled in and the fonts a document embeds.

The Carlito and Liberation faces are compiled in by the crate's
`embedded-fonts` feature. A build without it draws with the faces of the
machine instead, and refuses a family that is neither installed there nor
covered by its open substitute with `FONT_UNAVAILABLE` (exit 1, nothing
written). `jubarte doctor` says which build it is and what the machine has:

```sh
jubarte doctor            # the faces compiled in, the folders searched, what is missing
jubarte doctor --json
```

`doctor --json` has `schema_version: 1`. Its family report covers the four
open substitutes; it is not a document-specific availability check. An
installed family outside that list can still render a document.

The `FONT_UNAVAILABLE` guarantee covers missing catalogue faces, not missing
script glyphs. CJK/Thai/Devanagari/Thaana without a covering document or
installed fallback face paint `.notdef` blanks, even if a Latin substitute
is available. `doctor` lists the installed styles of the known script
fallback candidates in `script_families`; an empty `host` means missing.
Neither this list nor the substitute list proves coverage of every glyph.

Default per-user font directories are documented in the installation section
of this repository.

For known Word-layout differences, see:

- [`docs/WORD_LAYOUT_RULES.md`](https://github.com/jandira-tech/jubarte/blob/v0.21.0/docs/WORD_LAYOUT_RULES.md)
- [`docs/WORD_DIFFERENCES.md`](https://github.com/jandira-tech/jubarte/blob/v0.21.0/docs/WORD_DIFFERENCES.md)
- [`docs/WORD_COMMENT_BALLOONS.md`](https://github.com/jandira-tech/jubarte/blob/v0.21.0/docs/WORD_COMMENT_BALLOONS.md)

## Comparison modes

The default comparison mode is:

```sh
--mode word
```

It targets Word-like comparison behavior.

Classic PowerTools behavior is available with:

```sh
--mode powertools
```

Choose explicitly if exact comparison semantics matter to a regression test
or downstream workflow.

## Supported environments

| Surface | Supported/tested target |
|---|---|
| Rust / CLI | CI tests Linux, macOS and Windows |
| Rust toolchain | Rust 1.94+ |
| Python | CPython 3.10+ |
| Python release wheels | macOS x86_64/arm64, manylinux_2_28 x86_64/arm64, musllinux_1_2 x86_64/arm64, Windows x86_64 (abi3, CPython 3.10+) |
| Node | Node 18+ |
| Browser | WebAssembly builds |
| CLI release workflow | Linux x86_64/arm64, macOS x86_64/arm64, Windows x86_64 targets |

Release assets can vary by tag. Check the
[release page](https://github.com/jandira-tech/jubarte/releases)
before scripting a binary download.

A Word 97-2003 `.doc` converts to `.docx` with the native binary's
`jubarte convert old.doc` (or `jubarte::legacy_doc::doc_to_docx` in Rust):
text, headings, lists, bold, italic and tables. Every other command, and
the Python and JavaScript packages (the npm command line too), refuse a `.doc` (or an encrypted document of any Word
version) with `LEGACY_DOC` and the hint to save it as `.docx` without a
password, and RTF with `UNSUPPORTED_PACKAGE`. Convert them to `.docx` first.

## Troubleshooting

| Problem | What to check |
|---|---|
| PDF layout differs from Word | Verify required fonts; inspect `--font-report`; read `docs/WORD_DIFFERENCES.md` |
| Text is missing or wraps differently | Check font resolution and embedded/system font availability |
| Edit exits with a refusal | Read `report.jsonl` / stdout for `STALE_SOURCE`, `ANCHOR_NOT_FOUND`, `AMBIGUOUS_ANCHOR`, `OVERLAPPING_EDITS`, `UNSUPPORTED_STRUCTURE`, etc. |
| `STALE_SOURCE` | Re-run `jubarte read` and regenerate the plan from its new `sha256:` line |
| `AMBIGUOUS_ANCHOR` | Use a paragraph ID or a more specific exact anchor |
| Document already contains revisions | List them with `jubarte changes`; explicitly accept/reject them or set an edit-plan revision policy |
| Comment is present in DOCX but missing from rendered markup | Check the documented comment-balloon limitations and `docs/WORD_COMMENT_BALLOONS.md` |
| Output page count is not exactly Word's | The renderer targets Word behavior but is independent; inspect known differences before treating page count as an invariant |
| Prebuilt archive is absent for a platform | Install with Cargo or build from source; then check the release assets for a later tag |
| Need exact package differences | Use `jubarte debug diff` and the `text`, `runs`, `xml` or `render` debug catalogs |

## License

Jubarte is licensed under the [Apache License, Version 2.0](https://github.com/jandira-tech/jubarte/blob/v0.21.0/LICENSE)
(`Apache-2.0`) from version 0.19.0. Versions 0.18.0 and earlier were
released under `AGPL-3.0-only` and stay under it.

Parts of the engine are adapted from other projects under the MIT
License, and the renderer embeds fonts under the SIL Open Font License.
A `THIRD_PARTY_NOTICES.md` names them and carries their notices: one in
each crate that adapts upstream code, one in each package that ships the
compiled engine (the Python wheel, the npm library and the release
archives), one beside the installable fonts and one for the test
documents.

## Links

[Engine comparison site](https://jandira-tech.github.io/neurotic_docx_bench/) ·
[jandira.tech](https://www.jandira.tech) ·
[Discussions](https://github.com/jandira-tech/jubarte/discussions) ·
[Support](https://github.com/jandira-tech/jubarte/blob/v0.21.0/SUPPORT.md) · [Security](https://github.com/jandira-tech/jubarte/blob/v0.21.0/SECURITY.md)

- [GitHub](https://github.com/jandira-tech/jubarte)
- [crates.io](https://crates.io/crates/jubarte)
- [docs.rs](https://docs.rs/jubarte)
- [PyPI](https://pypi.org/project/jubarte-docx/)
- [npm](https://www.npmjs.com/package/jubarte-wasm)
- [Releases](https://github.com/jandira-tech/jubarte/releases)
- [npm CLI](https://www.npmjs.com/package/jubarte-redlines)

MCP Registry installation is pending until the owner configures three
repository variables and OIDC publishing: `MCP_REGISTRY_NAMESPACE`,
`MCP_PUBLISHER_VERSION` (the pinned `mcp-publisher` release, as `vX.Y.Z`) and
`MCP_PUBLISHER_SHA256` (that archive's 64-character lowercase SHA-256). With
the namespace unset, the release skips Registry publication with a warning;
with the namespace set and either pin missing or malformed, the Registry job
fails. Direct release downloads work either way.

