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/rules.py
ADDED
|
@@ -0,0 +1,964 @@
|
|
|
1
|
+
"""The twelve on-page rules (spec section 7). Each rule is a function `Ctx -> [Finding]`.
|
|
2
|
+
|
|
3
|
+
Hard rule: a rule may MOVE, TRIM or RESTATE text that is already on the page and may
|
|
4
|
+
insert an `<!-- OMNIRANK-TODO: ... -->` comment. It never writes a new sentence, a
|
|
5
|
+
number, a date or a name. When an edit would need one, the rule emits a TODO instead.
|
|
6
|
+
A rule also refuses to edit a paragraph that contains inline markup (a link, emphasis)
|
|
7
|
+
because rewriting its text would silently drop the markup; those findings carry no diff.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import html as htmllib
|
|
12
|
+
import itertools
|
|
13
|
+
import re
|
|
14
|
+
import unicodedata
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from datetime import date
|
|
17
|
+
|
|
18
|
+
from bs4 import Comment, Tag
|
|
19
|
+
from bs4.element import PreformattedString
|
|
20
|
+
|
|
21
|
+
from ..bands import DEFAULT_BAND, Band, measure, script_of
|
|
22
|
+
from ..schema.extract import _visible as tag_visible
|
|
23
|
+
from .extract import (
|
|
24
|
+
HEADINGS,
|
|
25
|
+
NOT_CONTENT,
|
|
26
|
+
Page,
|
|
27
|
+
Section,
|
|
28
|
+
Source,
|
|
29
|
+
Span,
|
|
30
|
+
clean,
|
|
31
|
+
is_plain,
|
|
32
|
+
is_question,
|
|
33
|
+
jsonld_types,
|
|
34
|
+
parse_date,
|
|
35
|
+
sentences,
|
|
36
|
+
to_ascii_digits,
|
|
37
|
+
visible_text,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
CORRELATIONAL = "[correlational]"
|
|
41
|
+
EXPERIMENTAL = "[experimental]"
|
|
42
|
+
GUIDELINE = "[guideline]"
|
|
43
|
+
STANDARD = "[standard]"
|
|
44
|
+
|
|
45
|
+
_NO_CAUSE = ("Treat the evidence tag as the limit of the evidence: OmniRank does not claim "
|
|
46
|
+
"this change causes citations or rankings.")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True)
|
|
50
|
+
class Edit:
|
|
51
|
+
start: int
|
|
52
|
+
end: int
|
|
53
|
+
text: str
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass(frozen=True)
|
|
57
|
+
class Finding:
|
|
58
|
+
id: str
|
|
59
|
+
rule: int
|
|
60
|
+
severity: str
|
|
61
|
+
evidence: str
|
|
62
|
+
message: str
|
|
63
|
+
line: int | None = None
|
|
64
|
+
heading: str = ""
|
|
65
|
+
before: str | None = None
|
|
66
|
+
after: str | None = None
|
|
67
|
+
todo: str | None = None
|
|
68
|
+
edits: tuple[Edit, ...] = ()
|
|
69
|
+
note: str = field(default="", compare=False)
|
|
70
|
+
|
|
71
|
+
@property
|
|
72
|
+
def has_edit(self) -> bool:
|
|
73
|
+
return bool(self.edits)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def band_for(lang: str | None) -> Band:
|
|
77
|
+
"""40-60 words, or 80-200 characters for scripts with no word separator."""
|
|
78
|
+
return Band("chars", 80, 200) if script_of(lang) == "cjk" else DEFAULT_BAND
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@dataclass
|
|
82
|
+
class Ctx:
|
|
83
|
+
page: Page
|
|
84
|
+
src: Source
|
|
85
|
+
band: Band
|
|
86
|
+
as_of: date
|
|
87
|
+
nl: str = "\n"
|
|
88
|
+
|
|
89
|
+
@property
|
|
90
|
+
def entity(self) -> str | None:
|
|
91
|
+
return self.page.entity
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
# --- shared helpers -----------------------------------------------------------------------
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def esc(text: str) -> str:
|
|
98
|
+
return htmllib.escape(text, quote=False)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def todo_comment(rule_id: str, text: str) -> str:
|
|
102
|
+
safe = text.replace("--", "-").replace(">", "")
|
|
103
|
+
return f"<!-- OMNIRANK-TODO: [{rule_id}] {safe} -->"
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def acknowledged(tag: Tag, rule_id: str) -> bool:
|
|
107
|
+
"""True when a TODO for `rule_id` already follows `tag`: the author has been told."""
|
|
108
|
+
marker = f"OMNIRANK-TODO: [{rule_id}]"
|
|
109
|
+
for sibling in tag.next_siblings:
|
|
110
|
+
if isinstance(sibling, Comment):
|
|
111
|
+
if marker in sibling:
|
|
112
|
+
return True
|
|
113
|
+
elif isinstance(sibling, Tag) or str(sibling).strip():
|
|
114
|
+
return False
|
|
115
|
+
return False
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def line_of(ctx: Ctx, tag: Tag) -> int | None:
|
|
119
|
+
offset = ctx.src.offset(tag)
|
|
120
|
+
return ctx.src.line_at(offset) if offset is not None else None
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def todo_after(ctx: Ctx, anchor: Tag, rule_id: str, text: str) -> tuple[str, tuple[Edit, ...]]:
|
|
124
|
+
comment = todo_comment(rule_id, text)
|
|
125
|
+
span = ctx.src.span(anchor)
|
|
126
|
+
if span is None:
|
|
127
|
+
return comment, ()
|
|
128
|
+
indent = ctx.src.indent_at(span.start)
|
|
129
|
+
return comment, (Edit(span.end, span.end, f"{ctx.nl}{indent}{comment}"),)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _replace_inner(ctx: Ctx, tag: Tag, text: str) -> Edit | None:
|
|
133
|
+
span = ctx.src.span(tag)
|
|
134
|
+
if span is None or not is_plain(tag):
|
|
135
|
+
return None
|
|
136
|
+
return Edit(span.open_end, span.close_start, esc(text))
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _open_tag(ctx: Ctx, span: Span) -> str:
|
|
140
|
+
return ctx.src.text[span.start:span.open_end]
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _delete(ctx: Ctx, span: Span) -> Edit:
|
|
144
|
+
"""Delete an element and, when it sits alone on its line, the line's whitespace."""
|
|
145
|
+
text = ctx.src.text
|
|
146
|
+
start, end = span.start, span.end
|
|
147
|
+
line_start = text.rfind("\n", 0, start) + 1
|
|
148
|
+
if not text[line_start:start].strip():
|
|
149
|
+
start = line_start
|
|
150
|
+
if text[end:end + 2] == "\r\n":
|
|
151
|
+
end += 2
|
|
152
|
+
elif text[end:end + 1] == "\n":
|
|
153
|
+
end += 1
|
|
154
|
+
return Edit(start, end, "")
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _size(text: str, band: Band) -> int:
|
|
158
|
+
return measure(text, band)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
# --- rule 1: BLUF -----------------------------------------------------------------------------
|
|
162
|
+
|
|
163
|
+
_DEFINES_EN = r"(?:is|are|was|were|refers to|means)\b"
|
|
164
|
+
_DEFINES_BN = r"(?:হলো|হল|হচ্ছে|বলতে)"
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def defines(sentence: str, entity: str) -> bool:
|
|
168
|
+
s, e = clean(sentence).casefold(), re.escape(entity.casefold())
|
|
169
|
+
return bool(re.match(rf"(?:the |an? )?{e}\s+{_DEFINES_EN}", s)
|
|
170
|
+
or re.match(rf"{e}\s*(?:\([^)]*\))?\s*{_DEFINES_BN}", s))
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _bluf_sections(ctx: Ctx) -> list[Section]:
|
|
174
|
+
out, seen_h1 = [], False
|
|
175
|
+
for sec in ctx.page.sections:
|
|
176
|
+
if sec.level == 1 and not seen_h1:
|
|
177
|
+
seen_h1 = True
|
|
178
|
+
out.append(sec)
|
|
179
|
+
elif sec.level in (2, 3) and is_question(visible_text(sec.heading)):
|
|
180
|
+
out.append(sec)
|
|
181
|
+
return out
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
_META_CLASS = {"byline", "author", "meta", "date", "posted", "updated", "published", "dateline"}
|
|
185
|
+
_META_TEXT = re.compile(
|
|
186
|
+
r"^(by|written by|author|posted|published|updated|last updated)\b|^(লেখক|লিখেছেন)", re.IGNORECASE)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _is_meta_paragraph(para: Tag) -> bool:
|
|
190
|
+
"""A byline or date line: it sits under the H1 but is not the answer."""
|
|
191
|
+
text = visible_text(para)
|
|
192
|
+
if len(text.split()) > 15:
|
|
193
|
+
return False
|
|
194
|
+
return bool(_META_CLASS & {c.lower() for c in para.get("class") or []}
|
|
195
|
+
or _META_TEXT.match(text))
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _answer_paragraphs(sec: Section) -> list[Tag]:
|
|
199
|
+
paras = sec.lead_paragraphs()
|
|
200
|
+
while paras and _is_meta_paragraph(paras[0]):
|
|
201
|
+
paras = paras[1:]
|
|
202
|
+
return paras
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def bluf(ctx: Ctx) -> list[Finding]:
|
|
206
|
+
findings = []
|
|
207
|
+
for sec in _bluf_sections(ctx):
|
|
208
|
+
paras = _answer_paragraphs(sec)
|
|
209
|
+
if not paras:
|
|
210
|
+
continue
|
|
211
|
+
head = visible_text(sec.heading)
|
|
212
|
+
first = visible_text(paras[0])
|
|
213
|
+
size = _size(first, ctx.band)
|
|
214
|
+
if ctx.band.contains(size) or acknowledged(sec.heading, "aeo.bluf"):
|
|
215
|
+
continue
|
|
216
|
+
findings.append(_bluf_one(ctx, sec, paras, head, first, size))
|
|
217
|
+
return findings
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
_DEPENDENT_START = re.compile(
|
|
221
|
+
r"^(however|but|also|it|this|these|they|that|those|such|then|moreover|furthermore|"
|
|
222
|
+
r"additionally|instead|thus|so|and|এটি|এটা|এগুলো|এগুলি|তারা|ইহা|তবে|কিন্তু|এছাড়াও|এছাড়া)\b"
|
|
223
|
+
r"|^(এটি|এটা|এগুলো|এগুলি|তারা|ইহা|তবে|কিন্তু|এছাড়াও|এছাড়া)(?=\s|$)", re.IGNORECASE)
|
|
224
|
+
_POINTS_ELSEWHERE = re.compile(
|
|
225
|
+
r"\b(above|below|this section|previous|previously|following|mentioned|earlier|later)\b"
|
|
226
|
+
r"|উপরে|নিচে|পূর্বে|আগে", re.IGNORECASE)
|
|
227
|
+
_QUALIFIER = re.compile(
|
|
228
|
+
r"\b(only|legacy|deprecated|discontinued|note|notes|applies to|apply to|does not apply|"
|
|
229
|
+
r"do not apply|except|unless|as of|since|until|version|v\d+|\d+\.x|beta|experimental|"
|
|
230
|
+
r"this (page|section|article)|not supported)\b|শুধু|কেবল|ব্যতীত|ছাড়া", re.IGNORECASE)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _unsafe_cut(pool: list[tuple[int, str]], chosen: int) -> str | None:
|
|
234
|
+
"""Why the first `chosen+1` sentences cannot stand alone as the answer, or None. The
|
|
235
|
+
answer is always a PREFIX of the existing sentences in their original order; it is
|
|
236
|
+
refused when it would lean on, or be qualified by, a sentence it leaves behind."""
|
|
237
|
+
answer = [s for _, s in pool[:chosen + 1]]
|
|
238
|
+
left = [s for _, s in pool[chosen + 1:]]
|
|
239
|
+
for sentence in (answer[0], answer[-1]):
|
|
240
|
+
if _DEPENDENT_START.match(sentence):
|
|
241
|
+
return f"the answer would start or end on {sentence.split()[0]!r}, which leans on a neighbouring sentence"
|
|
242
|
+
if any(_POINTS_ELSEWHERE.search(s) for s in answer):
|
|
243
|
+
return "a sentence in the answer points at text elsewhere (above, below, previous, following)"
|
|
244
|
+
if left and _DEPENDENT_START.match(left[0]):
|
|
245
|
+
return f"the next sentence starts with {left[0].split()[0]!r} and would be separated from what it refers to"
|
|
246
|
+
if any(_QUALIFIER.search(s) for s in left):
|
|
247
|
+
return "a sentence that would be left behind scopes or qualifies the answer (only, legacy, except, unless, version...)"
|
|
248
|
+
return None
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _bluf_one(ctx: Ctx, sec: Section, paras: list[Tag], head: str, first: str,
|
|
252
|
+
size: int) -> Finding:
|
|
253
|
+
unit = "words" if ctx.band.unit == "words" else "characters"
|
|
254
|
+
pool = [(i, s) for i, p in enumerate(paras) for s in sentences(visible_text(p))]
|
|
255
|
+
chosen, total = None, 0
|
|
256
|
+
for j in range(len(pool)):
|
|
257
|
+
total += _size(pool[j][1], ctx.band)
|
|
258
|
+
if ctx.band.contains(total):
|
|
259
|
+
chosen = j
|
|
260
|
+
break
|
|
261
|
+
if total > ctx.band.maximum:
|
|
262
|
+
break
|
|
263
|
+
base = {"rule": 1, "severity": "warning", "evidence": EXPERIMENTAL, "heading": head,
|
|
264
|
+
"line": line_of(ctx, paras[0]), "before": first}
|
|
265
|
+
where = f"the first paragraph under {head!r} has {size} {unit}"
|
|
266
|
+
defined = ctx.entity and sec.level == 1 and next(
|
|
267
|
+
(k for k, (_, s) in enumerate(pool) if defines(s, ctx.entity)), 0)
|
|
268
|
+
if defined:
|
|
269
|
+
todo, edits = todo_after(ctx, sec.heading, "aeo.bluf", (
|
|
270
|
+
f"the definition of {ctx.entity!r} is sentence {defined + 1} of the opening; put "
|
|
271
|
+
"it first by hand and check the sentences before it still make sense. OmniRank "
|
|
272
|
+
"does not reorder text."))
|
|
273
|
+
return Finding(id="aeo.bluf.buried", todo=todo, edits=edits, message=(
|
|
274
|
+
f"{where}, outside {ctx.band.describe()}, and the definition of {ctx.entity!r} "
|
|
275
|
+
f"comes after it. Answer-first is a writing convention, not a proven citation "
|
|
276
|
+
f"lever; moving a sentence can change what its neighbours mean, so OmniRank "
|
|
277
|
+
f"does not reorder. {_NO_CAUSE}"), **base)
|
|
278
|
+
if chosen is None:
|
|
279
|
+
if total < ctx.band.minimum:
|
|
280
|
+
text = (f"{where}; target {ctx.band.describe()}, and the page has no more text "
|
|
281
|
+
"under this heading to build a direct answer from. Write the answer "
|
|
282
|
+
"from facts you can source.")
|
|
283
|
+
todo, edits = todo_after(ctx, sec.heading, "aeo.bluf", text)
|
|
284
|
+
return Finding(id="aeo.bluf.length", todo=todo, edits=edits, message=(
|
|
285
|
+
f"{where}, below {ctx.band.describe()}. Answer-first is a writing "
|
|
286
|
+
f"convention, not a proven citation lever. {_NO_CAUSE}"), **base)
|
|
287
|
+
return Finding(id="aeo.bluf.length", message=(
|
|
288
|
+
f"{where}; no run of whole sentences fits {ctx.band.describe()}. Rewrite the "
|
|
289
|
+
f"opening by hand. {_NO_CAUSE}"), **base)
|
|
290
|
+
reason = _unsafe_cut(pool, chosen)
|
|
291
|
+
if reason:
|
|
292
|
+
todo, edits = todo_after(ctx, sec.heading, "aeo.bluf", (
|
|
293
|
+
f"{where}; target {ctx.band.describe()}. OmniRank did not trim it because "
|
|
294
|
+
f"{reason}. Rewrite the opening by hand."))
|
|
295
|
+
return Finding(id="aeo.bluf.length", todo=todo, edits=edits, message=(
|
|
296
|
+
f"{where}, outside {ctx.band.describe()}. No safe whole-sentence cut exists: "
|
|
297
|
+
f"{reason}. {_NO_CAUSE}"), **base)
|
|
298
|
+
edits = _bluf_edits(ctx, paras, pool, 0, chosen)
|
|
299
|
+
answer = " ".join(s for _, s in pool[:chosen + 1])
|
|
300
|
+
return Finding(id="aeo.bluf.length", after=answer, edits=edits, message=(
|
|
301
|
+
f"{where}, outside {ctx.band.describe()}. Using the first whole sentences, in their "
|
|
302
|
+
f"original order, that fit {ctx.band.describe()}; the rest is kept right after. "
|
|
303
|
+
f"{_NO_CAUSE}"), **base)
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def _bluf_edits(ctx: Ctx, paras: list[Tag], pool: list[tuple[int, str]], start: int,
|
|
307
|
+
chosen: int) -> tuple[Edit, ...]:
|
|
308
|
+
selected = set(range(start, chosen + 1))
|
|
309
|
+
touched = {pool[k][0] for k in selected} | {0}
|
|
310
|
+
spans = {}
|
|
311
|
+
for i in touched:
|
|
312
|
+
span = ctx.src.span(paras[i])
|
|
313
|
+
if span is None or not is_plain(paras[i]):
|
|
314
|
+
return () # inline markup / unverifiable: no diff
|
|
315
|
+
spans[i] = span
|
|
316
|
+
answer = " ".join(pool[k][1] for k in sorted(selected))
|
|
317
|
+
edits = []
|
|
318
|
+
for i in sorted(touched):
|
|
319
|
+
rest = " ".join(s for k, (pi, s) in enumerate(pool) if pi == i and k not in selected)
|
|
320
|
+
open_tag = _open_tag(ctx, spans[i])
|
|
321
|
+
indent = ctx.src.indent_at(spans[i].start)
|
|
322
|
+
if i == 0:
|
|
323
|
+
new = f"{open_tag}{esc(answer)}</{paras[0].name}>"
|
|
324
|
+
if rest:
|
|
325
|
+
new += f"{ctx.nl}{indent}{open_tag}{esc(rest)}</{paras[0].name}>"
|
|
326
|
+
edits.append(Edit(spans[i].start, spans[i].end, new))
|
|
327
|
+
elif rest:
|
|
328
|
+
edits.append(Edit(spans[i].start, spans[i].end,
|
|
329
|
+
f"{open_tag}{esc(rest)}</{paras[i].name}>"))
|
|
330
|
+
else:
|
|
331
|
+
edits.append(_delete(ctx, spans[i]))
|
|
332
|
+
return tuple(edits)
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
# --- rule 6: definition sentences ---------------------------------------------------------------
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def definition(ctx: Ctx) -> list[Finding]:
|
|
339
|
+
page = ctx.page
|
|
340
|
+
if page.intent != "define" or not ctx.entity or page.h1 is None:
|
|
341
|
+
return []
|
|
342
|
+
h1_section = next(s for s in page.sections if s.heading is page.h1)
|
|
343
|
+
lead = [s for p in h1_section.lead_paragraphs() for s in sentences(visible_text(p))]
|
|
344
|
+
if any(defines(s, ctx.entity) for s in lead) or acknowledged(page.h1, "aeo.definition"):
|
|
345
|
+
return []
|
|
346
|
+
for sec in page.sections:
|
|
347
|
+
for block in sec.blocks:
|
|
348
|
+
if block.name == "p" and any(defines(s, ctx.entity)
|
|
349
|
+
for s in sentences(visible_text(block))):
|
|
350
|
+
return [Finding(
|
|
351
|
+
id="aeo.definition.later", rule=6, severity="warning",
|
|
352
|
+
evidence=EXPERIMENTAL, heading=visible_text(page.h1),
|
|
353
|
+
line=line_of(ctx, block), before=visible_text(block),
|
|
354
|
+
message=(f"The definition of {ctx.entity!r} is under "
|
|
355
|
+
f"{visible_text(sec.heading)!r}, not under the H1. Move it up "
|
|
356
|
+
f"by hand. {_NO_CAUSE}"))]
|
|
357
|
+
text = (f"this page is about {ctx.entity!r} but no sentence defines it. Add one "
|
|
358
|
+
f"sentence of the form '{ctx.entity} is ...' (what category it belongs to and "
|
|
359
|
+
"what it does) from facts you can source.")
|
|
360
|
+
todo, edits = todo_after(ctx, page.h1, "aeo.definition", text)
|
|
361
|
+
return [Finding(
|
|
362
|
+
id="aeo.definition.missing", rule=6, severity="warning", evidence=EXPERIMENTAL,
|
|
363
|
+
heading=visible_text(page.h1), line=line_of(ctx, page.h1), todo=todo, edits=edits,
|
|
364
|
+
message=(f"Entity page for {ctx.entity!r} has no definition sentence. OmniRank "
|
|
365
|
+
f"will not write one. {_NO_CAUSE}"))]
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
# --- rule 2: question-shaped headings -------------------------------------------------------------
|
|
369
|
+
|
|
370
|
+
MAX_QUESTION_WORDS = 20
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def _max_questions(n: int) -> int:
|
|
374
|
+
"""At least a third of the H2/H3 stay statements: never turn every heading into a
|
|
375
|
+
question."""
|
|
376
|
+
return max(1, (2 * n) // 3)
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def question_headings(ctx: Ctx) -> list[Finding]:
|
|
380
|
+
secs = [s for s in ctx.page.sections if s.level in (2, 3)]
|
|
381
|
+
n = len(secs)
|
|
382
|
+
if n < 2:
|
|
383
|
+
return []
|
|
384
|
+
asked = sum(1 for s in secs if is_question(visible_text(s.heading)))
|
|
385
|
+
if n >= 3 and asked == n:
|
|
386
|
+
return [Finding(
|
|
387
|
+
id="aeo.question-heading.all", rule=2, severity="info", evidence=EXPERIMENTAL,
|
|
388
|
+
heading=visible_text(secs[0].heading), line=line_of(ctx, secs[0].heading),
|
|
389
|
+
message=("Every H2/H3 is a question. Keep some headings as statements; "
|
|
390
|
+
f"question headings belong where readers actually ask. {_NO_CAUSE}"))]
|
|
391
|
+
findings = []
|
|
392
|
+
for sec in secs:
|
|
393
|
+
if asked >= _max_questions(n):
|
|
394
|
+
break
|
|
395
|
+
head = visible_text(sec.heading)
|
|
396
|
+
paras = sec.lead_paragraphs()
|
|
397
|
+
if is_question(head) or not paras:
|
|
398
|
+
continue
|
|
399
|
+
sents = sentences(visible_text(paras[0]))
|
|
400
|
+
if not sents or not sents[0].endswith(("?", "?")) \
|
|
401
|
+
or len(sents[0].split()) > MAX_QUESTION_WORDS \
|
|
402
|
+
or not _fits_heading(head, sents[0]):
|
|
403
|
+
continue
|
|
404
|
+
findings.append(_convert(ctx, sec, paras[0], head, sents))
|
|
405
|
+
asked += 1
|
|
406
|
+
return findings
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
_CTA = re.compile(
|
|
410
|
+
r"\b(want to|ready to|interested|learn more|get started|sign up|contact|looking for|"
|
|
411
|
+
r"need help|any questions|curious|why wait)\b", re.IGNORECASE)
|
|
412
|
+
_SECOND_PERSON = re.compile(r"\b(you|your|yours|you're|we|our|ours|us)\b", re.IGNORECASE)
|
|
413
|
+
_PUNCT = ".,;:!?()\"'\u201c\u201d?"
|
|
414
|
+
_FILLER = {"the", "and", "for", "how", "what", "why", "who", "when", "where", "which", "with",
|
|
415
|
+
"about", "does", "are", "you", "your", "can", "should", "will", "that", "this"}
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
def _content_words(text: str) -> set[str]:
|
|
419
|
+
out = set()
|
|
420
|
+
for word in text.casefold().split():
|
|
421
|
+
word = word.strip(_PUNCT)
|
|
422
|
+
word = word[:-1] if word.endswith("s") and word.isascii() else word
|
|
423
|
+
if len(word) > 2 and word not in _FILLER:
|
|
424
|
+
out.add(word)
|
|
425
|
+
return out
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def _fits_heading(head: str, question: str) -> bool:
|
|
429
|
+
"""The question may replace the heading only if it keeps EVERY content word of the
|
|
430
|
+
heading and is a real question, not a call to action or a second-person hook."""
|
|
431
|
+
words = _content_words(head)
|
|
432
|
+
return (not _CTA.search(question) and not _SECOND_PERSON.search(question)
|
|
433
|
+
and bool(words) and words <= _content_words(question))
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def _convert(ctx: Ctx, sec: Section, para: Tag, head: str, sents: list[str]) -> Finding:
|
|
437
|
+
question, rest = sents[0], " ".join(sents[1:])
|
|
438
|
+
edits: tuple[Edit, ...] = ()
|
|
439
|
+
h_edit = _replace_inner(ctx, sec.heading, question)
|
|
440
|
+
span = ctx.src.span(para)
|
|
441
|
+
if h_edit and span and is_plain(para):
|
|
442
|
+
p_edit = (Edit(span.open_end, span.close_start, esc(rest)) if rest
|
|
443
|
+
else _delete(ctx, span))
|
|
444
|
+
edits = (h_edit, p_edit)
|
|
445
|
+
return Finding(
|
|
446
|
+
id="aeo.question-heading.convert", rule=2, severity="info", evidence=EXPERIMENTAL,
|
|
447
|
+
heading=head, line=line_of(ctx, sec.heading), before=head, after=question,
|
|
448
|
+
edits=edits, message=(
|
|
449
|
+
f"The section under {head!r} already opens by asking {question!r}. Using that "
|
|
450
|
+
f"question as the heading (the sentence moves, nothing is added). {_NO_CAUSE}"))
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
# --- rule 3: passage self-sufficiency --------------------------------------------------------------
|
|
454
|
+
|
|
455
|
+
_PRONOUN_START = re.compile(
|
|
456
|
+
r"^(it|this|that|they|these|those|he|she)\b|^(এটি|এটা|এগুলো|এগুলি|তারা|ইহা)(?=\s|$)",
|
|
457
|
+
re.IGNORECASE)
|
|
458
|
+
MIN_PASSAGE_WORDS = 8
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def _content_paragraphs(ctx: Ctx) -> list[Tag]:
|
|
462
|
+
return [b for s in ctx.page.sections for b in s.blocks if b.name == "p"]
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
def passage(ctx: Ctx) -> list[Finding]:
|
|
466
|
+
"""Flag-only. Which noun a pronoun stands for is not something the page's text
|
|
467
|
+
reliably says (the entity of the H1 is often NOT the referent), so the tool never
|
|
468
|
+
substitutes a name. It reports the sentence and leaves a TODO for the author."""
|
|
469
|
+
findings = []
|
|
470
|
+
for para in _content_paragraphs(ctx):
|
|
471
|
+
text = visible_text(para)
|
|
472
|
+
sents = sentences(text)
|
|
473
|
+
if not sents or len(text.split()) < MIN_PASSAGE_WORDS \
|
|
474
|
+
or not _PRONOUN_START.match(sents[0]) or acknowledged(para, "aeo.passage"):
|
|
475
|
+
continue
|
|
476
|
+
first = sents[0]
|
|
477
|
+
word = first.split()[0]
|
|
478
|
+
todo, edits = todo_after(ctx, para, "aeo.passage", (
|
|
479
|
+
f"the first sentence opens with \"{word}\"; rewrite it so this passage names "
|
|
480
|
+
"its own subject. OmniRank does not choose the name."))
|
|
481
|
+
findings.append(Finding(
|
|
482
|
+
id="aeo.passage.pronoun", rule=3, severity="info", evidence=EXPERIMENTAL,
|
|
483
|
+
line=line_of(ctx, para), before=first, todo=todo, edits=edits,
|
|
484
|
+
message=("A passage may be lifted on its own, so it should name its subject; "
|
|
485
|
+
f"this one opens with {word!r}. OmniRank does not guess what the "
|
|
486
|
+
f"pronoun refers to. {_NO_CAUSE}")))
|
|
487
|
+
return findings
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
# --- rule 4: facts with units, dates and sources -----------------------------------------------------
|
|
491
|
+
|
|
492
|
+
_STAT = re.compile(
|
|
493
|
+
r"\d[\d,.]*\s*(?:%|percent\b|per cent\b|million\b|billion\b|trillion\b|শতাংশ|কোটি|লক্ষ|লাখ)"
|
|
494
|
+
r"|[$€£৳]\s*\d|\d[\d,.]*\s*(?:USD|EUR|GBP|BDT)\b", re.IGNORECASE)
|
|
495
|
+
_SOURCE_CUE = re.compile(
|
|
496
|
+
r"according to|\bsources?\b|\bsurvey|\bstudy\b|\bstudies\b|reported by|\bcited\b"
|
|
497
|
+
r"|\(\s*[A-Z][^)]{0,60}\d{4}\s*\)|অনুযায়ী|সূত্র|জরিপ|গবেষণা", re.IGNORECASE)
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
def _has_source(tag: Tag) -> bool:
|
|
501
|
+
if any(tag_visible(c) for c in tag.find_all("cite")) or any(
|
|
502
|
+
tag_visible(a) for a in tag.find_all("a", href=re.compile(r"^https?://", re.IGNORECASE))):
|
|
503
|
+
return True
|
|
504
|
+
return bool(_SOURCE_CUE.search(visible_text(tag)))
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
def facts(ctx: Ctx) -> list[Finding]:
|
|
508
|
+
findings = []
|
|
509
|
+
seen: set[int] = set()
|
|
510
|
+
for tag in ctx.page.scope.find_all(["p", "li"]):
|
|
511
|
+
if id(tag) in seen or not visible_text(tag) or not _in_content(ctx, tag):
|
|
512
|
+
continue
|
|
513
|
+
seen.add(id(tag))
|
|
514
|
+
claim = next((s for s in sentences(visible_text(tag)) if _STAT.search(s)), None)
|
|
515
|
+
if claim is None or _has_source(tag) or acknowledged(tag, "aeo.facts"):
|
|
516
|
+
continue
|
|
517
|
+
todo, edits = todo_after(ctx, tag, "aeo.facts", (
|
|
518
|
+
f"cite a source and the date or period for the figure in \"{claim}\", or "
|
|
519
|
+
"remove the figure. OmniRank does not add or estimate statistics."))
|
|
520
|
+
findings.append(Finding(
|
|
521
|
+
id="aeo.facts.unsourced", rule=4, severity="warning", evidence=GUIDELINE,
|
|
522
|
+
line=line_of(ctx, tag), before=claim, todo=todo, edits=edits,
|
|
523
|
+
message=("A numeric claim has no cited source on the page. Add the source and "
|
|
524
|
+
"its date or period; the tool never supplies a figure or a source.")))
|
|
525
|
+
return findings
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
def _in_content(ctx: Ctx, tag: Tag) -> bool:
|
|
529
|
+
return tag_visible(tag) and not tag.find_parent(NOT_CONTENT)
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
# --- rule 5: lists and tables -----------------------------------------------------------------------
|
|
533
|
+
|
|
534
|
+
_NUMBERED = re.compile(r"^(\d+)[.)।]\s+(.*)$", re.DOTALL)
|
|
535
|
+
_BULLET = re.compile(r"^[-•*–—·]\s+(.*)$", re.DOTALL)
|
|
536
|
+
_TABLE_IMG = re.compile(r"table|comparison|matrix|chart|pricing", re.IGNORECASE)
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
def lists_tables(ctx: Ctx) -> list[Finding]:
|
|
540
|
+
return [*_table_headers(ctx), *_pseudo_lists(ctx), *_table_gaps(ctx)]
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
def _table_headers(ctx: Ctx) -> list[Finding]:
|
|
544
|
+
out = []
|
|
545
|
+
for table in ctx.page.scope.find_all("table"):
|
|
546
|
+
if not _in_content(ctx, table) or table.find("th") or table.find("table"):
|
|
547
|
+
continue
|
|
548
|
+
rows = table.find_all("tr")
|
|
549
|
+
cells = rows[0].find_all("td", recursive=False) if rows else []
|
|
550
|
+
labels_only = all(visible_text(c) and not re.search(r"\d", visible_text(c))
|
|
551
|
+
and len(visible_text(c).split()) <= 4 for c in cells)
|
|
552
|
+
if len(rows) < 2 or len(cells) < 2 or not labels_only \
|
|
553
|
+
or any(c.get("scope") for c in cells):
|
|
554
|
+
continue # a first row with numbers is data, not column labels
|
|
555
|
+
edits = []
|
|
556
|
+
for cell in cells:
|
|
557
|
+
span = ctx.src.span(cell)
|
|
558
|
+
if span is None:
|
|
559
|
+
edits = []
|
|
560
|
+
break
|
|
561
|
+
edits += [Edit(span.start, span.start + 3, '<th scope="col"'),
|
|
562
|
+
Edit(span.close_start, span.end, "</th>")]
|
|
563
|
+
labels = " | ".join(visible_text(c) for c in cells)
|
|
564
|
+
out.append(Finding(
|
|
565
|
+
id="aeo.table.header", rule=5, severity="warning", evidence=STANDARD,
|
|
566
|
+
line=line_of(ctx, table), before=labels, after=labels if edits else None,
|
|
567
|
+
edits=tuple(edits), message=(
|
|
568
|
+
"A data table has no header cells (<th>), so a parser cannot tell labels "
|
|
569
|
+
"from values. Marking the first row as column headers; no text changes.")))
|
|
570
|
+
return out
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
def _marked(block: Tag | None) -> bool:
|
|
574
|
+
if block is None or block.name != "p" or not is_plain(block):
|
|
575
|
+
return False
|
|
576
|
+
text = visible_text(block)
|
|
577
|
+
return bool(_NUMBERED.match(text) or _BULLET.match(text))
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
def _pseudo_lists(ctx: Ctx) -> list[Finding]:
|
|
581
|
+
out = []
|
|
582
|
+
for sec in ctx.page.sections:
|
|
583
|
+
run: list[Tag] = []
|
|
584
|
+
for block in [*sec.blocks, None]:
|
|
585
|
+
if _marked(block) and (not run or run[-1].find_next_sibling() is block):
|
|
586
|
+
run.append(block)
|
|
587
|
+
continue
|
|
588
|
+
out += _list_from_run(ctx, run)
|
|
589
|
+
run = [block] if _marked(block) else []
|
|
590
|
+
return out
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
def _list_from_run(ctx: Ctx, run: list[Tag]) -> list[Finding]:
|
|
594
|
+
if len(run) < 3:
|
|
595
|
+
return []
|
|
596
|
+
texts = [visible_text(p) for p in run]
|
|
597
|
+
nums = [_NUMBERED.match(x) for x in texts]
|
|
598
|
+
bullets = [_BULLET.match(x) for x in texts]
|
|
599
|
+
if all(nums) and [int(to_ascii_digits(m.group(1))) for m in nums] == list(range(1, len(run) + 1)):
|
|
600
|
+
items, tag = [m.group(2).strip() for m in nums], "ol"
|
|
601
|
+
elif all(bullets):
|
|
602
|
+
items, tag = [m.group(1).strip() for m in bullets], "ul"
|
|
603
|
+
else:
|
|
604
|
+
return []
|
|
605
|
+
if not all(items):
|
|
606
|
+
return []
|
|
607
|
+
spans = [ctx.src.span(p) for p in run]
|
|
608
|
+
edits: tuple[Edit, ...] = ()
|
|
609
|
+
if all(spans) and all(_open_tag(ctx, s) == "<p>" for s in spans):
|
|
610
|
+
indent = ctx.src.indent_at(spans[0].start)
|
|
611
|
+
body = "".join(f"{ctx.nl}{indent}<li>{esc(i)}</li>" for i in items)
|
|
612
|
+
edits = (Edit(spans[0].start, spans[-1].end, f"<{tag}>{body}{ctx.nl}{indent}</{tag}>"),)
|
|
613
|
+
return [Finding(
|
|
614
|
+
id="aeo.list.markup", rule=5, severity="warning", evidence=GUIDELINE,
|
|
615
|
+
line=line_of(ctx, run[0]), before=" / ".join(texts), after=" / ".join(items),
|
|
616
|
+
edits=edits, message=(
|
|
617
|
+
"Consecutive paragraphs are typed as a list (numbers or dashes) instead of "
|
|
618
|
+
"using <ol>/<ul>. Real list markup is what a parser reads as steps or items; "
|
|
619
|
+
"the words stay the same, only the markers are dropped."))]
|
|
620
|
+
|
|
621
|
+
|
|
622
|
+
def _table_gaps(ctx: Ctx) -> list[Finding]:
|
|
623
|
+
scope = ctx.page.scope
|
|
624
|
+
if scope.find("table"):
|
|
625
|
+
return []
|
|
626
|
+
for img in scope.find_all("img"):
|
|
627
|
+
label = f"{img.get('alt') or ''} {img.get('src') or ''}"
|
|
628
|
+
if _in_content(ctx, img) and _TABLE_IMG.search(label):
|
|
629
|
+
return [Finding(
|
|
630
|
+
id="aeo.table.image", rule=5, severity="warning", evidence=GUIDELINE,
|
|
631
|
+
line=line_of(ctx, img), before=clean(label),
|
|
632
|
+
message=("This looks like a table or chart delivered as an image. Text in "
|
|
633
|
+
"an image cannot be quoted; publish the same data as a real "
|
|
634
|
+
"<table> with <th> cells."))]
|
|
635
|
+
if ctx.page.intent == "compare":
|
|
636
|
+
return [Finding(
|
|
637
|
+
id="aeo.table.missing", rule=5, severity="info", evidence=GUIDELINE,
|
|
638
|
+
line=line_of(ctx, ctx.page.h1) if ctx.page.h1 else None,
|
|
639
|
+
message=("A comparison page has no <table>. Present the facts already on the "
|
|
640
|
+
"page as a table with <th> cells; OmniRank will not invent the cells."))]
|
|
641
|
+
return []
|
|
642
|
+
|
|
643
|
+
|
|
644
|
+
# --- rule 7: entity consistency ----------------------------------------------------------------------
|
|
645
|
+
|
|
646
|
+
|
|
647
|
+
def _norm(text: str) -> str:
|
|
648
|
+
return "".join(c for c in text.casefold() if unicodedata.category(c)[0] in "LMN")
|
|
649
|
+
|
|
650
|
+
|
|
651
|
+
def _page_text(ctx: Ctx) -> str:
|
|
652
|
+
parts = [visible_text(t) for t in ctx.page.scope.find_all(["p", "li", *HEADINGS, "td", "th"])
|
|
653
|
+
if _in_content(ctx, t) and not t.find_parent(["code", "pre"])]
|
|
654
|
+
return "\n".join(parts)
|
|
655
|
+
|
|
656
|
+
|
|
657
|
+
def entity_consistency(ctx: Ctx) -> list[Finding]:
|
|
658
|
+
entity, page = ctx.entity, ctx.page
|
|
659
|
+
if not entity or not entity.isascii() or len(_norm(entity)) < 3:
|
|
660
|
+
return []
|
|
661
|
+
findings = []
|
|
662
|
+
letters = [re.escape(c) for c in entity if c.isalnum()]
|
|
663
|
+
pattern = re.compile(r"(?<!\w)" + r"[\s\-_]?".join(letters) + r"(?!\w)", re.IGNORECASE)
|
|
664
|
+
forms: dict[str, str] = {}
|
|
665
|
+
for m in pattern.finditer(page.title + "\n" + _page_text(ctx)):
|
|
666
|
+
forms.setdefault(m.group(0).casefold(), m.group(0))
|
|
667
|
+
if len(forms) > 1:
|
|
668
|
+
findings.append(Finding(
|
|
669
|
+
id="aeo.entity.variants", rule=7, severity="warning", evidence=EXPERIMENTAL,
|
|
670
|
+
line=line_of(ctx, page.h1) if page.h1 else None, before=" | ".join(forms.values()),
|
|
671
|
+
message=(f"{entity!r} is written {len(forms)} different ways (spacing or "
|
|
672
|
+
"hyphenation). Pick one spelling and use it in the title, headings, "
|
|
673
|
+
f"schema and body. {_NO_CAUSE}")))
|
|
674
|
+
if page.title and _norm(entity) not in _norm(page.title):
|
|
675
|
+
findings.append(Finding(
|
|
676
|
+
id="aeo.entity.title", rule=7, severity="info", evidence=EXPERIMENTAL,
|
|
677
|
+
line=None, before=page.title,
|
|
678
|
+
message=(f"The <title> does not name {entity!r}, the entity the H1 is about. "
|
|
679
|
+
f"Name it the same way the H1 does. {_NO_CAUSE}")))
|
|
680
|
+
return findings
|
|
681
|
+
|
|
682
|
+
|
|
683
|
+
# --- rule 8: freshness ----------------------------------------------------------------------------------
|
|
684
|
+
|
|
685
|
+
STALE_DAYS = 730
|
|
686
|
+
_TIME_TAGS = ["p", "span", "div", "time", "small", "li", "em"]
|
|
687
|
+
|
|
688
|
+
|
|
689
|
+
_KEYWORD = re.compile(r"\b(?:updated|modified|revised)\b|হালনাগাদ|আপডেট", re.IGNORECASE)
|
|
690
|
+
_LEAD = re.compile(r"^[\s:\u2013\u2014-]*(?:on\s+|at\s+)?", re.IGNORECASE)
|
|
691
|
+
|
|
692
|
+
|
|
693
|
+
def _visible_updated(ctx: Ctx) -> tuple[date | None, Tag | None]:
|
|
694
|
+
"""The date that FOLLOWS an update keyword in a short, meta-like element ("Updated on
|
|
695
|
+
3 March 2024", "Published 2020-01-01, updated 2024-05-01"). A sentence that merely
|
|
696
|
+
mentions updating something ("We updated the pricing table on 1 Jan 2019.") has words
|
|
697
|
+
between the keyword and the date, so it is not the page's date."""
|
|
698
|
+
body = ctx.page.soup.find("body") or ctx.page.soup
|
|
699
|
+
for el in body.find_all(_TIME_TAGS):
|
|
700
|
+
text = visible_text(el)
|
|
701
|
+
if not text or len(text) > 100 or len(text.split()) > 14 or not tag_visible(el):
|
|
702
|
+
continue
|
|
703
|
+
for match in _KEYWORD.finditer(text):
|
|
704
|
+
tail = _LEAD.sub("", text[match.end():])
|
|
705
|
+
found = parse_date(tail, at_start=True)
|
|
706
|
+
if found is None:
|
|
707
|
+
for stamp in el.find_all("time"):
|
|
708
|
+
if clean(stamp.get_text()) and clean(stamp.get_text()) in tail:
|
|
709
|
+
found = parse_date(stamp.get("datetime", ""), at_start=True)
|
|
710
|
+
break
|
|
711
|
+
if found:
|
|
712
|
+
return found, el
|
|
713
|
+
return None, None
|
|
714
|
+
|
|
715
|
+
|
|
716
|
+
def _date_modified(ctx: Ctx) -> date | None:
|
|
717
|
+
for node in ctx.page.jsonld:
|
|
718
|
+
if isinstance(node.get("dateModified"), str) and (d := parse_date(node["dateModified"])):
|
|
719
|
+
return d
|
|
720
|
+
soup = ctx.page.soup
|
|
721
|
+
for tag in (soup.find("meta", attrs={"property": "article:modified_time"}),
|
|
722
|
+
soup.find("meta", attrs={"itemprop": "dateModified"})):
|
|
723
|
+
if tag and (d := parse_date(tag.get("content", ""))):
|
|
724
|
+
return d
|
|
725
|
+
return None
|
|
726
|
+
|
|
727
|
+
|
|
728
|
+
def freshness(ctx: Ctx) -> list[Finding]:
|
|
729
|
+
shown, el = _visible_updated(ctx)
|
|
730
|
+
declared = _date_modified(ctx)
|
|
731
|
+
line = line_of(ctx, el) if el else None
|
|
732
|
+
common = {"rule": 8, "evidence": GUIDELINE}
|
|
733
|
+
out = []
|
|
734
|
+
if shown and declared and shown != declared:
|
|
735
|
+
out.append(Finding(
|
|
736
|
+
id="aeo.freshness.mismatch", severity="warning", line=line, before=el and visible_text(el),
|
|
737
|
+
message=(f"The visible update date is {shown.isoformat()} but dateModified says "
|
|
738
|
+
f"{declared.isoformat()}. Make both state the date the content last "
|
|
739
|
+
"truly changed; OmniRank cannot know which is right."), **common))
|
|
740
|
+
elif declared and not shown:
|
|
741
|
+
out.append(Finding(
|
|
742
|
+
id="aeo.freshness.not-visible", severity="info",
|
|
743
|
+
message=(f"dateModified is {declared.isoformat()} but no 'Updated on' date is "
|
|
744
|
+
"visible to readers. Show the date, and only bump it when the "
|
|
745
|
+
"content really changed."), **common))
|
|
746
|
+
if shown and (ctx.as_of - shown).days > STALE_DAYS:
|
|
747
|
+
out.append(Finding(
|
|
748
|
+
id="aeo.freshness.stale", severity="info", line=line, before=el and visible_text(el),
|
|
749
|
+
rule=8, evidence=CORRELATIONAL,
|
|
750
|
+
message=(f"The page says it was last updated {shown.isoformat()}, over "
|
|
751
|
+
f"{STALE_DAYS // 365} years before {ctx.as_of.isoformat()}. Review numbers, "
|
|
752
|
+
"versions and links; do not change the date unless the content changes. "
|
|
753
|
+
f"{_NO_CAUSE}")))
|
|
754
|
+
return out
|
|
755
|
+
|
|
756
|
+
|
|
757
|
+
# --- rule 9: author and provenance ---------------------------------------------------------------------------
|
|
758
|
+
|
|
759
|
+
_ARTICLE_TYPES = {"Article", "BlogPosting", "NewsArticle", "TechArticle", "Report"}
|
|
760
|
+
_BYLINE_TEXT = re.compile(r"^(by|written by|author)\b|^(লেখক|লিখেছেন)", re.IGNORECASE)
|
|
761
|
+
_POLICY = re.compile(r"editorial|review[-_ ]policy|corrections|সম্পাদকীয়", re.IGNORECASE)
|
|
762
|
+
|
|
763
|
+
|
|
764
|
+
def _is_article(ctx: Ctx) -> bool:
|
|
765
|
+
soup = ctx.page.soup
|
|
766
|
+
kinds = {k for n in ctx.page.jsonld for k in jsonld_types(n)}
|
|
767
|
+
og = soup.find("meta", attrs={"property": "og:type"})
|
|
768
|
+
return bool(soup.find("article") or kinds & _ARTICLE_TYPES
|
|
769
|
+
or (og and (og.get("content") or "").strip().lower() == "article"))
|
|
770
|
+
|
|
771
|
+
|
|
772
|
+
def _has_byline(ctx: Ctx) -> bool:
|
|
773
|
+
for el in ctx.page.soup.find_all(True):
|
|
774
|
+
if not tag_visible(el) or not visible_text(el):
|
|
775
|
+
continue
|
|
776
|
+
classes = " ".join(el.get("class") or []).lower()
|
|
777
|
+
rel = [r.lower() for r in (el.get("rel") or [])]
|
|
778
|
+
if "author" in rel or el.get("itemprop") == "author" or "byline" in classes \
|
|
779
|
+
or re.search(r"\bauthor\b", classes):
|
|
780
|
+
return True
|
|
781
|
+
if el.name in ("p", "span", "div", "small", "li") and len(visible_text(el)) <= 120 \
|
|
782
|
+
and _BYLINE_TEXT.match(visible_text(el)):
|
|
783
|
+
return True
|
|
784
|
+
return False
|
|
785
|
+
|
|
786
|
+
|
|
787
|
+
def author(ctx: Ctx) -> list[Finding]:
|
|
788
|
+
page = ctx.page
|
|
789
|
+
if not _is_article(ctx) or page.h1 is None:
|
|
790
|
+
return []
|
|
791
|
+
if not _has_byline(ctx):
|
|
792
|
+
if acknowledged(page.h1, "aeo.author"):
|
|
793
|
+
return []
|
|
794
|
+
todo, edits = todo_after(ctx, page.h1, "aeo.author", (
|
|
795
|
+
"add a visible byline with the real author's name and credentials, and link "
|
|
796
|
+
"an editorial or review policy page. OmniRank does not name authors."))
|
|
797
|
+
return [Finding(
|
|
798
|
+
id="aeo.author.missing", rule=9, severity="warning", evidence=GUIDELINE,
|
|
799
|
+
line=line_of(ctx, page.h1), heading=visible_text(page.h1), todo=todo, edits=edits,
|
|
800
|
+
message=("No visible byline. Showing who wrote a page, and their credentials, "
|
|
801
|
+
"is advice in Google's guidance on helpful content."))]
|
|
802
|
+
for link in page.soup.find_all("a"):
|
|
803
|
+
if tag_visible(link) and _POLICY.search(f"{visible_text(link)} {link.get('href', '')}"):
|
|
804
|
+
return []
|
|
805
|
+
return [Finding(
|
|
806
|
+
id="aeo.author.policy", rule=9, severity="info", evidence=GUIDELINE,
|
|
807
|
+
line=line_of(ctx, page.h1), heading=visible_text(page.h1),
|
|
808
|
+
message="The page has a byline but links no editorial or review policy page.")]
|
|
809
|
+
|
|
810
|
+
|
|
811
|
+
# --- rule 10: semantic HTML --------------------------------------------------------------------------------------
|
|
812
|
+
|
|
813
|
+
_LANDMARKS = ("main", "article", "section", "nav", "aside", "header", "footer")
|
|
814
|
+
_HEADING_CLASSES = {"h1", "h2", "h3", "h4", "h5", "h6", "heading"}
|
|
815
|
+
|
|
816
|
+
|
|
817
|
+
def semantic(ctx: Ctx) -> list[Finding]:
|
|
818
|
+
soup, out = ctx.page.soup, []
|
|
819
|
+
common = {"rule": 10, "evidence": GUIDELINE}
|
|
820
|
+
if not soup.find("main") and not soup.find(attrs={"role": "main"}):
|
|
821
|
+
out.append(Finding(id="aeo.semantic.main", severity="info", message=(
|
|
822
|
+
"No <main> landmark. It marks the content a parser should read; add it by "
|
|
823
|
+
f"hand, wrapping only the page's own content. {_NO_CAUSE}"), **common))
|
|
824
|
+
levels = [s.level for s in ctx.page.sections]
|
|
825
|
+
notes = []
|
|
826
|
+
if levels.count(1) > 1:
|
|
827
|
+
notes.append(f"{levels.count(1)} <h1> elements")
|
|
828
|
+
for prev, nxt in itertools.pairwise(levels):
|
|
829
|
+
if nxt > prev + 1:
|
|
830
|
+
notes.append(f"heading level jumps from h{prev} to h{nxt}")
|
|
831
|
+
if notes:
|
|
832
|
+
out.append(Finding(id="aeo.semantic.headings", severity="info", message=(
|
|
833
|
+
"Heading structure: " + "; ".join(notes) + f". {_NO_CAUSE}"), **common))
|
|
834
|
+
for el in ctx.page.scope.find_all(["p", "div", "span"]):
|
|
835
|
+
text = visible_text(el)
|
|
836
|
+
if not text or not _in_content(ctx, el) or len(text.split()) > 10:
|
|
837
|
+
continue
|
|
838
|
+
only_bold = el.name == "p" and len([c for c in el.children if isinstance(c, Tag)]) == 1 \
|
|
839
|
+
and el.find(["strong", "b"]) is not None and clean(el.get_text()) == clean(
|
|
840
|
+
el.find(["strong", "b"]).get_text()) and not text.endswith((".", "।", "?", ":"))
|
|
841
|
+
styled = el.name in ("div", "span") and is_plain(el) \
|
|
842
|
+
and _HEADING_CLASSES & {c.lower() for c in el.get("class") or []}
|
|
843
|
+
if only_bold or styled:
|
|
844
|
+
out.append(Finding(id="aeo.semantic.pseudo-heading", severity="info",
|
|
845
|
+
line=line_of(ctx, el), before=text, message=(
|
|
846
|
+
"This text is styled to look like a heading but is not one. Use a real "
|
|
847
|
+
f"<h2>/<h3> so the section is addressable. {_NO_CAUSE}"), **common))
|
|
848
|
+
if len(soup.find_all("div")) >= 15 and not soup.find(_LANDMARKS):
|
|
849
|
+
out.append(Finding(id="aeo.semantic.div-soup", severity="info", message=(
|
|
850
|
+
"The page is built from <div> elements with no semantic landmarks "
|
|
851
|
+
f"(main, article, section, nav). {_NO_CAUSE}"), **common))
|
|
852
|
+
return out
|
|
853
|
+
|
|
854
|
+
|
|
855
|
+
# --- rule 11: quote-ability -----------------------------------------------------------------------------------------
|
|
856
|
+
|
|
857
|
+
LONG_SENTENCE_WORDS = 40
|
|
858
|
+
|
|
859
|
+
|
|
860
|
+
def quotable(ctx: Ctx) -> list[Finding]:
|
|
861
|
+
out = []
|
|
862
|
+
soup = ctx.page.soup
|
|
863
|
+
for trigger in soup.find_all(attrs={"aria-controls": True}):
|
|
864
|
+
label = visible_text(trigger)
|
|
865
|
+
if not tag_visible(trigger) or not is_question(label):
|
|
866
|
+
continue
|
|
867
|
+
for target_id in trigger["aria-controls"].split():
|
|
868
|
+
target = soup.find(id=target_id)
|
|
869
|
+
if target is not None and not tag_visible(target) and target.get_text(strip=True):
|
|
870
|
+
out.append(Finding(
|
|
871
|
+
id="aeo.quotable.collapsed", rule=11, severity="warning",
|
|
872
|
+
evidence=EXPERIMENTAL, line=line_of(ctx, trigger), before=label,
|
|
873
|
+
message=("The answer to this question sits in a collapsed panel that "
|
|
874
|
+
"needs JavaScript to open, so it is hidden text. Use a native "
|
|
875
|
+
f"<details>/<summary> or show the answer. {_NO_CAUSE}")))
|
|
876
|
+
h1 = next((s for s in ctx.page.sections if s.level == 1), None)
|
|
877
|
+
if h1 and ctx.band.unit == "words":
|
|
878
|
+
for para in h1.lead_paragraphs()[:1]:
|
|
879
|
+
for s in sentences(visible_text(para)):
|
|
880
|
+
if len(s.split()) > LONG_SENTENCE_WORDS:
|
|
881
|
+
out.append(Finding(
|
|
882
|
+
id="aeo.quotable.long-sentence", rule=11, severity="info",
|
|
883
|
+
evidence=EXPERIMENTAL, line=line_of(ctx, para), before=s,
|
|
884
|
+
message=(f"A sentence of {len(s.split())} words opens the page. Key "
|
|
885
|
+
f"facts quote better as short standalone sentences. {_NO_CAUSE}")))
|
|
886
|
+
return out
|
|
887
|
+
|
|
888
|
+
|
|
889
|
+
# --- rule 12: language correctness ---------------------------------------------------------------------------------------
|
|
890
|
+
|
|
891
|
+
|
|
892
|
+
def _script_letters(ctx: Ctx) -> dict[str, int]:
|
|
893
|
+
counts = {"bengali": 0, "latin": 0}
|
|
894
|
+
for node in ctx.page.scope.find_all(string=True):
|
|
895
|
+
parent = node.parent
|
|
896
|
+
if isinstance(node, PreformattedString) or not tag_visible(parent):
|
|
897
|
+
continue
|
|
898
|
+
marked = False
|
|
899
|
+
for el in [parent, *parent.parents]:
|
|
900
|
+
if isinstance(el, Tag) and (el.name in ("code", "pre", *NOT_CONTENT)
|
|
901
|
+
or (el.name != "html" and el.has_attr("lang"))):
|
|
902
|
+
marked = True
|
|
903
|
+
break
|
|
904
|
+
if marked:
|
|
905
|
+
continue
|
|
906
|
+
for ch in str(node):
|
|
907
|
+
if not unicodedata.category(ch).startswith("L"):
|
|
908
|
+
continue
|
|
909
|
+
if "\u0980" <= ch <= "\u09ff":
|
|
910
|
+
counts["bengali"] += 1
|
|
911
|
+
elif "LATIN" in unicodedata.name(ch, ""):
|
|
912
|
+
counts["latin"] += 1
|
|
913
|
+
return counts
|
|
914
|
+
|
|
915
|
+
|
|
916
|
+
def language(ctx: Ctx) -> list[Finding]:
|
|
917
|
+
counts = _script_letters(ctx)
|
|
918
|
+
total = sum(counts.values())
|
|
919
|
+
lang, out = ctx.page.lang, []
|
|
920
|
+
common = {"rule": 12}
|
|
921
|
+
bn, la = (counts["bengali"] / total, counts["latin"] / total) if total else (0.0, 0.0)
|
|
922
|
+
if not lang:
|
|
923
|
+
dominant = ("mostly Bengali script" if bn > 0.5 else "mostly Latin script"
|
|
924
|
+
if la > 0.5 and total >= 20 else "")
|
|
925
|
+
out.append(Finding(
|
|
926
|
+
id="aeo.lang.missing", severity="warning", evidence=STANDARD,
|
|
927
|
+
message=("The <html> element has no lang attribute. Set it to the page's real "
|
|
928
|
+
"language" + (f" (the visible text is {dominant}, which alone does not "
|
|
929
|
+
"identify the language)" if dominant else "") + ". OmniRank "
|
|
930
|
+
"will not choose a value."), **common))
|
|
931
|
+
return out
|
|
932
|
+
primary = lang.lower().split("-")[0]
|
|
933
|
+
if (primary not in ("bn", "as") and bn > 0.5) \
|
|
934
|
+
or (primary == "bn" and la > 0.8 and total >= 40):
|
|
935
|
+
out.append(Finding(
|
|
936
|
+
id="aeo.lang.mismatch", severity="warning", evidence=STANDARD, before=lang,
|
|
937
|
+
message=(f'The page declares lang="{lang}" but {max(bn, la):.0%} of its visible '
|
|
938
|
+
f"letters are {'Bengali' if bn > la else 'Latin'} script."), **common))
|
|
939
|
+
elif total >= 20 and bn >= 0.15 and la >= 0.15:
|
|
940
|
+
out.append(Finding(
|
|
941
|
+
id="aeo.lang.mixed", severity="info", evidence=GUIDELINE,
|
|
942
|
+
message=(f"Bengali ({bn:.0%}) and Latin-script ({la:.0%}) text are mixed with no "
|
|
943
|
+
'lang attribute on the inline parts. Wrap the minority-language '
|
|
944
|
+
'phrases in <span lang="..."> and spell transliterated terms one '
|
|
945
|
+
"way throughout."), **common))
|
|
946
|
+
return out
|
|
947
|
+
|
|
948
|
+
|
|
949
|
+
_OPEN_TODO = re.compile(r"<!--\s*OMNIRANK-TODO:(.*?)-->", re.DOTALL)
|
|
950
|
+
|
|
951
|
+
|
|
952
|
+
def open_todos(ctx: Ctx) -> list[Finding]:
|
|
953
|
+
"""Housekeeping, not one of the twelve rules: a TODO block is a placeholder the author
|
|
954
|
+
still owes. It is reported on every run until it is replaced or deleted."""
|
|
955
|
+
return [Finding(
|
|
956
|
+
id="aeo.todo.open", rule=0, severity="info", evidence=GUIDELINE,
|
|
957
|
+
line=ctx.src.line_at(m.start()), before=clean(m.group(1)),
|
|
958
|
+
message=("An OMNIRANK-TODO block is still open. Write the missing content from facts "
|
|
959
|
+
"you can source, then delete the block; do not publish the comment."))
|
|
960
|
+
for m in _OPEN_TODO.finditer(ctx.src.text)]
|
|
961
|
+
|
|
962
|
+
|
|
963
|
+
RULES = (bluf, question_headings, passage, facts, lists_tables, definition,
|
|
964
|
+
entity_consistency, freshness, author, semantic, quotable, language, open_todos)
|