svg-ultralight 0.39.0__py3-none-any.whl → 0.40.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.

@@ -0,0 +1,284 @@
1
+ """Compare results between Inkscape and fontTools.
2
+
3
+ Function `check_font_tools_alignment` will let you know if it's relatively safe to
4
+ use `pad_text_mix` or `pad_text_ft`, which improve `pad_text` by assigning `line_gap`
5
+ values to the resulting PaddedText instance and by aligning with the actual descent
6
+ and ascent of a font instead of by attempting to infer these from a referenve string.
7
+
8
+ See Enum `FontBboxError` for the possible error codes and their meanings returned by
9
+ `check_font`.
10
+
11
+ You can use `draw_comparison` to debug or explore differences between fontTools and
12
+ Inkscape.
13
+
14
+ :author: Shay Hill
15
+ :created: 2025-06-08
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import enum
21
+ import itertools as it
22
+ import string
23
+ import sys
24
+ from pathlib import Path
25
+ from typing import TYPE_CHECKING
26
+
27
+ from svg_ultralight import new_bbox_rect, new_svg_root_around_bounds, pad_bbox
28
+ from svg_ultralight.bounding_boxes.padded_text_initializers import (
29
+ DEFAULT_Y_BOUNDS_REFERENCE,
30
+ pad_text,
31
+ pad_text_ft,
32
+ )
33
+ from svg_ultralight.constructors import new_element
34
+ from svg_ultralight.font_tools.font_css import add_svg_font_class
35
+ from svg_ultralight.font_tools.font_info import get_svg_font_attributes
36
+ from svg_ultralight.main import write_svg
37
+
38
+ if TYPE_CHECKING:
39
+ import os
40
+ from collections.abc import Iterator
41
+
42
+ from svg_ultralight.bounding_boxes.type_bounding_box import BoundingBox
43
+
44
+
45
+ class FontBboxError(enum.Enum):
46
+ """Classify the type of error between Inkscape and fontTools bounding boxes.
47
+
48
+ INIT: Use `pad_text`.
49
+
50
+ FontTools failed to run. This can happen with fonts that, inentionally or
51
+ not, do not have the required tables or character sets to build a bounding box
52
+ around the TEXT_TEXT. You can only use the `pad_text` PaddedText constructor.
53
+ This font may work with other or ascii-only text.
54
+
55
+ ELEM_Y: Use `pad_text` or `pad_text_mix` with cautions.
56
+
57
+ The y coordinate of the element bounding box is off by more than 1% of
58
+ the height. This error matters, because the y coordinates are used by
59
+ `pad_bbox_ft` and `pad_bbox_mix`. You can use either of these functions with a
60
+ y_bounds_reference element and accept some potential error in `line_gap` or
61
+ explicitly pass `ascent` and `descent` values to `pad_text_ft` or `pad_text_mix`.
62
+
63
+ SAFE_ELEM_X: Use `pad_text_mix`.
64
+
65
+ The y bounds are accurate, but the x coordinate of the element
66
+ bounding box is off by more than 1%. This is called "safe" because it is not used
67
+ by pad_bbox_mix, but you cannot use `pad_text_ft` without expecting BoundingBox
68
+ inaccuracies.
69
+
70
+ LINE_Y: Use `pad_text` or `pad_text_mix` with caution.
71
+
72
+ All of the above match, but the y coordinate of the line bounding box
73
+ (the padded bounding box) is off by more than 1% of the height. This error
74
+ matters as does ELEM_Y, but it does not exist for any font on my system. Fonts
75
+ without ELEM_Y errors should not have LINE_Y errors.
76
+
77
+ SAFE_LINE_X: Use `pad_text_mix`.
78
+
79
+ All of the above match, but the x coordinate of the line bounding
80
+ box (the padded bounding box) is off by more than 1%. This is safe or unsafe as
81
+ SAFE_ELEM_X, but also does not exist for any font on my system.
82
+
83
+ NO_ERROR: Use `pad_text_ft`.
84
+
85
+ No errors were found. The bounding boxes match within 1% of the height.
86
+ You can use `pad_text_ft` to get the same result as `pad_text` or `pad_text_mix`
87
+ without the delay caused by an Inkscape call.
88
+ """
89
+
90
+ INIT = enum.auto()
91
+ ELEM_Y = enum.auto()
92
+ SAFE_ELEM_X = enum.auto()
93
+ LINE_Y = enum.auto()
94
+ SAFE_LINE_X = enum.auto()
95
+ NO_ERROR = enum.auto()
96
+
97
+
98
+ # ===================================================================================
99
+ # Produce some commonly used Western UTF-8 characters for test text.
100
+ # ===================================================================================
101
+
102
+
103
+ def _get_western_utf8() -> str:
104
+ """Return a string of the commonly used Western UTF-8 character set."""
105
+ western = " ".join(
106
+ [
107
+ string.ascii_lowercase,
108
+ string.ascii_uppercase,
109
+ string.digits,
110
+ string.punctuation,
111
+ "áÁéÉíÍóÓúÚñÑäÄëËïÏöÖüÜçÇàÀèÈìÌòÒùÙâÂêÊîÎôÔûÛãÃõÕåÅæÆøØœŒßÿŸ",
112
+ ]
113
+ )
114
+ return western + " "
115
+
116
+
117
+ DEFAULT_TEST_TEXT = _get_western_utf8()
118
+
119
+
120
+ def _format_bbox_error(
121
+ bbox_a: BoundingBox, bbox_b: BoundingBox
122
+ ) -> tuple[int, int, int, int]:
123
+ """Return the difference between two bounding boxes as a percentage of height."""
124
+ width = bbox_a.width
125
+ height = bbox_a.height
126
+ diff = (
127
+ bbox_b.x - bbox_a.x,
128
+ bbox_b.y - bbox_a.y,
129
+ bbox_b.width - bbox_a.width,
130
+ bbox_b.height - bbox_a.height,
131
+ )
132
+ scaled_diff = (x / y for x, y in zip(diff, (height, height, width, height)))
133
+ dx, dy, dw, dh = (int(x * 100) for x in scaled_diff)
134
+ return dx, dy, dw, dh
135
+
136
+
137
+ def check_font_tools_alignment(
138
+ inkscape: str | os.PathLike[str],
139
+ font: str | os.PathLike[str],
140
+ text: str | None = None,
141
+ ) -> tuple[FontBboxError, tuple[int, int, int, int] | None]:
142
+ """Return an error code and the difference b/t Inkscape and fontTools bboxes.
143
+
144
+ :param inkscape: path to an Inkscape executable
145
+ :param font_path: path to the font file
146
+ :return: a tuple of the error code and the percentage difference between the
147
+ bounding boxes as a tuple of (dx, dy, dw, dh) or (error, None) if there was
148
+ an error initializing fontTools.
149
+ """
150
+ if text is None:
151
+ text = DEFAULT_TEST_TEXT
152
+ try:
153
+ svg_attribs = get_svg_font_attributes(font)
154
+ text_elem = new_element("text", **svg_attribs, text=text)
155
+ rslt_pt = pad_text(inkscape, text_elem)
156
+ rslt_ft = pad_text_ft(
157
+ font,
158
+ text,
159
+ y_bounds_reference=DEFAULT_Y_BOUNDS_REFERENCE,
160
+ )
161
+ except Exception:
162
+ return FontBboxError.INIT, None
163
+
164
+ error = _format_bbox_error(rslt_pt.unpadded_bbox, rslt_ft.unpadded_bbox)
165
+ if error[1] or error[3]:
166
+ return FontBboxError.ELEM_Y, error
167
+ if error[0] or error[2]:
168
+ return FontBboxError.SAFE_ELEM_X, error
169
+
170
+ error = _format_bbox_error(rslt_pt.bbox, rslt_ft.bbox)
171
+ if error[1] or error[3]:
172
+ return FontBboxError.LINE_Y, error
173
+ if error[0] or error[2]:
174
+ return FontBboxError.SAFE_LINE_X, error
175
+
176
+ return FontBboxError.NO_ERROR, None
177
+
178
+
179
+ def draw_comparison(
180
+ inkscape: str | os.PathLike[str],
181
+ output: str | os.PathLike[str],
182
+ font: str | os.PathLike[str],
183
+ text: str | None = None,
184
+ ) -> None:
185
+ """Draw a font in Inkscape and fontTools.
186
+
187
+ :param inkscape: path to an Inkscape executable
188
+ :param output: path to the output SVG file
189
+ :param font: path to the font file
190
+ :param text: the text to render. If None, the font name will be used.
191
+ :effect: Writes an SVG file to the output path.
192
+
193
+ Compare the rendering and bounding boxes of a font in Inkscape and fontTools. The
194
+ bounding boxes drawn will always be accurate, but some fonts will not render the
195
+ Inkscape version in a browser. Conversely, Inskcape will not render the fontTools
196
+ version in Inkscape, because Inkscape does not read locally linked fonts. It
197
+ usually works, and it a good place to start if you'd like to compare fontTools
198
+ and Inkscape results.
199
+ """
200
+ if text is None:
201
+ text = Path(font).stem
202
+ font_size = 12
203
+ font_attributes = get_svg_font_attributes(font)
204
+ text_elem = new_element("text", text=text, **font_attributes, font_size=font_size)
205
+ padded_pt = pad_text(inkscape, text_elem)
206
+ padded_ft = pad_text_ft(
207
+ font,
208
+ text,
209
+ font_size,
210
+ y_bounds_reference=DEFAULT_Y_BOUNDS_REFERENCE,
211
+ fill="none",
212
+ stroke="orange",
213
+ stroke_width=0.05,
214
+ )
215
+
216
+ root = new_svg_root_around_bounds(pad_bbox(padded_pt.bbox, 10))
217
+ _ = add_svg_font_class(root, font)
218
+ root.append(
219
+ new_bbox_rect(
220
+ padded_pt.unpadded_bbox, fill="none", stroke_width=0.07, stroke="red"
221
+ )
222
+ )
223
+ root.append(
224
+ new_bbox_rect(
225
+ padded_ft.unpadded_bbox, fill="none", stroke_width=0.05, stroke="blue"
226
+ )
227
+ )
228
+ root.append(padded_pt.elem)
229
+ root.append(padded_ft.elem)
230
+ _ = sys.stdout.write(f"{Path(font).stem} comparison drawn at {output}.\n")
231
+ _ = write_svg(Path(output), root)
232
+
233
+
234
+ def _iter_fonts(*fonts_dirs: Path) -> Iterator[Path]:
235
+ """Yield a path to each ttf and otf file in the given directories.
236
+
237
+ :param fonts_dir: directory to search for ttf and otf files, multiple ok
238
+ :yield: paths to ttf and otf files in the given directories
239
+
240
+ A helper function for _test_every_font_on_my_system.
241
+ """
242
+ if not fonts_dirs:
243
+ return
244
+ head, *tail = fonts_dirs
245
+ ttf_files = head.glob("*.[tt][tt][ff]")
246
+ otf_files = head.glob("*.[oO][tT][fF]")
247
+ yield from it.chain(ttf_files, otf_files)
248
+ yield from _iter_fonts(*tail)
249
+
250
+
251
+ def _test_every_font_on_my_system(
252
+ inkscape: str | os.PathLike[str],
253
+ font_dirs: list[Path],
254
+ text: str | None = None,
255
+ ) -> None:
256
+ """Test every font on my system."""
257
+ if not Path(inkscape).with_suffix(".exe").exists():
258
+ _ = sys.stdout.write(f"Inkscape not found at {inkscape}\n")
259
+ return
260
+ font_dirs = [x for x in font_dirs if x.exists()]
261
+ if not font_dirs:
262
+ _ = sys.stdout.write("No font directories found.\n")
263
+ return
264
+
265
+ counts = dict.fromkeys(FontBboxError, 0)
266
+ for font_path in _iter_fonts(*font_dirs):
267
+ error, diff = check_font_tools_alignment(inkscape, font_path, text)
268
+ counts[error] += 1
269
+ if error is not FontBboxError.NO_ERROR:
270
+ _ = sys.stdout.write(f"Error with {font_path.name}: {error.name} {diff}\n")
271
+ for k, v in counts.items():
272
+ _ = sys.stdout.write(f"{k.name}: {v}\n")
273
+
274
+
275
+ if __name__ == "__main__":
276
+ _INKSCAPE = Path(r"C:\Program Files\Inkscape\bin\inkscape")
277
+ _FONT_DIRS = [
278
+ Path(r"C:\Windows\Fonts"),
279
+ Path(r"C:\Users\shaya\AppData\Local\Microsoft\Windows\Fonts"),
280
+ ]
281
+ _test_every_font_on_my_system(_INKSCAPE, _FONT_DIRS)
282
+
283
+ font = Path(r"C:\Windows\Fonts\arial.ttf")
284
+ draw_comparison(_INKSCAPE, "temp.svg", font)
@@ -0,0 +1,82 @@
1
+ """Link local fonts as css in an svg file.
2
+
3
+ :author: Shay Hill
4
+ :created: 2025-06-04
5
+ """
6
+
7
+ # pyright: reportUnknownMemberType = false
8
+ # pyright: reportAttributeAccessIssue = false
9
+ # pyright: reportUnknownArgumentType = false
10
+ # pyright: reportUnknownVariableType = false
11
+ # pyright: reportUnknownParameterType = false
12
+ # pyright: reportMissingTypeStubs = false
13
+
14
+ from __future__ import annotations
15
+
16
+ from pathlib import Path
17
+ from typing import TYPE_CHECKING
18
+
19
+ import cssutils
20
+
21
+ from svg_ultralight.constructors import new_element
22
+ from svg_ultralight.string_conversion import encode_to_css_class_name
23
+
24
+ if TYPE_CHECKING:
25
+ import os
26
+
27
+ from lxml.etree import (
28
+ _Element as EtreeElement, # pyright: ignore[reportPrivateUsage]
29
+ )
30
+
31
+
32
+ def _get_class_names_from_stylesheet(
33
+ stylesheet: cssutils.css.CSSStyleSheet,
34
+ ) -> list[str]:
35
+ """Extract all class names from a given CSS stylesheet.
36
+
37
+ :param stylesheet: A cssutils.css.CSSStyleSheet object.
38
+ :return: A list of class names (without the leading dot).
39
+ """
40
+ class_names: list[str] = []
41
+ for rule in stylesheet.cssRules:
42
+ if rule.type == rule.STYLE_RULE:
43
+ selectors = (s.strip() for s in rule.selectorText.split(","))
44
+ class_names.extend(s[1:] for s in selectors if s.startswith("."))
45
+ return class_names
46
+
47
+
48
+ def add_svg_font_class(root: EtreeElement, font: str | os.PathLike[str]) -> str:
49
+ """Add a css class for the font to the root element.
50
+
51
+ :param root: The root element of the SVG document.
52
+ :param font: Path to the font file.
53
+ :return: The class name for the font, e.g., "bahnschrift_2e_ttf"
54
+ """
55
+ assert Path(font).exists()
56
+ family_name = encode_to_css_class_name(Path(font).stem)
57
+ class_name = encode_to_css_class_name(Path(font).name)
58
+ style = root.find("style")
59
+ if style is None:
60
+ style = new_element("style", type="text/css")
61
+ root.insert(0, style)
62
+ css = style.text or ""
63
+
64
+ stylesheet = cssutils.parseString(css)
65
+ existing_class_names = _get_class_names_from_stylesheet(stylesheet)
66
+ if class_name in existing_class_names:
67
+ return class_name
68
+
69
+ font_face_rule = cssutils.css.CSSFontFaceRule()
70
+ font_face_rule.style = cssutils.css.CSSStyleDeclaration()
71
+ font_face_rule.style["font-family"] = f'"{family_name}"'
72
+ font_face_rule.style["src"] = rf"url('{Path(font).as_posix()}')"
73
+ stylesheet.add(font_face_rule)
74
+
75
+ style_rule = cssutils.css.CSSStyleRule(selectorText=f".{class_name}")
76
+ style_rule.style = cssutils.css.CSSStyleDeclaration()
77
+ style_rule.style["font-family"] = f'"{family_name}"'
78
+ stylesheet.add(style_rule)
79
+
80
+ style.text = stylesheet.cssText.decode("utf-8")
81
+
82
+ return class_name