pidatametrics 0.7.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.

Potentially problematic release.


This version of pidatametrics might be problematic. Click here for more details.

@@ -0,0 +1,5 @@
1
+ from .client import PiDataMetrics, PiAPIError
2
+ from .parsers import PiParsers
3
+ from .exporter import PiExporter
4
+ from .manager import PiReportManager
5
+ from .batch import ENDPOINTS, SERP_FEATURES, batch_to_rows, normalize_source
pidatametrics/batch.py ADDED
@@ -0,0 +1,259 @@
1
+ """Endpoint catalogue and source batches shared by the client and Colab runner."""
2
+
3
+ import inspect
4
+ import json
5
+ from collections.abc import Mapping
6
+ from datetime import datetime, timedelta, timezone
7
+
8
+ import requests
9
+
10
+
11
+ # Current UI names supplied by the package user. Keep filters open-ended so
12
+ # older labels and newly introduced features can still be passed to the API.
13
+ SERP_FEATURES = {
14
+ "AI Overview": "aiOverview", "Text ads": "textAds",
15
+ "Answer card": "answerCard", "App packs": "appPacks", "Carousel": "carousel",
16
+ "Citations": "citations", "Classic link": "classicLink",
17
+ "Classic link carousel": "classicLinkCarousel", "Classic link sitelinks": "classicLinkSitelinks",
18
+ "Datasets": "datasets", "Sports results": "sportsResults", "Filtered results": "filteredResults",
19
+ "Finance": "finance", "Find results on": "findResultsOn", "Flight pack": "flightPack",
20
+ "Hotel pack": "hotelPack", "Images": "images", "Jobs": "jobs",
21
+ "Knowledge panel": "knowledgePanel", "Maps": "maps", "People also ask": "peopleAlsoAsk",
22
+ "People also buy from": "peopleAlsoBuyFrom", "People also search": "peopleAlsoSearch",
23
+ "Products": "products", "Product listed ads": "productListedAds",
24
+ "Sites carousel": "sitesCarousel", "Site links": "siteLinks", "Source panel": "sourcePanel",
25
+ "Top posts": "topPosts", "Twitter cards": "twitterCards", "Videos": "videos",
26
+ }
27
+
28
+
29
+ def latest_workspace_period(client, workspace_id):
30
+ """Latest completed period within reported tracking ranges.
31
+
32
+ Closed ranges use their end period. Open ranges are capped at the previous
33
+ completed period using the workspace frequency. Tracking history does not
34
+ guarantee that a particular engine has finished processing that period.
35
+ """
36
+ history = client.get_workspace_tracking_history(workspace_id)
37
+ if not history:
38
+ raise ValueError(f"Workspace {workspace_id} has no tracking history; provide an explicit period")
39
+ today = datetime.now(timezone.utc).date()
40
+ yesterday = today - timedelta(days=1)
41
+ candidates = []
42
+ for interval in history:
43
+ end = interval.get("end")
44
+ if end:
45
+ candidates.append(end)
46
+ else:
47
+ start = interval.get("start", "")
48
+ if "W" in start:
49
+ last_week = today - timedelta(days=today.weekday() + 1)
50
+ year, week, _ = last_week.isocalendar()
51
+ end = f"{year}-W{week:02d}"
52
+ elif len(start) == 7:
53
+ end = (today.replace(day=1) - timedelta(days=1)).strftime("%Y-%m")
54
+ else:
55
+ end = yesterday.isoformat()
56
+ if not start or end >= start:
57
+ candidates.append(end)
58
+ if not candidates:
59
+ raise ValueError(f"Workspace {workspace_id} has no completed tracking periods; provide a period")
60
+ def period_key(value):
61
+ if "W" in value:
62
+ return datetime.strptime(value + "-1", "%G-W%V-%u")
63
+ return datetime.strptime(value, "%Y-%m" if len(value) == 7 else "%Y-%m-%d")
64
+ return max(candidates, key=period_key)
65
+
66
+
67
+ def _latest_defaults(client, endpoint, arguments, cache):
68
+ arguments = dict(arguments)
69
+ date_keys = ("start_period", "end_period") if endpoint == "get_llm_mentions" else ("period",)
70
+ needs_dates = endpoint in {
71
+ "get_llm_mentions", "get_returning_site_urls", "get_bulk_search_results",
72
+ "get_bulk_serp_data", "get_bulk_search_results_raw", "get_visibility_index_site_scores",
73
+ "get_visibility_index_search_term_group_scores", "get_rapid_returning_site_urls",
74
+ "get_rapid_bulk_search_results", "get_rapid_bulk_search_results_raw",
75
+ }
76
+ if needs_dates and any(arguments.get(key) in (None, "latest") for key in date_keys):
77
+ if endpoint.startswith("get_rapid_"):
78
+ now = datetime.now(timezone.utc)
79
+ completed = now.replace(hour=now.hour // 2 * 2, minute=0, second=0, microsecond=0) - timedelta(hours=2)
80
+ period = completed.strftime("%Y-%m-%dT%H/PT2H")
81
+ else:
82
+ workspace_id = arguments["workspace_id"]
83
+ if workspace_id not in cache:
84
+ cache[workspace_id] = latest_workspace_period(client, workspace_id)
85
+ period = cache[workspace_id]
86
+ for key in date_keys:
87
+ if arguments.get(key) in (None, "latest"):
88
+ arguments[key] = period
89
+ if endpoint == "get_llm_mentions" and len(period) == 7:
90
+ raise ValueError("LLM mentions requires daily or weekly periods; supply explicit start_period/end_period")
91
+ if endpoint == "get_market_intelligence_version" and arguments.get("version") in (None, "latest"):
92
+ versions = client.get_market_intelligence_versions(arguments["market_intelligence_id"])
93
+ if not versions:
94
+ raise ValueError("No market intelligence versions are available")
95
+ arguments["version"] = max(versions, key=lambda item: int(item["id"]))["id"]
96
+ return arguments
97
+
98
+
99
+ # Section, method, human label, source collection used by the example runner.
100
+ ENDPOINTS = (
101
+ ("2.1", "get_user", "Current user", "standard"),
102
+ ("2.2", "get_accounts", "Accessible accounts", "standard"),
103
+ ("2.3", "get_account", "Account details", "standard"),
104
+ ("2.4", "get_account_quota", "Account quota", "standard"),
105
+ ("2.5", "get_account_sites", "Account sites", "standard"),
106
+ ("2.6", "get_account_structure", "Account structure", "standard"),
107
+ ("3.1", "get_search_engines", "Search engines", "standard"),
108
+ ("3.2", "get_search_engine", "Search engine details", "standard"),
109
+ ("4.1", "get_workspaces", "Workspaces", "standard"),
110
+ ("4.2", "get_workspace", "Workspace details", "standard"),
111
+ ("4.3", "get_workspace_tracking_history", "Workspace tracking history", "standard"),
112
+ ("4.4", "get_workspace_sites", "Workspace sites", "standard"),
113
+ ("4.5", "get_stgs", "Search term groups", "standard"),
114
+ ("4.6", "get_workspace_search_terms", "All workspace search terms", "standard"),
115
+ ("4.7", "get_search_terms", "Search terms within groups", "standard"),
116
+ ("4.8", "get_site", "Site details", "standard"),
117
+ ("5.1", "get_visibility_indexes", "Visibility indexes", "standard"),
118
+ ("5.2", "get_visibility_index", "Visibility index details", "standard"),
119
+ ("5.3", "get_visibility_index_site_scores", "Visibility site scores", "standard"),
120
+ ("5.4", "get_visibility_index_search_term_group_scores", "Visibility group scores", "standard"),
121
+ ("7.1", "get_returning_site_urls", "Returning site URLs", "standard"),
122
+ ("7.2", "get_bulk_search_results", "Bulk search results", "standard"),
123
+ ("7.3", "get_bulk_search_results_raw", "Raw bulk search results", "standard"),
124
+ ("8.1", "get_bulk_volume", "Search volume (raw)", "standard"),
125
+ ("9.1", "get_rapid_workspaces", "Rapid workspaces", "rapid"),
126
+ ("9.2", "get_rapid_workspace", "Rapid workspace details", "rapid"),
127
+ ("9.3", "get_rapid_workspace_sites", "Rapid workspace sites", "rapid"),
128
+ ("9.4", "get_rapid_workspace_campaigns", "Rapid campaigns", "rapid"),
129
+ ("9.5", "get_rapid_workspace_campaign", "Rapid campaign details", "rapid"),
130
+ ("10.1", "get_rapid_returning_site_urls", "Rapid returning site URLs", "rapid"),
131
+ ("10.2", "get_rapid_bulk_search_results", "Rapid bulk search results", "rapid"),
132
+ ("10.3", "get_rapid_bulk_search_results_raw", "Rapid raw search results", "rapid"),
133
+ ("11.1", "get_market_intelligence_list", "Market intelligence reports", "mi"),
134
+ ("11.2", "get_market_intelligence", "Market intelligence details", "mi"),
135
+ ("11.3", "get_market_intelligence_versions", "Market intelligence versions", "mi"),
136
+ ("11.4", "get_market_intelligence_version", "Market intelligence version details", "mi"),
137
+ ("11.5", "get_market_intelligence_components", "Market intelligence components", "mi"),
138
+ ("11.6", "get_market_intelligence_component", "Market intelligence component data", "mi"),
139
+ ("12.1", "get_llm_mentions", "LLM mentions (raw)", "standard"),
140
+ )
141
+
142
+
143
+ def normalize_source(source):
144
+ """Copy a named source, or convert the original five-column SERP source."""
145
+ if isinstance(source, Mapping):
146
+ return dict(source)
147
+ if isinstance(source, (list, tuple)) and len(source) == 5:
148
+ return dict(zip(("market_label", "workspace_id", "workspace_name",
149
+ "search_engine_id", "search_engine_name"), source))
150
+ raise ValueError("Each source must be a dictionary or a five-item SERP source")
151
+
152
+
153
+ def run_batch(client, endpoint, sources=None, *, continue_on_error=False,
154
+ deduplicate=True, **params):
155
+ """Execute an endpoint for each distinct source request.
156
+
157
+ Source IDs are validated before any network calls. Only arguments used by
158
+ the selected endpoint are forwarded. Named source values override shared
159
+ params, allowing per-source dates/filters. Scalar IDs require one source
160
+ row per combination; array filters (stg_ids etc.) remain arrays.
161
+ """
162
+ allowed = {item[1] for item in ENDPOINTS} | {"get_search_term_groups", "get_bulk_serp_data"}
163
+ if endpoint not in allowed:
164
+ raise ValueError(f"Unknown batch endpoint: {endpoint}")
165
+ method = getattr(client, endpoint)
166
+ signature = inspect.signature(method)
167
+ accepted = {name for name, arg in signature.parameters.items()
168
+ if arg.kind not in (arg.VAR_POSITIONAL, arg.VAR_KEYWORD)}
169
+ # Legacy bulk method wraps the full documented bulk method signature.
170
+ if endpoint == "get_bulk_serp_data":
171
+ signature = inspect.signature(client.get_bulk_search_results)
172
+ accepted = {name for name, arg in signature.parameters.items() if arg.kind != arg.VAR_KEYWORD}
173
+ unknown = params.keys() - accepted
174
+ if unknown:
175
+ raise ValueError(f"Unsupported parameters for {endpoint}: {', '.join(sorted(unknown))}")
176
+ entries = [{}] if sources is None else [normalize_source(item) for item in sources]
177
+ planned = []
178
+ seen = {}
179
+ for number, source in enumerate(entries, 1):
180
+ if source.get("account_id", client.account_id) != client.account_id:
181
+ raise ValueError("Sources must use the client's account_id; create another client for another account")
182
+ arguments = dict(params)
183
+ arguments.update({key: value for key, value in source.items() if key in accepted})
184
+ for key, arg in signature.parameters.items():
185
+ if arg.kind in (arg.VAR_POSITIONAL, arg.VAR_KEYWORD):
186
+ continue
187
+ automatic = key in ("period", "start_period", "end_period") or (
188
+ endpoint == "get_market_intelligence_version" and key == "version")
189
+ if arg.default is inspect.Parameter.empty and arguments.get(key) is None and not automatic:
190
+ raise ValueError(f"Source {number}: {endpoint} requires {key}")
191
+ for key, value in arguments.items():
192
+ if (key.endswith("_id") or key in ("version", "component_key", "period")) and isinstance(value, (list, tuple, dict)):
193
+ raise ValueError(f"Source {number}: {key} is scalar; use a separate source for each value")
194
+ if endpoint == "get_bulk_volume" and ((arguments.get("start_date") is None) != (arguments.get("end_date") is None)):
195
+ raise ValueError(f"Source {number}: provide both start_date and end_date")
196
+ if arguments.get("top_url_only") in (True, "true") and arguments.get("site_id") is None:
197
+ raise ValueError(f"Source {number}: top_url_only requires site_id")
198
+ signature.bind_partial(**arguments)
199
+ planned.append({"endpoint": endpoint, "account_id": client.account_id,
200
+ "params": arguments, "sources": [source]})
201
+ # Resolve defaults before fetching data; share tracking-history lookups.
202
+ cache = {}
203
+ resolved = []
204
+ for plan in planned:
205
+ try:
206
+ arguments = _latest_defaults(client, endpoint, plan["params"], cache)
207
+ except requests.exceptions.RequestException as exc:
208
+ if not continue_on_error:
209
+ raise
210
+ resolved.append({**plan, "_resolution_error": exc})
211
+ continue
212
+ signature.bind(**arguments)
213
+ key = json.dumps(arguments, sort_keys=True, ensure_ascii=False)
214
+ if deduplicate and key in seen:
215
+ resolved[seen[key]]["sources"].extend(plan["sources"])
216
+ else:
217
+ seen[key] = len(resolved)
218
+ resolved.append({**plan, "params": arguments})
219
+ results = []
220
+ for plan in resolved:
221
+ client.last_meta = {}
222
+ try:
223
+ if "_resolution_error" in plan:
224
+ raise plan.pop("_resolution_error")
225
+ data = method(**plan["params"])
226
+ except requests.exceptions.RequestException as exc:
227
+ if not continue_on_error:
228
+ raise
229
+ status = exc.response.status_code if exc.response is not None else None
230
+ results.append({**plan, "data": None, "meta": dict(client.last_meta),
231
+ "error": {"type": type(exc).__name__, "status": status, "message": str(exc)}})
232
+ else:
233
+ results.append({**plan, "data": data, "meta": dict(client.last_meta), "error": None})
234
+ return results
235
+
236
+
237
+ def batch_to_rows(results):
238
+ """Lossless, consistent export schema for heterogeneous API response shapes.
239
+
240
+ Each top-level list item becomes one row. Nested data is stored as JSON,
241
+ not expanded into a Cartesian product. Empty results and errors have rows.
242
+ """
243
+ rows = []
244
+ for request_number, result in enumerate(results, 1):
245
+ data = result["data"]
246
+ empty = data is None or data == [] or data == {}
247
+ items = [data] if empty or not isinstance(data, list) else data
248
+ for row_number, item in enumerate(items, 1):
249
+ rows.append({
250
+ "request_number": request_number, "row_number": row_number,
251
+ "endpoint": result["endpoint"], "account_id": str(result["account_id"] or ""),
252
+ "status": "error" if result["error"] else "empty" if empty else "ok",
253
+ "sources_json": json.dumps(result["sources"], ensure_ascii=False),
254
+ "params_json": json.dumps(result["params"], ensure_ascii=False),
255
+ "meta_json": json.dumps(result["meta"], ensure_ascii=False),
256
+ "error_json": json.dumps(result["error"], ensure_ascii=False),
257
+ "data_json": json.dumps(item, ensure_ascii=False),
258
+ })
259
+ return rows
@@ -0,0 +1,374 @@
1
+ """Client for the January 2026 Pi Datametrics API (excluding deprecated section 6)."""
2
+
3
+ from urllib.parse import quote, urlencode
4
+
5
+ import requests
6
+ from requests.adapters import HTTPAdapter
7
+ from urllib3.util.retry import Retry
8
+
9
+
10
+ class PiAPIError(requests.exceptions.RequestException):
11
+ """An error reported in the API's JSON metadata."""
12
+
13
+ def __init__(self, message, *, meta=None, response=None):
14
+ super().__init__(message, response=response)
15
+ self.meta = meta or {}
16
+
17
+
18
+ class PiDataMetrics:
19
+ """Authenticated API client. Methods return the unmodified JSON ``data`` value.
20
+
21
+ Existing three-positional-argument construction remains supported. Supply
22
+ ``access_token`` to use an OAuth authorization-code token instead. The last
23
+ response envelope and quota metadata are available as ``last_response`` and
24
+ ``last_meta``. Use as a context manager to close the HTTP session.
25
+ """
26
+
27
+ api_url = "https://app.pi-datametrics.com/api"
28
+ auth_url = api_url + "/auth"
29
+
30
+ def __init__(self, client_id=None, client_secret=None, account_id=None, *,
31
+ access_token=None, timeout=60, max_retries=3, session=None):
32
+ self.account_id = account_id
33
+ self.base_url = f"{self.api_url}/accounts/{account_id}"
34
+ self.timeout = timeout
35
+ self.session = session if session is not None else requests.Session()
36
+ if not 0 <= max_retries <= 9:
37
+ raise ValueError("max_retries must be between 0 and 9 (at most 10 attempts)")
38
+ retry = Retry(total=max_retries, backoff_factor=1,
39
+ status_forcelist=tuple(range(500, 600)),
40
+ allowed_methods=frozenset(["GET"]), raise_on_status=False)
41
+ self.session.mount("https://", HTTPAdapter(max_retries=retry))
42
+ self.last_response = None
43
+ self.last_meta = {}
44
+ self.access_token = access_token or self._get_access_token(client_id, client_secret)
45
+ self.headers = {"Authorization": f"Bearer {self.access_token}",
46
+ "Content-Type": "application/json"}
47
+
48
+ def close(self):
49
+ self.session.close()
50
+
51
+ def run_batch(self, endpoint, sources=None, *, continue_on_error=False,
52
+ deduplicate=True, **params):
53
+ """Call one endpoint for multiple named or legacy five-column sources."""
54
+ from .batch import run_batch
55
+ return run_batch(self, endpoint, sources, continue_on_error=continue_on_error,
56
+ deduplicate=deduplicate, **params)
57
+
58
+ def __enter__(self):
59
+ return self
60
+
61
+ def __exit__(self, *exc):
62
+ self.close()
63
+
64
+ @staticmethod
65
+ def authorization_url(client_id, redirect_uri, state):
66
+ """Build the browser authorization URL; verify state in your callback."""
67
+ return "https://app.pi-datametrics.com/api-admin/authorise?" + urlencode({
68
+ "client_id": client_id, "response_type": "code",
69
+ "redirect_uri": redirect_uri, "state": state})
70
+
71
+ @classmethod
72
+ def request_token(cls, client_id, client_secret, *, grant_type="client_credentials",
73
+ code=None, redirect_uri=None, refresh_token=None, timeout=60):
74
+ """Return the complete OAuth token response for any documented grant."""
75
+ data = cls._token_data(client_id, client_secret, grant_type,
76
+ code, redirect_uri, refresh_token)
77
+ response = requests.post(cls.auth_url, data=data, timeout=timeout)
78
+ response.raise_for_status()
79
+ payload = response.json()
80
+ if not isinstance(payload, dict) or not payload.get("access_token"):
81
+ raise PiAPIError("Authentication returned no access token", response=response)
82
+ return payload
83
+
84
+ @staticmethod
85
+ def _token_data(client_id, client_secret, grant_type, code=None,
86
+ redirect_uri=None, refresh_token=None):
87
+ if not client_id or not client_secret:
88
+ raise ValueError("client_id and client_secret are required")
89
+ data = {"client_id": client_id, "client_secret": client_secret,
90
+ "grant_type": grant_type}
91
+ if grant_type == "authorization_code":
92
+ if not code or not redirect_uri:
93
+ raise ValueError("code and redirect_uri are required")
94
+ data.update(code=code, redirect_uri=redirect_uri)
95
+ elif grant_type == "refresh_token":
96
+ if not refresh_token:
97
+ raise ValueError("refresh_token is required")
98
+ data["refresh_token"] = refresh_token
99
+ elif grant_type != "client_credentials":
100
+ raise ValueError("Unsupported OAuth grant_type")
101
+ return data
102
+
103
+ def _get_access_token(self, client_id, client_secret):
104
+ response = self.session.post(self.auth_url, data=self._token_data(
105
+ client_id, client_secret, "client_credentials"), timeout=self.timeout)
106
+ response.raise_for_status()
107
+ payload = response.json()
108
+ if not isinstance(payload, dict) or not payload.get("access_token"):
109
+ raise PiAPIError("Authentication returned no access token", response=response)
110
+ return payload["access_token"]
111
+
112
+ @staticmethod
113
+ def _segment(value):
114
+ return quote(str(value), safe="")
115
+
116
+ def _request(self, path, params=None):
117
+ # Keep literal [] and repeated array keys, as required by existing users.
118
+ def wire(value):
119
+ return str(value).lower() if isinstance(value, bool) else value
120
+
121
+ query = {k: [wire(v) for v in value] if isinstance(value, (list, tuple))
122
+ else wire(value) for k, value in (params or {}).items() if value is not None}
123
+ url = self.api_url + "/" + path.lstrip("/")
124
+ if query:
125
+ url += "?" + urlencode(query, doseq=True, safe="[]")
126
+ prepared = self.session.prepare_request(requests.Request("GET", url, headers=self.headers))
127
+ prepared.url = url
128
+ settings = self.session.merge_environment_settings(url, {}, None, None, None)
129
+ self.last_response, self.last_meta = None, {}
130
+ response = self.session.send(prepared, timeout=self.timeout, **settings)
131
+ response.raise_for_status()
132
+ payload = response.json()
133
+ self.last_response = payload
134
+ if isinstance(payload, dict):
135
+ self.last_meta = payload.get("meta") or {}
136
+ status = self.last_meta.get("status", 200)
137
+ if self.last_meta.get("errors") or int(status) >= 400:
138
+ raise PiAPIError("Pi Datametrics API reported an error",
139
+ meta=self.last_meta, response=response)
140
+ if "data" in payload:
141
+ return payload["data"]
142
+ # Raw SERP examples in the specification use a top-level array.
143
+ return payload
144
+
145
+ def fetch_endpoint(self, endpoint_path, params=None):
146
+ """GET an account-relative endpoint; use named methods for global routes."""
147
+ if self.account_id is None:
148
+ raise ValueError("account_id is required for account endpoints")
149
+ return self._request(f"accounts/{self._segment(self.account_id)}/{endpoint_path.lstrip('/')}", params)
150
+
151
+ def get_user(self):
152
+ """2.1: Current user's details."""
153
+ return self._request("me")
154
+
155
+ def get_accounts(self):
156
+ """2.2: Accounts accessible to the user."""
157
+ return self._request("accounts")
158
+
159
+ def get_account(self):
160
+ """2.3: Configured account's details."""
161
+ if self.account_id is None:
162
+ raise ValueError("account_id is required")
163
+ return self._request(f"accounts/{self._segment(self.account_id)}")
164
+
165
+ def get_account_quota(self):
166
+ """2.4: Allocated, used and remaining quota."""
167
+ return self.fetch_endpoint("quota")
168
+
169
+ def get_account_sites(self):
170
+ """2.5: Account-level sites."""
171
+ return self.fetch_endpoint("sites")
172
+
173
+ def get_account_structure(self, workspace_ids=None):
174
+ """2.6: Workspace/group/term hierarchy, optionally filtered by workspace."""
175
+ return self.fetch_endpoint("account-structure", {"workspace-id[]": workspace_ids})
176
+
177
+ def get_search_engines(self, market=None, language=None):
178
+ """3.1: Global search engines, optionally filtered by market/language."""
179
+ return self._request("search-engines", {"market": market, "language": language})
180
+
181
+ def get_search_engine(self, search_engine_id):
182
+ """3.2: Global search engine details."""
183
+ return self._request(f"search-engines/{self._segment(search_engine_id)}")
184
+
185
+ def _workspace_path(self, workspace_id):
186
+ return f"workspaces/{self._segment(workspace_id)}"
187
+
188
+ def get_workspaces(self):
189
+ """4.1: Standard workspaces."""
190
+ return self.fetch_endpoint("workspaces")
191
+
192
+ def get_workspace(self, workspace_id):
193
+ """4.2: Standard workspace details."""
194
+ return self.fetch_endpoint(self._workspace_path(workspace_id))
195
+
196
+ def get_workspace_tracking_history(self, workspace_id):
197
+ """4.3: Tracked period ranges."""
198
+ return self.fetch_endpoint(self._workspace_path(workspace_id) + "/tracking-history")
199
+
200
+ def get_workspace_sites(self, workspace_id):
201
+ """4.4: Workspace sites."""
202
+ return self.fetch_endpoint(self._workspace_path(workspace_id) + "/sites")
203
+
204
+ def get_stgs(self, workspace_id):
205
+ """4.5: Workspace search term groups (original method name)."""
206
+ return self.fetch_endpoint(self._workspace_path(workspace_id) + "/search-term-groups")
207
+
208
+ get_search_term_groups = get_stgs
209
+
210
+ def get_workspace_search_terms(self, workspace_id):
211
+ """4.6: All search terms in a workspace."""
212
+ return self.fetch_endpoint(self._workspace_path(workspace_id) + "/search-terms")
213
+
214
+ def get_search_terms(self, workspace_id, stg_id):
215
+ """4.7: Search terms belonging to a group (original method name)."""
216
+ return self.fetch_endpoint(self._workspace_path(workspace_id)
217
+ + f"/search-term-groups/{self._segment(stg_id)}/search-terms")
218
+
219
+ def get_site(self, workspace_id, site_id):
220
+ """4.8: Workspace site details."""
221
+ return self.fetch_endpoint(self._workspace_path(workspace_id) + f"/sites/{self._segment(site_id)}")
222
+
223
+ def _index_path(self, workspace_id, index_id=None):
224
+ path = self._workspace_path(workspace_id) + "/visibility-indexes"
225
+ return path if index_id is None else path + "/" + self._segment(index_id)
226
+
227
+ def get_visibility_indexes(self, workspace_id):
228
+ """5.1: Workspace visibility indexes."""
229
+ return self.fetch_endpoint(self._index_path(workspace_id))
230
+
231
+ def get_visibility_index(self, workspace_id, index_id):
232
+ """5.2: Index details and search criteria."""
233
+ return self.fetch_endpoint(self._index_path(workspace_id, index_id))
234
+
235
+ def get_visibility_index_site_scores(self, workspace_id, index_id, period):
236
+ """5.3: Top-level site scores."""
237
+ return self.fetch_endpoint(self._index_path(workspace_id, index_id) + "/site-scores", {"period": period})
238
+
239
+ def get_visibility_index_search_term_group_scores(self, workspace_id, index_id, site_id, period):
240
+ """5.4: Group scores; uses site-scores with a site-id query parameter."""
241
+ return self.fetch_endpoint(self._index_path(workspace_id, index_id) + "/site-scores",
242
+ {"site-id": site_id, "period": period})
243
+
244
+ def get_returning_site_urls(self, workspace_id, search_engine_id, site_id, period, *,
245
+ stg_ids=None, ranking_mode=None):
246
+ """7.1: Returning URLs for a site; default API ranking is hypergraph."""
247
+ return self.fetch_endpoint(self._workspace_path(workspace_id) + "/search-data/returning-site-urls",
248
+ {"search-engine-id": search_engine_id, "site-id": site_id,
249
+ "period": period, "search-term-group-id[]": stg_ids,
250
+ "ranking-mode": ranking_mode})
251
+
252
+ def get_bulk_search_results(self, workspace_id, search_engine_id, period, *, stg_ids=None,
253
+ number_of_results=None, ranking_mode=None, site_id=None,
254
+ top_url_only=None, ranked_features_only=None, serp_features=None, **kwargs):
255
+ """7.2: Ranked SERP results with all documented filters.
256
+
257
+ ``kwargs`` also accepts original API parameter names, for compatibility.
258
+ """
259
+ params = {"search-engine-id": search_engine_id, "period": period,
260
+ "number-of-results": number_of_results, "ranking-mode": ranking_mode,
261
+ "site-id": site_id, "top-url-only": top_url_only,
262
+ "ranked-features-only": ranked_features_only,
263
+ "search-term-group-id[]": stg_ids, "serp-feature[]": serp_features}
264
+ params.update(kwargs)
265
+ if params.get("top-url-only") in (True, "true") and params.get("site-id") is None:
266
+ raise ValueError("top_url_only requires site_id")
267
+ return self.fetch_endpoint(self._workspace_path(workspace_id) + "/search-data/bulk-search-results", params)
268
+
269
+ def get_bulk_serp_data(self, workspace_id, search_engine_id, period, **kwargs):
270
+ """Compatibility wrapper preserving the original absolute ranking default.
271
+
272
+ New code should use get_bulk_search_results for the documented API default.
273
+ """
274
+ kwargs.setdefault("ranking_mode", "absolute")
275
+ return self.get_bulk_search_results(workspace_id, search_engine_id, period, **kwargs)
276
+
277
+ def get_bulk_search_results_raw(self, workspace_id, search_engine_id, period, *,
278
+ stg_ids=None, serp_features=None):
279
+ """7.3: Unranked, nested SERP blocks."""
280
+ return self.fetch_endpoint(self._workspace_path(workspace_id) + "/search-data/bulk-search-results-raw",
281
+ {"search-engine-id": search_engine_id, "period": period,
282
+ "search-term-group-id[]": stg_ids, "serp-feature[]": serp_features})
283
+
284
+ def get_bulk_volume(self, workspace_id, start_date=None, end_date=None, *,
285
+ stg_ids=None, search_terms=None, currency=None):
286
+ """8.1: Monthly volume/CPC/competition. Dates use YYYY-MM, not daily dates."""
287
+ if (start_date is None) != (end_date is None):
288
+ raise ValueError("Provide both start_date and end_date, or neither")
289
+ return self.fetch_endpoint(self._workspace_path(workspace_id) + "/volume-data/bulk-search-volume",
290
+ {"start-period": start_date, "end-period": end_date,
291
+ "search-term-group-id[]": stg_ids, "search-term[]": search_terms,
292
+ "currency": currency})
293
+
294
+ def _rapid_path(self, workspace_id, campaign_id=None):
295
+ path = f"rapid-workspaces/{self._segment(workspace_id)}"
296
+ return path if campaign_id is None else path + f"/campaigns/{self._segment(campaign_id)}"
297
+
298
+ def get_rapid_workspaces(self):
299
+ """9.1: Rapid workspaces."""
300
+ return self.fetch_endpoint("rapid-workspaces")
301
+
302
+ def get_rapid_workspace(self, workspace_id):
303
+ """9.2: Rapid workspace details."""
304
+ return self.fetch_endpoint(self._rapid_path(workspace_id))
305
+
306
+ def get_rapid_workspace_sites(self, workspace_id):
307
+ """9.3: Rapid workspace sites."""
308
+ return self.fetch_endpoint(self._rapid_path(workspace_id) + "/sites")
309
+
310
+ def get_rapid_workspace_campaigns(self, workspace_id):
311
+ """9.4: Rapid workspace campaigns."""
312
+ return self.fetch_endpoint(self._rapid_path(workspace_id) + "/campaigns")
313
+
314
+ def get_rapid_workspace_campaign(self, workspace_id, campaign_id):
315
+ """9.5: Campaign details."""
316
+ return self.fetch_endpoint(self._rapid_path(workspace_id, campaign_id))
317
+
318
+ def get_rapid_returning_site_urls(self, workspace_id, campaign_id, search_engine_id,
319
+ site_id, period, *, ranking_mode=None):
320
+ """10.1: Campaign site URLs; period format YYYY-MM-DDTHH/PT2H."""
321
+ return self.fetch_endpoint(self._rapid_path(workspace_id, campaign_id) + "/search-data/returning-site-urls",
322
+ {"search-engine-id": search_engine_id, "site-id": site_id,
323
+ "period": period, "ranking-mode": ranking_mode})
324
+
325
+ def get_rapid_bulk_search_results(self, workspace_id, campaign_id, search_engine_id,
326
+ period, *, number_of_results=None, ranking_mode=None):
327
+ """10.2: Ranked campaign SERP results."""
328
+ return self.fetch_endpoint(self._rapid_path(workspace_id, campaign_id) + "/search-data/bulk-search-results",
329
+ {"search-engine-id": search_engine_id, "period": period,
330
+ "number-of-results": number_of_results, "ranking-mode": ranking_mode})
331
+
332
+ def get_rapid_bulk_search_results_raw(self, workspace_id, campaign_id, search_engine_id,
333
+ period, *, number_of_results=None):
334
+ """10.3: Raw campaign SERP blocks, optionally limited per search result."""
335
+ return self.fetch_endpoint(self._rapid_path(workspace_id, campaign_id) + "/search-data/bulk-search-results-raw",
336
+ {"search-engine-id": search_engine_id, "period": period,
337
+ "number-of-results": number_of_results})
338
+
339
+ def _mi_path(self, market_intelligence_id):
340
+ return "market-intelligence/" + self._segment(market_intelligence_id)
341
+
342
+ def get_market_intelligence_list(self):
343
+ """11.1: Market intelligence reports."""
344
+ return self.fetch_endpoint("market-intelligence")
345
+
346
+ def get_market_intelligence(self, market_intelligence_id):
347
+ """11.2: Report details."""
348
+ return self.fetch_endpoint(self._mi_path(market_intelligence_id))
349
+
350
+ def get_market_intelligence_versions(self, market_intelligence_id):
351
+ """11.3: Report versions."""
352
+ return self.fetch_endpoint(self._mi_path(market_intelligence_id) + "/versions")
353
+
354
+ def get_market_intelligence_version(self, market_intelligence_id, version):
355
+ """11.4: Version details."""
356
+ return self.fetch_endpoint(self._mi_path(market_intelligence_id) + f"/versions/{self._segment(version)}")
357
+
358
+ def get_market_intelligence_components(self, market_intelligence_id, version=None):
359
+ """11.5: Available component keys and labels (latest version by default)."""
360
+ return self.fetch_endpoint(self._mi_path(market_intelligence_id) + "/components", {"version": version})
361
+
362
+ def get_market_intelligence_component(self, market_intelligence_id, component_key, version=None):
363
+ """11.6: Any report component, preserving its nested data structure."""
364
+ return self.fetch_endpoint(self._mi_path(market_intelligence_id) + f"/components/{self._segment(component_key)}",
365
+ {"version": version})
366
+
367
+ def get_llm_mentions(self, workspace_id, search_engine_id, start_period, end_period, stg_ids=None):
368
+ """12.1: LLM citations/mentions; daily or ISO weekly periods."""
369
+ if self.account_id is None:
370
+ raise ValueError("account_id is required for LLM mentions")
371
+ return self._request("data/llm/mentions", {
372
+ "account-id": self.account_id, "workspace-id": workspace_id,
373
+ "start-period": start_period, "end-period": end_period,
374
+ "search-engine-id": search_engine_id, "search-term-group-id[]": stg_ids})