threemf_tools.py 61 KB

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