aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGravatar Shakya Majumdar <[email protected]>2021-04-11 10:22:15 +0530
committerGravatar Shakya Majumdar <[email protected]>2021-04-11 10:22:15 +0530
commite51dfab90242822aeab6bd42e69296c133efe042 (patch)
treed6363465bcc2c8a936abb6c5d1f3231f961a6690
parentchange background color to match discord theme exactly (diff)
add caching
-rw-r--r--.gitignore2
-rw-r--r--bot/exts/evergreen/latex.py14
2 files changed, 15 insertions, 1 deletions
diff --git a/.gitignore b/.gitignore
index d3d2bb8d..ce122d29 100644
--- a/.gitignore
+++ b/.gitignore
@@ -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."""