slicer.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. """Pydantic schemas for slice requests."""
  2. from typing import Literal
  3. from pydantic import BaseModel, Field, model_validator
  4. class PresetRef(BaseModel):
  5. """A source-aware reference to a printer / process / filament preset.
  6. The SliceModal pulls dropdown options from four tiers (orca_cloud /
  7. cloud / local / standard). At submit time the client sends one of these
  8. per slot so the backend knows where to fetch the preset content from at
  9. slice time. ``cloud`` is Bambu Cloud (kept as the bare name for backward
  10. compatibility with existing requests); ``orca_cloud`` is Orca Cloud.
  11. """
  12. source: Literal["orca_cloud", "cloud", "local", "standard"]
  13. id: str = Field(
  14. ...,
  15. description=(
  16. "Orca Cloud profile id, Bambu Cloud setting_id, local DB row id (stringified), or standard preset name."
  17. ),
  18. )
  19. class SliceRequest(BaseModel):
  20. """Body for `POST /library/files/{file_id}/slice`.
  21. Two preset shapes are accepted per slot for backwards-compatibility:
  22. - **Legacy** — bare integer ``*_preset_id`` fields point into the
  23. ``local_presets`` table. Existing clients (and stale browser tabs after
  24. a Bambuddy upgrade) keep working unchanged.
  25. - **Source-aware** — ``*_preset`` carries an explicit
  26. ``{source, id}``. Required for cloud / standard tiers; also accepted
  27. (and equivalent) for local presets when the client is on the new modal.
  28. Exactly one of each pair must be set; the validator normalises legacy
  29. integer ids into a ``PresetRef(source='local', id=str(id))`` so the
  30. downstream resolver only deals with one shape.
  31. """
  32. # Legacy fields — kept optional so older clients continue to work.
  33. printer_preset_id: int | None = Field(
  34. default=None,
  35. description="DEPRECATED: prefer printer_preset. LocalPreset id with preset_type='printer'.",
  36. )
  37. process_preset_id: int | None = Field(
  38. default=None,
  39. description="DEPRECATED: prefer process_preset. LocalPreset id with preset_type='process'.",
  40. )
  41. filament_preset_id: int | None = Field(
  42. default=None,
  43. description="DEPRECATED: prefer filament_preset. LocalPreset id with preset_type='filament'.",
  44. )
  45. # Source-aware fields — set by the new SliceModal.
  46. printer_preset: PresetRef | None = None
  47. process_preset: PresetRef | None = None
  48. filament_preset: PresetRef | None = None
  49. # Multi-color: one PresetRef per AMS slot the source plate uses. Order is
  50. # significant — the slicer matches index-by-index against the plate's
  51. # filament slots. Always preferred over the legacy singular field; the
  52. # validator promotes a singular field into ``[singular]`` when the list
  53. # is empty so older clients keep working.
  54. filament_presets: list[PresetRef] = Field(default_factory=list)
  55. plate: int | None = Field(
  56. default=None,
  57. ge=0,
  58. description=(
  59. "Plate number to slice. ``None`` defaults to plate 1 on the sidecar "
  60. "(matches the pre-multi-plate behaviour). ``0`` is the sidecar's "
  61. "'all plates' sentinel — produces a single multi-plate 3MF whose "
  62. "``Metadata/plate_N.gcode`` entries cover every plate in the "
  63. "source. ``>= 1`` slices that one plate."
  64. ),
  65. )
  66. export_3mf: bool = Field(
  67. default=False,
  68. description="If true, request a 3MF response with embedded G-code instead of raw G-code.",
  69. )
  70. design_overrides: list[str] | None = Field(
  71. default=None,
  72. description=(
  73. "3MF only. Process setting keys from the source file's "
  74. "``different_settings_to_system`` to carry onto the picked process "
  75. "preset (#2622) — the designer's own wall count, infill, first-layer "
  76. "height and so on, which ``--load-settings`` would otherwise discard. "
  77. "Only keys the source actually lists as changed are applied; anything "
  78. "else is ignored. ``None``/empty means a plain profile slice."
  79. ),
  80. )
  81. use_embedded_settings: bool = Field(
  82. default=False,
  83. description=(
  84. "3MF only. Slice using the file's embedded "
  85. "``Metadata/project_settings.config`` (the designer's own tweaks — wall "
  86. "count, infill, etc.) instead of the picked printer/process/filament "
  87. "triplet. This is the 'slice as designed' path: no ``--load-settings`` "
  88. "override, so a MakerWorld author's settings survive. Ignored for STL / "
  89. "plain-model 3MF (no embedded profile to honour). The preset refs are "
  90. "still required by the validator but go unused on this path. Only makes "
  91. "sense when the picked printer matches the design's target model — the "
  92. "UI gates the toggle on that; there is no cross-printer re-targeting here "
  93. "(that is exactly what the profile path is for)."
  94. ),
  95. )
  96. bed_type: str | None = Field(
  97. default=None,
  98. max_length=64,
  99. description=(
  100. "Override the process preset's curr_bed_type for this slice. Canonical "
  101. "BambuStudio / OrcaSlicer values: 'Cool Plate', 'Engineering Plate', "
  102. "'High Temp Plate', 'Textured PEI Plate', 'Smooth PEI Plate', "
  103. "'Cool Plate (SuperTack)', 'Supertack Plate'. None ⇒ inherit from the "
  104. "process preset unchanged (#1337)."
  105. ),
  106. )
  107. auto_orient: bool = Field(
  108. default=False,
  109. description=(
  110. "Let the slicer pick each object's orientation before slicing "
  111. "(BambuStudio / OrcaSlicer ``--orient 1``, the GUI's 'Auto orient'). "
  112. "Off by default: it rotates geometry, so a model the designer laid "
  113. "flat on purpose would silently change. Applies on the embedded-"
  114. "settings path too — it is a CLI action, not a profile value (#2548)."
  115. ),
  116. )
  117. auto_arrange: bool = Field(
  118. default=False,
  119. description=(
  120. "Let the slicer lay the objects out on the plate before slicing "
  121. "(``--arrange 1``, the GUI's 'Auto arrange'). Off by default: it "
  122. "repositions objects, discarding a deliberate layout. Forced on "
  123. "regardless for cross-nozzle-class re-slices, where the source's "
  124. "coordinates land in the target's dead zone (#1493). Applies on the "
  125. "embedded-settings path too (#2548)."
  126. ),
  127. )
  128. @model_validator(mode="after")
  129. def normalise_preset_refs(self) -> "SliceRequest":
  130. """Each slot must end up with a `PresetRef` set. Legacy integer ids
  131. become `(source='local', id=str(int))` so the route handler only
  132. deals with the canonical shape. For filament: a non-empty
  133. ``filament_presets`` list satisfies the requirement on its own; an
  134. empty list falls back to the singular fields, which then promote
  135. into a one-element list.
  136. """
  137. for slot, ref_attr, legacy_attr in (
  138. ("printer", "printer_preset", "printer_preset_id"),
  139. ("process", "process_preset", "process_preset_id"),
  140. ):
  141. ref = getattr(self, ref_attr)
  142. legacy_id = getattr(self, legacy_attr)
  143. if ref is None and legacy_id is None:
  144. raise ValueError(
  145. f"{slot} preset is required: provide '{ref_attr}' (preferred) or legacy '{legacy_attr}'"
  146. )
  147. if ref is None:
  148. setattr(self, ref_attr, PresetRef(source="local", id=str(legacy_id)))
  149. # Filament accepts THREE shapes, in priority order:
  150. # 1. filament_presets — multi-color array (new clients)
  151. # 2. filament_preset — source-aware singular (single-color new clients)
  152. # 3. filament_preset_id — legacy bare integer (old clients)
  153. # The first non-empty shape wins; missing all three raises.
  154. if not self.filament_presets:
  155. if self.filament_preset is not None:
  156. self.filament_presets = [self.filament_preset]
  157. elif self.filament_preset_id is not None:
  158. fallback = PresetRef(source="local", id=str(self.filament_preset_id))
  159. self.filament_preset = fallback
  160. self.filament_presets = [fallback]
  161. else:
  162. raise ValueError(
  163. "filament preset is required: provide 'filament_presets' (preferred), "
  164. "'filament_preset', or legacy 'filament_preset_id'"
  165. )
  166. elif self.filament_preset is None:
  167. # Multi-color caller: backfill the singular from the first slot
  168. # so callers that still read the legacy field see a stable value.
  169. self.filament_preset = self.filament_presets[0]
  170. return self
  171. class SliceResponse(BaseModel):
  172. """Response from `POST /library/files/{file_id}/slice`. The result lands
  173. in the user's library as a new ``LibraryFile`` (in the same folder as
  174. the source)."""
  175. library_file_id: int
  176. name: str
  177. print_time_seconds: int
  178. filament_used_g: float
  179. filament_used_mm: float
  180. used_embedded_settings: bool = False
  181. class SliceArchiveResponse(BaseModel):
  182. """Response from `POST /archives/{archive_id}/slice`. The result lands
  183. in the user's archives as a new ``PrintArchive`` row, inheriting
  184. printer / project metadata from the source archive."""
  185. archive_id: int
  186. name: str
  187. print_time_seconds: int
  188. filament_used_g: float
  189. filament_used_mm: float
  190. used_embedded_settings: bool = False