| 1 |
|
| 2 |
|
| 3 |
import py |
| 4 |
import string |
| 5 |
import re |
| 6 |
|
| 7 |
nonalpha = "".join([chr(i) for i in range(256) if not chr(i).isalpha()]) |
| 8 |
replacement = (string.ascii_letters * (int(len(nonalpha) / len(string.ascii_letters)) + 1))[:len(nonalpha)] |
| 9 |
transtable = string.maketrans(nonalpha, replacement) |
| 10 |
del nonalpha |
| 11 |
del replacement |
| 12 |
|
| 13 |
def find_replacement(tex, used={}): |
| 14 |
replacement = tex.translate(transtable) |
| 15 |
while replacement in used: |
| 16 |
replacement += "a" |
| 17 |
used[replacement] = True |
| 18 |
return replacement |
| 19 |
|
| 20 |
def create_tex_eps(dot, temppath): |
| 21 |
result = ["\\documentclass{article}", |
| 22 |
"\\usepackage[dvips]{graphicx}", |
| 23 |
"\\usepackage{psfrag}", |
| 24 |
"\\pagestyle{empty}", |
| 25 |
"\\begin{document}", |
| 26 |
"\\onecolumn"] |
| 27 |
texre = re.compile("(\$.*?\$)") |
| 28 |
dotcontent = dot.read() |
| 29 |
def repl(match, already_seen={}): |
| 30 |
tex = match.group(1) |
| 31 |
if tex in already_seen: |
| 32 |
return already_seen[tex] |
| 33 |
r = find_replacement(tex) |
| 34 |
already_seen[tex] = r |
| 35 |
result.append("\\psfrag{%s}[cc][cc]{%s}" % (r, tex)) |
| 36 |
return r |
| 37 |
tempdot = temppath.join(dot.basename) |
| 38 |
eps = tempdot.new(ext='eps') |
| 39 |
dotcontent = texre.sub(repl, dotcontent) |
| 40 |
result.append("\\includegraphics{%s}" % eps) |
| 41 |
result.append("\\end{document}") |
| 42 |
tempdot.write(dotcontent) |
| 43 |
tex = eps.new(ext="tex") |
| 44 |
texcontent = "\n".join(result) |
| 45 |
tex.write(texcontent) |
| 46 |
|
| 47 |
epscontent = py.process.cmdexec("dot -Tps %s" % (tempdot, )) |
| 48 |
eps.write(re.sub("\n\[.*\]\nxshow", "\nshow", epscontent)) |
| 49 |
return tex, eps |
| 50 |
|
| 51 |
def process_dot(dot): |
| 52 |
temppath = py.test.ensuretemp("dot") |
| 53 |
tex, texcontent = create_tex_eps(dot, temppath) |
| 54 |
dvi = tex.new(ext="dvi") |
| 55 |
output = dvi.new(purebasename=dvi.purebasename + "out", ext="eps") |
| 56 |
oldpath = dot.dirpath() |
| 57 |
dvi.dirpath().chdir() |
| 58 |
py.process.cmdexec("latex %s" % (tex, )) |
| 59 |
py.process.cmdexec("dvips -E -o %s %s" % (output, dvi)) |
| 60 |
oldpath.chdir() |
| 61 |
return output |
| 62 |
|
| 63 |
|
| 64 |
if __name__ == '__main__': |
| 65 |
import optparse |
| 66 |
parser = optparse.OptionParser() |
| 67 |
parser.add_option("-T", dest="format", |
| 68 |
help="output format") |
| 69 |
options, args = parser.parse_args() |
| 70 |
if len(args) != 1: |
| 71 |
raise ValueError("need exactly one argument") |
| 72 |
epsfile = process_dot(py.path.local(args[0])) |
| 73 |
if options.format == "ps" or options.format == "eps": |
| 74 |
print epsfile.read() |
| 75 |
elif options.format == "png": |
| 76 |
png = epsfile.new(ext="png") |
| 77 |
py.process.cmdexec("convert %s %s" % (epsfile, png)) |
| 78 |
print png.read() |