geo-visibility-cli 0.2.1__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.
geo_check/history.py ADDED
@@ -0,0 +1,156 @@
1
+ """Run history: one JSON record per run, and deltas against the previous run."""
2
+
3
+ import json
4
+ import re
5
+ import unicodedata
6
+ from datetime import datetime, timezone
7
+ from pathlib import Path
8
+
9
+ CHART_MAX_POINTS = 12
10
+
11
+
12
+ def _now() -> datetime:
13
+ return datetime.now(timezone.utc)
14
+
15
+
16
+ def _norm(text: str) -> str:
17
+ t = unicodedata.normalize("NFKD", str(text))
18
+ t = "".join(c for c in t if not unicodedata.combining(c))
19
+ return re.sub(r"\s+", " ", t.casefold()).strip()
20
+
21
+
22
+ def _key(brand: str, category: str, city: str) -> tuple[str, str, str]:
23
+ return (_norm(brand), _norm(category), _norm(city))
24
+
25
+
26
+ def _slug(text: str) -> str:
27
+ return re.sub(r"[^a-z0-9]+", "-", _norm(text)).strip("-") or "x"
28
+
29
+
30
+ def make_record(result: dict, when: datetime) -> dict:
31
+ return {
32
+ "timestamp": when.strftime("%Y-%m-%dT%H:%M:%S.%fZ"),
33
+ "tool": result.get("tool"),
34
+ "brand": result["brand"],
35
+ "category": result["category"],
36
+ "city": result["city"],
37
+ "lang": result.get("lang"),
38
+ "engine": result.get("engine"),
39
+ "dry_run": result.get("dry_run", False),
40
+ "mention_rate": result["summary"]["mention_rate"],
41
+ "cited_domains": result.get("cited_domains", []),
42
+ "competitor_candidates": result.get("competitor_candidates", []),
43
+ }
44
+
45
+
46
+ def _valid_list(rec: dict, field: str, name_key: str) -> bool:
47
+ items = rec.get(field)
48
+ if items is None:
49
+ return True
50
+ return isinstance(items, list) and all(
51
+ isinstance(x, dict) and isinstance(x.get(name_key), str) for x in items
52
+ )
53
+
54
+
55
+ def _valid(rec: object) -> bool:
56
+ if not isinstance(rec, dict):
57
+ return False
58
+ rate = rec.get("mention_rate")
59
+ return (
60
+ isinstance(rec.get("timestamp"), str)
61
+ and isinstance(rate, (int, float))
62
+ and not isinstance(rate, bool)
63
+ and all(isinstance(rec.get(k), str) for k in ("brand", "category", "city"))
64
+ and _valid_list(rec, "cited_domains", "domain")
65
+ and _valid_list(rec, "competitor_candidates", "name")
66
+ )
67
+
68
+
69
+ def load_records(
70
+ history_dir: Path, brand: str, category: str, city: str, dry_run: bool = False
71
+ ) -> list[dict]:
72
+ """Records for the same brand/category/city and run kind (dry or real), oldest first.
73
+
74
+ Bad files and malformed records are skipped.
75
+ """
76
+ want = _key(brand, category, city)
77
+ out = []
78
+ if not history_dir.is_dir():
79
+ return out
80
+ for p in history_dir.glob("*.json"):
81
+ try:
82
+ rec = json.loads(p.read_text(encoding="utf-8"))
83
+ except (OSError, ValueError):
84
+ continue
85
+ if (
86
+ _valid(rec)
87
+ and _key(rec["brand"], rec["category"], rec["city"]) == want
88
+ and bool(rec.get("dry_run", False)) == bool(dry_run)
89
+ ):
90
+ out.append(rec)
91
+ out.sort(key=lambda r: r["timestamp"])
92
+ return out
93
+
94
+
95
+ def save_record(history_dir: Path, record: dict) -> Path:
96
+ history_dir.mkdir(parents=True, exist_ok=True)
97
+ ts = re.sub(r"[^0-9TZ]", "", record["timestamp"])
98
+ name = (
99
+ f"{ts}-{_slug(record['brand'])}-{_slug(record['category'])}-{_slug(record['city'])}.json"
100
+ )
101
+ path = history_dir / name
102
+ path.write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding="utf-8")
103
+ return path
104
+
105
+
106
+ def compute_changes(prev: dict, record: dict) -> dict:
107
+ """Deltas of the current record against the previous one."""
108
+
109
+ def names(rec, field, name_key):
110
+ return [x[name_key] for x in rec.get(field) or []]
111
+
112
+ def diff(field, name_key):
113
+ before, after = names(prev, field, name_key), names(record, field, name_key)
114
+ return (
115
+ [n for n in after if n not in before],
116
+ [n for n in before if n not in after],
117
+ )
118
+
119
+ new_d, lost_d = diff("cited_domains", "domain")
120
+ new_c, lost_c = diff("competitor_candidates", "name")
121
+ return {
122
+ "previous_timestamp": prev["timestamp"],
123
+ "previous_mention_rate": prev["mention_rate"],
124
+ "mention_rate_delta_points": round(
125
+ (record["mention_rate"] - prev["mention_rate"]) * 100, 1
126
+ ),
127
+ "new_cited_domains": new_d,
128
+ "lost_cited_domains": lost_d,
129
+ "new_competitors": new_c,
130
+ "lost_competitors": lost_c,
131
+ }
132
+
133
+
134
+ def prepare_run(result: dict, history_dir: Path) -> dict:
135
+ """Annotate `result` with `changes` and `history`; return the record to save later.
136
+
137
+ Nothing is written here: call `save_record` once the reports are on disk.
138
+ """
139
+ prior = load_records(
140
+ history_dir,
141
+ result["brand"],
142
+ result["category"],
143
+ result["city"],
144
+ bool(result.get("dry_run", False)),
145
+ )
146
+ record = make_record(result, _now())
147
+ result["changes"] = compute_changes(prior[-1], record) if prior else None
148
+ series = [{"timestamp": r["timestamp"], "mention_rate": r["mention_rate"]} for r in prior]
149
+ series.append({"timestamp": record["timestamp"], "mention_rate": record["mention_rate"]})
150
+ result["history"] = series
151
+ return record
152
+
153
+
154
+ def record_run(result: dict, history_dir: Path) -> None:
155
+ """Annotate `result` and append this run to the dir in one step."""
156
+ save_record(history_dir, prepare_run(result, history_dir))
@@ -0,0 +1,177 @@
1
+ """Self-contained HTML report (inline CSS, no JavaScript, inline SVG chart)."""
2
+
3
+ import re
4
+ from html import escape
5
+
6
+ from .history import CHART_MAX_POINTS
7
+ from .report import (
8
+ CHECKER_URL, FIVERR_URL, T, _lang, changes_items, changes_rate_line, robots_view,
9
+ takeaways,
10
+ )
11
+
12
+ ACCENT = "#2f5d8a"
13
+
14
+ CSS = f"""
15
+ :root {{ --accent: {ACCENT}; --ink: #222; --muted: #666; --line: #ddd; --bg: #fafafa; }}
16
+ * {{ box-sizing: border-box; }}
17
+ body {{ margin: 0; background: var(--bg); color: var(--ink); line-height: 1.5;
18
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }}
19
+ main {{ max-width: 860px; margin: 0 auto; padding: 32px 20px 48px; background: #fff;
20
+ border-left: 1px solid var(--line); border-right: 1px solid var(--line); }}
21
+ h1 {{ font-size: 1.6rem; margin: 0 0 8px; }}
22
+ h2 {{ font-size: 1.15rem; margin: 32px 0 8px; padding-bottom: 4px;
23
+ border-bottom: 2px solid var(--accent); }}
24
+ ul {{ padding-left: 20px; }}
25
+ li {{ margin: 4px 0; }}
26
+ .meta {{ color: var(--muted); list-style: none; padding: 0; }}
27
+ table {{ border-collapse: collapse; width: 100%; font-size: 0.95rem; }}
28
+ th, td {{ text-align: left; padding: 6px 10px; border-bottom: 1px solid var(--line); }}
29
+ th {{ background: #f0f0f0; font-weight: 600; }}
30
+ .rate {{ font-size: 2rem; font-weight: 700; color: var(--accent); }}
31
+ .note {{ color: var(--muted); font-style: italic; }}
32
+ footer {{ margin-top: 40px; padding: 16px; border: 1px solid var(--line); border-radius: 4px;
33
+ background: var(--bg); }}
34
+ footer a {{ color: var(--accent); }}
35
+ svg text {{ font-family: inherit; }}
36
+ """
37
+
38
+
39
+ def _e(x) -> str:
40
+ return escape(str(x), quote=True)
41
+
42
+
43
+ def _rich(text: str) -> str:
44
+ """Escape, then turn the **bold** markers used in the report strings into <strong>."""
45
+ return re.sub(r"\*\*(.+?)\*\*", r"<strong>\1</strong>", _e(text))
46
+
47
+
48
+ def _table(headers: list[str], rows: list[list]) -> str:
49
+ head = "".join(f"<th>{_e(h)}</th>" for h in headers)
50
+ body = "".join("<tr>" + "".join(f"<td>{_e(c)}</td>" for c in row) + "</tr>" for row in rows)
51
+ return f"<table><thead><tr>{head}</tr></thead><tbody>{body}</tbody></table>"
52
+
53
+
54
+ def _chart(history: list[dict], t: dict) -> str:
55
+ pts = history[-CHART_MAX_POINTS:]
56
+ bar_w, gap, h_plot, top, left = 36, 14, 120, 18, 36
57
+ width = left + len(pts) * (bar_w + gap) + gap
58
+ height = top + h_plot + 34
59
+ parts = [
60
+ f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {width} {height}" '
61
+ f'width="{width}" height="{height}" role="img" aria-label="{_e(t["history_alt"])}">',
62
+ f"<title>{_e(t['history_alt'])}</title>",
63
+ ]
64
+ for pct in (0, 50, 100):
65
+ y = top + h_plot - h_plot * pct / 100
66
+ parts.append(
67
+ f'<line x1="{left}" y1="{y:.1f}" x2="{width}" y2="{y:.1f}" stroke="#ddd"/>'
68
+ f'<text x="{left - 6}" y="{y + 4:.1f}" font-size="10" fill="#666" '
69
+ f'text-anchor="end">{pct}%</text>'
70
+ )
71
+ for i, p in enumerate(pts):
72
+ rate = max(0.0, min(1.0, float(p["mention_rate"])))
73
+ bh = h_plot * rate
74
+ x = left + gap + i * (bar_w + gap)
75
+ y = top + h_plot - bh
76
+ label = _e(str(p["timestamp"])[:10])
77
+ parts.append(
78
+ f'<rect x="{x}" y="{y:.1f}" width="{bar_w}" height="{bh:.1f}" fill="{ACCENT}">'
79
+ f"<title>{label}: {rate * 100:.0f}%</title></rect>"
80
+ f'<text x="{x + bar_w / 2}" y="{y - 4:.1f}" font-size="10" fill="#222" '
81
+ f'text-anchor="middle">{rate * 100:.0f}%</text>'
82
+ f'<text x="{x + bar_w / 2}" y="{top + h_plot + 14}" font-size="9" fill="#666" '
83
+ f'text-anchor="middle">{label[5:]}</text>'
84
+ )
85
+ parts.append("</svg>")
86
+ return "".join(parts)
87
+
88
+
89
+ def render_html(r: dict) -> str:
90
+ lang = _lang(r)
91
+ t = T[lang]
92
+ s = r["summary"]
93
+ b = [f"<h1>{_e(t['title'].format(brand=r['brand']))}</h1>"]
94
+ b.append(
95
+ '<ul class="meta">'
96
+ f"<li>{_e(t['category'])}: {_e(r['category'])}</li>"
97
+ f"<li>{_e(t['city'])}: {_e(r['city'])}</li>"
98
+ f"<li>{_e(t['engine'])}: {_e(r['engine'])}</li>"
99
+ f"<li>{_e(t['runs'])}: {_e(r['runs'])}</li></ul>"
100
+ )
101
+
102
+ b.append(f"<h2>{_e(t['summary'])}</h2>")
103
+ b.append(f'<p class="rate">{s["mention_rate"] * 100:.0f}%</p>')
104
+ b.append(
105
+ "<ul>"
106
+ f"<li>{_e(t['total_answers'])}: {_e(s['total_answers'])}</li>"
107
+ f"<li>{_e(t['answers_with_mention'])}: {_e(s['answers_with_mention'])}</li>"
108
+ f"<li>{_e(t['mention_rate'])}: {s['mention_rate'] * 100:.0f}%</li>"
109
+ f"<li>{_e(t['total_mentions'])}: {_e(s['total_mentions'])}</li></ul>"
110
+ )
111
+
112
+ b.append(f"<h2>{_e(t['meaning'])}</h2>")
113
+ b.append("<ul>" + "".join(f"<li>{_rich(x)}</li>" for x in takeaways(r)) + "</ul>")
114
+
115
+ ch = r.get("changes")
116
+ if ch:
117
+ b.append(f"<h2>{_e(t['changes'])}</h2><ul>")
118
+ b.append(f"<li>{_e(changes_rate_line(ch, s['mention_rate'], t))}</li>")
119
+ b.append(f"<li>{_e(t['ch_prev'].format(when=ch['previous_timestamp']))}</li>")
120
+ for label, items in changes_items(ch, t):
121
+ b.append(f"<li>{_e(label)}: {_e(', '.join(items) if items else t['ch_none'])}</li>")
122
+ b.append("</ul>")
123
+
124
+ hist = r.get("history")
125
+ if hist:
126
+ b.append(f"<h2>{_e(t['history'])}</h2>{_chart(hist, t)}")
127
+
128
+ b.append(f"<h2>{_e(t['questions'])}</h2>")
129
+ b.append(
130
+ _table(
131
+ t["q_cols"],
132
+ [[i["question"], i["mentions"], f"{i['answers_with_mention']}/{r['runs']}"]
133
+ for i in r["questions"]],
134
+ )
135
+ )
136
+
137
+ b.append(f"<h2>{_e(t['cited'])}</h2>")
138
+ if r["cited_domains"]:
139
+ b.append(_table(t["d_cols"], [[x["domain"], x["count"]] for x in r["cited_domains"]]))
140
+ else:
141
+ b.append(f'<p class="note">{_e(t["no_citations"])}</p>')
142
+
143
+ b.append(f"<h2>{_e(t['competitors'])}</h2>")
144
+ if r["competitor_candidates"]:
145
+ b.append(
146
+ _table(t["c_cols"], [[x["name"], x["count"]] for x in r["competitor_candidates"]])
147
+ )
148
+ else:
149
+ b.append(f'<p class="note">{_e(t["none_detected"])}</p>')
150
+
151
+ if r.get("robots") is not None:
152
+ v = robots_view(r, t)
153
+ b.append(f"<h2>{_e(v['title'])}</h2>")
154
+ if v["note"]:
155
+ b.append(f"<p>{_e(v['note'])}</p>")
156
+ else:
157
+ if v["simulated"]:
158
+ b.append(f'<p class="note">{_e(t["simulated"].strip("_"))}</p>')
159
+ b.append(_table(t["r_cols"], [list(row) for row in v["rows"]]))
160
+
161
+ b.append(
162
+ "<footer>"
163
+ f'<p>{_rich(t["cta_lead"])}</p>'
164
+ f'<p>{_e(t["footer_full"])}: <a href="{_e(FIVERR_URL)}">{_e(FIVERR_URL)}</a></p>'
165
+ f'<p>{_e(t["footer_free"])}: <a href="{_e(CHECKER_URL)}">{_e(CHECKER_URL)}</a></p>'
166
+ "</footer>"
167
+ )
168
+
169
+ return (
170
+ "<!DOCTYPE html>\n"
171
+ f'<html lang="{lang}"><head><meta charset="utf-8">'
172
+ '<meta name="viewport" content="width=device-width, initial-scale=1">'
173
+ f"<title>{_e(t['title'].format(brand=r['brand']))}</title>"
174
+ f"<style>{CSS}</style></head><body><main>"
175
+ + "\n".join(b)
176
+ + "</main></body></html>\n"
177
+ )
@@ -0,0 +1,84 @@
1
+ """Perplexity Agent API client (stdlib only)."""
2
+
3
+ import json
4
+ import os
5
+ import urllib.error
6
+ import urllib.request
7
+
8
+ API_URL = "https://api.perplexity.ai/v1/agent"
9
+ PRESET = "fast"
10
+
11
+
12
+ class PerplexityError(RuntimeError):
13
+ pass
14
+
15
+
16
+ def get_api_key() -> str:
17
+ key = os.environ.get("PERPLEXITY_API_KEY", "").strip()
18
+ if not key:
19
+ raise PerplexityError(
20
+ "PERPLEXITY_API_KEY is not set. Export it in your environment "
21
+ "(or use --dry-run to simulate without network)."
22
+ )
23
+ return key
24
+
25
+
26
+ def ask(question: str, api_key: str, timeout: int = 60) -> dict:
27
+ """Ask one question. Returns {'answer': str, 'citations': [url, ...]}."""
28
+ body = json.dumps({"preset": PRESET, "input": question}).encode("utf-8")
29
+ req = urllib.request.Request(
30
+ API_URL,
31
+ data=body,
32
+ method="POST",
33
+ headers={
34
+ "Authorization": f"Bearer {api_key}",
35
+ "Content-Type": "application/json",
36
+ },
37
+ )
38
+ try:
39
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
40
+ data = json.loads(resp.read().decode("utf-8"))
41
+ except urllib.error.HTTPError as e:
42
+ try:
43
+ snippet = e.read().decode("utf-8", errors="replace")[:300]
44
+ except Exception:
45
+ snippet = ""
46
+ msg = f"Perplexity API returned HTTP {e.code}"
47
+ if snippet:
48
+ msg += f": {snippet}"
49
+ raise PerplexityError(msg) from e
50
+ except (urllib.error.URLError, OSError, ValueError) as e:
51
+ raise PerplexityError(f"Perplexity request failed: {e}") from e
52
+
53
+ output = data.get("output") if isinstance(data, dict) else None
54
+ if not isinstance(output, list):
55
+ raise PerplexityError("Unexpected Perplexity response format")
56
+
57
+ texts: list[str] = []
58
+ citations: list[str] = []
59
+
60
+ def add_url(url):
61
+ if isinstance(url, str) and url and url not in citations:
62
+ citations.append(url)
63
+
64
+ for item in output:
65
+ if not isinstance(item, dict):
66
+ continue
67
+ if item.get("type") == "search_results":
68
+ for r in item.get("results") or []:
69
+ if isinstance(r, dict):
70
+ add_url(r.get("url"))
71
+ elif item.get("type") == "message":
72
+ for part in item.get("content") or []:
73
+ if not isinstance(part, dict) or part.get("type") != "output_text":
74
+ continue
75
+ text = part.get("text")
76
+ if isinstance(text, str) and text:
77
+ texts.append(text)
78
+ for an in part.get("annotations") or []:
79
+ if isinstance(an, dict) and an.get("type") == "url_citation":
80
+ add_url(an.get("url"))
81
+
82
+ if not texts:
83
+ raise PerplexityError("Unexpected Perplexity response format")
84
+ return {"answer": "\n".join(texts), "citations": citations}
geo_check/questions.py ADDED
@@ -0,0 +1,54 @@
1
+ """Buyer-style question generation from PT and EN templates."""
2
+
3
+ TEMPLATES = {
4
+ "pt": [
5
+ "Qual o melhor {category} em {city}?",
6
+ "Qual {category} em {city} tem as melhores avaliações?",
7
+ "Você recomenda algum {category} em {city}? Quais as opções?",
8
+ "Como escolher um bom {category} em {city}?",
9
+ "Quanto custa um {category} em {city} e quem são os principais?",
10
+ ],
11
+ "en": [
12
+ "What is the best {category} in {city}?",
13
+ "Which are the top-rated {category} options in {city}?",
14
+ "Can you recommend a {category} in {city}? What are the options?",
15
+ "How do I choose a good {category} in {city}?",
16
+ "How much does a {category} cost in {city} and who are the main ones?",
17
+ ],
18
+ }
19
+
20
+
21
+ _PT_WORDS = {
22
+ "dentista", "medico", "advogado", "restaurante", "academia", "pizzaria", "padaria",
23
+ "farmacia", "psicologo", "veterinario", "contador", "arquiteto", "engenheiro",
24
+ "eletricista", "encanador", "pediatra", "oftalmologista", "clinica", "escritorio",
25
+ "loja", "salao", "barbearia", "mecanico", "oficina", "imobiliaria", "escola",
26
+ "faculdade", "hotel", "pousada", "consultorio", "nutricionista", "fisioterapeuta",
27
+ }
28
+ _PT_SUFFIX = ("ista", "eiro", "eira", "aria", "ario", "orio", "ologo", "ador", "adora",
29
+ "ncia", "dade", "cao", "sao")
30
+
31
+
32
+ def detect_lang(category: str) -> str:
33
+ """'pt' if the category looks Portuguese (accents, common words, suffixes), else 'en'.
34
+
35
+ Only the category is inspected: city names carry accents in any language
36
+ (e.g. 'dentist' in 'São Paulo' is still an English query).
37
+ """
38
+ import unicodedata
39
+
40
+ if any(c in category.casefold() for c in "ãõçáéíóúâêôà"):
41
+ return "pt"
42
+ plain = "".join(
43
+ c for c in unicodedata.normalize("NFKD", category.casefold()) if not unicodedata.combining(c)
44
+ )
45
+ for w in plain.split():
46
+ if w in _PT_WORDS or (len(w) > 5 and w.endswith(_PT_SUFFIX)):
47
+ return "pt"
48
+ return "en"
49
+
50
+
51
+ def generate_questions(category: str, city: str, lang: str = "pt") -> list[str]:
52
+ if lang not in TEMPLATES:
53
+ raise ValueError(f"Unsupported language: {lang!r} (use 'pt' or 'en')")
54
+ return [t.format(category=category, city=city) for t in TEMPLATES[lang]]