vibe-sketcherDocumentation
Source code for vibesketcher.server.solid_reactions
"""REST routes for solid-state and surface reaction schemes (#192).
Edits are checked against the document revision and recorded; a step that
does not balance without a stated open reservoir is answered with 422 and
the reasons. The check route is a dry run.
"""
from __future__ import annotations
from typing import Any
from fastapi import APIRouter, HTTPException, Response
from pydantic import BaseModel, ConfigDict, Field, ValidationError
from vibesketcher.document.model import Document
from vibesketcher.server.documents import (
DocumentResponse,
RevisionRequest,
_response,
_with_edit,
)
from vibesketcher.server.store import Conflict, Entry, NotFound, Store
[docs]
class SchemeEditRequest(RevisionRequest):
participants: list[dict[str, Any]] = Field(default_factory=list, max_length=1000)
steps: list[dict[str, Any]] = Field(default_factory=list, max_length=500)
replace: bool = False
[docs]
class SchemeRemoveRequest(RevisionRequest):
ids: list[str] = Field(min_length=1, max_length=1500)
[docs]
class StepCheckRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
step: dict[str, Any]
participants: list[dict[str, Any]] = Field(default_factory=list, max_length=1000)
[docs]
class SchemeFigureRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
steps: list[str] | None = None
style: str | None = None
def _errors(error: ValidationError) -> list[str]:
return [f"{'.'.join(str(x) for x in e['loc'])}: {e['msg']}" for e in error.errors()]
[docs]
def router(store: Store) -> APIRouter:
routes = APIRouter(prefix="/api", tags=["solid reactions"])
def entry_or_404(identifier: str) -> Entry:
try:
return store.get(identifier)
except NotFound:
raise HTTPException(404, f"no document {identifier!r}") from None
def commit(entry: Entry, document: Document, request: RevisionRequest, summary: str) -> Any:
if request.revision != entry.document.revision:
raise HTTPException(409, {"revision": entry.document.revision})
try:
replaced = store.replace(
entry.id,
_with_edit(document, request, summary),
expected=request.revision,
warnings=entry.warnings,
)
except Conflict as error:
raise HTTPException(409, {"message": str(error), "revision": error.current}) from None
return _response(replaced)
@routes.get("/solid-reactions/examples")
def examples() -> dict[str, str]:
"""The worked schemes by name, with a one-line description each."""
from vibesketcher.document.solid_reactions import EXAMPLES
return {name: str(value["description"]) for name, value in EXAMPLES.items()}
@routes.get("/solid-reactions/examples/{name}")
def example(name: str) -> dict[str, Any]:
from vibesketcher.document.solid_reactions import example as get
try:
return get(name)
except ValueError as error:
raise HTTPException(404, str(error)) from None
@routes.get("/documents/{identifier}/solid-reactions")
def scheme_report(identifier: str) -> dict[str, Any]:
"""Participants with formula, charge and sites; steps with balances and site hops."""
from vibesketcher.document.solid_reactions import report
entry = entry_or_404(identifier)
return {"revision": entry.document.revision, **report(entry.document)}
@routes.post("/documents/{identifier}/solid-reactions")
def scheme_add(identifier: str, request: SchemeEditRequest) -> DocumentResponse:
"""Add (or with replace, change) participants and steps as one checked edit."""
from vibesketcher.document.solid_reactions import add
if not request.participants and not request.steps:
raise HTTPException(422, {"errors": ["give participants or steps"]})
entry = entry_or_404(identifier)
try:
document = add(entry.document, participants=request.participants,
steps=request.steps, replace=request.replace) # fmt: skip
except ValidationError as error:
raise HTTPException(422, {"errors": _errors(error)}) from None
except ValueError as error:
raise HTTPException(422, {"errors": str(error).split("; ")}) from None
names = [str(x.get("id")) for x in (*request.participants, *request.steps)]
response: DocumentResponse = commit(
entry, document, request, "Edited the solid reaction scheme (" + ", ".join(names) + ")"
)
return response
@routes.post("/documents/{identifier}/solid-reactions/remove")
def scheme_remove(identifier: str, request: SchemeRemoveRequest) -> DocumentResponse:
from vibesketcher.document.solid_reactions import remove
entry = entry_or_404(identifier)
try:
document = remove(entry.document, request.ids)
except ValueError as error:
raise HTTPException(422, {"errors": [str(error)]}) from None
response: DocumentResponse = commit(
entry, document, request, "Removed " + ", ".join(request.ids) + " from the scheme"
)
return response
@routes.post("/documents/{identifier}/solid-reactions/example")
def scheme_example(identifier: str, request: SchemeExampleRequest) -> DocumentResponse:
from vibesketcher.document.solid_reactions import apply_example
entry = entry_or_404(identifier)
try:
document = apply_example(entry.document, request.name)
except ValueError as error:
raise HTTPException(422, {"errors": [str(error)]}) from None
response: DocumentResponse = commit(
entry, document, request, f"Added the {request.name} scheme"
)
return response
@routes.post("/documents/{identifier}/solid-reactions/check")
def scheme_check(identifier: str, request: StepCheckRequest) -> dict[str, Any]:
"""Dry run: the balance and refusals of a step; the document is unchanged."""
from vibesketcher.document.solid_reactions import check_step
entry = entry_or_404(identifier)
try:
result = check_step(entry.document, request.step, request.participants)
except ValidationError as error:
raise HTTPException(422, {"errors": _errors(error)}) from None
except ValueError as error:
raise HTTPException(422, {"errors": [str(error)]}) from None
return {"revision": entry.document.revision, **result}
@routes.post("/documents/{identifier}/solid-reactions/figure")
def scheme_figure(identifier: str, request: SchemeFigureRequest) -> Response:
"""The scheme as an editable SVG with one text element per participant."""
from vibesketcher.render.solid_reactions import scheme_svg
entry = entry_or_404(identifier)
try:
svg = scheme_svg(entry.document, request.steps, style=request.style)
except (ValueError, KeyError) as error:
raise HTTPException(422, {"errors": [str(error)]}) from None
return Response(svg.encode("utf-8"), media_type="image/svg+xml")
return routes