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/__init__.py ADDED
@@ -0,0 +1,43 @@
1
+ """`unitbytes` — Unified, zero-dependency, provider-agnostic Python SDK & CLI for UnitBytes web data APIs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from ._exceptions import (
6
+ AuthenticationError,
7
+ ConfigurationError,
8
+ ProviderError,
9
+ RateLimitError,
10
+ UnitBytesError,
11
+ )
12
+ from ._serialization import format_records, sanitize_csv_cell
13
+ from ._transports import (
14
+ DEFAULT_RAPIDAPI_HOSTS,
15
+ ApifyTransport,
16
+ CloudGatewayTransport,
17
+ RapidApiTransport,
18
+ Transport,
19
+ ZylaTransport,
20
+ )
21
+ from .client import UnitBytes
22
+ from .trends import TrendReq
23
+
24
+ __version__ = "1.0.0"
25
+
26
+ __all__ = [
27
+ "__version__",
28
+ "UnitBytes",
29
+ "TrendReq",
30
+ "Transport",
31
+ "ApifyTransport",
32
+ "CloudGatewayTransport",
33
+ "RapidApiTransport",
34
+ "ZylaTransport",
35
+ "DEFAULT_RAPIDAPI_HOSTS",
36
+ "UnitBytesError",
37
+ "AuthenticationError",
38
+ "ConfigurationError",
39
+ "RateLimitError",
40
+ "ProviderError",
41
+ "format_records",
42
+ "sanitize_csv_cell",
43
+ ]
@@ -0,0 +1,94 @@
1
+ """Exception hierarchy and credential scrubbing utilities for the `unitbytes` SDK."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import Iterable
7
+
8
+ SIGNUP_URL = "https://unitbytes.com/actors/"
9
+
10
+ _SECRET_PATTERNS: tuple[re.Pattern[str], ...] = (
11
+ re.compile(r"apify_api_[A-Za-z0-9_-]{4,}"),
12
+ re.compile(r"\bub_(?:live_|test_)?[A-Za-z0-9._~-]{4,}"),
13
+ re.compile(r"\bzyla_[A-Za-z0-9._~-]{4,}"),
14
+ re.compile(r"(Bearer\s+)[A-Za-z0-9._~+/=-]{6,}", re.IGNORECASE),
15
+ re.compile(
16
+ r"((?:X-RapidAPI-Key|X-API-Key|Authorization)\s*[:=]\s*)['\"]?[^\s,'\"&]+['\"]?",
17
+ re.IGNORECASE,
18
+ ),
19
+ re.compile(
20
+ r"([?&](?:token|api_key|apiKey|apikey|access_token)=)[^&\s'\"#]+",
21
+ re.IGNORECASE,
22
+ ),
23
+ )
24
+
25
+
26
+ def redact_secrets(text: str, extra_secrets: Iterable[str | None] = ()) -> str:
27
+ """Scrub API keys, bearer tokens, and header credentials from diagnostic strings."""
28
+ if not text:
29
+ return ""
30
+ scrubbed = str(text)
31
+
32
+ for secret in extra_secrets:
33
+ if secret:
34
+ cleaned = str(secret).strip()
35
+ if len(cleaned) >= 4 and cleaned in scrubbed:
36
+ scrubbed = scrubbed.replace(cleaned, "[REDACTED]")
37
+
38
+ scrubbed = _SECRET_PATTERNS[0].sub("[REDACTED]", scrubbed)
39
+ scrubbed = _SECRET_PATTERNS[1].sub("[REDACTED]", scrubbed)
40
+ scrubbed = _SECRET_PATTERNS[2].sub("[REDACTED]", scrubbed)
41
+ scrubbed = _SECRET_PATTERNS[3].sub(r"\1[REDACTED]", scrubbed)
42
+ scrubbed = _SECRET_PATTERNS[4].sub(r"\1[REDACTED]", scrubbed)
43
+ scrubbed = _SECRET_PATTERNS[5].sub(r"\1[REDACTED]", scrubbed)
44
+ return scrubbed
45
+
46
+
47
+ class UnitBytesError(RuntimeError):
48
+ """Base exception for all `unitbytes` SDK errors with automatic credential scrubbing."""
49
+
50
+ def __init__(
51
+ self,
52
+ message: str,
53
+ *,
54
+ status_code: int | None = None,
55
+ code: str | None = None,
56
+ run_id: str | None = None,
57
+ secrets: Iterable[str | None] = (),
58
+ ) -> None:
59
+ safe_message = redact_secrets(str(message), secrets)
60
+ super().__init__(safe_message)
61
+ self.message = safe_message
62
+ self.status_code = status_code
63
+ self.code = code
64
+ self.run_id = run_id
65
+
66
+ def __str__(self) -> str:
67
+ return redact_secrets(self.message)
68
+
69
+ def __repr__(self) -> str:
70
+ cls_name = self.__class__.__name__
71
+ parts = [repr(redact_secrets(self.message))]
72
+ if self.status_code is not None:
73
+ parts.append(f"status_code={self.status_code!r}")
74
+ if self.code is not None:
75
+ parts.append(f"code={self.code!r}")
76
+ if self.run_id is not None:
77
+ parts.append(f"run_id={self.run_id!r}")
78
+ return f"{cls_name}({', '.join(parts)})"
79
+
80
+
81
+ class AuthenticationError(UnitBytesError):
82
+ """Raised when API credentials are missing, malformed, or rejected (HTTP 401/403)."""
83
+
84
+
85
+ class ConfigurationError(UnitBytesError):
86
+ """Raised when provider settings, endpoints, or URL schemes are invalid or untrusted."""
87
+
88
+
89
+ class RateLimitError(UnitBytesError):
90
+ """Raised when an upstream provider returns HTTP 429 Too Many Requests."""
91
+
92
+
93
+ class ProviderError(UnitBytesError):
94
+ """Raised when an upstream provider or actor run fails, times out, or attempts a redirect."""
@@ -0,0 +1,272 @@
1
+ """Shared JSON/JSONL/CSV serialization (with header & cell formula sanitization), atomic 0600 watchlist state persistence, and optional pandas helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ from decimal import Decimal, InvalidOperation
7
+ import io
8
+ import json
9
+ import os
10
+ from pathlib import Path
11
+ import re
12
+ import tempfile
13
+ from datetime import datetime, timezone
14
+ from typing import Any, Callable, Iterable, Mapping, Sequence
15
+
16
+ _CSV_FORMULA_PREFIXES = ("=", "+", "-", "@", "\t", "\r", "\n")
17
+ _CSV_LEADING_SPACE_FORMULA_CHARS = ("=", "+", "-", "@")
18
+ _CSV_NEGATIVE_NUMBER_RE = re.compile(r"^-[0-9]+(?:\.[0-9]+)?$")
19
+ _PANDAS_MISSING_MSG = (
20
+ "pandas is required when as_dataframe=True. "
21
+ "Install with `pip install 'unitbytes[pandas]'` or pass as_dataframe=False."
22
+ )
23
+
24
+
25
+ def try_import_pandas() -> Any | None:
26
+ """Import `pandas` if installed in the caller's environment without making it a runtime dependency."""
27
+ try:
28
+ import pandas as pd # type: ignore[import-not-found]
29
+
30
+ return pd
31
+ except ImportError:
32
+ return None
33
+
34
+
35
+ def require_pandas() -> Any:
36
+ """Return `pandas` module or raise a clear `ImportError` when `as_dataframe=True`."""
37
+ pd = try_import_pandas()
38
+ if pd is None:
39
+ raise ImportError(_PANDAS_MISSING_MSG)
40
+ return pd
41
+
42
+
43
+ def normalize_max_charge_usd(value: float | int | Decimal | None) -> Decimal | None:
44
+ """Validate `max_total_charge_usd` as a finite positive `Decimal`."""
45
+ if value is None:
46
+ return None
47
+ if isinstance(value, bool) or not isinstance(value, (int, float, Decimal)):
48
+ raise ValueError("max_total_charge_usd must be a positive number or None.")
49
+ try:
50
+ dec = Decimal(str(value))
51
+ except InvalidOperation as exc:
52
+ raise ValueError(f"Invalid max_total_charge_usd {value!r}.") from exc
53
+ if not dec.is_finite() or dec <= 0:
54
+ raise ValueError(f"max_total_charge_usd must be > 0, got {value!r}.")
55
+ return dec
56
+
57
+
58
+ def format_decimal_param(value: Decimal) -> str:
59
+ """Format a positive `Decimal` cleanly for URL query parameters without scientific notation."""
60
+ normalized = format(value.normalize(), "f")
61
+ if "." in normalized:
62
+ normalized = normalized.rstrip("0").rstrip(".")
63
+ return normalized or "0"
64
+
65
+
66
+ def sanitize_csv_cell(val: str) -> str:
67
+ """Neutralize spreadsheet formula injection (`=`, `+`, `-`, `@`, tab/CR/LF) on headers and cells."""
68
+ if not val:
69
+ return val
70
+ if val.startswith(_CSV_FORMULA_PREFIXES):
71
+ if _CSV_NEGATIVE_NUMBER_RE.fullmatch(val.strip()):
72
+ return val
73
+ return f"'{val}"
74
+ lstripped = val.lstrip(" ")
75
+ if lstripped and lstripped != val and lstripped.startswith(_CSV_LEADING_SPACE_FORMULA_CHARS):
76
+ if _CSV_NEGATIVE_NUMBER_RE.fullmatch(lstripped.strip()):
77
+ return val
78
+ return f"'{val}"
79
+ return val
80
+
81
+
82
+ def _flatten_for_csv(record: Mapping[str, Any]) -> dict[str, str]:
83
+ row: dict[str, str] = {}
84
+ for key, value in record.items():
85
+ safe_key = sanitize_csv_cell(str(key))
86
+ if value is None:
87
+ row[safe_key] = ""
88
+ elif isinstance(value, Mapping):
89
+ for sub_key, sub_val in value.items():
90
+ col = sanitize_csv_cell(f"{key}.{sub_key}")
91
+ if sub_val is None:
92
+ row[col] = ""
93
+ elif isinstance(sub_val, (Mapping, list, tuple)):
94
+ row[col] = sanitize_csv_cell(json.dumps(sub_val, ensure_ascii=False, default=str))
95
+ else:
96
+ row[col] = sanitize_csv_cell(str(sub_val))
97
+ elif isinstance(value, (list, tuple)):
98
+ row[safe_key] = sanitize_csv_cell(json.dumps(value, ensure_ascii=False, default=str))
99
+ else:
100
+ row[safe_key] = sanitize_csv_cell(str(value))
101
+ return row
102
+
103
+
104
+ def format_records(records: Any, fmt: str = "json") -> str:
105
+ """Serialize output records (dicts, lists, dataclasses, or DataFrames) as `json`, `jsonl`, or `csv`."""
106
+ mode = str(fmt or "json").strip().lower()
107
+ if mode not in {"json", "jsonl", "csv"}:
108
+ raise ValueError(f"Unsupported format {fmt!r}. Expected 'json', 'jsonl', or 'csv'.")
109
+
110
+ if hasattr(records, "to_dict") and not isinstance(records, Mapping):
111
+ if hasattr(records, "reset_index"):
112
+ records = records.reset_index().to_dict(orient="records")
113
+ else:
114
+ records = records.to_dict()
115
+
116
+ if mode == "json":
117
+ return json.dumps(records, ensure_ascii=False, indent=2, default=str)
118
+
119
+ items: list[dict[str, Any]]
120
+ if isinstance(records, Mapping):
121
+ items = [dict(records)]
122
+ elif isinstance(records, Sequence) and not isinstance(records, (str, bytes)):
123
+ items = [
124
+ dict(item.to_dict())
125
+ if hasattr(item, "to_dict") and callable(item.to_dict)
126
+ else (dict(item) if isinstance(item, Mapping) else {"value": item})
127
+ for item in records
128
+ ]
129
+ else:
130
+ items = [{"value": records}]
131
+
132
+ if mode == "jsonl":
133
+ return "\n".join(json.dumps(item, ensure_ascii=False, default=str) for item in items)
134
+
135
+ if not items:
136
+ return ""
137
+
138
+ flat_rows = [_flatten_for_csv(item) for item in items]
139
+ fieldnames: list[str] = []
140
+ seen: set[str] = set()
141
+ for row in flat_rows:
142
+ for col in row:
143
+ safe_col = sanitize_csv_cell(col)
144
+ if safe_col not in seen:
145
+ seen.add(safe_col)
146
+ fieldnames.append(safe_col)
147
+
148
+ buf = io.StringIO()
149
+ writer = csv.DictWriter(buf, fieldnames=fieldnames, lineterminator="\n")
150
+ writer.writeheader()
151
+ writer.writerows(flat_rows)
152
+ return buf.getvalue().rstrip("\n")
153
+
154
+
155
+ def load_watchlist_state(state_file: str | os.PathLike[str]) -> list[str]:
156
+ """Load ordered seen IDs from a local JSON watchlist state file."""
157
+ path = Path(state_file)
158
+ if not path.exists():
159
+ return []
160
+ raw_text = path.read_text(encoding="utf-8").strip()
161
+ if not raw_text:
162
+ return []
163
+ try:
164
+ data = json.loads(raw_text)
165
+ except json.JSONDecodeError:
166
+ return []
167
+
168
+ raw_ids: Iterable[Any]
169
+ if isinstance(data, Mapping):
170
+ raw_ids = (
171
+ data.get("seen_ids")
172
+ or data.get("seen_job_ids")
173
+ or data.get("seenIds")
174
+ or []
175
+ )
176
+ elif isinstance(data, list):
177
+ raw_ids = data
178
+ else:
179
+ return []
180
+
181
+ ordered: list[str] = []
182
+ seen: set[str] = set()
183
+ for val in raw_ids:
184
+ sid = str(val).strip()
185
+ if sid and sid not in seen:
186
+ seen.add(sid)
187
+ ordered.append(sid)
188
+ return ordered
189
+
190
+
191
+ def save_watchlist_state(
192
+ state_file: str | os.PathLike[str],
193
+ seen_ids: Iterable[str],
194
+ *,
195
+ id_field: str = "seen_ids",
196
+ max_entries: int = 50_000,
197
+ ) -> Path:
198
+ """Atomically persist seen IDs to `state_file` with strict `0600` file permissions."""
199
+ path = Path(state_file)
200
+ path.parent.mkdir(parents=True, exist_ok=True)
201
+
202
+ deduped: list[str] = []
203
+ seen_set: set[str] = set()
204
+ for val in seen_ids:
205
+ sid = str(val).strip()
206
+ if sid and sid not in seen_set:
207
+ seen_set.add(sid)
208
+ deduped.append(sid)
209
+
210
+ if max_entries > 0 and len(deduped) > max_entries:
211
+ deduped = deduped[-max_entries:]
212
+
213
+ payload: dict[str, Any] = {
214
+ "version": 1,
215
+ "updated_at": datetime.now(timezone.utc).isoformat(),
216
+ "count": len(deduped),
217
+ id_field: deduped,
218
+ }
219
+ if id_field != "seen_ids":
220
+ payload["seen_ids"] = deduped
221
+ serialized = json.dumps(payload, ensure_ascii=False, indent=2) + "\n"
222
+
223
+ fd, tmp_name = tempfile.mkstemp(
224
+ prefix=f".{path.name}.",
225
+ suffix=".tmp",
226
+ dir=str(path.parent),
227
+ )
228
+ tmp_path = Path(tmp_name)
229
+ try:
230
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
231
+ fh.write(serialized)
232
+ if os.name != "nt":
233
+ os.chmod(tmp_path, 0o600)
234
+ os.replace(tmp_path, path)
235
+ if os.name != "nt":
236
+ os.chmod(path, 0o600)
237
+ finally:
238
+ if tmp_path.exists():
239
+ tmp_path.unlink(missing_ok=True)
240
+ return path
241
+
242
+
243
+ def filter_unseen_by_key(
244
+ records: Sequence[Mapping[str, Any]],
245
+ *,
246
+ key_fn: Callable[[Mapping[str, Any]], str | None],
247
+ state_file: str | os.PathLike[str],
248
+ id_field: str = "seen_ids",
249
+ max_entries: int = 50_000,
250
+ max_return: int | None = None,
251
+ ) -> list[dict[str, Any]]:
252
+ """Filter records to previously unseen keys and atomically persist updated `0600` state."""
253
+ existing = load_watchlist_state(state_file)
254
+ seen_set = set(existing)
255
+ combined = list(existing)
256
+ unseen: list[dict[str, Any]] = []
257
+
258
+ for rec in records:
259
+ if not isinstance(rec, Mapping):
260
+ continue
261
+ rid = key_fn(rec)
262
+ if rid:
263
+ if rid in seen_set:
264
+ continue
265
+ seen_set.add(rid)
266
+ combined.append(rid)
267
+ unseen.append(dict(rec))
268
+ if max_return is not None and len(unseen) >= max_return:
269
+ break
270
+
271
+ save_watchlist_state(state_file, combined, id_field=id_field, max_entries=max_entries)
272
+ return unseen