omnirank 0.5.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.
Files changed (183) hide show
  1. omnirank/__init__.py +14 -0
  2. omnirank/__main__.py +6 -0
  3. omnirank/adapters/__init__.py +202 -0
  4. omnirank/adapters/astro.py +338 -0
  5. omnirank/adapters/base.py +372 -0
  6. omnirank/adapters/html.py +561 -0
  7. omnirank/adapters/jsx.py +340 -0
  8. omnirank/adapters/nextjs.py +692 -0
  9. omnirank/aeo/__init__.py +9 -0
  10. omnirank/aeo/extract.py +383 -0
  11. omnirank/aeo/propose.py +84 -0
  12. omnirank/aeo/rules.py +964 -0
  13. omnirank/aeo/runner.py +148 -0
  14. omnirank/applicability.py +98 -0
  15. omnirank/apply/__init__.py +23 -0
  16. omnirank/apply/engine.py +1254 -0
  17. omnirank/apply/journal.py +139 -0
  18. omnirank/apply/patch.py +144 -0
  19. omnirank/audit.py +185 -0
  20. omnirank/bands.py +106 -0
  21. omnirank/brief/__init__.py +0 -0
  22. omnirank/brief/analyze.py +197 -0
  23. omnirank/brief/constants.py +89 -0
  24. omnirank/brief/cost.py +62 -0
  25. omnirank/brief/egress.py +23 -0
  26. omnirank/brief/fetchpages.py +239 -0
  27. omnirank/brief/render.py +151 -0
  28. omnirank/brief/runner.py +369 -0
  29. omnirank/brief/serp.py +274 -0
  30. omnirank/brief/text.py +181 -0
  31. omnirank/cli.py +844 -0
  32. omnirank/clock.py +22 -0
  33. omnirank/cms/__init__.py +1 -0
  34. omnirank/cms/runner.py +170 -0
  35. omnirank/cms/wordpress.py +495 -0
  36. omnirank/cms/wordpress_apply.py +508 -0
  37. omnirank/cms/wordpress_plan.py +280 -0
  38. omnirank/config.py +81 -0
  39. omnirank/connect/__init__.py +4 -0
  40. omnirank/connect/bing.py +284 -0
  41. omnirank/connect/cloud_setup.py +43 -0
  42. omnirank/connect/confirm.py +242 -0
  43. omnirank/connect/constants.py +226 -0
  44. omnirank/connect/doctor.py +270 -0
  45. omnirank/connect/ga4.py +749 -0
  46. omnirank/connect/ga4_ai.py +123 -0
  47. omnirank/connect/google_auth.py +657 -0
  48. omnirank/connect/gsc.py +630 -0
  49. omnirank/connect/gsc_reports.py +169 -0
  50. omnirank/connect/http.py +310 -0
  51. omnirank/connect/indexnow.py +373 -0
  52. omnirank/connect/naver.py +536 -0
  53. omnirank/connect/runner.py +515 -0
  54. omnirank/connect/runner_ga4_ai.py +59 -0
  55. omnirank/connect/runner_more.py +489 -0
  56. omnirank/connect/runner_regional.py +260 -0
  57. omnirank/connect/secrets.py +190 -0
  58. omnirank/connect/urlcheck.py +41 -0
  59. omnirank/connect/yandex.py +350 -0
  60. omnirank/crawl/__init__.py +11 -0
  61. omnirank/crawl/analyze.py +493 -0
  62. omnirank/crawl/crawler.py +491 -0
  63. omnirank/crawl/custom.py +175 -0
  64. omnirank/crawl/export.py +67 -0
  65. omnirank/crawl/fetcher.py +212 -0
  66. omnirank/crawl/parse.py +102 -0
  67. omnirank/crawl/render.py +148 -0
  68. omnirank/crawl/robotsgate.py +198 -0
  69. omnirank/crawl/runner.py +295 -0
  70. omnirank/crawl/sitemap.py +99 -0
  71. omnirank/crawl/text.py +20 -0
  72. omnirank/crawl/urls.py +100 -0
  73. omnirank/crawlers.py +564 -0
  74. omnirank/data/ai_crawlers.json +269 -0
  75. omnirank/data/ai_referrers.json +42 -0
  76. omnirank/fetch.py +107 -0
  77. omnirank/fixes/__init__.py +92 -0
  78. omnirank/fixes/base.py +232 -0
  79. omnirank/fixes/canonical.py +243 -0
  80. omnirank/fixes/schema.py +126 -0
  81. omnirank/formats.py +134 -0
  82. omnirank/framework.py +223 -0
  83. omnirank/gates/__init__.py +48 -0
  84. omnirank/gates/aeo.py +114 -0
  85. omnirank/gates/contradictions.py +280 -0
  86. omnirank/gates/crawler_policy.py +85 -0
  87. omnirank/gates/geo.py +152 -0
  88. omnirank/gates/hygiene.py +81 -0
  89. omnirank/gates/jsonld.py +282 -0
  90. omnirank/gates/onpage.py +177 -0
  91. omnirank/gates/perf.py +115 -0
  92. omnirank/gates/security.py +264 -0
  93. omnirank/gates/seo.py +118 -0
  94. omnirank/gates/site.py +248 -0
  95. omnirank/geo_artifacts.py +199 -0
  96. omnirank/html.py +79 -0
  97. omnirank/keywords/__init__.py +5 -0
  98. omnirank/keywords/constants.py +69 -0
  99. omnirank/keywords/engine.py +384 -0
  100. omnirank/keywords/report.py +143 -0
  101. omnirank/keywords/runner.py +160 -0
  102. omnirank/keywords/source.py +60 -0
  103. omnirank/keywords/text.py +45 -0
  104. omnirank/locator.py +480 -0
  105. omnirank/logs/__init__.py +0 -0
  106. omnirank/logs/analyze.py +127 -0
  107. omnirank/logs/bots.py +69 -0
  108. omnirank/logs/ipranges.py +191 -0
  109. omnirank/logs/parse.py +452 -0
  110. omnirank/logs/paths.py +22 -0
  111. omnirank/logs/privacy.py +105 -0
  112. omnirank/logs/runner.py +179 -0
  113. omnirank/mcp_server.py +1480 -0
  114. omnirank/netguard.py +525 -0
  115. omnirank/packs/__init__.py +6 -0
  116. omnirank/packs/backlinks.py +535 -0
  117. omnirank/packs/blog.py +544 -0
  118. omnirank/packs/blog_cross.py +468 -0
  119. omnirank/packs/crawlers.py +23 -0
  120. omnirank/packs/entity.py +492 -0
  121. omnirank/packs/feeds.py +150 -0
  122. omnirank/packs/frontmatter.py +59 -0
  123. omnirank/packs/gsc.py +421 -0
  124. omnirank/packs/local.py +879 -0
  125. omnirank/packs/mdscan.py +326 -0
  126. omnirank/packs/miniyaml.py +378 -0
  127. omnirank/packs/model.py +46 -0
  128. omnirank/packs/product.py +979 -0
  129. omnirank/packs/refresh.py +165 -0
  130. omnirank/packs/runner.py +277 -0
  131. omnirank/packs/sitescan.py +294 -0
  132. omnirank/packs/textsafe.py +79 -0
  133. omnirank/packs/xmlsafe.py +92 -0
  134. omnirank/page.py +42 -0
  135. omnirank/registry.py +302 -0
  136. omnirank/report.py +251 -0
  137. omnirank/report_cmd/__init__.py +7 -0
  138. omnirank/report_cmd/delta.py +58 -0
  139. omnirank/report_cmd/files.py +64 -0
  140. omnirank/report_cmd/model.py +208 -0
  141. omnirank/report_cmd/notify.py +195 -0
  142. omnirank/report_cmd/pdf.py +83 -0
  143. omnirank/report_cmd/portfolio.py +342 -0
  144. omnirank/report_cmd/render.py +379 -0
  145. omnirank/report_cmd/runner.py +267 -0
  146. omnirank/robots.py +172 -0
  147. omnirank/scanner/__init__.py +10 -0
  148. omnirank/scanner/badge.py +90 -0
  149. omnirank/scanner/cache.py +69 -0
  150. omnirank/scanner/cli.py +96 -0
  151. omnirank/scanner/engine.py +289 -0
  152. omnirank/scanner/limits.py +98 -0
  153. omnirank/scanner/server.py +143 -0
  154. omnirank/scanner/service.py +328 -0
  155. omnirank/schema/__init__.py +13 -0
  156. omnirank/schema/catalog.py +679 -0
  157. omnirank/schema/catalog_specs.py +350 -0
  158. omnirank/schema/core.py +306 -0
  159. omnirank/schema/extract.py +396 -0
  160. omnirank/schema/gate.py +121 -0
  161. omnirank/schema/runner.py +213 -0
  162. omnirank/schema/validate.py +504 -0
  163. omnirank/schema/vocab.py +305 -0
  164. omnirank/schemas/omnirank.config.schema.json +268 -0
  165. omnirank/track/__init__.py +0 -0
  166. omnirank/track/ai_prompts.py +207 -0
  167. omnirank/track/analysis.py +197 -0
  168. omnirank/track/constants.py +155 -0
  169. omnirank/track/cost.py +229 -0
  170. omnirank/track/discover.py +277 -0
  171. omnirank/track/discover_cli.py +309 -0
  172. omnirank/track/discover_constants.py +95 -0
  173. omnirank/track/engines.py +216 -0
  174. omnirank/track/estimate_view.py +212 -0
  175. omnirank/track/history.py +261 -0
  176. omnirank/track/runner.py +586 -0
  177. omnirank/track/stats.py +138 -0
  178. omnirank/track/storage.py +128 -0
  179. omnirank-0.5.0.dist-info/METADATA +47 -0
  180. omnirank-0.5.0.dist-info/RECORD +183 -0
  181. omnirank-0.5.0.dist-info/WHEEL +5 -0
  182. omnirank-0.5.0.dist-info/entry_points.txt +2 -0
  183. omnirank-0.5.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,515 @@
1
+ """CLI handlers for `omnirank connect ...` and `omnirank doctor`.
2
+
3
+ Exit codes: 0 done; 1 work left undone (a declined write, inspection stopped at --max or the
4
+ local quota, per-URL errors) or doctor found a problem; 2 usage, refusal, authentication or
5
+ API failure. Every message printed here goes through ``redact()``; data output (rows, URLs)
6
+ is scrubbed of registered credential values.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import json
12
+ import sys
13
+ from pathlib import Path
14
+
15
+ from .. import __version__
16
+ from . import cloud_setup, doctor, google_auth, runner_more, runner_regional
17
+ from .confirm import ActionLog, ConfirmError, confirm_and_run
18
+ from .constants import (
19
+ GOOGLE_API_HOSTS,
20
+ SCOPE_GA4_READONLY,
21
+ SCOPE_GSC_READONLY,
22
+ SCOPE_GSC_WRITE,
23
+ SCOPE_SITE_VERIFICATION,
24
+ URL_INSPECTION_DAILY_LIMIT_PER_SITE,
25
+ )
26
+ from .gsc import (
27
+ GscClient,
28
+ GscError,
29
+ IndexingApiRefused,
30
+ InspectionQuota,
31
+ assert_indexing_api_allowed,
32
+ inspect_batch,
33
+ normalize_rows,
34
+ validate_property,
35
+ verification_guidance,
36
+ verification_instructions,
37
+ )
38
+ from .gsc_reports import build_report
39
+ from .http import ApiClient, ApiError
40
+ from .secrets import redact, redact_obj, scrub_registered
41
+
42
+ MAX_INPUT_FILE = 200_000_000
43
+ MAX_URLS_FILE = 10_000_000
44
+
45
+
46
+ class UsageError(Exception):
47
+ pass
48
+
49
+
50
+ def _err(message: object) -> None:
51
+ print(f"omnirank: {redact(message)}", file=sys.stderr)
52
+
53
+
54
+ def _emit(data: object) -> None:
55
+ print(scrub_registered(json.dumps(data, indent=2, ensure_ascii=False)))
56
+
57
+
58
+ def _api(root: Path, scopes: list[str]) -> GscClient:
59
+ source = google_auth.resolve_token_source(scopes, project_root=root)
60
+ return GscClient(ApiClient(source.token, allowed_hosts=GOOGLE_API_HOSTS))
61
+
62
+
63
+ def _read_json(path: str, what: str) -> dict:
64
+ p = Path(path)
65
+ try:
66
+ if p.stat().st_size > MAX_INPUT_FILE:
67
+ raise UsageError(f"{what} {path} is larger than {MAX_INPUT_FILE} bytes")
68
+ data = json.loads(p.read_text(encoding="utf-8"))
69
+ except OSError as exc:
70
+ raise UsageError(f"cannot read {what} {path}: {exc.strerror or exc}") from None
71
+ except (ValueError, UnicodeDecodeError):
72
+ raise UsageError(f"{what} {path} is not valid JSON") from None
73
+ if not isinstance(data, dict):
74
+ raise UsageError(f"{what} {path} is not a JSON object")
75
+ return data
76
+
77
+
78
+ # --- gsc ----------------------------------------------------------------------------------------
79
+
80
+ def _login(args, root: Path) -> int:
81
+ scopes = [SCOPE_GSC_READONLY]
82
+ if args.write_scope:
83
+ scopes.append(SCOPE_GSC_WRITE)
84
+ if args.verification_scope:
85
+ scopes.append(SCOPE_SITE_VERIFICATION)
86
+ if args.analytics_scope:
87
+ scopes.append(SCOPE_GA4_READONLY)
88
+ if args.device:
89
+ client_id, client_secret = google_auth.load_client_file(args.client_file, root)
90
+ # refuses Search Console scopes before any request (Google's device flow lacks them)
91
+ import time
92
+
93
+ import httpx
94
+ google_auth.device_flow(client_id, client_secret, scopes, http=httpx.Client(),
95
+ sleep=time.sleep, now=time.time, out=sys.stdout)
96
+ return 2
97
+ opener = None
98
+ if args.open_browser:
99
+ import webbrowser
100
+ opener = webbrowser.open
101
+ google_auth.loopback_login(args.client_file, scopes, project_root=root,
102
+ open_browser=opener)
103
+ return 0
104
+
105
+
106
+ def _logout(args, root: Path) -> int:
107
+ cache = google_auth.TokenCache(project_root=root)
108
+ if cache.delete():
109
+ print(f"Deleted the saved login {cache.path}. To revoke OmniRank's access at Google "
110
+ "too, use https://myaccount.google.com/permissions")
111
+ else:
112
+ print(f"No saved login at {cache.path}.")
113
+ return 0
114
+
115
+
116
+ def _sites(args, root: Path) -> int:
117
+ sites = _api(root, [SCOPE_GSC_READONLY]).list_sites()
118
+ if args.json:
119
+ _emit({"sites": sites})
120
+ return 0
121
+ if not sites:
122
+ print("No Search Console properties are visible to this credential.")
123
+ for s in sites:
124
+ print(scrub_registered(f" {s['siteUrl']} ({s['permissionLevel'] or 'unknown'})"))
125
+ return 0
126
+
127
+
128
+ def _sitemaps(args, root: Path) -> int:
129
+ validate_property(args.site)
130
+ if args.sitemaps_command in ("submit", "delete"):
131
+ action = GscClient(None).sitemap_action(args.site, args.sitemap, args.sitemaps_command)
132
+ client = _api(root, [SCOPE_GSC_WRITE]) if args.send else None
133
+ return confirm_and_run(action, send=args.send, yes=args.yes, log=ActionLog(root),
134
+ execute=lambda: client.execute(action))
135
+ client = _api(root, [SCOPE_GSC_READONLY])
136
+ if args.sitemaps_command == "get":
137
+ data = client.get_sitemap(args.site, args.sitemap)
138
+ if args.json:
139
+ _emit(data)
140
+ else:
141
+ _print_sitemaps([data])
142
+ return 0
143
+ maps = client.list_sitemaps(args.site)
144
+ if args.json:
145
+ _emit({"site": args.site, "sitemaps": maps})
146
+ else:
147
+ _print_sitemaps(maps)
148
+ return 0
149
+
150
+
151
+ def _print_sitemaps(maps: list[dict]) -> None:
152
+ if not maps:
153
+ print("No sitemaps are submitted for this property.")
154
+ for m in maps:
155
+ counts = "; ".join(f"{c['type']}: {c['submitted']} submitted" for c in m["contents"])
156
+ print(scrub_registered(f" {m['path']} last submitted {m['lastSubmitted'] or '?'} "
157
+ f"errors {m['errors'] or '?'} warnings {m['warnings'] or '?'}"
158
+ + (f" ({counts})" if counts else "")))
159
+
160
+
161
+ def _query(args, root: Path) -> int:
162
+ validate_property(args.site)
163
+ if args.top < 0:
164
+ raise UsageError("--top must be 0 or more")
165
+ client = _api(root, [SCOPE_GSC_READONLY])
166
+ res = client.query(args.site, args.start, args.end, args.dimensions,
167
+ search_type=args.type, max_rows=args.max_rows,
168
+ data_state=args.data_state)
169
+ rows = [{"keys": [r.dims[d] for d in args.dimensions], "clicks": r.clicks,
170
+ "impressions": r.impressions, "ctr": r.ctr, "position": r.position}
171
+ for r in res.rows]
172
+ if args.json:
173
+ _emit({"site": args.site, "startDate": args.start, "endDate": args.end,
174
+ "type": args.type, "dimensions": args.dimensions, "rows": rows,
175
+ "skippedRows": res.skipped, "truncated": res.truncated,
176
+ "requests": res.requests})
177
+ return 0
178
+ print(f"OmniRank {__version__} — Search Console {args.site} {args.start}..{args.end} "
179
+ f"({args.type}; dimensions: {', '.join(args.dimensions)})")
180
+ print(f" {len(rows)} row(s) in {res.requests} request(s)"
181
+ + (f"; {res.skipped} malformed row(s) skipped" if res.skipped else "")
182
+ + ("; TRUNCATED at --max-rows, more rows may exist" if res.truncated else ""))
183
+ for row in rows[:args.top]:
184
+ print(scrub_registered(f" {' | '.join(row['keys'])} clicks {row['clicks']:g} "
185
+ f"impressions {row['impressions']:g} ctr {row['ctr']:.3f} "
186
+ f"position {row['position']:.1f}"))
187
+ if len(rows) > args.top:
188
+ print(f" …and {len(rows) - args.top} more (use --json for every row)")
189
+ return 0
190
+
191
+
192
+ def _read_urls(args) -> list[str]:
193
+ urls = list(args.url or [])
194
+ if args.urls_file:
195
+ p = Path(args.urls_file)
196
+ try:
197
+ if p.stat().st_size > MAX_URLS_FILE:
198
+ raise UsageError(f"{args.urls_file} is larger than {MAX_URLS_FILE} bytes")
199
+ urls += [line.strip() for line in p.read_text(encoding="utf-8").splitlines()]
200
+ except OSError as exc:
201
+ raise UsageError(f"cannot read {args.urls_file}: {exc.strerror or exc}") from None
202
+ except UnicodeDecodeError:
203
+ raise UsageError(f"{args.urls_file} is not UTF-8 text") from None
204
+ urls = [u for u in urls if u and not u.startswith("#")]
205
+ if not urls:
206
+ raise UsageError("give at least one URL (--url or --urls-file)")
207
+ return urls
208
+
209
+
210
+ def _inspect(args, root: Path) -> int:
211
+ validate_property(args.site)
212
+ urls = _read_urls(args)
213
+ if not 1 <= args.max <= URL_INSPECTION_DAILY_LIMIT_PER_SITE:
214
+ raise UsageError(f"--max must be 1..{URL_INSPECTION_DAILY_LIMIT_PER_SITE}")
215
+ quota = InspectionQuota(root)
216
+ quota.remaining(args.site) # fail closed on an unreadable quota file first
217
+ client = _api(root, [SCOPE_GSC_READONLY])
218
+ res = inspect_batch(client, args.site, urls, quota=quota, max_urls=args.max)
219
+ data = {"site": args.site, "results": res.results, "errors": res.errors,
220
+ "not_inspected": res.not_inspected, "outside_property": res.outside_property,
221
+ "stopped_reason": res.stopped_reason or None,
222
+ "quota_used_today_locally": quota.used(args.site), "quota_limit": quota.limit}
223
+ if args.json:
224
+ _emit(data)
225
+ else:
226
+ print(f"OmniRank {__version__} — URL Inspection {args.site}")
227
+ for r in res.results:
228
+ print(scrub_registered(f" {r['url']} {r['verdict'] or '?'} "
229
+ f"{r['coverageState'] or '?'}"))
230
+ for e in res.errors:
231
+ print(redact(f" ERROR {e['url']}: {e['error']}"))
232
+ if res.outside_property:
233
+ print(f" {len(res.outside_property)} URL(s) not under the property were skipped")
234
+ if res.stopped_reason:
235
+ print(redact(f" stopped: {res.stopped_reason}"))
236
+ if res.not_inspected:
237
+ print(f" {len(res.not_inspected)} URL(s) not inspected (see --json)")
238
+ print(f" local count today: {quota.used(args.site)}/{quota.limit}")
239
+ if res.stopped_reason and not res.stopped_reason.startswith(("reached --max",
240
+ "the daily URL")):
241
+ return 2
242
+ return 1 if (res.not_inspected or res.errors) else 0
243
+
244
+
245
+ def _report(args, root: Path) -> int:
246
+ data = _read_json(args.rows, "--rows file")
247
+ dims = data.get("dimensions")
248
+ raw = data.get("rows")
249
+ if not isinstance(dims, list) or not all(isinstance(d, str) for d in dims):
250
+ raise UsageError("--rows file has no 'dimensions' list (use the output of "
251
+ "`omnirank connect gsc query --json`)")
252
+ if not isinstance(raw, list):
253
+ raise UsageError("--rows file has no 'rows' list")
254
+ rows, skipped = normalize_rows(raw, dims)
255
+ inspections = None
256
+ if args.inspections:
257
+ ins = _read_json(args.inspections, "--inspections file").get("results")
258
+ if not isinstance(ins, list):
259
+ raise UsageError("--inspections file has no 'results' list (use the output of "
260
+ "`omnirank connect gsc inspect --json`)")
261
+ inspections = ins
262
+ report = build_report(rows, dims, inspections)
263
+ report["rows_used"], report["rows_skipped"] = len(rows), skipped
264
+ if args.json:
265
+ _emit(report)
266
+ return 0
267
+ _print_report(report)
268
+ return 0
269
+
270
+
271
+ def _print_report(rep: dict) -> None:
272
+ print(f"OmniRank {__version__} — Search Console report (offline, from saved rows; "
273
+ f"{rep['rows_used']} rows, {rep['rows_skipped']} skipped)")
274
+ if rep["striking_distance"] is not None:
275
+ print(f"\n STRIKING DISTANCE (position 8-20): {len(rep['striking_distance'])}")
276
+ for s in rep["striking_distance"][:20]:
277
+ print(scrub_registered(f" {s['page']} {s['query'] or ''} pos {s['position']} "
278
+ f"impressions {s['impressions']:g}"))
279
+ if rep["low_ctr"] is not None:
280
+ flagged = rep["low_ctr"]["flagged"]
281
+ print(f"\n LOW CTR FOR ITS POSITION [heuristic]: {len(flagged)}")
282
+ print(f" rule: {rep['low_ctr']['rule']}")
283
+ for f in flagged[:20]:
284
+ print(scrub_registered(f" {f['query']} ctr {f['ctr']:.3f} vs band "
285
+ f"{f['band']} median {f['band_median_ctr']:.3f}"))
286
+ if rep["cannibalization"] is not None:
287
+ print(f"\n SEVERAL PAGES FOR ONE QUERY: {len(rep['cannibalization'])} (not an error "
288
+ "in itself; check intent)")
289
+ for c in rep["cannibalization"][:20]:
290
+ print(scrub_registered(f" {c['query']}: "
291
+ + ", ".join(p["page"] for p in c["pages"])))
292
+ for key, label in (("top_countries", "country"), ("top_devices", "device")):
293
+ if rep[key] is not None:
294
+ print(f"\n TOP {label.upper()}S")
295
+ for t in rep[key]:
296
+ print(scrub_registered(f" {t[label]} clicks {t['clicks']:g} "
297
+ f"impressions {t['impressions']:g}"))
298
+ if rep["coverage_by_template"] is not None:
299
+ print("\n INDEX COVERAGE BY TEMPLATE (from URL Inspection)")
300
+ for tpl, cell in rep["coverage_by_template"].items():
301
+ states = ", ".join(f"{k}: {v}" for k, v in cell["coverageState"].items())
302
+ print(scrub_registered(f" {tpl} {cell['urls']} URL(s) {states}"))
303
+ if rep["not_run"]:
304
+ print("\n NOT RUN")
305
+ for n in rep["not_run"]:
306
+ print(f" {n}")
307
+
308
+
309
+ def _verify_token(args, root: Path) -> int:
310
+ validate_property(args.site)
311
+ if args.method in ("ANALYTICS", "TAG_MANAGER"):
312
+ print(verification_guidance(args.site, args.method))
313
+ return 0
314
+ client = _api(root, [SCOPE_SITE_VERIFICATION])
315
+ token = client.verification_token(args.site, args.method)
316
+ print(scrub_registered(verification_instructions(args.site, args.method, token)))
317
+ return 0
318
+
319
+
320
+ def _indexing_api(args, root: Path) -> int:
321
+ assert_indexing_api_allowed(args.content_type)
322
+ _err(f"{args.content_type.strip()} pages are allowed to use the Indexing API, but "
323
+ "OmniRank does not implement Indexing API publishing (not built in this release); "
324
+ "nothing was sent. Use a sitemap, or Google's own Indexing API client.")
325
+ return 2
326
+
327
+
328
+ GSC = {"login": _login, "logout": _logout, "sites": _sites, "sitemaps": _sitemaps,
329
+ "query": _query, "inspect": _inspect, "report": _report,
330
+ "verify-token": _verify_token, "indexing-api": _indexing_api}
331
+
332
+
333
+ def run_connect(args: argparse.Namespace) -> int:
334
+ root = Path(getattr(args, "root", ".") or ".")
335
+ try:
336
+ if args.connect_command == "google-cloud":
337
+ print(cloud_setup.steps())
338
+ return 0
339
+ if not root.is_dir():
340
+ raise UsageError(f"--root {root} is not a directory")
341
+ if args.connect_command in ("ga4", "bing", "indexnow"):
342
+ return runner_more.dispatch(args, root)
343
+ if args.connect_command in ("yandex", "naver"):
344
+ return runner_regional.dispatch(args, root)
345
+ return GSC[args.gsc_command](args, root)
346
+ except IndexingApiRefused as exc:
347
+ _err(exc)
348
+ return 2
349
+ except (UsageError, GscError, google_auth.AuthError, ApiError, ConfirmError,
350
+ *runner_more.ERRORS, *runner_regional.ERRORS) as exc:
351
+ _err(exc)
352
+ return 2
353
+ except KeyboardInterrupt:
354
+ _err("interrupted")
355
+ return 130
356
+ except Exception as exc: # noqa: BLE001 - never let a traceback carry a secret out
357
+ _err(f"unexpected error ({type(exc).__name__}): {exc}")
358
+ return 2
359
+
360
+
361
+ def _fix_gitignore(args) -> int:
362
+ root = Path(args.root)
363
+ if doctor.gitignore_has_entry(root):
364
+ print(f"{root / '.gitignore'} already ignores .omnirank/; nothing to change.")
365
+ return 0
366
+ action, addition = doctor.gitignore_fix_action(root)
367
+ # --fix-gitignore is the explicit request to write; the y/N (or --yes) still applies.
368
+ return confirm_and_run(action, send=True, yes=args.yes, log=ActionLog(root),
369
+ execute=lambda: doctor.append_gitignore(root, addition))
370
+
371
+
372
+ def run_doctor(args: argparse.Namespace) -> int:
373
+ fix_code = 0
374
+ if args.fix_gitignore:
375
+ try:
376
+ fix_code = _fix_gitignore(args)
377
+ except (ConfirmError, OSError) as exc:
378
+ _err(exc)
379
+ return 2
380
+ try:
381
+ result = doctor.run(args.root, config_path=args.config, offline=args.offline)
382
+ except Exception as exc: # noqa: BLE001
383
+ _err(f"doctor failed ({type(exc).__name__}): {exc}")
384
+ return 2
385
+ if args.json:
386
+ print(json.dumps(redact_obj(result), indent=2, ensure_ascii=False))
387
+ else:
388
+ print(doctor.format_text(result, __version__))
389
+ if fix_code:
390
+ return fix_code
391
+ return 1 if result["problems"] else 0
392
+
393
+
394
+ def add_parsers(sub) -> None:
395
+ connect = sub.add_parser(
396
+ "connect", help="Connectors: Google Search Console, GA4, Bing Webmaster, IndexNow, "
397
+ "Yandex Webmaster, Naver checklist "
398
+ "(read-only by default; writes are dry runs unless --send, and need "
399
+ "y/N or --yes)")
400
+ csub = connect.add_subparsers(dest="connect_command", required=True)
401
+ csub.add_parser("google-cloud", help="Print the guided Google Cloud setup steps")
402
+
403
+ gsc = csub.add_parser("gsc", help="Google Search Console")
404
+ gsub = gsc.add_subparsers(dest="gsc_command", required=True)
405
+
406
+ def p(name, help_text):
407
+ parser = gsub.add_parser(name, help=help_text)
408
+ parser.add_argument("--root", default=".",
409
+ help="Project root: the action log and quota count go in "
410
+ "<root>/.omnirank/, and credentials inside it are refused "
411
+ "(default: .)")
412
+ return parser
413
+
414
+ login = p("login", "Log in with a Desktop OAuth client (loopback redirect, PKCE); saves a "
415
+ "refresh token outside the project, mode 0600")
416
+ login.add_argument("--client-file", required=True, metavar="PATH",
417
+ help="Desktop app OAuth client JSON, stored outside the project")
418
+ login.add_argument("--write-scope", action="store_true",
419
+ help="Also request the read/write Search Console scope (sitemap "
420
+ "submit/delete)")
421
+ login.add_argument("--verification-scope", action="store_true",
422
+ help="Also request siteverification.verify_only (verify-token)")
423
+ login.add_argument("--analytics-scope", action="store_true",
424
+ help="Also request analytics.readonly (GA4 reports)")
425
+ login.add_argument("--device", action="store_true",
426
+ help="Use the OAuth device flow (refused: Google's device flow does not "
427
+ "accept Search Console scopes)")
428
+ login.add_argument("--open-browser", action="store_true",
429
+ help="Open the consent URL in the default browser")
430
+ p("logout", "Delete the saved login (the token cache)")
431
+ sites = p("sites", "List the properties this credential can see")
432
+ sites.add_argument("--json", action="store_true")
433
+
434
+ sm = p("sitemaps", "List, get, submit or delete sitemaps")
435
+ smsub = sm.add_subparsers(dest="sitemaps_command", required=True)
436
+ for name, help_text in (("list", "List submitted sitemaps"),
437
+ ("get", "Show one sitemap"),
438
+ ("submit", "Submit a sitemap (WRITE: dry run unless --send)"),
439
+ ("delete", ("Remove a sitemap from Search Console (WRITE: dry "
440
+ "run unless --send)"))):
441
+ s = smsub.add_parser(name, help=help_text)
442
+ s.add_argument("--site", required=True,
443
+ help="Property: https://host/ (with trailing slash) or sc-domain:host")
444
+ s.add_argument("--root", default=".", help="Project root (default: .)")
445
+ if name != "list":
446
+ s.add_argument("--sitemap", required=True, metavar="URL",
447
+ help="Full sitemap URL under the property")
448
+ if name in ("submit", "delete"):
449
+ s.add_argument("--send", action="store_true",
450
+ help="Actually send it (after y/N). Without it: dry run")
451
+ s.add_argument("--yes", action="store_true",
452
+ help="Confirm in advance (non-interactive). The request is still "
453
+ "printed first")
454
+ else:
455
+ s.add_argument("--json", action="store_true")
456
+
457
+ q = p("query", "Search Analytics query, paginated with startRow")
458
+ q.add_argument("--site", required=True)
459
+ q.add_argument("--start", required=True, metavar="YYYY-MM-DD")
460
+ q.add_argument("--end", required=True, metavar="YYYY-MM-DD")
461
+ q.add_argument("--dimensions", nargs="+", default=["query"],
462
+ help="query, page, country, device, date, searchAppearance (default: query)")
463
+ q.add_argument("--type", default="web",
464
+ help="web, image, video, news, discover, googleNews (default: web)")
465
+ q.add_argument("--data-state", choices=["final", "all"], default=None)
466
+ q.add_argument("--max-rows", type=int, default=100_000,
467
+ help="Stop after this many rows (default 100000)")
468
+ q.add_argument("--top", type=int, default=25, help="Rows shown in text mode (default 25)")
469
+ q.add_argument("--json", action="store_true",
470
+ help="Every row as JSON (input for `connect gsc report --rows`)")
471
+
472
+ i = p("inspect", "URL Inspection, with a local per-property daily quota count")
473
+ i.add_argument("--site", required=True)
474
+ i.add_argument("--url", action="append", metavar="URL", help="A URL (repeatable)")
475
+ i.add_argument("--urls-file", metavar="PATH",
476
+ help="One URL per line, highest priority first")
477
+ i.add_argument("--max", type=int, default=20,
478
+ help="Inspect at most this many URLs this run (default 20)")
479
+ i.add_argument("--json", action="store_true")
480
+
481
+ r = p("report", "Derived reports from saved rows (offline): striking distance, low CTR, "
482
+ "cannibalization, countries/devices, coverage by template")
483
+ r.add_argument("--rows", required=True, metavar="PATH",
484
+ help="Output of `omnirank connect gsc query --json`")
485
+ r.add_argument("--inspections", metavar="PATH",
486
+ help="Output of `omnirank connect gsc inspect --json`")
487
+ r.add_argument("--json", action="store_true")
488
+
489
+ v = p("verify-token", "Get a verification token from Google and print exact placement "
490
+ "instructions (does not verify)")
491
+ v.add_argument("--site", required=True)
492
+ v.add_argument("--method", required=True,
493
+ choices=["FILE", "META", "DNS_TXT", "ANALYTICS", "TAG_MANAGER"],
494
+ help="FILE, META (URL-prefix) or DNS_TXT (sc-domain:) get a token from "
495
+ "Google; ANALYTICS and TAG_MANAGER print guidance only (URL-prefix)")
496
+
497
+ ix = p("indexing-api", "Check whether a content type may use the Google Indexing API "
498
+ "(only JobPosting and BroadcastEvent; nothing is sent)")
499
+ ix.add_argument("--content-type", required=True, metavar="TYPE")
500
+
501
+ runner_more.add_parsers(csub)
502
+ runner_regional.add_parsers(csub)
503
+
504
+ doc = sub.add_parser("doctor", help="Check Python, dependencies, config, credentials and "
505
+ "connector access. Never prints a secret")
506
+ doc.add_argument("--root", default=".", help="Project root (default: .)")
507
+ doc.add_argument("--config", help="Path to omnirank.config.json")
508
+ doc.add_argument("--offline", action="store_true",
509
+ help="Make no network request, even when credentials exist")
510
+ doc.add_argument("--json", action="store_true")
511
+ doc.add_argument("--fix-gitignore", action="store_true",
512
+ help="Append the line `.omnirank/` to <root>/.gitignore after printing "
513
+ "the change and asking y/N (logged to .omnirank/connect-log.jsonl)")
514
+ doc.add_argument("--yes", action="store_true",
515
+ help="With --fix-gitignore: confirm in advance (non-interactive)")
@@ -0,0 +1,59 @@
1
+ """CLI handler for `omnirank connect ga4 ai-referrals` (same conventions as runner_more:
2
+ exit 0 done, 1 TRUNCATED, 2 usage/auth/API failure; inputs are validated before any
3
+ credential is resolved or request is sent)."""
4
+ from __future__ import annotations
5
+
6
+ from collections.abc import Callable
7
+ from pathlib import Path
8
+
9
+ from .. import __version__
10
+ from . import ga4, ga4_ai
11
+
12
+
13
+ def run(args, root: Path, make_client: Callable[[Path], ga4.Ga4Client],
14
+ emit: Callable[[object], None]) -> int:
15
+ days = ga4_ai.parse_since(args.since)
16
+ ga4.validate_property_id(args.property)
17
+ referrers = ga4.load_ai_referrers()
18
+ data = ga4_ai.ai_vs_organic(make_client(root), args.property, days, referrers)
19
+ code = 1 if data["truncated"] else 0
20
+ if args.json:
21
+ emit(data)
22
+ return code
23
+ print(f"OmniRank {__version__} — GA4 AI-assistant referrals vs organic search "
24
+ f"{data['property']} {data['startDate']}..{data['endDate']} (read-only Data API)")
25
+ ai, org = data["ai"]["totals"], data["organic"]["totals"]
26
+ print(f" AI ASSISTANT REFERRALS: at least {ai['sessions']:g} session(s), "
27
+ f"{ai['engagedSessions']:g} engaged, {ai['keyEvents']:g} key event(s)")
28
+ for a in data["ai"]["by_assistant"]:
29
+ print(f" {a['name']}: at least {a['sessions']:g} session(s), "
30
+ f"{a['engagedSessions']:g} engaged, {a['keyEvents']:g} key event(s)")
31
+ print(f" Organic Search: {org['sessions']:g} session(s), {org['engagedSessions']:g} "
32
+ f"engaged, {org['keyEvents']:g} key event(s)")
33
+ if data["ai_sessions_per_100_organic"] is not None:
34
+ print(f" At least {data['ai_sessions_per_100_organic']:g} AI-referred session(s) per "
35
+ "100 Organic Search sessions")
36
+ if data["trend"]:
37
+ for label, part in (("first half", data["trend"]["first_half"]),
38
+ ("second half", data["trend"]["second_half"])):
39
+ print(f" {label} {part['start']}..{part['end']}: AI at least "
40
+ f"{part['ai_sessions']:g}, organic {part['organic_sessions']:g} session(s)")
41
+ if data["skipped_rows"]:
42
+ print(f" {data['skipped_rows']} row(s) skipped (malformed, unlisted source or a date "
43
+ "outside the window)")
44
+ if data["thresholded"]:
45
+ print(" Google applied thresholding to this report: small numbers may be hidden.")
46
+ if data["truncated"]:
47
+ print(f" TRUNCATED at {ga4_ai.MAX_ROWS} rows: the totals above are incomplete.")
48
+ print(f" {data['caveat']}")
49
+ return code
50
+
51
+
52
+ def add_parser(gsub, add_root: Callable) -> None:
53
+ p = gsub.add_parser("ai-referrals", help="AI-assistant referral sessions vs the Organic "
54
+ "Search trend (read-only; a LOWER BOUND)")
55
+ add_root(p)
56
+ p.add_argument("--property", required=True, help="GA4 property ID (digits)")
57
+ p.add_argument("--since", default="28d", metavar="Nd",
58
+ help=f"Days back from yesterday, 1d..{ga4_ai.MAX_DAYS}d (default 28d)")
59
+ p.add_argument("--json", action="store_true")