falseok 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.
- falseok/__init__.py +7 -0
- falseok/__main__.py +5 -0
- falseok/cli.py +120 -0
- falseok/data.py +390 -0
- falseok/page.py +768 -0
- falseok/signatures.json +524 -0
- falseok-0.2.0.dist-info/METADATA +218 -0
- falseok-0.2.0.dist-info/RECORD +12 -0
- falseok-0.2.0.dist-info/WHEEL +5 -0
- falseok-0.2.0.dist-info/entry_points.txt +2 -0
- falseok-0.2.0.dist-info/licenses/LICENSE +21 -0
- falseok-0.2.0.dist-info/top_level.txt +1 -0
falseok/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""falseok: catch the 200 OK that isn't."""
|
|
2
|
+
__version__ = "0.2.0"
|
|
3
|
+
|
|
4
|
+
from .data import DataReport, check_rows, compare, load_rows # noqa: E402
|
|
5
|
+
from .page import VERDICTS, PageResult, check_page, decode_html, load_signatures # noqa: E402
|
|
6
|
+
|
|
7
|
+
__all__ = ["check_page", "decode_html", "VERDICTS", "load_signatures", "PageResult", "compare", "check_rows", "load_rows", "DataReport"]
|
falseok/__main__.py
ADDED
falseok/cli.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""Command line: falseok page ... / falseok data ..."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import csv
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import sys
|
|
9
|
+
|
|
10
|
+
from . import __version__
|
|
11
|
+
from .data import compare, load_rows
|
|
12
|
+
from .page import check_page, decode_html, load_signatures
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _page(args) -> int:
|
|
16
|
+
sigs = load_signatures(args.signatures)
|
|
17
|
+
status = args.status
|
|
18
|
+
if status is not None and not 100 <= status <= 599:
|
|
19
|
+
raise ValueError(f"--status must be between 100 and 599, got {status}")
|
|
20
|
+
headers = None
|
|
21
|
+
if args.headers:
|
|
22
|
+
with open(args.headers, "rb") as f:
|
|
23
|
+
headers = f.read().decode("latin-1")
|
|
24
|
+
if headers.lstrip()[:1] == "{": # a JSON object instead of raw "Name: value" lines
|
|
25
|
+
try:
|
|
26
|
+
headers = json.loads(headers.encode("latin-1").decode("utf-8"))
|
|
27
|
+
except ValueError as e:
|
|
28
|
+
raise ValueError(f"{args.headers}: starts like JSON but is not valid JSON ({e})") from None
|
|
29
|
+
if not isinstance(headers, dict):
|
|
30
|
+
raise ValueError(f"{args.headers}: expected a JSON object of header names and values")
|
|
31
|
+
worst, out, stdin = 0, [], None
|
|
32
|
+
many = len(args.files) > 1
|
|
33
|
+
for path in args.files:
|
|
34
|
+
try:
|
|
35
|
+
if path == "-":
|
|
36
|
+
if stdin is None:
|
|
37
|
+
stdin = sys.stdin.buffer.read()
|
|
38
|
+
data = stdin
|
|
39
|
+
else:
|
|
40
|
+
with open(path, "rb") as f:
|
|
41
|
+
data = f.read()
|
|
42
|
+
except OSError as e:
|
|
43
|
+
print(f"falseok: {path}: {e.strerror or e}", file=sys.stderr)
|
|
44
|
+
worst = 2
|
|
45
|
+
if args.json:
|
|
46
|
+
out.append({"file": path, "verdict": None, "error": e.strerror or str(e)})
|
|
47
|
+
continue
|
|
48
|
+
r = check_page(data, status=status, signatures=sigs, headers=headers) # bytes: the headers may name the charset
|
|
49
|
+
if not r.ok:
|
|
50
|
+
worst = max(worst, 1)
|
|
51
|
+
if args.json:
|
|
52
|
+
out.append({"file": path, **r.to_dict()})
|
|
53
|
+
else:
|
|
54
|
+
who = f" [{r.vendor}]" if r.vendor else ""
|
|
55
|
+
print(f"{path + ': ' if many else ''}{r.verdict}{who}: {r.reason}", flush=True)
|
|
56
|
+
if args.json:
|
|
57
|
+
print(json.dumps(out if many else out[0], indent=2, ensure_ascii=False))
|
|
58
|
+
return worst
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _data(args) -> int:
|
|
62
|
+
rows = load_rows(args.file)
|
|
63
|
+
before = load_rows(args.vs) if args.vs else None
|
|
64
|
+
r = compare(rows, before, max_drop=args.max_drop)
|
|
65
|
+
if args.json:
|
|
66
|
+
print(json.dumps(r.to_dict(), indent=2, ensure_ascii=False, default=str))
|
|
67
|
+
else:
|
|
68
|
+
head = f"{r.rows} rows" + (f" (before: {r.rows_before})" if r.rows_before is not None else "")
|
|
69
|
+
print(("ok: " if r.ok else "PROBLEM: ") + head)
|
|
70
|
+
for i in r.issues:
|
|
71
|
+
print(f" - {i.kind}: {i.message}")
|
|
72
|
+
return 0 if r.ok else 1
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def main(argv=None) -> int:
|
|
76
|
+
p = argparse.ArgumentParser(
|
|
77
|
+
prog="falseok", description="Catch the 200 OK that isn't."
|
|
78
|
+
)
|
|
79
|
+
p.add_argument("--version", action="version", version=f"falseok {__version__}")
|
|
80
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
81
|
+
|
|
82
|
+
pg = sub.add_parser("page", help="is this HTML page real content or a block page?")
|
|
83
|
+
pg.add_argument("files", nargs="+", help="HTML files, or - for stdin")
|
|
84
|
+
pg.add_argument("--status", type=int, help="the HTTP status you got")
|
|
85
|
+
pg.add_argument("--headers", metavar="FILE", help="the response headers you got: a file of 'Name: value' lines "
|
|
86
|
+
"(what `curl -D FILE` saves) or a JSON object")
|
|
87
|
+
pg.add_argument("--signatures", help="use your own signatures JSON file")
|
|
88
|
+
pg.add_argument("--json", action="store_true")
|
|
89
|
+
pg.set_defaults(fn=_page)
|
|
90
|
+
|
|
91
|
+
dt = sub.add_parser("data", help="did this dataset silently break?")
|
|
92
|
+
dt.add_argument("file", help="today's data: .json, .jsonl or .csv")
|
|
93
|
+
dt.add_argument("--vs", help="the last good run, to compare against")
|
|
94
|
+
dt.add_argument("--max-drop", type=float, default=0.2, help="allowed row loss (default 0.2 = 20%%)")
|
|
95
|
+
dt.add_argument("--json", action="store_true")
|
|
96
|
+
dt.set_defaults(fn=_data)
|
|
97
|
+
|
|
98
|
+
args = p.parse_args(argv)
|
|
99
|
+
for stream in (sys.stdout, sys.stderr):
|
|
100
|
+
# A Windows console cannot print every character a page title may hold: replace, never crash.
|
|
101
|
+
try:
|
|
102
|
+
stream.reconfigure(errors="backslashreplace")
|
|
103
|
+
except (AttributeError, ValueError):
|
|
104
|
+
pass
|
|
105
|
+
try:
|
|
106
|
+
return args.fn(args)
|
|
107
|
+
except BrokenPipeError:
|
|
108
|
+
# The reader went away (`falseok ... | head -1`): stop quietly, as other command-line tools do.
|
|
109
|
+
try:
|
|
110
|
+
sys.stdout = open(os.devnull, "w")
|
|
111
|
+
except OSError:
|
|
112
|
+
pass
|
|
113
|
+
return 0
|
|
114
|
+
except (OSError, ValueError, csv.Error) as e:
|
|
115
|
+
print(f"falseok: {e}", file=sys.stderr)
|
|
116
|
+
return 2
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
if __name__ == "__main__":
|
|
120
|
+
sys.exit(main())
|
falseok/data.py
ADDED
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
"""Data check: did today's scrape silently lose rows or fields compared to the last good run?"""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import csv
|
|
5
|
+
import gzip
|
|
6
|
+
import io
|
|
7
|
+
import json
|
|
8
|
+
import re
|
|
9
|
+
from collections import Counter
|
|
10
|
+
from itertools import chain
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from typing import Iterable, List, Optional
|
|
13
|
+
|
|
14
|
+
from .page import load_signatures
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass
|
|
18
|
+
class Issue:
|
|
19
|
+
kind: str # rows_dropped, field_missing, field_emptied, field_constant, type_changed, duplicates, block_text
|
|
20
|
+
field: Optional[str]
|
|
21
|
+
message: str
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class DataReport:
|
|
26
|
+
rows: int
|
|
27
|
+
rows_before: Optional[int]
|
|
28
|
+
issues: List[Issue] = field(default_factory=list)
|
|
29
|
+
|
|
30
|
+
@property
|
|
31
|
+
def ok(self) -> bool:
|
|
32
|
+
return not self.issues
|
|
33
|
+
|
|
34
|
+
def to_dict(self) -> dict:
|
|
35
|
+
return {
|
|
36
|
+
"ok": self.ok,
|
|
37
|
+
"rows": self.rows,
|
|
38
|
+
"rows_before": self.rows_before,
|
|
39
|
+
"issues": [i.__dict__ for i in self.issues],
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _decode(data: bytes) -> str:
|
|
44
|
+
if data[:2] == b"\x1f\x8b":
|
|
45
|
+
try:
|
|
46
|
+
data = gzip.decompress(data)
|
|
47
|
+
except (OSError, EOFError):
|
|
48
|
+
raise ValueError("looks gzip-compressed but cannot be unpacked") from None
|
|
49
|
+
if data[:2] in (b"\xff\xfe", b"\xfe\xff"):
|
|
50
|
+
return data.decode("utf-16")
|
|
51
|
+
if b"\x00" in data[:4096]:
|
|
52
|
+
raise ValueError("binary file, not JSON or CSV")
|
|
53
|
+
try:
|
|
54
|
+
return data.decode("utf-8-sig")
|
|
55
|
+
except UnicodeDecodeError:
|
|
56
|
+
return data.decode("cp1252", errors="replace") # what Excel on Windows saves
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _row_lists(node, depth=0):
|
|
60
|
+
"""Every list of objects inside a JSON document, up to 3 levels down."""
|
|
61
|
+
if isinstance(node, list):
|
|
62
|
+
dicts = sum(1 for x in node if isinstance(x, dict))
|
|
63
|
+
if dicts:
|
|
64
|
+
yield dicts, node
|
|
65
|
+
if isinstance(node, dict) and depth < 3:
|
|
66
|
+
for v in node.values():
|
|
67
|
+
yield from _row_lists(v, depth + 1)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _from_json(text: str) -> List[dict]:
|
|
71
|
+
data = json.loads(text)
|
|
72
|
+
if isinstance(data, list):
|
|
73
|
+
return [r for r in data if isinstance(r, dict)]
|
|
74
|
+
if isinstance(data, dict):
|
|
75
|
+
found = sorted(_row_lists(data), key=lambda c: -c[0])
|
|
76
|
+
if found:
|
|
77
|
+
return [r for r in found[0][1] if isinstance(r, dict)]
|
|
78
|
+
return [data]
|
|
79
|
+
raise ValueError(f"the JSON holds a single {type(data).__name__}, not rows")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _from_jsonl(text: str) -> List[dict]:
|
|
83
|
+
rows = []
|
|
84
|
+
for n, line in enumerate(text.splitlines(), 1):
|
|
85
|
+
if not line.strip():
|
|
86
|
+
continue
|
|
87
|
+
try:
|
|
88
|
+
r = json.loads(line)
|
|
89
|
+
except json.JSONDecodeError as e:
|
|
90
|
+
raise ValueError(f"line {n} is not valid JSON ({e.msg})") from None
|
|
91
|
+
if isinstance(r, dict):
|
|
92
|
+
rows.append(r)
|
|
93
|
+
return rows
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _from_csv(text: str) -> List[dict]:
|
|
97
|
+
try:
|
|
98
|
+
csv.field_size_limit(2**31 - 1)
|
|
99
|
+
except OverflowError:
|
|
100
|
+
pass
|
|
101
|
+
sample = text[:8192]
|
|
102
|
+
try:
|
|
103
|
+
dialect = csv.Sniffer().sniff(sample, delimiters=",;\t|")
|
|
104
|
+
except csv.Error:
|
|
105
|
+
dialect = csv.excel
|
|
106
|
+
try:
|
|
107
|
+
table = list(csv.reader(io.StringIO(text), dialect))
|
|
108
|
+
except csv.Error as e:
|
|
109
|
+
raise ValueError(f"cannot read the CSV ({e})") from None
|
|
110
|
+
if not table:
|
|
111
|
+
return []
|
|
112
|
+
header, seen = [], Counter()
|
|
113
|
+
for i, name in enumerate(table[0]):
|
|
114
|
+
name = name.strip() or f"column_{i + 1}"
|
|
115
|
+
seen[name] += 1
|
|
116
|
+
header.append(name if seen[name] == 1 else f"{name}_{seen[name]}")
|
|
117
|
+
rows = []
|
|
118
|
+
for cells in table[1:]:
|
|
119
|
+
if not any(c.strip() for c in cells):
|
|
120
|
+
continue
|
|
121
|
+
row = {h: (cells[i] if i < len(cells) else None) for i, h in enumerate(header)}
|
|
122
|
+
for i in range(len(header), len(cells)):
|
|
123
|
+
row[f"column_{i + 1}"] = cells[i] # a ragged row: extra cells get their own columns
|
|
124
|
+
rows.append(row)
|
|
125
|
+
return rows
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def load_rows(path: str) -> List[dict]:
|
|
129
|
+
"""Read JSON (a list, or an object holding one), JSON Lines or CSV, guessing from the content.
|
|
130
|
+
|
|
131
|
+
Raises ValueError when the file holds no rows we can read.
|
|
132
|
+
"""
|
|
133
|
+
with open(path, "rb") as f:
|
|
134
|
+
text = _decode(f.read())
|
|
135
|
+
low = path.lower()
|
|
136
|
+
start = text.lstrip()[:1]
|
|
137
|
+
if low.endswith((".csv", ".tsv")) or start not in ("[", "{"):
|
|
138
|
+
if not text.strip():
|
|
139
|
+
return []
|
|
140
|
+
try:
|
|
141
|
+
scalar = json.loads(text)
|
|
142
|
+
except json.JSONDecodeError:
|
|
143
|
+
return _from_csv(text)
|
|
144
|
+
raise ValueError(f"the file holds a single JSON {type(scalar).__name__}, not rows")
|
|
145
|
+
if low.endswith((".jsonl", ".ndjson")):
|
|
146
|
+
return _from_jsonl(text)
|
|
147
|
+
try:
|
|
148
|
+
return _from_json(text)
|
|
149
|
+
except json.JSONDecodeError:
|
|
150
|
+
return _from_jsonl(text)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
_EMPTY_WORDS = {"null", "none", "n/a", "na", "nan", "undefined", "-"}
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _empty(v) -> bool:
|
|
157
|
+
if v is None:
|
|
158
|
+
return True
|
|
159
|
+
if isinstance(v, float) and v != v: # NaN
|
|
160
|
+
return True
|
|
161
|
+
if isinstance(v, str):
|
|
162
|
+
s = v.strip()
|
|
163
|
+
return not s or s.lower() in _EMPTY_WORDS
|
|
164
|
+
if isinstance(v, (list, dict, tuple, set)):
|
|
165
|
+
return not v
|
|
166
|
+
return False
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
_BOOL_WORDS = {"true", "false", "yes", "no", "y", "n", "on", "off"}
|
|
170
|
+
_NUMBER = re.compile(r"^[+-]?(\d[\d,. ']*)?\d$|^[+-]?\d*[.,]\d+$")
|
|
171
|
+
_MONEY = re.compile(r"^[\s$€£¥₹₽₺₩¢%]+|[\s$€£¥₹₽₺₩¢%]+$|^(usd|eur|gbp|ron|lei|chf|cad|aud)\s*|\s*(usd|eur|gbp|ron|lei|chf|cad|aud)$", re.I)
|
|
172
|
+
# A character no number can hold, even after the currency is taken off (re.I also folds ſ, İ and ı into s and i).
|
|
173
|
+
_NOT_NUMBER = re.compile(r"[^\d\s+\-.,'$€£¥₹₽₺₩¢%usdeiorgbpnlchfaUSDEIORGBPNLCHFAſİı]")
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _kind(v) -> str:
|
|
177
|
+
if isinstance(v, bool):
|
|
178
|
+
return "bool"
|
|
179
|
+
if isinstance(v, (int, float)):
|
|
180
|
+
return "number"
|
|
181
|
+
if isinstance(v, str):
|
|
182
|
+
s = v.strip().replace(" ", " ").replace(" ", " ")
|
|
183
|
+
if s.lower() in _BOOL_WORDS:
|
|
184
|
+
return "bool" # CSV keeps booleans as text
|
|
185
|
+
if _NOT_NUMBER.search(s):
|
|
186
|
+
return "text" # most text stops here, before the two slower patterns
|
|
187
|
+
if _NUMBER.match(_MONEY.sub("", s)):
|
|
188
|
+
return "number"
|
|
189
|
+
return "text"
|
|
190
|
+
if isinstance(v, (list, tuple)):
|
|
191
|
+
return "list"
|
|
192
|
+
if isinstance(v, dict):
|
|
193
|
+
return "object"
|
|
194
|
+
return type(v).__name__
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _same_kind(a: str, b: str) -> bool:
|
|
198
|
+
# 0/1 and true/false are the same column in different clothes.
|
|
199
|
+
return a == b or {a, b} == {"bool", "number"}
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _dump(v, depth: int = 0) -> str:
|
|
203
|
+
"""A stable text form of any value, also for dicts with odd keys."""
|
|
204
|
+
if depth > 40:
|
|
205
|
+
return "..." # deeper than any real record; stops runaway recursion
|
|
206
|
+
if isinstance(v, dict):
|
|
207
|
+
items = sorted(((str(k), _dump(x, depth + 1)) for k, x in v.items()))
|
|
208
|
+
return "{" + ",".join(f"{k}:{x}" for k, x in items) + "}"
|
|
209
|
+
if isinstance(v, (list, tuple)):
|
|
210
|
+
return "[" + ",".join(_dump(x, depth + 1) for x in v) + "]"
|
|
211
|
+
try:
|
|
212
|
+
return json.dumps(v)
|
|
213
|
+
except (TypeError, ValueError):
|
|
214
|
+
return repr(v)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _row_key(r: dict) -> str:
|
|
218
|
+
"""A row as text, to spot exact repeats. The C JSON encoder does it about 10 times faster than _dump; rows it
|
|
219
|
+
cannot encode (odd keys or values, deep nesting) fall back to _dump, marked so the two forms never mix."""
|
|
220
|
+
try:
|
|
221
|
+
return json.dumps(r, sort_keys=True)
|
|
222
|
+
except (TypeError, ValueError, RecursionError):
|
|
223
|
+
return "\x00" + _dump(r)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
_PLAIN_TYPES = (str, int, float, bool, type(None))
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
class _Profile:
|
|
230
|
+
def __init__(self, rows: List[dict], judged: Optional[dict] = None):
|
|
231
|
+
self.n = len(rows)
|
|
232
|
+
self.fields = Counter(chain.from_iterable(rows)) # rows where the key exists, in first-seen order
|
|
233
|
+
self.empty = Counter()
|
|
234
|
+
self.kinds = {}
|
|
235
|
+
self.values = {}
|
|
236
|
+
# Column by column. Real columns repeat their values ("Diesel" 2,000 times): equal values are counted in one
|
|
237
|
+
# C-level pass, then each distinct value is judged once (and once for both runs: pass the same judged dict).
|
|
238
|
+
# Keyed by (type, value), since 1, 1.0 and True are equal in Python but not the same value here.
|
|
239
|
+
judged = {} if judged is None else judged
|
|
240
|
+
for k, have in self.fields.items():
|
|
241
|
+
col = [r[k] for r in rows] if have == self.n else [r[k] for r in rows if k in r]
|
|
242
|
+
try:
|
|
243
|
+
counts = Counter(zip(map(type, col), col))
|
|
244
|
+
exact = (float, 0.0) not in counts # 0.0 and -0.0 would merge; they print differently
|
|
245
|
+
except TypeError: # a list or dict in the column
|
|
246
|
+
exact = False
|
|
247
|
+
if not exact:
|
|
248
|
+
self._slow(k, col)
|
|
249
|
+
continue
|
|
250
|
+
kinds, vals = Counter(), set()
|
|
251
|
+
for key, n in counts.items():
|
|
252
|
+
j = judged.get(key)
|
|
253
|
+
if j is None:
|
|
254
|
+
e = _empty(key[1])
|
|
255
|
+
j = judged[key] = [e, None if e else _kind(key[1]), None]
|
|
256
|
+
if j[0]:
|
|
257
|
+
self.empty[k] += n
|
|
258
|
+
continue
|
|
259
|
+
kinds[j[1]] += n
|
|
260
|
+
if len(vals) < 50:
|
|
261
|
+
if j[2] is None:
|
|
262
|
+
j[2] = _dump(key[1])[:200]
|
|
263
|
+
vals.add(j[2])
|
|
264
|
+
if kinds:
|
|
265
|
+
self.kinds[k] = kinds
|
|
266
|
+
self.values[k] = vals
|
|
267
|
+
|
|
268
|
+
def _slow(self, k, col) -> None:
|
|
269
|
+
"""Value by value, for a column holding lists or dicts (or a 0.0 next to a -0.0)."""
|
|
270
|
+
for v in col:
|
|
271
|
+
if _empty(v):
|
|
272
|
+
self.empty[k] += 1
|
|
273
|
+
continue
|
|
274
|
+
self.kinds.setdefault(k, Counter())[_kind(v)] += 1
|
|
275
|
+
vals = self.values.setdefault(k, set())
|
|
276
|
+
if len(vals) < 50:
|
|
277
|
+
vals.add(_dump(v)[:200])
|
|
278
|
+
|
|
279
|
+
def empty_rate(self, k) -> float:
|
|
280
|
+
# A missing key counts as empty.
|
|
281
|
+
return (self.empty[k] + self.n - self.fields[k]) / self.n if self.n else 0.0
|
|
282
|
+
|
|
283
|
+
def main_kind(self, k) -> Optional[str]:
|
|
284
|
+
c = self.kinds.get(k)
|
|
285
|
+
if not c:
|
|
286
|
+
return None
|
|
287
|
+
# Ties: text wins (the general kind), then by name; never by row order.
|
|
288
|
+
return sorted(c.items(), key=lambda kv: (-kv[1], kv[0] != "text", kv[0]))[0][0]
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _pct(x: float) -> str:
|
|
292
|
+
return f"{x * 100:.0f}%"
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
_PHRASES = None
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _block_phrases():
|
|
299
|
+
"""One search for every block phrase at once, built once (one pass per value instead of one per phrase)."""
|
|
300
|
+
global _PHRASES
|
|
301
|
+
if _PHRASES is None:
|
|
302
|
+
parts = [f"(?:{s['_rx'].pattern})" for s in load_signatures() if s.get("in_data")]
|
|
303
|
+
_PHRASES = re.compile("|".join(parts), re.I) if parts else re.compile(r"(?!)")
|
|
304
|
+
return _PHRASES
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _check_share(name: str, x: float) -> float:
|
|
308
|
+
if not isinstance(x, (int, float)) or x != x or not 0 <= x <= 1:
|
|
309
|
+
raise ValueError(f"{name} must be a share between 0 and 1 (0.2 = 20%), got {x!r}")
|
|
310
|
+
return x
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def compare(
|
|
314
|
+
rows: List[dict],
|
|
315
|
+
before: Optional[List[dict]] = None,
|
|
316
|
+
max_drop: float = 0.2,
|
|
317
|
+
max_empty_jump: float = 0.15,
|
|
318
|
+
max_duplicates: float = 0.05,
|
|
319
|
+
) -> DataReport:
|
|
320
|
+
"""Check a dataset on its own, and against a previous good run if you pass one."""
|
|
321
|
+
_check_share("max_drop", max_drop)
|
|
322
|
+
_check_share("max_empty_jump", max_empty_jump)
|
|
323
|
+
_check_share("max_duplicates", max_duplicates)
|
|
324
|
+
rows = [r for r in rows if isinstance(r, dict)]
|
|
325
|
+
if before is not None:
|
|
326
|
+
before = [r for r in before if isinstance(r, dict)]
|
|
327
|
+
judged: dict = {} # shared by both runs: most values come back from one day to the next
|
|
328
|
+
now = _Profile(rows, judged)
|
|
329
|
+
report = DataReport(rows=now.n, rows_before=len(before) if before is not None else None)
|
|
330
|
+
add = report.issues.append
|
|
331
|
+
|
|
332
|
+
if now.n == 0:
|
|
333
|
+
add(Issue("rows_dropped", None, "the dataset is empty"))
|
|
334
|
+
return report
|
|
335
|
+
|
|
336
|
+
# Duplicates: whole rows that repeat.
|
|
337
|
+
keys = Counter(_row_key(r) for r in rows)
|
|
338
|
+
dupes = sum(c - 1 for c in keys.values() if c > 1)
|
|
339
|
+
if dupes / now.n > max_duplicates:
|
|
340
|
+
add(Issue("duplicates", None, f"{dupes} of {now.n} rows are exact repeats ({_pct(dupes / now.n)})"))
|
|
341
|
+
|
|
342
|
+
# Block text that ended up inside the data ("Robot Check" as a product title).
|
|
343
|
+
phrases = _block_phrases()
|
|
344
|
+
hit_rows, example = 0, None
|
|
345
|
+
# Each distinct text is searched once; rows are walked only when some text matched.
|
|
346
|
+
hits = {v for v in {v for r in rows for v in r.values() if isinstance(v, str)} if phrases.search(v)}
|
|
347
|
+
for r in rows if hits else ():
|
|
348
|
+
for k, v in r.items():
|
|
349
|
+
if isinstance(v, str) and v in hits:
|
|
350
|
+
hit_rows += 1
|
|
351
|
+
example = example or (k, v[:60])
|
|
352
|
+
break
|
|
353
|
+
if hit_rows:
|
|
354
|
+
add(Issue("block_text", example[0], f'{hit_rows} {"row contains" if hit_rows == 1 else "rows contain"} block-page text, e.g. {example[0]} = "{example[1]}"'))
|
|
355
|
+
|
|
356
|
+
if before is None:
|
|
357
|
+
for k in now.fields:
|
|
358
|
+
rate = now.empty_rate(k)
|
|
359
|
+
if rate == 1.0 and now.n >= 3:
|
|
360
|
+
add(Issue("field_emptied", k, f"{k}: empty in all {now.n} rows"))
|
|
361
|
+
return report
|
|
362
|
+
|
|
363
|
+
old = _Profile(before, judged)
|
|
364
|
+
if old.n:
|
|
365
|
+
drop = (old.n - now.n) / old.n
|
|
366
|
+
if drop > max_drop:
|
|
367
|
+
add(Issue("rows_dropped", None, f"{now.n} rows, was {old.n} (-{_pct(drop)})"))
|
|
368
|
+
|
|
369
|
+
for k in old.fields:
|
|
370
|
+
if old.empty_rate(k) >= 0.95:
|
|
371
|
+
continue # was already empty, nothing to lose
|
|
372
|
+
if k not in now.fields:
|
|
373
|
+
add(Issue("field_missing", k, f"{k}: gone (was in {_pct(old.fields[k] / old.n)} of rows)"))
|
|
374
|
+
continue
|
|
375
|
+
e_old, e_now = old.empty_rate(k), now.empty_rate(k)
|
|
376
|
+
if e_now - e_old > max_empty_jump:
|
|
377
|
+
add(Issue("field_emptied", k, f"{k}: {_pct(e_old)} empty before, {_pct(e_now)} now"))
|
|
378
|
+
continue
|
|
379
|
+
k_old, k_now = old.main_kind(k), now.main_kind(k)
|
|
380
|
+
if k_old and k_now and not _same_kind(k_old, k_now):
|
|
381
|
+
add(Issue("type_changed", k, f"{k}: was mostly {k_old}, now mostly {k_now}"))
|
|
382
|
+
if len(old.values.get(k, ())) > 1 and len(now.values.get(k, ())) == 1 and now.n >= 5:
|
|
383
|
+
only = next(iter(now.values[k]))
|
|
384
|
+
add(Issue("field_constant", k, f"{k}: every row now has the same value {only[:40]}"))
|
|
385
|
+
return report
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def check_rows(rows: Iterable[dict], **kw) -> DataReport:
|
|
389
|
+
"""Check one dataset with no previous run to compare against."""
|
|
390
|
+
return compare(list(rows), None, **kw)
|