unitbytes 1.0.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.
unitbytes/client.py ADDED
@@ -0,0 +1,124 @@
1
+ """Unified provider-agnostic `UnitBytes` client wiring all 12 domain namespaces and generic `run()`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from decimal import Decimal
6
+ from typing import Any, Literal, Mapping
7
+
8
+ from ._serialization import normalize_max_charge_usd
9
+ from ._transports import (
10
+ HttpMethod,
11
+ ProviderLiteral,
12
+ Transport,
13
+ resolve_transport,
14
+ unwrap_items_payload,
15
+ )
16
+ from .ai import AiNamespace
17
+ from .ali1688 import Ali1688Namespace
18
+ from .alibaba import AlibabaNamespace
19
+ from .gmaps import GmapsNamespace
20
+ from .goofish import GoofishNamespace
21
+ from .jobs import JobsNamespace
22
+ from .news import NewsNamespace
23
+ from .reddit import RedditNamespace
24
+ from .rednote import RednoteNamespace
25
+ from .shopping import ShoppingNamespace
26
+ from .travel import TravelNamespace
27
+ from .trends import TrendsNamespace
28
+
29
+
30
+ class UnitBytes:
31
+ """Unified, zero-dependency, provider-agnostic Python client for UnitBytes APIs & scrapers.
32
+
33
+ Supports pluggable transports across Apify (`APIFY_TOKEN`), Cloud Gateways (`UNITBYTES_API_KEY` +
34
+ `UNITBYTES_BASE_URL`), RapidAPI (`RAPIDAPI_KEY`), and Zyla API Hub (`ZYLA_API_KEY`) with zero
35
+ caller code changes.
36
+ """
37
+
38
+ def __init__(
39
+ self,
40
+ api_key: str | None = None,
41
+ *,
42
+ api_token: str | None = None,
43
+ provider: ProviderLiteral = "auto",
44
+ base_url: str | None = None,
45
+ rapidapi_host: str | None = None,
46
+ timeout_secs: int = 180,
47
+ max_total_charge_usd: float | Decimal | None = None,
48
+ allow_custom_endpoints: bool = False,
49
+ prefer_standby: bool = False,
50
+ transport: Transport | None = None,
51
+ ) -> None:
52
+ self.timeout_secs = max(5, int(timeout_secs))
53
+ self.max_total_charge_usd = normalize_max_charge_usd(max_total_charge_usd)
54
+ self.allow_custom_endpoints = bool(allow_custom_endpoints)
55
+ self.prefer_standby = bool(prefer_standby)
56
+
57
+ self._transport: Transport = resolve_transport(
58
+ api_key=api_key,
59
+ api_token=api_token,
60
+ provider=provider,
61
+ base_url=base_url,
62
+ rapidapi_host=rapidapi_host,
63
+ timeout_secs=self.timeout_secs,
64
+ max_total_charge_usd=self.max_total_charge_usd,
65
+ allow_custom_endpoints=self.allow_custom_endpoints,
66
+ prefer_standby=self.prefer_standby,
67
+ transport=transport,
68
+ )
69
+ self.provider: str = getattr(self._transport, "provider_name", "custom")
70
+
71
+ # Domain namespaces
72
+ self.trends = TrendsNamespace(self)
73
+ self.jobs = JobsNamespace(self)
74
+ self.shopping = ShoppingNamespace(self)
75
+ self.travel = TravelNamespace(self)
76
+ self.ai = AiNamespace(self)
77
+ self.news = NewsNamespace(self)
78
+ self.gmaps = GmapsNamespace(self)
79
+ self.ali1688 = Ali1688Namespace(self)
80
+ self.alibaba = AlibabaNamespace(self)
81
+ self.goofish = GoofishNamespace(self)
82
+ self.rednote = RednoteNamespace(self)
83
+ self.reddit = RedditNamespace(self)
84
+
85
+ @property
86
+ def transport(self) -> Transport:
87
+ """Active pluggable `Transport` instance."""
88
+ return self._transport
89
+
90
+ def __repr__(self) -> str:
91
+ return (
92
+ f"UnitBytes(provider={self.provider!r}, timeout_secs={self.timeout_secs}, "
93
+ f"transport={self._transport!r})"
94
+ )
95
+
96
+ def run(
97
+ self,
98
+ actor_slug_or_endpoint: str,
99
+ payload: Mapping[str, Any] | None = None,
100
+ *,
101
+ method: Literal["GET", "POST"] | None = None,
102
+ params: Mapping[str, Any] | None = None,
103
+ rapidapi_host: str | None = None,
104
+ timeout_secs: int | None = None,
105
+ max_total_charge_usd: float | Decimal | None = None,
106
+ unwrap_items: bool = True,
107
+ ) -> Any:
108
+ """Execute any of the 66 UnitBytes actors or `/v1/{service}/{operation}` endpoints directly."""
109
+ http_method: HttpMethod | None = method
110
+ raw = self._transport.run_generic(
111
+ actor_slug_or_endpoint,
112
+ payload,
113
+ method=http_method,
114
+ params=params,
115
+ rapidapi_host=rapidapi_host,
116
+ timeout_secs=timeout_secs,
117
+ max_total_charge_usd=max_total_charge_usd,
118
+ )
119
+ if unwrap_items:
120
+ return unwrap_items_payload(raw)
121
+ return raw
122
+
123
+
124
+ __all__ = ["UnitBytes"]
unitbytes/gmaps.py ADDED
@@ -0,0 +1,339 @@
1
+ """Google Maps domain namespace (`ub.gmaps`) for B2B leads, place reviews, stateful review tracking, 4K photos, and Local Guide contributors."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from decimal import Decimal
6
+ import re
7
+ from typing import TYPE_CHECKING, Any, Literal, Mapping, Sequence
8
+
9
+ from ._transports import unwrap_items_payload
10
+
11
+ if TYPE_CHECKING:
12
+ from .client import UnitBytes
13
+
14
+ ACTOR_GMAPS_LEADS = "unitbytes/google-maps-leads-scraper"
15
+ ACTOR_GMAPS_REVIEWS = "unitbytes/google-maps-reviews-scraper"
16
+ ACTOR_GMAPS_REVIEWS_TRACKER = "unitbytes/google-maps-reviews-tracker"
17
+ ACTOR_GMAPS_PHOTOS = "unitbytes/google-maps-photos-scraper"
18
+ ACTOR_GMAPS_CONTRIBUTOR = "unitbytes/google-maps-contributor-scraper"
19
+
20
+ ReviewSortOption = Literal["newest", "lowest_rating", "highest_rating", "most_relevant"]
21
+ ReviewHookType = Literal["most_relevant", "lowest_rating", "newest"]
22
+ ContributorPlaceSort = Literal["negative_and_newest", "negative", "newest", "all"]
23
+
24
+ _VALID_REVIEW_SORTS = {"newest", "lowest_rating", "highest_rating", "most_relevant"}
25
+ _VALID_HOOK_TYPES = {"most_relevant", "lowest_rating", "newest"}
26
+ _VALID_CONTRIB_SORTS = {"negative_and_newest", "negative", "newest", "all"}
27
+ _CHIJ_RE = re.compile(r"^ChIJ[A-Za-z0-9_-]{8,}$")
28
+ _DIGITS_UID_RE = re.compile(r"^\d{15,25}$")
29
+
30
+
31
+ def _normalize_target_list(raw: Sequence[str] | str | None, *, label: str) -> list[str]:
32
+ if raw is None:
33
+ return []
34
+ if isinstance(raw, str):
35
+ items = [ln.strip() for ln in raw.splitlines() if ln.strip()]
36
+ else:
37
+ items = [str(x).strip() for x in raw if x is not None and str(x).strip()]
38
+ if not items:
39
+ raise ValueError(f"{label} must contain at least one non-empty target.")
40
+ return items
41
+
42
+
43
+ class GmapsNamespace:
44
+ """Google Maps B2B leads, reviews, review monitoring, photos, and Local Guide contributor intelligence (`ub.gmaps`)."""
45
+
46
+ def __init__(self, client: UnitBytes) -> None:
47
+ self._client = client
48
+
49
+ def leads(
50
+ self,
51
+ queries: Sequence[str] | str,
52
+ *,
53
+ max_places_per_query: int = 20,
54
+ scrape_contacts: bool = True,
55
+ include_review_hook: bool = True,
56
+ review_hook_type: ReviewHookType = "most_relevant",
57
+ language: str = "en",
58
+ region: str = "us",
59
+ max_concurrency: int = 3,
60
+ proxy_configuration: Mapping[str, Any] | None = None,
61
+ no_cache: bool = False,
62
+ max_total_charge_usd: float | Decimal | None = None,
63
+ ) -> list[dict[str, Any]]:
64
+ """Extract Google Maps B2B leads enriched with website contacts, social links, CMS/pixels, and outreach hooks."""
65
+ search_queries = _normalize_target_list(queries, label="queries")
66
+ if not (1 <= int(max_places_per_query) <= 200):
67
+ raise ValueError("max_places_per_query must be between 1 and 200.")
68
+ if review_hook_type not in _VALID_HOOK_TYPES:
69
+ raise ValueError(f"Invalid review_hook_type {review_hook_type!r}. Expected {sorted(_VALID_HOOK_TYPES)}.")
70
+
71
+ actor_input: dict[str, Any] = {
72
+ "searchQueries": search_queries,
73
+ "maxPlacesPerQuery": int(max_places_per_query),
74
+ "scrapeContacts": bool(scrape_contacts),
75
+ "includeReviewHook": bool(include_review_hook),
76
+ "reviewHookType": review_hook_type,
77
+ "language": str(language or "en").strip(),
78
+ "region": str(region or "us").strip().lower(),
79
+ "maxConcurrency": max(1, min(10, int(max_concurrency))),
80
+ }
81
+ if proxy_configuration is not None:
82
+ actor_input["proxyConfiguration"] = dict(proxy_configuration)
83
+
84
+ rest_params: dict[str, Any] = {
85
+ "query": search_queries[0],
86
+ "page_size": min(60, int(max_places_per_query)),
87
+ "enrich_contacts": bool(scrape_contacts),
88
+ "include_review_hook": bool(include_review_hook),
89
+ "language": str(language or "en").strip(),
90
+ "region": str(region or "us").strip().lower(),
91
+ "no_cache": no_cache or None,
92
+ }
93
+
94
+ raw = self._client._transport.execute_operation(
95
+ service="gmaps",
96
+ operation="search",
97
+ actor_slug=ACTOR_GMAPS_LEADS,
98
+ actor_input=actor_input,
99
+ http_method="GET",
100
+ params=rest_params,
101
+ max_total_charge_usd=max_total_charge_usd,
102
+ )
103
+ return [r for r in unwrap_items_payload(raw) if not r.get("error")]
104
+
105
+ def reviews(
106
+ self,
107
+ targets: Sequence[str] | str,
108
+ *,
109
+ max_reviews_per_place: int = 50,
110
+ max_places_per_query: int = 1,
111
+ sort: ReviewSortOption = "newest",
112
+ keyword: str = "",
113
+ language: str = "en",
114
+ region: str = "us",
115
+ max_concurrency: int = 3,
116
+ proxy_configuration: Mapping[str, Any] | None = None,
117
+ no_cache: bool = False,
118
+ max_total_charge_usd: float | Decimal | None = None,
119
+ ) -> list[dict[str, Any]]:
120
+ """Extract Google Maps business reviews sorted by `newest`, `lowest_rating`, `highest_rating`, or `most_relevant`."""
121
+ target_list = _normalize_target_list(targets, label="targets")
122
+ if sort not in _VALID_REVIEW_SORTS:
123
+ raise ValueError(f"Invalid sort {sort!r}. Expected {sorted(_VALID_REVIEW_SORTS)}.")
124
+ if not (1 <= int(max_reviews_per_place) <= 10000):
125
+ raise ValueError("max_reviews_per_place must be between 1 and 10000.")
126
+
127
+ actor_input: dict[str, Any] = {
128
+ "reviewsToCheck": target_list,
129
+ "maxReviewsPerPlace": int(max_reviews_per_place),
130
+ "maxPlacesPerQuery": max(1, min(20, int(max_places_per_query))),
131
+ "reviewsSort": sort,
132
+ "reviewKeyword": str(keyword or "").strip(),
133
+ "language": str(language or "en").strip(),
134
+ "region": str(region or "us").strip().lower(),
135
+ "maxConcurrency": max(1, min(10, int(max_concurrency))),
136
+ }
137
+ if proxy_configuration is not None:
138
+ actor_input["proxyConfiguration"] = dict(proxy_configuration)
139
+
140
+ first = target_list[0]
141
+ rest_params: dict[str, Any] = {
142
+ "place_id": first if _CHIJ_RE.fullmatch(first) else None,
143
+ "url": first if not _CHIJ_RE.fullmatch(first) else None,
144
+ "sort": sort,
145
+ "keyword": str(keyword or "").strip() or None,
146
+ "page_size": min(60, int(max_reviews_per_place)),
147
+ "language": str(language or "en").strip(),
148
+ "region": str(region or "us").strip().lower(),
149
+ "no_cache": no_cache or None,
150
+ }
151
+
152
+ raw = self._client._transport.execute_operation(
153
+ service="gmaps",
154
+ operation="reviews",
155
+ actor_slug=ACTOR_GMAPS_REVIEWS,
156
+ actor_input=actor_input,
157
+ http_method="GET",
158
+ params=rest_params,
159
+ max_total_charge_usd=max_total_charge_usd,
160
+ )
161
+ return [r for r in unwrap_items_payload(raw) if not r.get("error")]
162
+
163
+ def reviews_tracker(
164
+ self,
165
+ targets: Sequence[str] | str,
166
+ *,
167
+ track_changes: bool = True,
168
+ verify_disappeared_reviews: bool = True,
169
+ max_reviews_per_place: int = 50,
170
+ max_places_per_query: int = 1,
171
+ sort: ReviewSortOption = "newest",
172
+ keyword: str = "",
173
+ language: str = "en",
174
+ region: str = "us",
175
+ max_concurrency: int = 3,
176
+ proxy_configuration: Mapping[str, Any] | None = None,
177
+ max_total_charge_usd: float | Decimal | None = None,
178
+ ) -> list[dict[str, Any]]:
179
+ """Monitor Google Maps reviews with cross-run baseline diffing (`NEW`, `REMOVED`, `RATING_CHANGED`, `TEXT_EDITED`)."""
180
+ target_list = _normalize_target_list(targets, label="targets")
181
+ if sort not in _VALID_REVIEW_SORTS:
182
+ raise ValueError(f"Invalid sort {sort!r}. Expected {sorted(_VALID_REVIEW_SORTS)}.")
183
+
184
+ actor_input: dict[str, Any] = {
185
+ "reviewsToCheck": target_list,
186
+ "trackChanges": bool(track_changes),
187
+ "verifyDisappearedReviews": bool(verify_disappeared_reviews),
188
+ "maxReviewsPerPlace": max(1, min(10000, int(max_reviews_per_place))),
189
+ "maxPlacesPerQuery": max(1, min(20, int(max_places_per_query))),
190
+ "reviewsSort": sort,
191
+ "reviewKeyword": str(keyword or "").strip(),
192
+ "language": str(language or "en").strip(),
193
+ "region": str(region or "us").strip().lower(),
194
+ "maxConcurrency": max(1, min(10, int(max_concurrency))),
195
+ }
196
+ if proxy_configuration is not None:
197
+ actor_input["proxyConfiguration"] = dict(proxy_configuration)
198
+
199
+ first = target_list[0]
200
+ rest_params: dict[str, Any] = {
201
+ "place_id": first if _CHIJ_RE.fullmatch(first) else None,
202
+ "url": first if not _CHIJ_RE.fullmatch(first) else None,
203
+ "sort": sort,
204
+ "keyword": str(keyword or "").strip() or None,
205
+ "page_size": min(60, int(max_reviews_per_place)),
206
+ "language": str(language or "en").strip(),
207
+ "region": str(region or "us").strip().lower(),
208
+ }
209
+
210
+ raw = self._client._transport.execute_operation(
211
+ service="gmaps",
212
+ operation="reviews",
213
+ actor_slug=ACTOR_GMAPS_REVIEWS_TRACKER,
214
+ actor_input=actor_input,
215
+ http_method="GET",
216
+ params=rest_params,
217
+ max_total_charge_usd=max_total_charge_usd,
218
+ )
219
+ return [r for r in unwrap_items_payload(raw) if not r.get("error")]
220
+
221
+ def photos(
222
+ self,
223
+ targets: Sequence[str] | str | None = None,
224
+ *,
225
+ contributors: Sequence[str] | str | None = None,
226
+ category: str = "",
227
+ max_photos: int = 50,
228
+ max_places_per_search: int = 1,
229
+ high_res_only: bool = True,
230
+ scrape_photos: bool = True,
231
+ max_concurrency: int = 3,
232
+ proxy_configuration: Mapping[str, Any] | None = None,
233
+ no_cache: bool = False,
234
+ max_total_charge_usd: float | Decimal | None = None,
235
+ ) -> list[dict[str, Any]]:
236
+ """Extract full-resolution (`=s0`) Google Maps place, menu, food, interior, video, or contributor photos."""
237
+ place_list = _normalize_target_list(targets, label="targets") if targets is not None else []
238
+ contrib_list = _normalize_target_list(contributors, label="contributors") if contributors is not None else []
239
+ if not place_list and not contrib_list:
240
+ raise ValueError("Provide at least one target in 'targets' or 'contributors'.")
241
+
242
+ actor_input: dict[str, Any] = {
243
+ "category": str(category or "").strip(),
244
+ "maxPhotos": max(0, min(1000, int(max_photos))),
245
+ "maxPlacesPerSearch": max(1, min(20, int(max_places_per_search))),
246
+ "highResOnly": bool(high_res_only),
247
+ "scrapePhotos": bool(scrape_photos),
248
+ "maxConcurrency": max(1, min(10, int(max_concurrency))),
249
+ }
250
+ if place_list:
251
+ actor_input["placeUrls"] = place_list
252
+ if contrib_list:
253
+ actor_input["contributors"] = contrib_list
254
+ if proxy_configuration is not None:
255
+ actor_input["proxyConfiguration"] = dict(proxy_configuration)
256
+
257
+ first_place = place_list[0] if place_list else ""
258
+ first_contrib = contrib_list[0] if contrib_list else ""
259
+ rest_params: dict[str, Any] = {
260
+ "place_id": first_place if _CHIJ_RE.fullmatch(first_place) else None,
261
+ "url": first_place if (first_place and not _CHIJ_RE.fullmatch(first_place)) else None,
262
+ "user_id": first_contrib or None,
263
+ "category": str(category or "").strip() or None,
264
+ "page_size": min(60, max(1, int(max_photos))),
265
+ "high_res_only": bool(high_res_only),
266
+ "no_cache": no_cache or None,
267
+ }
268
+
269
+ raw = self._client._transport.execute_operation(
270
+ service="gmaps",
271
+ operation="photos",
272
+ actor_slug=ACTOR_GMAPS_PHOTOS,
273
+ actor_input=actor_input,
274
+ http_method="GET",
275
+ params=rest_params,
276
+ max_total_charge_usd=max_total_charge_usd,
277
+ )
278
+ return [r for r in unwrap_items_payload(raw) if not r.get("error")]
279
+
280
+ def contributor(
281
+ self,
282
+ contributors: Sequence[str] | str,
283
+ *,
284
+ max_reviews: int = 50,
285
+ scrape_reviews: bool = True,
286
+ place_sort: ContributorPlaceSort = "negative_and_newest",
287
+ max_reviewers_per_place: int = 20,
288
+ keyword: str = "",
289
+ output_format: Literal["flattened", "nested"] = "flattened",
290
+ language: str = "en",
291
+ country: str = "us",
292
+ max_concurrency: int = 3,
293
+ proxy_configuration: Mapping[str, Any] | None = None,
294
+ no_cache: bool = False,
295
+ max_total_charge_usd: float | Decimal | None = None,
296
+ ) -> list[dict[str, Any]]:
297
+ """Extract public Google Maps Local Guide / contributor profiles and review histories."""
298
+ contrib_list = _normalize_target_list(contributors, label="contributors")
299
+ if place_sort not in _VALID_CONTRIB_SORTS:
300
+ raise ValueError(f"Invalid place_sort {place_sort!r}. Expected {sorted(_VALID_CONTRIB_SORTS)}.")
301
+
302
+ actor_input: dict[str, Any] = {
303
+ "contributors": contrib_list,
304
+ "maxReviews": max(0, min(200, int(max_reviews))),
305
+ "scrapeReviews": bool(scrape_reviews),
306
+ "placeSort": place_sort,
307
+ "maxReviewersPerPlace": max(1, min(10000, int(max_reviewers_per_place))),
308
+ "keyword": str(keyword or "").strip(),
309
+ "outputFormat": output_format,
310
+ "language": str(language or "en").strip(),
311
+ "country": str(country or "us").strip().lower(),
312
+ "maxConcurrency": max(1, min(10, int(max_concurrency))),
313
+ }
314
+ if proxy_configuration is not None:
315
+ actor_input["proxyConfiguration"] = dict(proxy_configuration)
316
+
317
+ first = contrib_list[0]
318
+ rest_params: dict[str, Any] = {
319
+ "user_id": first if _DIGITS_UID_RE.fullmatch(first) else None,
320
+ "url": first if not _DIGITS_UID_RE.fullmatch(first) else None,
321
+ "page_size": min(60, max(1, int(max_reviews))),
322
+ "language": str(language or "en").strip(),
323
+ "region": str(country or "us").strip().lower(),
324
+ "no_cache": no_cache or None,
325
+ }
326
+
327
+ raw = self._client._transport.execute_operation(
328
+ service="gmaps",
329
+ operation="contributor",
330
+ actor_slug=ACTOR_GMAPS_CONTRIBUTOR,
331
+ actor_input=actor_input,
332
+ http_method="GET",
333
+ params=rest_params,
334
+ max_total_charge_usd=max_total_charge_usd,
335
+ )
336
+ return [r for r in unwrap_items_payload(raw) if not r.get("error")]
337
+
338
+
339
+ __all__ = ["GmapsNamespace"]