advent22/api/advent22_api/routers/days.py
2022-10-14 22:15:20 +00:00

147 lines
3.5 KiB
Python

import colorsys
import random
import re
# from datetime import date
from io import BytesIO
from fastapi import APIRouter, Depends
from fastapi.responses import StreamingResponse
from PIL import ImageDraw, ImageFont
from ..dav_common import dav_get_file, dav_list_files
from ._image import AdventImage
router = APIRouter(prefix="/days", tags=["days"])
loesungswort = "ABCDEFGHIJKLMNOPQRSTUVWX"
async def shuffle(string: str) -> str:
rnd = random.Random(loesungswort)
return "".join(rnd.sample(string, len(string)))
@router.on_event("startup")
async def startup() -> None:
print(loesungswort)
print(await shuffle(loesungswort))
@router.get("/letter/{index}")
async def get_letter(
index: int,
) -> str:
return (await shuffle(loesungswort))[index]
# @router.get("/date")
# def get_date() -> int:
# return date.today().day
# @router.get(
# "/picture",
# response_class=StreamingResponse,
# )
# async def get_picture():
# img = Image.open("hand.png").convert("RGBA")
# d1 = ImageDraw.Draw(img)
# font = ImageFont.truetype("Lena.ttf", 50)
# d1.text((260, 155), "W", font=font, fill=(0, 0, 255))
# # d1.text(xy=(400, 210), text="Deine Hände auch?",
# # font=Font, fill=(255, 0, 0))
# img_buffer = BytesIO()
# img.save(img_buffer, format="PNG", quality=85)
# img_buffer.seek(0)
# return StreamingResponse(
# content=img_buffer,
# media_type="image/png",
# )
_RE_IMAGE_FILE = re.compile(
r"\.(gif|jpe?g|tiff?|png|bmp)$",
flags=re.IGNORECASE,
)
async def load_image(
index: int,
) -> AdventImage:
"""
Bild laden und einen quadratischen Ausschnitt
aus der Mitte nehmen
"""
# Bild laden
rnd = random.Random(f"{loesungswort}{index}")
dat = rnd.choice(await dav_list_files(_RE_IMAGE_FILE, "/images"))
img_buffer = await dav_get_file(dat)
return await AdventImage.load_standard(img_buffer)
@router.get(
"/picture/{index}",
response_class=StreamingResponse,
)
async def get_picture_for_day(
index: int,
letter: str = Depends(get_letter),
adv_img: AdventImage = Depends(load_image),
) -> StreamingResponse:
"""
Bild für einen Tag erstellen
"""
# Font laden
font = ImageFont.truetype("Lena.ttf", 50)
# Position des Buchstaben bestimmen
rnd = random.Random(f"{loesungswort}{index}")
xy = tuple(rnd.choices(range(30, 470), k=2))
# betroffenen Bildbereich bestimmen
text_box = await adv_img.get_text_box(
xy=xy,
text=letter,
font=font,
)
if text_box is not None:
# Durchschnittsfarbe bestimmen
text_color = await adv_img.get_average_color(
box=text_box,
)
# etwas heller/dunkler machen
tc_h, tc_s, tc_v = colorsys.rgb_to_hsv(*text_color)
tc_v = int((tc_v - 127) * 0.97) + 127
if tc_v < 127:
tc_v += 3
else:
tc_v -= 3
text_color = colorsys.hsv_to_rgb(tc_h, tc_s, tc_v)
text_color = tuple(int(val) for val in text_color)
# Buchstaben verstecken
ImageDraw.Draw(adv_img.img).text(
xy=xy,
text=letter,
font=font,
anchor="mm",
fill=text_color,
)
# Bilddaten in Puffer laden
img_buffer = BytesIO()
adv_img.img.save(img_buffer, format="JPEG", quality=85)
img_buffer.seek(0)
return StreamingResponse(
content=img_buffer,
media_type="image/jpeg",
)