-
Notifications
You must be signed in to change notification settings - Fork 12
/
main.py
339 lines (286 loc) · 11.2 KB
/
main.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
# Modules
import re
import webbrowser
import numpy as np
import svgpathtools
from svgpathtools import Line, CubicBezier
"""
Usage:
- Only SVG file types are supported
- Use https://freesvg.org/ for free SVG files
- Or convert PNG images to SVG using https://convertio.co/png-svg/
"""
# Enter file location here
file = open(r"Images\Untitled (3).svg", "r")
data = str(file.read()).replace('fill="#000000" opacity="1.000000" stroke="none"', "")
file.close()
# Functions
# Detect the types of segments
def _tokenize_path(pathfinder):
FLOAT_RE = re.compile("[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?")
for x in re.compile("([MmZzLlHhVvCcSsQqTtAa])").split(pathfinder):
if x in set("MmZzLlHhVvCcSsQqTtAa"):
yield x
for token in FLOAT_RE.findall(x):
yield token
# transform into a complex number in the for (a + bi)
def aplusbiFormat(real, imaginary):
return real + imaginary * 1j
# Convert points to equations from the bezier points
def extract_path(pathfinder, current_pos=0j):
# Variables
elements = list(_tokenize_path(pathfinder))
elements.reverse()
segments = []
start_pos = None
command = None
# Loop through all the paths
while elements:
if elements[-1] in set("MmZzLlHhVvCcSsQqTtAa"):
command = elements.pop()
absolute = command in set("MZLHVCSQTA")
command = command.upper()
else:
if command is None:
raise ValueError("idk what happened so im just gonna say error. Error!")
if command == "M":
x = elements.pop()
y = elements.pop()
pos = float(x) + float(y) * 1j
if absolute:
current_pos = pos
else:
current_pos += pos
start_pos = current_pos
command = "L"
elif command == "Z":
if not (current_pos == start_pos):
segments.append(Line(current_pos, start_pos))
current_pos = start_pos
command = None
elif command == "L":
x = elements.pop()
y = elements.pop()
pos = float(x) + float(y) * 1j
if not absolute:
pos += current_pos
segments.append(Line(current_pos, pos))
current_pos = pos
elif command == "C":
control1 = float(elements.pop()) + float(elements.pop()) * 1j
control2 = float(elements.pop()) + float(elements.pop()) * 1j
final = float(elements.pop()) + float(elements.pop()) * 1j
if not absolute:
control1 += current_pos
control2 += current_pos
final += current_pos
segments.append(CubicBezier(current_pos, control1, control2, final))
current_pos = final
return segments
# get all the text in between the <path and ></path>
pathArray = re.findall(r'<path d="(.*?)"', data, re.DOTALL)
pathString = ""
for path in pathArray:
pathString += path
path = extract_path(pathString) # Get the path from the SVG file
equations, regularEquations = [], []
for segment in path:
# Iterate through each segment, a set of 4 points, in the SVG file and check what type of segment it is
if isinstance(segment, svgpathtools.path.Line):
# Extract the start and end points from the line segment
start = aplusbiFormat(segment.start.real, segment.start.imag)
end = aplusbiFormat(segment.end.real, segment.end.imag)
# check to make sure line doesn't have undefined slope to prevent mathematical errors
if end.real - start.real != 0 and end.imag - start.imag != 0:
# calculate the slope and y-intercept of the line segment
m = (end.imag - start.imag) / (end.real - start.real)
b = start.imag - m * start.real
# calculate the bounds of the line segment in the x direction
xMin = min(start.real, end.real)
xMax = max(start.real, end.real)
# calculate the bounds of the line segment in the y direction
yMin = min(start.imag, end.imag)
yMax = max(start.imag, end.imag)
# Convert the linear equation into the form y=mx+b and put it in latex format
equations.append(
"y="
+ str(m)
+ "x+"
+ str(b)
+ "\\\\left\\\\{"
+ str(xMin)
+ "\\\\le x \\\\le "
+ str(yMin)
+ "\\\\right\\\\}\\\\left\\\\{"
+ str(yMin)
+ "\\\\le y \\\\le "
+ str(yMax)
+ "\\\\right\\\\}"
)
# Convert the linear equation into the form y=mx+b and put it in lambda format
regularEquations.append(lambda x: m * x + b)
if end.real - start.real == 0:
# calculate the bounds of the line segment in the x direction
xMin = min(start.real, end.real)
xMax = max(start.real, end.real)
# calculate the bounds of the line segment in the y direction
yMin = min(start.imag, end.imag)
yMax = max(start.imag, end.imag)
# Convert the linear equation into the form x=c and put it in latex format
equations.append(
"x="
+ str(start.real)
+ "\\\\left\\\\{"
+ str(xMin)
+ "\\\\le x \\\\le "
+ str(yMin)
+ "\\\\right\\\\}\\\\left\\\\{"
+ str(yMin)
+ "\\\\le y \\\\le "
+ str(yMax)
+ "\\\\right\\\\}"
)
# Convert the linear equation into the form x=c and put it in lambda format
regularEquations.append(lambda x: start.real)
else:
yMin = min(start.imag, end.imag)
yMax = max(start.imag, end.imag)
# if the slope is undefined, then the line is vertical and the equation is in the form x=a
equations.append(
"x="
+ str(start.real)
+ "\\\\left\\\\{"
+ str(yMin)
+ "\\\\le y \\\\le "
+ str(yMax)
+ "\\\\right\\\\}"
)
# if the slope is undefined, then the line is vertical and the equation is in the form x=a
regularEquations.append(lambda x: start.real)
elif isinstance(segment, svgpathtools.path.CubicBezier):
# extract the bezier points from the segment
p0 = aplusbiFormat(segment.start.real, segment.start.imag)
p1 = aplusbiFormat(segment.control1.real, segment.control1.imag)
p2 = aplusbiFormat(segment.control2.real, segment.control2.imag)
p3 = aplusbiFormat(segment.end.real, segment.end.imag)
# Convert the bezier points into a parametric equation in latex format
equations.append(
"\\\\left((1-t)^3*"
+ str(p0.real)
+ "+3*t*(1-t)^2*"
+ str(p1.real)
+ "+3*t^2*(1-t)*"
+ str(p2.real)
+ "+t^3*"
+ str(p3.real)
+ ", (1-t)^3*"
+ str(p0.imag)
+ "+3*t*(1-t)^2*"
+ str(p1.imag)
+ "+3*t^2*(1-t)*"
+ str(p2.imag)
+ "+t^3*"
+ str(p3.imag)
+ ")\\\\right)"
)
# Convert the bezier points into a parametric equation in lambda format
regularEquations.append(
lambda t: (1 - t) ** 3 * p0
+ 3 * t * (1 - t) ** 2 * p1
+ 3 * t ** 2 * (1 - t) * p2
+ t ** 3 * p3
)
elif isinstance(segment, svgpathtools.path.QuadraticBezier):
# Quadratic Bezier segment
p0 = aplusbiFormat(segment.start.real, segment.start.imag)
p1 = aplusbiFormat(segment.control.real, segment.control.imag)
p2 = aplusbiFormat(segment.end.real, segment.end.imag)
# Convert the bezier points into a parametric equation in latex format
equations.append(
"\\\\left((1-t)^2*"
+ str(p0.real)
+ "+2*t*(1-t)*"
+ str(p1.real)
+ "+t^2*"
+ str(p2.real)
+ ", (1-t)^2*"
+ str(p0.imag)
+ "+2*t*(1-t)*"
+ str(p1.imag)
+ "+t^2*"
+ str(p2.imag)
+ ")\\\\right))"
)
# Convert the bezier points into a parametric equation in lambda format
regularEquations.append(
lambda t: (1 - t) ** 2 * p0 + 2 * t * (1 - t) * p1 + t ** 2 * p2
)
elif isinstance(segment, svgpathtools.path.Arc):
# Elliptical arc segment
p0 = aplusbiFormat(segment.start.real, segment.start.imag)
p1 = aplusbiFormat(segment.end.real, segment.end.imag)
r = aplusbiFormat(segment.radius.real, segment.radius.imag)
# Convert the bezier points into a parametric equation in latex format
equations.append(
"\\\\left("
+ str(p0.real)
+ "+"
+ str(r.real)
+ "*\\cos(t), "
+ str(p0.imag)
+ "+"
+ str(r.imag)
+ "*\\sin(t)\\\\right)"
)
# Convert the bezier points into a parametric equation in lambda format
regularEquations.append(lambda t: p0 + r * np.exp(1j * t))
else:
print("Unknown segment type: " + str(type(segment)))
# Define the Desmos API script
desmos = """
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://www.desmos.com/api/v1.8/calculator.js?apiKey=dcb31709b452b1cf9dc26972add0fda6"></script>
<div id="calculator" style="width: 100%; height: 100%;"></div>
<script>
var elt = document.getElementById('calculator');
var calculator = Desmos.GraphingCalculator(elt);
"""
# Add the bounds to the Desmos API script
desmos += (
"calculator.setMathBounds({ left: "
+ str(-194.97)
+ ", right: "
+ str(8852.635)
+ ", bottom: "
+ str(-221.556)
+ ", top: "
+ str(6152.893)
+ " });\n"
)
# Add each equation to the Desmos API script
for i in range(len(equations)):
desmos += (
"calculator.setExpression({ id: 'a-slider"
+ str(i)
+ "', latex: '"
+ equations[i]
+ "', color: Desmos.Colors.BLACK });\n"
)
desmos += "</script>"
# Save and open Desmos file
with open("spiderman.html", "w") as f:
f.write(desmos)
webbrowser.open("spiderman.html", new=2)
# TODO:
# Explain the math
# Complete to do in readme
# Clean up Github Profile
# Create sample HTML files
# save the equations to a file
# print all the eauations
for i in range(len(equations)):
print(equations[i].replace("\\\\", "\\"))
# save the equations to a file
with open("equations.txt", "w") as f:
for i in range(len(equations)):
f.write(equations[i].replace("\\\\", "\\") + "\n")