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
//! Validate command - Validate JSONL annotation files
use super::super::output::color;
use anno::core::grounded::{GroundedDocument, Location, Signal, SignalId, SignalValidationError};
use clap::Parser;
use std::fs;
/// Validate JSONL annotation files
#[derive(Parser, Debug)]
pub struct ValidateArgs {
/// JSONL files to validate
#[arg(required = true)]
pub files: Vec<String>,
}
/// Execute the validate command.
pub fn run(args: ValidateArgs) -> Result<(), String> {
let mut total_errors = 0;
let mut total_warnings = 0;
let mut total_entries = 0;
for file in &args.files {
let content =
fs::read_to_string(file).map_err(|e| format!("Failed to read {}: {}", file, e))?;
for (line_num, line) in content.lines().enumerate() {
if line.trim().is_empty() {
continue;
}
total_entries += 1;
let entry: serde_json::Value = serde_json::from_str(line)
.map_err(|e| format!("{}:{}: Invalid JSON: {}", file, line_num + 1, e))?;
let text = entry["text"]
.as_str()
.ok_or_else(|| format!("{}:{}: Missing 'text' field", file, line_num + 1))?;
let entities = entry["entities"]
.as_array()
.ok_or_else(|| format!("{}:{}: Missing 'entities' array", file, line_num + 1))?;
let mut doc = GroundedDocument::new(format!("{}:{}", file, line_num + 1), text);
for (i, ent) in entities.iter().enumerate() {
// Check for missing required fields
let start = match ent["start"].as_u64() {
Some(v) => v as usize,
None => {
eprintln!(
"{} {}:{}:entity[{}]: missing 'start' field",
color("33", "warn"),
file,
line_num + 1,
i
);
total_warnings += 1;
0
}
};
let end = match ent["end"].as_u64() {
Some(v) => v as usize,
None => {
eprintln!(
"{} {}:{}:entity[{}]: missing 'end' field",
color("33", "warn"),
file,
line_num + 1,
i
);
total_warnings += 1;
0
}
};
let ent_text = ent["text"].as_str().unwrap_or("");
let ent_type = ent["type"]
.as_str()
.or(ent["label"].as_str())
.unwrap_or("UNK");
let signal = Signal::new(
SignalId::new(i as u64),
Location::text(start, end),
ent_text,
ent_type,
1.0,
);
if let Some(err) = signal.validate_against(text) {
match err {
SignalValidationError::OutOfBounds { .. }
| SignalValidationError::InvalidSpan { .. } => {
eprintln!(
"{} {}:{}:entity[{}]: {}",
color("31", "error"),
file,
line_num + 1,
i,
err
);
total_errors += 1;
}
SignalValidationError::TextMismatch { .. } => {
eprintln!(
"{} {}:{}:entity[{}]: {}",
color("33", "warn"),
file,
line_num + 1,
i,
err
);
total_warnings += 1;
}
}
}
doc.add_signal(signal);
}
// Check for overlapping entity spans
let mut spans: Vec<(usize, usize, usize)> = Vec::new(); // (start, end, entity_index)
for (i, ent) in entities.iter().enumerate() {
let s = ent["start"].as_u64().unwrap_or(0) as usize;
let e = ent["end"].as_u64().unwrap_or(0) as usize;
if e > s {
for &(ps, pe, pi) in &spans {
if s < pe && e > ps {
eprintln!(
"{} {}:{}:entity[{}]: overlaps with entity[{}] ([{}..{}) vs [{}..{}))",
color("33", "warn"),
file,
line_num + 1,
i,
pi,
s,
e,
ps,
pe,
);
total_warnings += 1;
}
}
spans.push((s, e, i));
}
}
}
}
println!();
println!(
"Validated {} entries in {} file(s)",
total_entries,
args.files.len()
);
if total_errors > 0 {
println!("{} {} errors", color("31", "x"), total_errors);
}
if total_warnings > 0 {
println!("{} {} warnings", color("33", "!"), total_warnings);
}
if total_errors == 0 && total_warnings == 0 {
println!("{} All valid", color("32", "ok:"));
}
if total_errors > 0 {
return Err(format!("{} validation errors", total_errors));
}
Ok(())
}