1
- import re
2
-
3
1
import os .path as osp
4
2
import pickle
3
+ import re
5
4
import subprocess
6
5
import tempfile
7
6
from typing import Dict , Optional , Union
8
7
9
8
import matplotlib
10
9
import matplotlib .pyplot as plt
11
-
10
+ from doc2rst import DOCTEST_RST_DATA_PCL
12
11
from mathics import __version__ , settings , version_info , version_string
13
- from mathics import settings
14
12
from mathics .doc .utils import load_doctest_data
15
- from doc2rst import DOCTEST_RST_DATA_PCL
16
13
17
14
ASY_LATEX_BLOCK = re .compile (r"\\begin{asy}([\s\S]+?)\\end{asy}" )
18
15
IMAGE_LATEX_ENTRY = re .compile (r"(?m)\\includegraphics\[(.*?)\]{(.*?)}" )
23
20
SKIP_ASY = False
24
21
25
22
26
-
27
23
def convert_asy_code (content : str , key = "" ):
28
24
"""Convert asy code into a png picture.
29
25
Return a LaTeX includegraphics instruction"""
@@ -36,7 +32,9 @@ def convert_asy_code(content: str, key=""):
36
32
tmp_path , _ = osp .split (tmp_filename )
37
33
result = tmp_filename [:- 4 ] + ".png"
38
34
if not SKIP_ASY :
39
- subprocess .run (["asy" , "-f" , "png" , "-render" , "70" , tmp_filename ], cwd = tmp_path )
35
+ subprocess .run (
36
+ ["asy" , "-f" , "png" , "-render" , "70" , tmp_filename ], cwd = tmp_path
37
+ )
40
38
result = osp .abspath (result )
41
39
return r"\includegraphics[]{" + result + "}"
42
40
@@ -46,7 +44,7 @@ def convert_latex_to_png(content, key=""):
46
44
Generate a png image from LaTeX
47
45
code.
48
46
"""
49
- tmp_filename = get_tmp_filename (prefix = "eq_" + key , suffix = ".png" )
47
+ tmp_filename = get_tmp_filename (prefix = "eq_" + key , suffix = ".png" )
50
48
try :
51
49
latex_to_img (f"${ content } $" , tmp_filename )
52
50
except ValueError as e :
@@ -57,7 +55,7 @@ def convert_latex_to_png(content, key=""):
57
55
58
56
59
57
def convert_mathics_latex_to_RsT (
60
- out_latex : Optional [Union [str , dict ]], key = ""
58
+ out_latex : Optional [Union [str , dict ]], key = ""
61
59
) -> Optional [Union [str , dict ]]:
62
60
"""
63
61
Convert a LaTeX block into a RsT compatible
@@ -74,7 +72,9 @@ def convert_mathics_latex_to_RsT(
74
72
assert isinstance (out_latex , str )
75
73
# out_latex is a string
76
74
out_latex = str (out_latex ).strip ()
77
- out_latex = ASY_LATEX_BLOCK .sub (lambda m : convert_asy_code (m .group (1 ), key ), out_latex )
75
+ out_latex = ASY_LATEX_BLOCK .sub (
76
+ lambda m : convert_asy_code (m .group (1 ), key ), out_latex
77
+ )
78
78
out_latex = out_latex .strip ()
79
79
img_match = IMAGE_LATEX_ENTRY .fullmatch (out_latex )
80
80
if img_match :
@@ -94,7 +94,6 @@ def convert_mathics_latex_to_RsT(
94
94
return f":math:`{ out_latex } `\n "
95
95
96
96
97
-
98
97
def convert_output_to_rst (test_data , key = "" ):
99
98
"""
100
99
Convert the output data from a doctest
@@ -104,9 +103,11 @@ def convert_output_to_rst(test_data, key=""):
104
103
try :
105
104
converted_data = {
106
105
"query" : test_data ["query" ],
107
- "results" : [convert_result_to_rst (item , key ) for item in test_data ["results" ]],
106
+ "results" : [
107
+ convert_result_to_rst (item , key ) for item in test_data ["results" ]
108
+ ],
108
109
}
109
- except ValueError , RuntimeError :
110
+ except ( ValueError , RuntimeError ) :
110
111
print ("Result from " , test_data ["query" ], "could not be converted." )
111
112
return None
112
113
return converted_data
@@ -120,7 +121,10 @@ def convert_result_to_rst(result_dict, key=""):
120
121
converted_result = {
121
122
"line" : result_dict ["line" ],
122
123
"form" : "RsT" ,
123
- "out" : [convert_mathics_latex_to_RsT (out_line , key ) for out_line in result_dict ["out" ]],
124
+ "out" : [
125
+ convert_mathics_latex_to_RsT (out_line , key )
126
+ for out_line in result_dict ["out" ]
127
+ ],
124
128
"result" : convert_mathics_latex_to_RsT (result_dict ["result" ], key ),
125
129
}
126
130
for key in result_dict :
@@ -136,11 +140,12 @@ def convert_test_data_to_rst(latex_test_data):
136
140
"""
137
141
rst_tex_data = {}
138
142
for key , test in latex_test_data .items ():
139
- rst_tex_data [key ] = convert_output_to_rst (test , ("_" .join (key [:- 1 ])).replace (" " , "_" )+ "_" )
143
+ rst_tex_data [key ] = convert_output_to_rst (
144
+ test , ("_" .join (key [:- 1 ])).replace (" " , "_" ) + "_"
145
+ )
140
146
return rst_tex_data
141
147
142
148
143
-
144
149
def get_tmp_filename (prefix = "" , suffix = "" ):
145
150
# This produces a random name, where the png file is going to be stored.
146
151
# LaTeX does not have a native way to store an figure embedded in
@@ -158,23 +163,31 @@ def latex_to_img(tex, fn):
158
163
https://stackoverflow.com/questions/1381741/converting-latex-code-to-images-or-other-displayble-format-with-python
159
164
"""
160
165
matplotlib .rcParams ["text.latex.preamble" ] = (
161
- "\\ usepackage{multicol}\n " "\\ usepackage{amsmath}\n " "\\ usepackage{amssymb}\n " "\\ usepackage{graphicx}\n "
166
+ "\\ usepackage{multicol}\n "
167
+ "\\ usepackage{amsmath}\n "
168
+ "\\ usepackage{amssymb}\n "
169
+ "\\ usepackage{graphicx}\n "
162
170
)
163
171
# LaTeX from matplotlib does not accept linebreaks or
164
172
# the \text command. Use \mbox instead.
165
- tex = tex .replace (r' \text{' , r' \mbox{' )
173
+ tex = tex .replace (r" \text{" , r" \mbox{" )
166
174
tex = tex .replace ("\n " , " " )
167
175
# TODO: adjust the size of the figure.
168
- plt .figure (figsize = (3 ,1 ))
176
+ plt .figure (figsize = (3 , 1 ))
169
177
plt .rc ("text" , usetex = True )
170
178
plt .rc ("font" , family = "serif" )
171
179
plt .axis ("off" )
172
180
plt .text (0.05 , 0.5 , f"{ tex } " , size = 12 )
173
- plt .savefig (fn , format = "png" , bbox_inches = 'tight' , backend = "pgf" , dpi = 250 ,)
181
+ plt .savefig (
182
+ fn ,
183
+ format = "png" ,
184
+ bbox_inches = "tight" ,
185
+ backend = "pgf" ,
186
+ dpi = 250 ,
187
+ )
174
188
plt .close ()
175
189
176
190
177
-
178
191
def read_doctest_data (quiet = False ) -> Optional [Dict [tuple , dict ]]:
179
192
"""
180
193
Read doctest information from PCL file and return this.
@@ -193,7 +206,6 @@ def read_doctest_data(quiet=False) -> Optional[Dict[tuple, dict]]:
193
206
return {}
194
207
195
208
196
-
197
209
def main ():
198
210
"""Generate a pickle file with outputs compatible with RsT"""
199
211
latex_test_data = read_doctest_data ()
@@ -203,7 +215,5 @@ def main():
203
215
print ("done." )
204
216
205
217
206
-
207
-
208
- if __name__ == "__main__" :
218
+ if __name__ == "__main__" :
209
219
main ()
0 commit comments