vibe-sketcherDocumentation
Source code for vibesketcher.server.figures
"""REST routes for cyclic-topology schematics, multi-panel figures and figure math (#247).
``POST /api/documents/{id}/periodic/{structure}/topology`` draws a periodic
structure of a document on its torus (the document is not changed);
``POST /api/periodic/topology`` draws the torus of a posted AICCM convention
record. ``POST /api/figures/panels`` composes posted figure SVGs into one
labelled grid, ``POST /api/figures/math`` renders one figure string and
``GET /api/figures/math`` lists the supported symbol commands.
``POST /api/figures/diagram`` draws a workflow or taxonomy diagram from a
``vibesketcher.diagram/1`` spec and ``GET /api/figures/diagram/schema`` gives
the spec's JSON schema.
"""
from __future__ import annotations
from typing import Any, Literal
from fastapi import APIRouter, HTTPException, Response
from pydantic import BaseModel, ConfigDict, Field, ValidationError
from vibesketcher.server.store import NotFound, Store
_MEDIA = {"svg": "image/svg+xml", "pdf": "application/pdf", "png": "image/png"}
[docs]
class TopologyRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
repeats: tuple[int, int, int]
options: dict[str, Any] = Field(default_factory=dict)
format: Literal["svg", "pdf", "png"] = "svg"
dpi: int = 300
[docs]
class RecordTopologyRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
record: dict[str, Any]
options: dict[str, Any] = Field(default_factory=dict)
format: Literal["svg", "pdf", "png"] = "svg"
dpi: int = 300
[docs]
class PanelsRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
panels: list[dict[str, Any]] = Field(min_length=1, max_length=26)
options: dict[str, Any] = Field(default_factory=dict)
format: Literal["svg", "pdf", "png"] = "svg"
dpi: int = 300
[docs]
class MathRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
text: str
size: float = 12.0
format: Literal["svg", "pdf", "png"] = "svg"
dpi: int = 300
[docs]
class DiagramRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
spec: dict[str, Any]
format: Literal["svg", "pdf", "png"] = "svg"
dpi: int = 300
def _errors(error: ValidationError) -> HTTPException:
return HTTPException(422, {"errors": [e["msg"] for e in error.errors()]})
[docs]
def router(store: Store) -> APIRouter:
routes = APIRouter(prefix="/api", tags=["figures"])
def draw(make: Any, fmt: str) -> Response:
from vibesketcher.render import RenderUnavailable
try:
data = make()
except ValidationError as error:
raise _errors(error) from None
except ValueError as error:
raise HTTPException(422, {"errors": [str(error)]}) from None
except RenderUnavailable as error:
raise HTTPException(503, {"errors": [str(error)]}) from None
return Response(data, media_type=_MEDIA[fmt])
@routes.post("/documents/{identifier}/periodic/{structure}/topology")
def periodic_topology(identifier: str, structure: str, request: TopologyRequest) -> Response:
"""The ring or torus schematic of a periodic structure on ``repeats``."""
from vibesketcher.render.cyclic_topology import TopologyOptions, topology_figure
try:
entry = store.get(identifier)
except NotFound:
raise HTTPException(404, f"no document {identifier!r}") from None
found = {s.id: s for s in entry.document.periodic_structures}
if structure not in found:
raise HTTPException(404, "periodic structure not found")
return draw(
lambda: topology_figure(
found[structure],
request.repeats,
TopologyOptions.model_validate(request.options),
request.format,
dpi=request.dpi,
),
request.format,
)
@routes.post("/periodic/topology")
def record_topology(request: RecordTopologyRequest) -> Response:
"""The ring or torus schematic of an AICCM convention record's torus."""
from vibesketcher.render.cyclic_topology import (
TopologyOptions,
topology_figure_from_record,
)
return draw(
lambda: topology_figure_from_record(
request.record,
TopologyOptions.model_validate(request.options),
request.format,
dpi=request.dpi,
),
request.format,
)
@routes.post("/figures/panels")
def figure_panels(request: PanelsRequest) -> Response:
"""Posted panel SVGs as one labelled grid at a stated physical width."""
from vibesketcher.render.panels import Panel, PanelOptions, compose_panels
return draw(
lambda: compose_panels(
[Panel.model_validate(p) for p in request.panels],
PanelOptions.model_validate(request.options),
request.format,
dpi=request.dpi,
),
request.format,
)
@routes.post("/figures/math")
def figure_math(request: MathRequest) -> Response:
"""One figure string (plain text with ``$...$`` math) as a tight figure."""
from vibesketcher.render.mathtext import math_svg
def make() -> bytes:
svg = math_svg(request.text, request.size)
if request.format == "svg":
return svg
from vibesketcher.render.publication import convert
return convert(svg, request.format, dpi=request.dpi)
return draw(make, request.format)
@routes.get("/figures/math")
def figure_math_subset() -> dict[str, Any]:
"""The supported math subset: symbol commands, structures and limits."""
from vibesketcher.render import mathtext
return {
"symbols": dict(mathtext.SYMBOLS),
"structures": [
"_",
"^",
"\\frac{a}{b}",
"\\overline{x}",
"\\bar{x}",
"\\mathrm{...}",
"\\text{...}",
], # fmt: skip
"spaces": ["\\,", "\\;", "\\quad", "\\ ", "~"],
"escapes": ["\\{", "\\}", "\\_", "\\^", "\\$", "\\%", "\\#", "\\&"],
"max_length": mathtext.MAX_LENGTH,
"max_depth": mathtext.MAX_DEPTH,
}
@routes.post("/figures/diagram")
def figure_diagram(request: DiagramRequest) -> Response:
"""A workflow or taxonomy diagram drawn from its spec."""
from vibesketcher.render.diagram import diagram, load_spec
return draw(
lambda: diagram(load_spec(request.spec), request.format, dpi=request.dpi),
request.format,
)
@routes.get("/figures/diagram/schema")
def figure_diagram_schema() -> dict[str, Any]:
"""The JSON schema of a diagram spec (``vibesketcher.diagram/1``)."""
from vibesketcher.render.diagram import DiagramSpec
return DiagramSpec.model_json_schema(by_alias=True)
return routes