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.
Files changed (118) hide show
  1. replicator/__init__.py +6 -0
  2. replicator/app.py +204 -0
  3. replicator/config.py +48 -0
  4. replicator/core/__init__.py +0 -0
  5. replicator/core/assembly.py +117 -0
  6. replicator/core/blender_link.py +161 -0
  7. replicator/core/critique.py +594 -0
  8. replicator/core/drawing.py +389 -0
  9. replicator/core/dxf.py +120 -0
  10. replicator/core/evaluate.py +439 -0
  11. replicator/core/explain.py +139 -0
  12. replicator/core/export.py +96 -0
  13. replicator/core/fit.py +170 -0
  14. replicator/core/importers.py +185 -0
  15. replicator/core/materials.py +104 -0
  16. replicator/core/ops_advanced.py +496 -0
  17. replicator/core/ops_engineering.py +223 -0
  18. replicator/core/physics.py +147 -0
  19. replicator/core/printers.py +100 -0
  20. replicator/core/program.py +298 -0
  21. replicator/core/render.py +145 -0
  22. replicator/core/reverse.py +350 -0
  23. replicator/core/robot.py +153 -0
  24. replicator/core/step.py +245 -0
  25. replicator/fixtures/gaming_pc_liquid.json +2259 -0
  26. replicator/fixtures/gas_generator_rocket.json +876 -0
  27. replicator/fixtures/gas_generator_rocket_aero.json +861 -0
  28. replicator/fixtures/house_two_bed.json +979 -0
  29. replicator/fixtures/quadcopter_drone.json +687 -0
  30. replicator/fixtures/raspberry_pi_5.json +884 -0
  31. replicator/fixtures/rocket_engine.json +652 -0
  32. replicator/fixtures/turbofan.json +931 -0
  33. replicator/fixtures/vector_engine.json +314 -0
  34. replicator/gpu.py +81 -0
  35. replicator/image3d/__init__.py +0 -0
  36. replicator/image3d/comfy.py +181 -0
  37. replicator/image3d/pipeline.py +208 -0
  38. replicator/image3d/sheet.py +154 -0
  39. replicator/knowledge/__init__.py +61 -0
  40. replicator/knowledge/car_wheel_corner.md +21 -0
  41. replicator/knowledge/desk_lamp.md +21 -0
  42. replicator/knowledge/desktop_pc.md +20 -0
  43. replicator/knowledge/electronics_board.md +21 -0
  44. replicator/knowledge/exoskeleton.md +21 -0
  45. replicator/knowledge/house.md +22 -0
  46. replicator/knowledge/light_aircraft.md +22 -0
  47. replicator/knowledge/multirotor_drone.md +25 -0
  48. replicator/knowledge/print_replica.md +13 -0
  49. replicator/knowledge/rocket_engine.md +27 -0
  50. replicator/knowledge/turbofan.md +23 -0
  51. replicator/llm/__init__.py +0 -0
  52. replicator/llm/client.py +424 -0
  53. replicator/llm/prompts/blueprint.md +28 -0
  54. replicator/llm/prompts/edit.md +15 -0
  55. replicator/llm/prompts/explain.md +37 -0
  56. replicator/llm/prompts/name_parts.md +13 -0
  57. replicator/llm/prompts/program.md +72 -0
  58. replicator/llm/prompts/research_queries.md +8 -0
  59. replicator/mcp_server.py +307 -0
  60. replicator/qml/Main.qml +874 -0
  61. replicator/qml/Replicator/UI/Chip.qml +17 -0
  62. replicator/qml/Replicator/UI/DockHeader.qml +27 -0
  63. replicator/qml/Replicator/UI/Icon.qml +118 -0
  64. replicator/qml/Replicator/UI/IconButton.qml +31 -0
  65. replicator/qml/Replicator/UI/Kbd.qml +18 -0
  66. replicator/qml/Replicator/UI/NumField.qml +69 -0
  67. replicator/qml/Replicator/UI/Pill.qml +28 -0
  68. replicator/qml/Replicator/UI/RCombo.qml +51 -0
  69. replicator/qml/Replicator/UI/RMenu.qml +42 -0
  70. replicator/qml/Replicator/UI/RSlider.qml +23 -0
  71. replicator/qml/Replicator/UI/Segmented.qml +63 -0
  72. replicator/qml/Replicator/UI/Swatch.qml +47 -0
  73. replicator/qml/Replicator/UI/Theme.qml +149 -0
  74. replicator/qml/Replicator/UI/qmldir +14 -0
  75. replicator/qml/panels/AgentPrompt.qml +53 -0
  76. replicator/qml/panels/AttributeManager.qml +171 -0
  77. replicator/qml/panels/Commander.qml +136 -0
  78. replicator/qml/panels/HolodeckPanel.qml +117 -0
  79. replicator/qml/panels/IssuesCard.qml +78 -0
  80. replicator/qml/panels/LedgerPanel.qml +110 -0
  81. replicator/qml/panels/MaterialShelf.qml +97 -0
  82. replicator/qml/panels/ObjectManager.qml +107 -0
  83. replicator/qml/panels/Preferences.qml +211 -0
  84. replicator/qml/panels/Presenter.qml +316 -0
  85. replicator/qml/panels/StatusBar.qml +77 -0
  86. replicator/qml/panels/Timeline.qml +149 -0
  87. replicator/qml/panels/Welcome.qml +126 -0
  88. replicator/qml/viewport/Callouts.qml +87 -0
  89. replicator/qml/viewport/EdgeMaterial.qml +16 -0
  90. replicator/qml/viewport/GridMaterial.qml +16 -0
  91. replicator/qml/viewport/HoloMaterial.qml +23 -0
  92. replicator/qml/viewport/NavGizmo.qml +72 -0
  93. replicator/qml/viewport/ReferenceMaterial.qml +17 -0
  94. replicator/qml/viewport/Viewport.qml +583 -0
  95. replicator/qt/__init__.py +0 -0
  96. replicator/qt/bridge.py +1427 -0
  97. replicator/qt/drawing_sheet.py +33 -0
  98. replicator/qt/envmap.py +40 -0
  99. replicator/qt/library.py +68 -0
  100. replicator/qt/mesh_geometry.py +167 -0
  101. replicator/qt/svg.py +41 -0
  102. replicator/research/__init__.py +0 -0
  103. replicator/research/lane.py +281 -0
  104. replicator/shaders/edge.frag +9 -0
  105. replicator/shaders/edge.vert +7 -0
  106. replicator/shaders/grid.frag +52 -0
  107. replicator/shaders/grid.vert +6 -0
  108. replicator/shaders/holo.frag +41 -0
  109. replicator/shaders/reference.frag +15 -0
  110. replicator/shaders/reference.vert +6 -0
  111. replicator/voice.py +120 -0
  112. replicator_workshop-0.1.0.dist-info/METADATA +410 -0
  113. replicator_workshop-0.1.0.dist-info/RECORD +118 -0
  114. replicator_workshop-0.1.0.dist-info/WHEEL +5 -0
  115. replicator_workshop-0.1.0.dist-info/entry_points.txt +3 -0
  116. replicator_workshop-0.1.0.dist-info/licenses/LICENSE +21 -0
  117. replicator_workshop-0.1.0.dist-info/licenses/vendor/mcp-for-blender/LICENSE +21 -0
  118. replicator_workshop-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,314 @@
1
+ {
2
+ "version": 1,
3
+ "name": "Vector engine, reverse thrust",
4
+ "units": "mm",
5
+ "materials": {
6
+ "titanium": {
7
+ "base_color": [
8
+ 0.62,
9
+ 0.63,
10
+ 0.66
11
+ ],
12
+ "metalness": 1.0,
13
+ "roughness": 0.32
14
+ },
15
+ "ceramic": {
16
+ "base_color": [
17
+ 0.12,
18
+ 0.12,
19
+ 0.13
20
+ ],
21
+ "metalness": 0.0,
22
+ "roughness": 0.7
23
+ },
24
+ "glow": {
25
+ "base_color": [
26
+ 0.2,
27
+ 0.75,
28
+ 1.0
29
+ ],
30
+ "metalness": 0.0,
31
+ "roughness": 0.2,
32
+ "emissive": [
33
+ 0.2,
34
+ 0.75,
35
+ 1.0
36
+ ]
37
+ }
38
+ },
39
+ "blueprint": {
40
+ "summary": "A podded turbofan whose cascade reverser doors sit in a radial ring.",
41
+ "dimensions": [
42
+ 220,
43
+ 520,
44
+ 220
45
+ ]
46
+ },
47
+ "ops": [
48
+ {
49
+ "id": "nacelle_shell",
50
+ "op": "revolve",
51
+ "label": "Nacelle",
52
+ "part": "nacelle",
53
+ "material": "titanium",
54
+ "params": {
55
+ "points": [
56
+ [
57
+ 78,
58
+ 0
59
+ ],
60
+ [
61
+ 98,
62
+ 30
63
+ ],
64
+ [
65
+ 104,
66
+ 160
67
+ ],
68
+ [
69
+ 100,
70
+ 330
71
+ ],
72
+ [
73
+ 84,
74
+ 420
75
+ ],
76
+ [
77
+ 70,
78
+ 420
79
+ ],
80
+ [
81
+ 86,
82
+ 330
83
+ ],
84
+ [
85
+ 90,
86
+ 160
87
+ ],
88
+ [
89
+ 84,
90
+ 30
91
+ ],
92
+ [
93
+ 70,
94
+ 0
95
+ ]
96
+ ]
97
+ }
98
+ },
99
+ {
100
+ "id": "intake_lip",
101
+ "op": "torus",
102
+ "label": "Intake lip",
103
+ "part": "nacelle",
104
+ "material": "titanium",
105
+ "params": {
106
+ "major_radius": 76,
107
+ "minor_radius": 8,
108
+ "translate": [
109
+ 0,
110
+ 0,
111
+ 0
112
+ ]
113
+ }
114
+ },
115
+ {
116
+ "id": "nacelle",
117
+ "op": "boolean",
118
+ "label": "Nacelle and lip",
119
+ "part": "nacelle",
120
+ "inputs": [
121
+ "nacelle_shell",
122
+ "intake_lip"
123
+ ],
124
+ "params": {
125
+ "mode": "union"
126
+ }
127
+ },
128
+ {
129
+ "id": "core",
130
+ "op": "revolve",
131
+ "label": "Core and spinner",
132
+ "part": "core",
133
+ "material": "ceramic",
134
+ "params": {
135
+ "points": [
136
+ [
137
+ 0,
138
+ 10
139
+ ],
140
+ [
141
+ 22,
142
+ 20
143
+ ],
144
+ [
145
+ 40,
146
+ 60
147
+ ],
148
+ [
149
+ 46,
150
+ 300
151
+ ],
152
+ [
153
+ 38,
154
+ 470
155
+ ],
156
+ [
157
+ 20,
158
+ 510
159
+ ],
160
+ [
161
+ 0,
162
+ 515
163
+ ]
164
+ ]
165
+ }
166
+ },
167
+ {
168
+ "id": "blade",
169
+ "op": "box",
170
+ "label": "Fan blade",
171
+ "part": "fan",
172
+ "material": "titanium",
173
+ "params": {
174
+ "size": [
175
+ 4,
176
+ 14,
177
+ 70
178
+ ],
179
+ "translate": [
180
+ 0,
181
+ 45,
182
+ 44
183
+ ],
184
+ "rotate": [
185
+ 0,
186
+ 0,
187
+ 18
188
+ ]
189
+ }
190
+ },
191
+ {
192
+ "id": "fan",
193
+ "op": "array",
194
+ "label": "Fan, 18 blades",
195
+ "part": "fan",
196
+ "input": "blade",
197
+ "params": {
198
+ "mode": "radial",
199
+ "count": 18,
200
+ "axis": "y"
201
+ }
202
+ },
203
+ {
204
+ "id": "door",
205
+ "op": "box",
206
+ "label": "Reverser door",
207
+ "part": "reverser",
208
+ "material": "titanium",
209
+ "params": {
210
+ "size": [
211
+ 48,
212
+ 110,
213
+ 6
214
+ ],
215
+ "translate": [
216
+ 0,
217
+ 250,
218
+ 106
219
+ ],
220
+ "rotate": [
221
+ -14,
222
+ 0,
223
+ 0
224
+ ]
225
+ }
226
+ },
227
+ {
228
+ "id": "reverser",
229
+ "op": "array",
230
+ "label": "Reverser ring, 6 doors",
231
+ "part": "reverser",
232
+ "input": "door",
233
+ "params": {
234
+ "mode": "radial",
235
+ "count": 6,
236
+ "axis": "y"
237
+ }
238
+ },
239
+ {
240
+ "id": "nozzle_ring",
241
+ "op": "torus",
242
+ "label": "Exhaust glow ring",
243
+ "part": "nozzle",
244
+ "material": "glow",
245
+ "params": {
246
+ "major_radius": 74,
247
+ "minor_radius": 3,
248
+ "translate": [
249
+ 0,
250
+ 418,
251
+ 0
252
+ ]
253
+ }
254
+ },
255
+ {
256
+ "id": "pylon_raw",
257
+ "op": "extrude",
258
+ "label": "Pylon",
259
+ "part": "pylon",
260
+ "material": "titanium",
261
+ "params": {
262
+ "points": [
263
+ [
264
+ 0,
265
+ 40
266
+ ],
267
+ [
268
+ 24,
269
+ 320
270
+ ],
271
+ [
272
+ -6,
273
+ 320
274
+ ],
275
+ [
276
+ -20,
277
+ 60
278
+ ]
279
+ ],
280
+ "height": 14,
281
+ "axis": "x",
282
+ "translate": [
283
+ 0,
284
+ 0,
285
+ 0
286
+ ],
287
+ "rotate": [
288
+ 0,
289
+ 0,
290
+ 0
291
+ ]
292
+ }
293
+ },
294
+ {
295
+ "id": "pylon",
296
+ "op": "transform",
297
+ "label": "Pylon on top",
298
+ "part": "pylon",
299
+ "input": "pylon_raw",
300
+ "params": {
301
+ "rotate": [
302
+ 0,
303
+ 0,
304
+ 0
305
+ ],
306
+ "translate": [
307
+ 0,
308
+ 0,
309
+ 118
310
+ ]
311
+ }
312
+ }
313
+ ]
314
+ }
replicator/gpu.py ADDED
@@ -0,0 +1,81 @@
1
+ """Which GPU the window draws on. On a machine with an Intel iGPU beside an NVIDIA card, the card is left to the model
2
+ server (llama.cpp, vLLM, Ollama): a viewport holding a few hundred MB of VRAM can stop a large model from loading.
3
+
4
+ `REPLICATOR_GPU` picks the policy, read before Qt loads:
5
+ auto (default) pin to the iGPU when both an Intel Vulkan ICD and nvidia-smi are present, otherwise leave it to Qt
6
+ igpu always pin to the Intel/Mesa iGPU
7
+ any never pin; Qt picks
8
+ When pinned, the app checks nvidia-smi for its own PID after the first frame and quits if it landed on the card
9
+ anyway. `software=True` (the test harness, `--software`) draws with Mesa's llvmpipe on the CPU.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import os
14
+ import shutil
15
+ import subprocess
16
+ from pathlib import Path
17
+
18
+ MESA_EGL = "/usr/share/glvnd/egl_vendor.d/50_mesa.json"
19
+ INTEL_ICD = "/usr/share/vulkan/icd.d/intel_icd.json"
20
+
21
+
22
+ def policy() -> str:
23
+ p = os.environ.get("REPLICATOR_GPU", "auto").strip().lower()
24
+ return p if p in ("auto", "igpu", "any") else "auto"
25
+
26
+
27
+ def should_pin() -> bool:
28
+ p = policy()
29
+ if p == "any":
30
+ return False
31
+ if p == "igpu":
32
+ return True
33
+ return Path(INTEL_ICD).exists() and shutil.which("nvidia-smi") is not None
34
+
35
+
36
+ def pinned_env(software: bool = False, pin: bool | None = None) -> dict[str, str]:
37
+ pin = should_pin() if pin is None else pin
38
+ env = {"QSG_RHI_BACKEND": "opengl", "CUDA_VISIBLE_DEVICES": ""}
39
+ if pin:
40
+ env.update({
41
+ "__EGL_VENDOR_LIBRARY_FILENAMES": MESA_EGL,
42
+ "__GLX_VENDOR_LIBRARY_NAME": "mesa",
43
+ "VK_ICD_FILENAMES": INTEL_ICD,
44
+ "VK_DRIVER_FILES": INTEL_ICD,
45
+ "QT_FFMPEG_DECODING_HW_DEVICE_TYPES": ",",
46
+ "QT_FFMPEG_ENCODING_HW_DEVICE_TYPES": ",",
47
+ })
48
+ if software:
49
+ env.update({"LIBGL_ALWAYS_SOFTWARE": "1", "GALLIUM_DRIVER": "llvmpipe"})
50
+ if pin:
51
+ env.update({"VK_ICD_FILENAMES": "/dev/null", "VK_DRIVER_FILES": "/dev/null"})
52
+ return env
53
+
54
+
55
+ def apply(software: bool = False) -> bool:
56
+ """Set the environment before Qt loads; True when the window is pinned to the iGPU."""
57
+ pin = should_pin()
58
+ os.environ.update(pinned_env(software, pin))
59
+ return pin
60
+
61
+
62
+ def nvidia_pids() -> set[int]:
63
+ try:
64
+ out = subprocess.run(["nvidia-smi", "--query-compute-apps=pid", "--format=csv,noheader"],
65
+ capture_output=True, text=True, timeout=10).stdout
66
+ except (OSError, subprocess.TimeoutExpired):
67
+ return set()
68
+ pids = {int(x) for x in out.split() if x.strip().isdigit()}
69
+ try: # graphics (G) clients appear only in the plain table
70
+ full = subprocess.run(["nvidia-smi"], capture_output=True, text=True, timeout=10).stdout
71
+ for line in full.splitlines():
72
+ parts = line.split()
73
+ if len(parts) > 4 and parts[0] == "|" and parts[4].isdigit():
74
+ pids.add(int(parts[4]))
75
+ except (OSError, subprocess.TimeoutExpired):
76
+ pass
77
+ return pids
78
+
79
+
80
+ def on_nvidia(pid: int | None = None) -> bool:
81
+ return (pid or os.getpid()) in nvidia_pids()
File without changes
@@ -0,0 +1,181 @@
1
+ """ComfyUI for Image to 3D: upload images, run API-format workflows, fetch outputs.
2
+
3
+ Replicator talks to a ComfyUI you run yourself at $COMFY_URL (default http://127.0.0.1:8188) with the Hunyuan3D 2.x
4
+ and BiRefNet models below installed. It never loads a model in its own process.
5
+
6
+ On a machine where one GPU is shared between ComfyUI and an LLM server, set $REPLICATOR_COMFY_BRIDGE to a folder
7
+ holding a `bridge.py` with `ensure_up()` and `end_batch()`: acquire() calls it before the jobs, so the card can be
8
+ handed to ComfyUI and back. Without it, ComfyUI is assumed to be up already.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import os
14
+ import sys
15
+ import time
16
+ import urllib.error
17
+ import urllib.parse
18
+ import urllib.request
19
+ import uuid
20
+ from pathlib import Path
21
+
22
+ BRIDGE = os.environ.get("REPLICATOR_COMFY_BRIDGE", "")
23
+ COMFY = (os.environ.get("COMFY_URL") or os.environ.get("COMFY_LOCAL_URL") or "http://127.0.0.1:8188").rstrip("/")
24
+
25
+ MODEL_SINGLE = "hunyuan_3d_v2.1.safetensors"
26
+ MODEL_MULTI = "hunyuan3d-dit-v2-mv_fp16.safetensors"
27
+ BG_MODEL = "birefnet.safetensors"
28
+
29
+
30
+ class ComfyError(RuntimeError):
31
+ pass
32
+
33
+
34
+ def _bridge():
35
+ """The optional GPU hand-off module, or None when REPLICATOR_COMFY_BRIDGE is not set."""
36
+ if not BRIDGE:
37
+ return None
38
+ if BRIDGE not in sys.path:
39
+ sys.path.insert(0, BRIDGE)
40
+ try:
41
+ import bridge # noqa: PLC0415
42
+ except ImportError as e:
43
+ raise ComfyError(f"ComfyUI bridge not found in {BRIDGE} ({e}); fix or unset REPLICATOR_COMFY_BRIDGE") from e
44
+ return bridge
45
+
46
+
47
+ def _reachable() -> bool:
48
+ try:
49
+ with urllib.request.urlopen(COMFY + "/system_stats", timeout=5):
50
+ return True
51
+ except (OSError, ValueError):
52
+ return False
53
+
54
+
55
+ def acquire(log=print) -> None:
56
+ """Block until ComfyUI is up (through the bridge when one is configured). Raises ComfyError when it cannot."""
57
+ b = _bridge()
58
+ if b is None:
59
+ if not _reachable():
60
+ raise ComfyError(f"ComfyUI is not answering at {COMFY}; start it or set COMFY_URL")
61
+ log(f"image3d: ComfyUI at {COMFY}")
62
+ return
63
+ os.environ.setdefault("COMFY_BATCH", "120") # keep the card between the mask job and the mesh job
64
+ os.environ.setdefault("GEN_CLIENT", "replicator")
65
+ log("image3d: asking the bridge for the GPU (ComfyUI)")
66
+ try:
67
+ b.ensure_up()
68
+ except SystemExit as e: # bridge exits with wake instructions when it cannot start ComfyUI
69
+ raise ComfyError(f"ComfyUI could not get the card ({e})") from e
70
+ log("image3d: ComfyUI holds the card")
71
+
72
+
73
+ def release() -> None:
74
+ try:
75
+ b = _bridge()
76
+ if b is not None:
77
+ b.end_batch()
78
+ except ComfyError:
79
+ pass
80
+
81
+
82
+ def _json(path: str, body: dict | None = None, timeout: float = 60):
83
+ data = json.dumps(body).encode() if body is not None else None
84
+ req = urllib.request.Request(COMFY + path, data=data, headers={"Content-Type": "application/json"} if data else {})
85
+ try:
86
+ with urllib.request.urlopen(req, timeout=timeout) as r:
87
+ return json.load(r)
88
+ except urllib.error.HTTPError as e:
89
+ raise ComfyError(f"ComfyUI {path}: HTTP {e.code} {e.read()[:600].decode(errors='replace')}") from e
90
+
91
+
92
+ def upload(path: Path, subfolder: str = "replicator") -> str:
93
+ """POST /upload/image; returns the name LoadImage wants ("replicator/x.png")."""
94
+ boundary = uuid.uuid4().hex
95
+ body = b"".join([
96
+ f"--{boundary}\r\nContent-Disposition: form-data; name=\"subfolder\"\r\n\r\n{subfolder}\r\n".encode(),
97
+ f"--{boundary}\r\nContent-Disposition: form-data; name=\"overwrite\"\r\n\r\ntrue\r\n".encode(),
98
+ f"--{boundary}\r\nContent-Disposition: form-data; name=\"image\"; filename=\"{path.name}\"\r\n"
99
+ f"Content-Type: image/png\r\n\r\n".encode(), path.read_bytes(), f"\r\n--{boundary}--\r\n".encode()])
100
+ req = urllib.request.Request(COMFY + "/upload/image", data=body,
101
+ headers={"Content-Type": f"multipart/form-data; boundary={boundary}"})
102
+ with urllib.request.urlopen(req, timeout=60) as r:
103
+ res = json.load(r)
104
+ return f"{res['subfolder']}/{res['name']}" if res.get("subfolder") else res["name"]
105
+
106
+
107
+ def run(workflow: dict, log=print, timeout: float = 900) -> dict:
108
+ """Queue an API-format workflow and wait for it; returns the history entry's outputs."""
109
+ cid = "replicator-" + uuid.uuid4().hex[:8]
110
+ res = _json("/prompt", {"prompt": workflow, "client_id": cid})
111
+ if res.get("node_errors"):
112
+ raise ComfyError(f"workflow rejected: {json.dumps(res['node_errors'])[:800]}")
113
+ pid = res["prompt_id"]
114
+ t0, last = time.time(), -1
115
+ while time.time() - t0 < timeout:
116
+ hist = _json(f"/history/{pid}").get(pid)
117
+ if hist:
118
+ st = hist.get("status", {})
119
+ if st.get("status_str") == "error":
120
+ msgs = [m for m in st.get("messages", []) if m[0] == "execution_error"]
121
+ detail = msgs[0][1].get("exception_message", "") if msgs else st
122
+ raise ComfyError(f"ComfyUI failed: {str(detail)[:800]}")
123
+ if st.get("completed") or hist.get("outputs"):
124
+ return hist.get("outputs", {})
125
+ el = int(time.time() - t0)
126
+ if el // 15 != last:
127
+ last = el // 15
128
+ log(f"image3d: running ({el}s)")
129
+ time.sleep(1.0)
130
+ raise ComfyError(f"ComfyUI job {pid} did not finish in {timeout:.0f}s")
131
+
132
+
133
+ def fetch(item: dict) -> bytes:
134
+ """Download one output (a SavedResult dict: filename, subfolder, type)."""
135
+ q = urllib.parse.urlencode({"filename": item["filename"], "subfolder": item.get("subfolder", ""),
136
+ "type": item.get("type", "output")})
137
+ with urllib.request.urlopen(f"{COMFY}/view?{q}", timeout=120) as r:
138
+ return r.read()
139
+
140
+
141
+ # ---------------------------------------------------------------------------------------------- workflows (API format)
142
+
143
+ def mask_workflow(images: list[str], prefix: str) -> dict:
144
+ """One BiRefNet foreground mask per image, saved as greyscale PNGs (output index = image index)."""
145
+ wf: dict = {"bg": {"class_type": "LoadBackgroundRemovalModel", "inputs": {"bg_removal_name": BG_MODEL}}}
146
+ for i, name in enumerate(images):
147
+ wf[f"load{i}"] = {"class_type": "LoadImage", "inputs": {"image": name}}
148
+ wf[f"rm{i}"] = {"class_type": "RemoveBackground", "inputs": {"bg_removal_model": ["bg", 0], "image": [f"load{i}", 0]}}
149
+ wf[f"img{i}"] = {"class_type": "MaskToImage", "inputs": {"mask": [f"rm{i}", 0]}}
150
+ wf[f"save{i}"] = {"class_type": "SaveImage", "inputs": {"images": [f"img{i}", 0], "filename_prefix": f"{prefix}_mask{i}"}}
151
+ return wf
152
+
153
+
154
+ def mesh_workflow(views: dict[str, str], prefix: str, seed: int = 0, steps: int = 30, cfg: float = 5.0,
155
+ octree: int = 256) -> dict:
156
+ """Hunyuan3D shape generation. views: {"image": name} for one picture (Hunyuan3D 2.1), or any of
157
+ {"front", "left", "back", "right"} for multi-view (Hunyuan3D-2mv). Writes a GLB through SaveGLB."""
158
+ multi = "image" not in views
159
+ wf: dict = {
160
+ "ckpt": {"class_type": "ImageOnlyCheckpointLoader", "inputs": {"ckpt_name": MODEL_MULTI if multi else MODEL_SINGLE}},
161
+ "ms": {"class_type": "ModelSamplingAuraFlow", "inputs": {"model": ["ckpt", 0], "shift": 1.0}},
162
+ }
163
+ enc = {}
164
+ for key, name in views.items():
165
+ wf[f"load_{key}"] = {"class_type": "LoadImage", "inputs": {"image": name}}
166
+ wf[f"enc_{key}"] = {"class_type": "CLIPVisionEncode",
167
+ "inputs": {"clip_vision": ["ckpt", 1], "image": [f"load_{key}", 0], "crop": "none"}}
168
+ enc[key] = [f"enc_{key}", 0]
169
+ if multi:
170
+ wf["cond"] = {"class_type": "Hunyuan3Dv2ConditioningMultiView", "inputs": enc}
171
+ else:
172
+ wf["cond"] = {"class_type": "Hunyuan3Dv2Conditioning", "inputs": {"clip_vision_output": enc["image"]}}
173
+ wf["latent"] = {"class_type": "EmptyLatentHunyuan3Dv2", "inputs": {"resolution": 3072 if multi else 4096, "batch_size": 1}}
174
+ wf["ks"] = {"class_type": "KSampler", "inputs": {
175
+ "model": ["ms", 0], "positive": ["cond", 0], "negative": ["cond", 1], "latent_image": ["latent", 0],
176
+ "seed": seed, "steps": steps, "cfg": cfg, "sampler_name": "euler", "scheduler": "normal", "denoise": 1.0}}
177
+ wf["dec"] = {"class_type": "VAEDecodeHunyuan3D",
178
+ "inputs": {"samples": ["ks", 0], "vae": ["ckpt", 2], "num_chunks": 8000, "octree_resolution": octree}}
179
+ wf["mesh"] = {"class_type": "VoxelToMesh", "inputs": {"voxel": ["dec", 0], "algorithm": "surface net", "threshold": 0.6}}
180
+ wf["save"] = {"class_type": "SaveGLB", "inputs": {"mesh": ["mesh", 0], "filename_prefix": prefix}}
181
+ return wf