sciview 0.3.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.
- sciview/__init__.py +33 -0
- sciview/__main__.py +6 -0
- sciview/agent/__init__.py +4 -0
- sciview/agent/mcp.py +202 -0
- sciview/agent/tools.py +434 -0
- sciview/cli.py +238 -0
- sciview/engine/__init__.py +8 -0
- sciview/engine/assets.py +503 -0
- sciview/engine/camera.py +86 -0
- sciview/engine/color.py +136 -0
- sciview/engine/easing.py +103 -0
- sciview/engine/mathexpr.py +82 -0
- sciview/engine/surface.py +660 -0
- sciview/engine/text.py +344 -0
- sciview/engine/units.py +68 -0
- sciview/export.py +292 -0
- sciview/figures.py +80 -0
- sciview/fonts/Inter-Bold.otf +0 -0
- sciview/fonts/Inter-Medium.otf +0 -0
- sciview/fonts/Inter-Regular.otf +0 -0
- sciview/fonts/OFL-Inter.txt +93 -0
- sciview/fonts/OFL-Poppins.txt +93 -0
- sciview/fonts/Poppins-Bold.ttf +0 -0
- sciview/fonts/Poppins-Light.ttf +0 -0
- sciview/fonts/Poppins-Medium.ttf +0 -0
- sciview/fonts/Poppins-Regular.ttf +0 -0
- sciview/gui/favicon.svg +1 -0
- sciview/gui/index.html +106 -0
- sciview/gui/js/actions.js +374 -0
- sciview/gui/js/api.js +53 -0
- sciview/gui/js/dialogs.js +288 -0
- sciview/gui/js/geom.js +133 -0
- sciview/gui/js/icons.js +98 -0
- sciview/gui/js/inspector.js +925 -0
- sciview/gui/js/main.js +338 -0
- sciview/gui/js/state.js +524 -0
- sciview/gui/js/timeline.js +391 -0
- sciview/gui/js/ui.js +124 -0
- sciview/gui/js/viewport.js +250 -0
- sciview/gui/style.css +380 -0
- sciview/model/__init__.py +16 -0
- sciview/model/base.py +607 -0
- sciview/model/charts.py +515 -0
- sciview/model/context.py +212 -0
- sciview/model/data.py +51 -0
- sciview/model/figure.py +75 -0
- sciview/model/group.py +35 -0
- sciview/model/molecule.py +250 -0
- sciview/model/objects2d.py +484 -0
- sciview/model/objects3d.py +774 -0
- sciview/model/optics.py +345 -0
- sciview/model/plots.py +973 -0
- sciview/model/project.py +532 -0
- sciview/model/science.py +816 -0
- sciview/render.py +443 -0
- sciview/science/__init__.py +4 -0
- sciview/science/tomo.py +134 -0
- sciview/server.py +692 -0
- sciview/templates/clusters/assets/slice_neutron.png +0 -0
- sciview/templates/clusters/assets/slice_xray.png +0 -0
- sciview/templates/clusters/assets/voxels.csv +1401 -0
- sciview/templates/clusters/project.sciview.json +530 -0
- sciview/templates/data_story/project.sciview.json +638 -0
- sciview/templates/lattice/assets/lattice.csv +65 -0
- sciview/templates/lattice/project.sciview.json +202 -0
- sciview/templates/neutron_imaging/assets/radiograph.png +0 -0
- sciview/templates/neutron_imaging/project.sciview.json +341 -0
- sciview/templates/optics/project.sciview.json +238 -0
- sciview/templates/title_card/project.sciview.json +193 -0
- sciview/templates/tomography/assets/sample.npy +0 -0
- sciview/templates/tomography/assets/slice.png +0 -0
- sciview/templates/tomography/project.sciview.json +415 -0
- sciview/templates/waves/project.sciview.json +245 -0
- sciview-0.3.0.dist-info/METADATA +236 -0
- sciview-0.3.0.dist-info/RECORD +81 -0
- sciview-0.3.0.dist-info/WHEEL +5 -0
- sciview-0.3.0.dist-info/entry_points.txt +2 -0
- sciview-0.3.0.dist-info/licenses/LICENSE +24 -0
- sciview-0.3.0.dist-info/licenses/src/sciview/fonts/OFL-Inter.txt +93 -0
- sciview-0.3.0.dist-info/licenses/src/sciview/fonts/OFL-Poppins.txt +93 -0
- sciview-0.3.0.dist-info/top_level.txt +1 -0
sciview/__init__.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""SciView: make clear, beautiful scientific explainer videos.
|
|
2
|
+
|
|
3
|
+
Quick start::
|
|
4
|
+
|
|
5
|
+
import sciview as sv
|
|
6
|
+
|
|
7
|
+
film = sv.Project(duration=8, title="Neutron imaging")
|
|
8
|
+
src = film.add("box", name="Source", center=(-60, 0, 0), size=(14, 14, 14), edge_color="gold",
|
|
9
|
+
fill_color="gold", label="neutron source")
|
|
10
|
+
film.add("beam", source=(-53, 0, 0), target=(0, 0, 0), start=1.0)
|
|
11
|
+
film.add("title", text="Neutron imaging", subtitle="How a radiograph is made")
|
|
12
|
+
film.camera.key("azimuth", 0, -70).key("azimuth", 8, -40)
|
|
13
|
+
film.render("neutrons.mp4")
|
|
14
|
+
|
|
15
|
+
Open the graphical editor with ``sciview edit`` in a terminal.
|
|
16
|
+
"""
|
|
17
|
+
from .model import REGISTRY, CameraRig, Project, Prop, SceneObject, all_schemas
|
|
18
|
+
from .render import Renderer
|
|
19
|
+
|
|
20
|
+
__version__ = "0.3.0"
|
|
21
|
+
|
|
22
|
+
__all__ = ["Project", "SceneObject", "Prop", "CameraRig", "Renderer", "REGISTRY", "all_schemas",
|
|
23
|
+
"object_types", "load", "__version__"]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def object_types() -> list[str]:
|
|
27
|
+
"""Names of all object types that ``Project.add`` accepts."""
|
|
28
|
+
return sorted(REGISTRY)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def load(path) -> Project:
|
|
32
|
+
"""Open a project file."""
|
|
33
|
+
return Project.load(path)
|
sciview/__main__.py
ADDED
sciview/agent/mcp.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
"""SciView as an MCP server, so AI assistants (Claude Desktop, LM Studio, Ollama front-ends, any MCP
|
|
2
|
+
client) can build films with the tools in :mod:`sciview.agent.tools`.
|
|
3
|
+
|
|
4
|
+
It speaks JSON-RPC 2.0 over standard input and output, one message per line, as the Model Context
|
|
5
|
+
Protocol's stdio transport describes; nothing else is written to standard output.
|
|
6
|
+
|
|
7
|
+
sciview mcp film.sciview.json # edit the file; it is saved after every change
|
|
8
|
+
sciview mcp --editor http://localhost:8765 # drive a running editor: changes appear live,
|
|
9
|
+
# and Ctrl+Z there takes them back
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import base64
|
|
14
|
+
import json
|
|
15
|
+
import sys
|
|
16
|
+
import urllib.error
|
|
17
|
+
import urllib.request
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import IO
|
|
20
|
+
|
|
21
|
+
from .. import __version__
|
|
22
|
+
from ..model.project import Project
|
|
23
|
+
from .tools import MUTATING, TOOLS, FilmTools, ToolError
|
|
24
|
+
|
|
25
|
+
PROTOCOL_VERSIONS = ("2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05")
|
|
26
|
+
|
|
27
|
+
INSTRUCTIONS = """You are building a scientific explainer video in SciView.
|
|
28
|
+
Start with describe_film, and get_schema for any type before you use it. Times are seconds.
|
|
29
|
+
2D objects use pixels on the frame ((0, 0) is the top-left); 3D objects use scene units, z up.
|
|
30
|
+
Prefer place() and the user's own numbers and expressions; never invent scientific values: ask, or
|
|
31
|
+
use clearly marked placeholders. Locked objects and anything outside your scope are off limits.
|
|
32
|
+
After changing something, look at it with render_frame and fix what overlaps or leaves the frame."""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class FileBackend:
|
|
36
|
+
"""Tools on a project file; saved after every change (unless autosave is off)."""
|
|
37
|
+
|
|
38
|
+
def __init__(self, path: str | Path, scope: dict | None = None, autosave: bool = True):
|
|
39
|
+
self.path = Path(path)
|
|
40
|
+
project = Project.load(self.path) if self.path.exists() else Project(path=self.path)
|
|
41
|
+
self.tools = FilmTools(project, scope)
|
|
42
|
+
self.autosave = autosave
|
|
43
|
+
|
|
44
|
+
def call(self, name: str, args: dict) -> dict:
|
|
45
|
+
out = self.tools.call(name, args)
|
|
46
|
+
if name in MUTATING and self.autosave:
|
|
47
|
+
self.tools.project.save(self.path)
|
|
48
|
+
return out
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class EditorBackend:
|
|
52
|
+
"""Tools on the film open in a running SciView editor (sciview edit), through its local API."""
|
|
53
|
+
|
|
54
|
+
def __init__(self, url: str, scope: dict | None = None):
|
|
55
|
+
self.url = url.rstrip("/")
|
|
56
|
+
self.tools = FilmTools(Project(), scope)
|
|
57
|
+
|
|
58
|
+
def _req(self, method: str, path: str, body: dict | None = None):
|
|
59
|
+
data = None if body is None else json.dumps(body).encode()
|
|
60
|
+
req = urllib.request.Request(self.url + path, data=data, method=method,
|
|
61
|
+
headers={"X-SciView": "1", "Content-Type": "application/json"})
|
|
62
|
+
try:
|
|
63
|
+
with urllib.request.urlopen(req, timeout=60) as r:
|
|
64
|
+
return r.status, r.headers.get("Content-Type", ""), r.read()
|
|
65
|
+
except urllib.error.HTTPError as exc:
|
|
66
|
+
return exc.code, exc.headers.get("Content-Type", ""), exc.read()
|
|
67
|
+
except urllib.error.URLError as exc:
|
|
68
|
+
raise ToolError(f"cannot reach the SciView editor at {self.url}: {exc.reason}. Is 'sciview edit' running?") from None
|
|
69
|
+
|
|
70
|
+
def _load(self) -> int:
|
|
71
|
+
code, _, raw = self._req("GET", "/api/project")
|
|
72
|
+
if code != 200:
|
|
73
|
+
raise ToolError(f"the editor answered {code}")
|
|
74
|
+
st = json.loads(raw)
|
|
75
|
+
self.tools.project = Project.from_json(st["project"], st.get("path"))
|
|
76
|
+
return int(st["rev"])
|
|
77
|
+
|
|
78
|
+
def call(self, name: str, args: dict) -> dict:
|
|
79
|
+
if name == "render_frame":
|
|
80
|
+
t = float(args.get("time", 0))
|
|
81
|
+
scale = float(args.get("scale", 0.5))
|
|
82
|
+
code, ctype, raw = self._req("GET", f"/api/frame?t={t:.4f}&scale={min(max(scale, 0.1), 1.0)}")
|
|
83
|
+
if code != 200:
|
|
84
|
+
raise ToolError(f"the editor could not render: {raw[:200]!r}")
|
|
85
|
+
return {"jpeg": raw}
|
|
86
|
+
for _attempt in range(4):
|
|
87
|
+
rev = self._load()
|
|
88
|
+
before = len(self.tools.changes)
|
|
89
|
+
out = self.tools.call(name, args)
|
|
90
|
+
if name not in MUTATING:
|
|
91
|
+
return out
|
|
92
|
+
note = describe_change(name, args)
|
|
93
|
+
code, _, raw = self._req("POST", "/api/agent", {"project": self.tools.project.to_json(),
|
|
94
|
+
"base_rev": rev, "note": note})
|
|
95
|
+
if code == 200:
|
|
96
|
+
return out
|
|
97
|
+
del self.tools.changes[before:] # not applied: forget it, read the film again, retry
|
|
98
|
+
if code != 409:
|
|
99
|
+
raise ToolError(f"the editor refused the change ({code}): {raw[:200]!r}")
|
|
100
|
+
raise ToolError("the film keeps changing in the editor; try again in a moment")
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def describe_change(name: str, args: dict) -> str:
|
|
104
|
+
what = {"add_object": "added a {type}", "set_property": "set {name} of {id}", "add_keyframe": "animated {name} of {id}",
|
|
105
|
+
"remove_keyframe": "removed a keyframe of {id}", "set_timing": "changed the timing of {id}",
|
|
106
|
+
"delete": "deleted {id}", "group": "grouped objects", "place": "moved {id}"}.get(name, name)
|
|
107
|
+
try:
|
|
108
|
+
return "Assistant " + what.format(**{k: v for k, v in args.items() if isinstance(v, (str, int, float))})
|
|
109
|
+
except (KeyError, IndexError):
|
|
110
|
+
return "Assistant: " + name
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class Server:
|
|
114
|
+
"""JSON-RPC 2.0 message handling for the MCP tools (transport-independent)."""
|
|
115
|
+
|
|
116
|
+
def __init__(self, backend):
|
|
117
|
+
self.backend = backend
|
|
118
|
+
self.initialized = False
|
|
119
|
+
|
|
120
|
+
def tool_list(self) -> list[dict]:
|
|
121
|
+
return [{"name": n, "description": spec["description"], "inputSchema": spec["input"]} for n, spec in TOOLS.items()]
|
|
122
|
+
|
|
123
|
+
def handle(self, msg) -> dict | list | None:
|
|
124
|
+
if isinstance(msg, list):
|
|
125
|
+
out = [r for r in (self.handle(m) for m in msg) if r is not None]
|
|
126
|
+
return out or None
|
|
127
|
+
if not isinstance(msg, dict) or msg.get("jsonrpc") != "2.0" or "method" not in msg:
|
|
128
|
+
return _error(msg.get("id") if isinstance(msg, dict) else None, -32600, "invalid request")
|
|
129
|
+
method, mid, params = msg["method"], msg.get("id"), msg.get("params") or {}
|
|
130
|
+
is_note = "id" not in msg
|
|
131
|
+
try:
|
|
132
|
+
if method == "initialize":
|
|
133
|
+
asked = params.get("protocolVersion")
|
|
134
|
+
version = asked if asked in PROTOCOL_VERSIONS else PROTOCOL_VERSIONS[0]
|
|
135
|
+
self.initialized = True
|
|
136
|
+
return _result(mid, {"protocolVersion": version,
|
|
137
|
+
"capabilities": {"tools": {"listChanged": False}},
|
|
138
|
+
"serverInfo": {"name": "sciview", "title": "SciView", "version": __version__},
|
|
139
|
+
"instructions": INSTRUCTIONS})
|
|
140
|
+
if method.startswith("notifications/"):
|
|
141
|
+
return None
|
|
142
|
+
if method == "ping":
|
|
143
|
+
return _result(mid, {})
|
|
144
|
+
if method == "tools/list":
|
|
145
|
+
return _result(mid, {"tools": self.tool_list()})
|
|
146
|
+
if method == "tools/call":
|
|
147
|
+
return _result(mid, self.call_tool(params.get("name", ""), params.get("arguments") or {}))
|
|
148
|
+
if is_note:
|
|
149
|
+
return None
|
|
150
|
+
return _error(mid, -32601, f"method not found: {method}")
|
|
151
|
+
except Exception as exc: # never let one bad message stop the server
|
|
152
|
+
return None if is_note else _error(mid, -32603, f"internal error: {exc}")
|
|
153
|
+
|
|
154
|
+
def call_tool(self, name: str, args: dict) -> dict:
|
|
155
|
+
if name not in TOOLS:
|
|
156
|
+
return {"content": [{"type": "text", "text": f"unknown tool {name!r}"}], "isError": True}
|
|
157
|
+
try:
|
|
158
|
+
out = self.backend.call(name, args)
|
|
159
|
+
except ToolError as exc:
|
|
160
|
+
return {"content": [{"type": "text", "text": str(exc)}], "isError": True}
|
|
161
|
+
except (ValueError, KeyError, TypeError, OSError) as exc:
|
|
162
|
+
return {"content": [{"type": "text", "text": f"{type(exc).__name__}: {exc}"}], "isError": True}
|
|
163
|
+
content = []
|
|
164
|
+
if "png" in out or "jpeg" in out:
|
|
165
|
+
mime, raw = ("image/png", out.pop("png")) if "png" in out else ("image/jpeg", out.pop("jpeg"))
|
|
166
|
+
content.append({"type": "image", "data": base64.b64encode(raw).decode(), "mimeType": mime})
|
|
167
|
+
content.append({"type": "text", "text": json.dumps(out, ensure_ascii=False, default=str)})
|
|
168
|
+
return {"content": content, "isError": False, "structuredContent": out}
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _result(mid, result) -> dict:
|
|
172
|
+
return {"jsonrpc": "2.0", "id": mid, "result": result}
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _error(mid, code: int, message: str) -> dict:
|
|
176
|
+
return {"jsonrpc": "2.0", "id": mid, "error": {"code": code, "message": message}}
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def serve_stdio(backend, stdin: IO[str] | None = None, stdout: IO[str] | None = None) -> None:
|
|
180
|
+
"""Read JSON-RPC messages line by line until standard input closes."""
|
|
181
|
+
if stdin is None:
|
|
182
|
+
stdin = sys.stdin
|
|
183
|
+
if hasattr(stdin, "reconfigure"):
|
|
184
|
+
stdin.reconfigure(encoding="utf-8", errors="replace") # MCP messages are UTF-8 on every OS
|
|
185
|
+
if stdout is None:
|
|
186
|
+
stdout = sys.stdout
|
|
187
|
+
if hasattr(stdout, "reconfigure"):
|
|
188
|
+
stdout.reconfigure(encoding="utf-8", newline="\n") # no \r\n on Windows
|
|
189
|
+
server = Server(backend)
|
|
190
|
+
for line in stdin:
|
|
191
|
+
line = line.strip()
|
|
192
|
+
if not line:
|
|
193
|
+
continue
|
|
194
|
+
try:
|
|
195
|
+
msg = json.loads(line)
|
|
196
|
+
except json.JSONDecodeError:
|
|
197
|
+
reply = _error(None, -32700, "parse error")
|
|
198
|
+
else:
|
|
199
|
+
reply = server.handle(msg)
|
|
200
|
+
if reply is not None:
|
|
201
|
+
stdout.write(json.dumps(reply, ensure_ascii=False) + "\n")
|
|
202
|
+
stdout.flush()
|