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,207 @@
1
+ """The prompt set and the brand / competitor names for `omnirank track ai`.
2
+
3
+ Prompt file (JSON, UTF-8, at most ``MAX_FILE_BYTES``)::
4
+
5
+ {"version": 1,
6
+ "prompts": [{"id": "branded-1", "category": "branded", "text": "What is Acme?"}, ...]}
7
+
8
+ Validation is strict and fails closed: unknown keys, an unknown category, a bad id
9
+ (``[a-z0-9][a-z0-9-]{0,63}``, matched with ``fullmatch``), an empty or over-long text, a
10
+ control character other than newline/tab, a duplicate id or more than ``MAX_PROMPTS``
11
+ prompts are all errors. Prompt texts are NFC-normalized. Prompt discovery from Search
12
+ Console queries is not part of this module (backlog item 22).
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import re
18
+ import unicodedata
19
+ from dataclasses import dataclass
20
+ from pathlib import Path
21
+
22
+ from .analysis import domain_of
23
+
24
+ CATEGORIES = ("branded", "category", "comparison", "how-to", "local")
25
+ MAX_FILE_BYTES = 1_000_000
26
+ MAX_PROMPTS = 200
27
+ MAX_TEXT = 2000
28
+ MAX_NAME = 100
29
+ MAX_ALIASES = 20
30
+ MAX_COMPETITORS = 50
31
+ MAX_DOMAINS = 20
32
+ _ID = re.compile(r"[a-z0-9][a-z0-9-]{0,63}")
33
+ _CTRL = re.compile(r"[\x00-\x08\x0b-\x1f\x7f-\x9f\u2028\u2029\u202a-\u202e\u2066-\u2069]")
34
+
35
+
36
+ class PromptError(Exception):
37
+ pass
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class Prompt:
42
+ id: str
43
+ category: str
44
+ text: str
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class BrandSpec:
49
+ name: str
50
+ aliases: tuple[str, ...]
51
+ domains: tuple[str, ...]
52
+ competitors: tuple[str, ...]
53
+
54
+ @property
55
+ def names(self) -> tuple[str, ...]:
56
+ return (self.name, *self.aliases)
57
+
58
+
59
+ def _text(value: object, where: str) -> str:
60
+ if not isinstance(value, str):
61
+ raise PromptError(f"{where}: 'text' must be a string")
62
+ text = unicodedata.normalize("NFC", value).strip()
63
+ if not text:
64
+ raise PromptError(f"{where}: 'text' is empty")
65
+ if len(text) > MAX_TEXT:
66
+ raise PromptError(f"{where}: 'text' is longer than {MAX_TEXT} characters")
67
+ if _CTRL.search(text):
68
+ raise PromptError(f"{where}: 'text' contains a control character")
69
+ return text
70
+
71
+
72
+ def parse_prompts(data: object) -> list[Prompt]:
73
+ if not isinstance(data, dict):
74
+ raise PromptError("the prompt file must be a JSON object with a 'prompts' list")
75
+ unknown = set(data) - {"version", "prompts"}
76
+ if unknown:
77
+ raise PromptError(f"unknown key(s) in the prompt file: {', '.join(sorted(unknown))[:200]}")
78
+ if data.get("version", 1) != 1 or isinstance(data.get("version"), bool):
79
+ raise PromptError("unsupported prompt file version (expected 1)")
80
+ raw = data.get("prompts")
81
+ if not isinstance(raw, list) or not raw:
82
+ raise PromptError("'prompts' must be a non-empty list")
83
+ if len(raw) > MAX_PROMPTS:
84
+ raise PromptError(f"the prompt file may hold at most {MAX_PROMPTS} prompts")
85
+ out: list[Prompt] = []
86
+ seen: set[str] = set()
87
+ for i, item in enumerate(raw):
88
+ where = f"prompt #{i + 1}"
89
+ if not isinstance(item, dict):
90
+ raise PromptError(f"{where} is not an object")
91
+ if set(item) != {"id", "category", "text"}:
92
+ raise PromptError(f"{where} must have exactly the keys id, category and text")
93
+ pid = item["id"]
94
+ if not isinstance(pid, str) or not _ID.fullmatch(pid):
95
+ raise PromptError(f"{where}: id must match [a-z0-9][a-z0-9-]{{0,63}}")
96
+ if pid in seen:
97
+ raise PromptError(f"{where}: duplicate id {pid!r}")
98
+ seen.add(pid)
99
+ if item["category"] not in CATEGORIES:
100
+ raise PromptError(f"{where}: category must be one of {', '.join(CATEGORIES)}")
101
+ out.append(Prompt(pid, item["category"], _text(item["text"], where)))
102
+ return out
103
+
104
+
105
+ def load_prompts(path: str | Path) -> list[Prompt]:
106
+ p = Path(path)
107
+ try:
108
+ if p.stat().st_size > MAX_FILE_BYTES:
109
+ raise PromptError(f"{p} is larger than {MAX_FILE_BYTES} bytes")
110
+ with open(p, "rb") as fh:
111
+ blob = fh.read(MAX_FILE_BYTES + 1)
112
+ except OSError as exc:
113
+ raise PromptError(f"cannot read the prompt file {p}: {exc.strerror or exc}") from None
114
+ if len(blob) > MAX_FILE_BYTES:
115
+ raise PromptError(f"{p} is larger than {MAX_FILE_BYTES} bytes")
116
+ try:
117
+ data = json.loads(blob.decode("utf-8"))
118
+ except (ValueError, UnicodeDecodeError):
119
+ raise PromptError(f"{p} is not valid UTF-8 JSON") from None
120
+ return parse_prompts(data)
121
+
122
+
123
+ def _name(value: object, what: str) -> str:
124
+ if not isinstance(value, str):
125
+ raise PromptError(f"{what} must be a string")
126
+ name = unicodedata.normalize("NFC", value).strip()
127
+ if not name or len(name) > MAX_NAME:
128
+ raise PromptError(f"{what} must be 1..{MAX_NAME} characters")
129
+ if _CTRL.search(name):
130
+ raise PromptError(f"{what} contains a control character")
131
+ if not any(unicodedata.category(c)[0] in "LN" for c in name):
132
+ raise PromptError(f"{what} must contain a letter or digit")
133
+ return name
134
+
135
+
136
+ def _domain(value: object) -> str:
137
+ if not isinstance(value, str) or "/" in value or ":" in value:
138
+ raise PromptError("track.brandDomains entries must be bare host names like "
139
+ "example.com")
140
+ host = domain_of(f"https://{value}/")
141
+ if host is None:
142
+ raise PromptError(f"track.brandDomains entry {str(value)[:80]!r} is not a host name")
143
+ return host
144
+
145
+
146
+ def _str_list(value: object, what: str, limit: int) -> list:
147
+ if value is None:
148
+ return []
149
+ if not isinstance(value, list) or len(value) > limit:
150
+ raise PromptError(f"{what} must be a list of at most {limit} strings")
151
+ return value
152
+
153
+
154
+ def brand_from_record(b: object) -> BrandSpec:
155
+ """A brand saved in a run manifest, validated as strictly as fresh input."""
156
+ if not isinstance(b, dict) or set(b) - {"name", "aliases", "domains", "competitors"}:
157
+ raise PromptError("the saved brand must be an object with name, aliases, domains "
158
+ "and competitors")
159
+ name = _name(b.get("name"), "the saved brand name")
160
+ aliases = [_name(a, "a saved brand alias")
161
+ for a in _str_list(b.get("aliases"), "aliases", MAX_ALIASES)]
162
+ domains = [_domain(d) for d in _str_list(b.get("domains"), "domains", MAX_DOMAINS)]
163
+ comps = [_name(c, "a saved competitor name")
164
+ for c in _str_list(b.get("competitors"), "competitors", MAX_COMPETITORS)]
165
+ return BrandSpec(name, tuple(aliases), tuple(domains), tuple(comps))
166
+
167
+
168
+ def brand_from_config(raw: dict | None, *, brand: str | None = None,
169
+ competitors: list[str] | None = None) -> BrandSpec:
170
+ """Brand = ``--brand`` or ``site.name``; aliases = ``site.legalName`` +
171
+ ``track.brandAliases``; domains = host of ``site.url`` + ``track.brandDomains``;
172
+ competitors = top-level ``competitors`` + ``--competitor``."""
173
+ raw = raw or {}
174
+ site = raw.get("site") or {}
175
+ track = raw.get("track") or {}
176
+ name_src = brand if brand is not None else site.get("name")
177
+ if name_src is None:
178
+ raise PromptError("no brand name: pass --brand NAME or set site.name in "
179
+ "omnirank.config.json")
180
+ name = _name(name_src, "the brand name")
181
+ aliases: list[str] = []
182
+ for a in ([site["legalName"]] if site.get("legalName") else []) + list(
183
+ track.get("brandAliases") or []):
184
+ a = _name(a, "a brand alias")
185
+ if a.casefold() != name.casefold() and a not in aliases:
186
+ aliases.append(a)
187
+ if len(aliases) > MAX_ALIASES:
188
+ raise PromptError(f"at most {MAX_ALIASES} brand aliases")
189
+ domains: list[str] = []
190
+ if brand is None and site.get("url"):
191
+ host = domain_of(site["url"])
192
+ if host:
193
+ domains.append(host)
194
+ for d in track.get("brandDomains") or []:
195
+ host = _domain(d)
196
+ if host not in domains:
197
+ domains.append(host)
198
+ if len(domains) > MAX_DOMAINS:
199
+ raise PromptError(f"at most {MAX_DOMAINS} brand domains")
200
+ comps: list[str] = []
201
+ for c in list(raw.get("competitors") or []) + list(competitors or []):
202
+ c = _name(c, "a competitor name")
203
+ if c.casefold() != name.casefold() and c not in comps:
204
+ comps.append(c)
205
+ if len(comps) > MAX_COMPETITORS:
206
+ raise PromptError(f"at most {MAX_COMPETITORS} competitors")
207
+ return BrandSpec(name, tuple(aliases), tuple(domains), tuple(comps))
@@ -0,0 +1,197 @@
1
+ """Mention, sentiment and citation-domain extraction from one model answer.
2
+
3
+ Model output is untrusted DATA: it is only searched (``str.find`` on normalized text),
4
+ never executed, never used in a path, a shell or a format string. Matching rules:
5
+
6
+ * NFC-normalized and ``casefold()``-ed (case-insensitive, also for ß/ẞ etc.);
7
+ * whole words only: the character before and after a match must not be a "word"
8
+ character, defined as Unicode letter, mark or number or ``_`` (Python's ``\\w`` does not
9
+ treat Bengali vowel signs such as U+09BE as word characters, so ``re`` ``\\b`` would
10
+ split Bengali words);
11
+ * Bengali names only: one common case ending or particle may follow the name before the
12
+ boundary (অ্যাকমির, অ্যাকমিকে, অ্যাকমিতে...; ``constants.BENGALI_SUFFIXES``, a [heuristic]
13
+ UNVERIFIED list). Anything else that continues the word is not a match (অ্যাকমিওলজি).
14
+ Latin and other names stay strict whole-word matches;
15
+ * input is cut at ``MAX_ANALYZE_CHARS`` first, and every search is linear.
16
+
17
+ The sentiment label is a simple lexicon heuristic (``SENTIMENT_METHOD``): it counts a few
18
+ English and Bengali positive/negative words in the sentences that name the brand. It does
19
+ not understand negation or sarcasm.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import re
24
+ import unicodedata
25
+ from collections.abc import Iterable, Sequence
26
+ from urllib.parse import urlsplit
27
+
28
+ from .constants import BENGALI_SUFFIXES
29
+
30
+ MAX_ANALYZE_CHARS = 500_000
31
+ SENTIMENT_METHOD = ("[heuristic] lexicon word count in sentences naming the brand "
32
+ "(English + Bengali word lists; no negation handling)")
33
+
34
+ POSITIVE = ("good", "great", "excellent", "best", "reliable", "recommended", "recommend",
35
+ "popular", "trusted", "affordable", "easy", "leading", "top", "fast", "secure",
36
+ "ভালো", "ভাল", "সেরা", "নির্ভরযোগ্য", "জনপ্রিয়", "সহজ", "চমৎকার", "বিশ্বস্ত")
37
+ NEGATIVE = ("bad", "poor", "worst", "unreliable", "expensive", "slow", "complaints",
38
+ "complaint", "avoid", "scam", "buggy", "terrible", "insecure", "outdated",
39
+ "খারাপ", "ধীর", "ব্যয়বহুল", "অভিযোগ", "অনির্ভরযোগ্য", "প্রতারণা")
40
+
41
+ _SENTENCE_END = re.compile(r"[.!?।\n]")
42
+ _HOST = re.compile(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}"
43
+ r"[a-z0-9])?){1,20}")
44
+ _CTRL = re.compile(r"[\x00-\x1f\x7f-\x9f\u200e\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069]")
45
+ _CTRL_KEEP_NL = re.compile(r"[\x00-\x09\x0b-\x1f\x7f-\x9f\u200e\u200f\u2028\u2029"
46
+ r"\u202a-\u202e\u2066-\u2069]")
47
+
48
+
49
+ def normalize(text: str) -> str:
50
+ return unicodedata.normalize("NFC", text[:MAX_ANALYZE_CHARS]).casefold()
51
+
52
+
53
+ def _is_word(ch: str) -> bool:
54
+ return ch == "_" or unicodedata.category(ch)[0] in "LMN"
55
+
56
+
57
+ _BN_SUFFIXES = tuple(sorted({unicodedata.normalize("NFC", s) for s in BENGALI_SUFFIXES},
58
+ key=len, reverse=True))
59
+
60
+
61
+ def _is_bengali(ch: str) -> bool:
62
+ return "\u0980" <= ch <= "\u09ff"
63
+
64
+
65
+ def _boundary_after(text: str, end: int, bengali: bool) -> bool:
66
+ """True when ``end`` is a word boundary, or (for a Bengali name) when exactly one known
67
+ case ending / particle follows and THEN a word boundary."""
68
+ if end >= len(text) or not _is_word(text[end]):
69
+ return True
70
+ if not bengali:
71
+ return False
72
+ for suffix in _BN_SUFFIXES:
73
+ if text.startswith(suffix, end):
74
+ after = end + len(suffix)
75
+ if after >= len(text) or not _is_word(text[after]):
76
+ return True
77
+ return False
78
+
79
+
80
+ def _occurrences(norm_text: str, norm_name: str) -> Iterable[int]:
81
+ if not norm_name:
82
+ return
83
+ start = 0
84
+ n = len(norm_name)
85
+ bengali = _is_bengali(norm_name[-1])
86
+ while True:
87
+ i = norm_text.find(norm_name, start)
88
+ if i < 0:
89
+ return
90
+ before_ok = i == 0 or not _is_word(norm_text[i - 1])
91
+ after_ok = _boundary_after(norm_text, i + n, bengali)
92
+ if before_ok and after_ok:
93
+ yield i
94
+ start = i + 1
95
+
96
+
97
+ def _first_in(norm_text: str, names: Sequence[str]) -> int | None:
98
+ best = None
99
+ for name in names:
100
+ n = normalize(name)
101
+ for i in _occurrences(norm_text, n):
102
+ if best is None or i < best:
103
+ best = i
104
+ break
105
+ return best
106
+
107
+
108
+ def find_first(text: str, names: Sequence[str]) -> int | None:
109
+ """Offset (in the normalized text) of the first whole-word mention of any name."""
110
+ return _first_in(normalize(text), names)
111
+
112
+
113
+ def _sentences(norm_text: str) -> list[tuple[int, int]]:
114
+ spans, start = [], 0
115
+ for m in _SENTENCE_END.finditer(norm_text):
116
+ spans.append((start, m.end()))
117
+ start = m.end()
118
+ if start < len(norm_text):
119
+ spans.append((start, len(norm_text)))
120
+ return spans
121
+
122
+
123
+ def _count(segment: str, words: Sequence[str]) -> int:
124
+ return sum(1 for w in words for _ in _occurrences(segment, normalize(w)))
125
+
126
+
127
+ def sentiment(norm_text: str, names: Sequence[str]) -> str:
128
+ norm_names = [normalize(n) for n in names]
129
+ pos = neg = 0
130
+ hit = False
131
+ for a, b in _sentences(norm_text):
132
+ seg = norm_text[a:b]
133
+ if any(next(iter(_occurrences(seg, n)), None) is not None for n in norm_names):
134
+ hit = True
135
+ pos += _count(seg, POSITIVE)
136
+ neg += _count(seg, NEGATIVE)
137
+ if not hit:
138
+ return "not mentioned"
139
+ if pos and neg:
140
+ return "mixed"
141
+ if pos:
142
+ return "positive"
143
+ if neg:
144
+ return "negative"
145
+ return "neutral"
146
+
147
+
148
+ def analyze_text(text: str, brand) -> dict:
149
+ """Mention facts for one answer. ``first_mention_rank`` is the order in which the brand
150
+ is first named among the tracked names (brand + competitors) that appear: 1 = named
151
+ first. It is NOT a search ranking."""
152
+ norm = normalize(text if isinstance(text, str) else "")
153
+ brand_at = _first_in(norm, brand.names)
154
+ comp_at = {c: _first_in(norm, [c]) for c in brand.competitors}
155
+ co = [c for c in brand.competitors if comp_at[c] is not None]
156
+ rank = None
157
+ if brand_at is not None:
158
+ rank = 1 + sum(1 for c in co if comp_at[c] < brand_at)
159
+ return {"mentioned": brand_at is not None, "first_mention_rank": rank,
160
+ "co_mentions": co,
161
+ "sentiment": sentiment(norm, brand.names) if brand_at is not None
162
+ else "not mentioned"}
163
+
164
+
165
+ def domain_of(url: object) -> str | None:
166
+ """Lower-case ASCII (IDNA) host of an http(s) URL without a leading ``www.``; None
167
+ for anything else (other schemes, user info, spaces, malformed)."""
168
+ if not isinstance(url, str) or len(url) > 4096 or _CTRL.search(url) or " " in url:
169
+ return None
170
+ try:
171
+ parts = urlsplit(url)
172
+ _ = parts.port
173
+ except ValueError:
174
+ return None
175
+ if parts.scheme.lower() not in ("http", "https") or "@" in parts.netloc:
176
+ return None
177
+ host = (parts.hostname or "").rstrip(".")
178
+ if not host:
179
+ return None
180
+ try:
181
+ host = host.encode("idna").decode("ascii").lower()
182
+ except (UnicodeError, ValueError):
183
+ return None
184
+ host = host.removeprefix("www.")
185
+ return host if _HOST.fullmatch(host) else None
186
+
187
+
188
+ def domain_matches(host: str, domains: Sequence[str]) -> bool:
189
+ return any(host == d or host.endswith("." + d) for d in domains)
190
+
191
+
192
+ def printable(text: str, *, keep_newlines: bool = False, limit: int = 2000) -> str:
193
+ """Untrusted text made safe for a terminal: control and bidi-override characters
194
+ become ``?``; cut at ``limit`` characters."""
195
+ pattern = _CTRL_KEEP_NL if keep_newlines else _CTRL
196
+ out = pattern.sub("?", text[:limit])
197
+ return out + ("…" if len(text) > limit else "")
@@ -0,0 +1,155 @@
1
+ """Facts for `omnirank track` that go stale: LLM endpoints, default models, PRICES.
2
+
3
+ PRICES: VERIFY BEFORE RELYING. Every number below was read from the page named next to it
4
+ on ``CHECKED_ON`` (or, where marked UNVERIFIED, from a third-party page because the
5
+ official page did not show it). Providers change prices and retire models without notice.
6
+ OmniRank never fetches prices at run time. Override any engine's model and prices in
7
+ ``omnirank.config.json`` under ``track.pricing`` (see docs/track.md); a model with no
8
+ price here and no override is refused for real runs (never guessed).
9
+
10
+ All money is US dollars. Token prices are per 1,000,000 tokens.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ CHECKED_ON = "2026-11-29"
15
+ PRICING_WARNING = ("Prices come from OmniRank's dated pricing table (checked "
16
+ f"{CHECKED_ON}); VERIFY BEFORE RELYING. Override them in "
17
+ "omnirank.config.json track.pricing.")
18
+
19
+ ENGINES = ("gemini", "anthropic", "openai", "perplexity")
20
+ ENGINE_ALIASES = {"claude": "anthropic", "google": "gemini", "chatgpt": "openai"}
21
+ ENGINE_LABELS = {"gemini": "Gemini (Google)", "anthropic": "Claude (Anthropic)",
22
+ "openai": "OpenAI", "perplexity": "Perplexity"}
23
+
24
+ # Keys come from the environment ONLY (the provider's own conventional variable names).
25
+ ENV_KEYS = {"gemini": "GEMINI_API_KEY", "anthropic": "ANTHROPIC_API_KEY",
26
+ "openai": "OPENAI_API_KEY", "perplexity": "PERPLEXITY_API_KEY"}
27
+
28
+ # --- endpoints (key transport) ---------------------------------------------------------------
29
+ # Gemini: https://aistudio.google.com/docs/api-key (checked 2026-11-29): the documented curl
30
+ # sends `x-goog-api-key: KEY` as a header; a `key=` query parameter is NOT used by OmniRank.
31
+ # Path: https://aistudio.google.com/api-reference/generate-content
32
+ # `POST /v1beta/models/{model}:generateContent`.
33
+ GEMINI_HOST = "generativelanguage.googleapis.com"
34
+ GEMINI_URL = "https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent"
35
+ GEMINI_KEY_HEADER = "x-goog-api-key"
36
+ # Anthropic: https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool
37
+ # (checked 2026-11-29): `x-api-key` header, `anthropic-version` header. The pages show both
38
+ # "2023-06-01" and "2026-10-21"; OmniRank sends the long-standing 2023-06-01, which the
39
+ # Messages API reference example uses.
40
+ ANTHROPIC_HOST = "api.anthropic.com"
41
+ ANTHROPIC_URL = "https://api.anthropic.com/v1/messages"
42
+ ANTHROPIC_KEY_HEADER = "x-api-key"
43
+ ANTHROPIC_VERSION = "2023-06-01"
44
+ ANTHROPIC_WEB_SEARCH_TOOL = "web_search_20250305" # basic search (no dynamic filtering)
45
+ ANTHROPIC_MAX_SEARCHES = 1 # `max_uses`: bounds per-call search cost
46
+ # OpenAI: https://developers.openai.com/api/docs/guides/tools-web-search (checked
47
+ # 2026-11-29): `POST https://api.openai.com/v1/responses`, tool `{"type": "web_search"}`,
48
+ # citations as `url_citation` annotations. Bearer key.
49
+ OPENAI_HOST = "api.openai.com"
50
+ OPENAI_URL = "https://api.openai.com/v1/responses"
51
+ # Perplexity: https://docs.perplexity.ai/docs/sonar/models/sonar.md (checked 2026-11-29):
52
+ # `POST https://api.perplexity.ai/v1/sonar`, Bearer key, `citations` (URL list) and
53
+ # `search_results`. The page says "Sonar Chat Completions support ended on September 27,
54
+ # 2026" and that Sonar requests are being reformulated as Agent API requests: this client
55
+ # may need updating. The `usage` field is NOT shown on that page (UNVERIFIED shape:
56
+ # OpenAI-style `prompt_tokens`/`completion_tokens`).
57
+ PERPLEXITY_HOST = "api.perplexity.ai"
58
+ PERPLEXITY_URL = "https://api.perplexity.ai/v1/sonar"
59
+
60
+ ALLOWED_HOSTS = {"gemini": GEMINI_HOST, "anthropic": ANTHROPIC_HOST,
61
+ "openai": OPENAI_HOST, "perplexity": PERPLEXITY_HOST}
62
+
63
+ # Gemini grounding sources are redirect links on this host; the source domain is then
64
+ # taken from the chunk title (UNVERIFIED behaviour, observed in public examples).
65
+ GEMINI_REDIRECT_HOSTS = ("vertexaisearch.cloud.google.com",)
66
+
67
+ # --- default models -------------------------------------------------------------------------
68
+ DEFAULT_MODELS = {"gemini": "gemini-3.1-flash-lite", "anthropic": "claude-haiku-5-5",
69
+ "openai": "gpt-4.1-mini", "perplexity": "sonar"}
70
+
71
+ # --- pricing table: VERIFY BEFORE RELYING --------------------------------------------------
72
+ # input/output: USD per 1M tokens. per_search: USD per search/tool call the provider bills.
73
+ # per_request: USD per request (Perplexity request fee). search_input_tokens: input tokens
74
+ # ASSUMED per search for the estimate (search results billed as input).
75
+ PRICING: dict[str, dict[str, dict]] = {
76
+ "gemini": {
77
+ # https://aistudio.google.com/docs/pricing (checked 2026-11-29). Grounding with Google
78
+ # Search on Gemini 3+: 5,000 free searches/month shared, then $14 per 1,000. The
79
+ # estimate ignores the free tier (assumes every search is billed).
80
+ "gemini-3.1-flash-lite": {"input": 0.25, "output": 1.50, "per_search": 0.014,
81
+ "per_request": 0.0, "search_input_tokens": 0,
82
+ "source": "https://aistudio.google.com/docs/pricing",
83
+ "checked_on": CHECKED_ON, "verified": True},
84
+ "gemini-3-flash-preview": {"input": 0.50, "output": 3.00, "per_search": 0.014,
85
+ "per_request": 0.0, "search_input_tokens": 0,
86
+ "source": "https://aistudio.google.com/docs/pricing",
87
+ "checked_on": CHECKED_ON, "verified": True},
88
+ },
89
+ "anthropic": {
90
+ # https://platform.claude.com/docs/en/about-claude/pricing (checked 2026-11-29):
91
+ # Claude Haiku 5.5 $0.10 in / $0.50 out per MTok for prompts up to 100,000 tokens;
92
+ # web search $10 per 1,000 searches; search results count as input tokens.
93
+ "claude-haiku-5-5": {"input": 0.10, "output": 0.50, "per_search": 0.010,
94
+ "per_request": 0.0, "search_input_tokens": 10_000,
95
+ "source": "https://platform.claude.com/docs/en/about-claude/pricing",
96
+ "checked_on": CHECKED_ON, "verified": True},
97
+ "claude-sonnet-5-5": {"input": 2.00, "output": 10.00, "per_search": 0.010,
98
+ "per_request": 0.0, "search_input_tokens": 10_000,
99
+ "source": "https://platform.claude.com/docs/en/about-claude/pricing",
100
+ "checked_on": CHECKED_ON, "verified": True},
101
+ },
102
+ "openai": {
103
+ # https://developers.openai.com/api/docs/pricing (checked 2026-11-29): gpt-4.1-mini
104
+ # $0.40 in / $1.60 out; web search $10 per 1,000 calls; for gpt-4.1-mini search
105
+ # content is billed as a fixed block of 8,000 input tokens per call.
106
+ "gpt-4.1-mini": {"input": 0.40, "output": 1.60, "per_search": 0.010,
107
+ "per_request": 0.0, "search_input_tokens": 8_000,
108
+ "source": "https://developers.openai.com/api/docs/pricing",
109
+ "checked_on": CHECKED_ON, "verified": True,
110
+ "note": "UNVERIFIED: whether usage.input_tokens already includes the 8,000-token search block is not documented; the actual cost uses usage as reported"},
111
+ },
112
+ "perplexity": {
113
+ # UNVERIFIED: Perplexity's own pricing page did not show Sonar prices on 2026-11-29.
114
+ # Third-party summaries (requesty.ai, activepieces.com) give $1/$1 per MTok and a
115
+ # request fee of $5/$8/$12 per 1,000 by search context size; the estimate assumes
116
+ # the HIGHEST fee ($12 per 1,000) because the context size used is not confirmed.
117
+ "sonar": {"input": 1.00, "output": 1.00, "per_search": 0.0, "per_request": 0.012,
118
+ "search_input_tokens": 0,
119
+ "source": "UNVERIFIED third-party: https://www.requesty.ai/model/perplexity/sonar",
120
+ "checked_on": CHECKED_ON, "verified": False},
121
+ },
122
+ }
123
+
124
+ # --- estimate assumptions (documented in docs/track.md) ------------------------------------
125
+ DEFAULT_MAX_OUTPUT_TOKENS = 800 # sent to every engine as the output cap
126
+ BYTES_PER_TOKEN = 2 # [heuristic] input tokens ~ UTF-8 bytes / 2 (Bengali
127
+ # text is 3 bytes per character, so this over-counts
128
+ # Latin text and is roughly 1.5 tokens per Bengali char)
129
+ REQUEST_OVERHEAD_TOKENS = { # tool definitions / tool system prompt, assumed
130
+ "gemini": 50, "anthropic": 600, "openai": 200, "perplexity": 50}
131
+ ASSUMED_SEARCHES_PER_CALL = 1 # Anthropic is capped at 1 (max_uses); others are not
132
+ DEFAULT_MAX_COST_USD = 1.00
133
+ MAX_COST_HARD_LIMIT_USD = 1000.0
134
+
135
+ # --- Bengali case suffixes ([heuristic], UNVERIFIED) ---------------------------------------
136
+ # Bengali attaches case endings and particles directly to a name, without a space:
137
+ # অ্যাকমির (genitive), অ্যাকমিকে (objective), অ্যাকমিতে / অ্যাকমিয় (locative), অ্যাকমিও (also),
138
+ # অ্যাকমিই (emphatic), plural/classifier forms. A mention of a Bengali name may be followed by
139
+ # ONE of these endings and then a word boundary; anything else (অ্যাকমিওলজি) is not a mention.
140
+ # The list is a hand-made heuristic from common Bengali grammar, not from a dictionary or
141
+ # a morphological analyser, and was not checked against a corpus. It is applied only when
142
+ # the name ends in a Bengali-script character; Latin names stay strict whole-word matches.
143
+ BENGALI_SUFFIXES_CHECKED_ON = CHECKED_ON
144
+ BENGALI_SUFFIXES_NOTE = ("[heuristic] hand-made list of common Bengali case endings and "
145
+ "particles; UNVERIFIED against a corpus")
146
+ BENGALI_SUFFIXES = ("র", "ের", "এর", "কে", "রে", "তে", "ে", "য়", "য়ে", "এ", "দের", "রা",
147
+ "ও", "ই", "টি", "টা", "টির", "টার", "গুলো", "গুলি", "গুলোর", "গুলির")
148
+
149
+ # --- Search Console history ------------------------------------------------------------------
150
+ # Search Console data arrives with a delay of a few days; the default window ends this many
151
+ # days before today. ASSUMPTION (UNVERIFIED as an exact figure): Google's help describes the
152
+ # delay only as "a few days"; use --end to choose the end date yourself.
153
+ GSC_DATA_LAG_DAYS = 3
154
+ GSC_MAX_DAYS = 480 # Search Console keeps about 16 months of data
155
+ GSC_TOP_ROWS = 1000 # queries / pages kept per snapshot (top by clicks)