ParseSVG.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 12/18/2015 #
  6. # MIT Licence #
  7. # #
  8. # SVG Features supported: #
  9. # * Groups #
  10. # * Rectangles (w/ rounded corners) #
  11. # * Circles #
  12. # * Ellipses #
  13. # * Polygons #
  14. # * Polylines #
  15. # * Lines #
  16. # * Paths #
  17. # * All transformations #
  18. # #
  19. # Reference: www.w3.org/TR/SVG/Overview.html #
  20. # ##########################################################
  21. # import xml.etree.ElementTree as ET
  22. from svg.path import Line, Arc, CubicBezier, QuadraticBezier, parse_path
  23. from svg.path.path import Move
  24. from svg.path.path import Close
  25. from shapely.geometry import LineString, LinearRing, MultiLineString
  26. from shapely.affinity import skew, affine_transform, rotate
  27. import numpy as np
  28. from flatcamParsers.ParseFont import *
  29. log = logging.getLogger('base2')
  30. def svgparselength(lengthstr):
  31. """
  32. Parse an SVG length string into a float and a units
  33. string, if any.
  34. :param lengthstr: SVG length string.
  35. :return: Number and units pair.
  36. :rtype: tuple(float, str|None)
  37. """
  38. integer_re_str = r'[+-]?[0-9]+'
  39. number_re_str = r'(?:[+-]?[0-9]*\.[0-9]+(?:[Ee]' + integer_re_str + ')?' + r')|' + \
  40. r'(?:' + integer_re_str + r'(?:[Ee]' + integer_re_str + r')?)'
  41. length_re_str = r'(' + number_re_str + r')(em|ex|px|in|cm|mm|pt|pc|%)?'
  42. match = re.search(length_re_str, lengthstr)
  43. if match:
  44. return float(match.group(1)), match.group(2)
  45. return
  46. def path2shapely(path, object_type, res=1.0):
  47. """
  48. Converts an svg.path.Path into a Shapely
  49. Polygon or LinearString.
  50. :rtype : Polygon
  51. :rtype : LineString
  52. :param path: svg.path.Path instance
  53. :param res: Resolution (minimum step along path)
  54. :return: Shapely geometry object
  55. """
  56. points = []
  57. geometry = []
  58. geo_element = None
  59. rings = []
  60. closed = False
  61. for component in path:
  62. # Line
  63. if isinstance(component, Line):
  64. start = component.start
  65. x, y = start.real, start.imag
  66. if len(points) == 0 or points[-1] != (x, y):
  67. points.append((x, y))
  68. end = component.end
  69. points.append((end.real, end.imag))
  70. continue
  71. # Arc, CubicBezier or QuadraticBezier
  72. if isinstance(component, Arc) or \
  73. isinstance(component, CubicBezier) or \
  74. isinstance(component, QuadraticBezier):
  75. # How many points to use in the discrete representation.
  76. length = component.length(res / 10.0)
  77. # steps = int(length / res + 0.5)
  78. steps = int(length) * 2
  79. # solve error when step is below 1,
  80. # it may cause other problems, but LineString needs at least two points
  81. if steps == 0:
  82. steps = 1
  83. frac = 1.0 / steps
  84. # print length, steps, frac
  85. for i in range(steps):
  86. point = component.point(i * frac)
  87. x, y = point.real, point.imag
  88. if len(points) == 0 or points[-1] != (x, y):
  89. points.append((x, y))
  90. end = component.point(1.0)
  91. points.append((end.real, end.imag))
  92. continue
  93. # Move
  94. if isinstance(component, Move):
  95. if not points:
  96. continue
  97. else:
  98. rings.append(points)
  99. if closed is False:
  100. points = []
  101. else:
  102. closed = False
  103. start = component.start
  104. x, y = start.real, start.imag
  105. points = [(x, y)]
  106. continue
  107. closed = False
  108. # Close
  109. if isinstance(component, Close):
  110. if not points:
  111. continue
  112. else:
  113. rings.append(points)
  114. points = []
  115. closed = True
  116. continue
  117. log.warning("I don't know what this is: %s" % str(component))
  118. continue
  119. # if there are still points in points then add them to the last ring
  120. if points:
  121. rings.append(points)
  122. try:
  123. rings = MultiLineString(rings)
  124. except Exception as e:
  125. log.debug("ParseSVG.path2shapely() MString --> %s" % str(e))
  126. return None
  127. if len(rings) > 0:
  128. if len(rings) == 1 and not isinstance(rings, MultiLineString):
  129. # Polygons are closed and require more than 2 points
  130. if Point(rings[0][0]).almost_equals(Point(rings[0][-1])) and len(rings[0]) > 2:
  131. geo_element = Polygon(rings[0])
  132. else:
  133. geo_element = LineString(rings[0])
  134. else:
  135. try:
  136. geo_element = Polygon(rings[0], rings[1:])
  137. except Exception:
  138. coords = []
  139. for line in rings:
  140. coords.append(line.coords[0])
  141. coords.append(line.coords[1])
  142. try:
  143. geo_element = Polygon(coords)
  144. except Exception:
  145. geo_element = LineString(coords)
  146. geometry.append(geo_element)
  147. return geometry
  148. def svgrect2shapely(rect, n_points=32):
  149. """
  150. Converts an SVG rect into Shapely geometry.
  151. :param rect: Rect Element
  152. :type rect: xml.etree.ElementTree.Element
  153. :return: shapely.geometry.polygon.LinearRing
  154. """
  155. w = svgparselength(rect.get('width'))[0]
  156. h = svgparselength(rect.get('height'))[0]
  157. x_obj = rect.get('x')
  158. if x_obj is not None:
  159. x = svgparselength(x_obj)[0]
  160. else:
  161. x = 0
  162. y_obj = rect.get('y')
  163. if y_obj is not None:
  164. y = svgparselength(y_obj)[0]
  165. else:
  166. y = 0
  167. rxstr = rect.get('rx')
  168. rystr = rect.get('ry')
  169. if rxstr is None and rystr is None: # Sharp corners
  170. pts = [
  171. (x, y), (x + w, y), (x + w, y + h), (x, y + h), (x, y)
  172. ]
  173. else: # Rounded corners
  174. rx = 0.0 if rxstr is None else svgparselength(rxstr)[0]
  175. ry = 0.0 if rystr is None else svgparselength(rystr)[0]
  176. n_points = int(n_points / 4 + 0.5)
  177. t = np.arange(n_points, dtype=float) / n_points / 4
  178. x_ = (x + w - rx) + rx * np.cos(2 * np.pi * (t + 0.75))
  179. y_ = (y + ry) + ry * np.sin(2 * np.pi * (t + 0.75))
  180. lower_right = [(x_[i], y_[i]) for i in range(n_points)]
  181. x_ = (x + w - rx) + rx * np.cos(2 * np.pi * t)
  182. y_ = (y + h - ry) + ry * np.sin(2 * np.pi * t)
  183. upper_right = [(x_[i], y_[i]) for i in range(n_points)]
  184. x_ = (x + rx) + rx * np.cos(2 * np.pi * (t + 0.25))
  185. y_ = (y + h - ry) + ry * np.sin(2 * np.pi * (t + 0.25))
  186. upper_left = [(x_[i], y_[i]) for i in range(n_points)]
  187. x_ = (x + rx) + rx * np.cos(2 * np.pi * (t + 0.5))
  188. y_ = (y + ry) + ry * np.sin(2 * np.pi * (t + 0.5))
  189. lower_left = [(x_[i], y_[i]) for i in range(n_points)]
  190. pts = [(x + rx, y), (x - rx + w, y)] + \
  191. lower_right + \
  192. [(x + w, y + ry), (x + w, y + h - ry)] + \
  193. upper_right + \
  194. [(x + w - rx, y + h), (x + rx, y + h)] + \
  195. upper_left + \
  196. [(x, y + h - ry), (x, y + ry)] + \
  197. lower_left
  198. return Polygon(pts).buffer(0)
  199. # return LinearRing(pts)
  200. def svgcircle2shapely(circle):
  201. """
  202. Converts an SVG circle into Shapely geometry.
  203. :param circle: Circle Element
  204. :type circle: xml.etree.ElementTree.Element
  205. :return: Shapely representation of the circle.
  206. :rtype: shapely.geometry.polygon.LinearRing
  207. """
  208. # cx = float(circle.get('cx'))
  209. # cy = float(circle.get('cy'))
  210. # r = float(circle.get('r'))
  211. cx = svgparselength(circle.get('cx'))[0] # TODO: No units support yet
  212. cy = svgparselength(circle.get('cy'))[0] # TODO: No units support yet
  213. r = svgparselength(circle.get('r'))[0] # TODO: No units support yet
  214. # TODO: No resolution specified.
  215. return Point(cx, cy).buffer(r)
  216. def svgellipse2shapely(ellipse, n_points=64):
  217. """
  218. Converts an SVG ellipse into Shapely geometry
  219. :param ellipse: Ellipse Element
  220. :type ellipse: xml.etree.ElementTree.Element
  221. :param n_points: Number of discrete points in output.
  222. :return: Shapely representation of the ellipse.
  223. :rtype: shapely.geometry.polygon.LinearRing
  224. """
  225. cx = svgparselength(ellipse.get('cx'))[0] # TODO: No units support yet
  226. cy = svgparselength(ellipse.get('cy'))[0] # TODO: No units support yet
  227. rx = svgparselength(ellipse.get('rx'))[0] # TODO: No units support yet
  228. ry = svgparselength(ellipse.get('ry'))[0] # TODO: No units support yet
  229. t = np.arange(n_points, dtype=float) / n_points
  230. x = cx + rx * np.cos(2 * np.pi * t)
  231. y = cy + ry * np.sin(2 * np.pi * t)
  232. pts = [(x[i], y[i]) for i in range(n_points)]
  233. return Polygon(pts).buffer(0)
  234. # return LinearRing(pts)
  235. def svgline2shapely(line):
  236. """
  237. :param line: Line element
  238. :type line: xml.etree.ElementTree.Element
  239. :return: Shapely representation on the line.
  240. :rtype: shapely.geometry.polygon.LinearRing
  241. """
  242. x1 = svgparselength(line.get('x1'))[0]
  243. y1 = svgparselength(line.get('y1'))[0]
  244. x2 = svgparselength(line.get('x2'))[0]
  245. y2 = svgparselength(line.get('y2'))[0]
  246. return LineString([(x1, y1), (x2, y2)])
  247. def svgpolyline2shapely(polyline):
  248. ptliststr = polyline.get('points')
  249. points = parse_svg_point_list(ptliststr)
  250. return LineString(points)
  251. def svgpolygon2shapely(polygon):
  252. ptliststr = polygon.get('points')
  253. points = parse_svg_point_list(ptliststr)
  254. return Polygon(points).buffer(0)
  255. # return LinearRing(points)
  256. def getsvggeo(node, object_type, root=None):
  257. """
  258. Extracts and flattens all geometry from an SVG node
  259. into a list of Shapely geometry.
  260. :param node: xml.etree.ElementTree.Element
  261. :return: List of Shapely geometry
  262. :rtype: list
  263. """
  264. if root is None:
  265. root = node
  266. kind = re.search('(?:\{.*\})?(.*)$', node.tag).group(1)
  267. geo = []
  268. # Recurse
  269. if len(node) > 0:
  270. for child in node:
  271. subgeo = getsvggeo(child, object_type, root)
  272. if subgeo is not None:
  273. geo += subgeo
  274. # Parse
  275. elif kind == 'path':
  276. log.debug("***PATH***")
  277. P = parse_path(node.get('d'))
  278. P = path2shapely(P, object_type)
  279. # for path, the resulting geometry is already a list so no need to create a new one
  280. geo = P
  281. elif kind == 'rect':
  282. log.debug("***RECT***")
  283. R = svgrect2shapely(node)
  284. geo = [R]
  285. elif kind == 'circle':
  286. log.debug("***CIRCLE***")
  287. C = svgcircle2shapely(node)
  288. geo = [C]
  289. elif kind == 'ellipse':
  290. log.debug("***ELLIPSE***")
  291. E = svgellipse2shapely(node)
  292. geo = [E]
  293. elif kind == 'polygon':
  294. log.debug("***POLYGON***")
  295. poly = svgpolygon2shapely(node)
  296. geo = [poly]
  297. elif kind == 'line':
  298. log.debug("***LINE***")
  299. line = svgline2shapely(node)
  300. geo = [line]
  301. elif kind == 'polyline':
  302. log.debug("***POLYLINE***")
  303. pline = svgpolyline2shapely(node)
  304. geo = [pline]
  305. elif kind == 'use':
  306. log.debug('***USE***')
  307. # href= is the preferred name for this[1], but inkscape still generates xlink:href=.
  308. # [1] https://developer.mozilla.org/en-US/docs/Web/SVG/Element/use#Attributes
  309. href = node.attrib['href'] if 'href' in node.attrib else node.attrib['{http://www.w3.org/1999/xlink}href']
  310. ref = root.find(".//*[@id='%s']" % href.replace('#', ''))
  311. if ref is not None:
  312. geo = getsvggeo(ref, object_type, root)
  313. else:
  314. log.warning("Unknown kind: " + kind)
  315. geo = None
  316. # ignore transformation for unknown kind
  317. if geo is not None:
  318. # Transformations
  319. if 'transform' in node.attrib:
  320. trstr = node.get('transform')
  321. trlist = parse_svg_transform(trstr)
  322. # log.debug(trlist)
  323. # Transformations are applied in reverse order
  324. for tr in trlist[::-1]:
  325. if tr[0] == 'translate':
  326. geo = [translate(geoi, tr[1], tr[2]) for geoi in geo]
  327. elif tr[0] == 'scale':
  328. geo = [scale(geoi, tr[1], tr[2], origin=(0, 0))
  329. for geoi in geo]
  330. elif tr[0] == 'rotate':
  331. geo = [rotate(geoi, tr[1], origin=(tr[2], tr[3]))
  332. for geoi in geo]
  333. elif tr[0] == 'skew':
  334. geo = [skew(geoi, tr[1], tr[2], origin=(0, 0))
  335. for geoi in geo]
  336. elif tr[0] == 'matrix':
  337. geo = [affine_transform(geoi, tr[1:]) for geoi in geo]
  338. else:
  339. raise Exception('Unknown transformation: %s', tr)
  340. return geo
  341. def getsvgtext(node, object_type, units='MM'):
  342. """
  343. Extracts and flattens all geometry from an SVG node
  344. into a list of Shapely geometry.
  345. :param node: xml.etree.ElementTree.Element
  346. :return: List of Shapely geometry
  347. :rtype: list
  348. """
  349. kind = re.search('(?:\{.*\})?(.*)$', node.tag).group(1)
  350. geo = []
  351. # Recurse
  352. if len(node) > 0:
  353. for child in node:
  354. subgeo = getsvgtext(child, object_type, units=units)
  355. if subgeo is not None:
  356. geo += subgeo
  357. # Parse
  358. elif kind == 'tspan':
  359. current_attrib = node.attrib
  360. txt = node.text
  361. style_dict = {}
  362. parrent_attrib = node.getparent().attrib
  363. style = parrent_attrib['style']
  364. try:
  365. style_list = style.split(';')
  366. for css in style_list:
  367. style_dict[css.rpartition(':')[0]] = css.rpartition(':')[-1]
  368. pos_x = float(current_attrib['x'])
  369. pos_y = float(current_attrib['y'])
  370. # should have used the instance from FlatCAMApp.App but how? without reworking everything ...
  371. pf = ParseFont()
  372. pf.get_fonts_by_types()
  373. font_name = style_dict['font-family'].replace("'", '')
  374. if style_dict['font-style'] == 'italic' and style_dict['font-weight'] == 'bold':
  375. font_type = 'bi'
  376. elif style_dict['font-weight'] == 'bold':
  377. font_type = 'bold'
  378. elif style_dict['font-style'] == 'italic':
  379. font_type = 'italic'
  380. else:
  381. font_type = 'regular'
  382. # value of 2.2 should have been 2.83 (conversion value from pixels to points)
  383. # but the dimensions from Inkscape did not corelate with the ones after importing in FlatCAM
  384. # so I adjusted this
  385. font_size = svgparselength(style_dict['font-size'])[0] * 2.2
  386. geo = [pf.font_to_geometry(txt,
  387. font_name=font_name,
  388. font_size=font_size,
  389. font_type=font_type,
  390. units=units,
  391. coordx=pos_x,
  392. coordy=pos_y)
  393. ]
  394. geo = [(scale(g, 1.0, -1.0)) for g in geo]
  395. except Exception as e:
  396. log.debug(str(e))
  397. else:
  398. geo = None
  399. # ignore transformation for unknown kind
  400. if geo is not None:
  401. # Transformations
  402. if 'transform' in node.attrib:
  403. trstr = node.get('transform')
  404. trlist = parse_svg_transform(trstr)
  405. # log.debug(trlist)
  406. # Transformations are applied in reverse order
  407. for tr in trlist[::-1]:
  408. if tr[0] == 'translate':
  409. geo = [translate(geoi, tr[1], tr[2]) for geoi in geo]
  410. elif tr[0] == 'scale':
  411. geo = [scale(geoi, tr[1], tr[2], origin=(0, 0))
  412. for geoi in geo]
  413. elif tr[0] == 'rotate':
  414. geo = [rotate(geoi, tr[1], origin=(tr[2], tr[3]))
  415. for geoi in geo]
  416. elif tr[0] == 'skew':
  417. geo = [skew(geoi, tr[1], tr[2], origin=(0, 0))
  418. for geoi in geo]
  419. elif tr[0] == 'matrix':
  420. geo = [affine_transform(geoi, tr[1:]) for geoi in geo]
  421. else:
  422. raise Exception('Unknown transformation: %s', tr)
  423. return geo
  424. def parse_svg_point_list(ptliststr):
  425. """
  426. Returns a list of coordinate pairs extracted from the "points"
  427. attribute in SVG polygons and polyline's.
  428. :param ptliststr: "points" attribute string in polygon or polyline.
  429. :return: List of tuples with coordinates.
  430. """
  431. pairs = []
  432. last = None
  433. pos = 0
  434. i = 0
  435. for match in re.finditer(r'(\s*,\s*)|(\s+)', ptliststr.strip(' ')):
  436. val = float(ptliststr[pos:match.start()])
  437. if i % 2 == 1:
  438. pairs.append((last, val))
  439. else:
  440. last = val
  441. pos = match.end()
  442. i += 1
  443. # Check for last element
  444. val = float(ptliststr[pos:])
  445. if i % 2 == 1:
  446. pairs.append((last, val))
  447. else:
  448. log.warning("Incomplete coordinates.")
  449. return pairs
  450. def parse_svg_transform(trstr):
  451. """
  452. Parses an SVG transform string into a list
  453. of transform names and their parameters.
  454. Possible transformations are:
  455. * Translate: translate(<tx> [<ty>]), which specifies
  456. a translation by tx and ty. If <ty> is not provided,
  457. it is assumed to be zero. Result is
  458. ['translate', tx, ty]
  459. * Scale: scale(<sx> [<sy>]), which specifies a scale operation
  460. by sx and sy. If <sy> is not provided, it is assumed to be
  461. equal to <sx>. Result is: ['scale', sx, sy]
  462. * Rotate: rotate(<rotate-angle> [<cx> <cy>]), which specifies
  463. a rotation by <rotate-angle> degrees about a given point.
  464. If optional parameters <cx> and <cy> are not supplied,
  465. the rotate is about the origin of the current user coordinate
  466. system. Result is: ['rotate', rotate-angle, cx, cy]
  467. * Skew: skewX(<skew-angle>), which specifies a skew
  468. transformation along the x-axis. skewY(<skew-angle>), which
  469. specifies a skew transformation along the y-axis.
  470. Result is ['skew', angle-x, angle-y]
  471. * Matrix: matrix(<a> <b> <c> <d> <e> <f>), which specifies a
  472. transformation in the form of a transformation matrix of six
  473. values. matrix(a,b,c,d,e,f) is equivalent to applying the
  474. transformation matrix [a b c d e f]. Result is
  475. ['matrix', a, b, c, d, e, f]
  476. Note: All parameters to the transformations are "numbers",
  477. i.e. no units present.
  478. :param trstr: SVG transform string.
  479. :type trstr: str
  480. :return: List of transforms.
  481. :rtype: list
  482. """
  483. trlist = []
  484. assert isinstance(trstr, str)
  485. trstr = trstr.strip(' ')
  486. integer_re_str = r'[+-]?[0-9]+'
  487. number_re_str = r'(?:[+-]?[0-9]*\.[0-9]+(?:[Ee]' + integer_re_str + ')?' + r')|' + \
  488. r'(?:' + integer_re_str + r'(?:[Ee]' + integer_re_str + r')?)'
  489. # num_re_str = r'[\+\-]?[0-9\.e]+' # TODO: Negative exponents missing
  490. comma_or_space_re_str = r'(?:(?:\s+)|(?:\s*,\s*))'
  491. translate_re_str = r'translate\s*\(\s*(' + \
  492. number_re_str + r')(?:' + \
  493. comma_or_space_re_str + \
  494. r'(' + number_re_str + r'))?\s*\)'
  495. scale_re_str = r'scale\s*\(\s*(' + \
  496. number_re_str + r')' + \
  497. r'(?:' + comma_or_space_re_str + \
  498. r'(' + number_re_str + r'))?\s*\)'
  499. skew_re_str = r'skew([XY])\s*\(\s*(' + \
  500. number_re_str + r')\s*\)'
  501. rotate_re_str = r'rotate\s*\(\s*(' + \
  502. number_re_str + r')' + \
  503. r'(?:' + comma_or_space_re_str + \
  504. r'(' + number_re_str + r')' + \
  505. comma_or_space_re_str + \
  506. r'(' + number_re_str + r'))?\s*\)'
  507. matrix_re_str = r'matrix\s*\(\s*' + \
  508. r'(' + number_re_str + r')' + comma_or_space_re_str + \
  509. r'(' + number_re_str + r')' + comma_or_space_re_str + \
  510. r'(' + number_re_str + r')' + comma_or_space_re_str + \
  511. r'(' + number_re_str + r')' + comma_or_space_re_str + \
  512. r'(' + number_re_str + r')' + comma_or_space_re_str + \
  513. r'(' + number_re_str + r')\s*\)'
  514. while len(trstr) > 0:
  515. match = re.search(r'^' + translate_re_str, trstr)
  516. if match:
  517. trlist.append([
  518. 'translate',
  519. float(match.group(1)),
  520. float(match.group(2)) if (match.group(2) is not None) else 0.0
  521. ])
  522. trstr = trstr[len(match.group(0)):].strip(' ')
  523. continue
  524. match = re.search(r'^' + scale_re_str, trstr)
  525. if match:
  526. trlist.append([
  527. 'scale',
  528. float(match.group(1)),
  529. float(match.group(2)) if (match.group(2) is not None) else float(match.group(1))
  530. ])
  531. trstr = trstr[len(match.group(0)):].strip(' ')
  532. continue
  533. match = re.search(r'^' + skew_re_str, trstr)
  534. if match:
  535. trlist.append([
  536. 'skew',
  537. float(match.group(2)) if match.group(1) == 'X' else 0.0,
  538. float(match.group(2)) if match.group(1) == 'Y' else 0.0
  539. ])
  540. trstr = trstr[len(match.group(0)):].strip(' ')
  541. continue
  542. match = re.search(r'^' + rotate_re_str, trstr)
  543. if match:
  544. trlist.append([
  545. 'rotate',
  546. float(match.group(1)),
  547. float(match.group(2)) if match.group(2) else 0.0,
  548. float(match.group(3)) if match.group(3) else 0.0
  549. ])
  550. trstr = trstr[len(match.group(0)):].strip(' ')
  551. continue
  552. match = re.search(r'^' + matrix_re_str, trstr)
  553. if match:
  554. trlist.append(['matrix'] + [float(x) for x in match.groups()])
  555. trstr = trstr[len(match.group(0)):].strip(' ')
  556. continue
  557. # raise Exception("Don't know how to parse: %s" % trstr)
  558. log.error("[ERROR] Don't know how to parse: %s" % trstr)
  559. return trlist
  560. # if __name__ == "__main__":
  561. # tree = ET.parse('tests/svg/drawing.svg')
  562. # root = tree.getroot()
  563. # ns = re.search(r'\{(.*)\}', root.tag).group(1)
  564. # print(ns)
  565. # for geo in getsvggeo(root):
  566. # print(geo)