unitbytes 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
unitbytes/ai.py ADDED
@@ -0,0 +1,938 @@
1
+ """Google AI Overviews & AI Mode domain namespace (`ub.ai`) with GEO Share-of-Voice & Citation Gap auditing."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import asdict, dataclass, field
6
+ from decimal import Decimal
7
+ import ipaddress
8
+ import re
9
+ from typing import TYPE_CHECKING, Any, Literal, Mapping, Sequence
10
+ from urllib.parse import parse_qs, urlparse
11
+
12
+ from ._serialization import format_records
13
+ from ._transports import unwrap_items_payload
14
+
15
+ if TYPE_CHECKING:
16
+ from .client import UnitBytes
17
+
18
+ ACTOR_AI_OVERVIEWS = "unitbytes/google-ai-overviews-scraper"
19
+ ACTOR_AI_MODE = "unitbytes/google-ai-mode-scraper"
20
+
21
+ SurfaceMode = Literal["both", "overviews", "ai_mode"]
22
+ TimeRangeOption = Literal["any", "hour", "day", "week", "month", "year"]
23
+ GapType = Literal[
24
+ "both_organic_and_competitor",
25
+ "organic_ranked_uncited",
26
+ "related_only_uncited",
27
+ "competitor_cited",
28
+ ]
29
+
30
+ _QUERY_SPLIT_RE = re.compile(r"[\r\n]+")
31
+ _VALID_TIME_RANGES = {"any", "hour", "day", "week", "month", "year"}
32
+
33
+ _MULTI_PART_PUBLIC_SUFFIXES: frozenset[str] = frozenset(
34
+ {
35
+ "co.uk", "org.uk", "me.uk", "gov.uk", "ac.uk", "net.uk",
36
+ "com.au", "net.au", "org.au", "edu.au", "gov.au",
37
+ "com.br", "net.br", "org.br", "gov.br", "edu.br",
38
+ "co.jp", "ne.jp", "or.jp", "go.jp", "ac.jp",
39
+ "co.in", "net.in", "org.in", "gov.in", "ac.in", "edu.in",
40
+ "com.sg", "net.sg", "org.sg", "gov.sg", "edu.sg",
41
+ "com.mx", "org.mx", "gob.mx", "edu.mx",
42
+ "co.nz", "net.nz", "org.nz", "govt.nz",
43
+ "co.za", "org.za", "net.za", "gov.za",
44
+ "com.tw", "org.tw", "net.tw",
45
+ "com.hk", "org.hk", "net.hk",
46
+ "co.kr", "or.kr", "ne.kr",
47
+ "co.il", "org.il", "net.il",
48
+ "com.tr", "org.tr", "net.tr",
49
+ "com.ar", "org.ar", "net.ar",
50
+ "com.co", "org.co", "net.co",
51
+ "co.id", "or.id", "ac.id",
52
+ "com.my", "net.my", "org.my",
53
+ "com.ph", "net.ph", "org.ph",
54
+ "com.vn", "net.vn", "org.vn",
55
+ "co.th", "or.th", "ac.th",
56
+ "com.pl", "net.pl", "org.pl",
57
+ "com.es", "org.es", "gob.es",
58
+ "co.at", "or.at", "gv.at",
59
+ }
60
+ )
61
+
62
+ _VALID_GOOGLE_TLD_SUFFIXES: frozenset[str] = frozenset(
63
+ {
64
+ "com", "ad", "ae", "al", "am", "as", "at", "az", "ba", "be", "bf", "bg", "bi", "bj",
65
+ "bs", "bt", "by", "ca", "cat", "cd", "cf", "cg", "ch", "ci", "cl", "cm", "cn", "cv",
66
+ "cz", "de", "dj", "dk", "dm", "dz", "ee", "es", "fi", "fm", "fr", "ga", "ge", "gg",
67
+ "gl", "gm", "gr", "gy", "hn", "hr", "ht", "hu", "ie", "im", "iq", "is", "it", "je",
68
+ "jo", "kg", "ki", "kz", "la", "li", "lk", "lt", "lu", "lv", "md", "me", "mg", "mk",
69
+ "ml", "mn", "mu", "mv", "mw", "ne", "nl", "no", "nr", "nu", "pl", "pn", "ps", "pt",
70
+ "ro", "rs", "ru", "rw", "sc", "se", "sh", "si", "sk", "sm", "sn", "so", "sr", "st",
71
+ "td", "tg", "tl", "tm", "tn", "to", "tt", "vg", "vu",
72
+ "co.ao", "co.bw", "co.ck", "co.cr", "co.id", "co.il", "co.in", "co.jp", "co.ke",
73
+ "co.kr", "co.ls", "co.ma", "co.mz", "co.nz", "co.th", "co.tz", "co.ug", "co.uk",
74
+ "co.uz", "co.ve", "co.vi", "co.za", "co.zm", "co.zw",
75
+ "com.af", "com.ag", "com.ai", "com.ar", "com.au", "com.bd", "com.bh", "com.bn",
76
+ "com.bo", "com.br", "com.bz", "com.co", "com.cu", "com.cy", "com.do", "com.ec",
77
+ "com.eg", "com.et", "com.fj", "com.gh", "com.gi", "com.gt", "com.hk", "com.jm",
78
+ "com.kh", "com.kw", "com.lb", "com.ly", "com.mm", "com.mt", "com.mx", "com.my",
79
+ "com.na", "com.ng", "com.ni", "com.np", "com.om", "com.pa", "com.pe", "com.pg",
80
+ "com.ph", "com.pk", "com.pr", "com.py", "com.qa", "com.sa", "com.sb", "com.sg",
81
+ "com.sl", "com.sv", "com.tj", "com.tr", "com.tw", "com.ua", "com.uy", "com.vc",
82
+ "com.vn",
83
+ }
84
+ )
85
+
86
+
87
+ def _is_valid_google_search_host(host: str) -> bool:
88
+ for prefix in ("google.", "www.google."):
89
+ if host.startswith(prefix):
90
+ return host[len(prefix) :] in _VALID_GOOGLE_TLD_SUFFIXES
91
+ return False
92
+
93
+
94
+ def extract_clean_host(raw_domain_or_url: str) -> str:
95
+ s = str(raw_domain_or_url or "").strip().lower()
96
+ if not s:
97
+ return ""
98
+ if "://" in s:
99
+ try:
100
+ host = (urlparse(s).hostname or "").lower().strip(".")
101
+ except ValueError:
102
+ return ""
103
+ else:
104
+ host = s.split("/", 1)[0].split("?", 1)[0].split("#", 1)[0].split(":", 1)[0].strip(".")
105
+ while host.startswith("www."):
106
+ host = host[4:]
107
+ if "." not in host or any(c.isspace() for c in host):
108
+ return ""
109
+ try:
110
+ ipaddress.ip_address(host.split("%", 1)[0])
111
+ return ""
112
+ except ValueError:
113
+ pass
114
+ labels = host.split(".")
115
+ if len(labels) < 2 or any(not lbl for lbl in labels):
116
+ return ""
117
+ return host
118
+
119
+
120
+ def extract_registrable_domain(raw_domain_or_url: str) -> str:
121
+ """Normalize any URL or subdomain to its registrable `eTLD+1` root domain."""
122
+ host = extract_clean_host(raw_domain_or_url)
123
+ if not host:
124
+ return ""
125
+ labels = host.split(".")
126
+ if len(labels) == 2:
127
+ return "" if host in _MULTI_PART_PUBLIC_SUFFIXES else host
128
+ last_two = f"{labels[-2]}.{labels[-1]}"
129
+ if last_two in _MULTI_PART_PUBLIC_SUFFIXES:
130
+ return f"{labels[-3]}.{last_two}"
131
+ return last_two
132
+
133
+
134
+ def normalize_brand_target(raw_target: str) -> str:
135
+ s = str(raw_target or "").strip()
136
+ if not s:
137
+ return ""
138
+ dom = extract_registrable_domain(s)
139
+ if dom:
140
+ return dom
141
+ if "://" in s or "." in s:
142
+ return ""
143
+ tok = re.sub(r"[^a-z0-9\u00c0-\u024f+-]+", " ", s.lower()).strip()
144
+ return tok if len(tok) >= 2 else ""
145
+
146
+
147
+ def match_domain_or_brand(
148
+ target: str,
149
+ *,
150
+ domain: str = "",
151
+ url: str = "",
152
+ title: str = "",
153
+ publisher: str = "",
154
+ ) -> tuple[bool, bool]:
155
+ norm_t = str(target or "").strip().lower()
156
+ if not norm_t:
157
+ return False, False
158
+
159
+ raw_host = extract_clean_host(url or domain) or extract_clean_host(domain)
160
+ root_dom = extract_registrable_domain(raw_host) if raw_host else ""
161
+
162
+ if "." in norm_t:
163
+ if root_dom and (root_dom == norm_t or raw_host == norm_t or raw_host.endswith("." + norm_t)):
164
+ return True, True
165
+ return False, False
166
+
167
+ compact_slug = re.sub(r"[^a-z0-9]+", "", norm_t)
168
+ hyphen_slug = re.sub(r"\s+", "-", norm_t)
169
+ if root_dom:
170
+ labels = root_dom.split(".")
171
+ last_two = f"{labels[-2]}.{labels[-1]}" if len(labels) >= 2 else ""
172
+ root_stem = labels[-3] if (len(labels) >= 3 and last_two in _MULTI_PART_PUBLIC_SUFFIXES) else labels[0]
173
+ if root_stem and (root_stem == compact_slug or root_stem == hyphen_slug):
174
+ return True, True
175
+
176
+ haystack = f"{publisher or ''} {title or ''}".strip().lower()
177
+ if haystack and len(norm_t) >= 2:
178
+ pat = r"(?<![a-z0-9])" + re.escape(norm_t) + r"(?![a-z0-9])"
179
+ if re.search(pat, haystack):
180
+ return True, False
181
+ return False, False
182
+
183
+
184
+ def validate_google_search_url(raw_url: str) -> str:
185
+ cleaned = str(raw_url or "").strip()
186
+ if not cleaned:
187
+ raise ValueError("Google Search URL cannot be empty.")
188
+ if any(ch.isspace() or ord(ch) < 32 for ch in cleaned):
189
+ raise ValueError("Google Search URL must not contain whitespace or control characters.")
190
+ parsed = urlparse(cleaned)
191
+ if parsed.scheme.lower() != "https":
192
+ raise ValueError(f"Unsupported URL scheme {parsed.scheme!r}. Expected https://www.google.com/search?q=...")
193
+ if parsed.username or parsed.password or "@" in (parsed.netloc or ""):
194
+ raise ValueError("Google Search URL must not contain embedded credentials.")
195
+ if parsed.port not in (None, 443):
196
+ raise ValueError("Google Search URL port must be 443 (or omitted).")
197
+ host = (parsed.hostname or "").lower().rstrip(".")
198
+ if not _is_valid_google_search_host(host):
199
+ raise ValueError(f"Unsupported host {host!r} in start_urls. Expected a Google Search URL.")
200
+ path_str = parsed.path or ""
201
+ if not (path_str == "/search" or path_str.startswith("/search/")):
202
+ raise ValueError(f"Unsupported path {path_str!r} in start_urls. Expected '/search'.")
203
+ qs = parse_qs(parsed.query)
204
+ q = (qs.get("q") or qs.get("as_q") or [""])[0].strip()
205
+ if not q:
206
+ raise ValueError(f"Google Search URL {cleaned!r} is missing a non-empty 'q=' query parameter.")
207
+ return cleaned
208
+
209
+
210
+ def _escape_md_cell(val: Any) -> str:
211
+ text = str(val if val is not None else "").replace("\r", " ").replace("\n", " ")
212
+ return text.replace("|", "\\|").strip()
213
+
214
+
215
+ @dataclass(frozen=True)
216
+ class DomainSovMetrics:
217
+ domain: str
218
+ is_brand: bool
219
+ is_tracked_competitor: bool
220
+ queries_evaluated: int
221
+ ai_present_queries: int
222
+ cited_queries: int
223
+ citation_rate_pct: float
224
+ cited_when_ai_present_pct: float
225
+ total_citations: int
226
+ avg_citation_rank: float | None
227
+ best_citation_rank: int | None
228
+ organic_ranked_queries: int
229
+ best_organic_rank: int | None
230
+ cited_urls: list[str] = field(default_factory=list)
231
+
232
+ def to_dict(self) -> dict[str, Any]:
233
+ return asdict(self)
234
+
235
+
236
+ @dataclass(frozen=True)
237
+ class CitationGapItem:
238
+ query: str
239
+ surface: Literal["overviews", "ai_mode"]
240
+ gap_type: GapType
241
+ priority_score: int
242
+ brand_organic_rank: int | None
243
+ brand_organic_url: str | None
244
+ competitors_cited: list[str]
245
+ top_cited_urls: list[str]
246
+ recommendation: str
247
+
248
+ def to_dict(self) -> dict[str, Any]:
249
+ return asdict(self)
250
+
251
+
252
+ @dataclass(frozen=True)
253
+ class BrandShareOfVoiceReport:
254
+ """Complete GEO / AEO Share-of-Voice & Citation Gap audit across Google AI Overviews and/or AI Mode."""
255
+
256
+ brand_domain: str
257
+ competitor_domains: list[str]
258
+ surface: SurfaceMode
259
+ total_unique_queries: int
260
+ surface_observations: int
261
+ ai_triggered_observations: int
262
+ ai_trigger_rate_pct: float
263
+ query_level_brand_citation_rate_pct: float
264
+ brand_metrics: DomainSovMetrics
265
+ competitor_metrics: list[DomainSovMetrics]
266
+ discovered_competitors: list[DomainSovMetrics]
267
+ citation_gaps: list[CitationGapItem]
268
+ query_matrix: list[dict[str, Any]]
269
+
270
+ def to_dict(self) -> dict[str, Any]:
271
+ return {
272
+ "brand_domain": self.brand_domain,
273
+ "competitor_domains": list(self.competitor_domains),
274
+ "surface": self.surface,
275
+ "total_unique_queries": self.total_unique_queries,
276
+ "surface_observations": self.surface_observations,
277
+ "ai_triggered_observations": self.ai_triggered_observations,
278
+ "ai_trigger_rate_pct": self.ai_trigger_rate_pct,
279
+ "query_level_brand_citation_rate_pct": self.query_level_brand_citation_rate_pct,
280
+ "brand_metrics": self.brand_metrics.to_dict(),
281
+ "competitor_metrics": [m.to_dict() for m in self.competitor_metrics],
282
+ "discovered_competitors": [m.to_dict() for m in self.discovered_competitors],
283
+ "citation_gaps": [g.to_dict() for g in self.citation_gaps],
284
+ "query_matrix": [dict(r) for r in self.query_matrix],
285
+ }
286
+
287
+ def to_markdown(self) -> str:
288
+ lines: list[str] = [
289
+ f"# Google AI GEO Share-of-Voice Audit: `{self.brand_domain}`",
290
+ "",
291
+ f"- **Surface Audited**: `{self.surface}`",
292
+ f"- **Unique Queries**: `{self.total_unique_queries}` (`{self.surface_observations}` surface checks)",
293
+ f"- **AI Answer Trigger Rate**: `{self.ai_trigger_rate_pct:.1f}%` (`{self.ai_triggered_observations}/{self.surface_observations}`)",
294
+ f"- **Brand Citation Rate (All Checks)**: `{self.brand_metrics.citation_rate_pct:.1f}%` (`{self.brand_metrics.cited_queries}/{self.brand_metrics.queries_evaluated}`)",
295
+ f"- **Query-Level Brand Visibility**: `{self.query_level_brand_citation_rate_pct:.1f}%` of unique queries",
296
+ "",
297
+ "## 1. Brand vs. Competitor Share-of-Voice Leaderboard",
298
+ "",
299
+ "| Domain | Role | Cited Checks | Citation Rate % | Share When AI Present % | Avg Citation Rank | Best Organic Rank |",
300
+ "| :--- | :--- | :---: | :---: | :---: | :---: | :---: |",
301
+ ]
302
+ leaderboard = [self.brand_metrics, *self.competitor_metrics, *self.discovered_competitors[:5]]
303
+ for row in leaderboard:
304
+ role = "Target Brand" if row.is_brand else ("Tracked Competitor" if row.is_tracked_competitor else "Discovered Domain")
305
+ avg_rk = f"#{row.avg_citation_rank:.1f}" if row.avg_citation_rank is not None else "—"
306
+ org_rk = f"#{row.best_organic_rank}" if row.best_organic_rank is not None else "—"
307
+ lines.append(
308
+ f"| `{_escape_md_cell(row.domain)}` | {role} | {row.cited_queries}/{row.queries_evaluated} | "
309
+ f"{row.citation_rate_pct:.1f}% | {row.cited_when_ai_present_pct:.1f}% | {avg_rk} | {org_rk} |"
310
+ )
311
+ return "\n".join(lines)
312
+
313
+ def to_csv(self) -> str:
314
+ return format_records(self.query_matrix, fmt="csv")
315
+
316
+
317
+ class _DomainAccumulator:
318
+ def __init__(self, domain: str, *, is_brand: bool, is_tracked_competitor: bool) -> None:
319
+ self.domain = domain
320
+ self.is_brand = is_brand
321
+ self.is_tracked_competitor = is_tracked_competitor
322
+ self.cited_queries = 0
323
+ self.total_citations = 0
324
+ self.citation_ranks: list[int] = []
325
+ self.organic_ranked_queries = 0
326
+ self.organic_ranks: list[int] = []
327
+ self.cited_urls: list[str] = []
328
+
329
+ def record_observation(
330
+ self,
331
+ *,
332
+ matched_citation_ranks: Sequence[int],
333
+ matched_citation_urls: Sequence[str],
334
+ matched_organic_ranks: Sequence[int],
335
+ ) -> None:
336
+ if matched_citation_ranks:
337
+ self.cited_queries += 1
338
+ self.total_citations += len(matched_citation_ranks)
339
+ self.citation_ranks.extend(matched_citation_ranks)
340
+ for u in matched_citation_urls:
341
+ if u and u not in self.cited_urls:
342
+ self.cited_urls.append(u)
343
+ if matched_organic_ranks:
344
+ self.organic_ranked_queries += 1
345
+ self.organic_ranks.extend(matched_organic_ranks)
346
+
347
+ def finalize(self, *, queries_evaluated: int, ai_present_queries: int) -> DomainSovMetrics:
348
+ cit_rate = round((self.cited_queries / queries_evaluated) * 100.0, 2) if queries_evaluated > 0 else 0.0
349
+ ai_cit_rate = round((self.cited_queries / ai_present_queries) * 100.0, 2) if ai_present_queries > 0 else 0.0
350
+ avg_rk = round(sum(self.citation_ranks) / len(self.citation_ranks), 2) if self.citation_ranks else None
351
+ best_cit = min(self.citation_ranks) if self.citation_ranks else None
352
+ best_org = min(self.organic_ranks) if self.organic_ranks else None
353
+ return DomainSovMetrics(
354
+ domain=self.domain,
355
+ is_brand=self.is_brand,
356
+ is_tracked_competitor=self.is_tracked_competitor,
357
+ queries_evaluated=queries_evaluated,
358
+ ai_present_queries=ai_present_queries,
359
+ cited_queries=self.cited_queries,
360
+ citation_rate_pct=cit_rate,
361
+ cited_when_ai_present_pct=ai_cit_rate,
362
+ total_citations=self.total_citations,
363
+ avg_citation_rank=avg_rk,
364
+ best_citation_rank=best_cit,
365
+ organic_ranked_queries=self.organic_ranked_queries,
366
+ best_organic_rank=best_org,
367
+ cited_urls=self.cited_urls[:20],
368
+ )
369
+
370
+
371
+ def compute_share_of_voice_report(
372
+ brand_domain: str,
373
+ *,
374
+ overviews_records: Sequence[Mapping[str, Any]] | None = None,
375
+ ai_mode_records: Sequence[Mapping[str, Any]] | None = None,
376
+ competitor_domains: Sequence[str] | None = None,
377
+ surface: SurfaceMode = "both",
378
+ ) -> BrandShareOfVoiceReport:
379
+ """Compute Share-of-Voice %, average citation rank, and uncited Citation Gaps across Google AI surfaces."""
380
+ norm_brand = normalize_brand_target(brand_domain)
381
+ if not norm_brand:
382
+ raise ValueError(f"Invalid brand_domain {brand_domain!r}. Provide a valid root domain like 'hubspot.com'.")
383
+
384
+ norm_competitors: list[str] = []
385
+ for comp in competitor_domains or []:
386
+ nc = normalize_brand_target(comp)
387
+ if nc and nc != norm_brand and nc not in norm_competitors:
388
+ norm_competitors.append(nc)
389
+
390
+ observations: list[tuple[Literal["overviews", "ai_mode"], Mapping[str, Any]]] = []
391
+ if surface in ("both", "overviews"):
392
+ observations.extend(("overviews", r) for r in (overviews_records or []) if isinstance(r, Mapping))
393
+ if surface in ("both", "ai_mode"):
394
+ observations.extend(("ai_mode", r) for r in (ai_mode_records or []) if isinstance(r, Mapping))
395
+
396
+ brand_acc = _DomainAccumulator(norm_brand, is_brand=True, is_tracked_competitor=False)
397
+ comp_accs: dict[str, _DomainAccumulator] = {
398
+ c: _DomainAccumulator(c, is_brand=False, is_tracked_competitor=True) for c in norm_competitors
399
+ }
400
+ discovered_accs: dict[str, _DomainAccumulator] = {}
401
+
402
+ unique_queries_seen: dict[str, str] = {}
403
+ unique_queries_brand_cited: set[str] = set()
404
+ surface_obs_count = 0
405
+ ai_triggered_count = 0
406
+ citation_gaps: list[CitationGapItem] = []
407
+ query_matrix: list[dict[str, Any]] = []
408
+
409
+ for surf_kind, rec in observations:
410
+ query_str = str(rec.get("query") or "").strip()
411
+ if not query_str:
412
+ continue
413
+ q_norm = query_str.lower()
414
+ unique_queries_seen.setdefault(q_norm, query_str)
415
+ surface_obs_count += 1
416
+
417
+ if surf_kind == "overviews":
418
+ ai_present = bool(rec.get("hasAiOverview"))
419
+ raw_citations = rec.get("citations") if isinstance(rec.get("citations"), Sequence) else []
420
+ raw_related: Sequence[Mapping[str, Any]] = []
421
+ raw_organic = rec.get("organicResults") if isinstance(rec.get("organicResults"), Sequence) else []
422
+ else:
423
+ ai_present = bool(rec.get("hasAnswer")) or (
424
+ str(rec.get("status") or "ok") == "ok" and bool(str(rec.get("markdown") or "").strip())
425
+ )
426
+ all_sources = rec.get("sources") if isinstance(rec.get("sources"), Sequence) else []
427
+ explicit_cits = rec.get("citations") if isinstance(rec.get("citations"), Sequence) else []
428
+ if explicit_cits:
429
+ raw_citations = explicit_cits
430
+ raw_related = [s for s in all_sources if isinstance(s, Mapping) and str(s.get("section") or "") == "related"]
431
+ else:
432
+ raw_citations = [s for s in all_sources if isinstance(s, Mapping) and str(s.get("section") or "cited") == "cited"]
433
+ raw_related = [s for s in all_sources if isinstance(s, Mapping) and str(s.get("section") or "") == "related"]
434
+ raw_organic = []
435
+
436
+ if ai_present:
437
+ ai_triggered_count += 1
438
+
439
+ cited_entries: list[dict[str, Any]] = []
440
+ for idx, c in enumerate(raw_citations, start=1):
441
+ if not isinstance(c, Mapping):
442
+ continue
443
+ c_url = str(c.get("url") or "").strip()
444
+ c_dom = str(c.get("domain") or "").strip() or extract_clean_host(c_url)
445
+ c_root = extract_registrable_domain(c_url or c_dom) or c_dom
446
+ raw_rk = c.get("index") if surf_kind == "overviews" else (c.get("position") or c.get("index"))
447
+ try:
448
+ rk = int(raw_rk) if raw_rk is not None and int(raw_rk) > 0 else idx
449
+ except (TypeError, ValueError):
450
+ rk = idx
451
+ cited_entries.append(
452
+ {
453
+ "rank": rk,
454
+ "url": c_url,
455
+ "domain": c_dom,
456
+ "root_domain": c_root,
457
+ "title": str(c.get("title") or ""),
458
+ "publisher": str(c.get("publisher") or ""),
459
+ }
460
+ )
461
+
462
+ organic_entries: list[dict[str, Any]] = []
463
+ for idx, o in enumerate(raw_organic, start=1):
464
+ if not isinstance(o, Mapping):
465
+ continue
466
+ o_url = str(o.get("url") or "").strip()
467
+ o_disp = str(o.get("displayedUrl") or "").strip()
468
+ o_dom = str(o.get("domain") or "").strip() or extract_clean_host(o_url or o_disp)
469
+ raw_ork = o.get("rank") or o.get("position")
470
+ try:
471
+ ork = int(raw_ork) if raw_ork is not None and int(raw_ork) > 0 else idx
472
+ except (TypeError, ValueError):
473
+ ork = idx
474
+ organic_entries.append(
475
+ {
476
+ "rank": ork,
477
+ "url": o_url,
478
+ "displayed_url": o_disp,
479
+ "domain": o_dom,
480
+ "title": str(o.get("title") or ""),
481
+ }
482
+ )
483
+
484
+ brand_cit_ranks: list[int] = []
485
+ brand_cit_urls: list[str] = []
486
+ brand_org_ranks: list[int] = []
487
+ brand_org_urls: list[str] = []
488
+
489
+ for ce in cited_entries:
490
+ matched, _ = match_domain_or_brand(norm_brand, domain=ce["domain"], url=ce["url"], title=ce["title"], publisher=ce["publisher"])
491
+ if matched:
492
+ brand_cit_ranks.append(ce["rank"])
493
+ if ce["url"] and ce["url"] not in brand_cit_urls:
494
+ brand_cit_urls.append(ce["url"])
495
+
496
+ for oe in organic_entries:
497
+ matched, _ = match_domain_or_brand(norm_brand, domain=oe["domain"], url=oe["url"] or oe["displayed_url"], title=oe["title"])
498
+ if matched:
499
+ brand_org_ranks.append(oe["rank"])
500
+ if oe["url"] and oe["url"] not in brand_org_urls:
501
+ brand_org_urls.append(oe["url"])
502
+
503
+ brand_related_urls: list[str] = []
504
+ for rel in raw_related:
505
+ if not isinstance(rel, Mapping):
506
+ continue
507
+ r_url = str(rel.get("url") or "").strip()
508
+ r_dom = str(rel.get("domain") or "").strip() or extract_clean_host(r_url)
509
+ matched, _ = match_domain_or_brand(norm_brand, domain=r_dom, url=r_url, title=str(rel.get("title") or ""), publisher=str(rel.get("publisher") or ""))
510
+ if matched and r_url and r_url not in brand_related_urls:
511
+ brand_related_urls.append(r_url)
512
+
513
+ brand_acc.record_observation(
514
+ matched_citation_ranks=brand_cit_ranks,
515
+ matched_citation_urls=brand_cit_urls,
516
+ matched_organic_ranks=brand_org_ranks,
517
+ )
518
+ if brand_cit_ranks:
519
+ unique_queries_brand_cited.add(q_norm)
520
+
521
+ competitors_cited_this_obs: list[str] = []
522
+ for comp_key, c_acc in comp_accs.items():
523
+ c_ranks: list[int] = []
524
+ c_urls: list[str] = []
525
+ c_orgs: list[int] = []
526
+ for ce in cited_entries:
527
+ if match_domain_or_brand(comp_key, domain=ce["domain"], url=ce["url"], title=ce["title"], publisher=ce["publisher"])[0]:
528
+ c_ranks.append(ce["rank"])
529
+ if ce["url"] and ce["url"] not in c_urls:
530
+ c_urls.append(ce["url"])
531
+ for oe in organic_entries:
532
+ if match_domain_or_brand(comp_key, domain=oe["domain"], url=oe["url"] or oe["displayed_url"], title=oe["title"])[0]:
533
+ c_orgs.append(oe["rank"])
534
+ c_acc.record_observation(matched_citation_ranks=c_ranks, matched_citation_urls=c_urls, matched_organic_ranks=c_orgs)
535
+ if c_ranks and comp_key not in competitors_cited_this_obs:
536
+ competitors_cited_this_obs.append(comp_key)
537
+
538
+ discovered_per_obs: dict[str, tuple[list[int], list[str]]] = {}
539
+ for ce in cited_entries:
540
+ root_d = ce["root_domain"]
541
+ if not root_d:
542
+ continue
543
+ if match_domain_or_brand(norm_brand, domain=ce["domain"], url=ce["url"], title=ce["title"], publisher=ce["publisher"])[0]:
544
+ continue
545
+ if any(match_domain_or_brand(ck, domain=ce["domain"], url=ce["url"], title=ce["title"], publisher=ce["publisher"])[0] for ck in norm_competitors):
546
+ continue
547
+ b_ranks, b_urls = discovered_per_obs.setdefault(root_d, ([], []))
548
+ b_ranks.append(ce["rank"])
549
+ if ce["url"] and ce["url"] not in b_urls:
550
+ b_urls.append(ce["url"])
551
+ if root_d not in competitors_cited_this_obs:
552
+ competitors_cited_this_obs.append(root_d)
553
+
554
+ for disc_dom, (d_ranks, d_urls) in discovered_per_obs.items():
555
+ d_acc = discovered_accs.setdefault(disc_dom, _DomainAccumulator(disc_dom, is_brand=False, is_tracked_competitor=False))
556
+ d_acc.record_observation(matched_citation_ranks=d_ranks, matched_citation_urls=d_urls, matched_organic_ranks=[])
557
+
558
+ best_brand_cit_rank = min(brand_cit_ranks) if brand_cit_ranks else None
559
+ best_brand_org_rank = min(brand_org_ranks) if brand_org_ranks else None
560
+
561
+ gap_type: GapType | None = None
562
+ priority = 0
563
+ recommendation = ""
564
+ if not brand_cit_ranks:
565
+ if best_brand_org_rank is not None and competitors_cited_this_obs:
566
+ gap_type = "both_organic_and_competitor"
567
+ org_bonus = max(0, (11 - min(best_brand_org_rank, 10)) * 3)
568
+ priority = min(100, 68 + org_bonus + min(10, len(competitors_cited_this_obs) * 3))
569
+ recommendation = (
570
+ f"Ranks #{best_brand_org_rank} organically on Page 1 while {competitors_cited_this_obs[0]} wins AI citation; "
571
+ "add concise answer-first definition blocks, comparison tables, and verifiable stats."
572
+ )
573
+ elif best_brand_org_rank is not None:
574
+ gap_type = "organic_ranked_uncited"
575
+ org_bonus = max(0, (11 - min(best_brand_org_rank, 10)) * 3)
576
+ priority = min(95, 55 + org_bonus)
577
+ recommendation = (
578
+ f"Already ranks #{best_brand_org_rank} on Page 1 without an AI citation; "
579
+ "restructure H2/H3 Q&A headings and structured schema to trigger inline grounding."
580
+ )
581
+ elif brand_related_urls:
582
+ gap_type = "related_only_uncited"
583
+ priority = 65
584
+ recommendation = "Listed only in secondary 'related' AI Mode sources; sharpen direct factual claims to earn an inline cited footnote."
585
+ elif ai_present and competitors_cited_this_obs:
586
+ gap_type = "competitor_cited"
587
+ tracked_hit = any(c in norm_competitors for c in competitors_cited_this_obs)
588
+ priority = min(90, (60 if tracked_hit else 45) + min(20, len(competitors_cited_this_obs) * 4))
589
+ recommendation = (
590
+ f"Competitors ({', '.join(competitors_cited_this_obs[:3])}) own AI citations while {norm_brand} is absent; "
591
+ "publish dedicated comparison content and earn mentions on cited publisher domains."
592
+ )
593
+
594
+ if gap_type is not None:
595
+ citation_gaps.append(
596
+ CitationGapItem(
597
+ query=query_str,
598
+ surface=surf_kind,
599
+ gap_type=gap_type,
600
+ priority_score=priority,
601
+ brand_organic_rank=best_brand_org_rank,
602
+ brand_organic_url=brand_org_urls[0] if brand_org_urls else None,
603
+ competitors_cited=competitors_cited_this_obs[:8],
604
+ top_cited_urls=[ce["url"] for ce in cited_entries if ce["url"]][:5],
605
+ recommendation=recommendation,
606
+ )
607
+ )
608
+
609
+ query_matrix.append(
610
+ {
611
+ "query": query_str,
612
+ "surface": surf_kind,
613
+ "ai_present": ai_present,
614
+ "brand_cited": bool(brand_cit_ranks),
615
+ "brand_best_citation_rank": best_brand_cit_rank,
616
+ "brand_cited_urls": brand_cit_urls,
617
+ "brand_best_organic_rank": best_brand_org_rank,
618
+ "competitors_cited": competitors_cited_this_obs[:8],
619
+ "total_citations": len(cited_entries),
620
+ "gap_type": gap_type or "",
621
+ "priority_score": priority,
622
+ }
623
+ )
624
+
625
+ citation_gaps.sort(key=lambda g: (-g.priority_score, g.query.lower(), g.surface))
626
+ brand_metrics = brand_acc.finalize(queries_evaluated=surface_obs_count, ai_present_queries=ai_triggered_count)
627
+ competitor_metrics = sorted(
628
+ [acc.finalize(queries_evaluated=surface_obs_count, ai_present_queries=ai_triggered_count) for acc in comp_accs.values()],
629
+ key=lambda m: (-m.citation_rate_pct, m.avg_citation_rank or 999.0, m.domain),
630
+ )
631
+ discovered_metrics = sorted(
632
+ [acc.finalize(queries_evaluated=surface_obs_count, ai_present_queries=ai_triggered_count) for acc in discovered_accs.values()],
633
+ key=lambda m: (-m.cited_queries, -m.total_citations, m.avg_citation_rank or 999.0, m.domain),
634
+ )
635
+
636
+ total_unique = len(unique_queries_seen)
637
+ ai_trigger_rate = round((ai_triggered_count / surface_obs_count) * 100.0, 2) if surface_obs_count > 0 else 0.0
638
+ q_level_rate = round((len(unique_queries_brand_cited) / total_unique) * 100.0, 2) if total_unique > 0 else 0.0
639
+
640
+ return BrandShareOfVoiceReport(
641
+ brand_domain=norm_brand,
642
+ competitor_domains=norm_competitors,
643
+ surface=surface,
644
+ total_unique_queries=total_unique,
645
+ surface_observations=surface_obs_count,
646
+ ai_triggered_observations=ai_triggered_count,
647
+ ai_trigger_rate_pct=ai_trigger_rate,
648
+ query_level_brand_citation_rate_pct=q_level_rate,
649
+ brand_metrics=brand_metrics,
650
+ competitor_metrics=competitor_metrics,
651
+ discovered_competitors=discovered_metrics[:15],
652
+ citation_gaps=citation_gaps,
653
+ query_matrix=query_matrix,
654
+ )
655
+
656
+
657
+ def _normalize_queries(queries: Sequence[str] | str | None) -> list[str]:
658
+ if queries is None:
659
+ return []
660
+ raw_items: list[str] = []
661
+ if isinstance(queries, str):
662
+ raw_items.extend(part.strip() for part in _QUERY_SPLIT_RE.split(queries) if part.strip())
663
+ elif isinstance(queries, Sequence):
664
+ for entry in queries:
665
+ if isinstance(entry, bool) or not isinstance(entry, str):
666
+ raise ValueError("Each query in 'queries' must be a string.")
667
+ if entry.strip():
668
+ raw_items.append(entry.strip())
669
+ else:
670
+ raise ValueError("queries must be a string or sequence of search query strings.")
671
+
672
+ deduped: list[str] = []
673
+ seen: set[str] = set()
674
+ for item in raw_items:
675
+ if "://" in item[:12]:
676
+ validate_google_search_url(item)
677
+ key = item.lower()
678
+ if key not in seen:
679
+ seen.add(key)
680
+ deduped.append(item)
681
+ return deduped
682
+
683
+
684
+ def _normalize_start_urls(start_urls: Sequence[str | Mapping[str, Any]] | str | None) -> list[str]:
685
+ if start_urls is None:
686
+ return []
687
+ entries: Sequence[Any] = [start_urls] if isinstance(start_urls, str) else start_urls
688
+ cleaned: list[str] = []
689
+ seen: set[str] = set()
690
+ for entry in entries:
691
+ raw_u = str(entry.get("url") or "").strip() if isinstance(entry, Mapping) else str(entry or "").strip()
692
+ if not raw_u:
693
+ continue
694
+ safe_u = validate_google_search_url(raw_u)
695
+ if safe_u not in seen:
696
+ seen.add(safe_u)
697
+ cleaned.append(safe_u)
698
+ return cleaned
699
+
700
+
701
+ def _normalize_target_domains(target_domains: Sequence[str] | str | None) -> list[str]:
702
+ if target_domains is None:
703
+ return []
704
+ raw_list: Sequence[str] = (
705
+ [p.strip() for p in re.split(r"[\n,;]+", target_domains) if p.strip()]
706
+ if isinstance(target_domains, str)
707
+ else [str(x).strip() for x in target_domains if x is not None and str(x).strip()]
708
+ )
709
+ out: list[str] = []
710
+ for item in raw_list:
711
+ norm = normalize_brand_target(item)
712
+ if norm and norm not in out:
713
+ out.append(norm)
714
+ return out
715
+
716
+
717
+ class AiNamespace:
718
+ """Google AI Overviews, Google AI Mode, and GEO Brand Share-of-Voice audits (`ub.ai`)."""
719
+
720
+ def __init__(self, client: UnitBytes) -> None:
721
+ self._client = client
722
+
723
+ def overviews(
724
+ self,
725
+ queries: Sequence[str] | str | None = None,
726
+ *,
727
+ start_urls: Sequence[str | Mapping[str, Any]] | str | None = None,
728
+ max_queries: int = 25,
729
+ country: str = "US",
730
+ language: str = "",
731
+ location: str = "",
732
+ time_range: TimeRangeOption = "any",
733
+ target_domains: Sequence[str] | str | None = None,
734
+ include_organic_results: bool = True,
735
+ include_people_also_ask: bool = True,
736
+ resolve_urls: bool = True,
737
+ max_concurrency: int = 4,
738
+ proxy_configuration: Mapping[str, Any] | None = None,
739
+ max_total_charge_usd: float | Decimal | None = None,
740
+ ) -> list[dict[str, Any]]:
741
+ """Extract Google Search AI Overviews, unwrapped citations, Page 1 organic ranks, and PAA.
742
+
743
+ Apify pricing (`unitbytes/google-ai-overviews-scraper`): flat `$3.00 / 1,000 queries` across all plans + `$0.005` actor start.
744
+ """
745
+ norm_queries = _normalize_queries(queries)
746
+ norm_urls = _normalize_start_urls(start_urls)
747
+ if not norm_queries and not norm_urls:
748
+ raise ValueError("Provide at least one search query in 'queries' or a Google Search URL in 'start_urls'.")
749
+ if isinstance(max_queries, bool) or int(max_queries) < 1:
750
+ raise ValueError(f"max_queries must be >= 1, got {max_queries!r}.")
751
+ if isinstance(max_concurrency, bool) or not (1 <= int(max_concurrency) <= 8):
752
+ raise ValueError(f"max_concurrency must be between 1 and 8, got {max_concurrency!r}.")
753
+
754
+ tr_clean = str(time_range or "any").strip().lower()
755
+ if tr_clean not in _VALID_TIME_RANGES:
756
+ raise ValueError(f"Invalid time_range {time_range!r}. Expected one of: any, hour, day, week, month, year.")
757
+
758
+ norm_targets = _normalize_target_domains(target_domains)
759
+ capped_max = min(1000, int(max_queries))
760
+
761
+ run_input: dict[str, Any] = {
762
+ "maxQueries": capped_max,
763
+ "country": str(country or "US").strip().upper(),
764
+ "language": str(language or "").strip(),
765
+ "location": str(location or "").strip(),
766
+ "timeRange": tr_clean,
767
+ "includeOrganicResults": bool(include_organic_results),
768
+ "includePeopleAlsoAsk": bool(include_people_also_ask),
769
+ "resolveUrls": bool(resolve_urls),
770
+ "maxConcurrency": int(max_concurrency),
771
+ }
772
+ if norm_queries:
773
+ run_input["queries"] = norm_queries
774
+ if norm_urls:
775
+ run_input["startUrls"] = norm_urls
776
+ if norm_targets:
777
+ run_input["targetDomains"] = norm_targets
778
+ if proxy_configuration is not None:
779
+ run_input["proxyConfiguration"] = dict(proxy_configuration)
780
+
781
+ raw = self._client._transport.execute_operation(
782
+ service="ai",
783
+ operation="overviews",
784
+ actor_slug=ACTOR_AI_OVERVIEWS,
785
+ actor_input=run_input,
786
+ http_method="POST",
787
+ json_body=run_input,
788
+ max_total_charge_usd=max_total_charge_usd,
789
+ )
790
+ return [r for r in unwrap_items_payload(raw) if not r.get("error")]
791
+
792
+ def ai_mode(
793
+ self,
794
+ queries: Sequence[str] | str | None = None,
795
+ *,
796
+ start_urls: Sequence[str | Mapping[str, Any]] | str | None = None,
797
+ max_queries: int = 25,
798
+ country: str = "US",
799
+ language: str = "",
800
+ location: str = "",
801
+ target_domains: Sequence[str] | str | None = None,
802
+ resolve_urls: bool = True,
803
+ max_concurrency: int = 4,
804
+ proxy_configuration: Mapping[str, Any] | None = None,
805
+ max_total_charge_usd: float | Decimal | None = None,
806
+ ) -> list[dict[str, Any]]:
807
+ """Query Google AI Mode for conversational Markdown answers and cited vs. related sources.
808
+
809
+ Apify pricing (`unitbytes/google-ai-mode-scraper`): `$5.00 / 1,000 queries` (Free) to `$4.00 / 1,000 queries` (`GOLD+`) + `$0.005` actor start.
810
+ """
811
+ norm_queries = _normalize_queries(queries)
812
+ norm_urls = _normalize_start_urls(start_urls)
813
+ if not norm_queries and not norm_urls:
814
+ raise ValueError("Provide at least one prompt in 'queries' or a Google Search URL in 'start_urls'.")
815
+ if isinstance(max_queries, bool) or int(max_queries) < 1:
816
+ raise ValueError(f"max_queries must be >= 1, got {max_queries!r}.")
817
+ if isinstance(max_concurrency, bool) or not (1 <= int(max_concurrency) <= 8):
818
+ raise ValueError(f"max_concurrency must be between 1 and 8, got {max_concurrency!r}.")
819
+
820
+ norm_targets = _normalize_target_domains(target_domains)
821
+ capped_max = min(1000, int(max_queries))
822
+
823
+ run_input: dict[str, Any] = {
824
+ "maxQueries": capped_max,
825
+ "country": str(country or "US").strip().upper(),
826
+ "language": str(language or "").strip(),
827
+ "location": str(location or "").strip(),
828
+ "resolveUrls": bool(resolve_urls),
829
+ "maxConcurrency": int(max_concurrency),
830
+ }
831
+ if norm_queries:
832
+ run_input["queries"] = norm_queries
833
+ if norm_urls:
834
+ run_input["startUrls"] = norm_urls
835
+ if norm_targets:
836
+ run_input["targetDomains"] = norm_targets
837
+ if proxy_configuration is not None:
838
+ run_input["proxyConfiguration"] = dict(proxy_configuration)
839
+
840
+ raw = self._client._transport.execute_operation(
841
+ service="ai",
842
+ operation="ai-mode",
843
+ actor_slug=ACTOR_AI_MODE,
844
+ actor_input=run_input,
845
+ http_method="POST",
846
+ json_body=run_input,
847
+ max_total_charge_usd=max_total_charge_usd,
848
+ )
849
+ return [r for r in unwrap_items_payload(raw) if not r.get("error")]
850
+
851
+ def audit_brand_share_of_voice(
852
+ self,
853
+ queries: Sequence[str] | str,
854
+ brand_domain: str,
855
+ *,
856
+ competitor_domains: Sequence[str] | str | None = None,
857
+ surface: SurfaceMode = "both",
858
+ country: str = "US",
859
+ language: str = "",
860
+ location: str = "",
861
+ time_range: TimeRangeOption = "any",
862
+ resolve_urls: bool = True,
863
+ max_queries: int | None = None,
864
+ max_concurrency: int = 4,
865
+ proxy_configuration: Mapping[str, Any] | None = None,
866
+ max_total_charge_usd: float | Decimal | None = None,
867
+ ) -> BrandShareOfVoiceReport:
868
+ """Run a multi-query GEO / AEO Share-of-Voice & Citation Gap audit for `brand_domain` vs. `competitor_domains`."""
869
+ if surface not in ("both", "overviews", "ai_mode"):
870
+ raise ValueError(f"Invalid surface {surface!r}. Expected 'both', 'overviews', or 'ai_mode'.")
871
+
872
+ norm_queries = _normalize_queries(queries)
873
+ if not norm_queries:
874
+ raise ValueError("Provide at least one non-empty query in 'queries'.")
875
+ if max_queries is None and len(norm_queries) > 1000:
876
+ raise ValueError("audit_brand_share_of_voice supports up to 1000 unique queries per run.")
877
+
878
+ norm_brand = normalize_brand_target(brand_domain)
879
+ if not norm_brand:
880
+ raise ValueError(f"Invalid brand_domain {brand_domain!r}. Provide a root domain like 'hubspot.com'.")
881
+
882
+ norm_competitors = [c for c in _normalize_target_domains(competitor_domains) if c != norm_brand]
883
+ combined_targets = [norm_brand, *norm_competitors]
884
+ effective_max = max_queries if max_queries is not None else len(norm_queries)
885
+
886
+ ov_records: list[dict[str, Any]] = []
887
+ am_records: list[dict[str, Any]] = []
888
+
889
+ if surface in ("both", "overviews"):
890
+ ov_records = self.overviews(
891
+ norm_queries,
892
+ max_queries=effective_max,
893
+ country=country,
894
+ language=language,
895
+ location=location,
896
+ time_range=time_range,
897
+ target_domains=combined_targets,
898
+ include_organic_results=True,
899
+ include_people_also_ask=True,
900
+ resolve_urls=resolve_urls,
901
+ max_concurrency=max_concurrency,
902
+ proxy_configuration=proxy_configuration,
903
+ max_total_charge_usd=max_total_charge_usd,
904
+ )
905
+
906
+ if surface in ("both", "ai_mode"):
907
+ am_records = self.ai_mode(
908
+ norm_queries,
909
+ max_queries=effective_max,
910
+ country=country,
911
+ language=language,
912
+ location=location,
913
+ target_domains=combined_targets,
914
+ resolve_urls=resolve_urls,
915
+ max_concurrency=max_concurrency,
916
+ proxy_configuration=proxy_configuration,
917
+ max_total_charge_usd=max_total_charge_usd,
918
+ )
919
+
920
+ return compute_share_of_voice_report(
921
+ norm_brand,
922
+ overviews_records=ov_records,
923
+ ai_mode_records=am_records,
924
+ competitor_domains=norm_competitors,
925
+ surface=surface,
926
+ )
927
+
928
+
929
+ __all__ = [
930
+ "AiNamespace",
931
+ "BrandShareOfVoiceReport",
932
+ "CitationGapItem",
933
+ "DomainSovMetrics",
934
+ "compute_share_of_voice_report",
935
+ "extract_registrable_domain",
936
+ "normalize_brand_target",
937
+ "validate_google_search_url",
938
+ ]