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
omnirank/track/cost.py ADDED
@@ -0,0 +1,229 @@
1
+ """Cost estimates for `omnirank track ai`, computed BEFORE anything is spent.
2
+
3
+ Per call (all assumptions are documented in docs/track.md and printed with the estimate)::
4
+
5
+ input tokens = ceil(UTF-8 bytes of the prompt / BYTES_PER_TOKEN) [heuristic]
6
+ + REQUEST_OVERHEAD_TOKENS[engine] [assumed]
7
+ + search_input_tokens * ASSUMED_SEARCHES_PER_CALL [assumed/table]
8
+ output tokens = max_output (the cap sent to the API; a worst case for the answer text)
9
+ usd = input * price.input / 1e6 + output * price.output / 1e6
10
+ + price.per_search * ASSUMED_SEARCHES_PER_CALL + price.per_request
11
+
12
+ Batch = sum over prompts x runs, per engine; the engines are listed separately and only
13
+ the money is added up into a total (no blended quality number exists anywhere).
14
+ Actual cost after a call uses the API's usage fields when present (``actual_cost``),
15
+ otherwise the call's estimate.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import math
20
+ import re
21
+ from collections.abc import Iterable, Sequence
22
+ from dataclasses import dataclass
23
+
24
+ from . import constants as C
25
+
26
+ _MODEL = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,79}")
27
+ _DATE = re.compile(r"\d{4}-\d{2}-\d{2}")
28
+ _OVERRIDE_KEYS = {"model", "inputPerMTok", "outputPerMTok", "perSearch", "perRequest",
29
+ "searchInputTokens", "checkedOn", "source"}
30
+ MAX_PRICE = 10_000.0 # per MTok or per call: anything larger is a typo
31
+ _USD = re.compile(r"\d{1,6}(?:\.\d{1,6})?")
32
+
33
+
34
+ class CostError(Exception):
35
+ pass
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class Price:
40
+ engine: str
41
+ model: str
42
+ input: float
43
+ output: float
44
+ per_search: float
45
+ per_request: float
46
+ search_input_tokens: int
47
+ source: str
48
+ checked_on: str
49
+ verified: bool
50
+ overridden: bool
51
+ note: str = ""
52
+
53
+
54
+ def _money(value: object, name: str) -> float:
55
+ if isinstance(value, bool) or not isinstance(value, int | float):
56
+ raise CostError(f"track.pricing: {name} must be a number")
57
+ value = float(value)
58
+ if not math.isfinite(value) or value < 0 or value > MAX_PRICE:
59
+ raise CostError(f"track.pricing: {name} must be between 0 and {MAX_PRICE:g}")
60
+ return value
61
+
62
+
63
+ def _model(value: object) -> str:
64
+ if not isinstance(value, str) or not _MODEL.fullmatch(value):
65
+ raise CostError("a model id must be 1-80 characters of letters, digits and . _ : -")
66
+ return value
67
+
68
+
69
+ def resolve_price(engine: str, model: str | None, track: dict | None) -> Price:
70
+ """The price used for ``engine``: a ``track.pricing.<engine>`` override from the config
71
+ if present, else the dated table for ``model`` (or ``track.models.<engine>``, or the
72
+ default model). A model with no known price is refused, never guessed."""
73
+ if engine not in C.ENGINES:
74
+ raise CostError(f"unknown engine {str(engine)[:40]!r}")
75
+ track = track or {}
76
+ override = (track.get("pricing") or {}).get(engine)
77
+ if override is not None:
78
+ if not isinstance(override, dict) or set(override) - _OVERRIDE_KEYS:
79
+ raise CostError(f"track.pricing.{engine}: unknown key(s); allowed: "
80
+ f"{', '.join(sorted(_OVERRIDE_KEYS))}")
81
+ if "inputPerMTok" not in override or "outputPerMTok" not in override:
82
+ raise CostError(f"track.pricing.{engine} needs inputPerMTok and outputPerMTok")
83
+ tokens = override.get("searchInputTokens", 0)
84
+ if isinstance(tokens, bool) or not isinstance(tokens, int) or not 0 <= tokens <= 10**6:
85
+ raise CostError(f"track.pricing.{engine}.searchInputTokens must be 0..1000000")
86
+ checked = override.get("checkedOn", "unknown")
87
+ if checked != "unknown" and not (isinstance(checked, str) and _DATE.fullmatch(checked)):
88
+ raise CostError(f"track.pricing.{engine}.checkedOn must be YYYY-MM-DD")
89
+ source = override.get("source", "omnirank.config.json")
90
+ if not isinstance(source, str):
91
+ raise CostError(f"track.pricing.{engine}.source must be a string")
92
+ return Price(engine, _model(override.get("model")),
93
+ _money(override["inputPerMTok"], "inputPerMTok"),
94
+ _money(override["outputPerMTok"], "outputPerMTok"),
95
+ _money(override.get("perSearch", 0), "perSearch"),
96
+ _money(override.get("perRequest", 0), "perRequest"),
97
+ tokens, source[:200], checked, False, True)
98
+ chosen = model or (track.get("models") or {}).get(engine) or C.DEFAULT_MODELS[engine]
99
+ chosen = _model(chosen)
100
+ row = C.PRICING[engine].get(chosen)
101
+ if row is None:
102
+ raise CostError(f"no price for {engine} model {chosen!r} in OmniRank's table; add "
103
+ f"track.pricing.{engine} to omnirank.config.json (see docs/track.md)")
104
+ return Price(engine, chosen, row["input"], row["output"], row["per_search"],
105
+ row["per_request"], row["search_input_tokens"], row["source"],
106
+ row["checked_on"], row["verified"], False, row.get("note", ""))
107
+
108
+
109
+ def call_tokens(engine: str, price: Price, prompt_text: str, max_output: int) -> tuple[int, int]:
110
+ tin = (math.ceil(len(prompt_text.encode("utf-8")) / C.BYTES_PER_TOKEN)
111
+ + C.REQUEST_OVERHEAD_TOKENS[engine]
112
+ + price.search_input_tokens * C.ASSUMED_SEARCHES_PER_CALL)
113
+ return tin, max_output
114
+
115
+
116
+ def _finite(*values: object) -> None:
117
+ for v in values:
118
+ if isinstance(v, bool) or not isinstance(v, int | float) or not math.isfinite(v):
119
+ raise CostError("a cost input is not a finite number; refusing to estimate")
120
+
121
+
122
+ def estimate_call(engine: str, price: Price, prompt_text: str, max_output: int) -> float:
123
+ """Never negative, never NaN/inf: a non-finite input is an error, a negative one
124
+ counts as 0 (so a tampered value can never make spending look cheaper)."""
125
+ _finite(max_output, price.input, price.output, price.per_search, price.per_request,
126
+ price.search_input_tokens)
127
+ tin, tout = call_tokens(engine, price, prompt_text, max(0, max_output))
128
+ usd = (tin * max(0.0, price.input) / 1e6 + tout * max(0.0, price.output) / 1e6
129
+ + max(0.0, price.per_search) * C.ASSUMED_SEARCHES_PER_CALL
130
+ + max(0.0, price.per_request))
131
+ if not math.isfinite(usd):
132
+ raise CostError("the estimate is not a finite number; refusing to estimate")
133
+ return max(0.0, usd)
134
+
135
+
136
+ def estimate_batch(prompts: Sequence, prices: dict[str, Price], *, runs: int, max_output: int,
137
+ done: Iterable[tuple[str, str, int]] = ()) -> dict:
138
+ done = set(done)
139
+ engines: dict[str, dict] = {}
140
+ for engine, price in prices.items():
141
+ calls, usd = 0, 0.0
142
+ for p in prompts:
143
+ one = estimate_call(engine, price, p.text, max_output)
144
+ for r in range(runs):
145
+ if (engine, p.id, r) in done:
146
+ continue
147
+ calls += 1
148
+ usd += one
149
+ engines[engine] = {"model": price.model, "calls": calls, "usd": usd,
150
+ "price": {"input_per_mtok": price.input,
151
+ "output_per_mtok": price.output,
152
+ "per_search": price.per_search,
153
+ "per_request": price.per_request,
154
+ "search_input_tokens": price.search_input_tokens,
155
+ "source": price.source, "checked_on": price.checked_on,
156
+ "verified": price.verified, "note": price.note,
157
+ "overridden": price.overridden}}
158
+ return {"engines": engines, "calls": sum(e["calls"] for e in engines.values()),
159
+ "total_usd": sum(e["usd"] for e in engines.values()), "runs": runs,
160
+ "prompts": len(prompts), "max_output_tokens": max_output}
161
+
162
+
163
+ def format_estimate(est: dict) -> str:
164
+ lines = [(f"Cost estimate (before anything is sent): {est['prompts']} prompt(s) x "
165
+ f"{est['runs']} run(s) per engine, output capped at {est['max_output_tokens']} "
166
+ "tokens per answer")]
167
+ for engine, e in est["engines"].items():
168
+ p = e["price"]
169
+ flag = "" if p["verified"] else " UNVERIFIED price"
170
+ if p["overridden"]:
171
+ flag = " (price from your config)"
172
+ lines.append(f" {C.ENGINE_LABELS[engine]:<20} {e['model']:<24} {e['calls']:>5} "
173
+ f"call(s) ~${e['usd']:.4f}{flag}")
174
+ lines.append(f" ${p['input_per_mtok']:g}/MTok in, ${p['output_per_mtok']:g}/MTok out"
175
+ + (f", ${p['per_search']:g}/search" if p["per_search"] else "")
176
+ + (f", ${p['per_request']:g}/request" if p["per_request"] else "")
177
+ + (f", ~{p['search_input_tokens']} input tokens assumed per search"
178
+ if p["search_input_tokens"] else "")
179
+ + f"; checked {p['checked_on']}; {p['source']}")
180
+ if p.get("note"):
181
+ lines.append(f" note: {p['note']}")
182
+ lines.append(f" Total (money only; engines are reported separately): "
183
+ f"~${est['total_usd']:.4f} for {est['calls']} call(s)")
184
+ lines.append(f" Assumptions: input ~ UTF-8 bytes/{C.BYTES_PER_TOKEN} [heuristic] + "
185
+ "per-engine tool overhead; output = the full cap; "
186
+ f"{C.ASSUMED_SEARCHES_PER_CALL} search per call (Claude is capped at "
187
+ f"{C.ANTHROPIC_MAX_SEARCHES}; Gemini/OpenAI may search more, which costs more); "
188
+ "free tiers ignored.")
189
+ lines.append(" " + C.PRICING_WARNING)
190
+ return "\n".join(lines)
191
+
192
+
193
+ def _tokens(value: object) -> int | None:
194
+ if isinstance(value, bool) or not isinstance(value, int) or value < 0:
195
+ return None
196
+ return value
197
+
198
+
199
+ def actual_cost(price: Price, usage: dict | None, *, fallback: float) -> tuple[float, str]:
200
+ """(usd, basis). basis is "usage" when the API reported input and output tokens, else
201
+ "estimate" (the call's estimate is used, never a lower guess)."""
202
+ def fall() -> tuple[float, str]:
203
+ _finite(fallback)
204
+ return max(0.0, float(fallback)), "estimate"
205
+
206
+ if not isinstance(usage, dict):
207
+ return fall()
208
+ tin, tout = _tokens(usage.get("input_tokens")), _tokens(usage.get("output_tokens"))
209
+ if tin is None or tout is None:
210
+ return fall()
211
+ searches = _tokens(usage.get("searches")) or 0
212
+ # NOTE (UNVERIFIED): for OpenAI gpt-4.1-mini the pricing page says search content is
213
+ # billed as a fixed 8,000 input tokens per call; whether the Responses API's
214
+ # usage.input_tokens already includes that block is not documented on the pages read.
215
+ usd = (tin * max(0.0, price.input) / 1e6 + tout * max(0.0, price.output) / 1e6
216
+ + searches * max(0.0, price.per_search) + max(0.0, price.per_request))
217
+ if not math.isfinite(usd):
218
+ return fall()
219
+ return max(0.0, usd), "usage"
220
+
221
+
222
+ def parse_max_cost(text: str) -> float:
223
+ if not isinstance(text, str) or not _USD.fullmatch(text.strip()):
224
+ raise CostError("--max-cost must be a positive US dollar amount like 1.00")
225
+ value = float(text)
226
+ if not 0 < value <= C.MAX_COST_HARD_LIMIT_USD:
227
+ raise CostError(f"--max-cost must be more than 0 and at most "
228
+ f"{C.MAX_COST_HARD_LIMIT_USD:g}")
229
+ return value
@@ -0,0 +1,277 @@
1
+ """Prompt discovery for `omnirank track discover`: the owner's own Search Console queries
2
+ become a prompt set file in the format `omnirank track ai --prompts` reads.
3
+
4
+ Pure logic, no I/O, no network, no LLM. Prompt text is the owner's query text plus the fixed
5
+ strings in ``discover_constants.TEMPLATES`` (the only wording OmniRank adds is a trailing
6
+ "?" on a how-to prompt); nothing is paraphrased or invented.
7
+
8
+ Steps (all deterministic):
9
+
10
+ 1. Queries are merged by normalized text (NFKC, casefold, whitespace); clicks and
11
+ impressions are summed and the displayed variant is the one with the most impressions
12
+ (ties: the smallest string).
13
+ 2. Unsafe queries are dropped and counted by reason: ``unsafe`` (control, bidi or other
14
+ invisible format characters; zero-width joiners are kept only in Indic text; longer than
15
+ ``MAX_QUERY_CHARS``; no letter), ``injection_like`` (instruction-like phrases, template
16
+ markers) and ``pii_like`` (``@``, ``://``, "at ... dot com", 7+ digits in one run with
17
+ separators, IBAN-like, long secret-like tokens). Best-effort [heuristic] filters; queries
18
+ come from strangers and the owner must review the file (``DC.FILTER_NOTE``).
19
+ 3. Queries below ``--min-impressions`` are dropped when the export has impressions.
20
+ 4. Each remaining query gets ONE category, by cue, in this order of precedence:
21
+ comparison, branded, local, how-to (a question); so "why is acme slow" is branded. A query with no cue is skipped and
22
+ counted, never guessed.
23
+ 5. Within a category, rank = impressions desc, clicks desc, normalized query asc; a prompt
24
+ whose text equals a higher-ranked one (ignoring case, spacing and trailing "?") is a
25
+ duplicate and dropped.
26
+ 6. Caps: ``per_category`` first, then ``max_prompts`` taken round-robin by rank across the
27
+ categories, so one busy category cannot crowd the others out.
28
+ """
29
+ from __future__ import annotations
30
+
31
+ import re
32
+ import unicodedata
33
+ from collections import Counter
34
+ from collections.abc import Iterable, Sequence
35
+ from dataclasses import dataclass, field
36
+
37
+ from ..packs.gsc import norm_query
38
+ from . import analysis
39
+ from . import discover_constants as DC
40
+ from .ai_prompts import MAX_PROMPTS, BrandSpec, Prompt
41
+
42
+
43
+ class DiscoverError(Exception):
44
+ pass
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class QueryStat:
49
+ query: str
50
+ clicks: int
51
+ impressions: int | None
52
+
53
+
54
+ @dataclass
55
+ class Selection:
56
+ prompts: list[Prompt]
57
+ sources: dict[str, QueryStat]
58
+ skipped: dict[str, int]
59
+ candidates: dict[str, int] = field(default_factory=dict)
60
+
61
+
62
+ def tokens(text: str) -> list[str]:
63
+ """Words of the NFKC-casefolded text: runs of letters, marks and numbers (Bengali vowel
64
+ signs are marks, which Python's ``\\w`` does not cover) and zero-width joiners inside a
65
+ word; everything else separates."""
66
+ out: list[str] = []
67
+ cur: list[str] = []
68
+ for ch in unicodedata.normalize("NFKC", text).casefold():
69
+ cat = unicodedata.category(ch)
70
+ if cat[0] in "LMN" or (ch in "‌‍" and cur):
71
+ cur.append(ch)
72
+ elif cur:
73
+ out.append("".join(cur))
74
+ cur = []
75
+ if cur:
76
+ out.append("".join(cur))
77
+ return out
78
+
79
+
80
+ def _clean(text: str) -> str:
81
+ return " ".join(unicodedata.normalize("NFC", text).split())
82
+
83
+
84
+ _INJECTION = [re.compile(p) for p in DC.INJECTION_PATTERNS]
85
+ _PII = [re.compile(p) for p in DC.PII_PATTERNS]
86
+ _DIGITS = re.compile(DC.DIGIT_RUN_PATTERN)
87
+ _SECRET = re.compile(rf"[A-Za-z0-9+/_=-]{{{DC.SECRET_TOKEN_MIN},}}")
88
+
89
+
90
+ def _indic(text: str) -> bool:
91
+ return any(0x0900 <= ord(c) <= 0x0DFF for c in text)
92
+
93
+
94
+ def _reject(raw: str) -> str | None:
95
+ """Why a raw query must not become a prompt: ``unsafe`` (control, invisible or bidi
96
+ characters, too long, no letter), ``injection_like`` or ``pii_like``; else None."""
97
+ if analysis._CTRL.search(raw):
98
+ return "unsafe"
99
+ text = _clean(raw)
100
+ if not text or len(text) > DC.MAX_QUERY_CHARS:
101
+ return "unsafe"
102
+ indic = _indic(text)
103
+ for ch in text:
104
+ if unicodedata.category(ch) == "Cf" and not (ch in "\u200c\u200d" and indic):
105
+ return "unsafe"
106
+ if not any(unicodedata.category(c)[0] == "L" for c in text):
107
+ return "unsafe"
108
+ low = unicodedata.normalize("NFKC", text).casefold()
109
+ if any(p.search(low) for p in _INJECTION):
110
+ return "injection_like"
111
+ if any(p.search(low) for p in _PII):
112
+ return "pii_like"
113
+ if any(sum(c.isdigit() for c in m.group()) > DC.MAX_DIGITS_IN_RUN
114
+ for m in _DIGITS.finditer(text)):
115
+ return "pii_like"
116
+ for tok in _SECRET.findall(text):
117
+ if any(c.isdigit() for c in tok) or (tok != tok.lower() and tok != tok.upper()):
118
+ return "pii_like"
119
+ return None
120
+
121
+
122
+ def aggregate(stats: Iterable[QueryStat]) -> list[QueryStat]:
123
+ groups: dict[str, list[QueryStat]] = {}
124
+ for s in stats:
125
+ groups.setdefault(norm_query(s.query), []).append(s)
126
+ out = []
127
+ for key in sorted(groups):
128
+ rows = groups[key]
129
+ shown = min(rows, key=lambda r: (-(r.impressions or 0), _clean(r.query)))
130
+ imps = [r.impressions for r in rows if r.impressions is not None]
131
+ out.append(QueryStat(_clean(shown.query), sum(r.clicks for r in rows),
132
+ sum(imps) if imps else None))
133
+ return out
134
+
135
+
136
+ def _has_phrase(toks: Sequence[str], phrase: Sequence[str]) -> bool:
137
+ n = len(phrase)
138
+ return any(tuple(toks[i:i + n]) == tuple(phrase) for i in range(len(toks) - n + 1))
139
+
140
+
141
+ def local_term_tokens(terms: Iterable[str]) -> tuple[tuple[str, ...], ...]:
142
+ out = []
143
+ for t in terms:
144
+ toks = tokens(t)
145
+ if not toks or len("".join(toks)) < DC.MIN_LOCAL_TERM_CHARS:
146
+ raise DiscoverError(f"a --local-term needs at least {DC.MIN_LOCAL_TERM_CHARS} "
147
+ "letters or digits (short terms match too much)")
148
+ out.append(tuple(toks))
149
+ if len(out) > DC.MAX_LOCAL_TERMS:
150
+ raise DiscoverError(f"at most {DC.MAX_LOCAL_TERMS} --local-term values")
151
+ return tuple(out)
152
+
153
+
154
+ def classify(query: str, brand: BrandSpec | None,
155
+ local_terms: Iterable[str | tuple[str, ...]] = ()) -> str | None:
156
+ """comparison > branded > local > how-to (a question) > None."""
157
+ toks = tokens(query)
158
+ if not toks:
159
+ return None
160
+ if any(t in DC.COMPARISON_TOKENS for t in toks) or any(
161
+ _has_phrase(toks, p) for p in DC.COMPARISON_PHRASES):
162
+ return "comparison"
163
+ if brand is not None and analysis.find_first(
164
+ query, [*brand.names, *brand.domains]) is not None:
165
+ return "branded"
166
+ extra = [tuple(tokens(t)) if isinstance(t, str) else t for t in local_terms]
167
+ if any(_has_phrase(toks, p) for p in (*DC.LOCAL_PHRASES, *extra) if p):
168
+ return "local"
169
+ if (_clean(query).endswith(DC.QUESTION_MARKS) or toks[0] in DC.QUESTION_WORDS_EN
170
+ or any(t in DC.QUESTION_WORDS_BN for t in toks)):
171
+ return "how-to"
172
+ return None
173
+
174
+
175
+ def render(category: str, query: str) -> str:
176
+ """The prompt text: the query through its fixed template (TEMPLATE TEXT)."""
177
+ if category == "how-to" and query.endswith(DC.QUESTION_MARKS):
178
+ return query
179
+ return DC.TEMPLATES[category].replace("{query}", query)
180
+
181
+
182
+ def _dedupe_key(text: str) -> str:
183
+ key = norm_query(text)
184
+ while key.endswith(DC.QUESTION_MARKS):
185
+ key = key[:-1].rstrip()
186
+ return key
187
+
188
+
189
+ def _rank(s: QueryStat) -> tuple:
190
+ return (-(s.impressions or 0), -s.clicks, norm_query(s.query))
191
+
192
+
193
+ def select(stats: Iterable[QueryStat], brand: BrandSpec | None, *,
194
+ per_category: int = DC.DEFAULT_PER_CATEGORY, max_prompts: int = DC.DEFAULT_MAX_PROMPTS,
195
+ min_impressions: int = DC.DEFAULT_MIN_IMPRESSIONS,
196
+ local_terms: Iterable[str | tuple[str, ...]] = ()) -> Selection:
197
+ if not 1 <= per_category <= MAX_PROMPTS:
198
+ raise DiscoverError(f"--per-category must be 1..{MAX_PROMPTS}")
199
+ if not 1 <= max_prompts <= MAX_PROMPTS:
200
+ raise DiscoverError(f"--max-prompts must be 1..{MAX_PROMPTS}")
201
+ if isinstance(min_impressions, bool) or min_impressions < 0:
202
+ raise DiscoverError("--min-impressions must be 0 or more")
203
+ local_terms = tuple(local_terms)
204
+ skipped: Counter[str] = Counter()
205
+ safe: list[QueryStat] = []
206
+ dropped: dict[str, set[str]] = {}
207
+ for s in stats:
208
+ why = _reject(s.query)
209
+ if why:
210
+ dropped.setdefault(why, set()).add(norm_query(s.query))
211
+ else:
212
+ safe.append(s)
213
+ merged = aggregate(safe)
214
+ kept = {norm_query(s.query) for s in merged}
215
+ for why, keys in dropped.items():
216
+ skipped[why] = len(keys - kept)
217
+ ranked = sorted(merged, key=_rank)
218
+ cands: dict[str, list[tuple[QueryStat, str]]] = {c: [] for c in DC.CATEGORY_ORDER}
219
+ seen: set[str] = set()
220
+ for s in ranked:
221
+ if s.impressions is not None and s.impressions < min_impressions:
222
+ skipped["low_impressions"] += 1
223
+ continue
224
+ cat = classify(s.query, brand, local_terms)
225
+ if cat is None:
226
+ skipped["unclassified"] += 1
227
+ continue
228
+ text = render(cat, s.query)
229
+ key = _dedupe_key(text)
230
+ if key in seen:
231
+ skipped["duplicate"] += 1
232
+ continue
233
+ seen.add(key)
234
+ cands[cat].append((s, text))
235
+ counts = {c: len(v) for c, v in cands.items()}
236
+ capped = {c: v[:per_category] for c, v in cands.items()}
237
+ chosen: dict[str, list[tuple[QueryStat, str]]] = {c: [] for c in DC.CATEGORY_ORDER}
238
+ total, rank = 0, 0
239
+ while total < max_prompts and any(len(v) > rank for v in capped.values()):
240
+ for c in DC.CATEGORY_ORDER:
241
+ if total < max_prompts and len(capped[c]) > rank:
242
+ chosen[c].append(capped[c][rank])
243
+ total += 1
244
+ rank += 1
245
+ prompts: list[Prompt] = []
246
+ sources: dict[str, QueryStat] = {}
247
+ for c in DC.CATEGORY_ORDER:
248
+ for n, (s, text) in enumerate(chosen[c], start=1):
249
+ pid = f"{c}-{n}"
250
+ prompts.append(Prompt(pid, c, unicodedata.normalize("NFC", text)))
251
+ sources[pid] = s
252
+ return Selection(prompts, sources, {k: v for k, v in skipped.items() if v}, counts)
253
+
254
+
255
+ def prompt_file(prompts: Sequence[Prompt]) -> dict:
256
+ return {"version": 1, "prompts": [{"id": p.id, "category": p.category, "text": p.text}
257
+ for p in prompts]}
258
+
259
+
260
+ def stats_from_table(table) -> list[QueryStat]:
261
+ """From ``packs.gsc.load_export`` (the loader the blog pack uses)."""
262
+ if "query" not in table.columns:
263
+ raise DiscoverError("the CSV needs a 'Query' column (Search Console > Performance > "
264
+ "Queries > Export); columns found: "
265
+ + (", ".join(table.columns.values()) or "none"))
266
+ return [QueryStat(r.query, r.clicks, r.impressions) for r in table.rows
267
+ if r.query is not None]
268
+
269
+
270
+ def stats_from_gsc_rows(rows: Iterable) -> list[QueryStat]:
271
+ """From ``connect.gsc.GscClient.query(..., ["query"])`` rows."""
272
+ out = []
273
+ for r in rows:
274
+ q = r.dims.get("query")
275
+ if isinstance(q, str):
276
+ out.append(QueryStat(q, round(r.clicks), round(r.impressions)))
277
+ return out