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.
- omnirank/__init__.py +14 -0
- omnirank/__main__.py +6 -0
- omnirank/adapters/__init__.py +202 -0
- omnirank/adapters/astro.py +338 -0
- omnirank/adapters/base.py +372 -0
- omnirank/adapters/html.py +561 -0
- omnirank/adapters/jsx.py +340 -0
- omnirank/adapters/nextjs.py +692 -0
- omnirank/aeo/__init__.py +9 -0
- omnirank/aeo/extract.py +383 -0
- omnirank/aeo/propose.py +84 -0
- omnirank/aeo/rules.py +964 -0
- omnirank/aeo/runner.py +148 -0
- omnirank/applicability.py +98 -0
- omnirank/apply/__init__.py +23 -0
- omnirank/apply/engine.py +1254 -0
- omnirank/apply/journal.py +139 -0
- omnirank/apply/patch.py +144 -0
- omnirank/audit.py +185 -0
- omnirank/bands.py +106 -0
- omnirank/brief/__init__.py +0 -0
- omnirank/brief/analyze.py +197 -0
- omnirank/brief/constants.py +89 -0
- omnirank/brief/cost.py +62 -0
- omnirank/brief/egress.py +23 -0
- omnirank/brief/fetchpages.py +239 -0
- omnirank/brief/render.py +151 -0
- omnirank/brief/runner.py +369 -0
- omnirank/brief/serp.py +274 -0
- omnirank/brief/text.py +181 -0
- omnirank/cli.py +844 -0
- omnirank/clock.py +22 -0
- omnirank/cms/__init__.py +1 -0
- omnirank/cms/runner.py +170 -0
- omnirank/cms/wordpress.py +495 -0
- omnirank/cms/wordpress_apply.py +508 -0
- omnirank/cms/wordpress_plan.py +280 -0
- omnirank/config.py +81 -0
- omnirank/connect/__init__.py +4 -0
- omnirank/connect/bing.py +284 -0
- omnirank/connect/cloud_setup.py +43 -0
- omnirank/connect/confirm.py +242 -0
- omnirank/connect/constants.py +226 -0
- omnirank/connect/doctor.py +270 -0
- omnirank/connect/ga4.py +749 -0
- omnirank/connect/ga4_ai.py +123 -0
- omnirank/connect/google_auth.py +657 -0
- omnirank/connect/gsc.py +630 -0
- omnirank/connect/gsc_reports.py +169 -0
- omnirank/connect/http.py +310 -0
- omnirank/connect/indexnow.py +373 -0
- omnirank/connect/naver.py +536 -0
- omnirank/connect/runner.py +515 -0
- omnirank/connect/runner_ga4_ai.py +59 -0
- omnirank/connect/runner_more.py +489 -0
- omnirank/connect/runner_regional.py +260 -0
- omnirank/connect/secrets.py +190 -0
- omnirank/connect/urlcheck.py +41 -0
- omnirank/connect/yandex.py +350 -0
- omnirank/crawl/__init__.py +11 -0
- omnirank/crawl/analyze.py +493 -0
- omnirank/crawl/crawler.py +491 -0
- omnirank/crawl/custom.py +175 -0
- omnirank/crawl/export.py +67 -0
- omnirank/crawl/fetcher.py +212 -0
- omnirank/crawl/parse.py +102 -0
- omnirank/crawl/render.py +148 -0
- omnirank/crawl/robotsgate.py +198 -0
- omnirank/crawl/runner.py +295 -0
- omnirank/crawl/sitemap.py +99 -0
- omnirank/crawl/text.py +20 -0
- omnirank/crawl/urls.py +100 -0
- omnirank/crawlers.py +564 -0
- omnirank/data/ai_crawlers.json +269 -0
- omnirank/data/ai_referrers.json +42 -0
- omnirank/fetch.py +107 -0
- omnirank/fixes/__init__.py +92 -0
- omnirank/fixes/base.py +232 -0
- omnirank/fixes/canonical.py +243 -0
- omnirank/fixes/schema.py +126 -0
- omnirank/formats.py +134 -0
- omnirank/framework.py +223 -0
- omnirank/gates/__init__.py +48 -0
- omnirank/gates/aeo.py +114 -0
- omnirank/gates/contradictions.py +280 -0
- omnirank/gates/crawler_policy.py +85 -0
- omnirank/gates/geo.py +152 -0
- omnirank/gates/hygiene.py +81 -0
- omnirank/gates/jsonld.py +282 -0
- omnirank/gates/onpage.py +177 -0
- omnirank/gates/perf.py +115 -0
- omnirank/gates/security.py +264 -0
- omnirank/gates/seo.py +118 -0
- omnirank/gates/site.py +248 -0
- omnirank/geo_artifacts.py +199 -0
- omnirank/html.py +79 -0
- omnirank/keywords/__init__.py +5 -0
- omnirank/keywords/constants.py +69 -0
- omnirank/keywords/engine.py +384 -0
- omnirank/keywords/report.py +143 -0
- omnirank/keywords/runner.py +160 -0
- omnirank/keywords/source.py +60 -0
- omnirank/keywords/text.py +45 -0
- omnirank/locator.py +480 -0
- omnirank/logs/__init__.py +0 -0
- omnirank/logs/analyze.py +127 -0
- omnirank/logs/bots.py +69 -0
- omnirank/logs/ipranges.py +191 -0
- omnirank/logs/parse.py +452 -0
- omnirank/logs/paths.py +22 -0
- omnirank/logs/privacy.py +105 -0
- omnirank/logs/runner.py +179 -0
- omnirank/mcp_server.py +1480 -0
- omnirank/netguard.py +525 -0
- omnirank/packs/__init__.py +6 -0
- omnirank/packs/backlinks.py +535 -0
- omnirank/packs/blog.py +544 -0
- omnirank/packs/blog_cross.py +468 -0
- omnirank/packs/crawlers.py +23 -0
- omnirank/packs/entity.py +492 -0
- omnirank/packs/feeds.py +150 -0
- omnirank/packs/frontmatter.py +59 -0
- omnirank/packs/gsc.py +421 -0
- omnirank/packs/local.py +879 -0
- omnirank/packs/mdscan.py +326 -0
- omnirank/packs/miniyaml.py +378 -0
- omnirank/packs/model.py +46 -0
- omnirank/packs/product.py +979 -0
- omnirank/packs/refresh.py +165 -0
- omnirank/packs/runner.py +277 -0
- omnirank/packs/sitescan.py +294 -0
- omnirank/packs/textsafe.py +79 -0
- omnirank/packs/xmlsafe.py +92 -0
- omnirank/page.py +42 -0
- omnirank/registry.py +302 -0
- omnirank/report.py +251 -0
- omnirank/report_cmd/__init__.py +7 -0
- omnirank/report_cmd/delta.py +58 -0
- omnirank/report_cmd/files.py +64 -0
- omnirank/report_cmd/model.py +208 -0
- omnirank/report_cmd/notify.py +195 -0
- omnirank/report_cmd/pdf.py +83 -0
- omnirank/report_cmd/portfolio.py +342 -0
- omnirank/report_cmd/render.py +379 -0
- omnirank/report_cmd/runner.py +267 -0
- omnirank/robots.py +172 -0
- omnirank/scanner/__init__.py +10 -0
- omnirank/scanner/badge.py +90 -0
- omnirank/scanner/cache.py +69 -0
- omnirank/scanner/cli.py +96 -0
- omnirank/scanner/engine.py +289 -0
- omnirank/scanner/limits.py +98 -0
- omnirank/scanner/server.py +143 -0
- omnirank/scanner/service.py +328 -0
- omnirank/schema/__init__.py +13 -0
- omnirank/schema/catalog.py +679 -0
- omnirank/schema/catalog_specs.py +350 -0
- omnirank/schema/core.py +306 -0
- omnirank/schema/extract.py +396 -0
- omnirank/schema/gate.py +121 -0
- omnirank/schema/runner.py +213 -0
- omnirank/schema/validate.py +504 -0
- omnirank/schema/vocab.py +305 -0
- omnirank/schemas/omnirank.config.schema.json +268 -0
- omnirank/track/__init__.py +0 -0
- omnirank/track/ai_prompts.py +207 -0
- omnirank/track/analysis.py +197 -0
- omnirank/track/constants.py +155 -0
- omnirank/track/cost.py +229 -0
- omnirank/track/discover.py +277 -0
- omnirank/track/discover_cli.py +309 -0
- omnirank/track/discover_constants.py +95 -0
- omnirank/track/engines.py +216 -0
- omnirank/track/estimate_view.py +212 -0
- omnirank/track/history.py +261 -0
- omnirank/track/runner.py +586 -0
- omnirank/track/stats.py +138 -0
- omnirank/track/storage.py +128 -0
- omnirank-0.5.0.dist-info/METADATA +47 -0
- omnirank-0.5.0.dist-info/RECORD +183 -0
- omnirank-0.5.0.dist-info/WHEEL +5 -0
- omnirank-0.5.0.dist-info/entry_points.txt +2 -0
- omnirank-0.5.0.dist-info/top_level.txt +1 -0
omnirank/locator.py
ADDED
|
@@ -0,0 +1,480 @@
|
|
|
1
|
+
"""Resolve a finding's URL to the source file that owns it.
|
|
2
|
+
|
|
3
|
+
This is the competitive moat and the riskiest component in the product, so it
|
|
4
|
+
is built to refuse rather than to guess. Every incumbent keys its output to a
|
|
5
|
+
URL because a URL is the only thing it can see; OmniRank runs inside the
|
|
6
|
+
repository, so it can answer "which file is wrong?" -- but only where it can
|
|
7
|
+
answer correctly. Two equally specific route matches produce NOT_LOCATED, not a
|
|
8
|
+
coin flip. An unimplemented framework produces NOT_LOCATED, not a plausible
|
|
9
|
+
path. `none` confidence demotes the fix to display-only, and that is the
|
|
10
|
+
correct outcome, not a failure of the tool.
|
|
11
|
+
|
|
12
|
+
`Location.path` may be set while `confidence == "none"`: that is the "we know
|
|
13
|
+
the file but you may not edit it" case (a page exporting `generateMetadata`
|
|
14
|
+
rather than a static `metadata` object). Naming the file is strictly more
|
|
15
|
+
useful than silence, and the `none` still blocks the fix.
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import re
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
from pathlib import Path, PurePosixPath
|
|
22
|
+
from urllib.parse import urlsplit
|
|
23
|
+
|
|
24
|
+
from .applicability import LocatorConfidence
|
|
25
|
+
from .framework import Detection
|
|
26
|
+
|
|
27
|
+
PAGE_FILES = ("page.tsx", "page.jsx", "page.ts", "page.js")
|
|
28
|
+
|
|
29
|
+
_METADATA_EXPORT = re.compile(r"^\s*export\s+const\s+metadata\b")
|
|
30
|
+
_GENERATE_METADATA = re.compile(
|
|
31
|
+
r"^\s*export\s+(?:async\s+)?function\s+generateMetadata\b")
|
|
32
|
+
_HEAD_TAG = re.compile(r"<head\b", re.IGNORECASE)
|
|
33
|
+
|
|
34
|
+
# [slug] and [...slug]. `[[...slug]]` deliberately does NOT match: the opening
|
|
35
|
+
# bracket is not in the character class, so the two patterns stay disjoint.
|
|
36
|
+
_DYNAMIC = re.compile(r"^\[(\.{3})?([A-Za-z0-9_-]+)\]$")
|
|
37
|
+
_OPTIONAL_CATCH_ALL = re.compile(r"^\[\[\.{3}([A-Za-z0-9_-]+)\]\]$")
|
|
38
|
+
|
|
39
|
+
_CONFIDENCE_RANK: dict[LocatorConfidence, int] = {"none": 0, "inferred": 1, "exact": 2}
|
|
40
|
+
_BY_RANK: dict[int, LocatorConfidence] = {0: "none", 1: "inferred", 2: "exact"}
|
|
41
|
+
|
|
42
|
+
# Detection confidence propagates: a framework we only half-recognise cannot
|
|
43
|
+
# produce a confidently located file. A `low` detection therefore caps the
|
|
44
|
+
# locator at `none`, which caps applicability at display-only.
|
|
45
|
+
DETECTION_CEILING: dict[str, LocatorConfidence] = {
|
|
46
|
+
"high": "exact",
|
|
47
|
+
"medium": "inferred",
|
|
48
|
+
"low": "none",
|
|
49
|
+
"none": "none",
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass(frozen=True)
|
|
54
|
+
class Location:
|
|
55
|
+
"""Where a finding lives in the source tree, and how sure we are."""
|
|
56
|
+
|
|
57
|
+
path: str | None = None
|
|
58
|
+
line: int | None = None
|
|
59
|
+
confidence: LocatorConfidence = "none"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
NOT_LOCATED = Location()
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def route_of(url: str) -> str:
|
|
66
|
+
"""The site-relative route for a URL: always a leading '/', never trailing."""
|
|
67
|
+
trimmed = (urlsplit(url).path or "/").rstrip("/")
|
|
68
|
+
return trimmed or "/"
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _segments(route: str) -> list[str]:
|
|
72
|
+
return [part for part in route.split("/") if part]
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _min_confidence(*values: LocatorConfidence) -> LocatorConfidence:
|
|
76
|
+
return _BY_RANK[min(_CONFIDENCE_RANK[value] for value in values)]
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _app_root(root: Path) -> Path | None:
|
|
80
|
+
for candidate in ("app", "src/app"):
|
|
81
|
+
directory = root / candidate
|
|
82
|
+
if directory.is_dir():
|
|
83
|
+
return directory
|
|
84
|
+
return None
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _route_segments_for(page: Path, app_root: Path) -> list[str] | None:
|
|
88
|
+
"""The route pattern a page file serves, as segments, or `None` if the
|
|
89
|
+
file is not routable by any URL.
|
|
90
|
+
|
|
91
|
+
Route groups `(marketing)` are non-routing: they organise the tree
|
|
92
|
+
without appearing in the URL, so they are dropped here -- the page
|
|
93
|
+
underneath is still reachable, just at a shorter path.
|
|
94
|
+
|
|
95
|
+
A `_`-prefixed folder and an `@`-prefixed parallel-route slot are BOTH
|
|
96
|
+
different in kind, not degree, and neither is route-group semantics.
|
|
97
|
+
Next.js opts a `_`-prefixed folder *and everything beneath it* out of
|
|
98
|
+
routing entirely, so a page under `_internal/` is served by no URL at
|
|
99
|
+
all. A `@`-prefixed folder is a parallel-route SLOT, not a path segment:
|
|
100
|
+
per Next's own docs, "the `children` prop is an implicit slot ...
|
|
101
|
+
`app/page.js` is equivalent to `app/@children/page.js`", and a slot with
|
|
102
|
+
no matching sibling `page` at that level renders `default.js` or 404s --
|
|
103
|
+
it is never reached by stripping the `@name` and matching what's left,
|
|
104
|
+
the way a route group is. Stripping either prefix and matching on what
|
|
105
|
+
remains treats a folder that isn't a route group as if it were one.
|
|
106
|
+
Getting this wrong is how a locator confidently reports a file a real
|
|
107
|
+
deployment 404s on (an unmatched `@analytics/page.tsx` alone), or misses
|
|
108
|
+
the one it should have found (Next's own canonical shape, `app/page.tsx`
|
|
109
|
+
alongside `app/@auth/page.tsx`, where the un-prefixed sibling is exactly
|
|
110
|
+
the file that serves the route).
|
|
111
|
+
"""
|
|
112
|
+
out: list[str] = []
|
|
113
|
+
for part in page.parent.relative_to(app_root).parts:
|
|
114
|
+
if part.startswith("(") and part.endswith(")"):
|
|
115
|
+
continue
|
|
116
|
+
if part.startswith(("_", "@")):
|
|
117
|
+
return None
|
|
118
|
+
out.append(part)
|
|
119
|
+
return out
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _match(pattern: list[str], target: list[str]) -> tuple[int, bool] | None:
|
|
123
|
+
"""Match a route pattern against concrete segments.
|
|
124
|
+
|
|
125
|
+
Returns `(static_segments_matched, used_a_dynamic_segment)`, or None when
|
|
126
|
+
the pattern does not match. The static count is the specificity score:
|
|
127
|
+
`/blog/archive` must beat `/blog/[slug]`.
|
|
128
|
+
"""
|
|
129
|
+
if not pattern:
|
|
130
|
+
return (0, False) if not target else None
|
|
131
|
+
|
|
132
|
+
head, rest = pattern[0], pattern[1:]
|
|
133
|
+
|
|
134
|
+
if _OPTIONAL_CATCH_ALL.match(head):
|
|
135
|
+
# [[...slug]] matches zero or more segments and is always terminal.
|
|
136
|
+
return None if rest else (0, True)
|
|
137
|
+
|
|
138
|
+
dynamic = _DYNAMIC.match(head)
|
|
139
|
+
if dynamic:
|
|
140
|
+
if dynamic.group(1) is not None:
|
|
141
|
+
# [...slug] matches one or more segments and is always terminal.
|
|
142
|
+
return None if rest or not target else (0, True)
|
|
143
|
+
if not target:
|
|
144
|
+
return None
|
|
145
|
+
tail = _match(rest, target[1:])
|
|
146
|
+
return None if tail is None else (tail[0], True)
|
|
147
|
+
|
|
148
|
+
if not target or target[0] != head:
|
|
149
|
+
return None
|
|
150
|
+
tail = _match(rest, target[1:])
|
|
151
|
+
return None if tail is None else (tail[0] + 1, tail[1])
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _next_metadata(page: Path) -> tuple[int | None, LocatorConfidence]:
|
|
155
|
+
"""Where the page's metadata lives, and whether it is editable at all.
|
|
156
|
+
|
|
157
|
+
`export const metadata` is a static object literal an edit can target.
|
|
158
|
+
`generateMetadata` computes the value at request time -- the file is right
|
|
159
|
+
but the edit target is a function body this tool will not rewrite, so
|
|
160
|
+
confidence drops to `none`. A page with neither is still an exact location:
|
|
161
|
+
the mechanical fix inserts a new export rather than modifying one.
|
|
162
|
+
"""
|
|
163
|
+
try:
|
|
164
|
+
text = page.read_text(encoding="utf-8")
|
|
165
|
+
except (OSError, UnicodeDecodeError):
|
|
166
|
+
return None, "none"
|
|
167
|
+
|
|
168
|
+
generated: int | None = None
|
|
169
|
+
for number, line in enumerate(text.splitlines(), start=1):
|
|
170
|
+
if _METADATA_EXPORT.match(line):
|
|
171
|
+
return number, "exact"
|
|
172
|
+
if generated is None and _GENERATE_METADATA.match(line):
|
|
173
|
+
generated = number
|
|
174
|
+
if generated is not None:
|
|
175
|
+
return generated, "none"
|
|
176
|
+
return None, "exact"
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _head_line(path: Path) -> int | None:
|
|
180
|
+
"""1-indexed line of the first `<head` in an HTML file, else None."""
|
|
181
|
+
if path.suffix.lower() not in (".html", ".htm"):
|
|
182
|
+
return None
|
|
183
|
+
try:
|
|
184
|
+
text = path.read_text(encoding="utf-8")
|
|
185
|
+
except (OSError, UnicodeDecodeError):
|
|
186
|
+
return None
|
|
187
|
+
for number, line in enumerate(text.splitlines(), start=1):
|
|
188
|
+
if _HEAD_TAG.search(line):
|
|
189
|
+
return number
|
|
190
|
+
return None
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _locate_next_app_router(route: str, root: Path) -> Location:
|
|
194
|
+
app_root = _app_root(root)
|
|
195
|
+
if app_root is None:
|
|
196
|
+
return NOT_LOCATED
|
|
197
|
+
|
|
198
|
+
target = _segments(route)
|
|
199
|
+
matches: list[tuple[int, bool, Path]] = []
|
|
200
|
+
for page in sorted(app_root.rglob("*")):
|
|
201
|
+
if page.name not in PAGE_FILES or not page.is_file():
|
|
202
|
+
continue
|
|
203
|
+
segments = _route_segments_for(page, app_root)
|
|
204
|
+
if segments is None:
|
|
205
|
+
continue # under a `_private` folder or `@slot`: no URL reaches it
|
|
206
|
+
result = _match(segments, target)
|
|
207
|
+
if result is not None:
|
|
208
|
+
matches.append((result[0], result[1], page))
|
|
209
|
+
|
|
210
|
+
if not matches:
|
|
211
|
+
return NOT_LOCATED
|
|
212
|
+
|
|
213
|
+
top = max(score for score, _dynamic, _page in matches)
|
|
214
|
+
winners = [entry for entry in matches if entry[0] == top]
|
|
215
|
+
if len(winners) > 1:
|
|
216
|
+
# Two routes are equally entitled to this URL. Never pick one.
|
|
217
|
+
return NOT_LOCATED
|
|
218
|
+
|
|
219
|
+
_score, used_dynamic, page = winners[0]
|
|
220
|
+
route_confidence: LocatorConfidence = "inferred" if used_dynamic else "exact"
|
|
221
|
+
line, metadata_confidence = _next_metadata(page)
|
|
222
|
+
return Location(path=page.relative_to(root).as_posix(), line=line,
|
|
223
|
+
confidence=_min_confidence(route_confidence, metadata_confidence))
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
# Where a static site's HTML might live. "" is the repo root; the other two are
|
|
227
|
+
# the conventional build outputs a static project commits or generates.
|
|
228
|
+
STATIC_ROOTS: tuple[str, ...] = ("", "public", "dist")
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _prefixed(base: str, name: str) -> str:
|
|
232
|
+
return f"{base}/{name}" if base else name
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _resolve_candidate(root: Path, relative: str) -> Path | None:
|
|
236
|
+
"""The real on-disk path for `relative` under `root`, or `None` if it
|
|
237
|
+
escapes `root` or doesn't match on disk byte-for-byte.
|
|
238
|
+
|
|
239
|
+
Two independent gaps, one gate. First, `relative` is built directly from
|
|
240
|
+
URL segments, so a `../` in the URL (or, after `.resolve()`, a symlink
|
|
241
|
+
*inside* the repo whose target lives outside it) must not be allowed to
|
|
242
|
+
walk out of the repository -- nothing writes through a `Location.path`
|
|
243
|
+
yet, but the release that adds writing opens `root / location.path`
|
|
244
|
+
directly, and an escaped candidate today is arbitrary-file-write the day
|
|
245
|
+
that lands. Second,
|
|
246
|
+
`Path.is_file()` follows the host filesystem's own case folding, which is
|
|
247
|
+
on by default on macOS and Windows and off on Linux CI, so a naive check
|
|
248
|
+
would match `/pricing` to an on-disk `Pricing.html` on a contributor's
|
|
249
|
+
Mac and not in CI.
|
|
250
|
+
|
|
251
|
+
Walking `relative` one component at a time against each directory's real
|
|
252
|
+
`iterdir()` entries closes both at once: a literal `..` component is
|
|
253
|
+
never a real entry (`iterdir()` never yields `.` or `..`), so a traversal
|
|
254
|
+
attempt fails here before the filesystem is ever asked to resolve
|
|
255
|
+
anything, and comparing names exactly makes the match case-sensitive on
|
|
256
|
+
every platform, matching `next-app-router`'s plain string comparison.
|
|
257
|
+
The trailing `resolve()` + containment check is what catches the one
|
|
258
|
+
case a name-walk alone cannot: a symlink whose *target* -- not its own
|
|
259
|
+
name -- points outside `root`.
|
|
260
|
+
"""
|
|
261
|
+
current = root
|
|
262
|
+
for part in Path(relative).parts:
|
|
263
|
+
try:
|
|
264
|
+
names = {entry.name for entry in current.iterdir()}
|
|
265
|
+
except OSError:
|
|
266
|
+
return None
|
|
267
|
+
if part not in names:
|
|
268
|
+
return None
|
|
269
|
+
current = current / part
|
|
270
|
+
|
|
271
|
+
try:
|
|
272
|
+
resolved_root = root.resolve()
|
|
273
|
+
resolved_candidate = current.resolve()
|
|
274
|
+
except OSError:
|
|
275
|
+
return None
|
|
276
|
+
if not resolved_candidate.is_relative_to(resolved_root):
|
|
277
|
+
return None
|
|
278
|
+
return current
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def _locate_by_convention(root: Path, relatives: list[str]) -> Location:
|
|
282
|
+
"""Resolve only when EXACTLY ONE candidate exists.
|
|
283
|
+
|
|
284
|
+
Two candidates is a genuine ambiguity -- `pricing.html` and
|
|
285
|
+
`pricing/index.html` are both plausible owners of `/pricing` and the answer
|
|
286
|
+
depends on server configuration this tool cannot read. Picking one and
|
|
287
|
+
editing it is the failure mode the whole design exists to avoid. A
|
|
288
|
+
candidate that fails `_resolve_candidate` (escapes `root`, or only matches
|
|
289
|
+
case-insensitively) is not a candidate at all -- it is excluded before
|
|
290
|
+
the ambiguity count is taken, not treated as a tie-breaking loss.
|
|
291
|
+
"""
|
|
292
|
+
hits: list[tuple[str, Path]] = []
|
|
293
|
+
for relative in relatives:
|
|
294
|
+
candidate = _resolve_candidate(root, relative)
|
|
295
|
+
if candidate is not None and candidate.is_file():
|
|
296
|
+
hits.append((relative, candidate))
|
|
297
|
+
if len(hits) != 1:
|
|
298
|
+
return NOT_LOCATED
|
|
299
|
+
relative, candidate = hits[0]
|
|
300
|
+
return Location(path=relative, line=_head_line(candidate), confidence="exact")
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _locate_static(route: str, root: Path) -> Location:
|
|
304
|
+
if route == "/":
|
|
305
|
+
names = ("index.html",)
|
|
306
|
+
else:
|
|
307
|
+
stem = route.lstrip("/")
|
|
308
|
+
names = (f"{stem}/index.html", f"{stem}.html")
|
|
309
|
+
return _locate_by_convention(
|
|
310
|
+
root, [_prefixed(base, name) for base in STATIC_ROOTS for name in names])
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def _locate_jekyll(route: str, root: Path) -> Location:
|
|
314
|
+
"""Resolve to the SOURCE page, never `_site/`.
|
|
315
|
+
|
|
316
|
+
Patching built output is erased by the next `jekyll build`. A source page's
|
|
317
|
+
front matter is a durable edit target and serves exactly one route.
|
|
318
|
+
Following its `layout:` up to `_layouts/*.html` is a second hop whose
|
|
319
|
+
fan-out is every post on the site; that arrives with the edit engine in
|
|
320
|
+
a later release, not here.
|
|
321
|
+
"""
|
|
322
|
+
if route == "/":
|
|
323
|
+
names = ["index.html", "index.md", "index.markdown"]
|
|
324
|
+
else:
|
|
325
|
+
stem = route.lstrip("/")
|
|
326
|
+
names = [f"{stem}.md", f"{stem}.html", f"{stem}/index.md",
|
|
327
|
+
f"{stem}/index.html"]
|
|
328
|
+
return _locate_by_convention(root, names)
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def _locate_hugo(route: str, root: Path) -> Location:
|
|
332
|
+
"""Resolve into `content/`, Hugo's source tree, never `public/`."""
|
|
333
|
+
if route == "/":
|
|
334
|
+
names = ["content/_index.md"]
|
|
335
|
+
else:
|
|
336
|
+
stem = route.lstrip("/")
|
|
337
|
+
names = [f"content/{stem}.md", f"content/{stem}/index.md",
|
|
338
|
+
f"content/{stem}/_index.md"]
|
|
339
|
+
return _locate_by_convention(root, names)
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
ASTRO_PAGES = "src/pages"
|
|
343
|
+
_ASTRO_PAGE_SUFFIXES = (".astro", ".md", ".mdx", ".html")
|
|
344
|
+
_ASTRO_CONFIGS = ("astro.config.mjs", "astro.config.js", "astro.config.ts",
|
|
345
|
+
"astro.config.mts", "astro.config.cjs")
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def _astro_base_configured(root: Path) -> bool:
|
|
349
|
+
"""True when astro.config sets `base`, `i18n`, `redirects` or `srcDir` --
|
|
350
|
+
options that move routes or pages away from `src/pages/` -- or cannot be
|
|
351
|
+
read; the resolver then refuses."""
|
|
352
|
+
for name in _ASTRO_CONFIGS:
|
|
353
|
+
path = root / name
|
|
354
|
+
if path.is_file():
|
|
355
|
+
try:
|
|
356
|
+
text = path.read_text(encoding="utf-8")
|
|
357
|
+
except (OSError, UnicodeDecodeError):
|
|
358
|
+
return True
|
|
359
|
+
if re.search(r"\b(?:base|i18n|redirects|srcDir)\s*:", text):
|
|
360
|
+
return True
|
|
361
|
+
return False
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def _locate_astro(route: str, root: Path) -> Location:
|
|
365
|
+
"""Static `src/pages/` routes only, never `dist/`.
|
|
366
|
+
|
|
367
|
+
`/about` is `src/pages/about.astro` or `src/pages/about/index.astro` (or
|
|
368
|
+
the `.md`/`.mdx`/`.html` equivalents); exactly one must exist. Dynamic
|
|
369
|
+
routes (`[slug].astro`) are not resolved, `_`-prefixed files are not
|
|
370
|
+
routes in Astro, and a config with `base`, `i18n`, `redirects` or `srcDir`
|
|
371
|
+
changes the URL-to-file mapping in ways this resolver does not model, so
|
|
372
|
+
all of those are NOT_LOCATED.
|
|
373
|
+
"""
|
|
374
|
+
if _astro_base_configured(root):
|
|
375
|
+
return NOT_LOCATED
|
|
376
|
+
segments = _segments(route)
|
|
377
|
+
if any(part.startswith("_") for part in segments):
|
|
378
|
+
return NOT_LOCATED
|
|
379
|
+
stem = "/".join(segments)
|
|
380
|
+
names = ([f"index{suffix}" for suffix in _ASTRO_PAGE_SUFFIXES] if not stem else
|
|
381
|
+
[f"{stem}{suffix}" for suffix in _ASTRO_PAGE_SUFFIXES]
|
|
382
|
+
+ [f"{stem}/index{suffix}" for suffix in _ASTRO_PAGE_SUFFIXES])
|
|
383
|
+
return _locate_by_convention(root, [f"{ASTRO_PAGES}/{name}" for name in names])
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
# Frameworks with no entry here return NOT_LOCATED. `next-pages-router`,
|
|
387
|
+
# `nuxt`, `sveltekit`, `eleventy` and `wordpress` are deliberately absent: an
|
|
388
|
+
# honest `none` demotes their findings to display-only, which is correct,
|
|
389
|
+
# whereas a half-implemented resolver produces a confident diff against the
|
|
390
|
+
# wrong file.
|
|
391
|
+
_BY_FRAMEWORK = {
|
|
392
|
+
"next-app-router": _locate_next_app_router,
|
|
393
|
+
"static": _locate_static,
|
|
394
|
+
"jekyll": _locate_jekyll,
|
|
395
|
+
"hugo": _locate_hugo,
|
|
396
|
+
"astro": _locate_astro,
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def _escapes_root(root: Path, relative: str) -> bool:
|
|
401
|
+
"""True if `relative`, resolved against `root`, is not a descendant of it.
|
|
402
|
+
|
|
403
|
+
This is the module's final backstop, not its primary defence: every
|
|
404
|
+
resolver is expected to keep its own candidates inside `root` (see
|
|
405
|
+
`_resolve_candidate` for the convention resolvers; `next-app-router` is
|
|
406
|
+
contained by construction, since its candidates come from `rglob()` under
|
|
407
|
+
a known-good `app_root`). This check exists so that a future resolver
|
|
408
|
+
added to `_BY_FRAMEWORK` cannot reintroduce a path-traversal hole simply
|
|
409
|
+
by forgetting to; `locate()` is the one place every resolver's output
|
|
410
|
+
passes through on its way out of this module, so it is the one place a
|
|
411
|
+
module-wide guarantee can actually be enforced.
|
|
412
|
+
"""
|
|
413
|
+
try:
|
|
414
|
+
return not (root / relative).resolve().is_relative_to(root.resolve())
|
|
415
|
+
except OSError:
|
|
416
|
+
return True
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def locate(url: str, *, detection: Detection, root: str | Path) -> Location:
|
|
420
|
+
"""Resolve `url` to a source file. Unresolvable is `NOT_LOCATED`, never a guess."""
|
|
421
|
+
resolver = _BY_FRAMEWORK.get(detection.framework)
|
|
422
|
+
if resolver is None:
|
|
423
|
+
return NOT_LOCATED
|
|
424
|
+
|
|
425
|
+
base = Path(root)
|
|
426
|
+
found = resolver(route_of(url), base)
|
|
427
|
+
if found.path is None:
|
|
428
|
+
return NOT_LOCATED
|
|
429
|
+
if _escapes_root(base, found.path):
|
|
430
|
+
return NOT_LOCATED
|
|
431
|
+
|
|
432
|
+
ceiling = DETECTION_CEILING[detection.confidence]
|
|
433
|
+
return Location(path=found.path, line=found.line,
|
|
434
|
+
confidence=_min_confidence(found.confidence, ceiling))
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
_SINGLE_ROUTE_FRAMEWORKS = ("static", "jekyll", "hugo")
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def blast_radius(location: Location, *, detection: Detection,
|
|
441
|
+
root: str | Path) -> int | None:
|
|
442
|
+
"""How many routes the located file serves, or None when unprovable.
|
|
443
|
+
|
|
444
|
+
None is NOT zero and must never be read as one. `applicability.
|
|
445
|
+
blast_radius_ceiling()` treats it as the worst case, which is the guard
|
|
446
|
+
that stops a literal canonical being written into a layout serving
|
|
447
|
+
thousands of routes -- the single highest-severity failure mode in the
|
|
448
|
+
whole fixability table, and one no URL-keyed tool can even ask about.
|
|
449
|
+
"""
|
|
450
|
+
if location.path is None:
|
|
451
|
+
return None
|
|
452
|
+
if detection.framework in _SINGLE_ROUTE_FRAMEWORKS:
|
|
453
|
+
return 1
|
|
454
|
+
if detection.framework == "astro":
|
|
455
|
+
# A static page under src/pages serves exactly one route; anything
|
|
456
|
+
# else (a layout, a dynamic route, a file that is not there) is unknown.
|
|
457
|
+
path = PurePosixPath(location.path)
|
|
458
|
+
base = Path(root)
|
|
459
|
+
if (path.parts[:2] == ("src", "pages") and "[" not in location.path
|
|
460
|
+
and path.suffix in _ASTRO_PAGE_SUFFIXES
|
|
461
|
+
and (base / location.path).is_file()
|
|
462
|
+
and not any(p.startswith("_") for p in path.parts[2:])):
|
|
463
|
+
return 1
|
|
464
|
+
return None
|
|
465
|
+
if detection.framework != "next-app-router":
|
|
466
|
+
return None
|
|
467
|
+
|
|
468
|
+
base = Path(root)
|
|
469
|
+
app_root = _app_root(base)
|
|
470
|
+
if app_root is None:
|
|
471
|
+
return None
|
|
472
|
+
try:
|
|
473
|
+
segments = _route_segments_for(base / location.path, app_root)
|
|
474
|
+
except ValueError:
|
|
475
|
+
return None # located outside the app directory
|
|
476
|
+
if segments is None:
|
|
477
|
+
return None # not a routable page at all
|
|
478
|
+
dynamic = any(_DYNAMIC.match(segment) or _OPTIONAL_CATCH_ALL.match(segment)
|
|
479
|
+
for segment in segments)
|
|
480
|
+
return None if dynamic else 1
|
|
File without changes
|
omnirank/logs/analyze.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"""Per-bot aggregation of parsed log records into the `omnirank logs` report.
|
|
2
|
+
|
|
3
|
+
Definitions (docs/logs.md):
|
|
4
|
+
|
|
5
|
+
* hits -- requests whose user-agent CLAIMS to be that crawler (``claimed_by_user_agent``);
|
|
6
|
+
* unique URLs -- distinct shown paths (query dropped unless ``--keep-query``);
|
|
7
|
+
* crawl frequency -- hits per UTC day, active days and the mean per active day;
|
|
8
|
+
* wasted crawl -- hits that got a redirect (301, 302, 303, 307, 308), a 4xx, a 5xx, or asked
|
|
9
|
+
for a URL with a query string ("parameter URL"); a hit is counted once in ``total`` even
|
|
10
|
+
when several apply. ``304 Not Modified`` is not waste.
|
|
11
|
+
|
|
12
|
+
Memory is bounded: at most MAX_TRACKED_PATHS distinct paths are tracked per bot. After that,
|
|
13
|
+
hits on paths already tracked are still counted, and hits on NEW paths are counted only in
|
|
14
|
+
``untracked_path_hits``; ``unique_urls`` is then a lower bound (``unique_urls_capped``), and
|
|
15
|
+
``top_paths`` ranks the tracked paths only.
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
from collections import Counter
|
|
20
|
+
from dataclasses import dataclass, field
|
|
21
|
+
|
|
22
|
+
from . import bots, privacy
|
|
23
|
+
from .ipranges import IpRanges
|
|
24
|
+
from .parse import FileStats, Record
|
|
25
|
+
|
|
26
|
+
REDIRECTS = frozenset({301, 302, 303, 307, 308})
|
|
27
|
+
MAX_TRACKED_PATHS = 100_000
|
|
28
|
+
VERIFICATION = ("verified", "mismatch", "unverifiable", "not_checked")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class _BotStats:
|
|
33
|
+
bot: bots.Bot
|
|
34
|
+
hits: int = 0
|
|
35
|
+
paths: Counter = field(default_factory=Counter)
|
|
36
|
+
statuses: Counter = field(default_factory=Counter)
|
|
37
|
+
days: Counter = field(default_factory=Counter)
|
|
38
|
+
verification: Counter = field(default_factory=Counter)
|
|
39
|
+
wasted: Counter = field(default_factory=Counter)
|
|
40
|
+
untracked_path_hits: int = 0
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class Aggregator:
|
|
44
|
+
def __init__(self, *, ranges: IpRanges | None = None, keep_query: bool = False,
|
|
45
|
+
top: int = 10, max_paths: int | None = None):
|
|
46
|
+
self.ranges = ranges
|
|
47
|
+
self.keep_query = keep_query
|
|
48
|
+
self.top = top
|
|
49
|
+
self.max_paths = MAX_TRACKED_PATHS if max_paths is None else max_paths
|
|
50
|
+
self.other_hits = 0
|
|
51
|
+
self._bots: dict[str, _BotStats] = {}
|
|
52
|
+
|
|
53
|
+
def add(self, rec: Record) -> None:
|
|
54
|
+
bot = bots.classify(rec.ua)
|
|
55
|
+
if bot is None:
|
|
56
|
+
self.other_hits += 1
|
|
57
|
+
return
|
|
58
|
+
st = self._bots.get(bot.token)
|
|
59
|
+
if st is None:
|
|
60
|
+
st = self._bots[bot.token] = _BotStats(bot)
|
|
61
|
+
st.hits += 1
|
|
62
|
+
shown, had_query = privacy.clean_target(rec.target, keep_query=self.keep_query)
|
|
63
|
+
if shown in st.paths or len(st.paths) < self.max_paths:
|
|
64
|
+
st.paths[shown] += 1
|
|
65
|
+
else:
|
|
66
|
+
st.untracked_path_hits += 1
|
|
67
|
+
st.statuses[rec.status] += 1
|
|
68
|
+
st.days[rec.day.isoformat()] += 1
|
|
69
|
+
st.verification[self.ranges.check(bot.token, rec.ip) if self.ranges
|
|
70
|
+
else "not_checked"] += 1
|
|
71
|
+
kinds = []
|
|
72
|
+
if rec.status in REDIRECTS:
|
|
73
|
+
kinds.append("redirect")
|
|
74
|
+
if 400 <= rec.status <= 499:
|
|
75
|
+
kinds.append("client_error")
|
|
76
|
+
if 500 <= rec.status <= 599:
|
|
77
|
+
kinds.append("server_error")
|
|
78
|
+
if had_query:
|
|
79
|
+
kinds.append("parameter")
|
|
80
|
+
for kind in kinds:
|
|
81
|
+
st.wasted[kind] += 1
|
|
82
|
+
if kinds:
|
|
83
|
+
st.wasted["total"] += 1
|
|
84
|
+
|
|
85
|
+
@staticmethod
|
|
86
|
+
def _bot_report(st: _BotStats, top: int) -> dict:
|
|
87
|
+
days = dict(sorted(st.days.items()))
|
|
88
|
+
classes: Counter = Counter()
|
|
89
|
+
for code, n in st.statuses.items():
|
|
90
|
+
classes[f"{code // 100}xx"] += n
|
|
91
|
+
top_paths = sorted(st.paths.items(), key=lambda kv: (-kv[1], kv[0]))[:top]
|
|
92
|
+
wasted = {k: st.wasted[k] for k in ("redirect", "client_error", "server_error",
|
|
93
|
+
"parameter", "total")}
|
|
94
|
+
wasted["share"] = round(wasted["total"] / st.hits, 4)
|
|
95
|
+
return {
|
|
96
|
+
"token": st.bot.token, "vendor": st.bot.vendor, "purpose": st.bot.purpose,
|
|
97
|
+
"source": st.bot.source,
|
|
98
|
+
"hits": st.hits, "claimed_by_user_agent": st.hits,
|
|
99
|
+
"ip_verification": {k: st.verification[k] for k in VERIFICATION},
|
|
100
|
+
"unique_urls": len(st.paths),
|
|
101
|
+
"unique_urls_capped": st.untracked_path_hits > 0,
|
|
102
|
+
"untracked_path_hits": st.untracked_path_hits,
|
|
103
|
+
"status_codes": {str(k): v for k, v in sorted(st.statuses.items())},
|
|
104
|
+
"status_classes": dict(sorted(classes.items())),
|
|
105
|
+
"per_day": days, "active_days": len(days),
|
|
106
|
+
"avg_hits_per_active_day": round(st.hits / len(days), 2),
|
|
107
|
+
"first_day": next(iter(days)), "last_day": next(reversed(days)),
|
|
108
|
+
"top_paths": [{"path": p, "hits": n} for p, n in top_paths],
|
|
109
|
+
"wasted": wasted,
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
def report(self, files: list[FileStats]) -> dict:
|
|
113
|
+
ordered = sorted(self._bots.values(), key=lambda s: (-s.hits, s.bot.token))
|
|
114
|
+
by_purpose = {p: 0 for p in bots.PURPOSES}
|
|
115
|
+
for st in ordered:
|
|
116
|
+
by_purpose[st.bot.purpose] += st.hits
|
|
117
|
+
ai_hits = sum(s.hits for s in ordered)
|
|
118
|
+
totals = {"lines": sum(f.lines for f in files),
|
|
119
|
+
"records": ai_hits + self.other_hits,
|
|
120
|
+
"ai_hits": ai_hits, "other_hits": self.other_hits,
|
|
121
|
+
"malformed": sum(sum(f.malformed.values()) for f in files),
|
|
122
|
+
"non_request": sum(f.non_request for f in files)}
|
|
123
|
+
method = ("user-agent + operator IP ranges for " + ", ".join(self.ranges.tokens())
|
|
124
|
+
if self.ranges and self.ranges.tokens() else "user-agent only")
|
|
125
|
+
return {"totals": totals, "by_purpose": by_purpose,
|
|
126
|
+
"verification": {"method": method, "reverse_dns": "not built"},
|
|
127
|
+
"bots": [self._bot_report(s, self.top) for s in ordered]}
|
omnirank/logs/bots.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""AI-crawler classification for access logs.
|
|
2
|
+
|
|
3
|
+
All access to the crawler taxonomy goes through ``taxonomy()``. It reads the dated taxonomy
|
|
4
|
+
(``omnirank/crawlers.py`` + ``data/ai_crawlers.json``); each entry keeps its own ``verified``
|
|
5
|
+
flag and ``checked_on`` date, so unverified tokens stay visibly unverified.
|
|
6
|
+
|
|
7
|
+
A user-agent string is a CLAIM: anyone can send ``GPTBot`` in a request. Matching here only
|
|
8
|
+
says which crawler a request claims to be; ``ipranges`` can check the claim against IP
|
|
9
|
+
ranges the operator publishes.
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import re
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from functools import lru_cache
|
|
16
|
+
|
|
17
|
+
PURPOSES = ("training", "search", "user-fetch")
|
|
18
|
+
MAX_UA_CHARS = 2048 # only this much of a user-agent is searched
|
|
19
|
+
_PURPOSE = {"training": "training", "search": "search", "user": "user-fetch"}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class Bot:
|
|
24
|
+
token: str
|
|
25
|
+
vendor: str
|
|
26
|
+
purpose: str
|
|
27
|
+
source: str
|
|
28
|
+
verified: bool
|
|
29
|
+
checked_on: str | None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def taxonomy() -> tuple[Bot, ...]:
|
|
33
|
+
"""THE adapter to the crawler taxonomy (one place to switch to the dated table).
|
|
34
|
+
|
|
35
|
+
robots.txt control tokens (Google-Extended, Applebot-Extended) are left out: they never
|
|
36
|
+
appear in a User-Agent header, so they cannot be seen in a log. Reference crawlers
|
|
37
|
+
(classic search engines, outside the AI policy) are left out too."""
|
|
38
|
+
from .. import crawlers
|
|
39
|
+
return tuple(Bot(c.token, c.operator, _PURPOSE[c.category], c.source_url, c.verified,
|
|
40
|
+
c.checked_on)
|
|
41
|
+
for c in crawlers.CRAWLERS if not c.control_token and c.scope == "ai")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def taxonomy_checked_on() -> str | None:
|
|
45
|
+
from .. import crawlers
|
|
46
|
+
return crawlers.TABLE_CHECKED_ON
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@lru_cache(maxsize=1)
|
|
50
|
+
def _matcher() -> tuple[re.Pattern, dict[str, Bot]]:
|
|
51
|
+
table = taxonomy()
|
|
52
|
+
by_lower = {b.token.lower(): b for b in table}
|
|
53
|
+
alternatives = "|".join(re.escape(t) for t in sorted(by_lower, key=len, reverse=True))
|
|
54
|
+
pattern = re.compile(rf"(?:^|(?<=[\s(;,]))(?:{alternatives})(?=[/;),\s]|$)",
|
|
55
|
+
re.IGNORECASE)
|
|
56
|
+
return pattern, by_lower
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def classify(user_agent: str) -> Bot | None:
|
|
60
|
+
"""The AI crawler a user-agent string claims to be, or None. Case-insensitive, and only
|
|
61
|
+
as a PRODUCT token: at the start or after whitespace, ``(``, ``;`` or ``,``, and followed
|
|
62
|
+
by ``/``, ``;``, ``)``, ``,``, whitespace or the end. So ``NotGPTBot``, ``x_GPTBot``,
|
|
63
|
+
``GPTBot-Image``, ``Claude-UserX``, ``foo=GPTBot`` and a token inside a URL or e-mail
|
|
64
|
+
address (``https://x/notes/gptbot``, ``+claudebot@anthropic.com``) do not match."""
|
|
65
|
+
if not user_agent:
|
|
66
|
+
return None
|
|
67
|
+
pattern, by_lower = _matcher()
|
|
68
|
+
m = pattern.search(user_agent[:MAX_UA_CHARS])
|
|
69
|
+
return by_lower[m.group(0).lower()] if m else None
|