""" How accurately do AI vision models date historical photographs? The method lives here so it can be read, rerun and argued with. The results page at /ai-photo-dating-benchmark is built from what this script writes. The rules that keep the test fair: - A model is sent the image bytes and one fixed prompt. Never a title, caption, URL or filename: 114 of the 115 eligible captions contain the year, and most slugs do too, so all of those are kept away from the request entirely. - Images are re-encoded first, which drops EXIF and other embedded metadata. - Photographs showing a date in the frame are excluded by hand (review.json), because reading a date is not dating a photograph. - Prompt, photo list and scoring are fixed before the first full run. freeze refuses to change the photo list once results exist. - Every answer is scored, including ones that are bad or awkward. Refusals and unusable replies are counted and reported, not dropped. - Server-side refusal fallbacks are deliberately off. A fallback would silently swap in a different model, and this measures one named model at a time. - Each model runs on its vendor's default settings, as a person would meet it. Usage: python photo_dating_benchmark.py freeze # Firestore read, writes photos.json python photo_dating_benchmark.py prepare # downloads and re-encodes images python photo_dating_benchmark.py screen # dry run; add --spend --cap to pay python photo_dating_benchmark.py run --models claude-opus-5-5 # dry run, prints cost and sends nothing python photo_dating_benchmark.py run --models a,b --limit 5 --spend --cap 40 python photo_dating_benchmark.py score # writes results/summary.json python photo_dating_benchmark.py selftest # scoring check on made-up answers Nothing paid happens without --spend and --cap. The cap covers everything already in the raw files as well as this run, and is checked before every call. Keys are read from .env.local, the same way describe.py does. Values are never printed. """ import argparse import base64 import hashlib import io import json import os import pathlib import random import re import statistics import sys import time import urllib.request from datetime import datetime, timezone HERE = pathlib.Path(__file__).resolve().parent OUT = HERE / "benchmark" REVIEW = OUT / "review.json" PHOTOS = OUT / "photos.json" IMAGES = OUT / "images" RAW = OUT / "results" / "raw" # Pilot answers are kept and paid for, but are not part of the scored run. PILOT = OUT / "results" / "pilot" SCREEN = OUT / "results" / "screen.jsonl" SUMMARY = OUT / "results" / "summary.json" # Larger than this and the vendors downscale anyway, each in their own way. LONG_EDGE = 1568 JPEG_QUALITY = 90 REPEATS = 3 BOOTSTRAP_ROUNDS = 10000 BOOTSTRAP_SEED = 20261104 # A record that says only "circa" gets this many years either side. CIRCA_YEARS = 5 SCREEN_MODEL = "claude-haiku-5-5" # Tokens per call for the dry-run ceiling and the cap check. Real usage is what gets recorded. WORST_CASE_INPUT = 4000 WORST_CASE_OUTPUT = 4000 MAX_OUTPUT = 16000 # USD per million tokens (input, output), standard tier, read on 2026-11-04. # gemini-4-argon and gemini-3.8-flash double on later dates, listed in LATER_PRICES. PRICES = { "claude-opus-5-5": (4.00, 20.00), "claude-sonnet-5-5": (2.00, 10.00), "claude-haiku-5-5": (0.10, 0.50), "gpt-6.1-sol": (2.00, 10.00), "gpt-6.1-terra": (1.00, 5.00), "gemini-4-argon": (2.00, 10.00), "gemini-3.8-flash": (0.75, 3.75), } LATER_PRICES = { "gemini-4-argon": ("2026-12-01", (4.00, 20.00)), "gemini-3.8-flash": ("2027-01-01", (1.50, 7.50)), } PROMPT = """This is a scan of a historical photograph, possibly on a card mount. Estimate when the photograph was taken, using only what you can see in it. Reply with only a JSON object, with no other text, and these keys: "best_year": your single best estimate, as an integer "low_year": an integer "high_year": an integer, chosen so that you think there is an 80% chance the true year is between low_year and high_year "evidence": what in the image led you there, in under 40 words""" SCREEN_PROMPT = """Look carefully at this image, including any card mount, margins, stamps and handwriting. Transcribe any year, date or decade written anywhere in it. Do not estimate the date of the photograph itself. Reply with only a JSON object, with no other text, and these keys: "found": true or false "text": the date text you can read, or an empty string""" def load_env_files(): """Same loader as describe.py. A real shell variable always wins. Values are never printed.""" for name in (".env.local", ".env"): f = HERE.parent / name if not f.exists(): continue for line in f.read_text(encoding="utf-8").splitlines(): line = line.strip() if not line or line.startswith("#") or "=" not in line: continue if line.startswith("export "): line = line[len("export "):] k, _, v = line.partition("=") k, v = k.strip(), v.strip().strip('"').strip("'") if k and v and k not in os.environ: os.environ[k] = v # -------------------------------------------------------------------------- # Known dates # -------------------------------------------------------------------------- def parse_truth(raw) -> tuple[int, int, bool]: """ (low, high, exact) from a catalog date string. Raises on anything unrecognised, so a new shape of date stops the freeze instead of being scored wrongly. """ s = str(raw).strip().replace("–", "-") if m := re.fullmatch(r"(\d{4})(-\d{2}){0,2}", s): y = int(m.group(1)) return y, y, True # Trailing ? or ~ is the archive's own marker for an uncertain date. if m := re.fullmatch(r"(\d{4})(-\d{2}){0,2}[?~]", s): y = int(m.group(1)) return y - CIRCA_YEARS, y + CIRCA_YEARS, False if m := re.fullmatch(r"(\d{4})/(\d{4})~?", s): return int(m.group(1)), int(m.group(2)), False if m := re.fullmatch(r"c\. (\d{4})", s): y = int(m.group(1)) return y - CIRCA_YEARS, y + CIRCA_YEARS, False if m := re.fullmatch(r"c\. (\d{2})(\d{2})-(\d{2})", s): return int(m.group(1) + m.group(2)), int(m.group(1) + m.group(3)), False if m := re.fullmatch(r"early (\d{3})0s", s): return int(m.group(1)) * 10, int(m.group(1)) * 10 + 4, False raise ValueError(f"Unrecognised date: {raw!r}") def distance(year: float, low: int, high: int) -> float: """Years from `year` to the nearest edge of the known date. Zero inside it.""" return max(low - year, year - high, 0) # -------------------------------------------------------------------------- # freeze and prepare # -------------------------------------------------------------------------- def load_json(path): return json.loads(path.read_text(encoding="utf-8")) def write_json(path, data): path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(data, indent=1, ensure_ascii=True) + "\n", encoding="utf-8") def cmd_freeze(args): existing = list(RAW.glob("*.jsonl")) if RAW.exists() else [] if existing: sys.exit("Results already exist, so the photo list stays as it is. Changing it now would undo the point of freezing it.") # Importing initialises Firebase, so this stays out of the commands that do not need it. sys.path.insert(0, str(HERE)) from google.cloud.firestore_v1.base_query import FieldFilter from ingest_v3 import db from promo_pool import image_url, stated_free review = load_json(REVIEW) excluded = {e["id"]: e for e in review["exclusions"]} reviewed = set(review["reviewed_ids"]) tags = review["tags"] photos = [] eligible = 0 unreviewed = 0 query = db.collection("people").where(filter=FieldFilter("isPublic", "==", True)) for snap in query.stream(): doc = snap.to_dict() if not stated_free(doc) or not isinstance(doc.get("year"), int): continue # Photographs added to the archive after the review have not been looked at, # so they cannot be in the test until someone reviews them and adds their ids. if snap.id not in reviewed: unreviewed += 1 continue eligible += 1 low, high, exact = parse_truth(doc.get("dateTaken")) if snap.id in excluded: continue photos.append({ "id": snap.id, "title": doc.get("title"), "date_as_catalogued": doc.get("dateTaken"), "low": low, "high": high, "exact": exact, "tags": sorted(t for t, ids in tags.items() if snap.id in ids), "source_url": (doc.get("source") or {}).get("url"), "image_url": image_url(snap, doc, "view"), "image_sha256": None, }) photos.sort(key=lambda p: p["id"]) if eligible != len(reviewed): sys.exit(f"{len(reviewed)} photographs were reviewed but only {eligible} still pass stated_free. Find out why before freezing.") if unreviewed: print(f"{unreviewed} eligible photographs added since the review were left out") if eligible - len(excluded) != len(photos): sys.exit(f"{eligible} eligible, {len(excluded)} excluded, but {len(photos)} kept. review.json has gone stale; review the difference by hand.") write_json(PHOTOS, {"frozen_on": datetime.now(timezone.utc).date().isoformat(), "eligible": eligible, "photos": photos}) print(f"{eligible} eligible, {len(excluded)} excluded, {len(photos)} kept") def clean_image(raw: bytes) -> bytes: """Same pixels, smaller, with no metadata and no name. This is all a model ever sees of a photo.""" from PIL import Image im = Image.open(io.BytesIO(raw)).convert("RGB") im.thumbnail((LONG_EDGE, LONG_EDGE), Image.LANCZOS) # Pillow writes a source JPEG's comment back out on save, so only the pixels are carried over. clean = Image.new("RGB", im.size) clean.paste(im) buf = io.BytesIO() clean.save(buf, "JPEG", quality=JPEG_QUALITY, optimize=True) return buf.getvalue() def cmd_prepare(args): data = load_json(PHOTOS) IMAGES.mkdir(parents=True, exist_ok=True) for p in data["photos"]: path = IMAGES / f"{p['id']}.jpg" if not path.exists(): req = urllib.request.Request(p["image_url"], headers={"User-Agent": "photo-dating-benchmark"}) with urllib.request.urlopen(req, timeout=60) as r: path.write_bytes(clean_image(r.read())) digest = hashlib.sha256(path.read_bytes()).hexdigest() if p["image_sha256"] and p["image_sha256"] != digest: sys.exit(f"{p['id']}: image differs from the frozen one.") p["image_sha256"] = digest write_json(PHOTOS, data) print(f"{len(data['photos'])} images ready") def load_image(photo) -> str: raw = (IMAGES / f"{photo['id']}.jpg").read_bytes() if hashlib.sha256(raw).hexdigest() != photo["image_sha256"]: sys.exit(f"{photo['id']}: image differs from the frozen one. Run prepare.") return base64.standard_b64encode(raw).decode("ascii") # -------------------------------------------------------------------------- # Calling the models # -------------------------------------------------------------------------- def vendor_of(model: str) -> str: for prefix, vendor in (("claude-", "anthropic"), ("gpt-", "openai"), ("gemini-", "google")): if model.startswith(prefix): return vendor sys.exit(f"Unknown vendor for {model}") def call_anthropic(model, image_b64, prompt): import anthropic client = anthropic.Anthropic() response = client.messages.create( model=model, max_tokens=MAX_OUTPUT, messages=[{"role": "user", "content": [ {"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": image_b64}}, {"type": "text", "text": prompt}, ]}], ) text = "".join(b.text for b in response.content if b.type == "text") return {"text": text, "stop": response.stop_reason, "refused": response.stop_reason == "refusal", "input_tokens": response.usage.input_tokens, "output_tokens": response.usage.output_tokens} def call_openai(model, image_b64, prompt): import openai client = openai.OpenAI() response = client.responses.create( model=model, max_output_tokens=MAX_OUTPUT, store=False, input=[{"role": "user", "content": [ {"type": "input_image", "image_url": f"data:image/jpeg;base64,{image_b64}", "detail": "high"}, {"type": "input_text", "text": prompt}, ]}], ) refused = any(c.type == "refusal" for item in response.output if item.type == "message" for c in item.content) return {"text": response.output_text or "", "stop": response.status, "refused": refused, "input_tokens": response.usage.input_tokens, "output_tokens": response.usage.output_tokens} def call_google(model, image_b64, prompt): from google import genai from google.genai import types client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY")) response = client.models.generate_content( model=model, contents=[types.Part.from_bytes(data=base64.standard_b64decode(image_b64), mime_type="image/jpeg"), prompt], config=types.GenerateContentConfig(max_output_tokens=MAX_OUTPUT), ) usage = response.usage_metadata finish = response.candidates[0].finish_reason.name if response.candidates and response.candidates[0].finish_reason else "NONE" # Thinking is billed as output on this tier but counted separately. output = (usage.candidates_token_count or 0) + (usage.thoughts_token_count or 0) return {"text": response.text or "", "stop": finish, "refused": finish in ("SAFETY", "PROHIBITED_CONTENT", "RECITATION", "OTHER", "NONE"), "input_tokens": usage.prompt_token_count or 0, "output_tokens": output} CALLERS = {"anthropic": call_anthropic, "openai": call_openai, "google": call_google} KEYS = {"anthropic": "ANTHROPIC_API_KEY", "openai": "OPENAI_API_KEY", "google": "GEMINI_API_KEY"} def price_of(model, input_tokens, output_tokens, on=None) -> float: if model not in PRICES: sys.exit(f"No price on file for {model}. Add it to PRICES from the vendor's page first.") rates = PRICES[model] later = LATER_PRICES.get(model) if later and (on or datetime.now(timezone.utc).date().isoformat()) >= later[0]: rates = later[1] return (input_tokens * rates[0] + output_tokens * rates[1]) / 1_000_000 def extract_json(text: str): """The object in a reply, tolerating the code fence some models add. None if there isn't one.""" m = re.search(r"\{.*\}", text or "", flags=re.DOTALL) if not m: return None try: parsed = json.loads(m.group(0)) except json.JSONDecodeError: return None return parsed if isinstance(parsed, dict) else None def read_answer(text: str) -> dict | None: """best/low/high from a reply, or None if it cannot be scored. Malformed ranges are not repaired.""" parsed = extract_json(text) if not parsed: return None try: best, low, high = int(parsed["best_year"]), int(parsed["low_year"]), int(parsed["high_year"]) except (KeyError, TypeError, ValueError): return None if not low <= best <= high: return None return {"best": best, "low": low, "high": high, "evidence": str(parsed.get("evidence") or "")} def read_lines(path): if not path.exists(): return [] return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()] def spent_so_far() -> float: total = sum(r.get("cost_usd") or 0 for r in read_lines(SCREEN)) for folder in (RAW, PILOT): for path in folder.glob("*.jsonl") if folder.exists() else []: total += sum(r.get("cost_usd") or 0 for r in read_lines(path)) return total def raw_path(model: str) -> pathlib.Path: return RAW / f"{model}.jsonl" def require_keys(models): load_env_files() missing = sorted({KEYS[vendor_of(m)] for m in models if not os.environ.get(KEYS[vendor_of(m)])}) if missing: sys.exit("Missing from .env.local: " + ", ".join(missing)) def call_with_patience(model, image_b64, prompt, attempts=3): """A failed request is not an answer, so it writes nothing and is retried on the next run.""" for attempt in range(attempts): try: return CALLERS[vendor_of(model)](model, image_b64, prompt) except Exception as e: print(f" {model}: {type(e).__name__}, attempt {attempt + 1} of {attempts}") time.sleep(10 * (attempt + 1)) return None def append(path, row): path.parent.mkdir(parents=True, exist_ok=True) with path.open("a", encoding="utf-8") as f: f.write(json.dumps(row, ensure_ascii=True) + "\n") def estimate(n_calls, model) -> float: return n_calls * price_of(model, WORST_CASE_INPUT, WORST_CASE_OUTPUT) def cmd_run(args): photos = load_json(PHOTOS)["photos"][: args.limit or None] models = [m.strip() for m in args.models.split(",") if m.strip()] plan = [] for model in models: done = {(r["id"], r["repeat"]) for r in read_lines(raw_path(model))} todo = [(p, n) for p in photos for n in range(1, REPEATS + 1) if (p["id"], n) not in done] plan.append((model, todo)) print(f"{model}: {len(todo)} calls to make, at most ${estimate(len(todo), model):.2f}") print(f"Already spent: ${spent_so_far():.2f}") if not args.spend: print("Dry run. Nothing was sent. Add --spend and --cap to run.") return if args.cap is None: sys.exit("--spend needs --cap.") require_keys(models) for model, todo in plan: for photo, repeat in todo: # Leaves room for the longest reply a call is allowed, so the cap cannot be overrun. if args.cap - spent_so_far() < price_of(model, WORST_CASE_INPUT, MAX_OUTPUT): sys.exit(f"Stopping at the ${args.cap:.2f} cap. Rerun with a higher cap to carry on.") result = call_with_patience(model, load_image(photo), PROMPT) if result is None: sys.exit("Three failures in a row. Stopping so a broken run costs nothing more. Rerun to resume.") answer = None if result["refused"] else read_answer(result["text"]) append(raw_path(model), { "id": photo["id"], "model": model, "repeat": repeat, "at": datetime.now(timezone.utc).isoformat(timespec="seconds"), "status": "refused" if result["refused"] else "answered" if answer else "unusable", "answer": answer, "reply": result["text"], "stop": result["stop"], "input_tokens": result["input_tokens"], "output_tokens": result["output_tokens"], "cost_usd": price_of(model, result["input_tokens"], result["output_tokens"]), }) print(f" {model} {photo['id']} #{repeat}: {answer['best'] if answer else 'no answer'} total ${spent_so_far():.2f}") def cmd_screen(args): """A second look for dates the by-eye review missed. It flags; a person decides.""" photos = load_json(PHOTOS)["photos"] done = {r["id"] for r in read_lines(SCREEN)} todo = [p for p in photos if p["id"] not in done] print(f"{SCREEN_MODEL}: {len(todo)} calls to make, at most ${estimate(len(todo), SCREEN_MODEL):.2f}") if not args.spend: print("Dry run. Nothing was sent. Add --spend and --cap to run.") return if args.cap is None: sys.exit("--spend needs --cap.") require_keys([SCREEN_MODEL]) for photo in todo: if args.cap - spent_so_far() < price_of(SCREEN_MODEL, WORST_CASE_INPUT, MAX_OUTPUT): sys.exit(f"Stopping at the ${args.cap:.2f} cap.") result = call_with_patience(SCREEN_MODEL, load_image(photo), SCREEN_PROMPT) if result is None: sys.exit("Three failures in a row. Rerun to resume.") parsed = extract_json(result["text"]) or {} append(SCREEN, {"id": photo["id"], "found": parsed.get("found"), "text": parsed.get("text"), "reply": result["text"], "cost_usd": price_of(SCREEN_MODEL, result["input_tokens"], result["output_tokens"])}) if parsed.get("found") is not False: print(f" check by eye: {photo['id']} {parsed.get('text')!r}") # -------------------------------------------------------------------------- # Scoring # -------------------------------------------------------------------------- def mean(xs): return sum(xs) / len(xs) def score_answers(photo, answers) -> dict | None: """One row per photograph, so a photo counts once however many answers it got.""" good = [a for a in answers if a] if not good: return None errors = [distance(a["best"], photo["low"], photo["high"]) for a in good] return { "id": photo["id"], "error": mean(errors), "within5": mean([e <= 5 for e in errors]), "within10": mean([e <= 10 for e in errors]), "range_hit": mean([a["low"] <= photo["high"] and a["high"] >= photo["low"] for a in good]), "range_width": mean([a["high"] - a["low"] for a in good]), "spread": max(a["best"] for a in good) - min(a["best"] for a in good), } def bootstrap_median(values, rounds=BOOTSTRAP_ROUNDS, seed=BOOTSTRAP_SEED) -> list: rng = random.Random(seed) meds = sorted(statistics.median(rng.choices(values, k=len(values))) for _ in range(rounds)) return [meds[int(rounds * 0.025)], meds[int(rounds * 0.975) - 1]] def bootstrap_difference(pairs, rounds=BOOTSTRAP_ROUNDS, seed=BOOTSTRAP_SEED) -> list: """Interval on (median error A - median error B), resampling photographs so A and B stay paired.""" rng = random.Random(seed) diffs = [] for _ in range(rounds): sample = rng.choices(pairs, k=len(pairs)) diffs.append(statistics.median(a for a, _ in sample) - statistics.median(b for _, b in sample)) diffs.sort() return [diffs[int(rounds * 0.025)], diffs[int(rounds * 0.975) - 1]] def fixed_guess_rows(photos) -> list: """ The score of ignoring the image. Each photo is guessed as the median year of all the others, so it never sees its own answer. This still knows the date range of the test set, which a real guesser would not, so it is a strong baseline. """ rows = [] for i, p in enumerate(photos): others = [(q["low"] + q["high"]) / 2 for j, q in enumerate(photos) if j != i] guess = statistics.median(others) rows.append(score_answers(p, [{"best": guess, "low": guess, "high": guess}])) return rows def describe(rows, photo_ids) -> dict: subset = [r for r in rows if r["id"] in photo_ids] if not subset: return {"photos_scored": 0} errors = [r["error"] for r in subset] return { "photos_scored": len(subset), "median_error": statistics.median(errors), "median_error_ci95": bootstrap_median(errors), "mean_error": round(mean(errors), 2), "within_5_years": round(mean([r["within5"] for r in subset]), 3), "within_10_years": round(mean([r["within10"] for r in subset]), 3), } def subsets(photos) -> dict: return { "all": {p["id"] for p in photos}, "exact_dates_only": {p["id"] for p in photos if p["exact"]}, "no_famous_or_named": {p["id"] for p in photos if not p["tags"]}, } def summarise(photos, raw_by_model, review, eligible) -> dict: groups = subsets(photos) baseline = fixed_guess_rows(photos) base_by_id = {r["id"]: r["error"] for r in baseline} models = [] for model, rows in sorted(raw_by_model.items()): by_photo = {} for r in rows: by_photo.setdefault(r["id"], []).append(r) scored = [] for p in photos: row = score_answers(p, [r["answer"] for r in by_photo.get(p["id"], [])]) if row: scored.append(row) pairs = [(r["error"], base_by_id[r["id"]]) for r in scored] statuses = [r["status"] for r in rows] entry = { "model": model, "calls": len(rows), "answered": statuses.count("answered"), "refused": statuses.count("refused"), "unusable": statuses.count("unusable"), "cost_usd": round(sum(r.get("cost_usd") or 0 for r in rows), 2), "first_call": min((r["at"] for r in rows), default=None), "last_call": max((r["at"] for r in rows), default=None), "groups": {name: describe(scored, ids) for name, ids in groups.items()}, } if scored: entry["range_contains_truth"] = round(mean([r["range_hit"] for r in scored]), 3) entry["median_range_width"] = statistics.median(r["range_width"] for r in scored) entry["median_spread_across_repeats"] = statistics.median(r["spread"] for r in scored) entry["difference_from_fixed_guess_ci95"] = bootstrap_difference(pairs) decades = {} for r, p in ((r, next(p for p in photos if p["id"] == r["id"])) for r in scored): decades.setdefault((p["low"] + p["high"]) // 2 // 10 * 10, []).append(r["error"]) entry["by_decade"] = [{"decade": d, "photos": len(v), "median_error": statistics.median(v)} for d, v in sorted(decades.items())] models.append(entry) reasons = {} for e in review["exclusions"]: reasons[e["reason"]] = reasons.get(e["reason"], 0) + 1 years = [p["low"] for p in photos] + [p["high"] for p in photos] return { "generated_by": "scripts/photo_dating_benchmark.py", "prompt": PROMPT, "repeats": REPEATS, "circa_years": CIRCA_YEARS, "pool": { "eligible": eligible, "excluded": len(review["exclusions"]), "excluded_by_reason": reasons, "tested": len(photos), "exact_dates": sum(p["exact"] for p in photos), "famous_or_named": sum(bool(p["tags"]) for p in photos), "earliest_year": min(years), "latest_year": max(years), }, "fixed_guess": { "guess_year_all_photos": statistics.median((p["low"] + p["high"]) / 2 for p in photos), "groups": {name: describe(baseline, ids) for name, ids in groups.items()}, }, "models": models, } def cmd_score(args): data = load_json(PHOTOS) raw = {} if RAW.exists(): for path in sorted(RAW.glob("*.jsonl")): raw[path.stem] = read_lines(path) write_json(SUMMARY, summarise(data["photos"], raw, load_json(REVIEW), data["eligible"])) print(f"Wrote {SUMMARY.relative_to(HERE.parent)} for {len(raw)} model(s)") def cmd_selftest(args): """Made-up answers with results known in advance. No network, no cost, and nothing is written.""" assert parse_truth("1901") == (1901, 1901, True) assert parse_truth("1910-07-10") == (1910, 1910, True) assert parse_truth("1918-04") == (1918, 1918, True) assert parse_truth("1895~") == (1890, 1900, False) assert parse_truth("1899-07-04?") == (1894, 1904, False) assert parse_truth("1887/1896~") == (1887, 1896, False) assert parse_truth("c. 1887") == (1882, 1892, False) assert parse_truth("c. 1893–96") == (1893, 1896, False) assert parse_truth("c. 1920–55") == (1920, 1955, False) assert parse_truth("early 1890s") == (1890, 1894, False) for bad in ("", "None", "1890s", "about 1900"): try: parse_truth(bad) except ValueError: continue raise AssertionError(f"accepted {bad!r}") assert distance(1900, 1890, 1910) == 0 assert distance(1880, 1890, 1910) == 10 assert distance(1915, 1890, 1910) == 5 from PIL import Image source = Image.new("RGB", (3000, 2000), "gray") exif = Image.Exif() exif[0x9003] = "1901:01:01 00:00:00" buf = io.BytesIO() source.save(buf, "JPEG", comment=b"taken in 1901", exif=exif) cleaned = Image.open(io.BytesIO(clean_image(buf.getvalue()))) assert not cleaned.info.get("comment") and not cleaned.info.get("exif") and not len(cleaned.getexif()) assert b"1901" not in clean_image(buf.getvalue()) assert max(cleaned.size) == LONG_EDGE good = '{"best_year": 1900, "low_year": 1895, "high_year": 1905, "evidence": "collars"}' assert read_answer(good)["best"] == 1900 assert read_answer("```json\n" + good + "\n```")["high"] == 1905 assert read_answer("Probably about 1900.") is None assert read_answer('{"best_year": "around 1900", "low_year": 1, "high_year": 2}') is None assert read_answer('{"best_year": 1950, "low_year": 1890, "high_year": 1900}') is None # Twenty photos, two years apart: a perfect model, one always 10 years late, one that always refuses. photos = [{"id": f"p{i}", "low": 1880 + i * 2, "high": 1880 + i * 2, "exact": True, "tags": ["famous_subject"] if i == 0 else []} for i in range(20)] def rows_for(model, offset): return [{"id": p["id"], "model": model, "repeat": n, "status": "answered", "at": "2026-11-04T00:00:00+00:00", "cost_usd": 0.01, "answer": {"best": p["low"] + offset, "low": p["low"] + offset - 2, "high": p["low"] + offset + 2}} for p in photos for n in (1, 2, 3)] refuser = [{"id": p["id"], "model": "refuser", "repeat": 1, "status": "refused", "answer": None, "at": "2026-11-04T00:00:00+00:00", "cost_usd": 0} for p in photos] review = {"exclusions": [{"reason": "visible_date"}, {"reason": "visible_date"}, {"reason": "near_duplicate"}]} out = summarise(photos, {"perfect": rows_for("perfect", 0), "late": rows_for("late", 10), "refuser": refuser}, review, 23) by = {m["model"]: m for m in out["models"]} assert by["perfect"]["groups"]["all"]["median_error"] == 0 assert by["perfect"]["groups"]["all"]["within_5_years"] == 1 assert by["perfect"]["range_contains_truth"] == 1 assert by["perfect"]["median_spread_across_repeats"] == 0 assert by["late"]["groups"]["all"]["median_error"] == 10 assert by["late"]["groups"]["all"]["within_5_years"] == 0 assert by["late"]["groups"]["all"]["within_10_years"] == 1 assert by["late"]["range_contains_truth"] == 0 assert by["refuser"]["refused"] == 20 and by["refuser"]["groups"]["all"]["photos_scored"] == 0 assert by["perfect"]["groups"]["no_famous_or_named"]["photos_scored"] == 19 # Years 1880 to 1918 in steps of 2: the median guess sits near 1899, so the typical miss is about 10. fixed = out["fixed_guess"]["groups"]["all"]["median_error"] assert 9 <= fixed <= 11, fixed # The perfect model must clearly beat the fixed guess, and the interval must say so. assert by["perfect"]["difference_from_fixed_guess_ci95"][1] < 0 assert out["pool"]["excluded_by_reason"] == {"visible_date": 2, "near_duplicate": 1} assert price_of("claude-opus-5-5", 1_000_000, 1_000_000) == 24 assert price_of("gemini-4-argon", 1_000_000, 0, on="2026-12-01") == 4 assert price_of("gemini-4-argon", 1_000_000, 0, on="2026-11-30") == 2 print("selftest passed") def main(): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) sub = parser.add_subparsers(dest="command", required=True) sub.add_parser("freeze").set_defaults(fn=cmd_freeze) sub.add_parser("prepare").set_defaults(fn=cmd_prepare) sub.add_parser("score").set_defaults(fn=cmd_score) sub.add_parser("selftest").set_defaults(fn=cmd_selftest) run = sub.add_parser("run") run.add_argument("--models", required=True) run.add_argument("--limit", type=int, help="first N photos only, for the pilot") run.add_argument("--spend", action="store_true", help="actually call the models") run.add_argument("--cap", type=float, help="stop before total spend passes this many USD") run.set_defaults(fn=cmd_run) screen = sub.add_parser("screen") screen.add_argument("--spend", action="store_true") screen.add_argument("--cap", type=float) screen.set_defaults(fn=cmd_screen) args = parser.parse_args() args.fn(args) if __name__ == "__main__": main()