Skip to content

Commit

Permalink
ruff auto fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
ChrisLovering committed Sep 5, 2023
1 parent 9b28d38 commit 8773613
Show file tree
Hide file tree
Showing 6 changed files with 38 additions and 42 deletions.
Empty file added api/__init__.py
Empty file.
10 changes: 5 additions & 5 deletions api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from os import getenv
from pathlib import Path
from time import time
from typing import Optional, Union
from typing import Union

from fastapi import FastAPI, Request, Response
from fastapi.exceptions import HTTPException
Expand Down Expand Up @@ -42,7 +42,7 @@ def make_file_path(dh: str, request_url: URL) -> str:


@app.get("/duck", response_model=DuckResponse, status_code=201)
async def get_duck(request: Request, response: Response, seed: Optional[int] = None) -> DuckResponse:
async def get_duck(request: Request, response: Response, seed: int | None = None) -> DuckResponse:
"""Create a new random duck, with an optional seed."""
dh = sha1(str(time()).encode()).hexdigest()
file = CACHE / f"{dh}.png"
Expand Down Expand Up @@ -74,7 +74,7 @@ async def post_duck(request: Request, response: Response, duck: DuckRequest = No


@app.get("/manduck", response_model=DuckResponse, status_code=201)
async def get_man_duck(request: Request, response: Response, seed: Optional[int] = None) -> DuckResponse:
async def get_man_duck(request: Request, response: Response, seed: int | None = None) -> DuckResponse:
"""Create a new man_duck, with an optional seed."""
dh = sha1(str(time()).encode()).hexdigest()

Expand Down Expand Up @@ -108,7 +108,7 @@ async def post_man_duck(request: Request, response: Response, manduck: ManDuckRe


@app.get("/details/{type}", response_model=Union[ManDuckDetails, DuckyDetails])
async def get_details(type: str) -> Union[ManDuckDetails, DuckyDetails]:
async def get_details(type: str) -> ManDuckDetails | DuckyDetails:
"""Get details about accessories which can be used to build ducks/man-ducks."""
details = {
"ducky": DuckyDetails(
Expand All @@ -127,7 +127,7 @@ async def get_details(type: str) -> Union[ManDuckDetails, DuckyDetails]:
variation_2=list(ManDuckBuilder.EQUIPMENTS["variation_2"]),
),
variations=list(ManDuckBuilder.VARIATIONS),
)
),
}

return details.get(type, Response("Requested type is not available", 400))
9 changes: 4 additions & 5 deletions api/models.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from typing import Optional

from pydantic import BaseModel

Expand All @@ -25,15 +24,15 @@ class DressColors(BaseModel):
"""Valid options for a man ducky dress colors."""

shirt: PartOption
pants: Optional[PartOption]
pants: PartOption | None


class Accessories(BaseModel):
"""Valid accessories for a duck."""

hat: Optional[str]
outfit: Optional[str]
equipment: Optional[str]
hat: str | None
outfit: str | None
equipment: str | None


class DuckRequest(BaseModel):
Expand Down
7 changes: 3 additions & 4 deletions quackstack/colors.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
from collections import namedtuple
from colorsys import hls_to_rgb, rgb_to_hls
from random import Random
from typing import Tuple

DuckyColors = namedtuple("DuckyColors", "eye eye_wing wing body beak")
DressColors = namedtuple("DressColors", "shirt pants")


def make_color(random: Random, hue: float, dark_variant: bool) -> Tuple[float, float, float]:
def make_color(random: Random, hue: float, dark_variant: bool) -> tuple[float, float, float]:
"""Make a nice hls color to use in a duck."""
saturation = 1
lightness = random.uniform(.7, .85)
Expand Down Expand Up @@ -53,10 +52,10 @@ def make_man_duck_colors(ducky: tuple) -> DressColors:
second_varient = [((hls_[0] * 360 + 240) % 360) / 360, hls_[1], hls_[2]]

first = tuple(
map(lambda x: round(x * 255), hls_to_rgb(first_varient[0], first_varient[1], first_varient[2]))
round(x * 255) for x in hls_to_rgb(first_varient[0], first_varient[1], first_varient[2])
)
second = tuple(
map(lambda x: round(x * 255), hls_to_rgb(second_varient[0], second_varient[1], second_varient[2]))
round(x * 255) for x in hls_to_rgb(second_varient[0], second_varient[1], second_varient[2])
)

return DressColors(first, second)
17 changes: 8 additions & 9 deletions quackstack/ducky.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
from collections import namedtuple
from pathlib import Path
from random import Random
from typing import Optional, Tuple

from PIL import Image, ImageChops

Expand Down Expand Up @@ -32,13 +31,13 @@ class DuckBuilder:
filename.stem: filename for filename in (ASSETS_PATH / "accessories/outfits").iterdir()
}

def __init__(self, seed: Optional[int] = None):
def __init__(self, seed: int | None = None) -> None:
self.random = Random(seed)
self.output: Image.Image = Image.new("RGBA", DUCK_SIZE, color=(0, 0, 0, 0))

def generate_template(
self, colors: DuckyColors, hat: str, outfit: str, equipment: str
) -> Tuple[dict, DuckyColors, str, str, str]:
self, colors: DuckyColors, hat: str, outfit: str, equipment: str,
) -> tuple[dict, DuckyColors, str, str, str]:
"""Generate a duck structure from given configuration."""
template = {
"beak": (self.templates[5], colors.beak),
Expand All @@ -57,14 +56,14 @@ def generate_template(

return template, colors, hat, outfit, equipment

def generate_from_options(self, options: dict) -> Tuple[dict, DuckyColors, str, str, str]:
def generate_from_options(self, options: dict) -> tuple[dict, DuckyColors, str, str, str]:
"""Generate a duck from the provided request."""
return self.generate_template(
colors=DuckyColors(**options["colors"]),
**options["accessories"]
**options["accessories"],
)

def generate(self, *, options: Optional[dict] = None) -> ProceduralDucky:
def generate(self, *, options: dict | None = None) -> ProceduralDucky:
"""Actually generate the ducky from the provided request, else generate a random one."""
if options:
template, colors, hat, outfit, equipment = self.generate_from_options(options)
Expand All @@ -73,7 +72,7 @@ def generate(self, *, options: Optional[dict] = None) -> ProceduralDucky:
make_duck_colors(self.random),
self.random.choice([*list(self.hats), None]),
self.random.choice([*list(self.outfits), None]),
self.random.choice([*list(self.equipments), None])
self.random.choice([*list(self.equipments), None]),
)

for key in ["beak", "body", "eye", "equipment", "wing", "eye_wing", "hat", "outfit"]:
Expand All @@ -82,7 +81,7 @@ def generate(self, *, options: Optional[dict] = None) -> ProceduralDucky:

return ProceduralDucky(self.output, colors, hat, equipment, outfit)

def apply_layer(self, layer_path: str, recolor: Optional[Tuple[int, int, int]] = None) -> None:
def apply_layer(self, layer_path: str, recolor: tuple[int, int, int] | None = None) -> None:
"""Add the given layer on top of the ducky. Can be recolored with the recolor argument."""
try:
layer = Image.open(layer_path)
Expand Down
37 changes: 18 additions & 19 deletions quackstack/manducky.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
from collections import namedtuple
from pathlib import Path
from random import Random
from typing import Optional, Tuple

from PIL import Image, ImageChops

Expand All @@ -12,7 +11,7 @@
from .ducky import ProceduralDucky

ManDucky = namedtuple("ManDucky", "image")
Color = Tuple[int, int, int]
Color = tuple[int, int, int]

ASSETS_PATH = Path(qs_file).parent / Path("assets", "manduck")
MAN_DUCKY_SIZE = (600, 1194)
Expand All @@ -31,59 +30,59 @@ class ManDuckBuilder:
},
"variation_2": {
filename.stem: filename for filename in (ASSETS_PATH / "accessories/outfits/variation_2").iterdir()
}
},
}
EQUIPMENTS = {
"variation_1": {
filename.stem: filename for filename in (ASSETS_PATH / "accessories/equipment/variation_1").iterdir()
},
"variation_2": {
filename.stem: filename for filename in (ASSETS_PATH / "accessories/equipment/variation_2").iterdir()
}
},
}

def __init__(self, seed: Optional[int] = None):
def __init__(self, seed: int | None = None) -> None:
self.random = Random(seed)
self.output: Image.Image = Image.new("RGBA", MAN_DUCKY_SIZE, color=(0, 0, 0, 0))

def generate_template(
self, ducky: ProceduralDucky, dress_colors: DressColors, variation_: int
self, ducky: ProceduralDucky, dress_colors: DressColors, variation_: int,
) -> dict:
"""Generate a man duck structure from given configuration."""
variation = f"variation_{variation_}"

template = {
"bill": (
ASSETS_PATH / "templates/bill.png",
ducky.colors.beak
ducky.colors.beak,
),
"head": (
ASSETS_PATH / "templates/head.png",
ducky.colors.body
ducky.colors.body,
),
"eye": (
ASSETS_PATH / "templates/eye.png",
ducky.colors.eye
ducky.colors.eye,
),
"hands": (
ASSETS_PATH / f"templates/{variation}/hands.png",
ducky.colors.wing
)
ducky.colors.wing,
),
}

if variation_ == 1:
template["dress"] = (
ASSETS_PATH / "templates/variation_1/dress.png",
dress_colors.shirt
dress_colors.shirt,
)
else:
template["shirt"] = (
ASSETS_PATH / "templates/variation_2/shirt.png",
dress_colors.shirt
dress_colors.shirt,
)
template["pants"] = (
ASSETS_PATH / "templates/variation_2/pants.png",
dress_colors.pants
dress_colors.pants,
)

if ducky.hat:
Expand All @@ -102,29 +101,29 @@ def generate_from_options(self, options: dict) -> dict:
return self.generate_template(
ducky=ProceduralDucky(None, colors, **accessories),
dress_colors=DressColors(**options["dress_colors"]),
variation_=options["variation"]
variation_=options["variation"],
)

def generate(
self,
*,
options: Optional[dict] = None,
ducky: Optional[ProceduralDucky] = None
options: dict | None = None,
ducky: ProceduralDucky | None = None,
) -> ManDucky:
"""Actually generate the man ducky from the provided request, else generate a random one.."""
if options:
template = self.generate_from_options(options)
else:
template = self.generate_template(
ducky, make_man_duck_colors(ducky.colors.body), self.random.choice(self.VARIATIONS)
ducky, make_man_duck_colors(ducky.colors.body), self.random.choice(self.VARIATIONS),
)

for item in template.values():
self.apply_layer(*item)

return ManDucky(self.output)

def apply_layer(self, layer_path: str, recolor: Optional[Color] = None) -> None:
def apply_layer(self, layer_path: str, recolor: Color | None = None) -> None:
"""Add the given layer on top of the ducky. Can be recolored with the recolor argument."""
try:
layer = Image.open(layer_path)
Expand Down

0 comments on commit 8773613

Please sign in to comment.