ParseSVG.py 23 KB

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