twitterviewer 0.1.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.
@@ -0,0 +1,73 @@
1
+ """Python SDK for the TwitterViewer API (https://twitterviewer.ai)."""
2
+
3
+ from ._base import DEFAULT_BASE_URL, DEFAULT_MAX_RETRIES, DEFAULT_TIMEOUT, MAX_RETRY_AFTER_SEC
4
+ from ._client import AsyncTwitterViewer, TwitterViewer
5
+ from ._version import __version__
6
+ from .errors import (
7
+ APIConnectionError,
8
+ APIError,
9
+ APITimeoutError,
10
+ ErrorCode,
11
+ InvalidResponseError,
12
+ TwitterViewerError,
13
+ )
14
+ from .params import JsonFormat, Paper, Scope, Stats, TextFormat
15
+ from .types import (
16
+ Article,
17
+ Card,
18
+ ConvertResult,
19
+ CreditBalance,
20
+ Credits,
21
+ Media,
22
+ PdfDocument,
23
+ PlanCredits,
24
+ Poll,
25
+ PollOption,
26
+ PurchasedCredits,
27
+ RepliesResult,
28
+ ReplyTarget,
29
+ TextDocument,
30
+ Tweet,
31
+ User,
32
+ UserLite,
33
+ VideoVariant,
34
+ )
35
+
36
+ __all__ = [
37
+ "DEFAULT_BASE_URL",
38
+ "DEFAULT_MAX_RETRIES",
39
+ "DEFAULT_TIMEOUT",
40
+ "MAX_RETRY_AFTER_SEC",
41
+ "APIConnectionError",
42
+ "APIError",
43
+ "APITimeoutError",
44
+ "Article",
45
+ "AsyncTwitterViewer",
46
+ "Card",
47
+ "ConvertResult",
48
+ "CreditBalance",
49
+ "Credits",
50
+ "ErrorCode",
51
+ "InvalidResponseError",
52
+ "JsonFormat",
53
+ "Media",
54
+ "Paper",
55
+ "PdfDocument",
56
+ "PlanCredits",
57
+ "Poll",
58
+ "PollOption",
59
+ "PurchasedCredits",
60
+ "RepliesResult",
61
+ "ReplyTarget",
62
+ "Scope",
63
+ "Stats",
64
+ "TextDocument",
65
+ "TextFormat",
66
+ "Tweet",
67
+ "TwitterViewer",
68
+ "TwitterViewerError",
69
+ "User",
70
+ "UserLite",
71
+ "VideoVariant",
72
+ "__version__",
73
+ ]
twitterviewer/_base.py ADDED
@@ -0,0 +1,326 @@
1
+ """Request building, response parsing and the retry policy shared by both clients."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import random
7
+ import re
8
+ from collections.abc import Mapping
9
+ from dataclasses import dataclass
10
+ from typing import Any, Callable, Generic, Optional, TypeVar, Union
11
+ from urllib.parse import unquote
12
+
13
+ import httpx
14
+
15
+ from ._version import __version__
16
+ from .errors import (
17
+ APIConnectionError,
18
+ APIError,
19
+ APITimeoutError,
20
+ InvalidResponseError,
21
+ TwitterViewerError,
22
+ )
23
+ from .types import (
24
+ ConvertResult,
25
+ CreditBalance,
26
+ Credits,
27
+ PdfDocument,
28
+ RepliesResult,
29
+ TextDocument,
30
+ )
31
+
32
+ DEFAULT_BASE_URL = "https://twitterviewer.ai"
33
+ DEFAULT_TIMEOUT = 90.0
34
+ DEFAULT_MAX_RETRIES = 2
35
+ MAX_RETRY_AFTER_SEC = 120
36
+ """A longer wait asked by the server is not slept through: the error is raised instead."""
37
+
38
+ _BACKOFF_BASE_SEC = 0.5
39
+ _BACKOFF_MAX_SEC = 8.0
40
+ _ACCEPT_BY_FORMAT = {
41
+ "json": "application/json",
42
+ "markdown": "text/markdown",
43
+ "obsidian": "text/markdown",
44
+ "text": "text/plain",
45
+ "pdf": "application/pdf",
46
+ }
47
+ _HANDLE = re.compile(r"[A-Za-z0-9_]{1,15}")
48
+ _POST_ID = re.compile(r"[0-9]{1,25}")
49
+
50
+ T = TypeVar("T")
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class RequestSpec(Generic[T]):
55
+ method: str
56
+ path: str
57
+ parse: Callable[[httpx.Response], T]
58
+ accept: str = "application/json"
59
+ params: Optional[dict[str, str]] = None
60
+ body: Optional[dict[str, Any]] = None
61
+
62
+
63
+ class BaseClient:
64
+ def __init__(
65
+ self,
66
+ api_key: Optional[str],
67
+ base_url: Optional[str],
68
+ timeout: Optional[float],
69
+ max_retries: int,
70
+ ) -> None:
71
+ api_key = api_key or os.environ.get("TWITTERVIEWER_API_KEY")
72
+ if not api_key:
73
+ raise TwitterViewerError(
74
+ "No API key. Pass api_key= or set TWITTERVIEWER_API_KEY. "
75
+ "Create a key at https://twitterviewer.ai/account/api"
76
+ )
77
+ base_url = base_url or os.environ.get("TWITTERVIEWER_BASE_URL") or DEFAULT_BASE_URL
78
+ self._api_key = api_key
79
+ self.base_url = base_url.rstrip("/")
80
+ self.timeout = timeout
81
+ self.max_retries = max(0, max_retries)
82
+
83
+ def _request_kwargs(self, spec: RequestSpec[Any]) -> dict[str, Any]:
84
+ return {
85
+ "method": spec.method,
86
+ "url": self.base_url + spec.path,
87
+ "params": spec.params,
88
+ "json": spec.body,
89
+ "headers": {
90
+ "Authorization": f"Bearer {self._api_key}",
91
+ "Accept": spec.accept,
92
+ "User-Agent": f"twitterviewer-python/{__version__}",
93
+ },
94
+ "timeout": self.timeout,
95
+ }
96
+
97
+ def _delay_after_response(self, error: APIError, attempt: int) -> Optional[float]:
98
+ """Seconds to wait before retrying, or None to give up."""
99
+ if attempt >= self.max_retries:
100
+ return None
101
+ # 501 means no data source can serve the request; the server caches that answer.
102
+ if error.status != 429 and (error.status < 500 or error.status == 501):
103
+ return None
104
+ if error.retry_after_sec is None:
105
+ return _backoff(attempt)
106
+ if error.retry_after_sec > MAX_RETRY_AFTER_SEC:
107
+ return None
108
+ return float(error.retry_after_sec)
109
+
110
+ def _delay_after_transport_error(self, attempt: int) -> Optional[float]:
111
+ return _backoff(attempt) if attempt < self.max_retries else None
112
+
113
+
114
+ def _backoff(attempt: int) -> float:
115
+ delay = min(_BACKOFF_BASE_SEC * 2.0**attempt, _BACKOFF_MAX_SEC)
116
+ return delay * random.uniform(0.75, 1.0)
117
+
118
+
119
+ def connection_error(error: httpx.HTTPError) -> APIConnectionError:
120
+ if isinstance(error, httpx.TimeoutException):
121
+ return APITimeoutError(f"Request timed out: {error!r}")
122
+ return APIConnectionError(f"Request failed: {error!r}")
123
+
124
+
125
+ def _int(value: Any) -> Optional[int]:
126
+ try:
127
+ return int(value)
128
+ except (TypeError, ValueError):
129
+ return None
130
+
131
+
132
+ def api_error(response: httpx.Response) -> APIError:
133
+ code = ""
134
+ message = f"HTTP {response.status_code} {response.reason_phrase}".strip()
135
+ retry_after: Optional[int] = None
136
+ details: Optional[dict[str, Any]] = None
137
+ try:
138
+ error = response.json()["error"]
139
+ code = str(error["code"])
140
+ message = str(error.get("message") or message)
141
+ retry_after = _int(error.get("retryAfterSec"))
142
+ if isinstance(error.get("details"), dict):
143
+ details = error["details"]
144
+ except (ValueError, KeyError, TypeError, AttributeError):
145
+ pass # not an API error body
146
+ if retry_after is None:
147
+ retry_after = _int(response.headers.get("retry-after"))
148
+ return APIError(response.status_code, code, message, retry_after, details)
149
+
150
+
151
+ # Response parsers
152
+
153
+
154
+ def _rate_limit(response: httpx.Response) -> Optional[int]:
155
+ return _int(response.headers.get("x-ratelimit-remaining"))
156
+
157
+
158
+ def _header_credits(response: httpx.Response) -> Optional[Credits]:
159
+ charged = _int(response.headers.get("x-credits-charged"))
160
+ remaining = _int(response.headers.get("x-credits-remaining"))
161
+ if charged is None or remaining is None:
162
+ return None
163
+ return Credits(charged=charged, remaining=remaining)
164
+
165
+
166
+ def _json_parser(
167
+ model: Callable[[Mapping[str, Any], Optional[int]], T],
168
+ ) -> Callable[[httpx.Response], T]:
169
+ def parse(response: httpx.Response) -> T:
170
+ try:
171
+ return model(response.json(), _rate_limit(response))
172
+ except (ValueError, KeyError, TypeError, AttributeError) as exc:
173
+ raise InvalidResponseError(f"Unexpected response body: {exc!r}") from exc
174
+
175
+ return parse
176
+
177
+
178
+ def _expect_content_type(response: httpx.Response, *prefixes: str) -> str:
179
+ content_type = str(response.headers.get("content-type", ""))
180
+ if not content_type.startswith(prefixes):
181
+ raise InvalidResponseError(f"Unexpected content type: {content_type!r}")
182
+ return content_type
183
+
184
+
185
+ def _parse_text(response: httpx.Response) -> TextDocument:
186
+ content_type = _expect_content_type(response, "text/markdown", "text/plain")
187
+ return TextDocument(
188
+ content=response.text,
189
+ content_type=content_type,
190
+ posts_returned=_int(response.headers.get("x-posts-returned")),
191
+ credits=_header_credits(response),
192
+ rate_limit_remaining=_rate_limit(response),
193
+ )
194
+
195
+
196
+ def _filename(disposition: str) -> Optional[str]:
197
+ # filename* carries the title in its own script (RFC 5987); filename is the ASCII fallback.
198
+ match = re.search(r"filename\*=UTF-8''([^;\s]+)", disposition, re.IGNORECASE)
199
+ if match:
200
+ return unquote(match.group(1))
201
+ match = re.search(r'filename="([^"]*)"', disposition)
202
+ return match.group(1) if match else None
203
+
204
+
205
+ def _parse_pdf(response: httpx.Response) -> PdfDocument:
206
+ _expect_content_type(response, "application/pdf")
207
+ return PdfDocument(
208
+ content=response.content,
209
+ filename=_filename(response.headers.get("content-disposition", "")),
210
+ credits=_header_credits(response),
211
+ rate_limit_remaining=_rate_limit(response),
212
+ )
213
+
214
+
215
+ # Operations
216
+
217
+
218
+ def _without_none(values: Mapping[str, Any]) -> dict[str, Any]:
219
+ return {key: value for key, value in values.items() if value is not None}
220
+
221
+
222
+ def _query(values: Mapping[str, Any]) -> dict[str, str]:
223
+ return {
224
+ key: ("true" if value else "false") if isinstance(value, bool) else str(value)
225
+ for key, value in values.items()
226
+ if value is not None
227
+ }
228
+
229
+
230
+ def _check_json_format(format: Optional[str]) -> str:
231
+ format = format or "json"
232
+ if format == "pdf":
233
+ raise ValueError("Use convert_pdf() for PDF output")
234
+ return format
235
+
236
+
237
+ def convert(url: str, format: Optional[str], **options: Any) -> RequestSpec[ConvertResult]:
238
+ return RequestSpec(
239
+ "POST",
240
+ "/api/v1/convert",
241
+ _json_parser(ConvertResult.from_dict),
242
+ body=_without_none({"url": url, "format": _check_json_format(format), **options}),
243
+ )
244
+
245
+
246
+ def convert_by_query(url: str, format: Optional[str], **options: Any) -> RequestSpec[ConvertResult]:
247
+ return RequestSpec(
248
+ "GET",
249
+ "/api/v1/convert",
250
+ _json_parser(ConvertResult.from_dict),
251
+ params=_query({"url": url, "format": _check_json_format(format), **options}),
252
+ )
253
+
254
+
255
+ def convert_text(url: str, format: str, **options: Any) -> RequestSpec[TextDocument]:
256
+ if format not in ("markdown", "obsidian", "text"):
257
+ raise ValueError('format must be "markdown", "obsidian" or "text"')
258
+ return RequestSpec(
259
+ "POST",
260
+ "/api/v1/convert",
261
+ _parse_text,
262
+ accept=_ACCEPT_BY_FORMAT[format],
263
+ body=_without_none({"url": url, "format": format, **options}),
264
+ )
265
+
266
+
267
+ def convert_pdf(url: str, **options: Any) -> RequestSpec[PdfDocument]:
268
+ return RequestSpec(
269
+ "POST",
270
+ "/api/v1/convert",
271
+ _parse_pdf,
272
+ accept=_ACCEPT_BY_FORMAT["pdf"],
273
+ body=_without_none({"url": url, "format": "pdf", **options}),
274
+ )
275
+
276
+
277
+ def replies(url: str, max: Optional[int]) -> RequestSpec[RepliesResult]:
278
+ return RequestSpec(
279
+ "GET",
280
+ "/api/v1/replies",
281
+ _json_parser(RepliesResult.from_dict),
282
+ params=_query({"url": url, "max": max}),
283
+ )
284
+
285
+
286
+ def credits() -> RequestSpec[CreditBalance]:
287
+ return RequestSpec("GET", "/api/v1/credits", _json_parser(CreditBalance.from_dict))
288
+
289
+
290
+ SwapResult = Union[TextDocument, ConvertResult, PdfDocument]
291
+
292
+
293
+ def _handle_segment(handle: str) -> str:
294
+ name = handle[1:] if handle.startswith("@") else handle
295
+ if not _HANDLE.fullmatch(name):
296
+ raise ValueError(f"Not an X username: {handle!r}")
297
+ return name
298
+
299
+
300
+ def _swap(path: str, format: str, options: Mapping[str, Any]) -> RequestSpec[SwapResult]:
301
+ if format not in _ACCEPT_BY_FORMAT:
302
+ raise ValueError(f"Unknown format: {format!r}")
303
+ parse: Callable[[httpx.Response], SwapResult]
304
+ if format == "json":
305
+ parse = _json_parser(ConvertResult.from_dict)
306
+ elif format == "pdf":
307
+ parse = _parse_pdf
308
+ else:
309
+ parse = _parse_text
310
+ return RequestSpec(
311
+ "GET",
312
+ path,
313
+ parse,
314
+ accept=_ACCEPT_BY_FORMAT[format],
315
+ params=_query({"format": format, **options}),
316
+ )
317
+
318
+
319
+ def swap_profile(handle: str, format: str, **options: Any) -> RequestSpec[SwapResult]:
320
+ return _swap(f"/api/v1/swap/{_handle_segment(handle)}", format, options)
321
+
322
+
323
+ def swap_post(handle: str, post_id: str, format: str, **options: Any) -> RequestSpec[SwapResult]:
324
+ if not _POST_ID.fullmatch(post_id):
325
+ raise ValueError(f"Not a post id: {post_id!r}")
326
+ return _swap(f"/api/v1/swap/{_handle_segment(handle)}/status/{post_id}", format, options)