~nova/fletcher

ref: c1acd163f33f54a9b253f908f8387cb0c0a07fa7 fletcher/mathemagical.py -rw-r--r-- 5.3 KiB
c1acd163 — Novalinium muple 4 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
from sys import exc_info
import discord
import io
import logging
import matplotlib.pyplot as plt
import messagefuncs
import subprocess
import sympy
import tempfile

logger = logging.getLogger("fletcher")


def renderLatex(formula, fontsize=12, dpi=300, format="svg", file=None, preamble=""):
    """Renders LaTeX formula into image or prints to file."""
    plt.rc("text", usetex=True)
    plt.rc("text.latex", preamble=preamble)
    plt.rc("font", family="serif")
    fig = plt.figure(figsize=(0.01, 0.01), frameon=True)
    fig.text(
        0,
        0,
        formula,
        fontsize=fontsize,
        verticalalignment="center_baseline",
        clip_on=True,
    )
    plt.tight_layout()

    output = io.BytesIO() if file is None else file
    fig.savefig(
        output,
        dpi=dpi,
        transparent=False,
        format=format,
        bbox_inches="tight",
        pad_inches=None,
    )

    plt.close(fig)

    if file is None:
        output.seek(0)
        return output


async def latex_render_function(message, client, args, body=None, preamble=""):
    global config
    try:
        if body:
            renderstring = body
        else:
            try:
                renderstring = message.content.split(" ", 1)[1]
            except:
                return await messagefuncs.sendWrappedMessage(
                    "Please specify string to render as LaTeX",
                    message.channel,
                    delete_after=30,
                )
        if message.content.split(" ", 1)[0] == "!math":
            renderstring = f"$${renderstring}$$"
        if "math" in config and "extra-packages" in config["math"]:
            preamble = (
                r"\usepackage{"
                + r"}\usepackage{".join(config["math"]["extra-packages"].split(","))
                + preamble
                + r"}"
            )
        else:
            preamble = "\\usepackage[utf8]{inputenc}"
        try:
            await messagefuncs.sendWrappedMessage(
                "||```tex\n" + renderstring + "```||",
                message.channel,
                files=[
                    discord.File(
                        renderLatex(renderstring, format="png", preamble=preamble),
                        filename="fletcher-render.png",
                    )
                ],
            )
        except RuntimeError as e:
            renderstringSlashed = (
                renderstring.replace("\\\\\\\\", "quadslash")
                .replace("\\", "\\\\")
                .replace("quadslash", "\\\\\\\\")
            )
            exc_type, exc_obj, exc_tb = exc_info()
            logger.debug("LRF[{}]: {} {}".format(exc_tb.tb_lineno, type(e).__name__, e))
            await messagefuncs.sendWrappedMessage(
                "||```tex\n" + renderstringSlashed + "```||",
                message.channel,
                files=[
                    discord.File(
                        renderLatex(
                            renderstringSlashed,
                            format="png",
                            preamble=preamble,
                        ),
                        filename="fletcher-render.png",
                    )
                ],
            )
    except RuntimeError as e:
        exc_type, exc_obj, exc_tb = exc_info()
        logger.debug("LRF[{}]: {} {}".format(exc_tb.tb_lineno, type(e).__name__, e))
        await message.add_reaction("🚫")
        await messagefuncs.sendWrappedMessage(
            "||```tex\n"
            + preamble
            + "```||\n"
            + "||```tex\n"
            + renderstring
            + "```||\n"
            + f"Error rendering LaTeX: {e}",
            message.author,
        )
    except Exception as e:
        exc_type, exc_obj, exc_tb = exc_info()
        logger.error("LRF[{}]: {} {}".format(exc_tb.tb_lineno, type(e).__name__, e))


async def tengwar_render_function(message, client, args):
    try:
        command = ["perl", "./ptt/ptt.pl", "-oq", "./ptt/es.ptm"]
        p = subprocess.Popen(
            command,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
        )
        tengwar = (
            p.communicate(input=" ".join(args).encode("utf-8"))[0]
            .decode("utf-8")
            .strip()
        )
        await latex_render_function(
            message,
            client,
            args,
            body=tengwar,
            preamble=r"}\usepackage[all]{tengwarscript",
        )
    except Exception as e:
        exc_type, exc_obj, exc_tb = exc_info()
        logger.error("LRF[{}]: {} {}".format(exc_tb.tb_lineno, type(e).__name__, e))


# Register functions in client
def autoload(ch):
    ch.add_command(
        {
            "trigger": ["!math", "!latex"],
            "function": latex_render_function,
            "async": True,
            "args_num": 0,
            "long_run": True,
            "args_name": [],
            "description": "Render arguments as LaTeX formula (does not require `$$` in `!math` mode)",
        }
    )
    ch.add_command(
        {
            "trigger": ["!tengwar"],
            "function": tengwar_render_function,
            "async": True,
            "args_num": 0,
            "long_run": True,
            "args_name": [],
            "description": "Render arguments as Tengwar via LaTeX (tengwarscript package)",
        }
    )


async def autounload(ch):
    pass