diff options
author | 2022-01-10 13:51:08 +0530 | |
---|---|---|
committer | 2022-01-10 13:51:08 +0530 | |
commit | 69dc2cc350cb306ceafbeca8cf0d6216d8dc39c5 (patch) | |
tree | d3c54db9a39cc5107be3c37892fcd90ac5a4ccbf /bot/exts/fun/latex/_renderer.py | |
parent | Merge pull request #1008 from python-discord/fix-aoc-join-logic (diff) |
add latex command
Diffstat (limited to 'bot/exts/fun/latex/_renderer.py')
-rw-r--r-- | bot/exts/fun/latex/_renderer.py | 45 |
1 files changed, 45 insertions, 0 deletions
diff --git a/bot/exts/fun/latex/_renderer.py b/bot/exts/fun/latex/_renderer.py new file mode 100644 index 00000000..3f6528ad --- /dev/null +++ b/bot/exts/fun/latex/_renderer.py @@ -0,0 +1,45 @@ +import sys + +from pathlib import Path +from typing import BinaryIO + +import matplotlib.pyplot as plt + +# configure fonts and colors for matplotlib +plt.rcParams.update( + { + "font.size": 16, + "mathtext.fontset": "cm", # Computer Modern font set + "mathtext.rm": "serif", + "figure.facecolor": "36393F", # matches Discord's dark mode background color + "text.color": "white", + } +) + + +def render(text: str, file_handle: BinaryIO) -> None: + """ + Saves rendered image in `file_handle`. In case the input is invalid latex, it prints the error to `stderr`. + """ + fig = plt.figure() + fig.text(0, 1, text, horizontalalignment="left", verticalalignment="top") + try: + plt.savefig(file_handle, bbox_inches="tight", dpi=600) + except ValueError as err: + # get rid of traceback, keeping just the latex error + sys.exit(err) + + +def main(): + """ + Renders a latex query and saves the output in a specified file. + Expects two command line arguments: the query and the path to the output file. + """ + query = sys.argv[1] + out_file_path = Path(sys.argv[2]) + with open(out_file_path, "wb") as out_file: + render(query, out_file) + + +if __name__ == "__main__": + main() |