threemf_tools.py 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231
  1. """3MF file parsing utilities for filament tracking.
  2. This module provides functions to parse Bambu Lab 3MF files and extract
  3. per-layer filament usage data from the embedded G-code. This enables
  4. accurate partial usage reporting for multi-material prints.
  5. """
  6. import hashlib
  7. import json
  8. import logging
  9. import math
  10. import re
  11. import zipfile
  12. from collections import OrderedDict
  13. from dataclasses import dataclass, field
  14. from pathlib import Path
  15. from threading import Lock
  16. import defusedxml.ElementTree as ET
  17. logger = logging.getLogger(__name__)
  18. # Default filament properties
  19. DEFAULT_FILAMENT_DIAMETER = 1.75 # mm
  20. DEFAULT_FILAMENT_DENSITY = 1.24 # g/cm³ (PLA)
  21. def parse_gcode_layer_filament_usage(gcode_content: str) -> dict[int, dict[int, float]]:
  22. """Parse G-code to extract per-layer, per-filament cumulative extrusion in mm.
  23. This function tracks filament extrusion across layers and tool changes,
  24. building a cumulative usage map that can be used to calculate partial
  25. usage at any layer.
  26. Args:
  27. gcode_content: The raw G-code content as a string
  28. Returns:
  29. A nested dictionary mapping layer numbers to filament usage:
  30. {layer: {filament_id: cumulative_mm}, ...}
  31. Example:
  32. {0: {0: 125.5}, 1: {0: 250.0, 1: 50.0}, 2: {0: 375.0, 1: 150.0}}
  33. This shows:
  34. - Layer 0: filament 0 used 125.5mm cumulative
  35. - Layer 1: filament 0 used 250mm cumulative, filament 1 used 50mm
  36. - Layer 2: filament 0 used 375mm cumulative, filament 1 used 150mm
  37. G-code commands parsed:
  38. - M73 L<layer>: Layer change marker
  39. - M620 S<filament>: Filament/tool change (S255 = unload)
  40. - G0/G1/G2/G3 E<amount>: Extrusion moves
  41. """
  42. layer_filaments: dict[int, dict[int, float]] = {}
  43. current_layer = 0
  44. active_filament: int | None = None
  45. cumulative_extrusion: dict[int, float] = {} # filament_id -> total mm
  46. for line in gcode_content.splitlines():
  47. line = line.strip()
  48. if not line:
  49. continue
  50. # Handle comments - skip but check for layer markers
  51. if line.startswith(";"):
  52. # Some slicers use comment-based layer markers
  53. # e.g., "; CHANGE_LAYER" or ";LAYER_CHANGE"
  54. continue
  55. # Split line into command and inline comment
  56. if ";" in line:
  57. line = line.split(";")[0].strip()
  58. # Extract command and parameters
  59. parts = line.split()
  60. if not parts:
  61. continue
  62. cmd = parts[0].upper()
  63. # Layer change: M73 L<layer>
  64. # Bambu printers use M73 with L parameter for layer indication
  65. if cmd == "M73":
  66. for part in parts[1:]:
  67. part_upper = part.upper()
  68. if part_upper.startswith("L"):
  69. try:
  70. new_layer = int(part[1:])
  71. # Save current state before layer change
  72. if cumulative_extrusion:
  73. layer_filaments[current_layer] = cumulative_extrusion.copy()
  74. current_layer = new_layer
  75. except ValueError:
  76. pass # Skip G-code lines with unparseable layer numbers
  77. # Filament change: M620 S<filament>
  78. # Bambu uses M620 for AMS filament switching
  79. # S255 means full unload (no active filament)
  80. elif cmd == "M620":
  81. for part in parts[1:]:
  82. part_upper = part.upper()
  83. if part_upper.startswith("S"):
  84. filament_str = part[1:]
  85. if filament_str == "255":
  86. # Full unload - no active filament
  87. active_filament = None
  88. else:
  89. try:
  90. # Extract digits (e.g., "0A" -> 0, "1" -> 1)
  91. match = re.match(r"(\d+)", filament_str)
  92. if match:
  93. active_filament = int(match.group(1))
  94. except (ValueError, AttributeError):
  95. pass # Skip unparseable filament switch commands
  96. # Extrusion moves: G0/G1/G2/G3 with E parameter
  97. # Only G1 typically has extrusion, but check all for safety
  98. elif cmd in ("G0", "G1", "G2", "G3"):
  99. if active_filament is None:
  100. continue
  101. for part in parts[1:]:
  102. part_upper = part.upper()
  103. if part_upper.startswith("E"):
  104. try:
  105. extrusion = float(part[1:])
  106. # Only count positive extrusion (not retractions)
  107. if extrusion > 0:
  108. current = cumulative_extrusion.get(active_filament, 0)
  109. cumulative_extrusion[active_filament] = current + extrusion
  110. except ValueError:
  111. pass # Skip G-code lines with unparseable extrusion values
  112. # Save final layer state
  113. if cumulative_extrusion:
  114. layer_filaments[current_layer] = cumulative_extrusion.copy()
  115. return layer_filaments
  116. def mm_to_grams(
  117. length_mm: float,
  118. diameter_mm: float = DEFAULT_FILAMENT_DIAMETER,
  119. density_g_cm3: float = DEFAULT_FILAMENT_DENSITY,
  120. ) -> float:
  121. """Convert filament length in mm to weight in grams.
  122. Uses the formula: mass = volume × density
  123. where volume = π × r² × length
  124. Args:
  125. length_mm: Length of filament in millimeters
  126. diameter_mm: Filament diameter in millimeters (default: 1.75)
  127. density_g_cm3: Material density in g/cm³ (default: 1.24 for PLA)
  128. Returns:
  129. Weight in grams
  130. """
  131. radius_cm = (diameter_mm / 2) / 10 # Convert mm to cm
  132. length_cm = length_mm / 10 # Convert mm to cm
  133. volume_cm3 = math.pi * radius_cm * radius_cm * length_cm
  134. return volume_cm3 * density_g_cm3
  135. def extract_layer_filament_usage_from_3mf(file_path: Path) -> dict[int, dict[int, float]] | None:
  136. """Extract per-layer filament usage from a 3MF file's embedded G-code.
  137. Args:
  138. file_path: Path to the 3MF file
  139. Returns:
  140. Dictionary mapping layers to filament usage, or None if parsing fails.
  141. Format: {layer: {filament_id: cumulative_mm}, ...}
  142. """
  143. try:
  144. with zipfile.ZipFile(file_path, "r") as zf:
  145. # Find G-code file(s) - usually plate_1.gcode or Metadata/plate_1.gcode
  146. gcode_files = [f for f in zf.namelist() if f.endswith(".gcode")]
  147. if not gcode_files:
  148. return None
  149. # Use the first G-code file (typically only one per 3MF export)
  150. gcode_path = gcode_files[0]
  151. gcode_content = zf.read(gcode_path).decode("utf-8", errors="ignore")
  152. return parse_gcode_layer_filament_usage(gcode_content)
  153. except Exception:
  154. return None
  155. def get_cumulative_usage_at_layer(
  156. layer_usage: dict[int, dict[int, float]],
  157. target_layer: int,
  158. ) -> dict[int, float]:
  159. """Get cumulative filament usage (in mm) up to and including target_layer.
  160. Args:
  161. layer_usage: The output from parse_gcode_layer_filament_usage()
  162. target_layer: The layer number to get usage for
  163. Returns:
  164. Dictionary of {filament_id: cumulative_mm} for each filament used
  165. up to target_layer. Returns empty dict if no data available.
  166. """
  167. if not layer_usage:
  168. return {}
  169. # Find the highest recorded layer <= target_layer
  170. # (we store snapshots at layer changes, so we need the closest one)
  171. relevant_layers = [layer for layer in layer_usage if layer <= target_layer]
  172. if not relevant_layers:
  173. return {}
  174. max_layer = max(relevant_layers)
  175. return layer_usage.get(max_layer, {})
  176. def extract_filament_properties_from_3mf(file_path: Path) -> dict[int, dict]:
  177. """Extract filament properties (density, diameter, type) from 3MF metadata.
  178. Args:
  179. file_path: Path to the 3MF file
  180. Returns:
  181. Dictionary mapping filament IDs to their properties:
  182. {filament_id: {"diameter": 1.75, "density": 1.24, "type": "PLA"}, ...}
  183. Note: filament_id is 1-based (matches slot_id in slice_info.config)
  184. """
  185. properties: dict[int, dict] = {}
  186. try:
  187. with zipfile.ZipFile(file_path, "r") as zf:
  188. # Try slice_info.config first for filament types
  189. if "Metadata/slice_info.config" in zf.namelist():
  190. content = zf.read("Metadata/slice_info.config").decode()
  191. root = ET.fromstring(content)
  192. for f in root.findall(".//filament"):
  193. try:
  194. # id is 1-based in slice_info.config
  195. fid = int(f.get("id", 0))
  196. properties[fid] = {
  197. "type": f.get("type", "PLA"),
  198. "diameter": DEFAULT_FILAMENT_DIAMETER,
  199. "density": DEFAULT_FILAMENT_DENSITY,
  200. }
  201. except ValueError:
  202. pass # Skip filament entries with unparseable IDs
  203. # Try project_settings.config for density values
  204. if "Metadata/project_settings.config" in zf.namelist():
  205. content = zf.read("Metadata/project_settings.config").decode()
  206. try:
  207. data = json.loads(content)
  208. densities = data.get("filament_density", [])
  209. for i, density in enumerate(densities):
  210. # project_settings uses 0-based indexing, convert to 1-based
  211. fid = i + 1
  212. if fid not in properties:
  213. properties[fid] = {
  214. "type": "",
  215. "diameter": DEFAULT_FILAMENT_DIAMETER,
  216. }
  217. try:
  218. properties[fid]["density"] = float(density)
  219. except (ValueError, TypeError):
  220. properties[fid]["density"] = DEFAULT_FILAMENT_DENSITY
  221. except json.JSONDecodeError:
  222. pass # Skip malformed project_settings.config JSON
  223. except Exception:
  224. pass # Return whatever properties were collected before the error
  225. return properties
  226. def _first_settings_id(value: object) -> str | None:
  227. """A ``*_settings_id`` value is usually a string, occasionally a list (one
  228. entry per extruder). Return the first non-empty string, else None."""
  229. if isinstance(value, str):
  230. return value.strip() or None
  231. if isinstance(value, list):
  232. for item in value:
  233. if isinstance(item, str) and item.strip():
  234. return item.strip()
  235. return None
  236. def extract_embedded_presets_from_3mf(zf: zipfile.ZipFile) -> dict[str, str | None]:
  237. """Read the printer / process preset names a 3MF project was prepared with.
  238. BambuStudio / OrcaSlicer write the chosen preset names into
  239. ``Metadata/project_settings.config`` (``printer_settings_id`` and
  240. ``print_settings_id``). The SliceModal uses them to default its printer
  241. and process dropdowns to what the file was sliced for (#1325) instead of
  242. blindly taking the first listed preset.
  243. Returns ``{"printer": <name|None>, "process": <name|None>}``. Every failure
  244. mode (missing config, malformed JSON, unexpected shape) yields ``None``
  245. values so the modal falls back to its own defaults.
  246. """
  247. result: dict[str, str | None] = {"printer": None, "process": None}
  248. try:
  249. if "Metadata/project_settings.config" not in zf.namelist():
  250. return result
  251. data = json.loads(zf.read("Metadata/project_settings.config").decode())
  252. except (KeyError, ValueError, OSError):
  253. return result
  254. if not isinstance(data, dict):
  255. return result
  256. result["printer"] = _first_settings_id(data.get("printer_settings_id"))
  257. result["process"] = _first_settings_id(data.get("print_settings_id"))
  258. return result
  259. def extract_nozzle_mapping_from_3mf(zf: zipfile.ZipFile) -> dict[int, int] | None:
  260. """Extract per-slot nozzle/extruder mapping from a 3MF file.
  261. On dual-nozzle printers (H2D, H2D Pro), each filament slot is assigned to a
  262. specific nozzle. The slicer may override user preferences when using "Auto For
  263. Flush" mode, so the actual assignment comes from slice_info.config group_id
  264. attributes, not from the user's filament_nozzle_map preference.
  265. Priority:
  266. 1. group_id on <filament> elements in slice_info.config (actual assignment)
  267. 2. filament_nozzle_map in project_settings.config (user preference fallback)
  268. Both are mapped through physical_extruder_map to get MQTT extruder IDs (0=right, 1=left).
  269. Args:
  270. zf: An open ZipFile of the 3MF archive
  271. Returns:
  272. Dictionary mapping {slot_id: extruder_id} for dual-nozzle files,
  273. or None if single-nozzle, missing data, or parse error.
  274. """
  275. try:
  276. if "Metadata/project_settings.config" not in zf.namelist():
  277. return None
  278. content = zf.read("Metadata/project_settings.config").decode()
  279. data = json.loads(content)
  280. physical_extruder_map = data.get("physical_extruder_map")
  281. if not physical_extruder_map or len(physical_extruder_map) <= 1:
  282. return None # Single-nozzle printer
  283. # Check if only one extruder is active.
  284. # If so, we can skip the mapping and just assign all slots to that extruder.
  285. # extruder_nozzle_stats format: ["Standard#0|High Flow#0", "Standard#1"]
  286. # Each entry = one extruder. Format: <NozzleVolumeType>#<count>[|...]
  287. # #N is the count of physical nozzles of that type (0 = none installed).
  288. # Types: Standard, High Flow, Hybrid, TPU High Flow
  289. active_extruders = []
  290. for stats_str in data.get("extruder_nozzle_stats") or []:
  291. nozzle_counts = [n.partition("#")[2] for n in stats_str.split("|")]
  292. active_extruders.append(1 if any(c not in ("0", "") for c in nozzle_counts) else 0)
  293. # Parse slice_info once: needed by both the single-active shortcut
  294. # (to verify the slice is actually single-group, #1825) and Priority 1.
  295. si_root: ET.Element | None = None
  296. distinct_group_ids: set[int] = set()
  297. if "Metadata/slice_info.config" in zf.namelist():
  298. si_content = zf.read("Metadata/slice_info.config").decode()
  299. si_root = ET.fromstring(si_content)
  300. for filament_elem in si_root.findall(".//filament"):
  301. gid = filament_elem.get("group_id")
  302. if gid is not None:
  303. try:
  304. distinct_group_ids.add(int(gid))
  305. except (ValueError, TypeError):
  306. pass
  307. # Single-active shortcut: only safe when the slice actually uses one
  308. # group. extruder_nozzle_stats can under-report a second installed
  309. # nozzle when its volume-type differs from the profile's enumerated
  310. # types (HT-AMS / High-Flow asymmetry on H2D, #1825); without this
  311. # guard the shortcut collapses a real multi-extruder slice onto one
  312. # nozzle and the group_id mapping below is skipped.
  313. if sum(active_extruders) == 1 and len(distinct_group_ids) <= 1:
  314. nozzle_mapping: dict[int, int] = {}
  315. active_idx = active_extruders.index(1)
  316. target_extruder = int(physical_extruder_map[active_idx])
  317. if si_root is not None:
  318. for filament_elem in si_root.findall(".//filament"):
  319. try:
  320. nozzle_mapping[int(filament_elem.get("id"))] = target_extruder
  321. except (ValueError, TypeError):
  322. pass
  323. return nozzle_mapping or None
  324. # Priority 1: Use group_id from slice_info filament elements.
  325. # This reflects the actual slicer assignment (respects "Auto For Flush").
  326. nozzle_mapping: dict[int, int] = {}
  327. if si_root is not None:
  328. for filament_elem in si_root.findall(".//filament"):
  329. group_id_str = filament_elem.get("group_id")
  330. filament_id_str = filament_elem.get("id")
  331. if group_id_str is not None and filament_id_str:
  332. try:
  333. group_id = int(group_id_str)
  334. slot_id = int(filament_id_str)
  335. if group_id < len(physical_extruder_map):
  336. nozzle_mapping[slot_id] = int(physical_extruder_map[group_id])
  337. except (ValueError, TypeError, IndexError):
  338. pass
  339. if nozzle_mapping:
  340. return nozzle_mapping
  341. # Priority 2: Fall back to filament_nozzle_map (user preference).
  342. # This is correct when the user manually assigned nozzles, but may be
  343. # wrong when the slicer overrides via "Auto For Flush".
  344. filament_nozzle_map = data.get("filament_nozzle_map")
  345. if not filament_nozzle_map:
  346. return None
  347. for i, slicer_ext_str in enumerate(filament_nozzle_map):
  348. slot_id = i + 1
  349. try:
  350. slicer_ext = int(slicer_ext_str)
  351. if slicer_ext < len(physical_extruder_map):
  352. nozzle_mapping[slot_id] = int(physical_extruder_map[slicer_ext])
  353. except (ValueError, TypeError, IndexError):
  354. pass
  355. return nozzle_mapping if nozzle_mapping else None
  356. except Exception:
  357. return None
  358. @dataclass(frozen=True)
  359. class PlateMetadata:
  360. """Combined per-plate slice_info.config values from a single 3MF parse.
  361. Bundles the three fields the queue listing needs so a queue poll opens and
  362. parses each 3MF once instead of three times (#2573). ``filament_usage`` is
  363. the full per-filament list (other callers — usage tracking, Spoolman — need
  364. it); ``filament_used_grams`` is its ``used_g`` sum, precomputed here so the
  365. queue path doesn't re-sum on every hit.
  366. """
  367. print_time_seconds: int | None = None
  368. filament_usage: list[dict] = field(default_factory=list)
  369. bed_type: str | None = None
  370. filament_used_grams: float = 0.0
  371. _EMPTY_PLATE_METADATA = PlateMetadata()
  372. # Revision-keyed cache for parsed per-plate metadata. Queue polling re-lists the
  373. # same unchanged 3MFs every few seconds per connected client (#2573); without a
  374. # cache each row costs a ZIP open + XML parse. The key includes the file's
  375. # mtime_ns and size so a replaced or edited file transparently gets a fresh
  376. # entry — no manual invalidation needed. Bounded LRU + lock so it stays small
  377. # and is safe to touch from worker threads.
  378. _PLATE_METADATA_CACHE: "OrderedDict[tuple, PlateMetadata]" = OrderedDict()
  379. _PLATE_METADATA_CACHE_LOCK = Lock()
  380. _PLATE_METADATA_CACHE_MAX = 512
  381. def clear_plate_metadata_cache() -> None:
  382. """Drop all cached per-plate metadata (used by tests)."""
  383. with _PLATE_METADATA_CACHE_LOCK:
  384. _PLATE_METADATA_CACHE.clear()
  385. def _parse_plate_metadata_uncached(file_path: Path, plate_id: int | None) -> PlateMetadata:
  386. """Open the 3MF once and pull print time, filament usage and bed type.
  387. Replicates the per-field ``plate_id=None`` behaviour of the three legacy
  388. helpers exactly: usage collects every ``<filament>`` in the file, while
  389. print time and bed type come from the first ``<plate>``.
  390. """
  391. try:
  392. with zipfile.ZipFile(file_path, "r") as zf:
  393. if "Metadata/slice_info.config" not in zf.namelist():
  394. return _EMPTY_PLATE_METADATA
  395. content = zf.read("Metadata/slice_info.config").decode()
  396. root = ET.fromstring(content)
  397. except Exception as e:
  398. logger.warning("Failed to read plate metadata from %s: %s", file_path, e)
  399. return _EMPTY_PLATE_METADATA
  400. def _plate_index(plate_elem) -> int | None:
  401. for meta in plate_elem.findall("metadata"):
  402. if meta.get("key") == "index":
  403. try:
  404. return int(meta.get("value", "0"))
  405. except ValueError:
  406. return None
  407. return None
  408. def _collect_filaments(plate_elem) -> list[dict]:
  409. out: list[dict] = []
  410. for f in plate_elem.findall("filament"):
  411. filament_id = f.get("id")
  412. # Both the used_g float() and the id int() must stay inside the guard:
  413. # a non-numeric id or used_g is silently skipped (matches the legacy
  414. # helpers, which tolerated garbage rows rather than raising — a raise
  415. # here would 500 the whole queue listing).
  416. try:
  417. used_amount = float(f.get("used_g", "0"))
  418. if filament_id:
  419. out.append(
  420. {
  421. "slot_id": int(filament_id),
  422. "used_g": used_amount,
  423. "type": f.get("type", ""),
  424. "color": f.get("color", ""),
  425. }
  426. )
  427. except (ValueError, TypeError):
  428. continue
  429. return out
  430. print_time: int | None = None
  431. bed_type: str | None = None
  432. filament_usage: list[dict] = []
  433. matched_plate = None
  434. if plate_id is not None:
  435. for plate_elem in root.findall(".//plate"):
  436. if _plate_index(plate_elem) == plate_id:
  437. matched_plate = plate_elem
  438. break
  439. else:
  440. matched_plate = root.find(".//plate")
  441. if matched_plate is not None:
  442. for meta in matched_plate.findall("metadata"):
  443. key = meta.get("key")
  444. if key == "prediction" and print_time is None:
  445. try:
  446. print_time = int(meta.get("value", "0"))
  447. except ValueError:
  448. print_time = None
  449. elif key == "curr_bed_type" and meta.get("value"):
  450. bed_type = (meta.get("value") or "").strip()
  451. if plate_id is not None:
  452. if matched_plate is not None:
  453. filament_usage = _collect_filaments(matched_plate)
  454. else:
  455. # Legacy plate_id=None usage: every filament in the file, not just plate 1.
  456. for f in root.findall(".//filament"):
  457. filament_id = f.get("id")
  458. # int()/float() both guarded — a garbage id/used_g row is skipped, not raised.
  459. try:
  460. used_amount = float(f.get("used_g", "0"))
  461. if filament_id:
  462. filament_usage.append(
  463. {
  464. "slot_id": int(filament_id),
  465. "used_g": used_amount,
  466. "type": f.get("type", ""),
  467. "color": f.get("color", ""),
  468. }
  469. )
  470. except (ValueError, TypeError):
  471. continue
  472. return PlateMetadata(
  473. print_time_seconds=print_time,
  474. filament_usage=filament_usage,
  475. bed_type=bed_type,
  476. filament_used_grams=sum(f["used_g"] for f in filament_usage),
  477. )
  478. def extract_plate_metadata_from_3mf(file_path: Path, plate_id: int | None = None) -> PlateMetadata:
  479. """Return combined per-plate metadata, cached by file revision (#2573).
  480. The result is keyed by ``(path, plate_id, mtime_ns, size)`` so an unchanged
  481. file is parsed at most once; a replaced/edited file re-parses automatically.
  482. The returned ``PlateMetadata`` is shared and MUST be treated as read-only —
  483. callers that need a mutable filament list get a copy from the wrappers below.
  484. """
  485. file_path = Path(file_path)
  486. try:
  487. stat = file_path.stat()
  488. except OSError:
  489. # File missing/unreadable: parse (which will return empty) but don't
  490. # cache — the file may appear later and we don't want a sticky miss.
  491. return _parse_plate_metadata_uncached(file_path, plate_id)
  492. key = (str(file_path), plate_id, stat.st_mtime_ns, stat.st_size)
  493. with _PLATE_METADATA_CACHE_LOCK:
  494. cached = _PLATE_METADATA_CACHE.get(key)
  495. if cached is not None:
  496. _PLATE_METADATA_CACHE.move_to_end(key)
  497. return cached
  498. metadata = _parse_plate_metadata_uncached(file_path, plate_id)
  499. with _PLATE_METADATA_CACHE_LOCK:
  500. _PLATE_METADATA_CACHE[key] = metadata
  501. _PLATE_METADATA_CACHE.move_to_end(key)
  502. while len(_PLATE_METADATA_CACHE) > _PLATE_METADATA_CACHE_MAX:
  503. _PLATE_METADATA_CACHE.popitem(last=False)
  504. return metadata
  505. def extract_filament_usage_from_3mf(file_path: Path, plate_id: int | None = None) -> list[dict]:
  506. """Extract per-filament total usage from 3MF slice_info.config.
  507. This extracts the slicer-estimated total usage per filament slot,
  508. not the per-layer breakdown.
  509. Args:
  510. file_path: Path to the 3MF file
  511. plate_id: Optional plate index to filter for (for multi-plate files)
  512. Returns:
  513. List of filament usage dictionaries:
  514. [{"slot_id": 1, "used_g": 50.5, "type": "PLA", "color": "#FF0000"}, ...]
  515. """
  516. # Delegate to the cached combined parse (#2573). Return fresh dicts so callers
  517. # that mutate the list don't corrupt the shared cached PlateMetadata.
  518. return [dict(f) for f in extract_plate_metadata_from_3mf(file_path, plate_id).filament_usage]
  519. def extract_print_time_from_3mf(file_path: Path, plate_id: int | None = None) -> int | None:
  520. """Extract the slicer's predicted print time from a 3MF's slice_info.config.
  521. Multi-plate 3MFs carry one ``<plate><metadata key="prediction" .../></plate>``
  522. per plate. The archive-level `print_time_seconds` is the sum across all plates
  523. (see services/archive.py:200-264, #1593). For per-plate UI / notifications,
  524. callers re-read the 3MF and request the specific plate's value via this helper.
  525. Args:
  526. file_path: Path to the 3MF file
  527. plate_id: Plate index to filter for; if None, returns the first plate's
  528. ``prediction`` (matches the legacy single-plate read).
  529. Returns:
  530. Predicted print time in seconds, or None if not found / unparseable.
  531. """
  532. return extract_plate_metadata_from_3mf(file_path, plate_id).print_time_seconds
  533. def extract_bed_type_from_3mf(file_path: Path, plate_id: int | None = None) -> str | None:
  534. """Extract the build plate type (`curr_bed_type`) for a specific plate (#1281).
  535. ``archive.bed_type`` is captured at ingest time but is one value per archive
  536. (the first plate's `curr_bed_type` — see services/archive.py:235). For a
  537. multi-plate 3MF where different plates target different beds (e.g. a 40-plate
  538. file mixing PEI + Engineering), the archive-level value lies. When a queue
  539. item or print modal targets a specific plate, this re-reads the 3MF and
  540. returns that plate's actual bed type.
  541. Args:
  542. file_path: Path to the 3MF file
  543. plate_id: Plate index to filter for; if None, returns the first plate's
  544. ``curr_bed_type`` (matches the archive-level capture).
  545. Returns:
  546. Bed type string (e.g. "Textured PEI Plate"), or None if not found.
  547. """
  548. return extract_plate_metadata_from_3mf(file_path, plate_id).bed_type
  549. # Header values exposed as `{placeholder}` substitutions inside snippets.
  550. # Aliases let users write Prusa-style names (`{max_layer_z}`) that map onto
  551. # Bambu/Orca header keys (`max_z_height`).
  552. _HEADER_PLACEHOLDER_ALIASES = {
  553. "max_layer_z": "max_z_height",
  554. "max_print_height": "max_z_height",
  555. "total_layers": "total_layer_number",
  556. }
  557. _HEADER_KEY_RE = re.compile(r"^;\s*([^:]+?)\s*:\s*(.+?)\s*$")
  558. _PLACEHOLDER_RE = re.compile(r"\{([a-zA-Z_][a-zA-Z0-9_]*)\}")
  559. _START_GCODE_END_MARKER = "; MACHINE_START_GCODE_END"
  560. _EXECUTABLE_BLOCK_END_MARKER = "; EXECUTABLE_BLOCK_END"
  561. def _parse_3mf_gcode_header(content: str) -> dict[str, str]:
  562. """Parse the `; HEADER_BLOCK_START..END` block into a normalised dict.
  563. Keys are lowercased, ` [units]` suffixes stripped, and spaces converted
  564. to underscores so callers can look up `total_layer_number` regardless of
  565. whether the source line is `; total layer number: 80` or
  566. `; total filament length [mm] : 12155.34`.
  567. """
  568. header: dict[str, str] = {}
  569. in_header = False
  570. for raw_line in content.splitlines():
  571. line = raw_line.strip()
  572. if line == "; HEADER_BLOCK_START":
  573. in_header = True
  574. continue
  575. if line == "; HEADER_BLOCK_END":
  576. break
  577. if not in_header:
  578. continue
  579. m = _HEADER_KEY_RE.match(line)
  580. if not m:
  581. continue
  582. key, value = m.group(1), m.group(2)
  583. key = re.sub(r"\s*\[[^\]]*\]\s*$", "", key)
  584. key = key.strip().lower().replace(" ", "_")
  585. header[key] = value
  586. return header
  587. def _select_plate_gcode_name(names: list[str], plate_id: int | None) -> str | None:
  588. """Pick a plate's ``.gcode`` member out of a 3MF namelist.
  589. Prefers ``plate_<id>.gcode``, then falls back to the first ``.gcode``
  590. member so single-plate files — and files from slicers that don't use the
  591. plate naming convention — still resolve.
  592. """
  593. gcodes = [n for n in names if n.endswith(".gcode")]
  594. if not gcodes:
  595. return None
  596. if plate_id is not None:
  597. suffix = f"plate_{plate_id}.gcode"
  598. for name in gcodes:
  599. if name.endswith(suffix):
  600. return name
  601. return gcodes[0]
  602. # The header block sits at the very top of the plate G-code. Read only that
  603. # much: a sliced plate is routinely tens of megabytes and `ZipFile.read()`
  604. # would inflate all of it to reach ~40 lines.
  605. _HEADER_READ_LIMIT_BYTES = 64 * 1024
  606. def extract_max_z_height_from_3mf(file_path: Path, plate_id: int | None = None) -> float | None:
  607. """Return the plate's ``max_z_height`` in mm, or None if not knowable.
  608. This is the Z the toolhead sat at for the final layer — the same value
  609. Bambu's own end G-code adds its bed-drop offset to (``G1 Z{max_layer_z +
  610. 100}``). #2547 uses it to put the plate back into camera framing before the
  611. finish photo, which is only safe because it is a height the printer was
  612. physically at seconds earlier.
  613. None means "don't know" and callers must treat it as such rather than
  614. substituting a default: the file may be unreadable, carry no plate G-code,
  615. or come from a slicer that writes no ``max_z_height`` header. Guessing a
  616. height here would command a Z move to somewhere the nozzle has never been.
  617. """
  618. try:
  619. with zipfile.ZipFile(file_path, "r") as zf:
  620. target = _select_plate_gcode_name(zf.namelist(), plate_id)
  621. if target is None:
  622. return None
  623. with zf.open(target, "r") as fh:
  624. head = fh.read(_HEADER_READ_LIMIT_BYTES)
  625. except (OSError, zipfile.BadZipFile, KeyError) as e:
  626. logger.debug("max_z_height: cannot read %s: %s", file_path, e)
  627. return None
  628. raw = _parse_3mf_gcode_header(head.decode("utf-8", errors="ignore")).get("max_z_height")
  629. if raw is None:
  630. return None
  631. try:
  632. value = float(raw)
  633. except ValueError:
  634. logger.debug("max_z_height: unusable value %r in %s", raw, file_path)
  635. return None
  636. # Zero or negative means the header key is present but meaningless. Passed
  637. # on as a height it would become a move *toward* the bed, so drop it.
  638. return value if value > 0 else None
  639. def _substitute_placeholders(snippet: str, header: dict[str, str]) -> str:
  640. """Replace `{var}` placeholders with header values, leaving unknowns intact."""
  641. def repl(m: re.Match) -> str:
  642. name = m.group(1)
  643. value = header.get(name)
  644. if value is None:
  645. alias = _HEADER_PLACEHOLDER_ALIASES.get(name)
  646. if alias is not None:
  647. value = header.get(alias)
  648. if value is None:
  649. logger.warning(
  650. "G-code injection: placeholder {%s} not found in 3MF header; leaving as-is",
  651. name,
  652. )
  653. return m.group(0)
  654. return value
  655. return _PLACEHOLDER_RE.sub(repl, snippet)
  656. def _inject_start_at_marker(content: str, snippet: str) -> str:
  657. """Insert snippet immediately before `; MACHINE_START_GCODE_END`.
  658. The marker sits at the bottom of the printer's startup block — bed heat,
  659. homing, and nozzle prime are already done, so injected snippets land in
  660. the same place a slicer-side custom-start-gcode would. Falls back to
  661. prepending if the marker isn't present (older files / non-Bambu slicers).
  662. """
  663. marker_idx = content.find(_START_GCODE_END_MARKER)
  664. if marker_idx == -1:
  665. logger.warning(
  666. "G-code injection: '%s' not found, prepending start snippet to whole file",
  667. _START_GCODE_END_MARKER,
  668. )
  669. return snippet.rstrip("\n") + "\n" + content
  670. line_start = content.rfind("\n", 0, marker_idx)
  671. line_start = 0 if line_start == -1 else line_start + 1
  672. return content[:line_start] + snippet.rstrip("\n") + "\n" + content[line_start:]
  673. def _inject_end_before_marker(content: str, snippet: str) -> str:
  674. """Insert snippet immediately before `; EXECUTABLE_BLOCK_END`.
  675. The end snippet must run *inside* the executable block. Bambu firmware
  676. (verified on a P1S) does not execute G-code that sits after
  677. `; EXECUTABLE_BLOCK_END`, so appending to the file end silently drops the
  678. snippet — auto-eject / plate-clear moves never fire. Inserting before the
  679. marker places the snippet after the printer's own machine-end sequence but
  680. still within the executed block. Falls back to appending at the file end if
  681. the marker isn't present.
  682. """
  683. marker_idx = content.find(_EXECUTABLE_BLOCK_END_MARKER)
  684. if marker_idx == -1:
  685. logger.warning(
  686. "G-code injection: '%s' not found, appending end snippet to file end",
  687. _EXECUTABLE_BLOCK_END_MARKER,
  688. )
  689. return content.rstrip("\n") + "\n" + snippet.rstrip("\n") + "\n"
  690. line_start = content.rfind("\n", 0, marker_idx)
  691. line_start = 0 if line_start == -1 else line_start + 1
  692. return content[:line_start] + snippet.rstrip("\n") + "\n" + content[line_start:]
  693. def inject_gcode_into_3mf(
  694. source_path: Path,
  695. plate_id: int,
  696. start_gcode: str | None,
  697. end_gcode: str | None,
  698. ):
  699. """Create a temp copy of a 3MF with G-code injected at start/end.
  700. Snippets support `{placeholder}` substitution against values parsed from
  701. the 3MF G-code header block (e.g. `{max_layer_z}` → `16.00`). Start
  702. snippets are anchored to the `; MACHINE_START_GCODE_END` marker so they
  703. run after the printer's own startup (#422). End snippets are inserted just
  704. before `; EXECUTABLE_BLOCK_END` so they run inside the executable block —
  705. Bambu firmware (P1S) ignores g-code placed after that marker.
  706. The plate's `.gcode.md5` sidecar is recomputed so firmware that validates
  707. it against the gcode (e.g. P1S) still accepts the modified file.
  708. Args:
  709. source_path: Path to the original 3MF file.
  710. plate_id: Plate number (1-indexed) to inject into.
  711. start_gcode: G-code to insert after printer startup, or None.
  712. end_gcode: G-code to append, or None.
  713. Returns:
  714. Path to temp file with injected G-code, or None if injection failed.
  715. Caller is responsible for cleaning up the temp file.
  716. """
  717. import tempfile
  718. if not start_gcode and not end_gcode:
  719. return None
  720. try:
  721. # Find the target gcode file inside the 3MF
  722. with zipfile.ZipFile(source_path, "r") as zf:
  723. # Plate-specific gcode first, else the first one in the file.
  724. target_gcode = _select_plate_gcode_name(zf.namelist(), plate_id)
  725. if target_gcode is None:
  726. return None
  727. # Read and modify gcode content
  728. gcode_content = zf.read(target_gcode).decode("utf-8", errors="ignore")
  729. header = _parse_3mf_gcode_header(gcode_content)
  730. if start_gcode:
  731. resolved = _substitute_placeholders(start_gcode, header)
  732. # Log the post-substitution snippet so the actually-injected G-code
  733. # (placeholders like {max_layer_z} already resolved) is visible at DEBUG.
  734. logger.debug("G-code injection [%s]: resolved START snippet:\n%s", target_gcode, resolved)
  735. gcode_content = _inject_start_at_marker(gcode_content, resolved)
  736. if end_gcode:
  737. resolved = _substitute_placeholders(end_gcode, header)
  738. logger.debug("G-code injection [%s]: resolved END snippet:\n%s", target_gcode, resolved)
  739. gcode_content = _inject_end_before_marker(gcode_content, resolved)
  740. # The printer validates the plate gcode against an embedded
  741. # `<plate>.gcode.md5` sidecar (uppercase hex, no trailing newline).
  742. # Rewriting the gcode without refreshing this hash makes firmware
  743. # reject the file at load (P1S: HMS 0500-4003 "unable to parse"),
  744. # so recompute it from the exact bytes we're about to write.
  745. gcode_bytes = gcode_content.encode("utf-8")
  746. md5_name = target_gcode + ".md5"
  747. # Not a security hash — this reproduces Bambu's `.gcode.md5` sidecar
  748. # format, so flag it as non-security for the linters (ruff S324 / bandit B324).
  749. md5_value = hashlib.md5(gcode_bytes, usedforsecurity=False).hexdigest().upper().encode("ascii")
  750. # Write modified 3MF to temp file
  751. with tempfile.NamedTemporaryFile(delete=False, suffix=".3mf") as tmp:
  752. tmp_path = Path(tmp.name)
  753. with zipfile.ZipFile(tmp_path, "w", zipfile.ZIP_DEFLATED) as zf_write:
  754. for item in zf.namelist():
  755. info = zf.getinfo(item)
  756. if item == target_gcode:
  757. zf_write.writestr(info, gcode_bytes)
  758. elif item == md5_name:
  759. zf_write.writestr(info, md5_value)
  760. else:
  761. zf_write.writestr(info, zf.read(item))
  762. return tmp_path
  763. except Exception:
  764. # Clean up temp file on error
  765. if "tmp_path" in locals() and tmp_path.exists():
  766. tmp_path.unlink(missing_ok=True)
  767. return None
  768. def extract_project_filaments_from_3mf(zf: zipfile.ZipFile) -> list[dict]:
  769. """Project-wide AMS slot config from ``Metadata/project_settings.config``.
  770. Returns one dict per configured AMS slot in slot order (1-indexed), with
  771. ``type`` and ``color`` populated from the project's ``filament_type`` and
  772. ``filament_colour`` arrays. ``used_grams`` / ``used_meters`` are 0 because
  773. project_settings carries the configuration, not per-print usage — the
  774. fields exist for shape compatibility with the slice_info-derived list.
  775. The SliceModal needs this on **unsliced** project files: slice_info.config
  776. is empty until Bambu Studio has actually sliced the project, but the user
  777. can still pick filament profiles for a slice we're about to perform.
  778. """
  779. if "Metadata/project_settings.config" not in zf.namelist():
  780. return []
  781. try:
  782. proj = json.loads(zf.read("Metadata/project_settings.config").decode())
  783. except (ValueError, OSError):
  784. return []
  785. if not isinstance(proj, dict):
  786. return []
  787. types_arr = proj.get("filament_type") or []
  788. colors_arr = proj.get("filament_colour") or []
  789. slot_count = max(
  790. len(types_arr) if isinstance(types_arr, list) else 0, len(colors_arr) if isinstance(colors_arr, list) else 0
  791. )
  792. out: list[dict] = []
  793. for i in range(slot_count):
  794. out.append(
  795. {
  796. "slot_id": i + 1,
  797. "type": types_arr[i] if i < len(types_arr) and isinstance(types_arr[i], str) else "",
  798. "color": colors_arr[i] if i < len(colors_arr) and isinstance(colors_arr[i], str) else "",
  799. "used_grams": 0,
  800. "used_meters": 0,
  801. }
  802. )
  803. return out
  804. def expand_to_project_slots(zf: zipfile.ZipFile, used: list[dict]) -> list[dict]:
  805. """Widen a used-only filament list to one entry per project slot.
  806. ``used`` is the slice_info-derived list: only the slots whose G-code
  807. actually consumed filament, each carrying real usage figures. That is the
  808. right answer for print-time AMS matching, and the wrong one for the slice
  809. modal, because the list the modal builds is **positional** — index 0 is
  810. slot 1 all the way down to the ``filament_N.json`` parts handed to the CLI.
  811. A source whose only used slot is 4 therefore produced a single dropdown
  812. whose pick the CLI bound to slot 1, leaving slot 4 — the one the model
  813. prints with — on whatever the source had baked in (#2712).
  814. Returns the project's slots in slot order, each flagged ``used_in_plate``.
  815. Rows present in ``used`` are kept whole, so their usage figures, resolved
  816. type/colour and ``tray_info_idx`` survive; the rest come from the project
  817. configuration with zero usage. A used slot beyond the project's slot count
  818. is appended rather than dropped — the caller asked for a superset, and
  819. silently losing the one slot that prints would be the original bug again.
  820. ``used`` is returned unchanged when the file carries no project settings
  821. to widen against: a narrower-than-ideal list still prints correctly, an
  822. invented one might not.
  823. """
  824. project = extract_project_filaments_from_3mf(zf)
  825. if not project:
  826. return used
  827. by_slot = {f["slot_id"]: f for f in used}
  828. out: list[dict] = []
  829. for slot in project:
  830. known = by_slot.pop(slot["slot_id"], None)
  831. if known is not None:
  832. known["used_in_plate"] = True
  833. out.append(known)
  834. else:
  835. slot["used_in_plate"] = False
  836. out.append(slot)
  837. # Anything slice_info reported that the project doesn't declare.
  838. for leftover in by_slot.values():
  839. leftover["used_in_plate"] = True
  840. out.append(leftover)
  841. out.sort(key=lambda f: f["slot_id"])
  842. return out
  843. def extract_support_filament_slots_from_3mf(zf: zipfile.ZipFile) -> set[int]:
  844. """Slots referenced by the process settings for support material.
  845. Supports aren't attached to object geometry — they're generated by
  846. the slicer's process pass — so :func:`extract_plate_extruder_set_from_3mf`,
  847. which walks per-object extruder metadata + paint_color triangles,
  848. doesn't see them. Callers that need the complete set of slots a
  849. plate print will exercise (e.g. the SliceModal's filament-
  850. substitution logic) must union this in — otherwise a support-only
  851. slot (typical PLA-model + PVA-support setup) looks "unused" and its
  852. user-picked profile gets silently overwritten with slot 1's,
  853. producing a single-material print (#1881).
  854. Returns the empty set when supports are disabled, ``support_filament``
  855. / ``support_interface_filament`` are 0 (== "same as model"), the
  856. project has no embedded settings, or the file isn't a valid 3MF.
  857. """
  858. if "Metadata/project_settings.config" not in zf.namelist():
  859. return set()
  860. try:
  861. cfg = json.loads(zf.read("Metadata/project_settings.config").decode("utf-8"))
  862. except (json.JSONDecodeError, UnicodeDecodeError, OSError):
  863. return set()
  864. if not isinstance(cfg, dict):
  865. return set()
  866. # BambuStudio serialises bool config options as string "1"/"0" in
  867. # project_settings.config, but forks / older versions occasionally
  868. # write real booleans or ints — accept anything that isn't
  869. # unambiguously falsy.
  870. enable = cfg.get("enable_support")
  871. if enable in (False, 0, "0", "false", "False", "", None):
  872. return set()
  873. out: set[int] = set()
  874. for key in ("support_filament", "support_interface_filament"):
  875. raw = cfg.get(key)
  876. if raw is None:
  877. continue
  878. try:
  879. slot = int(raw)
  880. except (ValueError, TypeError):
  881. continue
  882. # Slot 0 means "same as model" — no dedicated slot to preserve.
  883. if slot > 0:
  884. out.add(slot)
  885. return out
  886. _PAINT_COLOR_ATTR_RE = re.compile(rb'paint_color="([0-9A-Fa-f]+)"')
  887. # Painted-face quadtree leaves include both real filament assignments and
  888. # tiny edit artifacts (single-leaf accidents from "tried a colour, undid,
  889. # repainted with a different one"). The threshold's only job is dropping
  890. # accidents — anything the user spent meaningful effort on must survive.
  891. # 5% of an object's painted triangles is well below any 60/40 / 70/30 /
  892. # 33/33/33 split a real two- or three-colour print would hit, so all
  893. # intentional colours are kept; one-off single-leaf paints (typically
  894. # 0.1-1.5% in observed projects) are filtered. Note that this fallback
  895. # path runs ONLY when the preview-slice path can't reach the sidecar; in
  896. # the normal flow the slicer's own pruning produces the canonical list and
  897. # this threshold isn't reached.
  898. _PAINT_NOISE_THRESHOLD = 0.05
  899. def extract_plate_extruder_set_from_3mf(zf: zipfile.ZipFile, plate_id: int) -> set[int]:
  900. """Extruder/AMS slot indices (1-indexed) used by objects on ``plate_id``.
  901. Three sources are unioned because Bambu Studio splits per-object extruder
  902. info across THREE places depending on how the user assigned colours:
  903. 1. ``model_settings.config`` — top-level ``<metadata key="extruder">``
  904. on each ``<object>`` (the "default extruder" for the whole object).
  905. 2. ``model_settings.config`` — per-``<part>`` ``<metadata key="extruder">``
  906. overrides (used when the user split an object into multiple parts
  907. with distinct filaments).
  908. 3. ``3D/Objects/object_*.model`` — ``paint_color`` attributes on
  909. individual ``<triangle>`` elements (used when the user "painted" a
  910. face with a different filament). The encoding is a hex string where
  911. each nibble is a TriangleSelector tree node: ``0`` = unpainted leaf,
  912. ``F`` = branch (4 children follow), ``1``..``E`` = leaf painted with
  913. extruder N. We don't decode the tree — every leaf-paint nibble in
  914. the string IS the extruder number, so a flat scan over hex chars
  915. yields the correct set without recursive parsing.
  916. Without (3) the painted-face data is invisible: model_settings says
  917. every object on a multi-color plate uses extruder 1 by default but the
  918. actual print uses 3, 4, 12 etc. via face paint, so the SliceModal would
  919. render only one filament dropdown for what's clearly a multi-colour
  920. print (#1150 follow-up).
  921. """
  922. if "Metadata/model_settings.config" not in zf.namelist():
  923. return set()
  924. try:
  925. root = ET.fromstring(zf.read("Metadata/model_settings.config").decode())
  926. except (ET.ParseError, OSError):
  927. return set()
  928. # Pass 1: object → set of extruders from XML metadata (sources 1 + 2)
  929. # plus the per-object .model file path so we can later scan source 3.
  930. object_extruders: dict[str, set[int]] = {}
  931. object_model_paths: dict[str, list[str]] = {}
  932. for obj_elem in root.findall(".//object"):
  933. obj_id = obj_elem.get("id")
  934. if not obj_id:
  935. continue
  936. extruders: set[int] = set()
  937. top = obj_elem.find("metadata[@key='extruder']")
  938. if top is not None:
  939. try:
  940. v = int(top.get("value", "0"))
  941. if v > 0:
  942. extruders.add(v)
  943. except (ValueError, TypeError):
  944. pass
  945. for part_elem in obj_elem.findall(".//part"):
  946. part_ext = part_elem.find("metadata[@key='extruder']")
  947. if part_ext is None:
  948. continue
  949. try:
  950. v = int(part_ext.get("value", "0"))
  951. if v > 0:
  952. extruders.add(v)
  953. except (ValueError, TypeError):
  954. pass
  955. object_extruders[obj_id] = extruders
  956. # Pass 2: 3dmodel.model maps each <object id="N"> to its component
  957. # .model file path(s). Bambu wraps object IDs that match
  958. # model_settings.config IDs around <components><component
  959. # path="/3D/Objects/object_K.model" objectid="..." /></components>.
  960. # Strip xmlns prefixes on attributes so ElementTree can find them
  961. # without namespace gymnastics — `p:path` becomes `path` etc.
  962. if "3D/3dmodel.model" in zf.namelist():
  963. try:
  964. raw = zf.read("3D/3dmodel.model").decode()
  965. stripped = re.sub(r'xmlns:?\w*="[^"]*"', "", raw)
  966. stripped = re.sub(r"<(/?)\w+:", r"<\1", stripped)
  967. stripped = re.sub(r" \w+:(\w+=)", r" \1", stripped)
  968. model_root = ET.fromstring(stripped)
  969. for obj_elem in model_root.findall(".//object"):
  970. oid = obj_elem.get("id")
  971. if not oid:
  972. continue
  973. comps = obj_elem.find("components")
  974. if comps is None:
  975. continue
  976. paths = []
  977. for c in comps.findall("component"):
  978. p = c.get("path")
  979. if p:
  980. paths.append(p.lstrip("/"))
  981. if paths:
  982. object_model_paths[oid] = paths
  983. except (ET.ParseError, OSError):
  984. pass # No 3dmodel — paint scan just won't apply
  985. # Pass 3: scan paint_color attrs in each per-object .model file. Cache
  986. # by file path because two objects often share the same component tree.
  987. paint_cache: dict[str, set[int]] = {}
  988. def _scan_paint(path: str) -> set[int]:
  989. if path in paint_cache:
  990. return paint_cache[path]
  991. out: set[int] = set()
  992. if path not in zf.namelist():
  993. paint_cache[path] = out
  994. return out
  995. try:
  996. data = zf.read(path)
  997. except OSError:
  998. paint_cache[path] = out
  999. return out
  1000. # Per-extruder triangle coverage. Each painted triangle may have
  1001. # multiple leaf nibbles (the quadtree subdivides the face into
  1002. # painted regions); we count one triangle per unique extruder per
  1003. # match so the resulting fraction is "what share of painted
  1004. # triangles include at least one leaf with extruder N". Noise from
  1005. # one-off edit artifacts is filtered out at the threshold below.
  1006. extruder_triangles: dict[int, int] = {}
  1007. total_painted = 0
  1008. for match in _PAINT_COLOR_ATTR_RE.finditer(data):
  1009. total_painted += 1
  1010. seen: set[int] = set()
  1011. for ch in match.group(1):
  1012. # Hex digit → 4-bit value. 0 = unpainted leaf, F = branch
  1013. # (decoded recursively but children are encoded inline, so
  1014. # we'll see them on later iterations). 1-E = leaf painted
  1015. # with extruder N.
  1016. if ch in b"123456789":
  1017. seen.add(ch - 0x30)
  1018. elif ch in b"ABCDEabcde":
  1019. seen.add((ch & 0x4F) - 0x37)
  1020. for e in seen:
  1021. extruder_triangles[e] = extruder_triangles.get(e, 0) + 1
  1022. if total_painted > 0:
  1023. cutoff = max(1, int(total_painted * _PAINT_NOISE_THRESHOLD))
  1024. for ext, count in extruder_triangles.items():
  1025. if count >= cutoff:
  1026. out.add(ext)
  1027. paint_cache[path] = out
  1028. return out
  1029. # Walk plates — collect extruders for objects on the requested plate.
  1030. used: set[int] = set()
  1031. for plate_elem in root.findall(".//plate"):
  1032. plater_id = None
  1033. for meta in plate_elem.findall("metadata"):
  1034. if meta.get("key") == "plater_id":
  1035. try:
  1036. plater_id = int(meta.get("value", ""))
  1037. except (ValueError, TypeError):
  1038. pass
  1039. break
  1040. if plater_id != plate_id:
  1041. continue
  1042. for inst in plate_elem.findall("model_instance"):
  1043. for inst_meta in inst.findall("metadata"):
  1044. if inst_meta.get("key") != "object_id":
  1045. continue
  1046. obj_id = inst_meta.get("value")
  1047. if not obj_id:
  1048. continue
  1049. used.update(object_extruders.get(obj_id, set()))
  1050. for path in object_model_paths.get(obj_id, []):
  1051. used.update(_scan_paint(path))
  1052. break
  1053. return used