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/aeo/__init__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""On-page answer-engine (AEO) checks with sourced diff proposals (spec section 7).
|
|
2
|
+
|
|
3
|
+
Nothing here writes a file and nothing here invents copy: every proposed sentence is
|
|
4
|
+
text already on the page, moved or restated; anything that needs a fact the page
|
|
5
|
+
does not contain becomes an `<!-- OMNIRANK-TODO: ... -->` block. See docs/aeo-onpage.md.
|
|
6
|
+
"""
|
|
7
|
+
from .propose import AeoResult, analyse
|
|
8
|
+
|
|
9
|
+
__all__ = ["AeoResult", "analyse"]
|
omnirank/aeo/extract.py
ADDED
|
@@ -0,0 +1,383 @@
|
|
|
1
|
+
"""Page model for the AEO rules: visible text, sections, intent, entity, source spans.
|
|
2
|
+
|
|
3
|
+
Everything here reads the page the way a visitor would: text inside hidden,
|
|
4
|
+
aria-hidden, sr-only, script, style, template and noscript elements is never part of
|
|
5
|
+
the page's text (it reuses `schema.extract._visible`, the one definition of
|
|
6
|
+
"visible" in this package). Parsing uses `html.parser` because, unlike lxml, it
|
|
7
|
+
records `sourceline`/`sourcepos`, which is what lets a finding say `file:line` and a
|
|
8
|
+
diff replace exactly the bytes of one element.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import html as htmllib
|
|
13
|
+
import json
|
|
14
|
+
import re
|
|
15
|
+
import unicodedata
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from datetime import date
|
|
18
|
+
|
|
19
|
+
from bs4 import BeautifulSoup, NavigableString, Tag
|
|
20
|
+
from bs4.element import PreformattedString
|
|
21
|
+
|
|
22
|
+
from ..html import find_ldjson_scripts
|
|
23
|
+
from ..schema.extract import _visible as _tag_visible
|
|
24
|
+
|
|
25
|
+
HEADINGS = ("h1", "h2", "h3", "h4", "h5", "h6")
|
|
26
|
+
BLOCKS = (*HEADINGS, "p", "ul", "ol", "table", "dl", "blockquote", "pre")
|
|
27
|
+
NOT_CONTENT = ("nav", "footer", "aside", "form")
|
|
28
|
+
INSIDE_ITEM = ("li", "td", "th", "dd", "dt", "blockquote", "figure", "figcaption")
|
|
29
|
+
|
|
30
|
+
_TERMINATORS = "।.!??"
|
|
31
|
+
_ABBREV = re.compile(
|
|
32
|
+
r"(?:\b(?:e\.g|i\.e|vs|etc|dr|mr|mrs|ms|prof|inc|no|fig|approx|ltd|co|st|jr|sr|eq|cf|ca|est|"
|
|
33
|
+
r"dept)\.|\b[A-Z]\.)$", re.IGNORECASE)
|
|
34
|
+
_BN_DIGITS = str.maketrans("০১২৩৪৫৬৭৮৯", "0123456789")
|
|
35
|
+
_MONTHS = {m: i for i, m in enumerate(
|
|
36
|
+
["january", "february", "march", "april", "may", "june", "july", "august",
|
|
37
|
+
"september", "october", "november", "december"], 1)}
|
|
38
|
+
_MONTHS.update({k[:3]: v for k, v in list(_MONTHS.items())})
|
|
39
|
+
_MONTHS["sept"] = 9
|
|
40
|
+
_MONTH_RE = "|".join(sorted(_MONTHS, key=len, reverse=True)) # real month names only
|
|
41
|
+
_DATE_ISO = re.compile(r"\b(\d{4})-(\d{2})-(\d{2})\b")
|
|
42
|
+
_DATE_MDY = re.compile(rf"\b({_MONTH_RE})\.? (\d{{1,2}}),? (\d{{4}})\b", re.IGNORECASE)
|
|
43
|
+
_DATE_DMY = re.compile(rf"\b(\d{{1,2}}) ({_MONTH_RE})\.?,? (\d{{4}})\b", re.IGNORECASE)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
# --- text ---------------------------------------------------------------------------
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def clean(text: str) -> str:
|
|
50
|
+
return " ".join(text.split())
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def visible_text(tag: Tag) -> str:
|
|
54
|
+
"""The text a visitor sees inside `tag`, hidden descendants excluded."""
|
|
55
|
+
parts: list[str] = []
|
|
56
|
+
|
|
57
|
+
def walk(node: Tag) -> None:
|
|
58
|
+
for child in node.children:
|
|
59
|
+
if isinstance(child, PreformattedString):
|
|
60
|
+
continue # comments, doctype, CDATA
|
|
61
|
+
if isinstance(child, NavigableString):
|
|
62
|
+
parts.append(str(child))
|
|
63
|
+
elif isinstance(child, Tag) and _tag_visible(child):
|
|
64
|
+
if child.name == "br":
|
|
65
|
+
parts.append(" ")
|
|
66
|
+
walk(child)
|
|
67
|
+
|
|
68
|
+
if _tag_visible(tag):
|
|
69
|
+
walk(tag)
|
|
70
|
+
return clean("".join(parts))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def is_plain(tag: Tag) -> bool:
|
|
74
|
+
"""True when `tag` holds only text: a rewrite cannot drop a link or emphasis."""
|
|
75
|
+
return all(isinstance(c, NavigableString) and not isinstance(c, PreformattedString)
|
|
76
|
+
for c in tag.children)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def sentences(text: str) -> list[str]:
|
|
80
|
+
"""Split on . ! ? and the Bengali danda, not after abbreviations or inside numbers."""
|
|
81
|
+
out: list[str] = []
|
|
82
|
+
start = 0
|
|
83
|
+
for i, ch in enumerate(text):
|
|
84
|
+
if ch not in _TERMINATORS:
|
|
85
|
+
continue
|
|
86
|
+
end = i + 1
|
|
87
|
+
while end < len(text) and text[end] in "\"')]”’":
|
|
88
|
+
end += 1
|
|
89
|
+
if end < len(text) and not text[end].isspace():
|
|
90
|
+
continue # 3.5, example.com, ?utm
|
|
91
|
+
following = text[end:].lstrip()
|
|
92
|
+
if following and (following[0].isdigit() or following[0].islower()):
|
|
93
|
+
continue # "approx. 40", "it. then": not a boundary
|
|
94
|
+
if ch == "." and _ABBREV.search(text[start:i + 1]):
|
|
95
|
+
continue
|
|
96
|
+
out.append(text[start:end].strip())
|
|
97
|
+
start = end
|
|
98
|
+
if text[start:].strip():
|
|
99
|
+
out.append(text[start:].strip())
|
|
100
|
+
return out
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def tokens(text: str) -> list[str]:
|
|
104
|
+
"""Whitespace tokens with edge punctuation stripped, case-folded. Bengali is
|
|
105
|
+
compared as-is: no normalisation beyond case-folding (a no-op for Bengali)."""
|
|
106
|
+
out = []
|
|
107
|
+
for piece in text.split():
|
|
108
|
+
start, end = 0, len(piece)
|
|
109
|
+
while start < end and unicodedata.category(piece[start])[0] in "PS":
|
|
110
|
+
start += 1
|
|
111
|
+
while end > start and unicodedata.category(piece[end - 1])[0] in "PS":
|
|
112
|
+
end -= 1
|
|
113
|
+
if start < end:
|
|
114
|
+
out.append(piece[start:end].casefold())
|
|
115
|
+
return out
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def to_ascii_digits(text: str) -> str:
|
|
119
|
+
return text.translate(_BN_DIGITS)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def parse_date(text: str, *, at_start: bool = False) -> date | None:
|
|
123
|
+
"""The first real calendar date in `text` (or, with `at_start`, one that begins it).
|
|
124
|
+
ISO, "March 3, 2024" and "3 March 2024" are understood; an unknown month name or an
|
|
125
|
+
impossible day is simply not a date."""
|
|
126
|
+
text = to_ascii_digits(text)
|
|
127
|
+
for pattern, order in ((_DATE_ISO, (1, 2, 3)), (_DATE_MDY, (3, 1, 2)),
|
|
128
|
+
(_DATE_DMY, (3, 2, 1))):
|
|
129
|
+
found = pattern.match(text) if at_start else pattern.search(text)
|
|
130
|
+
if not found:
|
|
131
|
+
continue
|
|
132
|
+
year, month, day = (found.group(i) for i in order)
|
|
133
|
+
try:
|
|
134
|
+
month_no = int(month) if month.isdigit() else _MONTHS[month.lower()]
|
|
135
|
+
return date(int(year), month_no, int(day))
|
|
136
|
+
except (KeyError, ValueError):
|
|
137
|
+
continue
|
|
138
|
+
return None
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
# --- source spans -------------------------------------------------------------------
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
@dataclass(frozen=True)
|
|
145
|
+
class Span:
|
|
146
|
+
start: int # offset of "<"
|
|
147
|
+
open_end: int # offset just after the opening tag's ">"
|
|
148
|
+
close_start: int # offset of "</"
|
|
149
|
+
end: int # offset just after the closing tag's ">"
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
class Source:
|
|
153
|
+
"""Source text with line lookup and element spans. A span is returned only when the
|
|
154
|
+
parsed element and the bytes it points at agree; otherwise None, and the caller
|
|
155
|
+
reports the finding without a diff rather than editing the wrong bytes."""
|
|
156
|
+
|
|
157
|
+
def __init__(self, text: str) -> None:
|
|
158
|
+
self.text = text
|
|
159
|
+
self._starts = [0] + [m.end() for m in re.finditer("\n", text)]
|
|
160
|
+
|
|
161
|
+
def offset(self, tag: Tag) -> int | None:
|
|
162
|
+
if tag.sourceline is None or tag.sourcepos is None:
|
|
163
|
+
return None
|
|
164
|
+
if not 1 <= tag.sourceline <= len(self._starts):
|
|
165
|
+
return None
|
|
166
|
+
return self._starts[tag.sourceline - 1] + tag.sourcepos
|
|
167
|
+
|
|
168
|
+
def line_at(self, offset: int) -> int:
|
|
169
|
+
lo, hi = 0, len(self._starts)
|
|
170
|
+
while lo + 1 < hi:
|
|
171
|
+
mid = (lo + hi) // 2
|
|
172
|
+
if self._starts[mid] <= offset:
|
|
173
|
+
lo = mid
|
|
174
|
+
else:
|
|
175
|
+
hi = mid
|
|
176
|
+
return lo + 1
|
|
177
|
+
|
|
178
|
+
def span(self, tag: Tag) -> Span | None:
|
|
179
|
+
start = self.offset(tag)
|
|
180
|
+
if start is None:
|
|
181
|
+
return None
|
|
182
|
+
name = re.escape(tag.name)
|
|
183
|
+
attrs = r"""(?:[^>"']|"[^"]*"|'[^']*')*"""
|
|
184
|
+
opening = re.compile(rf"<{name}(?=[\s/>]){attrs}>", re.IGNORECASE).match(self.text, start)
|
|
185
|
+
if opening is None or opening.group(0).endswith("/>"):
|
|
186
|
+
return None
|
|
187
|
+
tags = re.compile(rf"<(/?){name}(?=[\s/>]){attrs}>", re.IGNORECASE)
|
|
188
|
+
depth = 1
|
|
189
|
+
for found in tags.finditer(self.text, opening.end()):
|
|
190
|
+
depth += -1 if found.group(1) else 1
|
|
191
|
+
if depth == 0:
|
|
192
|
+
span = Span(start, opening.end(), found.start(), found.end())
|
|
193
|
+
return span if self._consistent(tag, span) else None
|
|
194
|
+
return None
|
|
195
|
+
|
|
196
|
+
def _consistent(self, tag: Tag, span: Span) -> bool:
|
|
197
|
+
"""The bytes between the tags, with markup stripped, must read as the parsed text.
|
|
198
|
+
A mismatch (an unclosed <p>, a script or comment inside) means the span cannot be
|
|
199
|
+
trusted, so it is refused rather than guessed."""
|
|
200
|
+
inner = re.sub(r"<[^>]*>", "", self.text[span.open_end:span.close_start])
|
|
201
|
+
return clean(htmllib.unescape(inner)) == clean(tag.get_text())
|
|
202
|
+
|
|
203
|
+
def indent_at(self, offset: int) -> str:
|
|
204
|
+
line_start = self._starts[self.line_at(offset) - 1]
|
|
205
|
+
prefix = self.text[line_start:offset]
|
|
206
|
+
return prefix if not prefix.strip() else prefix[:len(prefix) - len(prefix.lstrip())]
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
# --- the page -----------------------------------------------------------------------
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
@dataclass
|
|
213
|
+
class Section:
|
|
214
|
+
heading: Tag
|
|
215
|
+
blocks: list[Tag] = field(default_factory=list)
|
|
216
|
+
|
|
217
|
+
@property
|
|
218
|
+
def level(self) -> int:
|
|
219
|
+
return int(self.heading.name[1])
|
|
220
|
+
|
|
221
|
+
def lead_paragraphs(self) -> list[Tag]:
|
|
222
|
+
"""The paragraphs directly under the heading, up to the first non-paragraph."""
|
|
223
|
+
out = []
|
|
224
|
+
for block in self.blocks:
|
|
225
|
+
if block.name != "p":
|
|
226
|
+
break
|
|
227
|
+
out.append(block)
|
|
228
|
+
return out
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
@dataclass
|
|
232
|
+
class Page:
|
|
233
|
+
soup: BeautifulSoup
|
|
234
|
+
source: Source
|
|
235
|
+
lang: str | None
|
|
236
|
+
title: str
|
|
237
|
+
sections: list[Section]
|
|
238
|
+
h1: Tag | None
|
|
239
|
+
jsonld: list[dict]
|
|
240
|
+
noindex: bool
|
|
241
|
+
intent: str
|
|
242
|
+
entity: str | None
|
|
243
|
+
questions: list[str]
|
|
244
|
+
scope: Tag
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _in_scope(tag: Tag, scope: Tag) -> bool:
|
|
248
|
+
for parent in tag.parents:
|
|
249
|
+
if parent is scope:
|
|
250
|
+
return True
|
|
251
|
+
if isinstance(parent, Tag) and parent.name in NOT_CONTENT:
|
|
252
|
+
return False
|
|
253
|
+
return True
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def content_blocks(scope: Tag) -> list[Tag]:
|
|
257
|
+
out = []
|
|
258
|
+
for tag in scope.find_all(BLOCKS):
|
|
259
|
+
if not _tag_visible(tag) or not _in_scope(tag, scope):
|
|
260
|
+
continue
|
|
261
|
+
if tag.name == "p" and tag.find_parent(INSIDE_ITEM):
|
|
262
|
+
continue
|
|
263
|
+
if tag.name in ("ul", "ol") and tag.find_parent(("li", "nav")):
|
|
264
|
+
continue
|
|
265
|
+
out.append(tag)
|
|
266
|
+
return out
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def build_sections(blocks: list[Tag]) -> list[Section]:
|
|
270
|
+
sections: list[Section] = []
|
|
271
|
+
for block in blocks:
|
|
272
|
+
if block.name in HEADINGS:
|
|
273
|
+
if visible_text(block):
|
|
274
|
+
sections.append(Section(block))
|
|
275
|
+
elif sections:
|
|
276
|
+
sections[-1].blocks.append(block)
|
|
277
|
+
return sections
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
_QUESTION_START = re.compile(
|
|
281
|
+
r"^(what|why|how|when|where|who|whom|whose|which|can|could|does|do|did|is|are|was|"
|
|
282
|
+
r"were|should|will|would|কী|কি|কেন|কীভাবে|কিভাবে|কোথায়|কখন|কে|কত|কোন)\b", re.IGNORECASE)
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def is_question(text: str) -> bool:
|
|
286
|
+
text = clean(text)
|
|
287
|
+
if text.endswith(("?", "?")):
|
|
288
|
+
return True
|
|
289
|
+
return len(text.split()) >= 3 and bool(_QUESTION_START.match(text))
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
_INTENTS: tuple[tuple[str, re.Pattern[str]], ...] = (
|
|
293
|
+
("compare", re.compile(r"\bvs\.?\b|\bversus\b|\bcompar(e|ison)\b|difference between|"
|
|
294
|
+
r"বনাম|পার্থক্য", re.IGNORECASE)),
|
|
295
|
+
("how-to", re.compile(r"^how (to|do|can)\b|\bstep[- ]by[- ]step\b|^guide to\b|"
|
|
296
|
+
r"কীভাবে|কিভাবে", re.IGNORECASE)),
|
|
297
|
+
("define", re.compile(r"^(what (is|are)|define)\b|\bdefinition of\b|\bmeaning of\b|"
|
|
298
|
+
r"\s(কী|কি|কাকে বলে)\s*[??]?$", re.IGNORECASE)),
|
|
299
|
+
("list", re.compile(r"^(\d+|top \d+)\b|\btop \d+\b|\bbest\b|\blist of\b|তালিকা",
|
|
300
|
+
re.IGNORECASE)),
|
|
301
|
+
("local", re.compile(r"\bnear me\b|\bnearby\b|কাছাকাছি|আশেপাশে", re.IGNORECASE)),
|
|
302
|
+
("transactional", re.compile(r"\b(buy|price|pricing|order|discount|coupon|subscribe|"
|
|
303
|
+
r"sign up|free trial)\b|কিনুন|দাম", re.IGNORECASE)),
|
|
304
|
+
)
|
|
305
|
+
_DEFINE_EN = re.compile(r"^(?:what (?:is|are)|define)\s+(?:an?\s+|the\s+)?(.+?)\s*[??]?$",
|
|
306
|
+
re.IGNORECASE)
|
|
307
|
+
_DEFINE_BN = re.compile(r"^(.+?)\s+(?:কী|কি|কাকে বলে)\s*[??]?$")
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def detect_intent(h1: str, title: str) -> str:
|
|
311
|
+
"""One of define/compare/how-to/list/local/transactional, or "unknown" when
|
|
312
|
+
nothing on the page says. Never defaults to a guess."""
|
|
313
|
+
for text in (h1, title):
|
|
314
|
+
for name, pattern in _INTENTS:
|
|
315
|
+
if text and pattern.search(clean(text)):
|
|
316
|
+
return name
|
|
317
|
+
return "unknown"
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def jsonld_types(node: dict) -> list[str]:
|
|
321
|
+
kinds = node.get("@type")
|
|
322
|
+
kinds = [kinds] if isinstance(kinds, str) else (kinds if isinstance(kinds, list) else [])
|
|
323
|
+
return [k for k in kinds if isinstance(k, str)]
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def detect_entity(h1: str, intent: str, jsonld: list[dict]) -> str | None:
|
|
327
|
+
"""The page's subject, only from text a visitor can read: a "What is X?" / "X কী?"
|
|
328
|
+
heading, or a JSON-LD Product/SoftwareApplication/Service name that the H1 itself
|
|
329
|
+
shows verbatim. An Organization or publisher name is never the entity: it is not what
|
|
330
|
+
the page is about, and a name found only in markup is not on the page."""
|
|
331
|
+
if intent == "define":
|
|
332
|
+
for pattern in (_DEFINE_EN, _DEFINE_BN):
|
|
333
|
+
if m := pattern.match(clean(h1)):
|
|
334
|
+
return m.group(1).strip() or None
|
|
335
|
+
for node in jsonld:
|
|
336
|
+
name = node.get("name")
|
|
337
|
+
if set(jsonld_types(node)) & {"Product", "SoftwareApplication", "Service"} \
|
|
338
|
+
and isinstance(name, str) and clean(name) and clean(name).casefold() in h1.casefold():
|
|
339
|
+
return clean(name)
|
|
340
|
+
return None
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def load_jsonld(soup: BeautifulSoup) -> list[dict]:
|
|
344
|
+
nodes: list[dict] = []
|
|
345
|
+
|
|
346
|
+
def add(node: object) -> None:
|
|
347
|
+
if isinstance(node, list):
|
|
348
|
+
for item in node:
|
|
349
|
+
add(item)
|
|
350
|
+
elif isinstance(node, dict):
|
|
351
|
+
nodes.append(node)
|
|
352
|
+
add(node.get("@graph"))
|
|
353
|
+
|
|
354
|
+
for script in find_ldjson_scripts(soup):
|
|
355
|
+
try:
|
|
356
|
+
add(json.loads(script.string or script.get_text() or ""))
|
|
357
|
+
except (json.JSONDecodeError, RecursionError):
|
|
358
|
+
continue
|
|
359
|
+
return nodes
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def parse_page(text: str) -> Page:
|
|
363
|
+
soup = BeautifulSoup(text, "html.parser")
|
|
364
|
+
html_tag = soup.find("html")
|
|
365
|
+
lang = clean(html_tag.get("lang", "")) if isinstance(html_tag, Tag) else ""
|
|
366
|
+
title_tag = soup.find("title")
|
|
367
|
+
robots = soup.find("meta", attrs={"name": lambda v: v and v.strip().lower() == "robots"})
|
|
368
|
+
scope = soup.find("main") or soup.find("article") or soup.find("body") or soup
|
|
369
|
+
sections = build_sections(content_blocks(scope))
|
|
370
|
+
h1_section = next((s for s in sections if s.level == 1), None)
|
|
371
|
+
h1 = h1_section.heading if h1_section else None
|
|
372
|
+
h1_text = visible_text(h1) if h1 else ""
|
|
373
|
+
title = clean(title_tag.get_text()) if title_tag else ""
|
|
374
|
+
jsonld = load_jsonld(soup)
|
|
375
|
+
intent = detect_intent(h1_text, title)
|
|
376
|
+
return Page(
|
|
377
|
+
soup=soup, source=Source(text), lang=lang or None, title=title, sections=sections,
|
|
378
|
+
h1=h1, jsonld=jsonld,
|
|
379
|
+
noindex=bool(robots and "noindex" in (robots.get("content") or "").lower()),
|
|
380
|
+
intent=intent, entity=detect_entity(h1_text, intent, jsonld),
|
|
381
|
+
questions=[visible_text(s.heading) for s in sections
|
|
382
|
+
if s.level <= 3 and is_question(visible_text(s.heading))],
|
|
383
|
+
scope=scope)
|
omnirank/aeo/propose.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Run the rules, resolve overlapping edits, and render one unified diff."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from dataclasses import dataclass, field, replace
|
|
5
|
+
from datetime import date
|
|
6
|
+
|
|
7
|
+
from ..bands import Band
|
|
8
|
+
from ..clock import today
|
|
9
|
+
from ..fixes.base import newline_style, unified_diff
|
|
10
|
+
from .extract import parse_page, visible_text
|
|
11
|
+
from .rules import RULES, Ctx, Edit, Finding, band_for
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class AeoResult:
|
|
16
|
+
findings: list[Finding] = field(default_factory=list)
|
|
17
|
+
diff: str = ""
|
|
18
|
+
edited_text: str = ""
|
|
19
|
+
intent: str = "unknown"
|
|
20
|
+
entity: str | None = None
|
|
21
|
+
lang: str | None = None
|
|
22
|
+
questions: list[str] = field(default_factory=list)
|
|
23
|
+
skipped: str | None = None
|
|
24
|
+
source_path: str | None = None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _overlaps(a: Edit, b: Edit) -> bool:
|
|
28
|
+
if a.start == a.end and b.start == b.end:
|
|
29
|
+
return False
|
|
30
|
+
if a.start == a.end:
|
|
31
|
+
return b.start < a.start < b.end
|
|
32
|
+
if b.start == b.end:
|
|
33
|
+
return a.start < b.start < a.end
|
|
34
|
+
return a.start < b.end and b.start < a.end
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _resolve(findings: list[Finding]) -> tuple[list[Finding], list[Edit]]:
|
|
38
|
+
"""First finding wins; a later finding whose edit collides is kept as advice with no
|
|
39
|
+
diff, so nothing is applied twice and nothing is half-applied."""
|
|
40
|
+
accepted: list[Edit] = []
|
|
41
|
+
out: list[Finding] = []
|
|
42
|
+
for finding in findings:
|
|
43
|
+
if finding.edits and any(_overlaps(e, a) for e in finding.edits for a in accepted):
|
|
44
|
+
finding = replace(finding, edits=(), message=(
|
|
45
|
+
finding.message + " Not part of the diff: it overlaps another proposal. "
|
|
46
|
+
"Apply the diff, then run again."))
|
|
47
|
+
accepted.extend(finding.edits)
|
|
48
|
+
out.append(finding)
|
|
49
|
+
return out, accepted
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def apply_edits(text: str, edits: list[Edit]) -> str:
|
|
53
|
+
out, cursor = [], 0
|
|
54
|
+
for edit in sorted(edits, key=lambda e: (e.start, e.end)):
|
|
55
|
+
out.append(text[cursor:edit.start])
|
|
56
|
+
out.append(edit.text)
|
|
57
|
+
cursor = edit.end
|
|
58
|
+
out.append(text[cursor:])
|
|
59
|
+
return "".join(out)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def analyse(text: str, *, source_path: str | None = None, as_of: date | None = None,
|
|
63
|
+
band: Band | None = None) -> AeoResult:
|
|
64
|
+
"""Evaluate the twelve rules on one HTML document. Pure: reads nothing, writes nothing.
|
|
65
|
+
|
|
66
|
+
`source_path` is the file `text` was read from; only then is a unified diff built.
|
|
67
|
+
"""
|
|
68
|
+
page = parse_page(text)
|
|
69
|
+
result = AeoResult(intent=page.intent, entity=page.entity, lang=page.lang,
|
|
70
|
+
questions=page.questions, source_path=source_path, edited_text=text)
|
|
71
|
+
if page.noindex:
|
|
72
|
+
result.skipped = "noindex"
|
|
73
|
+
return result
|
|
74
|
+
if page.h1 is None or not any(visible_text(b) for s in page.sections for b in s.blocks):
|
|
75
|
+
result.skipped = "no-content"
|
|
76
|
+
return result
|
|
77
|
+
ctx = Ctx(page=page, src=page.source, band=band or band_for(page.lang),
|
|
78
|
+
as_of=as_of or today(), nl=newline_style(text))
|
|
79
|
+
found = [f for rule in RULES for f in rule(ctx)]
|
|
80
|
+
result.findings, edits = _resolve(found)
|
|
81
|
+
result.edited_text = apply_edits(text, edits)
|
|
82
|
+
if source_path:
|
|
83
|
+
result.diff = unified_diff(source_path, text, result.edited_text)
|
|
84
|
+
return result
|