Skip to content

Python

Tested with Python 3.10+ and requests 2.31+.

Minimal client

# cnw.py
import os
from typing import Any, Mapping

import requests

ENDPOINT = os.environ.get("CNW_ENDPOINT", "https://api.cutweaver.io")
API_KEY = os.environ.get("CNW_API_KEY")


class CnwError(Exception):
    def __init__(self, code: str, message: str, status: int) -> None:
        super().__init__(message)
        self.code = code
        self.status = status


def solve(payload: Mapping[str, Any], timeout: float = 10.0) -> dict:
    headers = {"Content-Type": "application/json"}
    if API_KEY:
        headers["X-API-Key"] = API_KEY

    res = requests.post(f"{ENDPOINT}/api/v1/solve", json=payload, headers=headers, timeout=timeout)
    data = res.json()

    if not data.get("ok"):
        err = data.get("error", {})
        raise CnwError(err.get("code", "unknown"), err.get("message", "Unknown error"), res.status_code)

    return data

Usage

from cnw import solve

response = solve({
    "sheets": [
        {"width": 3210, "height": 2250, "quantity": 1, "kerfWidth": 4},
    ],
    "pieces": [
        {"originalIndex": 0, "width": 800, "height": 600, "quantity": 4, "canRotate": True},
        {"originalIndex": 1, "width": 1200, "height": 900, "quantity": 2, "canRotate": True},
    ],
    "params": {"kerfWidth": 4},
    "strategy": "greedy",
})

result = response["result"]
print(f"Placed: {result['totalPlaced']}")
for sheet in result["sheets"]:
    print(f"Sheet {sheet['sheetIndex']}: {sheet['utilization'] * 100:.1f}%")

Retry with backoff

import time

from cnw import CnwError, solve


def solve_with_retry(payload, max_attempts: int = 3):
    for attempt in range(1, max_attempts + 1):
        try:
            return solve(payload)
        except CnwError as e:
            if e.status != 429 and e.status < 500:
                raise
            if attempt == max_attempts:
                raise
            time.sleep(2 ** attempt * 0.5)