labelzoom-sdk 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.
labelzoom/__init__.py ADDED
@@ -0,0 +1,71 @@
1
+ """Official Python SDK for the `LabelZoom <https://www.labelzoom.com>`_ API.
2
+
3
+ Converts barcode labels between ZPL, EPL, TSPL, DPL, PDF, LabelZoom XML/JSON and raster
4
+ images.
5
+
6
+ ```python
7
+ from labelzoom import LabelZoomClient
8
+
9
+ with LabelZoomClient() as client: # anonymous free tier; no key required
10
+ result = client.convert("zpl", "png", "^XA^FO20,20^A0N,28^FDhi^FS^XZ", dpi=300)
11
+ print(result.status, result.content_type, len(result.content))
12
+ ```
13
+ """
14
+
15
+ from ._version import __version__
16
+ from .client import (
17
+ API_KEY_ENV_VAR,
18
+ DEFAULT_BASE_URL,
19
+ AsyncLabelZoomClient,
20
+ ConversionResult,
21
+ LabelZoomClient,
22
+ )
23
+ from .errors import (
24
+ BadRequestError,
25
+ ForbiddenError,
26
+ LabelZoomError,
27
+ LabelZoomValidationError,
28
+ NotFoundError,
29
+ PayloadTooLargeError,
30
+ RateLimitedError,
31
+ ServerError,
32
+ UnauthorizedError,
33
+ )
34
+ from .formats import (
35
+ SOURCE_FORMATS,
36
+ TARGET_FORMATS,
37
+ ColorMode,
38
+ PdfConversionMode,
39
+ SourceFormat,
40
+ TargetFormat,
41
+ ZplImageCompression,
42
+ )
43
+ from .options import UNSET, ConversionOptions, DataRecord
44
+
45
+ __all__ = [
46
+ "API_KEY_ENV_VAR",
47
+ "DEFAULT_BASE_URL",
48
+ "SOURCE_FORMATS",
49
+ "TARGET_FORMATS",
50
+ "UNSET",
51
+ "AsyncLabelZoomClient",
52
+ "BadRequestError",
53
+ "ColorMode",
54
+ "ConversionOptions",
55
+ "ConversionResult",
56
+ "DataRecord",
57
+ "ForbiddenError",
58
+ "LabelZoomClient",
59
+ "LabelZoomError",
60
+ "LabelZoomValidationError",
61
+ "NotFoundError",
62
+ "PayloadTooLargeError",
63
+ "PdfConversionMode",
64
+ "RateLimitedError",
65
+ "ServerError",
66
+ "SourceFormat",
67
+ "TargetFormat",
68
+ "UnauthorizedError",
69
+ "ZplImageCompression",
70
+ "__version__",
71
+ ]
labelzoom/_version.py ADDED
@@ -0,0 +1,3 @@
1
+ """Single source of the package version; ``pyproject.toml`` reads it from here."""
2
+
3
+ __version__ = "0.1.0"
labelzoom/client.py ADDED
@@ -0,0 +1,525 @@
1
+ """The LabelZoom API clients: :class:`LabelZoomClient` and :class:`AsyncLabelZoomClient`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import os
7
+ import platform
8
+ import random
9
+ import re
10
+ import time
11
+ from collections.abc import Awaitable, Callable, Mapping, Sequence
12
+ from dataclasses import dataclass
13
+ from email.utils import parsedate_to_datetime
14
+ from types import TracebackType
15
+ from typing import Any, Final
16
+
17
+ import httpx
18
+
19
+ from ._version import __version__
20
+ from .errors import (
21
+ LabelZoomError,
22
+ LabelZoomValidationError,
23
+ error_for_status,
24
+ extract_message,
25
+ )
26
+ from .formats import (
27
+ ColorMode,
28
+ PdfConversionMode,
29
+ SourceFormat,
30
+ TargetFormat,
31
+ ZplImageCompression,
32
+ source_media_type,
33
+ source_wire_token,
34
+ target_wire_token,
35
+ validate_formats,
36
+ )
37
+ from .options import UNSET, ConversionOptions, DataRecord, _Unset, serialize_options
38
+
39
+ __all__ = [
40
+ "API_KEY_ENV_VAR",
41
+ "DEFAULT_BASE_URL",
42
+ "AsyncLabelZoomClient",
43
+ "ConversionResult",
44
+ "LabelZoomClient",
45
+ ]
46
+
47
+ #: The production API host.
48
+ DEFAULT_BASE_URL: Final = "https://api.labelzoom.com"
49
+
50
+ #: The environment variable consulted when no credential is passed.
51
+ API_KEY_ENV_VAR: Final = "LABELZOOM_API_KEY"
52
+
53
+ _REQUEST_ID_HEADER: Final = "X-LZ-Request-Id"
54
+ _CHARSET_PATTERN: Final = re.compile(r"charset=([^;]+)", re.IGNORECASE)
55
+
56
+ Body = str | bytes | bytearray
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class ConversionResult:
61
+ """The outcome of a successful conversion.
62
+
63
+ :attr:`content` is authoritative -- PDF, PNG, BMP, GIF and JPEG targets are binary, so
64
+ returning only a string would silently corrupt five of the eight targets.
65
+ """
66
+
67
+ #: The response body, exactly as the server sent it.
68
+ content: bytes
69
+ #: The HTTP status code.
70
+ status: int
71
+ #: The response ``Content-Type``, if the server sent one.
72
+ content_type: str | None = None
73
+ #: ``X-LZ-Request-Id``, when the server sent it. The support handle.
74
+ request_id: str | None = None
75
+
76
+ @property
77
+ def text(self) -> str:
78
+ """:attr:`content` decoded with the response charset, defaulting to UTF-8."""
79
+ return _decode(self.content, self.content_type)
80
+
81
+ def __len__(self) -> int:
82
+ return len(self.content)
83
+
84
+
85
+ class _BaseClient:
86
+ """Configuration and the pure request/response logic both clients share.
87
+
88
+ The two clients differ only in how they send and how they sleep. Everything that decides
89
+ *what* goes on the wire lives here, so the sync and async surfaces cannot drift.
90
+ """
91
+
92
+ def __init__(
93
+ self,
94
+ *,
95
+ api_key: str | _Unset | None,
96
+ base_url: str,
97
+ max_retries: int,
98
+ user_agent_suffix: str | None,
99
+ use_jitter: bool,
100
+ runtime: str,
101
+ ) -> None:
102
+ if max_retries < 0:
103
+ raise ValueError("max_retries cannot be negative.")
104
+
105
+ self._base_url = base_url.rstrip("/")
106
+ self._credential = _resolve_credential(api_key)
107
+ self._max_retries = max_retries
108
+ self._use_jitter = use_jitter
109
+
110
+ # The server parses a "LabelZoomStudio/" User-Agent prefix as a Studio version and
111
+ # silently changes PDF handling for versions <= 1.8.2, so the SDK's own token must
112
+ # come first.
113
+ suffix = (user_agent_suffix or "").strip()
114
+ self._user_agent = f"labelzoom-python-sdk/{__version__} ({runtime})"
115
+ if suffix:
116
+ self._user_agent = f"{self._user_agent} {suffix}"
117
+
118
+ @property
119
+ def is_authenticated(self) -> bool:
120
+ """Whether a credential was resolved. ``False`` means anonymous free-tier requests."""
121
+ return self._credential is not None
122
+
123
+ def _build_request(
124
+ self,
125
+ http: httpx.Client | httpx.AsyncClient,
126
+ source: SourceFormat,
127
+ target: TargetFormat,
128
+ body: Body,
129
+ as_base64_text: bool,
130
+ options: ConversionOptions | None,
131
+ ) -> httpx.Request:
132
+ validate_formats(source, target)
133
+
134
+ content = body.encode("utf-8") if isinstance(body, str) else bytes(body)
135
+ if not content:
136
+ # The gateway rejects a zero-length body with 400; catching it here saves a
137
+ # round trip and gives a clearer message.
138
+ raise LabelZoomValidationError(
139
+ "body",
140
+ "Source body cannot be empty; the API rejects zero-length requests.",
141
+ )
142
+
143
+ params = serialize_options(options)
144
+
145
+ headers = {
146
+ "Content-Type": "text/plain" if as_base64_text else source_media_type(source),
147
+ # Accept must be */*. The server's `produces` list omits image/gif, image/bmp
148
+ # and image/jpeg, so naming the target's exact media type yields a 406 from
149
+ # content negotiation before the handler ever runs.
150
+ "Accept": "*/*",
151
+ "User-Agent": self._user_agent,
152
+ }
153
+ if self._credential is not None:
154
+ headers["Authorization"] = f"Bearer {self._credential}"
155
+
156
+ url = (
157
+ f"{self._base_url}/api/v2/convert/"
158
+ f"{source_wire_token(source)}/to/{target_wire_token(target)}"
159
+ )
160
+
161
+ return http.build_request(
162
+ "POST",
163
+ url,
164
+ # Rule C7: no options means a bare URL, not an empty query string.
165
+ params=None if params is None else {"params": params},
166
+ headers=headers,
167
+ content=content,
168
+ )
169
+
170
+ def _next_delay(self, attempt: int, retry_after: float | None) -> float:
171
+ """1s, 2s, 4s with full jitter, overridden by a longer ``Retry-After``."""
172
+ backoff = float(2 ** (attempt - 1))
173
+ delay = backoff * random.random() if self._use_jitter else backoff
174
+
175
+ # The server knows better than the backoff curve when it tells us how long to wait.
176
+ if retry_after is not None and retry_after > delay:
177
+ delay = retry_after
178
+
179
+ return delay
180
+
181
+
182
+ class LabelZoomClient(_BaseClient):
183
+ """A synchronous LabelZoom API client.
184
+
185
+ Authentication is *optional*. Without a credential the API serves a free tier
186
+ (watermarked, first label only, 1 MB cap, no multi-page, JSON target or image-to-image),
187
+ so constructing a client with no key is a supported mode, not an error.
188
+
189
+ ```python
190
+ from labelzoom import LabelZoomClient
191
+
192
+ with LabelZoomClient() as client:
193
+ result = client.convert("zpl", "png", zpl, dpi=300)
194
+ Path("label.png").write_bytes(result.content)
195
+ ```
196
+ """
197
+
198
+ def __init__(
199
+ self,
200
+ api_key: str | _Unset | None = UNSET,
201
+ *,
202
+ base_url: str = DEFAULT_BASE_URL,
203
+ timeout: float | httpx.Timeout | None = 60.0,
204
+ max_retries: int = 2,
205
+ user_agent_suffix: str | None = None,
206
+ http_client: httpx.Client | None = None,
207
+ transport: httpx.BaseTransport | None = None,
208
+ use_jitter: bool = True,
209
+ sleep: Callable[[float], None] = time.sleep,
210
+ ) -> None:
211
+ """
212
+ :param api_key: An ``lz_live_``/``lz_test_`` key or a JWT. Omit the argument entirely
213
+ to read ``LABELZOOM_API_KEY`` from the environment; pass ``None`` or ``""`` to
214
+ force anonymous mode and suppress that fallback. (Omitting and passing ``None``
215
+ differ on purpose -- that is what the ``UNSET`` default is for.)
216
+ :param base_url: Defaults to :data:`DEFAULT_BASE_URL`. A path prefix is preserved,
217
+ so a reverse proxy at ``https://proxy/labelzoom`` works.
218
+ :param timeout: Per-request timeout in seconds. ``None`` disables it. Conversions of
219
+ large multi-page PDFs are the slow case.
220
+ :param max_retries: Retries *after* the initial attempt. ``0`` disables retrying.
221
+ :param http_client: Supply your own ``httpx.Client`` to share a connection pool. The
222
+ SDK will not close a client it did not create.
223
+ :param transport: An ``httpx.BaseTransport`` for the client the SDK creates --
224
+ ``httpx.MockTransport`` in tests.
225
+ :param use_jitter: Full jitter on retry backoff. Turn off for deterministic tests.
226
+ :param sleep: Replaces the delay between retries. Substitute a recording no-op in
227
+ tests rather than waiting out real seconds.
228
+ """
229
+ super().__init__(
230
+ api_key=api_key,
231
+ base_url=base_url,
232
+ max_retries=max_retries,
233
+ user_agent_suffix=user_agent_suffix,
234
+ use_jitter=use_jitter,
235
+ runtime=_runtime_token(),
236
+ )
237
+ self._sleep = sleep
238
+ self._owns_http = http_client is None
239
+ self._http = http_client or httpx.Client(timeout=timeout, transport=transport)
240
+
241
+ def convert(
242
+ self,
243
+ source: SourceFormat,
244
+ target: TargetFormat,
245
+ body: Body,
246
+ *,
247
+ options: ConversionOptions | None = None,
248
+ as_base64_text: bool = False,
249
+ dpi: int | _Unset = UNSET,
250
+ rotation: int | _Unset = UNSET,
251
+ scaling: float | _Unset = UNSET,
252
+ color_mode: ColorMode | _Unset = UNSET,
253
+ darkness: int | _Unset = UNSET,
254
+ position_x: int | _Unset = UNSET,
255
+ position_y: int | _Unset = UNSET,
256
+ watermark: bool | _Unset = UNSET,
257
+ dialect: str | _Unset = UNSET,
258
+ data: DataRecord | Sequence[DataRecord] | _Unset = UNSET,
259
+ label_width: float | _Unset = UNSET,
260
+ label_height: float | _Unset = UNSET,
261
+ pdf_conversion_mode: PdfConversionMode | _Unset = UNSET,
262
+ pdf_page_number: int | _Unset = UNSET,
263
+ zpl_commands_to_ignore: Sequence[str] | _Unset = UNSET,
264
+ zpl_image_compression: ZplImageCompression | _Unset = UNSET,
265
+ extra: Mapping[str, Any] | _Unset = UNSET,
266
+ ) -> ConversionResult:
267
+ """Convert a label from one format to another.
268
+
269
+ Only the options you pass are sent; the SDK never supplies a client-side default.
270
+
271
+ :param source: The input format. ``"url"`` posts the URL as the body and has the
272
+ *server* fetch it -- validate it first if it came from untrusted input.
273
+ :param target: The output format. ``"epl"``, ``"tspl"`` and ``"dpl"`` are absent by
274
+ design: they are source-only on the server.
275
+ :param body: The document, as ``bytes`` or ``str``.
276
+ :param options: A pre-built :class:`~labelzoom.ConversionOptions`. Keyword arguments
277
+ passed alongside it win.
278
+ :param as_base64_text: Send the body as base64 ``text/plain`` rather than the
279
+ source's own media type.
280
+ :param label_width: **Inches**, not dots.
281
+ :param label_height: **Inches**, not dots.
282
+ :param pdf_page_number: **0-based**. Omit to convert every page.
283
+ :raises LabelZoomValidationError: The request was rejected locally; nothing was sent.
284
+ :raises LabelZoomError: The API returned a non-2xx response.
285
+ """
286
+ merged = (options or ConversionOptions()).merge(
287
+ dpi=dpi,
288
+ rotation=rotation,
289
+ scaling=scaling,
290
+ color_mode=color_mode,
291
+ darkness=darkness,
292
+ position_x=position_x,
293
+ position_y=position_y,
294
+ watermark=watermark,
295
+ dialect=dialect,
296
+ data=data,
297
+ label_width=label_width,
298
+ label_height=label_height,
299
+ pdf_conversion_mode=pdf_conversion_mode,
300
+ pdf_page_number=pdf_page_number,
301
+ zpl_commands_to_ignore=zpl_commands_to_ignore,
302
+ zpl_image_compression=zpl_image_compression,
303
+ extra=extra,
304
+ )
305
+ request = self._build_request(self._http, source, target, body, as_base64_text, merged)
306
+
307
+ attempts = self._max_retries + 1
308
+ for attempt in range(1, attempts + 1):
309
+ try:
310
+ response = self._http.send(request)
311
+ except httpx.TransportError:
312
+ if attempt >= attempts:
313
+ raise
314
+ self._sleep(self._next_delay(attempt, None))
315
+ continue
316
+
317
+ if response.is_success:
318
+ return _result_from(response)
319
+
320
+ error = _error_from(response)
321
+ if attempt >= attempts or not _is_retryable(response.status_code):
322
+ raise error
323
+
324
+ self._sleep(self._next_delay(attempt, _retry_after_seconds(response)))
325
+
326
+ raise AssertionError("unreachable: the retry loop always returns or raises")
327
+
328
+ def close(self) -> None:
329
+ if self._owns_http:
330
+ self._http.close()
331
+
332
+ def __enter__(self) -> LabelZoomClient:
333
+ return self
334
+
335
+ def __exit__(
336
+ self,
337
+ exc_type: type[BaseException] | None,
338
+ exc: BaseException | None,
339
+ tb: TracebackType | None,
340
+ ) -> None:
341
+ self.close()
342
+
343
+
344
+ class AsyncLabelZoomClient(_BaseClient):
345
+ """The asyncio mirror of :class:`LabelZoomClient`.
346
+
347
+ Identical surface and identical wire behaviour; ``convert`` is a coroutine. The two
348
+ signatures are asserted to match in the test suite so they cannot drift.
349
+ """
350
+
351
+ def __init__(
352
+ self,
353
+ api_key: str | _Unset | None = UNSET,
354
+ *,
355
+ base_url: str = DEFAULT_BASE_URL,
356
+ timeout: float | httpx.Timeout | None = 60.0,
357
+ max_retries: int = 2,
358
+ user_agent_suffix: str | None = None,
359
+ http_client: httpx.AsyncClient | None = None,
360
+ transport: httpx.AsyncBaseTransport | None = None,
361
+ use_jitter: bool = True,
362
+ sleep: Callable[[float], Awaitable[None]] = asyncio.sleep,
363
+ ) -> None:
364
+ super().__init__(
365
+ api_key=api_key,
366
+ base_url=base_url,
367
+ max_retries=max_retries,
368
+ user_agent_suffix=user_agent_suffix,
369
+ use_jitter=use_jitter,
370
+ runtime=_runtime_token(),
371
+ )
372
+ self._sleep = sleep
373
+ self._owns_http = http_client is None
374
+ self._http = http_client or httpx.AsyncClient(timeout=timeout, transport=transport)
375
+
376
+ async def convert(
377
+ self,
378
+ source: SourceFormat,
379
+ target: TargetFormat,
380
+ body: Body,
381
+ *,
382
+ options: ConversionOptions | None = None,
383
+ as_base64_text: bool = False,
384
+ dpi: int | _Unset = UNSET,
385
+ rotation: int | _Unset = UNSET,
386
+ scaling: float | _Unset = UNSET,
387
+ color_mode: ColorMode | _Unset = UNSET,
388
+ darkness: int | _Unset = UNSET,
389
+ position_x: int | _Unset = UNSET,
390
+ position_y: int | _Unset = UNSET,
391
+ watermark: bool | _Unset = UNSET,
392
+ dialect: str | _Unset = UNSET,
393
+ data: DataRecord | Sequence[DataRecord] | _Unset = UNSET,
394
+ label_width: float | _Unset = UNSET,
395
+ label_height: float | _Unset = UNSET,
396
+ pdf_conversion_mode: PdfConversionMode | _Unset = UNSET,
397
+ pdf_page_number: int | _Unset = UNSET,
398
+ zpl_commands_to_ignore: Sequence[str] | _Unset = UNSET,
399
+ zpl_image_compression: ZplImageCompression | _Unset = UNSET,
400
+ extra: Mapping[str, Any] | _Unset = UNSET,
401
+ ) -> ConversionResult:
402
+ """Convert a label from one format to another. See :meth:`LabelZoomClient.convert`."""
403
+ merged = (options or ConversionOptions()).merge(
404
+ dpi=dpi,
405
+ rotation=rotation,
406
+ scaling=scaling,
407
+ color_mode=color_mode,
408
+ darkness=darkness,
409
+ position_x=position_x,
410
+ position_y=position_y,
411
+ watermark=watermark,
412
+ dialect=dialect,
413
+ data=data,
414
+ label_width=label_width,
415
+ label_height=label_height,
416
+ pdf_conversion_mode=pdf_conversion_mode,
417
+ pdf_page_number=pdf_page_number,
418
+ zpl_commands_to_ignore=zpl_commands_to_ignore,
419
+ zpl_image_compression=zpl_image_compression,
420
+ extra=extra,
421
+ )
422
+ request = self._build_request(self._http, source, target, body, as_base64_text, merged)
423
+
424
+ attempts = self._max_retries + 1
425
+ for attempt in range(1, attempts + 1):
426
+ try:
427
+ response = await self._http.send(request)
428
+ except httpx.TransportError:
429
+ if attempt >= attempts:
430
+ raise
431
+ await self._sleep(self._next_delay(attempt, None))
432
+ continue
433
+
434
+ if response.is_success:
435
+ return _result_from(response)
436
+
437
+ error = _error_from(response)
438
+ if attempt >= attempts or not _is_retryable(response.status_code):
439
+ raise error
440
+
441
+ await self._sleep(self._next_delay(attempt, _retry_after_seconds(response)))
442
+
443
+ raise AssertionError("unreachable: the retry loop always returns or raises")
444
+
445
+ async def aclose(self) -> None:
446
+ if self._owns_http:
447
+ await self._http.aclose()
448
+
449
+ async def __aenter__(self) -> AsyncLabelZoomClient:
450
+ return self
451
+
452
+ async def __aexit__(
453
+ self,
454
+ exc_type: type[BaseException] | None,
455
+ exc: BaseException | None,
456
+ tb: TracebackType | None,
457
+ ) -> None:
458
+ await self.aclose()
459
+
460
+
461
+ def _resolve_credential(api_key: str | _Unset | None) -> str | None:
462
+ if isinstance(api_key, _Unset):
463
+ return os.environ.get(API_KEY_ENV_VAR) or None
464
+ # An explicit None or "" forces anonymous and must not fall back to the environment.
465
+ return api_key or None
466
+
467
+
468
+ def _runtime_token() -> str:
469
+ return f"python/{platform.python_version()}"
470
+
471
+
472
+ def _result_from(response: httpx.Response) -> ConversionResult:
473
+ return ConversionResult(
474
+ content=response.content,
475
+ status=response.status_code,
476
+ content_type=response.headers.get("content-type"),
477
+ # httpx headers are case-insensitive, which matters here: the gateway sets
478
+ # X-LZ-Request-Id but CORS exposes it as X-LZ-Request-ID.
479
+ request_id=response.headers.get(_REQUEST_ID_HEADER),
480
+ )
481
+
482
+
483
+ def _error_from(response: httpx.Response) -> LabelZoomError:
484
+ raw_body = _decode(response.content, response.headers.get("content-type"))
485
+
486
+ return error_for_status(
487
+ status=response.status_code,
488
+ message=extract_message(raw_body, response.reason_phrase),
489
+ request_id=response.headers.get(_REQUEST_ID_HEADER),
490
+ raw_body=raw_body,
491
+ retry_after_seconds=_retry_after_seconds(response),
492
+ )
493
+
494
+
495
+ def _decode(content: bytes, content_type: str | None) -> str:
496
+ match = _CHARSET_PATTERN.search(content_type or "")
497
+ charset = match.group(1).strip().strip('"') if match else "utf-8"
498
+ try:
499
+ return content.decode(charset)
500
+ except (LookupError, UnicodeDecodeError):
501
+ # An unrecognized or mis-declared charset is not worth failing an otherwise good
502
+ # conversion over.
503
+ return content.decode("utf-8", errors="replace")
504
+
505
+
506
+ def _retry_after_seconds(response: httpx.Response) -> float | None:
507
+ header = response.headers.get("retry-after")
508
+ if header is None:
509
+ return None
510
+
511
+ try:
512
+ return float(header)
513
+ except ValueError:
514
+ pass
515
+
516
+ try:
517
+ when = parsedate_to_datetime(header)
518
+ except (TypeError, ValueError):
519
+ return None
520
+
521
+ return max(0.0, (when.timestamp() - time.time()))
522
+
523
+
524
+ def _is_retryable(status: int) -> bool:
525
+ return status == 429 or status >= 500