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/alibaba.py ADDED
@@ -0,0 +1,211 @@
1
+ """Alibaba.com B2B wholesale & verified supplier sourcing domain namespace (`ub.alibaba`)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from decimal import Decimal
6
+ from typing import TYPE_CHECKING, Any, Literal, Mapping, Sequence
7
+ from urllib.parse import urlparse
8
+
9
+ from ._transports import unwrap_items_payload
10
+
11
+ if TYPE_CHECKING:
12
+ from .client import UnitBytes
13
+
14
+ ACTOR_ALIBABA_PRODUCTS = "unitbytes/alibaba-scraper"
15
+ ACTOR_ALIBABA_SUPPLIERS = "unitbytes/alibaba-supplier-scraper"
16
+
17
+ AlibabaDetailLevel = Literal["full", "summary"]
18
+ AlibabaSortBy = Literal["default", "salesVolume", "priceAsc", "priceDesc", "reviewScore", "newest"]
19
+
20
+ _VALID_SORTS = {"default", "salesVolume", "priceAsc", "priceDesc", "reviewScore", "newest"}
21
+
22
+
23
+ def _normalize_queries(queries: Sequence[str] | str | None, keyword: str | None = None) -> list[str]:
24
+ out: list[str] = []
25
+ if keyword and str(keyword).strip():
26
+ out.append(str(keyword).strip())
27
+ if isinstance(queries, str) and queries.strip():
28
+ out.extend(p.strip() for p in queries.split(",") if p.strip())
29
+ elif isinstance(queries, Sequence) and not isinstance(queries, (str, bytes)):
30
+ out.extend(str(q).strip() for q in queries if q is not None and str(q).strip())
31
+ deduped: list[str] = []
32
+ seen: set[str] = set()
33
+ for q in out:
34
+ if q.lower() not in seen:
35
+ seen.add(q.lower())
36
+ deduped.append(q)
37
+ return deduped
38
+
39
+
40
+ def _extract_alibaba_subdomain(url_or_sub: str) -> tuple[str | None, str | None]:
41
+ cleaned = str(url_or_sub or "").strip()
42
+ if not cleaned:
43
+ return None, None
44
+ if cleaned.startswith(("http://", "https://")):
45
+ parsed = urlparse(cleaned)
46
+ host = (parsed.hostname or "").lower()
47
+ if host.endswith(".en.alibaba.com"):
48
+ return host.split(".en.alibaba.com")[0], cleaned
49
+ return None, cleaned
50
+ return cleaned, None
51
+
52
+
53
+ class AlibabaNamespace:
54
+ """Alibaba.com wholesale product & verified manufacturer directory methods (`ub.alibaba`)."""
55
+
56
+ def __init__(self, client: UnitBytes) -> None:
57
+ self._client = client
58
+
59
+ def search(
60
+ self,
61
+ queries: Sequence[str] | str | None = None,
62
+ *,
63
+ keyword: str | None = None,
64
+ category_url: str | None = None,
65
+ product_urls: Sequence[str] | None = None,
66
+ max_items: int = 20,
67
+ page: int = 1,
68
+ detail_level: AlibabaDetailLevel = "full",
69
+ sort_by: AlibabaSortBy = "default",
70
+ verified_only: bool = False,
71
+ trade_assurance_only: bool = False,
72
+ min_order_quantity_max: int | None = None,
73
+ price_min: float | None = None,
74
+ price_max: float | None = None,
75
+ country: str | None = None,
76
+ proxy_configuration: Mapping[str, Any] | None = None,
77
+ no_cache: bool = False,
78
+ max_total_charge_usd: float | Decimal | None = None,
79
+ ) -> list[dict[str, Any]]:
80
+ """Search Alibaba.com B2B wholesale products with MOQ tiers, FBA specs, and Trade Assurance / Verified filters."""
81
+ norm_queries = _normalize_queries(queries, keyword)
82
+ prod_urls = [str(u).strip() for u in (product_urls or []) if u and str(u).strip()]
83
+ cat_u = (category_url or "").strip() or None
84
+ if not norm_queries and not prod_urls and not cat_u:
85
+ raise ValueError("Provide at least one search query, category_url, or product_urls.")
86
+ if sort_by not in _VALID_SORTS:
87
+ raise ValueError(f"Invalid sort_by {sort_by!r}. Expected {sorted(_VALID_SORTS)}.")
88
+ if int(max_items) < 1:
89
+ raise ValueError("max_items must be >= 1.")
90
+
91
+ actor_input: dict[str, Any] = {
92
+ "mode": "products",
93
+ "maxItems": max(1, min(100000, int(max_items))),
94
+ "detailLevel": detail_level,
95
+ "sortBy": sort_by,
96
+ "verifiedOnly": bool(verified_only),
97
+ "tradeAssuranceOnly": bool(trade_assurance_only),
98
+ }
99
+ if norm_queries:
100
+ actor_input["queries"] = norm_queries
101
+ actor_input["keyword"] = norm_queries[0]
102
+ if cat_u:
103
+ actor_input["categoryUrl"] = cat_u
104
+ if prod_urls:
105
+ actor_input["productUrls"] = prod_urls
106
+ if min_order_quantity_max is not None:
107
+ actor_input["minOrderQuantityMax"] = max(1, int(min_order_quantity_max))
108
+ if country and str(country).strip():
109
+ actor_input["country"] = str(country).strip().upper()
110
+ if proxy_configuration is not None:
111
+ actor_input["proxyConfiguration"] = dict(proxy_configuration)
112
+
113
+ rest_params: dict[str, Any] = {
114
+ "keyword": norm_queries[0] if norm_queries else None,
115
+ "page": int(page),
116
+ "page_size": max(1, min(60, int(max_items))),
117
+ "sort_by": sort_by,
118
+ "verified_only": verified_only or None,
119
+ "trade_assurance_only": trade_assurance_only or None,
120
+ "min_moq": min_order_quantity_max,
121
+ "price_min": price_min,
122
+ "price_max": price_max,
123
+ "country": str(country).strip().upper() if country and str(country).strip() else None,
124
+ "no_cache": no_cache or None,
125
+ }
126
+
127
+ raw = self._client._transport.execute_operation(
128
+ service="alibaba",
129
+ operation="search",
130
+ actor_slug=ACTOR_ALIBABA_PRODUCTS,
131
+ actor_input=actor_input,
132
+ http_method="GET",
133
+ params=rest_params,
134
+ max_total_charge_usd=max_total_charge_usd,
135
+ )
136
+ return [r for r in unwrap_items_payload(raw) if not r.get("error")]
137
+
138
+ def suppliers(
139
+ self,
140
+ queries: Sequence[str] | str | None = None,
141
+ *,
142
+ supplier_urls: Sequence[str] | str | None = None,
143
+ max_items: int = 20,
144
+ page: int = 1,
145
+ verified_only: bool = False,
146
+ trade_assurance_only: bool = False,
147
+ country: str | None = None,
148
+ proxy_configuration: Mapping[str, Any] | None = None,
149
+ no_cache: bool = False,
150
+ max_total_charge_usd: float | Decimal | None = None,
151
+ ) -> list[dict[str, Any]]:
152
+ """Discover verified Alibaba.com manufacturers and audit TÜV/SGS factory profiles."""
153
+ norm_queries = _normalize_queries(queries)
154
+ sup_urls: list[str] = []
155
+ if isinstance(supplier_urls, str) and supplier_urls.strip():
156
+ sup_urls.append(supplier_urls.strip())
157
+ elif isinstance(supplier_urls, Sequence) and not isinstance(supplier_urls, (str, bytes)):
158
+ sup_urls.extend(str(u).strip() for u in supplier_urls if u is not None and str(u).strip())
159
+
160
+ if not norm_queries and not sup_urls:
161
+ raise ValueError("Provide at least one search query in 'queries' or storefront URL in 'supplier_urls'.")
162
+
163
+ actor_input: dict[str, Any] = {
164
+ "mode": "suppliers",
165
+ "maxItems": max(1, min(100000, int(max_items))),
166
+ "verifiedOnly": bool(verified_only),
167
+ "tradeAssuranceOnly": bool(trade_assurance_only),
168
+ }
169
+ if norm_queries:
170
+ actor_input["queries"] = norm_queries
171
+ actor_input["keyword"] = norm_queries[0]
172
+ if sup_urls:
173
+ actor_input["supplierUrls"] = sup_urls
174
+ if country and str(country).strip():
175
+ actor_input["country"] = str(country).strip().upper()
176
+ if proxy_configuration is not None:
177
+ actor_input["proxyConfiguration"] = dict(proxy_configuration)
178
+
179
+ if sup_urls and not norm_queries:
180
+ subdomain, full_url = _extract_alibaba_subdomain(sup_urls[0])
181
+ rest_op = "supplier"
182
+ rest_params: dict[str, Any] = {
183
+ "subdomain": subdomain,
184
+ "url": full_url if not subdomain else None,
185
+ "no_cache": no_cache or None,
186
+ }
187
+ else:
188
+ rest_op = "search"
189
+ rest_params = {
190
+ "keyword": norm_queries[0],
191
+ "page": int(page),
192
+ "page_size": max(1, min(60, int(max_items))),
193
+ "verified_only": True if verified_only else None,
194
+ "trade_assurance_only": trade_assurance_only or None,
195
+ "country": str(country).strip().upper() if country and str(country).strip() else None,
196
+ "no_cache": no_cache or None,
197
+ }
198
+
199
+ raw = self._client._transport.execute_operation(
200
+ service="alibaba",
201
+ operation=rest_op,
202
+ actor_slug=ACTOR_ALIBABA_SUPPLIERS,
203
+ actor_input=actor_input,
204
+ http_method="GET",
205
+ params=rest_params,
206
+ max_total_charge_usd=max_total_charge_usd,
207
+ )
208
+ return [r for r in unwrap_items_payload(raw) if not r.get("error")]
209
+
210
+
211
+ __all__ = ["AlibabaNamespace"]
unitbytes/cli.py ADDED
@@ -0,0 +1,454 @@
1
+ """Command-line interface (`unitbytes`) for querying UnitBytes domains and exporting JSON/JSONL/CSV."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ from pathlib import Path
9
+ import sys
10
+ from typing import Any, Sequence
11
+
12
+ from ._exceptions import AuthenticationError, ConfigurationError, UnitBytesError, redact_secrets
13
+ from ._serialization import format_records
14
+ from ._transports import Transport
15
+ from .client import UnitBytes
16
+
17
+ VERSION = "1.0.0"
18
+
19
+
20
+ def _add_shared_options(parser: argparse.ArgumentParser, *, is_root: bool = False) -> None:
21
+ default_val = None if is_root else argparse.SUPPRESS
22
+ parser.add_argument(
23
+ "--api-key",
24
+ "--token",
25
+ dest="api_key",
26
+ default=default_val,
27
+ help="API key or token (defaults to UNITBYTES_API_KEY, APIFY_TOKEN, RAPIDAPI_KEY, or ZYLA_API_KEY).",
28
+ )
29
+ parser.add_argument(
30
+ "--provider",
31
+ choices=("auto", "apify", "cloud", "rapidapi", "zyla"),
32
+ default="auto" if is_root else argparse.SUPPRESS,
33
+ help="Backend transport provider (default: auto).",
34
+ )
35
+ parser.add_argument(
36
+ "--base-url",
37
+ dest="base_url",
38
+ default=default_val,
39
+ help="Gateway or Zyla HTTPS base URL.",
40
+ )
41
+ parser.add_argument(
42
+ "--rapidapi-host",
43
+ dest="rapidapi_host",
44
+ default=default_val,
45
+ help="Optional RapidAPI host override (*.p.rapidapi.com).",
46
+ )
47
+ parser.add_argument(
48
+ "--timeout",
49
+ dest="timeout_secs",
50
+ type=int,
51
+ default=180 if is_root else argparse.SUPPRESS,
52
+ help="Request / run timeout in seconds (default: 180).",
53
+ )
54
+ parser.add_argument(
55
+ "--max-charge-usd",
56
+ dest="max_total_charge_usd",
57
+ type=float,
58
+ default=default_val,
59
+ help="Optional per-run USD spending cap on Apify.",
60
+ )
61
+ parser.add_argument(
62
+ "--allow-custom-endpoints",
63
+ dest="allow_custom_endpoints",
64
+ action="store_true",
65
+ default=False if is_root else argparse.SUPPRESS,
66
+ help="Allow custom HTTPS or localhost HTTP test endpoints.",
67
+ )
68
+ parser.add_argument(
69
+ "-f",
70
+ "--format",
71
+ dest="output_format",
72
+ choices=("json", "jsonl", "csv"),
73
+ default="json" if is_root else argparse.SUPPRESS,
74
+ help="Output serialization format: json, jsonl, or formula-safe csv (default: json).",
75
+ )
76
+ parser.add_argument(
77
+ "-o",
78
+ "--output",
79
+ dest="output_path",
80
+ default=default_val,
81
+ help="Write formatted output to a file instead of stdout.",
82
+ )
83
+
84
+
85
+ def build_parser() -> argparse.ArgumentParser:
86
+ parser = argparse.ArgumentParser(
87
+ prog="unitbytes",
88
+ description="Unified provider-agnostic CLI for UnitBytes web data APIs & scrapers.",
89
+ )
90
+ parser.add_argument("--version", action="version", version=f"%(prog)s {VERSION}")
91
+ _add_shared_options(parser, is_root=True)
92
+
93
+ leaf_common = argparse.ArgumentParser(add_help=False)
94
+ _add_shared_options(leaf_common, is_root=False)
95
+
96
+ domains = parser.add_subparsers(dest="domain", metavar="<domain>")
97
+
98
+ # 1. trends
99
+ p_trends = domains.add_parser("trends", help="Google Trends (Trending Now, timelines, breakouts).")
100
+ s_trends = p_trends.add_subparsers(dest="action", required=True)
101
+
102
+ t_now = s_trends.add_parser("trending-now", parents=[leaf_common], help="Fetch real-time trending searches.")
103
+ t_now.add_argument("--geo", default="US", help="2-letter ISO country or sub-region code (default: US).")
104
+ t_now.add_argument("--window", choices=("4h", "24h", "48h", "7d"), default="24h", help="Trending time window.")
105
+ t_now.add_argument("--hours", type=int, default=None, help="Optional custom lookback hours (1..191).")
106
+ t_now.add_argument("--language", default="en", help="ISO language code (default: en).")
107
+ t_now.add_argument("--max-events", type=int, default=50, help="Maximum records (default: 50).")
108
+
109
+ t_iot = s_trends.add_parser("interest-over-time", parents=[leaf_common], help="Fetch search interest timeline.")
110
+ t_iot.add_argument("keywords", nargs="+", help="Keywords to compare or track.")
111
+ t_iot.add_argument("--timeframe", default="today 12-m", help="Timeframe (e.g. 'today 12-m', 'now 7-d').")
112
+ t_iot.add_argument("--geo", default="US", help="Country or region code (default: US).")
113
+ t_iot.add_argument("--gprop", default="web", help="Property: web, youtube, froogle, news, images.")
114
+
115
+ t_bo = s_trends.add_parser("breakouts", parents=[leaf_common], help="Discover Breakout (+5,000%%) queries.")
116
+ t_bo.add_argument("keywords", nargs="*", help="Optional seed keywords (omit for geo-wide breakouts).")
117
+ t_bo.add_argument("--timeframe", default="today 3-m", help="Timeframe for seed keywords.")
118
+ t_bo.add_argument("--geo", default="US", help="Country code (default: US).")
119
+ t_bo.add_argument("--min-growth", type=float, default=500.0, help="Minimum growth %% (default: 500).")
120
+
121
+ # 2. jobs
122
+ p_jobs = domains.add_parser("jobs", help="Google Jobs search, ATS links, and hiring company signals.")
123
+ s_jobs = p_jobs.add_subparsers(dest="action", required=True)
124
+
125
+ j_search = s_jobs.add_parser("search", parents=[leaf_common], help="Search Google Jobs with ATS enrichment.")
126
+ j_search.add_argument("queries", nargs="+", help="Job search queries.")
127
+ j_search.add_argument("--location", action="append", dest="locations", help="Location filter (repeatable).")
128
+ j_search.add_argument("--country", default="us", help="2-letter country code (default: us).")
129
+ j_search.add_argument("--date-posted", choices=("any", "today", "3days", "week", "month"), default="any")
130
+ j_search.add_argument("--remote-only", action="store_true", help="Filter for remote roles only.")
131
+ j_search.add_argument("--direct-ats-only", action="store_true", help="Keep only direct employer/ATS links.")
132
+ j_search.add_argument("--only-new", action="store_true", help="Deduplicate against local 0600 watchlist state.")
133
+ j_search.add_argument("--state-file", default=None, help="Custom path for watchlist state JSON.")
134
+ j_search.add_argument("--max-jobs", type=int, default=25, help="Max jobs to return (default: 25).")
135
+
136
+ j_comp = s_jobs.add_parser("hiring-companies", parents=[leaf_common], help="Aggregate B2B hiring signals.")
137
+ j_comp.add_argument("queries", nargs="+", help="Job search queries.")
138
+ j_comp.add_argument("--location", action="append", dest="locations", help="Location filter.")
139
+ j_comp.add_argument("--country", default="us", help="Country code (default: us).")
140
+ j_comp.add_argument("--max-jobs", type=int, default=50, help="Max postings to sample (default: 50).")
141
+
142
+ # 3. shopping
143
+ p_shop = domains.add_parser("shopping", help="Google Shopping search and MAP compliance.")
144
+ s_shop = p_shop.add_subparsers(dest="action", required=True)
145
+
146
+ sh_search = s_shop.add_parser("search", parents=[leaf_common], help="Search Google Shopping offers.")
147
+ sh_search.add_argument("queries", nargs="+", help="Product search queries.")
148
+ sh_search.add_argument("--country", default="us", help="Country code (default: us).")
149
+ sh_search.add_argument("--sort-by", choices=("relevance", "price_asc", "price_desc", "rating_desc"), default="relevance")
150
+ sh_search.add_argument("--min-price", type=float, default=None)
151
+ sh_search.add_argument("--max-price", type=float, default=None)
152
+ sh_search.add_argument("--max-products", type=int, default=25)
153
+
154
+ # 4. travel
155
+ p_travel = domains.add_parser("travel", help="Google Flights & Google Hotels intelligence.")
156
+ s_travel = p_travel.add_subparsers(dest="action", required=True)
157
+
158
+ tr_fl = s_travel.add_parser("flights", parents=[leaf_common], help="Search Google Flights itineraries.")
159
+ tr_fl.add_argument("--from", "--origin", dest="from_origin", required=True, help="Origin IATA or city (e.g. JFK).")
160
+ tr_fl.add_argument("--to", "--destination", dest="to_destination", required=True, help="Destination IATA or city (e.g. LHR).")
161
+ tr_fl.add_argument("--departure-date", default=None, help="Departure date (YYYY-MM-DD).")
162
+ tr_fl.add_argument("--return-date", default=None, help="Optional return date (YYYY-MM-DD).")
163
+ tr_fl.add_argument("--cabin", choices=("economy", "premium_economy", "business", "first"), default="economy")
164
+ tr_fl.add_argument("--adults", type=int, default=1)
165
+ tr_fl.add_argument("--sort-by", choices=("best", "cheapest", "departure_time", "arrival_time", "duration", "emissions"), default="best")
166
+ tr_fl.add_argument("--currency", default="USD")
167
+ tr_fl.add_argument("--max-flights", type=int, default=20)
168
+
169
+ tr_ht = s_travel.add_parser("hotels", parents=[leaf_common], help="Search Google Hotels & OTA rates.")
170
+ tr_ht.add_argument("locations", nargs="+", help="Hotel destinations or property queries.")
171
+ tr_ht.add_argument("--check-in", dest="check_in_date", default=None, help="Check-in date (YYYY-MM-DD).")
172
+ tr_ht.add_argument("--check-out", dest="check_out_date", default=None, help="Check-out date (YYYY-MM-DD).")
173
+ tr_ht.add_argument("--adults", type=int, default=2)
174
+ tr_ht.add_argument("--currency", default="USD")
175
+ tr_ht.add_argument("--max-hotels", type=int, default=20)
176
+
177
+ # 5. ai
178
+ p_ai = domains.add_parser("ai", help="Google AI Overviews, AI Mode, and GEO Share-of-Voice.")
179
+ s_ai = p_ai.add_subparsers(dest="action", required=True)
180
+
181
+ ai_ov = s_ai.add_parser("overviews", parents=[leaf_common], help="Scrape Google Search AI Overviews.")
182
+ ai_ov.add_argument("queries", nargs="+", help="Search queries.")
183
+ ai_ov.add_argument("--country", default="US", help="Country code (default: US).")
184
+ ai_ov.add_argument("--location", default="", help="Optional city/region geo string.")
185
+ ai_ov.add_argument("--target-domain", action="append", dest="target_domains", help="Brand domain(s) to audit.")
186
+ ai_ov.add_argument("--max-queries", type=int, default=25)
187
+
188
+ ai_md = s_ai.add_parser("ai-mode", parents=[leaf_common], help="Query Google AI Mode.")
189
+ ai_md.add_argument("queries", nargs="+", help="Prompts/queries.")
190
+ ai_md.add_argument("--country", default="US")
191
+ ai_md.add_argument("--location", default="")
192
+ ai_md.add_argument("--target-domain", action="append", dest="target_domains")
193
+ ai_md.add_argument("--max-queries", type=int, default=25)
194
+
195
+ ai_sov = s_ai.add_parser("sov", parents=[leaf_common], help="Run GEO Brand Share-of-Voice audit.")
196
+ ai_sov.add_argument("queries", nargs="+", help="Queries to evaluate.")
197
+ ai_sov.add_argument("--brand", required=True, help="Target brand domain (e.g. hubspot.com).")
198
+ ai_sov.add_argument("--competitors", nargs="*", default=None, help="Competitor domains.")
199
+ ai_sov.add_argument("--surface", choices=("both", "overviews", "ai_mode"), default="both")
200
+ ai_sov.add_argument("--country", default="US")
201
+
202
+ # 6. news
203
+ p_news = domains.add_parser("news", help="Google News search and RAG citation context.")
204
+ s_news = p_news.add_subparsers(dest="action", required=True)
205
+ nw_s = s_news.add_parser("search", parents=[leaf_common], help="Search Google News articles.")
206
+ nw_s.add_argument("queries", nargs="+", help="News search queries.")
207
+ nw_s.add_argument("--country", default="us")
208
+ nw_s.add_argument("--time-range", choices=("any", "1h", "24h", "7d", "30d", "1y"), default="any")
209
+ nw_s.add_argument("--extract-content", action="store_true", help="Extract full article text.")
210
+ nw_s.add_argument("--max-articles", type=int, default=25)
211
+
212
+ # 7. gmaps
213
+ p_gm = domains.add_parser("gmaps", help="Google Maps leads, reviews, photos, and contributors.")
214
+ s_gm = p_gm.add_subparsers(dest="action", required=True)
215
+ gm_l = s_gm.add_parser("leads", parents=[leaf_common], help="Extract B2B leads from Google Maps.")
216
+ gm_l.add_argument("queries", nargs="+", help="Category + city queries.")
217
+ gm_l.add_argument("--max-places", type=int, default=20)
218
+ gm_l.add_argument("--region", default="us")
219
+
220
+ gm_r = s_gm.add_parser("reviews", parents=[leaf_common], help="Extract Google Maps place reviews.")
221
+ gm_r.add_argument("targets", nargs="+", help="Place URLs, Place IDs, or search queries.")
222
+ gm_r.add_argument("--max-reviews", type=int, default=50)
223
+ gm_r.add_argument("--sort", choices=("newest", "lowest_rating", "highest_rating", "most_relevant"), default="newest")
224
+
225
+ # 8. ali1688
226
+ p_1688 = domains.add_parser("ali1688", help="1688.com factory & cross-border sourcing.")
227
+ s_1688 = p_1688.add_subparsers(dest="action", required=True)
228
+ a16_s = s_1688.add_parser("search", parents=[leaf_common], help="Search 1688.com factory offers.")
229
+ a16_s.add_argument("keyword", help="Search keyword.")
230
+ a16_s.add_argument("--province", default=None)
231
+ a16_s.add_argument("--max-items", type=int, default=20)
232
+
233
+ # 9. goofish
234
+ p_gf = domains.add_parser("goofish", help="Goofish / Xianyu C2C marketplace.")
235
+ s_gf = p_gf.add_subparsers(dest="action", required=True)
236
+ gf_s = s_gf.add_parser("search", parents=[leaf_common], help="Search Goofish listings.")
237
+ gf_s.add_argument("keyword", help="Search keyword.")
238
+ gf_s.add_argument("--translate", action="store_true", help="Translate English slang offline.")
239
+ gf_s.add_argument("--prefer-standby", action="store_true", help="Use warm Apify Standby fast-path.")
240
+ gf_s.add_argument("--max-items", type=int, default=20)
241
+
242
+ # 10. rednote
243
+ p_rn = domains.add_parser("rednote", help="RedNote / Xiaohongshu social commerce.")
244
+ s_rn = p_rn.add_subparsers(dest="action", required=True)
245
+ rn_s = s_rn.add_parser("search", parents=[leaf_common], help="Search RedNote posts.")
246
+ rn_s.add_argument("keywords", nargs="+", help="Search keywords.")
247
+ rn_s.add_argument("--max-items", type=int, default=20)
248
+
249
+ # 11. reddit
250
+ p_rd = domains.add_parser("reddit", help="Reddit search, subreddits, posts, and comments.")
251
+ s_rd = p_rd.add_subparsers(dest="action", required=True)
252
+ rd_s = s_rd.add_parser("search", parents=[leaf_common], help="Search Reddit.")
253
+ rd_s.add_argument("query", help="Search query.")
254
+ rd_s.add_argument("--subreddit", default="")
255
+ rd_s.add_argument("--max-items", type=int, default=20)
256
+
257
+ # 12. generic run
258
+ p_run = domains.add_parser("run", parents=[leaf_common], help="Run any UnitBytes actor slug or /v1 endpoint.")
259
+ p_run.add_argument("target", help="Actor slug (e.g. offerup-scraper) or endpoint (e.g. offerup/search).")
260
+ p_run.add_argument("--input", dest="json_input", default="{}", help="JSON object payload (default: '{}').")
261
+ p_run.add_argument("--method", choices=("GET", "POST"), default=None, help="Optional HTTP method override.")
262
+
263
+ return parser
264
+
265
+
266
+ def _write_output(rendered: str, output_path: str | None) -> None:
267
+ if output_path:
268
+ target = Path(output_path)
269
+ target.parent.mkdir(parents=True, exist_ok=True)
270
+ target.write_text(rendered + ("\n" if rendered and not rendered.endswith("\n") else ""), encoding="utf-8")
271
+ if os.name != "nt":
272
+ try:
273
+ os.chmod(target, 0o600)
274
+ except OSError:
275
+ pass
276
+ else:
277
+ if rendered:
278
+ sys.stdout.write(rendered + "\n")
279
+
280
+
281
+ def main(
282
+ argv: Sequence[str] | None = None,
283
+ *,
284
+ transport: Transport | None = None,
285
+ ) -> int:
286
+ parser = build_parser()
287
+ args = parser.parse_args(list(argv) if argv is not None else None)
288
+
289
+ if not args.domain:
290
+ parser.print_help()
291
+ return 0
292
+
293
+ try:
294
+ ub = UnitBytes(
295
+ api_key=args.api_key,
296
+ provider=args.provider,
297
+ base_url=args.base_url,
298
+ rapidapi_host=args.rapidapi_host,
299
+ timeout_secs=args.timeout_secs,
300
+ max_total_charge_usd=args.max_total_charge_usd,
301
+ allow_custom_endpoints=args.allow_custom_endpoints,
302
+ transport=transport,
303
+ )
304
+
305
+ result: Any
306
+ if args.domain == "trends":
307
+ if args.action == "trending-now":
308
+ result = ub.trends.trending_now(
309
+ geo=args.geo,
310
+ time_window=args.window,
311
+ trending_hours=args.hours,
312
+ language=args.language,
313
+ max_events=args.max_events,
314
+ )
315
+ elif args.action == "interest-over-time":
316
+ result = ub.trends.interest_over_time(
317
+ args.keywords,
318
+ timeframe=args.timeframe,
319
+ geo=args.geo,
320
+ gprop=args.gprop,
321
+ as_dataframe=False,
322
+ )
323
+ else:
324
+ result = ub.trends.breakouts(
325
+ args.keywords or None,
326
+ timeframe=args.timeframe,
327
+ geo=args.geo,
328
+ min_growth_pct=args.min_growth,
329
+ )
330
+ elif args.domain == "jobs":
331
+ if args.action == "search":
332
+ result = ub.jobs.search(
333
+ args.queries,
334
+ locations=args.locations,
335
+ country=args.country,
336
+ date_posted=args.date_posted,
337
+ remote_only=args.remote_only,
338
+ direct_ats_only=args.direct_ats_only,
339
+ only_new=args.only_new,
340
+ state_file=args.state_file,
341
+ max_jobs=args.max_jobs,
342
+ )
343
+ else:
344
+ result = ub.jobs.aggregate_hiring_companies(
345
+ args.queries,
346
+ locations=args.locations,
347
+ country=args.country,
348
+ max_jobs=args.max_jobs,
349
+ )
350
+ elif args.domain == "shopping":
351
+ result = ub.shopping.search(
352
+ args.queries,
353
+ country=args.country,
354
+ sort_by=args.sort_by,
355
+ min_price=args.min_price,
356
+ max_price=args.max_price,
357
+ max_products=args.max_products,
358
+ )
359
+ elif args.domain == "travel":
360
+ if args.action == "flights":
361
+ result = ub.travel.flights(
362
+ from_origin=args.from_origin,
363
+ to_destination=args.to_destination,
364
+ departure_date=args.departure_date,
365
+ return_date=args.return_date,
366
+ cabin_class=args.cabin,
367
+ adults=args.adults,
368
+ sort_by=args.sort_by,
369
+ currency=args.currency,
370
+ max_flights=args.max_flights,
371
+ )
372
+ else:
373
+ result = ub.travel.hotels(
374
+ args.locations,
375
+ check_in_date=args.check_in_date,
376
+ check_out_date=args.check_out_date,
377
+ adults=args.adults,
378
+ currency=args.currency,
379
+ max_hotels=args.max_hotels,
380
+ )
381
+ elif args.domain == "ai":
382
+ if args.action == "overviews":
383
+ result = ub.ai.overviews(
384
+ args.queries,
385
+ country=args.country,
386
+ location=args.location,
387
+ target_domains=args.target_domains,
388
+ max_queries=args.max_queries,
389
+ )
390
+ elif args.action == "ai-mode":
391
+ result = ub.ai.ai_mode(
392
+ args.queries,
393
+ country=args.country,
394
+ location=args.location,
395
+ target_domains=args.target_domains,
396
+ max_queries=args.max_queries,
397
+ )
398
+ else:
399
+ report = ub.ai.audit_brand_share_of_voice(
400
+ args.queries,
401
+ args.brand,
402
+ competitor_domains=args.competitors,
403
+ surface=args.surface,
404
+ country=args.country,
405
+ )
406
+ result = report.query_matrix if args.output_format == "csv" else report.to_dict()
407
+ elif args.domain == "news":
408
+ result = ub.news.search(
409
+ args.queries,
410
+ country=args.country,
411
+ time_range=args.time_range,
412
+ extract_article_content=args.extract_content,
413
+ max_articles=args.max_articles,
414
+ )
415
+ elif args.domain == "gmaps":
416
+ if args.action == "leads":
417
+ result = ub.gmaps.leads(args.queries, max_places_per_query=args.max_places, region=args.region)
418
+ else:
419
+ result = ub.gmaps.reviews(args.targets, max_reviews_per_place=args.max_reviews, sort=args.sort)
420
+ elif args.domain == "ali1688":
421
+ result = ub.ali1688.search(args.keyword, province=args.province, max_items=args.max_items)
422
+ elif args.domain == "goofish":
423
+ result = ub.goofish.search(
424
+ args.keyword,
425
+ max_items=args.max_items,
426
+ translate_keywords=args.translate,
427
+ prefer_standby=True if args.prefer_standby else None,
428
+ )
429
+ elif args.domain == "rednote":
430
+ result = ub.rednote.search(args.keywords, max_items=args.max_items)
431
+ elif args.domain == "reddit":
432
+ result = ub.reddit.search(args.query, subreddit=args.subreddit, max_items=args.max_items)
433
+ elif args.domain == "run":
434
+ parsed_input = json.loads(args.json_input or "{}")
435
+ if not isinstance(parsed_input, dict):
436
+ raise ValueError("--input must be a JSON object.")
437
+ result = ub.run(args.target, parsed_input, method=args.method)
438
+ else:
439
+ parser.print_help()
440
+ return 2
441
+
442
+ rendered = format_records(result, fmt=args.output_format)
443
+ _write_output(rendered, args.output_path)
444
+ return 0
445
+ except (AuthenticationError, ConfigurationError, ValueError, json.JSONDecodeError) as exc:
446
+ sys.stderr.write(f"Error: {redact_secrets(str(exc), (args.api_key,))}\n")
447
+ return 2
448
+ except UnitBytesError as exc:
449
+ sys.stderr.write(f"Error: {redact_secrets(str(exc), (args.api_key,))}\n")
450
+ return 1
451
+
452
+
453
+ if __name__ == "__main__": # pragma: no cover
454
+ raise SystemExit(main())