svg-ultralight 0.32.2__py3-none-any.whl → 0.34.0__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 svg-ultralight might be problematic. Click here for more details.

@@ -8,6 +8,10 @@ from svg_ultralight.bounding_boxes.bound_helpers import (
8
8
  new_bbox_union,
9
9
  new_bound_union,
10
10
  new_element_union,
11
+ cut_bbox,
12
+ pad_bbox,
13
+ bbox_dict,
14
+ new_bbox_rect,
11
15
  )
12
16
  from svg_ultralight.bounding_boxes.supports_bounds import SupportsBounds
13
17
  from svg_ultralight.bounding_boxes.type_bound_collection import BoundCollection
@@ -20,7 +24,6 @@ from svg_ultralight.constructors.new_element import (
20
24
  new_sub_element,
21
25
  update_element,
22
26
  )
23
- from svg_ultralight.import_svg import import_svg
24
27
  from svg_ultralight.inkscape import (
25
28
  write_pdf,
26
29
  write_pdf_from_svg,
@@ -31,7 +34,12 @@ from svg_ultralight.inkscape import (
31
34
  from svg_ultralight.main import new_svg_root, write_svg
32
35
  from svg_ultralight.metadata import new_metadata
33
36
  from svg_ultralight.nsmap import NSMAP, new_qname
34
- from svg_ultralight.query import pad_text
37
+ from svg_ultralight.query import (
38
+ get_bounding_box,
39
+ get_bounding_boxes,
40
+ pad_text,
41
+ clear_svg_ultralight_cache,
42
+ )
35
43
  from svg_ultralight.root_elements import new_svg_root_around_bounds
36
44
  from svg_ultralight.string_conversion import (
37
45
  format_attr_dict,
@@ -53,15 +61,20 @@ __all__ = [
53
61
  "NSMAP",
54
62
  "PaddedText",
55
63
  "SupportsBounds",
64
+ "bbox_dict",
65
+ "clear_svg_ultralight_cache",
66
+ "cut_bbox",
56
67
  "deepcopy_element",
57
68
  "format_attr_dict",
58
69
  "format_number",
59
70
  "format_numbers",
60
71
  "format_numbers_in_string",
61
- "import_svg",
72
+ "get_bounding_box",
73
+ "get_bounding_boxes",
62
74
  "mat_apply",
63
75
  "mat_dot",
64
76
  "mat_invert",
77
+ "new_bbox_rect",
65
78
  "new_bbox_union",
66
79
  "new_bound_union",
67
80
  "new_element",
@@ -71,6 +84,7 @@ __all__ = [
71
84
  "new_sub_element",
72
85
  "new_svg_root",
73
86
  "new_svg_root_around_bounds",
87
+ "pad_bbox",
74
88
  "pad_text",
75
89
  "transform_element",
76
90
  "update_element",
svg_ultralight/animate.py CHANGED
@@ -34,7 +34,7 @@ def write_gif(
34
34
  :param loop: how many times to loop gif. 0 -> forever
35
35
  :effects: write file to gif
36
36
  """
37
- images = [Image.open(x) for x in pngs] # type: ignore
38
- images[0].save( # type: ignore
37
+ images = [Image.open(x) for x in pngs]
38
+ images[0].save(
39
39
  gif, save_all=True, append_images=images[1:], duration=duration, loop=loop
40
40
  )
@@ -95,3 +95,77 @@ def new_bound_union(*blems: SupportsBounds | EtreeElement) -> BoundElement:
95
95
  group = new_element_union(*blems)
96
96
  bbox = new_bbox_union(*blems)
97
97
  return BoundElement(group, bbox)
98
+
99
+
100
+ def _expand_pad(pad: float | tuple[float, ...]) -> tuple[float, float, float, float]:
101
+ """Expand a float pad argument into a 4-tuple."""
102
+ if isinstance(pad, (int, float)):
103
+ return pad, pad, pad, pad
104
+ if len(pad) == 1:
105
+ return pad[0], pad[0], pad[0], pad[0]
106
+ if len(pad) == 2:
107
+ return pad[0], pad[1], pad[0], pad[1]
108
+ if len(pad) == 3:
109
+ return pad[0], pad[1], pad[2], pad[1]
110
+ return pad[0], pad[1], pad[2], pad[3]
111
+
112
+
113
+ def cut_bbox(
114
+ bbox: SupportsBounds,
115
+ *,
116
+ x: float | None = None,
117
+ y: float | None = None,
118
+ x2: float | None = None,
119
+ y2: float | None = None,
120
+ ) -> BoundingBox:
121
+ """Return a new bounding box with updated limits.
122
+
123
+ :param bbox: the original bounding box or bounded element.
124
+ :param x: the new x-coordinate.
125
+ :param y: the new y-coordinate.
126
+ :param x2: the new x2-coordinate.
127
+ :param y2: the new y2-coordinate.
128
+ :return: a new bounding box with the updated limits.
129
+ """
130
+ x = bbox.x if x is None else x
131
+ y = bbox.y if y is None else y
132
+ x2 = bbox.x2 if x2 is None else x2
133
+ y2 = bbox.y2 if y2 is None else y2
134
+ width = x2 - x
135
+ height = y2 - y
136
+ return BoundingBox(x, y, width, height)
137
+
138
+
139
+ def pad_bbox(bbox: SupportsBounds, pad: float | tuple[float, ...]) -> BoundingBox:
140
+ """Return a new bounding box with padding.
141
+
142
+ :param bbox: the original bounding box or bounded element.
143
+ :param pad: the padding to apply.
144
+ If a single number, the same padding will be applied to all sides.
145
+ If a tuple, will be applied per css rules.
146
+ len = 1 : 0, 0, 0, 0
147
+ len = 2 : 0, 1, 0, 1
148
+ len = 3 : 0, 1, 2, 1
149
+ len = 4 : 0, 1, 2, 3
150
+ :return: a new bounding box with padding applied.
151
+ """
152
+ t, r, b, l = _expand_pad(pad)
153
+ return cut_bbox(bbox, x=bbox.x - l, y=bbox.y - t, x2=bbox.x2 + r, y2=bbox.y2 + b)
154
+
155
+
156
+ def bbox_dict(bbox: SupportsBounds) -> dict[str, float]:
157
+ """Return a dictionary representation of a bounding box.
158
+
159
+ :param bbox: the bounding box or bound element from which to extract dimensions.
160
+ :return: a dictionary with keys x, y, width, and height.
161
+ """
162
+ return {"x": bbox.x, "y": bbox.y, "width": bbox.width, "height": bbox.height}
163
+
164
+
165
+ def new_bbox_rect(bbox: BoundingBox, **kwargs: float | str) -> EtreeElement:
166
+ """Return a new rect element with the same dimensions as the bounding box.
167
+
168
+ :param bbox: the bounding box or bound element from which to extract dimensions.
169
+ :param kwargs: additional attributes for the rect element.
170
+ """
171
+ return new_element("rect", **bbox_dict(bbox), **kwargs)
svg_ultralight/layout.py CHANGED
@@ -43,7 +43,10 @@ def expand_pad_arg(pad: PadArg) -> tuple[float, float, float, float]:
43
43
  return expand_pad_arg([pad])
44
44
  as_ms = [m if isinstance(m, Measurement) else Measurement(m) for m in pad]
45
45
  as_units = [m.value for m in as_ms]
46
- as_units = [as_units[i % len(as_units)] for i in range(4)]
46
+ if len(as_units) == 3:
47
+ as_units = [*as_units, as_units[1]]
48
+ else:
49
+ as_units = [as_units[i % len(as_units)] for i in range(4)]
47
50
  return as_units[0], as_units[1], as_units[2], as_units[3]
48
51
 
49
52
 
@@ -99,7 +102,7 @@ def _infer_scale(
99
102
  * print_h == 0 / viewbox_h > 0
100
103
 
101
104
  The print area is invalid, but there is special handling for this. Interpret
102
- viewbox units as print_w.native_unit and determine print area from viewbox area 1
105
+ viewbox units as print_w.native_unit and determe print area from viewbox area 1
103
106
  to 1.
104
107
 
105
108
  >>> _infer_scale(Measurement("in"), Measurement("in"), 1, 2)
@@ -65,8 +65,8 @@ def _wrap_bag(title: str) -> EtreeElement:
65
65
  """
66
66
  items = title.split(",")
67
67
  agent = new_element(new_qname("rdf", "Bag"))
68
- for title in items:
69
- _ = new_sub_element(agent, new_qname("rdf", "li"), text=title)
68
+ for title_item in items:
69
+ _ = new_sub_element(agent, new_qname("rdf", "li"), text=title_item)
70
70
  return agent
71
71
 
72
72
 
svg_ultralight/query.py CHANGED
@@ -11,24 +11,36 @@ business card). Getting bounding boxes from Inkscape is not exceptionally fast.
11
11
 
12
12
  from __future__ import annotations
13
13
 
14
+ import hashlib
14
15
  import os
16
+ import pickle
15
17
  import re
16
18
  import uuid
19
+ from contextlib import suppress
17
20
  from copy import deepcopy
21
+ from pathlib import Path
18
22
  from subprocess import PIPE, Popen
19
- from tempfile import NamedTemporaryFile
23
+ from tempfile import NamedTemporaryFile, TemporaryFile
20
24
  from typing import TYPE_CHECKING
25
+ from warnings import warn
26
+
27
+ from lxml import etree
21
28
 
22
29
  from svg_ultralight.bounding_boxes.type_bounding_box import BoundingBox
23
30
  from svg_ultralight.bounding_boxes.type_padded_text import PaddedText
24
31
  from svg_ultralight.main import new_svg_root, write_svg
25
32
 
26
33
  if TYPE_CHECKING:
27
- from pathlib import Path
28
34
 
29
35
  from lxml.etree import _Element as EtreeElement # type: ignore
30
36
 
31
37
 
38
+ with TemporaryFile() as f:
39
+ _CACHE_DIR = Path(f.name).parent / "svg_ultralight_cache"
40
+
41
+ _CACHE_DIR.mkdir(exist_ok=True)
42
+
43
+
32
44
  def _fill_ids(*elem_args: EtreeElement) -> None:
33
45
  """Set the id attribute of an element and all its children. Keep existing ids.
34
46
 
@@ -66,8 +78,8 @@ def _envelop_copies(*elem_args: EtreeElement) -> EtreeElement:
66
78
  :param elem_args: one or more etree elements
67
79
  :return: an etree element enveloping copies of elem_args with all views normalized
68
80
  """
69
- envelope = new_svg_root(0, 0, 1, 1, id_=f"envelope_{uuid.uuid4()}")
70
- envelope.extend(deepcopy(e) for e in elem_args)
81
+ envelope = new_svg_root(0, 0, 1, 1)
82
+ envelope.extend([deepcopy(e) for e in elem_args])
71
83
  _normalize_views(envelope)
72
84
  return envelope
73
85
 
@@ -106,6 +118,8 @@ def map_ids_to_bounding_boxes(
106
118
  a (0, 0, 1, 1) root. This will put the boxes where you'd expect them to be, no
107
119
  matter what root you use.
108
120
  """
121
+ if not elem_args:
122
+ return {}
109
123
  _fill_ids(*elem_args)
110
124
  envelope = _envelop_copies(*elem_args)
111
125
 
@@ -123,40 +137,82 @@ def map_ids_to_bounding_boxes(
123
137
  return id2bbox
124
138
 
125
139
 
126
- def get_bounding_box(
140
+ def _hash_elem(elem: EtreeElement) -> str:
141
+ """Hash an EtreeElement.
142
+
143
+ Will match identical (excepting id) elements.
144
+ """
145
+ elem_copy = deepcopy(elem)
146
+ with suppress(KeyError):
147
+ _ = elem_copy.attrib.pop("id")
148
+ hash_object = hashlib.sha256(etree.tostring(elem_copy))
149
+ return hash_object.hexdigest()
150
+
151
+
152
+ def _try_bbox_cache(elem_hash: str) -> BoundingBox | None:
153
+ """Try to load a cached bounding box."""
154
+ cache_path = _CACHE_DIR / elem_hash
155
+ if not cache_path.exists():
156
+ return None
157
+ try:
158
+ with cache_path.open("rb") as f:
159
+ return pickle.load(f)
160
+ except (EOFError, pickle.UnpicklingError) as e:
161
+ msg = f"Error loading cache file {cache_path}: {e}"
162
+ warn(msg)
163
+ except Exception as e:
164
+ msg = f"Unexpected error loading cache file {cache_path}: {e}"
165
+ warn(msg)
166
+ return None
167
+
168
+
169
+ def get_bounding_boxes(
127
170
  inkscape: str | Path, *elem_args: EtreeElement
128
- ) -> BoundingBox | tuple[BoundingBox, ...]:
171
+ ) -> tuple[BoundingBox, ...]:
129
172
  r"""Get bounding box around a single element (or multiple elements).
130
173
 
131
174
  :param inkscape: path to an inkscape executable on your local file system
132
175
  IMPORTANT: path cannot end with ``.exe``.
133
176
  Use something like ``"C:\\Program Files\\Inkscape\\inkscape"``
134
177
  :param elem_args: xml elements
135
- :return: a BoundingBox instance around a single elem or a tuple of BoundingBox
136
- instances if multiple elem_args are passed.
178
+ :return: a BoundingBox instance around a each elem_arg
137
179
 
138
180
  This will work most of the time, but if you're missing an nsmap, you'll need to
139
181
  create an entire xml file with a custom nsmap (using
140
182
  `svg_ultralight.new_svg_root`) then call `map_ids_to_bounding_boxes` directly.
141
183
  """
142
- id2bbox = map_ids_to_bounding_boxes(inkscape, *elem_args)
143
- bboxes = [id2bbox[x.get("id", "")] for x in elem_args]
144
- if len(bboxes) == 1:
145
- return bboxes[0]
146
- return tuple(bboxes)
184
+ elem2hash = {elem: _hash_elem(elem) for elem in elem_args}
185
+ cached = [_try_bbox_cache(h) for h in elem2hash.values()]
186
+ if None not in cached:
187
+ return tuple(filter(None, cached))
147
188
 
189
+ hash2bbox = {h: c for h, c in zip(elem2hash.values(), cached) if c is not None}
190
+ remainder = [e for e, c in zip(elem_args, cached) if c is None]
191
+ id2bbox = map_ids_to_bounding_boxes(inkscape, *remainder)
192
+ for elem in remainder:
193
+ hash_ = elem2hash[elem]
194
+ hash2bbox[hash_] = id2bbox[elem.attrib["id"]]
195
+ with (_CACHE_DIR / hash_).open("wb") as f:
196
+ pickle.dump(hash2bbox[hash_], f)
197
+ return tuple(hash2bbox[h] for h in elem2hash.values())
148
198
 
149
- def _replace_text(text_elem: EtreeElement, new_text: str) -> None:
150
- """Replace the text in a text element.
151
199
 
152
- :param text_elem: an etree element with a text tag
153
- :param new_text: the new text to insert
200
+ def get_bounding_box(inkscape: str | Path, elem: EtreeElement) -> BoundingBox:
201
+ r"""Get bounding box around a single element.
154
202
 
155
- If the text element has tspans, replace each tspan.text with new_text.
203
+ :param inkscape: path to an inkscape executable on your local file system
204
+ IMPORTANT: path cannot end with ``.exe``.
205
+ Use something like ``"C:\\Program Files\\Inkscape\\inkscape"``
206
+ :param elem: xml element
207
+ :return: a BoundingBox instance around a single elem
156
208
  """
157
- text_elem.text = new_text
158
- for sub_elem in text_elem:
159
- sub_elem.text = new_text
209
+ return get_bounding_boxes(inkscape, elem)[0]
210
+
211
+
212
+ def clear_svg_ultralight_cache() -> None:
213
+ """Clear all cached bounding boxes."""
214
+ for cache_file in _CACHE_DIR.glob("*"):
215
+ cache_file.unlink()
160
216
 
161
217
 
162
218
  def pad_text(
@@ -179,12 +235,10 @@ def pad_text(
179
235
  _ = rmargin_ref.attrib.pop("id", None)
180
236
  _ = capline_ref.attrib.pop("id", None)
181
237
  rmargin_ref.attrib["text-anchor"] = "end"
182
- _replace_text(capline_ref, capline_reference_char)
183
- id2bbox = map_ids_to_bounding_boxes(inkscape, text_elem, rmargin_ref, capline_ref)
238
+ capline_ref.text = capline_reference_char
184
239
 
185
- bbox = id2bbox[text_elem.attrib["id"]]
186
- rmargin_bbox = id2bbox[rmargin_ref.attrib["id"]]
187
- capline_bbox = id2bbox[capline_ref.attrib["id"]]
240
+ bboxes = get_bounding_boxes(inkscape, text_elem, rmargin_ref, capline_ref)
241
+ bbox, rmargin_bbox, capline_bbox = bboxes
188
242
 
189
243
  tpad = bbox.y - capline_bbox.y
190
244
  rpad = -rmargin_bbox.x2
@@ -63,6 +63,9 @@ def mat_invert(tmat: _Matrix) -> _Matrix:
63
63
  """Invert a 2D transformation matrix in svg format."""
64
64
  a, b, c, d, e, f = tmat
65
65
  det = a * d - b * c
66
+ if det == 0:
67
+ msg = "Matrix is not invertible"
68
+ raise ValueError(msg)
66
69
  return (
67
70
  d / det,
68
71
  -b / det,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: svg-ultralight
3
- Version: 0.32.2
3
+ Version: 0.34.0
4
4
  Summary: a sensible way to create svg files with Python
5
5
  Author-email: Shay Hill <shay_public@hotmail.com>
6
6
  License: MIT
@@ -11,10 +11,10 @@ Requires-Dist: pillow
11
11
  Requires-Dist: paragraphs
12
12
  Requires-Dist: types-lxml
13
13
  Provides-Extra: dev
14
- Requires-Dist: pytest ; extra == 'dev'
15
- Requires-Dist: commitizen ; extra == 'dev'
16
- Requires-Dist: pre-commit ; extra == 'dev'
17
- Requires-Dist: tox ; extra == 'dev'
14
+ Requires-Dist: pytest; extra == "dev"
15
+ Requires-Dist: commitizen; extra == "dev"
16
+ Requires-Dist: pre-commit; extra == "dev"
17
+ Requires-Dist: tox; extra == "dev"
18
18
 
19
19
  # svg_ultralight
20
20
 
@@ -1,19 +1,18 @@
1
- svg_ultralight/__init__.py,sha256=k6oHfgxlQLUJmIhkQdBthMTvDqKFsWIp_ZaXxC1bwGM,2250
2
- svg_ultralight/animate.py,sha256=fE-zRU_uFrZIL9W78fcGz7qmrts8fz5UoWEy7b4xb44,1144
3
- svg_ultralight/import_svg.py,sha256=TVLbinch2g0RN-OlWyGXoQEO6vc2I_LsMXpOchwTJzE,1548
1
+ svg_ultralight/__init__.py,sha256=jqT_dNNvrSJ3SUndR3e323BbdNlZIEu_iIzmr0iwWNw,2500
2
+ svg_ultralight/animate.py,sha256=JSrBm-59BcNXDF0cGgl4-C89eBunjevZnwZxIWt48TU,1112
4
3
  svg_ultralight/inkscape.py,sha256=M8yTxXOu4NlXnhsMycvEJiIDpnDeiZ_bZakJBM38ZoU,9152
5
- svg_ultralight/layout.py,sha256=RBFJl6cIN6BYqXea5powEl2A4ZIxUJ0mtVoURkSZy_E,12240
4
+ svg_ultralight/layout.py,sha256=FgR45FsHax4xDjGkk9HEVW4OcwhtM8aqw2JUdZs_m7Q,12326
6
5
  svg_ultralight/main.py,sha256=6oNkZfD27UMdP-oYqp5agS_IGcYb8NkUZwM9Zdyb3SA,7287
7
- svg_ultralight/metadata.py,sha256=Mxgxrxe1Ar4kp2wTT29aadxgHNFaaNLABo29jStiWDg,4201
6
+ svg_ultralight/metadata.py,sha256=xR3ObM0QV7OQ90IKvfigR5B6e0JW6GGVGvTlL5NswWI,4211
8
7
  svg_ultralight/nsmap.py,sha256=y63upO78Rr-JJT56RWWZuyrsILh6HPoY4GhbYnK1A0g,1244
9
8
  svg_ultralight/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
- svg_ultralight/query.py,sha256=nsw7L_gH-EPf5LaNu5jtVPihq-qhKs1O2psMU3sTUXU,7732
9
+ svg_ultralight/query.py,sha256=F_yl-zbNQSOFxiuHT4qZ0LqLoYdD36BGTREJady5sBc,9430
11
10
  svg_ultralight/root_elements.py,sha256=pt9J6mPrnoTAZVF6vKTZoM_o947I8UCj6MbGcD2JUCk,2869
12
11
  svg_ultralight/string_conversion.py,sha256=WEmpf75RJmJ2lfJluagAz2wPsz6wM8XvTEwkq4U0vEc,7353
13
- svg_ultralight/transformations.py,sha256=64BN_UupvOZk4nbiKLKv09P3j0TPFhH6mKro_3QBqeY,3945
12
+ svg_ultralight/transformations.py,sha256=7-6NNh6xZ45mM_933fMuQfRGpI7q9Qrt5qse9e6FUek,4036
14
13
  svg_ultralight/unit_conversion.py,sha256=g07nhzXdjPvGcJmkhLdFbeDLrSmbI8uFoVgPo7G62Bg,9258
15
14
  svg_ultralight/bounding_boxes/__init__.py,sha256=qUEn3r4s-1QNHaguhWhhaNfdP4tl_B6YEqxtiTFuzhQ,78
16
- svg_ultralight/bounding_boxes/bound_helpers.py,sha256=YMClhdekeYbzD_ijXDAer-H3moWKN3lUNnZs1UNFFKc,3458
15
+ svg_ultralight/bounding_boxes/bound_helpers.py,sha256=1l0-Aw3p-9ru7Pm76Wa9K_ufSPRv54NDTG8WsMo_obQ,6125
17
16
  svg_ultralight/bounding_boxes/supports_bounds.py,sha256=fbHV6mGdeIVV3lS15vBKSrHiHKR7DMg4K5X__4LLmCE,4569
18
17
  svg_ultralight/bounding_boxes/type_bound_collection.py,sha256=b89TM2UsdaeApyjTQeMbx_FG_WcCiLAImEiHiZ6EWPI,2600
19
18
  svg_ultralight/bounding_boxes/type_bound_element.py,sha256=9RdxH8osOlAvPdWR0Ww9NsasHLPYFDs-MbydoV48x4E,2239
@@ -23,7 +22,7 @@ svg_ultralight/constructors/__init__.py,sha256=YcnO0iBQc19aL8Iemw0Y452MBMBIT2AN5
23
22
  svg_ultralight/constructors/new_element.py,sha256=VtMz9sPn9rMk6rui5Poysy3vezlOaS-tGIcGbu-SXmY,3406
24
23
  svg_ultralight/strings/__init__.py,sha256=Zalrf-ThFz7b7xKELx5lb2gOlBgV-6jk_k_EeSdVCVk,295
25
24
  svg_ultralight/strings/svg_strings.py,sha256=RYKMxOHq9abbZyGcFqsElBGLrBX-EjjNxln3s_ibi30,1296
26
- svg_ultralight-0.32.2.dist-info/METADATA,sha256=iXnT_qxV0Qg9tp3XAtv1b7TlxV-xkiYnAkCm700McgA,8871
27
- svg_ultralight-0.32.2.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
28
- svg_ultralight-0.32.2.dist-info/top_level.txt,sha256=se-6yqM_0Yg5orJKvKWdjQZ4iR4G_EjhL7oRgju-fdY,15
29
- svg_ultralight-0.32.2.dist-info/RECORD,,
25
+ svg_ultralight-0.34.0.dist-info/METADATA,sha256=MUbU1KYDWS-PKOOwFfkVJlvghN33UlKxW1ucx4NU3_E,8867
26
+ svg_ultralight-0.34.0.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91
27
+ svg_ultralight-0.34.0.dist-info/top_level.txt,sha256=se-6yqM_0Yg5orJKvKWdjQZ4iR4G_EjhL7oRgju-fdY,15
28
+ svg_ultralight-0.34.0.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: bdist_wheel (0.43.0)
2
+ Generator: setuptools (75.6.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,50 +0,0 @@
1
- """Import an svg file as a BoundElement.
2
-
3
- :author: Shay Hill
4
- :created: 2024-05-28
5
- """
6
-
7
- from __future__ import annotations
8
-
9
- from typing import TYPE_CHECKING
10
-
11
- from lxml import etree
12
-
13
- from svg_ultralight.bounding_boxes.type_bound_element import BoundElement
14
- from svg_ultralight.bounding_boxes.type_bounding_box import BoundingBox
15
- from svg_ultralight.constructors import new_element
16
-
17
- if TYPE_CHECKING:
18
- import os
19
-
20
- from lxml.etree import _Element as EtreeElement # type: ignore
21
-
22
-
23
- def _get_bounds_from_viewbox(root: EtreeElement) -> BoundingBox:
24
- """Get the BoundingBox from the viewbox attribute of the root element.
25
-
26
- :param root: The root element of the svg.
27
- :return: The BoundingBox of the svg.
28
- """
29
- viewbox = root.attrib.get("viewBox")
30
- if viewbox is None:
31
- msg = "SVG file has no viewBox attribute. Failed to create BoundingBox."
32
- raise ValueError(msg)
33
- x, y, width, height = map(float, viewbox.split())
34
- return BoundingBox(x, y, width, height)
35
-
36
-
37
- def import_svg(svg: str | os.PathLike[str]) -> BoundElement:
38
- """Import an svg file as a BoundElement.
39
-
40
- :param svg: The path to the svg file.
41
- :return: The BoundElement representation of the svg.
42
-
43
- The viewbox of the svg is used to create the BoundingBox of the BoundElement.
44
- """
45
- tree = etree.parse(svg)
46
- root = tree.getroot()
47
- bbox = _get_bounds_from_viewbox(root)
48
- root_as_elem = new_element("g")
49
- root_as_elem.extend(root)
50
- return BoundElement(root_as_elem, bbox)