vibe-sketcherDocumentation
Source code for vibesketcher.render.periodic_tex
"""Editable TikZ from the periodic renderer's own bounded SVG vocabulary.
This is not an SVG importer. Only :func:`periodic_figure_svg` supplies input;
unknown primitives/attributes fail closed so a new overlay cannot disappear
silently. Geometry and painter order therefore stay shared with SVG/PDF/PNG.
TikZ baseline anchors and path actions follow the PGF/TikZ manual, sections
15 and 17 (https://tikz.dev/tikz-actions, https://tikz.dev/tikz-shapes).
No external converter or TeX process runs during export.
"""
from __future__ import annotations
import math
import re
import xml.etree.ElementTree as ET
from dataclasses import dataclass
_SPECIAL = {
"\\": r"\textbackslash{}", "{": r"\{", "}": r"\}", "%": r"\%",
"&": r"\&", "#": r"\#", "_": r"\_", "$": r"\$", "^": r"\textasciicircum{}",
"~": r"\textasciitilde{}", "<": r"\textless{}", ">": r"\textgreater{}",
"Å": r"\AA{}", "×": r"\ensuremath{\times}", "π": r"\ensuremath{\pi}",
"δ": r"\ensuremath{\delta}", "Γ": r"\ensuremath{\Gamma}", "Δ": r"\ensuremath{\Delta}",
"Σ": r"\ensuremath{\Sigma}", "Λ": r"\ensuremath{\Lambda}",
"−": "-", "–": "--", "—": "---", "·": r"\ensuremath{\cdot}",
"°": r"\ensuremath{^\circ}",
"|": r"\textbar{}",
**{c: rf"\textsuperscript{{{v}}}" for c, v in zip("⁻⁺⁰¹²³⁴⁵⁶⁷⁸⁹", "-+0123456789", strict=True)},
} # fmt: skip
def _text(value: str) -> str:
# Each character is escaped once; labels can never introduce TeX commands.
return "".join(_SPECIAL.get(c, " " if c.isspace() else c) for c in value)
def _number(value: str) -> float:
result = float(value)
if not math.isfinite(result):
raise ValueError("non-finite figure coordinate")
return result
def _n(value: float) -> str:
if abs(value) < 0.0000005:
return "0"
return f"{value:.6f}".rstrip("0").rstrip(".")
def _tag(element: ET.Element) -> str:
return element.tag.removeprefix("{http://www.w3.org/2000/svg}")
def _attributes(element: ET.Element, allowed: str) -> None:
unknown = set(element.attrib) - set(allowed.split())
unknown = {k for k in unknown if k != "class" and not k.startswith("data-")}
if unknown:
raise ValueError(f"unsupported periodic TeX attributes: {', '.join(sorted(unknown))}")
@dataclass(frozen=True)
class _Transform:
sx: float = 1
sy: float = 1
tx: float = 0
ty: float = 0
def point(self, x: float, y: float) -> str:
return f"({_n(self.tx + self.sx * x)},{_n(self.ty + self.sy * y)})"
def then(self, value: str) -> _Transform:
sx, sy, tx, ty = self.sx, self.sy, self.tx, self.ty
rest = value.strip()
while rest:
match = re.match(r"(translate|scale)\(([^()]*)\)\s*", rest)
if not match:
raise ValueError("unsupported periodic TeX transform")
values = [_number(v) for v in re.split(r"[\s,]+", match[2].strip())]
if len(values) not in (1, 2):
raise ValueError("invalid periodic TeX transform")
a = values[0]
b = values[1] if len(values) == 2 else (a if match[1] == "scale" else 0)
if match[1] == "translate":
tx, ty = tx + sx * a, ty + sy * b
else:
sx, sy = sx * a, sy * b
rest = rest[match.end() :]
if not math.isclose(abs(sx), abs(sy)) or sx == 0:
raise ValueError("nonuniform periodic TeX transform")
return _Transform(sx, sy, tx, ty)
def _colour(value: str) -> str:
if value == "none":
return "none"
if not re.fullmatch(r"#[0-9a-fA-F]{3}(?:[0-9a-fA-F]{3})?", value):
raise ValueError("unsupported periodic TeX colour")
digits = value[1:]
if len(digits) == 3:
digits = "".join(c * 2 for c in digits)
r, g, b = (int(digits[i : i + 2], 16) for i in (0, 2, 4))
return f"{{rgb,255:red,{r};green,{g};blue,{b}}}"
def _style(element: ET.Element, transform: _Transform) -> str:
a = element.attrib
scale = abs(transform.sx) * 0.75 # SVG px = 1/96 inch = 0.75 PDF bp.
result = [f"fill={_colour(a.get('fill', '#000'))}", f"draw={_colour(a.get('stroke', 'none'))}"]
if "stroke" in a:
result.append(f"line width={_n(_number(a.get('stroke-width', '1')) * scale)}bp")
for key in ("fill-opacity", "stroke-opacity"):
if key in a:
result.append(f"{key.replace('-', ' ')}={_n(_number(a[key]))}")
if "stroke-linejoin" in a:
if a["stroke-linejoin"] not in ("round", "bevel", "miter"):
raise ValueError("unsupported line join")
result.append(f"line join={a['stroke-linejoin']}")
if "stroke-dasharray" in a:
dash = [_number(v) for v in re.split(r"[\s,]+", a["stroke-dasharray"])]
if len(dash) % 2:
dash *= 2
result.append(
"dash pattern="
+ " ".join(
f"{'on' if i % 2 == 0 else 'off'} {_n(v * scale)}bp" for i, v in enumerate(dash)
)
)
return ",".join(result)
def _font(size: float) -> str:
# \fontsize uses TeX pt (72.27/in), unlike coordinates/strokes in PDF bp.
return (
rf"\fontsize{{{_n(size * 0.75 * 72.27 / 72)}}}{{{_n(size * 0.9 * 72.27 / 72)}}}\selectfont"
)
def _label(element: ET.Element, transform: _Transform) -> str:
_attributes(element, "x y font-size text-anchor")
size = _number(element.attrib["font-size"])
scale = abs(transform.sx)
anchor = {"start": "base west", "middle": "base", "end": "base east"}.get(
element.get("text-anchor", "start")
)
if anchor is None:
raise ValueError("unsupported periodic TeX text anchor")
parts = [_text(element.text or "")]
offset = 0.0
for child in element:
if _tag(child) != "tspan" or len(child):
raise ValueError("unsupported periodic TeX text span")
_attributes(child, "dy font-size")
offset += _number(child.get("dy", "0"))
child_size = _number(child.get("font-size", str(size)))
body = _font(child_size * scale) + " " + _text(child.text or "")
parts.append(rf"\raisebox{{{_n(-offset * scale * 0.75)}bp}}{{{body}}}")
if child.tail:
parts.append(rf"\raisebox{{{_n(-offset * scale * 0.75)}bp}}{{{_text(child.tail)}}}")
p = transform.point(_number(element.get("x", "0")), _number(element.get("y", "0")))
return (
rf"\node[anchor={anchor},inner sep=0pt,outer sep=0pt,text=black,"
rf"font={{\sffamily{_font(size * scale)}}}] at {p} {{{''.join(parts)}}};"
)
def _draw(element: ET.Element, transform: _Transform, width: float, height: float) -> list[str]:
tag = _tag(element)
if tag == "g":
_attributes(element, "transform")
nested = transform.then(element.get("transform", ""))
return [line for child in element for line in _draw(child, nested, width, height)]
if tag == "title":
return [] # SVG accessibility metadata, not a visible label.
if tag == "text":
return [_label(element, transform)]
geometry = {
"line": "x1 y1 x2 y2",
"circle": "cx cy r",
"ellipse": "cx cy rx ry",
"polygon": "points",
"polyline": "points",
"rect": "x y width height",
}
if tag not in geometry or len(element):
raise ValueError(f"unsupported periodic TeX primitive: {tag}")
_attributes(
element,
geometry[tag] + " fill stroke stroke-width fill-opacity stroke-opacity "
"stroke-dasharray stroke-linejoin",
)
def number(key: str) -> float:
return _number(element.get(key, "0"))
def point(x: str, y: str) -> str:
return transform.point(number(x), number(y))
if tag == "line":
path = f"{point('x1', 'y1')} -- {point('x2', 'y2')}"
elif tag in ("circle", "ellipse"):
rx, ry = (number("r"), number("r")) if tag == "circle" else (number("rx"), number("ry"))
path = (
f"{point('cx', 'cy')} ellipse [x radius={_n(rx * abs(transform.sx))},"
f"y radius={_n(ry * abs(transform.sy))}]"
)
elif tag in ("polygon", "polyline"):
values = [_number(v) for v in re.split(r"[\s,]+", element.attrib["points"].strip())]
if len(values) < (6 if tag == "polygon" else 4) or len(values) % 2:
raise ValueError("invalid periodic TeX polygon")
path = " -- ".join(
transform.point(values[i], values[i + 1]) for i in range(0, len(values), 2)
)
if tag == "polygon":
path += " -- cycle"
else:
w = width if element.get("width") == "100%" else number("width")
h = height if element.get("height") == "100%" else number("height")
path = f"{point('x', 'y')} rectangle {transform.point(number('x') + w, number('y') + h)}"
return [rf"\path[{_style(element, transform)}] {path};"]
[docs]
def periodic_svg_to_tex(svg: bytes) -> bytes:
"""Convert only the generated periodic SVG vocabulary, refusing unknown features."""
root = ET.fromstring(svg)
if _tag(root) != "svg":
raise ValueError("expected a periodic SVG figure")
_attributes(root, "width height viewBox font-family data-vibe-angstrom-per-unit")
# The viewBox is in SVG pixels; the root width and height state the same size
# in pt (#251). A root without a viewBox gives its size in pixels.
if "viewBox" in root.attrib:
box = [_number(v) for v in re.split(r"[\s,]+", root.attrib["viewBox"].strip())]
if len(box) != 4 or box[0] or box[1]:
raise ValueError("expected a periodic SVG viewBox from the origin")
width, height = box[2], box[3]
else:
width, height = _number(root.attrib["width"]), _number(root.attrib["height"])
lines = [
"% Editable periodic figure from vibe-sketcher. Load \\usepackage{chemfig} (or tikz).",
"% Geometry follows the SVG projection; display bonds are not an authored chemical graph.",
"% SVG pixels are 0.75 bp. Unicode labels may need LuaLaTeX and an appropriate font.",
r"\begingroup",
r"\begin{tikzpicture}[x=0.75bp,y=-0.75bp]",
rf"\path[use as bounding box] (0,0) rectangle ({_n(width)},{_n(height)});",
rf"\clip (0,0) rectangle ({_n(width)},{_n(height)});",
]
for child in root:
lines.extend(_draw(child, _Transform(), width, height))
lines.extend([r"\end{tikzpicture}", r"\endgroup", ""])
return "\n".join(lines).encode("utf-8")