scripts/show_snapshot.py
scripts/show_snapshot.pyBrowse 4 files
838 tokens
3,529 bytes
Token encoding: o200k_base
Snapshot 24fd22b
← Back to SKILL.md
1"""2show_snapshot.py — Dump the population from a darwinian-evolver snapshot pickle.3 4Usage:5 python show_snapshot.py PATH/TO/iteration_N.pkl [--field prompt_template]6 7The script is intentionally Organism-agnostic: it walks `org.__dict__` and prints8all str fields. By default it shows `prompt_template` if present; pass --field to9target a different attribute (e.g. `regex_pattern`, `sql_query`, `code_block`).10"""11from __future__ import annotations12 13import argparse14import pickle15import sys16from pathlib import Path17 18 19def main() -> int:20 ap = argparse.ArgumentParser()21 ap.add_argument("snapshot", type=Path)22 ap.add_argument(23 "--field",24 default=None,25 help="Organism attribute to display. Defaults to the first str field found.",26 )27 ap.add_argument("--top", type=int, default=None, help="Show only top N by score.")28 ap.add_argument(29 "--i-trust-this-file",30 action="store_true",31 help=(32 "Required acknowledgement that the snapshot is from a trusted source. "33 "pickle.loads executes arbitrary code embedded in the file (RCE) and "34 "must NEVER be run on snapshots received from untrusted parties."35 ),36 )37 args = ap.parse_args()38 39 if not args.snapshot.exists():40 sys.exit(f"snapshot not found: {args.snapshot}")41 42 if not args.i_trust_this_file:43 sys.exit(44 "refusing to unpickle: pickle.loads is equivalent to executing arbitrary "45 "code from the snapshot file. Only proceed if you created/control this "46 "file, then re-run with --i-trust-this-file.\n"47 f" file: {args.snapshot}"48 )49 50 print(51 f"WARNING: unpickling {args.snapshot} — this executes code embedded in the "52 "file. Only safe for snapshots you produced yourself.",53 file=sys.stderr,54 )55 56 # The outer pickle wraps a dict; the inner pickle contains the actual organism57 # objects, which must be importable under their original dotted path. If you58 # ran a custom driver, make sure its module is on sys.path before calling this.59 outer = pickle.loads(args.snapshot.read_bytes()) # noqa: S301 — gated by --i-trust-this-file60 if not isinstance(outer, dict) or "population_snapshot" not in outer:61 sys.exit("not a darwinian-evolver snapshot (no population_snapshot key)")62 inner = pickle.loads(outer["population_snapshot"]) # noqa: S301 — gated by --i-trust-this-file63 pairs = inner["organisms"] # list of (Organism, EvaluationResult)64 65 print(f"# organisms: {len(pairs)}\n")66 ranked = sorted(pairs, key=lambda p: getattr(p[1], "score", 0) or 0, reverse=True)67 if args.top:68 ranked = ranked[: args.top]69 70 for i, (org, res) in enumerate(ranked):71 score = getattr(res, "score", float("nan"))72 print(f"=== rank {i} score={score:.3f} ===")73 # pick field74 field = args.field75 if field is None:76 for k, v in vars(org).items():77 if isinstance(v, str) and not k.startswith("_") and k not in {"id",}:78 field = k79 break80 val = getattr(org, field, None) if field else None81 if val is None:82 print(f" (no string field; org fields: {list(vars(org).keys())})")83 else:84 print(f" {field} ({len(val)} chars):")85 for ln in val.splitlines()[:30]:86 print(f" {ln}")87 print()88 return 089 90 91if __name__ == "__main__":92 sys.exit(main())93