Repository navigation
Expand file tree
/
Copy pathserver.py
More file actions
856 lines (755 loc) · 34.5 KB
/
Copy pathserver.py
File metadata and controls
856 lines (755 loc) · 34.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
import json
import os
import hashlib
import logging
import math
import subprocess
import sys
import tempfile
import time
import zipfile
import mimetypes
import xml.etree.ElementTree as ET
from contextlib import asynccontextmanager
from dataclasses import asdict
from pathlib import Path
from typing import Literal
from uuid import uuid4
import anyio
from fastapi import FastAPI, Request, HTTPException, Form, File, UploadFile
from fastapi.responses import FileResponse, JSONResponse, Response
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
from request_limits import RequestLimitSettings, RequestLimitsMiddleware
PORT = int(os.environ.get("PORT", "3000"))
HOST = os.environ.get("HOST", "0.0.0.0")
BASE_DIR = Path(__file__).parent.resolve()
ICONS_FOLDER = BASE_DIR / "Icons_SVG"
MAX_SVG_BYTES = 2 * 1024 * 1024
MAX_PENDING_EXPORTS = 8
def _positive_timeout(name: str, default: float) -> float:
value = os.environ.get(name, str(default)).strip()
try:
parsed = float(value)
except ValueError:
raise ValueError(f"{name} must be a finite positive number") from None
if not math.isfinite(parsed) or parsed <= 0:
raise ValueError(f"{name} must be a finite positive number")
return parsed
CAD_WORK_TIMEOUT_SECONDS = _positive_timeout("CAD_WORK_TIMEOUT_SECONDS", 75.0)
CAD_REQUEST_TIMEOUT_SECONDS = _positive_timeout("CAD_REQUEST_TIMEOUT_SECONDS", 85.0)
logger = logging.getLogger(__name__)
class CADWorkerTimeout(TimeoutError):
"""Raised when an isolated CAD process exceeds its work deadline."""
class CADWorkerCrashed(RuntimeError):
"""Raised when an isolated CAD process exits without a result."""
class CADWorkerFailed(RuntimeError):
"""Raised when a worker rejects geometry or cannot write its output."""
# Ensure font files under /assets are served with correct MIME types.
mimetypes.add_type("font/woff2", ".woff2")
mimetypes.add_type("font/ttf", ".ttf")
mimetypes.add_type("font/otf", ".otf")
@asynccontextmanager
async def lifespan(app: FastAPI):
# Keep CAD operations serial: OpenCascade work is expensive and can retain
# substantial memory. Waiting exports must not occupy API worker threads.
app.state.export_limiter = anyio.CapacityLimiter(1)
app.state.export_slots = anyio.Semaphore(MAX_PENDING_EXPORTS)
yield
app = FastAPI(title="InfinityGrid Sticker Designer API", lifespan=lifespan)
THREEMF_CORE_NS = "http://schemas.microsoft.com/3dmanufacturing/core/2015/02"
THREEMF_MATERIAL_NS = "http://schemas.microsoft.com/3dmanufacturing/material/2015/02"
THREEMF_PRODUCTION_NS = "http://schemas.microsoft.com/3dmanufacturing/production/2015/06"
BAMBU_NS = "http://schemas.bambulab.com/package/2021"
@app.middleware("http")
async def response_policy(request: Request, call_next):
if request.url.path in {"/api/export_step", "/api/export_3mf"}:
content_length = request.headers.get("content-length")
# Allow room for the multipart fields in addition to the SVG itself.
if content_length and content_length.isdigit() and int(content_length) > MAX_SVG_BYTES + 64 * 1024:
return JSONResponse(status_code=413, content={"detail": "SVG upload is too large (maximum 2 MB)."})
response = await call_next(request)
if request.url.path.startswith("/icons/") and response.status_code in {200, 304}:
# The frontend changes v whenever the icon catalog changes.
response.headers["Cache-Control"] = (
"public, max-age=86400, immutable" if request.query_params.get("v") else "no-cache"
)
elif request.url.path in {"/", "/api/icons"} or request.url.path.startswith(("/assets/js/", "/assets/css/")):
response.headers["Cache-Control"] = "no-cache"
return response
def _set_shape_metadata(shape, *, label=None, material=None, color=None):
if label is not None:
try:
shape.label = label
except Exception:
pass
if material is not None:
try:
shape.material = material
except Exception:
pass
if color is not None:
try:
shape.color = color
except Exception:
pass
def _build_label_parts_from_svg(svg_path: Path, w, h, sty):
"""Compatibility wrapper; native geometry is implemented in cad_worker."""
from cad_worker import build_label_parts_from_svg
return build_label_parts_from_svg(svg_path, w, h, sty)
def _apply_3mf_materials(three_mf_path: Path, base_item_count: int, content_item_count: int):
ET.register_namespace("", THREEMF_CORE_NS)
ET.register_namespace("m", THREEMF_MATERIAL_NS)
ET.register_namespace("p", THREEMF_PRODUCTION_NS)
with zipfile.ZipFile(three_mf_path, "r") as zin:
entries = {name: zin.read(name) for name in zin.namelist()}
model_path = next((name for name in entries if name.lower().endswith(".model")), None)
if not model_path:
return
root = ET.fromstring(entries[model_path])
root.set("xmlns:BambuStudio", BAMBU_NS)
resources = root.find(f"{{{THREEMF_CORE_NS}}}resources")
build = root.find(f"{{{THREEMF_CORE_NS}}}build")
if resources is None or build is None:
return
items = build.findall(f"{{{THREEMF_CORE_NS}}}item")
required_items = max(0, int(base_item_count)) + max(0, int(content_item_count))
if required_items <= 0 or len(items) < required_items:
return
base_items = items[:base_item_count]
content_items = items[base_item_count:base_item_count + content_item_count]
ordered_items = base_items + content_items
max_resource_id = 0
for node in list(resources):
rid = node.attrib.get("id")
if rid and rid.isdigit():
max_resource_id = max(max_resource_id, int(rid))
# Meshes are renumbered 1..N below, followed by assembly N+1. Material
# resources share that ID space and must stay outside the final object IDs.
material_resource_id = str(max(max_resource_id + 1, required_items + 2))
basematerials = ET.Element(
f"{{{THREEMF_CORE_NS}}}basematerials",
{"id": material_resource_id}
)
basematerials.append(
ET.Element(
f"{{{THREEMF_CORE_NS}}}base",
{"name": "Base_Black", "displaycolor": "#000000"}
)
)
basematerials.append(
ET.Element(
f"{{{THREEMF_CORE_NS}}}base",
{"name": "Content_White", "displaycolor": "#FFFFFF"}
)
)
resources.insert(0, basematerials)
objects_by_id = {
obj.attrib.get("id"): obj
for obj in resources.findall(f"{{{THREEMF_CORE_NS}}}object")
}
for i, item in enumerate(base_items):
obj_id = item.attrib.get("objectid")
item.attrib["pid"] = material_resource_id
item.attrib["pindex"] = "0"
obj = objects_by_id.get(obj_id)
if obj is not None:
obj.attrib["name"] = f"Base_Black_{i + 1}"
obj.attrib["pid"] = material_resource_id
obj.attrib["pindex"] = "0"
for i, item in enumerate(content_items):
obj_id = item.attrib.get("objectid")
item.attrib["pid"] = material_resource_id
item.attrib["pindex"] = "1"
obj = objects_by_id.get(obj_id)
if obj is not None:
obj.attrib["name"] = f"Content_White_{i + 1}"
obj.attrib["pid"] = material_resource_id
obj.attrib["pindex"] = "1"
# Base materials are part of core 3MF; no materials extension is needed.
# Preserve any independently required extensions emitted by the mesher.
required_extensions = root.attrib.get("requiredextensions", "").split()
required_extensions = [prefix for prefix in required_extensions if prefix != "m"]
if required_extensions:
root.attrib["requiredextensions"] = " ".join(required_extensions)
else:
root.attrib.pop("requiredextensions", None)
# Build a Bambu/Orca-friendly assembly object with explicit components.
# Many slicers (including Orca/Bambu family) read part/extruder metadata
# from this structure more reliably than core 3MF materials alone.
max_obj_id = 0
for obj_id in objects_by_id.keys():
if obj_id and obj_id.isdigit():
max_obj_id = max(max_obj_id, int(obj_id))
assembly_obj_id = str(max(max_obj_id, int(material_resource_id)) + 1)
assembly_obj = ET.Element(
f"{{{THREEMF_CORE_NS}}}object",
{"id": assembly_obj_id, "type": "model", f"{{{THREEMF_PRODUCTION_NS}}}UUID": str(uuid4())}
)
assembly_components = ET.SubElement(assembly_obj, f"{{{THREEMF_CORE_NS}}}components")
def _parse_transform12(transform_text: str):
if not transform_text:
return [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]
vals = []
for p in str(transform_text).split():
try:
vals.append(float(p))
except Exception:
pass
if len(vals) != 12:
return [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]
return vals
def _fmt_num(v: float):
s = f"{float(v):.9f}".rstrip("0").rstrip(".")
return s if s else "0"
component_infos = []
global_min_x = None
global_min_y = None
global_min_z = None
def _extract_object_bounds(obj_node):
mesh_node = obj_node.find(f"{{{THREEMF_CORE_NS}}}mesh")
if mesh_node is None:
return None
verts_node = mesh_node.find(f"{{{THREEMF_CORE_NS}}}vertices")
if verts_node is None:
return None
xs, ys, zs = [], [], []
for v in verts_node.findall(f"{{{THREEMF_CORE_NS}}}vertex"):
try:
xs.append(float(v.attrib.get("x", "0")))
ys.append(float(v.attrib.get("y", "0")))
zs.append(float(v.attrib.get("z", "0")))
except Exception:
continue
if not xs:
return None
return (min(xs), min(ys), min(zs), max(xs), max(ys), max(zs))
object_bounds = {}
for obj_id, obj in objects_by_id.items():
if obj_id:
b = _extract_object_bounds(obj)
if b is not None:
object_bounds[obj_id] = b
for idx, item in enumerate(ordered_items):
obj_id = item.attrib.get("objectid")
if not obj_id:
continue
transform_text = item.attrib.get("transform")
comp_attrs = {"objectid": obj_id, f"{{{THREEMF_PRODUCTION_NS}}}UUID": str(uuid4())}
if transform_text:
comp_attrs["transform"] = transform_text
ET.SubElement(assembly_components, f"{{{THREEMF_CORE_NS}}}component", comp_attrs)
transform_vals = _parse_transform12(transform_text)
tx, ty, tz = transform_vals[9], transform_vals[10], transform_vals[11]
matrix16 = " ".join([
_fmt_num(transform_vals[0]), _fmt_num(transform_vals[1]), _fmt_num(transform_vals[2]), _fmt_num(tx),
_fmt_num(transform_vals[3]), _fmt_num(transform_vals[4]), _fmt_num(transform_vals[5]), _fmt_num(ty),
_fmt_num(transform_vals[6]), _fmt_num(transform_vals[7]), _fmt_num(transform_vals[8]), _fmt_num(tz),
"0", "0", "0", "1"
])
obj = objects_by_id.get(obj_id)
part_name = obj.attrib.get("name") if obj is not None else ""
if not part_name:
part_name = f"Part_{idx + 1}"
extruder = "1" if idx < base_item_count else "2"
bounds = object_bounds.get(obj_id)
if bounds is not None:
min_x = bounds[0] + tx
min_y = bounds[1] + ty
min_z = bounds[2] + tz
global_min_x = min_x if global_min_x is None else min(global_min_x, min_x)
global_min_y = min_y if global_min_y is None else min(global_min_y, min_y)
global_min_z = min_z if global_min_z is None else min(global_min_z, min_z)
component_infos.append({
"part_name": part_name,
"object_id": obj_id,
"matrix16": matrix16,
"tx": _fmt_num(tx),
"ty": _fmt_num(ty),
"tz": _fmt_num(tz),
"extruder": extruder
})
resources.append(assembly_obj)
# Replace build with one assembly item (Bambu/Orca-style packaging).
for item in list(build.findall(f"{{{THREEMF_CORE_NS}}}item")):
build.remove(item)
build_item_attrs = {"objectid": assembly_obj_id, f"{{{THREEMF_PRODUCTION_NS}}}UUID": str(uuid4())}
# Move model into positive XY with a small margin so slicers using corner-origin
# beds don't flag "object over boundary" on import.
margin_xy = 5.0
shift_x = 0.0
shift_y = 0.0
shift_z = 0.0
if global_min_x is not None and global_min_x < margin_xy:
shift_x = margin_xy - global_min_x
if global_min_y is not None and global_min_y < margin_xy:
shift_y = margin_xy - global_min_y
if global_min_z is not None and global_min_z < 0.0:
shift_z = -global_min_z
if shift_x or shift_y or shift_z:
build_item_attrs["transform"] = " ".join([
"1", "0", "0",
"0", "1", "0",
"0", "0", "1",
_fmt_num(shift_x),
_fmt_num(shift_y),
_fmt_num(shift_z)
])
ET.SubElement(build, f"{{{THREEMF_CORE_NS}}}item", build_item_attrs)
# Drop unreferenced wrapper objects emitted by the mesher. Orca can treat
# those as extra parts (often black/default), which causes the duplicate
# InfinityGrid_Label_* entries and wrong color assignment in the object tree.
keep_object_ids = {assembly_obj_id}
for info in component_infos:
keep_object_ids.add(info["object_id"])
for obj in list(resources.findall(f"{{{THREEMF_CORE_NS}}}object")):
oid = obj.attrib.get("id")
if oid not in keep_object_ids:
resources.remove(obj)
# Renumber kept objects contiguously (1..N for mesh parts, N+1 for assembly).
# Orca/Bambu metadata uses source_object_id that aligns with contiguous object
# numbering in common project files.
mesh_old_ids = [info["object_id"] for info in component_infos]
id_map = {old_id: str(i + 1) for i, old_id in enumerate(mesh_old_ids)}
new_assembly_id = str(len(mesh_old_ids) + 1)
id_map[assembly_obj_id] = new_assembly_id
for obj in resources.findall(f"{{{THREEMF_CORE_NS}}}object"):
old_id = obj.attrib.get("id")
if old_id in id_map:
obj.attrib["id"] = id_map[old_id]
for comp in assembly_components.findall(f"{{{THREEMF_CORE_NS}}}component"):
old_ref = comp.attrib.get("objectid")
if old_ref in id_map:
comp.attrib["objectid"] = id_map[old_ref]
for item in build.findall(f"{{{THREEMF_CORE_NS}}}item"):
old_ref = item.attrib.get("objectid")
if old_ref in id_map:
item.attrib["objectid"] = id_map[old_ref]
assembly_obj_id = new_assembly_id
for idx, info in enumerate(component_infos):
mapped_obj_id = id_map.get(info["object_id"], info["object_id"])
info["mapped_object_id"] = mapped_obj_id
try:
info["source_object_id"] = str(int(mapped_obj_id) - 1)
except Exception:
info["source_object_id"] = str(idx)
def _upsert_model_metadata(meta_name: str, meta_value: str):
md_tag = f"{{{THREEMF_CORE_NS}}}metadata"
for node in root.findall(md_tag):
if node.attrib.get("name") == meta_name:
node.text = meta_value
return
new_node = ET.Element(md_tag, {"name": meta_name})
new_node.text = meta_value
resources_node = root.find(f"{{{THREEMF_CORE_NS}}}resources")
if resources_node is not None:
insert_at = list(root).index(resources_node)
root.insert(insert_at, new_node)
else:
root.append(new_node)
_upsert_model_metadata("Application", "OrcaSlicer")
_upsert_model_metadata("BambuStudio:3mfVersion", "1")
entries[model_path] = ET.tostring(root, encoding="utf-8", xml_declaration=True)
# Add Orca/Bambu project metadata files for part-to-extruder mapping.
model_settings_root = ET.Element("config")
object_cfg = ET.SubElement(model_settings_root, "object", {"id": assembly_obj_id})
ET.SubElement(object_cfg, "metadata", {"key": "name", "value": "InfinityGrid_Label"})
ET.SubElement(object_cfg, "metadata", {"key": "extruder", "value": "1"})
for idx, info in enumerate(component_infos, start=1):
part_node = ET.SubElement(
object_cfg,
"part",
{"id": str(idx), "subtype": "normal_part"}
)
ET.SubElement(part_node, "metadata", {"key": "name", "value": info["part_name"]})
ET.SubElement(part_node, "metadata", {"key": "matrix", "value": info["matrix16"]})
ET.SubElement(part_node, "metadata", {"key": "source_file", "value": "multicolor_label.3mf"})
ET.SubElement(part_node, "metadata", {"key": "source_object_id", "value": info["source_object_id"]})
ET.SubElement(part_node, "metadata", {"key": "source_volume_id", "value": "0"})
ET.SubElement(part_node, "metadata", {"key": "source_offset_x", "value": info["tx"]})
ET.SubElement(part_node, "metadata", {"key": "source_offset_y", "value": info["ty"]})
ET.SubElement(part_node, "metadata", {"key": "source_offset_z", "value": info["tz"]})
ET.SubElement(part_node, "metadata", {"key": "extruder", "value": info["extruder"]})
plate_node = ET.SubElement(model_settings_root, "plate")
ET.SubElement(plate_node, "metadata", {"key": "plater_id", "value": "1"})
ET.SubElement(plate_node, "metadata", {"key": "plater_name", "value": ""})
ET.SubElement(plate_node, "metadata", {"key": "locked", "value": "false"})
ET.SubElement(plate_node, "metadata", {"key": "filament_map_mode", "value": "Auto For Flush"})
ET.SubElement(plate_node, "metadata", {"key": "filament_maps", "value": "1 2"})
project_settings = {
"filament_colour": ["#000000", "#FFFFFF"],
"extruder_colour": ["#000000"],
"filament_type": ["PLA", "PLA"],
"filament_ids": ["", ""],
"filament_settings_id": ["Base_Black", "Content_White"],
"default_filament_profile": ["Base_Black", "Content_White"],
# Orca/Bambu validates relative E mode against layer-change reset.
# Provide the common reset snippet to avoid import/slice validation errors.
"before_layer_change_gcode": ";BEFORE_LAYER_CHANGE\n;[layer_z]\nG92 E0\n",
"use_relative_e_distances": "1"
}
slice_info_xml = (
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<config>\n"
" <header>\n"
" <header_item key=\"X-BBL-Client-Type\" value=\"slicer\"/>\n"
" <header_item key=\"X-BBL-Client-Version\" value=\"\"/>\n"
" </header>\n"
"</config>\n"
)
entries["Metadata/model_settings.config"] = ET.tostring(
model_settings_root, encoding="utf-8", xml_declaration=True
)
entries["Metadata/project_settings.config"] = json.dumps(
project_settings, indent=2
).encode("utf-8")
entries["Metadata/slice_info.config"] = slice_info_xml.encode("utf-8")
with zipfile.ZipFile(three_mf_path, "w", compression=zipfile.ZIP_DEFLATED) as zout:
for name, payload in entries.items():
zout.writestr(name, payload)
def build_step_worker(svg_text, w, h, sty, queue):
"""Compatibility wrapper for direct native STEP callers."""
from cad_worker import build_step_worker as isolated_worker
return isolated_worker(svg_text, w, h, sty, queue)
def build_3mf_worker(svg_text, w, h, sty, queue):
"""Compatibility wrapper for direct native 3MF callers."""
from cad_worker import build_3mf_worker as isolated_worker
return isolated_worker(svg_text, w, h, sty, queue)
# Setup CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=False,
allow_methods=["*"],
allow_headers=["*"],
)
app.add_middleware(
RequestLimitsMiddleware,
**asdict(RequestLimitSettings.from_env()),
)
def get_icon_catalog():
"""Read one consistent catalog; renames and edits both invalidate its version."""
if not ICONS_FOLDER.exists():
return [], "0-0"
entries = []
for path in ICONS_FOLDER.iterdir():
if path.suffix.lower() != ".svg" or not path.is_file():
continue
try:
info = path.stat()
except FileNotFoundError:
# A live icon-library refresh may remove a file during enumeration.
continue
entries.append((path.name, info.st_size, info.st_mtime_ns))
entries.sort()
fingerprint = hashlib.sha256(json.dumps(entries, ensure_ascii=True).encode("utf-8")).hexdigest()[:16]
return [entry[0] for entry in entries], f"{len(entries)}-{fingerprint}"
def get_icon_files():
return get_icon_catalog()[0]
def get_icons_version():
"""Version token that changes when icon files are added/updated/removed."""
return get_icon_catalog()[1]
@app.get("/api/icons")
def list_icons():
"""API endpoint to list available icons."""
icons, version = get_icon_catalog()
return JSONResponse(content={"files": icons, "version": version})
async def _read_svg_upload(svg_file: UploadFile):
try:
raw = await svg_file.read(MAX_SVG_BYTES + 1)
finally:
await svg_file.close()
if len(raw) > MAX_SVG_BYTES:
raise HTTPException(status_code=413, detail="SVG upload is too large (maximum 2 MB).")
try:
svg_text = raw.decode("utf-8-sig")
except UnicodeDecodeError:
raise HTTPException(status_code=422, detail="SVG must be UTF-8 encoded.") from None
if "<!DOCTYPE" in svg_text.upper() or "<!ENTITY" in svg_text.upper():
raise HTTPException(status_code=422, detail="SVG document types and entities are not supported.")
try:
root = ET.fromstring(svg_text)
except ET.ParseError:
raise HTTPException(status_code=422, detail="Upload a valid SVG document.") from None
if root.tag not in {"svg", "{http://www.w3.org/2000/svg}svg"}:
raise HTTPException(status_code=422, detail="The uploaded document must have an SVG root element.")
for node in root.iter():
if node.tag.rsplit("}", 1)[-1] in {"image", "script", "foreignObject"}:
raise HTTPException(status_code=422, detail="SVG must contain self-contained vector geometry.")
for attr, value in node.attrib.items():
if attr.rsplit("}", 1)[-1] == "href" and not value.startswith("#"):
raise HTTPException(status_code=422, detail="External SVG references are not supported.")
return svg_text
def _run_export(worker, svg_content, width, height, style, format_name):
class Result:
value = None
def put(self, value):
self.value = value
result = Result()
worker(svg_content, width, height, style, result)
if result.value is None:
raise HTTPException(status_code=500, detail=f"{format_name} export failed without details.")
status, payload = result.value
if status != "ok":
raise HTTPException(
status_code=422,
detail=f"{format_name} could not build this geometry. Try a simpler design or another geometry mode."
)
return payload
def _terminate_cad_process(process):
"""Stop a child and reap it, escalating when terminate is ineffective."""
if process.poll() is not None:
return
try:
process.terminate()
process.wait(timeout=1.0)
except (subprocess.TimeoutExpired, OSError):
try:
process.kill()
except OSError:
pass
try:
process.wait(timeout=1.0)
except (subprocess.TimeoutExpired, OSError):
logger.error("CAD worker process could not be reaped (pid=%s)", process.pid)
def _start_cad_process(request_path: Path):
"""Start the worker with no inherited stdio or visible Windows console."""
flags = getattr(subprocess, "CREATE_NO_WINDOW", 0) if os.name == "nt" else 0
return subprocess.Popen(
[sys.executable, str(BASE_DIR / "cad_worker.py"), str(request_path)],
cwd=str(BASE_DIR),
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
creationflags=flags,
close_fds=(os.name != "nt"),
)
async def _run_isolated_export(format_name, svg_content, width, height, style):
"""Run one native export in a disposable child process.
Only a small JSON status file crosses the process boundary. The potentially
large STEP/3MF payload stays in a private temporary output file.
"""
with tempfile.TemporaryDirectory(prefix="infinitygrid-cad-") as temp_dir:
temp_path = Path(temp_dir)
svg_path = temp_path / "label_content.svg"
output_path = temp_path / f"multicolor_label.{format_name}"
status_path = temp_path / "status.json"
request_path = temp_path / "request.json"
svg_path.write_text(svg_content, encoding="utf-8")
request_path.write_text(
json.dumps({
"format": format_name,
"svg_path": str(svg_path),
"output_path": str(output_path),
"status_path": str(status_path),
"width": float(width),
"height": float(height),
"style": style,
}),
encoding="utf-8",
)
# Start-up is part of the native work budget. This matters on a cold
# Windows interpreter where importing the CAD stack can take seconds.
deadline = time.monotonic() + CAD_WORK_TIMEOUT_SECONDS
try:
process = _start_cad_process(request_path)
except OSError as exc:
raise CADWorkerCrashed("CAD worker could not be started") from exc
try:
while True:
if status_path.is_file():
try:
status = json.loads(status_path.read_text(encoding="utf-8"))
except (OSError, ValueError):
status = None
if status is not None:
if status.get("status") == "ok" and output_path.is_file():
# Leave room in the 64 MiB deployment tmpfs for
# the validated SVG and the child's transient CAD
# file while allowing ordinary STEP assemblies.
if output_path.stat().st_size > 24 * 1024 * 1024:
raise CADWorkerFailed("CAD output exceeded the server limit")
return output_path.read_bytes()
raise CADWorkerFailed("CAD worker failed to build this geometry")
return_code = process.poll()
if return_code is not None:
raise CADWorkerCrashed(
f"CAD worker exited without a result (code {return_code})"
)
if time.monotonic() >= deadline:
raise CADWorkerTimeout("CAD export exceeded its time limit")
await anyio.sleep(0.05)
except BaseException:
# Cancellation and timeout both terminate the native process before
# the TemporaryDirectory context removes its input/output files.
with anyio.CancelScope(shield=True):
await anyio.to_thread.run_sync(_terminate_cad_process, process)
raise
finally:
if process.poll() is None:
with anyio.CancelScope(shield=True):
await anyio.to_thread.run_sync(_terminate_cad_process, process)
# A module-level seam keeps API tests deterministic without changing the
# production path or teaching it about test doubles.
_cad_process_runner = _run_isolated_export
async def _watch_request_disconnect(request: Request, cancel_scope: anyio.CancelScope, state: dict):
"""Cancel native work when the client closes its HTTP connection."""
receive = getattr(request, "_receive", None)
# Direct unit-test Requests may use Starlette's empty receiver. There is no
# connection to monitor in that case.
if receive is None or getattr(receive, "__name__", "") == "empty_receive":
return
try:
while True:
message = await receive()
if message.get("type") == "http.disconnect":
state["disconnected"] = True
cancel_scope.cancel()
return
except BaseException as exc:
if isinstance(exc, anyio.get_cancelled_exc_class()):
raise
logger.debug("Request disconnect watcher stopped: %s", exc)
async def _run_with_disconnect_watch(request: Request, operation):
"""Run an operation while watching the request connection."""
state = {"disconnected": False}
try:
with anyio.CancelScope() as disconnect_scope:
async with anyio.create_task_group() as task_group:
task_group.start_soon(_watch_request_disconnect, request, disconnect_scope, state)
try:
result = await operation()
finally:
task_group.cancel_scope.cancel()
if state["disconnected"]:
# Work has been cancelled and the child reaped. Complete the ASGI
# response lifecycle so middleware does not report a false 500.
raise HTTPException(status_code=499, detail="Client disconnected.")
return result
except BaseExceptionGroup as group:
# A parent exception plus the watcher task is represented as a group by
# AnyIO. Unwrap the common single-error case so FastAPI can render its
# normal HTTPException response instead of surfacing an exception group.
if len(group.exceptions) == 1:
raise group.exceptions[0]
raise
async def _export_response(request, svg_file, width, height, style, worker, extension, media_type):
slots = request.app.state.export_slots
limiter = request.app.state.export_limiter
try:
slots.acquire_nowait()
except anyio.WouldBlock:
raise HTTPException(
status_code=503,
detail="The export queue is full. Please try again shortly.",
headers={"Retry-After": "5"}
) from None
try:
async def operation():
# This deadline covers upload parsing, serialized CAD queue wait,
# child startup, and native work. It remains below common 90s client
# request limits while leaving cleanup time for the server.
with anyio.fail_after(CAD_REQUEST_TIMEOUT_SECONDS):
svg_content = await _read_svg_upload(svg_file)
async with limiter:
return await _cad_process_runner(
extension, svg_content, width, height, style
)
try:
payload = await _run_with_disconnect_watch(request, operation)
except (CADWorkerTimeout, TimeoutError) as exc:
raise HTTPException(
status_code=504,
detail="CAD export timed out. Please try a simpler design.",
) from exc
except CADWorkerFailed as exc:
raise HTTPException(
status_code=422,
detail="CAD could not build this geometry. Try a simpler design or another geometry mode.",
) from exc
except CADWorkerCrashed as exc:
logger.error("CAD worker crashed: %s", exc)
raise HTTPException(
status_code=500,
detail="CAD export worker failed. Please try again.",
) from exc
return Response(
content=payload,
media_type=media_type,
headers={"Content-Disposition": f'attachment; filename="multicolor_label.{extension}"'}
)
finally:
slots.release()
@app.post("/api/export_step")
async def export_step_endpoint(
request: Request,
svg_file: UploadFile = File(...),
width: float = Form(..., gt=0, le=300, allow_inf_nan=False),
height: float = Form(..., gt=0, le=300, allow_inf_nan=False),
style: Literal["flush", "raised"] = Form("flush")
):
"""Create a multi-body STEP assembly without blocking other requests."""
return await _export_response(
request, svg_file, width, height, style, build_step_worker, "step", "application/octet-stream"
)
@app.post("/api/export_3mf")
async def export_3mf_endpoint(
request: Request,
svg_file: UploadFile = File(...),
width: float = Form(..., gt=0, le=300, allow_inf_nan=False),
height: float = Form(..., gt=0, le=300, allow_inf_nan=False),
style: Literal["flush", "raised"] = Form("flush")
):
"""Create a 3MF assembly with black/white material assignments."""
return await _export_response(
request, svg_file, width, height, style, build_3mf_worker, "3mf", "model/3mf"
)
# Serve the Icons directory
app.mount("/icons", StaticFiles(directory=str(ICONS_FOLDER)), name="icons")
# Serve the 'assets' directory properly
assets_dir = BASE_DIR / "assets"
if assets_dir.exists():
app.mount("/assets", StaticFiles(directory=str(assets_dir)), name="assets")
@app.get("/favicon.ico", include_in_schema=False)
async def favicon_ico():
favicon_path = BASE_DIR / "favicon.svg"
if favicon_path.exists():
return FileResponse(favicon_path, media_type="image/svg+xml")
app_icon_path = BASE_DIR / "AppIcon.png"
if app_icon_path.exists():
return FileResponse(app_icon_path, media_type="image/png")
return Response(status_code=204)
@app.get("/favicon.svg", include_in_schema=False)
async def favicon_svg():
file_path = BASE_DIR / "favicon.svg"
if file_path.exists() and file_path.is_file():
return FileResponse(file_path, media_type="image/svg+xml")
raise HTTPException(status_code=404, detail="File not found")
@app.get("/AppIcon.png", include_in_schema=False)
async def app_icon_png():
file_path = BASE_DIR / "AppIcon.png"
if file_path.exists() and file_path.is_file():
return FileResponse(file_path, media_type="image/png")
raise HTTPException(status_code=404, detail="File not found")
@app.get("/")
async def serve_index():
index_path = BASE_DIR / "index.html"
if index_path.exists():
return FileResponse(index_path)
raise HTTPException(status_code=404, detail="Index.html not found")
if __name__ == "__main__":
icons = get_icon_files()
print()
print("InfinityGrid Sticker Designer (FastAPI + Build123d)")
print("-" * 50)
print(f"Server running at: http://{HOST}:{PORT}")
print(f"Icons folder: {ICONS_FOLDER}")
print(f"Icons found: {len(icons)}")
if len(icons) == 0:
print()
print("WARNING: No SVG files found in Icons_SVG folder.")
print()
print("Press Ctrl+C to stop.")
print()
uvicorn.run("server:app", host=HOST, port=PORT, reload=False, proxy_headers=False)