This repository has been archived by the owner on Dec 4, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
geo.py
425 lines (336 loc) · 9.89 KB
/
geo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
import re
import math
import logging
import numpy as np
from bs4 import BeautifulSoup
from common import clean_whitespace
LOG = logging.getLogger("geo")
def text_to_mm(text):
text = text.strip().lower()
match = re.compile(r"^([0-9.]+)\s*mm$", re.U).match(text)
if match:
return float(match.group(1))
match = re.compile(r"^([0-9.]+)\s*cm$", re.U).match(text)
if match:
return float(match.group(1)) * 10
match = re.compile(r"^([0-9.]+)\s*in$", re.U).match(text)
if match:
return float(match.group(1)) * 25.4
LOG.error(
"No conversion to millimeters found for '%s'.",
text
)
return None
def transform_poly(poly, xform):
poly2 = []
for vertex in poly:
v1 = np.matrix([[vertex[0]], [vertex[1]], [1]])
v2 = xform * v1
poly2.append([v2[0, 0], v2[1, 0]])
return poly2
def poly_points_bezier(_command, cursor, segment, absolute):
"""
Return absolute points
"""
vertex_list = [tuple(cursor)]
while segment:
vertex = tuple(segment[:2])
segment = segment[2:]
if absolute:
vertex_list.append(tuple(vertex))
else:
vertex_list.append((
cursor[0] + vertex[0],
cursor[1] + vertex[1]
))
def point(p0, p1, p2, p3, t):
return (
p0 * pow((1 - t), 3) +
p1 * 3 * pow((1 - t), 2) * t +
p2 * 3 * (1 - t) * pow(t, 2) +
p3 * pow(t, 3)
)
def ang_diff(a1, a2):
diff = a2 - a1
if diff > math.pi:
diff -= 2 * math.pi
if diff < -math.pi:
diff += 2 * math.pi
return diff
p = vertex_list
a1 = math.atan2(p[1][1] - p[0][1], p[1][0] - p[0][0])
a2 = math.atan2(p[2][1] - p[1][1], p[2][0] - p[1][0])
a3 = math.atan2(p[3][1] - p[2][1], p[3][0] - p[2][0])
d1 = ang_diff(a1, a2)
d2 = ang_diff(a2, a3)
dx = p[3][0] - p[0][0]
dy = p[3][1] - p[0][1]
length = math.sqrt(dx * dx + dy * dy)
d = abs(d1) + abs(d2)
vertex_list = []
n = 1 + int(10 * d) + int(length / 100)
for i in range(n):
t = float(i + 1) / n
x = point(p[0][0], p[1][0], p[2][0], p[3][0], t)
y = point(p[0][1], p[1][1], p[2][1], p[3][1], t)
vertex_list.append((x, y))
return vertex_list
def poly_points_linear(command, cursor, segment, absolute):
"""
Return absolute points
"""
if command.upper() == "H":
segment.insert(1, cursor[1] if absolute else 0)
if command.upper() == "V":
segment.insert(0, cursor[0] if absolute else 0)
if absolute:
return [list(segment)]
return [[
cursor[0] + segment[0],
cursor[1] + segment[1],
]]
def path_to_poly_list(path):
path = " " + clean_whitespace(path)
path = re.compile(" ([mlhvzcsqta])([0-9-])", re.I).sub(r"\1 \2", path)
path = re.sub(",", " ", path)
handlers = {
"M": {
"length": 2,
"draw": False,
"path": poly_points_linear,
},
"L": {
"length": 2,
"path": poly_points_linear,
},
"H": {
"length": 1,
"path": poly_points_linear,
},
"V": {
"length": 1,
"path": poly_points_linear,
},
"Z": {
"length": 0
},
"C": {
"length": 6,
"path": poly_points_bezier,
},
}
poly_list = [[]]
cursor = [0, 0]
command_list = re.compile(" ([mlhvzcsqta])", re.I).split(path)[1:]
for i in range(0, len(command_list), 2):
command = command_list[i]
absolute = command == command.upper()
values = clean_whitespace(command_list[i + 1]).split()
try:
handler = handlers[command.upper()]
except KeyError:
LOG.error("No handler for path segment: %s %s",
command, values)
break
try:
values = [float(v) for v in values]
except ValueError:
LOG.error("Could not convert all values to float: %s",
values)
break
if handler.get("draw", True) is False:
if poly_list[-1]:
poly_list.append([])
while values:
segment = values[:handler["length"]]
values = values[handler["length"]:]
if "value" in handler:
segment = handler["value"](segment)
if not "path" in handler:
break
vertex_list = handler["path"](
command, cursor, segment, absolute)
for vertex in vertex_list:
cursor = list(vertex)
poly_list[-1].append(cursor)
if command.upper() == "Z":
poly_list[-1].append(poly_list[-1][0])
poly_list = [[(v[0], v[1]) for v in poly] for poly in poly_list]
return poly_list
def parse_transform(text):
text = clean_whitespace(text)
match = re.compile(r"""
matrix\(
([0-9.e-]+),
([0-9.e-]+),
([0-9.e-]+),
([0-9.e-]+),
([0-9.e-]+),
([0-9.e-]+)
\)""", re.X).match(text)
if match:
LOG.debug("transform: %s" % match.group(0))
xform = [float(v) for v in match.groups()]
return np.matrix((
[xform[0], xform[2], xform[4]],
[xform[1], xform[3], xform[5]],
[0, 0, 1]
))
match = re.compile(r"""
translate\(
([0-9.e-]+),
([0-9.e-]+)
\)
""", re.X).match(text)
if match:
LOG.debug("transform: %s" % match.group(0))
xform = [float(v) for v in match.groups()]
return np.matrix((
[1, 0, xform[0]],
[0, 1, xform[1]],
[0, 0, 1]
))
match = re.compile(r"""
translate\(
([0-9.e-]+)
\)
""", re.X).match(text)
if match:
LOG.debug("transform: %s" % match.group(0))
xform = [float(v) for v in match.groups()]
return np.matrix((
[1, 0, xform[0]],
[0, 1, 0],
[0, 0, 1]
))
match = re.compile(r"""
rotate\(
([0-9.e-]+)
\)
""", re.X).match(text)
if match:
LOG.debug("transform: %s" % match.group(0))
xform = [float(v) for v in match.groups()]
theta = math.radians(xform[0])
return np.matrix((
[math.cos(theta), math.sin(theta), 0],
[-math.sin(theta), math.cos(theta), 0],
[0, 0, 1]
))
match = re.compile(r"""
rotate\(
([0-9.e-]+),
([0-9.e-]+),
([0-9.e-]+)
\)
""", re.X).match(text)
if match:
LOG.debug("transform: %s" % match.group(0))
xform = [float(v) for v in match.groups()]
theta = math.radians(xform[0])
return np.matrix((
[1, 0, xform[1]],
[0, 1, xform[2]],
[0, 0, 1]
)) * np.matrix((
[math.cos(theta), -math.sin(theta), 0],
[math.sin(theta), math.cos(theta), 0],
[0, 0, 1]
)) * np.matrix((
[1, 0, -xform[1]],
[0, 1, -xform[2]],
[0, 0, 1]
))
match = re.compile(r"""
scale\(
([0-9.e-]+),
([0-9.e-]+)
\)
""", re.X).match(text)
if match:
LOG.debug("transform: %s" % match.group(0))
xform = [float(v) for v in match.groups()]
return np.matrix((
[xform[0], 0, 0],
[0, xform[1], 0],
[0, 0, 1]
))
match = re.compile(r"""
scale\(
([0-9.e-]+)
\)
""", re.X).match(text)
if match:
LOG.debug("transform: %s" % match.group(0))
xform = [float(v) for v in match.groups()]
return np.matrix((
[xform[0], 0, 0],
[0, xform[0], 0],
[0, 0, 1]
))
LOG.warning(
"No transform procedure defined for '%s'", text)
return None
def extract_paths(node, xform=None, depth=None):
if xform is None:
xform = np.identity(3)
if depth is None:
depth = 0
if not hasattr(node, "name") or node.name is None:
return []
paths = []
if hasattr(node, "attrs") and "transform" in node.attrs:
LOG.debug("transform raw: %s %s", node.name, node["transform"])
xform_ = parse_transform(node["transform"])
if xform_ is not None:
xform = xform * xform_
if node.name == "path":
path = node.attrs["d"]
poly_list = path_to_poly_list(path)
poly_list = [transform_poly(poly, xform) for poly in poly_list]
paths += poly_list
elif node.name in ["svg", "g"]:
label = node.get("inkscape:label", None)
style = node.get("style", "")
if "display:none" not in style:
if label:
LOG.info(label)
for child in node:
paths += extract_paths(child, np.copy(xform), depth + 1)
else:
if label:
LOG.debug(label)
elif node.name.startswith("sodipodi"):
pass
elif node.name in ["metadata", "defs"]:
pass
else:
LOG.warning("Ignoring node: %s", node.name)
return paths
def svg2paths(svg_file):
LOG.info("Converting %s", svg_file.name)
svg_text = svg_file.read()
soup = BeautifulSoup(svg_text, "lxml")
svg = soup.find("svg")
xform = None
width = svg.get("width", None)
height = svg.get("height", None)
viewbox = svg.get("viewbox", None)
if width and height and viewbox:
width = text_to_mm(width)
height = text_to_mm(height)
viewbox = [float(v) for v in viewbox.split()]
unit_scale = [
width / viewbox[2],
height / viewbox[3]
]
LOG.info("Page size (mm): %0.3f x %0.3f", width, height)
LOG.info("View box: %0.3f %0.3f %0.3f %0.3f", *viewbox)
LOG.info("Unit scale: %0.3f, %0.3f", *unit_scale)
xform = np.matrix([
[unit_scale[0], 0, 0],
[0, -unit_scale[1], height],
[0, 0, 1]
])
paths = extract_paths(svg, xform)
return paths