forked from MakazhanAlpamys/Soup
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidator.py
More file actions
257 lines (223 loc) · 8.4 KB
/
Copy pathvalidator.py
File metadata and controls
257 lines (223 loc) · 8.4 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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
"""Dataset validation and statistics."""
from __future__ import annotations
from typing import Any, Optional
from soup_cli.data.formats import (
_DROP_EXCEPTIONS,
VALID_FORMATS,
_dispatch_conversion,
)
# How many per-row drop reasons to surface in `issues`. Enough to make
# `validate` actionable ("which rows and why") without flooding the output on a
# file where every row is bad.
_MAX_REASON_SAMPLES = 3
def _to_hashable(val: Any) -> Any:
"""Recursively convert values into type-tagged hashable nested tuples."""
if val is None or isinstance(val, (str, int, float, bool)):
return (type(val).__name__, val)
if isinstance(val, dict):
return (
"dict",
tuple(
(str(k), _to_hashable(v))
for k, v in sorted(val.items(), key=lambda item: str(item[0]))
),
)
if isinstance(val, list):
return ("list", tuple(_to_hashable(v) for v in val))
if isinstance(val, tuple):
return ("tuple", tuple(_to_hashable(v) for v in val))
if isinstance(val, set):
try:
return ("set", tuple(_to_hashable(v) for v in sorted(val, key=repr)))
except TypeError:
return ("set", tuple(_to_hashable(v) for v in val))
return (type(val).__name__, str(val))
def _row_signature(row: dict) -> tuple:
"""Return a type-tagged hashable canonical representation of a row dict."""
return tuple(
(str(k), _to_hashable(v))
for k, v in sorted(row.items(), key=lambda item: str(item[0]))
)
def _compute_row_text_length(row: dict) -> tuple[int, int]:
"""Compute text length and count empty/None fields without intermediate string joins."""
parts_len = 0
parts_count = 0
empty_count = 0
for v in row.values():
if v is None:
empty_count += 1
elif v:
v_str = v if isinstance(v, str) else str(v)
parts_len += len(v_str)
parts_count += 1
char_len = parts_len + (parts_count - 1 if parts_count > 0 else 0)
return char_len, empty_count
def validate_and_stats(data: list[dict], expected_format: Optional[str] = None) -> dict:
"""Compute stats and validate dataset."""
if not data:
return {
"total": 0,
"columns": [],
"avg_length": 0,
"min_length": 0,
"max_length": 0,
"empty_fields": 0,
"duplicates": 0,
"issues": ["Dataset is empty"],
"valid_rows": 0,
}
columns = list(data[0].keys())
empty_count = 0
short_count = 0
seen_rows: set[tuple] = set()
dup_count = 0
total_length = 0
min_length = float("inf")
max_length = 0
invalid_count = 0
sample_reasons: list[str] = []
check_format = bool(expected_format and expected_format in VALID_FORMATS)
# Probe whether the dataset values are all strings/None (flat rows).
# Real JSONL datasets are homogeneous — if row 0 is flat, all rows are.
# The fast path avoids the _to_hashable type-tagging overhead entirely.
# Guard with try/except for heterogeneous datasets (mixed formats).
_flat_values = all(
isinstance(v, str) or v is None for v in data[0].values()
)
for idx, row in enumerate(data):
# 1. Duplicate detection — fast path for flat rows (3x faster),
# type-tagged fallback for rows with non-string values (nested
# dicts/lists, ints, bools) where Python equality conflates types
# (e.g. 1 == True, 1 == 1.0).
if _flat_values:
try:
sig = tuple(sorted(row.items()))
if sig in seen_rows:
dup_count += 1
else:
seen_rows.add(sig)
except TypeError:
# Heterogeneous dataset: this row has unhashable values
# even though row 0 didn't. Fall back for this row.
sig = _row_signature(row)
if sig in seen_rows:
dup_count += 1
else:
seen_rows.add(sig)
else:
sig = _row_signature(row)
if sig in seen_rows:
dup_count += 1
else:
seen_rows.add(sig)
# 2. Format validation using real converter path (#712).
# Inlined from format_to_messages_with_reason: we already validated
# expected_format ∈ VALID_FORMATS above, so skip the per-row check.
if check_format:
try:
_dispatch_conversion(row, expected_format)
reason = None
except _DROP_EXCEPTIONS as exc:
reason = str(exc)
if reason is not None:
invalid_count += 1
if len(sample_reasons) < _MAX_REASON_SAMPLES:
sample_reasons.append(f"row {idx}: {reason}")
# 3. Shared text length & empty field calculation
char_len, empty_fields_in_row = _compute_row_text_length(row)
empty_count += empty_fields_in_row
total_length += char_len
if char_len < min_length:
min_length = char_len
if char_len > max_length:
max_length = char_len
if char_len < 10:
short_count += 1
valid_rows = len(data) - invalid_count
issues: list[str] = []
if check_format and invalid_count > 0:
issues.append(
f"{invalid_count} rows fail to convert for '{expected_format}' format "
f"(load_dataset would drop them)"
)
issues.extend(sample_reasons)
if invalid_count > len(sample_reasons):
issues.append(f"... and {invalid_count - len(sample_reasons)} more")
if dup_count > 0:
issues.append(f"{dup_count} duplicate rows found")
if empty_count > 0:
issues.append(f"{empty_count} empty fields found")
if short_count > 0:
issues.append(f"{short_count} samples are very short (<10 chars)")
return {
"total": len(data),
"columns": columns,
"avg_length": round(total_length / len(data)),
"min_length": int(min_length),
"max_length": int(max_length),
"empty_fields": empty_count,
"duplicates": dup_count,
"issues": issues,
"valid_rows": valid_rows,
}
def _percentile(sorted_vals: list, pct: int) -> int:
"""Compute a percentile from a sorted list."""
if not sorted_vals:
return 0
idx = int(len(sorted_vals) * pct / 100)
idx = min(idx, len(sorted_vals) - 1)
return sorted_vals[idx]
def extended_stats(data: list[dict]) -> dict:
"""Compute extended statistics: length distribution, token counts, languages."""
if not data:
return {
"total": 0,
"lengths": [],
"token_counts": [],
"length_p10": 0,
"length_p25": 0,
"length_p50": 0,
"length_p75": 0,
"length_p90": 0,
"avg_tokens": 0,
"min_tokens": 0,
"max_tokens": 0,
"languages": {},
}
lengths = []
token_counts = []
for row in data:
char_len, _ = _compute_row_text_length(row)
lengths.append(char_len)
# Approximate token count: ~4 chars per token for English
token_counts.append(max(1, char_len // 4))
sorted_lengths = sorted(lengths)
# Language detection (optional, lazy import)
languages: dict[str, int] = {}
try:
from langdetect import detect
sample_size = min(100, len(data))
for row in data[:sample_size]:
text = " ".join(str(v) for v in row.values() if v)
if len(text) > 20:
try:
lang = detect(text)
languages[lang] = languages.get(lang, 0) + 1
except Exception:
pass
except ImportError:
pass # langdetect not installed, skip
return {
"total": len(data),
"lengths": lengths,
"token_counts": token_counts,
"length_p10": _percentile(sorted_lengths, 10),
"length_p25": _percentile(sorted_lengths, 25),
"length_p50": _percentile(sorted_lengths, 50),
"length_p75": _percentile(sorted_lengths, 75),
"length_p90": _percentile(sorted_lengths, 90),
"avg_tokens": round(sum(token_counts) / len(token_counts)),
"min_tokens": min(token_counts),
"max_tokens": max(token_counts),
"languages": languages,
}