File size: 7,919 Bytes
4ec1bb3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# -*- coding: utf-8 -*-
"""AI Visibility Index: how stable is an AI answer?

SparkToro's 2026 work found that asking an AI tool the same recommendation
prompt repeatedly rarely returns the same list. Every published AI-visibility
number, including ours, takes ONE draw per market and reports it as a rate. If
the answer moves, that rate is one sample of a distribution nobody has measured.

This measures the distribution. It deliberately does NOT change the main index:
the monthly run keeps taking one draw per market so the series stays comparable
with August and September. This is a sub-study on a seeded random SUBSET, which
answers the question at about the cost of one ordinary run.

  avi_stability.py --dry-run          show the plan and cost, call nothing
  avi_stability.py                    run it (default 10 markets x 5 repeats)
  AVI_SB_MARKETS=8 AVI_SB_REPEATS=7 avi_stability.py

Output: ai_index/stability_<stamp>.json
"""
import datetime, json, os, random, statistics as st, sys, time

sys.path.insert(0, "/root/Desktop/SEMPITE Reports")
import ai_visibility_index as avi          # safe to import since 2026-09-20
from avi_matcher import mentioned, MATCHER_VERSION

N_MARKETS = int(os.environ.get("AVI_SB_MARKETS", 10))
N_REPEATS = int(os.environ.get("AVI_SB_REPEATS", 5))
SEED = int(os.environ.get("AVI_SB_SEED", 20261001))
DRY = "--dry-run" in sys.argv
OUT_DIR = "/root/Desktop/SEMPITE Reports/ai_index"

# from the cron note: a 50-market full run costs about $1.75 across 4 calls each
COST_PER_MARKET_COLLECTION = 1.75 / 50
MIN_BALANCE_HEADROOM = 5.00

ENGINES = ["chatgpt", "chatgpt_web", "google_ai"]      # claude stays paused

# ---------------------------------------------------------------- the subset
markets = [(c, city) for c in avi.FULL["categories"] for city in avi.FULL["cities"]]
rng = random.Random(SEED)
subset = rng.sample(markets, min(N_MARKETS, len(markets)))

collections = len(subset) * N_REPEATS
est_cost = collections * COST_PER_MARKET_COLLECTION
print(f"stability sub-study: {len(subset)} markets x {N_REPEATS} repeats = {collections} collections")
print(f"seed {SEED}, engines {ENGINES}")
print(f"estimated DataForSEO cost: ${est_cost:.2f}  (a full 50-market run is ~$1.75)")
print("\nmarkets:")
for c, city in subset:
    print(f"  {c} / {city}")

if DRY:
    print("\nDRY RUN. nothing called, nothing spent.")
    sys.exit(0)

bal = avi.dfs_balance()
print(f"\nDataForSEO balance: ${bal:.2f}")
if bal < est_cost + MIN_BALANCE_HEADROOM:
    sys.exit(f"balance ${bal:.2f} is under the estimate ${est_cost:.2f} plus ${MIN_BALANCE_HEADROOM:.2f} headroom. Not starting.")

# ---------------------------------------------------------------- collect
rows = []
for cat, city in subset:
    print(f"\n[{cat} / {city}]", flush=True)
    top3 = avi.maps_top3(cat, city)
    if not top3:
        print("  no maps data, skipping market"); continue
    q = (f"I need a {cat} in {city}. Who are the best {cat}s there? "
         f"Please recommend specific businesses by name.")
    row = {"category": cat, "city": city, "top3": top3, "repeats": []}
    for i in range(N_REPEATS):
        answers = {"chatgpt": avi.ask_chatgpt(q), "chatgpt_web": avi.ask_chatgpt(q, web=True),
                   "google_ai": avi.ask_google_ai(cat, city)}
        rep = {"repeat": i + 1, "collected_utc": datetime.datetime.utcnow().isoformat(timespec="seconds") + "Z",
               "answers": {}}
        for eng, ans in answers.items():
            if ans is None:
                continue                      # unavailable, never counted as a miss
            rep["answers"][eng] = {
                "top3_mentioned": [bool(mentioned(b["name"], ans, b.get("domain"))) for b in top3],
                "text": ans,
            }
        row["repeats"].append(rep)
        print(f"  repeat {i+1}/{N_REPEATS}: " +
              ", ".join(f"{e}={sum(a['top3_mentioned'])}/3" for e, a in rep["answers"].items()), flush=True)
        time.sleep(1.5)
    rows.append(row)

# ---------------------------------------------------------------- stability
def analyse(rows):
    out = {}
    for eng in ENGINES:
        pairs = []          # (times_named, repeats_with_an_answer) per business
        per_repeat_rates = []
        market_detail = []
        for r in rows:
            reps = [rep["answers"][eng] for rep in r["repeats"] if eng in rep["answers"]]
            if len(reps) < 2:
                continue    # cannot say anything about stability from one draw
            n = len(reps)
            counts = [sum(rep["top3_mentioned"][i] for rep in reps) for i in range(len(r["top3"]))]
            pairs += [(c, n) for c in counts]
            rates = [100 * (1 - sum(rep["top3_mentioned"]) / len(r["top3"])) for rep in reps]
            per_repeat_rates += rates
            market_detail.append({
                "market": f"{r['category']} / {r['city']}",
                "repeats": n,
                "per_business_times_named": counts,
                "invisibility_by_repeat_pct": [round(x, 1) for x in rates],
                "spread_pct": round(max(rates) - min(rates), 1),
            })
        if not pairs:
            out[eng] = {"status": "insufficient repeats"}
            continue
        always = sum(1 for c, n in pairs if c == n)
        never = sum(1 for c, n in pairs if c == 0)
        sometimes = len(pairs) - always - never
        ever = always + sometimes
        spreads = [m["spread_pct"] for m in market_detail]
        out[eng] = {
            "businesses_observed": len(pairs),
            "always_named": always,
            "never_named": never,
            "sometimes_named": sometimes,
            "unstable_share_of_ever_named_pct": round(100 * sometimes / ever, 1) if ever else None,
            "invisibility_mean_pct": round(st.mean(per_repeat_rates), 1),
            "invisibility_sd_pct": round(st.pstdev(per_repeat_rates), 1) if len(per_repeat_rates) > 1 else 0.0,
            "market_spread_pct": {"median": round(st.median(spreads), 1),
                                  "max": round(max(spreads), 1)},
            "markets": market_detail,
        }
    return out

stability = analyse(rows)
stamp = os.environ.get("AVI_STAMP") or datetime.date.today().strftime("%Y-%m")
out = {
    "run": stamp,
    "study": "stability sub-study",
    "generated_utc": datetime.datetime.utcnow().isoformat(timespec="seconds") + "Z",
    "design": {
        "why": ("Published AI-visibility rates, including our own, take one draw per market. "
                "This measures how much a single draw moves when the same prompt is repeated."),
        "markets_sampled": len(rows), "repeats_per_market": N_REPEATS, "seed": SEED,
        "selection": "seeded random sample of the 50-market frame; the frame itself is unchanged",
        "engines": ENGINES, "matcher": MATCHER_VERSION,
        "note": ("The monthly index still takes ONE draw per market so the series stays "
                 "comparable with earlier editions. This sub-study does not replace it."),
    },
    "stability": stability,
    "rows": rows,
}
path = f"{OUT_DIR}/stability_{stamp}.json"
if os.path.exists(path):
    path = f"{OUT_DIR}/stability_{stamp}_{datetime.datetime.utcnow():%d%H%M}.json"
json.dump(out, open(path, "w"), ensure_ascii=False, indent=1)

print("\n=== STABILITY ===")
for eng, s in stability.items():
    if s.get("status"):
        print(f"{eng:12} {s['status']}"); continue
    print(f"{eng:12} of {s['businesses_observed']} top-3 businesses: "
          f"{s['always_named']} always named, {s['sometimes_named']} sometimes, {s['never_named']} never")
    print(f"{'':12} {s['unstable_share_of_ever_named_pct']}% of those ever named were NOT named every time")
    print(f"{'':12} invisibility {s['invisibility_mean_pct']}% mean, sd {s['invisibility_sd_pct']} points, "
          f"median market spread {s['market_spread_pct']['median']} points")
print("\nsaved:", path)