structa-maestro 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.
- structa_maestro/__init__.py +294 -0
- structa_maestro/batch.py +564 -0
- structa_maestro/binding.py +206 -0
- structa_maestro/builder/__init__.py +0 -0
- structa_maestro/builder/result_builder.py +308 -0
- structa_maestro/cli.py +730 -0
- structa_maestro/confidence/__init__.py +49 -0
- structa_maestro/confidence/calibration.py +990 -0
- structa_maestro/confidence/normalizer.py +203 -0
- structa_maestro/config.py +111 -0
- structa_maestro/contracts/__init__.py +0 -0
- structa_maestro/contracts/enums.py +86 -0
- structa_maestro/contracts/models.py +229 -0
- structa_maestro/contracts/serialization.py +169 -0
- structa_maestro/documents/__init__.py +32 -0
- structa_maestro/documents/docx_parser.py +215 -0
- structa_maestro/documents/eml_parser.py +360 -0
- structa_maestro/documents/html_parser.py +337 -0
- structa_maestro/documents/inputs.py +277 -0
- structa_maestro/documents/loader.py +675 -0
- structa_maestro/documents/markdown_parser.py +225 -0
- structa_maestro/documents/models.py +33 -0
- structa_maestro/documents/normalization.py +24 -0
- structa_maestro/documents/pdf_parser.py +186 -0
- structa_maestro/documents/txt_parser.py +169 -0
- structa_maestro/engine.py +1201 -0
- structa_maestro/exceptions.py +38 -0
- structa_maestro/provenance/__init__.py +0 -0
- structa_maestro/provenance/associator.py +234 -0
- structa_maestro/py.typed +0 -0
- structa_maestro/review.py +1234 -0
- structa_maestro/schema/__init__.py +19 -0
- structa_maestro/schema/loader.py +616 -0
- structa_maestro/schema/models.py +269 -0
- structa_maestro/schema/pydantic_adapter.py +566 -0
- structa_maestro/schema/rules.py +526 -0
- structa_maestro/schema/serializer.py +156 -0
- structa_maestro/strategies/__init__.py +45 -0
- structa_maestro/strategies/base.py +101 -0
- structa_maestro/strategies/llm_anthropic.py +1142 -0
- structa_maestro/strategies/llm_config.py +154 -0
- structa_maestro/strategies/llm_gemini.py +1171 -0
- structa_maestro/strategies/llm_helpers.py +240 -0
- structa_maestro/strategies/llm_openai_compat.py +1183 -0
- structa_maestro/strategies/schema_compiler.py +248 -0
- structa_maestro/strategies/testing.py +71 -0
- structa_maestro/telemetry.py +800 -0
- structa_maestro/validation/__init__.py +0 -0
- structa_maestro/validation/cross_field.py +463 -0
- structa_maestro/validation/validator.py +531 -0
- structa_maestro-0.2.0.dist-info/METADATA +394 -0
- structa_maestro-0.2.0.dist-info/RECORD +55 -0
- structa_maestro-0.2.0.dist-info/WHEEL +4 -0
- structa_maestro-0.2.0.dist-info/entry_points.txt +2 -0
- structa_maestro-0.2.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,394 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: structa-maestro
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Structured data extraction engine transforming unstructured documents into validated, traceable canonical records.
|
|
5
|
+
Author: structa-maestro contributors
|
|
6
|
+
License: MIT License
|
|
7
|
+
|
|
8
|
+
Copyright (c) 2026 structa-maestro contributors
|
|
9
|
+
|
|
10
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
11
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
12
|
+
in the Software without restriction, including without limitation the rights
|
|
13
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
14
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
15
|
+
furnished to do so, subject to the following conditions:
|
|
16
|
+
|
|
17
|
+
The above copyright notice and this permission notice shall be included in all
|
|
18
|
+
copies or substantial portions of the Software.
|
|
19
|
+
|
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
21
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
22
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
23
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
24
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
25
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
26
|
+
SOFTWARE.
|
|
27
|
+
License-File: LICENSE
|
|
28
|
+
Keywords: document-processing,provenance,structured-extraction,validation
|
|
29
|
+
Classifier: Development Status :: 4 - Beta
|
|
30
|
+
Classifier: Intended Audience :: Developers
|
|
31
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
32
|
+
Classifier: Programming Language :: Python :: 3
|
|
33
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
34
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
35
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
36
|
+
Classifier: Typing :: Typed
|
|
37
|
+
Requires-Python: >=3.11
|
|
38
|
+
Requires-Dist: httpx<1.0,>=0.27
|
|
39
|
+
Requires-Dist: pydantic<3.0,>=2.7
|
|
40
|
+
Requires-Dist: pypdf<7.0,>=4.2
|
|
41
|
+
Requires-Dist: python-docx<2.0,>=1.1
|
|
42
|
+
Provides-Extra: dev
|
|
43
|
+
Requires-Dist: build>=1.2; extra == 'dev'
|
|
44
|
+
Requires-Dist: hypothesis>=6.100; extra == 'dev'
|
|
45
|
+
Requires-Dist: jsonschema>=4.22; extra == 'dev'
|
|
46
|
+
Requires-Dist: mypy>=1.11; extra == 'dev'
|
|
47
|
+
Requires-Dist: pip-audit>=2.7; extra == 'dev'
|
|
48
|
+
Requires-Dist: pytest-cov>=5.0; extra == 'dev'
|
|
49
|
+
Requires-Dist: pytest>=8.2; extra == 'dev'
|
|
50
|
+
Requires-Dist: ruff>=0.6; extra == 'dev'
|
|
51
|
+
Requires-Dist: twine>=5.1; extra == 'dev'
|
|
52
|
+
Description-Content-Type: text/markdown
|
|
53
|
+
|
|
54
|
+
# structa-maestro
|
|
55
|
+
|
|
56
|
+
[](https://github.com/ivnmoreno/structa-maestro/actions/workflows/ci.yml)
|
|
57
|
+
[](https://github.com/ivnmoreno/structa-maestro/actions/workflows/formal-assurance.yml)
|
|
58
|
+
[](https://github.com/ivnmoreno/structa-maestro/actions/workflows/security.yml)
|
|
59
|
+
[](https://github.com/ivnmoreno/structa-maestro/actions/workflows/evaluation.yml)
|
|
60
|
+
[](https://www.python.org/downloads/)
|
|
61
|
+
[](LICENSE)
|
|
62
|
+
[](https://github.com/astral-sh/ruff)
|
|
63
|
+
[](https://mypy-lang.org/)
|
|
64
|
+
[](docs/formal-assurance.md)
|
|
65
|
+
[](https://commitizen-tools.github.io/commitizen/)
|
|
66
|
+
|
|
67
|
+
**Structured Data Extraction Engine** — a reusable, stateless Python library (`structa_maestro`) with a minimal thin CLI (`structa-maestro`) that transforms unstructured documents (`TXT`, text-based `PDF`, `DOCX`, `HTML`, `Markdown`, and `EML`) into **validated, schema-conforming, provenance-backed canonical records** using only four pure-Python runtime dependencies (`pydantic`, `pypdf`, `python-docx`, `httpx`).
|
|
68
|
+
|
|
69
|
+
[Quick Start](#quick-usage-python-library) • [Input Formats](#supported-input-formats) • [Strategies](#built-in-extraction-strategies) • [CLI](#thin-cli-extract--extract-batch) • [Examples](#runnable-offline-examples) • [Formal Assurance](#formal-assurance-layer-lean-4--dev--ci-only) • [Docs](#further-documentation)
|
|
70
|
+
|
|
71
|
+
---
|
|
72
|
+
|
|
73
|
+
## What It Solves (and What It Does Not)
|
|
74
|
+
|
|
75
|
+
Unstructured business documents (invoices, contracts, employment records, applications, emails, reports) frequently need to be converted into reliable structured data. Ad-hoc LLM JSON generation blurs extracted values, schema validity, source evidence, and operational completion into a single fragile blob.
|
|
76
|
+
|
|
77
|
+
`structa-maestro` treats extraction as a staged data-processing operation with **five strictly separated quality dimensions**:
|
|
78
|
+
|
|
79
|
+
| Dimension | Question Answered | Epistemic Guarantee |
|
|
80
|
+
| --- | --- | --- |
|
|
81
|
+
| **Extracted value** | What value was identified? | Strictly distinguishes `missing`, explicit `null`, and `""` (zero silent coercion) |
|
|
82
|
+
| **Confidence** | How reliable does the strategy assess this value? | Bounded on declared scale (`0-1`), `calibrated: false` by default; opt-in empirical `CalibrationModel` sets `calibrated: true` only when warranted |
|
|
83
|
+
| **Provenance** | What source excerpt & location support it? | Verified verbatim against `PreparedDocument`; unlocated quotes marked `unverified` |
|
|
84
|
+
| **Validation** | Does the record satisfy schema & cross-field rules? | Deterministic non-coercing validator (`valid` / `invalid` / `not_validated`) |
|
|
85
|
+
| **Processing status** | Did the extraction pipeline complete? | `completed` / `partial` / `failed`, strictly independent of schema validity |
|
|
86
|
+
|
|
87
|
+
```mermaid
|
|
88
|
+
flowchart LR
|
|
89
|
+
In["Document (File / Bytes / Text / Stream) + ExtractionSchema"] --> Parse["Hardened Parsers (TXT, PDF, DOCX, HTML, MD, EML)"]
|
|
90
|
+
Parse --> Strat["Extraction Strategy (OpenAI / Anthropic / Gemini / Deterministic)"]
|
|
91
|
+
Strat --> Verify["Provenance + Confidence + Deterministic Validation"]
|
|
92
|
+
Verify --> Contract["Canonical Output Record Contract v1.0"]
|
|
93
|
+
Contract --> Bind["Optional Strict Typed Binding (Pydantic v2)"]
|
|
94
|
+
Verify -. "zero-PII events" .-> Obs["Observability Hooks (Sync / Async)"]
|
|
95
|
+
Formal["Lean 4 Formal Assurance (Dev/CI Only)"] -. "134 proofs + conformance" .-> Contract
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
> [!IMPORTANT]
|
|
99
|
+
> **Explicit Scope Boundaries**: `structa-maestro` is a focused structured extraction engine — **not** an OCR engine (image-only PDFs report `no_extractable_text`), **not** a RAG/vector/embedding search platform, and **not** a database-backed workflow server or multi-provider router.
|
|
100
|
+
|
|
101
|
+
---
|
|
102
|
+
|
|
103
|
+
## Supported Input Formats
|
|
104
|
+
|
|
105
|
+
Format detection inspects actual content signatures (magic bytes, binary checks, and archive contents) rather than blindly trusting filename extensions or media-type hints:
|
|
106
|
+
|
|
107
|
+
| Format | Media Type | Extensions | Provenance Locations | Built-In Hardening (Zero Extra Deps) |
|
|
108
|
+
| --- | --- | --- | --- | --- |
|
|
109
|
+
| **TXT** | `text/plain` | `.txt` | `line_start`, `line_end`, `char_*` | UTF-8 / UTF-8 BOM / UTF-16 / Latin-1 decoding, `max_file_bytes` |
|
|
110
|
+
| **PDF** | `application/pdf` | `.pdf` | `page`, `char_*` | Magic-byte validation, `max_pages` (default 200) & text caps |
|
|
111
|
+
| **DOCX** | `application/vnd.openxmlformats-officedocument.wordprocessingml.document` | `.docx` | `paragraph`, `section`, `char_*` | Pre-open ZIP-bomb inspection (`max_decompressed_bytes`) |
|
|
112
|
+
| **HTML** | `text/html` | `.html`, `.htm` | `section`, `paragraph`, `char_*` | Strips `<script>`/`<style>`/`<noscript>`/`<template>`/comments, incremental entity-expansion guard, zero network fetches |
|
|
113
|
+
| **Markdown** | `text/markdown` | `.md`, `.markdown` | `section`, `paragraph`, `line_*`, `char_*` | ATX/Setext heading tracking (ignoring `#` in fenced code blocks) |
|
|
114
|
+
| **EML** | `message/rfc822` | `.eml` | `section`, `paragraph`, `char_*` | Normalized `Headers` + `text/plain`/HTML body, 128-part / 16-depth MIME-bomb caps, safe attachment skipping (`attachments_skipped`) |
|
|
115
|
+
|
|
116
|
+
All formats work seamlessly from files or in-memory via `DocumentInput.from_bytes(...)`, `from_text(...)`, `from_stream(...)`, and `from_path(...)` with **zero temporary files written to disk**.
|
|
117
|
+
|
|
118
|
+
---
|
|
119
|
+
|
|
120
|
+
## Built-In Extraction Strategies
|
|
121
|
+
|
|
122
|
+
All strategies sit behind a strict **Strategy-to-Contract Firewall** (`StrategyOutput` → `ResultBuilder` → `ExtractionResult`), ensuring provider wire formats (`choices`, `tool_use`, `candidates`, `usageMetadata`, `usage`, etc.) never leak into Contract `v1.0`:
|
|
123
|
+
|
|
124
|
+
| Strategy | Mode | Wire Protocol | Structured Output & Hardening |
|
|
125
|
+
| --- | --- | --- | --- |
|
|
126
|
+
| `OpenAICompatibleLLMStrategy` / `AsyncOpenAICompatibleLLMStrategy` | Sync / Async | OpenAI Chat Completions (`/v1/chat/completions`, vLLM, Ollama, LiteLLM, proxies) | Strict `json_schema` + single-step JSON fallback, bounded retries (`Retry-After`, deadlines), `InputBudgetPolicy`, nonce + delimiter neutralization, token telemetry |
|
|
127
|
+
| `AnthropicLLMStrategy` / `AsyncAnthropicLLMStrategy` | Sync / Async | Native Anthropic Messages API (`/v1/messages`) | Forced `tool_use` (`emit_extraction_result`) + single-step JSON-text fallback, `429`/`529` overloaded retries, `x-api-key` scrubbing, `InputBudgetPolicy`, token telemetry |
|
|
128
|
+
| `GeminiLLMStrategy` / `AsyncGeminiLLMStrategy` | Sync / Async | Native Google Gemini API (`/v1beta/models/{model}:generateContent`) | Strict `responseJsonSchema` + single-step JSON-object fallback, header-only `x-goog-api-key` auth & `AIza...` scrubbing, safety refusal fail-fast, `thought` filtering, `InputBudgetPolicy`, `usageMetadata` telemetry |
|
|
129
|
+
| `DeterministicTestStrategy` / `AsyncDeterministicTestStrategy` | Sync / Async | In-process callable / static output | 100% offline deterministic testing, contract verification, and golden evaluation |
|
|
130
|
+
|
|
131
|
+
---
|
|
132
|
+
|
|
133
|
+
## Installation
|
|
134
|
+
|
|
135
|
+
Requires **Python 3.11, 3.12, or 3.13**.
|
|
136
|
+
|
|
137
|
+
```bash
|
|
138
|
+
pip install structa-maestro
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
For local development with testing, linting, and security tooling:
|
|
142
|
+
|
|
143
|
+
```bash
|
|
144
|
+
python3 -m venv .venv
|
|
145
|
+
source .venv/bin/activate
|
|
146
|
+
pip install -e ".[dev]"
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
> [!NOTE]
|
|
150
|
+
> Installing `structa-maestro` requires **zero Lean tooling** and installs only four pure-Python packages (`pydantic`, `pypdf`, `python-docx`, `httpx`).
|
|
151
|
+
|
|
152
|
+
---
|
|
153
|
+
|
|
154
|
+
## Quick Usage (Python Library)
|
|
155
|
+
|
|
156
|
+
```python
|
|
157
|
+
import os
|
|
158
|
+
from structa_maestro import (
|
|
159
|
+
ExtractionSchema,
|
|
160
|
+
OpenAICompatibleLLMStrategy,
|
|
161
|
+
extract,
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
schema = ExtractionSchema.from_dict(
|
|
165
|
+
{
|
|
166
|
+
"schema_id": "invoice-schema",
|
|
167
|
+
"schema_version": "1.0",
|
|
168
|
+
"cardinality": "single",
|
|
169
|
+
"fields": {
|
|
170
|
+
"invoice_number": {"type": "string", "required": True, "pattern": r"^INV-\d{4}-\d+$"},
|
|
171
|
+
"vendor_name": {"type": "string", "required": True},
|
|
172
|
+
"issue_date": {"type": "date", "required": True},
|
|
173
|
+
"total_amount": {"type": "decimal", "required": True, "min_value": 0},
|
|
174
|
+
"currency": {
|
|
175
|
+
"type": "string",
|
|
176
|
+
"required": True,
|
|
177
|
+
"allowed_values": ["USD", "EUR", "GBP"],
|
|
178
|
+
},
|
|
179
|
+
"notes": {"type": "string", "required": False, "nullable": True},
|
|
180
|
+
},
|
|
181
|
+
}
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
strategy = OpenAICompatibleLLMStrategy(
|
|
185
|
+
model="gpt-4o-mini",
|
|
186
|
+
api_key=os.environ["STRUCTA_MAESTRO_API_KEY"],
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
result = extract("invoice.pdf", schema, strategy=strategy, document_id="doc-001")
|
|
190
|
+
print(result.status, result.validation.status)
|
|
191
|
+
print(result.to_json(indent=2))
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
### Pydantic v2 Schemas, JSON Export & Strict Typed Binding
|
|
195
|
+
|
|
196
|
+
Define your schema once as a Pydantic v2 `BaseModel`, export it losslessly for CLI use, and opt into strict non-coercing binding after canonical extraction:
|
|
197
|
+
|
|
198
|
+
```python
|
|
199
|
+
from datetime import date
|
|
200
|
+
from decimal import Decimal
|
|
201
|
+
from enum import StrEnum
|
|
202
|
+
from pydantic import BaseModel, Field
|
|
203
|
+
from structa_maestro import (
|
|
204
|
+
ExtractionSchema,
|
|
205
|
+
RecordBindingError,
|
|
206
|
+
bind_records,
|
|
207
|
+
extract,
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
class Currency(StrEnum):
|
|
212
|
+
USD = "USD"
|
|
213
|
+
EUR = "EUR"
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
class Invoice(BaseModel):
|
|
217
|
+
invoice_number: str = Field(pattern=r"^INV-\d{4}-\d+$")
|
|
218
|
+
vendor_name: str = Field(min_length=1)
|
|
219
|
+
issue_date: date
|
|
220
|
+
total_amount: Decimal = Field(ge=0)
|
|
221
|
+
currency: Currency = Currency.USD
|
|
222
|
+
notes: str | None = None
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
schema = ExtractionSchema.from_pydantic(Invoice, schema_id="invoice-schema")
|
|
226
|
+
result = extract("invoice.pdf", schema, strategy=strategy)
|
|
227
|
+
|
|
228
|
+
try:
|
|
229
|
+
invoices: list[Invoice] = bind_records(result, Invoice)
|
|
230
|
+
except RecordBindingError as exc:
|
|
231
|
+
# Failed/invalid results are refused safely (no raw extracted values leaked in exc)
|
|
232
|
+
print(result.status, result.validation.status, exc)
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
> [!TIP]
|
|
236
|
+
> For multi-record `partial` extractions, pass `only_valid=True` to `bind_records(result, Invoice, only_valid=True)` to materialize only `completed` + `valid` records while preserving full provenance, confidence, and diagnostics on `ExtractionResult`.
|
|
237
|
+
|
|
238
|
+
### Native Asyncio Extraction (`aextract`, `aextract_batch`, FastAPI)
|
|
239
|
+
|
|
240
|
+
Use `AsyncOpenAICompatibleLLMStrategy`, `AsyncAnthropicLLMStrategy`, or `AsyncGeminiLLMStrategy` (backed by `httpx.AsyncClient` and non-blocking `asyncio.sleep` retries) with `aextract(...)` and `aextract_batch(...)`:
|
|
241
|
+
|
|
242
|
+
```python
|
|
243
|
+
import os
|
|
244
|
+
from structa_maestro import (
|
|
245
|
+
AsyncAnthropicLLMStrategy,
|
|
246
|
+
BatchOptions,
|
|
247
|
+
DocumentInput,
|
|
248
|
+
InMemoryTelemetryObserver,
|
|
249
|
+
aextract,
|
|
250
|
+
aextract_batch,
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
telemetry = InMemoryTelemetryObserver()
|
|
254
|
+
|
|
255
|
+
# Pooled client via `async with` (or pass a shared FastAPI lifespan `http_client=httpx.AsyncClient(...)`)
|
|
256
|
+
async with AsyncAnthropicLLMStrategy(
|
|
257
|
+
model="claude-sonnet-4-5",
|
|
258
|
+
api_key=os.environ["ANTHROPIC_API_KEY"],
|
|
259
|
+
) as strategy:
|
|
260
|
+
result = await aextract(
|
|
261
|
+
DocumentInput.from_bytes(upload_bytes, filename="invoice.pdf"),
|
|
262
|
+
schema,
|
|
263
|
+
strategy=strategy,
|
|
264
|
+
observers=[telemetry],
|
|
265
|
+
)
|
|
266
|
+
batch = await aextract_batch(
|
|
267
|
+
[doc_a, doc_b, doc_c],
|
|
268
|
+
schema,
|
|
269
|
+
strategy=strategy,
|
|
270
|
+
options=BatchOptions(max_workers=4),
|
|
271
|
+
observers=[telemetry],
|
|
272
|
+
)
|
|
273
|
+
|
|
274
|
+
print(telemetry.summary().to_json(indent=2))
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
- Blocking document parsing and synchronous strategies are offloaded via `asyncio.to_thread`, and external `asyncio.CancelledError` propagates cleanly while cancelling in-flight batch tasks.
|
|
278
|
+
- Observer callbacks (`InMemoryTelemetryObserver`, `StructuredLoggingObserver`, or custom `ExtractionObserver` / `AsyncExtractionObserver` adapters for OpenTelemetry/Prometheus) are strictly fault-isolated and carry zero raw text, extracted values, host paths, or credentials.
|
|
279
|
+
|
|
280
|
+
---
|
|
281
|
+
|
|
282
|
+
## Thin CLI (`extract` & `extract-batch`)
|
|
283
|
+
|
|
284
|
+
```bash
|
|
285
|
+
export STRUCTA_MAESTRO_API_KEY="your-api-key"
|
|
286
|
+
|
|
287
|
+
# Single document -> Canonical Output Record Contract v1.0 JSON (OpenAI default, --provider anthropic, or --provider gemini)
|
|
288
|
+
structa-maestro extract invoice.pdf --schema invoice_schema.json --pretty
|
|
289
|
+
ANTHROPIC_API_KEY="your-key" structa-maestro extract invoice.pdf --schema invoice_schema.json --provider anthropic --pretty
|
|
290
|
+
GEMINI_API_KEY="your-key" structa-maestro extract invoice.pdf --schema invoice_schema.json --provider gemini --pretty
|
|
291
|
+
|
|
292
|
+
# Pipe binary or text document via stdin ('-') without temporary files
|
|
293
|
+
cat invoice.pdf | structa-maestro extract - --schema invoice_schema.json --filename invoice.pdf
|
|
294
|
+
|
|
295
|
+
# Folder / multi-file batch -> Contract v1.0 JSON Lines (JSONL) + optional summary & telemetry
|
|
296
|
+
structa-maestro extract-batch ./invoices/ --schema invoice_schema.json \
|
|
297
|
+
--recursive --max-workers 4 --output results.jsonl \
|
|
298
|
+
--summary-json summary.json --telemetry-json telemetry.json
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
- **Exit codes**: `0` (all `completed` + `valid`), `2` (any `partial`/`failed`/`invalid` canonical result or early `--fail-fast` stop), `1` (CLI usage, empty discovery, schema, or configuration error).
|
|
302
|
+
- Supports reliability flags (`--provider`, `--max-tokens`, `--structured-output-mode`, `--max-retries`, `--max-input-chars`, `--overflow-policy`), `--calibrator <artifact.json>`, and `--telemetry-json <path>` while keeping `stdout` strictly Contract `v1.0`.
|
|
303
|
+
- Also provides offline human-review subcommands: `structa-maestro review-plan <result.json>` (exit `0` clean / `2` needs review) and `structa-maestro apply-review <result.json> --schema <schema.json> --decisions <decisions.json> [--audit-json <audit.json>]`.
|
|
304
|
+
|
|
305
|
+
---
|
|
306
|
+
|
|
307
|
+
## Runnable Offline Examples
|
|
308
|
+
|
|
309
|
+
All 15 scripts under [examples/](examples/) execute completely offline (zero API keys required) and are verified continuously in CI:
|
|
310
|
+
|
|
311
|
+
| Example Script | Capability Demonstrated |
|
|
312
|
+
| --- | --- |
|
|
313
|
+
| [basic_invoice_extraction.py](examples/basic_invoice_extraction.py) | End-to-end single-record extraction, provenance, confidence, and Contract `v1.0` JSON |
|
|
314
|
+
| [multi_record_extraction.py](examples/multi_record_extraction.py) | Multi-record extraction (`cardinality="multiple"`) with per-record validation |
|
|
315
|
+
| [custom_strategy_example.py](examples/custom_strategy_example.py) | Implementing a custom `ExtractionStrategy` behind the Strategy-to-Contract Firewall |
|
|
316
|
+
| [hardened_llm_strategy_example.py](examples/hardened_llm_strategy_example.py) | Strict `json_schema`, fallback, bounded retries, `InputBudgetPolicy`, and delimiter neutralization |
|
|
317
|
+
| [anthropic_strategy_example.py](examples/anthropic_strategy_example.py) | Sync & async `AnthropicLLMStrategy` forced `tool_use` + token telemetry over `httpx.MockTransport` |
|
|
318
|
+
| [gemini_strategy_example.py](examples/gemini_strategy_example.py) | Sync & async `GeminiLLMStrategy` strict `responseJsonSchema` + `usageMetadata` telemetry over `httpx.MockTransport` |
|
|
319
|
+
| [cross_field_validation_example.py](examples/cross_field_validation_example.py) | Declarative comparison, exact `Decimal` arithmetic balance, conditional & group rules |
|
|
320
|
+
| [batch_extraction_example.py](examples/batch_extraction_example.py) | Stateless concurrent `extract_batch(...)`, `fail_fast`, `BatchSummary`, and JSONL export |
|
|
321
|
+
| [in_memory_extraction_example.py](examples/in_memory_extraction_example.py) | Zero-temp-file `DocumentInput.from_bytes`, `from_text`, and `from_stream` extraction |
|
|
322
|
+
| [pydantic_schema_example.py](examples/pydantic_schema_example.py) | `ExtractionSchema.from_pydantic`, JSON export, and strict `bind_record` / `bind_records` |
|
|
323
|
+
| [async_extraction_example.py](examples/async_extraction_example.py) | Native asyncio `aextract`, `aextract_batch`, pooled `async with`, and concurrency bounds |
|
|
324
|
+
| [observability_telemetry_example.py](examples/observability_telemetry_example.py) | `InMemoryTelemetryObserver`, `StructuredLoggingObserver`, stage timings, and token rollups |
|
|
325
|
+
| [multiformat_extraction_example.py](examples/multiformat_extraction_example.py) | Consistent extraction & provenance across HTML, Markdown, and RFC 5322 EML documents |
|
|
326
|
+
| [confidence_calibration_example.py](examples/confidence_calibration_example.py) | Zero-dependency empirical calibration (`fit_calibrator`), ECE/Brier reduction, artifact persistence, and `calibrated: false` vs. `true` |
|
|
327
|
+
| [human_review_workflow_example.py](examples/human_review_workflow_example.py) | Stateless `plan_review` triage, immutable `apply_review` corrections + re-validation, privacy-safe `ReviewAudit`, and `bind_records` |
|
|
328
|
+
|
|
329
|
+
---
|
|
330
|
+
|
|
331
|
+
## Canonical Output Record Contract (`1.0`)
|
|
332
|
+
|
|
333
|
+
Every extraction returns an immutable `ExtractionResult` supporting lossless round-trip serialization (`ExtractionResult.from_json(result.to_json()) == result`):
|
|
334
|
+
|
|
335
|
+
- `contract_version`: `"1.0"`
|
|
336
|
+
- `extraction_id`: unique UUIDv4 per operation
|
|
337
|
+
- `status`: `"completed" | "partial" | "failed"`
|
|
338
|
+
- `source`: `{ "document_id", "filename", "media_type" }` (basename only — local host directories are never leaked)
|
|
339
|
+
- `schema`: `{ "schema_id", "schema_version" }`
|
|
340
|
+
- `records`: ordered list of `ExtractedRecord` (`record_id`, `status`, `fields`, `validation`, `errors`, `warnings`)
|
|
341
|
+
- `validation`: top-level deterministic `ValidationOutcome` (`"valid" | "invalid" | "not_validated"`, `errors`)
|
|
342
|
+
- `errors` / `warnings`: structured, privacy-safe `DiagnosticIssue` lists
|
|
343
|
+
|
|
344
|
+
---
|
|
345
|
+
|
|
346
|
+
## Current Limitations
|
|
347
|
+
|
|
348
|
+
> [!WARNING]
|
|
349
|
+
> - **Confidence calibration requires domain-representative data**: By default (`calibrator=None`), confidence scores report `"calibrated": false` and MUST NOT be interpreted as statistical probabilities. Even when an offline empirical `CalibrationModel` sets `"calibrated": true`, calibration reflects empirical accuracy on its fitting distribution only and never implies schema validity or factual truth.
|
|
350
|
+
> - **External model data transmission**: `OpenAICompatibleLLMStrategy`, `AsyncOpenAICompatibleLLMStrategy`, `AnthropicLLMStrategy`, `AsyncAnthropicLLMStrategy`, `GeminiLLMStrategy`, and `AsyncGeminiLLMStrategy` transmit prepared document text to the configured endpoint; review provider data-handling policies before processing confidential documents.
|
|
351
|
+
|
|
352
|
+
- **Intra-record validation scope**: Declarative cross-field and conditional validation rules operate within each extracted record (including nested objects and line-item arrays); cross-document validation remains out of scope.
|
|
353
|
+
- **Text-only extraction**: Scanned PDFs and embedded images are not OCR-processed.
|
|
354
|
+
|
|
355
|
+
---
|
|
356
|
+
|
|
357
|
+
## Golden Evaluation & Regression Suite
|
|
358
|
+
|
|
359
|
+
Contributors can run the repository-internal 50-case golden evaluation harness offline without external API keys (excluded from published wheels and sdists):
|
|
360
|
+
|
|
361
|
+
```bash
|
|
362
|
+
python -m evals validate-dataset
|
|
363
|
+
python -m evals run --strategy deterministic --baseline evals/baselines/deterministic_v2.0.0.json
|
|
364
|
+
```
|
|
365
|
+
|
|
366
|
+
See [docs/development.md](docs/development.md) for subset filtering, repeated-trial (`--trials`) distributions, differential strategy comparison (`python -m evals diff`), and on-demand live-model benchmarking.
|
|
367
|
+
|
|
368
|
+
---
|
|
369
|
+
|
|
370
|
+
## Formal Assurance Layer (Lean 4 — Dev & CI Only)
|
|
371
|
+
|
|
372
|
+
`formal/` contains an independent, zero-external-dependency **Lean 4** project (pinned via `formal/lean-toolchain`, excluded from Python wheels and sdists, with **zero runtime dependency** for `structa-maestro` consumers) that machine-checks **134 theorems** across **Canonical Output Record Contract v1.0** (46 theorems), **Schema Well-Formedness & Deterministic Validation Semantics** (32 theorems), **Declarative Cross-Field & Conditional Validation Rules** (30 theorems), and **Provenance Association, Source-Span Mapping & Full `ResultBuilder` Firewall Soundness** (26 theorems: span overlap/clamping/fallback, bounded excerpts, foreign-doc rejection, unlocated `UNVERIFIED`, `DIRECT` conflict downgrade, `record-NNN` uniqueness, `MISSING` sanitization, provenance fault isolation, validation-only warning propagation, and end-to-end `ValidExtractionResult` soundness), replayed from scratch via `Lean.Kernel.Environment.replay` and cross-checked against Python via a two-layer conformance suite:
|
|
373
|
+
|
|
374
|
+
```bash
|
|
375
|
+
cd formal && lake build && lake test
|
|
376
|
+
cd .. && STRUCTA_REQUIRE_LEAN_ORACLE=1 pytest tests/conformance/ -v
|
|
377
|
+
```
|
|
378
|
+
|
|
379
|
+
See [Formal Assurance Guide](docs/formal-assurance.md) for the 4-layer assurance diagram, complete assurance matrix, formal model scope, assumptions, and explicit non-goals.
|
|
380
|
+
|
|
381
|
+
---
|
|
382
|
+
|
|
383
|
+
## Further Documentation
|
|
384
|
+
|
|
385
|
+
- [Architecture](docs/architecture.md)
|
|
386
|
+
- [Formal Assurance Layer](docs/formal-assurance.md)
|
|
387
|
+
- [Public API & CLI Reference](docs/api.md)
|
|
388
|
+
- [Configuration & Security](docs/configuration.md)
|
|
389
|
+
- [Development & Quality Gates](docs/development.md)
|
|
390
|
+
- [Testing Strategy & CI Rules](docs/TESTING.md)
|
|
391
|
+
- [Contributing Guide](CONTRIBUTING.md)
|
|
392
|
+
- [Code of Conduct](CODE_OF_CONDUCT.md)
|
|
393
|
+
- [Security Policy](SECURITY.md)
|
|
394
|
+
- [Changelog](CHANGELOG.md)
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
structa_maestro/__init__.py,sha256=MTUVe9MNkizJ3NEM0WuQZpH_IGFKsFCyams3LR7u7Oo,7519
|
|
2
|
+
structa_maestro/batch.py,sha256=TqK7tvRUOraoT-bajGpE7H7Ln7njm79d4VoVCwqWqiQ,21945
|
|
3
|
+
structa_maestro/binding.py,sha256=mLNOdR2hxmudeouc_WCslI1GykA30hxQbeDh98Wf4OA,8384
|
|
4
|
+
structa_maestro/cli.py,sha256=GHoF7ExudYNJFouNymqIjtQxxEzw7-5qmr2a5cLCbrk,28030
|
|
5
|
+
structa_maestro/config.py,sha256=Gy6pZS8nPlhriYPCSetqKM--Om8VDy17XxAWSsZOHQ8,4212
|
|
6
|
+
structa_maestro/engine.py,sha256=izm_jK2gi7hglgqqWmyjhB6JqqD8WjS_1_koUGzhEN8,48055
|
|
7
|
+
structa_maestro/exceptions.py,sha256=Eyc2LkC86_jWJUnubYjCv8XgoJ_hh2JNvvXTy_LyoNc,1292
|
|
8
|
+
structa_maestro/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
9
|
+
structa_maestro/review.py,sha256=ti2tiVXRk-YFry2I9uD4xE_nGmmKTjyy3PFeiRRFhOs,50083
|
|
10
|
+
structa_maestro/telemetry.py,sha256=NyeSsjedVm3iUXoOYQu_mZCaGZY92ptb2j_b7xf74sQ,31881
|
|
11
|
+
structa_maestro/builder/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
12
|
+
structa_maestro/builder/result_builder.py,sha256=szlCJbo-5xlvgAFa38bOBSp4xCAvILaUxvmlEcmxQ7I,11892
|
|
13
|
+
structa_maestro/confidence/__init__.py,sha256=5iUAR70R9VEsM_dF7TYNAfJ5JDgQuJCw0wxfzOuycBs,1304
|
|
14
|
+
structa_maestro/confidence/calibration.py,sha256=_c--Qi8BFETppnZohhFxNW4A2g3d73qDcota_kcE15U,36729
|
|
15
|
+
structa_maestro/confidence/normalizer.py,sha256=EhGu-y_execSTaA3bF_pcSj_Bm0uBBG8Q9WHu7Khlrg,8175
|
|
16
|
+
structa_maestro/contracts/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
17
|
+
structa_maestro/contracts/enums.py,sha256=LAE5rLPbX919h3C7v9rAtMUs2r5jfUfbDlr7P1SpNBA,2001
|
|
18
|
+
structa_maestro/contracts/models.py,sha256=9jwdudDl3irxTo65mKPI8EfsXBR8jHUym5BgUrEJRzM,8660
|
|
19
|
+
structa_maestro/contracts/serialization.py,sha256=UbkMxAH3zK39434-gO4fq_QBHrjNca3oiUmSH2HO81c,6535
|
|
20
|
+
structa_maestro/documents/__init__.py,sha256=rlo7nP7sEUL5lS2psgnfEARSxMn95SQsx5UboLGfUrA,794
|
|
21
|
+
structa_maestro/documents/docx_parser.py,sha256=w4vDz8gu518XgNJZRzBQIMoilXMLGDNN_v1MKTjjAQA,7784
|
|
22
|
+
structa_maestro/documents/eml_parser.py,sha256=bOiMPG0QJ6fldwrWLyNgSsUgI2Z_mmHhusMIWHuaFhY,13123
|
|
23
|
+
structa_maestro/documents/html_parser.py,sha256=Ehs0dxnS9SzXbLvemgP_I3j148QuzQ45pF6OqViGhms,11197
|
|
24
|
+
structa_maestro/documents/inputs.py,sha256=a4emnv63nBcrJhBHTkV-EAky1oFnYIahnhnwUQ_nhuU,11136
|
|
25
|
+
structa_maestro/documents/loader.py,sha256=vEicf6f5aY5Etc95odCnz60i60zB4XijiXrWh5G70Kg,23650
|
|
26
|
+
structa_maestro/documents/markdown_parser.py,sha256=fuVhWZruU0vYbmL1VGasx68VVY8suTjsCF9x3llpiUg,7582
|
|
27
|
+
structa_maestro/documents/models.py,sha256=kN_QQlkkVWA_SFkWDK00zx23rrLilCW3nrr9sHBeywM,964
|
|
28
|
+
structa_maestro/documents/normalization.py,sha256=3dAZT02q1-Y_PLa54uq86EIrOR5vO8s7aj9x3aouo_M,1001
|
|
29
|
+
structa_maestro/documents/pdf_parser.py,sha256=WWhI1CaTBlkAVtc92tSB05F7dOEHgrJ_NsoY-OcA-XM,6323
|
|
30
|
+
structa_maestro/documents/txt_parser.py,sha256=It3zT6D7yL9chChKly3qxXuVb-wmuWvW-yeQ9cjsx68,5258
|
|
31
|
+
structa_maestro/provenance/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
32
|
+
structa_maestro/provenance/associator.py,sha256=-PjfgTwUGmHgXTEMQrlo3Al4P3f60WTZHQoE7r3_WLY,8455
|
|
33
|
+
structa_maestro/schema/__init__.py,sha256=jYnnLgjoruH3rI91_agNosuyfEkTTBNKoyoxG468zUY,716
|
|
34
|
+
structa_maestro/schema/loader.py,sha256=SjOVDz6AOUR5Sz-R52yOYZc5ODJkQUPsgg5dsWCuw04,23518
|
|
35
|
+
structa_maestro/schema/models.py,sha256=mVpy5YkyhzmXYGbhsY9T7cME9Z1VcpGg6nB0FXuClX0,11506
|
|
36
|
+
structa_maestro/schema/pydantic_adapter.py,sha256=NxtRYeIOvuMetpHryWVJI6yZNWLNiOx2AY86BJt_Psg,21604
|
|
37
|
+
structa_maestro/schema/rules.py,sha256=w8zlWlooaWRbbZN03BNrFl-M_rKoCMDXWOWjAxx9qDk,22172
|
|
38
|
+
structa_maestro/schema/serializer.py,sha256=YwR8FzDb70s1Kk1XgPOykCboWlFijQmYeeAW60IFZME,5343
|
|
39
|
+
structa_maestro/strategies/__init__.py,sha256=scxTDXWdrL-fQBrRfDQERxzdcj32Sp-RX70fefgxfRs,1206
|
|
40
|
+
structa_maestro/strategies/base.py,sha256=l_TFj8nkl5MPx04ZDaGkyyIdwhlbbMCLWVDxQa9d6ik,3409
|
|
41
|
+
structa_maestro/strategies/llm_anthropic.py,sha256=vIq-YvZ2mIKNDljptu19MQYGFOOclAnaaAkoIR15zsQ,44047
|
|
42
|
+
structa_maestro/strategies/llm_config.py,sha256=4JFunokeBdLwTwxTnJn_siBRnzRLLDu9SJJIFy-hpIg,6104
|
|
43
|
+
structa_maestro/strategies/llm_gemini.py,sha256=9r_I7vh9e19vn8s0BWJEzSMoTc1IBMciWzOWIfE9mSU,45041
|
|
44
|
+
structa_maestro/strategies/llm_helpers.py,sha256=YDmnEzYpyHL7A0inTKIr98G9LmLr7x-joA0Aq6JbzBk,7999
|
|
45
|
+
structa_maestro/strategies/llm_openai_compat.py,sha256=eI4X7hAL3FXeAHHG_Z1Lz1zDczhzM_3ypO3mKItnQBQ,46109
|
|
46
|
+
structa_maestro/strategies/schema_compiler.py,sha256=xzgp8BMFi8ixifzx37h9qbfQR3QBAOPA-HGUPD6zOtw,8741
|
|
47
|
+
structa_maestro/strategies/testing.py,sha256=3P2FtC_JVNzeVN6eRKihl5Gj5iczo2qA7PtNO983NNs,2374
|
|
48
|
+
structa_maestro/validation/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
49
|
+
structa_maestro/validation/cross_field.py,sha256=ybwFCIbaqYP1x09Bw-y7TOy7-Sc9BhqdxLDQzZSYsmo,16196
|
|
50
|
+
structa_maestro/validation/validator.py,sha256=KLP_CNRVwA4kx3BsH-tN-JDC-OMNDCs3CWkujdovYIY,20802
|
|
51
|
+
structa_maestro-0.2.0.dist-info/METADATA,sha256=ac_iydfAEigxB-zKlZGTtL2ITxlGz0RFhOokL1aBwV8,23746
|
|
52
|
+
structa_maestro-0.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
53
|
+
structa_maestro-0.2.0.dist-info/entry_points.txt,sha256=_rJDbE1sOLUw_puqhi0sylYyShni-SkS4-Ky5XdGoXM,61
|
|
54
|
+
structa_maestro-0.2.0.dist-info/licenses/LICENSE,sha256=QmS2p3j7dLTyJ9TpMhw--5OqmgWyBur_bGo_bbfhrJo,1085
|
|
55
|
+
structa_maestro-0.2.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 structa-maestro contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|