ParseSVG.py 21 KB

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