Datasets:
Formats:
csv
Languages:
English
Size:
< 1K
Tags:
ai-search
large-language-models
generative-engine-optimization
local-search
chatgpt
google-ai-mode
License:
Download code/avi_score.py from sempite/ai-visibility-index: direct link, hf CLI and curl.
- Browser
- Download file 7.21 kB
-
https://huggingface.co/datasets/sempite/ai-visibility-index/resolve/main/code/avi_score.py
- Command line
-
hf download hf://datasets/sempite/ai-visibility-index/code/avi_score.py
-
curl -L -o avi_score.py https://huggingface.co/datasets/sempite/ai-visibility-index/resolve/main/code/avi_score.py
7.21 kB
| # -*- coding: utf-8 -*- | |
| """Score AI Visibility Index runs with the current matcher and roll them up. | |
| Monthly runs are collected by ai_visibility_index.py (cron, 1st of the month). | |
| Editions are published quarterly from the pooled monthly runs; this script is | |
| the one place the published numbers come from. | |
| Usage: | |
| avi_score.py RUN [RUN ...] score each run, print a summary | |
| avi_score.py --pool RUN [RUN ...] also pool the runs into one edition | |
| --json OUT write the full result (per-run + pooled) as JSON | |
| --csv OUT write one row per (run, market, business, engine) for publication | |
| RUN is a month label (2026-09) or a path to an index_*.json file. | |
| Engines with no answer for a market are excluded from that market, never | |
| counted as a miss. Rates carry 95% Wilson intervals. | |
| """ | |
| import csv, json, math, os, sys | |
| HERE = os.path.dirname(os.path.abspath(__file__)) | |
| sys.path.insert(0, HERE) | |
| from avi_matcher import mentioned, MATCHER_VERSION | |
| INDEX_DIR = os.path.join(HERE, "ai_index") | |
| ENGINES = ("chatgpt", "chatgpt_web", "google_ai", "claude") | |
| # Stored answer text shorter than the real answer can hide a mention. August 2026 | |
| # kept only the first 1,500 characters; every AI Mode answer hit that cap. | |
| TRUNC_AT = 1500 | |
| def wilson(k, n, z=1.96): | |
| if not n: | |
| return None | |
| p = k / n | |
| d = 1 + z * z / n | |
| c = (p + z * z / (2 * n)) / d | |
| h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d | |
| return [round(100 * (c - h), 1), round(100 * (c + h), 1)] | |
| def load(run): | |
| path = run if os.path.exists(run) else os.path.join(INDEX_DIR, f"index_{run}_full.json") | |
| d = json.load(open(path)) | |
| d["_path"] = path | |
| return d | |
| def records(d): | |
| """One record per (market, business, engine) with the v2 verdict.""" | |
| out = [] | |
| for r in d["rows"]: | |
| for eng, a in r["answers"].items(): | |
| text = a.get("text") or "" | |
| if not text: | |
| continue | |
| truncated = len(text) >= TRUNC_AT and d.get("methodology", {}).get("answer_text") != "stored in full" | |
| for pos, b in enumerate(r["top3"], 1): | |
| out.append({ | |
| "run": d["run"], "category": r["category"], "city": r["city"], "engine": eng, | |
| "maps_position": pos, "business": b["name"], "domain": b.get("domain") or "", | |
| "rating": b.get("rating"), "reviews": b.get("reviews"), | |
| "mentioned": bool(mentioned(b["name"], text, b.get("domain"))), | |
| "answer_truncated": truncated, | |
| }) | |
| return out | |
| def rate(recs): | |
| n = len(recs) | |
| k = sum(1 for x in recs if x["mentioned"]) | |
| if not n: | |
| return {"mentioned": 0, "of": 0, "mention_pct": None, "invisible_pct": None, "invisible_ci95": None} | |
| lo, hi = wilson(k, n) | |
| return {"mentioned": k, "of": n, | |
| "mention_pct": round(100 * k / n, 1), | |
| "invisible_pct": round(100 - 100 * k / n, 1), | |
| "invisible_ci95": [round(100 - hi, 1), round(100 - lo, 1)]} | |
| def summarise(recs): | |
| s = {} | |
| for eng in ENGINES: | |
| er = [x for x in recs if x["engine"] == eng] | |
| if not er: | |
| continue | |
| markets = {(x["run"], x["category"], x["city"]) for x in er} | |
| trunc_markets = {(x["run"], x["category"], x["city"]) for x in er if x["answer_truncated"]} | |
| # A truncated answer can only UNDERCOUNT mentions, so a rate computed | |
| # over one is an upper bound on invisibility, not a measurement. Where | |
| # every stored answer for an engine-run was truncated there is nothing | |
| # defensible to publish, so the block reports the exclusion instead of | |
| # a number. This is what the package README has always said; before | |
| # 2026-09-20 the summary contradicted it by scoring August AI Mode. | |
| usable = [x for x in er if not x["answer_truncated"]] | |
| if not usable: | |
| s[eng] = { | |
| "markets_answered": len(markets), | |
| "excluded_from_published_rates": True, | |
| "exclusion_reason": ("every stored answer was truncated; a truncated answer can only " | |
| "undercount mentions, so no rate is defensible"), | |
| "answers_truncated": len(trunc_markets), | |
| } | |
| continue | |
| no1 = [x for x in usable if x["maps_position"] == 1] | |
| s[eng] = { | |
| "markets_answered": len({(x["run"], x["category"], x["city"]) for x in usable}), | |
| "top3": rate(usable), | |
| "no1_named": rate(no1), | |
| "markets_with_none_of_top3": sum( | |
| 1 for m in {(x["run"], x["category"], x["city"]) for x in usable} | |
| if not any(x["mentioned"] for x in usable if (x["run"], x["category"], x["city"]) == m)), | |
| "answers_truncated": len(trunc_markets), | |
| "by_category": {c: rate([x for x in usable if x["category"] == c]) | |
| for c in dict.fromkeys(x["category"] for x in usable)}, | |
| } | |
| return s | |
| def main(argv): | |
| pool = "--pool" in argv | |
| out_json = argv[argv.index("--json") + 1] if "--json" in argv else None | |
| out_csv = argv[argv.index("--csv") + 1] if "--csv" in argv else None | |
| skip = {out_json, out_csv} | |
| runs = [a for a in argv if not a.startswith("--") and a not in skip] | |
| result = {"matcher": MATCHER_VERSION, "runs": {}} | |
| allrecs = [] | |
| for run in runs: | |
| d = load(run) | |
| recs = records(d) | |
| allrecs += recs | |
| result["runs"][d["run"]] = {"file": os.path.basename(d["_path"]), | |
| "collected": d.get("generated_utc") or d["run"], | |
| "summary": summarise(recs)} | |
| if pool and len(runs) > 1: | |
| result["pooled"] = {"runs": list(result["runs"]), "summary": summarise(allrecs)} | |
| for label, block in list(result["runs"].items()) + ([("POOLED", result["pooled"])] if "pooled" in result else []): | |
| print(f"\n=== {label} ({MATCHER_VERSION}) ===") | |
| for eng, s in block["summary"].items(): | |
| if s.get("excluded_from_published_rates"): | |
| print(f" {eng:10} markets={s['markets_answered']:3} EXCLUDED: {s['exclusion_reason']} " | |
| f"(truncated={s['answers_truncated']})") | |
| continue | |
| t, n1 = s["top3"], s["no1_named"] | |
| print(f" {eng:10} markets={s['markets_answered']:3} top-3 invisible {t['invisible_pct']}% " | |
| f"{t['invisible_ci95']} ({t['of'] - t['mentioned']}/{t['of']}) #1 named {n1['mention_pct']}% " | |
| f"none-of-top3 markets={s['markets_with_none_of_top3']} truncated={s['answers_truncated']}") | |
| for c, r in s["by_category"].items(): | |
| print(f" {c:24} visible {r['mention_pct']}% ({r['mentioned']}/{r['of']})") | |
| if out_json: | |
| json.dump(result, open(out_json, "w"), indent=1) | |
| print("\nwrote", out_json) | |
| if out_csv: | |
| with open(out_csv, "w", newline="") as f: | |
| w = csv.DictWriter(f, fieldnames=list(allrecs[0])) | |
| w.writeheader() | |
| w.writerows(allrecs) | |
| print("wrote", out_csv) | |
| if __name__ == "__main__": | |
| main(sys.argv[1:]) | |