eval_variants.py
15.7 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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
"""Prepare fixed queries and evaluate two DesignImageSearch endpoints serially.
Use 'prepare --corpus EXPORT --queries NEW_DIRECTORY' once, then use
'run --queries DIRECTORY --blue-corpus EXPORT --green-corpus EXPORT
--blue-url URL --green-url URL --output NEW_DIRECTORY'. Exports are CSV or
JSON lists with id,url columns/keys. Export each endpoint's full tenant corpus
before running. URLs are the complete /images/search endpoints.
Optional --real-images is a CSV or JSON list of id,path records with labeled
matches. Paths are relative to the list file. Vectors are evaluated using
the first 20 returned results (MRR@20). Tokens come from DIS_BLUE_JWT and
DIS_GREEN_JWT, or from the environment variables selected with the CLI flags.
"""
import argparse
from collections import Counter
import csv
from hashlib import sha256
from io import BytesIO
import json
import os
from pathlib import Path
import random
import sys
from time import perf_counter
import cv2
import numpy as np
from PIL import Image
import pillow_avif # Registers AVIF with Pillow.
import requests
SAMPLE_SIZE = 300
MIN_DARK = 100
MIN_REAL = 20
VARIANTS = ('darken', 'crop', 'screenshot', 'white_border', 'phone')
GROUPS = ('dark', 'other', 'real')
TOP_N = 20
def read_records(path):
with path.open(encoding='utf-8-sig', newline='') as stream:
records = json.load(stream) if path.suffix.lower() == '.json' else list(csv.DictReader(stream))
if not isinstance(records, list):
raise ValueError(f'{path.name} must contain a list of records')
return records
def read_corpus(path):
corpus = {}
for record in read_records(path):
design_id, url = str(int(record['id'])), record['url']
if not isinstance(url, str) or not url.startswith(('http://', 'https://')):
raise ValueError(f'Invalid image URL for ID {design_id}')
if corpus.setdefault(design_id, url) != url:
raise ValueError(f'Conflicting URLs for ID {design_id} in {path.name}')
if not corpus:
raise ValueError(f'Empty candidate export: {path.name}')
return corpus
def matching_corpus(blue, green):
blue_only = blue.keys() - green.keys()
green_only = green.keys() - blue.keys()
different_urls = {key for key in blue.keys() & green.keys() if blue[key] != green[key]}
if blue_only or green_only or different_urls:
raise ValueError(f'Candidate corpora differ: blue-only={len(blue_only)}, '
f'green-only={len(green_only)}, URL mismatches={len(different_urls)}')
return blue
def is_dark(image):
gray = cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2GRAY)
foreground = gray[gray <= 245]
return bool(foreground.size and foreground.mean() < 70)
def variants(image, rng):
w, h = image.size
gamma = np.rint(255 * (np.arange(256) / 255) ** 1.8).astype(np.uint8)
yield 'darken', image.point(gamma.tolist() * 3)
cw, ch = max(1, round(w * .7)), max(1, round(h * .7))
x, y = (w - cw) // 2, (h - ch) // 2
yield 'crop', image.crop((x, y, x + cw, y + ch))
yield 'screenshot', image.resize((max(1, round(w * .6)), max(1, round(h * .6))),
Image.Resampling.LANCZOS)
bx, by = round(w * .15), round(h * .15)
framed = Image.new('RGB', (w + 2 * bx, h + 2 * by), 'white')
framed.paste(image, (bx, by))
yield 'white_border', framed
corners = np.float32([[0, 0], [w - 1, 0], [w - 1, h - 1], [0, h - 1]])
skewed = corners + np.float32([[.04*w, .03*h], [-.01*w, .01*h],
[-.04*w, -.02*h], [.01*w, -.04*h]])
matrix = cv2.getPerspectiveTransform(corners, skewed)
warped = cv2.warpPerspective(np.asarray(image), matrix, (w, h), borderMode=cv2.BORDER_REPLICATE)
noisy = warped + rng.normal(0, 4, warped.shape).astype(np.float32)
yield 'phone', Image.fromarray(np.clip(noisy, 0, 255).astype(np.uint8))
def sample_images(corpus, directory, seed, timeout):
candidates = sorted(corpus.items(), key=lambda pair: int(pair[0]))
random.Random(seed).shuffle(candidates)
reserved, remaining = [], []
download_failures = 0
with requests.Session() as session:
for design_id, url in candidates:
try:
response = session.get(url, timeout=timeout)
response.raise_for_status()
with Image.open(BytesIO(response.content)) as decoded:
image = decoded.convert('RGB')
if min(image.size) < 2:
raise ValueError('Image too small to generate variants')
except (requests.RequestException, OSError, ValueError):
download_failures += 1
continue
group = 'dark' if is_dark(image) else 'other'
bucket = reserved if group == 'dark' and len(reserved) < MIN_DARK else remaining
if bucket is remaining and len(remaining) == SAMPLE_SIZE - MIN_DARK:
continue
path = directory / f'{design_id}.png'
image.save(path)
bucket.append((design_id, group, path))
if len(reserved) + len(remaining) == SAMPLE_SIZE:
print(f'Sampled {SAMPLE_SIZE} images, download/decode failures={download_failures}')
return reserved + remaining
raise ValueError(f'Sampling requires {SAMPLE_SIZE} images with at least {MIN_DARK} dark; '
f'found {len(reserved) + len(remaining)} qualifying images '
f'({len(reserved)} reserved dark), failures={download_failures}')
def write_json(path, value):
path.write_text(json.dumps(value, indent=2, ensure_ascii=False) + '\n', encoding='utf-8')
def prepare(args):
from tempfile import TemporaryDirectory
corpus = read_corpus(args.corpus)
real = []
if args.real_images:
for record in read_records(args.real_images):
design_id = str(int(record['id']))
if design_id not in corpus:
raise ValueError(f'Real query target {design_id} is absent from the corpus')
real.append((design_id, args.real_images.parent / record['path']))
rng = np.random.default_rng(args.seed)
queries = []
with TemporaryDirectory(prefix='dis-eval-') as scratch:
samples = sample_images(corpus, Path(scratch), args.seed, args.timeout)
args.queries.mkdir(parents=True, exist_ok=False)
def save(image, design_id, group, variant):
screenshot = variant == 'screenshot'
path = args.queries / f'{len(queries):04}.{"jpg" if screenshot else "png"}'
image.save(path, **({'quality': 60} if screenshot else {}))
queries.append({'file': path.name, 'id': design_id, 'url': corpus[design_id],
'group': group, 'variant': variant,
'sha256': sha256(path.read_bytes()).hexdigest()})
for design_id, group, path in samples:
with Image.open(path) as image:
for variant, transformed in variants(image, rng):
save(transformed, design_id, group, variant)
for design_id, path in real:
with Image.open(path) as image:
save(image.convert('RGB'), design_id, 'real', 'real')
write_json(args.queries / 'manifest.json', {'seed': args.seed, 'queries': queries})
print(f'Saved {len(queries)} fixed queries ({len(real)} real) in {args.queries}')
def read_queries(directory, corpus):
manifest = json.loads((directory / 'manifest.json').read_text(encoding='utf-8'))
queries = manifest['queries']
if not queries or len({q['file'] for q in queries}) != len(queries):
raise ValueError('Manifest must have nonempty, unique query filenames')
observed = {}
variants_by_id = {}
for query in queries:
filename = query['file']
if Path(filename).name != filename or not filename.endswith(('.png', '.jpg')):
raise ValueError('Invalid query filename in manifest')
if corpus.get(query['id']) != query['url']:
raise ValueError(f"Prepared query target {query['id']} changed in the candidate corpus")
group, variant = query['group'], query['variant']
if (group, variant) == ('real', 'real'):
continue
if group not in GROUPS[:2] or variant not in VARIANTS:
raise ValueError('Invalid query group or variant')
design_id = query['id']
variants_by_id.setdefault(design_id, []).append(variant)
if observed.setdefault(design_id, group) != group:
raise ValueError(f'Conflicting query groups for ID {design_id}')
if len(observed) != SAMPLE_SIZE or Counter(observed.values())['dark'] < MIN_DARK:
raise ValueError('Manifest does not meet the D3 sample quotas')
if any(sorted(names) != sorted(VARIANTS) for names in variants_by_id.values()):
raise ValueError('Each sampled design must have all five variants exactly once')
for query in queries:
read_query_image(directory, query)
return queries
def read_query_image(directory, query):
data = (directory / query['file']).read_bytes()
if sha256(data).hexdigest() != query['sha256']:
raise ValueError(f"Query file contents changed: {query['file']}")
return data
def _measure(session, url, token, query, image, timeout):
start = perf_counter()
filename = query['file']
mime = 'image/jpeg' if filename.endswith('.jpg') else 'image/png'
rank, error = None, None
try:
response = session.post(url, headers={'Authorization': f'Bearer {token}'},
files={'file': (filename, image, mime)}, data={'top_n': TOP_N},
timeout=timeout, allow_redirects=False)
if response.status_code != 200:
error = f'HTTP {response.status_code}'
else:
results = response.json()['results']
if not isinstance(results, list) or len(results) > TOP_N:
raise ValueError('Invalid search results')
ids = [str(int(result['design_id'])) for result in results]
rank = ids.index(query['id']) + 1 if query['id'] in ids else None
except requests.Timeout:
error = 'timeout'
except requests.RequestException:
error = 'request_failed'
except (KeyError, TypeError, ValueError):
error = 'invalid_response'
elapsed = perf_counter() - start
if elapsed >= timeout or error == 'timeout':
error, rank, elapsed = 'timeout', None, max(elapsed, timeout)
return {'file': filename, 'id': query['id'], 'group': query['group'],
'variant': query['variant'], 'rank': rank, 'seconds': elapsed, 'error': error}
def metrics(rows):
if not rows:
return {'status': 'missing', 'queries': 0}
ranks = [row['rank'] for row in rows]
p50, p95 = np.percentile([row['seconds'] for row in rows], [50, 95])
return {'status': 'measured', 'queries': len(rows),
'top1': sum(rank == 1 for rank in ranks) / len(rows),
'top5': sum(rank is not None and rank <= 5 for rank in ranks) / len(rows),
'mrr': sum(1 / rank for rank in ranks if rank is not None) / len(rows),
'p50_seconds': float(p50), 'p95_seconds': float(p95),
'failures': sum(row['error'] is not None for row in rows),
'timeouts': sum(row['error'] == 'timeout' for row in rows)}
def summarize(rows):
return {
'overall': metrics(rows),
'groups': {group: metrics([row for row in rows if row['group'] == group]) for group in GROUPS},
'other_by_variant': {variant: metrics([row for row in rows
if row['group'] == 'other' and row['variant'] == variant])
for variant in VARIANTS},
}
def gate(blue, green):
def delta(before, after, key, threshold, strict=False):
if before['status'] == 'missing' or after['status'] == 'missing':
return 'missing'
change = after[key] - before[key]
passed = change > threshold if strict else change + 1e-12 >= threshold
return 'pass' if passed else 'fail'
checks = {'dark_top5': delta(blue['groups']['dark'], green['groups']['dark'], 'top5', 0, strict=True)}
for variant in VARIANTS:
checks[f'other_{variant}_top5'] = delta(blue['other_by_variant'][variant],
green['other_by_variant'][variant], 'top5', -.015)
for key in ('top1', 'top5'):
before, after = blue['groups']['real'], green['groups']['real']
checks[f'real_{key}'] = ('missing' if min(before['queries'], after['queries']) < MIN_REAL
else delta(before, after, key, 0))
bp95, gp95 = blue['overall']['p95_seconds'], green['overall']['p95_seconds']
checks['overall_p95'] = 'pass' if gp95 <= min(1.5, 1.5 * bp95) else 'fail'
return {'passed': all(result == 'pass' for result in checks.values()), 'checks': checks}
def run(args):
corpus = matching_corpus(read_corpus(args.blue_corpus), read_corpus(args.green_corpus))
queries = read_queries(args.queries, corpus)
tokens = [os.getenv(args.blue_token_env), os.getenv(args.green_token_env)]
if not all(tokens):
raise ValueError('Both JWT environment variables must be set')
args.output.mkdir(parents=True, exist_ok=False)
summary, rows = {}, []
for endpoint, url, token in zip(('blue', 'green'), (args.blue_url, args.green_url), tokens):
with requests.Session() as session:
measured = [_measure(session, url, token, query, read_query_image(args.queries, query),
args.timeout) for query in queries]
summary[endpoint] = summarize(measured)
rows.extend(dict(row, endpoint=endpoint) for row in measured)
decision = gate(summary['blue'], summary['green'])
write_json(args.output / 'summary.json', {'candidate_count': len(corpus), 'top_n': TOP_N,
'timeout_seconds': args.timeout, 'gate': decision,
**summary})
with (args.output / 'queries.csv').open('w', encoding='utf-8', newline='') as stream:
writer = csv.DictWriter(stream, fieldnames=list(rows[0]))
writer.writeheader()
writer.writerows(rows)
print('D3 GATE ' + ('PASS' if decision['passed'] else 'FAIL'))
return 0 if decision['passed'] else 1
def main():
parser = argparse.ArgumentParser(description=__doc__)
commands = parser.add_subparsers(dest='command', required=True)
prep = commands.add_parser('prepare', help='sample images and save a fixed manifest')
prep.add_argument('--corpus', required=True, type=Path)
prep.add_argument('--real-images', type=Path)
prep.add_argument('--seed', type=int, default=20261118)
evaluate = commands.add_parser('run', help='verify corpora and query both endpoints')
evaluate.add_argument('--blue-corpus', required=True, type=Path)
evaluate.add_argument('--green-corpus', required=True, type=Path)
evaluate.add_argument('--blue-url', required=True)
evaluate.add_argument('--green-url', required=True)
evaluate.add_argument('--blue-token-env', default='DIS_BLUE_JWT')
evaluate.add_argument('--green-token-env', default='DIS_GREEN_JWT')
evaluate.add_argument('--output', required=True, type=Path)
for command in (prep, evaluate):
command.add_argument('--queries', required=True, type=Path)
command.add_argument('--timeout', type=float, default=10)
args = parser.parse_args()
if not np.isfinite(args.timeout) or args.timeout <= 0:
parser.error('--timeout must be finite and positive')
try:
return prepare(args) if args.command == 'prepare' else run(args)
except (OSError, ValueError, TypeError, KeyError) as error:
print(f'Evaluation could not complete: {error}', file=sys.stderr)
return 2
if __name__ == '__main__':
raise SystemExit(main())