-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdraw.py
215 lines (182 loc) · 6.8 KB
/
draw.py
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
import os
import re
import io
import urllib
import aiohttp
from typing import Optional
import numpy
import asyncio
from scipy.special import gamma # noqa F401
import graphviz as gz
from matplotlib import pyplot as plt
import discord
from discord.ext import commands
from discord.utils import escape_markdown, escape_mentions
from core import basecog
from core.text import text
from core.config import config
PNG_HEADER = b"\x89PNG\r\n\x1a\n"
class Draw(basecog.Basecog):
"""LaTeX and Graph drawing commands"""
def __init__(self, bot):
super().__init__(bot)
self.rep_exp = {
"x": "x",
"sin": "numpy.sin",
"cos": "numpy.cos",
"tan": "numpy.tan",
"tg": "numpy.tan",
"arcsin": "numpy.arcsin",
"arccos": "numpy.arccos",
"arctan": "numpy.arctan",
"arctg": "numpy.arctg",
"sinh": "numpy.sinh",
"cosh": "numpy.cosh",
"tanh": "numpy.tanh",
"tgh": "numpy.tgh",
"arcsinh": "numpy.arcsinh",
"arccosh": "numpy.arccosh",
"arctanh": "numpy.arctanh",
"arctgh": "numpy.arctgh",
"exp": "numpy.exp",
"log": "numpy.log10",
"ln": "numpy.log",
"sqrt": "numpy.sqrt",
"cbrt": "numpy.cbrt",
"abs": "numpy.absolute",
"gamma": "gamma",
}
self.rep_op = {
"+": " + ",
"-": " - ",
"*": " * ",
"/": " / ",
"//": " // ",
"%": " % ",
"^": " ** ",
}
def string2func(self, string):
"""Evaluates the string and returns a function of x"""
# surround operators with spaces and replace ^ with **
for old, new in self.rep_op.items():
string = string.replace(old, new)
string = " ".join(string.split())
# string = unidecode.unidecode(string)
if not string.isascii():
raise ValueError(
"Non ASCII characters are forbidden to use in math expression"
)
# find all words and check if all are allowed:
for word in re.findall("[a-zA-Z_]+", string):
if word not in self.rep_exp.keys():
raise ValueError(
'"{}" is forbidden to use in math expression'.format(word)
)
for old, new in self.rep_exp.items():
string = re.sub(rf"\b{old}\b", new, string)
def func(x):
return eval(string) # nosec B307
return func
@commands.command(
help=text.fill("draw", "latex_help", prefix=config.prefix),
brief=text.get("draw", "latex_desc"),
description=text.get("draw", "latex_desc"),
)
async def latex(self, ctx, *, equation):
channel = ctx.channel
async with ctx.typing():
eq = urllib.parse.quote(equation)
imgURL = f"http://www.sciweavers.org/tex2img.php?eq={eq}&fc=White&im=png&fs=25&edit=0"
async with aiohttp.ClientSession() as session:
async with session.get(imgURL) as resp:
if resp.status != 200:
return await ctx.send("Could not get image.")
data = await resp.read()
if not data.startswith(PNG_HEADER):
return await ctx.send("Could not get image.")
datastream = io.BytesIO(data)
await channel.send(file=discord.File(datastream, "latex.png"))
@commands.command(
help=text.fill("draw", "plot_help", prefix=config.prefix),
brief=text.get("draw", "plot_desc"),
description=text.get("draw", "plot_desc"),
)
async def plot(
self, ctx, xmin: Optional[float] = -10, xmax: Optional[float] = 10, *, inp: str
):
equations = escape_mentions(escape_markdown(inp)).split(";")
fig = plt.figure(dpi=300)
ax = fig.add_subplot(1, 1, 1)
if xmin < 0 < xmax:
ax.spines["left"].set_position("zero")
# Eliminate upper and right axes
ax.spines["right"].set_color("none")
ax.spines["top"].set_color("none")
# Show ticks in the left and lower axes only
ax.xaxis.set_tick_params(bottom=True, direction="inout")
ax.yaxis.set_tick_params(left=True, direction="inout")
successful_eq = 0
msg = text.get("draw", "plot_err")
numpy.seterr(divide="ignore", invalid="ignore")
async with ctx.typing():
for eq in equations:
try:
func = self.string2func(eq)
x = numpy.linspace(xmin, xmax, 1000)
plt.plot(x, func(x))
plt.xlim(xmin, xmax)
successful_eq += 1
except Exception as e:
msg += "\n" + eq + " - " + str(e)
if msg != text.get("draw", "plot_err"):
await ctx.send(msg)
if successful_eq > 0:
if not os.path.isdir("assets"):
os.mkdir("assets")
plt.savefig("assets/plot.png", bbox_inches="tight", dpi=100)
plt.clf()
await ctx.send(file=discord.File("assets/plot.png"))
os.remove("assets/plot.png")
return
@commands.command(
name="digraph",
aliases=("graphviz",),
help=text.fill("draw", "digraph_help", prefix=config.prefix),
brief=text.get("draw", "digraph_desc"),
description=text.get("draw", "digraph_desc"),
)
async def digraph(self, ctx):
"""
input equation in dishraph format into graphviz
save the file into assets/graphviz.png
send the file to channel
"""
message = ctx.message
try:
equation = re.search("```([^`]*)```", message.content).group(1)
except AttributeError:
return
await message.add_reaction("▶️")
def check(reaction, user):
return (
reaction.message.id == message.id
and (str(reaction.emoji) == "▶️")
and user.id == message.author.id
)
try:
reaction, user = await self.bot.wait_for(
"reaction_add", check=check, timeout=300.0
)
except asyncio.TimeoutError:
pass
else:
src = gz.Source(equation, format="png")
if not os.path.isdir("assets"):
os.mkdir("assets")
src.render("assets/graphviz", view=False)
await ctx.send(file=discord.File("assets/graphviz.png"))
os.remove("assets/graphviz")
os.remove("assets/graphviz.png")
await message.clear_reaction("▶")
def setup(bot):
bot.add_cog(Draw(bot))