forked from LayerLens/stratix-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocument_evaluation.py
More file actions
212 lines (181 loc) · 6.65 KB
/
document_evaluation.py
File metadata and controls
212 lines (181 loc) · 6.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
#!/usr/bin/env python3
"""Document Evaluation -- LayerLens Python SDK Sample.
Evaluates document processing for extraction accuracy, cross-field
consistency, and structural integrity using dedicated judges.
Prerequisites:
pip install layerlens --index-url https://sdk.layerlens.ai/package
export LAYERLENS_STRATIX_API_KEY=your-api-key
Usage:
python document_evaluation.py
"""
from __future__ import annotations
import os
import sys
import json
import time
from typing import Any
from layerlens import Stratix
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
from _helpers import create_judge, upload_trace_dict, poll_evaluation_results
# ---------------------------------------------------------------------------
# Sample data
# ---------------------------------------------------------------------------
SAMPLES: list[dict[str, Any]] = [
{
"id": "doc-001",
"name": "Invoice (complete)",
"document_type": "invoice",
"ground_truth": {
"vendor": "Acme Corp",
"date": "2026-03-01",
"total": 1250.00,
"line_items": [
{"description": "Widget A", "qty": 10, "price": 50.00},
{"description": "Widget B", "qty": 5, "price": 150.00},
],
},
"extracted": {
"vendor": "Acme Corp",
"date": "2026-03-01",
"total": 1250.00,
"line_items": [
{"description": "Widget A", "qty": 10, "price": 50.00},
{"description": "Widget B", "qty": 5, "price": 150.00},
],
},
},
{
"id": "doc-002",
"name": "Receipt (partial extraction)",
"document_type": "receipt",
"ground_truth": {
"vendor": "Coffee Shop",
"date": "2026-03-15",
"total": 12.50,
"tax": 1.06,
},
"extracted": {
"vendor": "Coffee Shop",
"date": "2026-03-15",
"total": 12.50,
},
},
]
JUDGE_DEFINITIONS: list[dict[str, str]] = [
{
"name": "Document Extraction Judge",
"evaluation_goal": (
"Evaluate whether the extracted fields from the document match "
"the ground truth. Check for missing fields, incorrect values, "
"and extraction completeness."
),
},
{
"name": "Document Consistency Judge",
"evaluation_goal": (
"Evaluate whether the extracted document fields are internally "
"consistent. Check that totals match line items, dates are valid, "
"and cross-field references are correct."
),
},
{
"name": "Document Structure Judge",
"evaluation_goal": (
"Evaluate whether the extracted document maintains proper structural "
"integrity. Check for correct nesting, proper field types, and "
"valid data formats."
),
},
]
# ---------------------------------------------------------------------------
# Display
# ---------------------------------------------------------------------------
_PASS_COLOR = "\033[92m"
_FAIL_COLOR = "\033[91m"
_RESET = "\033[0m"
def display_result(label: str, score: float | None, passed: bool | None, reasoning: str) -> None:
"""Display a single evaluation result."""
score_str = f"{score:.2f}" if score is not None else "N/A"
if passed is not None:
color = _PASS_COLOR if passed else _FAIL_COLOR
status = "PASS" if passed else "FAIL"
else:
color = ""
status = "PEND"
detail = (reasoning[:60] + "...") if reasoning else ""
print(f" {label:14s} {color}{status:6s}{_RESET} ({score_str}) - {detail}")
# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------
def main() -> None:
"""Run document evaluation on all samples."""
print("=== LayerLens Document Evaluation Sample ===\n")
try:
client = Stratix()
except Exception as exc:
print(f"ERROR: Failed to initialize LayerLens client: {exc}")
sys.exit(1)
# Create judges up front
print(f"Creating {len(JUDGE_DEFINITIONS)} judges...")
judges = []
for jdef in JUDGE_DEFINITIONS:
judge = create_judge(
client,
name=f"{jdef['name']} {int(time.time())}",
evaluation_goal=jdef["evaluation_goal"],
)
judges.append((jdef["name"].replace("Document ", "").replace(" Judge", ""), judge))
print(f" Created: {judge.name} (id={judge.id})")
print()
if not judges:
print("ERROR: No judges were created. Cannot proceed.")
sys.exit(1)
print(f"Evaluating {len(SAMPLES)} document extractions...\n")
passed_all = 0
try:
for sample in SAMPLES:
print(f"Sample: {sample['name']}")
trace_result = upload_trace_dict(
client,
input_text=json.dumps(sample["ground_truth"]),
output_text=json.dumps(sample["extracted"]),
metadata={
"document_type": sample["document_type"],
"ground_truth": sample["ground_truth"],
},
)
trace_id = trace_result.trace_ids[0] if trace_result.trace_ids else sample["id"]
all_passed = True
for label, judge in judges:
evaluation = client.trace_evaluations.create(
trace_id=trace_id,
judge_id=judge.id,
)
if not evaluation:
display_result(label, None, None, "Failed to create evaluation")
all_passed = False
continue
results = poll_evaluation_results(client, evaluation.id)
if results:
r = results[0]
display_result(label, r.score, r.passed, r.reasoning or "")
if not r.passed:
all_passed = False
else:
display_result(label, None, None, "(results pending)")
all_passed = False
if all_passed:
passed_all += 1
print()
print(f"Overall: {passed_all}/{len(SAMPLES)} documents passed all checks")
finally:
# Clean up judges
print("\nCleaning up judges...")
for _, judge in judges:
try:
client.judges.delete(judge.id)
print(f" Deleted: {judge.name}")
except Exception:
print(f" WARNING: Could not delete judge {judge.id}")
if __name__ == "__main__":
main()