fixed image generation

This commit is contained in:
Daniel Knüttel 2018-01-18 10:47:45 +01:00
parent de0ee68ded
commit f24a4ae652
2 changed files with 13 additions and 17 deletions

View File

@ -2,12 +2,16 @@ from telegram.ext import RegexHandler
from .rendering import get_png from .rendering import get_png
from .static import static_content from .static import static_content
import logging
logger = logging.getLogger(__name__)
def handle_exception_in_get_png(bot, update, exception, text): def handle_exception_in_get_png(bot, update, exception, text):
update.message.reply_text("**Error** while processing '__{}__'.\n\nException was: **{}**.".format(text, exception), parse_mode = "Markdown") update.message.reply_text("**Error** while processing '__{}__'.\n\nException was: **{}**.".format(text, exception), parse_mode = "Markdown")
def render_math(bot, update): def render_math(bot, update):
text = update.message.text[len("/rmath"):] text = update.message.text[len("/rmath"):]
tex = "${}$".format(text) tex = text
try: try:
png = get_png(tex) png = get_png(tex)
@ -27,7 +31,7 @@ def render_math_caption(bot, update):
caption = text[text.index("<") + 1:text.index(">")] caption = text[text.index("<") + 1:text.index(">")]
text = text[text.index(">") + 1:] text = text[text.index(">") + 1:]
tex = "${}$".format(text) tex = text
try: try:
png = get_png(tex) png = get_png(tex)

View File

@ -1,27 +1,19 @@
from sympy import preview
from io import BytesIO from io import BytesIO
import cairosvg, time, os import matplotlib.pyplot as plt
def get_png(tex): def get_png(tex):
buf = BytesIO() buf = BytesIO()
preview(tex, output = "svg", viewer = "BytesIO", outputbuffer = buf)
buf.seek(0)
fname = "/tmp/{}".format(time.time()) plt.text(0, 0.6, r"$%s$" % tex, fontsize = 50)
fig = plt.gca()
fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)
cairosvg.svg2png(bytestring=buf.read(), parent_widht=500, parent_height=500, write_to=fname) plt.savefig(buf)
buf.seek(0) buf.seek(0)
with open(fname, "rb") as fin:
buf.write(fin.read())
with open(fname, "rb") as fin:
with open("test.png", "wb") as fout:
fout.write(fin.read())
os.unlink(fname)
buf.seek(0)
return buf return buf