slicer_filament_resolver.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. """Shared spool ``slicer_filament`` → ``(tray_info_idx, setting_id)`` resolver.
  2. The internal-inventory and Spoolman-inventory routes both need to translate
  3. a spool's stored slicer-preset reference (cloud preset ID / local preset ID /
  4. GF-prefix Bambu filament ID / free-text material name) into the two MQTT
  5. fields ``ams_filament_setting`` consumes: the printer-side ``tray_info_idx``
  6. (filament_id) and the slicer-side ``setting_id``. The two routes were drifting
  7. in lockstep before #1713 — internal mode resolved everything, Spoolman mode
  8. silently dropped slicer_filament on the floor and only the generic-material
  9. fallback fired. This module is the single chokepoint so the two flows can't
  10. diverge again.
  11. Resolver outcomes:
  12. - Returns ``("", "", None)`` when ``slicer_filament`` is empty, unresolvable,
  13. or sanitised away as a slicer-rejected value (literal material name,
  14. PFUS / PFCN cloud setting_id). The caller is responsible for the
  15. generic-material fallback when this happens.
  16. - Returns ``(tray_info_idx, setting_id, sub_brand_override)`` otherwise.
  17. The third element is non-empty when a cloud-detail lookup or a local-
  18. preset name provides a more specific brand label than the spool's own
  19. ``"<brand> <material> <subtype>"`` concatenation — the caller should
  20. prefer it over its computed default.
  21. The resolver is async because the GFS / PFUS / PFCN branches need cloud
  22. authentication and the local-preset branch reads ``LocalPreset`` from the
  23. DB. ``current_user=None`` reads the shared cloud sign-in, the one used with
  24. login off. With login on that one is usually empty, so a caller without a
  25. user of its own (tag auto-assign, the Spoolman link) gets no cloud lookup, and
  26. cloud-prefix presets fall back to a static ``normalize_slicer_filament``
  27. parse. API-key assigns and the replay on insert pass the key's owner or the
  28. assigning user instead (#3519).
  29. """
  30. from __future__ import annotations
  31. import json
  32. import logging
  33. import re
  34. from dataclasses import dataclass
  35. from sqlalchemy import select
  36. from sqlalchemy.ext.asyncio import AsyncSession
  37. from backend.app.core.permissions import Permission
  38. from backend.app.models.user import User
  39. from backend.app.utils.filament_finish import different_finish
  40. from backend.app.utils.filament_ids import (
  41. GENERIC_FILAMENT_IDS,
  42. GENERIC_IDS_REPLACED_ON_REUSE,
  43. filament_id_to_setting_id,
  44. normalize_slicer_filament,
  45. orca_to_bambu_filament_id,
  46. setting_id_to_filament_id,
  47. )
  48. from backend.app.utils.filament_types import is_material_name
  49. from backend.app.utils.slicer_strings import first_slicer_string
  50. logger = logging.getLogger(__name__)
  51. # Orca Cloud profile ids are UUIDs, the one preset reference in this codebase
  52. # with no letter prefix to key off. A spool stores the bare id (the spool form
  53. # persists ``preset.setting_id`` verbatim), so shape is all there is to go on.
  54. _ORCA_PROFILE_ID = re.compile(r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}")
  55. @dataclass(frozen=True)
  56. class OrcaFilamentLookup:
  57. """Outcome of resolving an Orca Cloud profile to a printer filament id.
  58. ``filament_id`` is empty when nothing usable was found; ``reason`` then says
  59. why, so a caller in front of a user can say so instead of quietly sending
  60. a generic id (#3216). ``source`` is ``"own"`` for the profile's own id,
  61. ``"inherited"`` for one taken from a parent.
  62. """
  63. filament_id: str = ""
  64. name: str | None = None
  65. filament_type: str | None = None
  66. source: str = ""
  67. reason: str = ""
  68. # How many ``inherits`` hops to follow before giving up. Orca presets are one
  69. # or two deep in practice; the cap only guards against a cycle in hand-edited
  70. # profiles.
  71. _MAX_INHERITS_DEPTH = 5
  72. def _content_filament_id(content: dict) -> str:
  73. """A profile's filament_id as the printer knows it.
  74. One copied from an OrcaSlicer system preset is Orca's own id ("OFMUWNkp"),
  75. which the printer cannot resolve; it is translated with Orca's own table,
  76. and one the table does not know reads as none, so the lookup goes on to
  77. the parents (#3387)."""
  78. raw = content.get("filament_id")
  79. if isinstance(raw, list):
  80. raw = raw[0] if raw else None
  81. return orca_to_bambu_filament_id(raw.strip()) if isinstance(raw, str) else ""
  82. def _catalog_filament_id(preset_name: str) -> str:
  83. """Bambu catalog id for a Bambu system preset name, or ``""``.
  84. An Orca profile that inherits a system preset ("Bambu PLA Basic @BBL H2D")
  85. carries no id of its own. Its parent's id is the one the printer and the
  86. slicer both know -- OrcaSlicer since 2.5 translates the Bambu catalog ids
  87. at the printer boundary -- so it beats a generic for the material.
  88. """
  89. from backend.app.api.routes.cloud import _BUILTIN_FILAMENT_NAMES
  90. base = preset_name.split("@")[0].strip().lstrip("#").strip().lower()
  91. if not base:
  92. return ""
  93. for fid, fname in _BUILTIN_FILAMENT_NAMES.items():
  94. if fname.lower() == base:
  95. return fid
  96. return ""
  97. async def lookup_orca_filament_id(
  98. db: AsyncSession,
  99. current_user: User | None,
  100. profile_id: str,
  101. ) -> OrcaFilamentLookup:
  102. """Look up the filament id an Orca Cloud profile puts in an AMS slot.
  103. OrcaSlicer resolves a slot to a preset by ``filament_id`` alone, so this is
  104. the value that decides whether "Sync filaments" finds the user's profile or
  105. falls back to Generic (#3216). Tried in order: the profile's own id; the
  106. nearest parent among the user's Orca profiles that has one; the Bambu
  107. catalog id of a Bambu system parent.
  108. Best-effort by construction: this runs inside spool assignment and slot
  109. configuration, so a missing pairing, a revoked token or a lapsed permission
  110. must degrade to the caller's fallback rather than fail the request. That is
  111. also why ``clear_on_auth_failure=False`` -- Orca reports every refresh
  112. rejection with one composite reason, so this caller cannot tell a real
  113. revocation from a lost rotation race and must not wipe a working pairing on
  114. it. The Orca Cloud routes hit the same failure in front of a user and clear
  115. there.
  116. """
  117. if current_user is not None and not current_user.has_permission(Permission.ORCA_CLOUD_AUTH.value):
  118. logger.info("Orca filament lookup skipped for %r: caller lacks orca_cloud:auth", profile_id)
  119. return OrcaFilamentLookup(reason="no_permission")
  120. svc = None
  121. try:
  122. from backend.app.api.routes.orca_cloud import _build_authenticated_service
  123. svc = await _build_authenticated_service(db, current_user, clear_on_auth_failure=False)
  124. profile = await svc.get_profile(profile_id)
  125. content = profile.get("content") if isinstance(profile, dict) else None
  126. if not isinstance(content, dict):
  127. logger.info("Orca filament lookup for %r: profile has no content", profile_id)
  128. return OrcaFilamentLookup(reason="no_filament_id")
  129. raw_name = profile.get("name")
  130. name = raw_name if isinstance(raw_name, str) and raw_name else None
  131. filament_type = _preset_filament_type(content.get("filament_type"))
  132. own = _content_filament_id(content)
  133. if own:
  134. logger.info("Orca filament lookup for %r: own filament_id %r", profile_id, own)
  135. return OrcaFilamentLookup(own, name, filament_type, source="own")
  136. parent = content.get("inherits")
  137. parent = parent.strip() if isinstance(parent, str) else ""
  138. by_name: dict[str, dict] | None = None
  139. for _ in range(_MAX_INHERITS_DEPTH):
  140. if not parent:
  141. break
  142. if by_name is None:
  143. # One more pull, only for a profile that needs its parent. A
  144. # failure here keeps the name and type already read, as the
  145. # lookup returned them before it followed parents.
  146. by_name = {}
  147. try:
  148. entries = await svc.list_profiles()
  149. except Exception as e:
  150. logger.info("Orca filament lookup for %r: could not read its parents: %s", profile_id, e)
  151. return OrcaFilamentLookup(name=name, filament_type=filament_type, reason="lookup_failed")
  152. for entry in entries:
  153. entry_content = entry.get("content") if isinstance(entry, dict) else None
  154. if not isinstance(entry_content, dict):
  155. continue
  156. for key in (entry.get("name"), entry_content.get("name")):
  157. if isinstance(key, str) and key:
  158. by_name.setdefault(key, entry_content)
  159. parent_content = by_name.get(parent)
  160. if parent_content is None:
  161. catalog = _catalog_filament_id(parent)
  162. if catalog:
  163. logger.info(
  164. "Orca filament lookup for %r: catalog filament_id %r of system parent %r",
  165. profile_id,
  166. catalog,
  167. parent,
  168. )
  169. return OrcaFilamentLookup(catalog, name, filament_type, source="inherited")
  170. break
  171. inherited = _content_filament_id(parent_content)
  172. if inherited:
  173. logger.info(
  174. "Orca filament lookup for %r: filament_id %r inherited from %r", profile_id, inherited, parent
  175. )
  176. return OrcaFilamentLookup(inherited, name, filament_type, source="inherited")
  177. next_parent = parent_content.get("inherits")
  178. parent = next_parent.strip() if isinstance(next_parent, str) else ""
  179. logger.info("Orca filament lookup for %r: no filament_id on the profile or its parents", profile_id)
  180. return OrcaFilamentLookup(name=name, filament_type=filament_type, reason="no_filament_id")
  181. except Exception as e:
  182. # INFO, not DEBUG: this is the line that explains a slot coming out as
  183. # Generic in a support bundle (#3216).
  184. logger.info("Orca filament lookup failed for %r: %s", profile_id, e)
  185. return OrcaFilamentLookup(reason="lookup_failed")
  186. finally:
  187. # A raise in `finally` escapes the `except` above, so guard it: closing
  188. # an httpx client must never be what fails a spool assignment.
  189. if svc is not None:
  190. try:
  191. await svc.close()
  192. except Exception as e: # noqa: BLE001 - close() is best-effort
  193. logger.debug("Orca client close failed after lookup of %r: %s", profile_id, e)
  194. async def _orca_filament_id(
  195. db: AsyncSession,
  196. current_user: User | None,
  197. profile_id: str,
  198. ) -> tuple[str, str | None, str | None]:
  199. """``(filament_id, name, filament_type)`` for the spool resolver below --
  200. all empty/None when nothing was found, which leaves it on its generic
  201. fallback. See ``lookup_orca_filament_id``."""
  202. found = await lookup_orca_filament_id(db, current_user, profile_id)
  203. return (found.filament_id, found.name, found.filament_type)
  204. def _preset_filament_type(raw: object) -> str | None:
  205. """Read a slicer preset's ``filament_type`` field.
  206. Bambu Studio and OrcaSlicer both store it as a one-element array
  207. (``["PLA"]``); some hand-written and older profiles store a bare string,
  208. and Orca Cloud can return it INI-quoted (``'"PLA"'``, #3380).
  209. ``orca_profiles._extract_filament_fields`` accepts both and this has to
  210. agree with it, since that is what fills ``LocalPreset.filament_type``.
  211. The value is still run through ``printer_filament_type`` by the caller.
  212. That is a no-op for every type the app knows -- ``TestTheMaterialsBambuddyOffers``
  213. pins exactly that -- and a pass-through for a type it does not, so nothing
  214. the slicer says is discarded. It only bites on a hand-edited profile whose
  215. ``filament_type`` is a product line, which is the case this whole module
  216. exists to keep out of an AMS slot.
  217. """
  218. return first_slicer_string(raw)
  219. def reusable_slot_filament_id(
  220. current_tray_info_idx: str | None,
  221. current_tray_type: str | None,
  222. current_tray_sub_brands: str | None,
  223. tray_type: str,
  224. spool_text: str,
  225. ) -> str:
  226. """The slot's own filament id, when a spool without a preset may keep it.
  227. A spool whose preset is empty or unresolvable would otherwise get the
  228. generic id for its material, which turns a genuine Bambu PLA Basic into
  229. Generic PLA. When the slot already holds a specific filament id of the same
  230. type, keeping it is closer. Shared by both inventory modes (#3433): the
  231. Spoolman route went straight to the generic id.
  232. Not kept: a generic id, a cloud user preset (PFUS/PFCN), a material name
  233. left in that field by a Bambuddy from before #2902, another type, and
  234. another finish when both name one (a Silk spool does not take a Matte id).
  235. ``spool_text`` is the spool's material and subtype.
  236. """
  237. current = (current_tray_info_idx or "").strip()
  238. if (
  239. current
  240. and current not in GENERIC_IDS_REPLACED_ON_REUSE
  241. and not current.startswith("PFUS")
  242. and not current.startswith("PFCN")
  243. and not is_material_name(current)
  244. and current_tray_type
  245. and current_tray_type.upper() == tray_type.upper()
  246. and not different_finish(spool_text, current_tray_sub_brands)
  247. ):
  248. return current
  249. return ""
  250. async def resolve_slicer_filament(
  251. *,
  252. db: AsyncSession,
  253. current_user: User | None,
  254. slicer_filament: str | None,
  255. slicer_filament_name: str | None,
  256. material: str | None,
  257. ) -> tuple[str, str, str | None, str | None]:
  258. """Resolve a spool's slicer-preset reference to printer-side ids.
  259. ``slicer_filament``: the spool's stored reference (e.g. ``"GFA01"``,
  260. ``"PFUS990b6e19965353"``, ``"38"`` for a numeric LocalPreset id, or
  261. free-text). May be empty or None — returns the empty tuple in that case.
  262. ``slicer_filament_name``: optional builtin-name realignment hint. When
  263. set and the resolved tray_info_idx maps to a different builtin name,
  264. the resolver swaps to the builtin whose name matches (e.g. user picked
  265. "Bambu PLA Matte" but the cloud lookup landed on "Bambu PLA Basic").
  266. ``material``: spool material string for the local-preset fallback
  267. branch when the LocalPreset's setting JSON doesn't carry a filament_id.
  268. Returns ``(tray_info_idx, setting_id, sub_brand_override, type_override)``
  269. — all empty when nothing resolved. ``sub_brand_override`` is non-None when
  270. a more specific brand label is available (cloud detail name or local preset
  271. name); ``None`` means the caller should use its own default.
  272. ``type_override`` is the preset's own ``filament_type`` when the preset
  273. carries one — the slicer's answer to what the material is, rather than one
  274. parsed out of the spool's material column. It is what the caller should
  275. write into ``tray_type``. ``None`` means no preset said, and the caller
  276. falls back to reducing the spool's material (``printer_filament_type``).
  277. Raised in the #2902 thread by @doncaruana: a preset has to be chosen from
  278. a list the slicer defines, so its type needs no interpreting. It cannot be
  279. the only source, though — ``slicer_filament`` is nullable on a spool while
  280. ``material`` is required, and the spool this issue was reported for had no
  281. preset at all.
  282. """
  283. sf = (slicer_filament or "").strip()
  284. if not sf:
  285. return ("", "", None, None)
  286. tray_info_idx = ""
  287. setting_id = ""
  288. sub_brand_override: str | None = None
  289. type_override: str | None = None
  290. base_sf = sf.split("_")[0] if "_" in sf else sf
  291. # Cloud-side preset IDs in three known shapes:
  292. # GFS… — Bambu official cloud preset
  293. # PFUS… — cloud user-created preset
  294. # PFCN… — cloud shared / partner preset (e.g. Polymaker's "(Custom)"
  295. # Bambu Lab H2D variant, #1648)
  296. # All three need a cloud-detail lookup to extract the underlying
  297. # filament_id; without it the raw cloud id ends up in tray_info_idx
  298. # and the printer's calibration table can't resolve it.
  299. # Source order is Orca Cloud, Bambu Cloud, local import, generic fallback.
  300. # Orca goes first because its ids are the only ones identified by shape
  301. # rather than prefix -- and because, before #3003, a UUID fell through every
  302. # branch below into ``normalize_slicer_filament``, which passes anything it
  303. # does not recognise straight through. A 36-character UUID then went into
  304. # tray_info_idx, an 8-character field, and the slot ended up pointing at the
  305. # first 8 characters of a UUID: the same failure the PFUS guard at the
  306. # bottom of this function exists for.
  307. if _ORCA_PROFILE_ID.fullmatch(base_sf):
  308. tray_info_idx, orca_name, orca_type = await _orca_filament_id(db, current_user, base_sf)
  309. if orca_type:
  310. type_override = orca_type
  311. if orca_name:
  312. sub_brand_override = orca_name.split("@")[0].strip()
  313. # setting_id is left empty here: the UUID is what the slicer cannot
  314. # resolve, and unlike a PFUS there is no cloud id form it accepts
  315. # instead. All three callers then derive one from the filament_id
  316. # (`filament_id_to_setting_id`), which is what keeps the slot from
  317. # going out half configured -- the same path a local import takes.
  318. elif base_sf.startswith("GFS") or base_sf.startswith("PFUS") or base_sf.startswith("PFCN"):
  319. setting_id = base_sf
  320. try:
  321. from backend.app.api.routes.cloud import build_authenticated_cloud
  322. cloud = await build_authenticated_cloud(db, current_user)
  323. if cloud is not None and cloud.is_authenticated:
  324. try:
  325. detail = await cloud.get_setting_detail(base_sf)
  326. # The preset's own type, straight from the slicer's own
  327. # profile -- no parsing of a product name (#2902). The
  328. # preset JSON is nested under ``setting``; some responses
  329. # carry it at the top level instead, the same shape spread
  330. # ``preset_resolver`` documents.
  331. cloud_setting = detail.get("setting")
  332. type_override = _preset_filament_type(
  333. (cloud_setting if isinstance(cloud_setting, dict) else detail).get("filament_type")
  334. )
  335. # A custom preset's OWN filament_id is the only thing that
  336. # gets it into an AMS slot as itself: the printer stores
  337. # that id, the slicer matches its presets against it, and
  338. # the 8-character field fits it exactly ("P" + 7 hex).
  339. #
  340. # Bambu Cloud normally returns it on the envelope, which is
  341. # what the captures in #1053 show for a Studio-created
  342. # preset (filament_id: "Pbd31b30"). The `setting` fallback
  343. # here is belt-and-braces for a response that carries it in
  344. # the preset JSON instead, the same spread `filament_type`
  345. # above has to handle -- no captured response has needed it
  346. # yet, and it costs a dict lookup to be ready for one.
  347. #
  348. # An Orca-created preset has no filament_id anywhere: the
  349. # envelope says null and `setting` is a delta from the base
  350. # (#1053 again). Those legitimately fall to base_id below
  351. # and reach the slicer as the profile they inherit from --
  352. # an OrcaSlicer preset-format gap, filed upstream as
  353. # OrcaSlicer PR #13315, not something resolvable here.
  354. own_filament_id = detail.get("filament_id") or (
  355. cloud_setting.get("filament_id") if isinstance(cloud_setting, dict) else None
  356. )
  357. # An official preset's id comes from its full setting_id
  358. # (#3387). The detail read above is the suffix-free base's,
  359. # and for some bases that is another filament: "GFSA05" is
  360. # Bambu PLA Matte @BBL X1, while "GFSA05_07" -- and the
  361. # bare id Bambuddy builds from GFA05 -- is Bambu PLA Silk.
  362. # Its type and name only count when it is the same filament.
  363. # A spool named after that very preset is the exception: it
  364. # was picked as Bambu's legacy bare preset ("Bambu TPU 95A
  365. # @BBL X1C", "GFSU00" -> GFU01), not built by Bambuddy, and
  366. # Bambu's own id is then the right one.
  367. official = setting_id_to_filament_id(sf) if base_sf.startswith("GFS") else ""
  368. detail_name = detail.get("name")
  369. if (
  370. official
  371. and own_filament_id
  372. and isinstance(detail_name, str)
  373. and detail_name.strip()
  374. and detail_name.strip() == (slicer_filament_name or "").strip()
  375. ):
  376. official = own_filament_id
  377. if official:
  378. tray_info_idx = official
  379. if own_filament_id and own_filament_id != official:
  380. type_override = None
  381. else:
  382. cloud_name = detail.get("name", "")
  383. if cloud_name:
  384. sub_brand_override = cloud_name.split("@")[0].strip()
  385. elif own_filament_id:
  386. tray_info_idx = own_filament_id
  387. cloud_name = detail.get("name", "")
  388. if cloud_name:
  389. sub_brand_override = cloud_name.replace(r"@.*$", "").split("@")[0].strip()
  390. elif detail.get("base_id"):
  391. tray_info_idx = setting_id_to_filament_id(detail["base_id"])
  392. finally:
  393. await cloud.close()
  394. elif cloud is not None:
  395. await cloud.close()
  396. elif not base_sf.startswith("GFS"):
  397. # A custom preset has no static form; without a sign-in the slot
  398. # falls back to a generic filament, which nothing else reports
  399. # (#3519). An official GFS one parses fine without the cloud.
  400. logger.warning(
  401. "Slicer-filament resolve: custom preset %r not looked up, no Bambu Cloud sign-in "
  402. "for this caller; the slot may get a generic filament",
  403. sf,
  404. )
  405. except Exception as e:
  406. logger.warning("Slicer-filament resolve: cloud lookup failed for %r: %s", sf, e)
  407. if not tray_info_idx:
  408. tray_info_idx, setting_id = normalize_slicer_filament(sf)
  409. elif base_sf.startswith("GF"):
  410. tray_info_idx, setting_id = normalize_slicer_filament(sf)
  411. else:
  412. try:
  413. local_id = int(sf)
  414. from backend.app.models.local_preset import LocalPreset as LP
  415. lp_result = await db.execute(select(LP).where(LP.id == local_id, LP.preset_type == "filament"))
  416. lp = lp_result.scalar_one_or_none()
  417. if lp:
  418. # The slicer's own answer, extracted from the profile at import
  419. # time by ``orca_profiles``. Preferred over anything parsed out
  420. # of the spool's material column (#2902).
  421. type_override = _preset_filament_type(lp.filament_type)
  422. # Local preset's setting JSON carries the printer-recognized
  423. # filament_id (e.g. "P4d64437") — use that directly so the
  424. # slicer can resolve the specific preset. Falls through to
  425. # generic material id only when the JSON doesn't carry one.
  426. lp_filament_id = ""
  427. if lp.setting:
  428. try:
  429. setting_data = json.loads(lp.setting)
  430. raw_fid = setting_data.get("filament_id")
  431. if isinstance(raw_fid, str) and raw_fid:
  432. lp_filament_id = raw_fid
  433. except (json.JSONDecodeError, AttributeError):
  434. pass
  435. if lp_filament_id:
  436. tray_info_idx = lp_filament_id
  437. setting_id = filament_id_to_setting_id(lp_filament_id)
  438. else:
  439. # Deliberately not widened to cover product-line materials
  440. # ("PLA+", "HTPLA") the way the callers' own fallbacks were
  441. # (#2902). Returning an id here rather than "" would skip
  442. # the caller's whole no-id block, and with it the slot-reuse
  443. # branch that keeps a printer's calibrated preset -- so the
  444. # widening belongs there, after reuse has had its turn.
  445. mat = (material or lp.filament_type or "").upper().strip()
  446. tray_info_idx = (
  447. GENERIC_FILAMENT_IDS.get(mat) or GENERIC_FILAMENT_IDS.get(mat.split("-")[0].split(" ")[0]) or ""
  448. )
  449. if lp.name:
  450. sub_brand_override = lp.name.split("@")[0].strip()
  451. except (ValueError, TypeError):
  452. tray_info_idx, setting_id = normalize_slicer_filament(sf)
  453. # Realign tray_info_idx to a builtin whose name matches slicer_filament_name
  454. # when the current resolution lands on a builtin with a different name
  455. # (e.g. cloud detail returned PLA Basic but the spool was labelled PLA Matte).
  456. if tray_info_idx and slicer_filament_name:
  457. from backend.app.api.routes.cloud import _BUILTIN_FILAMENT_NAMES
  458. expected_name = _BUILTIN_FILAMENT_NAMES.get(tray_info_idx, "")
  459. if expected_name and expected_name != slicer_filament_name:
  460. for fid, fname in _BUILTIN_FILAMENT_NAMES.items():
  461. if fname == slicer_filament_name:
  462. tray_info_idx = fid
  463. setting_id = filament_id_to_setting_id(fid)
  464. break
  465. # Defend against tray_info_idx values the slicer cannot resolve. Three
  466. # shapes leak through and must be discarded so the caller's generic-
  467. # material fallback can rescue the slot:
  468. # 1. Literal material names ("PLA", "PETG-CF") that pass through
  469. # normalize_slicer_filament unchanged when the spool's slicer_filament
  470. # is free-text rather than a real preset ID. Product lines ("PLA+",
  471. # "HTPLA") count as material names too -- see is_material_name, which
  472. # is shared with the slot-reuse check that must agree with this.
  473. # 2. PFUS-prefix cloud setting_ids — valid as setting_id but rejected
  474. # by the slicer as tray_info_idx (the printer's calibration table
  475. # indexes by filament_id, and a PFUS isn't one). This normally gets
  476. # realigned to a P-prefix local id via the caller's printer_kp
  477. # lookup, but a caller with no cloud sign-in (see the module
  478. # docstring) gets no cloud lookup and would leave the raw PFUS in
  479. # tray_info_idx — overwriting a correctly-configured slot.
  480. # 3. PFCN-prefix cloud shared / partner presets (e.g. Polymaker's
  481. # "(Custom)" H2D variants, #1648) — same shape problem as PFUS.
  482. # 4. Orca Cloud profile UUIDs, when the branch above could not reach the
  483. # profile to trade one for its filament_id (#3003). Worst of the four
  484. # at 36 characters against an 8-character field.
  485. # Valid tray_info_idx values: "GF" + letter + digits (Bambu official) or
  486. # "P" followed by hex (user/local presets, NOT "PFUS" or "PFCN").
  487. if tray_info_idx and (
  488. is_material_name(tray_info_idx)
  489. or tray_info_idx.startswith("PFUS")
  490. or tray_info_idx.startswith("PFCN")
  491. or _ORCA_PROFILE_ID.fullmatch(tray_info_idx)
  492. ):
  493. tray_info_idx = ""
  494. # Preserve setting_id when it's still a valid slicer reference
  495. # (PFUS / PFCN cloud user/shared preset, or GFS Bambu official
  496. # preset). The slicer accepts these as setting_id even though
  497. # they're rejected as tray_info_idx; without preservation the
  498. # slicer falls back to whatever generic filament the caller's
  499. # tray_info_idx fallback produces and shows "Generic <Material>"
  500. # instead of the user's actual custom preset (#1815). Material-name
  501. # leaks (e.g. setting_id="PETG") are still cleared — those are
  502. # never valid slicer references.
  503. if not (
  504. setting_id
  505. and (setting_id.startswith("PFUS") or setting_id.startswith("PFCN") or setting_id.startswith("GFS"))
  506. ):
  507. setting_id = ""
  508. return (tray_info_idx, setting_id, sub_brand_override, type_override)