├── .gitignore ├── LICENSE ├── README.md ├── krakenio └── __init__.py ├── requirements.txt ├── setup.cfg ├── setup.py ├── tests ├── test.jpg └── test_client.py └── tox.ini /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | local_settings.py 55 | 56 | # Flask stuff: 57 | instance/ 58 | .webassets-cache 59 | 60 | # Scrapy stuff: 61 | .scrapy 62 | 63 | # Sphinx documentation 64 | docs/_build/ 65 | 66 | # PyBuilder 67 | target/ 68 | 69 | # IPython Notebook 70 | .ipynb_checkpoints 71 | 72 | # pyenv 73 | .python-version 74 | 75 | # celery beat schedule file 76 | celerybeat-schedule 77 | 78 | # dotenv 79 | .env 80 | 81 | # virtualenv 82 | venv/ 83 | ENV/ 84 | 85 | # Spyder project settings 86 | .spyderproject 87 | 88 | # Rope project settings 89 | .ropeproject 90 | 91 | .env 92 | *.pyc 93 | __pycache__/ 94 | *.egg-info/ 95 | dist/ 96 | build/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | LICENSE - MIT 2 | 3 | Copyright (c) 2013-2025 Nekkra UG 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Official Kraken.io library for Python 2 | =========== 3 | 4 | With this Python Client you can plug into the power and speed of [Kraken.io](http://kraken.io/) Image Optimizer. 5 | 6 | ## Important Notice 7 | 8 | As of version **0.2.0**, this package **only supports Python 3.8 and later**. If you are using an older Python version, please install an earlier (<=0.1.0) version of this package. 9 | 10 | * [Installation](#installation) 11 | * [Getting Started](#getting-started) 12 | * [Downloading Images](#downloading-images) 13 | * [How To Use](#how-to-use) 14 | * [Wait and Callback URL](#wait-and-callback-url) 15 | * [Wait Option](#wait-option) 16 | * [Callback URL](#callback-url) 17 | * [Authentication](#authentication) 18 | * [Usage - Image URL](#usage---image-url) 19 | * [Usage - Image Upload](#usage---image-upload) 20 | * [Usage - User status](#usage---user-status) 21 | * [Lossy Optimization](#lossy-optimization) 22 | * [Image Resizing](#image-resizing) 23 | * [WebP Compression](#webp-compression) 24 | * [PDF Compression](#pdf-compression) 25 | * [Amazon S3, Rackspace Cloud Files, and Google Cloud Storage](#amazon-s3-rackspace-cloud-files-and-google-cloud-storage) 26 | * [Amazon S3](#amazon-s3) 27 | * [Rackspace Cloud Files](#rackspace-cloud-files) 28 | * [Google Cloud Storage](#google-cloud-storage) 29 | 30 | ## Installation 31 | 32 | pip install krakenio 33 | 34 | ## Getting Started 35 | 36 | First you need to sign-up for the [Kraken API](https://kraken.io/plans/) and obtain your unique **API Key** and **API Secret**. You will find both under [API Credentials](https://kraken.io/account/api-credentials). Once you have set up your account, you can start using Kraken.io's image optimization API in your applications. 37 | 38 | ## Downloading Images 39 | 40 | Remember: never link to optimized images offered to download. You have to download them first, and then replace them in your websites or applications. Optimized images are available on our servers **for one hour** only, after which they are permanently deleted. 41 | 42 | ## How to use 43 | 44 | You can optimize your images in two ways - by providing an URL of the image you want to optimize or by uploading an image file directly to Kraken API. 45 | 46 | The first option (image URL) is great for images that are already in production or any other place on the Internet. The second one (direct upload) is ideal for your deployment process, build script or the on-the-fly processing of your user's uploads where you don't have the images available online yet. 47 | 48 | ## Wait and Callback URL 49 | 50 | Kraken gives you two options for fetching optimization results. With the `wait` option set the results will be returned immediately in the response. With the `callback_url` option set the results will be posted to the URL specified in your request. 51 | 52 | ### Wait option 53 | 54 | With the `wait` option turned on for every request to the API, the connection will be held open unil the image has been optimized. Once this is done you will get an immediate response with a JSON object containing your optimization results. To use this option simply set `"wait": true` in your request. 55 | 56 | **Request:** 57 | 58 | ````js 59 | { 60 | "auth": { 61 | "api_key": "your-api-key", 62 | "api_secret": "your-api-secret" 63 | }, 64 | "url": "http://awesome-website.com/images/header.jpg", 65 | "wait": true 66 | } 67 | ```` 68 | 69 | **Response** 70 | 71 | ````js 72 | { 73 | "success": true, 74 | "file_name": "header.jpg", 75 | "original_size": 324520, 76 | "kraked_size": 165358, 77 | "saved_bytes": 159162, 78 | "kraked_url": "http://dl.kraken.io/d1aacd2a2280c2ffc7b4906a09f78f46/header.jpg" 79 | } 80 | ```` 81 | 82 | ### Callback URL 83 | 84 | With the Callback URL the HTTPS connection will be terminated immediately and a unique `id` will be returned in the response body. After the optimization is over Kraken will POST a message to the `callback_url` specified in your request. The ID in the response will reflect the ID in the results posted to your Callback URL. 85 | 86 | We recommend [hookbin](https://hookbin.com) as an easy way to capture optimization results for initial testing. 87 | 88 | **Request:** 89 | 90 | ````js 91 | { 92 | "auth": { 93 | "api_key": "your-api-key", 94 | "api_secret": "your-api-secret" 95 | }, 96 | "url": "http://image-url.com/file.jpg", 97 | "callback_url": "http://awesome-website.com/kraken_results" 98 | } 99 | ```` 100 | 101 | **Response:** 102 | 103 | ````js 104 | { 105 | "id": "18fede37617a787649c3f60b9f1f280d" 106 | } 107 | ```` 108 | 109 | **Results posted to the Callback URL:** 110 | 111 | ````js 112 | { 113 | "id": "18fede37617a787649c3f60b9f1f280d" 114 | "success": true, 115 | "file_name": "file.jpg", 116 | "original_size": 324520, 117 | "kraked_size": 165358, 118 | "saved_bytes": 159162, 119 | "kraked_url": "http://dl.kraken.io/18fede37617a787649c3f60b9f1f280d/file.jpg" 120 | } 121 | ```` 122 | 123 | ## Authentication 124 | 125 | The first step is to authenticate to Kraken API by providing your unique API Key and API Secret while creating a new Kraken instance: 126 | 127 | ````python 128 | from krakenio import Client 129 | 130 | api = Client('your-api-key', 'your-api-secret') 131 | ```` 132 | 133 | ## Usage - Image URL 134 | 135 | To optimize an image by providing image URL use the `kraken.url()` method. You will need to provide two mandatory parameters - `url` to the image and `wait` or `callback_url`: 136 | 137 | ````python 138 | from krakenio import Client 139 | 140 | api = Client('your-api-key', 'your-api-secret') 141 | 142 | data = { 143 | 'wait': True 144 | } 145 | 146 | result = api.url('your-image-url', data); 147 | 148 | if result.get('success'): 149 | print result.get('kraked_url') 150 | else: 151 | print result.get('message') 152 | ```` 153 | 154 | Depending on a choosen response option (Wait or Callback URL) in the `data` object you will find either the optimization ID or optimization results containing a `success` property, file name, original file size, kraked file size, amount of savings and optimized image URL: 155 | 156 | ````js 157 | { 158 | success: true, 159 | file_name: 'file.jpg', 160 | original_size: 30664, 161 | kraked_size: 577, 162 | saved_bytes: 30087, 163 | kraked_url: 'http://dl.kraken.io/d1/aa/cd/2a2280c2ffc7b4906a09f78f46/file.jpg' 164 | } 165 | ```` 166 | 167 | ## Usage - Image Upload 168 | 169 | If you want to upload your images directly to Kraken API use the `kraken.upload()` method. You will need to provide two mandatory parameters - `file` which is either a string containing a path to the file or a Stream Object and `wait` or `callback_url`. 170 | 171 | In the `data` object you will find the same optimization properties as with `url` option above. 172 | 173 | ````python 174 | from krakenio import Client 175 | 176 | api = Client('your-api-key', 'your-api-secret') 177 | 178 | data = { 179 | 'wait': True 180 | } 181 | 182 | result = api.upload('/path/to/file.jpg', data); 183 | 184 | if result.get('success'): 185 | print result.get('kraked_url') 186 | else: 187 | print result.get('message') 188 | ```` 189 | 190 | ## Usage - User status 191 | 192 | If you want to check your quotas or your account status, you can use `user_status()` which will return a response similar to the following: 193 | 194 | 195 | ```json 196 | { 197 | "success": true, 198 | "active": true, 199 | "plan_name": "Enterprise", 200 | "quota_total": 64424509440, 201 | "quota_used": 313271610, 202 | "quota_remaining": 64111237830 203 | } 204 | ``` 205 | 206 | ```python 207 | from krakenio import Client 208 | 209 | # Initialize Kraken client 210 | api = Client(api_key="your-api-key", api_secret="your-api-secret") 211 | 212 | # Get user status 213 | result = api.user_status() 214 | 215 | if result.get("success"): 216 | print("Success:", result) 217 | else: 218 | print("Error:", result.get("message")) 219 | ``` 220 | 221 | ## Lossy Optimization 222 | 223 | When you decide to sacrifice just a small amount of image quality (usually unnoticeable to the human eye), you will be able to save up to 90% of the initial file weight. Lossy optimization will give you outstanding results with just a fraction of image quality loss. 224 | 225 | To use lossy optimizations simply set `lossy: true` in your request: 226 | 227 | ````python 228 | data = { 229 | 'wait': True, 230 | 'lossy': True 231 | } 232 | ```` 233 | 234 | ## Image Resizing 235 | 236 | Image resizing option is great for creating thumbnails or preview images in your applications. Kraken will first resize the given image and then optimize it with its vast array of optimization algorithms. The `resize` option needs a few parameters to be passed like desired `width` and/or `height` and a mandatory `strategy` property. For example: 237 | 238 | ````python 239 | from krakenio import Client 240 | 241 | api = Client('your-api-key', 'your-api-secret') 242 | 243 | data = { 244 | 'wait': True, 245 | 'lossy': True, 246 | 'resize': { 247 | 'width': 100, 248 | 'height': 75, 249 | 'strategy': 'crop' 250 | } 251 | } 252 | 253 | result = api.upload('/path/to/file.jpg', data); 254 | 255 | if result.get('success'): 256 | print result.get('kraked_url') 257 | else: 258 | print result.get('message') 259 | ```` 260 | 261 | The `strategy` property can have one of the following values: 262 | 263 | - `exact` - Resize by exact width/height. No aspect ratio will be maintained. 264 | - `portrait` - Exact width will be set, height will be adjusted according to aspect ratio. 265 | - `landscape` - Exact height will be set, width will be adjusted according to aspect ratio. 266 | - `auto` - The best strategy (portrait or landscape) will be selected for a given image according to aspect ratio. 267 | - `crop` - This option will crop your image to the exact size you specify with no distortion. 268 | 269 | ## WebP Compression 270 | 271 | WebP is a new image format introduced by Google in 2010 which supports both lossy and lossless compression. According to [Google](https://developers.google.com/speed/webp/), WebP lossless images are **26% smaller** in size compared to PNGs and WebP lossy images are **25-34% smaller** in size compared to JPEG images. 272 | 273 | WebP's lossy compression:WebP compression no longer requires setting `'webp': True` . Instead, you should make a standard optimization request, and Kraken.io will handle WebP conversion based on your configured settings. 274 | 275 | ````python 276 | data = { 277 | 'wait': True, 278 | 'lossy': True, 279 | 'convert': { 280 | 'format': 'webp' 281 | } 282 | } 283 | ```` 284 | 285 | ### Optimize WebP Image 286 | 287 | ```python 288 | data = { 289 | 'wait': True, 290 | 'lossy': True 291 | } 292 | ``` 293 | 294 | ## PDF Compression 295 | 296 | Kraken.io now supports PDF compression, allowing you to optimize PDF files with minimal loss of quality. 297 | 298 | Kraken API automatically determines the optimal compression settings based on the content type of the PDF (e.g., image-heavy, text-heavy, or mixed content). Additionally, users can optionally provide custom parameters to further control the compression process. 299 | 300 | ```python 301 | data = { 302 | 'wait': True 303 | } 304 | ``` 305 | 306 | **Optional Parameters:** 307 | 308 | [API Docs for PDF Compression](https://kraken.io/docs/pdf-compression) 309 | 310 | - `level` - Optimization level for the PDF. Available options are `screen`, `ebook`, `printer` and `prepress`. **Overrides DPI values**. 311 | - `quality` - JPEG quality for embedded images. Acceptable values: **1-100**. Higher values preserve more detail but increase file size. Default is **65**. 312 | - `dpi` - Resolution for images within the PDF. Default value is calculated based on the PDF type. Adjust this value based on your desired output quality. 313 | - `downsampleType` - Method used to downsample images. Available options are `bicubic`, `average` and `subsample` 314 | 315 | 316 | ```python 317 | data = { 318 | 'wait': True, 319 | 'level': 'ebook', 320 | 'quality': 60, 321 | 'dpi': 150, 322 | 'downsampleType': 'bicubic' 323 | } 324 | ``` 325 | 326 | ## External Storage 327 | 328 | Kraken API allows you to store optimized images directly in your S3, Cloud Files, Azure and SoftLayer. With just a few additional parameters your optimized images will be pushed to your external storage in no time. 329 | 330 | ### Amazon S3 331 | 332 | **Mandatory Parameters:** 333 | - `key` - Your unique Amazon "Access Key ID". 334 | - `secret` - Your unique Amazon "Secret Access Key". 335 | - `bucket` - Name of a destination container on your Amazon S3 account. 336 | - `region` - Name of the region your S3 bucket is located in. 337 | 338 | **Optional Parameters:** 339 | - `path` - Destination path in your S3 bucket (e.g. `"images/layout/header.jpg"`). Defaults to root `"/"`. 340 | - `acl` - Permissions of a destination object. This can be `"public_read"` or `"private"`. Defaults to `"public_read"`. 341 | 342 | The above parameters must be passed in a `s3_store` object: 343 | 344 | ````python 345 | from krakenio import Client 346 | 347 | api = Client('your-api-key', 'your-api-secret') 348 | 349 | data = { 350 | 'wait': True, 351 | 'lossy': True, 352 | 's3_store': { 353 | 'key': 'your-amazon-access-key', 354 | 'secret': 'your-amazon-secret-key', 355 | 'bucket': 'destination-bucket', 356 | 'region': 'us-east-1' 357 | } 358 | } 359 | 360 | result = api.upload('/path/to/file.jpg', data); 361 | 362 | if result.get('success'): 363 | print result.get('kraked_url') 364 | else: 365 | print result.get('message') 366 | ```` 367 | 368 | The `result` object will contain `kraked_url` key pointing directly to the optimized file in your Amazon S3 account: 369 | 370 | ````js 371 | { 372 | kraked_url: "http://s3.amazonaws.com/YOUR_CONTAINER/path/to/file.jpg" 373 | } 374 | ```` 375 | 376 | ### Rackspace Cloud Files 377 | 378 | **Mandatory Parameters:** 379 | - `user` - Your Rackspace username. 380 | - `key` - Your unique Cloud Files API Key. 381 | - `container` - Name of a destination container on your Cloud Files account. 382 | 383 | **Optional Parameters:** 384 | - `path` - Destination path in your container (e.g. `"images/layout/header.jpg"`). Defaults to root `"/"`. 385 | 386 | The above parameters must be passed in a `cf_store` object: 387 | 388 | ````python 389 | from krakenio import Client 390 | 391 | api = Client('your-api-key', 'your-api-secret') 392 | 393 | data = { 394 | 'wait': True, 395 | 'lossy': True, 396 | 'cf_store': { 397 | 'user': 'your-rackspace-username', 398 | 'key': 'your-rackspace-api-key', 399 | 'container': 'destination-container' 400 | } 401 | } 402 | 403 | result = api.upload('/path/to/file.jpg', data); 404 | 405 | if result.get('success'): 406 | print result.get('kraked_url') 407 | else: 408 | print result.get('message') 409 | ```` 410 | 411 | If your container is CDN-enabled, the optimization results will contain `kraked_url` which points directly to the optimized file location in your Cloud Files account, for example: 412 | 413 | ````js 414 | kraked_url: "http://e9ffc04970a269a54eeb-cc00fdd2d4f11dffd931005c9e8de53a.r2.cf1.rackcdn.com/path/to/file.jpg" 415 | ```` 416 | 417 | If your container is not CDN-enabled `kraked_url` will point to the optimized image URL in the Kraken API: 418 | 419 | ````js 420 | kraked_url: "http://dl.kraken.io/ec/df/a5/c55d5668b1b5fe9e420554c4ee/file.jpg" 421 | ```` 422 | 423 | ### Google Cloud Storage 424 | 425 | Kraken.io API allows you to store optimized images directly in your Google Cloud Storage (GCS) bucket. Follow the steps below to configure your GCS integration and securely store your optimized images. 426 | 427 | #### Prerequisites: 428 | 429 | Ensure you have access to Google Cloud Platform (GCP) and an active project where you will store your images. 430 | 431 | #### Mandatory Parameters: 432 | 433 | - `gcs_store.bucket` - Name of the destination bucket on your Google Cloud Storage account. 434 | - `gcs_store.credentials` - Your service account credentials (JSON format) to authenticate with GCS. 435 | 436 | #### Optional Parameters: 437 | 438 | - `gcs_store.path` - Destination path in your GCS bucket (e.g., "images/layout/header.jpg"). Defaults to root `/`. 439 | - `gcs_store.acl` - Permissions of the destination object. This can be "publicRead" or "private". Defaults to "private". 440 | - `gcs_store.metadata` - Metadata you would like to assign to your GCS object (optimized image). 441 | 442 | #### Important: 443 | 444 | Make sure your Google Cloud Storage bucket has the appropriate permissions set to allow Kraken.io API to store images. 445 | 446 | #### Step 1: Creating a Google Cloud Storage Bucket 447 | 448 | 1. Log in to your Google Cloud Console. 449 | 2. Navigate to the "Storage" section and select "Browser." 450 | 3. Click "Create bucket" and follow the prompts. 451 | 4. Note the bucket name for later use. 452 | 453 | #### Step 2: Obtaining GCS Credentials 454 | 455 | To interact with GCS through the API, you need appropriate credentials as a service account key: 456 | 457 | 1. Go to "IAM & Admin" in Google Cloud Console. 458 | 2. Select "Service Accounts" and click "Create Service Account." 459 | 3. Enter a name and description for the service account. 460 | 4. Assign necessary roles like "Storage Object Admin" or "Storage Object Creator." 461 | 5. Click "Create Key" and choose JSON type. This will download a JSON file with your credentials. 462 | 6. Securely store this JSON file. It contains sensitive information that allows access to your GCS resources. 463 | 464 | #### Step 3: Configuring Your Kraken.io API Request 465 | 466 | Include the necessary details in your Kraken.io API request to store the optimized image directly in your GCS bucket. Insert the JSON file's contents into the `credentials` property inside `gcs_store`. 467 | 468 | ```python 469 | import json 470 | import requests 471 | 472 | from krakenio import Client 473 | 474 | api = Client("your_api_key", "your_api_secret") 475 | 476 | with open("path/to/your/credentials.json", "r") as f: 477 | credentials = json.load(f) 478 | 479 | params = { 480 | "wait": True, 481 | "lossy": True, 482 | "gcs_store": { 483 | "acl": "private", 484 | "bucket": "your-bucket-name", 485 | "path": "path/to/your/image.png", 486 | "credentials": credentials 487 | } 488 | } 489 | 490 | result = api.url("https://example.com/image.png", params) 491 | 492 | if result.get("success"): 493 | print(f"Success. Optimized image URL: {result.get('kraked_url')}") 494 | else: 495 | print(f"Fail. Error message: {result.get('message')}") 496 | 497 | ``` 498 | 499 | ## LICENSE - MIT 500 | 501 | Copyright (c) 2025 Nekkra UG 502 | 503 | Permission is hereby granted, free of charge, to any person 504 | obtaining a copy of this software and associated documentation 505 | files (the "Software"), to deal in the Software without 506 | restriction, including without limitation the rights to use, 507 | copy, modify, merge, publish, distribute, sublicense, and/or sell 508 | copies of the Software, and to permit persons to whom the 509 | Software is furnished to do so, subject to the following 510 | conditions: 511 | 512 | The above copyright notice and this permission notice shall be 513 | included in all copies or substantial portions of the Software. 514 | 515 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 516 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 517 | OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 518 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 519 | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 520 | WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 521 | FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 522 | OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /krakenio/__init__.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | 3 | __version__ = "2.0.0" 4 | 5 | 6 | import json 7 | from io import BytesIO 8 | import requests 9 | import sys 10 | 11 | class Client: 12 | """Client for interacting with the Kraken.io API.""" 13 | 14 | def __init__(self, api_key, api_secret): 15 | if not api_key: 16 | raise ValueError("Please provide a Kraken.io API Key") 17 | if not api_secret: 18 | raise ValueError("Please provide a Kraken.io API Secret") 19 | 20 | self.api_key = api_key 21 | self.api_secret = api_secret 22 | self.api_base_url = "https://api.kraken.io/" 23 | self.api_v1_url = self.api_base_url + "v1/" 24 | self.auth = {"auth": {"api_key": self.api_key, "api_secret": self.api_secret}} 25 | self.headers = { 26 | "User-Agent": "Kraken-Python-Client/0.2.0 (Python/3.x; +https://github.com/krakenio/kraken-python)", 27 | "Content-Type": "application/json", 28 | } 29 | 30 | def url(self, image_url, params): 31 | """Optimize an image from a URL.""" 32 | if not image_url: 33 | raise ValueError("Please provide a valid image URL for optimization") 34 | if not params: 35 | raise ValueError("Please provide image optimization parameters") 36 | 37 | api_endpoint = self.api_v1_url + "url" 38 | request_data = params.copy() 39 | request_data["url"] = image_url 40 | request_data.update(self.auth) 41 | 42 | response = requests.post(api_endpoint, headers=self.headers, data=json.dumps(request_data)) 43 | return self._handle_response(response) 44 | 45 | def upload(self, file_path, params): 46 | """Upload and optimize a local image file.""" 47 | if not file_path: 48 | raise ValueError("Please provide a valid file path to the image") 49 | if not params: 50 | raise ValueError("Please provide image optimization parameters") 51 | 52 | api_endpoint = self.api_v1_url + "upload" 53 | request_data = params.copy() 54 | request_data.update(self.auth) 55 | 56 | with open(file_path, "rb") as file: 57 | files = {"file": file} 58 | response = requests.post(api_endpoint, headers={"User-Agent": self.headers["User-Agent"]}, files=files, data={"data": json.dumps(request_data)}) 59 | return self._handle_response(response) 60 | 61 | def upload_bytesio(self, img, params): 62 | """Upload and optimize an image from a BytesIO object.""" 63 | if not isinstance(img, BytesIO): 64 | raise ValueError("Please provide a valid BytesIO file-like object") 65 | if not params: 66 | raise ValueError("Please provide image optimization parameters") 67 | 68 | api_endpoint = self.api_v1_url + "upload" 69 | request_data = params.copy() 70 | request_data.update(self.auth) 71 | 72 | filename = getattr(img, "name", "image.jpg") 73 | files = {"file": (filename, img)} 74 | 75 | response = requests.post(api_endpoint, headers={"User-Agent": self.headers["User-Agent"]}, files=files, data={"data": json.dumps(request_data)}, timeout=30) 76 | return self._handle_response(response) 77 | 78 | def user_status(self): 79 | """Check Kraken.io user status (quota usage, plan, etc.).""" 80 | api_endpoint = self.api_base_url + "user_status" 81 | response = requests.post(api_endpoint, headers=self.headers, data=json.dumps(self.auth)) 82 | return self._handle_response(response) 83 | 84 | def _handle_response(self, response): 85 | """Handles API response and raises errors when needed.""" 86 | try: 87 | response.raise_for_status() 88 | except requests.HTTPError: 89 | try: 90 | error_json = response.json() 91 | print(f"[Kraken Error] HTTP {response.status_code}: {error_json}", file=sys.stderr) 92 | except ValueError: 93 | print(f"[Kraken Error] HTTP {response.status_code}: {response.text}", file=sys.stderr) 94 | raise 95 | return response.json() 96 | 97 | 98 | # Example usage 99 | if __name__ == "__main__": 100 | client = Client("your_api_key", "your_api_secret") 101 | 102 | # Optimize image from URL 103 | params = {"wait": True, "lossy": True} 104 | result = client.url("https://example.com/image.jpg", params) 105 | print("Optimized URL:", result.get("kraked_url")) 106 | 107 | # Optimize image from local file 108 | result = client.upload("/path/to/image.jpg", params) 109 | print("Optimized URL:", result.get("kraked_url")) 110 | 111 | # Check user status 112 | user_status = client.user_status() 113 | print("User status:", user_status) 114 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | requests>=2.28.0 2 | urllib3<2.0 3 | requests-mock>=1.9.0 4 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bdist_wheel] 2 | universal=1 -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | 3 | from setuptools import setup, find_packages 4 | 5 | NAME = "krakenio" 6 | VERSION = "0.2.0" 7 | DESCRIPTION = "Kraken.io API Client" 8 | LONG_DESCRIPTION = ( 9 | "Official Python client for integrating with the Kraken.io Image Optimizer, " 10 | "providing fast and powerful image optimization capabilities." 11 | ) 12 | URL = "https://github.com/kraken-io/kraken-python" 13 | AUTHOR = "Nekkra UG" 14 | AUTHOR_EMAIL = "support@kraken.io" 15 | LICENSE = "MIT" 16 | KEYWORDS = ["kraken", "kraken.io", "image", "optimizer", "resizer"] 17 | 18 | INSTALL_REQUIRES = [ 19 | "requests>=2.28.0", 20 | "urllib3<2.0", 21 | ] 22 | 23 | EXTRAS_REQUIRE = { 24 | "test": [ 25 | "python-dotenv>=1.0.0", 26 | ], 27 | } 28 | 29 | CLASSIFIERS = [ 30 | "Development Status :: 5 - Production/Stable", 31 | "Intended Audience :: Developers", 32 | "Natural Language :: English", 33 | "License :: OSI Approved :: MIT License", 34 | "Programming Language :: Python :: 3.8", 35 | "Programming Language :: Python :: 3.9", 36 | "Programming Language :: Python :: 3.10", 37 | "Programming Language :: Python :: 3.11", 38 | "Programming Language :: Python :: 3.12", 39 | "Topic :: Software Development", 40 | "Topic :: Software Development :: Libraries", 41 | "Topic :: Software Development :: Libraries :: Python Modules", 42 | "Topic :: Utilities", 43 | ] 44 | 45 | required_fields = { 46 | "name": NAME, 47 | "version": VERSION, 48 | "description": DESCRIPTION, 49 | "long_description": LONG_DESCRIPTION, 50 | "long_description_content_type": "text/plain", 51 | "url": URL, 52 | "author": AUTHOR, 53 | "author_email": AUTHOR_EMAIL, 54 | "license": LICENSE, 55 | "packages": find_packages(exclude=["tests", "*.tests", "*.tests.*"]), 56 | "install_requires": INSTALL_REQUIRES, 57 | "extras_require": EXTRAS_REQUIRE, 58 | "classifiers": CLASSIFIERS, 59 | "keywords": KEYWORDS, 60 | "python_requires": ">=3.8", 61 | } 62 | 63 | for field_name, field_value in required_fields.items(): 64 | if not field_value: 65 | raise ValueError(f"Missing required field: {field_name}") 66 | 67 | setup(**required_fields) -------------------------------------------------------------------------------- /tests/test.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kraken-io/kraken-python/d8ff5824b7a3b66d9d16fe6e86673e198f03e8c5/tests/test.jpg -------------------------------------------------------------------------------- /tests/test_client.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import os 3 | from io import BytesIO 4 | from dotenv import load_dotenv 5 | from krakenio import Client 6 | 7 | # Load environment variables from .env 8 | load_dotenv() 9 | 10 | 11 | class TestKrakenClient(unittest.TestCase): 12 | def setUp(self): 13 | # Load API credentials from .env 14 | self.api_key = os.getenv("KRAKEN_API_KEY") 15 | self.api_secret = os.getenv("KRAKEN_API_SECRET") 16 | 17 | # Check if credentials are provided 18 | if not self.api_key or not self.api_secret: 19 | raise ValueError("KRAKEN_API_KEY and KRAKEN_API_SECRET must be set in .env") 20 | 21 | self.client = Client(api_key=self.api_key, api_secret=self.api_secret) 22 | self.params = {"lossy": True, "wait": True} # 'wait': True ensures immediate response 23 | 24 | # Expected response format for successful calls 25 | self.expected_success_keys = { 26 | "success": bool, 27 | "file_name": str, 28 | "original_size": int, 29 | "kraked_size": int, 30 | "saved_bytes": int, 31 | "kraked_url": str, 32 | } 33 | 34 | # Expected response format for error calls 35 | self.expected_error_keys = { 36 | "success": bool, 37 | "message": str, 38 | } 39 | 40 | def test_init_missing_api_key(self): 41 | with self.assertRaises(ValueError): 42 | Client(api_key=None, api_secret="secret") 43 | 44 | def test_init_missing_api_secret(self): 45 | with self.assertRaises(ValueError): 46 | Client(api_key="key", api_secret=None) 47 | 48 | def test_url_success(self): 49 | image_url = "https://assets.kraken.io/assets/images/index-results/05-original.jpg" 50 | result = self.client.url(image_url=image_url, params=self.params) 51 | self.assertTrue(result["success"], f"Expected success, got: {result}") 52 | self.assertIn("kraked_url", result, "Expected 'kraked_url' in response") 53 | self.assertIsInstance(result, dict, "Response should be a dictionary") 54 | for key, expected_type in self.expected_success_keys.items(): 55 | self.assertIn(key, result, f"Missing key: {key}") 56 | self.assertIsInstance(result[key], expected_type) 57 | 58 | def test_url_failure(self): 59 | image_url = "https://assets.kraken.io/assets/images/index-results/05-original-false.jpg" 60 | try: 61 | result = self.client.url(image_url=image_url, params=self.params) 62 | self.assertFalse(result["success"], f"Expected failure, got: {result}") 63 | self.assertIsInstance(result, dict, "Error response should be a dictionary") 64 | for key, expected_type in self.expected_error_keys.items(): 65 | self.assertIn(key, result, f"Missing key: {key}") 66 | self.assertIsInstance(result[key], expected_type) 67 | self.assertEqual(result["success"], False, "Success should be False in error response") 68 | except Exception as e: 69 | self.assertTrue(isinstance(e, Exception), "Expected an exception for invalid URL") 70 | 71 | def test_upload_success(self): 72 | file_path = os.path.join(os.path.dirname(__file__), "test.jpg") 73 | self.assertTrue(os.path.exists(file_path), f"File not found: {file_path}") 74 | result = self.client.upload(file_path=file_path, params=self.params) 75 | self.assertTrue(result["success"], f"Expected success, got: {result}") 76 | self.assertIn("kraked_url", result, "Expected 'kraked_url' in response") 77 | self.assertIsInstance(result, dict, "Response should be a dictionary") 78 | for key, expected_type in self.expected_success_keys.items(): 79 | self.assertIn(key, result, f"Missing key: {key}") 80 | self.assertIsInstance(result[key], expected_type) 81 | 82 | def test_user_status(self): 83 | result = self.client.user_status() 84 | self.assertTrue(result["success"], f"Expected success, got: {result}") 85 | self.assertIn("active", result, "Expected 'active' in response") 86 | self.assertIn("plan_name", result, "Expected 'plan_name' in response") 87 | self.assertIn("quota_total", result, "Expected 'quota_total' in response") 88 | self.assertIn("quota_used", result, "Expected 'quota_used' in response") 89 | self.assertIn("quota_remaining", result, "Expected 'quota_remaining' in response") 90 | self.assertIsInstance(result["quota_total"], int, "quota_total should be an integer") 91 | self.assertIsInstance(result["quota_used"], int, "quota_used should be an integer") 92 | self.assertIsInstance(result["quota_remaining"], int, "quota_remaining should be an integer") 93 | 94 | if __name__ == "__main__": 95 | unittest.main() 96 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py38, py39, py310, py311, py312, py313 3 | 4 | [testenv] 5 | deps = 6 | requests>=2.28.0 7 | urllib3<2.0 8 | python-dotenv>=1.0.0 9 | commands = 10 | python -m unittest discover -s tests -v --------------------------------------------------------------------------------