diff options
| author | 2021-04-11 10:22:15 +0530 | |
|---|---|---|
| committer | 2021-04-11 10:22:15 +0530 | |
| commit | e51dfab90242822aeab6bd42e69296c133efe042 (patch) | |
| tree | d6363465bcc2c8a936abb6c5d1f3231f961a6690 | |
| parent | change background color to match discord theme exactly (diff) | |
add caching
| -rw-r--r-- | .gitignore | 2 | ||||
| -rw-r--r-- | bot/exts/evergreen/latex.py | 14 | 
2 files changed, 15 insertions, 1 deletions
@@ -1,7 +1,7 @@  # bot (project-specific)  log/*  data/* - +_latex_cache/* diff --git a/bot/exts/evergreen/latex.py b/bot/exts/evergreen/latex.py index d140e79d..0c29f958 100644 --- a/bot/exts/evergreen/latex.py +++ b/bot/exts/evergreen/latex.py @@ -1,4 +1,6 @@  import asyncio +import hashlib +import pathlib  import re  from concurrent.futures import ThreadPoolExecutor  from io import BytesIO @@ -28,6 +30,10 @@ FORMATTED_CODE_REGEX = re.compile(      re.DOTALL | re.IGNORECASE,              # "." also matches newlines, case insensitive  ) +CACHE_DIRECTORY = pathlib.Path("_latex_cache") +if not CACHE_DIRECTORY.exists(): +    CACHE_DIRECTORY.mkdir() +  class Latex(commands.Cog):      """Renders latex.""" @@ -60,7 +66,12 @@ class Latex(commands.Cog):      async def latex(self, ctx: commands.Context, *, text: str) -> None:          """Renders the text in latex and sends the image."""          text = self._prepare_input(text) +        query_hash = hashlib.md5(text.encode()).hexdigest() +        image_path = CACHE_DIRECTORY.joinpath(f"{query_hash}.png")          async with ctx.typing(): +            if image_path.exists(): +                await ctx.send(file=discord.File(image_path)) +                return              with ThreadPoolExecutor() as pool:                  image = await asyncio.get_running_loop().run_in_executor( @@ -69,6 +80,9 @@ class Latex(commands.Cog):              await ctx.send(file=discord.File(image, "latex.png")) +            with open(image_path, "wb") as f: +                f.write(image.getbuffer()) +  def setup(bot: commands.Bot) -> None:      """Load the Latex Cog."""  |