返回 last30days-skill
shortform_ab.py
根目录 / scripts / shortform_ab.py
1 #!/usr/bin/env python3
2 """A/B parity harness: ScrapeCreators vs keyless TikTok and Instagram.
3
4 Runs the research engine once per topic per arm and compares what each arm
5 returns for TikTok and Instagram. Arms of the same topic run concurrently so
6 they hit the same moment on the platforms.
7
8 Arms:
9 A ScrapeCreators (the user's normal config).
10 B Keyless, engine discovery only, creator expansion off, freshness on.
11 B-nofresh B with the web-backend freshness parameters off.
12 C Keyless, creator expansion on.
13 D C plus a host-discovered URL envelope (--shortform-urls). Runs only
14 when <fixtures-dir>/<topic-slug>.json exists; skipped otherwise.
15
16 A host run also passes the TikTok hashtags and creators it infers (runbook
17 step 3). When <fixtures-dir>/<topic-slug>.host.json exists ({"tiktok_creators":
18 [...], "tiktok_hashtags": [...]}), arms A, C and D get those flags, so the paid
19 and keyless lanes start from the same host input.
20
21 Keyless arms read a private copy of the user's .env with the ScrapeCreators
22 key lines removed (LAST30DAYS_CONFIG_DIR points at it). The copy is deleted
23 on exit. Config values are never printed.
24
25 Dev tool, run from the repo root with Python 3.12+:
26 uv run python scripts/shortform_ab.py --topics "Labubu,Claude Code" --arms A,B
27 """
28
29 from __future__ import annotations
30
31 import argparse
32 import atexit
33 import concurrent.futures
34 import json
35 import math
36 import os
37 import re
38 import shutil
39 import signal
40 import statistics
41 import subprocess
42 import sys
43 import tempfile
44 import time
45 from datetime import date, datetime
46 from pathlib import Path
47 from typing import Any
48
49 REPO_ROOT = Path(__file__).resolve().parent.parent
50 ENGINE = REPO_ROOT / "skills" / "last30days" / "scripts" / "last30days.py"
51
52 PLATFORMS = ("tiktok", "instagram")
53 ALL_ARMS = ("A", "B", "B-nofresh", "C", "D")
54 RUN_TIMEOUT_SECONDS = 180
55 HEAD_SIZE = 10
56 SC_KEY_NAMES = ("SCRAPECREATORS_API_KEY", "SCRAPE_CREATORS_API_KEY")
57
58 # Parity bar.
59 MIN_IN_WINDOW_RATIO = 0.5
60 MIN_HEAD_RECALL = 0.4
61 WALL_SLACK_SECONDS = 30.0
62 WALL_CEILING_SECONDS = 180.0
63
64 # 24 fixed topics, 4 per category, chosen to stay busy on TikTok year-round.
65 TOPICS: dict[str, list[str]] = {
66 "product/tech": ["Claude Code", "iPhone 17", "Nintendo Switch 2", "Meta Ray-Ban glasses"],
67 "celebrity/music": ["Sabrina Carpenter", "Taylor Swift", "Bad Bunny", "Charli XCX"],
68 "consumer trend": ["Labubu", "Stanley cup", "matcha", "Dubai chocolate"],
69 "food/how-to": ["air fryer recipes", "sourdough", "cottage cheese recipes", "meal prep"],
70 "news event": ["NFL", "Formula 1", "stock market", "Premier League"],
71 "niche hobby": ["crochet", "mechanical keyboards", "pickleball", "aquascaping"],
72 }
73
74 FIELDS = ("date", "creator", "views", "likes", "comments", "caption")
75
76 _TIKTOK_ID = re.compile(r"/(?:video|photo)/(\d+)")
77 _IG_CODE = re.compile(r"/(?:reels?|p|tv)/([A-Za-z0-9_-]+)")
78 _PLATFORM_ERROR = {
79 p: re.compile(rf"(?i)\b{p}\b[^\n]*\b(error|failed|exception|429|timed out)\b") for p in PLATFORMS
80 }
81
82
83 # ---------------------------------------------------------------------------
84 # Pure metric functions (unit-tested in tests/test_shortform_ab.py)
85 # ---------------------------------------------------------------------------
86
87
88 def video_id(platform: str, url: str) -> str | None:
89 """Return the TikTok numeric video id or the Instagram shortcode in ``url``."""
90 if not url:
91 return None
92 pattern = _TIKTOK_ID if platform == "tiktok" else _IG_CODE
93 match = pattern.search(url)
94 return match.group(1) if match else None
95
96
97 def item_ids(platform: str, items: list[dict[str, Any]]) -> set[str]:
98 return {vid for vid in (video_id(platform, str(i.get("url") or "")) for i in items) if vid}
99
100
101 def parse_day(value: Any) -> date | None:
102 if not value:
103 return None
104 try:
105 return date.fromisoformat(str(value)[:10])
106 except ValueError:
107 return None
108
109
110 def window_counts(items: list[dict[str, Any]], range_from: str, range_to: str) -> dict[str, int]:
111 """Count items inside the window, outside it (stale leaks), and undated."""
112 start, end = parse_day(range_from), parse_day(range_to)
113 counts = {"in_window": 0, "stale": 0, "undated": 0}
114 for item in items:
115 day = parse_day(item.get("published_at"))
116 if day is None or start is None or end is None:
117 counts["undated"] += 1
118 elif start <= day <= end:
119 counts["in_window"] += 1
120 else:
121 counts["stale"] += 1
122 return counts
123
124
125 def recall(baseline_ids: set[str], arm_ids: set[str]) -> float | None:
126 """Share of the baseline's ids the arm also returned; None when the baseline is empty."""
127 if not baseline_ids:
128 return None
129 return len(baseline_ids & arm_ids) / len(baseline_ids)
130
131
132 def _metric(item: dict[str, Any], key: str) -> float:
133 value = (item.get("engagement") or {}).get(key)
134 try:
135 return float(value) if value is not None else -1.0
136 except (TypeError, ValueError):
137 return -1.0
138
139
140 def head_ids(platform: str, items: list[dict[str, Any]], size: int = HEAD_SIZE) -> list[str]:
141 """Ids of the top ``size`` items by views (TikTok) or likes (Instagram)."""
142 key = "views" if platform == "tiktok" else "likes"
143 ranked = sorted(items, key=lambda i: _metric(i, key), reverse=True)
144 out: list[str] = []
145 for item in ranked:
146 vid = video_id(platform, str(item.get("url") or ""))
147 if vid and vid not in out:
148 out.append(vid)
149 if len(out) == size:
150 break
151 return out
152
153
154 def head_recall(platform: str, baseline_items: list[dict[str, Any]], arm_ids: set[str]) -> float | None:
155 head = head_ids(platform, baseline_items)
156 if not head:
157 return None
158 return sum(1 for vid in head if vid in arm_ids) / len(head)
159
160
161 def completeness(items: list[dict[str, Any]]) -> dict[str, float | None]:
162 """Per-field share of items carrying date, creator, views, likes, comments, caption."""
163 if not items:
164 return {field: None for field in FIELDS}
165 present = {field: 0 for field in FIELDS}
166 for item in items:
167 eng = item.get("engagement") or {}
168 present["date"] += bool(item.get("published_at"))
169 present["creator"] += bool(item.get("author"))
170 for key in ("views", "likes", "comments"):
171 present[key] += eng.get(key) is not None
172 present["caption"] += bool(str(item.get("body") or item.get("snippet") or "").strip())
173 return {field: present[field] / len(items) for field in FIELDS}
174
175
176 QUOTABLE_LIKES = 5 # Top Community Comments floor for a platform that counts likes
177
178
179 def _comment_likes(comment: dict[str, Any]) -> int:
180 for key in ("digg_count", "likes", "like_count", "comment_like_count", "score"):
181 value = comment.get(key)
182 if isinstance(value, (int, float)):
183 return int(value)
184 return 0
185
186
187 def quotable(items: list[dict[str, Any]]) -> int:
188 """Items whose best community comment clears the report's like floor."""
189 count = 0
190 for item in items:
191 comments = item.get("top_comments") or (item.get("metadata") or {}).get("top_comments") or []
192 likes = [_comment_likes(c) for c in comments if isinstance(c, dict) and not c.get("is_uploader")]
193 count += bool(likes) and max(likes) >= QUOTABLE_LIKES
194 return count
195
196
197 def median_views(items: list[dict[str, Any]]) -> float | None:
198 return median([(i.get("engagement") or {}).get("views") for i in items])
199
200
201 def median(values: list[float | None]) -> float | None:
202 clean = [v for v in values if v is not None]
203 return statistics.median(clean) if clean else None
204
205
206 def p90(values: list[float | None]) -> float | None:
207 """Nearest-rank 90th percentile."""
208 clean = sorted(v for v in values if v is not None)
209 if not clean:
210 return None
211 rank = max(1, math.ceil(0.9 * len(clean)))
212 return clean[rank - 1]
213
214
215 def parity_verdict(
216 *,
217 arm_in_window: list[float],
218 a_in_window: list[float],
219 arm_head_recall: list[float | None],
220 arm_stale: list[int],
221 arm_wall: list[float],
222 a_wall: list[float],
223 ) -> dict[str, Any]:
224 """Check one keyless arm on one platform against the parity bar."""
225 checks: dict[str, bool] = {}
226 a_med = median(a_in_window)
227 arm_med = median(arm_in_window)
228 checks["in_window"] = (
229 arm_med is not None and a_med is not None and arm_med >= MIN_IN_WINDOW_RATIO * a_med
230 )
231 hr = median(arm_head_recall)
232 checks["head_recall"] = hr is not None and hr >= MIN_HEAD_RECALL
233 checks["stale"] = sum(arm_stale) == 0
234 arm_p90, a_p90 = p90(arm_wall), p90(a_wall)
235 checks["wall"] = (
236 arm_p90 is not None
237 and a_p90 is not None
238 and arm_p90 <= a_p90 + WALL_SLACK_SECONDS
239 and arm_p90 < WALL_CEILING_SECONDS
240 )
241 return {"pass": all(checks.values()), "checks": checks}
242
243
244 def slugify(topic: str) -> str:
245 return re.sub(r"[^a-z0-9]+", "-", topic.lower()).strip("-")
246
247
248 def strip_sc_keys(env_text: str) -> str:
249 """Drop ScrapeCreators key lines (plain or ``export``-prefixed) from .env text."""
250 kept = []
251 for line in env_text.splitlines():
252 key = line.strip()
253 if key.startswith("export "):
254 key = key[len("export "):].lstrip()
255 key = key.split("=", 1)[0].strip()
256 if key in SC_KEY_NAMES:
257 continue
258 kept.append(line)
259 return "\n".join(kept) + ("\n" if kept else "")
260
261
262 # ---------------------------------------------------------------------------
263 # Running arms
264 # ---------------------------------------------------------------------------
265
266 _PRIVATE_DIRS: list[str] = []
267
268
269 def _cleanup_private_dirs() -> None:
270 while _PRIVATE_DIRS:
271 shutil.rmtree(_PRIVATE_DIRS.pop(), ignore_errors=True)
272
273
274 def _source_config_file() -> Path:
275 override = os.environ.get("LAST30DAYS_CONFIG_DIR")
276 if override:
277 return Path(override) / ".env"
278 return Path.home() / ".config" / "last30days" / ".env"
279
280
281 def make_keyless_config_dir() -> str:
282 """Private temp config dir holding the user's .env minus ScrapeCreators keys."""
283 path = tempfile.mkdtemp(prefix="l30d-ab-")
284 _PRIVATE_DIRS.append(path)
285 os.chmod(path, 0o700)
286 source = _source_config_file()
287 text = source.read_text(encoding="utf-8-sig") if source.exists() else ""
288 target = Path(path) / ".env"
289 fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
290 with os.fdopen(fd, "w", encoding="utf-8") as handle:
291 handle.write(strip_sc_keys(text))
292 return path
293
294
295 def keychain_has_sc_key() -> bool:
296 """True when the macOS Keychain holds the ScrapeCreators key (value never read)."""
297 if sys.platform != "darwin" or not shutil.which("security"):
298 return False
299 result = subprocess.run(
300 ["security", "find-generic-password", "-s", "last30days-SCRAPECREATORS_API_KEY"],
301 capture_output=True,
302 check=False,
303 )
304 return result.returncode == 0
305
306
307 def arm_env(arm: str, keyless_dir: str | None, skip_keychain: bool) -> dict[str, str]:
308 env = dict(os.environ)
309 if arm == "A":
310 return env
311 for key in SC_KEY_NAMES:
312 env.pop(key, None)
313 env["LAST30DAYS_CONFIG_DIR"] = keyless_dir or ""
314 # Keyless arms read no secret store at all: the Keychain (and any
315 # LAST30DAYS_KEYCHAIN_ALIASES entry) is skipped, and pass(1) points at an
316 # empty store, so no ScrapeCreators key can reload behind the arm.
317 env["LAST30DAYS_SKIP_KEYCHAIN"] = "1"
318 env.pop("LAST30DAYS_KEYCHAIN_ALIASES", None)
319 env["PASSWORD_STORE_DIR"] = os.path.join(keyless_dir or tempfile.gettempdir(), "no-pass-store")
320 env["LAST30DAYS_SHORTFORM_FRESHNESS"] = "off" if arm == "B-nofresh" else "on"
321 env["LAST30DAYS_SHORTFORM_CREATOR_EXPANSION"] = "off" if arm in ("B", "B-nofresh") else "on"
322 if arm == "D":
323 # A host run: SKILL.md marks the host's own web search as native.
324 env["LAST30DAYS_NATIVE_SEARCH"] = "1"
325 return env
326
327
328 def host_flags(fixtures_dir: Path | None, topic: str) -> list[str]:
329 """--tiktok-creators/--tiktok-hashtags from the topic's .host.json sidecar."""
330 if fixtures_dir is None:
331 return []
332 path = fixtures_dir / f"{slugify(topic)}.host.json"
333 if not path.exists():
334 return []
335 data = json.loads(path.read_text())
336 flags: list[str] = []
337 for key, flag in (("tiktok_creators", "--tiktok-creators"), ("tiktok_hashtags", "--tiktok-hashtags")):
338 values = [str(v).strip().lstrip("@#") for v in data.get(key) or [] if str(v).strip()]
339 if values:
340 flags.append(f"{flag}={','.join(values)}")
341 return flags
342
343
344 def arm_command(topic: str, arm: str, fixture: Path | None,
345 extra: list[str] | None = None) -> list[str]:
346 cmd = [
347 sys.executable,
348 str(ENGINE),
349 topic,
350 "--emit=json",
351 "--json-profile=raw",
352 "--auto-resolve",
353 "--save-dir=",
354 "--search=tiktok,instagram",
355 ]
356 if arm == "D" and fixture is not None:
357 cmd += ["--shortform-urls", str(fixture)]
358 if arm in ("A", "C", "D"):
359 cmd += list(extra or [])
360 return cmd
361
362
363 def _platform_items(payload: dict[str, Any], platform: str) -> list[dict[str, Any]]:
364 items = (payload.get("items_by_source") or {}).get(platform) or []
365 return [i for i in items if isinstance(i, dict)]
366
367
368 def run_arm(topic: str, arm: str, *, keyless_dir: str | None, skip_keychain: bool,
369 fixtures_dir: Path | None, workdir: str) -> dict[str, Any]:
370 fixture = None
371 if arm == "D":
372 candidate = fixtures_dir / f"{slugify(topic)}.json" if fixtures_dir else None
373 if candidate is None or not candidate.exists():
374 return {"arm": arm, "skipped": "no shortform-urls fixture for this topic"}
375 fixture = candidate
376 cmd = arm_command(topic, arm, fixture, host_flags(fixtures_dir, topic))
377 started = time.monotonic()
378 result: dict[str, Any] = {"arm": arm, "skipped": None, "timed_out": False, "exit_code": None}
379 try:
380 proc = subprocess.run(
381 cmd, cwd=workdir, env=arm_env(arm, keyless_dir, skip_keychain),
382 capture_output=True, text=True, timeout=RUN_TIMEOUT_SECONDS, check=False,
383 )
384 stdout, stderr, result["exit_code"] = proc.stdout, proc.stderr, proc.returncode
385 except subprocess.TimeoutExpired as exc:
386 stdout = exc.stdout.decode() if isinstance(exc.stdout, bytes) else (exc.stdout or "")
387 stderr = exc.stderr.decode() if isinstance(exc.stderr, bytes) else (exc.stderr or "")
388 result["timed_out"] = True
389 result["wall"] = round(time.monotonic() - started, 2)
390 payload: dict[str, Any] = {}
391 try:
392 start = stdout.find("{")
393 if start >= 0:
394 payload, _ = json.JSONDecoder().raw_decode(stdout[start:])
395 except json.JSONDecodeError:
396 payload = {}
397 result["parse_ok"] = bool(payload)
398 result["range_from"] = payload.get("range_from")
399 result["range_to"] = payload.get("range_to")
400 run_failed = result["timed_out"] or result["exit_code"] != 0 or not payload
401 errors = payload.get("errors_by_source") or {}
402 result["platforms"] = {}
403 for platform in PLATFORMS:
404 items = _platform_items(payload, platform)
405 stderr_match = _PLATFORM_ERROR[platform].search(stderr or "")
406 platform_error = errors.get(platform) or (stderr_match.group(0) if stderr_match else None)
407 result["platforms"][platform] = {
408 "items": items,
409 "failed": bool(run_failed or (not items and platform_error)),
410 "error": (str(platform_error)[:200] if platform_error else None),
411 }
412 if run_failed:
413 result["stderr_tail"] = (stderr or "")[-400:]
414 return result
415
416
417 def score_topic(topic: str, runs: dict[str, dict[str, Any]]) -> dict[str, Any]:
418 """Turn raw arm runs for one topic into per-arm, per-platform metrics."""
419 baseline = runs.get("A")
420 scored: dict[str, Any] = {}
421 for arm, run in runs.items():
422 if run.get("skipped"):
423 scored[arm] = {"skipped": run["skipped"]}
424 continue
425 entry: dict[str, Any] = {"wall": run["wall"], "exit_code": run["exit_code"],
426 "timed_out": run["timed_out"], "platforms": {}}
427 if run.get("stderr_tail"):
428 entry["stderr_tail"] = run["stderr_tail"]
429 for platform in PLATFORMS:
430 pdata = run["platforms"][platform]
431 items = pdata["items"]
432 ids = item_ids(platform, items)
433 counts = window_counts(items, run.get("range_from") or "", run.get("range_to") or "")
434 metrics: dict[str, Any] = {
435 "items": len(items),
436 **counts,
437 "failed": pdata["failed"],
438 "error": pdata["error"],
439 "completeness": completeness(items),
440 "quotable": quotable(items),
441 "median_views": median_views(items),
442 "ids": sorted(ids),
443 }
444 if baseline and not baseline.get("skipped") and arm != "A":
445 base_items = baseline["platforms"][platform]["items"]
446 metrics["recall"] = recall(item_ids(platform, base_items), ids)
447 metrics["head_recall"] = head_recall(platform, base_items, ids)
448 entry["platforms"][platform] = metrics
449 scored[arm] = entry
450 return {"topic": topic, "arms": scored}
451
452
453 def summarize(results: list[dict[str, Any]], arms: list[str]) -> dict[str, Any]:
454 summary: dict[str, Any] = {}
455
456 def series(arm: str, platform: str, key: str) -> list[Any]:
457 out = []
458 for res in results:
459 entry = res["arms"].get(arm) or {}
460 if entry.get("skipped") or not entry:
461 continue
462 out.append(entry["platforms"][platform].get(key))
463 return out
464
465 def walls(arm: str) -> list[float]:
466 return [r["arms"][arm]["wall"] for r in results
467 if arm in r["arms"] and not r["arms"][arm].get("skipped")]
468
469 for arm in arms:
470 runs = walls(arm)
471 arm_sum: dict[str, Any] = {"runs": len(runs), "p90_wall": p90(runs),
472 "median_wall": median(runs), "platforms": {}}
473 for platform in PLATFORMS:
474 failed = series(arm, platform, "failed")
475 comp = [c for c in series(arm, platform, "completeness") if c]
476 comp_mean = {
477 f: median([c[f] for c in comp if c[f] is not None]) for f in FIELDS
478 } if comp else {f: None for f in FIELDS}
479 plat: dict[str, Any] = {
480 "median_in_window": median(series(arm, platform, "in_window")),
481 "stale_total": sum(series(arm, platform, "stale")),
482 "undated_total": sum(series(arm, platform, "undated")),
483 "median_recall": median(series(arm, platform, "recall")),
484 "median_head_recall": median(series(arm, platform, "head_recall")),
485 "failure_rate": (sum(bool(f) for f in failed) / len(failed)) if failed else None,
486 "median_completeness": comp_mean,
487 "median_quotable": median(series(arm, platform, "quotable")),
488 "median_views": median(series(arm, platform, "median_views")),
489 }
490 if arm != "A" and runs and "A" in arms:
491 # Compare on the topics where both arms ran.
492 paired = [r for r in results if arm in r["arms"] and not r["arms"][arm].get("skipped")
493 and "A" in r["arms"] and not r["arms"]["A"].get("skipped")]
494 plat["parity"] = parity_verdict(
495 arm_in_window=[r["arms"][arm]["platforms"][platform]["in_window"] for r in paired],
496 a_in_window=[r["arms"]["A"]["platforms"][platform]["in_window"] for r in paired],
497 arm_head_recall=[r["arms"][arm]["platforms"][platform].get("head_recall") for r in paired],
498 arm_stale=[r["arms"][arm]["platforms"][platform]["stale"] for r in paired],
499 arm_wall=[r["arms"][arm]["wall"] for r in paired],
500 a_wall=[r["arms"]["A"]["wall"] for r in paired],
501 )
502 arm_sum["platforms"][platform] = plat
503 summary[arm] = arm_sum
504 return summary
505
506
507 # ---------------------------------------------------------------------------
508 # Rendering
509 # ---------------------------------------------------------------------------
510
511
512 def _fmt(value: Any, pct: bool = False) -> str:
513 if value is None:
514 return "-"
515 if pct:
516 return f"{value * 100:.0f}%"
517 if isinstance(value, float):
518 return f"{value:.1f}"
519 return str(value)
520
521
522 def _comp_avg(comp: dict[str, float | None]) -> float | None:
523 vals = [v for v in comp.values() if v is not None]
524 return sum(vals) / len(vals) if vals else None
525
526
527 def render_markdown(meta: dict[str, Any], results: list[dict[str, Any]], summary: dict[str, Any],
528 arms: list[str]) -> str:
529 lines = [
530 "# Short-form A/B parity run",
531 "",
532 f"- Started: {meta['started']}",
533 f"- Engine commit: {meta['commit']}",
534 f"- Arms: {', '.join(arms)}",
535 f"- Topics: {len(results)}",
536 f"- Keyless config: ScrapeCreators key removed"
537 + ("; Keychain skipped for keyless arms" if meta.get("skip_keychain") else ""),
538 "",
539 "Parity bar (per keyless arm, per platform): median in-window >= 50% of A, "
540 "median head recall >= 40%, stale leaks 0, p90 wall <= A p90 + 30s and < 180s.",
541 "",
542 "## Per-arm summary",
543 "",
544 "| Arm | Platform | Median in-window | Stale | Undated | Recall | Head recall "
545 "| Completeness | Fail rate | p90 wall | Parity |",
546 "|---|---|---|---|---|---|---|---|---|---|---|",
547 ]
548 one_liners = []
549 for arm in arms:
550 s = summary[arm]
551 for platform in PLATFORMS:
552 p = s["platforms"][platform]
553 parity = p.get("parity")
554 verdict = "-"
555 if parity:
556 failed = [k for k, ok in parity["checks"].items() if not ok]
557 verdict = "PASS" if parity["pass"] else "FAIL (" + ", ".join(failed) + ")"
558 lines.append(
559 f"| {arm} | {platform} | {_fmt(p['median_in_window'])} | {p['stale_total']} "
560 f"| {p['undated_total']} | {_fmt(p['median_recall'], True)} "
561 f"| {_fmt(p['median_head_recall'], True)} | {_fmt(_comp_avg(p['median_completeness']), True)} "
562 f"| {_fmt(p['failure_rate'], True)} | {_fmt(s['p90_wall'])}s | {verdict} |"
563 )
564 tk, ig = s["platforms"]["tiktok"], s["platforms"]["instagram"]
565 one_liners.append(
566 f"- {arm}: TikTok median {_fmt(tk['median_in_window'])} in-window, head recall "
567 f"{_fmt(tk['median_head_recall'], True)}, {tk['stale_total']} stale; Instagram median "
568 f"{_fmt(ig['median_in_window'])}, {ig['stale_total']} stale; p90 wall {_fmt(s['p90_wall'])}s; "
569 f"TikTok videos with a quotable top comment {_fmt(tk.get('median_quotable'))}, median views "
570 f"{_fmt(tk.get('median_views'))}"
571 + (f"; TikTok parity {'PASS' if tk['parity']['pass'] else 'FAIL'}" if tk.get("parity") else "")
572 )
573 lines += ["", "## One line per arm", "", *one_liners, "", "## Per topic", ""]
574 lines += [
575 "| Topic | Arm | Wall | TikTok in/stale/undated | TT recall | TT head | "
576 "IG in/stale/undated | IG recall | IG head | Notes |",
577 "|---|---|---|---|---|---|---|---|---|---|",
578 ]
579 for res in results:
580 for arm in arms:
581 entry = res["arms"].get(arm)
582 if not entry:
583 continue
584 if entry.get("skipped"):
585 lines.append(f"| {res['topic']} | {arm} | - | - | - | - | - | - | - | skipped: {entry['skipped']} |")
586 continue
587 tk, ig = entry["platforms"]["tiktok"], entry["platforms"]["instagram"]
588 notes = []
589 if entry["timed_out"]:
590 notes.append("timeout")
591 elif entry["exit_code"] != 0:
592 notes.append(f"exit {entry['exit_code']}")
593 for name, p in (("TT", tk), ("IG", ig)):
594 if p["failed"]:
595 notes.append(f"{name} failed" + (f": {p['error'][:60]}" if p["error"] else ""))
596 lines.append(
597 f"| {res['topic']} | {arm} | {_fmt(entry['wall'])}s "
598 f"| {tk['in_window']}/{tk['stale']}/{tk['undated']} | {_fmt(tk.get('recall'), True)} "
599 f"| {_fmt(tk.get('head_recall'), True)} "
600 f"| {ig['in_window']}/{ig['stale']}/{ig['undated']} | {_fmt(ig.get('recall'), True)} "
601 f"| {_fmt(ig.get('head_recall'), True)} | {'; '.join(notes).replace('|', '/')} |"
602 )
603 return "\n".join(lines) + "\n"
604
605
606 # ---------------------------------------------------------------------------
607 # CLI
608 # ---------------------------------------------------------------------------
609
610
611 def _split(raw: str | None) -> list[str]:
612 return [part.strip() for part in (raw or "").split(",") if part.strip()]
613
614
615 def build_parser() -> argparse.ArgumentParser:
616 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
617 parser.add_argument("--topics", help="Comma-separated topics; replaces the fixed 24-topic set")
618 parser.add_argument("--rotating", help="Comma-separated extra topics appended to the set (e.g. this week's trends)")
619 parser.add_argument("--arms", default=",".join(ALL_ARMS), help=f"Comma-separated arms (default: {','.join(ALL_ARMS)})")
620 parser.add_argument("--fixtures-dir", type=Path, help="Directory of <topic-slug>.json shortform-urls envelopes for arm D")
621 parser.add_argument("--out", type=Path, help="Markdown report path (JSON written next to it)")
622 return parser
623
624
625 def main(argv: list[str] | None = None) -> int:
626 args = build_parser().parse_args(argv)
627 if sys.version_info < (3, 12):
628 print("shortform_ab.py needs Python 3.12+ (try: uv run python scripts/shortform_ab.py)", file=sys.stderr)
629 return 2
630 arms = _split(args.arms)
631 unknown = [a for a in arms if a not in ALL_ARMS]
632 if unknown:
633 print(f"Unknown arms: {', '.join(unknown)}", file=sys.stderr)
634 return 2
635 topics = _split(args.topics) or [t for group in TOPICS.values() for t in group]
636 topics += _split(args.rotating)
637
638 stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
639 out_md = args.out or Path(tempfile.gettempdir()) / "last30days-shortform-ab" / f"ab-{stamp}.md"
640 out_md.parent.mkdir(parents=True, exist_ok=True)
641 out_json = out_md.with_suffix(".json")
642
643 atexit.register(_cleanup_private_dirs)
644 signal.signal(signal.SIGTERM, lambda *_: sys.exit(143))
645
646 keyless = any(a != "A" for a in arms)
647 keyless_dir = make_keyless_config_dir() if keyless else None
648 skip_keychain = keyless and keychain_has_sc_key()
649 workdir = tempfile.mkdtemp(prefix="l30d-ab-cwd-")
650 _PRIVATE_DIRS.append(workdir)
651
652 commit = subprocess.run(["git", "rev-parse", "--short", "HEAD"], cwd=REPO_ROOT,
653 capture_output=True, text=True, check=False).stdout.strip() or "unknown"
654 meta = {"started": datetime.now().isoformat(timespec="seconds"), "commit": commit,
655 "skip_keychain": skip_keychain, "python": sys.version.split()[0]}
656
657 results = []
658 try:
659 for index, topic in enumerate(topics, 1):
660 print(f"[{index}/{len(topics)}] {topic}: running {', '.join(arms)}", file=sys.stderr, flush=True)
661 with concurrent.futures.ThreadPoolExecutor(max_workers=len(arms)) as pool:
662 futures = {
663 arm: pool.submit(run_arm, topic, arm, keyless_dir=keyless_dir, skip_keychain=skip_keychain,
664 fixtures_dir=args.fixtures_dir, workdir=workdir)
665 for arm in arms
666 }
667 runs = {arm: fut.result() for arm, fut in futures.items()}
668 results.append(score_topic(topic, runs))
669 finally:
670 _cleanup_private_dirs()
671
672 summary = summarize(results, arms)
673 out_md.write_text(render_markdown(meta, results, summary, arms), encoding="utf-8")
674 out_json.write_text(json.dumps({"meta": meta, "arms": arms, "summary": summary, "topics": results},
675 indent=2, sort_keys=True), encoding="utf-8")
676 print(f"Wrote {out_md}\nWrote {out_json}", file=sys.stderr)
677 return 0
678
679
680 if __name__ == "__main__":
681 raise SystemExit(main())
682
682 lines PYTHON