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/track/runner.py
ADDED
|
@@ -0,0 +1,586 @@
|
|
|
1
|
+
"""CLI handlers for `omnirank track` (Search Console history) and `omnirank track ai`
|
|
2
|
+
(BYOK AI-answer tracking).
|
|
3
|
+
|
|
4
|
+
Exit codes: 0 done; 1 work left undone (a declined run, the spending ceiling reached, an
|
|
5
|
+
engine stopped after rate limiting or repeated failures); 2 usage error, refusal, missing
|
|
6
|
+
key, authentication failure or API failure. Every message goes through ``redact()``;
|
|
7
|
+
model output is never printed (only numbers derived from it).
|
|
8
|
+
|
|
9
|
+
Spending rules for `track ai` (docs/track.md):
|
|
10
|
+
|
|
11
|
+
1. The cost estimate is ALWAYS printed first. ``--estimate`` stops there (no key needed,
|
|
12
|
+
nothing sent, nothing written).
|
|
13
|
+
2. A run whose estimate exceeds ``--max-cost`` is refused before any question.
|
|
14
|
+
3. Then ``[y/N]`` (``--yes`` skips it); on a non-terminal stdin without ``--yes`` the run
|
|
15
|
+
is REFUSED. Every decision is appended to ``.omnirank/connect-log.jsonl`` and
|
|
16
|
+
``approved`` is written BEFORE the first paid call, so an unwritable log blocks spending.
|
|
17
|
+
4. Each generation call is sent once (no retries). Before every call the running cost
|
|
18
|
+
(actual usage where the API reports it, else the estimate) plus that call's estimate must
|
|
19
|
+
stay within ``--max-cost``; otherwise the batch stops. The first 401/403 stops the
|
|
20
|
+
whole batch; a 429 stops that engine; three failures in a row stop that engine.
|
|
21
|
+
5. Every finished call is saved at once under ``.omnirank/ai-runs/<run-id>/`` so an
|
|
22
|
+
interrupted batch can be continued with ``--resume <run-id>``.
|
|
23
|
+
"""
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import argparse
|
|
27
|
+
import json
|
|
28
|
+
import math
|
|
29
|
+
import re
|
|
30
|
+
import secrets as pysecrets
|
|
31
|
+
import sys
|
|
32
|
+
from datetime import UTC, datetime
|
|
33
|
+
from pathlib import Path
|
|
34
|
+
|
|
35
|
+
from .. import clock
|
|
36
|
+
from ..config import ConfigError, load_config
|
|
37
|
+
from ..connect import google_auth
|
|
38
|
+
from ..connect.confirm import ActionLog, ConfirmError
|
|
39
|
+
from ..connect.constants import GOOGLE_API_HOSTS, SCOPE_GSC_READONLY
|
|
40
|
+
from ..connect.gsc import GscClient, GscError, validate_property
|
|
41
|
+
from ..connect.http import ApiClient, ApiError
|
|
42
|
+
from ..connect.secrets import redact
|
|
43
|
+
from . import ai_prompts, analysis, cost, engines, estimate_view, history, stats, storage
|
|
44
|
+
from . import constants as C
|
|
45
|
+
|
|
46
|
+
MIN_RUNS = 5
|
|
47
|
+
MAX_RUNS = 50
|
|
48
|
+
MAX_CALLS = 2000
|
|
49
|
+
MAX_CONSECUTIVE_FAILURES = 3
|
|
50
|
+
RUNS_SUBDIR = "ai-runs"
|
|
51
|
+
RUN_SCHEMA = "omnirank.track.ai-run"
|
|
52
|
+
RESULT_SCHEMA = "omnirank.track.ai-result"
|
|
53
|
+
_RUN_ID = re.compile(r"\d{4}-\d{2}-\d{2}-[0-9a-f]{8}")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class UsageError(Exception):
|
|
57
|
+
pass
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _err(message: object) -> None:
|
|
61
|
+
print(f"omnirank: {analysis.printable(redact(message), limit=4000)}", file=sys.stderr)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _now() -> str:
|
|
65
|
+
return datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _config(root: Path, path: str | None) -> dict | None:
|
|
69
|
+
p = Path(path) if path else root / "omnirank.config.json"
|
|
70
|
+
if not p.exists():
|
|
71
|
+
if path:
|
|
72
|
+
raise UsageError(f"--config {path} does not exist")
|
|
73
|
+
return None
|
|
74
|
+
try:
|
|
75
|
+
return load_config(p).raw
|
|
76
|
+
except ConfigError as exc:
|
|
77
|
+
raise UsageError(str(exc)) from None
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
# --- search side --------------------------------------------------------------------------------
|
|
81
|
+
|
|
82
|
+
def run_search(args, root: Path) -> int:
|
|
83
|
+
days = history.parse_since(args.since)
|
|
84
|
+
raw = _config(root, args.config) or {}
|
|
85
|
+
site = args.site or (raw.get("indexing") or {}).get("gscProperty")
|
|
86
|
+
if not site:
|
|
87
|
+
raise UsageError("no Search Console property: pass --site https://example.com/ (or "
|
|
88
|
+
"sc-domain:example.com) or set indexing.gscProperty in the config")
|
|
89
|
+
validate_property(site)
|
|
90
|
+
if not 1 <= args.top <= 100:
|
|
91
|
+
raise UsageError("--top must be 1..100")
|
|
92
|
+
start, end = history.window(days, args.end)
|
|
93
|
+
source = google_auth.resolve_token_source([SCOPE_GSC_READONLY], project_root=root)
|
|
94
|
+
client = GscClient(ApiClient(source.token, allowed_hosts=GOOGLE_API_HOSTS))
|
|
95
|
+
snap = history.pull(client, site, start, end)
|
|
96
|
+
prev, notes = history.previous(root, snap)
|
|
97
|
+
delta = history.compare(prev, snap, top=args.top) if prev else None
|
|
98
|
+
path = history.save(root, snap)
|
|
99
|
+
if args.json:
|
|
100
|
+
print(json.dumps({"snapshot_path": str(path), "snapshot": snap,
|
|
101
|
+
"previous": None if prev is None else
|
|
102
|
+
{"start": prev["start"], "end": prev["end"]},
|
|
103
|
+
"delta": delta, "notes": notes}, indent=2, ensure_ascii=False))
|
|
104
|
+
return 0
|
|
105
|
+
print(history.format_report(snap, prev, delta))
|
|
106
|
+
for n in notes:
|
|
107
|
+
print(f" note: {analysis.printable(n)}")
|
|
108
|
+
print(f" saved {path}")
|
|
109
|
+
return 0
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
# --- ai: helpers ------------------------------------------------------------------------------------
|
|
113
|
+
|
|
114
|
+
def _engines(text: str | None, *, estimate: bool) -> list[str]:
|
|
115
|
+
if text is None:
|
|
116
|
+
if estimate:
|
|
117
|
+
return list(C.ENGINES)
|
|
118
|
+
present = [e for e in C.ENGINES if (engines.key_from_env(e) or "")]
|
|
119
|
+
if not present:
|
|
120
|
+
raise UsageError("no API key found; set at least one of "
|
|
121
|
+
+ ", ".join(C.ENV_KEYS.values())
|
|
122
|
+
+ " (or use --estimate, which needs no key)")
|
|
123
|
+
return present
|
|
124
|
+
out: list[str] = []
|
|
125
|
+
for part in text.split(","):
|
|
126
|
+
name = C.ENGINE_ALIASES.get(part.strip().lower(), part.strip().lower())
|
|
127
|
+
if name not in C.ENGINES:
|
|
128
|
+
raise UsageError(f"unknown engine {part.strip()[:40]!r}; use "
|
|
129
|
+
f"{', '.join(C.ENGINES)}")
|
|
130
|
+
if name not in out:
|
|
131
|
+
out.append(name)
|
|
132
|
+
if not out:
|
|
133
|
+
raise UsageError("--engines is empty")
|
|
134
|
+
return out
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _runs(args) -> int:
|
|
138
|
+
n = args.runs
|
|
139
|
+
if not 1 <= n <= MAX_RUNS:
|
|
140
|
+
raise UsageError(f"--runs must be 1..{MAX_RUNS}")
|
|
141
|
+
if n < MIN_RUNS:
|
|
142
|
+
if not args.allow_few_runs:
|
|
143
|
+
raise UsageError(f"at least {MIN_RUNS} runs per prompt per engine are needed to "
|
|
144
|
+
"see run-to-run variance; pass --allow-few-runs to use fewer")
|
|
145
|
+
print(f"omnirank: WARNING: only {n} run(s) per prompt per engine: the run-to-run "
|
|
146
|
+
"variance estimates are unreliable below 5 runs.", file=sys.stderr)
|
|
147
|
+
return n
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _max_output(n: int) -> int:
|
|
151
|
+
if not 64 <= n <= 4096:
|
|
152
|
+
raise UsageError("--max-output-tokens must be 64..4096")
|
|
153
|
+
return n
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _run_dir(root: Path, run_id: str, *, create: bool) -> Path:
|
|
157
|
+
if not isinstance(run_id, str) or not _RUN_ID.fullmatch(run_id):
|
|
158
|
+
raise UsageError("a run id looks like 2026-11-29-0a1b2c3d")
|
|
159
|
+
base = storage.state_subdir(root, RUNS_SUBDIR, create=create)
|
|
160
|
+
d = base / run_id
|
|
161
|
+
if d.is_symlink():
|
|
162
|
+
raise UsageError(f"{d} is a symlink; refusing to use it")
|
|
163
|
+
if create and not d.exists():
|
|
164
|
+
d.mkdir(mode=0o700)
|
|
165
|
+
if not d.is_dir():
|
|
166
|
+
raise UsageError(f"no run {run_id} in {base}")
|
|
167
|
+
if not d.resolve().is_relative_to(root.resolve()):
|
|
168
|
+
raise UsageError(f"{d} resolves outside the project root")
|
|
169
|
+
return d
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
_PID = re.compile(r"[a-z0-9][a-z0-9-]{0,63}")
|
|
173
|
+
_SENTIMENTS = frozenset({"positive", "negative", "mixed", "neutral", "not mentioned"})
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _int(v: object) -> bool:
|
|
177
|
+
return isinstance(v, int) and not isinstance(v, bool)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _usd_ok(v: object) -> bool:
|
|
181
|
+
return isinstance(v, int | float) and not isinstance(v, bool) and math.isfinite(v) \
|
|
182
|
+
and 0 <= v <= C.MAX_COST_HARD_LIMIT_USD
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _valid_record(rec: object, run_id: str) -> bool:
|
|
186
|
+
"""A saved result is used (report, resume, spend total) only if every field the code
|
|
187
|
+
reads has the expected type; anything else is ignored and counted."""
|
|
188
|
+
if not (isinstance(rec, dict) and rec.get("schema") == RESULT_SCHEMA
|
|
189
|
+
and rec.get("run_id") == run_id and rec.get("engine") in C.ENGINES
|
|
190
|
+
and isinstance(rec.get("prompt_id"), str) and _PID.fullmatch(rec["prompt_id"])
|
|
191
|
+
and _int(rec.get("run")) and 0 <= rec["run"] < MAX_RUNS
|
|
192
|
+
and rec.get("status") in ("ok", "error") and _usd_ok(rec.get("cost_usd"))):
|
|
193
|
+
return False
|
|
194
|
+
cited = rec.get("cited_domains")
|
|
195
|
+
if cited is not None and not (isinstance(cited, list)
|
|
196
|
+
and all(isinstance(x, str) for x in cited)):
|
|
197
|
+
return False
|
|
198
|
+
a = rec.get("analysis")
|
|
199
|
+
if not isinstance(a, dict) or not isinstance(a.get("mentioned"), bool):
|
|
200
|
+
return False
|
|
201
|
+
if rec["status"] == "ok":
|
|
202
|
+
rank = a.get("first_mention_rank")
|
|
203
|
+
co = a.get("co_mentions")
|
|
204
|
+
if not ((rank is None or (_int(rank) and rank >= 1))
|
|
205
|
+
and isinstance(co, list) and all(isinstance(x, str) for x in co)
|
|
206
|
+
and a.get("sentiment") in _SENTIMENTS):
|
|
207
|
+
return False
|
|
208
|
+
return True
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _load_run(root: Path, run_id: str) -> tuple[Path, dict, list[dict], int]:
|
|
212
|
+
d = _run_dir(root, run_id, create=False)
|
|
213
|
+
manifest = storage.read_json(d / "manifest.json")
|
|
214
|
+
if not isinstance(manifest, dict) or manifest.get("schema") != RUN_SCHEMA:
|
|
215
|
+
raise UsageError(f"{d}/manifest.json is not an OmniRank AI-run manifest")
|
|
216
|
+
results, invalid = [], 0
|
|
217
|
+
for p in sorted(d.iterdir())[:MAX_CALLS * 10]:
|
|
218
|
+
if p.name == "manifest.json" or p.name.startswith(".") or p.suffix != ".json":
|
|
219
|
+
continue
|
|
220
|
+
try:
|
|
221
|
+
rec = storage.read_json(p, max_bytes=20_000_000)
|
|
222
|
+
except storage.StorageError:
|
|
223
|
+
invalid += 1
|
|
224
|
+
continue
|
|
225
|
+
if _valid_record(rec, run_id):
|
|
226
|
+
results.append(rec)
|
|
227
|
+
else:
|
|
228
|
+
invalid += 1
|
|
229
|
+
return d, manifest, results, invalid
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _manifest(m: dict, run_id: str, track_cfg: dict | None) -> tuple:
|
|
233
|
+
"""Every manifest field validated with the same rules as fresh input. Any failure
|
|
234
|
+
refuses the run before anything is estimated or sent."""
|
|
235
|
+
try:
|
|
236
|
+
if m.get("version") != 1 or isinstance(m.get("version"), bool) \
|
|
237
|
+
or m.get("run_id") != run_id:
|
|
238
|
+
raise UsageError("wrong version or run id")
|
|
239
|
+
prompts = ai_prompts.parse_prompts({"version": 1, "prompts": m.get("prompts")})
|
|
240
|
+
brand = ai_prompts.brand_from_record(m.get("brand"))
|
|
241
|
+
engine_models = m.get("engines")
|
|
242
|
+
if not isinstance(engine_models, dict) or not engine_models:
|
|
243
|
+
raise UsageError("no engines")
|
|
244
|
+
prices = {}
|
|
245
|
+
for e, model in engine_models.items():
|
|
246
|
+
if e not in C.ENGINES:
|
|
247
|
+
raise UsageError(f"unknown engine {str(e)[:40]!r}")
|
|
248
|
+
price = cost.resolve_price(e, model if isinstance(model, str) else "", track_cfg)
|
|
249
|
+
if price.model != model:
|
|
250
|
+
raise UsageError(f"{e}: the configured price is for {price.model!r}, not "
|
|
251
|
+
f"the saved model {str(model)[:80]!r}")
|
|
252
|
+
prices[e] = price
|
|
253
|
+
runs = m.get("runs")
|
|
254
|
+
if not _int(runs) or not 1 <= runs <= MAX_RUNS:
|
|
255
|
+
raise UsageError(f"runs must be 1..{MAX_RUNS}")
|
|
256
|
+
max_output = m.get("max_output_tokens")
|
|
257
|
+
if not _int(max_output):
|
|
258
|
+
raise UsageError("max_output_tokens must be an integer")
|
|
259
|
+
max_output = _max_output(max_output)
|
|
260
|
+
except (UsageError, ai_prompts.PromptError, cost.CostError) as exc:
|
|
261
|
+
raise UsageError(f"the saved run manifest is not usable ({exc}); nothing was "
|
|
262
|
+
"sent") from None
|
|
263
|
+
return prompts, brand, prices, list(prices), runs, max_output
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def _report(summary: dict, brand, *, as_json: bool, extra: dict | None = None) -> None:
|
|
267
|
+
if as_json:
|
|
268
|
+
print(json.dumps({**(extra or {}), "summary": summary,
|
|
269
|
+
"disclaimer": stats.DISCLAIMER,
|
|
270
|
+
"sentiment_method": analysis.SENTIMENT_METHOD},
|
|
271
|
+
indent=2, ensure_ascii=False))
|
|
272
|
+
else:
|
|
273
|
+
print(stats.format_summary(summary, brand))
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
# --- ai: run ----------------------------------------------------------------------------------------
|
|
277
|
+
|
|
278
|
+
def run_ai(args, root: Path) -> int:
|
|
279
|
+
if args.report:
|
|
280
|
+
_, manifest, results, invalid = _load_run(root, args.report)
|
|
281
|
+
try:
|
|
282
|
+
brand = ai_prompts.brand_from_record(manifest.get("brand"))
|
|
283
|
+
except ai_prompts.PromptError as exc:
|
|
284
|
+
raise UsageError(f"the saved run manifest is not usable ({exc})") from None
|
|
285
|
+
_report(stats.summarize(results, brand), brand, as_json=args.json,
|
|
286
|
+
extra={"run_id": args.report, "invalid_results": invalid})
|
|
287
|
+
if invalid and not args.json:
|
|
288
|
+
print(f"\n {invalid} saved result file(s) were not valid and were ignored.")
|
|
289
|
+
return 0
|
|
290
|
+
max_cost = cost.parse_max_cost(args.max_cost)
|
|
291
|
+
max_output = _max_output(args.max_output_tokens)
|
|
292
|
+
budget = estimate_view.parse_budget(args.budget) if args.budget is not None else None
|
|
293
|
+
if budget is not None:
|
|
294
|
+
args.estimate = True # a budget what-if never sends or saves anything
|
|
295
|
+
raw = _config(root, args.config)
|
|
296
|
+
track_cfg = (raw or {}).get("track")
|
|
297
|
+
done: set[tuple[str, str, int]] = set()
|
|
298
|
+
if args.resume:
|
|
299
|
+
if args.prompts or args.engines:
|
|
300
|
+
raise UsageError("--resume continues a saved run with its own prompts and "
|
|
301
|
+
"engines; do not pass --prompts or --engines with it")
|
|
302
|
+
run_dir, manifest, previous, _invalid = _load_run(root, args.resume)
|
|
303
|
+
run_id = args.resume
|
|
304
|
+
prompts, brand, prices, names, runs, max_output = _manifest(manifest, run_id,
|
|
305
|
+
track_cfg)
|
|
306
|
+
done = {(r["engine"], r["prompt_id"], r["run"]) for r in previous
|
|
307
|
+
if r["status"] == "ok"}
|
|
308
|
+
spent_before = math.fsum(r["cost_usd"] for r in previous)
|
|
309
|
+
else:
|
|
310
|
+
if not args.prompts:
|
|
311
|
+
raise UsageError("--prompts FILE is required (or --report / --resume RUN_ID)")
|
|
312
|
+
prompts = ai_prompts.load_prompts(args.prompts)
|
|
313
|
+
brand = ai_prompts.brand_from_config(raw, brand=args.brand, competitors=args.competitor)
|
|
314
|
+
names = _engines(args.engines, estimate=args.estimate)
|
|
315
|
+
runs = _runs(args)
|
|
316
|
+
prices = {e: cost.resolve_price(e, None, track_cfg) for e in names}
|
|
317
|
+
run_id = run_dir = None
|
|
318
|
+
spent_before = 0.0
|
|
319
|
+
est = cost.estimate_batch(prompts, prices, runs=runs, max_output=max_output, done=done)
|
|
320
|
+
info = sys.stderr if args.json else sys.stdout # keep stdout pure JSON with --json
|
|
321
|
+
if args.json and args.estimate:
|
|
322
|
+
extra = {"estimate_details": {
|
|
323
|
+
"tokens": estimate_view.engine_tokens(prompts, prices, runs=runs,
|
|
324
|
+
max_output=max_output, done=done),
|
|
325
|
+
"confidence": estimate_view.confidence(est),
|
|
326
|
+
"assumptions": estimate_view.assumptions(prices, max_output=max_output)}}
|
|
327
|
+
if budget is not None:
|
|
328
|
+
extra["budget_what_if"] = estimate_view.what_if(prompts, prices, budget,
|
|
329
|
+
max_output=max_output)
|
|
330
|
+
print(json.dumps({"estimate": est, "max_cost_usd": max_cost,
|
|
331
|
+
"pricing_warning": C.PRICING_WARNING, **extra},
|
|
332
|
+
indent=2, ensure_ascii=False))
|
|
333
|
+
return 0
|
|
334
|
+
print(cost.format_estimate(est), file=info)
|
|
335
|
+
print(estimate_view.format_details(prompts, prices, est, runs=runs, max_output=max_output,
|
|
336
|
+
done=done), file=info)
|
|
337
|
+
if budget is not None:
|
|
338
|
+
print("\n" + estimate_view.format_what_if(
|
|
339
|
+
estimate_view.what_if(prompts, prices, budget, max_output=max_output)), file=info)
|
|
340
|
+
if args.estimate:
|
|
341
|
+
print("Estimate only: nothing was sent and nothing was saved.", file=info)
|
|
342
|
+
return 0
|
|
343
|
+
if est["calls"] == 0:
|
|
344
|
+
print("Nothing left to run.", file=info)
|
|
345
|
+
return 0
|
|
346
|
+
if est["calls"] > MAX_CALLS:
|
|
347
|
+
raise UsageError(f"{est['calls']} calls is more than the {MAX_CALLS} allowed in one "
|
|
348
|
+
"batch; use fewer prompts, runs or engines")
|
|
349
|
+
keys = {}
|
|
350
|
+
missing = []
|
|
351
|
+
for e in names:
|
|
352
|
+
k = engines.key_from_env(e)
|
|
353
|
+
if not k:
|
|
354
|
+
missing.append(C.ENV_KEYS[e])
|
|
355
|
+
keys[e] = k
|
|
356
|
+
if missing:
|
|
357
|
+
raise UsageError(f"missing API key(s): {', '.join(missing)} (keys are read from the "
|
|
358
|
+
"environment only)")
|
|
359
|
+
if spent_before:
|
|
360
|
+
print(f"This run has already spent ~${spent_before:.4f} (from the saved cost_usd of "
|
|
361
|
+
"its results); --max-cost applies to the whole run.", file=info)
|
|
362
|
+
if spent_before + est["total_usd"] > max_cost:
|
|
363
|
+
raise UsageError(f"already spent ~${spent_before:.4f} plus the estimate "
|
|
364
|
+
f"~${est['total_usd']:.4f} is above --max-cost ${max_cost:.2f}; "
|
|
365
|
+
"raise --max-cost or run fewer prompts/runs/engines")
|
|
366
|
+
log = ActionLog(root)
|
|
367
|
+
run_id = run_id or f"{clock.today().isoformat()}-{pysecrets.token_hex(4)}"
|
|
368
|
+
summary_line = (f"track ai run {run_id}: {est['calls']} paid call(s) to "
|
|
369
|
+
f"{', '.join(names)}; estimate ${est['total_usd']:.4f}; "
|
|
370
|
+
f"ceiling ${max_cost:.2f}")
|
|
371
|
+
|
|
372
|
+
def entry(outcome: str, **extra) -> dict:
|
|
373
|
+
return {"ts": _now(), "connector": "track-ai", "action": "run", "method": "POST",
|
|
374
|
+
"url": ", ".join(engines.endpoint(e, prices[e].model) for e in names),
|
|
375
|
+
"summary": summary_line, "body": None, "outcome": outcome, **extra}
|
|
376
|
+
|
|
377
|
+
print(f"\nAbout to send {est['calls']} paid API call(s) ({', '.join(names)}), estimated "
|
|
378
|
+
f"~${est['total_usd']:.4f}. The ${max_cost:.2f} ceiling is checked before each call "
|
|
379
|
+
"(spent so far plus that call's estimate); a single call can cost more than its "
|
|
380
|
+
"estimate, so the total can pass the ceiling once before the batch stops.", file=info)
|
|
381
|
+
for e in names:
|
|
382
|
+
print(f" {C.ENGINE_LABELS[e]}: POST {engines.endpoint(e, prices[e].model)} "
|
|
383
|
+
f"(model {prices[e].model}, key from ${C.ENV_KEYS[e]}, web search/grounding on, "
|
|
384
|
+
f"no retries)", file=info)
|
|
385
|
+
print(f" Results and redacted raw responses will be saved in "
|
|
386
|
+
f"{root / '.omnirank' / RUNS_SUBDIR}/<run-id>/.", file=info)
|
|
387
|
+
if not args.yes:
|
|
388
|
+
if not sys.stdin.isatty():
|
|
389
|
+
log.append(entry("refused", reason="stdin is not a terminal and --yes was not given"))
|
|
390
|
+
_err("refusing to spend: stdin is not a terminal, so there is no one to confirm. "
|
|
391
|
+
"Re-run interactively, or pass --yes to confirm in advance.")
|
|
392
|
+
return 2
|
|
393
|
+
print("Spend this? [y/N] ", end="", flush=True, file=info)
|
|
394
|
+
if sys.stdin.readline().strip().lower() not in ("y", "yes"):
|
|
395
|
+
log.append(entry("declined"))
|
|
396
|
+
print("Nothing was sent.", file=info)
|
|
397
|
+
return 1
|
|
398
|
+
log.append(entry("approved"))
|
|
399
|
+
if run_dir is None:
|
|
400
|
+
run_dir = _run_dir(root, run_id, create=True)
|
|
401
|
+
storage.write_json(run_dir, "manifest.json", {
|
|
402
|
+
"schema": RUN_SCHEMA, "version": 1, "run_id": run_id,
|
|
403
|
+
"createdOn": clock.today().isoformat(),
|
|
404
|
+
"brand": {"name": brand.name, "aliases": list(brand.aliases),
|
|
405
|
+
"domains": list(brand.domains), "competitors": list(brand.competitors)},
|
|
406
|
+
"prompts": [{"id": p.id, "category": p.category, "text": p.text} for p in prompts],
|
|
407
|
+
"engines": {e: prices[e].model for e in names}, "runs": runs,
|
|
408
|
+
"max_output_tokens": max_output, "estimate": est})
|
|
409
|
+
outcome = _execute(run_dir, run_id, prompts, names, prices, keys, runs, max_output,
|
|
410
|
+
max_cost, done, brand, spent_before)
|
|
411
|
+
log.append(entry("finished", spent_usd=round(outcome["spent"], 6), calls=outcome["calls"],
|
|
412
|
+
stopped=outcome["stopped"]))
|
|
413
|
+
_, _, results, _ = _load_run(root, run_id)
|
|
414
|
+
print(f"\nRun {run_id}: {outcome['calls']} call(s) sent now; the run has spent "
|
|
415
|
+
f"~${outcome['spent']:.4f} in total "
|
|
416
|
+
"(from API usage where reported, else the estimate). Saved in "
|
|
417
|
+
f"{run_dir}.", file=info)
|
|
418
|
+
for msg in outcome["messages"]:
|
|
419
|
+
print(f" {analysis.printable(redact(msg))}", file=info)
|
|
420
|
+
print(file=info)
|
|
421
|
+
_report(stats.summarize(results, brand), brand, as_json=args.json,
|
|
422
|
+
extra={"run_id": run_id, "spent_usd": outcome["spent"], "calls": outcome["calls"]})
|
|
423
|
+
if outcome["auth_abort"]:
|
|
424
|
+
_err(outcome["auth_abort"])
|
|
425
|
+
return 2
|
|
426
|
+
if outcome["stopped"]:
|
|
427
|
+
print(f"Not finished; continue with: omnirank track ai --resume {run_id}", file=info)
|
|
428
|
+
return 1
|
|
429
|
+
return 0
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def _execute(run_dir, run_id, prompts, names, prices, keys, runs, max_output, max_cost,
|
|
433
|
+
done, brand, spent_before: float = 0.0) -> dict:
|
|
434
|
+
clients = {e: engines.make_client(e, keys[e]) for e in names}
|
|
435
|
+
stopped_engines: dict[str, str] = {}
|
|
436
|
+
failures = dict.fromkeys(names, 0)
|
|
437
|
+
spent, calls = spent_before, 0 # only ever increases (every addition is >= 0)
|
|
438
|
+
messages: list[str] = []
|
|
439
|
+
auth_abort = None
|
|
440
|
+
ceiling = False
|
|
441
|
+
for r in range(runs):
|
|
442
|
+
for p in prompts:
|
|
443
|
+
for e in names:
|
|
444
|
+
if ceiling or auth_abort:
|
|
445
|
+
break
|
|
446
|
+
if e in stopped_engines or (e, p.id, r) in done:
|
|
447
|
+
continue
|
|
448
|
+
price = prices[e]
|
|
449
|
+
est = cost.estimate_call(e, price, p.text, max_output)
|
|
450
|
+
if spent + est > max_cost:
|
|
451
|
+
ceiling = True
|
|
452
|
+
messages.append(f"stopped at the spending ceiling: ${spent:.4f} spent, the "
|
|
453
|
+
f"next call is estimated at ${est:.4f} and --max-cost is "
|
|
454
|
+
f"${max_cost:.2f}")
|
|
455
|
+
break
|
|
456
|
+
calls += 1
|
|
457
|
+
rec = {"schema": RESULT_SCHEMA, "version": 1, "run_id": run_id, "engine": e,
|
|
458
|
+
"model": price.model, "prompt_id": p.id, "category": p.category,
|
|
459
|
+
"run": r}
|
|
460
|
+
try:
|
|
461
|
+
data, ans = engines.ask(e, clients[e], price.model, p.text, max_output)
|
|
462
|
+
except ApiError as exc:
|
|
463
|
+
spent += max(0.0, est) # unknown whether billed: count the estimate
|
|
464
|
+
if engines.is_auth_error(exc):
|
|
465
|
+
auth_abort = (f"stopped: {C.ENGINE_LABELS[e]} rejected the API key "
|
|
466
|
+
f"(HTTP {exc.status}); no further calls were sent. "
|
|
467
|
+
f"{exc}")
|
|
468
|
+
break
|
|
469
|
+
failures[e] += 1
|
|
470
|
+
rec.update(status="error", error=str(exc)[:500], cost_usd=est,
|
|
471
|
+
cost_basis="estimate", analysis={"mentioned": False},
|
|
472
|
+
cited_domains=None)
|
|
473
|
+
storage.write_text(run_dir, f"{e}-{p.id}-r{r:02d}.json",
|
|
474
|
+
storage.storable_json(rec))
|
|
475
|
+
if exc.status == 429:
|
|
476
|
+
stopped_engines[e] = "rate limited (HTTP 429); not retried"
|
|
477
|
+
elif failures[e] >= MAX_CONSECUTIVE_FAILURES:
|
|
478
|
+
stopped_engines[e] = f"{failures[e]} failures in a row"
|
|
479
|
+
continue
|
|
480
|
+
failures[e] = 0
|
|
481
|
+
usd, basis = cost.actual_cost(price, ans.usage, fallback=est)
|
|
482
|
+
spent += max(0.0, usd)
|
|
483
|
+
status = "ok" if ans.text.strip() else "error"
|
|
484
|
+
rec.update(status=status, text=ans.text,
|
|
485
|
+
text_redacted=redact(ans.text) != ans.text,
|
|
486
|
+
cited_domains=ans.cited_domains, usage=ans.usage, cost_usd=usd,
|
|
487
|
+
cost_basis=basis,
|
|
488
|
+
analysis=analysis.analyze_text(ans.text, brand) if status == "ok"
|
|
489
|
+
else {"mentioned": False},
|
|
490
|
+
response=data)
|
|
491
|
+
if status != "ok":
|
|
492
|
+
rec["error"] = "the response had no answer text"
|
|
493
|
+
storage.write_text(run_dir, f"{e}-{p.id}-r{r:02d}.json",
|
|
494
|
+
storage.storable_json(rec))
|
|
495
|
+
if spent > max_cost:
|
|
496
|
+
ceiling = True
|
|
497
|
+
messages.append(f"stopped: the spending ceiling ${max_cost:.2f} was "
|
|
498
|
+
f"passed (${spent:.4f} spent; the last call cost more than "
|
|
499
|
+
"estimated)")
|
|
500
|
+
if ceiling or auth_abort:
|
|
501
|
+
break
|
|
502
|
+
if ceiling or auth_abort:
|
|
503
|
+
break
|
|
504
|
+
for e, why in stopped_engines.items():
|
|
505
|
+
messages.append(f"{C.ENGINE_LABELS[e]} stopped: {why}")
|
|
506
|
+
return {"spent": spent, "calls": calls, "messages": messages, "auth_abort": auth_abort,
|
|
507
|
+
"stopped": bool(ceiling or auth_abort or stopped_engines)}
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
# --- dispatch ---------------------------------------------------------------------------------------
|
|
511
|
+
|
|
512
|
+
def run_track(args: argparse.Namespace) -> int:
|
|
513
|
+
root = Path(args.root or ".")
|
|
514
|
+
try:
|
|
515
|
+
if not root.is_dir():
|
|
516
|
+
raise UsageError(f"--root {root} is not a directory")
|
|
517
|
+
if args.track_command == "ai":
|
|
518
|
+
return run_ai(args, root)
|
|
519
|
+
if args.track_command == "discover":
|
|
520
|
+
from .discover_cli import run_discover
|
|
521
|
+
return run_discover(args, root)
|
|
522
|
+
return run_search(args, root)
|
|
523
|
+
except (UsageError, history.HistoryError, ai_prompts.PromptError, cost.CostError,
|
|
524
|
+
storage.StorageError, GscError, google_auth.AuthError, ApiError,
|
|
525
|
+
ConfirmError, ValueError) as exc:
|
|
526
|
+
_err(exc)
|
|
527
|
+
return 2
|
|
528
|
+
except KeyboardInterrupt:
|
|
529
|
+
_err("interrupted; finished calls are saved (use --resume RUN_ID to continue)")
|
|
530
|
+
return 130
|
|
531
|
+
except Exception as exc: # noqa: BLE001 - never let a traceback carry a secret out
|
|
532
|
+
_err(f"unexpected error ({type(exc).__name__}): {exc}")
|
|
533
|
+
return 2
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
def add_parsers(sub) -> None:
|
|
537
|
+
track = sub.add_parser(
|
|
538
|
+
"track", help="Track Search Console history (deltas between runs) and, with your own "
|
|
539
|
+
"API keys, how AI answer engines mention your brand (`track ai`)")
|
|
540
|
+
track.add_argument("--since", default="7d", metavar="Nd",
|
|
541
|
+
help="Window length ending a few days before today (default 7d)")
|
|
542
|
+
track.add_argument("--site", help="Search Console property (default: "
|
|
543
|
+
"indexing.gscProperty in the config)")
|
|
544
|
+
track.add_argument("--end", metavar="YYYY-MM-DD", help="Last day of the window")
|
|
545
|
+
track.add_argument("--top", type=int, default=10, help="Movers to list (1..100)")
|
|
546
|
+
track.add_argument("--root", default=".", help="Project root (snapshots go in "
|
|
547
|
+
"<root>/.omnirank/history/)")
|
|
548
|
+
track.add_argument("--config", help="Config file (default <root>/omnirank.config.json)")
|
|
549
|
+
track.add_argument("--json", action="store_true", help="Emit JSON")
|
|
550
|
+
tsub = track.add_subparsers(dest="track_command")
|
|
551
|
+
ai = tsub.add_parser(
|
|
552
|
+
"ai", help="Sample AI answers for a prompt set (BYOK; prints a cost estimate and asks "
|
|
553
|
+
"before spending anything)")
|
|
554
|
+
ai.add_argument("--prompts", metavar="FILE", help="Prompt set JSON (see docs/track.md)")
|
|
555
|
+
ai.add_argument("--runs", type=int, default=MIN_RUNS,
|
|
556
|
+
help=f"Runs per prompt per engine (default and minimum {MIN_RUNS})")
|
|
557
|
+
ai.add_argument("--allow-few-runs", action="store_true",
|
|
558
|
+
help=f"Allow fewer than {MIN_RUNS} runs (variance becomes unreliable)")
|
|
559
|
+
ai.add_argument("--engines", metavar="LIST",
|
|
560
|
+
help="Comma list of gemini, anthropic (claude), openai, perplexity "
|
|
561
|
+
"(default: every engine whose key is set; --estimate: all four)")
|
|
562
|
+
ai.add_argument("--estimate", action="store_true",
|
|
563
|
+
help="Print the cost estimate only: no key needed, nothing sent or saved")
|
|
564
|
+
ai.add_argument("--max-cost", default=f"{C.DEFAULT_MAX_COST_USD:.2f}", metavar="USD",
|
|
565
|
+
help="Hard spending ceiling for this batch in US dollars (default "
|
|
566
|
+
f"{C.DEFAULT_MAX_COST_USD:.2f})")
|
|
567
|
+
ai.add_argument("--max-output-tokens", type=int, default=C.DEFAULT_MAX_OUTPUT_TOKENS,
|
|
568
|
+
help=f"Answer length cap sent to every engine (default "
|
|
569
|
+
f"{C.DEFAULT_MAX_OUTPUT_TOKENS})")
|
|
570
|
+
ai.add_argument("--budget", metavar="USD",
|
|
571
|
+
help="What-if: print how many runs of the prompt set fit this budget "
|
|
572
|
+
"(implies --estimate: no key needed, nothing sent or saved)")
|
|
573
|
+
ai.add_argument("--yes", action="store_true",
|
|
574
|
+
help="Confirm the spend in advance (the estimate is still printed)")
|
|
575
|
+
ai.add_argument("--brand", help="Brand name (default: site.name in the config)")
|
|
576
|
+
ai.add_argument("--competitor", action="append", metavar="NAME",
|
|
577
|
+
help="Competitor name (repeatable; adds to `competitors` in the config)")
|
|
578
|
+
ai.add_argument("--resume", metavar="RUN_ID", help="Continue a stopped run")
|
|
579
|
+
ai.add_argument("--report", metavar="RUN_ID",
|
|
580
|
+
help="Re-print the report of a saved run (offline, no key, no spend)")
|
|
581
|
+
ai.add_argument("--root", default=".", help="Project root (runs go in "
|
|
582
|
+
"<root>/.omnirank/ai-runs/)")
|
|
583
|
+
ai.add_argument("--config", help="Config file (default <root>/omnirank.config.json)")
|
|
584
|
+
ai.add_argument("--json", action="store_true", help="Emit JSON")
|
|
585
|
+
from .discover_cli import add_parser as add_discover_parser
|
|
586
|
+
add_discover_parser(tsub)
|