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.
Files changed (55) hide show
  1. structa_maestro/__init__.py +294 -0
  2. structa_maestro/batch.py +564 -0
  3. structa_maestro/binding.py +206 -0
  4. structa_maestro/builder/__init__.py +0 -0
  5. structa_maestro/builder/result_builder.py +308 -0
  6. structa_maestro/cli.py +730 -0
  7. structa_maestro/confidence/__init__.py +49 -0
  8. structa_maestro/confidence/calibration.py +990 -0
  9. structa_maestro/confidence/normalizer.py +203 -0
  10. structa_maestro/config.py +111 -0
  11. structa_maestro/contracts/__init__.py +0 -0
  12. structa_maestro/contracts/enums.py +86 -0
  13. structa_maestro/contracts/models.py +229 -0
  14. structa_maestro/contracts/serialization.py +169 -0
  15. structa_maestro/documents/__init__.py +32 -0
  16. structa_maestro/documents/docx_parser.py +215 -0
  17. structa_maestro/documents/eml_parser.py +360 -0
  18. structa_maestro/documents/html_parser.py +337 -0
  19. structa_maestro/documents/inputs.py +277 -0
  20. structa_maestro/documents/loader.py +675 -0
  21. structa_maestro/documents/markdown_parser.py +225 -0
  22. structa_maestro/documents/models.py +33 -0
  23. structa_maestro/documents/normalization.py +24 -0
  24. structa_maestro/documents/pdf_parser.py +186 -0
  25. structa_maestro/documents/txt_parser.py +169 -0
  26. structa_maestro/engine.py +1201 -0
  27. structa_maestro/exceptions.py +38 -0
  28. structa_maestro/provenance/__init__.py +0 -0
  29. structa_maestro/provenance/associator.py +234 -0
  30. structa_maestro/py.typed +0 -0
  31. structa_maestro/review.py +1234 -0
  32. structa_maestro/schema/__init__.py +19 -0
  33. structa_maestro/schema/loader.py +616 -0
  34. structa_maestro/schema/models.py +269 -0
  35. structa_maestro/schema/pydantic_adapter.py +566 -0
  36. structa_maestro/schema/rules.py +526 -0
  37. structa_maestro/schema/serializer.py +156 -0
  38. structa_maestro/strategies/__init__.py +45 -0
  39. structa_maestro/strategies/base.py +101 -0
  40. structa_maestro/strategies/llm_anthropic.py +1142 -0
  41. structa_maestro/strategies/llm_config.py +154 -0
  42. structa_maestro/strategies/llm_gemini.py +1171 -0
  43. structa_maestro/strategies/llm_helpers.py +240 -0
  44. structa_maestro/strategies/llm_openai_compat.py +1183 -0
  45. structa_maestro/strategies/schema_compiler.py +248 -0
  46. structa_maestro/strategies/testing.py +71 -0
  47. structa_maestro/telemetry.py +800 -0
  48. structa_maestro/validation/__init__.py +0 -0
  49. structa_maestro/validation/cross_field.py +463 -0
  50. structa_maestro/validation/validator.py +531 -0
  51. structa_maestro-0.2.0.dist-info/METADATA +394 -0
  52. structa_maestro-0.2.0.dist-info/RECORD +55 -0
  53. structa_maestro-0.2.0.dist-info/WHEEL +4 -0
  54. structa_maestro-0.2.0.dist-info/entry_points.txt +2 -0
  55. structa_maestro-0.2.0.dist-info/licenses/LICENSE +21 -0
File without changes
@@ -0,0 +1,463 @@
1
+ """Deterministic, non-coercing cross-field and conditional validation evaluator (Spec 004)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from datetime import date, datetime
7
+ from decimal import Decimal
8
+ from typing import Any
9
+
10
+ from structa_maestro.contracts.enums import (
11
+ FieldPresence,
12
+ FieldType,
13
+ IssueSeverity,
14
+ PipelineStage,
15
+ )
16
+ from structa_maestro.contracts.models import DiagnosticIssue
17
+ from structa_maestro.schema.models import ExtractionSchema, FieldSpec
18
+ from structa_maestro.schema.rules import (
19
+ ArithmeticRule,
20
+ ArithmeticTerm,
21
+ ComparisonOperator,
22
+ ComparisonRule,
23
+ ConditionalPresenceKind,
24
+ ConditionalPresenceRule,
25
+ ConditionOperator,
26
+ FieldCondition,
27
+ GroupPresenceKind,
28
+ GroupPresenceRule,
29
+ RuleSeverity,
30
+ resolve_schema_field_spec,
31
+ )
32
+
33
+ _NUMERIC_TYPES = frozenset({FieldType.INTEGER, FieldType.DECIMAL})
34
+
35
+
36
+ def _to_exact_decimal(value: Any) -> Decimal | None:
37
+ if isinstance(value, bool):
38
+ return None
39
+ if isinstance(value, Decimal):
40
+ return None if (value.is_nan() or value.is_infinite()) else value
41
+ if isinstance(value, int):
42
+ return Decimal(value)
43
+ if isinstance(value, float):
44
+ dec = Decimal(str(value))
45
+ return None if (dec.is_nan() or dec.is_infinite()) else dec
46
+ return None
47
+
48
+
49
+ def _is_valid_value_for_spec(value: Any, spec: FieldSpec) -> bool:
50
+ """Strict non-coercing type validity check matching DeterministicValidator."""
51
+ if value is None:
52
+ return False
53
+ ft = spec.field_type
54
+ if ft == FieldType.STRING:
55
+ return isinstance(value, str)
56
+ if ft == FieldType.INTEGER:
57
+ return not isinstance(value, bool) and isinstance(value, int)
58
+ if ft == FieldType.DECIMAL:
59
+ return _to_exact_decimal(value) is not None
60
+ if ft == FieldType.BOOLEAN:
61
+ return isinstance(value, bool)
62
+ if ft == FieldType.DATE:
63
+ return isinstance(value, date) and not isinstance(value, datetime)
64
+ if ft == FieldType.ARRAY:
65
+ return isinstance(value, list)
66
+ if ft == FieldType.OBJECT:
67
+ return isinstance(value, dict)
68
+ return False
69
+
70
+
71
+ def _resolve_record_path(
72
+ fields: Mapping[str, tuple[FieldPresence, Any]],
73
+ schema: ExtractionSchema,
74
+ path: str,
75
+ ) -> tuple[FieldPresence, Any, FieldSpec]:
76
+ """Resolve top-level or dot-separated nested object path from record fields without mutation."""
77
+ spec = resolve_schema_field_spec(schema.fields, path)
78
+ segments = path.split(".")
79
+ top_presence, top_value = fields.get(segments[0], (FieldPresence.MISSING, None))
80
+ if len(segments) == 1:
81
+ return top_presence, top_value, spec
82
+
83
+ if top_presence == FieldPresence.MISSING or not isinstance(top_value, dict):
84
+ return FieldPresence.MISSING, None, spec
85
+
86
+ current: Any = top_value
87
+ for idx, seg in enumerate(segments[1:], start=1):
88
+ if not isinstance(current, dict) or seg not in current:
89
+ return FieldPresence.MISSING, None, spec
90
+ current = current[seg]
91
+ if idx < len(segments) - 1 and not isinstance(current, dict):
92
+ return FieldPresence.MISSING, None, spec
93
+
94
+ return FieldPresence.PRESENT, current, spec
95
+
96
+
97
+ def _resolve_nested_dict_path(
98
+ obj: Mapping[str, Any],
99
+ props: Mapping[str, FieldSpec],
100
+ path: str,
101
+ ) -> tuple[FieldPresence, Any, FieldSpec]:
102
+ spec = resolve_schema_field_spec(props, path)
103
+ current: Any = obj
104
+ for seg in path.split("."):
105
+ if not isinstance(current, Mapping) or seg not in current:
106
+ return FieldPresence.MISSING, None, spec
107
+ current = current[seg]
108
+ return FieldPresence.PRESENT, current, spec
109
+
110
+
111
+ def _make_rule_issue(
112
+ *,
113
+ code: str,
114
+ severity: RuleSeverity,
115
+ message: str,
116
+ record_id: str,
117
+ field_path: str,
118
+ expected: str | None = None,
119
+ actual: str | None = None,
120
+ ) -> DiagnosticIssue:
121
+ issue_sev = IssueSeverity.ERROR if severity == RuleSeverity.ERROR else IssueSeverity.WARNING
122
+ return DiagnosticIssue(
123
+ code=code,
124
+ severity=issue_sev,
125
+ stage=PipelineStage.VALIDATION,
126
+ message=message,
127
+ record_id=record_id,
128
+ field_path=field_path,
129
+ expected=expected,
130
+ actual=actual,
131
+ )
132
+
133
+
134
+ def _compare_typed_values(
135
+ left_val: Any,
136
+ left_type: FieldType,
137
+ right_val: Any,
138
+ right_type: FieldType,
139
+ operator: ComparisonOperator,
140
+ ) -> bool:
141
+ if left_type in _NUMERIC_TYPES and right_type in _NUMERIC_TYPES:
142
+ lv = _to_exact_decimal(left_val)
143
+ rv = _to_exact_decimal(right_val)
144
+ if lv is None or rv is None:
145
+ return True
146
+ else:
147
+ lv = left_val
148
+ rv = right_val
149
+
150
+ if operator == ComparisonOperator.EQ:
151
+ return bool(lv == rv)
152
+ if operator == ComparisonOperator.NE:
153
+ return bool(lv != rv)
154
+ if operator == ComparisonOperator.LT:
155
+ return bool(lv < rv)
156
+ if operator == ComparisonOperator.LTE:
157
+ return bool(lv <= rv)
158
+ if operator == ComparisonOperator.GT:
159
+ return bool(lv > rv)
160
+ if operator == ComparisonOperator.GTE:
161
+ return bool(lv >= rv)
162
+ return True
163
+
164
+
165
+ def _eval_comparison(
166
+ rule: ComparisonRule,
167
+ fields: Mapping[str, tuple[FieldPresence, Any]],
168
+ schema: ExtractionSchema,
169
+ record_id: str,
170
+ ) -> DiagnosticIssue | None:
171
+ lp, lv, lspec = _resolve_record_path(fields, schema, rule.left_field)
172
+ rp, rv, rspec = _resolve_record_path(fields, schema, rule.right_field)
173
+
174
+ if (
175
+ lp == FieldPresence.MISSING
176
+ or rp == FieldPresence.MISSING
177
+ or lv is None
178
+ or rv is None
179
+ or not _is_valid_value_for_spec(lv, lspec)
180
+ or not _is_valid_value_for_spec(rv, rspec)
181
+ ):
182
+ return None
183
+
184
+ if _compare_typed_values(lv, lspec.field_type, rv, rspec.field_type, rule.operator):
185
+ return None
186
+
187
+ default_msg = (
188
+ f"Cross-field rule '{rule.rule_id}' failed: "
189
+ f"'{rule.left_field}' ({rule.operator.value}) '{rule.right_field}' did not hold."
190
+ )
191
+ return _make_rule_issue(
192
+ code="cross_field_comparison_failed",
193
+ severity=rule.severity,
194
+ message=rule.message or default_msg,
195
+ record_id=record_id,
196
+ field_path=rule.left_field,
197
+ expected=f"{rule.left_field} {rule.operator.value} {rule.right_field}",
198
+ actual=f"{lv} vs {rv}",
199
+ )
200
+
201
+
202
+ def _eval_arithmetic_term(
203
+ term: ArithmeticTerm,
204
+ fields: Mapping[str, tuple[FieldPresence, Any]],
205
+ schema: ExtractionSchema,
206
+ ) -> Decimal | None:
207
+ presence, value, spec = _resolve_record_path(fields, schema, term.field)
208
+ if presence == FieldPresence.MISSING or value is None:
209
+ return Decimal("0") if term.treat_missing_as_zero else None
210
+
211
+ if spec.field_type == FieldType.ARRAY:
212
+ if not isinstance(value, list):
213
+ return None
214
+ total = Decimal("0")
215
+ if term.item_field is not None:
216
+ if spec.items is None or not spec.items.properties:
217
+ return None
218
+ for elem in value:
219
+ if not isinstance(elem, Mapping):
220
+ return None
221
+ ep, ev, espec = _resolve_nested_dict_path(
222
+ elem,
223
+ spec.items.properties,
224
+ term.item_field,
225
+ )
226
+ if (
227
+ ep == FieldPresence.MISSING
228
+ or ev is None
229
+ or not _is_valid_value_for_spec(ev, espec)
230
+ ):
231
+ return None
232
+ dec_elem = _to_exact_decimal(ev)
233
+ if dec_elem is None:
234
+ return None
235
+ total += dec_elem
236
+ else:
237
+ if spec.items is None:
238
+ return None
239
+ for elem in value:
240
+ if elem is None or not _is_valid_value_for_spec(elem, spec.items):
241
+ return None
242
+ dec_elem = _to_exact_decimal(elem)
243
+ if dec_elem is None:
244
+ return None
245
+ total += dec_elem
246
+ return total * Decimal(term.sign)
247
+
248
+ if not _is_valid_value_for_spec(value, spec):
249
+ return None
250
+ dec = _to_exact_decimal(value)
251
+ if dec is None:
252
+ return None
253
+ return dec * Decimal(term.sign)
254
+
255
+
256
+ def _eval_arithmetic(
257
+ rule: ArithmeticRule,
258
+ fields: Mapping[str, tuple[FieldPresence, Any]],
259
+ schema: ExtractionSchema,
260
+ record_id: str,
261
+ ) -> DiagnosticIssue | None:
262
+ tp, tv, tspec = _resolve_record_path(fields, schema, rule.target_field)
263
+ if tp == FieldPresence.MISSING or tv is None or not _is_valid_value_for_spec(tv, tspec):
264
+ return None
265
+ target_dec = _to_exact_decimal(tv)
266
+ if target_dec is None:
267
+ return None
268
+
269
+ computed = Decimal("0")
270
+ for term in rule.terms:
271
+ val = _eval_arithmetic_term(term, fields, schema)
272
+ if val is None:
273
+ return None
274
+ computed += val
275
+
276
+ if abs(computed - target_dec) <= rule.tolerance:
277
+ return None
278
+
279
+ default_msg = (
280
+ f"Cross-field arithmetic rule '{rule.rule_id}' failed: "
281
+ f"computed {computed} does not match '{rule.target_field}' ({target_dec}) "
282
+ f"within tolerance {rule.tolerance}."
283
+ )
284
+ return _make_rule_issue(
285
+ code="cross_field_arithmetic_mismatch",
286
+ severity=rule.severity,
287
+ message=rule.message or default_msg,
288
+ record_id=record_id,
289
+ field_path=rule.target_field,
290
+ expected=f"{computed} (+/- {rule.tolerance})",
291
+ actual=str(target_dec),
292
+ )
293
+
294
+
295
+ def _values_equal_strict(actual: Any, expected: Any, field_type: FieldType) -> bool:
296
+ if field_type in _NUMERIC_TYPES:
297
+ a_dec = _to_exact_decimal(actual)
298
+ e_dec = _to_exact_decimal(expected)
299
+ return a_dec is not None and e_dec is not None and a_dec == e_dec
300
+ if isinstance(actual, bool) != isinstance(expected, bool):
301
+ return False
302
+ return bool(actual == expected)
303
+
304
+
305
+ def _eval_condition(
306
+ cond: FieldCondition,
307
+ fields: Mapping[str, tuple[FieldPresence, Any]],
308
+ schema: ExtractionSchema,
309
+ ) -> bool:
310
+ presence, value, spec = _resolve_record_path(fields, schema, cond.field)
311
+
312
+ if cond.operator == ConditionOperator.IS_MISSING:
313
+ return presence == FieldPresence.MISSING
314
+ if cond.operator == ConditionOperator.IS_PRESENT:
315
+ return presence == FieldPresence.PRESENT and value is not None
316
+
317
+ # Value predicates evaluate to False when controlling field is missing, null, or type-invalid
318
+ if (
319
+ presence == FieldPresence.MISSING
320
+ or value is None
321
+ or not _is_valid_value_for_spec(value, spec)
322
+ ):
323
+ return False
324
+
325
+ if cond.operator == ConditionOperator.EQUALS:
326
+ return _values_equal_strict(value, cond.value, spec.field_type)
327
+ if cond.operator == ConditionOperator.NOT_EQUALS:
328
+ return not _values_equal_strict(value, cond.value, spec.field_type)
329
+ if cond.operator == ConditionOperator.IN and cond.values is not None:
330
+ return any(_values_equal_strict(value, item, spec.field_type) for item in cond.values)
331
+ return False
332
+
333
+
334
+ def _eval_conditional_presence(
335
+ rule: ConditionalPresenceRule,
336
+ fields: Mapping[str, tuple[FieldPresence, Any]],
337
+ schema: ExtractionSchema,
338
+ record_id: str,
339
+ ) -> list[DiagnosticIssue]:
340
+ if not _eval_condition(rule.when, fields, schema):
341
+ return []
342
+
343
+ issues: list[DiagnosticIssue] = []
344
+ for target_path in rule.target_fields:
345
+ tp, tv, tspec = _resolve_record_path(fields, schema, target_path)
346
+ if rule.kind == ConditionalPresenceKind.REQUIRED_IF:
347
+ is_satisfied = tp == FieldPresence.PRESENT and (tv is not None or tspec.nullable)
348
+ if not is_satisfied:
349
+ default_msg = (
350
+ f"Conditional rule '{rule.rule_id}' failed: field '{target_path}' is "
351
+ f"required when '{rule.when.field}' satisfies '{rule.when.operator.value}'."
352
+ )
353
+ issues.append(
354
+ _make_rule_issue(
355
+ code="conditional_required_missing",
356
+ severity=rule.severity,
357
+ message=rule.message or default_msg,
358
+ record_id=record_id,
359
+ field_path=target_path,
360
+ expected=f"present {target_path}",
361
+ actual="missing" if tp == FieldPresence.MISSING else "null",
362
+ )
363
+ )
364
+ elif rule.kind == ConditionalPresenceKind.FORBIDDEN_IF and (
365
+ tp == FieldPresence.PRESENT and tv is not None
366
+ ):
367
+ default_msg = (
368
+ f"Conditional rule '{rule.rule_id}' failed: field '{target_path}' is "
369
+ f"forbidden when '{rule.when.field}' satisfies '{rule.when.operator.value}'."
370
+ )
371
+ issues.append(
372
+ _make_rule_issue(
373
+ code="conditional_forbidden_present",
374
+ severity=rule.severity,
375
+ message=rule.message or default_msg,
376
+ record_id=record_id,
377
+ field_path=target_path,
378
+ expected=f"absent {target_path}",
379
+ actual="present",
380
+ )
381
+ )
382
+ return issues
383
+
384
+
385
+ def _eval_group_presence(
386
+ rule: GroupPresenceRule,
387
+ fields: Mapping[str, tuple[FieldPresence, Any]],
388
+ schema: ExtractionSchema,
389
+ record_id: str,
390
+ ) -> DiagnosticIssue | None:
391
+ present_fields: list[str] = []
392
+ for fpath in rule.fields:
393
+ fp, fv, _ = _resolve_record_path(fields, schema, fpath)
394
+ if fp == FieldPresence.PRESENT and fv is not None:
395
+ present_fields.append(fpath)
396
+
397
+ if rule.kind == GroupPresenceKind.MUTUALLY_EXCLUSIVE and len(present_fields) > 1:
398
+ default_msg = (
399
+ f"Group rule '{rule.rule_id}' failed: fields {', '.join(present_fields)} "
400
+ "are mutually exclusive."
401
+ )
402
+ return _make_rule_issue(
403
+ code="mutually_exclusive_fields",
404
+ severity=rule.severity,
405
+ message=rule.message or default_msg,
406
+ record_id=record_id,
407
+ field_path=present_fields[0],
408
+ expected=f"at most one of {', '.join(rule.fields)}",
409
+ actual=f"present: {', '.join(present_fields)}",
410
+ )
411
+
412
+ if rule.kind == GroupPresenceKind.AT_LEAST_ONE_OF and not present_fields:
413
+ default_msg = (
414
+ f"Group rule '{rule.rule_id}' failed: at least one of "
415
+ f"{', '.join(rule.fields)} must be present."
416
+ )
417
+ return _make_rule_issue(
418
+ code="missing_required_group",
419
+ severity=rule.severity,
420
+ message=rule.message or default_msg,
421
+ record_id=record_id,
422
+ field_path=rule.fields[0],
423
+ expected=f"at least one of {', '.join(rule.fields)}",
424
+ actual="none present",
425
+ )
426
+
427
+ return None
428
+
429
+
430
+ def evaluate_cross_field_rules(
431
+ fields: Mapping[str, tuple[FieldPresence, Any]],
432
+ schema: ExtractionSchema,
433
+ *,
434
+ record_id: str,
435
+ ) -> tuple[list[DiagnosticIssue], list[DiagnosticIssue]]:
436
+ """Evaluate all declared ExtractionSchema.rules in order, separating errors and warnings."""
437
+ errors: list[DiagnosticIssue] = []
438
+ warnings: list[DiagnosticIssue] = []
439
+
440
+ for rule in schema.rules:
441
+ emitted: list[DiagnosticIssue] = []
442
+ if isinstance(rule, ComparisonRule):
443
+ issue = _eval_comparison(rule, fields, schema, record_id)
444
+ if issue is not None:
445
+ emitted.append(issue)
446
+ elif isinstance(rule, ArithmeticRule):
447
+ issue = _eval_arithmetic(rule, fields, schema, record_id)
448
+ if issue is not None:
449
+ emitted.append(issue)
450
+ elif isinstance(rule, ConditionalPresenceRule):
451
+ emitted.extend(_eval_conditional_presence(rule, fields, schema, record_id))
452
+ elif isinstance(rule, GroupPresenceRule):
453
+ issue = _eval_group_presence(rule, fields, schema, record_id)
454
+ if issue is not None:
455
+ emitted.append(issue)
456
+
457
+ for diag in emitted:
458
+ if diag.severity == IssueSeverity.ERROR:
459
+ errors.append(diag)
460
+ else:
461
+ warnings.append(diag)
462
+
463
+ return errors, warnings