| 1 | #!/usr/bin/env python3 |
| 2 | """Compare the X results of two saved last30days report JSON files. |
| 3 | |
| 4 | Dev tool for checking one X lane against another on the same topic and |
| 5 | window. Each input is the output of ``last30days.py <topic> --emit=json |
| 6 | --json-profile=raw``; the optional envelope is the candidate's ``--x-posts`` |
| 7 | file, so a baseline post the candidate fetched but did not keep still counts |
| 8 | toward recall. |
| 9 | |
| 10 | python3 scripts/x_lane_parity.py baseline.json candidate.json [--envelope x-posts.json] |
| 11 | """ |
| 12 | |
| 13 | from __future__ import annotations |
| 14 | |
| 15 | import argparse |
| 16 | import json |
| 17 | import re |
| 18 | import sys |
| 19 | from pathlib import Path |
| 20 | |
| 21 | _STATUS_RE = re.compile(r"/status/(\d+)") |
| 22 | _METRICS = ("likes", "reposts", "replies", "quotes") |
| 23 | TOP_N = 10 |
| 24 | |
| 25 | |
| 26 | def _load(path: str) -> dict: |
| 27 | return json.loads(Path(path).read_text(encoding="utf-8")) |
| 28 | |
| 29 | |
| 30 | def _x_items(report: dict) -> list[dict]: |
| 31 | return list((report.get("items_by_source") or {}).get("x") or []) |
| 32 | |
| 33 | |
| 34 | def _require_same_run_shape(base: dict, cand: dict, envelope: dict | None) -> None: |
| 35 | """Refuse to compare reports that cover different topics or windows.""" |
| 36 | for key in ("topic", "range_from", "range_to"): |
| 37 | if base.get(key) != cand.get(key): |
| 38 | raise ValueError(f"reports differ on {key}: {base.get(key)!r} vs {cand.get(key)!r}") |
| 39 | if envelope is not None and envelope.get("topic") != cand.get("topic"): |
| 40 | raise ValueError( |
| 41 | f"envelope topic {envelope.get('topic')!r} does not match the candidate report {cand.get('topic')!r}" |
| 42 | ) |
| 43 | |
| 44 | |
| 45 | def _post_id(item: dict) -> str | None: |
| 46 | match = _STATUS_RE.search(str(item.get("url") or "")) |
| 47 | return match.group(1) if match else None |
| 48 | |
| 49 | |
| 50 | def _likes(item: dict) -> int: |
| 51 | value = (item.get("engagement") or {}).get("likes") |
| 52 | return int(value) if isinstance(value, (int, float)) else 0 |
| 53 | |
| 54 | |
| 55 | def _envelope_ids(payload: dict | None) -> set[str]: |
| 56 | if not payload: |
| 57 | return set() |
| 58 | return { |
| 59 | str(post.get("id")) |
| 60 | for call in payload.get("calls") or [] |
| 61 | for post in call.get("posts") or [] |
| 62 | if post.get("id") |
| 63 | } |
| 64 | |
| 65 | |
| 66 | def _ratio(numerator: float, denominator: float) -> float: |
| 67 | return round(numerator / denominator, 3) if denominator else 0.0 |
| 68 | |
| 69 | |
| 70 | def compare(baseline: str, candidate: str, *, envelope: str | None = None) -> dict: |
| 71 | """Counts, top-liked recall, field completeness, and author spread.""" |
| 72 | base, cand = _load(baseline), _load(candidate) |
| 73 | env = _load(envelope) if envelope else None |
| 74 | _require_same_run_shape(base, cand, env) |
| 75 | base_items = _x_items(base) |
| 76 | cand_items = _x_items(cand) |
| 77 | cand_ids = {pid for pid in map(_post_id, cand_items) if pid} | _envelope_ids(env) |
| 78 | top = sorted(base_items, key=_likes, reverse=True)[:TOP_N] |
| 79 | top_ids = [pid for pid in map(_post_id, top) if pid] |
| 80 | complete = sum( |
| 81 | 1 for item in cand_items |
| 82 | if all(isinstance((item.get("engagement") or {}).get(m), (int, float)) for m in _METRICS) |
| 83 | ) |
| 84 | return { |
| 85 | "baseline_count": len(base_items), |
| 86 | "candidate_count": len(cand_items), |
| 87 | "count_ratio": _ratio(len(cand_items), len(base_items)), |
| 88 | "top_liked_recall": _ratio(sum(1 for pid in top_ids if pid in cand_ids), len(top_ids)), |
| 89 | "candidate_field_completeness": _ratio(complete, len(cand_items)), |
| 90 | "baseline_authors": len({item.get("author") for item in base_items}), |
| 91 | "candidate_authors": len({item.get("author") for item in cand_items}), |
| 92 | } |
| 93 | |
| 94 | |
| 95 | def main(argv: list[str] | None = None) -> int: |
| 96 | parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) |
| 97 | parser.add_argument("baseline") |
| 98 | parser.add_argument("candidate") |
| 99 | parser.add_argument("--envelope") |
| 100 | args = parser.parse_args(argv) |
| 101 | json.dump(compare(args.baseline, args.candidate, envelope=args.envelope), sys.stdout, indent=2) |
| 102 | sys.stdout.write("\n") |
| 103 | return 0 |
| 104 | |
| 105 | |
| 106 | if __name__ == "__main__": |
| 107 | raise SystemExit(main()) |
| 108 |