Initial commit
This commit is contained in:
67
src/kakigoori/__init__.py
Normal file
67
src/kakigoori/__init__.py
Normal file
@@ -0,0 +1,67 @@
|
||||
import urllib.parse
|
||||
import uuid
|
||||
from io import BytesIO
|
||||
|
||||
import aiohttp
|
||||
|
||||
from kakigoori.kakigoori_image_format import KakigooriImageFormat
|
||||
|
||||
|
||||
class Kakigoori:
|
||||
api_key = None
|
||||
base_url = None
|
||||
|
||||
def __init__(self, api_key=None, base_url="https://kakigoori.dev"):
|
||||
self.api_key = api_key
|
||||
self.base_url = base_url
|
||||
|
||||
async def upload(self, image: bytes) -> tuple[str, str]:
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.post(
|
||||
urllib.parse.urljoin(self.base_url, "/upload/"),
|
||||
headers={"Authorization": f"{self.api_key}"},
|
||||
data={"file": BytesIO(image)},
|
||||
) as response:
|
||||
if response.status != 200 and response.status != 201:
|
||||
raise Exception(f"Server returned error {response.status}")
|
||||
|
||||
response = await response.json()
|
||||
|
||||
return response["id"], response["created"]
|
||||
|
||||
async def get_image(
|
||||
self,
|
||||
image_id: str | uuid.UUID,
|
||||
image_format: KakigooriImageFormat | str = KakigooriImageFormat.auto,
|
||||
height: int | None = None,
|
||||
width: int | None = None,
|
||||
) -> bytes:
|
||||
if isinstance(image_id, str):
|
||||
image_id = uuid.UUID(image_id)
|
||||
|
||||
if isinstance(image_format, KakigooriImageFormat):
|
||||
image_format = image_format.value
|
||||
|
||||
if height and width:
|
||||
if height > width:
|
||||
width = None
|
||||
else:
|
||||
height = None
|
||||
|
||||
if height:
|
||||
url = urllib.parse.urljoin(
|
||||
self.base_url, f"/{image_id}/height/{height}/{image_format}/"
|
||||
)
|
||||
elif width:
|
||||
url = urllib.parse.urljoin(
|
||||
self.base_url, f"/{image_id}/width/{width}/{image_format}/"
|
||||
)
|
||||
else:
|
||||
url = urllib.parse.urljoin(self.base_url, f"/{image_id}/{image_format}/")
|
||||
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(url, allow_redirects=True) as response:
|
||||
if response.status == 200:
|
||||
return await response.read()
|
||||
else:
|
||||
raise Exception(f"Server returned error {response.status}")
|
8
src/kakigoori/kakigoori_image_format.py
Normal file
8
src/kakigoori/kakigoori_image_format.py
Normal file
@@ -0,0 +1,8 @@
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class KakigooriImageFormat(str, Enum):
|
||||
auto = "auto"
|
||||
original = "original"
|
||||
avif = "avif"
|
||||
webp = "webp"
|
0
src/kakigoori/py.typed
Normal file
0
src/kakigoori/py.typed
Normal file
Reference in New Issue
Block a user