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,493 @@
1
+ """Site-level analysis of a finished crawl -> the report dict (JSON/CSV/SARIF source).
2
+
3
+ Definitions (also in docs/crawl.md):
4
+
5
+ * link graph: unique (source, target) internal ``<a href>`` pairs, self-links excluded.
6
+ ``in_degree``/``out_degree`` count those pairs. ``depth`` is the shortest distance from
7
+ the start URL over link AND redirect edges (each hop counts 1); ``None`` = unreachable.
8
+ * orphan: a sitemap URL (not the start URL) with no inbound internal link from any
9
+ crawled page.
10
+ * broken link: an internal link pair whose target answered 4xx/5xx or no HTTP response
11
+ (plus external targets when ``--check-external`` ran).
12
+ * redirect chain: a linked/sitemap/start URL whose redirect needs 2+ hops to end;
13
+ loop: a hop revisits a URL already in the chain.
14
+ * exact duplicate: identical main-content text (``<main>``, else ``<article>``, else
15
+ ``<body>``; lower-cased word tokens, ALL of them hashed). Near duplicate: Jaccard
16
+ similarity of 5-word shingle sets >= 0.90 (exact when both sets have <= 256 shingles,
17
+ otherwise estimated from each page's bottom-256 sketch, computed once per page).
18
+ Candidate pairs come from LSH banding of a 128-bin one-permutation MinHash signature
19
+ (16 bands x 8 rows; a pair at Jaccard 0.90 is missed with probability ~1e-4); at most
20
+ ``NEAR_PAIR_BUDGET`` candidate pairs are examined, beyond that the report says the
21
+ near-duplicate analysis was truncated.
22
+ * soft 404 (HEURISTIC): an OK (2xx) page whose title or h1 reads like an error page, plus
23
+ a site-level probe of a URL that cannot exist.
24
+ """
25
+ from __future__ import annotations
26
+
27
+ import hashlib
28
+ import heapq
29
+ import re
30
+ from bisect import bisect_right
31
+ from collections import Counter, defaultdict, deque
32
+ from dataclasses import dataclass
33
+
34
+ from .. import __version__, clock
35
+ from .crawler import MAX_LINKS_TOTAL, CrawlResult, robots_directives
36
+ from .urls import host_of
37
+
38
+ SHINGLE = 5
39
+ NEAR_THRESHOLD = 0.90
40
+ SKETCH = 256
41
+ MAX_NEAR_PAGES = 5000
42
+ NEAR_PAIR_BUDGET = 500_000
43
+ BINS, BANDS, ROWS = 128, 16, 8
44
+ _BIN_SHIFT = 57 # top 7 bits of a 64-bit hash pick one of 128 bins
45
+ _LOW = (1 << _BIN_SHIFT) - 1
46
+ _HREFLANG = re.compile(r"[A-Za-z]{2,3}(?:-[A-Za-z]{4})?(?:-(?:[A-Za-z]{2}|\d{3}))?")
47
+ _SOFT404 = re.compile(r"\b(?:404|not found|page not found|no longer (?:exists|available)|"
48
+ r"does ?n[o']t exist|cannot be found)\b|পাওয়া যায়নি", re.IGNORECASE)
49
+
50
+ NOTES = [
51
+ ("Public read-only scan: robots.txt obeyed for the OmniRank user-agent; only same-site "
52
+ "URLs are fetched."),
53
+ ("Soft-404 detection is a heuristic (error-like title/h1 on a 2xx page, and a probe URL "
54
+ "that should not exist); confirm by hand."),
55
+ "Near-duplicate threshold: Jaccard >= 0.90 on 5-word shingles of the main content.",
56
+ ("Counts describe this crawl only; a stopped budget (see 'budget') means the site may "
57
+ "have more pages and links than were seen."),
58
+ ]
59
+
60
+
61
+ def _ok_html(rec: dict) -> bool:
62
+ return rec["parsed"] and 200 <= rec["status"] < 300
63
+
64
+
65
+ def _indexable(rec: dict) -> bool:
66
+ if not _ok_html(rec):
67
+ return False
68
+ if any(t in ("noindex", "none") for t in robots_directives(rec)):
69
+ return False
70
+ return rec["canonical"] in (None, rec["url"])
71
+
72
+
73
+ def _hash64(text: str) -> int:
74
+ return int.from_bytes(hashlib.blake2b(text.encode("utf-8"), digest_size=8).digest(), "big")
75
+
76
+
77
+ def _shingles(tokens: list[str]) -> set[int]:
78
+ low = [t.casefold() for t in tokens]
79
+ return {_hash64(" ".join(low[i:i + SHINGLE])) for i in range(len(low) - SHINGLE + 1)}
80
+
81
+
82
+ @dataclass
83
+ class _Sketch:
84
+ url: str
85
+ size: int # number of distinct shingles
86
+ full: frozenset | None # all shingles when size <= SKETCH
87
+ bottom: list[int] # the SKETCH smallest shingle hashes, sorted
88
+ signature: tuple # densified one-permutation MinHash, BINS slots
89
+
90
+
91
+ def _sketch(url: str, tokens: list[str]) -> _Sketch | None:
92
+ hashes = _shingles(tokens)
93
+ if not hashes:
94
+ return None
95
+ bins: list[int | None] = [None] * BINS
96
+ for h in hashes:
97
+ b, v = h >> _BIN_SHIFT, h & _LOW
98
+ if bins[b] is None or v < bins[b]:
99
+ bins[b] = v
100
+ filled = [i for i, v in enumerate(bins) if v is not None]
101
+ signature = []
102
+ for i, v in enumerate(bins):
103
+ if v is not None:
104
+ signature.append((v, 0))
105
+ else: # densify: borrow the next filled bin (rotation)
106
+ j = next((k for k in filled if k > i), filled[0])
107
+ signature.append((bins[j], (j - i) % BINS))
108
+ return _Sketch(url, len(hashes), frozenset(hashes) if len(hashes) <= SKETCH else None,
109
+ heapq.nsmallest(SKETCH, hashes), tuple(signature))
110
+
111
+
112
+ def _jaccard(a: _Sketch, b: _Sketch) -> float:
113
+ if a.full is not None and b.full is not None:
114
+ return len(a.full & b.full) / len(a.full | b.full)
115
+ t = min(a.bottom[-1], b.bottom[-1])
116
+ sa = set(a.bottom[:bisect_right(a.bottom, t)])
117
+ sb = set(b.bottom[:bisect_right(b.bottom, t)])
118
+ return len(sa & sb) / len(sa | sb)
119
+
120
+
121
+ def near_duplicates(pages: list[tuple[str, list[str]]],
122
+ same_group: dict[str, int] | None = None) -> tuple[list[dict], bool]:
123
+ """Near-duplicate pairs among ``(url, tokens)`` pages, and whether the pair budget
124
+ (or the page cap) cut the analysis short."""
125
+ same_group = same_group or {}
126
+ truncated = len(pages) > MAX_NEAR_PAGES
127
+ sketches = [s for s in (_sketch(u, t) for u, t in pages[:MAX_NEAR_PAGES]) if s]
128
+ buckets: dict[tuple, list[int]] = defaultdict(list)
129
+ for idx, sk in enumerate(sketches):
130
+ for band in range(BANDS):
131
+ key = (band, sk.signature[band * ROWS:(band + 1) * ROWS])
132
+ buckets[key].append(idx)
133
+ examined = 0
134
+ seen: set[tuple[int, int]] = set()
135
+ found: list[tuple[int, int, float]] = []
136
+ for members in buckets.values():
137
+ if truncated and examined >= NEAR_PAIR_BUDGET:
138
+ break
139
+ for x in range(len(members)):
140
+ for y in range(x + 1, len(members)):
141
+ pair = (members[x], members[y])
142
+ if pair in seen:
143
+ continue
144
+ if examined >= NEAR_PAIR_BUDGET:
145
+ truncated = True
146
+ break
147
+ examined += 1
148
+ seen.add(pair)
149
+ a, b = sketches[pair[0]], sketches[pair[1]]
150
+ if a.url in same_group and same_group.get(b.url) == same_group[a.url]:
151
+ continue
152
+ if min(a.size, b.size) / max(a.size, b.size) < NEAR_THRESHOLD:
153
+ continue
154
+ j = _jaccard(a, b)
155
+ if j >= NEAR_THRESHOLD:
156
+ found.append((pair[0], pair[1], j))
157
+ if truncated and examined >= NEAR_PAIR_BUDGET:
158
+ break
159
+ found.sort()
160
+ return ([{"urls": [sketches[i].url, sketches[k].url], "jaccard": round(j, 4)}
161
+ for i, k, j in found], truncated)
162
+
163
+
164
+ def _issue(ident: str, severity: str, url: str, observed: str, expected: str, fix: str,
165
+ evidence: str, *, heuristic: bool = False) -> dict:
166
+ out = {"id": ident, "severity": severity, "layer": "crawl", "gate": ident, "url": url,
167
+ "observed": observed, "expected": expected, "fix": fix, "evidence": evidence}
168
+ if heuristic:
169
+ out["heuristic"] = True
170
+ return out
171
+
172
+
173
+ def _groups(pages: list[dict], key) -> list[list[str]]:
174
+ by: dict[str, list[str]] = defaultdict(list)
175
+ for rec in pages:
176
+ value = key(rec)
177
+ if value:
178
+ by[" ".join(value.casefold().split())].append(rec["url"])
179
+ return [urls for urls in by.values() if len(urls) > 1]
180
+
181
+
182
+ def build_report(result: CrawlResult) -> dict:
183
+ records = result.records
184
+ pages = list(records.values())
185
+ ok_pages = [r for r in pages if _ok_html(r)]
186
+ issues: list[dict] = []
187
+
188
+ # --- link graph ------------------------------------------------------------------
189
+ pairs: list[tuple[str, str]] = []
190
+ seen_pairs: set[tuple[str, str]] = set()
191
+ for link in result.links:
192
+ pair = (link["source"], link["target"])
193
+ if link["internal"] and pair[0] != pair[1] and pair not in seen_pairs:
194
+ seen_pairs.add(pair)
195
+ pairs.append(pair)
196
+ indeg: Counter = Counter(t for _, t in pairs)
197
+ outdeg: Counter = Counter(s for s, _ in pairs)
198
+ adjacency: dict[str, list[str]] = defaultdict(list)
199
+ for s, t in pairs + list(result.redirect_edges):
200
+ adjacency[s].append(t)
201
+ depth: dict[str, int] = {result.start_url: 0}
202
+ queue = deque([result.start_url])
203
+ while queue:
204
+ node = queue.popleft()
205
+ for nxt in adjacency[node]:
206
+ if nxt not in depth:
207
+ depth[nxt] = depth[node] + 1
208
+ queue.append(nxt)
209
+
210
+ # --- broken links ------------------------------------------------------------------
211
+ broken = []
212
+ for s, t in pairs:
213
+ rec = records.get(t)
214
+ if rec is not None and not rec["blocked_by_policy"] and not rec.get("skipped") and \
215
+ (rec["status"] == 0 or rec["status"] >= 400):
216
+ broken.append((s, t, rec["status"]))
217
+ issues.append(_issue("crawl.link.broken", "error", s,
218
+ f"links to {t} which answered "
219
+ f"{rec['status'] or 'no response: ' + (rec['error'] or '')}",
220
+ "internal links point to pages that answer 2xx",
221
+ "update or remove the link, or restore the page",
222
+ "[standard]"))
223
+ for ext in result.external:
224
+ if ext["status"] is not None and (ext["status"] == 0 or ext["status"] >= 400) \
225
+ and ext["result"] != "blocked-by-policy":
226
+ sources = sorted({lk["source"] for lk in result.links if lk["target"] == ext["url"]})
227
+ for s in sources:
228
+ broken.append((s, ext["url"], ext["status"]))
229
+ issues.append(_issue("crawl.link.broken-external", "warning", s,
230
+ f"links to {ext['url']} which answered {ext['status']}",
231
+ "external links resolve", "update or remove the link",
232
+ "[standard]"))
233
+
234
+ # --- redirects ---------------------------------------------------------------------
235
+ redirects = [r for r in pages if r["redirect"]]
236
+ chains = [r for r in redirects if r["redirect"]["result"] == "ok"
237
+ and r["redirect"]["hops"] >= 2]
238
+ loops = [r for r in redirects if r["redirect"]["result"] == "loop"]
239
+ for r in chains:
240
+ issues.append(_issue("crawl.redirect.chain", "warning", r["url"],
241
+ f"{r['redirect']['hops']} hops to {r['redirect']['final_url']}",
242
+ "one redirect hop at most", "point links and the first "
243
+ "redirect straight at the final URL", "[guideline]"))
244
+ for r in loops:
245
+ issues.append(_issue("crawl.redirect.loop", "error", r["url"],
246
+ "redirect chain returns to a URL it already visited",
247
+ "redirects end at a page", "break the loop", "[standard]"))
248
+ for r in redirects:
249
+ if r["redirect"]["result"] == "too-many-hops":
250
+ issues.append(_issue("crawl.redirect.too-many-hops", "error", r["url"],
251
+ f"more than {result.config['max_redirects']} hops",
252
+ "a short redirect chain", "shorten the chain",
253
+ "[guideline]"))
254
+
255
+ # --- sitemap vs crawl --------------------------------------------------------------
256
+ sitemap_urls = result.sitemap.urls
257
+ in_sitemap = set(sitemap_urls)
258
+ # an inbound link that reaches a page through a redirect still counts
259
+ reached = set(indeg)
260
+ for _, t in pairs:
261
+ rec = records.get(t)
262
+ if rec is not None and rec["redirect"] and rec["redirect"]["result"] == "ok":
263
+ reached.add(rec["redirect"]["final_url"])
264
+ orphans = [u for u in sitemap_urls if u != result.start_url and u not in reached]
265
+ for u in orphans:
266
+ issues.append(_issue("crawl.orphan", "warning", u,
267
+ "listed in the sitemap but no crawled page links to it",
268
+ "every important page has an internal link",
269
+ "link to it from a relevant page, or drop it from the sitemap",
270
+ "[guideline]"))
271
+ not_linked = [r["url"] for r in pages if r["source"] == "sitemap"]
272
+ not_linked += [u for u in sitemap_urls if u not in records and u not in not_linked]
273
+ sitemap_not_ok = [u for u in sitemap_urls if u in records and not _indexable(records[u])]
274
+ for u in sitemap_not_ok:
275
+ issues.append(_issue("crawl.sitemap.not-indexable", "warning", u,
276
+ f"in the sitemap but answered {records[u]['status']} or is not "
277
+ "indexable (noindex, canonicalised or not HTML)",
278
+ "a sitemap lists only canonical, indexable 200 URLs",
279
+ "remove it from the sitemap or fix the page", "[guideline]"))
280
+ missing_from_sitemap = [r["url"] for r in pages if _indexable(r)
281
+ and r["url"] not in in_sitemap]
282
+ if sitemap_urls:
283
+ for u in missing_from_sitemap:
284
+ issues.append(_issue("crawl.sitemap.missing-page", "info", u,
285
+ "indexable page found by crawling but not in the sitemap",
286
+ "the sitemap lists every indexable page",
287
+ "add it to the sitemap (or make it non-indexable)",
288
+ "[guideline]"))
289
+
290
+ # --- duplicates --------------------------------------------------------------------
291
+ by_hash: dict[str, list[str]] = defaultdict(list)
292
+ for r in ok_pages:
293
+ digest = result.content_hashes.get(r["url"])
294
+ if digest:
295
+ by_hash[digest].append(r["url"])
296
+ exact = [urls for urls in by_hash.values() if len(urls) > 1]
297
+ exact_of = {u: i for i, urls in enumerate(exact) for u in urls}
298
+ for urls in exact:
299
+ for u in urls[1:]:
300
+ issues.append(_issue("crawl.duplicate.exact", "warning", u,
301
+ f"same main content as {urls[0]}", "unique content per URL",
302
+ "merge the pages or canonicalise to one", "[guideline]"))
303
+ near, near_truncated = near_duplicates(
304
+ [(r["url"], result.tokens.get(r["url"]) or []) for r in ok_pages], exact_of)
305
+ for pair in near:
306
+ ua, ub = pair["urls"]
307
+ issues.append(_issue("crawl.duplicate.near", "info", ub,
308
+ f"main content {pair['jaccard']:.0%} similar to {ua}",
309
+ "substantially different content per URL",
310
+ "differentiate or consolidate the pages", "[guideline]"))
311
+ title_groups = _groups(ok_pages, lambda r: r["title"])
312
+ desc_groups = _groups(ok_pages, lambda r: r["description"])
313
+ for urls in title_groups:
314
+ for u in urls:
315
+ issues.append(_issue("crawl.title.duplicate", "warning", u,
316
+ f"title shared by {len(urls)} pages", "a unique <title>",
317
+ "write a distinct title", "[guideline]"))
318
+ for urls in desc_groups:
319
+ for u in urls:
320
+ issues.append(_issue("crawl.description.duplicate", "info", u,
321
+ f"meta description shared by {len(urls)} pages",
322
+ "a unique meta description", "write a distinct description",
323
+ "[guideline]"))
324
+
325
+ # --- hreflang ----------------------------------------------------------------------
326
+ invalid = non_recip = bad_target = not_checked = missing_self = dup_lang = 0
327
+ for r in ok_pages:
328
+ alts = r["hreflang"]
329
+ if not alts:
330
+ continue
331
+ if all(a["href"] != r["url"] for a in alts):
332
+ missing_self += 1
333
+ issues.append(_issue("crawl.hreflang.missing-self", "warning", r["url"],
334
+ "hreflang set does not include the page itself",
335
+ "each page lists itself among its alternates",
336
+ "add a self-referencing hreflang", "[guideline]"))
337
+ counts = Counter(a["lang"].lower() for a in alts)
338
+ for lang, n in counts.items():
339
+ if n > 1 and len({a["href"] for a in alts if a["lang"].lower() == lang}) > 1:
340
+ dup_lang += 1
341
+ issues.append(_issue("crawl.hreflang.duplicate-lang", "error", r["url"],
342
+ f"hreflang {lang!r} points to more than one URL",
343
+ "one URL per language(-region) code",
344
+ "keep one alternate per code", "[guideline]"))
345
+ for alt in alts:
346
+ lang, href = alt["lang"], alt["href"]
347
+ if lang.lower() != "x-default" and not _HREFLANG.fullmatch(lang):
348
+ invalid += 1
349
+ issues.append(_issue("crawl.hreflang.invalid", "error", r["url"],
350
+ f"hreflang {lang!r} is not a language(-region) code",
351
+ "ISO 639-1 language, optional ISO 3166-1 region, or "
352
+ "x-default", "fix the code", "[guideline]"))
353
+ if href is None or href == r["url"] or lang.lower() == "x-default":
354
+ continue
355
+ target = records.get(href)
356
+ if target is None:
357
+ not_checked += 1 # other site, robots.txt or a budget
358
+ continue
359
+ if not _ok_html(target):
360
+ bad_target += 1
361
+ issues.append(_issue("crawl.hreflang.bad-target", "warning", r["url"],
362
+ f"hreflang {lang} points to {href}, which answered "
363
+ f"{target['status']} or is not HTML",
364
+ "alternates answer 200", "point it at the live alternate",
365
+ "[guideline]"))
366
+ elif r["url"] not in {a["href"] for a in target["hreflang"]}:
367
+ non_recip += 1
368
+ issues.append(_issue("crawl.hreflang.non-reciprocal", "warning", r["url"],
369
+ f"hreflang {lang} -> {href}, but {href} does not link "
370
+ "back", "hreflang annotations are reciprocal",
371
+ "add the return annotation on the alternate",
372
+ "[guideline]"))
373
+
374
+ # --- canonical ---------------------------------------------------------------------
375
+ canon_cross = canon_bad = canon_chain = 0
376
+ for r in ok_pages:
377
+ target_url = r["canonical"]
378
+ if not target_url or target_url == r["url"]:
379
+ continue
380
+ if host_of(target_url) != result.site_host:
381
+ canon_cross += 1
382
+ issues.append(_issue("crawl.canonical.cross-domain", "info", r["url"],
383
+ f"canonical points to another host: {target_url}",
384
+ "intentional cross-domain canonicals only",
385
+ "check the canonical is meant to leave the site",
386
+ "[guideline]"))
387
+ continue
388
+ target = records.get(target_url)
389
+ if target is None:
390
+ continue
391
+ if not _ok_html(target):
392
+ canon_bad += 1
393
+ issues.append(_issue("crawl.canonical.target-not-ok", "error", r["url"],
394
+ f"canonical {target_url} answered {target['status']}",
395
+ "the canonical URL answers 200 with HTML",
396
+ "point the canonical at a live page", "[guideline]"))
397
+ elif target["canonical"] not in (None, target_url):
398
+ canon_chain += 1
399
+ issues.append(_issue("crawl.canonical.chain", "warning", r["url"],
400
+ f"canonical {target_url} itself canonicalises to "
401
+ f"{target['canonical']}", "canonicals point at the final URL",
402
+ "point the canonical straight at the final URL",
403
+ "[guideline]"))
404
+
405
+ # --- soft 404 ----------------------------------------------------------------------
406
+ soft = [r for r in ok_pages
407
+ if any(_SOFT404.search(t or "") for t in [r["title"], *r["h1"]])]
408
+ for r in soft:
409
+ issues.append(_issue("crawl.soft404", "warning", r["url"],
410
+ f"answered {r['status']} but reads like an error page "
411
+ f"(title {r['title']!r})", "missing pages answer 404 or 410",
412
+ "return a real 404/410, or fix the content", "[experimental]",
413
+ heuristic=True))
414
+ if result.probe and 200 <= result.probe["status"] < 300:
415
+ issues.append(_issue("crawl.soft404.site", "warning", result.probe["url"],
416
+ f"a URL that should not exist answered {result.probe['status']}",
417
+ "unknown URLs answer 404", "make the catch-all route return 404",
418
+ "[experimental]", heuristic=True))
419
+
420
+ for u in result.blocked_by_robots:
421
+ issues.append(_issue("crawl.robots.blocked", "info", u,
422
+ "linked but disallowed by robots.txt for OmniRank; not fetched",
423
+ "(informational)", "none needed if intended", "[standard]"))
424
+ missing_alt = sum(len(r["images_missing_alt"]) for r in ok_pages)
425
+ missing_dims = sum(len(r["images_missing_dimensions"]) for r in ok_pages)
426
+ for r in ok_pages:
427
+ if r["images_missing_alt"]:
428
+ issues.append(_issue("crawl.image.alt-missing", "info", r["url"],
429
+ f"{len(r['images_missing_alt'])} <img> without alt",
430
+ "alt text (alt=\"\" for decorative images)",
431
+ "add alt attributes", "[standard]"))
432
+ if r["images_missing_dimensions"]:
433
+ issues.append(_issue("crawl.image.dimensions-missing", "info", r["url"],
434
+ f"{len(r['images_missing_dimensions'])} <img> without "
435
+ "width/height", "explicit width and height",
436
+ "add width and height attributes", "[guideline]"))
437
+
438
+ external_targets = sorted({lk["target"] for lk in result.links if not lk["internal"]})
439
+ depths = [depth[r["url"]] for r in pages if r["url"] in depth]
440
+
441
+ page_rows = []
442
+ for r in pages:
443
+ row = {k: v for k, v in r.items() if k != "crawl_depth"}
444
+ row.update(depth=depth.get(r["url"]), in_degree=indeg[r["url"]],
445
+ out_degree=outdeg[r["url"]], indexable=_indexable(r),
446
+ in_sitemap=r["url"] in in_sitemap)
447
+ page_rows.append(row)
448
+
449
+ summary = {
450
+ "pages_fetched": len(pages),
451
+ "status_counts": dict(sorted(Counter(str(r["status"]) for r in pages).items())),
452
+ "redirects": len(redirects), "redirect_chains": len(chains),
453
+ "redirect_loops": len(loops), "broken_links": len(broken),
454
+ "blocked_by_robots": len(result.blocked_by_robots),
455
+ "orphans": len(orphans), "sitemap_urls": len(sitemap_urls),
456
+ "sitemap_offsite_ignored": result.sitemap.offsite,
457
+ "sitemap_not_linked": len(not_linked), "sitemap_url_not_ok": len(sitemap_not_ok),
458
+ "crawled_not_in_sitemap": len(missing_from_sitemap),
459
+ "exact_duplicate_groups": len(exact), "near_duplicate_pairs": len(near),
460
+ "duplicate_title_groups": len(title_groups),
461
+ "duplicate_description_groups": len(desc_groups),
462
+ "hreflang_invalid": invalid, "hreflang_non_reciprocal": non_recip,
463
+ "hreflang_bad_target": bad_target, "hreflang_not_checked": not_checked,
464
+ "hreflang_missing_self": missing_self, "hreflang_duplicate_lang": dup_lang,
465
+ "canonical_cross_domain": canon_cross, "canonical_target_not_ok": canon_bad,
466
+ "canonical_chain": canon_chain, "near_duplicate_truncated": near_truncated,
467
+ "soft_404": len(soft),
468
+ "external_links": len(external_targets),
469
+ "images_missing_alt": missing_alt, "images_missing_dimensions": missing_dims,
470
+ "noindex": sum(1 for r in ok_pages
471
+ if any(t in ("noindex", "none") for t in robots_directives(r))),
472
+ "max_depth": max(depths) if depths else None,
473
+ "unreachable": sum(1 for r in pages if r["url"] not in depth),
474
+ }
475
+ return {
476
+ "tool": "omnirank crawl", "version": __version__, "scan": "public read-only scan",
477
+ "generated_on": clock.today().isoformat(), "start_url": result.start_url,
478
+ "config": result.config, "rendered": result.rendered,
479
+ "robots": result.robots, "sitemap": result.sitemap.to_dict(),
480
+ "budget": {"exhausted": result.exhausted, "bytes": result.bytes_downloaded},
481
+ "soft404_probe": result.probe, "summary": summary, "issues": issues,
482
+ "duplicates": {"exact": exact, "near": near, "titles": title_groups,
483
+ "descriptions": desc_groups},
484
+ "pages": page_rows, "links": result.links, "external": result.external,
485
+ "blocked_by_robots": list(result.blocked_by_robots),
486
+ "notes": NOTES + ([(f"Only the first {MAX_LINKS_TOTAL} links are stored in this "
487
+ "report; degrees and broken-link counts cover those links.")]
488
+ if result.links_truncated else [])
489
+ + (["Near-duplicate analysis truncated (page cap or pair budget reached)."]
490
+ if near_truncated else []),
491
+ "near_duplicate_threshold": NEAR_THRESHOLD,
492
+ "links_truncated": result.links_truncated, "aborted": result.aborted,
493
+ }