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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import xml.etree.ElementTree as ET
|
2 |
+
import re
|
3 |
+
import numpy as np
|
4 |
+
from PIL import Image, ImageDraw, ImageFont
|
5 |
+
from io import BytesIO
|
6 |
+
import base64
|
7 |
+
|
8 |
+
|
9 |
+
# =========================
|
10 |
+
# ===== Grid related ======
|
11 |
+
# =========================
|
12 |
+
def create_grid_image(res=50, cell_size=12, header_size=12):
|
13 |
+
# Define the size of the grid
|
14 |
+
rows = res
|
15 |
+
cols = res
|
16 |
+
|
17 |
+
img_width = (cols + 1) * cell_size
|
18 |
+
img_height = (rows + 1) * cell_size
|
19 |
+
|
20 |
+
# Create a new image with a white background
|
21 |
+
img = Image.new('RGB', (img_width, img_height), 'white')
|
22 |
+
draw = ImageDraw.Draw(img)
|
23 |
+
|
24 |
+
# Load a font
|
25 |
+
try:
|
26 |
+
font = ImageFont.truetype("arial.ttf", header_size*0.85)
|
27 |
+
except IOError:
|
28 |
+
font = ImageFont.load_default()
|
29 |
+
|
30 |
+
# Draw the headers
|
31 |
+
for j in range(cols):
|
32 |
+
# Draw column header (letters)
|
33 |
+
text = str(j +1)
|
34 |
+
text_bbox = draw.textbbox((0, 0), text, font=font)
|
35 |
+
text_width = text_bbox[2] - text_bbox[0]
|
36 |
+
text_height = text_bbox[3] - text_bbox[1]
|
37 |
+
text_x = (j + 1) * cell_size + (cell_size - text_width) / 2
|
38 |
+
text_y = img_height - cell_size # - (cell_size - text_height) / 2
|
39 |
+
draw.text((text_x, text_y), text, fill="black", font=font)
|
40 |
+
|
41 |
+
for i in range(rows):
|
42 |
+
# Draw row header (numbers)
|
43 |
+
text = str(rows - i)
|
44 |
+
text_bbox = draw.textbbox((0, 0), text, font=font)
|
45 |
+
text_width = text_bbox[2] - text_bbox[0]
|
46 |
+
text_height = text_bbox[3] - text_bbox[1]
|
47 |
+
text_x = (cell_size - text_width) / 2
|
48 |
+
text_y = i * cell_size + (cell_size - text_height) / 2 - 0.2*text_height
|
49 |
+
draw.text((text_x, text_y), text, fill="black", font=font)
|
50 |
+
|
51 |
+
# Draw the grid
|
52 |
+
i = 1
|
53 |
+
draw.line([(i * cell_size, 0), (i * cell_size, img_height)], fill="black")
|
54 |
+
# Horizontal lines
|
55 |
+
draw.line([(0, img_height - cell_size), (img_width, img_height - cell_size)], fill="black")
|
56 |
+
|
57 |
+
positions={}
|
58 |
+
# Draw the grid
|
59 |
+
for i in range(rows)[::-1]:
|
60 |
+
for j in range(cols):
|
61 |
+
# Draw cell border
|
62 |
+
if j == 0:
|
63 |
+
draw.rectangle([(j + 0) * cell_size, (i + 0) * cell_size, (j + 1) * cell_size, (i + 1) * cell_size], outline="black")
|
64 |
+
if i == rows - 1:
|
65 |
+
draw.rectangle([(j + 0) * cell_size, (i + 1) * cell_size, (j + 1) * cell_size, (i + 2) * cell_size], outline="black")
|
66 |
+
|
67 |
+
# Calculate the position of the text
|
68 |
+
text = f"x{j + 1}y{i + 1}"
|
69 |
+
text_bbox = draw.textbbox((0, 0), text, font=font)
|
70 |
+
text_width = text_bbox[2] - text_bbox[0]
|
71 |
+
text_height = text_bbox[3] - text_bbox[1]
|
72 |
+
text_x = (j + 1) * cell_size + (cell_size - text_width) / 2
|
73 |
+
text_y = (i + 1) * cell_size + (cell_size - text_height) / 2
|
74 |
+
|
75 |
+
center_y = int(img_height - cell_size - (i * cell_size) - cell_size / 2)
|
76 |
+
center_x = int(j * cell_size + cell_size / 2 + cell_size)
|
77 |
+
positions[text] = (center_x, center_y)
|
78 |
+
return img, positions
|
79 |
+
|
80 |
+
|
81 |
+
def cells_to_pixels(res=50, cell_size=12, header_size=12):
|
82 |
+
# Define the size of the grid
|
83 |
+
rows = res
|
84 |
+
cols = res
|
85 |
+
|
86 |
+
img_width = (cols + 1) * cell_size
|
87 |
+
img_height = (rows + 1) * cell_size
|
88 |
+
|
89 |
+
positions={}
|
90 |
+
# Draw the grid
|
91 |
+
for i in range(rows)[::-1]:
|
92 |
+
for j in range(cols):
|
93 |
+
# Calculate the position of the text
|
94 |
+
text = f"x{j + 1}y{i + 1}"
|
95 |
+
|
96 |
+
center_y = int(img_height - cell_size - (i * cell_size) - cell_size / 2)
|
97 |
+
center_x = int(j * cell_size + cell_size / 2 + cell_size)
|
98 |
+
positions[text] = (center_x, center_y)
|
99 |
+
|
100 |
+
return positions
|
101 |
+
|
102 |
+
|
103 |
+
# =========================
|
104 |
+
# ===== LLM related =======
|
105 |
+
# =========================
|
106 |
+
def image_to_str(image: Image):
|
107 |
+
buffer = BytesIO()
|
108 |
+
image.save(buffer, format="JPEG")
|
109 |
+
buffer.seek(0)
|
110 |
+
image = base64.b64encode(buffer.read()).decode('utf-8')
|
111 |
+
return image
|
112 |
+
|
113 |
+
|
114 |
+
|
115 |
+
# =================================
|
116 |
+
# ===== SVG process related =======
|
117 |
+
# =================================
|
118 |
+
def bezier_point(P, t):
|
119 |
+
"""Calculate a point on the Bézier curve for a given t."""
|
120 |
+
return (1-t)**3 * P[0] + 3*(1-t)**2 * t * P[1] + 3*(1-t) * t**2 * P[2] + t**3 * P[3]
|
121 |
+
|
122 |
+
|
123 |
+
def estimate_bezier_control_points_helper(sampled_points, t_values):
|
124 |
+
n = len(sampled_points)
|
125 |
+
|
126 |
+
if n == 1:
|
127 |
+
# Linear interpolation: the control points are simply the two points
|
128 |
+
P0 = np.array(sampled_points[0])
|
129 |
+
P1 = np.array(sampled_points[0]).astype(np.float64) + 0.0001
|
130 |
+
return np.array([P0, P1])
|
131 |
+
|
132 |
+
if n == 2:
|
133 |
+
# Linear interpolation: the control points are simply the two points
|
134 |
+
P0 = np.array(sampled_points[0])
|
135 |
+
P1 = np.array(sampled_points[1])
|
136 |
+
return np.array([P0, P1])
|
137 |
+
|
138 |
+
if n > len(t_values):
|
139 |
+
t_values = np.linespace(0,1,n)
|
140 |
+
|
141 |
+
elif n == 3:
|
142 |
+
# Quadratic Bézier curve: we need to solve for three control points
|
143 |
+
A = np.zeros((n, 3))
|
144 |
+
for i in range(n):
|
145 |
+
t = t_values[i]
|
146 |
+
A[i, 0] = (1-t)**2
|
147 |
+
A[i, 1] = 2*(1-t)*t
|
148 |
+
A[i, 2] = t**2
|
149 |
+
|
150 |
+
# Points (flattened)
|
151 |
+
B = np.array(sampled_points).reshape(-1, 2) # Assuming 2D points
|
152 |
+
|
153 |
+
# Solve the system (least squares)
|
154 |
+
P = np.linalg.lstsq(A, B, rcond=None)[0]
|
155 |
+
return P
|
156 |
+
|
157 |
+
# Matrix A
|
158 |
+
A = np.zeros((n, 4))
|
159 |
+
for i in range(n):
|
160 |
+
t = t_values[i]
|
161 |
+
A[i, 0] = (1-t)**3
|
162 |
+
A[i, 1] = 3*(1-t)**2 * t
|
163 |
+
A[i, 2] = 3*(1-t) * t**2
|
164 |
+
A[i, 3] = t**3
|
165 |
+
|
166 |
+
# Points (flattened)
|
167 |
+
B = np.array(sampled_points).reshape(-1, 2) # Assuming 2D points
|
168 |
+
|
169 |
+
# Solve the system (least squares)
|
170 |
+
P = np.linalg.lstsq(A, B, rcond=None)[0]
|
171 |
+
return P
|
172 |
+
|
173 |
+
|
174 |
+
def estimate_bezier_control_points( sampled_points, t_values):
|
175 |
+
if len(sampled_points) != len(t_values):
|
176 |
+
t_values = np.linspace(0,1, len(sampled_points))
|
177 |
+
P = estimate_bezier_control_points_helper(sampled_points, t_values)
|
178 |
+
|
179 |
+
if len(sampled_points) > 4:
|
180 |
+
# Calculate the mean squared error between sampled points and the fitted Bézier curve.
|
181 |
+
errors = []
|
182 |
+
for i, t in enumerate(t_values):
|
183 |
+
B_t = bezier_point(P, t)
|
184 |
+
error = np.linalg.norm(B_t - sampled_points[i])
|
185 |
+
errors.append(error)
|
186 |
+
error = np.mean(errors)
|
187 |
+
|
188 |
+
if error > 5 and len(sampled_points) >= 7:
|
189 |
+
mid = len(sampled_points) // 2
|
190 |
+
left_sampled_points = sampled_points[:mid+1]
|
191 |
+
right_sampled_points = sampled_points[mid:]
|
192 |
+
left_t_values = np.array(t_values[:mid+1])
|
193 |
+
right_t_values = np.array(t_values[mid:])
|
194 |
+
|
195 |
+
if len(left_sampled_points) == 3: # this applies in case we have 7 points
|
196 |
+
left_sampled_points.append(right_sampled_points[0])
|
197 |
+
left_t_values.append(right_t_values[0])
|
198 |
+
|
199 |
+
# Normalize t_values for each segment
|
200 |
+
left_t_values = (left_t_values - left_t_values[0]) / (left_t_values[-1] - left_t_values[0])
|
201 |
+
right_t_values = (right_t_values - right_t_values[0]) / (right_t_values[-1] - right_t_values[0])
|
202 |
+
|
203 |
+
# Recursively fit curves to each segment
|
204 |
+
P_left = estimate_bezier_control_points_helper(left_sampled_points, left_t_values)
|
205 |
+
P_right = estimate_bezier_control_points_helper(right_sampled_points, right_t_values)
|
206 |
+
P_right[0] = P_left[-1] # I added this to have the long strokes look more connected
|
207 |
+
return [P_left, P_right]
|
208 |
+
return [P]
|
209 |
+
|
210 |
+
|
211 |
+
def get_control_points(strokes_all, t_values_all, cells_to_pixels_map):
|
212 |
+
net_points = []
|
213 |
+
for j in range(len(strokes_all)):
|
214 |
+
sampled_cells = strokes_all[j]
|
215 |
+
t_values = t_values_all[j]
|
216 |
+
sampled_points = []
|
217 |
+
for cell in sampled_cells:
|
218 |
+
y,x = cells_to_pixels_map[cell]
|
219 |
+
sampled_points.append([y,x])
|
220 |
+
points_lst = estimate_bezier_control_points(sampled_points, t_values)
|
221 |
+
net_points.append(points_lst)
|
222 |
+
return net_points
|
223 |
+
|
224 |
+
|
225 |
+
def get_control_points_single_stroke(strokes_all, t_values_all, cells_to_pixels_map):
|
226 |
+
sampled_points = []
|
227 |
+
for cell in strokes_all:
|
228 |
+
y,x = cells_to_pixels_map[cell]
|
229 |
+
sampled_points.append([y,x])
|
230 |
+
points_lst = estimate_bezier_control_points(sampled_points, t_values_all)
|
231 |
+
return points_lst
|
232 |
+
|
233 |
+
|
234 |
+
def create_svg_path_data(control_points):
|
235 |
+
# Start the path with 'M' for the first point
|
236 |
+
# print("control_points", control_points[0])
|
237 |
+
path_data = 'M ' + np.array2string(np.array(control_points[0]), formatter={'float_kind':lambda x: "%.2f" % x}, separator=' ')[1:-1]
|
238 |
+
# Add 'L' for each subsequent point
|
239 |
+
|
240 |
+
# check if point
|
241 |
+
if len(control_points) == 1:
|
242 |
+
path_data += ' '
|
243 |
+
# check if line
|
244 |
+
elif len(control_points) == 2:
|
245 |
+
path_data += ' L '
|
246 |
+
# check if quadratic
|
247 |
+
elif len(control_points) == 3:
|
248 |
+
path_data += ' Q '
|
249 |
+
# check if cubic
|
250 |
+
elif len(control_points) == 4:
|
251 |
+
path_data += ' C '
|
252 |
+
|
253 |
+
# path_data += ' C '
|
254 |
+
for point in control_points[1:]:
|
255 |
+
# print("pt", point[0], point[1])
|
256 |
+
path_data += str(point[0]) + " " + str(point[1]) + " "
|
257 |
+
|
258 |
+
# Return the complete 'd' attribute string
|
259 |
+
return path_data
|
260 |
+
|
261 |
+
|
262 |
+
def format_svg(all_control_points, dim, stroke_width):
|
263 |
+
svg_width, svg_height = dim
|
264 |
+
sketch_text_svg = f"""<svg width="{svg_width}" height="{svg_height}" xmlns="http://www.w3.org/2000/svg">\n"""
|
265 |
+
for i, path in enumerate(all_control_points):
|
266 |
+
gropu_text = f"""<g id="s{i + 1}" stroke="black" stroke-width="{stroke_width}" fill="none" stroke-linecap="round">\n"""
|
267 |
+
for sub_path_cp in path: #sometimes 1 or 2
|
268 |
+
path_data = create_svg_path_data(sub_path_cp)
|
269 |
+
gropu_text += f"""<path d="{path_data}"/>\n"""
|
270 |
+
gropu_text += "</g>\n"
|
271 |
+
sketch_text_svg += gropu_text
|
272 |
+
sketch_text_svg += "</svg>"
|
273 |
+
return sketch_text_svg
|
274 |
+
|
275 |
+
|
276 |
+
def format_svg_single_stroke(group, dim, stroke_width, stroke_counter, stroke_color="black"):
|
277 |
+
sketch_text_svg = ""
|
278 |
+
gropu_text = f"""<g id="s{stroke_counter}" stroke="{stroke_color}" stroke-width="{stroke_width}" fill="none" stroke-linecap="round">\n"""
|
279 |
+
for sub_path_cp in group:
|
280 |
+
path_data = create_svg_path_data(sub_path_cp)
|
281 |
+
gropu_text += f"""<path d="{path_data}"/>\n"""
|
282 |
+
gropu_text += "</g>\n"
|
283 |
+
sketch_text_svg += gropu_text
|
284 |
+
return sketch_text_svg
|
285 |
+
|
286 |
+
|
287 |
+
# Note that this parse only the *first* part in the text in which you have the <strokes> </strokes> tags.
|
288 |
+
def parse_xml_string(llm_output, res):
|
289 |
+
|
290 |
+
strokes_start_marker = "<strokes>"
|
291 |
+
strokes_end_marker = "</strokes>"
|
292 |
+
|
293 |
+
# Find the start and end indices of the JSON string
|
294 |
+
start_index = llm_output.find(strokes_start_marker)
|
295 |
+
if start_index != -1:
|
296 |
+
# start_index += len(strokes_start_marker) # Move past the marker
|
297 |
+
end_index = llm_output.find(strokes_end_marker, start_index)
|
298 |
+
else:
|
299 |
+
return None # XML markers not found
|
300 |
+
|
301 |
+
if end_index == -1:
|
302 |
+
return None # End marker not found
|
303 |
+
|
304 |
+
# Extract the JSON string
|
305 |
+
strokes_str = llm_output[start_index:end_index + len(strokes_end_marker)].strip()#[:-1]
|
306 |
+
xml_str = f"<wrap>{strokes_str}</wrap>"
|
307 |
+
# Parse the XML string
|
308 |
+
root = ET.fromstring(xml_str)
|
309 |
+
|
310 |
+
# Initialize lists to hold strokes and t_values
|
311 |
+
strokes_list = "[\n"
|
312 |
+
t_values_list = "[\n"
|
313 |
+
|
314 |
+
# Iterate over all the strokes
|
315 |
+
for stroke in root.find('strokes'):
|
316 |
+
# Extract points and clean them up
|
317 |
+
points_text = stroke.find('points').text
|
318 |
+
|
319 |
+
# Extract t_values and convert them to float
|
320 |
+
t_values_text = stroke.find('t_values').text
|
321 |
+
|
322 |
+
# Append to the lists
|
323 |
+
strokes_list += f"[{points_text}],\n"
|
324 |
+
t_values_list += f"[{t_values_text}],\n"
|
325 |
+
|
326 |
+
strokes_list = re.sub(r'\d+', lambda x: str(min(int(x.group()), res)), strokes_list)
|
327 |
+
strokes_list = re.sub(r'\d+', lambda x: str(max(int(x.group()), 1)), strokes_list)
|
328 |
+
|
329 |
+
strokes_list += "]"
|
330 |
+
t_values_list += "]"
|
331 |
+
return strokes_list, t_values_list
|
332 |
+
|
333 |
+
|
334 |
+
def parse_xml_string_single_stroke(llm_output, res, stroke_counter):
|
335 |
+
strokes_start_marker = f"<s{stroke_counter}>"
|
336 |
+
strokes_end_marker = f"</s{stroke_counter}>"
|
337 |
+
|
338 |
+
# Find the start and end indices of the JSON string
|
339 |
+
start_index = llm_output.find(strokes_start_marker)
|
340 |
+
if start_index != -1:
|
341 |
+
# start_index += len(strokes_start_marker) # Move past the marker
|
342 |
+
end_index = llm_output.find(strokes_end_marker, start_index)
|
343 |
+
else:
|
344 |
+
return None # XML markers not found
|
345 |
+
|
346 |
+
if end_index == -1:
|
347 |
+
return None # End marker not found
|
348 |
+
|
349 |
+
# Extract the JSON string
|
350 |
+
strokes_str = llm_output[start_index:end_index + len(strokes_end_marker)].strip()#[:-1]
|
351 |
+
xml_str = f"<wrap>{strokes_str}</wrap>"
|
352 |
+
# Parse the XML string
|
353 |
+
root = ET.fromstring(xml_str)
|
354 |
+
|
355 |
+
# Iterate over all the strokes
|
356 |
+
stroke = root.find(f"s{stroke_counter}")
|
357 |
+
points_text = stroke.find('points').text
|
358 |
+
|
359 |
+
# Extract t_values and convert them to float
|
360 |
+
t_values_text = stroke.find('t_values').text
|
361 |
+
|
362 |
+
# Append to the lists
|
363 |
+
strokes_list = f"[{points_text}]"
|
364 |
+
t_values_list = f"[{t_values_text}]"
|
365 |
+
|
366 |
+
strokes_list = re.sub(r'\d+', lambda x: str(min(int(x.group()), res)), strokes_list)
|
367 |
+
strokes_list = re.sub(r'\d+', lambda x: str(max(int(x.group()), 1)), strokes_list)
|
368 |
+
|
369 |
+
return strokes_list, t_values_list
|
370 |
+
|
371 |
+
|
372 |
+
# =====================================
|
373 |
+
# ===== Collaborative Sketching =======
|
374 |
+
# =====================================
|
375 |
+
def get_cur_stroke_text(stroke_counter, llm_output):
|
376 |
+
start_marker = f"<s{stroke_counter}>"
|
377 |
+
end_marker = f"</s{stroke_counter}>"
|
378 |
+
|
379 |
+
# Find the start and end indices of the JSON string
|
380 |
+
start_index = llm_output.find(start_marker)
|
381 |
+
if start_index != -1:
|
382 |
+
# start_index += len(strokes_start_marker) # Move past the marker
|
383 |
+
end_index = llm_output.find(end_marker, start_index)
|
384 |
+
else:
|
385 |
+
return "" # XML markers not found
|
386 |
+
|
387 |
+
if end_index == -1:
|
388 |
+
return "" # End marker not found
|
389 |
+
|
390 |
+
# Extract the JSON string
|
391 |
+
strokes_str = llm_output[start_index:end_index + len(end_marker)].strip()#[:-1]
|
392 |
+
return strokes_str
|