slicer_api.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. """HTTP client for an OrcaSlicer / BambuStudio API sidecar.
  2. Bambuddy stores user printer/process/filament profiles itself (cloud-synced
  3. or locally imported), so the slice flow always sends the model file plus an
  4. explicit JSON profile triplet to the sidecar's `/slice` endpoint. The sidecar
  5. shape mirrors `AFKFelix/orca-slicer-api` (multipart upload, `--load-settings`
  6. under the hood, response body is raw G-code or 3MF with metadata in the
  7. `X-Print-Time-Seconds` / `X-Filament-Used-G` / `X-Filament-Used-Mm` headers).
  8. """
  9. import asyncio
  10. import io
  11. import logging
  12. import time
  13. import zipfile
  14. from collections.abc import Callable
  15. from typing import NamedTuple
  16. import httpx
  17. logger = logging.getLogger(__name__)
  18. class SlicerApiError(Exception):
  19. """Base error from the slicer API sidecar."""
  20. class SlicerApiUnavailableError(SlicerApiError):
  21. """Sidecar is unreachable (connection error, no response)."""
  22. class SlicerApiServerError(SlicerApiError):
  23. """Sidecar responded with a 5xx — usually the wrapped slicer CLI exited
  24. non-zero (range-validation reject, segfault on complex models, etc.).
  25. Distinguished from `SlicerApiUnavailableError` so the caller can decide
  26. whether to retry with a different request shape (e.g. a 3MF embedded-
  27. settings fallback)."""
  28. class SlicerInputError(SlicerApiError):
  29. """Sidecar rejected the input as invalid (4xx)."""
  30. class SlicerTimeoutError(SlicerApiError):
  31. """We gave up waiting on a slice that never finished.
  32. Kept apart from ``SlicerApiUnavailableError`` because they call for
  33. opposite reactions and used to be reported as the same thing: an
  34. ``httpx.ReadTimeout`` is a subclass of ``RequestError``, so a slice that
  35. simply took a long time surfaced as "Slicer sidecar unreachable" — sending
  36. the reporter of #2730 off to check a sidecar that was reachable throughout
  37. and still slicing when we hung up on it.
  38. """
  39. class SliceResult(NamedTuple):
  40. """Result of a slice operation."""
  41. content: bytes
  42. print_time_seconds: int
  43. filament_used_g: float
  44. filament_used_mm: float
  45. _shared_http_client: httpx.AsyncClient | None = None
  46. # Fallback for callers that don't pass one (tests, and any path that runs
  47. # without a DB session to read the setting from). The user-facing value is
  48. # ``slicer_stall_timeout_minutes`` under Settings -> Workflow -> Slicer.
  49. DEFAULT_SLICE_STALL_TIMEOUT_SECONDS = 15 * 60.0
  50. # How often the progress poller ticks. Also the granularity of the stall check,
  51. # since a missed tick is what the stall clock is counting.
  52. _PROGRESS_POLL_INTERVAL = 1.0
  53. async def get_stall_timeout_seconds(db) -> float:
  54. """Read ``slicer_stall_timeout_minutes`` (Settings -> Workflow -> Slicer).
  55. Falls back to the default on anything unparseable rather than failing the
  56. slice — a bad settings row must not be the reason a print doesn't happen.
  57. """
  58. from backend.app.api.routes.settings import get_setting
  59. try:
  60. raw = await get_setting(db, "slicer_stall_timeout_minutes")
  61. except Exception:
  62. return DEFAULT_SLICE_STALL_TIMEOUT_SECONDS
  63. try:
  64. minutes = int(str(raw).strip())
  65. except (TypeError, ValueError):
  66. return DEFAULT_SLICE_STALL_TIMEOUT_SECONDS
  67. if minutes < 1:
  68. return DEFAULT_SLICE_STALL_TIMEOUT_SECONDS
  69. return float(minutes) * 60.0
  70. def _format_sidecar_error(response: httpx.Response) -> str:
  71. """Build a human-readable error string from a sidecar 4xx/5xx response.
  72. The sidecar's `AppError` middleware emits a JSON body of the shape
  73. ``{"message": "...", "details": "..."}``. Earlier versions of this
  74. client only read ``message``, which left every CLI failure surfaced
  75. as the generic ``Failed to slice the model`` because the *actual*
  76. CLI stderr / `error_string` lives in ``details``. Including both
  77. means ``bambuddy.log`` carries the real reason a slice rejected
  78. the supplied profiles instead of an unhelpful generic line.
  79. """
  80. try:
  81. payload = response.json()
  82. except Exception:
  83. return response.text[:500]
  84. if not isinstance(payload, dict):
  85. return str(payload)[:500]
  86. message = payload.get("message") or ""
  87. details = payload.get("details") or ""
  88. if message and details:
  89. return f"{message}: {details}"[:500]
  90. return (message or details or response.text)[:500]
  91. def _handle_slice_response(response: httpx.Response, *, export_3mf: bool) -> SliceResult:
  92. """Turn a sidecar ``/slice`` HTTP response into a validated ``SliceResult``.
  93. Shared by ``slice_with_profiles`` / ``slice_without_profiles`` so the status
  94. handling and output validation live in one place.
  95. Beyond the status check, this guards against the sidecar (or a reverse proxy
  96. in front of it) returning **HTTP 200 with a body that isn't a real slice**
  97. (#2671): a stock/misconfigured sidecar, a proxy interstitial or truncated
  98. response, or an OrcaSlicer/BambuStudio CLI crash that produces empty output.
  99. Without this check Bambuddy would store that tiny blob as a ``.gcode.3mf``,
  100. let it be queued, and FTP it to the printer — a silently-broken print. When
  101. a 3MF export was requested the body must be a valid ZIP (3MF container);
  102. anything else is treated as a sidecar failure.
  103. Raises:
  104. SlicerInputError: 4xx from the sidecar (bad input / proxy body limit).
  105. SlicerApiServerError: 5xx, or a 2xx whose body is not a valid 3MF.
  106. """
  107. if response.status_code == 413:
  108. # A 413 almost never comes from the slicer itself — it's a reverse proxy
  109. # (nginx/SWAG/Traefik) or a CDN capping the multipart upload (model +
  110. # profiles). Name the real fix so the user doesn't tweak the wrong layer.
  111. raise SlicerInputError(
  112. "The slice request was rejected as too large (HTTP 413). A reverse proxy "
  113. "in front of the slicer sidecar is capping the request body — raise "
  114. "'client_max_body_size' (nginx/SWAG) or the equivalent on the proxy that "
  115. "sits directly in front of the sidecar, then reload it. If the sidecar is "
  116. "behind Cloudflare, note its request-size cap."
  117. )
  118. if response.status_code >= 500:
  119. raise SlicerApiServerError(f"Slicer CLI failed ({response.status_code}): {_format_sidecar_error(response)}")
  120. if response.status_code >= 400:
  121. raise SlicerInputError(f"Slicer rejected input ({response.status_code}): {_format_sidecar_error(response)}")
  122. content = response.content
  123. if export_3mf and not zipfile.is_zipfile(io.BytesIO(content)):
  124. # 200 OK but the body is not a 3MF zip → the sidecar did not produce a
  125. # usable slice. Surface it loudly instead of persisting a corrupt file.
  126. detail = _format_sidecar_error(response) if len(content) <= 500 else ""
  127. raise SlicerApiServerError(
  128. f"Slicer sidecar returned HTTP {response.status_code} but the body is not a valid "
  129. f"3MF ({len(content)} bytes). This usually means a misconfigured sidecar, an "
  130. f"OrcaSlicer/BambuStudio CLI crash producing no output, or a reverse proxy returning "
  131. f"an error page or truncating the response — verify the sidecar URL and any proxy in "
  132. f"front of it." + (f" Body: {detail}" if detail else "")
  133. )
  134. return SliceResult(
  135. content=content,
  136. print_time_seconds=_safe_int(response.headers.get("x-print-time-seconds")),
  137. filament_used_g=_safe_float(response.headers.get("x-filament-used-g")),
  138. filament_used_mm=_safe_float(response.headers.get("x-filament-used-mm")),
  139. )
  140. def set_shared_http_client(client: httpx.AsyncClient | None) -> None:
  141. """Register an app-scoped client so per-request services can pool transport."""
  142. global _shared_http_client
  143. _shared_http_client = client
  144. def _guess_model_content_type(filename: str) -> str:
  145. lower = filename.lower()
  146. if lower.endswith(".stl"):
  147. return "model/stl"
  148. if lower.endswith(".3mf") or lower.endswith(".gcode.3mf"):
  149. return "model/3mf"
  150. if lower.endswith(".step") or lower.endswith(".stp"):
  151. return "model/step"
  152. return "application/octet-stream"
  153. class _Liveness:
  154. """Tracks when the slicer last showed a sign of life.
  155. ``deadline`` is what the slice waits against, and it moves forward on every
  156. genuine progress update. A slice therefore fails only after the configured
  157. window of *silence*, however long the whole thing has been running (#2730).
  158. ``progress_supported`` stays False for sidecars that never answer the
  159. progress endpoint. Those give us nothing to judge liveness by, so the caller
  160. treats the same window as a total-elapsed ceiling rather than pretending a
  161. stall can be detected.
  162. """
  163. def __init__(self, window_seconds: float, poll_interval: float = _PROGRESS_POLL_INTERVAL) -> None:
  164. # Liveness can only be observed as often as the poller ticks, so a
  165. # window shorter than a few ticks would expire in the gap between two
  166. # polls and fail every slice instantly, however healthy. The settings
  167. # schema already floors the user-facing value at a minute; this guards
  168. # the constructor, which tests and any future caller can pass anything.
  169. self.window_seconds = max(window_seconds, poll_interval * 3)
  170. self.progress_supported = False
  171. self.started_at = time.monotonic()
  172. self._last_alive = self.started_at
  173. def saw_progress_endpoint(self) -> None:
  174. self.progress_supported = True
  175. def mark_alive(self) -> None:
  176. self._last_alive = time.monotonic()
  177. @property
  178. def deadline(self) -> float:
  179. """Monotonic time at which we stop waiting."""
  180. base = self._last_alive if self.progress_supported else self.started_at
  181. return base + self.window_seconds
  182. def silent_for(self) -> float:
  183. return time.monotonic() - self._last_alive
  184. def elapsed(self) -> float:
  185. return time.monotonic() - self.started_at
  186. def timeout_message(self) -> str:
  187. minutes = self.window_seconds / 60
  188. if self.progress_supported:
  189. return (
  190. f"The slicer stopped reporting progress for {minutes:.0f} minutes "
  191. f"(slicing had been running for {self.elapsed() / 60:.0f} minutes). "
  192. "Raise 'Slicer stall timeout' under Settings -> Workflow -> Slicer if this model "
  193. "legitimately needs longer between progress updates."
  194. )
  195. return (
  196. f"Slicing did not finish within {minutes:.0f} minutes, and this sidecar does not "
  197. "report progress, so there was no way to tell a slow model from a stalled one. "
  198. "Raise 'Slicer stall timeout' under Settings -> Workflow -> Slicer, or update the "
  199. "sidecar to a version that reports progress."
  200. )
  201. class SlicerApiService:
  202. """Talks to an OrcaSlicer / BambuStudio API sidecar."""
  203. def __init__(
  204. self,
  205. base_url: str,
  206. *,
  207. client: httpx.AsyncClient | None = None,
  208. timeout_seconds: float = DEFAULT_SLICE_STALL_TIMEOUT_SECONDS,
  209. ) -> None:
  210. """``timeout_seconds`` bounds *silence*, not total slicing time (#2730).
  211. While a slice is running Bambuddy polls the sidecar's progress channel
  212. once a second, so it can tell a model that is merely slow from one that
  213. has stopped: the clock is reset by every progress update, and only runs
  214. out when the slicer has said nothing for this long. A heavy model that
  215. keeps reporting will run to completion however long it takes.
  216. Sidecars too old to report progress have no liveness signal to offer, so
  217. for those the same number bounds total elapsed time — the pre-#2730
  218. behaviour, but configurable and no longer five minutes flat.
  219. """
  220. self.base_url = base_url.rstrip("/")
  221. self.timeout_seconds = timeout_seconds
  222. # Instance-level so tests can compress the timing; production always
  223. # uses the module default.
  224. self.progress_poll_interval = _PROGRESS_POLL_INTERVAL
  225. if client is not None:
  226. self._client = client
  227. self._owns_client = False
  228. elif _shared_http_client is not None:
  229. self._client = _shared_http_client
  230. self._owns_client = False
  231. else:
  232. self._client = httpx.AsyncClient(timeout=timeout_seconds)
  233. self._owns_client = True
  234. async def close(self) -> None:
  235. if self._owns_client:
  236. await self._client.aclose()
  237. async def __aenter__(self) -> "SlicerApiService":
  238. return self
  239. async def __aexit__(self, *_: object) -> None:
  240. await self.close()
  241. async def health(self) -> dict:
  242. """GET /health — used to surface a clear "sidecar offline" error before
  243. accepting a slice request from the user."""
  244. try:
  245. response = await self._client.get(f"{self.base_url}/health", timeout=10.0)
  246. except httpx.RequestError as exc:
  247. raise SlicerApiUnavailableError(f"Slicer sidecar unreachable: {exc}") from exc
  248. if response.status_code >= 400:
  249. raise SlicerApiUnavailableError(f"Slicer sidecar /health returned {response.status_code}")
  250. return response.json()
  251. async def list_bundled_profiles(self) -> dict:
  252. """GET /profiles/bundled — return the slicer's stock profiles by slot.
  253. Powers the "Standard" tier of Bambuddy's SliceModal preset dropdowns.
  254. The sidecar walks the slicer's read-only `resources/profiles/BBL/`
  255. tree and returns ``{printer, process, filament}`` arrays of
  256. ``{name, base_id}`` (alphabetised, instantiable presets only — abstract
  257. bases like `fdm_filament_pla` are filtered out by the sidecar).
  258. Returns an empty-shaped dict when the sidecar is unreachable so the
  259. unified-presets endpoint can degrade to "no standard tier" without
  260. crashing the modal — cloud + local-imported profiles still render.
  261. """
  262. try:
  263. response = await self._client.get(f"{self.base_url}/profiles/bundled", timeout=10.0)
  264. except httpx.RequestError as exc:
  265. raise SlicerApiUnavailableError(f"Slicer sidecar unreachable: {exc}") from exc
  266. if response.status_code >= 400:
  267. raise SlicerApiUnavailableError(f"Slicer sidecar /profiles/bundled returned {response.status_code}")
  268. return response.json()
  269. async def _poll_progress(
  270. self,
  271. request_id: str,
  272. on_progress: Callable[[dict], None],
  273. *,
  274. liveness: "_Liveness | None" = None,
  275. ) -> None:
  276. """Poll the sidecar's progress endpoint at ~1Hz and forward each
  277. snapshot to ``on_progress``. Runs until cancelled.
  278. 4xx is NOT treated as terminal: the FIRST poll fires the moment
  279. the slice POST is sent, which can be milliseconds before the
  280. request actually lands on the sidecar and `progressStore.start()`
  281. runs — so a fresh request legitimately returns 404 for the first
  282. tick or two. Bailing on the first 404 (the original implementation)
  283. meant we'd quit before progress could ever arrive. The polling
  284. task is cancelled by the outer slice request anyway, so a
  285. sustained 404 (older sidecar without progress support, or post-
  286. slice grace expiry) just costs a few wasted GETs that the cancel
  287. will stop. Network errors and non-JSON 5xx are swallowed; the
  288. next tick retries.
  289. When ``liveness`` is supplied this doubles as the stall watchdog: every
  290. 200 carrying a *changed* payload marks the slicer alive, which is what
  291. keeps the slice's deadline moving (#2730). An unchanged payload
  292. deliberately does not count — the sidecar re-serves its last snapshot on
  293. every poll, so treating a repeat as progress would leave the watchdog
  294. unable to detect a stall at all.
  295. """
  296. url = f"{self.base_url}/slice/progress/{request_id}"
  297. last_payload: dict | None = None
  298. while True:
  299. try:
  300. response = await self._client.get(url, timeout=5.0)
  301. if response.status_code == 200:
  302. payload = response.json()
  303. if isinstance(payload, dict):
  304. if liveness is not None:
  305. liveness.saw_progress_endpoint()
  306. if payload != last_payload:
  307. liveness.mark_alive()
  308. last_payload = payload
  309. on_progress(payload)
  310. # 404 / other 4xx = no progress available (yet, or ever
  311. # for older sidecars). Keep polling — the outer slice
  312. # request will cancel this task on completion.
  313. except (httpx.RequestError, ValueError):
  314. # ValueError covers JSONDecodeError when the sidecar
  315. # returns a non-JSON 5xx. Don't crash the poller.
  316. pass
  317. try:
  318. await asyncio.sleep(self.progress_poll_interval)
  319. except asyncio.CancelledError:
  320. return
  321. async def _post_slice(
  322. self,
  323. *,
  324. files: list | dict,
  325. data: dict,
  326. request_id: str | None,
  327. on_progress: Callable[[dict], None] | None,
  328. ) -> httpx.Response:
  329. """POST /slice, supervised by the progress channel rather than a clock.
  330. Before #2730 this was a plain ``httpx`` call with a flat 300 s timeout on
  331. every phase. A genuinely heavy model — the reporter's was a MakerWorld
  332. model that Bambu Studio also took a long time over — hit the ceiling
  333. while it was still slicing perfectly happily, and because
  334. ``httpx.ReadTimeout`` is a ``RequestError`` it was reported as "Slicer
  335. sidecar unreachable". Meanwhile Bambuddy was polling the sidecar's
  336. progress endpoint once a second and could see the thing working.
  337. So the read timeout comes off the HTTP call and the poller supervises
  338. instead: the deadline is pushed forward by every progress update, and
  339. only a genuine silence ends the wait. Connect and pool keep short
  340. timeouts — a sidecar that won't accept the connection at all is
  341. unreachable, and should still say so quickly.
  342. """
  343. liveness = _Liveness(self.timeout_seconds, self.progress_poll_interval)
  344. # Poll whenever we have a request_id, even if the caller wants no
  345. # progress callbacks: the poll is what makes stall detection possible,
  346. # and one GET per second is cheaper than a wrongly-cancelled slice.
  347. progress_task: asyncio.Task | None = None
  348. if request_id is not None:
  349. progress_task = asyncio.create_task(
  350. self._poll_progress(request_id, on_progress or (lambda _payload: None), liveness=liveness),
  351. name=f"slicer-progress-{request_id}",
  352. )
  353. post_task = asyncio.create_task(
  354. self._client.post(
  355. f"{self.base_url}/slice",
  356. files=files,
  357. data=data,
  358. timeout=httpx.Timeout(connect=30.0, read=None, write=None, pool=30.0),
  359. ),
  360. name="slicer-slice-post",
  361. )
  362. try:
  363. while True:
  364. remaining = liveness.deadline - time.monotonic()
  365. if remaining <= 0:
  366. post_task.cancel()
  367. logger.warning(
  368. "Slice abandoned after %.0fs (silent for %.0fs, progress channel %s)",
  369. liveness.elapsed(),
  370. liveness.silent_for(),
  371. "available" if liveness.progress_supported else "unavailable",
  372. )
  373. raise SlicerTimeoutError(liveness.timeout_message())
  374. # Re-check at poll granularity so a progress update that lands
  375. # mid-wait extends the deadline promptly.
  376. done, _pending = await asyncio.wait({post_task}, timeout=min(remaining, self.progress_poll_interval))
  377. if post_task in done:
  378. break
  379. finally:
  380. if progress_task is not None:
  381. progress_task.cancel()
  382. # Await both so neither is left pending — a cancelled POST still
  383. # needs its connection released back to the pool.
  384. await asyncio.gather(post_task, progress_task or asyncio.sleep(0), return_exceptions=True)
  385. try:
  386. return post_task.result()
  387. except httpx.RequestError as exc:
  388. raise SlicerApiUnavailableError(f"Slicer sidecar unreachable: {exc}") from exc
  389. async def slice_with_profiles(
  390. self,
  391. *,
  392. model_bytes: bytes,
  393. model_filename: str,
  394. printer_profile_json: str,
  395. process_profile_json: str,
  396. filament_profile_jsons: list[str],
  397. plate: int | None = None,
  398. export_3mf: bool = False,
  399. arrange: bool = False,
  400. request_id: str | None = None,
  401. on_progress: Callable[[dict], None] | None = None,
  402. ) -> SliceResult:
  403. """POST /slice with model + printer/process/filament profiles.
  404. ``filament_profile_jsons`` is plate-slot-ordered: index 0 is the
  405. profile for slot 1, etc. Single-color callers pass a one-element
  406. list. Multiple ``filamentProfile`` parts are sent as a repeated form
  407. field — the sidecar's route declares ``maxCount: 16`` and the
  408. slicing service joins them as semicolon-separated
  409. ``--load-filaments`` for the OrcaSlicer / BambuStudio CLI.
  410. ``arrange`` forwards the sidecar's ``--arrange`` flag to BambuStudio.
  411. When True the slicer auto-repositions objects on the target bed,
  412. which Bambuddy uses for cross-nozzle-class re-slices (#1493) where
  413. the source's X1C-coordinate layout would otherwise drop into an H2D
  414. dead zone or trigger the multi-extruder geometry pipeline's polygon
  415. clipping crash. Default off so single-printer slices preserve the
  416. user's deliberate layout.
  417. ``request_id``: when supplied, the sidecar wires --pipe to a
  418. per-request FIFO and publishes structured JSON progress events to
  419. its in-memory ProgressStore under this id. Bambuddy's slice
  420. dispatch polls ``GET /slice/progress/{request_id}`` in parallel
  421. to drive the live-progress toast.
  422. Raises:
  423. SlicerInputError: 4xx from sidecar (caller-supplied input is bad).
  424. SlicerApiUnavailableError: connection error or 5xx from sidecar.
  425. """
  426. # httpx supports repeated multipart fields when files is a list of
  427. # tuples — using the dict form would silently overwrite duplicate
  428. # keys and ship only the last filament profile.
  429. files: list[tuple[str, tuple[str, bytes, str]]] = [
  430. ("file", (model_filename, model_bytes, _guess_model_content_type(model_filename))),
  431. ("printerProfile", ("printer.json", printer_profile_json.encode("utf-8"), "application/json")),
  432. ("presetProfile", ("preset.json", process_profile_json.encode("utf-8"), "application/json")),
  433. ]
  434. for idx, fjson in enumerate(filament_profile_jsons):
  435. files.append(
  436. (
  437. "filamentProfile",
  438. (f"filament_{idx + 1}.json", fjson.encode("utf-8"), "application/json"),
  439. )
  440. )
  441. data: dict[str, str] = {}
  442. if plate is not None:
  443. data["plate"] = str(plate)
  444. if export_3mf:
  445. data["exportType"] = "3mf"
  446. if arrange:
  447. # Sidecar reads non-empty truthy strings as True; only send the
  448. # field when we want the flag on, so default-off callers exactly
  449. # match the previous wire payload.
  450. data["arrange"] = "true"
  451. if request_id is not None:
  452. data["requestId"] = request_id
  453. # When the caller supplied a request_id, kick off a parallel
  454. # poller that reads the sidecar's --pipe-fed progress endpoint
  455. # and surfaces structured updates via on_progress. Uses a
  456. # short-tick poll (1s) since the slicer emits stage changes
  457. # several times per minute on complex models.
  458. response = await self._post_slice(files=files, data=data, request_id=request_id, on_progress=on_progress)
  459. return _handle_slice_response(response, export_3mf=export_3mf)
  460. async def slice_without_profiles(
  461. self,
  462. *,
  463. model_bytes: bytes,
  464. model_filename: str,
  465. plate: int | None = None,
  466. export_3mf: bool = False,
  467. request_id: str | None = None,
  468. on_progress: Callable[[dict], None] | None = None,
  469. ) -> SliceResult:
  470. """POST /slice with only the model file and no profile triplet.
  471. For 3MF inputs this lets the slicer fall back on the file's embedded
  472. `Metadata/project_settings.config`. Used as a fallback when
  473. `slice_with_profiles` triggers a CLI segfault or other 5xx —
  474. complex H2D / multi-extruder models hit upstream bugs in both the
  475. OrcaSlicer and BambuStudio CLIs when invoked via `--load-settings`.
  476. Also used by the SliceModal's per-plate filament discovery path:
  477. for an unsliced project file we run a real preview slice via the
  478. sidecar to find which AMS slots the picked plate consumes. The
  479. ``request_id`` parameter routes the sidecar's --pipe progress
  480. events to the ProgressStore so the modal's inline spinner +
  481. toast can show "Generating G-code (75%)" for that preview as
  482. well.
  483. """
  484. files = {
  485. "file": (model_filename, model_bytes, _guess_model_content_type(model_filename)),
  486. }
  487. data: dict[str, str] = {}
  488. if plate is not None:
  489. data["plate"] = str(plate)
  490. if export_3mf:
  491. data["exportType"] = "3mf"
  492. if request_id is not None:
  493. data["requestId"] = request_id
  494. # Same progress-poller wiring as slice_with_profiles. Used by the
  495. # SliceModal's preview slice (for filament discovery) AND the
  496. # embedded-settings fallback path triggered by an Orca/Bambu CLI
  497. # segfault on complex H2D models — both want to keep updating
  498. # the user's toast through the slow operation.
  499. response = await self._post_slice(files=files, data=data, request_id=request_id, on_progress=on_progress)
  500. return _handle_slice_response(response, export_3mf=export_3mf)
  501. def _safe_int(value: str | None) -> int:
  502. if not value:
  503. return 0
  504. try:
  505. return int(float(value))
  506. except (TypeError, ValueError):
  507. return 0
  508. def _safe_float(value: str | None) -> float:
  509. if not value:
  510. return 0.0
  511. try:
  512. return float(value)
  513. except (TypeError, ValueError):
  514. return 0.0