forked from devksingh4/fogelbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
latex.py
55 lines (49 loc) · 1.56 KB
/
latex.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
import requests
import uuid
import shutil
import re
HOST = 'https://rtex.probablyaweb.site'
def load_template():
with open('template.tex', encoding = 'utf-8') as f:
raw = f.read()
# Remove any comments from the template
cleaned = re.sub(r'%.*\n', '', raw)
return cleaned
def render_latex(latex):
template = load_template()
id = str(uuid.uuid4())
tempFit = template.replace("#CONTENT", latex)
payload = {'code': tempFit, 'format': 'png'}
response = requests.post(HOST + '/api/v2', data = payload)
response.raise_for_status()
jdata = response.json()
if jdata['status'] != 'success':
return None
else:
downloadUrl = HOST + '/api/v2/' + jdata['filename']
response = requests.get(downloadUrl, stream = True)
response.raise_for_status()
with open('{}.png'.format(id), 'wb') as out_file:
shutil.copyfileobj(response.raw, out_file)
return id
def extract_inline_tex(content):
parts = iter(content.split('$$'))
latex = ''
try:
while True:
it = next(parts)
if (it == ''):
word = ''
else:
word = " \\text{" + it + "} "
if word != '':
latex += word.replace('#', '\\#') \
.replace('$', '\\$') \
.replace('%', '\\%')
latex += ' '
word = next(parts)
if word != '':
latex += word.strip('`')
except StopIteration:
pass
return latex.rstrip()