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,384 @@
|
|
|
1
|
+
"""Keyword analyses over a Search Console export.
|
|
2
|
+
|
|
3
|
+
Reused from ``omnirank.packs.gsc`` (not re-implemented): the CSV loader, ``cannibalization``
|
|
4
|
+
and ``decay``. Added here: query-level aggregation, striking distance, question mining,
|
|
5
|
+
heuristic intent labels, deterministic clustering and the optional volumes import.
|
|
6
|
+
|
|
7
|
+
Everything is deterministic: ties break on the query text, never on dict or set order.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import csv
|
|
12
|
+
import io
|
|
13
|
+
import math
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from ..packs import gsc as pack_gsc
|
|
18
|
+
from ..packs.gsc import GscError, Table, norm_query
|
|
19
|
+
from . import constants as C
|
|
20
|
+
from . import source, text
|
|
21
|
+
|
|
22
|
+
MODES = ("striking", "decay", "cannibal", "cluster", "questions")
|
|
23
|
+
MAX_VOLUME_ROWS = 1_000_000
|
|
24
|
+
VOLUME_FIELD_LIMIT = 4096
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class KeywordsError(GscError):
|
|
28
|
+
"""An input cannot be used; the message says what was needed."""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True)
|
|
32
|
+
class QueryStat:
|
|
33
|
+
query: str # as shown in the export (first spelling seen)
|
|
34
|
+
clicks: int
|
|
35
|
+
impressions: int
|
|
36
|
+
position: float | None # impression-weighted average
|
|
37
|
+
top_page: str | None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
# --- aggregation --------------------------------------------------------------------------------
|
|
41
|
+
|
|
42
|
+
def aggregate_queries(table: Table) -> list[QueryStat]:
|
|
43
|
+
"""One row per query (NFKC/case-folded), summing over pages. Needs a Query column."""
|
|
44
|
+
if "query" not in table.columns:
|
|
45
|
+
raise KeywordsError(f"{table.path} has no 'Query' column; keyword analyses need one "
|
|
46
|
+
"(export the Queries table, or Query+Page via the API)")
|
|
47
|
+
has_imp = "impressions" in table.columns
|
|
48
|
+
shown: dict[str, str] = {}
|
|
49
|
+
acc: dict[str, list] = {} # key -> [clicks, impressions, pos*w, w, {page: weight}]
|
|
50
|
+
for r in table.rows:
|
|
51
|
+
if r.query is None:
|
|
52
|
+
continue
|
|
53
|
+
key = norm_query(r.query)
|
|
54
|
+
shown.setdefault(key, r.query)
|
|
55
|
+
a = acc.setdefault(key, [0, 0, 0.0, 0, {}])
|
|
56
|
+
a[0] += r.clicks
|
|
57
|
+
a[1] += r.impressions or 0
|
|
58
|
+
if r.position is not None:
|
|
59
|
+
w = (r.impressions if has_imp else 1) or 1
|
|
60
|
+
a[2] += r.position * w
|
|
61
|
+
a[3] += w
|
|
62
|
+
if r.page is not None:
|
|
63
|
+
a[4][r.page] = a[4].get(r.page, 0) + ((r.impressions if has_imp else r.clicks) or 0)
|
|
64
|
+
out = []
|
|
65
|
+
for key, a in acc.items():
|
|
66
|
+
top = min(a[4], key=lambda p: (-a[4][p], p)) if a[4] else None
|
|
67
|
+
out.append(QueryStat(shown[key], a[0], a[1], a[2] / a[3] if a[3] else None, top))
|
|
68
|
+
out.sort(key=lambda s: (-s.impressions, -s.clicks, s.query))
|
|
69
|
+
return out
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
# --- intent and questions -----------------------------------------------------------------------
|
|
73
|
+
|
|
74
|
+
def intent(query: str) -> str:
|
|
75
|
+
"""Heuristic label: navigational, transactional, commercial, informational, unclassified.
|
|
76
|
+
|
|
77
|
+
Keyword-list based and checked in that priority order; the first token that matches wins.
|
|
78
|
+
It looks at the words only, never at the results page, so treat it as a hint.
|
|
79
|
+
"""
|
|
80
|
+
toks = set(text.tokens(query))
|
|
81
|
+
first = text.tokens(query)[:1]
|
|
82
|
+
for label, words in (("navigational", C.INTENT_NAVIGATIONAL),
|
|
83
|
+
("transactional", C.INTENT_TRANSACTIONAL),
|
|
84
|
+
("commercial", C.INTENT_COMMERCIAL)):
|
|
85
|
+
if toks & words:
|
|
86
|
+
return label
|
|
87
|
+
if (first and first[0] in C.QUESTION_START_EN) or toks & C.QUESTION_ANY_BN \
|
|
88
|
+
or toks & C.INTENT_INFORMATIONAL:
|
|
89
|
+
return "informational"
|
|
90
|
+
return "unclassified"
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def is_question(query: str) -> bool:
|
|
94
|
+
toks = text.tokens(query)
|
|
95
|
+
if not toks:
|
|
96
|
+
return False
|
|
97
|
+
return (query.rstrip().endswith(("?", "?")) or toks[0] in C.QUESTION_START_EN
|
|
98
|
+
or any(t in C.QUESTION_ANY_BN for t in toks))
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
# --- volumes (user supplied; never invented) ----------------------------------------------------
|
|
102
|
+
|
|
103
|
+
def _vol_int(s: str) -> int | None:
|
|
104
|
+
s = s.strip().replace(",", "").replace(" ", "")
|
|
105
|
+
return int(s) if s.isascii() and s.isdigit() and len(s) <= 12 else None
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _diff(s: str) -> float | None:
|
|
109
|
+
try:
|
|
110
|
+
v = float(s.strip())
|
|
111
|
+
except ValueError:
|
|
112
|
+
return None
|
|
113
|
+
return v if math.isfinite(v) and 0 <= v <= 100 else None
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def load_volumes(path: str | Path) -> tuple[dict[str, tuple[int, float | None]], dict]:
|
|
117
|
+
"""``keyword,volume[,difficulty]`` -> {normalised keyword: (volume, difficulty|None)}.
|
|
118
|
+
|
|
119
|
+
A row with a missing or non-numeric volume is skipped (counted in ``bad_rows``); a
|
|
120
|
+
difficulty outside 0..100 or non-numeric is dropped, the volume kept. Nothing is
|
|
121
|
+
estimated or defaulted."""
|
|
122
|
+
path = Path(path)
|
|
123
|
+
try:
|
|
124
|
+
raw = path.open("rb")
|
|
125
|
+
except OSError as exc:
|
|
126
|
+
raise KeywordsError(f"cannot open {path}: {exc.strerror or exc}") from exc
|
|
127
|
+
old = csv.field_size_limit(VOLUME_FIELD_LIMIT)
|
|
128
|
+
try:
|
|
129
|
+
with raw:
|
|
130
|
+
head = raw.read(2)
|
|
131
|
+
raw.seek(0)
|
|
132
|
+
enc = "utf-16" if head in (b"\xff\xfe", b"\xfe\xff") else "utf-8-sig"
|
|
133
|
+
try:
|
|
134
|
+
data = io.TextIOWrapper(raw, encoding=enc, errors="strict", newline="")
|
|
135
|
+
first = data.readline()
|
|
136
|
+
data.seek(0)
|
|
137
|
+
delim = pack_gsc._sniff(first)
|
|
138
|
+
reader = csv.reader(data, delimiter=delim)
|
|
139
|
+
header = next(reader, None) or []
|
|
140
|
+
names = [pack_gsc._header_key(h) for h in header]
|
|
141
|
+
kw_i = next((i for i, n in enumerate(names) if n in ("keyword", "keywords",
|
|
142
|
+
"query", "term")), None)
|
|
143
|
+
vol_i = next((i for i, n in enumerate(names)
|
|
144
|
+
if n in ("volume", "search volume", "monthly volume")), None)
|
|
145
|
+
dif_i = next((i for i, n in enumerate(names)
|
|
146
|
+
if n in ("difficulty", "keyword difficulty", "kd")), None)
|
|
147
|
+
if kw_i is None or vol_i is None:
|
|
148
|
+
raise KeywordsError(
|
|
149
|
+
f"{path} needs columns 'keyword' and 'volume' (optional 'difficulty'); "
|
|
150
|
+
f"found: {', '.join(repr(h.strip()) for h in header[:8])}")
|
|
151
|
+
out: dict[str, tuple[int, float | None]] = {}
|
|
152
|
+
rows = bad = 0
|
|
153
|
+
for rec in reader:
|
|
154
|
+
if not rec or all(not f.strip() for f in rec):
|
|
155
|
+
continue
|
|
156
|
+
rows += 1
|
|
157
|
+
if rows > MAX_VOLUME_ROWS:
|
|
158
|
+
break
|
|
159
|
+
if len(rec) <= max(kw_i, vol_i):
|
|
160
|
+
bad += 1
|
|
161
|
+
continue
|
|
162
|
+
vol = _vol_int(rec[vol_i])
|
|
163
|
+
key = norm_query(rec[kw_i])
|
|
164
|
+
if vol is None or not key:
|
|
165
|
+
bad += 1
|
|
166
|
+
continue
|
|
167
|
+
dif = _diff(rec[dif_i]) if dif_i is not None and dif_i < len(rec) else None
|
|
168
|
+
out[key] = (vol, dif)
|
|
169
|
+
except UnicodeDecodeError as exc:
|
|
170
|
+
raise KeywordsError(f"{path} is not valid UTF-8 or UTF-16 text") from exc
|
|
171
|
+
except csv.Error as exc:
|
|
172
|
+
raise KeywordsError(f"{path} is not a readable CSV ({exc})") from exc
|
|
173
|
+
finally:
|
|
174
|
+
csv.field_size_limit(old)
|
|
175
|
+
return out, {"rows": rows, "bad_rows": bad}
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _with_volume(item: dict, volumes) -> dict:
|
|
179
|
+
if volumes is not None:
|
|
180
|
+
got = volumes.get(norm_query(item["query"]))
|
|
181
|
+
item["volume"], item["difficulty"] = got if got else (None, None)
|
|
182
|
+
return item
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
# --- striking distance --------------------------------------------------------------------------
|
|
186
|
+
|
|
187
|
+
def striking(stats: list[QueryStat], *, min_impressions: int = C.DEFAULT_MIN_IMPRESSIONS,
|
|
188
|
+
volumes=None) -> list[dict] | None:
|
|
189
|
+
"""Queries whose average position is 8..20 inclusive. None when there is no Position
|
|
190
|
+
column. Ordered by impressions; no click gain is estimated (that needs a CTR model that
|
|
191
|
+
this tool does not claim to have)."""
|
|
192
|
+
if not any(s.position is not None for s in stats):
|
|
193
|
+
return None
|
|
194
|
+
out = []
|
|
195
|
+
for s in stats:
|
|
196
|
+
if s.position is None or s.impressions < min_impressions:
|
|
197
|
+
continue
|
|
198
|
+
# the RAW average decides membership; the shown position is rounded to one decimal
|
|
199
|
+
if C.STRIKING_MIN_POSITION <= s.position <= C.STRIKING_MAX_POSITION:
|
|
200
|
+
out.append(_with_volume({
|
|
201
|
+
"query": s.query, "position": round(s.position, 1),
|
|
202
|
+
"impressions": s.impressions, "clicks": s.clicks, "top_page": s.top_page,
|
|
203
|
+
"intent": intent(s.query)}, volumes))
|
|
204
|
+
return out
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
# --- questions ----------------------------------------------------------------------------------
|
|
208
|
+
|
|
209
|
+
def questions(stats: list[QueryStat], *, min_impressions: int = C.DEFAULT_MIN_IMPRESSIONS,
|
|
210
|
+
volumes=None) -> list[dict]:
|
|
211
|
+
return [_with_volume({"query": s.query, "impressions": s.impressions, "clicks": s.clicks,
|
|
212
|
+
"position": None if s.position is None else round(s.position, 1),
|
|
213
|
+
"top_page": s.top_page, "intent": intent(s.query),
|
|
214
|
+
"evidence": C.EVIDENCE}, volumes)
|
|
215
|
+
for s in stats if s.impressions >= min_impressions and is_question(s.query)]
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
# --- reused computations ------------------------------------------------------------------------
|
|
219
|
+
|
|
220
|
+
def cannibalization(table: Table, **kw):
|
|
221
|
+
got = pack_gsc.cannibalization(table, **kw)
|
|
222
|
+
if got is not None:
|
|
223
|
+
for c in got:
|
|
224
|
+
c["evidence"] = C.EVIDENCE_TAGS["cannibal"]
|
|
225
|
+
return got
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def decay(current: Table, previous: Table | None, **kw):
|
|
229
|
+
got = pack_gsc.decay(current, previous, **kw)
|
|
230
|
+
if got is not None:
|
|
231
|
+
got["evidence"] = C.EVIDENCE_TAGS["decay"]
|
|
232
|
+
return got
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
# --- clustering ---------------------------------------------------------------------------------
|
|
236
|
+
|
|
237
|
+
def cluster(stats: list[QueryStat], *, max_queries: int = C.CLUSTER_MAX_QUERIES,
|
|
238
|
+
volumes=None) -> dict:
|
|
239
|
+
"""Group queries whose content-token sets have Jaccard similarity >= 1/2 (union-find,
|
|
240
|
+
so the grouping is transitive). Considers the ``max_queries`` highest-impression queries;
|
|
241
|
+
a token shared by more than ``CLUSTER_MAX_TOKEN_FANOUT`` queries is not used to find
|
|
242
|
+
candidate pairs (so a pair that shares only such tokens is not compared)."""
|
|
243
|
+
ordered = sorted(stats, key=lambda s: (-s.impressions, -s.clicks, s.query))
|
|
244
|
+
used = ordered[:max_queries]
|
|
245
|
+
sets = [frozenset(text.content_tokens(s.query)) for s in used]
|
|
246
|
+
parent = list(range(len(used)))
|
|
247
|
+
|
|
248
|
+
def find(i: int) -> int:
|
|
249
|
+
while parent[i] != i:
|
|
250
|
+
parent[i] = parent[parent[i]]
|
|
251
|
+
i = parent[i]
|
|
252
|
+
return i
|
|
253
|
+
|
|
254
|
+
index: dict[str, list[int]] = {}
|
|
255
|
+
for i, ts in enumerate(sets):
|
|
256
|
+
for t in ts:
|
|
257
|
+
index.setdefault(t, []).append(i)
|
|
258
|
+
# No set of already-compared pairs: union-find makes a repeated comparison harmless, and
|
|
259
|
+
# such a set would grow without bound. Work is capped by CLUSTER_MAX_PAIRS instead.
|
|
260
|
+
budget = C.CLUSTER_MAX_PAIRS
|
|
261
|
+
truncated = False
|
|
262
|
+
num, den = C.CLUSTER_JACCARD_NUM, C.CLUSTER_JACCARD_DEN
|
|
263
|
+
for members in index.values():
|
|
264
|
+
if len(members) > C.CLUSTER_MAX_TOKEN_FANOUT:
|
|
265
|
+
continue
|
|
266
|
+
for a in range(len(members)):
|
|
267
|
+
ia = members[a]
|
|
268
|
+
x = sets[ia]
|
|
269
|
+
for b in range(a + 1, len(members)):
|
|
270
|
+
budget -= 1
|
|
271
|
+
if budget < 0:
|
|
272
|
+
truncated = True
|
|
273
|
+
break
|
|
274
|
+
ib = members[b]
|
|
275
|
+
y = sets[ib]
|
|
276
|
+
inter = len(x & y)
|
|
277
|
+
union = len(x) + len(y) - inter
|
|
278
|
+
if union and inter * den >= union * num:
|
|
279
|
+
rx, ry = find(ia), find(ib)
|
|
280
|
+
if rx != ry:
|
|
281
|
+
parent[max(rx, ry)] = min(rx, ry)
|
|
282
|
+
if truncated:
|
|
283
|
+
break
|
|
284
|
+
if truncated:
|
|
285
|
+
break
|
|
286
|
+
groups: dict[int, list[int]] = {}
|
|
287
|
+
for i in range(len(used)):
|
|
288
|
+
groups.setdefault(find(i), []).append(i)
|
|
289
|
+
clusters = []
|
|
290
|
+
singletons = 0
|
|
291
|
+
for members in groups.values():
|
|
292
|
+
if len(members) < 2:
|
|
293
|
+
singletons += 1
|
|
294
|
+
continue
|
|
295
|
+
ms = [used[i] for i in members]
|
|
296
|
+
label = min(ms, key=lambda s: (-s.impressions, len(s.query), s.query)).query
|
|
297
|
+
intents: dict[str, int] = {}
|
|
298
|
+
for s in ms:
|
|
299
|
+
k = intent(s.query)
|
|
300
|
+
intents[k] = intents.get(k, 0) + 1
|
|
301
|
+
item = {
|
|
302
|
+
"label": label, "size": len(ms), "impressions": sum(s.impressions for s in ms),
|
|
303
|
+
"clicks": sum(s.clicks for s in ms),
|
|
304
|
+
"queries": [s.query for s in sorted(
|
|
305
|
+
ms, key=lambda s: (-s.impressions, s.query))][:C.CLUSTER_MEMBER_LIMIT],
|
|
306
|
+
"intents": dict(sorted(intents.items())), "evidence": C.EVIDENCE}
|
|
307
|
+
if volumes is not None:
|
|
308
|
+
vs = [volumes.get(norm_query(s.query)) for s in ms]
|
|
309
|
+
item["supplied_volume_total"] = sum(v[0] for v in vs if v) if any(vs) else None
|
|
310
|
+
item["supplied_volume_coverage"] = f"{sum(1 for v in vs if v)}/{len(ms)}"
|
|
311
|
+
clusters.append(item)
|
|
312
|
+
clusters.sort(key=lambda c: (-c["impressions"], -c["size"], c["label"]))
|
|
313
|
+
return {"clusters": clusters, "singletons": singletons, "considered": len(used),
|
|
314
|
+
"skipped_beyond_cap": len(ordered) - len(used), "evidence": C.EVIDENCE,
|
|
315
|
+
"truncated": truncated,
|
|
316
|
+
"thresholds": {"token_jaccard": f"{C.CLUSTER_JACCARD_NUM}/{C.CLUSTER_JACCARD_DEN}",
|
|
317
|
+
"max_queries": max_queries,
|
|
318
|
+
"max_token_fanout": C.CLUSTER_MAX_TOKEN_FANOUT,
|
|
319
|
+
"max_pairs": C.CLUSTER_MAX_PAIRS},
|
|
320
|
+
"method": "content-token Jaccard + union-find; transitive, so a chain of "
|
|
321
|
+
"similar queries can merge queries that are not themselves similar"}
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
# --- whole report -------------------------------------------------------------------------------
|
|
325
|
+
|
|
326
|
+
def analyse(table: Table, *, modes=MODES, previous: Table | None = None,
|
|
327
|
+
min_impressions: int = C.DEFAULT_MIN_IMPRESSIONS, volumes=None,
|
|
328
|
+
max_queries: int = C.CLUSTER_MAX_QUERIES, volume_info: dict | None = None,
|
|
329
|
+
decay_window: int = 90) -> dict:
|
|
330
|
+
notes: list[str] = []
|
|
331
|
+
rep: dict = {"notice": C.NOTICE_NO_VOLUME, "modes": list(modes),
|
|
332
|
+
"rows": len(table.rows), "columns": table.columns,
|
|
333
|
+
"lists_reviewed_on": C.LISTS_REVIEWED_ON, "notes": notes,
|
|
334
|
+
"evidence_tags": {m: C.EVIDENCE_TAGS[m] for m in (*modes, "intent")
|
|
335
|
+
if m in C.EVIDENCE_TAGS}}
|
|
336
|
+
if table.bad_rows:
|
|
337
|
+
notes.append(f"{table.bad_rows} row(s) skipped (non-numeric or short rows); first "
|
|
338
|
+
f"problem: {table.bad_sample or 'short row'}")
|
|
339
|
+
if table.truncated:
|
|
340
|
+
if table.delimiter == "api":
|
|
341
|
+
notes.append(f"the Search Analytics pull stopped at the {source.API_MAX_ROWS:,}-row "
|
|
342
|
+
"cap; the data is incomplete")
|
|
343
|
+
else:
|
|
344
|
+
notes.append(f"only the first {pack_gsc.MAX_ROWS:,} rows were read")
|
|
345
|
+
if len(table.rows) + table.bad_rows == pack_gsc.EXPORT_ROW_LIMIT:
|
|
346
|
+
notes.append("the export has exactly 1,000 rows, Search Console's web-UI export "
|
|
347
|
+
"limit; it is probably truncated")
|
|
348
|
+
if volume_info is not None:
|
|
349
|
+
rep["volumes"] = volume_info
|
|
350
|
+
needs_query = any(m in modes for m in ("striking", "cluster", "questions"))
|
|
351
|
+
stats = aggregate_queries(table) if "query" in table.columns else None
|
|
352
|
+
if needs_query and stats is None:
|
|
353
|
+
raise KeywordsError(f"{table.path} has no 'Query' column; {', '.join(modes)} need one")
|
|
354
|
+
rep["queries"] = len(stats) if stats is not None else 0
|
|
355
|
+
if "striking" in modes:
|
|
356
|
+
rep["striking"] = striking(stats, min_impressions=min_impressions, volumes=volumes)
|
|
357
|
+
if rep["striking"] is None:
|
|
358
|
+
notes.append("striking distance skipped: the export has no Position column")
|
|
359
|
+
if "cannibal" in modes:
|
|
360
|
+
rep["cannibalization"] = cannibalization(table, min_impressions=min_impressions)
|
|
361
|
+
if rep["cannibalization"] is None:
|
|
362
|
+
notes.append("cannibalization skipped: the export needs Query and Page columns "
|
|
363
|
+
"together")
|
|
364
|
+
if "decay" in modes:
|
|
365
|
+
try:
|
|
366
|
+
rep["decay"] = decay(table, previous, window_days=decay_window)
|
|
367
|
+
except GscError as exc:
|
|
368
|
+
rep["decay"] = None
|
|
369
|
+
notes.append(f"decay skipped: {exc}")
|
|
370
|
+
else:
|
|
371
|
+
if rep["decay"] is None:
|
|
372
|
+
notes.append("decay skipped: it needs a second, earlier export "
|
|
373
|
+
"(--gsc-prev-csv or --property's previous window) or a Date "
|
|
374
|
+
f"column covering two {decay_window}-day windows "
|
|
375
|
+
f"({2 * decay_window} days)")
|
|
376
|
+
if "questions" in modes:
|
|
377
|
+
rep["questions"] = questions(stats, min_impressions=min_impressions, volumes=volumes)
|
|
378
|
+
if "cluster" in modes:
|
|
379
|
+
rep["clusters"] = cluster(stats, max_queries=max_queries, volumes=volumes)
|
|
380
|
+
if rep["clusters"]["truncated"]:
|
|
381
|
+
notes.append("clustering truncated: pair budget reached "
|
|
382
|
+
f"({C.CLUSTER_MAX_PAIRS:,} comparisons); some similar queries may be "
|
|
383
|
+
"unmerged")
|
|
384
|
+
return rep
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""Text, JSON and CSV renderings. Untrusted text (queries, pages) is made terminal-safe in
|
|
2
|
+
text output and formula-safe in CSV output."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import csv
|
|
6
|
+
import io
|
|
7
|
+
import json
|
|
8
|
+
|
|
9
|
+
from ..track.analysis import printable
|
|
10
|
+
|
|
11
|
+
CSV_DANGEROUS = ("=", "+", "-", "@", "\t", "\r")
|
|
12
|
+
NA = "n/a" # a volume/difficulty the user did not supply (JSON: null)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def safe_cell(value: object) -> str:
|
|
16
|
+
"""A CSV cell that a spreadsheet will not evaluate: a leading ``= + - @`` (or tab/CR) gets
|
|
17
|
+
a ``'`` in front."""
|
|
18
|
+
if value is None:
|
|
19
|
+
return ""
|
|
20
|
+
s = str(value)
|
|
21
|
+
return "'" + s if s.startswith(CSV_DANGEROUS) else s
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def p(value: object, limit: int = 200) -> str:
|
|
25
|
+
return printable("" if value is None else str(value), limit=limit)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def to_json(rep: dict) -> str:
|
|
29
|
+
return json.dumps(rep, indent=2, ensure_ascii=False)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
_CSV = {
|
|
33
|
+
"striking": ("query", "position", "impressions", "clicks", "top_page", "intent",
|
|
34
|
+
"volume", "difficulty"),
|
|
35
|
+
"questions": ("query", "impressions", "clicks", "position", "top_page", "intent",
|
|
36
|
+
"volume", "difficulty"),
|
|
37
|
+
"clusters": ("label", "size", "impressions", "clicks", "queries"),
|
|
38
|
+
"cannibalization": ("query", "total_impressions", "total_clicks", "pages"),
|
|
39
|
+
"decay": ("page", "previous_clicks", "current_clicks", "drop_pct"),
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def to_csv(rep: dict, mode: str) -> str:
|
|
44
|
+
key = {"cluster": "clusters", "cannibal": "cannibalization"}.get(mode, mode)
|
|
45
|
+
cols = [c for c in _CSV[key] if c not in ("volume", "difficulty")
|
|
46
|
+
or "volumes" in rep]
|
|
47
|
+
if key == "clusters":
|
|
48
|
+
rows = rep["clusters"]["clusters"]
|
|
49
|
+
elif key == "decay":
|
|
50
|
+
rows = rep["decay"]["decayed"]
|
|
51
|
+
else:
|
|
52
|
+
rows = rep[key] or []
|
|
53
|
+
buf = io.StringIO()
|
|
54
|
+
w = csv.writer(buf, lineterminator="\n")
|
|
55
|
+
w.writerow(cols)
|
|
56
|
+
for r in rows:
|
|
57
|
+
cells = []
|
|
58
|
+
for c in cols:
|
|
59
|
+
v = r.get(c)
|
|
60
|
+
if c == "queries":
|
|
61
|
+
v = " | ".join(v)
|
|
62
|
+
elif c == "pages":
|
|
63
|
+
v = " | ".join(x["page"] for x in v)
|
|
64
|
+
elif c in ("volume", "difficulty") and v is None:
|
|
65
|
+
v = NA
|
|
66
|
+
cells.append(safe_cell(v))
|
|
67
|
+
w.writerow(cells)
|
|
68
|
+
return buf.getvalue()
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _vol(r: dict) -> str:
|
|
72
|
+
if "volume" not in r:
|
|
73
|
+
return ""
|
|
74
|
+
v, d = r["volume"], r["difficulty"]
|
|
75
|
+
vs = f"{v} (supplied)" if v is not None else NA
|
|
76
|
+
ds = f"{d:g} (supplied)" if d is not None else NA
|
|
77
|
+
return f" volume {vs}, difficulty {ds}"
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def to_text(rep: dict, limit: int = 25) -> str:
|
|
81
|
+
n_q = rep["queries"]
|
|
82
|
+
head = (f"Keyword report: {rep['rows']} row(s), {n_q} distinct "
|
|
83
|
+
f"quer{'y' if n_q == 1 else 'ies'}")
|
|
84
|
+
out = [head, f" {rep['notice']}"]
|
|
85
|
+
if "volumes" in rep:
|
|
86
|
+
v = rep["volumes"]
|
|
87
|
+
out.append(f" volumes file: {v['rows']} row(s) read, {v['bad_rows']} skipped")
|
|
88
|
+
if rep.get("striking") is not None and "striking" in rep["modes"]:
|
|
89
|
+
s = rep["striking"]
|
|
90
|
+
out += ["", f"Striking distance (average position 8-20; {rep['evidence_tags']['striking']}): {len(s)}"]
|
|
91
|
+
for r in s[:limit]:
|
|
92
|
+
out.append(f" {p(r['query'])} pos {r['position']:g}, {r['impressions']} impr, "
|
|
93
|
+
f"{r['clicks']} clicks, intent {r['intent']}{_vol(r)}")
|
|
94
|
+
if r["top_page"]:
|
|
95
|
+
out.append(f" top page {p(r['top_page'])}")
|
|
96
|
+
if len(s) > limit:
|
|
97
|
+
out.append(f" ... {len(s) - limit} more (raise --limit or use --format json)")
|
|
98
|
+
if rep.get("cannibalization") is not None and "cannibal" in rep["modes"]:
|
|
99
|
+
c = rep["cannibalization"]
|
|
100
|
+
out += ["", f"Cannibalization (one query, 2+ pages) [correlational]: {len(c)}"]
|
|
101
|
+
for r in c[:limit]:
|
|
102
|
+
out.append(f" {p(r['query'])} {len(r['pages'])} pages, "
|
|
103
|
+
f"{r['total_impressions']} impr")
|
|
104
|
+
for pg in r["pages"][:5]:
|
|
105
|
+
out.append(f" {p(pg['page'])} {pg['impressions']} impr, "
|
|
106
|
+
f"{pg['clicks']} clicks")
|
|
107
|
+
out.append(" Several pages ranking for one query is not an error in itself.")
|
|
108
|
+
if rep.get("decay") is not None and "decay" in rep["modes"]:
|
|
109
|
+
d = rep["decay"]
|
|
110
|
+
pct = int(d["thresholds"]["drop_ratio"] * 100)
|
|
111
|
+
out += ["", (f"Decay ({d['mode']}) [correlational]: {len(d['decayed'])} page(s) lost >= {pct}% of "
|
|
112
|
+
"clicks")]
|
|
113
|
+
for r in d["decayed"][:limit]:
|
|
114
|
+
out.append(f" {p(r['page'])} {r['previous_clicks']} -> {r['current_clicks']} "
|
|
115
|
+
f"clicks (-{r['drop_pct']}%)")
|
|
116
|
+
if d["absent_from_current"]:
|
|
117
|
+
out.append(f" {len(d['absent_from_current'])} page(s) absent from the current "
|
|
118
|
+
"data (exports are truncated; this is not evidence of decay)")
|
|
119
|
+
out.append(" The cause is not known (seasonality, ranking, SERP changes).")
|
|
120
|
+
if rep.get("clusters") is not None and "cluster" in rep["modes"]:
|
|
121
|
+
c = rep["clusters"]
|
|
122
|
+
sing = c["singletons"]
|
|
123
|
+
out += ["", (f"Query clusters [experimental]: {len(c['clusters'])} cluster(s) of 2+ "
|
|
124
|
+
f"queries, {sing} single quer{'y' if sing == 1 else 'ies'} "
|
|
125
|
+
f"({c['considered']} considered, {c['skipped_beyond_cap']} beyond the "
|
|
126
|
+
"cap)")]
|
|
127
|
+
for r in c["clusters"][:limit]:
|
|
128
|
+
out.append(f" {p(r['label'])} {r['size']} queries, {r['impressions']} impr, "
|
|
129
|
+
f"{r['clicks']} clicks")
|
|
130
|
+
for q in r["queries"][:8]:
|
|
131
|
+
out.append(f" {p(q)}")
|
|
132
|
+
out.append(f" Method: {c['method']}.")
|
|
133
|
+
if rep.get("questions") is not None and "questions" in rep["modes"]:
|
|
134
|
+
q = rep["questions"]
|
|
135
|
+
out += ["", f"Questions in your own queries [experimental]: {len(q)}"]
|
|
136
|
+
for r in q[:limit]:
|
|
137
|
+
out.append(f" {p(r['query'])} {r['impressions']} impr, intent "
|
|
138
|
+
f"{r['intent']}{_vol(r)}")
|
|
139
|
+
for n in rep["notes"]:
|
|
140
|
+
out.append(f" note: {p(n)}")
|
|
141
|
+
out.append(" Intent labels and clusters are heuristic word-list results, not search-engine "
|
|
142
|
+
"data.")
|
|
143
|
+
return "\n".join(out)
|