replicator-workshop 0.1.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.
- replicator/__init__.py +6 -0
- replicator/app.py +204 -0
- replicator/config.py +48 -0
- replicator/core/__init__.py +0 -0
- replicator/core/assembly.py +117 -0
- replicator/core/blender_link.py +161 -0
- replicator/core/critique.py +594 -0
- replicator/core/drawing.py +389 -0
- replicator/core/dxf.py +120 -0
- replicator/core/evaluate.py +439 -0
- replicator/core/explain.py +139 -0
- replicator/core/export.py +96 -0
- replicator/core/fit.py +170 -0
- replicator/core/importers.py +185 -0
- replicator/core/materials.py +104 -0
- replicator/core/ops_advanced.py +496 -0
- replicator/core/ops_engineering.py +223 -0
- replicator/core/physics.py +147 -0
- replicator/core/printers.py +100 -0
- replicator/core/program.py +298 -0
- replicator/core/render.py +145 -0
- replicator/core/reverse.py +350 -0
- replicator/core/robot.py +153 -0
- replicator/core/step.py +245 -0
- replicator/fixtures/gaming_pc_liquid.json +2259 -0
- replicator/fixtures/gas_generator_rocket.json +876 -0
- replicator/fixtures/gas_generator_rocket_aero.json +861 -0
- replicator/fixtures/house_two_bed.json +979 -0
- replicator/fixtures/quadcopter_drone.json +687 -0
- replicator/fixtures/raspberry_pi_5.json +884 -0
- replicator/fixtures/rocket_engine.json +652 -0
- replicator/fixtures/turbofan.json +931 -0
- replicator/fixtures/vector_engine.json +314 -0
- replicator/gpu.py +81 -0
- replicator/image3d/__init__.py +0 -0
- replicator/image3d/comfy.py +181 -0
- replicator/image3d/pipeline.py +208 -0
- replicator/image3d/sheet.py +154 -0
- replicator/knowledge/__init__.py +61 -0
- replicator/knowledge/car_wheel_corner.md +21 -0
- replicator/knowledge/desk_lamp.md +21 -0
- replicator/knowledge/desktop_pc.md +20 -0
- replicator/knowledge/electronics_board.md +21 -0
- replicator/knowledge/exoskeleton.md +21 -0
- replicator/knowledge/house.md +22 -0
- replicator/knowledge/light_aircraft.md +22 -0
- replicator/knowledge/multirotor_drone.md +25 -0
- replicator/knowledge/print_replica.md +13 -0
- replicator/knowledge/rocket_engine.md +27 -0
- replicator/knowledge/turbofan.md +23 -0
- replicator/llm/__init__.py +0 -0
- replicator/llm/client.py +424 -0
- replicator/llm/prompts/blueprint.md +28 -0
- replicator/llm/prompts/edit.md +15 -0
- replicator/llm/prompts/explain.md +37 -0
- replicator/llm/prompts/name_parts.md +13 -0
- replicator/llm/prompts/program.md +72 -0
- replicator/llm/prompts/research_queries.md +8 -0
- replicator/mcp_server.py +307 -0
- replicator/qml/Main.qml +874 -0
- replicator/qml/Replicator/UI/Chip.qml +17 -0
- replicator/qml/Replicator/UI/DockHeader.qml +27 -0
- replicator/qml/Replicator/UI/Icon.qml +118 -0
- replicator/qml/Replicator/UI/IconButton.qml +31 -0
- replicator/qml/Replicator/UI/Kbd.qml +18 -0
- replicator/qml/Replicator/UI/NumField.qml +69 -0
- replicator/qml/Replicator/UI/Pill.qml +28 -0
- replicator/qml/Replicator/UI/RCombo.qml +51 -0
- replicator/qml/Replicator/UI/RMenu.qml +42 -0
- replicator/qml/Replicator/UI/RSlider.qml +23 -0
- replicator/qml/Replicator/UI/Segmented.qml +63 -0
- replicator/qml/Replicator/UI/Swatch.qml +47 -0
- replicator/qml/Replicator/UI/Theme.qml +149 -0
- replicator/qml/Replicator/UI/qmldir +14 -0
- replicator/qml/panels/AgentPrompt.qml +53 -0
- replicator/qml/panels/AttributeManager.qml +171 -0
- replicator/qml/panels/Commander.qml +136 -0
- replicator/qml/panels/HolodeckPanel.qml +117 -0
- replicator/qml/panels/IssuesCard.qml +78 -0
- replicator/qml/panels/LedgerPanel.qml +110 -0
- replicator/qml/panels/MaterialShelf.qml +97 -0
- replicator/qml/panels/ObjectManager.qml +107 -0
- replicator/qml/panels/Preferences.qml +211 -0
- replicator/qml/panels/Presenter.qml +316 -0
- replicator/qml/panels/StatusBar.qml +77 -0
- replicator/qml/panels/Timeline.qml +149 -0
- replicator/qml/panels/Welcome.qml +126 -0
- replicator/qml/viewport/Callouts.qml +87 -0
- replicator/qml/viewport/EdgeMaterial.qml +16 -0
- replicator/qml/viewport/GridMaterial.qml +16 -0
- replicator/qml/viewport/HoloMaterial.qml +23 -0
- replicator/qml/viewport/NavGizmo.qml +72 -0
- replicator/qml/viewport/ReferenceMaterial.qml +17 -0
- replicator/qml/viewport/Viewport.qml +583 -0
- replicator/qt/__init__.py +0 -0
- replicator/qt/bridge.py +1427 -0
- replicator/qt/drawing_sheet.py +33 -0
- replicator/qt/envmap.py +40 -0
- replicator/qt/library.py +68 -0
- replicator/qt/mesh_geometry.py +167 -0
- replicator/qt/svg.py +41 -0
- replicator/research/__init__.py +0 -0
- replicator/research/lane.py +281 -0
- replicator/shaders/edge.frag +9 -0
- replicator/shaders/edge.vert +7 -0
- replicator/shaders/grid.frag +52 -0
- replicator/shaders/grid.vert +6 -0
- replicator/shaders/holo.frag +41 -0
- replicator/shaders/reference.frag +15 -0
- replicator/shaders/reference.vert +6 -0
- replicator/voice.py +120 -0
- replicator_workshop-0.1.0.dist-info/METADATA +410 -0
- replicator_workshop-0.1.0.dist-info/RECORD +118 -0
- replicator_workshop-0.1.0.dist-info/WHEEL +5 -0
- replicator_workshop-0.1.0.dist-info/entry_points.txt +3 -0
- replicator_workshop-0.1.0.dist-info/licenses/LICENSE +21 -0
- replicator_workshop-0.1.0.dist-info/licenses/vendor/mcp-for-blender/LICENSE +21 -0
- replicator_workshop-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""A drawing sheet on disk: the SVG from core.drawing, plus a PNG that Qt renders from it."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import time
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from ..core import assembly, drawing
|
|
10
|
+
from ..core.evaluate import Evaluator
|
|
11
|
+
from ..core.program import check
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def render_png(svg: str, png: Path, dpi: int = 150) -> Path:
|
|
15
|
+
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
|
16
|
+
from PySide6.QtGui import QGuiApplication
|
|
17
|
+
|
|
18
|
+
from .svg import render_png as qt_render
|
|
19
|
+
QGuiApplication.instance() or QGuiApplication([])
|
|
20
|
+
return qt_render(svg, png, drawing.SHEET, dpi)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def make(program_path: Path, out: Path, style: str = "blueprint", dpi: int = 150) -> tuple[Path, Path, float]:
|
|
24
|
+
program = check(json.loads(program_path.read_text()))
|
|
25
|
+
t0 = time.perf_counter()
|
|
26
|
+
shapes = Evaluator(program_path.parent).step(program)
|
|
27
|
+
svg = drawing.sheet_svg(program, shapes, assembly.components(program, shapes), style,
|
|
28
|
+
source="Replicator · " + program_path.name)
|
|
29
|
+
seconds = time.perf_counter() - t0
|
|
30
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
31
|
+
svg_path = out / f"{program_path.stem}.svg"
|
|
32
|
+
svg_path.write_text(svg)
|
|
33
|
+
return svg_path, render_png(svg, out / f"{program_path.stem}.png", dpi), seconds
|
replicator/qt/envmap.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""A procedural studio HDRI (equirectangular, RGBA32F) for the light probe: a soft grey dome, a bright overhead
|
|
2
|
+
soft box, two strip lights and a warm floor bounce. Metals need something to reflect; this is it, made locally."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
from PySide6.QtCore import QByteArray, QSize
|
|
7
|
+
from PySide6.QtQuick3D import QQuick3DTextureData
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def studio_hdri(w: int = 1024, h: int = 512) -> np.ndarray:
|
|
11
|
+
u = (np.arange(w) + 0.5) / w
|
|
12
|
+
v = (np.arange(h) + 0.5) / h
|
|
13
|
+
phi = (u * 2 - 1) * np.pi # longitude
|
|
14
|
+
theta = (0.5 - v) * np.pi # latitude, +pi/2 = up
|
|
15
|
+
P, T = np.meshgrid(phi, theta)
|
|
16
|
+
up = np.sin(T)
|
|
17
|
+
sky = np.clip(up, 0, 1)
|
|
18
|
+
col = np.zeros((h, w, 3), np.float32)
|
|
19
|
+
col += (0.55 + 0.35 * sky)[..., None] * np.array([0.92, 0.95, 1.0]) # dome
|
|
20
|
+
col += (np.clip(-up, 0, 1) ** 0.6)[..., None] * np.array([0.38, 0.34, 0.30]) # floor bounce
|
|
21
|
+
col *= np.where(up < 0, 0.6, 1.0)[..., None]
|
|
22
|
+
# overhead soft box
|
|
23
|
+
box = np.exp(-((T - 1.25) / 0.18) ** 2) * np.exp(-(P / 0.55) ** 2)
|
|
24
|
+
col += (box * 9.0)[..., None]
|
|
25
|
+
# two vertical strip lights, left and right of the key
|
|
26
|
+
for c, s in ((-1.9, 5.0), (1.6, 3.5)):
|
|
27
|
+
strip = np.exp(-((P - c) / 0.07) ** 2) * (np.abs(T - 0.25) < 0.55)
|
|
28
|
+
col += (strip * s)[..., None]
|
|
29
|
+
rgba = np.concatenate([col, np.ones((h, w, 1), np.float32)], axis=2)
|
|
30
|
+
return np.ascontiguousarray(rgba[::-1]) # Qt textures start at the bottom row
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class EnvMap(QQuick3DTextureData):
|
|
34
|
+
def __init__(self):
|
|
35
|
+
super().__init__()
|
|
36
|
+
img = studio_hdri()
|
|
37
|
+
self.setSize(QSize(img.shape[1], img.shape[0]))
|
|
38
|
+
self.setFormat(QQuick3DTextureData.Format.RGBA32F)
|
|
39
|
+
self.setHasTransparency(False)
|
|
40
|
+
self.setTextureData(QByteArray(img.tobytes()))
|
replicator/qt/library.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""What the start screen offers: the bundled examples, the user's recent builds and reverse-engineering projects.
|
|
2
|
+
Only the head of each JSON file is parsed for the name and step count, and only the newest few files are read."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import time
|
|
7
|
+
from functools import lru_cache
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from .. import FIXTURES
|
|
11
|
+
from ..image3d.pipeline import OUT as IMAGE3D_OUT
|
|
12
|
+
|
|
13
|
+
RECENT_LIMIT = 8
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _row(path: Path, kind: str) -> dict | None:
|
|
17
|
+
try:
|
|
18
|
+
prog = json.loads(path.read_text())
|
|
19
|
+
ops = prog["ops"]
|
|
20
|
+
except (OSError, ValueError, KeyError, TypeError):
|
|
21
|
+
return None
|
|
22
|
+
kinds: dict[str, int] = {}
|
|
23
|
+
for op in ops:
|
|
24
|
+
kinds[op.get("op", "?")] = kinds.get(op.get("op", "?"), 0) + 1
|
|
25
|
+
comps = {op.get("component") or op.get("part") or op["id"] for op in ops}
|
|
26
|
+
top = sorted(kinds, key=lambda k: -kinds[k])[:3]
|
|
27
|
+
mt = path.stat().st_mtime
|
|
28
|
+
return {"path": str(path), "name": prog.get("name") or path.stem, "kind": kind, "steps": len(ops),
|
|
29
|
+
"components": len(comps), "ops": ", ".join(top), "mtime": mt,
|
|
30
|
+
"when": time.strftime("%d %b %H:%M", time.localtime(mt)),
|
|
31
|
+
"summary": ((prog.get("blueprint") or {}).get("summary") or "")[:160]}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def examples() -> list[dict]:
|
|
35
|
+
rows = [_row(p, "example") for p in sorted(FIXTURES.glob("*.json"))]
|
|
36
|
+
return [r for r in rows if r]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def recents(out: Path) -> list[dict]:
|
|
40
|
+
files: list[tuple[Path, str]] = [(p, "dream") for p in out.glob("*.json")]
|
|
41
|
+
files += [(p, "reverse") for p in (out / "reverse").glob("*/program.json")]
|
|
42
|
+
files += [(p, "image") for p in IMAGE3D_OUT.glob("*/program.json")]
|
|
43
|
+
files.sort(key=lambda t: -t[0].stat().st_mtime)
|
|
44
|
+
rows, seen = [], set()
|
|
45
|
+
for p, kind in files[:RECENT_LIMIT * 4]: # repeated runs of one subject show once, newest first
|
|
46
|
+
r = _row(p, kind)
|
|
47
|
+
if r and (kind, r["name"]) not in seen:
|
|
48
|
+
seen.add((kind, r["name"]))
|
|
49
|
+
rows.append(r)
|
|
50
|
+
if len(rows) == RECENT_LIMIT:
|
|
51
|
+
break
|
|
52
|
+
return rows
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@lru_cache(maxsize=64)
|
|
56
|
+
def figure_extent(path: Path) -> tuple[float, float]:
|
|
57
|
+
"""How much of a reference view's height the figure fills, and where its middle sits (0 top .. 1 bottom).
|
|
58
|
+
The viewport uses it to stand the picture at exactly the model's height."""
|
|
59
|
+
import numpy as np
|
|
60
|
+
from PIL import Image
|
|
61
|
+
try:
|
|
62
|
+
a = np.asarray(Image.open(path).convert("L").resize((128, 128)))
|
|
63
|
+
except OSError:
|
|
64
|
+
return 0.7, 0.5
|
|
65
|
+
rows = np.nonzero((a < 235).sum(axis=1) > 1)[0]
|
|
66
|
+
if len(rows) < 4:
|
|
67
|
+
return 0.7, 0.5
|
|
68
|
+
return float((rows[-1] - rows[0] + 1) / 128), float((rows[0] + rows[-1] + 1) / 2 / 128)
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""Viewport geometry: a solid (positions + normals split at sharp edges) and its feature lines (C4D 'lines' look)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
from PySide6.QtCore import Property, QByteArray, QObject, Signal
|
|
6
|
+
from PySide6.QtGui import QColor, QVector3D
|
|
7
|
+
from PySide6.QtQuick3D import QQuick3DGeometry
|
|
8
|
+
|
|
9
|
+
A = QQuick3DGeometry.Attribute
|
|
10
|
+
SHARP_DEG = 35.0
|
|
11
|
+
EDGE_DEG = 28.0
|
|
12
|
+
MAX_EDGE_TRIS = 250_000
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def mesh_arrays(m) -> tuple[np.ndarray, np.ndarray]:
|
|
16
|
+
"""Interleaved [x y z nx ny nz] float32 and uint32 indices."""
|
|
17
|
+
mn = m.calculate_normals(0, SHARP_DEG).to_mesh()
|
|
18
|
+
vp = np.asarray(mn.vert_properties, np.float32)
|
|
19
|
+
tri = np.asarray(mn.tri_verts, np.uint32)
|
|
20
|
+
if vp.shape[1] >= 6:
|
|
21
|
+
return np.ascontiguousarray(vp[:, :6]), tri
|
|
22
|
+
p = vp[:, :3][tri.reshape(-1)]
|
|
23
|
+
a, b, c = p[0::3], p[1::3], p[2::3]
|
|
24
|
+
n = np.cross(b - a, c - a)
|
|
25
|
+
n /= np.linalg.norm(n, axis=1, keepdims=True) + 1e-12
|
|
26
|
+
verts = np.hstack([p, np.repeat(n, 3, axis=0)]).astype(np.float32)
|
|
27
|
+
return verts, np.arange(len(p), dtype=np.uint32).reshape(-1, 3)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def feature_edges(V: np.ndarray, F: np.ndarray) -> np.ndarray:
|
|
31
|
+
"""Line segments [k, 2, 3] along creases sharper than EDGE_DEG and open boundaries (welded by position)."""
|
|
32
|
+
if len(F) == 0 or len(F) > MAX_EDGE_TRIS:
|
|
33
|
+
return np.zeros((0, 2, 3), np.float32)
|
|
34
|
+
P = V[:, :3]
|
|
35
|
+
key = np.round(P / (np.ptp(P, axis=0).max() * 1e-6 + 1e-12)).astype(np.int64)
|
|
36
|
+
_, weld = np.unique(key, axis=0, return_inverse=True)
|
|
37
|
+
Fw = weld.reshape(-1)[F]
|
|
38
|
+
a, b, c = (P[F[:, i]] for i in range(3))
|
|
39
|
+
fn = np.cross(b - a, c - a)
|
|
40
|
+
fn /= np.linalg.norm(fn, axis=1, keepdims=True) + 1e-12
|
|
41
|
+
e = np.concatenate([Fw[:, [0, 1]], Fw[:, [1, 2]], Fw[:, [2, 0]]])
|
|
42
|
+
eraw = np.concatenate([F[:, [0, 1]], F[:, [1, 2]], F[:, [2, 0]]])
|
|
43
|
+
face = np.tile(np.arange(len(F)), 3)
|
|
44
|
+
es = np.sort(e, axis=1)
|
|
45
|
+
order = np.lexsort((es[:, 1], es[:, 0]))
|
|
46
|
+
es, face, eraw = es[order], face[order], eraw[order]
|
|
47
|
+
same = np.all(es[1:] == es[:-1], axis=1)
|
|
48
|
+
keep = []
|
|
49
|
+
i, n = 0, len(es)
|
|
50
|
+
cos_t = np.cos(np.radians(EDGE_DEG))
|
|
51
|
+
idx = np.nonzero(same)[0]
|
|
52
|
+
paired = np.zeros(n, bool)
|
|
53
|
+
paired[idx] = True
|
|
54
|
+
paired[idx + 1] = True
|
|
55
|
+
# boundaries: edges with no partner
|
|
56
|
+
keep.append(eraw[~paired])
|
|
57
|
+
# creases: partner faces whose normals differ by more than EDGE_DEG
|
|
58
|
+
sharp = idx[np.einsum("ij,ij->i", fn[face[idx]], fn[face[idx + 1]]) < cos_t]
|
|
59
|
+
keep.append(eraw[sharp])
|
|
60
|
+
E = np.concatenate(keep) if keep else np.zeros((0, 2), np.uint32)
|
|
61
|
+
return np.ascontiguousarray(P[E].astype(np.float32))
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class EdgeGeometry(QQuick3DGeometry):
|
|
65
|
+
def __init__(self, data: QByteArray, lo, hi):
|
|
66
|
+
super().__init__()
|
|
67
|
+
self.setVertexData(data)
|
|
68
|
+
self.setStride(12)
|
|
69
|
+
self.setPrimitiveType(QQuick3DGeometry.PrimitiveType.Lines)
|
|
70
|
+
self.addAttribute(A.Semantic.PositionSemantic, 0, A.ComponentType.F32Type)
|
|
71
|
+
self.setBounds(QVector3D(*lo), QVector3D(*hi))
|
|
72
|
+
self.update()
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class MeshGeometry(QQuick3DGeometry):
|
|
76
|
+
"""One leaf shape. phase: 0 static, 1 arriving (materialize), 2 leaving (dematerialize, reverse playback).
|
|
77
|
+
|
|
78
|
+
The bridge caches these per shape, but Qt Quick 3D draws a geometry object only for the first Model that adopts
|
|
79
|
+
it: once that Model is destroyed (every step change rebuilds the Repeater3D delegates) a new Model holding the same
|
|
80
|
+
object renders nothing, and update() does not bring it back. So the cache keeps the computed buffers and
|
|
81
|
+
`for_step` hands each step a fresh object built from them (cheap: the byte arrays are shared, not recomputed)."""
|
|
82
|
+
changed = Signal()
|
|
83
|
+
|
|
84
|
+
def __init__(self, shape, material: dict | None, phase: int, comp_color: str, comp_label: str, _from=None):
|
|
85
|
+
super().__init__()
|
|
86
|
+
if _from is not None: # a fresh Qt object over another one's buffers
|
|
87
|
+
self.__dict__.update({k: v for k, v in _from.__dict__.items() if k.startswith("_") or k == "materialName"})
|
|
88
|
+
else:
|
|
89
|
+
self._id, self._label, self._part, self._comp = shape.id, shape.label, shape.part, shape.component
|
|
90
|
+
self.materialName = ""
|
|
91
|
+
self._comp_color = QColor(comp_color)
|
|
92
|
+
self._comp_label = comp_label
|
|
93
|
+
self._offset = QVector3D(0, 0, 0)
|
|
94
|
+
mat = material or {}
|
|
95
|
+
c = mat.get("base_color", [0.72, 0.73, 0.76])
|
|
96
|
+
e = mat.get("emissive", [0, 0, 0])
|
|
97
|
+
self._color = QColor.fromRgbF(*[min(max(float(x), 0.0), 1.0) for x in c[:3]])
|
|
98
|
+
self._emissive = QColor.fromRgbF(*[min(max(float(x), 0.0), 1.0) for x in e[:3]])
|
|
99
|
+
self._metal = float(mat.get("metalness", 0.0))
|
|
100
|
+
self._rough = float(mat.get("roughness", 0.5))
|
|
101
|
+
self._opacity = min(max(float(mat.get("opacity", 1.0)), 0.05), 1.0)
|
|
102
|
+
verts, tri = mesh_arrays(shape.manifold)
|
|
103
|
+
self._tris = len(tri)
|
|
104
|
+
self._lo, self._hi = verts[:, :3].min(0), verts[:, :3].max(0)
|
|
105
|
+
self._vbytes = QByteArray(verts.tobytes())
|
|
106
|
+
self._ibytes = QByteArray(tri.astype(np.uint32).tobytes())
|
|
107
|
+
self._ebytes = QByteArray(np.ascontiguousarray(feature_edges(verts, tri).reshape(-1, 3)).tobytes())
|
|
108
|
+
self._phase = phase
|
|
109
|
+
self.setVertexData(self._vbytes)
|
|
110
|
+
self.setIndexData(self._ibytes)
|
|
111
|
+
self.setStride(24)
|
|
112
|
+
self.setPrimitiveType(QQuick3DGeometry.PrimitiveType.Triangles)
|
|
113
|
+
self.addAttribute(A.Semantic.PositionSemantic, 0, A.ComponentType.F32Type)
|
|
114
|
+
self.addAttribute(A.Semantic.NormalSemantic, 12, A.ComponentType.F32Type)
|
|
115
|
+
self.addAttribute(A.Semantic.IndexSemantic, 0, A.ComponentType.U32Type)
|
|
116
|
+
self.setBounds(QVector3D(*self._lo.tolist()), QVector3D(*self._hi.tolist()))
|
|
117
|
+
self.update()
|
|
118
|
+
self._edges = EdgeGeometry(self._ebytes, self._lo.tolist(), self._hi.tolist())
|
|
119
|
+
|
|
120
|
+
def for_step(self, phase: int) -> "MeshGeometry":
|
|
121
|
+
"""A new Qt geometry object over these cached buffers, for the next step's delegate."""
|
|
122
|
+
return MeshGeometry(None, None, phase, "", "", _from=self)
|
|
123
|
+
|
|
124
|
+
def set_offset(self, v) -> None:
|
|
125
|
+
self._offset = QVector3D(*v)
|
|
126
|
+
|
|
127
|
+
def _ro(t): # noqa: N805
|
|
128
|
+
return lambda f: Property(t, f, constant=True)
|
|
129
|
+
|
|
130
|
+
@_ro(str)
|
|
131
|
+
def shapeId(self): return self._id
|
|
132
|
+
@_ro(str)
|
|
133
|
+
def label(self): return self._label
|
|
134
|
+
@_ro(str)
|
|
135
|
+
def part(self): return self._part
|
|
136
|
+
@_ro(str)
|
|
137
|
+
def component(self): return self._comp
|
|
138
|
+
@_ro(str)
|
|
139
|
+
def componentLabel(self): return self._comp_label
|
|
140
|
+
@_ro(QColor)
|
|
141
|
+
def componentColor(self): return self._comp_color
|
|
142
|
+
@_ro(int)
|
|
143
|
+
def phase(self): return self._phase
|
|
144
|
+
@_ro(bool)
|
|
145
|
+
def fresh(self): return self._phase == 1
|
|
146
|
+
@_ro(QColor)
|
|
147
|
+
def baseColor(self): return self._color
|
|
148
|
+
@_ro(QColor)
|
|
149
|
+
def emissive(self): return self._emissive
|
|
150
|
+
@_ro(float)
|
|
151
|
+
def metalness(self): return self._metal
|
|
152
|
+
@_ro(float)
|
|
153
|
+
def roughness(self): return self._rough
|
|
154
|
+
@_ro(float)
|
|
155
|
+
def opacity(self): return self._opacity
|
|
156
|
+
@_ro(float)
|
|
157
|
+
def minY(self): return float(self._lo[1])
|
|
158
|
+
@_ro(float)
|
|
159
|
+
def maxY(self): return float(self._hi[1])
|
|
160
|
+
@_ro(QVector3D)
|
|
161
|
+
def center(self): return QVector3D(*((self._lo + self._hi) / 2).tolist())
|
|
162
|
+
@_ro(QVector3D)
|
|
163
|
+
def explodeOffset(self): return self._offset
|
|
164
|
+
@_ro(int)
|
|
165
|
+
def triangles(self): return self._tris
|
|
166
|
+
@_ro(QObject)
|
|
167
|
+
def edges(self): return self._edges
|
replicator/qt/svg.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""SVG to PNG with QtSvg (the blueprint sheets). Safe off the GUI thread: it paints into a QImage, not a window."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import re
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from PySide6.QtCore import QByteArray
|
|
8
|
+
from PySide6.QtGui import QFontDatabase, QImage, QPainter
|
|
9
|
+
from PySide6.QtSvg import QSvgRenderer
|
|
10
|
+
|
|
11
|
+
_FAMILY = re.compile(r'font-family="([^"]*)"')
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _one_family(css: str) -> str:
|
|
15
|
+
"""QtSvg reads a CSS family list as one name and falls back; hand it the first installed family instead."""
|
|
16
|
+
names = [n.strip().strip("'\"") for n in css.split(",")]
|
|
17
|
+
have = set(QFontDatabase.families())
|
|
18
|
+
for n in names:
|
|
19
|
+
if n in have:
|
|
20
|
+
return n
|
|
21
|
+
mono = "monospace" in names and "sans-serif" not in names
|
|
22
|
+
system = QFontDatabase.systemFont(QFontDatabase.SystemFont.FixedFont if mono else QFontDatabase.SystemFont.GeneralFont).family()
|
|
23
|
+
if system in have:
|
|
24
|
+
return system
|
|
25
|
+
# fontconfig can name a system font that is not installed (an alias such as Noto Sans); take a real one
|
|
26
|
+
kind = "Mono" if mono else "Sans"
|
|
27
|
+
return next((f for f in sorted(have) if kind in f and (mono or "Mono" not in f)), min(have, default=system))
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def render_png(svg: str, png: Path, size_mm: tuple[float, float], dpi: int = 150) -> Path:
|
|
31
|
+
svg = _FAMILY.sub(lambda m: f'font-family="{_one_family(m.group(1))}"', svg)
|
|
32
|
+
w, h = (round(v / 25.4 * dpi) for v in size_mm)
|
|
33
|
+
img = QImage(w, h, QImage.Format.Format_RGB32)
|
|
34
|
+
img.fill(0xFFFFFF)
|
|
35
|
+
painter = QPainter(img)
|
|
36
|
+
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
|
37
|
+
QSvgRenderer(QByteArray(svg.encode())).render(painter)
|
|
38
|
+
painter.end()
|
|
39
|
+
if not img.save(str(png)):
|
|
40
|
+
raise OSError(f"could not write {png}")
|
|
41
|
+
return png
|
|
File without changes
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
"""The research lane: a small, bounded web lookup that feeds Explain.
|
|
2
|
+
|
|
3
|
+
Replicator's models never answer "how does this work" from memory. Explain asks this lane instead: it searches,
|
|
4
|
+
reads a few pages, and hands the model a short numbered list of excerpts. The model may only state what an excerpt
|
|
5
|
+
says and must cite it; `core/explain.py` then checks every sentence against the excerpt it cites.
|
|
6
|
+
|
|
7
|
+
"Limited context" is literal. The lane has hard budgets (queries, pages, bytes per page, characters per excerpt,
|
|
8
|
+
characters in total), so one explanation costs a few kilobytes of reading and a few thousand tokens of context, and
|
|
9
|
+
a page can never flood the model. Pages are untrusted text: they are reduced to plain sentences, never executed,
|
|
10
|
+
and the prompt tells the model to treat them as quotations, not instructions.
|
|
11
|
+
|
|
12
|
+
Backends (all plain HTTPS GETs with a generic User-Agent, nothing about the user or the project is sent):
|
|
13
|
+
wikipedia the MediaWiki API: search, then the plain-text extract of each hit (no scraping needed)
|
|
14
|
+
searxng your own SearXNG instance (`search_url` in ~/.config/Replicator/services.json) for the wider web
|
|
15
|
+
Public search sites answer scripts with a bot check, and the lane does not try to get round one: without a
|
|
16
|
+
SearXNG address it reads Wikipedia only.
|
|
17
|
+
Only the search words leave the machine: the object's name and its part names.
|
|
18
|
+
"""
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import json
|
|
22
|
+
import math
|
|
23
|
+
import re
|
|
24
|
+
import time
|
|
25
|
+
import urllib.parse
|
|
26
|
+
import urllib.request
|
|
27
|
+
from dataclasses import asdict, dataclass, field
|
|
28
|
+
from html.parser import HTMLParser
|
|
29
|
+
|
|
30
|
+
UA = "Replicator-research/1.0 (local desktop app)"
|
|
31
|
+
TIMEOUT = 12
|
|
32
|
+
MAX_QUERIES = 4 # searches per explanation
|
|
33
|
+
MAX_PAGES = 6 # pages read per explanation
|
|
34
|
+
MAX_PAGE_BYTES = 400_000
|
|
35
|
+
EXCERPT_CHARS = 620 # one excerpt
|
|
36
|
+
EXCERPTS_PER_SOURCE = 2
|
|
37
|
+
CONTEXT_CHARS = 6400 # everything the model gets to read
|
|
38
|
+
STOP = set("a an the of and or to in on for with by from at as is are was were be been it its this that these those "
|
|
39
|
+
"which who whom what how why when where can could may might will would should than then also into over "
|
|
40
|
+
"under between not no but if so such their there his her they them we you your our has have had do does "
|
|
41
|
+
"did more most other some any each used use using one two new".split())
|
|
42
|
+
SKIP_HOSTS = ("youtube.", "facebook.", "twitter.", "x.com", "instagram.", "pinterest.", "tiktok.", "reddit.")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class Source:
|
|
47
|
+
n: int
|
|
48
|
+
title: str
|
|
49
|
+
url: str
|
|
50
|
+
domain: str
|
|
51
|
+
excerpts: list[str] = field(default_factory=list)
|
|
52
|
+
|
|
53
|
+
def as_dict(self) -> dict:
|
|
54
|
+
return asdict(self)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _get(url: str, limit: int = MAX_PAGE_BYTES) -> str:
|
|
58
|
+
if not url.lower().startswith(("https://", "http://")):
|
|
59
|
+
raise ValueError("only http(s) pages are read")
|
|
60
|
+
req = urllib.request.Request(url, headers={"User-Agent": UA, "Accept-Language": "en"})
|
|
61
|
+
_pace(urllib.parse.urlparse(url).netloc)
|
|
62
|
+
with urllib.request.urlopen(req, timeout=TIMEOUT) as r:
|
|
63
|
+
ctype = r.headers.get("Content-Type", "")
|
|
64
|
+
if "html" not in ctype and "json" not in ctype and "text" not in ctype:
|
|
65
|
+
raise ValueError(f"not a text page ({ctype})")
|
|
66
|
+
raw = r.read(limit)
|
|
67
|
+
return raw.decode(r.headers.get_content_charset() or "utf-8", "replace")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
_last: dict[str, float] = {}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _pace(host: str, gap: float = 0.6) -> None:
|
|
74
|
+
"""Be a polite client: never more than one request per `gap` seconds to the same host."""
|
|
75
|
+
wait = _last.get(host, 0.0) + gap - time.monotonic()
|
|
76
|
+
if wait > 0:
|
|
77
|
+
time.sleep(wait)
|
|
78
|
+
_last[host] = time.monotonic()
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class _Text(HTMLParser):
|
|
82
|
+
"""HTML to readable text: paragraphs, headings and list items; scripts, styles, nav and footers dropped."""
|
|
83
|
+
DROP = {"script", "style", "noscript", "nav", "footer", "header", "aside", "form", "svg", "button", "figure"}
|
|
84
|
+
BLOCK = {"p", "li", "h1", "h2", "h3", "h4", "td", "br", "div", "section", "article", "blockquote", "dd"}
|
|
85
|
+
|
|
86
|
+
def __init__(self):
|
|
87
|
+
super().__init__(convert_charrefs=True)
|
|
88
|
+
self.out: list[str] = []
|
|
89
|
+
self.skip = 0
|
|
90
|
+
self.title = ""
|
|
91
|
+
self._in_title = False
|
|
92
|
+
|
|
93
|
+
def handle_starttag(self, tag, attrs):
|
|
94
|
+
if tag in self.DROP:
|
|
95
|
+
self.skip += 1
|
|
96
|
+
elif tag == "title":
|
|
97
|
+
self._in_title = True
|
|
98
|
+
elif tag in self.BLOCK:
|
|
99
|
+
self.out.append("\n")
|
|
100
|
+
|
|
101
|
+
def handle_endtag(self, tag):
|
|
102
|
+
if tag in self.DROP and self.skip:
|
|
103
|
+
self.skip -= 1
|
|
104
|
+
elif tag == "title":
|
|
105
|
+
self._in_title = False
|
|
106
|
+
elif tag in self.BLOCK:
|
|
107
|
+
self.out.append("\n")
|
|
108
|
+
|
|
109
|
+
def handle_data(self, data):
|
|
110
|
+
if self._in_title:
|
|
111
|
+
self.title += data
|
|
112
|
+
elif not self.skip:
|
|
113
|
+
self.out.append(data)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def page_text(markup: str) -> tuple[str, list[str]]:
|
|
117
|
+
"""(title, paragraphs) of an HTML page. Paragraphs shorter than a sentence are menu debris and are dropped."""
|
|
118
|
+
p = _Text()
|
|
119
|
+
try:
|
|
120
|
+
p.feed(markup)
|
|
121
|
+
except Exception: # noqa: BLE001 - broken markup: keep what was read so far
|
|
122
|
+
pass
|
|
123
|
+
paras = []
|
|
124
|
+
for block in "".join(p.out).split("\n"):
|
|
125
|
+
t = re.sub(r"\s+", " ", block).strip()
|
|
126
|
+
t = re.sub(r"\[\d+\]", "", t) # footnote markers
|
|
127
|
+
if len(t) >= 80 and t.count(" ") >= 12:
|
|
128
|
+
paras.append(t)
|
|
129
|
+
return re.sub(r"\s+", " ", p.title).strip(), paras
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def words(text: str) -> list[str]:
|
|
133
|
+
return [w for w in re.findall(r"[a-z][a-z0-9\-]{2,}", text.lower()) if w not in STOP]
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _stem(w: str) -> str:
|
|
137
|
+
for suf in ("ings", "ing", "ers", "er", "ed", "es", "s"):
|
|
138
|
+
if w.endswith(suf) and len(w) - len(suf) >= 4:
|
|
139
|
+
return w[: -len(suf)]
|
|
140
|
+
return w
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def stems(text: str) -> set[str]:
|
|
144
|
+
return {_stem(w) for w in words(text)}
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def rank(paragraphs: list[str], query_terms: set[str], k: int = EXCERPTS_PER_SOURCE) -> list[str]:
|
|
148
|
+
"""The k paragraphs that say the most about the query terms (BM25-style, favouring explanatory prose)."""
|
|
149
|
+
if not paragraphs:
|
|
150
|
+
return []
|
|
151
|
+
docs = [[_stem(w) for w in words(p)] for p in paragraphs]
|
|
152
|
+
n = len(docs)
|
|
153
|
+
df: dict[str, int] = {}
|
|
154
|
+
for d in docs:
|
|
155
|
+
for t in set(d):
|
|
156
|
+
df[t] = df.get(t, 0) + 1
|
|
157
|
+
avg = sum(len(d) for d in docs) / n or 1.0
|
|
158
|
+
scored = []
|
|
159
|
+
for i, d in enumerate(docs):
|
|
160
|
+
s = 0.0
|
|
161
|
+
for t in query_terms:
|
|
162
|
+
f = d.count(t)
|
|
163
|
+
if f:
|
|
164
|
+
idf = math.log(1 + (n - df[t] + 0.5) / (df[t] + 0.5))
|
|
165
|
+
s += idf * f * 2.2 / (f + 1.2 * (0.25 + 0.75 * len(d) / avg))
|
|
166
|
+
if re.search(r"\b(works?|because|so that|allows?|causes?|drives?|converts?|used to|function|purpose)\b",
|
|
167
|
+
paragraphs[i].lower()):
|
|
168
|
+
s *= 1.25 # prefer text that explains over text that lists
|
|
169
|
+
s *= 1.0 + 0.15 * (1 - i / n) # and the top of the page over the bottom
|
|
170
|
+
scored.append((s, i))
|
|
171
|
+
top = sorted((x for x in scored if x[0] > 0), reverse=True)[:k]
|
|
172
|
+
return [clip(paragraphs[i]) for _, i in sorted(top, key=lambda x: x[1])]
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def clip(text: str, limit: int = EXCERPT_CHARS) -> str:
|
|
176
|
+
"""Cut at a sentence end inside the budget."""
|
|
177
|
+
if len(text) <= limit:
|
|
178
|
+
return text
|
|
179
|
+
cut = text[:limit]
|
|
180
|
+
end = max(cut.rfind(". "), cut.rfind("; "))
|
|
181
|
+
return (cut[: end + 1] if end > limit * 0.5 else cut.rsplit(" ", 1)[0] + " …").strip()
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
# ------------------------------------------------------------------ backends
|
|
185
|
+
def wikipedia(query: str, limit: int = 3) -> list[tuple[str, str, list[str]]]:
|
|
186
|
+
"""[(title, url, paragraphs)] from the MediaWiki API (search, then plain-text extracts)."""
|
|
187
|
+
api = "https://en.wikipedia.org/w/api.php?"
|
|
188
|
+
hits = json.loads(_get(api + urllib.parse.urlencode(
|
|
189
|
+
{"action": "query", "list": "search", "srsearch": query, "srlimit": limit, "format": "json"})))
|
|
190
|
+
titles = [h["title"] for h in hits.get("query", {}).get("search", [])]
|
|
191
|
+
out = []
|
|
192
|
+
for t in titles:
|
|
193
|
+
data = json.loads(_get(api + urllib.parse.urlencode(
|
|
194
|
+
{"action": "query", "prop": "extracts", "explaintext": 1, "exsectionformat": "plain",
|
|
195
|
+
"titles": t, "format": "json", "redirects": 1})))
|
|
196
|
+
for page in data.get("query", {}).get("pages", {}).values():
|
|
197
|
+
text = page.get("extract") or ""
|
|
198
|
+
paras = [re.sub(r"\s+", " ", p).strip() for p in text.split("\n")]
|
|
199
|
+
paras = [p for p in paras if len(p) >= 80 and p.count(" ") >= 12]
|
|
200
|
+
if paras:
|
|
201
|
+
out.append((page.get("title", t), "https://en.wikipedia.org/wiki/" +
|
|
202
|
+
urllib.parse.quote(page.get("title", t).replace(" ", "_")), paras))
|
|
203
|
+
return out
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def searxng_url(base: str, query: str) -> str:
|
|
207
|
+
"""`base` is an instance (http://host:8888) or a full template with {query} (as browsers store search engines)."""
|
|
208
|
+
base = base.replace("%7Bquery%7D", "{query}").replace("%7bquery%7d", "{query}")
|
|
209
|
+
if "{query}" in base:
|
|
210
|
+
return base.replace("{query}", urllib.parse.quote_plus(query))
|
|
211
|
+
return base.rstrip("/").removesuffix("/search") + "/search?" + urllib.parse.urlencode({"q": query, "format": "json"})
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def searxng(base: str, query: str, limit: int = 5) -> list[tuple[str, str]]:
|
|
215
|
+
data = json.loads(_get(searxng_url(base, query)))
|
|
216
|
+
if not data.get("results") and data.get("unresponsive_engines"):
|
|
217
|
+
raise RuntimeError("no results; engines down: " + ", ".join(e[0] for e in data["unresponsive_engines"]))
|
|
218
|
+
return [(r.get("title", ""), r["url"]) for r in data.get("results", [])[:limit] if r.get("url")]
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
# ------------------------------------------------------------------ the lane
|
|
222
|
+
def gather(queries: list[str], focus: list[str], search_url: str = "", log=print) -> list[Source]:
|
|
223
|
+
"""Run the lane: at most MAX_QUERIES searches and MAX_PAGES pages, at most CONTEXT_CHARS of excerpts.
|
|
224
|
+
`focus` are the words the excerpts should be about (the object and its parts)."""
|
|
225
|
+
terms = set()
|
|
226
|
+
for f in focus + queries:
|
|
227
|
+
terms |= stems(f)
|
|
228
|
+
sources: list[Source] = []
|
|
229
|
+
seen: set[str] = set()
|
|
230
|
+
budget = CONTEXT_CHARS
|
|
231
|
+
|
|
232
|
+
def add(title: str, url: str, paras: list[str]) -> None:
|
|
233
|
+
nonlocal budget
|
|
234
|
+
key = url.split("#")[0].rstrip("/")
|
|
235
|
+
if key in seen or budget <= 0 or len(sources) >= MAX_PAGES:
|
|
236
|
+
return
|
|
237
|
+
ex = []
|
|
238
|
+
for e in rank(paras, terms):
|
|
239
|
+
if len(e) <= budget:
|
|
240
|
+
ex.append(e)
|
|
241
|
+
budget -= len(e)
|
|
242
|
+
if ex:
|
|
243
|
+
seen.add(key)
|
|
244
|
+
sources.append(Source(len(sources) + 1, title[:120] or key, url,
|
|
245
|
+
urllib.parse.urlparse(url).netloc.removeprefix("www."), ex))
|
|
246
|
+
|
|
247
|
+
for q in queries[:MAX_QUERIES]:
|
|
248
|
+
if len(sources) >= MAX_PAGES or budget <= 0:
|
|
249
|
+
break
|
|
250
|
+
log(f"research: searching “{q}”")
|
|
251
|
+
try:
|
|
252
|
+
for title, url, paras in wikipedia(q, 2):
|
|
253
|
+
add(title, url, paras)
|
|
254
|
+
except Exception as e: # noqa: BLE001 - one backend failing must not end the lane
|
|
255
|
+
log(f"research: wikipedia unavailable ({e})")
|
|
256
|
+
hits = []
|
|
257
|
+
if search_url:
|
|
258
|
+
try:
|
|
259
|
+
hits = searxng(search_url, q)
|
|
260
|
+
except Exception as e: # noqa: BLE001
|
|
261
|
+
log(f"research: SearXNG unavailable ({e})")
|
|
262
|
+
for title, url in hits[:3]:
|
|
263
|
+
host = urllib.parse.urlparse(url).netloc
|
|
264
|
+
if any(s in host for s in SKIP_HOSTS) or "wikipedia.org" in host or len(sources) >= MAX_PAGES:
|
|
265
|
+
continue
|
|
266
|
+
try:
|
|
267
|
+
ptitle, paras = page_text(_get(url))
|
|
268
|
+
add(title or ptitle, url, paras)
|
|
269
|
+
except Exception as e: # noqa: BLE001 - a dead or binary page is skipped
|
|
270
|
+
log(f"research: skipped {host} ({e})")
|
|
271
|
+
log(f"research: {len(sources)} source(s), {CONTEXT_CHARS - budget:,} characters of excerpts")
|
|
272
|
+
return sources
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def context_block(sources: list[Source]) -> str:
|
|
276
|
+
"""The numbered excerpts exactly as the model sees them."""
|
|
277
|
+
lines = []
|
|
278
|
+
for s in sources:
|
|
279
|
+
lines.append(f"[{s.n}] {s.title} ({s.domain})")
|
|
280
|
+
lines += [f" “{e}”" for e in s.excerpts]
|
|
281
|
+
return "\n".join(lines)
|