Repository navigation
Expand file tree
/
Copy pathdriver.py
More file actions
423 lines (373 loc) · 14.1 KB
/
Copy pathdriver.py
File metadata and controls
423 lines (373 loc) · 14.1 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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
"""Long-form bench driver: submit arms to the bench dw.serve, wait, and
measure each output through the server's compare and assess routes (the
same routes the MCP tools call, so the tester can repeat any number).
Stdlib only; never fetches media files."""
import argparse
import json
import math
import os
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from dataclasses import dataclass
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
DEFAULT_SERVER = "http://127.0.0.1:18766"
DEFAULT_TOKEN_FILE = "~/.dw-bench-token"
MAX_COMPARE_BYTES = 4_000_000
MAX_COMPARE_MOMENTS = 8
TERMINAL = ("succeeded", "failed", "cancelled")
@dataclass
class Arm:
name: str
scene: str
workflow: str # path under bench/workflows/
arguments: dict
seed: int
workflow_id_suffix: str = "" # distinct inline id forces a step-cache miss
moments: list | None = None # overrides the scene's moments for this arm
@dataclass
class Scene:
name: str
crop: list
moments: list # "frame:N" at segments 1, middle and last
face_reference: str | None = None
lines: list | None = None
crop_verified: bool = False
def load_arms(path):
data = json.loads(Path(path).read_text())
return [
Arm(
name=a["name"],
scene=a["scene"],
workflow=a["workflow"],
arguments=a.get("arguments") or {},
seed=a["seed"],
workflow_id_suffix=a.get("workflow_id_suffix", ""),
moments=a.get("moments"),
)
for a in data
]
def load_scenes(path):
data = json.loads(Path(path).read_text())
return {
s["name"]: Scene(
name=s["name"],
crop=s["crop"],
moments=s["moments"],
face_reference=s.get("face_reference"),
lines=s.get("lines"),
crop_verified=s.get("crop_verified", False),
)
for s in data
}
def http(method, path, server, token, payload=None, params=None):
"""One JSON request; the single seam the tests fake."""
url = server.rstrip("/") + path
if params:
url += "?" + urllib.parse.urlencode(params)
headers = {"Accept": "application/json"}
if token:
headers["Authorization"] = f"Bearer {token}"
data = None
if payload is not None:
data = json.dumps(payload).encode()
headers["Content-Type"] = "application/json"
request = urllib.request.Request(url, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(request, timeout=120) as response:
return json.loads(response.read() or b"null")
except urllib.error.HTTPError as e:
raise RuntimeError(
f"{method} {path}: {e.code} {e.read().decode()[:500]}"
) from e
def _write_atomic(path, text):
"""Write via a temp file and rename, so an interrupted run never leaves a
truncated record."""
target = Path(path)
target.parent.mkdir(parents=True, exist_ok=True)
tmp = target.with_name(target.name + ".tmp")
tmp.write_text(text)
os.replace(tmp, target)
def health(server, token):
return http("GET", "/api/health", server, token)
def submit(arm, server, token, workspace=None):
workflow = json.loads((HERE / "workflows" / arm.workflow).read_text())
if arm.workflow_id_suffix:
workflow["id"] = (
workflow.get("id", Path(arm.workflow).stem) + arm.workflow_id_suffix
)
payload = {
"workflow": workflow,
"arguments": {**arm.arguments, "seed": arm.seed},
"note": f"bench arm {arm.name} (scene {arm.scene}, seed {arm.seed})",
"acknowledged_cost": True,
}
params = {"workspace": workspace} if workspace else None
job = http("POST", "/api/jobs", server, token, payload, params)
return job["id"]
def wait(job_id, server, token, timeout_s, poll_s=15):
deadline = time.monotonic() + timeout_s
while True:
job = http("GET", f"/api/jobs/{job_id}", server, token)
if job.get("status") in TERMINAL:
return job
if time.monotonic() >= deadline:
raise TimeoutError(
f"job {job_id} still {job.get('status')} after {timeout_s}s"
)
time.sleep(poll_s)
def output_name(job):
"""The gallery name of the job's deliverable video: the last video file
in the manifest, `final` subfolder first."""
kinds = job.get("output_kinds") or {}
videos = [
(entry.get("subfolder") == "final", name)
for entry in job.get("manifest") or []
for name in entry.get("files") or []
if kinds.get(name, "video") == "video"
]
finals = [name for final, name in videos if final]
best = (finals or [name for _, name in videos] or [None])[-1]
if best is None:
raise ValueError(f"job {job.get('id')} wrote no video")
return best
def _mean(values):
return sum(values) / len(values) if values else None
def _stats(out, values, name_mean, name_max):
values = [v for v in values if v is not None]
if values:
out[name_mean] = _mean(values)
out[name_max] = max(values)
SPLIT_MEASURES = ("saturation", "lightness", "contrast", "detail")
def _number(value):
return (
float(value)
if isinstance(value, (int, float)) and not isinstance(value, bool)
else None
)
def _split(out, segment_looks):
"""Seam/segment split of each look measure (#1324), from analyze_seams'
`segment_looks`. With endpoint windows the parts sum exactly:
total = seams + segments, where seams is the sum of each next segment's
first window minus this one's last, and segments the sum of each
segment's last window minus its first. A segment without the measure is
skipped and the seam bridges it, so the sum still telescopes.
The split says where a measure changes, not whether a viewer sees the
change: it informs a viewing verdict and doesn't replace one."""
for m in SPLIT_MEASURES:
spans = []
for entry in segment_looks or []:
first = _number(((entry or {}).get("first") or {}).get(m))
last = _number(((entry or {}).get("last") or {}).get(m))
if first is not None and last is not None:
spans.append((first, last))
if not spans:
continue
steps = [b[0] - a[1] for a, b in zip(spans, spans[1:])]
seams = sum(steps)
segments = sum(last - first for first, last in spans)
out[f"split_{m}_total"] = spans[-1][1] - spans[0][0]
out[f"split_{m}_segments"] = segments
if not steps:
continue # one segment: no seam to split by
out[f"split_{m}_seams"] = seams
if abs(seams) + abs(segments) > 0:
out[f"split_{m}_seam_share"] = seams / (abs(seams) + abs(segments))
if seams != 0:
agree = sum(1 for s in steps if s * seams > 0)
out[f"split_{m}_seam_sign"] = agree / len(steps)
def measure(job, scene, server, token, workspace=None, moments=None):
name = output_name(job)
params = {"probe": "analyze_seams"}
if workspace:
params["workspace"] = workspace
answer = http(
"GET",
f"/api/gallery/{urllib.parse.quote(name, safe='/')}/assess",
server,
token,
params=params,
)
seams = answer.get("seams") or []
out = {}
_split(out, answer.get("segment_looks"))
_stats(out, [s.get("jump_ratio") for s in seams], "seam_jump_mean", "seam_jump_max")
_stats(out, [s.get("look_ratio") for s in seams], "seam_look_mean", "seam_look_max")
_stats(
out,
[abs(s["level_step_db"]) for s in seams if s.get("level_step_db") is not None],
"seam_level_step_db_mean",
"seam_level_step_db_max",
)
at = moments or scene.moments
cells = []
# the compare route takes 1 to MAX_COMPARE_MOMENTS moments per call
for i in range(0, len(at), MAX_COMPARE_MOMENTS):
payload = {
"names": [name],
"max_dimension": 384,
"max_total_bytes": MAX_COMPARE_BYTES,
"at": at[i : i + MAX_COMPARE_MOMENTS],
"crop": scene.crop,
"texture_bands": True,
}
compared = http(
"POST",
"/api/gallery/compare",
server,
token,
payload,
{"workspace": workspace} if workspace else None,
)
row = (compared.get("texture") or [{}])[0]
cells += [c.get("texture") for c in row.get("cells") or []]
if len(cells) >= 2 and cells[0] and cells[-1]:
# Two-sided: blur (ratio < 1) and crust (ratio > 1) both count as
# drift, so the measure is |ln(last / first)| and lower is better.
for band in ("fine", "mid", "coarse"):
luma = cells[0].get("luma") or {}, cells[-1].get("luma") or {}
first, last = luma[0].get(band), luma[1].get(band)
if first and last and first > 0 and last > 0:
out[f"texture_{band}_seg_last"] = abs(math.log(last / first))
if job.get("started_at") is not None and job.get("finished_at") is not None:
out["wall_minutes"] = (job["finished_at"] - job["started_at"]) / 60.0
return out
def run_arms(
arms, scenes, server, token, do_measure, timeout_s, workspace=None, out_path=None
):
ids = {arm.name: submit(arm, server, token, workspace) for arm in arms}
records = []
def flush():
if out_path:
_write_atomic(out_path, json.dumps(records, indent=2))
for arm in arms:
record = {
"arm": arm.name,
"scene": arm.scene,
"seed": arm.seed,
"job_id": ids[arm.name],
}
try:
job = wait(ids[arm.name], server, token, timeout_s)
record["status"] = job.get("status")
record["error"] = job.get("error")
if job.get("status") == "succeeded":
record["output"] = output_name(job)
if do_measure:
record["measures"] = measure(
job, scenes[arm.scene], server, token, workspace, arm.moments
)
except Exception as exc: # one arm's failure must not lose the others
record.setdefault("status", "error")
record["error"] = f"{type(exc).__name__}: {exc}"
records.append(record)
flush()
return records
def measure_records(
records, scenes, arms, server, token, workspace=None, out_path=None
):
"""Measure again, without running again, every succeeded record, with the
scene crops and moments as they are now (an arm's own moments, when an
arms file names one, win). Other records pass through untouched."""
moments = {arm.name: arm.moments for arm in arms}
for record in records:
if record.get("status") != "succeeded":
continue
job = http("GET", f"/api/jobs/{record['job_id']}", server, token)
record["measures"] = measure(
job,
scenes[record["scene"]],
server,
token,
workspace,
moments.get(record["arm"]),
)
record["error"] = None # a measure error from the run is now stale
if out_path:
_write_atomic(out_path, json.dumps(records, indent=2))
return records
def report(records):
lines = []
keys = sorted({k for r in records for k in r.get("measures", {})})
lines.append("| arm | scene | seed | status | " + " | ".join(keys) + " |")
lines.append("|" + "---|" * (4 + len(keys)))
for r in records:
m = r.get("measures", {})
cells = [f"{m[k]:.3f}" if k in m else "" for k in keys]
lines.append(
f"| {r['arm']} | {r['scene']} | {r['seed']} | {r['status']} | "
+ " | ".join(cells)
+ " |"
)
return "\n".join(lines)
def _token(args):
if args.token_file:
return Path(args.token_file).expanduser().read_text().strip()
if os.environ.get("BENCH_TOKEN"):
return os.environ["BENCH_TOKEN"]
path = Path(DEFAULT_TOKEN_FILE).expanduser()
if path.is_file():
return path.read_text().strip()
raise SystemExit(
f"no bench token: pass --token-file, set BENCH_TOKEN, or write {DEFAULT_TOKEN_FILE}"
)
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--server", default=os.environ.get("BENCH_SERVER", DEFAULT_SERVER)
)
parser.add_argument("--token-file")
parser.add_argument("--workspace")
sub = parser.add_subparsers(dest="command", required=True)
run = sub.add_parser("run", help="submit arms, wait, optionally measure")
run.add_argument("arms")
run.add_argument("--scenes", default=str(HERE / "scenes.json"))
run.add_argument("--measure", action="store_true")
run.add_argument("--out")
run.add_argument("--timeout", type=int, default=7200)
meas = sub.add_parser(
"measure", help="measure a record's succeeded jobs again; rewrites it"
)
meas.add_argument("record")
meas.add_argument("--scenes", default=str(HERE / "scenes.json"))
meas.add_argument("--arms", help="arms file whose per-arm moments apply")
rep = sub.add_parser("report", help="markdown tables from records")
rep.add_argument("records", nargs="+")
args = parser.parse_args(argv)
if args.command == "report":
for path in args.records:
print(f"### {path}\n")
print(report(json.loads(Path(path).read_text())))
print()
return 0
token = _token(args)
if args.command == "measure":
measure_records(
json.loads(Path(args.record).read_text()),
load_scenes(args.scenes),
load_arms(args.arms) if args.arms else [],
args.server,
token,
args.workspace,
args.record,
)
return 0
records = run_arms(
load_arms(args.arms),
load_scenes(args.scenes) if args.measure else {},
args.server,
token,
args.measure,
args.timeout,
args.workspace,
args.out,
)
if not args.out:
print(json.dumps(records, indent=2))
return 0
if __name__ == "__main__":
sys.exit(main())