Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
name: test

on:
push:
pull_request:

jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
python-version: ["3.10", "3.11", "3.12", "3.13"]
os: [ubuntu-latest]
include:
# 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
with:
python-version: ${{ matrix.python-version }}
- run: python -m pip install -e ".[dev]"
- run: python -m pytest
- run: python -m mypy tryiton
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,5 @@ build/
dist/
.venv/
venv/
.pytest_cache/
.mypy_cache/
67 changes: 67 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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/<version>`.
- 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 <status>` 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
43 changes: 43 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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)
Expand Down
14 changes: 13 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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"
Expand All @@ -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
73 changes: 73 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading