webpninja 1.0.0__tar.gz

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,39 @@
1
+ # build output
2
+ dist/
3
+
4
+ # generated types
5
+ .astro/
6
+
7
+ # dependencies
8
+ node_modules/
9
+
10
+ # Not committed: this project bundles native-binary optional deps
11
+ # (lightningcss, sharp, esbuild) whose platform-specific packages have a
12
+ # known npm bug where a lockfile generated on one OS causes `npm install`
13
+ # to skip the correct binary on another OS/Docker build. Letting each
14
+ # environment resolve its own lockfile avoids that class of failure.
15
+ package-lock.json
16
+
17
+ # logs
18
+ npm-debug.log*
19
+ yarn-debug.log*
20
+ yarn-error.log*
21
+ pnpm-debug.log*
22
+
23
+ # environment variables
24
+ .env
25
+ .env.production
26
+ api/.env
27
+
28
+ # macOS-specific files
29
+ .DS_Store
30
+
31
+ # jetbrains setting folder
32
+ .idea/
33
+
34
+ # Python SDK build/test artifacts
35
+ __pycache__/
36
+ *.egg-info/
37
+ .pytest_cache/
38
+ sdks/python/dist/
39
+ sdks/python/build/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 WebP Ninja
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,69 @@
1
+ Metadata-Version: 2.5
2
+ Name: webpninja
3
+ Version: 1.0.0
4
+ Summary: Official Python client for the WebP Ninja image compression API
5
+ Project-URL: Homepage, https://webpninja.com
6
+ Project-URL: Documentation, https://webpninja.com/docs
7
+ Project-URL: Repository, https://github.com/yantrixlab/WebPNinja
8
+ Author: WebP Ninja
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: avif,image-compression,jpeg,png,webp
12
+ Requires-Python: >=3.8
13
+ Requires-Dist: requests>=2.25
14
+ Provides-Extra: test
15
+ Requires-Dist: pytest>=7; extra == 'test'
16
+ Requires-Dist: responses>=0.23; extra == 'test'
17
+ Description-Content-Type: text/markdown
18
+
19
+ # webpninja
20
+
21
+ Official Python client for the [WebP Ninja](https://webpninja.com) Developer API — server-side
22
+ image compression for WebP, JPEG, PNG, and AVIF.
23
+
24
+ ## Install
25
+
26
+ ```bash
27
+ pip install webpninja
28
+ ```
29
+
30
+ Requires Python 3.8 or later.
31
+
32
+ ## Usage
33
+
34
+ ```python
35
+ from webpninja import WebPNinja
36
+
37
+ client = WebPNinja("webpninja_live_your_key")
38
+ # or: client = WebPNinja() # reads WEBPNINJA_API_KEY from the environment
39
+
40
+ client.compress_to_file("photo.png", "photo.webp", format="webp", quality=75)
41
+ ```
42
+
43
+ Or get the compressed bytes directly:
44
+
45
+ ```python
46
+ data = client.compress("photo.png", format="webp", quality=75)
47
+ ```
48
+
49
+ `input` can be a file path or raw bytes.
50
+
51
+ ## Error handling
52
+
53
+ ```python
54
+ from webpninja import WebPNinja, RateLimitError, AuthenticationError
55
+
56
+ try:
57
+ client.compress("photo.png", format="webp")
58
+ except RateLimitError as err:
59
+ print(f"Quota: {err.used}/{err.quota}")
60
+ except AuthenticationError:
61
+ print("Check your API key.")
62
+ ```
63
+
64
+ All errors extend `WebPNinjaError` and carry `.status` (the HTTP status code) and `.message`.
65
+ See [webpninja.com/docs](https://webpninja.com/docs) for the full error reference.
66
+
67
+ ## License
68
+
69
+ MIT
@@ -0,0 +1,51 @@
1
+ # webpninja
2
+
3
+ Official Python client for the [WebP Ninja](https://webpninja.com) Developer API — server-side
4
+ image compression for WebP, JPEG, PNG, and AVIF.
5
+
6
+ ## Install
7
+
8
+ ```bash
9
+ pip install webpninja
10
+ ```
11
+
12
+ Requires Python 3.8 or later.
13
+
14
+ ## Usage
15
+
16
+ ```python
17
+ from webpninja import WebPNinja
18
+
19
+ client = WebPNinja("webpninja_live_your_key")
20
+ # or: client = WebPNinja() # reads WEBPNINJA_API_KEY from the environment
21
+
22
+ client.compress_to_file("photo.png", "photo.webp", format="webp", quality=75)
23
+ ```
24
+
25
+ Or get the compressed bytes directly:
26
+
27
+ ```python
28
+ data = client.compress("photo.png", format="webp", quality=75)
29
+ ```
30
+
31
+ `input` can be a file path or raw bytes.
32
+
33
+ ## Error handling
34
+
35
+ ```python
36
+ from webpninja import WebPNinja, RateLimitError, AuthenticationError
37
+
38
+ try:
39
+ client.compress("photo.png", format="webp")
40
+ except RateLimitError as err:
41
+ print(f"Quota: {err.used}/{err.quota}")
42
+ except AuthenticationError:
43
+ print("Check your API key.")
44
+ ```
45
+
46
+ All errors extend `WebPNinjaError` and carry `.status` (the HTTP status code) and `.message`.
47
+ See [webpninja.com/docs](https://webpninja.com/docs) for the full error reference.
48
+
49
+ ## License
50
+
51
+ MIT
@@ -0,0 +1,25 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "webpninja"
7
+ version = "1.0.0"
8
+ description = "Official Python client for the WebP Ninja image compression API"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.8"
12
+ dependencies = ["requests>=2.25"]
13
+ authors = [{ name = "WebP Ninja" }]
14
+ keywords = ["webp", "image-compression", "png", "jpeg", "avif"]
15
+
16
+ [project.optional-dependencies]
17
+ test = ["pytest>=7", "responses>=0.23"]
18
+
19
+ [project.urls]
20
+ Homepage = "https://webpninja.com"
21
+ Documentation = "https://webpninja.com/docs"
22
+ Repository = "https://github.com/yantrixlab/WebPNinja"
23
+
24
+ [tool.hatch.build.targets.wheel]
25
+ packages = ["webpninja"]
@@ -0,0 +1,121 @@
1
+ import pytest
2
+ import responses
3
+
4
+ from webpninja import (
5
+ WebPNinja,
6
+ AuthenticationError,
7
+ ValidationError,
8
+ PayloadTooLargeError,
9
+ RateLimitError,
10
+ )
11
+
12
+ COMPRESS_URL = "https://api.webpninja.com/api/v1/compress"
13
+
14
+
15
+ @responses.activate
16
+ def test_compress_success(tmp_path):
17
+ responses.add(
18
+ responses.POST,
19
+ COMPRESS_URL,
20
+ body=b"fake-webp-bytes",
21
+ status=200,
22
+ content_type="image/webp",
23
+ )
24
+
25
+ photo = tmp_path / "photo.png"
26
+ photo.write_bytes(b"fake-png-bytes")
27
+
28
+ client = WebPNinja(api_key="webpninja_live_test")
29
+ result = client.compress(str(photo), format="webp", quality=75)
30
+
31
+ assert result == b"fake-webp-bytes"
32
+ sent = responses.calls[0].request
33
+ assert sent.headers["Authorization"] == "Bearer webpninja_live_test"
34
+
35
+
36
+ @responses.activate
37
+ def test_compress_accepts_raw_bytes():
38
+ responses.add(responses.POST, COMPRESS_URL, body=b"ok", status=200)
39
+
40
+ client = WebPNinja(api_key="webpninja_live_test")
41
+ result = client.compress(b"raw-bytes", format="png")
42
+
43
+ assert result == b"ok"
44
+
45
+
46
+ def test_compress_rejects_bad_input_type():
47
+ client = WebPNinja(api_key="webpninja_live_test")
48
+ with pytest.raises(TypeError):
49
+ client.compress(12345, format="webp")
50
+
51
+
52
+ @responses.activate
53
+ def test_compress_maps_401_to_authentication_error():
54
+ responses.add(
55
+ responses.POST,
56
+ COMPRESS_URL,
57
+ json={"error": "Invalid or revoked API key"},
58
+ status=401,
59
+ )
60
+
61
+ client = WebPNinja(api_key="webpninja_live_bad")
62
+ with pytest.raises(AuthenticationError):
63
+ client.compress(b"bytes", format="webp")
64
+
65
+
66
+ @responses.activate
67
+ def test_compress_maps_400_to_validation_error():
68
+ responses.add(
69
+ responses.POST,
70
+ COMPRESS_URL,
71
+ json={"error": "format must be one of: webp, jpeg, png, avif"},
72
+ status=400,
73
+ )
74
+
75
+ client = WebPNinja(api_key="webpninja_live_test")
76
+ with pytest.raises(ValidationError):
77
+ client.compress(b"bytes", format="bogus")
78
+
79
+
80
+ @responses.activate
81
+ def test_compress_maps_413_with_plan_fields():
82
+ responses.add(
83
+ responses.POST,
84
+ COMPRESS_URL,
85
+ json={
86
+ "error": "File exceeds your plan's upload limit",
87
+ "maxUploadMb": 15,
88
+ "fileSizeMb": 20,
89
+ },
90
+ status=413,
91
+ )
92
+
93
+ client = WebPNinja(api_key="webpninja_live_test")
94
+ with pytest.raises(PayloadTooLargeError) as exc_info:
95
+ client.compress(b"bytes", format="webp")
96
+
97
+ assert exc_info.value.max_upload_mb == 15
98
+ assert exc_info.value.file_size_mb == 20
99
+
100
+
101
+ @responses.activate
102
+ def test_compress_maps_429_with_quota_fields():
103
+ responses.add(
104
+ responses.POST,
105
+ COMPRESS_URL,
106
+ json={"error": "Daily quota exceeded", "quota": 15, "used": 15},
107
+ status=429,
108
+ )
109
+
110
+ client = WebPNinja(api_key="webpninja_live_test")
111
+ with pytest.raises(RateLimitError) as exc_info:
112
+ client.compress(b"bytes", format="webp")
113
+
114
+ assert exc_info.value.quota == 15
115
+ assert exc_info.value.used == 15
116
+
117
+
118
+ def test_missing_api_key(monkeypatch):
119
+ monkeypatch.delenv("WEBPNINJA_API_KEY", raising=False)
120
+ with pytest.raises(ValueError):
121
+ WebPNinja()
@@ -0,0 +1,19 @@
1
+ from .client import WebPNinja
2
+ from .errors import (
3
+ WebPNinjaError,
4
+ ValidationError,
5
+ AuthenticationError,
6
+ PayloadTooLargeError,
7
+ CompressionError,
8
+ RateLimitError,
9
+ )
10
+
11
+ __all__ = [
12
+ "WebPNinja",
13
+ "WebPNinjaError",
14
+ "ValidationError",
15
+ "AuthenticationError",
16
+ "PayloadTooLargeError",
17
+ "CompressionError",
18
+ "RateLimitError",
19
+ ]
@@ -0,0 +1,51 @@
1
+ import os
2
+ from pathlib import Path
3
+
4
+ import requests
5
+
6
+ from .errors import error_from_response
7
+
8
+ DEFAULT_BASE_URL = "https://api.webpninja.com"
9
+
10
+
11
+ class WebPNinja:
12
+ def __init__(self, api_key=None, base_url=DEFAULT_BASE_URL):
13
+ self.api_key = api_key or os.environ.get("WEBPNINJA_API_KEY")
14
+ if not self.api_key:
15
+ raise ValueError(
16
+ "Missing API key: pass one to WebPNinja(api_key) or set WEBPNINJA_API_KEY"
17
+ )
18
+ self.base_url = base_url
19
+
20
+ def compress(self, input, format, quality=80, filename="image"):
21
+ data, name = self._resolve_input(input, filename)
22
+
23
+ response = requests.post(
24
+ f"{self.base_url}/api/v1/compress",
25
+ headers={"Authorization": f"Bearer {self.api_key}"},
26
+ files={"file": (name, data)},
27
+ data={"format": format, "quality": str(quality)},
28
+ )
29
+
30
+ if not response.ok:
31
+ try:
32
+ body = response.json()
33
+ except ValueError:
34
+ body = None
35
+ raise error_from_response(response.status_code, body)
36
+
37
+ return response.content
38
+
39
+ def compress_to_file(self, input, output_path, format, quality=80):
40
+ result = self.compress(input, format=format, quality=quality)
41
+ Path(output_path).write_bytes(result)
42
+ return result
43
+
44
+ @staticmethod
45
+ def _resolve_input(input, default_filename):
46
+ if isinstance(input, (str, os.PathLike)):
47
+ path = Path(input)
48
+ return path.read_bytes(), path.name
49
+ if isinstance(input, (bytes, bytearray)):
50
+ return bytes(input), default_filename
51
+ raise TypeError("input must be a file path or bytes")
@@ -0,0 +1,53 @@
1
+ class WebPNinjaError(Exception):
2
+ """Base error for all WebP Ninja API failures."""
3
+
4
+ def __init__(self, message, status=None):
5
+ super().__init__(message)
6
+ self.message = message
7
+ self.status = status
8
+
9
+
10
+ class ValidationError(WebPNinjaError):
11
+ def __init__(self, message):
12
+ super().__init__(message, 400)
13
+
14
+
15
+ class AuthenticationError(WebPNinjaError):
16
+ def __init__(self, message):
17
+ super().__init__(message, 401)
18
+
19
+
20
+ class PayloadTooLargeError(WebPNinjaError):
21
+ def __init__(self, message, max_upload_mb=None, file_size_mb=None):
22
+ super().__init__(message, 413)
23
+ self.max_upload_mb = max_upload_mb
24
+ self.file_size_mb = file_size_mb
25
+
26
+
27
+ class CompressionError(WebPNinjaError):
28
+ def __init__(self, message):
29
+ super().__init__(message, 422)
30
+
31
+
32
+ class RateLimitError(WebPNinjaError):
33
+ def __init__(self, message, quota=None, used=None):
34
+ super().__init__(message, 429)
35
+ self.quota = quota
36
+ self.used = used
37
+
38
+
39
+ def error_from_response(status, body):
40
+ body = body or {}
41
+ message = body.get("error") or f"Request failed with status {status}"
42
+
43
+ if status == 400:
44
+ return ValidationError(message)
45
+ if status == 401:
46
+ return AuthenticationError(message)
47
+ if status == 413:
48
+ return PayloadTooLargeError(message, body.get("maxUploadMb"), body.get("fileSizeMb"))
49
+ if status == 422:
50
+ return CompressionError(message)
51
+ if status == 429:
52
+ return RateLimitError(message, body.get("quota"), body.get("used"))
53
+ return WebPNinjaError(message, status)