Skip to content

Instantly share code, notes, and snippets.

@chr5tphr
Last active May 21, 2021 18:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chr5tphr/7d453f9bdf8211ad8a395b311caf11b8 to your computer and use it in GitHub Desktop.
Save chr5tphr/7d453f9bdf8211ad8a395b311caf11b8 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import xml.etree.ElementTree as ET
import logging
import os
import click
import yaml
logger = logging.getLogger(__name__)
@click.command()
@click.argument('config_path', type=click.Path(exists=True))
@click.argument('output', type=click.Path())
def main(
output,
config_path
):
ns = {
'dc': 'http://purl.org/dc/elements/1.1/',
'cc': 'http://creativecommons.org/ns#',
'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
'svg': 'http://www.w3.org/2000/svg',
'': 'http://www.w3.org/2000/svg',
'xlink': 'http://www.w3.org/1999/xlink',
'sodipodi': 'http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd',
'inkscape': 'http://www.inkscape.org/namespaces/inkscape'
}
logging.basicConfig(level=logging.INFO, format='%(levelname)s - %(message)s')
with open(config_path, 'r') as fd:
config = yaml.safe_load(fd)
try:
template = config.pop('template')
except KeyError as error:
raise RuntimeError("No template key found in '{}'".format(config_path)) from error
tree = ET.parse(template)
for elem in tree.iterfind('.//text', ns):
tspan = next(iter(elem), None)
if tspan is not None:
newtext = config.pop(elem.get('id'), tspan.text)
tspan.text = newtext
for elem in tree.iterfind('.//image', ns):
href = '{%s}href' % ns['xlink']
absref = '{%s}absref' % ns['sodipodi']
eid = elem.get('id')
oldpath = elem.get(href, '')
newpath = config.pop(eid, oldpath)
if not newpath:
logger.warning('Empty path for node \'%s\'', eid)
continue
abspath = os.path.abspath(newpath)
if not os.path.isfile(abspath):
logger.warning('File not found for node \'%s\': \'%s\'', eid, abspath)
continue
elem.set(href, abspath)
elem.set(absref, abspath)
if config:
logger.warning('Following config entries were not used: \'%s\'', '\', \''.join(list(config)))
tree.write(output)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment