Metadata-Version: 2.5
Name: tabula-razer
Version: 0.1.0b2
Summary: Standalone OpenContracts structured data extraction: run a fieldset against any OpenContracts-compatible API and emit one JSONL per field.
Project-URL: Homepage, https://github.com/Open-Source-Legal/tabula-razer
Project-URL: Documentation, https://github.com/Open-Source-Legal/tabula-razer#readme
Project-URL: Issues, https://github.com/Open-Source-Legal/tabula-razer/issues
Author: OpenContracts contributors
License-Expression: MIT
License-File: LICENSE
Keywords: extraction,legal,llm,opencontracts,pydantic-ai
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Legal Industry
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Text Processing :: General
Requires-Python: >=3.10
Requires-Dist: httpx<1,>=0.27
Requires-Dist: pydantic-ai-slim<2,>=1.107.10
Requires-Dist: pydantic<3,>=2.7
Requires-Dist: typing-extensions>=4.6
Provides-Extra: all
Requires-Dist: pydantic-ai-slim[anthropic,google,openai]<2,>=1.107.10; extra == 'all'
Provides-Extra: anthropic
Requires-Dist: pydantic-ai-slim[anthropic]<2,>=1.107.10; extra == 'anthropic'
Provides-Extra: google
Requires-Dist: pydantic-ai-slim[google]<2,>=1.107.10; extra == 'google'
Provides-Extra: openai
Requires-Dist: pydantic-ai-slim[openai]<2,>=1.107.10; extra == 'openai'
Provides-Extra: test
Requires-Dist: graphql-core<3.4,>=3.2; extra == 'test'
Requires-Dist: hypothesis>=6.100; extra == 'test'
Requires-Dist: plasmapdf<0.2,>=0.1.3; extra == 'test'
Requires-Dist: pytest-asyncio>=0.23; extra == 'test'
Requires-Dist: pytest-cov>=5; extra == 'test'
Requires-Dist: pytest>=8; extra == 'test'
Description-Content-Type: text/markdown

# Tabula Razer

OpenContracts' structured data extraction pipeline as a standalone Python
package. Choose a fieldset (a group of extraction columns) and a set of
documents. The CLI reads from an OpenContracts-compatible GraphQL server, an
OpenContracts corpus export, or an offline JSON bundle, and writes one JSONL
file per runnable column.

```
out/
├── effective-date.jsonl      ← column "Effective Date"
├── governing-law.jsonl       ← column "Governing Law"
├── parties.jsonl             ← column "Parties"
└── manifest.json             ← run scope, model, file names, and counts
```

## Architecture

1. **Source.** A `DocumentSource` resolves the fieldset and document
   selection. The GraphQL, corpus export and bundle adapters expose the same
   interface.
2. **Runner and index.** The asyncio runner limits concurrency, loads each
   document's text, annotations, relationships and (for PDFs) PAWLS token
   layer once, and shares its in-memory `DocumentIndex` across the selected
   columns. Parent IDs, or parent → child relationships where those are
   absent, form the section hierarchy. The index supports keyword search,
   section traversal and following relationships, with optional semantic
   search delegated to the source. See
   [Native OpenContracts layers](#native-opencontracts-layers) and
   [Relationships](#relationships).
3. **Extraction engine.** A pydantic-ai agent extracts one field from one
   document at a time. It builds a prompt from the column's query, examples,
   and fenced constraints. Short documents with full text can be included in
   the prompt. The engine validates the typed result and grounds extracted
   strings in the document text when possible.
4. **Writer.** The CLI streams results to local JSONL files and records run
   state in the manifest.

The OpenContracts server's `doc_extract_query_task` imports the package's
engine, document index, models, prompt assembly, output parsing,
diagnostics, and grounding.
The server runs its own ORM-backed extraction and persists `Datacell` records.
See the [OpenContracts integration](https://github.com/Open-Source-Legal/OpenContracts/pull/2607).

## Install

```bash
pip install "tabula-razer[openai] @ git+https://github.com/Open-Source-Legal/tabula-razer.git"
# From a clone of this repository:
pip install -e ".[all,test]"
```

Python 3.10+, Linux / macOS / Windows. Provider keys come from the usual
environment variables (`OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, ...).

## Upstream requirements

For a live run, supply an OpenContracts server base URL or its GraphQL
endpoint with `--api-url`. The server must expose the
[GraphQL reads below](#graphql-contract) and have a fieldset and processed
documents available to the caller. A corpus run requires read access to both
the corpus and the documents. Use a bearer JWT or an API key
(`--auth-scheme KEY`) for authenticated access.

The CLI reads plain text from the media URLs returned by the server, so the
machine running it needs network access to the API and the media host.
Annotations supply section structure and retrieval. Server-side semantic
search is optional. If the source lacks a plain-text extract, the engine uses
reconstructed annotation excerpts. An explicit null based on excerpts is
recorded as `insufficient_document_text` because absence is unverified.

For PDFs the source also reads the PAWLS token layer (`pawlsParseFile`) and
each annotation's native `json` position, so annotations are placed by their
tokens and grounded values carry bounding boxes. Without them, annotations
are located by searching for their text.

Two offline sources replace the API:

- `--oc-export` reads an OpenContracts corpus export (V1, V2 or V3) as it
  is. Pass the export ZIP, its extracted directory, or its `data.json`.
  Exports carry no extraction columns, so `--fieldsets` supplies them, in
  the bundle's `fieldsets` shape.
- `--bundle` reads a local JSON file containing fieldsets, documents, text
  or text-file references, annotations and, optionally, relationships,
  document relationships and PAWLS layers. Unknown keys are rejected rather
  than ignored.

Every run uses the configured model provider for inference. Use
`--model test` to exercise the pipeline with a local test model.

## Command line

```bash
export OC_API_TOKEN=...     # a JWT or an API key (--auth-scheme KEY)

# every document in a corpus
tabula-razer run --api-url https://contracts.example.com \
  --fieldset 12 --corpus 4 --output-dir out/ --model openai:gpt-4o-mini

# specific documents (add --corpus to include that corpus's non-structural annotations)
tabula-razer run --api-url ... --fieldset 12 --document 101 --document 102 --output-dir out/

# the documents of an existing server extract (its fieldset is used unless --fieldset is given)
tabula-razer run --api-url ... --extract 31 --output-dir out/

# see what a fieldset will do before spending tokens
tabula-razer fieldset --api-url ... --fieldset 12

# an OpenContracts corpus export, no server; --corpus is the export's corpus.id
tabula-razer run --oc-export corpus_export.zip --fieldsets fieldsets.json \
  --fieldset fs-nda --corpus 7 --output-dir out/
```

`run` prints the JSONL paths (one per extracted column) to stdout. Progress
and a summary go to stderr. IDs can be Relay global IDs or numeric primary
keys.

| Flag | Default | Meaning |
|---|---|---|
| `--model` | `openai:gpt-4o-mini` | Any pydantic-ai model spec. `test` makes no LLM calls (plumbing check). `openai:gpt-5.6*` is routed to the Responses API automatically. |
| `--concurrency` | 4 | Concurrent cells, and documents held in memory. |
| `--request-limit` | 20 | Model requests allowed per cell. |
| `--full-text-char-limit` | 24000 | Documents this short are inlined into the prompt. |
| `--no-semantic-search` | off | Drop the server-side `semanticSearch` tool; keyword search over annotations is always available. |
| `--no-grounding` | off | Skip locating extracted strings in the text. |
| `--no-layout` | off | Ignore PDF token layers: locate annotations by text search and ground values without bounding boxes. |
| `--hierarchy-label` | `OC_PARENT_CHILD` | Relationship label read as parent → child edges where annotations have no `parent_id` (repeatable, added to the default). |
| `--oc-export` / `--fieldsets` | — | Read an OpenContracts corpus export natively, with fieldsets from a JSON file. |
| `--include-llm-log` | off | Store each cell's full message history. |
| `--resume` | off | Keep `completed` / `not_found` lines in `--output-dir` and run the rest. |
| `--strict` | off | Exit 3 if any cell failed. |

From the repository root, run the bundled example with the local test model.

```bash
tabula-razer run --bundle tests/fixtures/nda_bundle.json \
  --fieldset fs-nda --corpus corpus-ndas --output-dir out/ --model test
```

## Outputs

Each runnable column gets a `<column>.jsonl` file with one
`ExtractionRecord` per resolved document. A row includes document and column
IDs, the typed value or failure details, source annotation IDs, grounding
spans, model usage, and timestamps. The file is flushed as each cell finishes,
so row order follows completion order.

```json
{"schema_version": 1, "fieldset_id": "RmllbGRzZXRUeXBlOjEy", "column_id": "...",
 "column_name": "Governing Law", "document_id": "...", "document_title": "Mutual NDA",
 "status": "completed", "data": "the State of Delaware", "output_type": "str",
 "extract_is_list": false,
 "sources": ["QW5ub3RhdGlvblR5cGU6OTE="],
 "grounding": [{"query_text": "the State of Delaware", "matched_text": "the State of Delaware",
                "char_start": 1840, "char_end": 1861, "match_type": "exact", "match_quality": 1.0,
                "annotation_ids": ["QW5ub3RhdGlvblR5cGU6OTE="]}],
 "failure_mode": null, "error": null, "model": "openai:gpt-4o-mini",
 "usage": {"requests": 3, "input_tokens": 5120, "output_tokens": 64},
 "started_at": "...", "completed_at": "..."}
```

- **`status`**: one of
  - `completed`: a value was extracted;
  - `not_found`: the agent explicitly committed to "not in this document" (`failure_mode: agent_committed_none`);
  - `failed`: no answer. `failure_mode` says why:
    - from the server's vocabulary: `usage_limit_exceeded`, `tool_loop_no_output`, `no_final_response`;
    - added by this package: `invalid_output`, `invalid_column`, `document_load_failed`, `insufficient_document_text`, `exception`.
- **`sources`**: annotation IDs the agent's tools surfaced while answering. These are the citations, the same signal as the server's `Datacell.sources`.
- **`grounding`**: where each extracted string sits in the document text, plus the most specific annotations containing it. Each span also gives its OpenContracts-native location, ready to highlight or import as an annotation:
  - **`annotation_type`**: `TOKEN_LABEL` for a PDF whose PAWLS layer is in use, otherwise `SPAN_LABEL`;
  - **`page`**: for a token location, its first page;
  - **`annotation_json`**: for a token location, per page the `bounds`, `tokensJsons` and `rawText` PlasmaPDF would give the match, as the server does; for a span, `{start, end, text}`;
  - **`page_sizes`**: for a token location, each page's `{width, height}` in PDF points, to scale the bounds.

  These are `null` when the text was rebuilt from annotations.

From the test export (`tests/oc_export_fixture.py`), the match ends inside
the token `Delaware.`, and the location covers that whole token:

```json
"grounding": [{"query_text": "the State of Delaware", "matched_text": "the State of Delaware",
  "char_start": 236, "char_end": 257, "match_type": "exact", "match_quality": 1.0,
  "annotation_ids": ["102", "s-3-p"], "annotation_type": "TOKEN_LABEL", "page": 1,
  "annotation_json": {"1": {"bounds": {"top": 146.935, "bottom": 159.365, "left": 208.0, "right": 516.65},
    "tokensJsons": [{"pageIndex": 1, "tokenIndex": 20}, {"pageIndex": 1, "tokenIndex": 21},
                    {"pageIndex": 1, "tokenIndex": 22}, {"pageIndex": 1, "tokenIndex": 23}],
    "rawText": "the State of Delaware."}},
  "page_sizes": {"1": {"width": 612.0, "height": 792.0}}}]
```

The manifest records the source and selection, model settings, document
count, each column's file name and status counts, and skipped columns. The
runner creates it before writing rows and sets `finished_at` when the run
finishes. `--resume` validates the source, fieldset definition, corpus,
extract, and resolved document set, then keeps settled rows and reruns the
rest. Start in a fresh directory if earlier output lacks a run identity.

The `skipped_columns` list covers manual-entry metadata columns, columns
with a custom server-side `task_name`, and columns with neither `query` nor
`match_text`.

## Native OpenContracts layers

OpenContracts positions PDF annotations in token space: page → token
indices plus a bounding box, over the document's PAWLS layer. Its plain-text
layer is derived from the same tokens (PlasmaPDF joins every token's text, in
order, with one space), so a character offset and a token index are two views
of one layer. Nothing needs converting down. Tabula Razer keeps each
annotation's `annotation_json` as stored (v1 `tokensJsons`, compact v2 ranges,
or a `{start, end, text}` span), along with `link_url` and
`content_modalities`.

Per document, the index builds a compact `LayoutIndex` from the PAWLS layer,
holding each token's character range and box, and each page's size, in flat
arrays, and then drops the parsed pages. The index maps both ways:

- **Inbound.** An annotation's token references become its exact character
  segments. This places annotations a text search would put at the wrong
  occurrence of repeated boilerplate, and ones it cannot find at all: OCR'd
  `rawText`, or text holding the `´` / `⋅` the text layer normalises.
  Tokens join one segment only while nothing but image or empty tokens
  separate them, so an annotation over tokens that are not adjacent covers
  each run and never the text between. Containment, citations and grounding
  use the segments; `DocumentIndex.span()` gives the extent, for ordering.
- **Outbound.** A grounded character span becomes token `annotation_json`
  as PlasmaPDF's `convert_doc_span_to_opencontract_annotation_json`
  projects it: every text token the span touches plus image tokens inside
  it, `rawText` joined PlasmaPDF's way, and `bounds` widened by
  `0.1 × size / 2` per side, capped at 1pt vertically and 5pt horizontally,
  so every token box stays enclosed. PlasmaPDF pads pages before the last
  from a box that also counts the next page's first token; every page here
  gets its last-page rule instead.

The layer is used only when the text it derives matches the document's
text. Only differences that move no offset are allowed: the 1:1 look-alike
replacements PlasmaPDF versions disagree on (`‘ ’ ´` → `'`, `⋅` → `.`) and
trailing whitespace. Real server text layers differ in exactly those ways.
Any other mismatch (logged as a warning for PDFs), DOCX display PAWLS, or an
unreadable layer falls back to text search, with no annotation dropped. A
PDF with no plain-text extract takes the derived text, and so does a PDF in
a corpus export, as the server's importer does.

Property tests (`tests/test_layout.py`, `tests/test_index_layout.py`) check
over generated layers that no content is clipped or lost:
- every token's text appears in the derived text, whole and in order,
  identical to PlasmaPDF's;
- token references resolve to segments that hold every referenced token
  whole and no text of any token they do not reference;
- projections keep every token the span touches, with bounds that enclose
  each token box, and equal PlasmaPDF's tokens, `rawText` and bounds;
- compact and verbose encodings carry the same tokens;
- annotations larger than the server's 50,000-token decode limit are not
  truncated;
- the alignment check accepts look-alike folds and trailing whitespace, and
  rejects any other character change, insertion or deletion.

Text and projection parity are checked against PlasmaPDF (a test
dependency), the library the server builds its PDF text layer and grounding
boxes with. Bounds are compared on single-page spans and last pages, and
spans ending at offset 1 or earlier are skipped, where PlasmaPDF records the
first token one character late. Two deliberate differences from the
server's own decoders:
- a malformed compact page or token keeps its position as an empty
  placeholder rather than being dropped, so later references still resolve;
- spans are computed from range ends, so the decode limit never applies.

Set `OC_EXPORT_FIXTURE` to a real corpus export to check that every token
annotation in it places on its own `rawText` and maps back to exactly its
own tokens. For example, the OpenContracts repository's
`opencontractserver/tests/fixtures/Test_Corpus_EXPORT.zip` passes.

## GraphQL contract

The GraphQL adapter implements `oc_extract.sources.DocumentSource` using
these reads.

| Method | OpenContracts GraphQL field used |
|---|---|
| `get_fieldset` | `fieldset(id) { fullColumnList }` |
| `get_extract` | `extract(id) { fieldset corpus fullDocumentList }` |
| `list_documents` | `corpus(id) { documents }` (paginated) / `document(id)` (alias-batched) |
| `get_document_text` | `document { txtExtractFile }` (resolved at document load; storage requests use a separate client) |
| `get_pawls_pages` *(PDFs)* | `document { pawlsParseFile }` (fetched like the text) |
| `get_annotations` | `document { allAnnotations(corpusId:) { … json linkUrl contentModalities parent { id } annotationLabel { … } } }` |
| `get_relationships` | `document { allRelationships(corpusId:) { id structural relationshipLabel sourceAnnotations targetAnnotations } }`, endpoints past 100 paged through `relationship(id:)` |
| `get_document_relationships` | `document { allDocRelationships(corpusId:) { id relationshipType data annotationLabel sourceDocument targetDocument } }` |
| `semantic_search` *(optional)* | `semanticSearch(documentId:, corpusId:)` |

Custom `DocumentSource` adapters can feed the same runner. They implement
`checkpoint_identity()` to support resume, and may implement
`get_pawls_pages()` to return a PAWLS layer (v1 or compact),
`get_relationships()` and `get_document_relationships()`.

## Corpus exports

`OpenContractsExportSource` (`--oc-export`) reads an export's `data.json` as
the server writes it:

- **Documents** are `annotated_docs`, keyed by file name, which becomes the
  document ID. Each document's `content` and `pawls_file_content` are its
  layers, falling back to its structural set for either.
- **Annotations** are `labelled_text` plus the parser's
  `structural_annotations` from `structural_annotation_sets`, matched by the
  document's `structural_set_hash`. `parent_id` links may cross between the
  two groups.
- **Labels.** `annotationLabel` resolves through `text_labels`, by label key
  for labelled annotations and by name for structural ones, as the server
  writes them.
- **Relationships** are the document's `relationships`, its structural set's
  `structural_relationships` and the corpus-level `relationships` that touch
  its annotations, labelled by name.

The export's `corpus.id` selects every document except the V3 `Readme.CAML`
article. The PDFs in the ZIP are not read. `from_paths` parses `data.json`
one document at a time and keeps each token layer as minified JSON text,
about a tenth of its parsed size, until its document loads, so the whole
export is never held parsed at once.

A bundle can carry the same layers: `pawls_file_content` (or `pawls_path`)
and `relationships` on a document, and `annotation_json` on an annotation.

## Relationships

Relationships link source annotations to target annotations under a label
(`Relationship`: `id`, `label`, `source_annotation_ids`,
`target_annotation_ids`, `structural`). They come from every source: a
bundle document's `relationships`, the three places an export keeps them,
or GraphQL `allRelationships`.

- **Structure.** Where annotations have no `parent_id`, relationships with a
  hierarchy label make the tree: `OC_PARENT_CHILD`, plus any
  `--hierarchy-label` (source parent → target children; the first listed
  wins if several name a parent). If neither gives any hierarchy, the
  server's `OC_SUBTREE_GROUP` rows do: each annotation's parent is the
  smallest group holding it. Groups are capped at 500 descendants, so this
  can skip a level but never names a non-ancestor. GraphQL skips those rows,
  which the server derives from the parent links and `OC_PARENT_CHILD` rows
  it already reads.
- **Links.** Every other relationship is something the agent can follow.
  Annotations carry a `relationship_count`, and `get_related_annotations`
  lists each relationship's label, this annotation's role (source or
  target) and the annotations on the other side. Ones in other documents
  are given by ID. What it surfaces is cited in `sources`. The tool and its
  prompt line appear only for documents that have relationships.

Document relationships link whole documents (`DocumentRelationship`:
`relationship_type` RELATIONSHIP or NOTES, `label`, the two document IDs and
titles, and `data`, the relationship's JSON payload, kept verbatim). They
come from GraphQL `allDocRelationships` or a bundle's top-level
`document_relationships`; corpus exports carry none.
`get_document_relationships` gives the agent each link's direction, the
other document and its data (cut short past 4,000 characters for the
prompt, never in the model). The tool and its prompt line appear only for
documents that have such links.

## Python API

```python
from oc_extract import DocumentSelection, EngineConfig, OpenContractsGraphQLSource, run_extraction

async with OpenContractsGraphQLSource("https://contracts.example.com", token=token) as source:
    result = await run_extraction(
        source,
        fieldset_id="12",
        selection=DocumentSelection(corpus_id="4"),
        output_dir="out",
        config=EngineConfig(model="anthropic:claude-sonnet-5-5"),
    )
result.files          # [Path("out/effective-date.jsonl"), ...]
```

`extract_column(DocumentContext, Column, ...)` runs a single cell when you
need finer control.

## Agent tools

| Tool | Purpose |
|---|---|
| `similarity_search` | Server-side vector search (when the source supports it) |
| `search_annotations` | IDF-weighted keyword search; filter by structural / label |
| `get_document_outline` | Section tree of structural annotations |
| `get_annotation` | One annotation with its ancestors and children |
| `get_related_annotations` | Annotations linked by labelled relationships (only when the document has any) |
| `get_document_relationships` | Links to other documents, with their data (only when the document has any) |
| `get_subtree_text` | A section's full text from its heading |
| `list_annotation_labels` | Labels present, with counts |
| `load_document_text` | Raw text slices |

## Development

```bash
pip install -e ".[test]"
python -m pytest
```

The tests make no network or LLM calls:

- the GraphQL client runs against a fake OpenContracts server using the
  checked-in [SDL fixture](tests/fixtures/opencontracts.graphql);
- the agent runs on pydantic-ai's `FunctionModel` / `TestModel`.

Set `OC_GRAPHQL_SCHEMA` to the path of an OpenContracts checkout's
`config/graphql/schema.graphql` to run the same tests against its full
GraphQL contract. Set `OC_EXPORT_FIXTURE` to a corpus export to check
native placement on real data (see
[Native OpenContracts layers](#native-opencontracts-layers)).

## Publishing

PyPI Trusted Publishing uses project `tabula-razer`, GitHub owner
`Open-Source-Legal`, repository `tabula-razer`, workflow `publish.yml`,
and environment `pypi`.

Publish a GitHub release tagged with the package version prefixed by `v`,
such as `v0.1.0b1`. The workflow runs CI on that commit, builds and checks
the wheel and source distribution, then uploads them to PyPI using OIDC.
Run the workflow manually to build and validate the GitHub Actions artifact.
