From 095bcdea1ec38304f8e4357a1c32075ee1cc6282 Mon Sep 17 00:00:00 2001 From: 0xBitBuster Date: Thu, 26 Nov 2026 15:35:40 +0100 Subject: [PATCH 1/2] feat: live try-on endpoints, contract tests, CI and User-Agent (2.1.0) - Live try-on server methods: prepare garment, start/get/stop session, config - API errors carry the envelope's error.name / error.message (they were "HTTP 4xx" with a wrong or missing name) - TypedDict response types and py.typed; mypy --strict clean - wait_for_result no longer crashes on a failed job (AttributeError); job ids escaped - User-Agent: tryiton-python/2.1.0 on every request - Shared contract test suite (fixtures from tryiton/backend/api-contract) + GitHub Actions CI - CHANGELOG.md; README live try-on and development sections - Includes earlier uncommitted comment edits Co-Authored-By: Claude Opus 5.5 --- .github/workflows/test.yml | 26 +++ .gitignore | 2 + CHANGELOG.md | 67 ++++++++ README.md | 43 +++++ pyproject.toml | 14 +- tests/conftest.py | 73 +++++++++ tests/fixtures/sdk-cases.json | 296 ++++++++++++++++++++++++++++++++++ tests/test_client.py | 118 ++++++++++++++ tests/test_contract.py | 142 ++++++++++++++++ tryiton/__init__.py | 27 +++- tryiton/client.py | 161 +++++++++++++----- tryiton/py.typed | 0 tryiton/types.py | 112 +++++++++++++ 13 files changed, 1035 insertions(+), 46 deletions(-) create mode 100644 .github/workflows/test.yml create mode 100644 CHANGELOG.md create mode 100644 tests/conftest.py create mode 100644 tests/fixtures/sdk-cases.json create mode 100644 tests/test_client.py create mode 100644 tests/test_contract.py create mode 100644 tryiton/py.typed create mode 100644 tryiton/types.py diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..61628a9 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,26 @@ +name: test + +on: + push: + pull_request: + +jobs: + test: + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"] + os: [ubuntu-latest] + include: + # setup-python has no 3.8 build for ubuntu-24.04 (ubuntu-latest). + - python-version: "3.8" + os: ubuntu-22.04 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + - run: python -m pip install -e ".[dev]" + - run: python -m pytest + - run: python -m mypy tryiton diff --git a/.gitignore b/.gitignore index f953b04..8beb97f 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,5 @@ build/ dist/ .venv/ venv/ +.pytest_cache/ +.mypy_cache/ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..471944e --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,67 @@ +# Changelog + +All notable changes to the `tryiton` Python SDK are documented here. The format is based on +[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project follows +[Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [2.1.0] - Unreleased + +### Added + +- Live (real-time webcam) try-on endpoints: `get_live_config`, `prepare_live_garment`, `start_live_session`, + `get_live_session` and `stop_live_session`. +- Every request sends `User-Agent: tryiton-python/`. +- Typed responses: `TypedDict`s `LiveConfig`, `LiveGarment`, `LiveSession`, `LiveSessionStart` (plus the nested + `LiveGarmentInput`, `LiveSessionGarment`, `LiveConnection`) in `tryiton.types`, re-exported from `tryiton`. They are + plain dicts at runtime. `Status` and `Credits` stay dataclasses and now live in `tryiton.types` too (still importable + from `tryiton` and `tryiton.client`). +- `py.typed` marker, so type checkers use the package's annotations. +- The shared cross-SDK contract tests, unit tests, and a GitHub Actions workflow (Python 3.8 to 3.13, pytest + mypy). + `pip install -e ".[dev]"` installs the tooling. + +### Fixed + +- API errors now carry the backend's `error.name` and `error.message` (`{"ok": false, "error": {...}}`). Before, the + message was always `HTTP ` and `error_name` was empty. Legacy top-level `error`/`message` strings still work. +- `wait_for_result` on a failed job raised `AttributeError` instead of `TryItOnError`, because `GET /status` sends the + failure reason as a plain string. It now raises `TryItOnError` with that reason as the message and `error_name` + `"ProcessingError"`. +- `get_status` (and so `wait_for_result`) URL-escapes the job id. +- `Status.error` is annotated as `Optional[str]`, matching what the API returns (was `Optional[Dict[str, str]]`). +- `tryiton.__version__` was stuck at `0.1.0`; it now matches the package version. + +## [2.0.0] - 2026-07-14 + +### Changed + +- **Breaking:** `try_on_clothes` is now `try_on_fashion` and calls `POST /tryon/fashion` (it covers clothing, footwear, + eyewear, headwear, jewelry and accessories). + +## [1.1.0] - 2026-07-14 + +### Added + +- `region` for `try_on_tattoo`: pins the tattoo to a normalized `{x, y, w, h}` box on the body image. + +## [1.0.0] - 2026-06-24 + +### Added + +- `num_samples` (1-4) and `output_format` (`png`/`jpeg`) on every try-on. + +### Removed + +- **Breaking:** the `seed`, `segmentation_free` and `garment_photo_type` options of the clothes try-on. + +## [0.1.0] - 2026-06-22 + +### Added + +- Initial release: clothing/accessory, hairstyle and tattoo try-on, `get_status`, `get_credits` and the + `wait_for_result` polling helper. + +[2.1.0]: https://github.com/tryiton-now/tryiton-python/compare/v2.0.0...HEAD +[2.0.0]: https://github.com/tryiton-now/tryiton-python/compare/v1.1.0...v2.0.0 +[1.1.0]: https://github.com/tryiton-now/tryiton-python/compare/v1.0.0...v1.1.0 +[1.0.0]: https://github.com/tryiton-now/tryiton-python/compare/v0.1.0...v1.0.0 +[0.1.0]: https://github.com/tryiton-now/tryiton-python/releases/tag/v0.1.0 diff --git a/README.md b/README.md index 1701be1..d68abf0 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,30 @@ status = client.get_status(job_id) # Status(status, output, error) credits = client.get_credits() # Credits(on_demand, subscription, purchased, reserved) ``` +## Live try-on (real-time webcam) + +Your server prepares garments and starts sessions with the API key. The shopper's browser streams with the +[`tryiton-live`](https://www.npmjs.com/package/tryiton-live) npm package, using only the session-scoped response. + +```python +# Once per product, e.g. at catalog sync (cached per image + category): +garment = client.prepare_live_garment(product_image_url, category="clothing", subcategory="tops") + +# When a shopper opens live try-on. Return `start` to the browser as-is (e.g. as JSON): +start = client.start_live_session( + garment_id=garment["id"], + end_user_id=shopper_id, # one stream per end user + allowed_origin="https://shop.example.com", # locks the media token to your site +) + +client.get_live_session(start["session"]["id"]) # {"status", "seconds", "creditsCharged", ...} +client.stop_live_session(start["session"]["id"]) # end it from your server +client.get_live_config() # {"enabled", "secondsPerCredit", "maxSeconds", ...} +``` + +Billing is per `secondsPerCredit` seconds of streamed video, from the first try-on frame. Garment switches during a +session are free. + ## Error handling All failures raise `TryItOnError`, which carries the HTTP status code and the API error name. @@ -83,11 +107,30 @@ except TryItOnError as err: print(err.status, err.error_name, str(err)) # e.g. 429, "OutOfCredits" ``` +## Typing + +The package ships `py.typed`. `get_status` and `get_credits` return the `Status` and `Credits` dataclasses. The live +methods return plain dicts typed as `TypedDict`s (`LiveConfig`, `LiveGarment`, `LiveSession`, `LiveSessionStart`), +all importable from `tryiton`. + ## Notes - Output image URLs expire 72 hours after completion. Download any results you want to keep. - Failed jobs are never charged. +## Development + +```bash +python -m venv .venv && . .venv/bin/activate # Windows: .venv\Scripts\activate +pip install -e ".[dev]" +pytest # unit tests + the shared contract cases +python -m mypy tryiton # strict type check +``` + +`tests/fixtures/sdk-cases.json` holds the request/response cases every TryItOn SDK runs. It is generated: edit the +source in the backend repo (`api-contract/sdk-cases.json`) and re-sync, never the copy here. Changes are listed in +[CHANGELOG.md](CHANGELOG.md). + ## Documentation Full documentation, parameter reference, and guides: [docs.tryiton.now](https://docs.tryiton.now) diff --git a/pyproject.toml b/pyproject.toml index 2a36daf..25cc2fa 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "tryiton" -version = "2.0.0" +version = "2.1.0" description = "Official Python SDK for the TryItOn virtual try-on API." readme = "README.md" requires-python = ">=3.8" @@ -13,6 +13,9 @@ authors = [{ name = "TryItOn" }] keywords = ["tryiton", "virtual-try-on", "tryon", "fashion", "ai", "sdk"] dependencies = ["requests>=2.25"] +[project.optional-dependencies] +dev = ["pytest", "mypy", "types-requests"] + [project.urls] Homepage = "https://tryiton.now" Documentation = "https://docs.tryiton.now" @@ -21,3 +24,12 @@ Issues = "https://github.com/tryiton-now/tryiton-python/issues" [tool.setuptools] packages = ["tryiton"] + +[tool.setuptools.package-data] +tryiton = ["py.typed"] + +[tool.pytest.ini_options] +testpaths = ["tests"] + +[tool.mypy] +strict = true diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..10d70dc --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,73 @@ +"""Shared test helpers: a fake requests transport adapter mounted on a real Session. + +Stubbing at the adapter keeps the client's real request building (headers, JSON +encoding, URL quoting) under test; only the network hop is replaced. +""" + +import json +from typing import Any, Callable, Dict, List, Optional + +import pytest +import requests +from requests.adapters import BaseAdapter + +import tryiton + + +class FakeAdapter(BaseAdapter): + """Replies with queued (status, body) pairs in order and records every request. + + A queued item that is an exception instance is raised instead, to simulate a + transport failure. + """ + + def __init__(self, replies: List[Any]): + super().__init__() + self.replies = list(replies) + self.requests: List[requests.PreparedRequest] = [] + self.timeouts: List[Any] = [] + + def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None): + self.requests.append(request) + self.timeouts.append(timeout) + if not self.replies: + raise AssertionError(f"Unexpected extra request: {request.method} {request.url}") + reply = self.replies.pop(0) + if isinstance(reply, BaseException): + raise reply + return build_response(request, reply) + + def close(self): + pass + + +def build_response(request: requests.PreparedRequest, reply: Dict[str, Any]) -> requests.Response: + """A Response from a fixture reply: ``{"status", "body"}`` (JSON) or ``{"status", "raw"}``.""" + resp = requests.Response() + resp.status_code = reply["status"] + resp.request = request + resp.url = request.url or "" + if "raw" in reply: + resp._content = reply["raw"].encode("utf-8") + resp.headers["Content-Type"] = "text/html" + else: + resp._content = json.dumps(reply["body"]).encode("utf-8") + resp.headers["Content-Type"] = "application/json" + resp.encoding = "utf-8" + return resp + + +@pytest.fixture +def make_client() -> Callable[..., Any]: + """Build ``(client, adapter)``: a TryItOn client whose session replies with `replies`.""" + + def factory(replies: List[Any], *, api_key: str = "test-key", base_url: Optional[str] = None, **kwargs: Any): + adapter = FakeAdapter(replies) + session = requests.Session() + session.mount("https://", adapter) + session.mount("http://", adapter) + if base_url is not None: + kwargs["base_url"] = base_url + return tryiton.TryItOn(api_key=api_key, session=session, **kwargs), adapter + + return factory diff --git a/tests/fixtures/sdk-cases.json b/tests/fixtures/sdk-cases.json new file mode 100644 index 0000000..9aced2c --- /dev/null +++ b/tests/fixtures/sdk-cases.json @@ -0,0 +1,296 @@ +{ + "_comment": "Source of truth for the TryItOn SDK contract tests. Edit HERE only (tryiton/backend/api-contract/), then run `node tryiton-sdk/sync-contract.mjs` to copy it into every SDK repo. Every SDK test suite runs every case. Method and param names are canonical camelCase; each SDK maps them to its own idiom (try_on_fashion / TryOnFashion / ...). In expectResult objects, an SDK may also carry the envelope's `ok` field (e.g. getStatus returns the whole body): ignore keys the case does not list only for `ok`; every listed key must match.", + "version": 1, + "baseUrl": "https://api.test/api/v1", + "apiKey": "test-key", + "methodCases": [ + { + "name": "tryOnFashion sends every option snake_case and returns the job id", + "method": "tryOnFashion", + "params": { + "modelImage": "https://example.com/model.jpg", + "garmentImage": "https://example.com/shirt.jpg", + "category": "clothing", + "subcategory": "tops", + "mode": "quality", + "numSamples": 2, + "outputFormat": "jpeg", + "moderationLevel": "conservative" + }, + "responses": [{ "status": 201, "body": { "ok": true, "jobId": "job_1" } }], + "expectRequests": [ + { + "method": "POST", + "path": "/tryon/fashion", + "body": { + "model_image": "https://example.com/model.jpg", + "garment_image": "https://example.com/shirt.jpg", + "category": "clothing", + "subcategory": "tops", + "mode": "quality", + "num_samples": 2, + "output_format": "jpeg", + "moderation_level": "conservative" + } + } + ], + "expectResult": "job_1" + }, + { + "name": "tryOnFashion omits unset options", + "method": "tryOnFashion", + "params": { "modelImage": "data:image/png;base64,AAAA", "garmentImage": "https://example.com/shirt.jpg" }, + "responses": [{ "status": 201, "body": { "ok": true, "jobId": "job_2" } }], + "expectRequests": [ + { + "method": "POST", + "path": "/tryon/fashion", + "body": { "model_image": "data:image/png;base64,AAAA", "garment_image": "https://example.com/shirt.jpg" } + } + ], + "expectResult": "job_2" + }, + { + "name": "tryOnHairstyle", + "method": "tryOnHairstyle", + "params": { "faceImage": "https://example.com/face.jpg", "haircut": "BuzzCut", "hairColor": "ash blonde", "numSamples": 1, "outputFormat": "png" }, + "responses": [{ "status": 201, "body": { "ok": true, "jobId": "job_3" } }], + "expectRequests": [ + { + "method": "POST", + "path": "/tryon/hairstyle", + "body": { "face_image": "https://example.com/face.jpg", "haircut": "BuzzCut", "hair_color": "ash blonde", "num_samples": 1, "output_format": "png" } + } + ], + "expectResult": "job_3" + }, + { + "name": "tryOnTattoo with a region", + "method": "tryOnTattoo", + "params": { + "bodyImage": "https://example.com/arm.jpg", + "designImage": "https://example.com/design.png", + "placement": "fine-line, black ink", + "region": { "x": 0.32, "y": 0.18, "w": 0.28, "h": 0.34 } + }, + "responses": [{ "status": 201, "body": { "ok": true, "jobId": "job_4" } }], + "expectRequests": [ + { + "method": "POST", + "path": "/tryon/tattoo", + "body": { + "body_image": "https://example.com/arm.jpg", + "design_image": "https://example.com/design.png", + "placement": "fine-line, black ink", + "region": { "x": 0.32, "y": 0.18, "w": 0.28, "h": 0.34 } + } + } + ], + "expectResult": "job_4" + }, + { + "name": "getStatus of a completed job", + "method": "getStatus", + "params": { "jobId": "job_1" }, + "responses": [{ "status": 200, "body": { "ok": true, "status": "completed", "output": ["https://cdn.test/a.png"], "error": null } }], + "expectRequests": [{ "method": "GET", "path": "/status/job_1" }], + "expectResult": { "status": "completed", "output": ["https://cdn.test/a.png"], "error": null } + }, + { + "name": "getStatus of a failed job: error is a plain string", + "method": "getStatus", + "params": { "jobId": "job_9" }, + "responses": [{ "status": 200, "body": { "ok": true, "status": "failed", "output": [], "error": "We couldn't find a person in the photo." } }], + "expectRequests": [{ "method": "GET", "path": "/status/job_9" }], + "expectResult": { "status": "failed", "output": [], "error": "We couldn't find a person in the photo." } + }, + { + "name": "getStatus escapes the job id", + "method": "getStatus", + "params": { "jobId": "a/b c" }, + "responses": [{ "status": 200, "body": { "ok": true, "status": "processing", "output": [], "error": null } }], + "expectRequests": [{ "method": "GET", "path": "/status/a%2Fb%20c" }], + "expectResult": { "status": "processing", "output": [], "error": null } + }, + { + "name": "getCredits", + "method": "getCredits", + "params": {}, + "responses": [{ "status": 200, "body": { "ok": true, "credits": { "on_demand": 0, "subscription": 58, "purchased": 1, "reserved": 0 } } }], + "expectRequests": [{ "method": "GET", "path": "/credits" }], + "expectResult": { "on_demand": 0, "subscription": 58, "purchased": 1, "reserved": 0 } + }, + { + "name": "waitForResult polls until completed", + "method": "waitForResult", + "params": { "jobId": "job_1" }, + "responses": [ + { "status": 200, "body": { "ok": true, "status": "processing", "output": [], "error": null } }, + { "status": 200, "body": { "ok": true, "status": "completed", "output": ["https://cdn.test/a.png", "https://cdn.test/b.png"], "error": null } } + ], + "expectRequests": [ + { "method": "GET", "path": "/status/job_1" }, + { "method": "GET", "path": "/status/job_1" } + ], + "expectResult": ["https://cdn.test/a.png", "https://cdn.test/b.png"] + }, + { + "name": "waitForResult raises the job's own failure reason", + "method": "waitForResult", + "params": { "jobId": "job_9" }, + "responses": [{ "status": 200, "body": { "ok": true, "status": "failed", "output": [], "error": "We couldn't find a person in the photo." } }], + "expectRequests": [{ "method": "GET", "path": "/status/job_9" }], + "expectError": { "status": null, "errorName": "ProcessingError", "message": "We couldn't find a person in the photo." } + }, + { + "name": "getLiveConfig strips ok", + "method": "getLiveConfig", + "params": {}, + "responses": [{ "status": 200, "body": { "ok": true, "enabled": true, "secondsPerCredit": 2, "maxSeconds": 180, "minCredits": 5, "maxConcurrentSessions": 3 } }], + "expectRequests": [{ "method": "GET", "path": "/live/config" }], + "expectResult": { "enabled": true, "secondsPerCredit": 2, "maxSeconds": 180, "minCredits": 5, "maxConcurrentSessions": 3 } + }, + { + "name": "prepareLiveGarment", + "method": "prepareLiveGarment", + "params": { "garmentImage": "https://example.com/shirt.jpg", "category": "clothing", "subcategory": "tops" }, + "responses": [ + { + "status": 201, + "body": { "ok": true, "garment": { "id": "g1", "category": "clothing", "subcategory": "tops", "description": "a navy polo", "createdAt": "2026-11-26T12:20:59.512Z" } } + } + ], + "expectRequests": [ + { "method": "POST", "path": "/live/garments", "body": { "garment_image": "https://example.com/shirt.jpg", "category": "clothing", "subcategory": "tops" } } + ], + "expectResult": { "id": "g1", "category": "clothing", "subcategory": "tops", "description": "a navy polo", "createdAt": "2026-11-26T12:20:59.512Z" } + }, + { + "name": "startLiveSession returns the whole response unchanged", + "method": "startLiveSession", + "params": { "garmentId": "g1", "maxSeconds": 30, "endUserId": "u1", "allowedOrigin": "https://shop.test" }, + "responses": [ + { + "status": 201, + "body": { + "ok": true, + "session": { + "id": "s1", + "status": "active", + "endReason": null, + "seconds": 0, + "creditsCharged": 0, + "endUserId": "u1", + "createdAt": "2026-11-26T12:21:57.402Z", + "endedAt": null + }, + "clientSecret": "cs", + "connection": { "provider": "decart", "model": "lucy-vton-latest", "token": "tok" }, + "secondsPerCredit": 2, + "maxSeconds": 30, + "secondsLeft": 30, + "garment": { + "id": "g1", + "category": "clothing", + "subcategory": "tops", + "description": null, + "createdAt": "2026-11-26T12:20:59.512Z", + "input": { "prompt": "p", "enhancePrompt": true, "referenceImage": "data:image/jpeg;base64,AA" } + } + } + } + ], + "expectRequests": [ + { "method": "POST", "path": "/live/sessions", "body": { "garment_id": "g1", "max_seconds": 30, "end_user_id": "u1", "allowed_origin": "https://shop.test" } } + ], + "expectResultIsResponseBody": true + }, + { + "name": "startLiveSession with no options sends an empty object", + "method": "startLiveSession", + "params": {}, + "responses": [ + { + "status": 201, + "body": { + "ok": true, + "session": { "id": "s2", "status": "active", "endReason": null, "seconds": 0, "creditsCharged": 0, "endUserId": null, "createdAt": "x", "endedAt": null }, + "clientSecret": "cs", + "connection": { "provider": "decart", "model": "lucy-vton-latest", "token": "tok" }, + "secondsPerCredit": 2, + "maxSeconds": 180, + "secondsLeft": 116, + "garment": null + } + } + ], + "expectRequests": [{ "method": "POST", "path": "/live/sessions", "body": {} }], + "expectResultIsResponseBody": true + }, + { + "name": "getLiveSession escapes the id", + "method": "getLiveSession", + "params": { "sessionId": "a/b" }, + "responses": [ + { + "status": 200, + "body": { + "ok": true, + "session": { "id": "a/b", "status": "ended", "endReason": "user", "seconds": 9, "creditsCharged": 5, "endUserId": null, "createdAt": "x", "endedAt": "y" } + } + } + ], + "expectRequests": [{ "method": "GET", "path": "/live/sessions/a%2Fb" }], + "expectResult": { "id": "a/b", "status": "ended", "endReason": "user", "seconds": 9, "creditsCharged": 5, "endUserId": null, "createdAt": "x", "endedAt": "y" } + }, + { + "name": "stopLiveSession posts an empty object", + "method": "stopLiveSession", + "params": { "sessionId": "s1" }, + "responses": [ + { + "status": 200, + "body": { + "ok": true, + "session": { "id": "s1", "status": "ended", "endReason": "user", "seconds": 4, "creditsCharged": 2, "endUserId": "u1", "createdAt": "x", "endedAt": "y" } + } + } + ], + "expectRequests": [{ "method": "POST", "path": "/live/sessions/s1/stop", "body": {} }], + "expectResult": { "id": "s1", "status": "ended", "endReason": "user", "seconds": 4, "creditsCharged": 2, "endUserId": "u1", "createdAt": "x", "endedAt": "y" } + } + ], + "errorCases": [ + { + "name": "API envelope", + "response": { "status": 429, "body": { "ok": false, "error": { "name": "OutOfCredits", "message": "You do not have enough credits left. Please buy more." } } }, + "expectError": { "status": 429, "errorName": "OutOfCredits", "message": "You do not have enough credits left. Please buy more." } + }, + { + "name": "envelope without a name", + "response": { "status": 400, "body": { "ok": false, "error": { "message": "Invalid category/subcategory." } } }, + "expectError": { "status": 400, "errorName": null, "message": "Invalid category/subcategory." } + }, + { + "name": "legacy top-level strings", + "response": { "status": 400, "body": { "error": "BadRequest", "message": "legacy message" } }, + "expectError": { "status": 400, "errorName": "BadRequest", "message": "legacy message" } + }, + { + "name": "empty body", + "response": { "status": 502, "raw": "" }, + "expectError": { "status": 502, "errorName": null, "message": "HTTP 502" } + }, + { + "name": "non-JSON body", + "response": { "status": 500, "raw": "oops" }, + "expectError": { "status": 500, "errorName": null, "messageAnyOf": ["HTTP 500", "oops"] } + } + ], + "_errorCasesUsage": "Run each errorCase against getCredits() (GET /credits) and getLiveSession('s1'); both must raise the SDK's error type with the expected fields.", + "userAgent": { + "_comment": "Every request sends User-Agent: tryiton-/, e.g. tryiton-node/2.1.0, tryiton-python/2.1.0, tryiton-go/2.1.0, tryiton-php/2.1.0, tryiton-ruby/2.1.0. Tests assert the exact string from the SDK's version constant, and that the constant matches the package manifest where one exists.", + "pattern": "^tryiton-(node|python|go|php|ruby)/\\d+\\.\\d+\\.\\d+$" + }, + "authHeader": "Bearer test-key" +} diff --git a/tests/test_client.py b/tests/test_client.py new file mode 100644 index 0000000..ab83cbe --- /dev/null +++ b/tests/test_client.py @@ -0,0 +1,118 @@ +"""Unit tests for behavior the shared contract cases don't cover.""" + +import re +from pathlib import Path + +import pytest +import requests + +import tryiton +from tryiton import TryItOn, TryItOnError + +PROCESSING = {"status": 200, "body": {"ok": True, "status": "processing", "output": [], "error": None}} + + +def test_version_matches_pyproject(): + pyproject = (Path(__file__).parent.parent / "pyproject.toml").read_text(encoding="utf-8") + # tomllib is 3.11+; the [project] version line is simple enough to match directly. + match = re.search(r'^version\s*=\s*"([^"]+)"', pyproject, re.MULTILINE) + assert match, "no version in pyproject.toml" + assert tryiton.__version__ == match.group(1) + + +def test_py_typed_marker_ships_with_the_package(): + assert (Path(tryiton.__file__).parent / "py.typed").is_file() + + +@pytest.mark.parametrize("api_key", ["", None]) +def test_missing_api_key(api_key): + with pytest.raises(TryItOnError) as info: + TryItOn(api_key=api_key) + assert info.value.error_name == "ConfigError" + assert info.value.status is None + + +def test_default_base_url_and_trailing_slash(make_client): + client, adapter = make_client([{"status": 200, "body": {"ok": True, "credits": {}}}]) + client.get_credits() + assert adapter.requests[0].url == "https://tryiton.now/api/v1/credits" + + client, adapter = make_client([{"status": 200, "body": {"ok": True, "credits": {}}}], base_url="https://x.test/v1/") + client.get_credits() + assert adapter.requests[0].url == "https://x.test/v1/credits" + + +def test_user_agent_overrides_session_default(make_client): + client, adapter = make_client([{"status": 200, "body": {"ok": True, "credits": {}}}]) + client._session.headers["User-Agent"] = "custom/1.0" + client.get_credits() + assert adapter.requests[0].headers["User-Agent"] == f"tryiton-python/{tryiton.__version__}" + + +def test_request_timeout_is_passed_to_transport(make_client): + client, adapter = make_client([{"status": 200, "body": {"ok": True, "credits": {}}}], timeout=7.5) + client.get_credits() + assert adapter.timeouts == [7.5] + + +@pytest.mark.parametrize( + "exc", + [requests.ConnectionError("connection refused"), requests.Timeout("read timed out")], + ids=["connection", "timeout"], +) +def test_transport_errors_map_to_network_error(make_client, exc): + client, _ = make_client([exc]) + with pytest.raises(TryItOnError) as info: + client.get_credits() + assert info.value.error_name == "NetworkError" + assert info.value.status is None + assert str(exc) in str(info.value) + assert info.value.__cause__ is exc + + +def test_get_credits_defaults_missing_buckets_to_zero(make_client): + client, _ = make_client([{"status": 200, "body": {"ok": True, "credits": {"subscription": 3}}}]) + assert client.get_credits() == tryiton.Credits(on_demand=0, subscription=3, purchased=0, reserved=0) + + +def test_wait_for_result_times_out(make_client): + client, adapter = make_client([PROCESSING]) + # A negative timeout puts the deadline in the past, so the first poll is the last. + with pytest.raises(TryItOnError) as info: + client.wait_for_result("job_1", poll_interval=0, timeout=-1) + assert info.value.error_name == "Timeout" + assert info.value.status is None + assert len(adapter.requests) == 1 + + +def test_wait_for_result_failed_without_reason(make_client): + client, _ = make_client([{"status": 200, "body": {"ok": True, "status": "failed", "output": [], "error": None}}]) + with pytest.raises(TryItOnError) as info: + client.wait_for_result("job_1", poll_interval=0) + assert str(info.value) == "Try-on failed." + assert info.value.error_name == "ProcessingError" + + +def test_wait_for_result_accepts_legacy_error_object(make_client): + legacy = {"name": "ModerationError", "message": "Blocked by moderation."} + client, _ = make_client([{"status": 200, "body": {"ok": True, "status": "failed", "output": [], "error": legacy}}]) + with pytest.raises(TryItOnError) as info: + client.wait_for_result("job_1", poll_interval=0) + assert str(info.value) == "Blocked by moderation." + assert info.value.error_name == "ModerationError" + + +def test_wait_for_result_surfaces_http_errors(make_client): + error = {"status": 404, "body": {"ok": False, "error": {"name": "AppError", "message": "Tryon not found."}}} + client, _ = make_client([PROCESSING, error]) + with pytest.raises(TryItOnError) as info: + client.wait_for_result("job_1", poll_interval=0) + assert (info.value.status, info.value.error_name, str(info.value)) == (404, "AppError", "Tryon not found.") + + +def test_typed_responses_are_plain_dicts(make_client): + garment = {"id": "g1", "category": "clothing", "subcategory": None, "description": None, "createdAt": "x"} + client, _ = make_client([{"status": 201, "body": {"ok": True, "garment": garment}}]) + result = client.prepare_live_garment("https://example.com/shirt.jpg") + assert type(result) is dict + assert result == garment diff --git a/tests/test_contract.py b/tests/test_contract.py new file mode 100644 index 0000000..ebec380 --- /dev/null +++ b/tests/test_contract.py @@ -0,0 +1,142 @@ +"""Shared SDK contract cases (tests/fixtures/sdk-cases.json). + +The fixture is generated: edit tryiton/backend/api-contract/sdk-cases.json and run +`node tryiton-sdk/sync-contract.mjs`. Canonical names are camelCase; the tables +below map them to this SDK's snake_case methods and keyword arguments. +""" + +import dataclasses +import json +import re +from pathlib import Path + +import pytest + +import tryiton +from tryiton import TryItOnError + +CASES = json.loads((Path(__file__).parent / "fixtures" / "sdk-cases.json").read_text(encoding="utf-8")) +BASE_URL = CASES["baseUrl"] +USER_AGENT = f"tryiton-python/{tryiton.__version__}" + +METHODS = { + "tryOnFashion": "try_on_fashion", + "tryOnHairstyle": "try_on_hairstyle", + "tryOnTattoo": "try_on_tattoo", + "getStatus": "get_status", + "getCredits": "get_credits", + "waitForResult": "wait_for_result", + "getLiveConfig": "get_live_config", + "prepareLiveGarment": "prepare_live_garment", + "startLiveSession": "start_live_session", + "getLiveSession": "get_live_session", + "stopLiveSession": "stop_live_session", +} + +PARAMS = { + "modelImage": "model_image", + "garmentImage": "garment_image", + "category": "category", + "subcategory": "subcategory", + "mode": "mode", + "numSamples": "num_samples", + "outputFormat": "output_format", + "moderationLevel": "moderation_level", + "faceImage": "face_image", + "haircut": "haircut", + "hairColor": "hair_color", + "bodyImage": "body_image", + "designImage": "design_image", + "placement": "placement", + "region": "region", + "jobId": "job_id", + "sessionId": "session_id", + "garmentId": "garment_id", + "maxSeconds": "max_seconds", + "endUserId": "end_user_id", + "allowedOrigin": "allowed_origin", +} + +# Extra kwargs per method, so polling cases run instantly. +EXTRA_KWARGS = {"waitForResult": {"poll_interval": 0}} + + +def call(client, case): + method = case["method"] + assert method in METHODS, f"No Python mapping for contract method {method!r}" + kwargs = {} + for name, value in case["params"].items(): + assert name in PARAMS, f"No Python mapping for contract param {name!r}" + kwargs[PARAMS[name]] = value + kwargs.update(EXTRA_KWARGS.get(method, {})) + return getattr(client, METHODS[method])(**kwargs) + + +def plain(value): + """Status and Credits are dataclasses; compare them as the dicts the fixture lists.""" + return dataclasses.asdict(value) if dataclasses.is_dataclass(value) else value + + +def assert_request(prepared, expected): + assert prepared.method == expected["method"] + assert prepared.url.startswith(BASE_URL), prepared.url + assert prepared.url[len(BASE_URL):] == expected["path"] + assert prepared.headers["Authorization"] == CASES["authHeader"] + assert prepared.headers["User-Agent"] == USER_AGENT + if "body" in expected: + assert prepared.headers["Content-Type"] == "application/json" + assert json.loads(prepared.body) == expected["body"] + if expected["method"] == "GET": + assert prepared.body is None + + +def assert_error(err, expected): + assert err.status == expected["status"] + assert err.error_name == expected["errorName"] + if "messageAnyOf" in expected: + assert str(err) in expected["messageAnyOf"] + else: + assert str(err) == expected["message"] + + +def test_user_agent_matches_contract_pattern(): + assert re.match(CASES["userAgent"]["pattern"], USER_AGENT) + + +@pytest.mark.parametrize("case", CASES["methodCases"], ids=[c["name"] for c in CASES["methodCases"]]) +def test_method_case(make_client, case): + client, adapter = make_client(case["responses"], api_key=CASES["apiKey"], base_url=BASE_URL) + + if "expectError" in case: + with pytest.raises(TryItOnError) as info: + call(client, case) + assert_error(info.value, case["expectError"]) + else: + result = call(client, case) + if case.get("expectResultIsResponseBody"): + assert result == case["responses"][-1]["body"] + else: + assert plain(result) == case["expectResult"] + + assert len(adapter.requests) == len(case["expectRequests"]) + for prepared, expected in zip(adapter.requests, case["expectRequests"]): + assert_request(prepared, expected) + + +ERROR_TARGETS = { + "get_credits": (lambda c: c.get_credits(), "/credits"), + "get_live_session": (lambda c: c.get_live_session("s1"), "/live/sessions/s1"), +} + + +@pytest.mark.parametrize("target", list(ERROR_TARGETS)) +@pytest.mark.parametrize("case", CASES["errorCases"], ids=[c["name"] for c in CASES["errorCases"]]) +def test_error_case(make_client, case, target): + client, adapter = make_client([case["response"]], api_key=CASES["apiKey"], base_url=BASE_URL) + invoke, path = ERROR_TARGETS[target] + + with pytest.raises(TryItOnError) as info: + invoke(client) + + assert_error(info.value, case["expectError"]) + assert_request(adapter.requests[0], {"method": "GET", "path": path}) diff --git a/tryiton/__init__.py b/tryiton/__init__.py index 7d09bb1..cebe251 100644 --- a/tryiton/__init__.py +++ b/tryiton/__init__.py @@ -7,9 +7,32 @@ TryItOn, TryItOnError, HAIRCUTS, +) +from .types import ( Status, Credits, + LiveConfig, + LiveGarment, + LiveGarmentInput, + LiveSessionGarment, + LiveConnection, + LiveSession, + LiveSessionStart, ) -__all__ = ["TryItOn", "TryItOnError", "HAIRCUTS", "Status", "Credits"] -__version__ = "0.1.0" +__all__ = [ + "TryItOn", + "TryItOnError", + "HAIRCUTS", + "Status", + "Credits", + "LiveConfig", + "LiveGarment", + "LiveGarmentInput", + "LiveSessionGarment", + "LiveConnection", + "LiveSession", + "LiveSessionStart", +] +# Single source of the SDK version (sent in the User-Agent); keep it equal to pyproject.toml. +__version__ = "2.1.0" diff --git a/tryiton/client.py b/tryiton/client.py index 81587ef..04906f6 100644 --- a/tryiton/client.py +++ b/tryiton/client.py @@ -3,11 +3,13 @@ from __future__ import annotations import time -from dataclasses import dataclass -from typing import Any, Dict, List, Optional +from typing import Any, Dict, List, Optional, cast +from urllib.parse import quote import requests +from .types import Credits, LiveConfig, LiveGarment, LiveSession, LiveSessionStart, Status + DEFAULT_BASE_URL = "https://tryiton.now/api/v1" # Supported `haircut` values for hairstyle try-on. @@ -35,23 +37,6 @@ def __init__(self, message: str, *, status: Optional[int] = None, error_name: Op self.error_name = error_name -@dataclass -class Status: - """A job's status snapshot.""" - - status: str # "processing" | "completed" | "failed" - output: List[str] - error: Optional[Dict[str, str]] - - -@dataclass -class Credits: - on_demand: int - subscription: int - purchased: int - reserved: int - - class TryItOn: """Client for the TryItOn virtual try-on API. @@ -80,8 +65,10 @@ def __init__( self.base_url = base_url.rstrip("/") self.timeout = timeout self._session = session or requests.Session() + # Imported here, not at module level: the package __init__ imports this module first. + from . import __version__ - # ── Try-on submissions ──────────────────────────────────────────────── + self._user_agent = f"tryiton-python/{__version__}" def try_on_fashion( self, @@ -113,7 +100,7 @@ def try_on_fashion( "output_format": output_format, "moderation_level": moderation_level, } - return self._request("POST", "/tryon/fashion", body)["jobId"] + return cast(str, self._request("POST", "/tryon/fashion", body)["jobId"]) def try_on_hairstyle( self, @@ -136,7 +123,7 @@ def try_on_hairstyle( "num_samples": num_samples, "output_format": output_format, } - return self._request("POST", "/tryon/hairstyle", body)["jobId"] + return cast(str, self._request("POST", "/tryon/hairstyle", body)["jobId"]) def try_on_tattoo( self, @@ -150,12 +137,9 @@ def try_on_tattoo( ) -> str: """Ink a design onto skin. Returns the job id. - Position the tattoo in either of two ways, and they compose: - `placement` is free text ("on the right forearm, small"), while `region` - pins the exact spot as a rectangle on the body image -- - ``{"x": .., "y": .., "w": .., "h": ..}``, normalized 0-1 from the - top-left corner, each side at least 0.06. With a region, `placement` - only describes size/style. + `placement` is free text ("on the right forearm, small"). `region` pins the + exact spot: ``{"x", "y", "w", "h"}`` normalized 0-1 from the top-left, + each side >= 0.06; with it, `placement` only describes size/style. `num_samples` is 1-4 (charged per image) and `output_format` is "png" or "jpeg". @@ -168,13 +152,11 @@ def try_on_tattoo( "num_samples": num_samples, "output_format": output_format, } - return self._request("POST", "/tryon/tattoo", body)["jobId"] - - # ── Status & credits ────────────────────────────────────────────────── + return cast(str, self._request("POST", "/tryon/tattoo", body)["jobId"]) def get_status(self, job_id: str) -> Status: - """Fetch the current status of a job.""" - data = self._request("GET", f"/status/{job_id}") + """Fetch the current status of a job. The id is URL-escaped.""" + data = self._request("GET", f"/status/{quote(str(job_id), safe='')}") return Status( status=data.get("status", "processing"), output=data.get("output") or [], @@ -191,6 +173,86 @@ def get_credits(self) -> Credits: reserved=c.get("reserved", 0), ) + # Live (real-time webcam) try-on. Server side only: the end user's browser + # streams with the `tryiton-live` npm package, using the response of + # start_live_session (session-scoped credentials, never your API key). + + def get_live_config(self) -> LiveConfig: + """Live try-on availability and pricing for your account. + + Returns a dict with ``enabled``, ``secondsPerCredit``, ``maxSeconds``, + ``minCredits`` and ``maxConcurrentSessions``. + """ + data = self._request("GET", "/live/config") + return cast(LiveConfig, {k: v for k, v in data.items() if k != "ok"}) + + def prepare_live_garment( + self, + garment_image: str, + *, + category: Optional[str] = None, + subcategory: Optional[str] = None, + ) -> LiveGarment: + """Prepare a garment for live try-on. Returns the garment dict. + + Do it once per product ahead of time (e.g. at catalog sync): it's cached + per image and category, so starting a session or switching garments + later is instant. `garment_image` is a URL or base64 data URL. Passing + `category` (and `subcategory`, e.g. "tops") is recommended; omit it to + let it be detected. + + The dict has ``id`` (pass it to start_live_session), ``category``, + ``subcategory``, ``description`` and ``createdAt``. + """ + body = { + "garment_image": garment_image, + "category": category, + "subcategory": subcategory, + } + return cast(LiveGarment, self._request("POST", "/live/garments", body)["garment"]) + + def start_live_session( + self, + *, + garment_id: Optional[str] = None, + max_seconds: Optional[int] = None, + end_user_id: Optional[str] = None, + allowed_origin: Optional[str] = None, + ) -> LiveSessionStart: + """Start a live session for one end user. Holds the first credit. + + Returns the full response body (``session``, ``clientSecret``, + ``connection``, ``secondsPerCredit``, ``maxSeconds``, ``secondsLeft``, + ``garment``). Send it to the browser unchanged; it streams with + ``connectLiveTryOn`` from the `tryiton-live` npm package. + + `garment_id` is a prepared garment to start with. `max_seconds` caps the + session (10 to the account's maxSeconds). `end_user_id` is your id for + the end user: one stream per end user, a restart ends the previous one. + `allowed_origin` locks the media token to your site, e.g. + "https://shop.example.com". + """ + body = { + "garment_id": garment_id, + "max_seconds": max_seconds, + "end_user_id": end_user_id, + "allowed_origin": allowed_origin, + } + return cast(LiveSessionStart, self._request("POST", "/live/sessions", body)) + + def get_live_session(self, session_id: str) -> LiveSession: + """Status and usage of a live session. Returns the session dict.""" + data = self._request("GET", f"/live/sessions/{quote(session_id, safe='')}") + return cast(LiveSession, data["session"]) + + def stop_live_session(self, session_id: str) -> LiveSession: + """End a live session from your server (e.g. the user left). Idempotent. + + Returns the ended session dict. + """ + data = self._request("POST", f"/live/sessions/{quote(session_id, safe='')}/stop", {}) + return cast(LiveSession, data["session"]) + def wait_for_result( self, job_id: str, @@ -208,11 +270,7 @@ def wait_for_result( if status.status == "completed": return status.output if status.status == "failed": - err = status.error or {} - raise TryItOnError( - err.get("message", "Try-on failed."), - error_name=err.get("name", "ProcessingError"), - ) + raise _job_failure(status.error) if time.monotonic() > deadline: raise TryItOnError( f"Timed out waiting for job {job_id} after {timeout}s.", @@ -220,11 +278,9 @@ def wait_for_result( ) time.sleep(poll_interval) - # ── Internals ───────────────────────────────────────────────────────── - def _request(self, method: str, path: str, body: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: url = f"{self.base_url}{path}" - headers = {"Authorization": f"Bearer {self.api_key}"} + headers = {"Authorization": f"Bearer {self.api_key}", "User-Agent": self._user_agent} payload = None if body is not None: payload = {k: v for k, v in body.items() if v is not None} @@ -243,10 +299,29 @@ def _request(self, method: str, path: str, body: Optional[Dict[str, Any]] = None data = {} if not resp.ok: + # API envelope: {"ok": false, "error": {"name", "message"}}. Older shapes put strings at the top level. + if not isinstance(data, dict): + data = {} + error = data.get("error") + api_error: Dict[str, Any] = error if isinstance(error, dict) else {} + top_message = data.get("message") if isinstance(data.get("message"), str) else None + top_name = error if isinstance(error, str) else None raise TryItOnError( - data.get("message", f"HTTP {resp.status_code}"), + api_error.get("message") or top_message or f"HTTP {resp.status_code}", status=resp.status_code, - error_name=data.get("error"), + error_name=api_error.get("name") or top_name, ) return data + + +def _job_failure(error: Any) -> TryItOnError: + """The error for a failed job. `GET /status` sends the reason as a plain string; a + `{"name", "message"}` dict is still accepted from older API versions.""" + if isinstance(error, dict): + return TryItOnError( + error.get("message") or "Try-on failed.", + error_name=error.get("name") or "ProcessingError", + ) + message = error if isinstance(error, str) and error else "Try-on failed." + return TryItOnError(message, error_name="ProcessingError") diff --git a/tryiton/py.typed b/tryiton/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/tryiton/types.py b/tryiton/types.py new file mode 100644 index 0000000..c0a86b4 --- /dev/null +++ b/tryiton/types.py @@ -0,0 +1,112 @@ +"""Response types for the TryItOn API client. + +`Status` and `Credits` are dataclasses (attribute access, as since 0.1.0). The live +try-on responses are `TypedDict`s: plain dicts at runtime, typed for checkers. They +mirror the backend's JSON (camelCase keys) and may gain keys in later API versions. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import List, Optional, TypedDict + + +@dataclass +class Status: + """A job's status snapshot, from ``GET /status/{id}``.""" + + status: str # "processing" | "completed" | "failed" + output: List[str] + # The failure reason of a failed job, as plain text; None otherwise. + error: Optional[str] + + +@dataclass +class Credits: + """Your credit balance, from ``GET /credits``.""" + + on_demand: int + subscription: int + purchased: int + reserved: int + + +class LiveConfig(TypedDict): + """Live try-on availability and pricing, from ``GET /live/config``.""" + + enabled: bool + secondsPerCredit: int + maxSeconds: int + minCredits: int + maxConcurrentSessions: int + + +class LiveGarment(TypedDict): + """A garment prepared for live try-on.""" + + id: str + category: str + subcategory: Optional[str] + description: Optional[str] + createdAt: str # ISO 8601 + + +class LiveGarmentInput(TypedDict): + """The stream input for a prepared garment.""" + + prompt: str + enhancePrompt: bool + referenceImage: str # data URL + + +class LiveSessionGarment(LiveGarment): + """The starting garment of a live session, with its stream input.""" + + input: Optional[LiveGarmentInput] + + +class LiveConnection(TypedDict): + """Media-provider connection details for the end user's browser.""" + + provider: str + model: str + token: str + + +class LiveSession(TypedDict): + """A live session's status and usage.""" + + id: str + status: str # "active" | "ended" + endReason: Optional[str] + seconds: int + creditsCharged: int + endUserId: Optional[str] + createdAt: str # ISO 8601 + endedAt: Optional[str] + + +class LiveSessionStart(TypedDict): + """The full ``POST /live/sessions`` response. Send it to the browser unchanged.""" + + ok: bool + session: LiveSession + clientSecret: str + connection: LiveConnection + secondsPerCredit: int + maxSeconds: int + secondsLeft: int + garment: Optional[LiveSessionGarment] + + +__all__ = [ + "Status", + "Credits", + "LiveConfig", + "LiveGarment", + "LiveGarmentInput", + "LiveSessionGarment", + "LiveConnection", + "LiveSession", + "LiveSessionStart", +] From 1863a1a85fb67ad20472ee694843711ad9d8c6c1 Mon Sep 17 00:00:00 2001 From: 0xBitBuster Date: Thu, 26 Nov 2026 15:39:56 +0100 Subject: [PATCH 2/2] ci: run Python 3.9 on ubuntu-22.04 ubuntu-latest (26.04) has no setup-python build for 3.9 any more, same as 3.8. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/test.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 61628a9..6354771 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -10,12 +10,14 @@ jobs: strategy: fail-fast: false matrix: - python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"] + python-version: ["3.10", "3.11", "3.12", "3.13"] os: [ubuntu-latest] include: - # setup-python has no 3.8 build for ubuntu-24.04 (ubuntu-latest). + # setup-python has no 3.8/3.9 builds for newer ubuntu-latest images; pin the old ones to 22.04. - python-version: "3.8" os: ubuntu-22.04 + - python-version: "3.9" + os: ubuntu-22.04 steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5