This repository has been archived by the owner on Oct 18, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzugai.py
64 lines (57 loc) · 1.96 KB
/
zugai.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
from contextlib import contextmanager
from typing import List
import os
import subprocess
DEFAULTS = {
"timeout": 15,
"png_dimensions": "x1000>"
}
DEFAULTS |= {k: type(v)(os.getenv(f"ZUGAI_{k.upper()}", v))
for k, v in DEFAULTS.items()}
class RunException(Exception):
"""
Something went wrong while invoking zugai.
"""
pass
def run(verbing: str, cmd_args: List[str], timeout: float = DEFAULTS["timeout"], **kwargs):
"""
Run a command (`cmd_args`) described in error messages by the gerund `verbing`.
Times out after 15 seconds by default.
"""
try:
result = subprocess.run(cmd_args, **kwargs, check=True, timeout=timeout, capture_output=True)
return result.stdout
except BaseException as e:
message = f"Error while {verbing}:\n{e}\n"
if e.stderr: message += f"\nStderr:\n```\n{e.stderr.decode().strip()}\n```\n"
if e.output: message += f"\nStdout:\n```\n{e.output.decode().strip()}\n```\n"
raise RunException(message)
@contextmanager
def latex_png(sentence: str, png_dimensions: str = DEFAULTS["png_dimensions"]):
"""
Convert the given sentence to LaTeX, then to PDF, then to PNG, then present
the PNG file in a `with` context.
Example:
```py
with latex_png("Hỉo ka") as png_file:
print(len(png_file.read()))
```
"""
tex = run("parsing", ["zugai-exe", "--to-xbar-latex"],
input=bytes(sentence, encoding="utf-8"))
with open("a.tex", "wb") as f: f.write(tex)
run("converting to pdf", ["xelatex", "a.tex"])
run("converting to png", ["convert",
"-define", "png:color-type=6",
"-density", "500", "-quality", "100",
"-background", "#36393E",
"-alpha", "remove", "-alpha", "off",
"-trim",
"-resize", png_dimensions,
"-bordercolor", "#36393E", "-border", "40x20",
"a.pdf", "a.png"])
f = open("a.png", "rb")
try:
yield f
finally:
f.close()