sketchkit 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of sketchkit might be problematic. Click here for more details.

@@ -0,0 +1,403 @@
1
+ import os
2
+ import shutil
3
+
4
+ import glob
5
+ import numpy as np
6
+ import gdown
7
+
8
+ import xml.etree.ElementTree as ET
9
+ import pandas as pd
10
+ from pathlib import Path as PathLibPath
11
+
12
+ from svg.path import parse_path, path
13
+ from sketchkit.utils.dataset import SketchDataset
14
+ from sketchkit.core.sketch import Sketch, Path, Curve, Vertex, Point
15
+ from sketchkit.utils.transform import line_to_cubic
16
+ from sketchkit.utils.file import extract_files, download_with_wget, dir_md5, CISLAB_CDN
17
+
18
+
19
+ _INVALID = {"rect", "circle", "ellipse", "line", "polyline", "polygon"}
20
+
21
+
22
+ def parse_svg(svg_path: str) -> list[Path]:
23
+ """Parse an SVG file into a list of Path objects.
24
+
25
+ Args:
26
+ svg_path (str): Path to the SVG file to parse.
27
+
28
+ Returns:
29
+ list[Path]: Parsed sketch represented as a list of Path objects.
30
+
31
+ Raises:
32
+ AssertionError: If a transform attribute is encountered.
33
+ Exception: If an arc segment is encountered.
34
+ """
35
+ tree = ET.parse(svg_path)
36
+ root = tree.getroot()
37
+
38
+ paths: list[Path] = []
39
+
40
+ for elem in root.iter():
41
+ tag = elem.tag.split("}", 1)[-1]
42
+ if tag in _INVALID:
43
+ continue
44
+ if tag != "path":
45
+ continue
46
+
47
+ if "transform" in elem.attrib:
48
+ raise AssertionError("Transform not supported")
49
+
50
+ d = elem.attrib.get("d", "")
51
+ if not d:
52
+ continue
53
+
54
+ cps: list[tuple[float, float]] = []
55
+ ps = parse_path(d)
56
+ for seg in ps:
57
+ t = type(seg)
58
+
59
+ if t == path.Move:
60
+ cps.append((seg.start.real, seg.start.imag))
61
+
62
+ elif t == path.CubicBezier:
63
+ if not cps:
64
+ s = seg.start
65
+ cps.append((s.real, s.imag))
66
+ c1, c2, e = seg.control1, seg.control2, seg.end
67
+ cps.extend([(c1.real, c1.imag), (c2.real, c2.imag), (e.real, e.imag)])
68
+
69
+ elif t == path.Line:
70
+ if not cps:
71
+ s = seg.start
72
+ cps.append((s.real, s.imag))
73
+ s, e = seg.start, seg.end
74
+ p0 = (s.real, s.imag)
75
+ p1 = (e.real, e.imag)
76
+ cubic = line_to_cubic(np.stack([p0, p1], axis=0))
77
+ cps.extend(
78
+ [
79
+ (cubic[1, 0], cubic[1, 1]),
80
+ (cubic[2, 0], cubic[2, 1]),
81
+ (cubic[3, 0], cubic[3, 1]),
82
+ ]
83
+ )
84
+
85
+ elif t == path.Arc:
86
+ raise Exception("Arc not supported")
87
+
88
+ if len(cps) > 1 and (len(cps) - 1) % 3 == 0:
89
+ n = (len(cps) - 1) // 3
90
+ curves: List[Curve] = []
91
+ for i in range(n):
92
+ p0 = cps[i * 3 + 0]
93
+ c1 = cps[i * 3 + 1]
94
+ c2 = cps[i * 3 + 2]
95
+ p3 = cps[i * 3 + 3]
96
+ curves.append(
97
+ Curve(
98
+ Vertex(float(p0[0]), float(p0[1])),
99
+ Vertex(float(p3[0]), float(p3[1])),
100
+ Point(float(c1[0]), float(c1[1])),
101
+ Point(float(c2[0]), float(c2[1])),
102
+ )
103
+ )
104
+ if curves:
105
+ paths.append(Path(curves=curves))
106
+
107
+ return paths
108
+
109
+
110
+ class ControlSketch(SketchDataset):
111
+ """ControlSketch dataset loader (SketchDataset-style).
112
+
113
+ Directory structure (after download & extract):
114
+ controlsketch_sketches/
115
+ ├── train/<category>/*.svg
116
+ ├── validation/<category>/*.svg
117
+ └── test/<category>/*.svg
118
+
119
+ References:
120
+ - Original dataset: https://swiftsketch.github.io/#controlsketch-data
121
+ - Paper: "SwiftSketch: A Diffusion Model for Image-to-Vector Sketch Generation" by E Arar, 2025
122
+ """
123
+
124
+ md5_sum = "c45dad0c08988df3d4036e85e5363e8a"
125
+ metadata = ["id", "sub_id", "category", "split", "filepath"]
126
+
127
+ def __init__(
128
+ self,
129
+ root: str | PathLibPath | None = None,
130
+ load_all: bool = False,
131
+ cislab_source: bool = False,
132
+ ):
133
+ """Initialize the ControlSketch dataset.
134
+
135
+ Args:
136
+ root (str | PathLibPath | None): Root directory to store/load the dataset.
137
+ If None, uses the default dataset directory.
138
+ load_all (bool): If True, loads all data into memory for faster access.
139
+ If False, loads data on-demand. Defaults to False.
140
+ cislab_source (bool): If True, downloads from CISLAB CDN mirror.
141
+ If False, downloads from original Google storage. Defaults to False.
142
+ """
143
+
144
+ super().__init__(root, load_all=load_all, cislab_source=cislab_source)
145
+
146
+ def _check_integrity(self) -> bool:
147
+ """Check the integrity of the cached dataset using MD5 checksum.
148
+
149
+ Returns:
150
+ bool: True if the dataset integrity is verified, False otherwise.
151
+ """
152
+
153
+ print(f"Checking integrity of cached {self.__class__.__name__} dataset...")
154
+ ds_root = os.path.join(self.root, "controlsketch_sketches")
155
+ if not os.path.isdir(ds_root):
156
+ return False
157
+ if getattr(self, "md5_sum", None) in (None, "", 0):
158
+ return True
159
+ return dir_md5(ds_root) == self.md5_sum
160
+
161
+ def _download(self):
162
+ """Download and extract the ControlSketch dataset.
163
+
164
+ Downloads the dataset archive from CISLAB CDN or Google Drive,
165
+ extracts it into the dataset root, and removes the source file if successful.
166
+ """
167
+ if os.path.exists(self.root):
168
+ shutil.rmtree(self.root)
169
+ os.makedirs(self.root, exist_ok=True)
170
+
171
+ zip_name = "controlsketch_sketches.zip"
172
+ zip_path = os.path.join(self.root, zip_name)
173
+
174
+ if self.cislab_source:
175
+ try:
176
+ url = f"{CISLAB_CDN}/datasets/{self.__class__.__name__}/{zip_name}"
177
+ print(f"Downloading ControlSketch from CISLAB CDN: {url}")
178
+ download_with_wget(url, file_path=zip_path, pg_bar=True)
179
+ except Exception:
180
+ print(
181
+ "CISLAB mirror unavailable. Falling back to Google Drive (gdown)."
182
+ )
183
+ file_id = "1-kffChm6RXwTuP8qxUOT-QDf8-bSCH0w"
184
+ if not os.path.exists(zip_path):
185
+ print("Downloading ControlSketch from Google Drive…")
186
+ gdown.download(id=file_id, output=zip_path, quiet=False)
187
+ print("Download finished.")
188
+ else:
189
+ file_id = "1-kffChm6RXwTuP8qxUOT-QDf8-bSCH0w"
190
+ if not os.path.exists(zip_path):
191
+ print("Downloading ControlSketch from Google Drive…")
192
+ gdown.download(id=file_id, output=zip_path, quiet=False)
193
+ print("Download finished.")
194
+
195
+ try:
196
+ print("Extracting ControlSketch…")
197
+ extract_files(zip_path, self.root, remove_sourcefile=True)
198
+ print("Extraction finished.")
199
+ except Exception as e:
200
+ raise e
201
+
202
+ print("MD5 Checksum:", dir_md5(self.root))
203
+
204
+ def _load_items_metadata(self):
205
+ """Build metadata index for dataset items.
206
+
207
+ Scans the extracted dataset directory for train/validation/test splits,
208
+ collects all SVG files with their category and split, and saves results
209
+ into a cached Parquet file.
210
+
211
+ Raises:
212
+ FileNotFoundError: If the dataset directory is not found.
213
+ """
214
+ ds_root = os.path.join(self.root, "controlsketch_sketches")
215
+ if not os.path.isdir(ds_root):
216
+ raise FileNotFoundError(f"Not found dataset root: {ds_root}")
217
+
218
+ meta_cache = os.path.join(self.root, ".metadata.parquet")
219
+
220
+ if os.path.exists(meta_cache):
221
+ try:
222
+ items = pd.read_parquet(meta_cache)
223
+ if set(items.columns.tolist()) == set(self.metadata):
224
+ self.items_metadata = items
225
+ self.raw_data = [None] * len(self.items_metadata)
226
+ return
227
+ except Exception:
228
+ pass
229
+ try:
230
+ os.remove(meta_cache)
231
+ except Exception:
232
+ pass
233
+
234
+ splits = ["train", "validation", "test"]
235
+ rows = []
236
+ gid = 0
237
+
238
+ for sp in splits:
239
+ sp_dir = os.path.join(ds_root, sp)
240
+ if not os.path.isdir(sp_dir):
241
+ continue
242
+
243
+ cats = [
244
+ d for d in os.listdir(sp_dir) if os.path.isdir(os.path.join(sp_dir, d))
245
+ ]
246
+ for cat in sorted(cats):
247
+ cdir = os.path.join(sp_dir, cat)
248
+ svgs = sorted(glob.glob(os.path.join(cdir, "*.svg")))
249
+ for sub_id, fp in enumerate(svgs):
250
+ row = {
251
+ "id": gid,
252
+ "sub_id": sub_id,
253
+ "category": cat,
254
+ "split": sp,
255
+ }
256
+ if "filepath" in self.metadata:
257
+ row["filepath"] = fp
258
+ rows.append(row)
259
+ gid += 1
260
+
261
+ self.items_metadata = pd.DataFrame(rows, columns=self.metadata)
262
+
263
+ try:
264
+ self.items_metadata.to_parquet(meta_cache, compression="zstd")
265
+ except Exception:
266
+ self.items_metadata.to_parquet(meta_cache)
267
+
268
+ self.raw_data = [None] * len(self.items_metadata)
269
+
270
+ def _load_all(self):
271
+ """Load all sketch data into memory if load_all is enabled.
272
+
273
+ Concatenates all sketch data from all categories and splits into a single
274
+ numpy array for faster access. Only loads if self.load_all is True.
275
+ """
276
+ for idx in range(len(self.items_metadata)):
277
+ fp = self.items_metadata.iloc[idx]["filepath"]
278
+ self.raw_data[idx] = parse_svg(fp)
279
+
280
+ def __getitem__(self, idx: int) -> Sketch:
281
+ """Get one sketch by index.
282
+
283
+ Args:
284
+ idx (int): Global index of the sketch.
285
+
286
+ Returns:
287
+ Sketch: A Sketch object containing parsed paths.
288
+
289
+ Raises:
290
+ IndexError: If the index is out of range.
291
+ """
292
+ if idx < 0 or idx >= len(self):
293
+ raise IndexError("Index out of range")
294
+
295
+ if self.raw_data[idx] is None:
296
+ fp = self.items_metadata.iloc[idx]["filepath"]
297
+ self.raw_data[idx] = parse_svg(fp)
298
+
299
+ paths = self.raw_data[idx]
300
+ return Sketch(paths=paths)
301
+
302
+ def extra_repr(self) -> str:
303
+ """Return dataset summary.
304
+
305
+ Returns:
306
+ str: A string with number of categories and sample counts
307
+ for train/validation/test splits.
308
+ """
309
+ df = self.items_metadata
310
+
311
+ def _n(sp):
312
+ return int((df["split"] == sp).sum()) if isinstance(df, pd.DataFrame) else 0
313
+
314
+ num_train = _n("train")
315
+ num_val = _n("validation")
316
+ num_test = _n("test")
317
+
318
+ n_cat = df["category"].nunique() if len(df) else 0
319
+ return f"Categories: {n_cat}\nTrain: {num_train} Validation: {num_val} Test samples: {num_test}"
320
+
321
+
322
+ if __name__ == "__main__":
323
+ import psutil
324
+ from rich.console import Console
325
+ import time
326
+
327
+ console = Console()
328
+
329
+ console.print("ControlSketch Dataset Test", style="bold blue")
330
+ console.print()
331
+
332
+ # console.print("1. Default Load", style="green")
333
+ # dataset = ControlSketch()
334
+ # # show brief information of the dataset
335
+ # console.print(dataset)
336
+ # process = psutil.Process()
337
+ # memory_mb = process.memory_info().rss / 1024 / 1024
338
+ # console.print(f"Current memory usage: {memory_mb:.2f} MB")
339
+
340
+ # # search data with "category = cat" and "split = train"
341
+ # cats = dataset.items_metadata[
342
+ # (dataset.items_metadata["category"] == "cat")
343
+ # & (dataset.items_metadata["split"] == "train")
344
+ # ]
345
+ # start_time = time.time()
346
+ # cats_sketch = [dataset[row.id] for _, row in cats[:100].iterrows()]
347
+ # console.print(f"Loading 100 sketches in {time.time() - start_time}")
348
+ # del dataset, cats
349
+
350
+ # console.print()
351
+
352
+ # console.print("2. Load All", style="green")
353
+ # dataset = ControlSketch(load_all=True)
354
+ # # show brief information of the dataset
355
+ # console.print(dataset)
356
+ # process = psutil.Process()
357
+ # memory_mb = process.memory_info().rss / 1024 / 1024
358
+ # console.print(f"Current memory usage: {memory_mb:.2f} MB")
359
+ # # search data with "category = cow" and "split = test"
360
+ # cows = dataset.items_metadata[
361
+ # (dataset.items_metadata["category"] == "cow")
362
+ # & (dataset.items_metadata["split"] == "test")
363
+ # ]
364
+ # start_time = time.time()
365
+ # cow_sketch = [dataset[row.id] for _, row in cows[:100].iterrows()]
366
+ # console.print(f"Loading 100 sketches in {time.time() - start_time}")
367
+ # del dataset, cows
368
+
369
+ # console.print()
370
+
371
+ console.print("3. Load from CISLAB CDN", style="green")
372
+
373
+ # tempfile can create a temporary directory
374
+ import tempfile
375
+
376
+ with tempfile.TemporaryDirectory() as tmpdir:
377
+ dataset = ControlSketch(root=tmpdir, cislab_source=True)
378
+ # show brief information of the dataset
379
+ console.print(dataset)
380
+ process = psutil.Process()
381
+ memory_mb = process.memory_info().rss / 1024 / 1024
382
+ console.print(f"Current memory usage: {memory_mb:.2f} MB")
383
+ bears = dataset.items_metadata[
384
+ (dataset.items_metadata["category"] == "bear")
385
+ & (dataset.items_metadata["split"] == "validation")
386
+ ]
387
+ start_time = time.time()
388
+ bears_sketch = [dataset[row.id] for _, row in bears[:100].iterrows()]
389
+ console.print(f"Loading 100 sketches in {time.time() - start_time}")
390
+ del dataset, bears
391
+
392
+ console.print()
393
+
394
+ from PIL import Image
395
+ from sketchkit.renderer.cairo_renderer import CairoRenderer
396
+
397
+ renderer = CairoRenderer(256, (1, 1, 1))
398
+ raster_image = renderer.render(bears_sketch[0])
399
+ outpath = "test.png"
400
+ if outpath is not None:
401
+ raster_image_png = Image.fromarray(raster_image, "RGB")
402
+ raster_image_png.save(outpath, "PNG")
403
+