flashforge-python-api 1.6.0__py3-none-any.whl → 3.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 (70) hide show
  1. flashforge/__init__.py +137 -56
  2. flashforge/_removed.py +65 -0
  3. flashforge/api/__init__.py +12 -18
  4. flashforge/api/constants/__init__.py +11 -11
  5. flashforge/api/constants/commands.py +18 -15
  6. flashforge/api/constants/endpoints.py +11 -11
  7. flashforge/api/misc/__init__.py +8 -8
  8. flashforge/api/network/__init__.py +11 -11
  9. flashforge/api/network/utils.py +71 -71
  10. flashforge/backends/__init__.py +80 -0
  11. flashforge/backends/connect.py +275 -0
  12. flashforge/backends/creator5_backend.py +191 -0
  13. flashforge/backends/dual_api_backend.py +170 -0
  14. flashforge/backends/dual_api_models.py +145 -0
  15. flashforge/backends/http_core.py +431 -0
  16. flashforge/backends/http_printer_backend.py +254 -0
  17. flashforge/backends/legacy_backend.py +436 -0
  18. flashforge/backends/printer_backend.py +217 -0
  19. flashforge/backends/types.py +125 -0
  20. flashforge/capabilities/__init__.py +98 -0
  21. flashforge/capabilities/models.py +67 -0
  22. flashforge/capabilities/palettes/__init__.py +28 -0
  23. flashforge/capabilities/palettes/ad5x_palette.py +70 -0
  24. flashforge/capabilities/palettes/creator5_palette.py +78 -0
  25. flashforge/capabilities/palettes/palette.py +54 -0
  26. flashforge/{api/controls/creator5_palette.py → capabilities/palettes/palette_snap.py} +226 -258
  27. flashforge/capabilities/printer_capabilities.py +145 -0
  28. flashforge/capabilities/registry.py +125 -0
  29. flashforge/capabilities/resolve_model.py +61 -0
  30. flashforge/discovery/__init__.py +39 -39
  31. flashforge/discovery/discovery.py +150 -77
  32. flashforge/exceptions.py +90 -51
  33. flashforge/models/__init__.py +52 -55
  34. flashforge/models/machine_info.py +540 -543
  35. flashforge/{api/controls/info.py → models/machine_info_parser.py} +35 -242
  36. flashforge/models/responses.py +119 -254
  37. flashforge/status/__init__.py +43 -0
  38. flashforge/status/printer_snapshot.py +396 -0
  39. flashforge/tcp/__init__.py +55 -54
  40. flashforge/tcp/a3_client.py +427 -427
  41. flashforge/tcp/a4_client.py +304 -304
  42. flashforge/tcp/ff_client.py +609 -590
  43. flashforge/tcp/gcode/__init__.py +15 -13
  44. flashforge/tcp/gcode/a3_gcode_controller.py +109 -109
  45. flashforge/tcp/gcode/gcode_controller.py +292 -308
  46. flashforge/tcp/gcode/gcodes.py +81 -99
  47. flashforge/tcp/gcode/legacy_gcode_controller.py +56 -0
  48. flashforge/tcp/parsers/__init__.py +27 -27
  49. flashforge/tcp/parsers/endstop_status.py +248 -248
  50. flashforge/tcp/parsers/location_info.py +83 -83
  51. flashforge/tcp/parsers/print_status.py +180 -180
  52. flashforge/tcp/parsers/printer_info.py +146 -146
  53. flashforge/tcp/parsers/temp_info.py +218 -218
  54. flashforge/tcp/parsers/thumbnail_info.py +274 -274
  55. flashforge/tcp/tcp_client.py +52 -12
  56. flashforge/threemf/__init__.py +40 -40
  57. flashforge/threemf/parser.py +560 -560
  58. flashforge/threemf/warnings.py +58 -58
  59. {flashforge_python_api-1.6.0.dist-info → flashforge_python_api-3.1.0.dist-info}/METADATA +46 -47
  60. flashforge_python_api-3.1.0.dist-info/RECORD +69 -0
  61. {flashforge_python_api-1.6.0.dist-info → flashforge_python_api-3.1.0.dist-info}/WHEEL +1 -1
  62. {flashforge_python_api-1.6.0.dist-info → flashforge_python_api-3.1.0.dist-info}/licenses/LICENSE +21 -21
  63. flashforge/api/controls/__init__.py +0 -17
  64. flashforge/api/controls/control.py +0 -413
  65. flashforge/api/controls/files.py +0 -210
  66. flashforge/api/controls/job_control.py +0 -896
  67. flashforge/api/controls/temp_control.py +0 -309
  68. flashforge/client.py +0 -609
  69. flashforge_python_api-1.6.0.dist-info/RECORD +0 -52
  70. {flashforge_python_api-1.6.0.dist-info → flashforge_python_api-3.1.0.dist-info}/entry_points.txt +0 -0
@@ -1,560 +1,560 @@
1
- """
2
- FlashForge Python API - Sliced 3MF parser
3
-
4
- Reads what a client needs to know about a sliced ``.3mf`` before it sends the
5
- file to a printer: which filaments (tools) the print uses, with their material
6
- and color, plus the plate thumbnail, time and weight estimates, the printer model
7
- the file was sliced for, and any slicer warnings.
8
-
9
- This is the information a client needs to build material mappings. The Creator 5
10
- series does not report a stored file's tools, so for that family, parsing the
11
- 3MF before upload is the only way to map tools to Material Station slots
12
- correctly.
13
-
14
- Tested with output from Orca-FlashForge, OrcaSlicer, Flash Studio and Snapmaker
15
- Orca. The fields
16
- match ``ThreeMfParser`` in the TypeScript ``slicer-meta`` package.
17
-
18
- The parser reads only small, bounded parts of the archive: the slice metadata,
19
- the plate image and the start of the plate G-code. It never decompresses the
20
- whole G-code, so a large or hostile archive costs a bounded amount of memory.
21
- Parsing is synchronous file I/O. In an asyncio program, run it in an executor
22
- (for example ``await asyncio.to_thread(parse_3mf, path)``).
23
- """
24
-
25
- from __future__ import annotations
26
-
27
- import os
28
- import re
29
- import zipfile
30
- import zlib
31
- from enum import StrEnum
32
- from typing import IO, TypeVar
33
- from xml.etree import ElementTree
34
-
35
- from pydantic import BaseModel, ConfigDict, Field
36
-
37
- from ..exceptions import FlashForgeError
38
- from .warnings import translate_warning
39
-
40
- # Size limits for the parts of the archive the parser reads. A real
41
- # slice_info.config is 1-2 KB and a plate image well under 100 KB, so these
42
- # bounds only ever stop a malformed or hostile archive.
43
- MAX_SLICE_INFO_BYTES = 4 * 1024 * 1024
44
- MAX_THUMBNAIL_BYTES = 8 * 1024 * 1024
45
- # How much of the plate G-code to scan for the header comments. The header and
46
- # the summary block sit at the start of the file; embedded thumbnails can push
47
- # the summary back by a few hundred KB, so the scan stops at the first
48
- # executable line or at this bound, whichever comes first.
49
- MAX_GCODE_HEADER_BYTES = 1024 * 1024
50
-
51
- _T = TypeVar("_T")
52
-
53
- _SLICE_INFO = "Metadata/slice_info.config"
54
- _PLATE_GCODE = re.compile(r"^Metadata/plate_(\d+)\.gcode$")
55
- _HEX6 = re.compile(r"^#[0-9A-Fa-f]{6}$")
56
- _HEX8 = re.compile(r"^#[0-9A-Fa-f]{8}$")
57
- _HEX3 = re.compile(r"^#[0-9A-Fa-f]{3}$")
58
- _GENERATED_BY = re.compile(r"^;\s*generated by\s+(.+?)\s+(\d\S*)(?:\s+on\s|\s*$)", re.IGNORECASE)
59
- _DURATION = re.compile(r"(?:(\d+)d\s*)?(?:(\d+)h\s*)?(?:(\d+)m\s*)?(?:(\d+)s)?")
60
-
61
-
62
- class ThreeMFError(FlashForgeError):
63
- """Base class for errors raised while reading a 3MF file."""
64
-
65
-
66
- class ThreeMFFormatError(ThreeMFError):
67
- """The file is not a readable 3MF archive, or its slice metadata is malformed."""
68
-
69
-
70
- class ThreeMFNotSlicedError(ThreeMFError):
71
- """
72
- The archive holds no sliced plate G-code.
73
-
74
- A project 3MF saved from the slicer has models but no G-code, so a printer
75
- cannot print it. Export the sliced plate from the slicer instead.
76
- """
77
-
78
-
79
- class ThreeMFMultiplePlatesError(ThreeMFError):
80
- """
81
- The archive holds more than one sliced plate.
82
-
83
- Which plate a printer prints from such a file is not known, so a client
84
- cannot tell which tools and materials the print uses. Export a single plate
85
- from the slicer instead.
86
- """
87
-
88
- def __init__(self, plate_count: int) -> None:
89
- """
90
- Args:
91
- plate_count: The number of sliced plates in the archive.
92
- """
93
- super().__init__(
94
- f"This 3MF holds {plate_count} sliced plates. Export a single plate from the "
95
- "slicer and try again."
96
- )
97
- self.plate_count = plate_count
98
-
99
-
100
- class PrinterFamily(StrEnum):
101
- """The printer model a 3MF was sliced for, as far as this library can tell."""
102
-
103
- ADVENTURER_5M = "adventurer_5m"
104
- ADVENTURER_5M_PRO = "adventurer_5m_pro"
105
- AD5X = "ad5x"
106
- CREATOR_5 = "creator_5"
107
- CREATOR_5_PRO = "creator_5_pro"
108
-
109
-
110
- def printer_family_from_model_id(model_id: str | None) -> PrinterFamily | None:
111
- """
112
- Map a slicer printer-model id to a printer family.
113
-
114
- Slicers write ids such as ``Flashforge-Adventurer-5M-Pro``, ``Flashforge-AD5X``
115
- and ``Flashforge-Creator-5-Pro``. The comparison ignores case, spaces, hyphens
116
- and underscores, so ``Flashforge Adventurer 5M Pro`` matches too.
117
-
118
- Args:
119
- model_id: The id from the file, or ``None``.
120
-
121
- Returns:
122
- The matching family, or ``None`` for an unknown or missing id.
123
- """
124
- if not model_id:
125
- return None
126
- folded = re.sub(r"[\s_\-]+", "", model_id).lower()
127
- if "ad5x" in folded:
128
- return PrinterFamily.AD5X
129
- if "creator5pro" in folded:
130
- return PrinterFamily.CREATOR_5_PRO
131
- if "creator5" in folded:
132
- return PrinterFamily.CREATOR_5
133
- if "5mpro" in folded:
134
- return PrinterFamily.ADVENTURER_5M_PRO
135
- if "adventurer5m" in folded or folded.endswith("ad5m"):
136
- return PrinterFamily.ADVENTURER_5M
137
- return None
138
-
139
-
140
- class ThreeMFFilament(BaseModel):
141
- """One filament (tool) that the sliced plate uses."""
142
-
143
- model_config = ConfigDict(frozen=True)
144
-
145
- filament_id: int = Field(description="The slicer's filament number (1-based)")
146
- tool_id: int = Field(
147
- description=(
148
- "The tool id a material mapping uses for this filament (0-based: filament 1 "
149
- "is tool 0)"
150
- )
151
- )
152
- material_name: str = Field(default="", description="Material type, e.g. 'PLA'")
153
- color: str = Field(
154
- default="", description="Filament color as #RRGGBB, or '' if the file has none"
155
- )
156
- used_m: float | None = Field(default=None, description="Filament length used, in meters")
157
- used_g: float | None = Field(default=None, description="Filament weight used, in grams")
158
-
159
-
160
- class ThreeMFWarning(BaseModel):
161
- """A warning the slicer recorded for the plate."""
162
-
163
- model_config = ConfigDict(frozen=True)
164
-
165
- key: str = Field(description="Raw warning key, e.g. 'bed_temperature_too_high_than_filament'")
166
- message: str = Field(description="Readable text for the key")
167
- level: int = Field(default=0, description="Severity level as the slicer wrote it")
168
- error_code: str = Field(default="", description="The slicer's error code, if any")
169
-
170
-
171
- class ThreeMFFile(BaseModel):
172
- """What a sliced 3MF says about its print."""
173
-
174
- model_config = ConfigDict(frozen=True)
175
-
176
- file_name: str = Field(description="The file's base name")
177
- plate_index: int = Field(description="The index of the sliced plate (1-based)")
178
- printer_model_id: str | None = Field(
179
- default=None, description="The printer model id the file was sliced for"
180
- )
181
- slicer_name: str | None = Field(default=None, description="e.g. 'Orca-Flashforge'")
182
- slicer_version: str | None = Field(default=None, description="e.g. '1.4.2'")
183
- estimated_time_s: int | None = Field(
184
- default=None, description="The slicer's print time estimate, in seconds"
185
- )
186
- total_weight_g: float | None = Field(
187
- default=None, description="Total filament weight, in grams"
188
- )
189
- first_layer_time_s: float | None = Field(
190
- default=None, description="The slicer's first-layer time estimate, in seconds"
191
- )
192
- layer_count: int | None = Field(default=None, description="Total layer count")
193
- support_used: bool = Field(default=False, description="Whether the plate uses supports")
194
- nozzle_diameters: list[float] = Field(
195
- default_factory=list, description="Nozzle diameter per extruder, in mm"
196
- )
197
- object_names: list[str] = Field(
198
- default_factory=list, description="Names of the objects on the plate"
199
- )
200
- filaments: list[ThreeMFFilament] = Field(
201
- default_factory=list, description="The filaments the plate uses, by filament id"
202
- )
203
- warnings: list[ThreeMFWarning] = Field(
204
- default_factory=list, description="Warnings the slicer recorded"
205
- )
206
- thumbnail_png: bytes | None = Field(
207
- default=None, repr=False, description="The plate preview image (PNG bytes)"
208
- )
209
-
210
- @property
211
- def tool_count(self) -> int:
212
- """The number of filaments (tools) the plate uses."""
213
- return len(self.filaments)
214
-
215
- @property
216
- def printer_family(self) -> PrinterFamily | None:
217
- """The printer family the file was sliced for, if the id is known."""
218
- return printer_family_from_model_id(self.printer_model_id)
219
-
220
-
221
- def parse_3mf(
222
- source: str | os.PathLike[str] | IO[bytes],
223
- *,
224
- file_name: str | None = None,
225
- ) -> ThreeMFFile:
226
- """
227
- Parse a sliced 3MF file.
228
-
229
- Args:
230
- source: A path to the file, or a binary file object open for reading.
231
- file_name: The name to report in :attr:`ThreeMFFile.file_name`. Defaults
232
- to the base name of ``source`` when it is a path.
233
-
234
- Returns:
235
- The parsed metadata.
236
-
237
- Raises:
238
- FileNotFoundError: If ``source`` is a path that does not exist.
239
- ThreeMFFormatError: If the file is not a valid ZIP archive, has a corrupt
240
- entry, or its slice metadata is malformed or too large.
241
- ThreeMFNotSlicedError: If the archive holds no sliced plate G-code.
242
- ThreeMFMultiplePlatesError: If the archive holds more than one sliced plate.
243
- """
244
- if file_name is None:
245
- file_name = (
246
- os.path.basename(os.fspath(source))
247
- if isinstance(source, (str, os.PathLike))
248
- else "unknown.3mf"
249
- )
250
-
251
- try:
252
- archive = zipfile.ZipFile(source)
253
- except FileNotFoundError:
254
- raise
255
- except (zipfile.BadZipFile, OSError, ValueError) as err:
256
- raise ThreeMFFormatError(f"'{file_name}' is not a readable 3MF archive: {err}") from err
257
-
258
- with archive:
259
- try:
260
- return _parse_archive(archive, file_name)
261
- except (zipfile.BadZipFile, zlib.error, EOFError, NotImplementedError) as err:
262
- # A corrupt entry (bad CRC, truncated or unsupported compression).
263
- raise ThreeMFFormatError(f"'{file_name}' has a corrupt entry: {err}") from err
264
-
265
-
266
- def _parse_archive(archive: zipfile.ZipFile, file_name: str) -> ThreeMFFile:
267
- plates: dict[int, str] = {}
268
- for name in archive.namelist():
269
- match = _PLATE_GCODE.match(name)
270
- if match:
271
- plates[int(match.group(1))] = name
272
-
273
- if not plates:
274
- raise ThreeMFNotSlicedError(
275
- f"'{file_name}' holds no sliced G-code. Slice the plate and export the sliced "
276
- "file from the slicer."
277
- )
278
- if len(plates) > 1:
279
- raise ThreeMFMultiplePlatesError(len(plates))
280
-
281
- plate_index, gcode_name = next(iter(plates.items()))
282
-
283
- fields: dict[str, object] = {"file_name": file_name, "plate_index": plate_index}
284
- filaments: list[ThreeMFFilament] = []
285
-
286
- if _SLICE_INFO in archive.namelist():
287
- raw = _read_bounded(archive, _SLICE_INFO, MAX_SLICE_INFO_BYTES)
288
- if raw is None:
289
- raise ThreeMFFormatError(f"'{file_name}' has an oversized slice_info.config.")
290
- filaments = _parse_slice_info(raw, plate_index, fields, file_name)
291
-
292
- header = _scan_gcode_header(archive, gcode_name)
293
- _apply_gcode_header(header, fields)
294
- if not filaments:
295
- filaments = _filaments_from_header(header)
296
- fields["filaments"] = filaments
297
-
298
- thumbnail_name = f"Metadata/plate_{plate_index}.png"
299
- if thumbnail_name in archive.namelist():
300
- fields["thumbnail_png"] = _read_bounded(archive, thumbnail_name, MAX_THUMBNAIL_BYTES)
301
-
302
- return ThreeMFFile.model_validate(fields)
303
-
304
-
305
- def _read_bounded(archive: zipfile.ZipFile, name: str, limit: int) -> bytes | None:
306
- """Read one entry, or return None when it is larger than ``limit``."""
307
- if archive.getinfo(name).file_size > limit:
308
- return None
309
- with archive.open(name) as handle:
310
- data = handle.read(limit + 1)
311
- # file_size comes from the archive and can lie, so check what was read too.
312
- return None if len(data) > limit else data
313
-
314
-
315
- # --------------------------------------------------------------------------- #
316
- # slice_info.config
317
- # --------------------------------------------------------------------------- #
318
-
319
-
320
- def _parse_slice_info(
321
- raw: bytes, plate_index: int, fields: dict[str, object], file_name: str
322
- ) -> list[ThreeMFFilament]:
323
- try:
324
- root = ElementTree.fromstring(raw)
325
- except ElementTree.ParseError as err:
326
- raise ThreeMFFormatError(f"'{file_name}' has a malformed slice_info.config: {err}") from err
327
-
328
- plates = root.findall("plate")
329
- if not plates:
330
- return []
331
-
332
- plate = plates[0]
333
- for candidate in plates:
334
- if _plate_metadata(candidate).get("index") == str(plate_index):
335
- plate = candidate
336
- break
337
-
338
- meta = _plate_metadata(plate)
339
- if meta.get("printer_model_id"):
340
- fields["printer_model_id"] = meta["printer_model_id"]
341
- prediction = _to_float(meta.get("prediction"))
342
- if prediction is not None:
343
- fields["estimated_time_s"] = int(round(prediction))
344
- weight = _to_float(meta.get("weight"))
345
- if weight is not None:
346
- fields["total_weight_g"] = weight
347
- first_layer = _to_float(meta.get("first_layer_time"))
348
- if first_layer is not None:
349
- fields["first_layer_time_s"] = first_layer
350
- fields["support_used"] = meta.get("support_used", "").lower() in ("true", "1")
351
- fields["nozzle_diameters"] = [
352
- value
353
- for value in (
354
- _to_float(part) for part in re.split(r"[,\s]+", meta.get("nozzle_diameters", ""))
355
- )
356
- if value is not None
357
- ]
358
- fields["object_names"] = [
359
- obj.get("name", "") for obj in plate.findall("object") if obj.get("name")
360
- ]
361
- fields["warnings"] = [
362
- ThreeMFWarning(
363
- key=warning.get("msg", ""),
364
- message=translate_warning(warning.get("msg", "")),
365
- level=_to_int(warning.get("level")) or 0,
366
- error_code=warning.get("error_code", "") or "",
367
- )
368
- for warning in plate.findall("warning")
369
- ]
370
-
371
- filaments: list[ThreeMFFilament] = []
372
- for element in plate.findall("filament"):
373
- filament_id = _to_int(element.get("id"))
374
- if filament_id is None or filament_id < 1:
375
- continue
376
- filaments.append(
377
- ThreeMFFilament(
378
- filament_id=filament_id,
379
- tool_id=filament_id - 1,
380
- material_name=(element.get("type") or "").strip(),
381
- color=_normalize_color(element.get("color")),
382
- used_m=_to_float(element.get("used_m")),
383
- used_g=_to_float(element.get("used_g")),
384
- )
385
- )
386
- filaments.sort(key=lambda item: item.filament_id)
387
- return filaments
388
-
389
-
390
- def _plate_metadata(plate: ElementTree.Element) -> dict[str, str]:
391
- return {
392
- item.get("key", ""): item.get("value", "") or ""
393
- for item in plate.findall("metadata")
394
- if item.get("key")
395
- }
396
-
397
-
398
- # --------------------------------------------------------------------------- #
399
- # Plate G-code header
400
- # --------------------------------------------------------------------------- #
401
-
402
-
403
- def _scan_gcode_header(archive: zipfile.ZipFile, name: str) -> dict[str, str]:
404
- """
405
- Collect ``; key = value`` and ``; key: value`` comments from the G-code start.
406
-
407
- Stops at the first executable line block, at the end of the config block,
408
- or after :data:`MAX_GCODE_HEADER_BYTES`. The first occurrence of a key wins.
409
- """
410
- header: dict[str, str] = {}
411
- consumed = 0
412
- with archive.open(name) as handle:
413
- for raw_line in handle:
414
- consumed += len(raw_line)
415
- if consumed > MAX_GCODE_HEADER_BYTES:
416
- break
417
- line = raw_line.decode("utf-8", errors="replace").strip()
418
- if not line.startswith(";"):
419
- continue
420
- if "EXECUTABLE_BLOCK_START" in line or "CONFIG_BLOCK_END" in line:
421
- break
422
- generated = _GENERATED_BY.match(line)
423
- if generated and "generated_by" not in header:
424
- header["generated_by_name"] = generated.group(1).strip()
425
- header["generated_by_version"] = generated.group(2).strip()
426
- header["generated_by"] = line
427
- continue
428
- body = line.lstrip(";").strip()
429
- for separator in (" = ", ": "):
430
- if separator in body:
431
- key, value = body.split(separator, 1)
432
- header.setdefault(key.strip().lower(), value.strip())
433
- break
434
- return header
435
-
436
-
437
- def _apply_gcode_header(header: dict[str, str], fields: dict[str, object]) -> None:
438
- if header.get("generated_by_name"):
439
- fields["slicer_name"] = header["generated_by_name"]
440
- fields["slicer_version"] = header["generated_by_version"]
441
-
442
- if "estimated_time_s" not in fields:
443
- eta = next(
444
- (
445
- value
446
- for key, value in header.items()
447
- if key.startswith("estimated printing time") and "first layer" not in key
448
- ),
449
- None,
450
- )
451
- if eta is None:
452
- # Orca-FlashForge before 1.3.0:
453
- # "; model printing time: 43m 42s; total estimated time: 43m 42s"
454
- legacy = header.get("model printing time", "")
455
- if "total estimated time:" in legacy:
456
- eta = legacy.split("total estimated time:", 1)[1]
457
- seconds = _parse_duration(eta)
458
- if seconds is not None:
459
- fields["estimated_time_s"] = seconds
460
-
461
- layers = _to_int(header.get("total layer number")) or _to_int(header.get("total layers count"))
462
- if layers is not None:
463
- fields["layer_count"] = layers
464
-
465
- if "total_weight_g" not in fields:
466
- weight = _to_float(header.get("total filament used [g]"))
467
- if weight is not None:
468
- fields["total_weight_g"] = weight
469
-
470
- if "printer_model_id" not in fields and header.get("printer_model"):
471
- fields["printer_model_id"] = header["printer_model"]
472
-
473
-
474
- def _filaments_from_header(header: dict[str, str]) -> list[ThreeMFFilament]:
475
- """
476
- Fall back to the G-code header when slice_info.config lists no filaments.
477
-
478
- Uses the ``; filament: 1,2`` id list when present, otherwise every filament
479
- with a non-zero weight in ``; filament used [g]``.
480
- """
481
- grams = [_to_float(part) for part in _split_list(header.get("filament used [g]"))]
482
- meters_mm = [_to_float(part) for part in _split_list(header.get("filament used [mm]"))]
483
- types = _split_list(header.get("filament_type"), separator=";")
484
- colors = _split_list(header.get("filament_colour"), separator=";")
485
-
486
- ids = [
487
- value for value in (_to_int(part) for part in _split_list(header.get("filament"))) if value
488
- ]
489
- if not ids:
490
- ids = [index + 1 for index, value in enumerate(grams) if value]
491
- if not ids and len(types) == 1:
492
- ids = [1]
493
-
494
- filaments: list[ThreeMFFilament] = []
495
- for filament_id in sorted(set(ids)):
496
- index = filament_id - 1
497
- length_mm = _pick(meters_mm, index)
498
- filaments.append(
499
- ThreeMFFilament(
500
- filament_id=filament_id,
501
- tool_id=index,
502
- material_name=(_pick(types, index) or "").strip(),
503
- color=_normalize_color(_pick(colors, index)),
504
- used_m=round(length_mm / 1000, 2) if length_mm is not None else None,
505
- used_g=_pick(grams, index),
506
- )
507
- )
508
- return filaments
509
-
510
-
511
- # --------------------------------------------------------------------------- #
512
- # Value helpers
513
- # --------------------------------------------------------------------------- #
514
-
515
-
516
- def _pick(values: list[_T], index: int) -> _T | None:
517
- return values[index] if 0 <= index < len(values) else None
518
-
519
-
520
- def _split_list(value: str | None, separator: str = ",") -> list[str]:
521
- if not value:
522
- return []
523
- return [part.strip().strip('"') for part in value.split(separator)]
524
-
525
-
526
- def _to_float(value: str | None) -> float | None:
527
- if value is None:
528
- return None
529
- try:
530
- return float(str(value).strip())
531
- except ValueError:
532
- return None
533
-
534
-
535
- def _to_int(value: str | None) -> int | None:
536
- number = _to_float(value)
537
- return int(number) if number is not None else None
538
-
539
-
540
- def _normalize_color(value: str | None) -> str:
541
- """Return ``#RRGGBB`` (upper case) for a usable color, or ``''``."""
542
- color = (value or "").strip()
543
- if color and not color.startswith("#"):
544
- color = f"#{color}"
545
- if _HEX8.match(color):
546
- color = color[:7]
547
- elif _HEX3.match(color):
548
- color = "#" + "".join(ch * 2 for ch in color[1:])
549
- return color.upper() if _HEX6.match(color) else ""
550
-
551
-
552
- def _parse_duration(value: str | None) -> int | None:
553
- """Convert ``1d 2h 5m 30s`` style text to seconds."""
554
- if not value:
555
- return None
556
- match = next((m for m in _DURATION.finditer(value) if any(m.groups())), None)
557
- if match is None:
558
- return None
559
- days, hours, minutes, seconds = (int(group) if group else 0 for group in match.groups())
560
- return ((days * 24 + hours) * 60 + minutes) * 60 + seconds
1
+ """
2
+ FlashForge Python API - Sliced 3MF parser
3
+
4
+ Reads what a client needs to know about a sliced ``.3mf`` before it sends the
5
+ file to a printer: which filaments (tools) the print uses, with their material
6
+ and color, plus the plate thumbnail, time and weight estimates, the printer model
7
+ the file was sliced for, and any slicer warnings.
8
+
9
+ This is the information a client needs to build material mappings. The Creator 5
10
+ series does not report a stored file's tools, so for that family, parsing the
11
+ 3MF before upload is the only way to map tools to Material Station slots
12
+ correctly.
13
+
14
+ Tested with output from Orca-FlashForge, OrcaSlicer, Flash Studio and Snapmaker
15
+ Orca. The fields
16
+ match ``ThreeMfParser`` in the TypeScript ``slicer-meta`` package.
17
+
18
+ The parser reads only small, bounded parts of the archive: the slice metadata,
19
+ the plate image and the start of the plate G-code. It never decompresses the
20
+ whole G-code, so a large or hostile archive costs a bounded amount of memory.
21
+ Parsing is synchronous file I/O. In an asyncio program, run it in an executor
22
+ (for example ``await asyncio.to_thread(parse_3mf, path)``).
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import os
28
+ import re
29
+ import zipfile
30
+ import zlib
31
+ from enum import StrEnum
32
+ from typing import IO, TypeVar
33
+ from xml.etree import ElementTree
34
+
35
+ from pydantic import BaseModel, ConfigDict, Field
36
+
37
+ from ..exceptions import FlashForgeError
38
+ from .warnings import translate_warning
39
+
40
+ # Size limits for the parts of the archive the parser reads. A real
41
+ # slice_info.config is 1-2 KB and a plate image well under 100 KB, so these
42
+ # bounds only ever stop a malformed or hostile archive.
43
+ MAX_SLICE_INFO_BYTES = 4 * 1024 * 1024
44
+ MAX_THUMBNAIL_BYTES = 8 * 1024 * 1024
45
+ # How much of the plate G-code to scan for the header comments. The header and
46
+ # the summary block sit at the start of the file; embedded thumbnails can push
47
+ # the summary back by a few hundred KB, so the scan stops at the first
48
+ # executable line or at this bound, whichever comes first.
49
+ MAX_GCODE_HEADER_BYTES = 1024 * 1024
50
+
51
+ _T = TypeVar("_T")
52
+
53
+ _SLICE_INFO = "Metadata/slice_info.config"
54
+ _PLATE_GCODE = re.compile(r"^Metadata/plate_(\d+)\.gcode$")
55
+ _HEX6 = re.compile(r"^#[0-9A-Fa-f]{6}$")
56
+ _HEX8 = re.compile(r"^#[0-9A-Fa-f]{8}$")
57
+ _HEX3 = re.compile(r"^#[0-9A-Fa-f]{3}$")
58
+ _GENERATED_BY = re.compile(r"^;\s*generated by\s+(.+?)\s+(\d\S*)(?:\s+on\s|\s*$)", re.IGNORECASE)
59
+ _DURATION = re.compile(r"(?:(\d+)d\s*)?(?:(\d+)h\s*)?(?:(\d+)m\s*)?(?:(\d+)s)?")
60
+
61
+
62
+ class ThreeMFError(FlashForgeError):
63
+ """Base class for errors raised while reading a 3MF file."""
64
+
65
+
66
+ class ThreeMFFormatError(ThreeMFError):
67
+ """The file is not a readable 3MF archive, or its slice metadata is malformed."""
68
+
69
+
70
+ class ThreeMFNotSlicedError(ThreeMFError):
71
+ """
72
+ The archive holds no sliced plate G-code.
73
+
74
+ A project 3MF saved from the slicer has models but no G-code, so a printer
75
+ cannot print it. Export the sliced plate from the slicer instead.
76
+ """
77
+
78
+
79
+ class ThreeMFMultiplePlatesError(ThreeMFError):
80
+ """
81
+ The archive holds more than one sliced plate.
82
+
83
+ Which plate a printer prints from such a file is not known, so a client
84
+ cannot tell which tools and materials the print uses. Export a single plate
85
+ from the slicer instead.
86
+ """
87
+
88
+ def __init__(self, plate_count: int) -> None:
89
+ """
90
+ Args:
91
+ plate_count: The number of sliced plates in the archive.
92
+ """
93
+ super().__init__(
94
+ f"This 3MF holds {plate_count} sliced plates. Export a single plate from the "
95
+ "slicer and try again."
96
+ )
97
+ self.plate_count = plate_count
98
+
99
+
100
+ class PrinterFamily(StrEnum):
101
+ """The printer model a 3MF was sliced for, as far as this library can tell."""
102
+
103
+ ADVENTURER_5M = "adventurer_5m"
104
+ ADVENTURER_5M_PRO = "adventurer_5m_pro"
105
+ AD5X = "ad5x"
106
+ CREATOR_5 = "creator_5"
107
+ CREATOR_5_PRO = "creator_5_pro"
108
+
109
+
110
+ def printer_family_from_model_id(model_id: str | None) -> PrinterFamily | None:
111
+ """
112
+ Map a slicer printer-model id to a printer family.
113
+
114
+ Slicers write ids such as ``Flashforge-Adventurer-5M-Pro``, ``Flashforge-AD5X``
115
+ and ``Flashforge-Creator-5-Pro``. The comparison ignores case, spaces, hyphens
116
+ and underscores, so ``Flashforge Adventurer 5M Pro`` matches too.
117
+
118
+ Args:
119
+ model_id: The id from the file, or ``None``.
120
+
121
+ Returns:
122
+ The matching family, or ``None`` for an unknown or missing id.
123
+ """
124
+ if not model_id:
125
+ return None
126
+ folded = re.sub(r"[\s_\-]+", "", model_id).lower()
127
+ if "ad5x" in folded:
128
+ return PrinterFamily.AD5X
129
+ if "creator5pro" in folded:
130
+ return PrinterFamily.CREATOR_5_PRO
131
+ if "creator5" in folded:
132
+ return PrinterFamily.CREATOR_5
133
+ if "5mpro" in folded:
134
+ return PrinterFamily.ADVENTURER_5M_PRO
135
+ if "adventurer5m" in folded or folded.endswith("ad5m"):
136
+ return PrinterFamily.ADVENTURER_5M
137
+ return None
138
+
139
+
140
+ class ThreeMFFilament(BaseModel):
141
+ """One filament (tool) that the sliced plate uses."""
142
+
143
+ model_config = ConfigDict(frozen=True)
144
+
145
+ filament_id: int = Field(description="The slicer's filament number (1-based)")
146
+ tool_id: int = Field(
147
+ description=(
148
+ "The tool id a material mapping uses for this filament (0-based: filament 1 "
149
+ "is tool 0)"
150
+ )
151
+ )
152
+ material_name: str = Field(default="", description="Material type, e.g. 'PLA'")
153
+ color: str = Field(
154
+ default="", description="Filament color as #RRGGBB, or '' if the file has none"
155
+ )
156
+ used_m: float | None = Field(default=None, description="Filament length used, in meters")
157
+ used_g: float | None = Field(default=None, description="Filament weight used, in grams")
158
+
159
+
160
+ class ThreeMFWarning(BaseModel):
161
+ """A warning the slicer recorded for the plate."""
162
+
163
+ model_config = ConfigDict(frozen=True)
164
+
165
+ key: str = Field(description="Raw warning key, e.g. 'bed_temperature_too_high_than_filament'")
166
+ message: str = Field(description="Readable text for the key")
167
+ level: int = Field(default=0, description="Severity level as the slicer wrote it")
168
+ error_code: str = Field(default="", description="The slicer's error code, if any")
169
+
170
+
171
+ class ThreeMFFile(BaseModel):
172
+ """What a sliced 3MF says about its print."""
173
+
174
+ model_config = ConfigDict(frozen=True)
175
+
176
+ file_name: str = Field(description="The file's base name")
177
+ plate_index: int = Field(description="The index of the sliced plate (1-based)")
178
+ printer_model_id: str | None = Field(
179
+ default=None, description="The printer model id the file was sliced for"
180
+ )
181
+ slicer_name: str | None = Field(default=None, description="e.g. 'Orca-Flashforge'")
182
+ slicer_version: str | None = Field(default=None, description="e.g. '1.4.2'")
183
+ estimated_time_s: int | None = Field(
184
+ default=None, description="The slicer's print time estimate, in seconds"
185
+ )
186
+ total_weight_g: float | None = Field(
187
+ default=None, description="Total filament weight, in grams"
188
+ )
189
+ first_layer_time_s: float | None = Field(
190
+ default=None, description="The slicer's first-layer time estimate, in seconds"
191
+ )
192
+ layer_count: int | None = Field(default=None, description="Total layer count")
193
+ support_used: bool = Field(default=False, description="Whether the plate uses supports")
194
+ nozzle_diameters: list[float] = Field(
195
+ default_factory=list, description="Nozzle diameter per extruder, in mm"
196
+ )
197
+ object_names: list[str] = Field(
198
+ default_factory=list, description="Names of the objects on the plate"
199
+ )
200
+ filaments: list[ThreeMFFilament] = Field(
201
+ default_factory=list, description="The filaments the plate uses, by filament id"
202
+ )
203
+ warnings: list[ThreeMFWarning] = Field(
204
+ default_factory=list, description="Warnings the slicer recorded"
205
+ )
206
+ thumbnail_png: bytes | None = Field(
207
+ default=None, repr=False, description="The plate preview image (PNG bytes)"
208
+ )
209
+
210
+ @property
211
+ def tool_count(self) -> int:
212
+ """The number of filaments (tools) the plate uses."""
213
+ return len(self.filaments)
214
+
215
+ @property
216
+ def printer_family(self) -> PrinterFamily | None:
217
+ """The printer family the file was sliced for, if the id is known."""
218
+ return printer_family_from_model_id(self.printer_model_id)
219
+
220
+
221
+ def parse_3mf(
222
+ source: str | os.PathLike[str] | IO[bytes],
223
+ *,
224
+ file_name: str | None = None,
225
+ ) -> ThreeMFFile:
226
+ """
227
+ Parse a sliced 3MF file.
228
+
229
+ Args:
230
+ source: A path to the file, or a binary file object open for reading.
231
+ file_name: The name to report in :attr:`ThreeMFFile.file_name`. Defaults
232
+ to the base name of ``source`` when it is a path.
233
+
234
+ Returns:
235
+ The parsed metadata.
236
+
237
+ Raises:
238
+ FileNotFoundError: If ``source`` is a path that does not exist.
239
+ ThreeMFFormatError: If the file is not a valid ZIP archive, has a corrupt
240
+ entry, or its slice metadata is malformed or too large.
241
+ ThreeMFNotSlicedError: If the archive holds no sliced plate G-code.
242
+ ThreeMFMultiplePlatesError: If the archive holds more than one sliced plate.
243
+ """
244
+ if file_name is None:
245
+ file_name = (
246
+ os.path.basename(os.fspath(source))
247
+ if isinstance(source, (str, os.PathLike))
248
+ else "unknown.3mf"
249
+ )
250
+
251
+ try:
252
+ archive = zipfile.ZipFile(source)
253
+ except FileNotFoundError:
254
+ raise
255
+ except (zipfile.BadZipFile, OSError, ValueError) as err:
256
+ raise ThreeMFFormatError(f"'{file_name}' is not a readable 3MF archive: {err}") from err
257
+
258
+ with archive:
259
+ try:
260
+ return _parse_archive(archive, file_name)
261
+ except (zipfile.BadZipFile, zlib.error, EOFError, NotImplementedError) as err:
262
+ # A corrupt entry (bad CRC, truncated or unsupported compression).
263
+ raise ThreeMFFormatError(f"'{file_name}' has a corrupt entry: {err}") from err
264
+
265
+
266
+ def _parse_archive(archive: zipfile.ZipFile, file_name: str) -> ThreeMFFile:
267
+ plates: dict[int, str] = {}
268
+ for name in archive.namelist():
269
+ match = _PLATE_GCODE.match(name)
270
+ if match:
271
+ plates[int(match.group(1))] = name
272
+
273
+ if not plates:
274
+ raise ThreeMFNotSlicedError(
275
+ f"'{file_name}' holds no sliced G-code. Slice the plate and export the sliced "
276
+ "file from the slicer."
277
+ )
278
+ if len(plates) > 1:
279
+ raise ThreeMFMultiplePlatesError(len(plates))
280
+
281
+ plate_index, gcode_name = next(iter(plates.items()))
282
+
283
+ fields: dict[str, object] = {"file_name": file_name, "plate_index": plate_index}
284
+ filaments: list[ThreeMFFilament] = []
285
+
286
+ if _SLICE_INFO in archive.namelist():
287
+ raw = _read_bounded(archive, _SLICE_INFO, MAX_SLICE_INFO_BYTES)
288
+ if raw is None:
289
+ raise ThreeMFFormatError(f"'{file_name}' has an oversized slice_info.config.")
290
+ filaments = _parse_slice_info(raw, plate_index, fields, file_name)
291
+
292
+ header = _scan_gcode_header(archive, gcode_name)
293
+ _apply_gcode_header(header, fields)
294
+ if not filaments:
295
+ filaments = _filaments_from_header(header)
296
+ fields["filaments"] = filaments
297
+
298
+ thumbnail_name = f"Metadata/plate_{plate_index}.png"
299
+ if thumbnail_name in archive.namelist():
300
+ fields["thumbnail_png"] = _read_bounded(archive, thumbnail_name, MAX_THUMBNAIL_BYTES)
301
+
302
+ return ThreeMFFile.model_validate(fields)
303
+
304
+
305
+ def _read_bounded(archive: zipfile.ZipFile, name: str, limit: int) -> bytes | None:
306
+ """Read one entry, or return None when it is larger than ``limit``."""
307
+ if archive.getinfo(name).file_size > limit:
308
+ return None
309
+ with archive.open(name) as handle:
310
+ data = handle.read(limit + 1)
311
+ # file_size comes from the archive and can lie, so check what was read too.
312
+ return None if len(data) > limit else data
313
+
314
+
315
+ # --------------------------------------------------------------------------- #
316
+ # slice_info.config
317
+ # --------------------------------------------------------------------------- #
318
+
319
+
320
+ def _parse_slice_info(
321
+ raw: bytes, plate_index: int, fields: dict[str, object], file_name: str
322
+ ) -> list[ThreeMFFilament]:
323
+ try:
324
+ root = ElementTree.fromstring(raw)
325
+ except ElementTree.ParseError as err:
326
+ raise ThreeMFFormatError(f"'{file_name}' has a malformed slice_info.config: {err}") from err
327
+
328
+ plates = root.findall("plate")
329
+ if not plates:
330
+ return []
331
+
332
+ plate = plates[0]
333
+ for candidate in plates:
334
+ if _plate_metadata(candidate).get("index") == str(plate_index):
335
+ plate = candidate
336
+ break
337
+
338
+ meta = _plate_metadata(plate)
339
+ if meta.get("printer_model_id"):
340
+ fields["printer_model_id"] = meta["printer_model_id"]
341
+ prediction = _to_float(meta.get("prediction"))
342
+ if prediction is not None:
343
+ fields["estimated_time_s"] = int(round(prediction))
344
+ weight = _to_float(meta.get("weight"))
345
+ if weight is not None:
346
+ fields["total_weight_g"] = weight
347
+ first_layer = _to_float(meta.get("first_layer_time"))
348
+ if first_layer is not None:
349
+ fields["first_layer_time_s"] = first_layer
350
+ fields["support_used"] = meta.get("support_used", "").lower() in ("true", "1")
351
+ fields["nozzle_diameters"] = [
352
+ value
353
+ for value in (
354
+ _to_float(part) for part in re.split(r"[,\s]+", meta.get("nozzle_diameters", ""))
355
+ )
356
+ if value is not None
357
+ ]
358
+ fields["object_names"] = [
359
+ obj.get("name", "") for obj in plate.findall("object") if obj.get("name")
360
+ ]
361
+ fields["warnings"] = [
362
+ ThreeMFWarning(
363
+ key=warning.get("msg", ""),
364
+ message=translate_warning(warning.get("msg", "")),
365
+ level=_to_int(warning.get("level")) or 0,
366
+ error_code=warning.get("error_code", "") or "",
367
+ )
368
+ for warning in plate.findall("warning")
369
+ ]
370
+
371
+ filaments: list[ThreeMFFilament] = []
372
+ for element in plate.findall("filament"):
373
+ filament_id = _to_int(element.get("id"))
374
+ if filament_id is None or filament_id < 1:
375
+ continue
376
+ filaments.append(
377
+ ThreeMFFilament(
378
+ filament_id=filament_id,
379
+ tool_id=filament_id - 1,
380
+ material_name=(element.get("type") or "").strip(),
381
+ color=_normalize_color(element.get("color")),
382
+ used_m=_to_float(element.get("used_m")),
383
+ used_g=_to_float(element.get("used_g")),
384
+ )
385
+ )
386
+ filaments.sort(key=lambda item: item.filament_id)
387
+ return filaments
388
+
389
+
390
+ def _plate_metadata(plate: ElementTree.Element) -> dict[str, str]:
391
+ return {
392
+ item.get("key", ""): item.get("value", "") or ""
393
+ for item in plate.findall("metadata")
394
+ if item.get("key")
395
+ }
396
+
397
+
398
+ # --------------------------------------------------------------------------- #
399
+ # Plate G-code header
400
+ # --------------------------------------------------------------------------- #
401
+
402
+
403
+ def _scan_gcode_header(archive: zipfile.ZipFile, name: str) -> dict[str, str]:
404
+ """
405
+ Collect ``; key = value`` and ``; key: value`` comments from the G-code start.
406
+
407
+ Stops at the first executable line block, at the end of the config block,
408
+ or after :data:`MAX_GCODE_HEADER_BYTES`. The first occurrence of a key wins.
409
+ """
410
+ header: dict[str, str] = {}
411
+ consumed = 0
412
+ with archive.open(name) as handle:
413
+ for raw_line in handle:
414
+ consumed += len(raw_line)
415
+ if consumed > MAX_GCODE_HEADER_BYTES:
416
+ break
417
+ line = raw_line.decode("utf-8", errors="replace").strip()
418
+ if not line.startswith(";"):
419
+ continue
420
+ if "EXECUTABLE_BLOCK_START" in line or "CONFIG_BLOCK_END" in line:
421
+ break
422
+ generated = _GENERATED_BY.match(line)
423
+ if generated and "generated_by" not in header:
424
+ header["generated_by_name"] = generated.group(1).strip()
425
+ header["generated_by_version"] = generated.group(2).strip()
426
+ header["generated_by"] = line
427
+ continue
428
+ body = line.lstrip(";").strip()
429
+ for separator in (" = ", ": "):
430
+ if separator in body:
431
+ key, value = body.split(separator, 1)
432
+ header.setdefault(key.strip().lower(), value.strip())
433
+ break
434
+ return header
435
+
436
+
437
+ def _apply_gcode_header(header: dict[str, str], fields: dict[str, object]) -> None:
438
+ if header.get("generated_by_name"):
439
+ fields["slicer_name"] = header["generated_by_name"]
440
+ fields["slicer_version"] = header["generated_by_version"]
441
+
442
+ if "estimated_time_s" not in fields:
443
+ eta = next(
444
+ (
445
+ value
446
+ for key, value in header.items()
447
+ if key.startswith("estimated printing time") and "first layer" not in key
448
+ ),
449
+ None,
450
+ )
451
+ if eta is None:
452
+ # Orca-FlashForge before 1.3.0:
453
+ # "; model printing time: 43m 42s; total estimated time: 43m 42s"
454
+ legacy = header.get("model printing time", "")
455
+ if "total estimated time:" in legacy:
456
+ eta = legacy.split("total estimated time:", 1)[1]
457
+ seconds = _parse_duration(eta)
458
+ if seconds is not None:
459
+ fields["estimated_time_s"] = seconds
460
+
461
+ layers = _to_int(header.get("total layer number")) or _to_int(header.get("total layers count"))
462
+ if layers is not None:
463
+ fields["layer_count"] = layers
464
+
465
+ if "total_weight_g" not in fields:
466
+ weight = _to_float(header.get("total filament used [g]"))
467
+ if weight is not None:
468
+ fields["total_weight_g"] = weight
469
+
470
+ if "printer_model_id" not in fields and header.get("printer_model"):
471
+ fields["printer_model_id"] = header["printer_model"]
472
+
473
+
474
+ def _filaments_from_header(header: dict[str, str]) -> list[ThreeMFFilament]:
475
+ """
476
+ Fall back to the G-code header when slice_info.config lists no filaments.
477
+
478
+ Uses the ``; filament: 1,2`` id list when present, otherwise every filament
479
+ with a non-zero weight in ``; filament used [g]``.
480
+ """
481
+ grams = [_to_float(part) for part in _split_list(header.get("filament used [g]"))]
482
+ meters_mm = [_to_float(part) for part in _split_list(header.get("filament used [mm]"))]
483
+ types = _split_list(header.get("filament_type"), separator=";")
484
+ colors = _split_list(header.get("filament_colour"), separator=";")
485
+
486
+ ids = [
487
+ value for value in (_to_int(part) for part in _split_list(header.get("filament"))) if value
488
+ ]
489
+ if not ids:
490
+ ids = [index + 1 for index, value in enumerate(grams) if value]
491
+ if not ids and len(types) == 1:
492
+ ids = [1]
493
+
494
+ filaments: list[ThreeMFFilament] = []
495
+ for filament_id in sorted(set(ids)):
496
+ index = filament_id - 1
497
+ length_mm = _pick(meters_mm, index)
498
+ filaments.append(
499
+ ThreeMFFilament(
500
+ filament_id=filament_id,
501
+ tool_id=index,
502
+ material_name=(_pick(types, index) or "").strip(),
503
+ color=_normalize_color(_pick(colors, index)),
504
+ used_m=round(length_mm / 1000, 2) if length_mm is not None else None,
505
+ used_g=_pick(grams, index),
506
+ )
507
+ )
508
+ return filaments
509
+
510
+
511
+ # --------------------------------------------------------------------------- #
512
+ # Value helpers
513
+ # --------------------------------------------------------------------------- #
514
+
515
+
516
+ def _pick(values: list[_T], index: int) -> _T | None:
517
+ return values[index] if 0 <= index < len(values) else None
518
+
519
+
520
+ def _split_list(value: str | None, separator: str = ",") -> list[str]:
521
+ if not value:
522
+ return []
523
+ return [part.strip().strip('"') for part in value.split(separator)]
524
+
525
+
526
+ def _to_float(value: str | None) -> float | None:
527
+ if value is None:
528
+ return None
529
+ try:
530
+ return float(str(value).strip())
531
+ except ValueError:
532
+ return None
533
+
534
+
535
+ def _to_int(value: str | None) -> int | None:
536
+ number = _to_float(value)
537
+ return int(number) if number is not None else None
538
+
539
+
540
+ def _normalize_color(value: str | None) -> str:
541
+ """Return ``#RRGGBB`` (upper case) for a usable color, or ``''``."""
542
+ color = (value or "").strip()
543
+ if color and not color.startswith("#"):
544
+ color = f"#{color}"
545
+ if _HEX8.match(color):
546
+ color = color[:7]
547
+ elif _HEX3.match(color):
548
+ color = "#" + "".join(ch * 2 for ch in color[1:])
549
+ return color.upper() if _HEX6.match(color) else ""
550
+
551
+
552
+ def _parse_duration(value: str | None) -> int | None:
553
+ """Convert ``1d 2h 5m 30s`` style text to seconds."""
554
+ if not value:
555
+ return None
556
+ match = next((m for m in _DURATION.finditer(value) if any(m.groups())), None)
557
+ if match is None:
558
+ return None
559
+ days, hours, minutes, seconds = (int(group) if group else 0 for group in match.groups())
560
+ return ((days * 24 + hours) * 60 + minutes) * 60 + seconds