2021-01-06 03:33:36 -05:00
|
|
|
import base64
|
2020-12-20 13:25:21 -05:00
|
|
|
import io
|
2020-07-09 08:31:22 -04:00
|
|
|
import os
|
|
|
|
import subprocess
|
2020-07-22 12:07:52 -04:00
|
|
|
import tempfile
|
2021-01-06 03:33:36 -05:00
|
|
|
import urllib
|
2020-07-09 08:31:22 -04:00
|
|
|
|
|
|
|
import jinja2
|
|
|
|
|
|
|
|
# =============================================================================
|
|
|
|
def generate_outfile(
|
|
|
|
templatesdir,
|
|
|
|
templatename,
|
|
|
|
context,
|
|
|
|
outfilename,
|
|
|
|
log = None,
|
2020-07-22 12:07:52 -04:00
|
|
|
cachedir = None,
|
2021-01-06 03:33:36 -05:00
|
|
|
options = {},
|
2020-07-09 08:31:22 -04:00
|
|
|
):
|
|
|
|
|
|
|
|
# Template rendering
|
|
|
|
# -------------------------------------------------------------------------
|
|
|
|
log.info("Generating SVG using '{}' template".format(templatename))
|
2020-07-25 08:51:04 -04:00
|
|
|
log.debug("Context : {}".format(context))
|
2021-01-06 03:33:36 -05:00
|
|
|
log.debug("Options : {}".format(options))
|
2020-07-09 08:31:22 -04:00
|
|
|
|
2020-07-22 12:07:52 -04:00
|
|
|
log.debug(
|
|
|
|
"Initializing jinja2 with template dir '{}'" \
|
|
|
|
.format(templatesdir)
|
|
|
|
)
|
2020-07-09 08:31:22 -04:00
|
|
|
jj2_env = jinja2.Environment(
|
2020-07-22 12:07:52 -04:00
|
|
|
loader = jinja2.FileSystemLoader(
|
|
|
|
str(templatesdir),
|
|
|
|
)
|
2020-07-09 08:31:22 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
try:
|
|
|
|
jj2_tpl = jj2_env.get_template(
|
2020-07-22 12:07:52 -04:00
|
|
|
# Jinja specific path format
|
|
|
|
"{}/template.svg.j2".format(templatename),
|
2020-07-09 08:31:22 -04:00
|
|
|
)
|
2020-07-22 12:07:52 -04:00
|
|
|
except Exception as e:
|
2020-07-09 08:31:22 -04:00
|
|
|
log.error("Could not find template '{}'".format(templatename))
|
2020-07-22 12:07:52 -04:00
|
|
|
log.debug(e, exc_info=1)
|
2020-07-09 08:31:22 -04:00
|
|
|
return None
|
|
|
|
|
|
|
|
# To SVG
|
|
|
|
# -------------------------------------------------------------------------
|
2020-07-22 12:07:52 -04:00
|
|
|
if outfilename.suffix == ".svg":
|
2021-01-06 03:33:36 -05:00
|
|
|
|
|
|
|
if options.get("svg_embed_png", False):
|
|
|
|
log.debug("embedding png images")
|
|
|
|
|
|
|
|
with open(outfilename, "w") as out:
|
|
|
|
for line in jj2_tpl.render(context).splitlines():
|
|
|
|
l = line.strip()
|
|
|
|
|
|
|
|
if ( l.startswith("xlink:href=\"file://")
|
|
|
|
and l.endswith(".png\"") ):
|
|
|
|
image_url = urllib.parse.urlparse(
|
|
|
|
"=".join( l.split("=")[1:] )[1:-1],
|
|
|
|
)
|
|
|
|
log.debug("embedding image '{}'".format(image_url.path))
|
|
|
|
with open(image_url.path, "rb") as image:
|
|
|
|
line = "xlink:href=\"data:image/png;base64,{d}\"" \
|
|
|
|
.format(
|
|
|
|
d = base64 \
|
|
|
|
.b64encode(image.read()) \
|
|
|
|
.decode("ascii"),
|
|
|
|
)
|
|
|
|
|
|
|
|
out.write(line)
|
|
|
|
out.write("\n")
|
|
|
|
|
|
|
|
else:
|
|
|
|
jj2_tpl.stream(context).dump( str(outfilename) )
|
|
|
|
|
2020-07-09 08:31:22 -04:00
|
|
|
return outfilename
|
|
|
|
|
|
|
|
# To PNG with inkscape
|
|
|
|
# -------------------------------------------------------------------------
|
2020-07-22 12:07:52 -04:00
|
|
|
if outfilename.suffix == ".png":
|
2020-07-09 08:31:22 -04:00
|
|
|
|
2020-07-22 12:07:52 -04:00
|
|
|
cachedir.mkdir(parents=True, exist_ok=True)
|
2020-07-09 08:31:22 -04:00
|
|
|
|
2020-09-02 03:09:35 -04:00
|
|
|
tmpsvg = tempfile.NamedTemporaryFile(
|
2020-08-28 06:51:49 -04:00
|
|
|
suffix=".svg",
|
|
|
|
mode = "w",
|
2020-09-02 03:09:35 -04:00
|
|
|
delete = False,
|
2020-07-22 12:07:52 -04:00
|
|
|
dir = str(cachedir),
|
2020-09-02 03:09:35 -04:00
|
|
|
)
|
|
|
|
tmpsvg.close()
|
|
|
|
try:
|
|
|
|
log.info(
|
|
|
|
"Exporting to {} using inkscape" \
|
|
|
|
.format(outfilename.suffix),
|
|
|
|
)
|
|
|
|
import subprocess
|
|
|
|
|
|
|
|
jj2_tpl.stream(context).dump( tmpsvg.name )
|
|
|
|
|
|
|
|
inkscape_process = subprocess.Popen(
|
|
|
|
[
|
|
|
|
"inkscape",
|
|
|
|
tmpsvg.name,
|
|
|
|
"--export-filename",
|
|
|
|
str(outfilename),
|
|
|
|
],
|
|
|
|
stdout = subprocess.PIPE,
|
|
|
|
stderr = subprocess.STDOUT,
|
|
|
|
universal_newlines = True,
|
|
|
|
)
|
2020-07-22 12:07:52 -04:00
|
|
|
|
2020-09-02 03:09:35 -04:00
|
|
|
for line_out in iter(inkscape_process.stdout.readline, ""):
|
|
|
|
log.debug(line_out)
|
2020-07-09 08:31:22 -04:00
|
|
|
|
2020-09-02 03:09:35 -04:00
|
|
|
inkscape_process.stdout.close()
|
2020-07-09 08:31:22 -04:00
|
|
|
|
2020-09-02 03:09:35 -04:00
|
|
|
rv = inkscape_process.wait()
|
2020-07-09 08:31:22 -04:00
|
|
|
|
2020-09-02 03:09:35 -04:00
|
|
|
if rv != 0:
|
|
|
|
raise Exception(
|
|
|
|
"Bad inkscape return code '{}'" \
|
|
|
|
.format(inkscape_process.returncode)
|
|
|
|
)
|
2020-07-09 08:31:22 -04:00
|
|
|
|
|
|
|
|
2020-09-02 03:09:35 -04:00
|
|
|
return outfilename
|
2020-07-16 16:22:25 -04:00
|
|
|
|
2020-09-02 03:09:35 -04:00
|
|
|
except Exception as e:
|
|
|
|
log.warning("Failed to export with inkscape")
|
|
|
|
log.debug(e, exc_info=True)
|
2020-07-09 08:31:22 -04:00
|
|
|
|
2020-09-02 03:09:35 -04:00
|
|
|
finally:
|
|
|
|
os.unlink(tmpsvg.name)
|
2020-07-09 08:31:22 -04:00
|
|
|
|
|
|
|
# To png, pdf or ps with cairosvg
|
|
|
|
# -------------------------------------------------------------------------
|
2020-07-22 12:07:52 -04:00
|
|
|
if outfilename.suffix in [ ".png", ".pdf", ".ps" ]:
|
2020-07-09 08:31:22 -04:00
|
|
|
|
2020-07-22 12:07:52 -04:00
|
|
|
log.info("Exporting to {} using cairosvg".format(outfilename.suffix))
|
2020-07-09 08:31:22 -04:00
|
|
|
|
|
|
|
try:
|
|
|
|
import cairosvg
|
|
|
|
except ImportError as e:
|
|
|
|
log.error(
|
|
|
|
"Failed to export to '{}' with cairosvg" \
|
|
|
|
.format(
|
|
|
|
outfilename,
|
|
|
|
)
|
|
|
|
)
|
|
|
|
log.debug(e)
|
|
|
|
|
2020-08-28 06:52:53 -04:00
|
|
|
else:
|
|
|
|
svg_str = jj2_tpl.render(context)
|
|
|
|
|
|
|
|
if outfilename.suffix == ".png":
|
|
|
|
conversion_fun = cairosvg.svg2png
|
|
|
|
elif outfilename.suffix == ".pdf":
|
|
|
|
conversion_fun = cairosvg.svg2pdf
|
|
|
|
elif outfilename.suffix == ".ps":
|
|
|
|
conversion_fun = cairosvg.svg2ps
|
|
|
|
|
|
|
|
conversion_fun(
|
|
|
|
bytestring = svg_str,
|
|
|
|
write_to = str(outfilename),
|
|
|
|
)
|
2020-07-09 08:31:22 -04:00
|
|
|
|
2020-08-28 06:52:53 -04:00
|
|
|
return outfilename
|
2020-07-09 08:31:22 -04:00
|
|
|
|
|
|
|
# To unsupported format
|
|
|
|
# -------------------------------------------------------------------------
|
|
|
|
log.error(
|
|
|
|
"Can't export to '{}' : unsupported format '{}'" \
|
|
|
|
.format(
|
|
|
|
outfilename,
|
2020-07-22 12:07:52 -04:00
|
|
|
outfilename.suffix,
|
2020-07-09 08:31:22 -04:00
|
|
|
)
|
|
|
|
)
|
|
|
|
return None
|
2020-12-20 13:25:21 -05:00
|
|
|
|
|
|
|
# =============================================================================
|
|
|
|
def generate_pic(
|
|
|
|
templatesdir,
|
|
|
|
templatename,
|
|
|
|
context,
|
|
|
|
outform="svg",
|
|
|
|
log = None,
|
|
|
|
cachedir = None,
|
2021-01-06 03:33:36 -05:00
|
|
|
options = {},
|
2020-12-20 13:25:21 -05:00
|
|
|
):
|
|
|
|
|
|
|
|
if outform not in ["svg", "png"]:
|
|
|
|
raise ValueError("unsupported output format '{}'".format(outform))
|
|
|
|
|
|
|
|
# Template rendering
|
|
|
|
# -------------------------------------------------------------------------
|
|
|
|
log.info("Generating SVG using '{}' template".format(templatename))
|
|
|
|
log.debug("Context : {}".format(context))
|
|
|
|
|
|
|
|
log.debug(
|
|
|
|
"Initializing jinja2 with template dir '{}'" \
|
|
|
|
.format(templatesdir)
|
|
|
|
)
|
|
|
|
jj2_env = jinja2.Environment(
|
|
|
|
loader = jinja2.FileSystemLoader(
|
|
|
|
str(templatesdir),
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
try:
|
|
|
|
jj2_tpl = jj2_env.get_template(
|
|
|
|
# Jinja specific path format
|
|
|
|
"{}/template.svg.j2".format(templatename),
|
|
|
|
)
|
|
|
|
except jinja2.exceptions.TemplateNotFound as e:
|
|
|
|
raise e
|
|
|
|
except Exception as e:
|
|
|
|
log.error("Could not find template '{}'".format(templatename))
|
|
|
|
log.debug(e, exc_info=1)
|
|
|
|
return None
|
|
|
|
|
|
|
|
# To SVG
|
|
|
|
# -------------------------------------------------------------------------
|
|
|
|
if outform == "svg":
|
2021-01-06 03:33:36 -05:00
|
|
|
|
|
|
|
out = io.StringIO()
|
|
|
|
|
|
|
|
if options.get("svg_embed_png", False):
|
|
|
|
log.debug("embedding png images")
|
|
|
|
|
|
|
|
for line in jj2_tpl.render(context).splitlines():
|
|
|
|
l = line.strip()
|
|
|
|
|
|
|
|
if ( l.startswith("xlink:href=\"")
|
|
|
|
and l.endswith(".png\"") ):
|
|
|
|
image_url = urllib.parse.urlparse(
|
|
|
|
"=".join( l.split("=")[1:] )[1:-1],
|
|
|
|
)
|
|
|
|
log.debug("embedding image '{}'".format(image_url.path))
|
|
|
|
with open(image_url.path, "rb") as image:
|
|
|
|
line = "xlink:href=\"data:image/png;base64,{d}\"" \
|
|
|
|
.format(
|
|
|
|
d = base64 \
|
|
|
|
.b64encode(image.read()) \
|
|
|
|
.decode("ascii"),
|
|
|
|
)
|
|
|
|
|
|
|
|
out.write(line)
|
|
|
|
out.write("\n")
|
|
|
|
else:
|
|
|
|
out.write(jj2_tpl.render(context))
|
|
|
|
|
|
|
|
out.seek(0)
|
|
|
|
return out
|
2020-12-20 13:25:21 -05:00
|
|
|
|
|
|
|
# To PNG with inkscape
|
|
|
|
# -------------------------------------------------------------------------
|
|
|
|
if outform == "png":
|
|
|
|
|
|
|
|
if cachedir is None:
|
|
|
|
cachedir_tmp = tempfile.TemporaryDirectory()
|
|
|
|
cachedir = cachedir_tmp.name
|
|
|
|
else:
|
|
|
|
cachedir.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
|
|
|
tmpsvg = tempfile.NamedTemporaryFile(
|
|
|
|
suffix=".svg",
|
|
|
|
mode = "w",
|
|
|
|
delete = False,
|
|
|
|
dir = str(cachedir),
|
|
|
|
)
|
|
|
|
tmpsvg.close()
|
|
|
|
tmppng = tempfile.NamedTemporaryFile(
|
|
|
|
suffix = ".png",
|
|
|
|
mode = "w",
|
|
|
|
delete = False,
|
|
|
|
dir = str(cachedir),
|
|
|
|
)
|
|
|
|
tmppng.close()
|
|
|
|
try:
|
|
|
|
log.info(
|
|
|
|
"Exporting to {} using inkscape" \
|
|
|
|
.format(outform),
|
|
|
|
)
|
|
|
|
import subprocess
|
|
|
|
|
|
|
|
jj2_tpl.stream(context).dump( tmpsvg.name )
|
|
|
|
|
|
|
|
inkscape_process = subprocess.Popen(
|
|
|
|
[
|
|
|
|
"inkscape",
|
|
|
|
tmpsvg.name,
|
|
|
|
"--export-filename",
|
|
|
|
tmppng.name,
|
|
|
|
],
|
|
|
|
stdout = subprocess.PIPE,
|
|
|
|
stderr = subprocess.STDOUT,
|
|
|
|
universal_newlines = True,
|
|
|
|
)
|
|
|
|
|
|
|
|
for line_out in iter(inkscape_process.stdout.readline, ""):
|
|
|
|
log.debug(line_out)
|
|
|
|
|
|
|
|
inkscape_process.stdout.close()
|
|
|
|
|
|
|
|
rv = inkscape_process.wait()
|
|
|
|
|
|
|
|
if rv != 0:
|
|
|
|
raise Exception(
|
|
|
|
"Bad inkscape return code '{}'" \
|
|
|
|
.format(inkscape_process.returncode)
|
|
|
|
)
|
|
|
|
|
|
|
|
with open(tmppng.name, "rb") as fh:
|
|
|
|
buf = io.BytesIO(fh.read())
|
|
|
|
|
|
|
|
return buf
|
|
|
|
|
|
|
|
except Exception as e:
|
|
|
|
log.warning("Failed to export with inkscape")
|
|
|
|
log.debug(e, exc_info=True)
|
|
|
|
|
|
|
|
finally:
|
|
|
|
os.unlink(tmpsvg.name)
|
|
|
|
os.unlink(tmppng.name)
|
|
|
|
|
|
|
|
try:
|
|
|
|
cachedir_tmp.cleanup()
|
|
|
|
except:
|
|
|
|
pass
|
|
|
|
|
|
|
|
return None
|