got rid of svg2path changes (reverted to master)

ElementTree
Andy Port 2018-05-28 20:14:45 -07:00
parent f966999bc5
commit 609cbc776a
1 changed files with 100 additions and 80 deletions

View File

@ -1,10 +1,11 @@
"""A submodule of tools for creating path objects from SVG files. """This submodule contains tools for creating path objects from SVG files.
The main tool being the svg2paths() function.""" The main tool being the svg2paths() function."""
# External dependencies # External dependencies
from __future__ import division, absolute_import, print_function from __future__ import division, absolute_import, print_function
import os from xml.dom.minidom import parse
import xml.etree.cElementTree as etree from os import path as os_path, getcwd
import re
# Internal dependencies # Internal dependencies
from .parser import parse_path from .parser import parse_path
@ -18,8 +19,8 @@ COORD_PAIR_TMPLT = re.compile(
def ellipse2pathd(ellipse): def ellipse2pathd(ellipse):
"""converts the parameters from an ellipse or a circle to a string """converts the parameters from an ellipse or a circle to a string for a
for a Path object d-attribute""" Path object d-attribute"""
cx = ellipse.get('cx', None) cx = ellipse.get('cx', None)
cy = ellipse.get('cy', None) cy = ellipse.get('cy', None)
@ -45,8 +46,8 @@ def ellipse2pathd(ellipse):
def polyline2pathd(polyline_d, is_polygon=False): def polyline2pathd(polyline_d, is_polygon=False):
"""converts the string from a polyline points-attribute to a string """converts the string from a polyline points-attribute to a string for a
for a Path object d-attribute""" Path object d-attribute"""
points = COORD_PAIR_TMPLT.findall(polyline_d) points = COORD_PAIR_TMPLT.findall(polyline_d)
closed = (float(points[0][0]) == float(points[-1][0]) and closed = (float(points[0][0]) == float(points[-1][0]) and
float(points[0][1]) == float(points[-1][1])) float(points[0][1]) == float(points[-1][1]))
@ -88,21 +89,15 @@ def rect2pathd(rect):
return d return d
def line2pathd(l): def svg2paths(svg_file_location,
return 'M' + l['x1'] + ' ' + l['y1'] + 'L' + l['x2'] + ' ' + l['y2'] return_svg_attributes=False,
convert_circles_to_paths=True,
convert_ellipses_to_paths=True,
CONVERSIONS = {'circle': ellipse2pathd, convert_lines_to_paths=True,
'ellipse': ellipse2pathd, convert_polylines_to_paths=True,
'line': line2pathd, convert_polygons_to_paths=True,
'polyline': polyline2pathd, convert_rectangles_to_paths=True):
'polygon': polygon2pathd, """Converts an SVG into a list of Path objects and attribute dictionaries.
'rect': rect2pathd}
def svg2paths(svg_file_location, return_svg_attributes=False,
conversions=CONVERSIONS, return_tree=False):
"""Converts SVG to list of Path objects and attribute dictionaries.
Converts an SVG file into a list of Path objects and a list of Converts an SVG file into a list of Path objects and a list of
dictionaries containing their attributes. This currently supports dictionaries containing their attributes. This currently supports
@ -111,81 +106,106 @@ def svg2paths(svg_file_location, return_svg_attributes=False,
Args: Args:
svg_file_location (string): the location of the svg file svg_file_location (string): the location of the svg file
return_svg_attributes (bool): Set to True and a dictionary of return_svg_attributes (bool): Set to True and a dictionary of
svg-attributes will be extracted and returned. See also svg-attributes will be extracted and returned. See also the
the `svg2paths2()` function. `svg2paths2()` function.
convert_circles_to_paths: Set to False to exclude SVG-Circle convert_circles_to_paths: Set to False to exclude SVG-Circle
elements (converted to Paths). By default circles are elements (converted to Paths). By default circles are included as
included as paths of two `Arc` objects. paths of two `Arc` objects.
convert_ellipses_to_paths (bool): Set to False to exclude convert_ellipses_to_paths (bool): Set to False to exclude SVG-Ellipse
SVG-Ellipse elements (converted to Paths). By default elements (converted to Paths). By default ellipses are included as
ellipses are included as paths of two `Arc` objects. paths of two `Arc` objects.
convert_lines_to_paths (bool): Set to False to exclude SVG-Line convert_lines_to_paths (bool): Set to False to exclude SVG-Line elements
(converted to Paths)
convert_polylines_to_paths (bool): Set to False to exclude SVG-Polyline
elements (converted to Paths) elements (converted to Paths)
convert_polylines_to_paths (bool): Set to False to exclude convert_polygons_to_paths (bool): Set to False to exclude SVG-Polygon
SVG-Polyline elements (converted to Paths) elements (converted to Paths)
convert_polygons_to_paths (bool): Set to False to exclude convert_rectangles_to_paths (bool): Set to False to exclude SVG-Rect
SVG-Polygon elements (converted to Paths) elements (converted to Paths).
convert_rectangles_to_paths (bool): Set to False to exclude
SVG-Rect elements (converted to Paths).
Returns: Returns:
list: The list of Path objects. list: The list of Path objects.
list: The list of corresponding path attribute dictionaries. list: The list of corresponding path attribute dictionaries.
dict (optional): A dictionary of svg-attributes (see ` dict (optional): A dictionary of svg-attributes (see `svg2paths2()`).
svg2paths2()`).
""" """
if os.path.dirname(svg_file_location) == '': if os_path.dirname(svg_file_location) == '':
svg_file_location = os.path.join(getcwd(), svg_file_location) svg_file_location = os_path.join(getcwd(), svg_file_location)
tree = etree.parse(svg_file_location) doc = parse(svg_file_location)
# get URI namespace def dom2dict(element):
root_tag = tree.getroot().tag """Converts DOM elements to dictionaries of attributes."""
if root_tag[0] == "{": keys = list(element.attributes.keys())
prefix = root_tag[:root_tag.find('}') + 1] values = [val.value for val in list(element.attributes.values())]
else: return dict(list(zip(keys, values)))
prefix = ''
# etree.register_namespace('', prefix)
def getElementsByTagName(tag): # Use minidom to extract path strings from input SVG
return tree.iter(tag=prefix+tag) paths = [dom2dict(el) for el in doc.getElementsByTagName('path')]
# Get d-strings for Path elements
paths = [el.attrib for el in getElementsByTagName('path')]
d_strings = [el['d'] for el in paths] d_strings = [el['d'] for el in paths]
attribute_dictionary_list = paths attribute_dictionary_list = paths
# Get d-strings for Path-like elements (using `conversions` dict) # Use minidom to extract polyline strings from input SVG, convert to
for tag, fcn in conversions.items(): # path strings, add to list
attributes = [el.attrib for el in getElementsByTagName(tag)] if convert_polylines_to_paths:
d_strings += [fcn(d) for d in attributes] plins = [dom2dict(el) for el in doc.getElementsByTagName('polyline')]
d_strings += [polyline2pathd(pl['points']) for pl in plins]
attribute_dictionary_list += plins
# Use minidom to extract polygon strings from input SVG, convert to
# path strings, add to list
if convert_polygons_to_paths:
pgons = [dom2dict(el) for el in doc.getElementsByTagName('polygon')]
d_strings += [polygon2pathd(pg['points']) for pg in pgons]
attribute_dictionary_list += pgons
if convert_lines_to_paths:
lines = [dom2dict(el) for el in doc.getElementsByTagName('line')]
d_strings += [('M' + l['x1'] + ' ' + l['y1'] +
'L' + l['x2'] + ' ' + l['y2']) for l in lines]
attribute_dictionary_list += lines
if convert_ellipses_to_paths:
ellipses = [dom2dict(el) for el in doc.getElementsByTagName('ellipse')]
d_strings += [ellipse2pathd(e) for e in ellipses]
attribute_dictionary_list += ellipses
if convert_circles_to_paths:
circles = [dom2dict(el) for el in doc.getElementsByTagName('circle')]
d_strings += [ellipse2pathd(c) for c in circles]
attribute_dictionary_list += circles
if convert_rectangles_to_paths:
rectangles = [dom2dict(el) for el in doc.getElementsByTagName('rect')]
d_strings += [rect2pathd(r) for r in rectangles]
attribute_dictionary_list += rectangles
if return_svg_attributes:
svg_attributes = dom2dict(doc.getElementsByTagName('svg')[0])
doc.unlink()
path_list = [parse_path(d) for d in d_strings] path_list = [parse_path(d) for d in d_strings]
if return_tree: # svg2paths3 default behavior
return path_list, tree
elif return_svg_attributes: # svg2paths2 default behavior
svg_attributes = getElementsByTagName('svg')[0].attrib
return path_list, attribute_dictionary_list, svg_attributes return path_list, attribute_dictionary_list, svg_attributes
else:
else: # svg2paths default behavior doc.unlink()
path_list = [parse_path(d) for d in d_strings]
return path_list, attribute_dictionary_list return path_list, attribute_dictionary_list
def svg2paths2(svg_file_location, return_svg_attributes=True, def svg2paths2(svg_file_location,
conversions=CONVERSIONS, return_tree=False): return_svg_attributes=True,
convert_circles_to_paths=True,
convert_ellipses_to_paths=True,
convert_lines_to_paths=True,
convert_polylines_to_paths=True,
convert_polygons_to_paths=True,
convert_rectangles_to_paths=True):
"""Convenience function; identical to svg2paths() except that """Convenience function; identical to svg2paths() except that
return_svg_attributes=True by default. See svg2paths() docstring return_svg_attributes=True by default. See svg2paths() docstring for more
for more info.""" info."""
return svg2paths(svg_file_location=svg_file_location, return svg2paths(svg_file_location=svg_file_location,
return_svg_attributes=return_svg_attributes, return_svg_attributes=return_svg_attributes,
conversions=conversions, return_tree=return_tree) convert_circles_to_paths=convert_circles_to_paths,
convert_ellipses_to_paths=convert_ellipses_to_paths,
convert_lines_to_paths=convert_lines_to_paths,
def svg2paths3(svg_file_location, return_svg_attributes=True, convert_polylines_to_paths=convert_polylines_to_paths,
conversions=CONVERSIONS, return_tree=True): convert_polygons_to_paths=convert_polygons_to_paths,
"""Convenience function; identical to svg2paths() except that convert_rectangles_to_paths=convert_rectangles_to_paths)
return_tree=True. See svg2paths() docstring for more info."""
return svg2paths(svg_file_location=svg_file_location,
return_svg_attributes=return_svg_attributes,
conversions=conversions, return_tree=return_tree)