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,309 @@
1
+ """CLI for `omnirank track discover`: turn the owner's own Search Console queries into a
2
+ prompt set file for `omnirank track ai --prompts`.
3
+
4
+ Nothing is sent to any LLM and nothing is spent. Order of events:
5
+
6
+ 1. read the queries (a Search Console CSV export through the blog pack's hardened loader,
7
+ or the read-only Search Analytics API for ``--property``);
8
+ 2. select prompts (``discover.py``: deterministic, capped, de-duplicated);
9
+ 3. print the prompts and the cost estimate of RUNNING them with `track ai` (the same
10
+ estimator, with the breakdown, confidence note, assumptions and optional ``--budget``);
11
+ 4. only with ``--out FILE``: show exactly what will be written, ask ``[y/N]`` (``--yes``
12
+ skips the question; a non-terminal without ``--yes`` is refused), log ``approved`` to
13
+ ``.omnirank/connect-log.jsonl`` BEFORE writing, then write atomically.
14
+
15
+ The output path must stay inside ``--root`` (no ``..``, no symlinked component, no missing
16
+ directory is created), end in ``.json``, and not look like an env file, key, credential or
17
+ lock file. An existing file is replaced only with ``--force``.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import hashlib
22
+ import json
23
+ import re
24
+ from pathlib import Path
25
+
26
+ from ..connect import google_auth
27
+ from ..connect.confirm import ActionLog, ConfirmError
28
+ from ..connect.constants import GOOGLE_API_HOSTS, SCOPE_GSC_READONLY
29
+ from ..connect.gsc import GscClient, validate_property
30
+ from ..connect.http import ApiClient
31
+ from ..packs import gsc as csv_gsc
32
+ from . import ai_prompts, analysis, cost, estimate_view, history, storage
33
+ from . import constants as C
34
+ from . import discover as D
35
+ from . import discover_constants as DC
36
+ from .runner import UsageError, _config, _engines, _max_output
37
+
38
+ _DENY_NAME = re.compile(
39
+ r"(?i)(?:\.env.*|package-lock\.json|npm-shrinkwrap\.json|package\.json|composer\.json|"
40
+ r"tsconfig(?:\..+)?\.json|deno\.json|omnirank\.config\.json|.+\.config\.json|"
41
+ r".*(?:^|[._-])(?:id_rsa|id_ed25519|credentials?|secrets?|private[-_]?key|"
42
+ r"service[-_]?account)(?:[._-].*)?)")
43
+ _DENY_DIRS = (".git", ".omnirank", "node_modules") # compared casefolded
44
+ _LABELS = {"unsafe": "unsafe (control or invisible characters, too long)",
45
+ "injection_like": "that look like instructions to an AI",
46
+ "pii_like": "that look like personal data",
47
+ "low_impressions": "below the impressions floor",
48
+ "unclassified": "without a cue (unclassified)", "duplicate": "duplicate"}
49
+
50
+
51
+ def _same_dir(cur: Path, other: Path) -> bool:
52
+ try:
53
+ return other.exists() and cur.samefile(other)
54
+ except OSError:
55
+ return False
56
+
57
+
58
+ def _existing_is_prompt_set(target: Path) -> bool:
59
+ try:
60
+ ai_prompts.load_prompts(target)
61
+ except ai_prompts.PromptError:
62
+ return False
63
+ return True
64
+
65
+
66
+ def confine_out(root: Path, out: str, *, force: bool) -> tuple[Path, str]:
67
+ """(directory, file name) for ``--out`` or UsageError. Nothing is created."""
68
+ if not isinstance(out, str) or not out or "\x00" in out:
69
+ raise UsageError("--out needs a file name like prompts.json")
70
+ p = Path(out)
71
+ if ".." in p.parts:
72
+ raise UsageError("--out must not contain '..'")
73
+ rroot = root.resolve()
74
+ if p.is_absolute():
75
+ for base, cand in ((root, p), (rroot, p), (rroot, p.parent.resolve() / p.name)):
76
+ try:
77
+ rel = cand.relative_to(base)
78
+ break
79
+ except ValueError:
80
+ continue
81
+ else:
82
+ raise UsageError(f"--out {analysis.printable(out, limit=200)} is outside the "
83
+ f"project root {root}")
84
+ else:
85
+ rel = p
86
+ if not rel.parts:
87
+ raise UsageError("--out needs a file name like prompts.json")
88
+ cur = root
89
+ for part in rel.parts[:-1]:
90
+ if part.casefold() in _DENY_DIRS:
91
+ raise UsageError(f"--out may not write inside {part}/")
92
+ cur = cur / part
93
+ if cur.is_symlink():
94
+ raise UsageError(f"{cur} is a symlink; refusing to write through it")
95
+ if not cur.is_dir():
96
+ raise UsageError(f"the directory {cur} does not exist (it is not created)")
97
+ if any(_same_dir(cur, root / d) for d in _DENY_DIRS):
98
+ raise UsageError(f"{cur} is the same directory as a protected one "
99
+ f"({', '.join(_DENY_DIRS)}); refusing")
100
+ name = rel.parts[-1]
101
+ try:
102
+ storage._check_name(name)
103
+ except storage.StorageError:
104
+ raise UsageError("--out must be a file name made of letters, digits, '.', '_' or "
105
+ "'-', ending in .json") from None
106
+ if not name.endswith(".json") or _DENY_NAME.fullmatch(name):
107
+ raise UsageError(f"--out {name!r} is not allowed (.json only; not an env file, key, "
108
+ "credential, lock file or project/tool config)")
109
+ if not cur.resolve().is_relative_to(rroot):
110
+ raise UsageError(f"{cur} resolves outside the project root")
111
+ target = cur / name
112
+ if target.is_symlink():
113
+ raise UsageError(f"{target} is a symlink; refusing to write through it")
114
+ if target.exists():
115
+ if not target.is_file():
116
+ raise UsageError(f"{target} exists and is not a regular file")
117
+ if not force:
118
+ raise UsageError(f"{target} already exists; pass --force to overwrite it")
119
+ if not _existing_is_prompt_set(target):
120
+ raise UsageError(f"{target} exists and is not a valid prompt set file; "
121
+ "refusing to overwrite it even with --force (choose another "
122
+ "name)")
123
+ return cur, name
124
+
125
+
126
+ def _stats_from_args(args, root: Path) -> tuple[list[D.QueryStat], list[str]]:
127
+ if bool(args.gsc_csv) == bool(args.property):
128
+ raise UsageError("pass exactly one of --gsc-csv FILE or --property SITE")
129
+ notes: list[str] = []
130
+ if args.gsc_csv:
131
+ try:
132
+ table = csv_gsc.load_export(args.gsc_csv)
133
+ except csv_gsc.GscError as exc:
134
+ raise UsageError(str(exc)) from None
135
+ if table.bad_rows:
136
+ notes.append(f"{table.bad_rows} row(s) of the CSV could not be read and were "
137
+ "ignored")
138
+ if table.truncated:
139
+ notes.append(f"only the first {csv_gsc.MAX_ROWS} rows were read")
140
+ return D.stats_from_table(table), notes
141
+ site = validate_property(args.property)
142
+ days = history.parse_since(args.since)
143
+ start, end = history.window(days, args.end)
144
+ source = google_auth.resolve_token_source([SCOPE_GSC_READONLY], project_root=root)
145
+ client = GscClient(ApiClient(source.token, allowed_hosts=GOOGLE_API_HOSTS))
146
+ result = client.query(site, start, end, ["query"], max_rows=DC.GSC_QUERY_ROWS)
147
+ if result.truncated:
148
+ notes.append(f"only the top {DC.GSC_QUERY_ROWS} queries by clicks were read")
149
+ if result.skipped:
150
+ notes.append(f"{result.skipped} row(s) from the API were invalid and were ignored")
151
+ notes.append(f"Search Console {site} {start} .. {end} (read-only)")
152
+ return D.stats_from_gsc_rows(result.rows), notes
153
+
154
+
155
+ def _show_prompts(sel: D.Selection) -> None:
156
+ for p in sel.prompts:
157
+ src = sel.sources[p.id]
158
+ imp = "n/a" if src.impressions is None else src.impressions
159
+ print(f" {p.id:<14} {p.category:<11} {analysis.printable(p.text, limit=400)}"
160
+ f" (clicks {src.clicks}, impressions {imp})")
161
+
162
+
163
+ def run_discover(args, root: Path) -> int:
164
+ dest = confine_out(root, args.out, force=args.force) if args.out is not None else None
165
+ raw = _config(root, args.config)
166
+ track_cfg = (raw or {}).get("track")
167
+ try:
168
+ brand = ai_prompts.brand_from_config(raw, brand=args.brand)
169
+ except ai_prompts.PromptError:
170
+ brand = None
171
+ names = _engines(args.engines, estimate=True)
172
+ if not 1 <= args.runs <= 50:
173
+ raise UsageError("--runs must be 1..50")
174
+ max_output = _max_output(args.max_output_tokens)
175
+ budget = estimate_view.parse_budget(args.budget) if args.budget is not None else None
176
+ prices = {e: cost.resolve_price(e, None, track_cfg) for e in names}
177
+ try:
178
+ local = D.local_term_tokens(args.local_term or [])
179
+ stats, notes = _stats_from_args(args, root)
180
+ sel = D.select(stats, brand, per_category=args.per_category,
181
+ max_prompts=args.max_prompts, min_impressions=args.min_impressions,
182
+ local_terms=local)
183
+ except D.DiscoverError as exc:
184
+ raise UsageError(str(exc)) from None
185
+ print(f"Read {len(stats)} query row(s) from your own Search Console data.")
186
+ for n in notes:
187
+ print(f" note: {analysis.printable(n)}")
188
+ if brand is None:
189
+ print(" note: no brand name (set site.name in the config or pass --brand), so no "
190
+ "query is treated as branded")
191
+ if sel.skipped:
192
+ print("Skipped: " + ", ".join(f"{n} {_LABELS[k]}" for k, n in sel.skipped.items()))
193
+ if not sel.prompts:
194
+ print("No prompts could be generated from these queries (no question, branded, "
195
+ "comparison or local cue matched, or the impressions floor removed them).")
196
+ print("Nothing was written.")
197
+ return 1
198
+ print(f"\nFound {len(sel.prompts)} prompt(s); each is one of your own queries"
199
+ + (" (a how-to gets a trailing '?')" if any(
200
+ p.category == "how-to" for p in sel.prompts) else "") + ":")
201
+ _show_prompts(sel)
202
+ print(f" {DC.FILTER_NOTE}.")
203
+ print(f" [heuristic] categories come from cue words ({DC.CHECKED_ON}); "
204
+ f"{DC.TEMPLATE_NOTE.split(': ', 1)[1]}.")
205
+ prompts = ai_prompts.parse_prompts(D.prompt_file(sel.prompts))
206
+ est = cost.estimate_batch(prompts, prices, runs=args.runs, max_output=max_output)
207
+ print(f"\nWhat it would cost to RUN these with `omnirank track ai` ({args.runs} run(s) "
208
+ "per prompt per engine; nothing is sent by this command):")
209
+ print(cost.format_estimate(est))
210
+ print(estimate_view.format_details(prompts, prices, est, runs=args.runs,
211
+ max_output=max_output))
212
+ if budget is not None:
213
+ print("\n" + estimate_view.format_what_if(
214
+ estimate_view.what_if(prompts, prices, budget, max_output=max_output)))
215
+ if dest is None:
216
+ print("\nNothing was written. Re-run with --out FILE to save these prompts "
217
+ "(you will be asked to confirm).")
218
+ return 0
219
+ return _write(args, root, prompts, sel, *dest)
220
+
221
+
222
+ def _write(args, root: Path, prompts, sel, directory: Path, name: str) -> int:
223
+ directory, name = confine_out(root, str(Path(directory) / name), force=args.force)
224
+ target = directory / name
225
+ text = json.dumps(D.prompt_file(prompts), ensure_ascii=False, indent=2) + "\n"
226
+ digest = hashlib.sha256(text.encode("utf-8")).hexdigest()[:16]
227
+ existed = target.exists()
228
+ summary = (f"write {len(prompts)} prompt(s) to {target}"
229
+ + (" (overwrites the existing file)" if existed else "")
230
+ + f"; sha256 {digest}")
231
+ log = ActionLog(root)
232
+
233
+ def entry(outcome: str, **extra) -> dict:
234
+ return {"ts": _now(), "connector": "track-discover", "action": "write-prompts",
235
+ "method": "WRITE", "url": str(target), "summary": summary, "body": None,
236
+ "outcome": outcome, **extra}
237
+
238
+ print(f"\nWill write {len(prompts)} prompt(s) to {target}"
239
+ + (" (this will overwrite the existing file)" if existed else "")
240
+ + f" (sha256 {digest}); nothing else is changed.")
241
+ if not args.yes:
242
+ import sys
243
+ if not sys.stdin.isatty():
244
+ log.append(entry("refused", reason="stdin is not a terminal and --yes was not given"))
245
+ raise UsageError("refusing to write: stdin is not a terminal, so there is no one "
246
+ "to confirm. Re-run interactively, or pass --yes to confirm in "
247
+ "advance.")
248
+ print("Write this? [y/N] ", end="", flush=True)
249
+ if sys.stdin.readline().strip().lower() not in ("y", "yes"):
250
+ log.append(entry("declined"))
251
+ print("Nothing was written.")
252
+ return 1
253
+ log.append(entry("approved"))
254
+ try:
255
+ storage.write_text(directory, name, text)
256
+ except (storage.StorageError, OSError) as exc:
257
+ log.append(entry("failed", error=str(exc)[:300]))
258
+ raise UsageError(f"could not write {target}: {exc}") from None
259
+ try:
260
+ log.append(entry("written"))
261
+ except ConfirmError as exc:
262
+ print(f"Wrote {target}.")
263
+ raise UsageError(f"the file WAS written, but the action log could not record it "
264
+ f"({exc})") from None
265
+ print(f"Wrote {target}. Next: omnirank track ai --prompts {target.name} --estimate")
266
+ return 0
267
+
268
+
269
+ def _now() -> str:
270
+ from .runner import _now as now
271
+ return now()
272
+
273
+
274
+ def add_parser(tsub) -> None:
275
+ d = tsub.add_parser(
276
+ "discover", help="Generate a prompt set for `track ai` from your own Search Console "
277
+ "queries (no LLM; prints the cost estimate first; --out needs "
278
+ "confirmation)")
279
+ d.add_argument("--gsc-csv", metavar="FILE", help="Search Console export with a Query column")
280
+ d.add_argument("--property", metavar="SITE",
281
+ help="Read the queries from Search Console (read-only API) instead")
282
+ d.add_argument("--since", default="28d", metavar="Nd", help="With --property: window "
283
+ "length (default 28d)")
284
+ d.add_argument("--end", metavar="YYYY-MM-DD", help="With --property: last day")
285
+ d.add_argument("--out", metavar="FILE", help="Write the prompt set here (inside --root; "
286
+ "asks before writing)")
287
+ d.add_argument("--force", action="store_true", help="Allow --out to replace a file")
288
+ d.add_argument("--yes", action="store_true", help="Confirm the write in advance (the "
289
+ "estimate and prompts are still printed)")
290
+ d.add_argument("--brand", help="Brand name (default: site.name in the config)")
291
+ d.add_argument("--per-category", type=int, default=DC.DEFAULT_PER_CATEGORY, metavar="N",
292
+ help=f"At most N prompts per category (default {DC.DEFAULT_PER_CATEGORY})")
293
+ d.add_argument("--max-prompts", type=int, default=DC.DEFAULT_MAX_PROMPTS, metavar="N",
294
+ help=f"At most N prompts in total (default {DC.DEFAULT_MAX_PROMPTS}, "
295
+ f"max {ai_prompts.MAX_PROMPTS})")
296
+ d.add_argument("--min-impressions", type=int, default=DC.DEFAULT_MIN_IMPRESSIONS,
297
+ metavar="N", help="Ignore queries with fewer impressions (default "
298
+ f"{DC.DEFAULT_MIN_IMPRESSIONS}; only when the export "
299
+ "has impressions)")
300
+ d.add_argument("--local-term", action="append", metavar="TERM",
301
+ help="A place name that makes a query local, e.g. your city (repeatable)")
302
+ d.add_argument("--engines", metavar="LIST", help="Engines for the estimate (default all)")
303
+ d.add_argument("--runs", type=int, default=5, help="Runs per prompt for the estimate "
304
+ "(default 5)")
305
+ d.add_argument("--max-output-tokens", type=int, default=C.DEFAULT_MAX_OUTPUT_TOKENS,
306
+ help="Answer cap used in the estimate")
307
+ d.add_argument("--budget", metavar="USD", help="Also print a what-if for this budget")
308
+ d.add_argument("--root", default=".", help="Project root (--out must stay inside it)")
309
+ d.add_argument("--config", help="Config file (default <root>/omnirank.config.json)")
@@ -0,0 +1,95 @@
1
+ """Cue words and the fixed template text for `omnirank track discover`.
2
+
3
+ Prompt text is built ONLY from the owner's own Search Console query text plus the fixed
4
+ strings in ``TEMPLATES`` below. Those strings are the only wording OmniRank itself adds to
5
+ a prompt; they are listed here so they can be audited.
6
+
7
+ The cue lists are [heuristic], hand-made on 2026-11-29 from common English and Bengali
8
+ usage. They were NOT checked against a corpus or a dictionary, and they will misclassify
9
+ some queries (a query that matches no cue is skipped and counted, never guessed).
10
+ All entries are stored in the same normal form as the query text (NFKC, casefold).
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import unicodedata
15
+
16
+ CHECKED_ON = "2026-11-29"
17
+ CUES_NOTE = ("[heuristic] hand-made English and Bengali cue lists (2026-11-29); not checked "
18
+ "against a corpus; a query that matches no cue is skipped, never guessed")
19
+
20
+
21
+ def _n(text: str) -> str:
22
+ return unicodedata.normalize("NFKC", text).casefold()
23
+
24
+
25
+ def _set(*words: str) -> frozenset[str]:
26
+ return frozenset(_n(w) for w in words)
27
+
28
+
29
+ # --- TEMPLATE TEXT -------------------------------------------------------------------------
30
+ # The ONLY wording OmniRank adds. {query} is the owner's own query, NFC-normalized with
31
+ # whitespace collapsed. A how-to prompt gets a trailing "?" unless the query already ends
32
+ # with a question mark; every other category is the query unchanged.
33
+ TEMPLATES = {
34
+ "branded": "{query}",
35
+ "comparison": "{query}",
36
+ "how-to": "{query}?",
37
+ "local": "{query}",
38
+ }
39
+ TEMPLATE_NOTE = ("TEMPLATE TEXT: the only wording OmniRank adds to a generated prompt is "
40
+ "the trailing question mark of a how-to prompt; everything else is the "
41
+ "owner's own query")
42
+ QUESTION_MARKS = ("?", "?")
43
+
44
+ # --- question cues -----------------------------------------------------------------------------
45
+ # English: the FIRST word of the query. Bengali: ANY word (Bengali is verb-final and the
46
+ # interrogative can sit anywhere in the sentence).
47
+ QUESTION_WORDS_EN = _set(
48
+ "who", "whom", "whose", "what", "which", "when", "where", "why", "how", "is", "are",
49
+ "am", "was", "were", "can", "could", "do", "does", "did", "should", "would", "will",
50
+ "shall", "has", "have", "may", "might")
51
+ QUESTION_WORDS_BN = _set(
52
+ "কেন", "কীভাবে", "কিভাবে", "কি", "কী", "কোথায়", "কোথায়", "কখন", "কে", "কাকে", "কার",
53
+ "কোন", "কোনটি", "কোনটা", "কত", "কতটা", "কতগুলো", "কেমন", "কিসের", "কিসে")
54
+
55
+ # --- comparison cues ---------------------------------------------------------------------------
56
+ COMPARISON_TOKENS = _set("vs", "versus", "alternative", "alternatives", "comparison",
57
+ "compare", "compared", "বনাম", "বিকল্প", "তুলনা")
58
+ COMPARISON_PHRASES = (tuple(_n(w) for w in ("better", "than")),)
59
+
60
+ # --- local cues --------------------------------------------------------------------------------
61
+ # Owner-supplied terms (`--local-term`, e.g. a city name) are added to these at run time.
62
+ LOCAL_PHRASES = tuple(tuple(_n(w) for w in phrase) for phrase in (
63
+ ("near", "me"), ("nearby",), ("closest",), ("open", "now"),
64
+ ("কাছাকাছি",), ("আশেপাশে",), ("নিকটবর্তী",), ("আমার", "কাছে")))
65
+
66
+ # --- filters for hostile or private query text ------------------------------------------------
67
+ # Search Console queries are typed by STRANGERS, and the prompts are sent to third-party LLM
68
+ # APIs. These filters are a best-effort [heuristic] (2026-11-29), NOT a guarantee: the owner
69
+ # must review the generated file before running `track ai`.
70
+ INJECTION_PATTERNS = ( # matched on the NFKC-casefolded query
71
+ r"ignore\s+(?:all\s+|any\s+)?(?:previous|prior|above)\s+instructions",
72
+ r"\bsystem\s*:", r"\bassistant\s*:", r"\byou\s+are\s+now\b", r"disregard",
73
+ r"jailbreak", r"prompt\s+injection", r"<\|", r"`", r"\{\{", r"\}\}")
74
+ PII_PATTERNS = (
75
+ r"@", r"://",
76
+ r"\bat\b.{0,40}\bdot\s+[a-z]{2,6}\b", # "bob at example dot com"
77
+ r"\b[a-z]{2}\d{2}[a-z0-9]{10,30}\b", # IBAN-like
78
+ )
79
+ DIGIT_RUN_PATTERN = r"\d(?:[\s().+\-]*\d)*" # digits with separators between
80
+ MAX_DIGITS_IN_RUN = 6 # 7+ digits in one run (phone, card, account number)
81
+ SECRET_TOKEN_MIN = 24 # a long base64/hex-like token with a digit or mixed case
82
+ FILTER_NOTE = ("[heuristic] best-effort filters for instruction-like text and personal data "
83
+ "(2026-11-29); queries come from strangers, so REVIEW the generated file "
84
+ "before running `track ai`; prompts are sent to third-party LLM APIs")
85
+ MIN_LOCAL_TERM_CHARS = 3
86
+
87
+ # --- limits ------------------------------------------------------------------------------------
88
+ DEFAULT_PER_CATEGORY = 10
89
+ DEFAULT_MAX_PROMPTS = 40
90
+ DEFAULT_MIN_IMPRESSIONS = 10
91
+ MAX_QUERY_CHARS = 200 # longer queries are skipped (a prompt is a short question)
92
+ MAX_DIGIT_RUN = 6 # a query with 7+ digits in a row may hold a phone/account no.
93
+ MAX_LOCAL_TERMS = 20
94
+ GSC_QUERY_ROWS = 5000 # rows read with --property (top queries by clicks)
95
+ CATEGORY_ORDER = ("branded", "comparison", "how-to", "local")
@@ -0,0 +1,216 @@
1
+ """BYOK REST clients for Gemini, Claude (Anthropic), OpenAI and Perplexity.
2
+
3
+ * Keys come from the environment only (``constants.ENV_KEYS``) and are registered with
4
+ ``redact()`` the moment they are read.
5
+ * Gemini and Anthropic keys travel in a request HEADER (``x-goog-api-key`` /
6
+ ``x-api-key``); OpenAI and Perplexity use ``Authorization: Bearer``. No key is ever put
7
+ in a URL.
8
+ * Each client may only talk to its provider's host (``ApiClient(allowed_hosts=...)``),
9
+ never follows redirects, and every generation call is sent ONCE (``max_retries=0``): a
10
+ generation POST costs money, so a 429/5xx is reported, not retried.
11
+ * Parsing is defensive: a missing or odd field yields an empty text / ``None`` usage /
12
+ ``None`` citations, never a guess. ``cited_domains`` is ``None`` when the response has no
13
+ citation structure at all (the report then says "n/a"), and a list (possibly empty)
14
+ when it does.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ from dataclasses import dataclass
19
+ from urllib.parse import quote
20
+
21
+ from ..connect.http import ApiClient, ApiError
22
+ from ..connect.secrets import env_secret
23
+ from . import constants as C
24
+ from .analysis import domain_of
25
+
26
+ MAX_TEXT_CHARS = 200_000
27
+ MAX_BYTES = 5_000_000
28
+ TIMEOUT = 90.0
29
+ AUTH_STATUSES = frozenset({401, 403})
30
+ LLM_AUTH_HINT = ("check the API key in the environment variable, that it is active and "
31
+ "has billing enabled, and that the model is available to this account")
32
+
33
+
34
+ @dataclass
35
+ class Answer:
36
+ text: str
37
+ usage: dict | None
38
+ cited_domains: list[str] | None
39
+
40
+
41
+ def key_from_env(engine: str) -> str | None:
42
+ return env_secret(C.ENV_KEYS[engine])
43
+
44
+
45
+ def endpoint(engine: str, model: str) -> str:
46
+ if engine == "gemini":
47
+ return C.GEMINI_URL.format(model=quote(model, safe=""))
48
+ return {"anthropic": C.ANTHROPIC_URL, "openai": C.OPENAI_URL,
49
+ "perplexity": C.PERPLEXITY_URL}[engine]
50
+
51
+
52
+ def make_client(engine: str, key: str, **kw) -> ApiClient:
53
+ common = {"allowed_hosts": [C.ALLOWED_HOSTS[engine]], "auth_hint": LLM_AUTH_HINT,
54
+ "timeout": TIMEOUT, "max_bytes": MAX_BYTES, "max_retries": 0, **kw}
55
+ if engine == "gemini":
56
+ return ApiClient(None, header_credential=(C.GEMINI_KEY_HEADER, lambda: key), **common)
57
+ if engine == "anthropic":
58
+ return ApiClient(None, header_credential=(C.ANTHROPIC_KEY_HEADER, lambda: key),
59
+ extra_headers={"anthropic-version": C.ANTHROPIC_VERSION}, **common)
60
+ return ApiClient(lambda: key, **common)
61
+
62
+
63
+ def request_body(engine: str, model: str, prompt: str, max_output: int) -> dict:
64
+ if engine == "gemini":
65
+ return {"contents": [{"role": "user", "parts": [{"text": prompt}]}],
66
+ "tools": [{"google_search": {}}],
67
+ "generationConfig": {"maxOutputTokens": max_output}}
68
+ if engine == "anthropic":
69
+ return {"model": model, "max_tokens": max_output,
70
+ "messages": [{"role": "user", "content": prompt}],
71
+ "tools": [{"type": C.ANTHROPIC_WEB_SEARCH_TOOL, "name": "web_search",
72
+ "max_uses": C.ANTHROPIC_MAX_SEARCHES}]}
73
+ if engine == "openai":
74
+ return {"model": model, "input": prompt, "tools": [{"type": "web_search"}],
75
+ "max_output_tokens": max_output}
76
+ return {"model": model, "messages": [{"role": "user", "content": prompt}],
77
+ "max_tokens": max_output}
78
+
79
+
80
+ def ask(engine: str, client: ApiClient, model: str, prompt: str,
81
+ max_output: int) -> tuple[dict, Answer]:
82
+ """One generation call (sent once). Returns the raw JSON and the parsed answer."""
83
+ data = client.request("POST", endpoint(engine, model),
84
+ json_body=request_body(engine, model, prompt, max_output),
85
+ max_retries=0)
86
+ return data, parse(engine, data)
87
+
88
+
89
+ def is_auth_error(exc: BaseException) -> bool:
90
+ return isinstance(exc, ApiError) and exc.status in AUTH_STATUSES
91
+
92
+
93
+ # --- parsing ----------------------------------------------------------------------------------
94
+
95
+ def _int(value: object) -> int | None:
96
+ return value if isinstance(value, int) and not isinstance(value, bool) and value >= 0 \
97
+ else None
98
+
99
+
100
+ def _usage(tin: object, tout: object, searches: int) -> dict | None:
101
+ tin, tout = _int(tin), _int(tout)
102
+ if tin is None or tout is None:
103
+ return None
104
+ return {"input_tokens": tin, "output_tokens": tout, "searches": searches}
105
+
106
+
107
+ def _list(value: object) -> list:
108
+ return value if isinstance(value, list) else []
109
+
110
+
111
+ def _dict(value: object) -> dict:
112
+ return value if isinstance(value, dict) else {}
113
+
114
+
115
+ def _domains(urls: list) -> list[str]:
116
+ out: list[str] = []
117
+ for u in urls:
118
+ d = domain_of(u)
119
+ if d and d not in out:
120
+ out.append(d)
121
+ return out
122
+
123
+
124
+ def _cap(text: str) -> str:
125
+ return text[:MAX_TEXT_CHARS]
126
+
127
+
128
+ def _gemini(data: dict) -> Answer:
129
+ cands = _list(data.get("candidates"))
130
+ cand = _dict(cands[0]) if cands else {}
131
+ text = "".join(p.get("text") for p in _list(_dict(cand.get("content")).get("parts"))
132
+ if isinstance(p, dict) and isinstance(p.get("text"), str))
133
+ gm = cand.get("groundingMetadata")
134
+ cited = None
135
+ searches = 0
136
+ if isinstance(gm, dict):
137
+ urls = []
138
+ for chunk in _list(gm.get("groundingChunks")):
139
+ web = _dict(_dict(chunk).get("web"))
140
+ uri = web.get("uri")
141
+ host = domain_of(uri)
142
+ if host is not None and host in C.GEMINI_REDIRECT_HOSTS:
143
+ title = web.get("title")
144
+ uri = f"https://{title}/" if isinstance(title, str) and "/" not in title \
145
+ else None
146
+ urls.append(uri)
147
+ cited = _domains(urls)
148
+ searches = len(_list(gm.get("webSearchQueries")))
149
+ um = _dict(data.get("usageMetadata"))
150
+ out_tokens = _int(um.get("candidatesTokenCount"))
151
+ thoughts = _int(um.get("thoughtsTokenCount")) or 0
152
+ usage = _usage(um.get("promptTokenCount"),
153
+ None if out_tokens is None else out_tokens + thoughts, searches)
154
+ return Answer(_cap(text), usage, cited)
155
+
156
+
157
+ def _anthropic(data: dict) -> Answer:
158
+ parts, urls, has_cit = [], [], False
159
+ for block in _list(data.get("content")):
160
+ if not isinstance(block, dict):
161
+ continue
162
+ if block.get("type") == "web_search_tool_result":
163
+ has_cit = True
164
+ if block.get("type") == "text" and isinstance(block.get("text"), str):
165
+ parts.append(block["text"])
166
+ for c in _list(block.get("citations")):
167
+ has_cit = True
168
+ urls.append(_dict(c).get("url"))
169
+ u = _dict(data.get("usage"))
170
+ searches = _int(_dict(u.get("server_tool_use")).get("web_search_requests")) or 0
171
+ return Answer(_cap("".join(parts)), _usage(u.get("input_tokens"), u.get("output_tokens"),
172
+ searches), _domains(urls) if has_cit else None)
173
+
174
+
175
+ def _openai(data: dict) -> Answer:
176
+ parts, urls, has_cit, searches = [], [], False, 0
177
+ for item in _list(data.get("output")):
178
+ if not isinstance(item, dict):
179
+ continue
180
+ if item.get("type") == "web_search_call":
181
+ searches += 1
182
+ has_cit = True
183
+ if item.get("type") != "message":
184
+ continue
185
+ for c in _list(item.get("content")):
186
+ c = _dict(c)
187
+ if c.get("type") == "output_text" and isinstance(c.get("text"), str):
188
+ parts.append(c["text"])
189
+ for a in _list(c.get("annotations")):
190
+ a = _dict(a)
191
+ if a.get("type") == "url_citation":
192
+ has_cit = True
193
+ urls.append(a.get("url"))
194
+ u = _dict(data.get("usage"))
195
+ return Answer(_cap("".join(parts)), _usage(u.get("input_tokens"), u.get("output_tokens"),
196
+ searches), _domains(urls) if has_cit else None)
197
+
198
+
199
+ def _perplexity(data: dict) -> Answer:
200
+ choices = _list(data.get("choices"))
201
+ msg = _dict(_dict(choices[0]).get("message")) if choices else {}
202
+ text = msg.get("content") if isinstance(msg.get("content"), str) else ""
203
+ cited = None
204
+ if isinstance(data.get("citations"), list) or isinstance(data.get("search_results"), list):
205
+ urls = list(_list(data.get("citations")))
206
+ urls += [_dict(r).get("url") for r in _list(data.get("search_results"))]
207
+ cited = _domains(urls)
208
+ u = _dict(data.get("usage"))
209
+ return Answer(_cap(text), _usage(u.get("prompt_tokens"), u.get("completion_tokens"), 0),
210
+ cited)
211
+
212
+
213
+ def parse(engine: str, data: object) -> Answer:
214
+ data = data if isinstance(data, dict) else {}
215
+ return {"gemini": _gemini, "anthropic": _anthropic, "openai": _openai,
216
+ "perplexity": _perplexity}[engine](data)