Skip to content

Commit

Permalink
advent: increase interaction timeout and optimise
Browse files Browse the repository at this point in the history
optimisation to cache image data when switching to/from full view.
this is done by lru_cache, currently with a size of 16 (enough for
8 /leaderboard calls, with 2 image each)
  • Loading branch information
katrinafyi committed Dec 3, 2024
1 parent da303f8 commit d39fb19
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
4 changes: 2 additions & 2 deletions uqcsbot/advent.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import io
import os
from datetime import datetime
from datetime import datetime, timedelta
from random import choices
from typing import Any, Callable, Dict, Iterable, List, Optional, Literal
import requests
Expand Down Expand Up @@ -141,7 +141,7 @@

class LeaderboardView(discord.ui.View):
TRUNCATED_COUNT = 20
TIMEOUT = 180 # seconds
TIMEOUT = timedelta(hours=24).total_seconds()

def __init__(
self,
Expand Down
17 changes: 14 additions & 3 deletions uqcsbot/utils/advent_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@
Dict,
Optional,
Callable,
NamedTuple,
Tuple,
cast,
)
from dataclasses import dataclass
from collections import defaultdict
from collections.abc import Hashable
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
from functools import lru_cache
from io import BytesIO

import PIL.Image
Expand All @@ -33,8 +35,16 @@
Times = Dict[Star, Seconds]
Delta = Optional[Seconds]
Json = Dict[str, Any]

Colour = str
ColourFragment = NamedTuple("ColourFragment", [("text", str), ("colour", Colour)])


@dataclass(frozen=True)
class ColourFragment(Hashable):
text: str
colour: Colour


Leaderboard = list[str | ColourFragment]

# Puzzles are unlocked at midnight EST.
Expand Down Expand Up @@ -437,6 +447,7 @@ def _isolate_leaderboard_layers(
return spaces_str, cast(Dict[str, Any], layers)


@lru_cache(maxsize=16)
def render_leaderboard_to_image(leaderboard: Leaderboard) -> bytes:
spaces, layers = _isolate_leaderboard_layers(leaderboard)

Expand All @@ -462,7 +473,7 @@ def render_leaderboard_to_image(leaderboard: Leaderboard) -> bytes:

buf = BytesIO()
img.save(buf, format="PNG", optimize=True)
return buf.getvalue() # XXX: why do we need to getvalue()?
return buf.getvalue()


def build_leaderboard(
Expand Down

0 comments on commit d39fb19

Please sign in to comment.