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
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
"""Readers that turn a page, the project config or markdown frontmatter into Facts.
|
|
2
|
+
|
|
3
|
+
Fact keys (dotted names) are the only interface between the readers and ``core``:
|
|
4
|
+
``site.*`` (name, legalName, url, logo, sameAs, phone, email, address,
|
|
5
|
+
searchUrlTemplate), ``page.*`` (url, name, description, image, language,
|
|
6
|
+
breadcrumbs), ``article.*`` (headline, datePublished, dateModified) and
|
|
7
|
+
``author.*`` (name, url, jobTitle, sameAs, worksFor).
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import re
|
|
12
|
+
from collections.abc import Mapping
|
|
13
|
+
from urllib.parse import urljoin, urlparse
|
|
14
|
+
|
|
15
|
+
from bs4 import BeautifulSoup, Tag
|
|
16
|
+
|
|
17
|
+
from .gate import Fact
|
|
18
|
+
from .vocab import is_http_url, is_iso_date
|
|
19
|
+
|
|
20
|
+
Facts = dict[str, Fact]
|
|
21
|
+
_WS = re.compile(r"\s+")
|
|
22
|
+
OPACITY0 = re.compile(r"opacity:0(?:\.0+)?(?:;|!|$)")
|
|
23
|
+
HIDDEN_CLASSES = frozenset({"sr-only", "visually-hidden", "screen-reader-text"})
|
|
24
|
+
_MODIFIED_WORDS = re.compile(r"updated|modified|edit|revised", re.IGNORECASE)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _clean(text: str | None) -> str:
|
|
28
|
+
return _WS.sub(" ", text or "").strip()
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def merge_facts(*layers: Mapping[str, Fact]) -> Facts:
|
|
32
|
+
"""Combine fact layers; the first layer that has a key wins."""
|
|
33
|
+
out: Facts = {}
|
|
34
|
+
for layer in layers:
|
|
35
|
+
for key, fact in layer.items():
|
|
36
|
+
out.setdefault(key, fact)
|
|
37
|
+
return out
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def origin(url: str) -> str | None:
|
|
41
|
+
parts = urlparse(url)
|
|
42
|
+
if parts.scheme in ("http", "https") and parts.netloc:
|
|
43
|
+
return f"{parts.scheme}://{parts.netloc}"
|
|
44
|
+
return None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
# --- config ---------------------------------------------------------------------
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def facts_from_config(config) -> Facts:
|
|
51
|
+
raw = config.raw if hasattr(config, "raw") else dict(config)
|
|
52
|
+
facts: Facts = {}
|
|
53
|
+
site = raw.get("site", {})
|
|
54
|
+
for key, name in (("name", "site.name"), ("legalName", "site.legalName"),
|
|
55
|
+
("url", "site.url")):
|
|
56
|
+
if site.get(key):
|
|
57
|
+
facts[name] = Fact(site[key].rstrip("/") if key == "url" else site[key],
|
|
58
|
+
f"config:site.{key}")
|
|
59
|
+
same = [v for v in (raw.get("sameAs") or {}).values() if v]
|
|
60
|
+
if same:
|
|
61
|
+
facts["site.sameAs"] = Fact(same, "config:sameAs")
|
|
62
|
+
nap = raw.get("nap", {})
|
|
63
|
+
if nap.get("phone"):
|
|
64
|
+
facts["site.phone"] = Fact(nap["phone"], "config:nap.phone")
|
|
65
|
+
if nap.get("email"):
|
|
66
|
+
facts["site.email"] = Fact(nap["email"], "config:nap.email")
|
|
67
|
+
address = {k: nap[k] for k in ("street", "city", "region", "postalCode", "country")
|
|
68
|
+
if nap.get(k)}
|
|
69
|
+
if address:
|
|
70
|
+
facts["site.address"] = Fact(address, "config:nap")
|
|
71
|
+
return facts
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
# --- frontmatter ------------------------------------------------------------------
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _scalar(text: str):
|
|
78
|
+
text = text.strip()
|
|
79
|
+
if len(text) >= 2 and text[0] == text[-1] and text[0] in "'\"":
|
|
80
|
+
return text[1:-1]
|
|
81
|
+
if text.startswith("[") and text.endswith("]"):
|
|
82
|
+
return [_scalar(p) for p in text[1:-1].split(",") if p.strip()]
|
|
83
|
+
return text
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
_KEY = re.compile(r"^(\s*)([A-Za-z0-9_-]+):(?:\s+(.*)|\s*)$")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _parse_block(lines: list[str], i: int, indent: int):
|
|
90
|
+
"""Parse a mapping or a ``- item`` list at ``indent``. Returns (value, next index)."""
|
|
91
|
+
if i < len(lines) and lines[i].lstrip().startswith("- "):
|
|
92
|
+
items = []
|
|
93
|
+
while i < len(lines) and lines[i].lstrip().startswith("- ") \
|
|
94
|
+
and len(lines[i]) - len(lines[i].lstrip()) >= indent:
|
|
95
|
+
items.append(_scalar(lines[i].lstrip()[2:]))
|
|
96
|
+
i += 1
|
|
97
|
+
return items, i
|
|
98
|
+
out: dict = {}
|
|
99
|
+
while i < len(lines):
|
|
100
|
+
m = _KEY.match(lines[i])
|
|
101
|
+
if not m or len(m.group(1)) < indent:
|
|
102
|
+
break
|
|
103
|
+
if len(m.group(1)) > indent:
|
|
104
|
+
i += 1
|
|
105
|
+
continue
|
|
106
|
+
key, rest = m.group(2), m.group(3)
|
|
107
|
+
i += 1
|
|
108
|
+
if rest is None or rest == "":
|
|
109
|
+
nxt_indent = len(lines[i]) - len(lines[i].lstrip()) if i < len(lines) else 0
|
|
110
|
+
if i < len(lines) and nxt_indent > indent - (1 if indent else 0) \
|
|
111
|
+
and (nxt_indent > indent or lines[i].lstrip().startswith("- ")):
|
|
112
|
+
out[key], i = _parse_block(lines, i, nxt_indent)
|
|
113
|
+
else:
|
|
114
|
+
out[key] = ""
|
|
115
|
+
else:
|
|
116
|
+
out[key] = _scalar(rest)
|
|
117
|
+
return out, i
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def parse_frontmatter(text: str) -> dict:
|
|
121
|
+
"""A small YAML subset: scalars, quoted strings, inline/dash lists, one nested map."""
|
|
122
|
+
if not text.startswith("---"):
|
|
123
|
+
return {}
|
|
124
|
+
body = text.split("\n", 1)[1] if "\n" in text else ""
|
|
125
|
+
end = re.search(r"^---\s*$", body, re.MULTILINE)
|
|
126
|
+
if not end:
|
|
127
|
+
return {}
|
|
128
|
+
lines = [ln for ln in body[:end.start()].splitlines() if ln.strip()
|
|
129
|
+
and not ln.lstrip().startswith("#")]
|
|
130
|
+
data, _ = _parse_block(lines, 0, 0)
|
|
131
|
+
return data if isinstance(data, dict) else {}
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
_FM_ALIASES = {
|
|
135
|
+
"page.name": ("title",),
|
|
136
|
+
"article.headline": ("title",),
|
|
137
|
+
"page.description": ("description", "summary", "excerpt"),
|
|
138
|
+
"article.datePublished": ("datePublished", "date", "published", "publishDate", "pubDate"),
|
|
139
|
+
"article.dateModified": ("dateModified", "updated", "lastmod", "modified",
|
|
140
|
+
"last_modified_at"),
|
|
141
|
+
"page.image": ("image", "cover", "featured_image", "thumbnail"),
|
|
142
|
+
"page.url": ("canonical", "url"),
|
|
143
|
+
"page.language": ("lang", "language"),
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def facts_from_frontmatter(text: str) -> Facts:
|
|
148
|
+
data = parse_frontmatter(text)
|
|
149
|
+
facts: Facts = {}
|
|
150
|
+
for fact_key, aliases in _FM_ALIASES.items():
|
|
151
|
+
for alias in aliases:
|
|
152
|
+
value = data.get(alias)
|
|
153
|
+
if isinstance(value, str) and value.strip():
|
|
154
|
+
facts[fact_key] = Fact(value.strip(), f"frontmatter:{alias}")
|
|
155
|
+
break
|
|
156
|
+
author = data.get("author")
|
|
157
|
+
if isinstance(author, str) and author.strip():
|
|
158
|
+
facts["author.name"] = Fact(author.strip(), "frontmatter:author")
|
|
159
|
+
elif isinstance(author, dict):
|
|
160
|
+
for sub, key in (("name", "author.name"), ("url", "author.url"),
|
|
161
|
+
("jobTitle", "author.jobTitle"), ("worksFor", "author.worksFor"),
|
|
162
|
+
("sameAs", "author.sameAs")):
|
|
163
|
+
value = author.get(sub)
|
|
164
|
+
if isinstance(value, str):
|
|
165
|
+
value = value.strip()
|
|
166
|
+
if value:
|
|
167
|
+
if sub == "sameAs" and isinstance(value, str):
|
|
168
|
+
value = [value]
|
|
169
|
+
facts[key] = Fact(value, f"frontmatter:author.{sub}")
|
|
170
|
+
return facts
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
# --- html -----------------------------------------------------------------------------
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _visible(tag: Tag) -> bool:
|
|
177
|
+
"""False for markup inside hidden containers (we never mark up what users cannot see)."""
|
|
178
|
+
for el in [tag, *tag.parents]:
|
|
179
|
+
if not isinstance(el, Tag):
|
|
180
|
+
continue
|
|
181
|
+
if el.name in ("script", "style", "template", "noscript", "head"):
|
|
182
|
+
return False
|
|
183
|
+
if el.has_attr("hidden") or el.get("aria-hidden") == "true":
|
|
184
|
+
return False
|
|
185
|
+
style = (el.get("style") or "").replace(" ", "").lower()
|
|
186
|
+
if "display:none" in style or "visibility:hidden" in style \
|
|
187
|
+
or OPACITY0.search(style) \
|
|
188
|
+
or HIDDEN_CLASSES & {c.lower() for c in el.get("class") or []}:
|
|
189
|
+
return False
|
|
190
|
+
return True
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _meta(soup: BeautifulSoup, attr: str, name: str) -> str | None:
|
|
194
|
+
tag = soup.find("meta", attrs={attr: lambda v: v and v.strip().lower() == name})
|
|
195
|
+
content = _clean(tag.get("content")) if tag else ""
|
|
196
|
+
return content or None
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _absolute(base: str | None, href: str | None) -> str | None:
|
|
200
|
+
if not href or not href.strip():
|
|
201
|
+
return None
|
|
202
|
+
value = urljoin(base, href.strip()) if base else href.strip()
|
|
203
|
+
return value if is_http_url(value) else None
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _breadcrumbs(soup: BeautifulSoup, base: str | None, page_url: str | None):
|
|
207
|
+
nav = None
|
|
208
|
+
for cand in soup.find_all(["nav", "ol", "ul", "div"]):
|
|
209
|
+
label = (cand.get("aria-label") or "").lower()
|
|
210
|
+
classes = " ".join(cand.get("class") or []).lower()
|
|
211
|
+
if ("breadcrumb" in label or "breadcrumb" in classes
|
|
212
|
+
or "breadcrumb" in (cand.get("id") or "").lower()) and _visible(cand):
|
|
213
|
+
nav = cand
|
|
214
|
+
break
|
|
215
|
+
if nav is None:
|
|
216
|
+
return None
|
|
217
|
+
items = nav.find_all("li") or nav.find_all("a")
|
|
218
|
+
crumbs = []
|
|
219
|
+
fell_back = False
|
|
220
|
+
for pos, li in enumerate(items):
|
|
221
|
+
name = _clean(li.get_text(" "))
|
|
222
|
+
link = li if li.name == "a" else li.find("a")
|
|
223
|
+
url = _absolute(base, link.get("href")) if link else None
|
|
224
|
+
if not name:
|
|
225
|
+
continue
|
|
226
|
+
if url is None and pos == len(items) - 1 and page_url:
|
|
227
|
+
url = page_url
|
|
228
|
+
fell_back = url is not None
|
|
229
|
+
crumbs.append({"name": name, "url": url})
|
|
230
|
+
if not crumbs or any(c["url"] is None for c in crumbs):
|
|
231
|
+
return None
|
|
232
|
+
where = "html:breadcrumb nav"
|
|
233
|
+
if fell_back:
|
|
234
|
+
where += " (last item has no link; its URL is the page URL)"
|
|
235
|
+
return Fact(crumbs, where)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _dates(soup: BeautifulSoup) -> Facts:
|
|
239
|
+
facts: Facts = {}
|
|
240
|
+
|
|
241
|
+
def put(key, value, where):
|
|
242
|
+
if key not in facts and value and is_iso_date(value.strip()):
|
|
243
|
+
facts[key] = Fact(value.strip(), where)
|
|
244
|
+
|
|
245
|
+
for t in soup.find_all("time", attrs={"datetime": True}):
|
|
246
|
+
if not _visible(t):
|
|
247
|
+
continue
|
|
248
|
+
prop = (t.get("itemprop") or "").strip()
|
|
249
|
+
classes = " ".join(t.get("class") or []).lower()
|
|
250
|
+
if prop == "datePublished" or "published" in classes or "entry-date" in classes:
|
|
251
|
+
put("article.datePublished", t["datetime"], "html:time[datetime] (datePublished)")
|
|
252
|
+
elif prop == "dateModified" or "updated" in classes or "modified" in classes:
|
|
253
|
+
put("article.dateModified", t["datetime"], "html:time[datetime] (dateModified)")
|
|
254
|
+
meta_dates = (("article.datePublished", "article:published_time"),
|
|
255
|
+
("article.dateModified", "article:modified_time"),
|
|
256
|
+
("article.dateModified", "og:updated_time"))
|
|
257
|
+
for key, prop in meta_dates:
|
|
258
|
+
put(key, _meta(soup, "property", prop), f"html:meta[{prop}]")
|
|
259
|
+
if "article.datePublished" not in facts:
|
|
260
|
+
scope = soup.find("article") or soup
|
|
261
|
+
found = facts.get("article.dateModified")
|
|
262
|
+
|
|
263
|
+
def unclassified(t) -> bool:
|
|
264
|
+
classes = " ".join(t.get("class") or []).lower()
|
|
265
|
+
marked = any(w in classes for w in ("published", "entry-date", "updated",
|
|
266
|
+
"modified"))
|
|
267
|
+
return (_visible(t) and not t.get("itemprop") and not marked
|
|
268
|
+
and not (found and t["datetime"].strip() == found.value))
|
|
269
|
+
|
|
270
|
+
times = [t for t in scope.find_all("time", attrs={"datetime": True})
|
|
271
|
+
if unclassified(t)]
|
|
272
|
+
if len(times) == 1:
|
|
273
|
+
t = times[0]
|
|
274
|
+
context = _clean(t.parent.get_text(" ")) if t.parent else ""
|
|
275
|
+
if not _MODIFIED_WORDS.search(context):
|
|
276
|
+
put("article.datePublished", t["datetime"],
|
|
277
|
+
"html:time[datetime] (the only <time> in the article)")
|
|
278
|
+
return facts
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def _author(soup: BeautifulSoup, base: str | None) -> Facts:
|
|
282
|
+
facts: Facts = {}
|
|
283
|
+
for a in soup.find_all(["a", "link"], attrs={"rel": True}):
|
|
284
|
+
rel = a.get("rel")
|
|
285
|
+
rels = rel if isinstance(rel, list) else [rel]
|
|
286
|
+
if "author" in [r.lower() for r in rels] and _visible(a):
|
|
287
|
+
name = _clean(a.get_text(" "))
|
|
288
|
+
if name:
|
|
289
|
+
facts["author.name"] = Fact(name, "html:a[rel=author]")
|
|
290
|
+
url = _absolute(base, a.get("href"))
|
|
291
|
+
if url:
|
|
292
|
+
facts["author.url"] = Fact(url, "html:a[rel=author]@href")
|
|
293
|
+
return facts
|
|
294
|
+
holder = soup.find(attrs={"itemprop": "author"})
|
|
295
|
+
if holder is not None and _visible(holder):
|
|
296
|
+
name_el = holder.find(attrs={"itemprop": "name"}) or holder
|
|
297
|
+
name = _clean(name_el.get_text(" "))
|
|
298
|
+
if name:
|
|
299
|
+
facts["author.name"] = Fact(name, "html:[itemprop=author]")
|
|
300
|
+
link = holder.find("a", href=True)
|
|
301
|
+
url = _absolute(base, link["href"]) if link else None
|
|
302
|
+
if url:
|
|
303
|
+
facts["author.url"] = Fact(url, "html:[itemprop=author] a@href")
|
|
304
|
+
return facts
|
|
305
|
+
name = _meta(soup, "name", "author")
|
|
306
|
+
if name:
|
|
307
|
+
facts["author.name"] = Fact(name, "html:meta[name=author]")
|
|
308
|
+
return facts
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def _search_template(soup: BeautifulSoup, base: str | None) -> Fact | None:
|
|
312
|
+
for form in soup.find_all("form"):
|
|
313
|
+
if not _visible(form):
|
|
314
|
+
continue
|
|
315
|
+
role = (form.get("role") or "").lower()
|
|
316
|
+
field = form.find("input", attrs={"type": lambda v: v and v.lower() == "search"})
|
|
317
|
+
if role != "search" and field is None:
|
|
318
|
+
continue
|
|
319
|
+
field = field or form.find("input", attrs={"name": True})
|
|
320
|
+
name = field.get("name") if field else None
|
|
321
|
+
action = _absolute(base, form.get("action"))
|
|
322
|
+
if name and action and (form.get("method") or "get").lower() == "get" \
|
|
323
|
+
and "?" not in action:
|
|
324
|
+
return Fact(f"{action}?{name}={{search_term_string}}", "html:form[role=search]")
|
|
325
|
+
return None
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def facts_from_html(html: str, page_url: str | None = None) -> Facts:
|
|
329
|
+
soup = BeautifulSoup(html, "lxml")
|
|
330
|
+
facts: Facts = {}
|
|
331
|
+
|
|
332
|
+
canonical = None
|
|
333
|
+
for link in soup.find_all("link", attrs={"rel": True}):
|
|
334
|
+
rel = link.get("rel")
|
|
335
|
+
if "canonical" in [r.lower() for r in (rel if isinstance(rel, list) else [rel])]:
|
|
336
|
+
canonical = _absolute(page_url, link.get("href"))
|
|
337
|
+
break
|
|
338
|
+
if canonical:
|
|
339
|
+
facts["page.url"] = Fact(canonical, "html:link[rel=canonical]")
|
|
340
|
+
elif page_url and is_http_url(page_url):
|
|
341
|
+
facts["page.url"] = Fact(page_url, "input:page-url")
|
|
342
|
+
url = facts["page.url"].value if "page.url" in facts else None
|
|
343
|
+
base = url or page_url
|
|
344
|
+
|
|
345
|
+
title = _clean(soup.title.get_text()) if soup.title else ""
|
|
346
|
+
og_title = _meta(soup, "property", "og:title")
|
|
347
|
+
h1 = next((_clean(h.get_text(" ")) for h in soup.find_all("h1")
|
|
348
|
+
if _visible(h) and _clean(h.get_text(" "))), "")
|
|
349
|
+
if title:
|
|
350
|
+
facts["page.name"] = Fact(title, "html:title")
|
|
351
|
+
elif og_title:
|
|
352
|
+
facts["page.name"] = Fact(og_title, "html:meta[og:title]")
|
|
353
|
+
if h1:
|
|
354
|
+
facts["article.headline"] = Fact(h1, "html:h1")
|
|
355
|
+
elif title:
|
|
356
|
+
facts["article.headline"] = Fact(title, "html:title")
|
|
357
|
+
|
|
358
|
+
desc = _meta(soup, "name", "description")
|
|
359
|
+
if desc:
|
|
360
|
+
facts["page.description"] = Fact(desc, "html:meta[description]")
|
|
361
|
+
|
|
362
|
+
image = _absolute(base, _meta(soup, "property", "og:image"))
|
|
363
|
+
where = "html:meta[og:image]"
|
|
364
|
+
if not image:
|
|
365
|
+
art = soup.find("article")
|
|
366
|
+
img = art.find("img", src=True) if art else None
|
|
367
|
+
image = _absolute(base, img["src"]) if img is not None and _visible(img) else None
|
|
368
|
+
where = "html:article img"
|
|
369
|
+
if image:
|
|
370
|
+
facts["page.image"] = Fact(image, where)
|
|
371
|
+
|
|
372
|
+
html_tag = soup.find("html")
|
|
373
|
+
lang = _clean(html_tag.get("lang")) if html_tag else ""
|
|
374
|
+
if lang:
|
|
375
|
+
facts["page.language"] = Fact(lang, "html:html[lang]")
|
|
376
|
+
|
|
377
|
+
crumbs = _breadcrumbs(soup, base, url)
|
|
378
|
+
if crumbs:
|
|
379
|
+
facts["page.breadcrumbs"] = crumbs
|
|
380
|
+
facts.update(_dates(soup))
|
|
381
|
+
facts.update(_author(soup, base))
|
|
382
|
+
|
|
383
|
+
site_name = _meta(soup, "property", "og:site_name")
|
|
384
|
+
if site_name:
|
|
385
|
+
facts["site.name"] = Fact(site_name, "html:meta[og:site_name]")
|
|
386
|
+
logo = _absolute(base, _meta(soup, "property", "og:logo"))
|
|
387
|
+
if not logo:
|
|
388
|
+
el = soup.find(attrs={"itemprop": "logo"})
|
|
389
|
+
logo = _absolute(base, (el.get("src") or el.get("href") or el.get("content"))
|
|
390
|
+
if el is not None else None)
|
|
391
|
+
if logo:
|
|
392
|
+
facts["site.logo"] = Fact(logo, "html:og:logo/itemprop=logo")
|
|
393
|
+
template = _search_template(soup, base)
|
|
394
|
+
if template:
|
|
395
|
+
facts["site.searchUrlTemplate"] = template
|
|
396
|
+
return facts
|
omnirank/schema/gate.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""The no-fabrication gate (spec section 6).
|
|
2
|
+
|
|
3
|
+
A property reaches the output only through :meth:`Gate.emit` (a value read from a
|
|
4
|
+
recorded source) or :meth:`Gate.derive` (structure computed from facts that
|
|
5
|
+
already have a source, such as ``@id`` links). Anything else becomes a ``Gap``.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from .vocab import is_duration, is_http_url, is_iso_date, is_number, is_time
|
|
13
|
+
|
|
14
|
+
SOURCE_PREFIXES = ("html:", "config:", "frontmatter:", "input:", "derived:")
|
|
15
|
+
NO_VALUE = "no value found on the page, in the config or in frontmatter"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class Fact:
|
|
20
|
+
"""A value plus where it was read from (``html:...``, ``config:...``, ``frontmatter:...``)."""
|
|
21
|
+
|
|
22
|
+
value: Any
|
|
23
|
+
where: str
|
|
24
|
+
# Identity of the page element behind the value; defaults to ``where``. Two properties
|
|
25
|
+
# sharing a claim cannot both be filled (one element, one property).
|
|
26
|
+
claim: str | None = None
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class Gap:
|
|
31
|
+
"""A property that was left out, and why. ``required`` gaps make the CLI exit 1."""
|
|
32
|
+
|
|
33
|
+
property: str
|
|
34
|
+
reason: str
|
|
35
|
+
required: bool = False
|
|
36
|
+
|
|
37
|
+
def to_dict(self) -> dict:
|
|
38
|
+
return {"property": self.property, "reason": self.reason, "required": self.required}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _blank(value: Any) -> bool:
|
|
42
|
+
if value is None:
|
|
43
|
+
return True
|
|
44
|
+
if isinstance(value, str):
|
|
45
|
+
return not value.strip()
|
|
46
|
+
if isinstance(value, (list, tuple, dict)):
|
|
47
|
+
return len(value) == 0
|
|
48
|
+
return False
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass
|
|
52
|
+
class Gate:
|
|
53
|
+
omitted: list[Gap] = field(default_factory=list)
|
|
54
|
+
sources: dict[str, str] = field(default_factory=dict)
|
|
55
|
+
# When set, one page element (an ``html:`` source) may fill only one property.
|
|
56
|
+
exclusive_html: bool = False
|
|
57
|
+
_claims: dict[str, str] = field(default_factory=dict)
|
|
58
|
+
|
|
59
|
+
def gap(self, label: str, reason: str, required: bool = False) -> None:
|
|
60
|
+
self.omitted.append(Gap(label, reason, required))
|
|
61
|
+
|
|
62
|
+
def emit(self, node: dict, scope: str, prop: str, fact: Fact | None, *,
|
|
63
|
+
path: str | None = None, required: bool = False, kind: str = "text") -> bool:
|
|
64
|
+
"""Write ``node[prop]`` from ``fact`` iff it has a real, well-formed source."""
|
|
65
|
+
label = f"{scope}.{path or prop}"
|
|
66
|
+
if fact is None:
|
|
67
|
+
self.gap(label, NO_VALUE, required)
|
|
68
|
+
return False
|
|
69
|
+
if not isinstance(fact.where, str) or not fact.where.startswith(SOURCE_PREFIXES) \
|
|
70
|
+
or not fact.where.split(":", 1)[1].strip():
|
|
71
|
+
self.gap(label, "value has no recorded source; refusing to emit it", required)
|
|
72
|
+
return False
|
|
73
|
+
if _blank(fact.value):
|
|
74
|
+
self.gap(label, f"value from {fact.where} is empty", required)
|
|
75
|
+
return False
|
|
76
|
+
if self.exclusive_html and fact.where.startswith("html:"):
|
|
77
|
+
owner = next((o for k in (fact.claim or fact.where).split("|")
|
|
78
|
+
if (o := self._claims.get(k, label)) != label), label)
|
|
79
|
+
if owner != label:
|
|
80
|
+
self.gap(label, f"{fact.where} already supplies {owner}; one page element "
|
|
81
|
+
"never fills two properties", required)
|
|
82
|
+
return False
|
|
83
|
+
value = fact.value
|
|
84
|
+
if kind == "texts":
|
|
85
|
+
items = value if isinstance(value, list) else [value]
|
|
86
|
+
if not items or not all(isinstance(v, str) and v.strip() for v in items):
|
|
87
|
+
self.gap(label, f"value from {fact.where} is not a list of non-empty text", required)
|
|
88
|
+
return False
|
|
89
|
+
value = items
|
|
90
|
+
elif kind == "urls":
|
|
91
|
+
items = value if isinstance(value, list) else [value]
|
|
92
|
+
good = [v for v in items if is_http_url(v)]
|
|
93
|
+
if len(good) != len(items):
|
|
94
|
+
self.gap(label, f"dropped value(s) from {fact.where} that are not absolute "
|
|
95
|
+
"http(s) URLs", False)
|
|
96
|
+
if not good:
|
|
97
|
+
return False
|
|
98
|
+
value = good
|
|
99
|
+
else:
|
|
100
|
+
check = {"text": lambda v: isinstance(v, str) and bool(v.strip()),
|
|
101
|
+
"url": is_http_url, "date": is_iso_date,
|
|
102
|
+
"int": lambda v: isinstance(v, int) and not isinstance(v, bool),
|
|
103
|
+
"number": is_number, "duration": is_duration, "time": is_time}[kind]
|
|
104
|
+
if not check(value):
|
|
105
|
+
self.gap(label, f"value from {fact.where} is not a valid {kind}: {value!r}",
|
|
106
|
+
required)
|
|
107
|
+
return False
|
|
108
|
+
node[prop] = value
|
|
109
|
+
if self.exclusive_html and fact.where.startswith("html:"):
|
|
110
|
+
for key in (fact.claim or fact.where).split("|"):
|
|
111
|
+
self._claims[key] = label
|
|
112
|
+
self.sources[label] = fact.where
|
|
113
|
+
return True
|
|
114
|
+
|
|
115
|
+
def derive(self, node: dict, scope: str, prop: str, value: Any, *, from_: str,
|
|
116
|
+
path: str | None = None) -> None:
|
|
117
|
+
"""Structure computed from sourced facts (an @id link, an ordinal, a template)."""
|
|
118
|
+
if not from_ or not from_.strip():
|
|
119
|
+
raise ValueError("derive() needs the name of the facts it derives from")
|
|
120
|
+
node[prop] = value
|
|
121
|
+
self.sources[f"{scope}.{path or prop}"] = f"derived:{from_}"
|