-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
279 lines (227 loc) Β· 8.64 KB
/
utils.py
File metadata and controls
279 lines (227 loc) Β· 8.64 KB
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
import torch
import torch.nn.functional as F
from svgpathtools import svgstr2paths
from prepare_data import parse_viewbox, make_quantizer
def top_p_filtering(logits, p=0.9):
"""
Apply top-p (nucleus) filtering to the logits.
"""
sorted_logits, sorted_indices = torch.sort(logits, descending=True)
cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
sorted_indices_to_remove = cumulative_probs > p
sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
sorted_indices_to_remove[..., 0] = False
indices_to_remove = sorted_indices[sorted_indices_to_remove]
logits[:, indices_to_remove] = -float("Inf")
return logits
def top_k_filtering(logits, k):
"""
Apply top-k filtering to the logits.
"""
if k <= 0:
return logits
top_k = min(k, logits.size(-1))
values, _ = torch.topk(logits, top_k)
min_values = values[:, -1].unsqueeze(-1)
logits[logits < min_values] = -float("Inf")
return logits
def svg_stroke5(svg_content: str, bins=128, max_sequence_length: int = 200):
"""
Convert SVG path data to a quantized stroke-5 tensor representation.
Each row: (dx, dy, p0, p1, p2) where p0=move, p1=line, p2=end-of-sequence. (One hot pen state encoding)
"""
paths, _ = svgstr2paths(svg_content)
min_x, max_x, min_y, max_y = parse_viewbox(svg_content)
quantize_point = make_quantizer(min_x, max_x, min_y, max_y, bins)
tensor = torch.zeros((max_sequence_length, 5)) # (seq_len, 5)
max_sequence_length = max_sequence_length - 1 # reserve last row for end token
idx = 0
prev = None
for path in paths:
if idx >= max_sequence_length:
break
# Move command (absolute delta from 0,0 if first move)
start_quantized = quantize_point(path[0].start)
dx = start_quantized.real - (prev.real if prev else 0)
dy = start_quantized.imag - (prev.imag if prev else 0)
tensor[idx] = torch.tensor([dx, dy, 0.0, 0.0, 0.0])
prev = start_quantized
idx += 1
# Line segments
for seg in path:
if idx >= max_sequence_length:
break
end_quantized = quantize_point(seg.end)
dx = end_quantized.real - prev.real
dy = end_quantized.imag - prev.imag
tensor[idx] = torch.tensor([dx, dy, 1.0, 0.0, 0.0])
prev = end_quantized
idx += 1
tensor[idx:, 4] = 1.0 # mark unused rows with pen state p2=1
return tensor
def svg_strokes_to_tensor_quantized(
svg_content: str, bins=128, max_sequence_length: int = 200
):
"""
Convert SVG path data to a quantized *stroke* tensor representation.
Each row: (dx, dy, flag)
"""
paths, _ = svgstr2paths(svg_content)
min_x, max_x, min_y, max_y = parse_viewbox(svg_content)
quantize_point = make_quantizer(min_x, max_x, min_y, max_y, bins)
tensor = torch.zeros((max_sequence_length, 3)) # (seq_len, 3)
idx = 0
prev = None
for path in paths:
if idx >= max_sequence_length:
break
# Move command (absolute delta from 0,0 if first move)
start_quantized = quantize_point(path[0].start)
dx = start_quantized.real - (prev.real if prev else 0)
dy = start_quantized.imag - (prev.imag if prev else 0)
tensor[idx] = torch.tensor([dx, dy, 0.0])
prev = start_quantized
idx += 1
# Line segments
for seg in path:
if idx >= max_sequence_length:
break
end_quantized = quantize_point(seg.end)
dx = end_quantized.real - prev.real
dy = end_quantized.imag - prev.imag
tensor[idx] = torch.tensor([dx, dy, 1.0])
prev = end_quantized
idx += 1
return tensor
def svg_strokes_to_tensor(svg_content: str, max_sequence_length: int = 200):
"""
Convert SVG path data to a *stroke* tensor of (dx, dy, flag).
flag=0 for move, 1 for line continuation.
"""
paths, _ = svgstr2paths(svg_content)
tensor = torch.zeros((max_sequence_length, 3))
idx = 0
prev = None
for path in paths:
if idx >= max_sequence_length:
break
# Move
start = path[0].start
dx = start.real - (prev.real if prev else 0)
dy = start.imag - (prev.imag if prev else 0)
tensor[idx] = torch.tensor([dx, dy, 0.0])
prev = start
idx += 1
# Lines
for seg in path:
if idx >= max_sequence_length:
break
end = seg.end
dx = end.real - prev.real
dy = end.imag - prev.imag
tensor[idx] = torch.tensor([dx, dy, 1.0])
prev = end
idx += 1
return tensor
def tensor_to_svg_strokes(tensor: torch.Tensor, size=256, stroke_width=0.8) -> str:
"""
Reconstruct SVG from *stroke* tensor (dx, dy, flag).
"""
svg_parts = [f'<svg viewBox="0 0 {size} {size}"><g stroke-width="{stroke_width}">']
path_cmds = []
x, y = 0.0, 0.0 # start at origin
for i in range(tensor.shape[0]):
lst = tensor[i].tolist()
dx, dy, flag = lst[0], lst[1], lst[2]
if dx == 0.0 and dy == 0.0 and flag == 0.0:
continue
x += dx
y += dy
if flag == 0.0: # Move
if path_cmds:
path_str = " ".join(path_cmds)
svg_parts.append(f'<path d="{path_str}" stroke="black" fill="none"/>')
path_cmds = []
path_cmds.append(f"M {x} {y}")
else: # Line
path_cmds.append(f"L {x} {y}")
# Flush last path
if path_cmds:
path_str = " ".join(path_cmds)
svg_parts.append(f'<path d="{path_str}" stroke="black" fill="none"/>')
svg_parts.append("</g></svg>")
return "\n".join(svg_parts)
def svg_to_tensor_quantized(svg_content: str, bins=128, max_sequence_length: int = 200):
"""
Convert SVG path data to a quantized tensor representation.
"""
paths, _ = svgstr2paths(svg_content)
min_x, max_x, min_y, max_y = parse_viewbox(svg_content)
quantize_point = make_quantizer(min_x, max_x, min_y, max_y, bins)
tensor = torch.zeros((max_sequence_length, 3)) # (seq_len, 3)
idx = 0
for path in paths:
if idx >= max_sequence_length:
break
start_quantized = quantize_point(path[0].start)
tensor[idx, 0] = start_quantized.real
tensor[idx, 1] = start_quantized.imag
# tensor[idx, 2] = 0.0 # no-op, already zero for move
idx += 1
for segment in path:
if idx >= max_sequence_length:
break
end_quantized = quantize_point(segment.end)
tensor[idx, 0] = end_quantized.real
tensor[idx, 1] = end_quantized.imag
tensor[idx, 2] = 1.0 # Line command
idx += 1
return tensor
def svg_to_tensor(svg_content: str, max_sequence_length: int = 200):
"""
Convert SVG path data to a tensor of (x, y, flag),
where flag=0 for a move (start of path), 1 for a line continuation.
"""
paths, _ = svgstr2paths(svg_content)
tensor = torch.zeros((max_sequence_length, 3)) # (seq_len, 3)
idx = 0
for path in paths:
if idx >= max_sequence_length:
break
# Start point (move)
tensor[idx, 0] = path[0].start.real
tensor[idx, 1] = path[0].start.imag
# tensor[idx, 2] = 0.0 # no-op, already zero for move
idx += 1
# Segments
for seg in path:
if idx >= max_sequence_length:
break
tensor[idx, 0] = seg.end.real
tensor[idx, 1] = seg.end.imag
tensor[idx, 2] = 1.0
idx += 1
return tensor
def tensor_to_svg(tensor: torch.Tensor, size=256, stroke_width=0.8) -> str:
"""Convert a tensor representation of a sketch to an SVG string."""
svg_parts = [f'<svg viewBox="0 0 {size} {size}"><g stroke-width="{stroke_width}">']
path_cmds = []
for i in range(tensor.shape[0]):
x, y, flag = tensor[i].tolist()
# Skip unused rows (all zeros)
if x == 0.0 and y == 0.0 and flag == 0.0:
continue
if flag == 0.0:
if path_cmds:
path_str = " ".join(path_cmds)
svg_parts.append(f'<path d="{path_str}" stroke="black" fill="none"/>')
path_cmds = []
path_cmds.append(f"M {x} {y}")
else:
path_cmds.append(f"L {x} {y}")
# Flush last path
if path_cmds:
path_str = " ".join(path_cmds)
svg_parts.append(f'<path d="{path_str}" stroke="black" fill="none"/>')
svg_parts.append("</g></svg>")
return "\n".join(svg_parts)