Guest User

ink_bug.py

a guest
May 16th, 2016
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.47 KB | None | 0 0
  1.  
  2. from xml.dom.minidom import parse
  3. import re
  4. import subprocess as sp
  5.  
  6. source = "./ink-bug.svg"
  7. tmp_svg = "./tmp4738233729506.svg"
  8. output_path =  "./output/"
  9.  
  10.  
  11.  
  12. special_name_re = re.compile("\s*\$exp\s*:\s*(.+)")
  13.  
  14.  
  15. def generate_svg (filename, node):
  16.     b = """<?xml version="1.0" encoding="UTF-8" standalone="no"?>
  17. <svg
  18.   xmlns:dc="http://purl.org/dc/elements/1.1/"
  19.   xmlns:cc="http://creativecommons.org/ns#"
  20.   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
  21.   xmlns:svg="http://www.w3.org/2000/svg"
  22.   xmlns="http://www.w3.org/2000/svg"
  23.   version="1.1"
  24.   id="svg2"
  25.   viewBox="0 0 744.09448819 1052.3622047">
  26.  <defs
  27.     id="defs4" />
  28.  <metadata
  29.     id="metadata7">
  30.    <rdf:RDF>
  31.      <cc:Work
  32.         rdf:about="">
  33.        <dc:format>image/svg+xml</dc:format>
  34.        <dc:type
  35.           rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
  36.        <dc:title></dc:title>
  37.      </cc:Work>
  38.    </rdf:RDF>
  39.  </metadata>
  40.  <g
  41.     id="layer1">"""
  42.     e = """  </g>
  43. </svg>
  44. """
  45.     f = open(filename, "w")
  46.     f.write(b + node.toxml() + e)
  47.     return f.close()
  48.  
  49.  
  50.  
  51.  
  52. def find_figure_node (nodes):
  53.     return next(node for node in nodes
  54.                 if not(node.nodeName in ["text", "#text"]))
  55.  
  56.  
  57. class InkComm:
  58.     def __init__(self):
  59.         "Open unbuffered pipe to Inkscape shell in text mode"
  60.         self.p = sp.Popen(['inkscape', '--shell'],
  61.                           bufsize=0, universal_newlines=True,
  62.                           stdin=sp.PIPE, stdout=sp.PIPE)
  63.         self.read()
  64.  
  65.     def read(self):
  66.         "Read from open Inkscape shell till '>' occur"
  67.         rv = ''
  68.         while True:
  69.             r = self.p.stdout.read(1)
  70.             if r == '>':
  71.                 break
  72.             rv += r
  73.         return rv
  74.  
  75.     def write(self, words_of_wisdom):
  76.         "Write data and newline char"
  77.         return self.p.stdin.write(words_of_wisdom + '\n')
  78.    
  79.     def close(self):
  80.         "Guess what this method does"
  81.         stdout, stderr = self.p.communicate('quit\n')
  82.         return self.p.returncode, stdout, stderr
  83.  
  84.     def get_svg_geometry (self, svgfile):
  85.         "Returns list contains [x, y, width, height] of svg"
  86.         self.write("-S " + svgfile)
  87.         s = self.read().splitlines()[0]
  88.         return map(float,s.split(',')[1:])
  89.  
  90.     def export_svg_area_in_png (self, svg, pngout, svgarea,
  91.                                 width=None, height=None):
  92.         com = svg
  93.         com += " --export-png={0}".format(pngout)
  94.         com += " --export-area-snap"
  95.         com += " --export-area={0}".format(':'.join(map(str,svgarea)))
  96.         com += " --export-background='#ffffff'"
  97.         if height: com += " --export-height={0}".format(height)
  98.         if width: com += " --export-width={0}".format(width)
  99.        
  100.         self.write(com)
  101.         self.read()
  102.         return(pngout)
  103.  
  104.  
  105. fig_table = {"star-01":{'y':590},
  106.              "star-02":{'y':368},
  107.              "star-03":{'y':210},
  108.              "star-04":{'y':0},
  109.              "star-05":{'y':-212},
  110.              "star-06":{'y':-445},
  111.              "star-07":{'y':-664},
  112.              "star-08":{'y':-865},
  113.              "star-09":{'y':-1110},
  114.              "star-10":{'y':-1325},
  115. }
  116.  
  117. def expand_area (x,y,w,h):
  118.     rd = .3
  119.     dx = w*rd
  120.     x1 =  x - dx
  121.     x2 =  x + w + dx
  122.     y1 =  y
  123.     y2 =  y + 1.5*h
  124.     return x1,y1,x2,y2
  125.  
  126.            
  127. ink_proc = InkComm()
  128.  
  129. def test_raster(svg, yopts, of):
  130.     x, y, w, h = ink_proc.get_svg_geometry(tmp_svg)
  131.     real_y = yopts['y']
  132.     # real_y = 886.154 - y
  133.     print "{:s}  {:f}  {:f}".format(of, y, real_y)
  134.     real_h = yopts.get('h') or h
  135.     ink_proc.export_svg_area_in_png(svg, of,
  136.                                     expand_area(x, real_y, w, real_h),
  137.                                     width = 150)
  138.  
  139.  
  140. def gen_rfiles (xmlfile):
  141.     xml = parse(xmlfile)
  142.     text_elements = xml.getElementsByTagName("text")
  143.     for text_element in text_elements:
  144.         x = text_element.firstChild
  145.         if x.hasChildNodes():
  146.             t = x.firstChild.nodeValue
  147.             m = special_name_re.match(t)
  148.             if m:
  149.                 nam = m.group(1).strip()
  150.                 yopts = fig_table.get(nam)
  151.                 if yopts:
  152.                     figure = find_figure_node(text_element.parentNode.childNodes)
  153.                     generate_svg(tmp_svg, figure)
  154.                     test_raster(tmp_svg, yopts, output_path + nam + '.png')
  155.  
  156.  
  157.  
  158.    
  159.  
  160. gen_rfiles(source)
  161.  
  162. ink_proc.close()
Advertisement
Add Comment
Please, Sign In to add comment