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
structa_maestro/cli.py
ADDED
|
@@ -0,0 +1,730 @@
|
|
|
1
|
+
"""Thin CLI delegating directly to structa_maestro.extract and extract_batch."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
from collections.abc import Sequence
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import BinaryIO, TextIO
|
|
11
|
+
|
|
12
|
+
from structa_maestro.batch import BatchOptions, discover_batch_documents
|
|
13
|
+
from structa_maestro.confidence.calibration import CalibrationModel
|
|
14
|
+
from structa_maestro.config import DocumentLimits, sanitize_message
|
|
15
|
+
from structa_maestro.contracts.enums import ProcessingStatus, ValidationStatus
|
|
16
|
+
from structa_maestro.contracts.models import ExtractionResult
|
|
17
|
+
from structa_maestro.documents.inputs import DocumentInput
|
|
18
|
+
from structa_maestro.engine import extract, extract_batch
|
|
19
|
+
from structa_maestro.exceptions import ConfigurationError, StructaMaestroError
|
|
20
|
+
from structa_maestro.review import (
|
|
21
|
+
MAX_REVIEW_PAYLOAD_BYTES,
|
|
22
|
+
ReviewPolicy,
|
|
23
|
+
ReviewSubmission,
|
|
24
|
+
apply_review,
|
|
25
|
+
plan_review,
|
|
26
|
+
)
|
|
27
|
+
from structa_maestro.schema.models import ExtractionSchema
|
|
28
|
+
from structa_maestro.strategies.base import ExtractionStrategy
|
|
29
|
+
from structa_maestro.strategies.llm_anthropic import (
|
|
30
|
+
DEFAULT_ANTHROPIC_BASE_URL,
|
|
31
|
+
DEFAULT_ANTHROPIC_MAX_TOKENS,
|
|
32
|
+
AnthropicLLMStrategy,
|
|
33
|
+
)
|
|
34
|
+
from structa_maestro.strategies.llm_config import (
|
|
35
|
+
DEFAULT_MAX_INPUT_CHARS,
|
|
36
|
+
InputBudgetOverflowPolicy,
|
|
37
|
+
InputBudgetPolicy,
|
|
38
|
+
RetryPolicy,
|
|
39
|
+
StructuredOutputMode,
|
|
40
|
+
parse_max_input_chars_arg,
|
|
41
|
+
)
|
|
42
|
+
from structa_maestro.strategies.llm_gemini import (
|
|
43
|
+
DEFAULT_GEMINI_BASE_URL,
|
|
44
|
+
GeminiLLMStrategy,
|
|
45
|
+
)
|
|
46
|
+
from structa_maestro.strategies.llm_openai_compat import OpenAICompatibleLLMStrategy
|
|
47
|
+
from structa_maestro.telemetry import InMemoryTelemetryObserver
|
|
48
|
+
|
|
49
|
+
_DEFAULT_API_KEY_ENV = "STRUCTA_MAESTRO_API_KEY"
|
|
50
|
+
_DEFAULT_BASE_URL = "https://api.openai.com/v1"
|
|
51
|
+
_DEFAULT_MODEL = "gpt-4o-mini"
|
|
52
|
+
_DEFAULT_ANTHROPIC_API_KEY_ENV = "ANTHROPIC_API_KEY"
|
|
53
|
+
_DEFAULT_ANTHROPIC_MODEL = "claude-sonnet-4-5"
|
|
54
|
+
_DEFAULT_GEMINI_API_KEY_ENV = "GEMINI_API_KEY"
|
|
55
|
+
_DEFAULT_GEMINI_MODEL = "gemini-2.5-flash"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _resolve_provider_defaults(args: argparse.Namespace) -> tuple[str, str, str]:
|
|
59
|
+
if args.provider == "anthropic":
|
|
60
|
+
model = args.model if args.model is not None else _DEFAULT_ANTHROPIC_MODEL
|
|
61
|
+
base_url = args.base_url if args.base_url is not None else DEFAULT_ANTHROPIC_BASE_URL
|
|
62
|
+
api_key_env = (
|
|
63
|
+
args.api_key_env if args.api_key_env is not None else _DEFAULT_ANTHROPIC_API_KEY_ENV
|
|
64
|
+
)
|
|
65
|
+
return model, base_url, api_key_env
|
|
66
|
+
if args.provider == "gemini":
|
|
67
|
+
model = args.model if args.model is not None else _DEFAULT_GEMINI_MODEL
|
|
68
|
+
base_url = args.base_url if args.base_url is not None else DEFAULT_GEMINI_BASE_URL
|
|
69
|
+
api_key_env = (
|
|
70
|
+
args.api_key_env if args.api_key_env is not None else _DEFAULT_GEMINI_API_KEY_ENV
|
|
71
|
+
)
|
|
72
|
+
return model, base_url, api_key_env
|
|
73
|
+
model = args.model if args.model is not None else _DEFAULT_MODEL
|
|
74
|
+
base_url = args.base_url if args.base_url is not None else _DEFAULT_BASE_URL
|
|
75
|
+
api_key_env = args.api_key_env if args.api_key_env is not None else _DEFAULT_API_KEY_ENV
|
|
76
|
+
return model, base_url, api_key_env
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _add_common_extraction_args(parser: argparse.ArgumentParser) -> None:
|
|
80
|
+
parser.add_argument("--schema", required=True, help="Path to the JSON extraction schema file.")
|
|
81
|
+
parser.add_argument(
|
|
82
|
+
"--provider",
|
|
83
|
+
choices=["openai", "anthropic", "gemini"],
|
|
84
|
+
default="openai",
|
|
85
|
+
help="LLM provider strategy backend (default: openai).",
|
|
86
|
+
)
|
|
87
|
+
parser.add_argument(
|
|
88
|
+
"--model",
|
|
89
|
+
default=None,
|
|
90
|
+
help=(
|
|
91
|
+
"Model identifier (default: gpt-4o-mini for openai, claude-sonnet-4-5 for anthropic, "
|
|
92
|
+
"gemini-2.5-flash for gemini)."
|
|
93
|
+
),
|
|
94
|
+
)
|
|
95
|
+
parser.add_argument(
|
|
96
|
+
"--base-url",
|
|
97
|
+
default=None,
|
|
98
|
+
help=(
|
|
99
|
+
"Provider endpoint base URL (default: https://api.openai.com/v1 for openai, "
|
|
100
|
+
"https://api.anthropic.com for anthropic, "
|
|
101
|
+
"https://generativelanguage.googleapis.com for gemini)."
|
|
102
|
+
),
|
|
103
|
+
)
|
|
104
|
+
parser.add_argument(
|
|
105
|
+
"--api-key-env",
|
|
106
|
+
default=None,
|
|
107
|
+
help=(
|
|
108
|
+
"Environment variable holding the API key "
|
|
109
|
+
"(default: STRUCTA_MAESTRO_API_KEY for openai, ANTHROPIC_API_KEY for anthropic, "
|
|
110
|
+
"GEMINI_API_KEY for gemini)."
|
|
111
|
+
),
|
|
112
|
+
)
|
|
113
|
+
parser.add_argument(
|
|
114
|
+
"--max-tokens",
|
|
115
|
+
type=int,
|
|
116
|
+
default=DEFAULT_ANTHROPIC_MAX_TOKENS,
|
|
117
|
+
help=(
|
|
118
|
+
f"Maximum output tokens for Anthropic Messages and Gemini generateContent APIs "
|
|
119
|
+
f"(default: {DEFAULT_ANTHROPIC_MAX_TOKENS})."
|
|
120
|
+
),
|
|
121
|
+
)
|
|
122
|
+
parser.add_argument(
|
|
123
|
+
"--max-file-mb",
|
|
124
|
+
type=int,
|
|
125
|
+
default=25,
|
|
126
|
+
help="Maximum raw file size in MB (default: 25).",
|
|
127
|
+
)
|
|
128
|
+
parser.add_argument(
|
|
129
|
+
"--max-bytes",
|
|
130
|
+
type=int,
|
|
131
|
+
default=None,
|
|
132
|
+
help=(
|
|
133
|
+
"Optional byte-exact override for maximum input payload size (overrides --max-file-mb)."
|
|
134
|
+
),
|
|
135
|
+
)
|
|
136
|
+
parser.add_argument(
|
|
137
|
+
"--max-decompressed-mb",
|
|
138
|
+
type=int,
|
|
139
|
+
default=50,
|
|
140
|
+
help="Maximum decompressed/extracted text size in MB (default: 50).",
|
|
141
|
+
)
|
|
142
|
+
parser.add_argument(
|
|
143
|
+
"--max-pages",
|
|
144
|
+
type=int,
|
|
145
|
+
default=200,
|
|
146
|
+
help="Maximum PDF page count (default: 200).",
|
|
147
|
+
)
|
|
148
|
+
parser.add_argument(
|
|
149
|
+
"--structured-output-mode",
|
|
150
|
+
choices=[m.value for m in StructuredOutputMode],
|
|
151
|
+
default=StructuredOutputMode.STRICT_WITH_FALLBACK.value,
|
|
152
|
+
help="Structured output enforcement mode (default: strict_with_fallback).",
|
|
153
|
+
)
|
|
154
|
+
parser.add_argument(
|
|
155
|
+
"--max-retries",
|
|
156
|
+
type=int,
|
|
157
|
+
default=2,
|
|
158
|
+
help="Maximum bounded retries on transient provider/output failures (default: 2).",
|
|
159
|
+
)
|
|
160
|
+
parser.add_argument(
|
|
161
|
+
"--max-input-chars",
|
|
162
|
+
default=str(DEFAULT_MAX_INPUT_CHARS),
|
|
163
|
+
help=(
|
|
164
|
+
"Maximum prepared document characters sent to the model, or 'none' to disable "
|
|
165
|
+
f"(default: {DEFAULT_MAX_INPUT_CHARS})."
|
|
166
|
+
),
|
|
167
|
+
)
|
|
168
|
+
parser.add_argument(
|
|
169
|
+
"--overflow-policy",
|
|
170
|
+
choices=[p.value for p in InputBudgetOverflowPolicy],
|
|
171
|
+
default=InputBudgetOverflowPolicy.REJECT.value,
|
|
172
|
+
help="Overflow policy when input exceeds --max-input-chars (default: reject).",
|
|
173
|
+
)
|
|
174
|
+
parser.add_argument(
|
|
175
|
+
"--telemetry-json",
|
|
176
|
+
default=None,
|
|
177
|
+
help="Optional path to write privacy-safe TelemetrySummary JSON.",
|
|
178
|
+
)
|
|
179
|
+
parser.add_argument(
|
|
180
|
+
"--calibrator",
|
|
181
|
+
default=None,
|
|
182
|
+
help="Optional path to a saved Confidence CalibrationModel JSON artifact.",
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
187
|
+
parser = argparse.ArgumentParser(
|
|
188
|
+
prog="structa-maestro",
|
|
189
|
+
description=(
|
|
190
|
+
"Extract validated, provenance-backed canonical structured records from "
|
|
191
|
+
"TXT, text-based PDF, DOCX, HTML, Markdown, or EML documents."
|
|
192
|
+
),
|
|
193
|
+
)
|
|
194
|
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
|
195
|
+
|
|
196
|
+
ext = subparsers.add_parser(
|
|
197
|
+
"extract",
|
|
198
|
+
help="Extract structured records from one document (or '-' for stdin) using a JSON schema.",
|
|
199
|
+
)
|
|
200
|
+
ext.add_argument(
|
|
201
|
+
"document",
|
|
202
|
+
help=(
|
|
203
|
+
"Path to the input document (TXT, PDF, DOCX, HTML, Markdown, or EML), "
|
|
204
|
+
"or '-' to read from binary stdin."
|
|
205
|
+
),
|
|
206
|
+
)
|
|
207
|
+
_add_common_extraction_args(ext)
|
|
208
|
+
ext.add_argument(
|
|
209
|
+
"--filename",
|
|
210
|
+
default=None,
|
|
211
|
+
help="Optional filename hint for stdin ('-') input (sanitized to basename only).",
|
|
212
|
+
)
|
|
213
|
+
ext.add_argument("--output", help="Optional path to write canonical JSON output.")
|
|
214
|
+
ext.add_argument("--document-id", help="Optional caller-supplied source document identifier.")
|
|
215
|
+
ext.add_argument(
|
|
216
|
+
"--pretty",
|
|
217
|
+
action="store_true",
|
|
218
|
+
help="Pretty-print canonical JSON output with 2-space indentation.",
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
batch = subparsers.add_parser(
|
|
222
|
+
"extract-batch",
|
|
223
|
+
help="Extract structured records from multiple files or directories as JSON Lines (JSONL).",
|
|
224
|
+
)
|
|
225
|
+
batch.add_argument(
|
|
226
|
+
"inputs",
|
|
227
|
+
nargs="+",
|
|
228
|
+
help="One or more input document file paths and/or directories.",
|
|
229
|
+
)
|
|
230
|
+
_add_common_extraction_args(batch)
|
|
231
|
+
batch.add_argument(
|
|
232
|
+
"--recursive",
|
|
233
|
+
action="store_true",
|
|
234
|
+
help="Recursively scan subdirectories when directory inputs are provided.",
|
|
235
|
+
)
|
|
236
|
+
batch.add_argument(
|
|
237
|
+
"--max-workers",
|
|
238
|
+
type=int,
|
|
239
|
+
default=1,
|
|
240
|
+
help="Bounded in-process concurrency worker count (1..32, default: 1).",
|
|
241
|
+
)
|
|
242
|
+
batch.add_argument(
|
|
243
|
+
"--fail-fast",
|
|
244
|
+
action="store_true",
|
|
245
|
+
help="Stop scheduling remaining documents after the first failed extraction.",
|
|
246
|
+
)
|
|
247
|
+
batch.add_argument("--output", help="Optional path to write Contract v1.0 JSONL output.")
|
|
248
|
+
batch.add_argument(
|
|
249
|
+
"--summary-json", help="Optional path to write aggregate batch summary JSON."
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
rev_plan = subparsers.add_parser(
|
|
253
|
+
"review-plan",
|
|
254
|
+
help="Deterministically triage a Contract v1.0 ExtractionResult JSON for human review.",
|
|
255
|
+
)
|
|
256
|
+
rev_plan.add_argument("result_file", help="Path to a Contract v1.0 ExtractionResult JSON file.")
|
|
257
|
+
rev_plan.add_argument(
|
|
258
|
+
"--min-confidence",
|
|
259
|
+
default="0.85",
|
|
260
|
+
help=(
|
|
261
|
+
"Minimum '0-1' confidence threshold in [0.0, 1.0], or 'none' to disable "
|
|
262
|
+
"(default: 0.85)."
|
|
263
|
+
),
|
|
264
|
+
)
|
|
265
|
+
rev_plan.add_argument(
|
|
266
|
+
"--require-calibrated",
|
|
267
|
+
action="store_true",
|
|
268
|
+
help="Flag present fields whose confidence is not empirically calibrated.",
|
|
269
|
+
)
|
|
270
|
+
rev_plan.add_argument(
|
|
271
|
+
"--flag-missing-confidence",
|
|
272
|
+
action="store_true",
|
|
273
|
+
help="Flag present fields that have no confidence score.",
|
|
274
|
+
)
|
|
275
|
+
rev_plan.add_argument(
|
|
276
|
+
"--flag-missing-provenance",
|
|
277
|
+
action="store_true",
|
|
278
|
+
help="Flag present fields that have no provenance entries.",
|
|
279
|
+
)
|
|
280
|
+
rev_plan.add_argument("--output", help="Optional path to write ReviewPlan JSON output.")
|
|
281
|
+
rev_plan.add_argument(
|
|
282
|
+
"--pretty",
|
|
283
|
+
action="store_true",
|
|
284
|
+
help="Pretty-print ReviewPlan JSON output with 2-space indentation.",
|
|
285
|
+
)
|
|
286
|
+
|
|
287
|
+
rev_apply = subparsers.add_parser(
|
|
288
|
+
"apply-review",
|
|
289
|
+
help=(
|
|
290
|
+
"Immutably apply ReviewSubmission decisions, re-validate, and emit Contract v1.0 JSON."
|
|
291
|
+
),
|
|
292
|
+
)
|
|
293
|
+
rev_apply.add_argument(
|
|
294
|
+
"result_file",
|
|
295
|
+
help="Path to a Contract v1.0 ExtractionResult JSON file.",
|
|
296
|
+
)
|
|
297
|
+
rev_apply.add_argument("--schema", required=True, help="Path to the JSON extraction schema.")
|
|
298
|
+
rev_apply.add_argument(
|
|
299
|
+
"--decisions",
|
|
300
|
+
required=True,
|
|
301
|
+
help="Path to a ReviewSubmission JSON file.",
|
|
302
|
+
)
|
|
303
|
+
rev_apply.add_argument("--output", help="Optional path to write updated Contract v1.0 JSON.")
|
|
304
|
+
rev_apply.add_argument(
|
|
305
|
+
"--audit-json",
|
|
306
|
+
default=None,
|
|
307
|
+
help="Optional path to write privacy-safe ReviewAudit JSON.",
|
|
308
|
+
)
|
|
309
|
+
rev_apply.add_argument(
|
|
310
|
+
"--pretty",
|
|
311
|
+
action="store_true",
|
|
312
|
+
help="Pretty-print canonical JSON output with 2-space indentation.",
|
|
313
|
+
)
|
|
314
|
+
return parser
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def _load_result_json_file(path_str: str) -> ExtractionResult:
|
|
318
|
+
if not isinstance(path_str, str) or not path_str.strip():
|
|
319
|
+
raise ConfigurationError("ExtractionResult file path must be non-empty.")
|
|
320
|
+
target = Path(path_str)
|
|
321
|
+
try:
|
|
322
|
+
if not target.exists() or not target.is_file():
|
|
323
|
+
raise ConfigurationError(f"ExtractionResult file not found: '{target.name}'.")
|
|
324
|
+
if target.stat().st_size > MAX_REVIEW_PAYLOAD_BYTES:
|
|
325
|
+
raise ConfigurationError(
|
|
326
|
+
f"ExtractionResult file exceeds maximum size limit "
|
|
327
|
+
f"({MAX_REVIEW_PAYLOAD_BYTES} bytes)."
|
|
328
|
+
)
|
|
329
|
+
raw_text = target.read_text(encoding="utf-8")
|
|
330
|
+
except ConfigurationError:
|
|
331
|
+
raise
|
|
332
|
+
except (OSError, UnicodeDecodeError) as exc:
|
|
333
|
+
raise ConfigurationError(
|
|
334
|
+
f"Unable to read ExtractionResult file ({type(exc).__name__})."
|
|
335
|
+
) from exc
|
|
336
|
+
return ExtractionResult.from_json(raw_text)
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def _parse_min_confidence_arg(raw: str) -> float | None:
|
|
340
|
+
cleaned = raw.strip()
|
|
341
|
+
if cleaned.lower() == "none":
|
|
342
|
+
return None
|
|
343
|
+
try:
|
|
344
|
+
return float(cleaned)
|
|
345
|
+
except ValueError as exc:
|
|
346
|
+
raise ConfigurationError(
|
|
347
|
+
"--min-confidence must be a float in [0.0, 1.0] or 'none'."
|
|
348
|
+
) from exc
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def _build_strategy_and_limits(
|
|
352
|
+
args: argparse.Namespace,
|
|
353
|
+
*,
|
|
354
|
+
api_key_val: str,
|
|
355
|
+
api_key_env: str,
|
|
356
|
+
model: str,
|
|
357
|
+
base_url: str,
|
|
358
|
+
strategy_override: ExtractionStrategy | None,
|
|
359
|
+
) -> tuple[ExtractionStrategy, DocumentLimits]:
|
|
360
|
+
max_file_bytes = (
|
|
361
|
+
args.max_bytes if args.max_bytes is not None else args.max_file_mb * 1024 * 1024
|
|
362
|
+
)
|
|
363
|
+
limits = DocumentLimits(
|
|
364
|
+
max_file_bytes=max_file_bytes,
|
|
365
|
+
max_decompressed_bytes=args.max_decompressed_mb * 1024 * 1024,
|
|
366
|
+
max_pages=args.max_pages,
|
|
367
|
+
)
|
|
368
|
+
retry_policy = RetryPolicy(max_retries=args.max_retries)
|
|
369
|
+
input_budget = InputBudgetPolicy(
|
|
370
|
+
max_input_chars=parse_max_input_chars_arg(args.max_input_chars),
|
|
371
|
+
overflow_policy=InputBudgetOverflowPolicy(args.overflow_policy),
|
|
372
|
+
)
|
|
373
|
+
if strategy_override is not None:
|
|
374
|
+
return strategy_override, limits
|
|
375
|
+
if not api_key_val.strip():
|
|
376
|
+
raise ConfigurationError(
|
|
377
|
+
f"Configuration error: environment variable '{api_key_env}' is not set."
|
|
378
|
+
)
|
|
379
|
+
if args.provider == "anthropic":
|
|
380
|
+
strategy: ExtractionStrategy = AnthropicLLMStrategy(
|
|
381
|
+
model=model,
|
|
382
|
+
api_key=api_key_val,
|
|
383
|
+
base_url=base_url,
|
|
384
|
+
max_tokens=args.max_tokens,
|
|
385
|
+
structured_output_mode=args.structured_output_mode,
|
|
386
|
+
retry_policy=retry_policy,
|
|
387
|
+
input_budget=input_budget,
|
|
388
|
+
)
|
|
389
|
+
return strategy, limits
|
|
390
|
+
if args.provider == "gemini":
|
|
391
|
+
strategy = GeminiLLMStrategy(
|
|
392
|
+
model=model,
|
|
393
|
+
api_key=api_key_val,
|
|
394
|
+
base_url=base_url,
|
|
395
|
+
max_output_tokens=args.max_tokens,
|
|
396
|
+
structured_output_mode=args.structured_output_mode,
|
|
397
|
+
retry_policy=retry_policy,
|
|
398
|
+
input_budget=input_budget,
|
|
399
|
+
)
|
|
400
|
+
return strategy, limits
|
|
401
|
+
strategy = OpenAICompatibleLLMStrategy(
|
|
402
|
+
model=model,
|
|
403
|
+
api_key=api_key_val,
|
|
404
|
+
base_url=base_url,
|
|
405
|
+
structured_output_mode=args.structured_output_mode,
|
|
406
|
+
retry_policy=retry_policy,
|
|
407
|
+
input_budget=input_budget,
|
|
408
|
+
)
|
|
409
|
+
return strategy, limits
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def run_cli(
|
|
413
|
+
argv: Sequence[str] | None = None,
|
|
414
|
+
*,
|
|
415
|
+
stdout: TextIO | None = None,
|
|
416
|
+
stderr: TextIO | None = None,
|
|
417
|
+
stdin_buffer: BinaryIO | None = None,
|
|
418
|
+
strategy_override: ExtractionStrategy | None = None,
|
|
419
|
+
) -> int:
|
|
420
|
+
"""Execute the thin CLI (`extract` or `extract-batch`) and return exit code 0, 1, or 2."""
|
|
421
|
+
out = stdout if stdout is not None else sys.stdout
|
|
422
|
+
err = stderr if stderr is not None else sys.stderr
|
|
423
|
+
parser = _build_parser()
|
|
424
|
+
|
|
425
|
+
try:
|
|
426
|
+
args = parser.parse_args(list(argv) if argv is not None else None)
|
|
427
|
+
except SystemExit as exc:
|
|
428
|
+
code = exc.code
|
|
429
|
+
return code if isinstance(code, int) else 1
|
|
430
|
+
|
|
431
|
+
if args.command == "review-plan":
|
|
432
|
+
try:
|
|
433
|
+
loaded_result = _load_result_json_file(args.result_file)
|
|
434
|
+
min_conf = _parse_min_confidence_arg(args.min_confidence)
|
|
435
|
+
policy = ReviewPolicy(
|
|
436
|
+
min_confidence=min_conf,
|
|
437
|
+
require_calibrated_confidence=args.require_calibrated,
|
|
438
|
+
flag_missing_confidence=args.flag_missing_confidence,
|
|
439
|
+
flag_missing_provenance=args.flag_missing_provenance,
|
|
440
|
+
)
|
|
441
|
+
plan = plan_review(loaded_result, policy=policy)
|
|
442
|
+
except StructaMaestroError as exc:
|
|
443
|
+
err.write(f"Error: {sanitize_message(str(exc))}\n")
|
|
444
|
+
return 1
|
|
445
|
+
except Exception as exc:
|
|
446
|
+
err.write(f"Fatal error: {sanitize_message(type(exc).__name__)}\n")
|
|
447
|
+
return 1
|
|
448
|
+
|
|
449
|
+
plan_json = plan.to_json(indent=2 if args.pretty else None)
|
|
450
|
+
if args.output:
|
|
451
|
+
try:
|
|
452
|
+
out_path = Path(args.output)
|
|
453
|
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
454
|
+
out_path.write_text(plan_json + "\n", encoding="utf-8")
|
|
455
|
+
except OSError as exc:
|
|
456
|
+
err.write(f"Output write error: {sanitize_message(type(exc).__name__)}\n")
|
|
457
|
+
return 1
|
|
458
|
+
else:
|
|
459
|
+
out.write(plan_json + "\n")
|
|
460
|
+
return 2 if plan.needs_review else 0
|
|
461
|
+
|
|
462
|
+
if args.command == "apply-review":
|
|
463
|
+
try:
|
|
464
|
+
if (
|
|
465
|
+
args.output
|
|
466
|
+
and args.audit_json
|
|
467
|
+
and Path(args.output).resolve() == Path(args.audit_json).resolve()
|
|
468
|
+
):
|
|
469
|
+
raise ConfigurationError("--output and --audit-json cannot point to the same file.")
|
|
470
|
+
if args.audit_json is not None and not args.audit_json.strip():
|
|
471
|
+
raise ConfigurationError("--audit-json must be a non-empty file path.")
|
|
472
|
+
loaded_result = _load_result_json_file(args.result_file)
|
|
473
|
+
schema = ExtractionSchema.from_json_file(args.schema)
|
|
474
|
+
submission = ReviewSubmission.from_file(args.decisions)
|
|
475
|
+
applied = apply_review(loaded_result, schema, submission, redact_values=True)
|
|
476
|
+
except StructaMaestroError as exc:
|
|
477
|
+
err.write(f"Error: {sanitize_message(str(exc))}\n")
|
|
478
|
+
return 1
|
|
479
|
+
except Exception as exc:
|
|
480
|
+
err.write(f"Fatal error: {sanitize_message(type(exc).__name__)}\n")
|
|
481
|
+
return 1
|
|
482
|
+
|
|
483
|
+
updated_json = applied.result.to_json(indent=2 if args.pretty else None)
|
|
484
|
+
if args.output:
|
|
485
|
+
try:
|
|
486
|
+
out_path = Path(args.output)
|
|
487
|
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
488
|
+
out_path.write_text(updated_json + "\n", encoding="utf-8")
|
|
489
|
+
except OSError as exc:
|
|
490
|
+
err.write(f"Output write error: {sanitize_message(type(exc).__name__)}\n")
|
|
491
|
+
return 1
|
|
492
|
+
else:
|
|
493
|
+
out.write(updated_json + "\n")
|
|
494
|
+
|
|
495
|
+
if args.audit_json:
|
|
496
|
+
try:
|
|
497
|
+
audit_path = Path(args.audit_json)
|
|
498
|
+
audit_path.parent.mkdir(parents=True, exist_ok=True)
|
|
499
|
+
audit_path.write_text(applied.audit.to_json(indent=2) + "\n", encoding="utf-8")
|
|
500
|
+
except OSError as exc:
|
|
501
|
+
err.write(f"Audit write error: {sanitize_message(type(exc).__name__)}\n")
|
|
502
|
+
return 1
|
|
503
|
+
|
|
504
|
+
if (
|
|
505
|
+
applied.result.status == ProcessingStatus.COMPLETED
|
|
506
|
+
and applied.result.validation.status == ValidationStatus.VALID
|
|
507
|
+
):
|
|
508
|
+
return 0
|
|
509
|
+
return 2
|
|
510
|
+
|
|
511
|
+
if args.command not in ("extract", "extract-batch"):
|
|
512
|
+
err.write(f"Unsupported command: {args.command}\n")
|
|
513
|
+
return 1
|
|
514
|
+
|
|
515
|
+
resolved_model, resolved_base_url, resolved_api_key_env = _resolve_provider_defaults(args)
|
|
516
|
+
api_key_val = os.environ.get(resolved_api_key_env, "")
|
|
517
|
+
secrets_to_scrub = (api_key_val,) if api_key_val else ()
|
|
518
|
+
|
|
519
|
+
if args.command == "extract":
|
|
520
|
+
telemetry_observer: InMemoryTelemetryObserver | None = None
|
|
521
|
+
try:
|
|
522
|
+
if args.telemetry_json is not None:
|
|
523
|
+
if not args.telemetry_json.strip():
|
|
524
|
+
raise ConfigurationError("--telemetry-json must be a non-empty file path.")
|
|
525
|
+
if (
|
|
526
|
+
args.output
|
|
527
|
+
and Path(args.output).resolve() == Path(args.telemetry_json).resolve()
|
|
528
|
+
):
|
|
529
|
+
raise ConfigurationError(
|
|
530
|
+
"--output and --telemetry-json cannot point to the same file."
|
|
531
|
+
)
|
|
532
|
+
telemetry_observer = InMemoryTelemetryObserver()
|
|
533
|
+
if args.filename is not None and args.document != "-":
|
|
534
|
+
raise ConfigurationError(
|
|
535
|
+
"--filename is only supported when reading from stdin ('-')."
|
|
536
|
+
)
|
|
537
|
+
schema = ExtractionSchema.from_json_file(args.schema)
|
|
538
|
+
calibrator = (
|
|
539
|
+
CalibrationModel.from_file(args.calibrator) if args.calibrator is not None else None
|
|
540
|
+
)
|
|
541
|
+
strategy, limits = _build_strategy_and_limits(
|
|
542
|
+
args,
|
|
543
|
+
api_key_val=api_key_val,
|
|
544
|
+
api_key_env=resolved_api_key_env,
|
|
545
|
+
model=resolved_model,
|
|
546
|
+
base_url=resolved_base_url,
|
|
547
|
+
strategy_override=strategy_override,
|
|
548
|
+
)
|
|
549
|
+
doc_target: str | DocumentInput
|
|
550
|
+
if args.document == "-":
|
|
551
|
+
in_stream = stdin_buffer if stdin_buffer is not None else sys.stdin.buffer
|
|
552
|
+
doc_target = DocumentInput.from_stream(
|
|
553
|
+
in_stream,
|
|
554
|
+
filename=args.filename,
|
|
555
|
+
document_id=args.document_id,
|
|
556
|
+
)
|
|
557
|
+
else:
|
|
558
|
+
doc_target = args.document
|
|
559
|
+
extract_kwargs: dict[str, object] = {
|
|
560
|
+
"strategy": strategy,
|
|
561
|
+
"limits": limits,
|
|
562
|
+
"document_id": args.document_id,
|
|
563
|
+
"calibrator": calibrator,
|
|
564
|
+
}
|
|
565
|
+
if telemetry_observer is not None:
|
|
566
|
+
extract_kwargs["observers"] = (telemetry_observer,)
|
|
567
|
+
result = extract(
|
|
568
|
+
doc_target,
|
|
569
|
+
schema,
|
|
570
|
+
**extract_kwargs, # type: ignore[arg-type]
|
|
571
|
+
)
|
|
572
|
+
except StructaMaestroError as exc:
|
|
573
|
+
err.write(f"Error: {sanitize_message(str(exc), secrets=secrets_to_scrub)}\n")
|
|
574
|
+
return 1
|
|
575
|
+
except Exception as exc:
|
|
576
|
+
err.write(
|
|
577
|
+
f"Fatal error: {sanitize_message(type(exc).__name__, secrets=secrets_to_scrub)}\n"
|
|
578
|
+
)
|
|
579
|
+
return 1
|
|
580
|
+
|
|
581
|
+
indent = 2 if args.pretty else None
|
|
582
|
+
serialized = result.to_json(indent=indent)
|
|
583
|
+
|
|
584
|
+
if args.output:
|
|
585
|
+
try:
|
|
586
|
+
out_path = Path(args.output)
|
|
587
|
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
588
|
+
out_path.write_text(serialized + "\n", encoding="utf-8")
|
|
589
|
+
except OSError as exc:
|
|
590
|
+
safe_err = sanitize_message(type(exc).__name__, secrets=secrets_to_scrub)
|
|
591
|
+
err.write(f"Output write error: {safe_err}\n")
|
|
592
|
+
return 1
|
|
593
|
+
else:
|
|
594
|
+
out.write(serialized + "\n")
|
|
595
|
+
|
|
596
|
+
if telemetry_observer is not None and args.telemetry_json:
|
|
597
|
+
try:
|
|
598
|
+
tel_path = Path(args.telemetry_json)
|
|
599
|
+
tel_path.parent.mkdir(parents=True, exist_ok=True)
|
|
600
|
+
tel_path.write_text(
|
|
601
|
+
telemetry_observer.summary().to_json(indent=2) + "\n",
|
|
602
|
+
encoding="utf-8",
|
|
603
|
+
)
|
|
604
|
+
except OSError as exc:
|
|
605
|
+
safe_err = sanitize_message(type(exc).__name__, secrets=secrets_to_scrub)
|
|
606
|
+
err.write(f"Telemetry write error: {safe_err}\n")
|
|
607
|
+
return 1
|
|
608
|
+
|
|
609
|
+
if (
|
|
610
|
+
result.status == ProcessingStatus.COMPLETED
|
|
611
|
+
and result.validation.status == ValidationStatus.VALID
|
|
612
|
+
):
|
|
613
|
+
return 0
|
|
614
|
+
return 2
|
|
615
|
+
|
|
616
|
+
# extract-batch subcommand
|
|
617
|
+
batch_telemetry_observer: InMemoryTelemetryObserver | None = None
|
|
618
|
+
try:
|
|
619
|
+
if (
|
|
620
|
+
args.output
|
|
621
|
+
and args.summary_json
|
|
622
|
+
and Path(args.output).resolve() == Path(args.summary_json).resolve()
|
|
623
|
+
):
|
|
624
|
+
raise ConfigurationError("--output and --summary-json cannot point to the same file.")
|
|
625
|
+
if args.telemetry_json is not None:
|
|
626
|
+
if not args.telemetry_json.strip():
|
|
627
|
+
raise ConfigurationError("--telemetry-json must be a non-empty file path.")
|
|
628
|
+
tel_resolved = Path(args.telemetry_json).resolve()
|
|
629
|
+
if args.output and Path(args.output).resolve() == tel_resolved:
|
|
630
|
+
raise ConfigurationError(
|
|
631
|
+
"--output and --telemetry-json cannot point to the same file."
|
|
632
|
+
)
|
|
633
|
+
if args.summary_json and Path(args.summary_json).resolve() == tel_resolved:
|
|
634
|
+
raise ConfigurationError(
|
|
635
|
+
"--summary-json and --telemetry-json cannot point to the same file."
|
|
636
|
+
)
|
|
637
|
+
batch_telemetry_observer = InMemoryTelemetryObserver()
|
|
638
|
+
schema = ExtractionSchema.from_json_file(args.schema)
|
|
639
|
+
calibrator = (
|
|
640
|
+
CalibrationModel.from_file(args.calibrator) if args.calibrator is not None else None
|
|
641
|
+
)
|
|
642
|
+
batch_options = BatchOptions(
|
|
643
|
+
max_workers=args.max_workers,
|
|
644
|
+
fail_fast=args.fail_fast,
|
|
645
|
+
)
|
|
646
|
+
strategy, limits = _build_strategy_and_limits(
|
|
647
|
+
args,
|
|
648
|
+
api_key_val=api_key_val,
|
|
649
|
+
api_key_env=resolved_api_key_env,
|
|
650
|
+
model=resolved_model,
|
|
651
|
+
base_url=resolved_base_url,
|
|
652
|
+
strategy_override=strategy_override,
|
|
653
|
+
)
|
|
654
|
+
discovered_paths = discover_batch_documents(args.inputs, recursive=args.recursive)
|
|
655
|
+
if not discovered_paths:
|
|
656
|
+
raise ConfigurationError(
|
|
657
|
+
"No supported input documents "
|
|
658
|
+
"(.txt, .pdf, .docx, .html, .htm, .md, .markdown, .eml) were discovered."
|
|
659
|
+
)
|
|
660
|
+
batch_kwargs: dict[str, object] = {
|
|
661
|
+
"strategy": strategy,
|
|
662
|
+
"limits": limits,
|
|
663
|
+
"options": batch_options,
|
|
664
|
+
"calibrator": calibrator,
|
|
665
|
+
}
|
|
666
|
+
if batch_telemetry_observer is not None:
|
|
667
|
+
batch_kwargs["observers"] = (batch_telemetry_observer,)
|
|
668
|
+
batch_result = extract_batch(
|
|
669
|
+
discovered_paths,
|
|
670
|
+
schema,
|
|
671
|
+
**batch_kwargs, # type: ignore[arg-type]
|
|
672
|
+
)
|
|
673
|
+
except StructaMaestroError as exc:
|
|
674
|
+
err.write(f"Error: {sanitize_message(str(exc), secrets=secrets_to_scrub)}\n")
|
|
675
|
+
return 1
|
|
676
|
+
except Exception as exc:
|
|
677
|
+
err.write(
|
|
678
|
+
f"Fatal error: {sanitize_message(type(exc).__name__, secrets=secrets_to_scrub)}\n"
|
|
679
|
+
)
|
|
680
|
+
return 1
|
|
681
|
+
|
|
682
|
+
jsonl_payload = batch_result.to_jsonl()
|
|
683
|
+
if args.output:
|
|
684
|
+
try:
|
|
685
|
+
out_path = Path(args.output)
|
|
686
|
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
687
|
+
out_path.write_text(jsonl_payload, encoding="utf-8")
|
|
688
|
+
except OSError as exc:
|
|
689
|
+
safe_err = sanitize_message(type(exc).__name__, secrets=secrets_to_scrub)
|
|
690
|
+
err.write(f"Output write error: {safe_err}\n")
|
|
691
|
+
return 1
|
|
692
|
+
else:
|
|
693
|
+
out.write(jsonl_payload)
|
|
694
|
+
|
|
695
|
+
if args.summary_json:
|
|
696
|
+
try:
|
|
697
|
+
sum_path = Path(args.summary_json)
|
|
698
|
+
sum_path.parent.mkdir(parents=True, exist_ok=True)
|
|
699
|
+
sum_path.write_text(batch_result.summary.to_json(indent=2) + "\n", encoding="utf-8")
|
|
700
|
+
except OSError as exc:
|
|
701
|
+
safe_err = sanitize_message(type(exc).__name__, secrets=secrets_to_scrub)
|
|
702
|
+
err.write(f"Summary write error: {safe_err}\n")
|
|
703
|
+
return 1
|
|
704
|
+
|
|
705
|
+
if batch_telemetry_observer is not None and args.telemetry_json:
|
|
706
|
+
try:
|
|
707
|
+
tel_path = Path(args.telemetry_json)
|
|
708
|
+
tel_path.parent.mkdir(parents=True, exist_ok=True)
|
|
709
|
+
tel_path.write_text(
|
|
710
|
+
batch_telemetry_observer.summary().to_json(indent=2) + "\n",
|
|
711
|
+
encoding="utf-8",
|
|
712
|
+
)
|
|
713
|
+
except OSError as exc:
|
|
714
|
+
safe_err = sanitize_message(type(exc).__name__, secrets=secrets_to_scrub)
|
|
715
|
+
err.write(f"Telemetry write error: {safe_err}\n")
|
|
716
|
+
return 1
|
|
717
|
+
|
|
718
|
+
summary = batch_result.summary
|
|
719
|
+
if (
|
|
720
|
+
not summary.aborted_early
|
|
721
|
+
and summary.completed_count == summary.total_documents
|
|
722
|
+
and summary.valid_count == summary.total_documents
|
|
723
|
+
):
|
|
724
|
+
return 0
|
|
725
|
+
return 2
|
|
726
|
+
|
|
727
|
+
|
|
728
|
+
def main(argv: Sequence[str] | None = None) -> None:
|
|
729
|
+
"""Console script entry point for `structa-maestro`."""
|
|
730
|
+
raise SystemExit(run_cli(argv))
|