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,160 @@
|
|
|
1
|
+
"""CLI handler for `omnirank keywords`.
|
|
2
|
+
|
|
3
|
+
Exit codes: 0 done; 2 usage error, unreadable input, refusal or API/authentication failure.
|
|
4
|
+
Read-only: the only network access is the Search Analytics query endpoint through
|
|
5
|
+
``connect.gsc.GscClient`` (read-only scope); nothing is written except stdout."""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import sys
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from ..connect import google_auth
|
|
12
|
+
from ..connect.constants import GOOGLE_API_HOSTS, SCOPE_GSC_READONLY
|
|
13
|
+
from ..connect.gsc import GscClient, GscError, validate_property
|
|
14
|
+
from ..connect.http import ApiClient, ApiError
|
|
15
|
+
from ..connect.secrets import redact
|
|
16
|
+
from ..packs.gsc import GscError as CsvError
|
|
17
|
+
from . import constants as C
|
|
18
|
+
from . import engine, report, source
|
|
19
|
+
|
|
20
|
+
MODE_FLAGS = ("striking", "decay", "cannibal", "cluster", "questions")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class UsageError(Exception):
|
|
24
|
+
pass
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _make_client(root: Path):
|
|
28
|
+
src = google_auth.resolve_token_source([SCOPE_GSC_READONLY], project_root=root)
|
|
29
|
+
return GscClient(ApiClient(src.token, allowed_hosts=GOOGLE_API_HOSTS))
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _err(msg: object) -> None:
|
|
33
|
+
print(f"omnirank: {report.p(redact(str(msg)), 2000)}", file=sys.stderr)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _positive(value: int, name: str, maximum: int = 1_000_000) -> int:
|
|
37
|
+
if isinstance(value, bool) or not 1 <= value <= maximum:
|
|
38
|
+
raise UsageError(f"{name} must be 1..{maximum}")
|
|
39
|
+
return value
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def run_keywords(args) -> int:
|
|
43
|
+
try:
|
|
44
|
+
return _run(args)
|
|
45
|
+
except (UsageError, engine.KeywordsError, source.SourceError, GscError, CsvError,
|
|
46
|
+
google_auth.AuthError, ApiError, ValueError) as exc:
|
|
47
|
+
_err(exc)
|
|
48
|
+
return 2
|
|
49
|
+
except KeyboardInterrupt:
|
|
50
|
+
_err("interrupted")
|
|
51
|
+
return 130
|
|
52
|
+
except Exception as exc: # noqa: BLE001 - never let a traceback carry a secret out
|
|
53
|
+
_err(f"unexpected error ({type(exc).__name__}): {exc}")
|
|
54
|
+
return 2
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _run(args) -> int:
|
|
58
|
+
if bool(args.gsc_csv) == bool(args.property):
|
|
59
|
+
raise UsageError("give exactly one source: --gsc-csv FILE (a Search Console export) "
|
|
60
|
+
"or --property SITE (Search Console API, read-only), not both")
|
|
61
|
+
if args.gsc_prev_csv and not args.gsc_csv:
|
|
62
|
+
raise UsageError("--gsc-prev-csv goes with --gsc-csv")
|
|
63
|
+
explicit = [m for m in MODE_FLAGS if getattr(args, m)]
|
|
64
|
+
modes = tuple(explicit) or engine.MODES
|
|
65
|
+
min_imp = _positive(args.min_impressions, "--min-impressions")
|
|
66
|
+
limit = _positive(args.limit, "--limit")
|
|
67
|
+
max_queries = _positive(args.max_queries, "--max-queries", C.CLUSTER_HARD_MAX_QUERIES)
|
|
68
|
+
decay_window = _positive(args.decay_window, "--decay-window", 365)
|
|
69
|
+
if args.format == "csv" and len(modes) != 1:
|
|
70
|
+
raise UsageError("--format csv needs exactly one mode (for example --striking)")
|
|
71
|
+
volumes = vinfo = None
|
|
72
|
+
if args.volumes:
|
|
73
|
+
volumes, vinfo = engine.load_volumes(args.volumes)
|
|
74
|
+
|
|
75
|
+
previous = None
|
|
76
|
+
if args.gsc_csv:
|
|
77
|
+
from ..packs.gsc import load_export
|
|
78
|
+
table = load_export(args.gsc_csv)
|
|
79
|
+
if args.gsc_prev_csv:
|
|
80
|
+
previous = load_export(args.gsc_prev_csv)
|
|
81
|
+
else:
|
|
82
|
+
site = validate_property(args.property)
|
|
83
|
+
cur, prev = source.windows(args.days, args.end)
|
|
84
|
+
client = _make_client(Path(args.root or "."))
|
|
85
|
+
table = source.fetch_table(client, site, *cur)
|
|
86
|
+
if "decay" in modes:
|
|
87
|
+
previous = source.fetch_table(client, site, *prev)
|
|
88
|
+
rep = engine.analyse(table, modes=modes, previous=previous, min_impressions=min_imp,
|
|
89
|
+
volumes=volumes, max_queries=max_queries, volume_info=vinfo,
|
|
90
|
+
decay_window=decay_window)
|
|
91
|
+
if previous is not None and previous.bad_rows:
|
|
92
|
+
rep["notes"].append(f"previous period: {previous.bad_rows} row(s) skipped")
|
|
93
|
+
if previous is not None and previous.truncated:
|
|
94
|
+
rep["notes"].append("previous period: the pull/read hit its row cap; decay may be "
|
|
95
|
+
"understated or overstated")
|
|
96
|
+
if "decay" in explicit and rep.get("decay") is None:
|
|
97
|
+
why = next((n for n in rep["notes"] if n.startswith("decay skipped")), "")
|
|
98
|
+
raise UsageError("decay cannot run: a single undated export cannot show it; give an "
|
|
99
|
+
"earlier export with --gsc-prev-csv FILE, a Date column covering two "
|
|
100
|
+
f"--decay-window windows (default 90 days each, 180 in all), or "
|
|
101
|
+
f"--property. {why}")
|
|
102
|
+
for key in ("striking", "questions", "cannibalization"):
|
|
103
|
+
if isinstance(rep.get(key), list):
|
|
104
|
+
rep[key] = rep[key][:limit]
|
|
105
|
+
if rep.get("decay"):
|
|
106
|
+
rep["decay"]["decayed"] = rep["decay"]["decayed"][:limit]
|
|
107
|
+
if rep.get("clusters"):
|
|
108
|
+
rep["clusters"]["clusters"] = rep["clusters"]["clusters"][:limit]
|
|
109
|
+
if args.format == "json":
|
|
110
|
+
print(report.to_json(rep))
|
|
111
|
+
elif args.format == "csv":
|
|
112
|
+
sys.stdout.write(report.to_csv(rep, modes[0]))
|
|
113
|
+
else:
|
|
114
|
+
print(report.to_text(rep, limit))
|
|
115
|
+
return 0
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def add_parsers(sub) -> None:
|
|
119
|
+
kw = sub.add_parser(
|
|
120
|
+
"keywords", help="First-party keyword engine over your own Search Console data: "
|
|
121
|
+
"striking distance, decay, cannibalization, query clusters, "
|
|
122
|
+
"questions (no paid index, no invented volume)")
|
|
123
|
+
src = kw.add_argument_group("source (exactly one)")
|
|
124
|
+
src.add_argument("--gsc-csv", metavar="FILE", help="Search Console export (Query/Page/"
|
|
125
|
+
"Clicks/Impressions/Position columns)")
|
|
126
|
+
src.add_argument("--property", metavar="SITE",
|
|
127
|
+
help="Search Console property (https://host/ or sc-domain:host); "
|
|
128
|
+
"read-only API")
|
|
129
|
+
kw.add_argument("--gsc-prev-csv", metavar="FILE",
|
|
130
|
+
help="Earlier export of the same length, for --decay with --gsc-csv")
|
|
131
|
+
modes = kw.add_argument_group("analyses (default: all)")
|
|
132
|
+
modes.add_argument("--striking", action="store_true",
|
|
133
|
+
help="Queries at average position 8-20")
|
|
134
|
+
modes.add_argument("--decay", action="store_true", help="Pages whose clicks fell")
|
|
135
|
+
modes.add_argument("--cannibal", action="store_true",
|
|
136
|
+
help="Queries with impressions on 2+ pages")
|
|
137
|
+
modes.add_argument("--cluster", action="store_true",
|
|
138
|
+
help="Group similar queries [experimental]")
|
|
139
|
+
modes.add_argument("--questions", action="store_true",
|
|
140
|
+
help="Questions found in your own queries [experimental]")
|
|
141
|
+
kw.add_argument("--volumes", metavar="FILE",
|
|
142
|
+
help="Your own CSV: keyword,volume[,difficulty]; used as given, never "
|
|
143
|
+
"estimated")
|
|
144
|
+
kw.add_argument("--min-impressions", type=int, default=C.DEFAULT_MIN_IMPRESSIONS,
|
|
145
|
+
help=f"Noise floor (default {C.DEFAULT_MIN_IMPRESSIONS})")
|
|
146
|
+
kw.add_argument("--limit", type=int, default=25, help="Rows listed per analysis "
|
|
147
|
+
"(default 25)")
|
|
148
|
+
kw.add_argument("--max-queries", type=int, default=C.CLUSTER_MAX_QUERIES,
|
|
149
|
+
help=f"Queries clustered, highest impressions first (default "
|
|
150
|
+
f"{C.CLUSTER_MAX_QUERIES}, at most {C.CLUSTER_HARD_MAX_QUERIES})")
|
|
151
|
+
kw.add_argument("--decay-window", type=int, default=90, metavar="DAYS",
|
|
152
|
+
help="--decay with a Date column: length of each of the two windows "
|
|
153
|
+
"(default 90, so 180 days of data are needed)")
|
|
154
|
+
kw.add_argument("--days", type=int, default=28,
|
|
155
|
+
help="--property: window length in days, 7..90 (default 28)")
|
|
156
|
+
kw.add_argument("--end", metavar="YYYY-MM-DD",
|
|
157
|
+
help="--property: last day of the window (default 3 days before today)")
|
|
158
|
+
kw.add_argument("--root", default=".", help="Project root (for stored credentials)")
|
|
159
|
+
kw.add_argument("--format", choices=("text", "json", "csv"), default="text",
|
|
160
|
+
help="csv needs exactly one analysis flag")
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Where the rows come from: a Search Console CSV export or the read-only Search Analytics
|
|
2
|
+
API (``connect.gsc.GscClient.query``). Nothing here writes anything."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from datetime import date, timedelta
|
|
6
|
+
|
|
7
|
+
from .. import clock
|
|
8
|
+
from ..packs.gsc import Row as GscCsvRow
|
|
9
|
+
from ..packs.gsc import Table, norm_page
|
|
10
|
+
|
|
11
|
+
DATA_LAG_DAYS = 3 # the newest days of Search Console data are still incomplete
|
|
12
|
+
MIN_DAYS, MAX_DAYS = 7, 90
|
|
13
|
+
API_MAX_ROWS = 100_000 # fetch_table's default row cap per window
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class SourceError(Exception):
|
|
17
|
+
pass
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def windows(days: int, end: str | None):
|
|
21
|
+
"""(current, previous) as ISO (start, end) pairs of equal length, the previous one
|
|
22
|
+
immediately before the current one. Without ``end`` the window stops DATA_LAG_DAYS before
|
|
23
|
+
today (``omnirank.clock``)."""
|
|
24
|
+
if isinstance(days, bool) or not MIN_DAYS <= days <= MAX_DAYS:
|
|
25
|
+
raise SourceError(f"--days must be {MIN_DAYS}..{MAX_DAYS}")
|
|
26
|
+
today = clock.today()
|
|
27
|
+
if end is None:
|
|
28
|
+
last = today - timedelta(days=DATA_LAG_DAYS)
|
|
29
|
+
else:
|
|
30
|
+
try:
|
|
31
|
+
last = date.fromisoformat(end)
|
|
32
|
+
except ValueError:
|
|
33
|
+
raise SourceError(f"--end {end[:20]!r} is not a YYYY-MM-DD date") from None
|
|
34
|
+
if last > today:
|
|
35
|
+
raise SourceError(f"--end {end} is in the future (today is {today})")
|
|
36
|
+
cur_start = last - timedelta(days=days - 1)
|
|
37
|
+
prev_end = cur_start - timedelta(days=1)
|
|
38
|
+
prev_start = prev_end - timedelta(days=days - 1)
|
|
39
|
+
return ((cur_start.isoformat(), last.isoformat()),
|
|
40
|
+
(prev_start.isoformat(), prev_end.isoformat()))
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def fetch_table(client, site: str, start: str, end: str, *, max_rows: int = API_MAX_ROWS) -> Table:
|
|
44
|
+
"""Query x page rows for one window as a ``packs.gsc.Table``. Counts are rounded to
|
|
45
|
+
whole numbers (the API reports integers); rows the client rejected count as bad rows."""
|
|
46
|
+
res = client.query(site, start, end, ["query", "page"], max_rows=max_rows)
|
|
47
|
+
table = Table(f"{site} {start}..{end}",
|
|
48
|
+
columns={"query": "query", "page": "page", "clicks": "clicks",
|
|
49
|
+
"impressions": "impressions", "position": "position"},
|
|
50
|
+
delimiter="api", bad_rows=res.skipped, truncated=res.truncated)
|
|
51
|
+
if res.skipped:
|
|
52
|
+
table.bad_sample = f"{res.skipped} API row(s) failed validation"
|
|
53
|
+
for r in res.rows:
|
|
54
|
+
q, p = r.dims.get("query"), r.dims.get("page")
|
|
55
|
+
if not q or not p:
|
|
56
|
+
table.bad_rows += 1
|
|
57
|
+
continue
|
|
58
|
+
table.rows.append(GscCsvRow(q, norm_page(p), round(r.clicks),
|
|
59
|
+
round(r.impressions), float(r.position), None))
|
|
60
|
+
return table
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Unicode-aware query tokenisation (stdlib only; no stemmer, no external NLP).
|
|
2
|
+
|
|
3
|
+
A token is a maximal run of letters, combining marks (so Bengali vowel signs and the virama
|
|
4
|
+
stay attached to their consonants), digits, and ZWNJ/ZWJ *inside* a word (they carry meaning
|
|
5
|
+
in Bengali conjuncts). Everything else separates tokens. Text is NFKC-normalised and
|
|
6
|
+
case-folded first. The only "stemming" is stripping one trailing ``s`` from ASCII words of
|
|
7
|
+
five or more letters that do not end in ``ss``, ``us`` or ``is`` (shoes -> shoe).
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import unicodedata
|
|
12
|
+
|
|
13
|
+
from . import constants as C
|
|
14
|
+
|
|
15
|
+
_JOINERS = ""
|
|
16
|
+
MAX_QUERY_CHARS = 512
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def tokens(query: str) -> list[str]:
|
|
20
|
+
s = unicodedata.normalize("NFKC", query[:MAX_QUERY_CHARS]).casefold()
|
|
21
|
+
out: list[str] = []
|
|
22
|
+
cur: list[str] = []
|
|
23
|
+
for ch in s:
|
|
24
|
+
cat = unicodedata.category(ch)
|
|
25
|
+
if cat[0] in "LMN" or (ch in _JOINERS and cur):
|
|
26
|
+
cur.append(ch)
|
|
27
|
+
else:
|
|
28
|
+
if cur:
|
|
29
|
+
out.append("".join(cur).rstrip(_JOINERS))
|
|
30
|
+
cur = []
|
|
31
|
+
if cur:
|
|
32
|
+
out.append("".join(cur).rstrip(_JOINERS))
|
|
33
|
+
return [t for t in out if t]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _light(token: str) -> str:
|
|
37
|
+
if (len(token) >= 5 and token.isascii() and token.endswith("s")
|
|
38
|
+
and not token.endswith(("ss", "us", "is"))):
|
|
39
|
+
return token[:-1]
|
|
40
|
+
return token
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def content_tokens(query: str) -> list[str]:
|
|
44
|
+
"""Tokens without stopwords, with the light plural strip applied."""
|
|
45
|
+
return [_light(t) for t in tokens(query) if t not in C.STOPWORDS]
|