slicer.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. """Pydantic schemas for slice requests."""
  2. import re
  3. from typing import Any, Literal
  4. from pydantic import BaseModel, Field, model_validator
  5. # `#RRGGBB` or `#RRGGBBAA`. Bambu Studio writes the 6-digit form into
  6. # `filament_colour` but accepts and round-trips the 8-digit one, and the AMS
  7. # reports colours with an alpha byte, so both have to pass.
  8. _HEX_COLOUR = re.compile(r"#(?:[0-9a-fA-F]{6}|[0-9a-fA-F]{8})")
  9. class PresetRef(BaseModel):
  10. """A source-aware reference to a printer / process / filament preset.
  11. The SliceModal pulls dropdown options from four tiers (orca_cloud /
  12. cloud / local / standard). At submit time the client sends one of these
  13. per slot so the backend knows where to fetch the preset content from at
  14. slice time. ``cloud`` is Bambu Cloud (kept as the bare name for backward
  15. compatibility with existing requests); ``orca_cloud`` is Orca Cloud.
  16. """
  17. source: Literal["orca_cloud", "cloud", "local", "standard"]
  18. id: str = Field(
  19. ...,
  20. description=(
  21. "Orca Cloud profile id, Bambu Cloud setting_id, local DB row id (stringified), or standard preset name."
  22. ),
  23. )
  24. class SliceRequest(BaseModel):
  25. """Body for `POST /library/files/{file_id}/slice`.
  26. Two preset shapes are accepted per slot for backwards-compatibility:
  27. - **Legacy** — bare integer ``*_preset_id`` fields point into the
  28. ``local_presets`` table. Existing clients (and stale browser tabs after
  29. a Bambuddy upgrade) keep working unchanged.
  30. - **Source-aware** — ``*_preset`` carries an explicit
  31. ``{source, id}``. Required for cloud / standard tiers; also accepted
  32. (and equivalent) for local presets when the client is on the new modal.
  33. Exactly one of each pair must be set; the validator normalises legacy
  34. integer ids into a ``PresetRef(source='local', id=str(id))`` so the
  35. downstream resolver only deals with one shape.
  36. """
  37. # Legacy fields — kept optional so older clients continue to work.
  38. printer_preset_id: int | None = Field(
  39. default=None,
  40. description="DEPRECATED: prefer printer_preset. LocalPreset id with preset_type='printer'.",
  41. )
  42. process_preset_id: int | None = Field(
  43. default=None,
  44. description="DEPRECATED: prefer process_preset. LocalPreset id with preset_type='process'.",
  45. )
  46. filament_preset_id: int | None = Field(
  47. default=None,
  48. description="DEPRECATED: prefer filament_preset. LocalPreset id with preset_type='filament'.",
  49. )
  50. # Source-aware fields — set by the new SliceModal.
  51. printer_preset: PresetRef | None = None
  52. process_preset: PresetRef | None = None
  53. filament_preset: PresetRef | None = None
  54. # Multi-color: one PresetRef per AMS slot the source plate uses. Order is
  55. # significant — the slicer matches index-by-index against the plate's
  56. # filament slots. Always preferred over the legacy singular field; the
  57. # validator promotes a singular field into ``[singular]`` when the list
  58. # is empty so older clients keep working.
  59. filament_presets: list[PresetRef] = Field(default_factory=list)
  60. # Per-slot filament colour, plate-slot-ordered like ``filament_presets``.
  61. # Neither Bambu Studio nor OrcaSlicer store a colour on a *filament preset*
  62. # — it is a per-project property their GUIs set from the plate — so the CLI
  63. # falls back to its compiled-in default (#00AE42, Bambu green) for every
  64. # slice unless something supplies one. That default is what #2977 saw: a
  65. # green plate thumbnail, `filament_colour = #00AE42` in the output, and a
  66. # "Color mismatch" against the AMS slot the print was mapped to.
  67. #
  68. # `default_filament_colour` is NOT a substitute. Measured against a
  69. # 02.08.02.61 sidecar: sending it alone leaves `filament_colour` at
  70. # #00AE42, because the CLI never reads it — it is consumed by the GUI when
  71. # initialising a project. The colour has to be written to `filament_colour`
  72. # itself, which is what this field ends up doing.
  73. filament_colours: list[str] = Field(
  74. default_factory=list,
  75. description=(
  76. "Per-slot filament colour as ``#RRGGBB`` / ``#RRGGBBAA``, in the same "
  77. "plate-slot order as ``filament_presets``. Written onto each resolved "
  78. "filament profile as ``filament_colour`` so the sliced file records the "
  79. "colour actually being printed instead of the slicer's built-in default "
  80. "(#2977). A shorter list than ``filament_presets`` leaves the remaining "
  81. "slots to the fallback chain; an empty string in any position does the "
  82. "same for that one slot. An omitted list (older clients) falls back to "
  83. "the preset's own ``default_filament_colour``, then to the colour the "
  84. "source file's plate was designed with."
  85. ),
  86. )
  87. plate: int | None = Field(
  88. default=None,
  89. ge=0,
  90. description=(
  91. "Plate number to slice. ``None`` defaults to plate 1 on the sidecar "
  92. "(matches the pre-multi-plate behaviour). ``0`` is the sidecar's "
  93. "'all plates' sentinel — produces a single multi-plate 3MF whose "
  94. "``Metadata/plate_N.gcode`` entries cover every plate in the "
  95. "source. ``>= 1`` slices that one plate."
  96. ),
  97. )
  98. export_3mf: bool = Field(
  99. default=False,
  100. description="If true, request a 3MF response with embedded G-code instead of raw G-code.",
  101. )
  102. design_overrides: list[str] | None = Field(
  103. default=None,
  104. description=(
  105. "3MF only. Process setting keys from the source file's "
  106. "``different_settings_to_system`` to carry onto the picked process "
  107. "preset (#2622) — the designer's own wall count, infill, first-layer "
  108. "height and so on, which ``--load-settings`` would otherwise discard. "
  109. "Only keys the source actually lists as changed are applied; anything "
  110. "else is ignored. An empty list is not the same answer as ``None``: "
  111. "it says the caller was shown the file's settings and chose none of "
  112. "them, which also holds back the support carry-over (#1881) for the "
  113. "support keys the file offered, while ``None`` — a caller that "
  114. "predates the per-key choice — leaves that carry-over unconditional."
  115. ),
  116. )
  117. process_overrides: dict[str, Any] | None = Field(
  118. default=None,
  119. description=(
  120. "The user's own process-setting edits from the slice modal's settings "
  121. "panel, as a sparse ``{option_key: value}`` map (layer height, wall "
  122. "count, supports, speeds — OrcaSlicer's process parameter set). Written "
  123. "into the process JSON *after* the source's support settings and the "
  124. "designer's carried tweaks, so an explicit choice here wins over both. "
  125. "Values are normalised to the string forms a process preset stores; "
  126. "keys that aren't valid config keys are dropped rather than failing "
  127. "the slice. ``None``/empty leaves the picked preset untouched."
  128. ),
  129. )
  130. use_embedded_settings: bool = Field(
  131. default=False,
  132. description=(
  133. "3MF only. Slice using the file's embedded "
  134. "``Metadata/project_settings.config`` (the designer's own tweaks — wall "
  135. "count, infill, etc.) instead of the picked printer/process/filament "
  136. "triplet. This is the 'slice as designed' path: no ``--load-settings`` "
  137. "override, so a MakerWorld author's settings survive. Ignored for STL / "
  138. "plain-model 3MF (no embedded profile to honour). The preset refs are "
  139. "still required by the validator but go unused on this path. Only makes "
  140. "sense when the picked printer matches the design's target model — the "
  141. "UI gates the toggle on that; there is no cross-printer re-targeting here "
  142. "(that is exactly what the profile path is for)."
  143. ),
  144. )
  145. bed_type: str | None = Field(
  146. default=None,
  147. max_length=64,
  148. description=(
  149. "Override the process preset's curr_bed_type for this slice. Canonical "
  150. "BambuStudio / OrcaSlicer values: 'Cool Plate', 'Engineering Plate', "
  151. "'High Temp Plate', 'Textured PEI Plate', 'Smooth PEI Plate', "
  152. "'Cool Plate (SuperTack)', 'Supertack Plate'. None ⇒ inherit from the "
  153. "process preset unchanged (#1337)."
  154. ),
  155. )
  156. auto_orient: bool = Field(
  157. default=False,
  158. description=(
  159. "Let the slicer pick each object's orientation before slicing "
  160. "(BambuStudio / OrcaSlicer ``--orient 1``, the GUI's 'Auto orient'). "
  161. "Off by default: it rotates geometry, so a model the designer laid "
  162. "flat on purpose would silently change. Applies on the embedded-"
  163. "settings path too — it is a CLI action, not a profile value (#2548)."
  164. ),
  165. )
  166. auto_arrange: bool = Field(
  167. default=False,
  168. description=(
  169. "Let the slicer lay the objects out on the plate before slicing "
  170. "(``--arrange 1``, the GUI's 'Auto arrange'). Off by default: it "
  171. "repositions objects, discarding a deliberate layout. Forced on "
  172. "regardless for cross-nozzle-class re-slices, where the source's "
  173. "coordinates land in the target's dead zone (#1493). Applies on the "
  174. "embedded-settings path too (#2548)."
  175. ),
  176. )
  177. @model_validator(mode="after")
  178. def normalise_preset_refs(self) -> "SliceRequest":
  179. """Each slot must end up with a `PresetRef` set. Legacy integer ids
  180. become `(source='local', id=str(int))` so the route handler only
  181. deals with the canonical shape. For filament: a non-empty
  182. ``filament_presets`` list satisfies the requirement on its own; an
  183. empty list falls back to the singular fields, which then promote
  184. into a one-element list.
  185. """
  186. for slot, ref_attr, legacy_attr in (
  187. ("printer", "printer_preset", "printer_preset_id"),
  188. ("process", "process_preset", "process_preset_id"),
  189. ):
  190. ref = getattr(self, ref_attr)
  191. legacy_id = getattr(self, legacy_attr)
  192. if ref is None and legacy_id is None:
  193. raise ValueError(
  194. f"{slot} preset is required: provide '{ref_attr}' (preferred) or legacy '{legacy_attr}'"
  195. )
  196. if ref is None:
  197. setattr(self, ref_attr, PresetRef(source="local", id=str(legacy_id)))
  198. # Filament accepts THREE shapes, in priority order:
  199. # 1. filament_presets — multi-color array (new clients)
  200. # 2. filament_preset — source-aware singular (single-color new clients)
  201. # 3. filament_preset_id — legacy bare integer (old clients)
  202. # The first non-empty shape wins; missing all three raises.
  203. if not self.filament_presets:
  204. if self.filament_preset is not None:
  205. self.filament_presets = [self.filament_preset]
  206. elif self.filament_preset_id is not None:
  207. fallback = PresetRef(source="local", id=str(self.filament_preset_id))
  208. self.filament_preset = fallback
  209. self.filament_presets = [fallback]
  210. else:
  211. raise ValueError(
  212. "filament preset is required: provide 'filament_presets' (preferred), "
  213. "'filament_preset', or legacy 'filament_preset_id'"
  214. )
  215. elif self.filament_preset is None:
  216. # Multi-color caller: backfill the singular from the first slot
  217. # so callers that still read the legacy field see a stable value.
  218. self.filament_preset = self.filament_presets[0]
  219. # Colours are pasted straight into a profile the slicer parses, so a
  220. # malformed one is rejected here rather than passed through. Empty
  221. # strings survive: they are how a caller says "no colour for this
  222. # slot" without having to shorten the list and shift every slot after
  223. # it. Normalised to upper-case so a slice never differs from another
  224. # only by the case of a hex digit.
  225. normalised: list[str] = []
  226. for i, colour in enumerate(self.filament_colours):
  227. value = (colour or "").strip()
  228. if not value:
  229. normalised.append("")
  230. continue
  231. if not _HEX_COLOUR.fullmatch(value):
  232. raise ValueError(f"filament_colours[{i}] must be '#RRGGBB' or '#RRGGBBAA', got {colour!r}")
  233. normalised.append("#" + value[1:].upper())
  234. self.filament_colours = normalised
  235. return self
  236. class SliceResponse(BaseModel):
  237. """Response from `POST /library/files/{file_id}/slice`. The result lands
  238. in the user's library as a new ``LibraryFile`` (in the same folder as
  239. the source)."""
  240. library_file_id: int
  241. name: str
  242. print_time_seconds: int
  243. filament_used_g: float
  244. filament_used_mm: float
  245. used_embedded_settings: bool = False
  246. # Set when the source lives in an external folder that could not receive
  247. # the result (read-only, unreachable, not writable), so the file went to
  248. # managed storage instead. Names which of those it was. ``None`` on every
  249. # normal slice. Reported rather than silently absorbed: filing the output
  250. # somewhere the user isn't looking, with no signal, is what made #2810
  251. # impossible to reproduce from the UI.
  252. external_write_fallback: str | None = None
  253. class SliceArchiveResponse(BaseModel):
  254. """Response from `POST /archives/{archive_id}/slice`. The result lands
  255. in the user's archives as a new ``PrintArchive`` row, inheriting
  256. printer / project metadata from the source archive."""
  257. archive_id: int
  258. name: str
  259. print_time_seconds: int
  260. filament_used_g: float
  261. filament_used_mm: float
  262. used_embedded_settings: bool = False