Compare commits

..
Author SHA1 Message Date
Hanashi de0e48f3f1 don't allow 8 2026-08-10 01:58:29 -04:00
Hanashi 66acb8e195 batch sizes 2026-08-10 01:55:34 -04:00
430 changed files with 7804 additions and 22224 deletions
@@ -1,135 +0,0 @@
{
"db_name": "MySQL",
"query": "\nSELECT\n token as `token: McpSessionToken`,\n user_token as `user_token: UserToken`,\n maybe_mcp_client_name,\n maybe_mcp_client_version,\n maybe_mcp_client_vendor,\n ip_address_creation,\n ip_address_update,\n created_at,\n updated_at,\n expires_at,\n maybe_deleted_at\nFROM mcp_sessions\nWHERE user_token = ?\nORDER BY id DESC\nLIMIT ? OFFSET ?\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "token: McpSessionToken",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | UNIQUE_KEY | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 128
}
},
{
"ordinal": 1,
"name": "user_token: UserToken",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | MULTIPLE_KEY | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 128
}
},
{
"ordinal": 2,
"name": "maybe_mcp_client_name",
"type_info": {
"type": "VarString",
"flags": "BINARY",
"char_set": 224,
"max_size": 1020
}
},
{
"ordinal": 3,
"name": "maybe_mcp_client_version",
"type_info": {
"type": "VarString",
"flags": "BINARY",
"char_set": 224,
"max_size": 1020
}
},
{
"ordinal": 4,
"name": "maybe_mcp_client_vendor",
"type_info": {
"type": "VarString",
"flags": "BINARY",
"char_set": 224,
"max_size": 1020
}
},
{
"ordinal": 5,
"name": "ip_address_creation",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | MULTIPLE_KEY | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 160
}
},
{
"ordinal": 6,
"name": "ip_address_update",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 160
}
},
{
"ordinal": 7,
"name": "created_at",
"type_info": {
"type": "Timestamp",
"flags": "NOT_NULL | BINARY | TIMESTAMP",
"char_set": 63,
"max_size": 19
}
},
{
"ordinal": 8,
"name": "updated_at",
"type_info": {
"type": "Timestamp",
"flags": "NOT_NULL | BINARY | TIMESTAMP | ON_UPDATE_NOW",
"char_set": 63,
"max_size": 19
}
},
{
"ordinal": 9,
"name": "expires_at",
"type_info": {
"type": "Timestamp",
"flags": "NOT_NULL | BINARY | TIMESTAMP",
"char_set": 63,
"max_size": 19
}
},
{
"ordinal": 10,
"name": "maybe_deleted_at",
"type_info": {
"type": "Timestamp",
"flags": "MULTIPLE_KEY | BINARY",
"char_set": 63,
"max_size": 19
}
}
],
"parameters": {
"Right": 3
},
"nullable": [
false,
false,
true,
true,
true,
false,
false,
false,
false,
false,
true
]
},
"hash": "5ad1951163b15a9e241f949f2e66cde830d51d70b395f93000bc47ecb9c2083f"
}
@@ -1,12 +0,0 @@
{
"db_name": "MySQL",
"query": "\nUPDATE mcp_sessions\nSET maybe_deleted_at = NOW()\nWHERE private_session_token = ?\n AND maybe_deleted_at IS NULL\nLIMIT 1\n ",
"describe": {
"columns": [],
"parameters": {
"Right": 1
},
"nullable": []
},
"hash": "827eb468e1f732f72e0dc8f655add2b50f12cb933bba230a1fd4abb594a1944a"
}
@@ -1,113 +0,0 @@
{
"db_name": "MySQL",
"query": "\nSELECT\n users.token as `user_token: UserToken`,\n users.username,\n users.display_name,\n users.email_address,\n users.user_role_slug,\n users.is_banned,\n user_roles.can_ban_users,\n users.maybe_feature_flags,\n mcp_sessions.token as `mcp_session_token: McpSessionToken`\nFROM mcp_sessions\nINNER JOIN users\n ON users.token = mcp_sessions.user_token\nLEFT OUTER JOIN user_roles\n ON users.user_role_slug = user_roles.slug\nWHERE mcp_sessions.private_session_token = ?\n AND mcp_sessions.maybe_deleted_at IS NULL\n AND mcp_sessions.expires_at > NOW()\n AND users.user_deleted_at IS NULL\n AND users.mod_deleted_at IS NULL\nLIMIT 1\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "user_token: UserToken",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | UNIQUE_KEY | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 128
}
},
{
"ordinal": 1,
"name": "username",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | UNIQUE_KEY | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 80
}
},
{
"ordinal": 2,
"name": "display_name",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 80
}
},
{
"ordinal": 3,
"name": "email_address",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | UNIQUE_KEY | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 1020
}
},
{
"ordinal": 4,
"name": "user_role_slug",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | MULTIPLE_KEY | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 64
}
},
{
"ordinal": 5,
"name": "is_banned",
"type_info": {
"type": "Tiny",
"flags": "NOT_NULL",
"char_set": 63,
"max_size": 1
}
},
{
"ordinal": 6,
"name": "can_ban_users",
"type_info": {
"type": "Tiny",
"flags": "",
"char_set": 63,
"max_size": 1
}
},
{
"ordinal": 7,
"name": "maybe_feature_flags",
"type_info": {
"type": "VarString",
"flags": "BINARY",
"char_set": 224,
"max_size": 1020
}
},
{
"ordinal": 8,
"name": "mcp_session_token: McpSessionToken",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | UNIQUE_KEY | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 128
}
}
],
"parameters": {
"Right": 1
},
"nullable": [
false,
false,
false,
false,
false,
false,
true,
true,
false
]
},
"hash": "847acba63c2ee29b5d59bea4cdd88f12ec4b3e8a4317ab26a1e9039c0b66a1b2"
}
@@ -1,12 +0,0 @@
{
"db_name": "MySQL",
"query": "\nUPDATE mcp_sessions\nSET maybe_deleted_at = NOW()\nWHERE token = ?\n AND maybe_deleted_at IS NULL\nLIMIT 1\n ",
"describe": {
"columns": [],
"parameters": {
"Right": 1
},
"nullable": []
},
"hash": "8b61abdfcfcd5c601489521793ef5c8cbe47f408e5c7e9c9a6bf01c9c8a57247"
}
@@ -1,135 +0,0 @@
{
"db_name": "MySQL",
"query": "\nSELECT\n token as `token: McpSessionToken`,\n user_token as `user_token: UserToken`,\n maybe_mcp_client_name,\n maybe_mcp_client_version,\n maybe_mcp_client_vendor,\n ip_address_creation,\n ip_address_update,\n created_at,\n updated_at,\n expires_at,\n maybe_deleted_at\nFROM mcp_sessions\nWHERE token = ?\nLIMIT 1\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "token: McpSessionToken",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | UNIQUE_KEY | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 128
}
},
{
"ordinal": 1,
"name": "user_token: UserToken",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | MULTIPLE_KEY | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 128
}
},
{
"ordinal": 2,
"name": "maybe_mcp_client_name",
"type_info": {
"type": "VarString",
"flags": "BINARY",
"char_set": 224,
"max_size": 1020
}
},
{
"ordinal": 3,
"name": "maybe_mcp_client_version",
"type_info": {
"type": "VarString",
"flags": "BINARY",
"char_set": 224,
"max_size": 1020
}
},
{
"ordinal": 4,
"name": "maybe_mcp_client_vendor",
"type_info": {
"type": "VarString",
"flags": "BINARY",
"char_set": 224,
"max_size": 1020
}
},
{
"ordinal": 5,
"name": "ip_address_creation",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | MULTIPLE_KEY | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 160
}
},
{
"ordinal": 6,
"name": "ip_address_update",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 160
}
},
{
"ordinal": 7,
"name": "created_at",
"type_info": {
"type": "Timestamp",
"flags": "NOT_NULL | BINARY | TIMESTAMP",
"char_set": 63,
"max_size": 19
}
},
{
"ordinal": 8,
"name": "updated_at",
"type_info": {
"type": "Timestamp",
"flags": "NOT_NULL | BINARY | TIMESTAMP | ON_UPDATE_NOW",
"char_set": 63,
"max_size": 19
}
},
{
"ordinal": 9,
"name": "expires_at",
"type_info": {
"type": "Timestamp",
"flags": "NOT_NULL | BINARY | TIMESTAMP",
"char_set": 63,
"max_size": 19
}
},
{
"ordinal": 10,
"name": "maybe_deleted_at",
"type_info": {
"type": "Timestamp",
"flags": "MULTIPLE_KEY | BINARY",
"char_set": 63,
"max_size": 19
}
}
],
"parameters": {
"Right": 1
},
"nullable": [
false,
false,
true,
true,
true,
false,
false,
false,
false,
false,
true
]
},
"hash": "c59cea297d441b4960074802809af5ff0bdf8969abb34c01101584bffd887010"
}
@@ -1,12 +0,0 @@
{
"db_name": "MySQL",
"query": "\nUPDATE mcp_sessions\nSET\n expires_at = NOW() + INTERVAL ? DAY,\n private_refresh_token = ?,\n ip_address_update = ?\nWHERE private_session_token = ?\n AND private_refresh_token = ?\n AND maybe_deleted_at IS NULL\n AND expires_at > NOW()\nLIMIT 1\n ",
"describe": {
"columns": [],
"parameters": {
"Right": 5
},
"nullable": []
},
"hash": "ed8f7ef94099d2dddf50f819316485351e149db72ce8a4f5cff6b57f4b84244d"
}
@@ -1,12 +0,0 @@
{
"db_name": "MySQL",
"query": "\nINSERT INTO mcp_sessions\nSET\n token = ?,\n private_session_token = ?,\n private_refresh_token = ?,\n user_token = ?,\n maybe_mcp_client_name = ?,\n maybe_mcp_client_version = ?,\n maybe_mcp_client_vendor = ?,\n ip_address_creation = ?,\n ip_address_update = ?,\n created_at = NOW(),\n expires_at = NOW() + INTERVAL ? DAY\n ",
"describe": {
"columns": [],
"parameters": {
"Right": 10
},
"nullable": []
},
"hash": "f67a73ea3d5751cc76d2d6f954bd939179b3e9005a359e04c3a4dd78f8fe562e"
}
-97
View File
@@ -1,97 +0,0 @@
# AGENTS.md
This file provides guidance for coding agents when working with the Artcraft monorepo.
## Project Overview
Artcraft is a web and desktop application for generating AI image and video. It is written in
Rust and TypeScript and contains desktop, server, and frontend components.
## Project Structure
```
artcraft/
├── _database/ # Schema definitions and migrations (MySQL, SQLite, Elasticsearch, etc.)
│ ├── elasticsearch/ # Elasticsearch schema and queries
│ └── sql/ # MySQL and SQLite schema definitions and migrations
│ ├── artcraft_migrations/ # ArtCraft desktop app SQLite migrations
│ ├── migrations/ # Server MySQL migrations
│ └── migrations_squashed/ # Fully materialized MySQL schema definitions for most tables
├── _tools/ # Various 3rd party tool integrations and configurations
│ └── postman/ # Postman configs for test HTTP requests against development and production
├── build/ # Dockerfile build instructions for server components
├── crates/ # Rust workspace
│ ├── api_clients/ # HTTP clients for calling internal and 3rd party services
│ ├── cli/ # Command line tools
│ ├── desktop/ # Desktop (Tauri) apps
│ │ └── artcraft/ # (Important) ArtCraft, the desktop app. This is one of our main pieces of software
│ ├── lib/ # Various utility libraries for servers, CLI tools, desktop, etc.
│ ├── schema/ # Data definition layer: MySQL, SQlite, Redis, S3/R2 buckets, etc.
│ │ ├── buckets/ # Declares R2 cloud bucket topology
│ │ ├── database/ # MySQL, SQLite, Elasticsearch, Redis, etc.
│ │ │ ├── elasticsearch_schema/ # Elasticsearch
│ │ │ ├── migration/ # (deprecated) Online schema adapters for MySQL
│ │ │ ├── mysql_queries/ # Sqlx MySQL queries for our backend monolith `storyteller-web`, jobs, etc.
│ │ │ ├── redis_common/ # Redis support
│ │ │ ├── redis_schema/ # Redis key and HKEY topology
│ │ │ ├── sqlite_queries/ # (deprecated) Sqlite queries
│ │ │ └── sqlite_tasks/ # Queries for the ArtCraft desktop app's "tasks" database.
│ │ ├── public/ # Token identifier and enum variant definitions
│ │ │ ├── composite_identifier/ # MySQL composite key system
│ │ │ ├── enums/ # MySQL "enums" stored in VARCHAR fields.
│ │ │ └── tokens/ # Primary database identifiers with Stripe-like ID prefixes, eg. "user_{entropy}"
│ │ └── service/ # Backend HTTP services and jobs
│ │ ├── job/ # Backend jobs.
│ │ │ └── video_thumbnail_job/ # Render video thumbnails
│ │ ├── plugins/ # Collections of reusable Actix-Web HTTP functions (user and billing systems)
│ │ └── web/ # HTTP web servers
│ │ └── storyteller_web/ # (Important) Our main HTTP API monolith and backend.
│ └── frontend/ # Nx typescript monorepo for our websites and Tauri desktop apps
│ ├── apps/ # Websites and Tauri desktop apps
│ │ ├── artcraft/ # ArtCraft the Tauri app's frontend. Used in conjunction with `artcraft` the Rust crate.
│ │ └── artcraft-website/ # The website for https://getartcraft.com
│ └── libs/ # Support libraries, reusable React components, etc.
└── Cargo.toml # Rust monorepo workspace
```
## Code Style
- Rust with no minimum supported version
- Actix-web for HTTP services
- SQLx for MySQL and SQLite; prefer `sqlx::query!` / `sqlx::query_as!` compile-time checked macros over runtime `sqlx::query()` whenever possible
- MySQL queries belong in the `mysql_queries` crate, not in application/service crates like `storyteller-web` — call those query functions instead of embedding `sqlx::query!` / `sqlx::query()` in handlers. (Query-writing conventions live in `crates/schema/database/mysql_queries/AGENTS.md`.)
- A mix of wreq and reqwest for Rust HTTP clients
- Never use `println!` or `eprintln!` outside of tests; use `log` crate macros instead
- When two crates export the same type name, alias imports with a suffix: `use foo::Bar as BarFoo;`
- Prefer `use` imports over inline fully-qualified paths; only qualify inline for true one-offs or std collisions
- TypeScript with Nx, React, Vite, Zustand, and Three.js
- Use two spaces for indentation
### File Layout
Organize for top-to-bottom reading. Important things first, details later.
- **Constants** at the top (after imports)
- **Structs/enums** next; outer structs above inner sub-structs
- **API types** in order: Request, Response, Error
- **In impl blocks**: constructors first, then public methods, then private helpers
- Private helpers go *below* the methods that call them
- Among helpers: meatier logic above leaf-level formatters
- **In test modules**: constants first, then test cases (grouped into sub-modules when 2+), then helper functions last
## Markdown
- **Tables must be space-padded so columns align in plain text.** Markdown
tables are read raw (terminals, diffs, editors) at least as often as
rendered, and condensed tables are unreadable there. Pad every cell to its
column width:
```markdown
| Model | Configuration | Credits | Speed | Score |
|--------------|---------------|--------------------|---------|
| Meshy 6 | text or image | 104 | 80.0 | +24 |
| Rodin 2.5 | text or image | 13 | 10.0 | +3 |
```
Not: `| Model | Configuration | Credits | Speed | Score |` packed tight
with varying widths per row.
-1
View File
@@ -1 +0,0 @@
AGENTS.md
+96
View File
@@ -0,0 +1,96 @@
# CLAUDE.md
This file provides guidance for Claude Code when working with the Artcraft monorepo.
## Project Overview
Artcraft is a web and desktop application for generating AI image and video. It is written in
Rust and TypeScript and contains desktop, server, and frontend components.
## Project Structure
```
artcraft/
├── _database/ # Schema definitions and migrations (MySQL, SQLite, Elasticsearch, etc.)
│ ├── elasticsearch/ # Elasticsearch schema and queries
│ └── sql/ # MySQL and SQLite schema definitions and migrations
│ ├── artcraft_migrations/ # ArtCraft desktop app SQLite migrations
│ ├── migrations/ # Server MySQL migrations
│ └── migrations_squashed/ # Fully materialized MySQL schema definitions for most tables
├── _tools/ # Various 3rd party tool integrations and configurations
│ └── postman/ # Postman configs for test HTTP requests against development and production
├── build/ # Dockerfile build instructions for server components
├── crates/ # Rust workspace
│ ├── api_clients/ # HTTP clients for calling internal and 3rd party services
│ ├── cli/ # Command line tools
│ ├── desktop/ # Desktop (Tauri) apps
│ │ └── artcraft/ # (Important) ArtCraft, the desktop app. This is one of our main pieces of software
│ ├── lib/ # Various utility libraries for servers, CLI tools, desktop, etc.
│ ├── schema/ # Data definition layer: MySQL, SQlite, Redis, S3/R2 buckets, etc.
│ │ ├── buckets/ # Declares R2 cloud bucket topology
│ │ ├── database/ # MySQL, SQLite, Elasticsearch, Redis, etc.
│ │ │ ├── elasticsearch_schema/ # Elasticsearch
│ │ │ ├── migration/ # (deprecated) Online schema adapters for MySQL
│ │ │ ├── mysql_queries/ # Sqlx MySQL queries for our backend monolith `storyteller-web`, jobs, etc.
│ │ │ ├── redis_common/ # Redis support
│ │ │ ├── redis_schema/ # Redis key and HKEY topology
│ │ │ ├── sqlite_queries/ # (deprecated) Sqlite queries
│ │ │ └── sqlite_tasks/ # Queries for the ArtCraft desktop app's "tasks" database.
│ │ ├── public/ # Token identifier and enum variant definitions
│ │ │ ├── composite_identifier/ # MySQL composite key system
│ │ │ ├── enums/ # MySQL "enums" stored in VARCHAR fields.
│ │ │ └── tokens/ # Primary database identifiers with Stripe-like ID prefixes, eg. "user_{entropy}"
│ │ └── service/ # Backend HTTP services and jobs
│ │ ├── job/ # Backend jobs.
│ │ │ └── video_thumbnail_job/ # Render video thumbnails
│ │ ├── plugins/ # Collections of reusable Actix-Web HTTP functions (user and billing systems)
│ │ └── web/ # HTTP web servers
│ │ └── storyteller_web/ # (Important) Our main HTTP API monolith and backend.
│ └── frontend/ # Nx typescript monorepo for our websites and Tauri desktop apps
│ ├── apps/ # Websites and Tauri desktop apps
│ │ ├── artcraft/ # ArtCraft the Tauri app's frontend. Used in conjunction with `artcraft` the Rust crate.
│ │ └── artcraft-website/ # The website for https://getartcraft.com
│ └── libs/ # Support libraries, reusable React components, etc.
└── Cargo.toml # Rust monorepo workspace
```
## Code Style
- Rust with no minimum supported version
- Actix-web for HTTP services
- SQLx for MySQL and SQLite. MySQL queries belong in the `mysql_queries` crate, not in application/service crates like `storyteller-web` — call those query functions instead of embedding `sqlx::query!` / `sqlx::query()` in handlers. (Query-writing conventions live in `crates/schema/database/mysql_queries/CLAUDE.md`.)
- A mix of wreq and reqwest for Rust HTTP clients
- Never use `println!` or `eprintln!` outside of tests; use `log` crate macros instead
- When two crates export the same type name, alias imports with a suffix: `use foo::Bar as BarFoo;`
- Prefer `use` imports over inline fully-qualified paths; only qualify inline for true one-offs or std collisions
- TypeScript with Nx, React, Vite, Zustand, and Three.js
- Use two spaces for indentation
### File Layout
Organize for top-to-bottom reading. Important things first, details later.
- **Constants** at the top (after imports)
- **Structs/enums** next; outer structs above inner sub-structs
- **API types** in order: Request, Response, Error
- **In impl blocks**: constructors first, then public methods, then private helpers
- Private helpers go *below* the methods that call them
- Among helpers: meatier logic above leaf-level formatters
- **In test modules**: constants first, then test cases (grouped into sub-modules when 2+), then helper functions last
## Markdown
- **Tables must be space-padded so columns align in plain text.** Markdown
tables are read raw (terminals, diffs, editors) at least as often as
rendered, and condensed tables are unreadable there. Pad every cell to its
column width:
```markdown
| Model | Configuration | Credits | Speed | Score |
|--------------|---------------|--------------------|---------|
| Meshy 6 | text or image | 104 | 80.0 | +24 |
| Rodin 2.5 | text or image | 13 | 10.0 | +3 |
```
Not: `| Model | Configuration | Credits | Speed | Score |` packed tight
with varying widths per row.
@@ -1,5 +0,0 @@
-- noinspection SqlDialectInspectionForFile
-- noinspection SqlNoDataSourceInspectionForFile
-- noinspection SqlResolveForFile
DROP TABLE IF EXISTS mcp_sessions;
@@ -1,65 +0,0 @@
-- noinspection SqlDialectInspectionForFile
-- noinspection SqlNoDataSourceInspectionForFile
-- noinspection SqlResolveForFile
-- Sessions for MCP and other non-human users.
-- These work like `user_sessions`, but are created and consumed by MCP clients.
CREATE TABLE mcp_sessions (
id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
-- Non-private "primary key" for the session.
-- Used as a key to delete/manage sessions in the dashboard.
token VARCHAR(32) NOT NULL,
-- Private entropy presented by clients; used for lookup of live sessions.
private_session_token VARCHAR(64) NOT NULL,
-- Private refresh credential. Presenting this on the refresh endpoint extends the
-- session's expiry and ROTATES this value — the previous refresh token becomes invalid.
private_refresh_token VARCHAR(64) NOT NULL,
-- The user that the session belongs to.
user_token VARCHAR(32) NOT NULL,
-- ========== CLIENT INFO ==========
-- Trimmed name of the MCP client, if any.
maybe_mcp_client_name VARCHAR(255) DEFAULT NULL,
-- Trimmed version of the MCP client, if any.
maybe_mcp_client_version VARCHAR(255) DEFAULT NULL,
-- Trimmed vendor of the MCP client, if any.
maybe_mcp_client_vendor VARCHAR(255) DEFAULT NULL,
-- ========== IP ADDRESSES ==========
-- IP address that created the session. Wide enough for IPv4/IPv6.
ip_address_creation VARCHAR(40) NOT NULL,
-- IP address that last updated the session. Wide enough for IPv4/IPv6.
ip_address_update VARCHAR(40) NOT NULL,
-- ========== TIMESTAMPS ==========
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
-- When the session expires, if not refreshed.
-- This must be set by the server code, or the session is invalid.
expires_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
-- Soft-delete timestamp. NULL means the session is live.
-- deletion = session termination
maybe_deleted_at TIMESTAMP NULL,
-- INDICES --
PRIMARY KEY (id),
UNIQUE KEY (token),
UNIQUE KEY (private_session_token),
UNIQUE KEY (private_refresh_token),
KEY fk_user_token (user_token),
KEY index_ip_address_creation (ip_address_creation),
KEY index_maybe_deleted_at (maybe_deleted_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
-38
View File
@@ -1,38 +0,0 @@
# SQL Migrations
Incremental schema changes applied in order by timestamp prefix.
## Naming Convention
Migration directories follow the format:
```
YYYY-MM-DD-HHMMSS-NNNN_description_goes_here/
up.sql
down.sql
```
These are created with the `diesel` tool, and in particular:
> `diesel migration generate description_goes_here`
- `NNNN` is a zero-padded sequence number for ordering multiple migrations on the same timestamp.
- `up.sql` applies the migration forward.
- `down.sql` reverses it.
## Table Conventions
- Primary key `id` columns must be `BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT`. Do not use signed IDs.
- Always create tables with `ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin`.
- All SQL files should start with the standard IntelliJ noinspection comments:
```sql
-- noinspection SqlDialectInspectionForFile
-- noinspection SqlNoDataSourceInspectionForFile
-- noinspection SqlResolveForFile
```
## Rules
- Every `up.sql` must have a corresponding `down.sql` that cleanly reverses the migration.
- For `CREATE TABLE` migrations, the `down.sql` is typically `DROP TABLE IF EXISTS table_name;`.
- For `ALTER TABLE` migrations, the `down.sql` reverses the alteration (e.g. `DROP COLUMN`).
-1
View File
@@ -1 +0,0 @@
AGENTS.md
+38
View File
@@ -0,0 +1,38 @@
# SQL Migrations
Incremental schema changes applied in order by timestamp prefix.
## Naming Convention
Migration directories follow the format:
```
YYYY-MM-DD-HHMMSS-NNNN_description_goes_here/
up.sql
down.sql
```
These are created with the `diesel` tool, and in particular:
> `diesel migration generate description_goes_here`
- `NNNN` is a zero-padded sequence number for ordering multiple migrations on the same timestamp.
- `up.sql` applies the migration forward.
- `down.sql` reverses it.
## Table Conventions
- Primary key `id` columns must be `BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT`. Do not use signed IDs.
- Always create tables with `ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin`.
- All SQL files should start with the standard IntelliJ noinspection comments:
```sql
-- noinspection SqlDialectInspectionForFile
-- noinspection SqlNoDataSourceInspectionForFile
-- noinspection SqlResolveForFile
```
## Rules
- Every `up.sql` must have a corresponding `down.sql` that cleanly reverses the migration.
- For `CREATE TABLE` migrations, the `down.sql` is typically `DROP TABLE IF EXISTS table_name;`.
- For `ALTER TABLE` migrations, the `down.sql` reverses the alteration (e.g. `DROP COLUMN`).
@@ -1,26 +0,0 @@
# Squashed / Materialized Schemas
Fully materialized table definitions representing the current state of each table
after all migrations have been applied. These are not executed — they exist as
human-readable documentation of the current schema.
## When to Update
Update the corresponding squashed file whenever a migration changes a table's schema
(adding columns, changing types, dropping and recreating, etc.).
## Table Conventions
- Primary key `id` columns must be `BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT`. Do not use signed IDs.
- Always create tables with `ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin`.
- All SQL files should start with the standard IntelliJ noinspection comments:
```sql
-- noinspection SqlDialectInspectionForFile
-- noinspection SqlNoDataSourceInspectionForFile
-- noinspection SqlResolveForFile
```
## File Organization
Files are named after their table (e.g. `users.sql`, `media_files.sql`).
Some tables are grouped into subdirectories (e.g. `user_tables/`).
@@ -1 +0,0 @@
AGENTS.md
@@ -0,0 +1,26 @@
# Squashed / Materialized Schemas
Fully materialized table definitions representing the current state of each table
after all migrations have been applied. These are not executed — they exist as
human-readable documentation of the current schema.
## When to Update
Update the corresponding squashed file whenever a migration changes a table's schema
(adding columns, changing types, dropping and recreating, etc.).
## Table Conventions
- Primary key `id` columns must be `BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT`. Do not use signed IDs.
- Always create tables with `ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin`.
- All SQL files should start with the standard IntelliJ noinspection comments:
```sql
-- noinspection SqlDialectInspectionForFile
-- noinspection SqlNoDataSourceInspectionForFile
-- noinspection SqlResolveForFile
```
## File Organization
Files are named after their table (e.g. `users.sql`, `media_files.sql`).
Some tables are grouped into subdirectories (e.g. `user_tables/`).
@@ -1,65 +0,0 @@
-- noinspection SqlDialectInspectionForFile
-- noinspection SqlNoDataSourceInspectionForFile
-- noinspection SqlResolveForFile
-- Sessions for MCP and other non-human users.
-- These work like `user_sessions`, but are created and consumed by MCP clients.
CREATE TABLE mcp_sessions (
id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
-- Non-private "primary key" for the session.
-- Used as a key to delete/manage sessions in the dashboard.
token VARCHAR(32) NOT NULL,
-- Private entropy presented by clients; used for lookup of live sessions.
private_session_token VARCHAR(64) NOT NULL,
-- Private refresh credential. Presenting this on the refresh endpoint extends the
-- session's expiry and ROTATES this value — the previous refresh token becomes invalid.
private_refresh_token VARCHAR(64) NOT NULL,
-- The user that the session belongs to.
user_token VARCHAR(32) NOT NULL,
-- ========== CLIENT INFO ==========
-- Trimmed name of the MCP client, if any.
maybe_mcp_client_name VARCHAR(255) DEFAULT NULL,
-- Trimmed version of the MCP client, if any.
maybe_mcp_client_version VARCHAR(255) DEFAULT NULL,
-- Trimmed vendor of the MCP client, if any.
maybe_mcp_client_vendor VARCHAR(255) DEFAULT NULL,
-- ========== IP ADDRESSES ==========
-- IP address that created the session. Wide enough for IPv4/IPv6.
ip_address_creation VARCHAR(40) NOT NULL,
-- IP address that last updated the session. Wide enough for IPv4/IPv6.
ip_address_update VARCHAR(40) NOT NULL,
-- ========== TIMESTAMPS ==========
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
-- When the session expires, if not refreshed.
-- This must be set by the server code, or the session is invalid.
expires_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
-- Soft-delete timestamp. NULL means the session is live.
-- deletion = session termination
maybe_deleted_at TIMESTAMP NULL,
-- INDICES --
PRIMARY KEY (id),
UNIQUE KEY (token),
UNIQUE KEY (private_session_token),
UNIQUE KEY (private_refresh_token),
KEY fk_user_token (user_token),
KEY index_ip_address_creation (ip_address_creation),
KEY index_maybe_deleted_at (maybe_deleted_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
-59
View File
@@ -1,59 +0,0 @@
# Rust Workspace
All Rust code lives under `crates/`. The workspace is defined in `Cargo.toml` at the repo root.
## Code Style
- Two spaces for indentation (not four)
- No minimum supported Rust version; use latest stable features freely
- Never use `println!` or `eprintln!` outside of tests; use `log` crate macros instead
- Use `anyhow::Result` / `AnyhowResult` for fallible functions in application code
- Fields that are optional use the `maybe_` prefix: `maybe_creator_user_token`
- When two crates export the same type name, alias with a suffix: `use foo::Bar as BarFoo;`
- Prefer `use` imports over inline fully-qualified paths; only qualify inline for true one-offs or std prelude collisions (`Result`, `Option`, `Error`)
## File Layout
Organize for top-to-bottom reading. Important things first, details later.
1. **Constants** at the top (after imports)
2. **Primary public type** (the main struct/enum the file defines)
3. **Supporting types** below the primary type
4. **API types** in order: Request, Response, Error
5. **`impl` blocks** after their type definitions
- Constructors first, then public methods, then private helpers
- Callers above callees — follow the call chain downward
## Test Layout
Within `#[cfg(test)] mod tests { ... }`:
1. **Imports**
2. **Constants** (test IDs, URLs, fixture data) — small context that tests reference
3. **Test functions or sub-modules** grouped by category
4. **Helper functions** (builders, pipeline runners, assertions)
Constants provide small context up front. Test cases come next so engineers see *what* is
tested before *how* the helpers work.
Group related tests into sub-modules (`mod pricing_tests { ... }`) when a category has 2+
tests. Don't wrap a single test in its own module. Keep nesting to two levels max. Shared
helpers go in the parent `mod tests` so sub-modules can `use super::*`.
## Building
- Most crates: `cargo check -p {crate_name}` or `cargo test -p {crate_name}`
- Crates using SQLx: `SQLX_OFFLINE=true cargo check -p {crate_name}`
- `storyteller-web` and `mysql_queries` require `SQLX_OFFLINE=true`
- `storyteller-web` has ~370 pre-existing warnings — check the last few lines for actual errors
## Key Crates
- `storyteller_web` — main HTTP API monolith (actix-web)
- `artcraft` (desktop) — Tauri desktop app
- `artcraft_router` — provider routing for image/video generation (Artcraft, Fal, KinoviWeb, Muapi)
- `artcraft_api_defs` — shared HTTP API type definitions
- `kinovi_web_client` — HTTP client for the Kinovi/KinoviWeb video generation service
- `enums` — database-backed enums stored as VARCHAR fields
- `tokens` — primary key identifiers with Stripe-like prefixes (e.g. `user_`, `mf_`)
- `mysql_queries` — SQLx MySQL queries for the backend
-1
View File
@@ -1 +0,0 @@
AGENTS.md
+59
View File
@@ -0,0 +1,59 @@
# Rust Workspace
All Rust code lives under `crates/`. The workspace is defined in `Cargo.toml` at the repo root.
## Code Style
- Two spaces for indentation (not four)
- No minimum supported Rust version; use latest stable features freely
- Never use `println!` or `eprintln!` outside of tests; use `log` crate macros instead
- Use `anyhow::Result` / `AnyhowResult` for fallible functions in application code
- Fields that are optional use the `maybe_` prefix: `maybe_creator_user_token`
- When two crates export the same type name, alias with a suffix: `use foo::Bar as BarFoo;`
- Prefer `use` imports over inline fully-qualified paths; only qualify inline for true one-offs or std prelude collisions (`Result`, `Option`, `Error`)
## File Layout
Organize for top-to-bottom reading. Important things first, details later.
1. **Constants** at the top (after imports)
2. **Primary public type** (the main struct/enum the file defines)
3. **Supporting types** below the primary type
4. **API types** in order: Request, Response, Error
5. **`impl` blocks** after their type definitions
- Constructors first, then public methods, then private helpers
- Callers above callees — follow the call chain downward
## Test Layout
Within `#[cfg(test)] mod tests { ... }`:
1. **Imports**
2. **Constants** (test IDs, URLs, fixture data) — small context that tests reference
3. **Test functions or sub-modules** grouped by category
4. **Helper functions** (builders, pipeline runners, assertions)
Constants provide small context up front. Test cases come next so engineers see *what* is
tested before *how* the helpers work.
Group related tests into sub-modules (`mod pricing_tests { ... }`) when a category has 2+
tests. Don't wrap a single test in its own module. Keep nesting to two levels max. Shared
helpers go in the parent `mod tests` so sub-modules can `use super::*`.
## Building
- Most crates: `cargo check -p {crate_name}` or `cargo test -p {crate_name}`
- Crates using SQLx: `SQLX_OFFLINE=true cargo check -p {crate_name}`
- `storyteller-web` and `mysql_queries` require `SQLX_OFFLINE=true`
- `storyteller-web` has ~370 pre-existing warnings — check the last few lines for actual errors
## Key Crates
- `storyteller_web` — main HTTP API monolith (actix-web)
- `artcraft` (desktop) — Tauri desktop app
- `artcraft_router` — provider routing for image/video generation (Artcraft, Fal, KinoviWeb, Muapi)
- `artcraft_api_defs` — shared HTTP API type definitions
- `kinovi_web_client` — HTTP client for the Kinovi/KinoviWeb video generation service
- `enums` — database-backed enums stored as VARCHAR fields
- `tokens` — primary key identifiers with Stripe-like prefixes (e.g. `user_`, `mf_`)
- `mysql_queries` — SQLx MySQL queries for the backend
@@ -1,22 +0,0 @@
# artcraft_api_defs
Shared HTTP API type definitions used by both the server (`storyteller_web`) and clients.
## Structure
Organized by feature: `users/`, `media_file/`, `jobs/`, `moderation/`, etc.
## Conventions
- Request types: `#[derive(Deserialize, ToSchema)]`
- Response types: `#[derive(Serialize, ToSchema)]`
- Path params: `#[derive(Deserialize, ToSchema)]` with `PathInfo` suffix
- Query params: `#[derive(Deserialize, IntoParams)]`
## Orphan Rule
Types that need `ResponseError` impl (actix-web) CANNOT live here because of Rust's orphan rule. Keep error response types in `storyteller_web` and only put data types here.
## Dependencies
Only `serde`, `serde_derive`, `utoipa`, `chrono`, `url`, and internal schema crates (`enums`, `tokens`). No actix-web dependency.
@@ -1 +0,0 @@
AGENTS.md
@@ -0,0 +1,22 @@
# artcraft_api_defs
Shared HTTP API type definitions used by both the server (`storyteller_web`) and clients.
## Structure
Organized by feature: `users/`, `media_file/`, `jobs/`, `moderation/`, etc.
## Conventions
- Request types: `#[derive(Deserialize, ToSchema)]`
- Response types: `#[derive(Serialize, ToSchema)]`
- Path params: `#[derive(Deserialize, ToSchema)]` with `PathInfo` suffix
- Query params: `#[derive(Deserialize, IntoParams)]`
## Orphan Rule
Types that need `ResponseError` impl (actix-web) CANNOT live here because of Rust's orphan rule. Keep error response types in `storyteller_web` and only put data types here.
## Dependencies
Only `serde`, `serde_derive`, `utoipa`, `chrono`, `url`, and internal schema crates (`enums`, `tokens`). No actix-web dependency.
@@ -7,7 +7,6 @@ pub mod folders;
pub mod generate;
pub mod internal;
pub mod jobs;
pub mod mcp_sessions;
pub mod media_file;
pub mod moderation;
pub mod omni_api;
@@ -1,42 +0,0 @@
use chrono::{DateTime, Utc};
use serde_derive::{Deserialize, Serialize};
use utoipa::ToSchema;
use tokens::tokens::mcp_sessions::McpSessionToken;
/// Canonical wire shape for an MCP session, used by the dashboard list.
///
/// NB: the secret `private_session_token` is NEVER included here — it is returned exactly once,
/// at creation time. The `token` is the non-private management handle.
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
pub struct McpSessionInfo {
pub token: McpSessionToken,
/// Trimmed name of the MCP client that created the session, if any.
pub maybe_mcp_client_name: Option<String>,
/// Trimmed version of the MCP client, if any.
pub maybe_mcp_client_version: Option<String>,
/// Trimmed vendor of the MCP client, if any.
pub maybe_mcp_client_vendor: Option<String>,
pub ip_address_creation: String,
pub ip_address_update: String,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
/// When the session expires, if not refreshed.
pub expires_at: DateTime<Utc>,
/// Termination timestamp. `None` for live (though possibly expired) sessions.
pub maybe_deleted_at: Option<DateTime<Utc>>,
}
/// Path info for endpoints addressed by the session's management `token` (NOT the secret
/// `private_session_token`): `POST /v1/mcp/session/{token}/delete`.
#[derive(Deserialize, ToSchema)]
pub struct McpSessionPathInfo {
pub token: McpSessionToken,
}
@@ -1,34 +0,0 @@
use serde_derive::{Deserialize, Serialize};
use utoipa::ToSchema;
use tokens::tokens::mcp_session_private::McpSessionPrivateToken;
use tokens::tokens::mcp_session_refresh::McpSessionRefreshToken;
// ── POST /v1/mcp/session/create ──
#[derive(Deserialize, ToSchema)]
pub struct CreateMcpSessionRequest {
/// Name of the MCP client creating the session, if any.
pub maybe_mcp_client_name: Option<String>,
/// Version of the MCP client, if any.
pub maybe_mcp_client_version: Option<String>,
/// Vendor of the MCP client, if any.
pub maybe_mcp_client_vendor: Option<String>,
}
#[derive(Serialize, ToSchema)]
pub struct CreateMcpSessionSuccessResponse {
pub success: bool,
/// The secret credential the MCP client presents in the `Authorization` header. This is the
/// ONLY time it is ever returned — the caller must store it now, as it cannot be retrieved
/// again.
pub private_session_token: McpSessionPrivateToken,
/// The secret credential the MCP client presents on `/v1/mcp/session/refresh` to extend the
/// session. Each successful refresh returns a NEW refresh token and invalidates this one —
/// store whichever value is newest.
pub private_refresh_token: McpSessionRefreshToken,
}
@@ -1,9 +0,0 @@
use serde_derive::Serialize;
use utoipa::ToSchema;
// ── POST /v1/mcp/session/{token}/delete ──
#[derive(Serialize, ToSchema)]
pub struct DeleteMcpSessionSuccessResponse {
pub success: bool,
}
@@ -1,24 +0,0 @@
use serde_derive::{Deserialize, Serialize};
use utoipa::{IntoParams, ToSchema};
use crate::mcp_sessions::common::McpSessionInfo;
// ── GET /v1/mcp/session/list ──
#[derive(Deserialize, ToSchema, IntoParams)]
pub struct ListMcpSessionsQueryParams {
/// Page size. Defaults server-side if omitted.
pub limit: Option<u32>,
/// Number of rows to skip. Defaults to 0.
pub offset: Option<u32>,
}
#[derive(Serialize, ToSchema)]
pub struct ListMcpSessionsSuccessResponse {
pub success: bool,
/// The user's MCP sessions (including terminated ones), newest first. The secret
/// `private_session_token` is never listed.
pub mcp_sessions: Vec<McpSessionInfo>,
}
@@ -1,6 +0,0 @@
pub mod common;
pub mod create_mcp_session;
pub mod delete_mcp_session;
pub mod list_mcp_sessions;
pub mod refresh_mcp_session;
pub mod revoke_mcp_session;
@@ -1,22 +0,0 @@
use serde_derive::{Deserialize, Serialize};
use utoipa::ToSchema;
use tokens::tokens::mcp_session_refresh::McpSessionRefreshToken;
// ── POST /v1/mcp/session/refresh ──
#[derive(Deserialize, ToSchema)]
pub struct RefreshMcpSessionRequest {
/// The session's CURRENT refresh token (from creation, or from the most recent refresh).
/// A stale or wrong value is an error — refresh tokens rotate and are never replayable.
pub private_refresh_token: McpSessionRefreshToken,
}
#[derive(Serialize, ToSchema)]
pub struct RefreshMcpSessionSuccessResponse {
pub success: bool,
/// The NEW refresh token to present on the next refresh. The one just used is now invalid —
/// the caller must store this replacement.
pub private_refresh_token: McpSessionRefreshToken,
}
@@ -1,9 +0,0 @@
use serde_derive::Serialize;
use utoipa::ToSchema;
// ── POST /v1/mcp/session/revoke ──
#[derive(Serialize, ToSchema)]
pub struct RevokeMcpSessionSuccessResponse {
pub success: bool,
}
@@ -14,14 +14,6 @@ pub enum ApiClientGenerationProvider {
Midjourney,
Sora,
WorldLabs,
Higgsfield,
Krea,
Leonardo,
Magnific,
Openart,
Picsart,
Pixverse,
Runway,
/// A value not known to this client build (preserved as-is).
Unknown(String),
}
@@ -35,14 +27,6 @@ impl From<String> for ApiClientGenerationProvider {
"midjourney" => Self::Midjourney,
"sora" => Self::Sora,
"world_labs" => Self::WorldLabs,
"higgsfield" => Self::Higgsfield,
"krea" => Self::Krea,
"leonardo" => Self::Leonardo,
"magnific" => Self::Magnific,
"openart" => Self::Openart,
"picsart" => Self::Picsart,
"pixverse" => Self::Pixverse,
"runway" => Self::Runway,
_ => Self::Unknown(value),
}
}
@@ -57,14 +41,6 @@ impl From<ApiClientGenerationProvider> for String {
ApiClientGenerationProvider::Midjourney => "midjourney".to_string(),
ApiClientGenerationProvider::Sora => "sora".to_string(),
ApiClientGenerationProvider::WorldLabs => "world_labs".to_string(),
ApiClientGenerationProvider::Higgsfield => "higgsfield".to_string(),
ApiClientGenerationProvider::Krea => "krea".to_string(),
ApiClientGenerationProvider::Leonardo => "leonardo".to_string(),
ApiClientGenerationProvider::Magnific => "magnific".to_string(),
ApiClientGenerationProvider::Openart => "openart".to_string(),
ApiClientGenerationProvider::Picsart => "picsart".to_string(),
ApiClientGenerationProvider::Pixverse => "pixverse".to_string(),
ApiClientGenerationProvider::Runway => "runway".to_string(),
ApiClientGenerationProvider::Unknown(other) => other,
}
}
@@ -97,14 +73,6 @@ mod tests {
(ApiClientGenerationProvider::Midjourney, "midjourney"),
(ApiClientGenerationProvider::Sora, "sora"),
(ApiClientGenerationProvider::WorldLabs, "world_labs"),
(ApiClientGenerationProvider::Higgsfield, "higgsfield"),
(ApiClientGenerationProvider::Krea, "krea"),
(ApiClientGenerationProvider::Leonardo, "leonardo"),
(ApiClientGenerationProvider::Magnific, "magnific"),
(ApiClientGenerationProvider::Openart, "openart"),
(ApiClientGenerationProvider::Picsart, "picsart"),
(ApiClientGenerationProvider::Pixverse, "pixverse"),
(ApiClientGenerationProvider::Runway, "runway"),
];
for (variant, s) in all {
assert_eq!(String::from(variant.clone()), s, "serialize mismatch for {:?}", variant);
@@ -16,8 +16,6 @@ pub enum ApiClientImageModel {
GptImage1p5,
GptImage2,
GrokImagineImage,
GptImage2p5Flare,
GptImage2p5Sunburst,
GrokImagineImageQuality,
Midjourney7,
Midjourney7Niji,
@@ -44,8 +42,6 @@ impl From<String> for ApiClientImageModel {
"gpt_image_1" => Self::GptImage1,
"gpt_image_1p5" => Self::GptImage1p5,
"gpt_image_2" => Self::GptImage2,
"gpt_image_2p5_flare" => Self::GptImage2p5Flare,
"gpt_image_2p5_sunburst" => Self::GptImage2p5Sunburst,
"grok_imagine_image" => Self::GrokImagineImage,
"grok_imagine_image_q" => Self::GrokImagineImageQuality,
"midjourney_7" => Self::Midjourney7,
@@ -74,8 +70,6 @@ impl From<ApiClientImageModel> for String {
ApiClientImageModel::GptImage1 => "gpt_image_1".to_string(),
ApiClientImageModel::GptImage1p5 => "gpt_image_1p5".to_string(),
ApiClientImageModel::GptImage2 => "gpt_image_2".to_string(),
ApiClientImageModel::GptImage2p5Flare => "gpt_image_2p5_flare".to_string(),
ApiClientImageModel::GptImage2p5Sunburst => "gpt_image_2p5_sunburst".to_string(),
ApiClientImageModel::GrokImagineImage => "grok_imagine_image".to_string(),
ApiClientImageModel::GrokImagineImageQuality => "grok_imagine_image_q".to_string(),
ApiClientImageModel::Midjourney7 => "midjourney_7".to_string(),
@@ -122,8 +116,6 @@ mod tests {
(ApiClientImageModel::GptImage1, "gpt_image_1"),
(ApiClientImageModel::GptImage1p5, "gpt_image_1p5"),
(ApiClientImageModel::GptImage2, "gpt_image_2"),
(ApiClientImageModel::GptImage2p5Flare, "gpt_image_2p5_flare"),
(ApiClientImageModel::GptImage2p5Sunburst, "gpt_image_2p5_sunburst"),
(ApiClientImageModel::GrokImagineImage, "grok_imagine_image"),
(ApiClientImageModel::GrokImagineImageQuality, "grok_imagine_image_q"),
(ApiClientImageModel::Midjourney7, "midjourney_7"),
@@ -19,10 +19,6 @@ pub enum RouterImageModel {
GptImage1p5,
#[serde(rename = "gpt_image_2")]
GptImage2,
#[serde(rename = "gpt_image_2p5_flare")]
GptImage2p5Flare,
#[serde(rename = "gpt_image_2p5_sunburst")]
GptImage2p5Sunburst,
#[serde(rename = "grok_imagine_image")]
GrokImagineImage,
#[serde(rename = "grok_imagine_image_q")]
@@ -91,14 +87,4 @@ mod tests {
fn seedream_5p0_pro_ultra_serializes_to_seedream_5p0_pro_u() {
assert_round_trip(RouterImageModel::Seedream5p0ProUltra, "seedream_5p0_pro_u");
}
#[test]
fn gpt_image_2p5_flare_serializes_to_gpt_image_2p5_flare() {
assert_round_trip(RouterImageModel::GptImage2p5Flare, "gpt_image_2p5_flare");
}
#[test]
fn gpt_image_2p5_sunburst_serializes_to_gpt_image_2p5_sunburst() {
assert_round_trip(RouterImageModel::GptImage2p5Sunburst, "gpt_image_2p5_sunburst");
}
}
@@ -16,8 +16,6 @@ use crate::generate::generate_image::providers::artcraft::flux_pro_1p1_ultra::bu
use crate::generate::generate_image::providers::artcraft::gpt_image_1::build::build_artcraft_gpt_image_1;
use crate::generate::generate_image::providers::artcraft::gpt_image_1p5::build::build_artcraft_gpt_image_1p5;
use crate::generate::generate_image::providers::artcraft::gpt_image_2::build::build_artcraft_gpt_image_2;
use crate::generate::generate_image::providers::artcraft::gpt_image_2p5_flare::build::build_artcraft_gpt_image_2p5_flare;
use crate::generate::generate_image::providers::artcraft::gpt_image_2p5_sunburst::build::build_artcraft_gpt_image_2p5_sunburst;
use crate::generate::generate_image::providers::artcraft::midjourney_7::build::build_artcraft_midjourney_7;
use crate::generate::generate_image::providers::artcraft::midjourney_7_niji::build::build_artcraft_midjourney_7_niji;
use crate::generate::generate_image::providers::artcraft::midjourney_8::build::build_artcraft_midjourney_8;
@@ -38,8 +36,6 @@ use crate::generate::generate_image::providers::fal::flux_pro_1p1_ultra::build::
use crate::generate::generate_image::providers::fal::gpt_image_1::build::build_fal_gpt_image_1;
use crate::generate::generate_image::providers::fal::gpt_image_1p5::build::build_fal_gpt_image_1p5;
use crate::generate::generate_image::providers::fal::gpt_image_2::build::build_fal_gpt_image_2;
use crate::generate::generate_image::providers::fal::gpt_image_2p5_flare::build::build_fal_gpt_image_2p5_flare;
use crate::generate::generate_image::providers::fal::gpt_image_2p5_sunburst::build::build_fal_gpt_image_2p5_sunburst;
use crate::generate::generate_image::providers::fal::nano_banana::build::build_fal_nano_banana;
use crate::generate::generate_image::providers::fal::nano_banana_2::build::build_fal_nano_banana_2;
use crate::generate::generate_image::providers::fal::nano_banana_pro::build::build_fal_nano_banana_pro;
@@ -120,8 +116,6 @@ impl GenerateImageRequestBuilder {
(RouterProvider::Artcraft, RouterImageModel::GptImage1) => build_artcraft_gpt_image_1(self),
(RouterProvider::Artcraft, RouterImageModel::GptImage1p5) => build_artcraft_gpt_image_1p5(self),
(RouterProvider::Artcraft, RouterImageModel::GptImage2) => build_artcraft_gpt_image_2(self),
(RouterProvider::Artcraft, RouterImageModel::GptImage2p5Flare) => build_artcraft_gpt_image_2p5_flare(self),
(RouterProvider::Artcraft, RouterImageModel::GptImage2p5Sunburst) => build_artcraft_gpt_image_2p5_sunburst(self),
(RouterProvider::Artcraft, RouterImageModel::NanoBanana) => build_artcraft_nano_banana(self),
(RouterProvider::Artcraft, RouterImageModel::NanoBanana2) => build_artcraft_nano_banana_2(self),
(RouterProvider::Artcraft, RouterImageModel::NanoBananaPro) => build_artcraft_nano_banana_pro(self),
@@ -143,8 +137,6 @@ impl GenerateImageRequestBuilder {
(RouterProvider::Fal, RouterImageModel::GptImage1) => build_fal_gpt_image_1(self),
(RouterProvider::Fal, RouterImageModel::GptImage1p5) => build_fal_gpt_image_1p5(self),
(RouterProvider::Fal, RouterImageModel::GptImage2) => build_fal_gpt_image_2(self),
(RouterProvider::Fal, RouterImageModel::GptImage2p5Flare) => build_fal_gpt_image_2p5_flare(self),
(RouterProvider::Fal, RouterImageModel::GptImage2p5Sunburst) => build_fal_gpt_image_2p5_sunburst(self),
(RouterProvider::Fal, RouterImageModel::NanoBanana) => build_fal_nano_banana(self),
(RouterProvider::Fal, RouterImageModel::NanoBanana2) => build_fal_nano_banana_2(self),
(RouterProvider::Fal, RouterImageModel::NanoBananaPro) => build_fal_nano_banana_pro(self),
@@ -19,10 +19,6 @@ use crate::generate::generate_image::providers::artcraft::gpt_image_1p5::cost::A
use crate::generate::generate_image::providers::artcraft::gpt_image_1p5::request::ArtcraftGptImage1p5RequestState;
use crate::generate::generate_image::providers::artcraft::gpt_image_2::cost::ArtcraftGptImage2CostState;
use crate::generate::generate_image::providers::artcraft::gpt_image_2::request::ArtcraftGptImage2RequestState;
use crate::generate::generate_image::providers::artcraft::gpt_image_2p5_flare::cost::ArtcraftGptImage2p5FlareCostState;
use crate::generate::generate_image::providers::artcraft::gpt_image_2p5_flare::request::ArtcraftGptImage2p5FlareRequestState;
use crate::generate::generate_image::providers::artcraft::gpt_image_2p5_sunburst::cost::ArtcraftGptImage2p5SunburstCostState;
use crate::generate::generate_image::providers::artcraft::gpt_image_2p5_sunburst::request::ArtcraftGptImage2p5SunburstRequestState;
use crate::generate::generate_image::providers::artcraft::midjourney_7::cost::ArtcraftMidjourney7CostState;
use crate::generate::generate_image::providers::artcraft::midjourney_7::request::ArtcraftMidjourney7RequestState;
use crate::generate::generate_image::providers::artcraft::midjourney_7_niji::cost::ArtcraftMidjourney7NijiCostState;
@@ -63,10 +59,6 @@ use crate::generate::generate_image::providers::fal::gpt_image_1p5::cost::FalGpt
use crate::generate::generate_image::providers::fal::gpt_image_1p5::request::FalGptImage1p5RequestState;
use crate::generate::generate_image::providers::fal::gpt_image_2::cost::FalGptImage2CostState;
use crate::generate::generate_image::providers::fal::gpt_image_2::request::FalGptImage2RequestState;
use crate::generate::generate_image::providers::fal::gpt_image_2p5_flare::cost::FalGptImage2p5FlareCostState;
use crate::generate::generate_image::providers::fal::gpt_image_2p5_flare::request::FalGptImage2p5FlareRequestState;
use crate::generate::generate_image::providers::fal::gpt_image_2p5_sunburst::cost::FalGptImage2p5SunburstCostState;
use crate::generate::generate_image::providers::fal::gpt_image_2p5_sunburst::request::FalGptImage2p5SunburstRequestState;
use crate::generate::generate_image::providers::fal::nano_banana::cost::FalNanoBananaCostState;
use crate::generate::generate_image::providers::fal::nano_banana::request::FalNanoBananaRequestState;
use crate::generate::generate_image::providers::fal::nano_banana_2::cost::FalNanoBanana2CostState;
@@ -100,8 +92,6 @@ pub enum ImageGenerationRequest {
ArtcraftGptImage1(ArtcraftGptImage1RequestState),
ArtcraftGptImage1p5(ArtcraftGptImage1p5RequestState),
ArtcraftGptImage2(ArtcraftGptImage2RequestState),
ArtcraftGptImage2p5Flare(ArtcraftGptImage2p5FlareRequestState),
ArtcraftGptImage2p5Sunburst(ArtcraftGptImage2p5SunburstRequestState),
ArtcraftNanoBanana(ArtcraftNanoBananaRequestState),
ArtcraftNanoBanana2(ArtcraftNanoBanana2RequestState),
ArtcraftNanoBananaPro(ArtcraftNanoBananaProRequestState),
@@ -124,8 +114,6 @@ pub enum ImageGenerationRequest {
FalGptImage1(FalGptImage1RequestState),
FalGptImage1p5(FalGptImage1p5RequestState),
FalGptImage2(FalGptImage2RequestState),
FalGptImage2p5Flare(FalGptImage2p5FlareRequestState),
FalGptImage2p5Sunburst(FalGptImage2p5SunburstRequestState),
FalNanoBanana(FalNanoBananaRequestState),
FalNanoBanana2(FalNanoBanana2RequestState),
FalNanoBananaPro(FalNanoBananaProRequestState),
@@ -152,8 +140,6 @@ impl ImageGenerationRequest {
Self::ArtcraftGptImage1(_) => RouterProvider::Artcraft,
Self::ArtcraftGptImage1p5(_) => RouterProvider::Artcraft,
Self::ArtcraftGptImage2(_) => RouterProvider::Artcraft,
Self::ArtcraftGptImage2p5Flare(_) => RouterProvider::Artcraft,
Self::ArtcraftGptImage2p5Sunburst(_) => RouterProvider::Artcraft,
Self::ArtcraftNanoBanana(_) => RouterProvider::Artcraft,
Self::ArtcraftNanoBanana2(_) => RouterProvider::Artcraft,
Self::ArtcraftNanoBananaPro(_) => RouterProvider::Artcraft,
@@ -175,8 +161,6 @@ impl ImageGenerationRequest {
Self::FalGptImage1(_) => RouterProvider::Fal,
Self::FalGptImage1p5(_) => RouterProvider::Fal,
Self::FalGptImage2(_) => RouterProvider::Fal,
Self::FalGptImage2p5Flare(_) => RouterProvider::Fal,
Self::FalGptImage2p5Sunburst(_) => RouterProvider::Fal,
Self::FalNanoBanana(_) => RouterProvider::Fal,
Self::FalNanoBanana2(_) => RouterProvider::Fal,
Self::FalNanoBananaPro(_) => RouterProvider::Fal,
@@ -217,12 +201,6 @@ impl ImageGenerationRequest {
Self::ArtcraftGptImage2(request) => {
Ok(ArtcraftGptImage2CostState::from_request(request).estimate_cost())
}
Self::ArtcraftGptImage2p5Flare(request) => {
Ok(ArtcraftGptImage2p5FlareCostState::from_request(request).estimate_cost())
}
Self::ArtcraftGptImage2p5Sunburst(request) => {
Ok(ArtcraftGptImage2p5SunburstCostState::from_request(request).estimate_cost())
}
Self::ArtcraftNanoBanana(request) => {
Ok(ArtcraftNanoBananaCostState::from_request(request).estimate_cost())
}
@@ -271,8 +249,6 @@ impl ImageGenerationRequest {
Self::FalGptImage1(request) => Ok(FalGptImage1CostState::from_request(request).estimate_cost()),
Self::FalGptImage1p5(request) => Ok(FalGptImage1p5CostState::from_request(request).estimate_cost()),
Self::FalGptImage2(request) => Ok(FalGptImage2CostState::from_request(request).estimate_cost()),
Self::FalGptImage2p5Flare(request) => Ok(FalGptImage2p5FlareCostState::from_request(request).estimate_cost()),
Self::FalGptImage2p5Sunburst(request) => Ok(FalGptImage2p5SunburstCostState::from_request(request).estimate_cost()),
Self::FalNanoBanana(request) => Ok(FalNanoBananaCostState::from_request(request).estimate_cost()),
Self::FalNanoBanana2(request) => Ok(FalNanoBanana2CostState::from_request(request).estimate_cost()),
Self::FalNanoBananaPro(request) => Ok(FalNanoBananaProCostState::from_request(request).estimate_cost()),
@@ -320,14 +296,6 @@ impl ImageGenerationRequest {
let artcraft_client = client.get_artcraft_client_ref()?;
request.send(artcraft_client).await
}
Self::ArtcraftGptImage2p5Flare(request) => {
let artcraft_client = client.get_artcraft_client_ref()?;
request.send(artcraft_client).await
}
Self::ArtcraftGptImage2p5Sunburst(request) => {
let artcraft_client = client.get_artcraft_client_ref()?;
request.send(artcraft_client).await
}
Self::ArtcraftNanoBanana(request) => {
let artcraft_client = client.get_artcraft_client_ref()?;
request.send(artcraft_client).await
@@ -411,14 +379,6 @@ impl ImageGenerationRequest {
let fal_client = client.get_fal_client_ref()?;
request.send(fal_client).await
}
Self::FalGptImage2p5Flare(request) => {
let fal_client = client.get_fal_client_ref()?;
request.send(fal_client).await
}
Self::FalGptImage2p5Sunburst(request) => {
let fal_client = client.get_fal_client_ref()?;
request.send(fal_client).await
}
Self::FalNanoBanana(request) => {
// nano_banana (Gemini 2.5 Flash) is webhook-required.
let fal_client = client.get_fal_client_ref()?;
@@ -22,15 +22,14 @@ use crate::generate::generate_image::generate_image_request_builder::GenerateIma
/// Per-model build functions are expected to validate model-specific
/// constraints (e.g. unsupported aspect ratios) BEFORE calling this helper.
/// Validation that's identical across every Artcraft image model — batch count
/// (1..=[`max_batch_count`]) and image_inputs shape — lives here.
/// (1..=4) and image_inputs shape — lives here.
pub fn build_artcraft_omni_image_request(
builder: GenerateImageRequestBuilder,
model: CommonImageModelEnum,
) -> Result<OmniGenImageCostAndGenerateRequest, ArtcraftRouterError> {
let strategy = builder.request_mismatch_mitigation_strategy;
let image_batch_count =
plan_batch_count_with_max(builder.image_batch_count, strategy, max_batch_count(model))?;
let image_batch_count = plan_batch_count(builder.image_batch_count, strategy)?;
let image_media_tokens = resolve_image_list_ref(builder.image_inputs.clone())?;
let aspect_ratio = builder.aspect_ratio.map(to_aspect_ratio_enum);
@@ -53,47 +52,26 @@ pub fn build_artcraft_omni_image_request(
})
}
/// The largest batch each Artcraft image model accepts. Seedream 5.0 Pro and
/// Ultra accept batches of up to 8; every other model caps at 4.
pub fn max_batch_count(model: CommonImageModelEnum) -> u16 {
match model {
CommonImageModelEnum::Seedream5p0Pro | CommonImageModelEnum::Seedream5p0ProUltra => 8,
_ => 4,
}
}
/// Validate batch count (1..=4). Mirrors the v1 plan-level validation that
/// every Artcraft image model performs.
pub fn plan_batch_count(
image_batch_count: Option<u16>,
strategy: RequestMismatchMitigationStrategy,
) -> Result<u16, ArtcraftRouterError> {
plan_batch_count_with_max(image_batch_count, strategy, 4)
}
/// Validate batch count (1..=`max`), clamping or erroring per the mitigation
/// strategy when the request exceeds the model's cap.
pub fn plan_batch_count_with_max(
image_batch_count: Option<u16>,
strategy: RequestMismatchMitigationStrategy,
max: u16,
) -> Result<u16, ArtcraftRouterError> {
let count = image_batch_count.unwrap_or(1);
if count == 0 {
return Err(ArtcraftRouterError::Client(ClientError::UserRequestedZeroGenerations));
}
if count <= max {
return Ok(count);
}
match strategy {
RequestMismatchMitigationStrategy::ErrorOut => {
Err(ArtcraftRouterError::Client(ClientError::ModelDoesNotSupportOption {
field: "image_batch_count",
value: format!("{}", count),
}))
}
RequestMismatchMitigationStrategy::PayMoreUpgrade
| RequestMismatchMitigationStrategy::PayLessDowngrade => Ok(max),
match count {
0 => Err(ArtcraftRouterError::Client(ClientError::UserRequestedZeroGenerations)),
1..=4 => Ok(count),
_ => match strategy {
RequestMismatchMitigationStrategy::ErrorOut => {
Err(ArtcraftRouterError::Client(ClientError::ModelDoesNotSupportOption {
field: "image_batch_count",
value: format!("{}", count),
}))
}
RequestMismatchMitigationStrategy::PayMoreUpgrade
| RequestMismatchMitigationStrategy::PayLessDowngrade => Ok(4),
},
}
}
@@ -1,290 +0,0 @@
use artcraft_api_defs::omni_gen::cost_and_generate_requests::omni_gen_image_cost_and_generate_request::OmniGenImageCostAndGenerateRequest;
use enums::common::generation::common_aspect_ratio::CommonAspectRatio as CommonAspectRatioEnum;
use enums::common::generation::common_quality::CommonQuality as CommonQualityEnum;
use enums::common::generation::common_resolution::CommonResolution as CommonResolutionEnum;
use fal_client::requests::api::image::common::gpt_image_2_resolution::GptImage2Resolution;
use fal_client::requests::api::image::common::gpt_image_2p5::gpt_image_2p5_image_size::GptImage2p5ImageSize;
use crate::generate::generate_image::image_generation_cost_estimate::ImageGenerationCostEstimate;
/// Artcraft price per output image, in hundredths of a US cent, by output dimensions and
/// quality (`[low, medium, high]`). Rows are stored landscape-first; portrait orientations of
/// the same dimensions price identically. Dimensions come from the aspect ratio preset and
/// resolution tier the same way the Fal request builder derives them.
const OUTPUT_IMAGE_PRICE_TABLE: &[(u32, u32, [u64; 3])] = &[
// 1:1
(1024, 1024, [ 65, 152, 582]),
(2048, 2048, [103, 239, 919]),
(2880, 2880, [151, 352, 1357]),
// 4:3
(1024, 768, [ 46, 105, 400]),
(2048, 1536, [ 73, 170, 652]),
(3072, 2304, [120, 279, 1073]),
(3312, 2480, [134, 311, 1194]),
// 16:9
(1088, 608, [ 32, 75, 285]),
(1920, 1080, [ 49, 114, 436]),
(2048, 1152, [ 53, 121, 467]),
(3072, 1728, [ 87, 204, 783]),
(3840, 2160, [124, 286, 1102]),
];
/// Artcraft price per reference image on an edit request, in hundredths of a US cent.
const REFERENCE_IMAGE_PRICE: u64 = 88;
/// The inputs that determine an Artcraft GPT Image 2.5 price. Shared by Flare and Sunburst,
/// which are priced identically.
#[derive(Clone, Debug)]
pub struct ArtcraftGptImage2p5CostInputs {
pub quality: Option<CommonQualityEnum>,
pub aspect_ratio: Option<CommonAspectRatioEnum>,
pub resolution: Option<CommonResolutionEnum>,
pub num_reference_images: usize,
pub num_images: u16,
}
impl ArtcraftGptImage2p5CostInputs {
pub fn from_omni_request(request: &OmniGenImageCostAndGenerateRequest) -> Self {
Self {
quality: request.quality,
aspect_ratio: request.aspect_ratio,
resolution: request.resolution,
num_reference_images: request.image_media_tokens.as_ref().map(|tokens| tokens.len()).unwrap_or(0),
num_images: request.image_batch_count.unwrap_or(1),
}
}
/// Per-image price rounded up to whole cents, times the batch size. Quality defaults to
/// high. Without an aspect ratio, text-to-image prices as landscape 4:3 and edit as auto,
/// matching the Fal defaults the request would fall back to.
pub fn estimate_cost(&self) -> ImageGenerationCostEstimate {
let quality = self.quality.unwrap_or(CommonQualityEnum::High);
let (width, height) = self.output_dimensions();
let hundredths_per_image = output_image_price(quality, width, height)
+ REFERENCE_IMAGE_PRICE * self.num_reference_images as u64;
let cost_in_usd_cents = hundredths_per_image.div_ceil(100) * self.num_images as u64;
ImageGenerationCostEstimate {
cost_in_credits: Some(cost_in_usd_cents),
cost_in_usd_cents: Some(cost_in_usd_cents),
is_free: false,
is_unlimited: false,
is_rate_limited: false,
has_watermark: false,
failures_are_refunded: None,
}
}
fn output_dimensions(&self) -> (u32, u32) {
let is_edit = self.num_reference_images > 0;
let default_size = if is_edit { GptImage2p5ImageSize::Auto } else { GptImage2p5ImageSize::Landscape4x3 };
let size = self.aspect_ratio.map(to_image_size).unwrap_or(default_size);
size.estimated_output_dimensions(self.resolution.map(to_resolution))
}
}
/// Look up the per-image price. Dimensions not in the table fall back to the largest row,
/// which is the most expensive.
fn output_image_price(quality: CommonQualityEnum, width: u32, height: u32) -> u64 {
let prices = lookup_price_row(width, height)
.unwrap_or_else(|| OUTPUT_IMAGE_PRICE_TABLE[OUTPUT_IMAGE_PRICE_TABLE.len() - 1].2);
match quality {
CommonQualityEnum::Low => prices[0],
CommonQualityEnum::Medium => prices[1],
CommonQualityEnum::High => prices[2],
}
}
fn lookup_price_row(width: u32, height: u32) -> Option<[u64; 3]> {
let long_edge = width.max(height);
let short_edge = width.min(height);
OUTPUT_IMAGE_PRICE_TABLE.iter()
.find(|(w, h, _)| *w == long_edge && *h == short_edge)
.map(|(_, _, prices)| *prices)
}
/// Mirrors the Fal request builder's aspect ratio mapping.
fn to_image_size(aspect_ratio: CommonAspectRatioEnum) -> GptImage2p5ImageSize {
use CommonAspectRatioEnum as Ar;
match aspect_ratio {
Ar::Auto | Ar::Auto2k | Ar::Auto3k | Ar::Auto4k => GptImage2p5ImageSize::Auto,
Ar::Square => GptImage2p5ImageSize::Square,
Ar::SquareHd => GptImage2p5ImageSize::SquareHd,
Ar::WideFourByThree | Ar::WideFiveByFour => GptImage2p5ImageSize::Landscape4x3,
Ar::WideThreeByTwo | Ar::WideSixteenByNine | Ar::WideTwentyOneByNine | Ar::Wide => GptImage2p5ImageSize::Landscape16x9,
Ar::TallThreeByFour | Ar::TallFourByFive => GptImage2p5ImageSize::Portrait4x3,
Ar::TallTwoByThree | Ar::TallNineBySixteen | Ar::TallNineByTwentyOne | Ar::Tall => GptImage2p5ImageSize::Portrait16x9,
}
}
/// Mirrors the Fal request builder's resolution mapping.
fn to_resolution(resolution: CommonResolutionEnum) -> GptImage2Resolution {
use CommonResolutionEnum as R;
match resolution {
R::HalfK | R::FourEightyP | R::SevenTwentyP | R::OneK => GptImage2Resolution::OneK,
R::TenEightyP | R::TwoK => GptImage2Resolution::TwoK,
R::ThreeK => GptImage2Resolution::ThreeK,
R::FourK => GptImage2Resolution::FourK,
}
}
#[cfg(test)]
mod tests {
use super::*;
use CommonAspectRatioEnum as Ar;
use CommonQualityEnum as Q;
use CommonResolutionEnum as R;
const ALL_ASPECT_RATIOS: &[Ar] = &[
Ar::Auto, Ar::Auto2k, Ar::Auto3k, Ar::Auto4k, Ar::Square, Ar::SquareHd,
Ar::WideFourByThree, Ar::WideFiveByFour, Ar::WideThreeByTwo, Ar::WideSixteenByNine,
Ar::WideTwentyOneByNine, Ar::Wide, Ar::TallThreeByFour, Ar::TallFourByFive,
Ar::TallTwoByThree, Ar::TallNineBySixteen, Ar::TallNineByTwentyOne, Ar::Tall,
];
const ALL_RESOLUTIONS: &[Option<R>] = &[
None, Some(R::HalfK), Some(R::FourEightyP), Some(R::SevenTwentyP), Some(R::OneK),
Some(R::TenEightyP), Some(R::TwoK), Some(R::ThreeK), Some(R::FourK),
];
// (aspect_ratio, resolution, [low, medium, high]) — cents per image, text-to-image
const TEXT_GRID: &[(Option<Ar>, Option<R>, [u64; 3])] = &[
(None, None, [1, 2, 4]), // landscape 4:3 default
(Some(Ar::Square), None, [1, 2, 6]),
(Some(Ar::Square), Some(R::OneK), [1, 2, 6]),
(Some(Ar::Square), Some(R::TwoK), [2, 3, 10]),
(Some(Ar::Square), Some(R::ThreeK), [2, 4, 14]),
(Some(Ar::Square), Some(R::FourK), [2, 4, 14]),
(Some(Ar::SquareHd), None, [2, 3, 10]),
(Some(Ar::SquareHd), Some(R::OneK), [1, 2, 6]),
(Some(Ar::WideFourByThree), None, [1, 2, 4]),
(Some(Ar::WideFourByThree), Some(R::TwoK), [1, 2, 7]),
(Some(Ar::WideFourByThree), Some(R::ThreeK), [2, 3, 11]),
(Some(Ar::WideFourByThree), Some(R::FourK), [2, 4, 12]),
(Some(Ar::TallThreeByFour), None, [1, 2, 4]),
(Some(Ar::TallFourByFive), Some(R::FourK), [2, 4, 12]),
(Some(Ar::WideSixteenByNine), None, [1, 2, 5]),
(Some(Ar::WideSixteenByNine), Some(R::OneK), [1, 1, 3]),
(Some(Ar::WideSixteenByNine), Some(R::TenEightyP), [1, 2, 5]),
(Some(Ar::WideSixteenByNine), Some(R::TwoK), [1, 2, 5]),
(Some(Ar::WideSixteenByNine), Some(R::ThreeK), [1, 3, 8]),
(Some(Ar::WideSixteenByNine), Some(R::FourK), [2, 3, 12]),
(Some(Ar::TallNineBySixteen), None, [1, 2, 5]),
(Some(Ar::Wide), Some(R::HalfK), [1, 1, 3]),
(Some(Ar::Tall), Some(R::ThreeK), [1, 3, 8]),
(Some(Ar::Auto), None, [2, 3, 12]),
(Some(Ar::Auto4k), Some(R::OneK), [2, 3, 12]),
];
mod text_to_image_tests {
use super::*;
#[test]
fn grid() {
for &(aspect_ratio, resolution, expected) in TEXT_GRID {
for (quality, expected) in [Q::Low, Q::Medium, Q::High].into_iter().zip(expected) {
let actual = make_inputs(0, Some(quality), aspect_ratio, resolution, 1).estimate_cost().cost_in_usd_cents.unwrap();
assert_eq!(actual, expected, "{aspect_ratio:?} {resolution:?} {quality:?}");
}
}
}
#[test]
fn quality_defaults_to_high() {
assert_eq!(cents(make_inputs(0, None, Some(Ar::Square), None, 1)), 6);
}
#[test]
fn batch_multiplies_per_image_cents() {
for &(aspect_ratio, resolution, _) in TEXT_GRID {
let per_image = cents(make_inputs(0, Some(Q::High), aspect_ratio, resolution, 1));
for batch in 2..=4u16 {
assert_eq!(cents(make_inputs(0, Some(Q::High), aspect_ratio, resolution, batch)), per_image * batch as u64);
}
}
}
}
mod edit_image_tests {
use super::*;
#[test]
fn no_aspect_ratio_prices_as_auto() {
// 1102 + 88 = 1190
assert_eq!(cents(make_inputs(1, Some(Q::High), None, None, 1)), 12);
assert_eq!(cents(make_inputs(1, Some(Q::High), Some(Ar::Auto), None, 1)), 12);
}
#[test]
fn reference_images_add_to_price() {
// Square high 582, plus 88 per reference image
assert_eq!(cents(make_inputs(1, Some(Q::High), Some(Ar::Square), None, 1)), 7); // 670
assert_eq!(cents(make_inputs(4, Some(Q::High), Some(Ar::Square), None, 1)), 10); // 934
assert_eq!(cents(make_inputs(16, Some(Q::High), Some(Ar::Square), None, 1)), 20); // 1990
assert_eq!(cents(make_inputs(1, Some(Q::Low), Some(Ar::Square), None, 1)), 2); // 153
}
#[test]
fn batch_multiplies_per_image_cents() {
assert_eq!(cents(make_inputs(1, Some(Q::High), Some(Ar::Square), None, 4)), 28);
}
}
mod table_coverage_tests {
use super::*;
#[test]
fn every_reachable_dimension_has_a_table_row() {
for &aspect_ratio in ALL_ASPECT_RATIOS {
for &resolution in ALL_RESOLUTIONS {
for refs in [0, 1] {
let (w, h) = make_inputs(refs, None, Some(aspect_ratio), resolution, 1).output_dimensions();
assert!(lookup_price_row(w, h).is_some(), "{aspect_ratio:?} {resolution:?} => {w}x{h} missing from price table");
}
}
}
for refs in [0, 1] {
for &resolution in ALL_RESOLUTIONS {
let (w, h) = make_inputs(refs, None, None, resolution, 1).output_dimensions();
assert!(lookup_price_row(w, h).is_some(), "no aspect, {resolution:?}, {refs} refs => {w}x{h} missing from price table");
}
}
}
#[test]
fn unknown_dimensions_fall_back_to_most_expensive_row() {
assert_eq!(output_image_price(Q::High, 640, 640), 1102);
}
#[test]
fn orientation_does_not_change_price() {
assert_eq!(output_image_price(Q::High, 768, 1024), output_image_price(Q::High, 1024, 768));
assert_eq!(output_image_price(Q::Medium, 1080, 1920), output_image_price(Q::Medium, 1920, 1080));
}
#[test]
fn prices_rise_with_quality_and_size() {
for &(_, _, prices) in OUTPUT_IMAGE_PRICE_TABLE {
assert!(prices[0] < prices[1] && prices[1] < prices[2], "{prices:?}");
}
assert!(output_image_price(Q::High, 1024, 1024) < output_image_price(Q::High, 2048, 2048));
assert!(output_image_price(Q::High, 2048, 2048) < output_image_price(Q::High, 2880, 2880));
assert!(output_image_price(Q::High, 1088, 608) < output_image_price(Q::High, 1920, 1080));
assert!(output_image_price(Q::High, 3072, 1728) < output_image_price(Q::High, 3840, 2160));
}
}
fn cents(inputs: ArtcraftGptImage2p5CostInputs) -> u64 {
inputs.estimate_cost().cost_in_usd_cents.unwrap()
}
fn make_inputs(
num_reference_images: usize,
quality: Option<Q>,
aspect_ratio: Option<Ar>,
resolution: Option<R>,
num_images: u16,
) -> ArtcraftGptImage2p5CostInputs {
ArtcraftGptImage2p5CostInputs { quality, aspect_ratio, resolution, num_reference_images, num_images }
}
}
@@ -1,114 +0,0 @@
use enums::common::generation::common_image_model::CommonImageModel as CommonImageModelEnum;
use crate::errors::artcraft_router_error::ArtcraftRouterError;
use crate::generate::generate_image::generate_image_request_builder::GenerateImageRequestBuilder;
use crate::generate::generate_image::image_generation_draft_or_request::ImageGenerationDraftOrRequest;
use crate::generate::generate_image::image_generation_request::ImageGenerationRequest;
use crate::generate::generate_image::providers::artcraft::build_common::build_artcraft_omni_image_request;
use crate::generate::generate_image::providers::artcraft::gpt_image_2p5_flare::request::ArtcraftGptImage2p5FlareRequestState;
pub fn build_artcraft_gpt_image_2p5_flare(
builder: GenerateImageRequestBuilder,
) -> Result<ImageGenerationDraftOrRequest, ArtcraftRouterError> {
let request = build_artcraft_omni_image_request(builder, CommonImageModelEnum::GptImage2p5Flare)?;
Ok(ImageGenerationDraftOrRequest::Request(
ImageGenerationRequest::ArtcraftGptImage2p5Flare(ArtcraftGptImage2p5FlareRequestState { request }),
))
}
#[cfg(test)]
mod tests {
use super::*;
use artcraft_api_defs::omni_gen::cost_and_generate_requests::omni_gen_image_cost_and_generate_request::OmniGenImageCostAndGenerateRequest;
use enums::common::generation::common_aspect_ratio::CommonAspectRatio as CommonAspectRatioEnum;
use enums::common::generation::common_quality::CommonQuality as CommonQualityEnum;
use enums::common::generation::common_resolution::CommonResolution as CommonResolutionEnum;
use tokens::tokens::media_files::MediaFileToken;
use crate::api::image_list_ref::ImageListRef;
use crate::api::router_aspect_ratio::RouterAspectRatio;
use crate::api::router_image_model::RouterImageModel;
use crate::api::router_provider::RouterProvider;
use crate::api::router_quality::RouterQuality;
use crate::api::router_resolution::RouterResolution;
use crate::client::request_mismatch_mitigation_strategy::RequestMismatchMitigationStrategy;
use crate::errors::client_error::ClientError;
#[test]
fn build2_routes_to_omni_request_with_flare_model() {
let request = unwrap_request(base_builder().build2());
assert_eq!(request.model, Some(CommonImageModelEnum::GptImage2p5Flare));
assert_eq!(request.prompt.as_deref(), Some("a cat in space"));
assert_eq!(request.image_batch_count, Some(1));
assert!(request.image_media_tokens.is_none());
assert!(request.aspect_ratio.is_none());
assert!(request.resolution.is_none());
assert!(request.quality.is_none());
assert!(request.idempotency_token.is_some());
}
#[test]
fn omni_request_carries_all_generation_fields() {
let request = unwrap_request(GenerateImageRequestBuilder {
aspect_ratio: Some(RouterAspectRatio::WideSixteenByNine),
resolution: Some(RouterResolution::TwoK),
quality: Some(RouterQuality::Medium),
image_batch_count: Some(3),
idempotency_token: Some("idem-123".to_string()),
image_inputs: Some(ImageListRef::MediaFileTokens(vec![MediaFileToken::generate(), MediaFileToken::generate()])),
..base_builder()
}.build2());
assert_eq!(request.aspect_ratio, Some(CommonAspectRatioEnum::WideSixteenByNine));
assert_eq!(request.resolution, Some(CommonResolutionEnum::TwoK));
assert_eq!(request.quality, Some(CommonQualityEnum::Medium));
assert_eq!(request.image_batch_count, Some(3));
assert_eq!(request.idempotency_token.as_deref(), Some("idem-123"));
assert_eq!(request.image_media_tokens.map(|tokens| tokens.len()), Some(2));
}
#[test]
fn batch_count_is_validated() {
assert!(matches!(
GenerateImageRequestBuilder { image_batch_count: Some(0), ..base_builder() }.build2(),
Err(ArtcraftRouterError::Client(ClientError::UserRequestedZeroGenerations))
));
assert!(matches!(
GenerateImageRequestBuilder { image_batch_count: Some(5), ..base_builder() }.build2(),
Err(ArtcraftRouterError::Client(ClientError::ModelDoesNotSupportOption { .. }))
));
let request = unwrap_request(GenerateImageRequestBuilder {
image_batch_count: Some(5),
request_mismatch_mitigation_strategy: RequestMismatchMitigationStrategy::PayLessDowngrade,
..base_builder()
}.build2());
assert_eq!(request.image_batch_count, Some(4));
}
fn base_builder() -> GenerateImageRequestBuilder {
GenerateImageRequestBuilder {
model: RouterImageModel::GptImage2p5Flare,
provider: RouterProvider::Artcraft,
prompt: Some("a cat in space".to_string()),
image_inputs: None,
resolution: None,
aspect_ratio: None,
quality: None,
image_batch_count: None,
horizontal_angle: None,
vertical_angle: None,
zoom: None,
request_mismatch_mitigation_strategy: RequestMismatchMitigationStrategy::ErrorOut,
generation_mode_mismatch_strategy: None,
idempotency_token: None,
}
}
fn unwrap_request(result: Result<ImageGenerationDraftOrRequest, ArtcraftRouterError>) -> OmniGenImageCostAndGenerateRequest {
let ImageGenerationDraftOrRequest::Request(
ImageGenerationRequest::ArtcraftGptImage2p5Flare(state)
) = result.expect("build should succeed") else {
panic!("expected Artcraft GPT Image 2.5 Flare request")
};
state.request
}
}
@@ -1,106 +0,0 @@
use crate::generate::generate_image::image_generation_cost_estimate::ImageGenerationCostEstimate;
use crate::generate::generate_image::providers::artcraft::gpt_image_2p5_common_cost::ArtcraftGptImage2p5CostInputs;
use crate::generate::generate_image::providers::artcraft::gpt_image_2p5_flare::request::ArtcraftGptImage2p5FlareRequestState;
/// Cost state for Artcraft GPT Image 2.5 Flare. The price table is shared with the other
/// GPT Image 2.5 variant; see `gpt_image_2p5_common_cost`.
#[derive(Clone, Debug)]
pub struct ArtcraftGptImage2p5FlareCostState {
inputs: ArtcraftGptImage2p5CostInputs,
}
impl ArtcraftGptImage2p5FlareCostState {
pub fn from_request(request: &ArtcraftGptImage2p5FlareRequestState) -> Self {
Self { inputs: ArtcraftGptImage2p5CostInputs::from_omni_request(&request.request) }
}
pub fn estimate_cost(&self) -> ImageGenerationCostEstimate {
self.inputs.estimate_cost()
}
}
#[cfg(test)]
mod tests {
use tokens::tokens::media_files::MediaFileToken;
use crate::api::image_list_ref::ImageListRef;
use crate::api::router_aspect_ratio::RouterAspectRatio;
use crate::api::router_image_model::RouterImageModel;
use crate::api::router_provider::RouterProvider;
use crate::api::router_quality::RouterQuality;
use crate::api::router_resolution::RouterResolution;
use crate::client::request_mismatch_mitigation_strategy::RequestMismatchMitigationStrategy;
use crate::generate::generate_image::generate_image_request_builder::GenerateImageRequestBuilder;
use RouterAspectRatio as Ar;
use RouterQuality as Q;
use RouterResolution as R;
// (reference_images, quality, aspect_ratio, resolution, batch, expected_cents)
const CASES: &[(usize, Option<Q>, Option<Ar>, Option<R>, u16, u64)] = &[
(0, None, None, None, 1, 4),
(0, Some(Q::Low), Some(Ar::Square), None, 1, 1),
(0, Some(Q::Medium), Some(Ar::Square), None, 1, 2),
(0, Some(Q::High), Some(Ar::Square), None, 1, 6),
(0, Some(Q::High), Some(Ar::Square), None, 4, 24),
(0, Some(Q::High), Some(Ar::SquareHd), None, 1, 10),
(0, Some(Q::High), Some(Ar::Square), Some(R::TwoK), 1, 10),
(0, Some(Q::High), Some(Ar::Square), Some(R::FourK), 1, 14),
(0, Some(Q::High), Some(Ar::WideFourByThree), None, 1, 4),
(0, Some(Q::High), Some(Ar::WideSixteenByNine), None, 1, 5),
(0, Some(Q::High), Some(Ar::WideSixteenByNine), Some(R::OneK), 1, 3),
(0, Some(Q::High), Some(Ar::WideSixteenByNine), Some(R::FourK), 1, 12),
(0, Some(Q::Medium), Some(Ar::TallNineBySixteen), Some(R::ThreeK), 2, 6),
(0, Some(Q::High), Some(Ar::Auto), None, 1, 12),
(1, None, None, None, 1, 12),
(1, Some(Q::High), Some(Ar::Square), None, 1, 7),
(4, Some(Q::High), Some(Ar::Square), None, 1, 10),
(1, Some(Q::High), Some(Ar::Square), None, 4, 28),
(1, Some(Q::Low), Some(Ar::Square), None, 1, 2),
];
#[test]
fn costs_through_build2() {
for &(refs, quality, aspect_ratio, resolution, batch, expected) in CASES {
assert_eq!(cost_cents(refs, quality, aspect_ratio, resolution, batch), expected, "{refs} refs {quality:?} {aspect_ratio:?} {resolution:?} x{batch}");
}
}
#[test]
fn estimate_flags() {
let cost = builder(0, Some(Q::High), Some(Ar::Square), None, 1).build2().unwrap().estimate_cost().unwrap();
assert_eq!(cost.cost_in_credits, cost.cost_in_usd_cents);
assert!(!cost.is_free);
assert!(!cost.is_unlimited);
assert!(!cost.is_rate_limited);
assert!(!cost.has_watermark);
}
fn cost_cents(refs: usize, quality: Option<Q>, aspect_ratio: Option<Ar>, resolution: Option<R>, batch: u16) -> u64 {
builder(refs, quality, aspect_ratio, resolution, batch)
.build2().unwrap().estimate_cost().unwrap().cost_in_usd_cents.unwrap()
}
fn builder(refs: usize, quality: Option<Q>, aspect_ratio: Option<Ar>, resolution: Option<R>, batch: u16) -> GenerateImageRequestBuilder {
let image_inputs = if refs == 0 {
None
} else {
Some(ImageListRef::MediaFileTokens((0..refs).map(|_| MediaFileToken::generate()).collect()))
};
GenerateImageRequestBuilder {
model: RouterImageModel::GptImage2p5Flare,
provider: RouterProvider::Artcraft,
prompt: Some("a cat in space".to_string()),
image_inputs,
resolution,
aspect_ratio,
quality,
image_batch_count: Some(batch),
horizontal_angle: None,
vertical_angle: None,
zoom: None,
request_mismatch_mitigation_strategy: RequestMismatchMitigationStrategy::ErrorOut,
generation_mode_mismatch_strategy: None,
idempotency_token: None,
}
}
}
@@ -1,3 +0,0 @@
pub mod build;
pub mod cost;
pub mod request;
@@ -1,17 +0,0 @@
use artcraft_api_defs::omni_gen::cost_and_generate_requests::omni_gen_image_cost_and_generate_request::OmniGenImageCostAndGenerateRequest;
use crate::client::router_artcraft_client::RouterArtcraftClient;
use crate::errors::artcraft_router_error::ArtcraftRouterError;
use crate::generate::generate_image::generate_image_response::GenerateImageResponse;
use crate::generate::generate_image::providers::artcraft::request_common::send_artcraft_omni_image_request;
#[derive(Clone, Debug)]
pub struct ArtcraftGptImage2p5FlareRequestState {
pub request: OmniGenImageCostAndGenerateRequest,
}
impl ArtcraftGptImage2p5FlareRequestState {
pub async fn send(&self, client: &RouterArtcraftClient) -> Result<GenerateImageResponse, ArtcraftRouterError> {
send_artcraft_omni_image_request(&self.request, client).await
}
}
@@ -1,114 +0,0 @@
use enums::common::generation::common_image_model::CommonImageModel as CommonImageModelEnum;
use crate::errors::artcraft_router_error::ArtcraftRouterError;
use crate::generate::generate_image::generate_image_request_builder::GenerateImageRequestBuilder;
use crate::generate::generate_image::image_generation_draft_or_request::ImageGenerationDraftOrRequest;
use crate::generate::generate_image::image_generation_request::ImageGenerationRequest;
use crate::generate::generate_image::providers::artcraft::build_common::build_artcraft_omni_image_request;
use crate::generate::generate_image::providers::artcraft::gpt_image_2p5_sunburst::request::ArtcraftGptImage2p5SunburstRequestState;
pub fn build_artcraft_gpt_image_2p5_sunburst(
builder: GenerateImageRequestBuilder,
) -> Result<ImageGenerationDraftOrRequest, ArtcraftRouterError> {
let request = build_artcraft_omni_image_request(builder, CommonImageModelEnum::GptImage2p5Sunburst)?;
Ok(ImageGenerationDraftOrRequest::Request(
ImageGenerationRequest::ArtcraftGptImage2p5Sunburst(ArtcraftGptImage2p5SunburstRequestState { request }),
))
}
#[cfg(test)]
mod tests {
use super::*;
use artcraft_api_defs::omni_gen::cost_and_generate_requests::omni_gen_image_cost_and_generate_request::OmniGenImageCostAndGenerateRequest;
use enums::common::generation::common_aspect_ratio::CommonAspectRatio as CommonAspectRatioEnum;
use enums::common::generation::common_quality::CommonQuality as CommonQualityEnum;
use enums::common::generation::common_resolution::CommonResolution as CommonResolutionEnum;
use tokens::tokens::media_files::MediaFileToken;
use crate::api::image_list_ref::ImageListRef;
use crate::api::router_aspect_ratio::RouterAspectRatio;
use crate::api::router_image_model::RouterImageModel;
use crate::api::router_provider::RouterProvider;
use crate::api::router_quality::RouterQuality;
use crate::api::router_resolution::RouterResolution;
use crate::client::request_mismatch_mitigation_strategy::RequestMismatchMitigationStrategy;
use crate::errors::client_error::ClientError;
#[test]
fn build2_routes_to_omni_request_with_sunburst_model() {
let request = unwrap_request(base_builder().build2());
assert_eq!(request.model, Some(CommonImageModelEnum::GptImage2p5Sunburst));
assert_eq!(request.prompt.as_deref(), Some("a cat in space"));
assert_eq!(request.image_batch_count, Some(1));
assert!(request.image_media_tokens.is_none());
assert!(request.aspect_ratio.is_none());
assert!(request.resolution.is_none());
assert!(request.quality.is_none());
assert!(request.idempotency_token.is_some());
}
#[test]
fn omni_request_carries_all_generation_fields() {
let request = unwrap_request(GenerateImageRequestBuilder {
aspect_ratio: Some(RouterAspectRatio::WideSixteenByNine),
resolution: Some(RouterResolution::TwoK),
quality: Some(RouterQuality::Medium),
image_batch_count: Some(3),
idempotency_token: Some("idem-123".to_string()),
image_inputs: Some(ImageListRef::MediaFileTokens(vec![MediaFileToken::generate(), MediaFileToken::generate()])),
..base_builder()
}.build2());
assert_eq!(request.aspect_ratio, Some(CommonAspectRatioEnum::WideSixteenByNine));
assert_eq!(request.resolution, Some(CommonResolutionEnum::TwoK));
assert_eq!(request.quality, Some(CommonQualityEnum::Medium));
assert_eq!(request.image_batch_count, Some(3));
assert_eq!(request.idempotency_token.as_deref(), Some("idem-123"));
assert_eq!(request.image_media_tokens.map(|tokens| tokens.len()), Some(2));
}
#[test]
fn batch_count_is_validated() {
assert!(matches!(
GenerateImageRequestBuilder { image_batch_count: Some(0), ..base_builder() }.build2(),
Err(ArtcraftRouterError::Client(ClientError::UserRequestedZeroGenerations))
));
assert!(matches!(
GenerateImageRequestBuilder { image_batch_count: Some(5), ..base_builder() }.build2(),
Err(ArtcraftRouterError::Client(ClientError::ModelDoesNotSupportOption { .. }))
));
let request = unwrap_request(GenerateImageRequestBuilder {
image_batch_count: Some(5),
request_mismatch_mitigation_strategy: RequestMismatchMitigationStrategy::PayLessDowngrade,
..base_builder()
}.build2());
assert_eq!(request.image_batch_count, Some(4));
}
fn base_builder() -> GenerateImageRequestBuilder {
GenerateImageRequestBuilder {
model: RouterImageModel::GptImage2p5Sunburst,
provider: RouterProvider::Artcraft,
prompt: Some("a cat in space".to_string()),
image_inputs: None,
resolution: None,
aspect_ratio: None,
quality: None,
image_batch_count: None,
horizontal_angle: None,
vertical_angle: None,
zoom: None,
request_mismatch_mitigation_strategy: RequestMismatchMitigationStrategy::ErrorOut,
generation_mode_mismatch_strategy: None,
idempotency_token: None,
}
}
fn unwrap_request(result: Result<ImageGenerationDraftOrRequest, ArtcraftRouterError>) -> OmniGenImageCostAndGenerateRequest {
let ImageGenerationDraftOrRequest::Request(
ImageGenerationRequest::ArtcraftGptImage2p5Sunburst(state)
) = result.expect("build should succeed") else {
panic!("expected Artcraft GPT Image 2.5 Sunburst request")
};
state.request
}
}
@@ -1,106 +0,0 @@
use crate::generate::generate_image::image_generation_cost_estimate::ImageGenerationCostEstimate;
use crate::generate::generate_image::providers::artcraft::gpt_image_2p5_common_cost::ArtcraftGptImage2p5CostInputs;
use crate::generate::generate_image::providers::artcraft::gpt_image_2p5_sunburst::request::ArtcraftGptImage2p5SunburstRequestState;
/// Cost state for Artcraft GPT Image 2.5 Sunburst. The price table is shared with the other
/// GPT Image 2.5 variant; see `gpt_image_2p5_common_cost`.
#[derive(Clone, Debug)]
pub struct ArtcraftGptImage2p5SunburstCostState {
inputs: ArtcraftGptImage2p5CostInputs,
}
impl ArtcraftGptImage2p5SunburstCostState {
pub fn from_request(request: &ArtcraftGptImage2p5SunburstRequestState) -> Self {
Self { inputs: ArtcraftGptImage2p5CostInputs::from_omni_request(&request.request) }
}
pub fn estimate_cost(&self) -> ImageGenerationCostEstimate {
self.inputs.estimate_cost()
}
}
#[cfg(test)]
mod tests {
use tokens::tokens::media_files::MediaFileToken;
use crate::api::image_list_ref::ImageListRef;
use crate::api::router_aspect_ratio::RouterAspectRatio;
use crate::api::router_image_model::RouterImageModel;
use crate::api::router_provider::RouterProvider;
use crate::api::router_quality::RouterQuality;
use crate::api::router_resolution::RouterResolution;
use crate::client::request_mismatch_mitigation_strategy::RequestMismatchMitigationStrategy;
use crate::generate::generate_image::generate_image_request_builder::GenerateImageRequestBuilder;
use RouterAspectRatio as Ar;
use RouterQuality as Q;
use RouterResolution as R;
// (reference_images, quality, aspect_ratio, resolution, batch, expected_cents)
const CASES: &[(usize, Option<Q>, Option<Ar>, Option<R>, u16, u64)] = &[
(0, None, None, None, 1, 4),
(0, Some(Q::Low), Some(Ar::Square), None, 1, 1),
(0, Some(Q::Medium), Some(Ar::Square), None, 1, 2),
(0, Some(Q::High), Some(Ar::Square), None, 1, 6),
(0, Some(Q::High), Some(Ar::Square), None, 4, 24),
(0, Some(Q::High), Some(Ar::SquareHd), None, 1, 10),
(0, Some(Q::High), Some(Ar::Square), Some(R::TwoK), 1, 10),
(0, Some(Q::High), Some(Ar::Square), Some(R::FourK), 1, 14),
(0, Some(Q::High), Some(Ar::WideFourByThree), None, 1, 4),
(0, Some(Q::High), Some(Ar::WideSixteenByNine), None, 1, 5),
(0, Some(Q::High), Some(Ar::WideSixteenByNine), Some(R::OneK), 1, 3),
(0, Some(Q::High), Some(Ar::WideSixteenByNine), Some(R::FourK), 1, 12),
(0, Some(Q::Medium), Some(Ar::TallNineBySixteen), Some(R::ThreeK), 2, 6),
(0, Some(Q::High), Some(Ar::Auto), None, 1, 12),
(1, None, None, None, 1, 12),
(1, Some(Q::High), Some(Ar::Square), None, 1, 7),
(4, Some(Q::High), Some(Ar::Square), None, 1, 10),
(1, Some(Q::High), Some(Ar::Square), None, 4, 28),
(1, Some(Q::Low), Some(Ar::Square), None, 1, 2),
];
#[test]
fn costs_through_build2() {
for &(refs, quality, aspect_ratio, resolution, batch, expected) in CASES {
assert_eq!(cost_cents(refs, quality, aspect_ratio, resolution, batch), expected, "{refs} refs {quality:?} {aspect_ratio:?} {resolution:?} x{batch}");
}
}
#[test]
fn estimate_flags() {
let cost = builder(0, Some(Q::High), Some(Ar::Square), None, 1).build2().unwrap().estimate_cost().unwrap();
assert_eq!(cost.cost_in_credits, cost.cost_in_usd_cents);
assert!(!cost.is_free);
assert!(!cost.is_unlimited);
assert!(!cost.is_rate_limited);
assert!(!cost.has_watermark);
}
fn cost_cents(refs: usize, quality: Option<Q>, aspect_ratio: Option<Ar>, resolution: Option<R>, batch: u16) -> u64 {
builder(refs, quality, aspect_ratio, resolution, batch)
.build2().unwrap().estimate_cost().unwrap().cost_in_usd_cents.unwrap()
}
fn builder(refs: usize, quality: Option<Q>, aspect_ratio: Option<Ar>, resolution: Option<R>, batch: u16) -> GenerateImageRequestBuilder {
let image_inputs = if refs == 0 {
None
} else {
Some(ImageListRef::MediaFileTokens((0..refs).map(|_| MediaFileToken::generate()).collect()))
};
GenerateImageRequestBuilder {
model: RouterImageModel::GptImage2p5Sunburst,
provider: RouterProvider::Artcraft,
prompt: Some("a cat in space".to_string()),
image_inputs,
resolution,
aspect_ratio,
quality,
image_batch_count: Some(batch),
horizontal_angle: None,
vertical_angle: None,
zoom: None,
request_mismatch_mitigation_strategy: RequestMismatchMitigationStrategy::ErrorOut,
generation_mode_mismatch_strategy: None,
idempotency_token: None,
}
}
}
@@ -1,3 +0,0 @@
pub mod build;
pub mod cost;
pub mod request;
@@ -1,17 +0,0 @@
use artcraft_api_defs::omni_gen::cost_and_generate_requests::omni_gen_image_cost_and_generate_request::OmniGenImageCostAndGenerateRequest;
use crate::client::router_artcraft_client::RouterArtcraftClient;
use crate::errors::artcraft_router_error::ArtcraftRouterError;
use crate::generate::generate_image::generate_image_response::GenerateImageResponse;
use crate::generate::generate_image::providers::artcraft::request_common::send_artcraft_omni_image_request;
#[derive(Clone, Debug)]
pub struct ArtcraftGptImage2p5SunburstRequestState {
pub request: OmniGenImageCostAndGenerateRequest,
}
impl ArtcraftGptImage2p5SunburstRequestState {
pub async fn send(&self, client: &RouterArtcraftClient) -> Result<GenerateImageResponse, ArtcraftRouterError> {
send_artcraft_omni_image_request(&self.request, client).await
}
}
@@ -8,9 +8,6 @@ pub mod flux_pro_1p1_ultra;
pub mod gpt_image_1;
pub mod gpt_image_1p5;
pub mod gpt_image_2;
pub(crate) mod gpt_image_2p5_common_cost;
pub mod gpt_image_2p5_flare;
pub mod gpt_image_2p5_sunburst;
pub mod midjourney_7;
pub mod midjourney_7_niji;
pub mod midjourney_8;
@@ -1,5 +0,0 @@
//! Planning and transport shared by the GPT Image 2.5 Flare and Sunburst Fal providers.
//! The two models take identical parameters; only the Fal endpoint differs.
pub mod plan;
pub mod send;
@@ -1,330 +0,0 @@
use fal_client::requests::api::image::common::gpt_image_2_resolution::GptImage2Resolution;
use fal_client::requests::api::image::common::gpt_image_2p5::gpt_image_2p5_edit_image_params::GptImage2p5EditImageParams;
use fal_client::requests::api::image::common::gpt_image_2p5::gpt_image_2p5_image_size::GptImage2p5ImageSize;
use fal_client::requests::api::image::common::gpt_image_2p5::gpt_image_2p5_num_images::GptImage2p5NumImages;
use fal_client::requests::api::image::common::gpt_image_2p5::gpt_image_2p5_quality::GptImage2p5Quality;
use fal_client::requests::api::image::common::gpt_image_2p5::gpt_image_2p5_text_to_image_params::GptImage2p5TextToImageParams;
use crate::api::image_list_ref::ImageListRef;
use crate::api::router_aspect_ratio::RouterAspectRatio;
use crate::api::router_quality::RouterQuality;
use crate::api::router_resolution::RouterResolution;
use crate::client::request_mismatch_mitigation_strategy::RequestMismatchMitigationStrategy;
use crate::errors::artcraft_router_error::ArtcraftRouterError;
use crate::errors::client_error::ClientError;
use crate::generate::generate_image::generate_image_request_builder::GenerateImageRequestBuilder;
/// Planned GPT Image 2.5 parameters. The mode is chosen by whether the builder carries
/// reference images: none means text-to-image, one or more means edit.
#[derive(Clone, Debug)]
pub enum PlannedGptImage2p5Params {
TextToImage(GptImage2p5TextToImageParams),
EditImage(GptImage2p5EditImageParams),
}
pub fn plan_gpt_image_2p5_params(
builder: &GenerateImageRequestBuilder,
) -> Result<PlannedGptImage2p5Params, ArtcraftRouterError> {
let prompt = builder.prompt.clone().unwrap_or_default();
let image_urls = resolve_image_urls(builder.image_inputs.clone())?;
let num_images = plan_num_images(builder.image_batch_count, builder.request_mismatch_mitigation_strategy)?;
let image_size = plan_image_size(builder.aspect_ratio);
let resolution = plan_resolution(builder.resolution);
let quality = Some(plan_quality(builder.quality));
if image_urls.is_empty() {
Ok(PlannedGptImage2p5Params::TextToImage(GptImage2p5TextToImageParams {
prompt,
num_images,
image_size,
resolution,
quality,
background: None,
output_format: None,
output_compression: None,
}))
} else {
Ok(PlannedGptImage2p5Params::EditImage(GptImage2p5EditImageParams {
prompt,
image_urls,
mask_url: None,
num_images,
image_size,
resolution,
quality,
background: None,
output_format: None,
output_compression: None,
}))
}
}
fn plan_num_images(
count: Option<u16>,
strategy: RequestMismatchMitigationStrategy,
) -> Result<GptImage2p5NumImages, ArtcraftRouterError> {
let count = count.unwrap_or(1);
match count {
0 => Err(ArtcraftRouterError::Client(ClientError::UserRequestedZeroGenerations)),
1 => Ok(GptImage2p5NumImages::One),
2 => Ok(GptImage2p5NumImages::Two),
3 => Ok(GptImage2p5NumImages::Three),
4 => Ok(GptImage2p5NumImages::Four),
_ => match strategy {
RequestMismatchMitigationStrategy::ErrorOut => {
Err(ArtcraftRouterError::Client(ClientError::ModelDoesNotSupportOption {
field: "image_batch_count",
value: format!("{}", count),
}))
}
_ => Ok(GptImage2p5NumImages::Four),
},
}
}
/// The router only exposes low / medium / high; GPT Image 2.5's `xhigh` and `max` tiers are
/// not reachable through it. Fal's default (`high`) applies when unspecified.
fn plan_quality(quality: Option<RouterQuality>) -> GptImage2p5Quality {
match quality {
Some(RouterQuality::Low) => GptImage2p5Quality::Low,
Some(RouterQuality::Medium) => GptImage2p5Quality::Medium,
Some(RouterQuality::High) | None => GptImage2p5Quality::High,
}
}
fn plan_resolution(resolution: Option<RouterResolution>) -> Option<GptImage2Resolution> {
resolution.map(|r| match r {
RouterResolution::HalfK
| RouterResolution::FourEightyP
| RouterResolution::SevenTwentyP
| RouterResolution::OneK => GptImage2Resolution::OneK,
RouterResolution::TenEightyP | RouterResolution::TwoK => GptImage2Resolution::TwoK,
RouterResolution::ThreeK => GptImage2Resolution::ThreeK,
RouterResolution::FourK => GptImage2Resolution::FourK,
})
}
/// `None` lets Fal apply its own default (`landscape_4_3` for text-to-image, `auto` for edit).
fn plan_image_size(aspect_ratio: Option<RouterAspectRatio>) -> Option<GptImage2p5ImageSize> {
aspect_ratio.map(|ar| match ar {
RouterAspectRatio::Auto
| RouterAspectRatio::Auto2k
| RouterAspectRatio::Auto3k
| RouterAspectRatio::Auto4k => GptImage2p5ImageSize::Auto,
RouterAspectRatio::Square => GptImage2p5ImageSize::Square,
RouterAspectRatio::SquareHd => GptImage2p5ImageSize::SquareHd,
RouterAspectRatio::WideFourByThree
| RouterAspectRatio::WideFiveByFour => GptImage2p5ImageSize::Landscape4x3,
RouterAspectRatio::WideThreeByTwo
| RouterAspectRatio::WideSixteenByNine
| RouterAspectRatio::WideTwentyOneByNine
| RouterAspectRatio::Wide => GptImage2p5ImageSize::Landscape16x9,
RouterAspectRatio::TallThreeByFour
| RouterAspectRatio::TallFourByFive => GptImage2p5ImageSize::Portrait4x3,
RouterAspectRatio::TallTwoByThree
| RouterAspectRatio::TallNineBySixteen
| RouterAspectRatio::TallNineByTwentyOne
| RouterAspectRatio::Tall => GptImage2p5ImageSize::Portrait16x9,
})
}
fn resolve_image_urls(
image_inputs: Option<ImageListRef>,
) -> Result<Vec<String>, ArtcraftRouterError> {
match image_inputs {
None => Ok(vec![]),
Some(ImageListRef::Urls(urls)) => Ok(urls),
Some(ImageListRef::MediaFileTokens(_)) => {
Err(ArtcraftRouterError::Client(ClientError::FalOnlySupportsUrls))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fmt::Debug;
use crate::api::router_image_model::RouterImageModel;
use crate::api::router_provider::RouterProvider;
const IMAGE_URL: &str = "https://example.com/img.jpg";
#[test]
fn mode_is_based_on_image_urls() {
let text = unwrap_t2i(plan_gpt_image_2p5_params(&base_builder()));
assert_eq!(text.prompt, "a cat in space");
let edit = unwrap_edit(plan_gpt_image_2p5_params(&with_reference_image(base_builder())));
assert_eq!(edit.prompt, "a cat in space");
assert_eq!(edit.image_urls, vec![IMAGE_URL]);
assert!(edit.mask_url.is_none());
}
#[test]
fn optional_fal_fields_are_left_to_fal_defaults() {
let text = unwrap_t2i(plan_gpt_image_2p5_params(&base_builder()));
assert!(text.background.is_none());
assert!(text.output_format.is_none());
assert!(text.output_compression.is_none());
assert!(text.image_size.is_none());
assert!(text.resolution.is_none());
}
#[test]
fn media_file_tokens_are_rejected() {
let result = plan_gpt_image_2p5_params(&GenerateImageRequestBuilder {
image_inputs: Some(ImageListRef::MediaFileTokens(vec![])),
..base_builder()
});
assert!(matches!(result, Err(ArtcraftRouterError::Client(ClientError::FalOnlySupportsUrls))));
}
#[test]
fn num_images_maps_exhaustively_for_text_and_edit() {
let cases = [(1, "One"), (2, "Two"), (3, "Three"), (4, "Four")];
for (count, expected) in cases {
let text = unwrap_t2i(plan_gpt_image_2p5_params(&GenerateImageRequestBuilder {
image_batch_count: Some(count),
..base_builder()
}));
assert_debug(text.num_images, expected);
let edit = unwrap_edit(plan_gpt_image_2p5_params(&with_reference_image(GenerateImageRequestBuilder {
image_batch_count: Some(count),
..base_builder()
})));
assert_debug(edit.num_images, expected);
}
}
#[test]
fn num_images_rejects_zero_and_handles_overflow_by_strategy() {
assert!(matches!(
plan_gpt_image_2p5_params(&GenerateImageRequestBuilder { image_batch_count: Some(0), ..base_builder() }),
Err(ArtcraftRouterError::Client(ClientError::UserRequestedZeroGenerations))
));
assert!(matches!(
plan_gpt_image_2p5_params(&GenerateImageRequestBuilder { image_batch_count: Some(5), ..base_builder() }),
Err(ArtcraftRouterError::Client(ClientError::ModelDoesNotSupportOption { .. }))
));
let text = unwrap_t2i(plan_gpt_image_2p5_params(&GenerateImageRequestBuilder {
image_batch_count: Some(5),
request_mismatch_mitigation_strategy: RequestMismatchMitigationStrategy::PayMoreUpgrade,
..base_builder()
}));
assert_debug(text.num_images, "Four");
}
#[test]
fn quality_maps_exhaustively_for_text_and_edit() {
let cases = [
(None, "Some(High)"),
(Some(RouterQuality::Low), "Some(Low)"),
(Some(RouterQuality::Medium), "Some(Medium)"),
(Some(RouterQuality::High), "Some(High)"),
];
for (quality, expected) in cases {
let text = unwrap_t2i(plan_gpt_image_2p5_params(&GenerateImageRequestBuilder { quality, ..base_builder() }));
assert_debug(text.quality, expected);
let edit = unwrap_edit(plan_gpt_image_2p5_params(&with_reference_image(GenerateImageRequestBuilder { quality, ..base_builder() })));
assert_debug(edit.quality, expected);
}
}
#[test]
fn resolution_maps_exhaustively_for_text_and_edit() {
let cases = [
(None, "None"),
(Some(RouterResolution::HalfK), "Some(OneK)"),
(Some(RouterResolution::FourEightyP), "Some(OneK)"),
(Some(RouterResolution::SevenTwentyP), "Some(OneK)"),
(Some(RouterResolution::OneK), "Some(OneK)"),
(Some(RouterResolution::TenEightyP), "Some(TwoK)"),
(Some(RouterResolution::TwoK), "Some(TwoK)"),
(Some(RouterResolution::ThreeK), "Some(ThreeK)"),
(Some(RouterResolution::FourK), "Some(FourK)"),
];
for (resolution, expected) in cases {
let text = unwrap_t2i(plan_gpt_image_2p5_params(&GenerateImageRequestBuilder { resolution, ..base_builder() }));
assert_debug(text.resolution, expected);
let edit = unwrap_edit(plan_gpt_image_2p5_params(&with_reference_image(GenerateImageRequestBuilder { resolution, ..base_builder() })));
assert_debug(edit.resolution, expected);
}
}
#[test]
fn aspect_ratio_maps_exhaustively_for_text_and_edit() {
let cases = [
(None, "None"),
(Some(RouterAspectRatio::Auto), "Some(Auto)"),
(Some(RouterAspectRatio::Auto2k), "Some(Auto)"),
(Some(RouterAspectRatio::Auto3k), "Some(Auto)"),
(Some(RouterAspectRatio::Auto4k), "Some(Auto)"),
(Some(RouterAspectRatio::Square), "Some(Square)"),
(Some(RouterAspectRatio::SquareHd), "Some(SquareHd)"),
(Some(RouterAspectRatio::WideThreeByTwo), "Some(Landscape16x9)"),
(Some(RouterAspectRatio::WideFourByThree), "Some(Landscape4x3)"),
(Some(RouterAspectRatio::WideFiveByFour), "Some(Landscape4x3)"),
(Some(RouterAspectRatio::WideSixteenByNine), "Some(Landscape16x9)"),
(Some(RouterAspectRatio::WideTwentyOneByNine), "Some(Landscape16x9)"),
(Some(RouterAspectRatio::Wide), "Some(Landscape16x9)"),
(Some(RouterAspectRatio::TallTwoByThree), "Some(Portrait16x9)"),
(Some(RouterAspectRatio::TallThreeByFour), "Some(Portrait4x3)"),
(Some(RouterAspectRatio::TallFourByFive), "Some(Portrait4x3)"),
(Some(RouterAspectRatio::TallNineBySixteen), "Some(Portrait16x9)"),
(Some(RouterAspectRatio::TallNineByTwentyOne), "Some(Portrait16x9)"),
(Some(RouterAspectRatio::Tall), "Some(Portrait16x9)"),
];
for (aspect_ratio, expected) in cases {
let text = unwrap_t2i(plan_gpt_image_2p5_params(&GenerateImageRequestBuilder { aspect_ratio, ..base_builder() }));
assert_debug(text.image_size, expected);
let edit = unwrap_edit(plan_gpt_image_2p5_params(&with_reference_image(GenerateImageRequestBuilder { aspect_ratio, ..base_builder() })));
assert_debug(edit.image_size, expected);
}
}
fn base_builder() -> GenerateImageRequestBuilder {
GenerateImageRequestBuilder {
model: RouterImageModel::GptImage2p5Flare,
provider: RouterProvider::Fal,
prompt: Some("a cat in space".to_string()),
image_inputs: None,
resolution: None,
aspect_ratio: None,
quality: None,
image_batch_count: None,
horizontal_angle: None,
vertical_angle: None,
zoom: None,
request_mismatch_mitigation_strategy: RequestMismatchMitigationStrategy::ErrorOut,
generation_mode_mismatch_strategy: None,
idempotency_token: None,
}
}
fn with_reference_image(builder: GenerateImageRequestBuilder) -> GenerateImageRequestBuilder {
GenerateImageRequestBuilder {
image_inputs: Some(ImageListRef::Urls(vec![IMAGE_URL.to_string()])),
..builder
}
}
fn unwrap_t2i(result: Result<PlannedGptImage2p5Params, ArtcraftRouterError>) -> GptImage2p5TextToImageParams {
match result.expect("plan should succeed") {
PlannedGptImage2p5Params::TextToImage(params) => params,
PlannedGptImage2p5Params::EditImage(_) => panic!("expected text-to-image"),
}
}
fn unwrap_edit(result: Result<PlannedGptImage2p5Params, ArtcraftRouterError>) -> GptImage2p5EditImageParams {
match result.expect("plan should succeed") {
PlannedGptImage2p5Params::EditImage(params) => params,
PlannedGptImage2p5Params::TextToImage(_) => panic!("expected edit-image"),
}
}
fn assert_debug<T: Debug>(actual: T, expected: &str) {
assert_eq!(format!("{:?}", actual), expected);
}
}
@@ -1,42 +0,0 @@
use std::fmt::Debug;
use std::sync::Arc;
use fal_client::requests::traits::fal_endpoint_trait::FalEndpoint;
use crate::client::router_fal_client::RouterFalClient;
use crate::errors::artcraft_router_error::ArtcraftRouterError;
use crate::generate::generate_image::generate_image_response::{FalImageResponsePayload, GenerateImageResponse};
/// Send any GPT Image 2.5 request (Flare or Sunburst, text-to-image or edit) to Fal, via
/// webhook when the client has one configured and via the queue otherwise.
pub async fn send_gpt_image_2p5_request<T>(
request: &T,
client: &RouterFalClient,
) -> Result<GenerateImageResponse, ArtcraftRouterError>
where
T: FalEndpoint + Clone + Debug + Send + Sync + 'static,
{
let outbound: Arc<dyn Debug + Send + Sync> = Arc::new(request.clone());
let payload = if let Some(webhook_url) = &client.webhook_url {
let response = request.send_webhook_request(&client.api_key, webhook_url).await?;
FalImageResponsePayload {
request_id: response.request_id,
gateway_request_id: response.gateway_request_id,
maybe_status_url: None,
maybe_response_url: None,
maybe_outbound_request: Some(outbound),
}
} else {
let response = request.send_queue_request(&client.api_key).await?;
FalImageResponsePayload {
request_id: Some(response.request_id),
gateway_request_id: None,
maybe_status_url: Some(response.status_url),
maybe_response_url: Some(response.response_url),
maybe_outbound_request: Some(outbound),
}
};
Ok(GenerateImageResponse::Fal(payload))
}
@@ -1,129 +0,0 @@
use fal_client::requests::api::image::edit::gpt_image_2p5_flare_edit_image::api::GptImage2p5FlareEditImageRequest;
use fal_client::requests::api::image::text::gpt_image_2p5_flare_text_to_image::api::GptImage2p5FlareTextToImageRequest;
use crate::errors::artcraft_router_error::ArtcraftRouterError;
use crate::generate::generate_image::generate_image_request_builder::GenerateImageRequestBuilder;
use crate::generate::generate_image::image_generation_draft_or_request::ImageGenerationDraftOrRequest;
use crate::generate::generate_image::image_generation_request::ImageGenerationRequest;
use crate::generate::generate_image::providers::fal::gpt_image_2p5_common::plan::{plan_gpt_image_2p5_params, PlannedGptImage2p5Params};
use crate::generate::generate_image::providers::fal::gpt_image_2p5_flare::request::FalGptImage2p5FlareRequestState;
/// Text-to-image and edit share one model entry; the mode is chosen by whether the builder
/// carries reference images. Planning is shared with the other GPT Image 2.5 variant.
pub fn build_fal_gpt_image_2p5_flare(
builder: GenerateImageRequestBuilder,
) -> Result<ImageGenerationDraftOrRequest, ArtcraftRouterError> {
let state = match plan_gpt_image_2p5_params(&builder)? {
PlannedGptImage2p5Params::TextToImage(params) => {
FalGptImage2p5FlareRequestState::TextToImage(GptImage2p5FlareTextToImageRequest { params })
}
PlannedGptImage2p5Params::EditImage(params) => {
FalGptImage2p5FlareRequestState::EditImage(GptImage2p5FlareEditImageRequest { params })
}
};
Ok(ImageGenerationDraftOrRequest::Request(
ImageGenerationRequest::FalGptImage2p5Flare(state),
))
}
#[cfg(test)]
mod tests {
use super::*;
use fal_client::requests::traits::fal_endpoint_trait::FalEndpoint;
use crate::api::image_list_ref::ImageListRef;
use crate::api::router_aspect_ratio::RouterAspectRatio;
use crate::api::router_image_model::RouterImageModel;
use crate::api::router_provider::RouterProvider;
use crate::api::router_quality::RouterQuality;
use crate::api::router_resolution::RouterResolution;
use crate::client::request_mismatch_mitigation_strategy::RequestMismatchMitigationStrategy;
#[test]
fn build2_routes_to_flare_text_to_image() {
let request = unwrap_t2i(base_builder().build2());
assert_eq!(request.params.prompt, "a cat in space");
assert_eq!(GptImage2p5FlareTextToImageRequest::ENDPOINT, "openai/gpt-image-2.5/flare/text-to-image");
}
#[test]
fn build2_routes_to_flare_edit_when_reference_images_present() {
let request = unwrap_edit(GenerateImageRequestBuilder {
image_inputs: Some(ImageListRef::Urls(vec!["https://example.com/img.jpg".to_string()])),
..base_builder()
}.build2());
assert_eq!(request.params.image_urls, vec!["https://example.com/img.jpg"]);
assert_eq!(GptImage2p5FlareEditImageRequest::ENDPOINT, "openai/gpt-image-2.5/flare/edit");
}
#[test]
fn planned_fields_reach_the_fal_request() {
let request = unwrap_t2i(GenerateImageRequestBuilder {
aspect_ratio: Some(RouterAspectRatio::WideSixteenByNine),
resolution: Some(RouterResolution::TwoK),
quality: Some(RouterQuality::Medium),
image_batch_count: Some(3),
..base_builder()
}.build2());
assert_eq!(format!("{:?}", request.params.image_size), "Some(Landscape16x9)");
assert_eq!(format!("{:?}", request.params.resolution), "Some(TwoK)");
assert_eq!(format!("{:?}", request.params.quality), "Some(Medium)");
assert_eq!(format!("{:?}", request.params.num_images), "Three");
}
#[test]
fn raw_wire_request_matches_fal_schema() {
let request = unwrap_t2i(GenerateImageRequestBuilder {
aspect_ratio: Some(RouterAspectRatio::Square),
quality: Some(RouterQuality::High),
image_batch_count: Some(2),
..base_builder()
}.build2());
let json = serde_json::to_value(request.to_raw_request().unwrap()).unwrap();
assert_eq!(json, serde_json::json!({
"prompt": "a cat in space",
"image_size": "square",
"quality": "high",
"num_images": 2,
"output_format": "png",
}));
}
fn base_builder() -> GenerateImageRequestBuilder {
GenerateImageRequestBuilder {
model: RouterImageModel::GptImage2p5Flare,
provider: RouterProvider::Fal,
prompt: Some("a cat in space".to_string()),
image_inputs: None,
resolution: None,
aspect_ratio: None,
quality: None,
image_batch_count: None,
horizontal_angle: None,
vertical_angle: None,
zoom: None,
request_mismatch_mitigation_strategy: RequestMismatchMitigationStrategy::ErrorOut,
generation_mode_mismatch_strategy: None,
idempotency_token: None,
}
}
fn unwrap_t2i(result: Result<ImageGenerationDraftOrRequest, ArtcraftRouterError>) -> GptImage2p5FlareTextToImageRequest {
let ImageGenerationDraftOrRequest::Request(
ImageGenerationRequest::FalGptImage2p5Flare(FalGptImage2p5FlareRequestState::TextToImage(request))
) = result.expect("build should succeed") else {
panic!("expected GPT Image 2.5 Flare text-to-image request")
};
request
}
fn unwrap_edit(result: Result<ImageGenerationDraftOrRequest, ArtcraftRouterError>) -> GptImage2p5FlareEditImageRequest {
let ImageGenerationDraftOrRequest::Request(
ImageGenerationRequest::FalGptImage2p5Flare(FalGptImage2p5FlareRequestState::EditImage(request))
) = result.expect("build should succeed") else {
panic!("expected GPT Image 2.5 Flare edit-image request")
};
request
}
}
@@ -1,133 +0,0 @@
use fal_client::requests::traits::fal_request_cost_calculator_trait::FalRequestCostCalculator;
use crate::generate::generate_image::image_generation_cost_estimate::ImageGenerationCostEstimate;
use crate::generate::generate_image::providers::fal::gpt_image_2p5_flare::request::FalGptImage2p5FlareRequestState;
/// Cost state for Fal GPT Image 2.5 Flare. Delegates to `fal_client`'s calculator, which
/// prices by output dimensions (aspect ratio and resolution tier), quality, batch size and,
/// for edits, the number of reference images.
#[derive(Clone, Debug)]
pub struct FalGptImage2p5FlareCostState {
cost_in_usd_cents: u64,
}
impl FalGptImage2p5FlareCostState {
pub fn from_request(request: &FalGptImage2p5FlareRequestState) -> Self {
let cost_in_usd_cents = match request {
FalGptImage2p5FlareRequestState::TextToImage(request) => request.calculate_cost_in_cents(),
FalGptImage2p5FlareRequestState::EditImage(request) => request.calculate_cost_in_cents(),
};
Self { cost_in_usd_cents }
}
pub fn estimate_cost(&self) -> ImageGenerationCostEstimate {
ImageGenerationCostEstimate {
cost_in_credits: Some(self.cost_in_usd_cents),
cost_in_usd_cents: Some(self.cost_in_usd_cents),
is_free: false,
is_unlimited: false,
is_rate_limited: false,
has_watermark: false,
failures_are_refunded: None,
}
}
}
#[cfg(test)]
mod tests {
use crate::api::image_list_ref::ImageListRef;
use crate::api::router_aspect_ratio::RouterAspectRatio;
use crate::api::router_image_model::RouterImageModel;
use crate::api::router_provider::RouterProvider;
use crate::api::router_quality::RouterQuality;
use crate::api::router_resolution::RouterResolution;
use crate::client::request_mismatch_mitigation_strategy::RequestMismatchMitigationStrategy;
use crate::generate::generate_image::generate_image_request_builder::GenerateImageRequestBuilder;
use RouterAspectRatio as Ar;
use RouterQuality as Q;
use RouterResolution as R;
// (quality, aspect_ratio, resolution, batch, expected_cents) — text-to-image
const TEXT_CASES: &[(Option<Q>, Option<Ar>, Option<R>, u16, u64)] = &[
(None, None, None, 1, 4), // Fal default: landscape_4_3, high
(Some(Q::Low), Some(Ar::Square), None, 1, 1),
(Some(Q::Medium), Some(Ar::Square), None, 1, 2),
(Some(Q::High), Some(Ar::Square), None, 1, 6),
(Some(Q::High), Some(Ar::Square), None, 4, 24),
(Some(Q::High), Some(Ar::SquareHd), None, 1, 9),
(Some(Q::High), Some(Ar::Square), Some(R::TwoK), 1, 9),
(Some(Q::High), Some(Ar::Square), Some(R::FourK), 1, 13),
(Some(Q::High), Some(Ar::WideFourByThree), None, 1, 4),
(Some(Q::High), Some(Ar::TallThreeByFour), None, 1, 4),
(Some(Q::High), Some(Ar::WideSixteenByNine), None, 1, 4),
(Some(Q::High), Some(Ar::WideSixteenByNine), Some(R::OneK), 1, 3),
(Some(Q::High), Some(Ar::WideSixteenByNine), Some(R::FourK), 1, 11),
(Some(Q::Medium), Some(Ar::TallNineBySixteen), Some(R::ThreeK), 2, 4),
(Some(Q::High), Some(Ar::Auto), None, 1, 11),
(Some(Q::High), Some(Ar::Auto4k), None, 1, 11),
];
// (reference_images, quality, aspect_ratio, resolution, batch, expected_cents) — edit
const EDIT_CASES: &[(usize, Option<Q>, Option<Ar>, Option<R>, u16, u64)] = &[
(1, None, None, None, 1, 11), // Fal default: auto, high
(1, Some(Q::Low), Some(Ar::Square), None, 1, 2),
(1, Some(Q::High), Some(Ar::Square), None, 1, 7),
(3, Some(Q::High), Some(Ar::Square), None, 1, 8),
(1, Some(Q::High), Some(Ar::Square), None, 4, 28),
(1, Some(Q::High), Some(Ar::WideSixteenByNine), Some(R::FourK), 1, 11),
(2, Some(Q::High), Some(Ar::Auto), None, 1, 12),
];
#[test]
fn text_to_image_costs() {
for &(quality, aspect_ratio, resolution, batch, expected) in TEXT_CASES {
assert_eq!(cost_cents(0, quality, aspect_ratio, resolution, batch), expected, "{quality:?} {aspect_ratio:?} {resolution:?} x{batch}");
}
}
#[test]
fn edit_image_costs() {
for &(refs, quality, aspect_ratio, resolution, batch, expected) in EDIT_CASES {
assert_eq!(cost_cents(refs, quality, aspect_ratio, resolution, batch), expected, "{refs} refs {quality:?} {aspect_ratio:?} {resolution:?} x{batch}");
}
}
#[test]
fn estimate_flags() {
let cost = builder(0, Some(Q::High), Some(Ar::Square), None, 1).build2().unwrap().estimate_cost().unwrap();
assert_eq!(cost.cost_in_credits, cost.cost_in_usd_cents);
assert!(!cost.is_free);
assert!(!cost.is_unlimited);
assert!(!cost.is_rate_limited);
assert!(!cost.has_watermark);
}
fn cost_cents(refs: usize, quality: Option<Q>, aspect_ratio: Option<Ar>, resolution: Option<R>, batch: u16) -> u64 {
builder(refs, quality, aspect_ratio, resolution, batch)
.build2().unwrap().estimate_cost().unwrap().cost_in_usd_cents.unwrap()
}
fn builder(refs: usize, quality: Option<Q>, aspect_ratio: Option<Ar>, resolution: Option<R>, batch: u16) -> GenerateImageRequestBuilder {
let image_inputs = if refs == 0 {
None
} else {
Some(ImageListRef::Urls(vec!["https://example.com/img.jpg".to_string(); refs]))
};
GenerateImageRequestBuilder {
model: RouterImageModel::GptImage2p5Flare,
provider: RouterProvider::Fal,
prompt: Some("a cat in space".to_string()),
image_inputs,
resolution,
aspect_ratio,
quality,
image_batch_count: Some(batch),
horizontal_angle: None,
vertical_angle: None,
zoom: None,
request_mismatch_mitigation_strategy: RequestMismatchMitigationStrategy::ErrorOut,
generation_mode_mismatch_strategy: None,
idempotency_token: None,
}
}
}
@@ -1,3 +0,0 @@
pub mod build;
pub mod cost;
pub mod request;
@@ -1,86 +0,0 @@
use fal_client::requests::api::image::edit::gpt_image_2p5_flare_edit_image::api::GptImage2p5FlareEditImageRequest;
use fal_client::requests::api::image::text::gpt_image_2p5_flare_text_to_image::api::GptImage2p5FlareTextToImageRequest;
use crate::client::router_fal_client::RouterFalClient;
use crate::errors::artcraft_router_error::ArtcraftRouterError;
use crate::generate::generate_image::generate_image_response::GenerateImageResponse;
use crate::generate::generate_image::providers::fal::gpt_image_2p5_common::send::send_gpt_image_2p5_request;
#[derive(Clone, Debug)]
pub enum FalGptImage2p5FlareRequestState {
TextToImage(GptImage2p5FlareTextToImageRequest),
EditImage(GptImage2p5FlareEditImageRequest),
}
impl FalGptImage2p5FlareRequestState {
pub async fn send(&self, client: &RouterFalClient) -> Result<GenerateImageResponse, ArtcraftRouterError> {
match self {
Self::TextToImage(request) => send_gpt_image_2p5_request(request, client).await,
Self::EditImage(request) => send_gpt_image_2p5_request(request, client).await,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use fal_client::creds::fal_api_key::FalApiKey;
use fal_client::requests::api::image::common::gpt_image_2_resolution::GptImage2Resolution;
use fal_client::requests::api::image::common::gpt_image_2p5::gpt_image_2p5_edit_image_params::GptImage2p5EditImageParams;
use fal_client::requests::api::image::common::gpt_image_2p5::gpt_image_2p5_image_size::GptImage2p5ImageSize;
use fal_client::requests::api::image::common::gpt_image_2p5::gpt_image_2p5_num_images::GptImage2p5NumImages;
use fal_client::requests::api::image::common::gpt_image_2p5::gpt_image_2p5_quality::GptImage2p5Quality;
use fal_client::requests::api::image::common::gpt_image_2p5::gpt_image_2p5_text_to_image_params::GptImage2p5TextToImageParams;
use test_data::web::image_urls::JUNO_AT_LAKE_IMAGE_URL;
#[tokio::test]
#[ignore] // requires real API key, incurs cost
async fn send_text_to_image_webhook() {
let request = FalGptImage2p5FlareRequestState::TextToImage(GptImage2p5FlareTextToImageRequest {
params: GptImage2p5TextToImageParams {
prompt: "a polished product photo of a glass compass".to_string(),
num_images: GptImage2p5NumImages::One,
image_size: Some(GptImage2p5ImageSize::Square),
resolution: Some(GptImage2Resolution::OneK),
quality: Some(GptImage2p5Quality::Low),
background: None,
output_format: None,
output_compression: None,
},
});
let response = request.send(&client_with_webhook()).await.expect("send should succeed");
let payload = response.get_fal_payload().expect("expected Fal payload");
assert!(payload.request_id.is_some() || payload.gateway_request_id.is_some());
}
#[tokio::test]
#[ignore] // requires real API key, incurs cost
async fn send_edit_image_webhook() {
let request = FalGptImage2p5FlareRequestState::EditImage(GptImage2p5FlareEditImageRequest {
params: GptImage2p5EditImageParams {
prompt: "make this look like an elegant magazine cover image".to_string(),
image_urls: vec![JUNO_AT_LAKE_IMAGE_URL.to_string()],
mask_url: None,
num_images: GptImage2p5NumImages::One,
image_size: Some(GptImage2p5ImageSize::Square),
resolution: Some(GptImage2Resolution::OneK),
quality: Some(GptImage2p5Quality::Low),
background: None,
output_format: None,
output_compression: None,
},
});
let response = request.send(&client_with_webhook()).await.expect("send should succeed");
let payload = response.get_fal_payload().expect("expected Fal payload");
assert!(payload.request_id.is_some() || payload.gateway_request_id.is_some());
}
fn client_with_webhook() -> RouterFalClient {
let secret = std::fs::read_to_string("/Users/bt/Artcraft/credentials/fal_api_key.txt")
.expect("Failed to read fal_api_key.txt");
RouterFalClient::new_with_webhook(
FalApiKey::from_str(secret.trim()),
"https://example.com/fal-webhook-test".to_string(),
)
}
}
@@ -1,129 +0,0 @@
use fal_client::requests::api::image::edit::gpt_image_2p5_sunburst_edit_image::api::GptImage2p5SunburstEditImageRequest;
use fal_client::requests::api::image::text::gpt_image_2p5_sunburst_text_to_image::api::GptImage2p5SunburstTextToImageRequest;
use crate::errors::artcraft_router_error::ArtcraftRouterError;
use crate::generate::generate_image::generate_image_request_builder::GenerateImageRequestBuilder;
use crate::generate::generate_image::image_generation_draft_or_request::ImageGenerationDraftOrRequest;
use crate::generate::generate_image::image_generation_request::ImageGenerationRequest;
use crate::generate::generate_image::providers::fal::gpt_image_2p5_common::plan::{plan_gpt_image_2p5_params, PlannedGptImage2p5Params};
use crate::generate::generate_image::providers::fal::gpt_image_2p5_sunburst::request::FalGptImage2p5SunburstRequestState;
/// Text-to-image and edit share one model entry; the mode is chosen by whether the builder
/// carries reference images. Planning is shared with the other GPT Image 2.5 variant.
pub fn build_fal_gpt_image_2p5_sunburst(
builder: GenerateImageRequestBuilder,
) -> Result<ImageGenerationDraftOrRequest, ArtcraftRouterError> {
let state = match plan_gpt_image_2p5_params(&builder)? {
PlannedGptImage2p5Params::TextToImage(params) => {
FalGptImage2p5SunburstRequestState::TextToImage(GptImage2p5SunburstTextToImageRequest { params })
}
PlannedGptImage2p5Params::EditImage(params) => {
FalGptImage2p5SunburstRequestState::EditImage(GptImage2p5SunburstEditImageRequest { params })
}
};
Ok(ImageGenerationDraftOrRequest::Request(
ImageGenerationRequest::FalGptImage2p5Sunburst(state),
))
}
#[cfg(test)]
mod tests {
use super::*;
use fal_client::requests::traits::fal_endpoint_trait::FalEndpoint;
use crate::api::image_list_ref::ImageListRef;
use crate::api::router_aspect_ratio::RouterAspectRatio;
use crate::api::router_image_model::RouterImageModel;
use crate::api::router_provider::RouterProvider;
use crate::api::router_quality::RouterQuality;
use crate::api::router_resolution::RouterResolution;
use crate::client::request_mismatch_mitigation_strategy::RequestMismatchMitigationStrategy;
#[test]
fn build2_routes_to_sunburst_text_to_image() {
let request = unwrap_t2i(base_builder().build2());
assert_eq!(request.params.prompt, "a cat in space");
assert_eq!(GptImage2p5SunburstTextToImageRequest::ENDPOINT, "openai/gpt-image-2.5/sunburst/text-to-image");
}
#[test]
fn build2_routes_to_sunburst_edit_when_reference_images_present() {
let request = unwrap_edit(GenerateImageRequestBuilder {
image_inputs: Some(ImageListRef::Urls(vec!["https://example.com/img.jpg".to_string()])),
..base_builder()
}.build2());
assert_eq!(request.params.image_urls, vec!["https://example.com/img.jpg"]);
assert_eq!(GptImage2p5SunburstEditImageRequest::ENDPOINT, "openai/gpt-image-2.5/sunburst/edit");
}
#[test]
fn planned_fields_reach_the_fal_request() {
let request = unwrap_t2i(GenerateImageRequestBuilder {
aspect_ratio: Some(RouterAspectRatio::WideSixteenByNine),
resolution: Some(RouterResolution::TwoK),
quality: Some(RouterQuality::Medium),
image_batch_count: Some(3),
..base_builder()
}.build2());
assert_eq!(format!("{:?}", request.params.image_size), "Some(Landscape16x9)");
assert_eq!(format!("{:?}", request.params.resolution), "Some(TwoK)");
assert_eq!(format!("{:?}", request.params.quality), "Some(Medium)");
assert_eq!(format!("{:?}", request.params.num_images), "Three");
}
#[test]
fn raw_wire_request_matches_fal_schema() {
let request = unwrap_t2i(GenerateImageRequestBuilder {
aspect_ratio: Some(RouterAspectRatio::Square),
quality: Some(RouterQuality::High),
image_batch_count: Some(2),
..base_builder()
}.build2());
let json = serde_json::to_value(request.to_raw_request().unwrap()).unwrap();
assert_eq!(json, serde_json::json!({
"prompt": "a cat in space",
"image_size": "square",
"quality": "high",
"num_images": 2,
"output_format": "png",
}));
}
fn base_builder() -> GenerateImageRequestBuilder {
GenerateImageRequestBuilder {
model: RouterImageModel::GptImage2p5Sunburst,
provider: RouterProvider::Fal,
prompt: Some("a cat in space".to_string()),
image_inputs: None,
resolution: None,
aspect_ratio: None,
quality: None,
image_batch_count: None,
horizontal_angle: None,
vertical_angle: None,
zoom: None,
request_mismatch_mitigation_strategy: RequestMismatchMitigationStrategy::ErrorOut,
generation_mode_mismatch_strategy: None,
idempotency_token: None,
}
}
fn unwrap_t2i(result: Result<ImageGenerationDraftOrRequest, ArtcraftRouterError>) -> GptImage2p5SunburstTextToImageRequest {
let ImageGenerationDraftOrRequest::Request(
ImageGenerationRequest::FalGptImage2p5Sunburst(FalGptImage2p5SunburstRequestState::TextToImage(request))
) = result.expect("build should succeed") else {
panic!("expected GPT Image 2.5 Sunburst text-to-image request")
};
request
}
fn unwrap_edit(result: Result<ImageGenerationDraftOrRequest, ArtcraftRouterError>) -> GptImage2p5SunburstEditImageRequest {
let ImageGenerationDraftOrRequest::Request(
ImageGenerationRequest::FalGptImage2p5Sunburst(FalGptImage2p5SunburstRequestState::EditImage(request))
) = result.expect("build should succeed") else {
panic!("expected GPT Image 2.5 Sunburst edit-image request")
};
request
}
}
@@ -1,133 +0,0 @@
use fal_client::requests::traits::fal_request_cost_calculator_trait::FalRequestCostCalculator;
use crate::generate::generate_image::image_generation_cost_estimate::ImageGenerationCostEstimate;
use crate::generate::generate_image::providers::fal::gpt_image_2p5_sunburst::request::FalGptImage2p5SunburstRequestState;
/// Cost state for Fal GPT Image 2.5 Sunburst. Delegates to `fal_client`'s calculator, which
/// prices by output dimensions (aspect ratio and resolution tier), quality, batch size and,
/// for edits, the number of reference images.
#[derive(Clone, Debug)]
pub struct FalGptImage2p5SunburstCostState {
cost_in_usd_cents: u64,
}
impl FalGptImage2p5SunburstCostState {
pub fn from_request(request: &FalGptImage2p5SunburstRequestState) -> Self {
let cost_in_usd_cents = match request {
FalGptImage2p5SunburstRequestState::TextToImage(request) => request.calculate_cost_in_cents(),
FalGptImage2p5SunburstRequestState::EditImage(request) => request.calculate_cost_in_cents(),
};
Self { cost_in_usd_cents }
}
pub fn estimate_cost(&self) -> ImageGenerationCostEstimate {
ImageGenerationCostEstimate {
cost_in_credits: Some(self.cost_in_usd_cents),
cost_in_usd_cents: Some(self.cost_in_usd_cents),
is_free: false,
is_unlimited: false,
is_rate_limited: false,
has_watermark: false,
failures_are_refunded: None,
}
}
}
#[cfg(test)]
mod tests {
use crate::api::image_list_ref::ImageListRef;
use crate::api::router_aspect_ratio::RouterAspectRatio;
use crate::api::router_image_model::RouterImageModel;
use crate::api::router_provider::RouterProvider;
use crate::api::router_quality::RouterQuality;
use crate::api::router_resolution::RouterResolution;
use crate::client::request_mismatch_mitigation_strategy::RequestMismatchMitigationStrategy;
use crate::generate::generate_image::generate_image_request_builder::GenerateImageRequestBuilder;
use RouterAspectRatio as Ar;
use RouterQuality as Q;
use RouterResolution as R;
// (quality, aspect_ratio, resolution, batch, expected_cents) — text-to-image
const TEXT_CASES: &[(Option<Q>, Option<Ar>, Option<R>, u16, u64)] = &[
(None, None, None, 1, 4), // Fal default: landscape_4_3, high
(Some(Q::Low), Some(Ar::Square), None, 1, 1),
(Some(Q::Medium), Some(Ar::Square), None, 1, 2),
(Some(Q::High), Some(Ar::Square), None, 1, 6),
(Some(Q::High), Some(Ar::Square), None, 4, 24),
(Some(Q::High), Some(Ar::SquareHd), None, 1, 9),
(Some(Q::High), Some(Ar::Square), Some(R::TwoK), 1, 9),
(Some(Q::High), Some(Ar::Square), Some(R::FourK), 1, 13),
(Some(Q::High), Some(Ar::WideFourByThree), None, 1, 4),
(Some(Q::High), Some(Ar::TallThreeByFour), None, 1, 4),
(Some(Q::High), Some(Ar::WideSixteenByNine), None, 1, 4),
(Some(Q::High), Some(Ar::WideSixteenByNine), Some(R::OneK), 1, 3),
(Some(Q::High), Some(Ar::WideSixteenByNine), Some(R::FourK), 1, 11),
(Some(Q::Medium), Some(Ar::TallNineBySixteen), Some(R::ThreeK), 2, 4),
(Some(Q::High), Some(Ar::Auto), None, 1, 11),
(Some(Q::High), Some(Ar::Auto4k), None, 1, 11),
];
// (reference_images, quality, aspect_ratio, resolution, batch, expected_cents) — edit
const EDIT_CASES: &[(usize, Option<Q>, Option<Ar>, Option<R>, u16, u64)] = &[
(1, None, None, None, 1, 11), // Fal default: auto, high
(1, Some(Q::Low), Some(Ar::Square), None, 1, 2),
(1, Some(Q::High), Some(Ar::Square), None, 1, 7),
(3, Some(Q::High), Some(Ar::Square), None, 1, 8),
(1, Some(Q::High), Some(Ar::Square), None, 4, 28),
(1, Some(Q::High), Some(Ar::WideSixteenByNine), Some(R::FourK), 1, 11),
(2, Some(Q::High), Some(Ar::Auto), None, 1, 12),
];
#[test]
fn text_to_image_costs() {
for &(quality, aspect_ratio, resolution, batch, expected) in TEXT_CASES {
assert_eq!(cost_cents(0, quality, aspect_ratio, resolution, batch), expected, "{quality:?} {aspect_ratio:?} {resolution:?} x{batch}");
}
}
#[test]
fn edit_image_costs() {
for &(refs, quality, aspect_ratio, resolution, batch, expected) in EDIT_CASES {
assert_eq!(cost_cents(refs, quality, aspect_ratio, resolution, batch), expected, "{refs} refs {quality:?} {aspect_ratio:?} {resolution:?} x{batch}");
}
}
#[test]
fn estimate_flags() {
let cost = builder(0, Some(Q::High), Some(Ar::Square), None, 1).build2().unwrap().estimate_cost().unwrap();
assert_eq!(cost.cost_in_credits, cost.cost_in_usd_cents);
assert!(!cost.is_free);
assert!(!cost.is_unlimited);
assert!(!cost.is_rate_limited);
assert!(!cost.has_watermark);
}
fn cost_cents(refs: usize, quality: Option<Q>, aspect_ratio: Option<Ar>, resolution: Option<R>, batch: u16) -> u64 {
builder(refs, quality, aspect_ratio, resolution, batch)
.build2().unwrap().estimate_cost().unwrap().cost_in_usd_cents.unwrap()
}
fn builder(refs: usize, quality: Option<Q>, aspect_ratio: Option<Ar>, resolution: Option<R>, batch: u16) -> GenerateImageRequestBuilder {
let image_inputs = if refs == 0 {
None
} else {
Some(ImageListRef::Urls(vec!["https://example.com/img.jpg".to_string(); refs]))
};
GenerateImageRequestBuilder {
model: RouterImageModel::GptImage2p5Sunburst,
provider: RouterProvider::Fal,
prompt: Some("a cat in space".to_string()),
image_inputs,
resolution,
aspect_ratio,
quality,
image_batch_count: Some(batch),
horizontal_angle: None,
vertical_angle: None,
zoom: None,
request_mismatch_mitigation_strategy: RequestMismatchMitigationStrategy::ErrorOut,
generation_mode_mismatch_strategy: None,
idempotency_token: None,
}
}
}
@@ -1,3 +0,0 @@
pub mod build;
pub mod cost;
pub mod request;
@@ -1,86 +0,0 @@
use fal_client::requests::api::image::edit::gpt_image_2p5_sunburst_edit_image::api::GptImage2p5SunburstEditImageRequest;
use fal_client::requests::api::image::text::gpt_image_2p5_sunburst_text_to_image::api::GptImage2p5SunburstTextToImageRequest;
use crate::client::router_fal_client::RouterFalClient;
use crate::errors::artcraft_router_error::ArtcraftRouterError;
use crate::generate::generate_image::generate_image_response::GenerateImageResponse;
use crate::generate::generate_image::providers::fal::gpt_image_2p5_common::send::send_gpt_image_2p5_request;
#[derive(Clone, Debug)]
pub enum FalGptImage2p5SunburstRequestState {
TextToImage(GptImage2p5SunburstTextToImageRequest),
EditImage(GptImage2p5SunburstEditImageRequest),
}
impl FalGptImage2p5SunburstRequestState {
pub async fn send(&self, client: &RouterFalClient) -> Result<GenerateImageResponse, ArtcraftRouterError> {
match self {
Self::TextToImage(request) => send_gpt_image_2p5_request(request, client).await,
Self::EditImage(request) => send_gpt_image_2p5_request(request, client).await,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use fal_client::creds::fal_api_key::FalApiKey;
use fal_client::requests::api::image::common::gpt_image_2_resolution::GptImage2Resolution;
use fal_client::requests::api::image::common::gpt_image_2p5::gpt_image_2p5_edit_image_params::GptImage2p5EditImageParams;
use fal_client::requests::api::image::common::gpt_image_2p5::gpt_image_2p5_image_size::GptImage2p5ImageSize;
use fal_client::requests::api::image::common::gpt_image_2p5::gpt_image_2p5_num_images::GptImage2p5NumImages;
use fal_client::requests::api::image::common::gpt_image_2p5::gpt_image_2p5_quality::GptImage2p5Quality;
use fal_client::requests::api::image::common::gpt_image_2p5::gpt_image_2p5_text_to_image_params::GptImage2p5TextToImageParams;
use test_data::web::image_urls::JUNO_AT_LAKE_IMAGE_URL;
#[tokio::test]
#[ignore] // requires real API key, incurs cost
async fn send_text_to_image_webhook() {
let request = FalGptImage2p5SunburstRequestState::TextToImage(GptImage2p5SunburstTextToImageRequest {
params: GptImage2p5TextToImageParams {
prompt: "a polished product photo of a glass compass".to_string(),
num_images: GptImage2p5NumImages::One,
image_size: Some(GptImage2p5ImageSize::Square),
resolution: Some(GptImage2Resolution::OneK),
quality: Some(GptImage2p5Quality::Low),
background: None,
output_format: None,
output_compression: None,
},
});
let response = request.send(&client_with_webhook()).await.expect("send should succeed");
let payload = response.get_fal_payload().expect("expected Fal payload");
assert!(payload.request_id.is_some() || payload.gateway_request_id.is_some());
}
#[tokio::test]
#[ignore] // requires real API key, incurs cost
async fn send_edit_image_webhook() {
let request = FalGptImage2p5SunburstRequestState::EditImage(GptImage2p5SunburstEditImageRequest {
params: GptImage2p5EditImageParams {
prompt: "make this look like an elegant magazine cover image".to_string(),
image_urls: vec![JUNO_AT_LAKE_IMAGE_URL.to_string()],
mask_url: None,
num_images: GptImage2p5NumImages::One,
image_size: Some(GptImage2p5ImageSize::Square),
resolution: Some(GptImage2Resolution::OneK),
quality: Some(GptImage2p5Quality::Low),
background: None,
output_format: None,
output_compression: None,
},
});
let response = request.send(&client_with_webhook()).await.expect("send should succeed");
let payload = response.get_fal_payload().expect("expected Fal payload");
assert!(payload.request_id.is_some() || payload.gateway_request_id.is_some());
}
fn client_with_webhook() -> RouterFalClient {
let secret = std::fs::read_to_string("/Users/bt/Artcraft/credentials/fal_api_key.txt")
.expect("Failed to read fal_api_key.txt");
RouterFalClient::new_with_webhook(
FalApiKey::from_str(secret.trim()),
"https://example.com/fal-webhook-test".to_string(),
)
}
}
@@ -6,9 +6,6 @@ pub mod flux_pro_1p1_ultra;
pub mod gpt_image_1;
pub mod gpt_image_1p5;
pub mod gpt_image_2;
pub mod gpt_image_2p5_common;
pub mod gpt_image_2p5_flare;
pub mod gpt_image_2p5_sunburst;
pub mod nano_banana;
pub mod nano_banana_2;
pub mod nano_banana_pro;
@@ -1,127 +0,0 @@
# generate_video
This module implements the v2 video generation pipeline. It replaces the v1 system
(in `generate_video/`) with a two-phase approach that separates request planning from
execution, allowing cost estimation and media uploads to happen at the right time.
## Lifecycle
```
GenerateVideoRequestBuilder
│
▼ build2()
VideoGenerationDraftOrRequest
│
├─ Draft(VideoGenerationDraftRequest)
│ │
│ ▼ estimate_cost() ← cost estimate from draft state
│ │
│ ▼ finalize(context) ← uploads media, resolves tokens
│ │
│ ▼
│ VideoGenerationRequest
│ │
│ ▼ estimate_cost() ← cost estimate from finalized request
│ │
│ ▼ send_request() ← fires the API call
│ │
│ ▼
│ GenerateVideoResponse
│
└─ Request(VideoGenerationRequest) ← skips draft phase (used by Artcraft provider)
```
### Key types
- **`GenerateVideoRequestBuilder`** — generic builder with provider/model/prompt/resolution/etc.
Located in `generate_video/generate_video_request_builder.rs`. The `use_new_builder()` method
gates which provider+model combos use the v2 path. `build2()` dispatches to the correct
provider's build function.
- **`VideoGenerationDraftOrRequest`** — the output of `build2()`. Either `Draft` (for providers
that need media upload/resolution, like Kinovi) or `Request` (for providers that work with
media file tokens directly, like Artcraft).
- **`VideoGenerationDraftRequest`** — enum with one variant per provider+model. Holds
materialized settings (resolution, duration, batch count) plus unresolved media references.
Can estimate cost without network calls.
- **`VideoGenerationDraftContext`** — context needed during `finalize()`: the provider client,
media file token-to-URL map, and character token-to-ID map.
- **`VideoGenerationRequest`** — enum with one variant per provider+model. Holds a fully
materialized request ready to send. All media URLs are resolved and uploaded.
### Cost estimation
Cost can be estimated at two stages:
1. **From draft** — before `finalize()`. Uses the planned resolution/duration/batch count.
Good for showing the user a price before committing.
2. **From request** — after `finalize()`. Uses the final materialized request. Should match
the draft estimate for the same parameters.
## Module layout
```
generate_video/
├── mod.rs
├── video_generation_draft.rs ← VideoGenerationDraftRequest enum
├── video_generation_draft_context.rs ← context for finalize()
├── video_generation_draft_or_request.rs
├── video_generation_request.rs ← VideoGenerationRequest enum
└── providers/
├── artcraft/ ← Artcraft provider (uses media file tokens directly)
│ ├── seedance_2p0/ ← Seedance 2.0 Pro model (skips draft, returns Request directly)
│ │ ├── mod.rs
│ │ ├── build.rs ← builder → Request conversion + plan helpers
│ │ ├── cost.rs ← standalone cost estimation (independent of kinovi_web_client)
│ │ └── request.rs ← request state + send() via Artcraft multi-function API
│ └── seedance_2p0_fast/ ← Seedance 2.0 Fast model (skips draft, 480p/720p only)
│ ├── mod.rs
│ ├── build.rs ← builder → Request conversion + plan helpers (no 1080p)
│ ├── cost.rs ← standalone cost estimation with Fast-specific pricing
│ └── request.rs ← request state + send() via Artcraft omni-gen API
└── kinovi/ ← Kinovi/KinoviWeb provider
├── mod.rs
├── resolve.rs ← shared: media token resolution, upload helpers
├── upload.rs ← shared: download + re-upload to KinoviWeb CDN
├── seedance_2p0/ ← Seedance 2.0 Pro model
│ ├── mod.rs
│ ├── build.rs ← builder → draft conversion + plan helpers
│ ├── cost.rs ← cost estimation state
│ ├── draft.rs ← draft state + finalize (to_request)
│ └── request.rs ← request state + send()
└── seedance_2p0_fast/ ← Seedance 2.0 Fast model
├── mod.rs
├── build.rs
├── cost.rs
├── draft.rs
└── request.rs
```
## Adding a new provider or model
1. **Create the module** under `providers/{provider}/{model}/` with these files:
- `mod.rs` — declares sub-modules
- `build.rs` — `build_{provider}_{model}(builder) -> VideoGenerationDraftOrRequest`.
Contains `plan_*` helpers for aspect ratio, resolution, batch count, duration.
- `draft.rs` — draft state struct with `to_request()` async method for finalization.
**Not needed** if the provider uses media tokens directly (no upload/resolution needed);
in that case `build.rs` returns `VideoGenerationDraftOrRequest::Request(...)` directly.
- `cost.rs` — cost state with `from_request()` and `estimate_cost()`. Add `from_draft()`
if the provider uses the draft phase.
- `request.rs` — request state with `send()` async method.
2. **Register the module** in the parent provider's `mod.rs`.
3. **Add enum variants** in:
- `video_generation_draft.rs` — `VideoGenerationDraftRequest` enum + `estimate_cost` + `finalize`
(skip if provider has no draft phase)
- `video_generation_request.rs` — `VideoGenerationRequest` enum + `estimate_cost` + `send_request`
4. **Wire into the builder** in `generate_video_request_builder.rs`:
- Add the `(Provider, Model)` pair to `use_new_builder()` returning `true`
- Add the dispatch arm in `build2()`
5. **Tests**: each `build.rs` and `cost.rs` should have comprehensive tests. `request.rs`
should have `#[ignore]` live API tests for manual verification.
@@ -0,0 +1,127 @@
# generate_video
This module implements the v2 video generation pipeline. It replaces the v1 system
(in `generate_video/`) with a two-phase approach that separates request planning from
execution, allowing cost estimation and media uploads to happen at the right time.
## Lifecycle
```
GenerateVideoRequestBuilder
│
▼ build2()
VideoGenerationDraftOrRequest
│
├─ Draft(VideoGenerationDraftRequest)
│ │
│ ▼ estimate_cost() ← cost estimate from draft state
│ │
│ ▼ finalize(context) ← uploads media, resolves tokens
│ │
│ ▼
│ VideoGenerationRequest
│ │
│ ▼ estimate_cost() ← cost estimate from finalized request
│ │
│ ▼ send_request() ← fires the API call
│ │
│ ▼
│ GenerateVideoResponse
│
└─ Request(VideoGenerationRequest) ← skips draft phase (used by Artcraft provider)
```
### Key types
- **`GenerateVideoRequestBuilder`** — generic builder with provider/model/prompt/resolution/etc.
Located in `generate_video/generate_video_request_builder.rs`. The `use_new_builder()` method
gates which provider+model combos use the v2 path. `build2()` dispatches to the correct
provider's build function.
- **`VideoGenerationDraftOrRequest`** — the output of `build2()`. Either `Draft` (for providers
that need media upload/resolution, like Kinovi) or `Request` (for providers that work with
media file tokens directly, like Artcraft).
- **`VideoGenerationDraftRequest`** — enum with one variant per provider+model. Holds
materialized settings (resolution, duration, batch count) plus unresolved media references.
Can estimate cost without network calls.
- **`VideoGenerationDraftContext`** — context needed during `finalize()`: the provider client,
media file token-to-URL map, and character token-to-ID map.
- **`VideoGenerationRequest`** — enum with one variant per provider+model. Holds a fully
materialized request ready to send. All media URLs are resolved and uploaded.
### Cost estimation
Cost can be estimated at two stages:
1. **From draft** — before `finalize()`. Uses the planned resolution/duration/batch count.
Good for showing the user a price before committing.
2. **From request** — after `finalize()`. Uses the final materialized request. Should match
the draft estimate for the same parameters.
## Module layout
```
generate_video/
├── mod.rs
├── video_generation_draft.rs ← VideoGenerationDraftRequest enum
├── video_generation_draft_context.rs ← context for finalize()
├── video_generation_draft_or_request.rs
├── video_generation_request.rs ← VideoGenerationRequest enum
└── providers/
├── artcraft/ ← Artcraft provider (uses media file tokens directly)
│ ├── seedance_2p0/ ← Seedance 2.0 Pro model (skips draft, returns Request directly)
│ │ ├── mod.rs
│ │ ├── build.rs ← builder → Request conversion + plan helpers
│ │ ├── cost.rs ← standalone cost estimation (independent of kinovi_web_client)
│ │ └── request.rs ← request state + send() via Artcraft multi-function API
│ └── seedance_2p0_fast/ ← Seedance 2.0 Fast model (skips draft, 480p/720p only)
│ ├── mod.rs
│ ├── build.rs ← builder → Request conversion + plan helpers (no 1080p)
│ ├── cost.rs ← standalone cost estimation with Fast-specific pricing
│ └── request.rs ← request state + send() via Artcraft omni-gen API
└── kinovi/ ← Kinovi/KinoviWeb provider
├── mod.rs
├── resolve.rs ← shared: media token resolution, upload helpers
├── upload.rs ← shared: download + re-upload to KinoviWeb CDN
├── seedance_2p0/ ← Seedance 2.0 Pro model
│ ├── mod.rs
│ ├── build.rs ← builder → draft conversion + plan helpers
│ ├── cost.rs ← cost estimation state
│ ├── draft.rs ← draft state + finalize (to_request)
│ └── request.rs ← request state + send()
└── seedance_2p0_fast/ ← Seedance 2.0 Fast model
├── mod.rs
├── build.rs
├── cost.rs
├── draft.rs
└── request.rs
```
## Adding a new provider or model
1. **Create the module** under `providers/{provider}/{model}/` with these files:
- `mod.rs` — declares sub-modules
- `build.rs` — `build_{provider}_{model}(builder) -> VideoGenerationDraftOrRequest`.
Contains `plan_*` helpers for aspect ratio, resolution, batch count, duration.
- `draft.rs` — draft state struct with `to_request()` async method for finalization.
**Not needed** if the provider uses media tokens directly (no upload/resolution needed);
in that case `build.rs` returns `VideoGenerationDraftOrRequest::Request(...)` directly.
- `cost.rs` — cost state with `from_request()` and `estimate_cost()`. Add `from_draft()`
if the provider uses the draft phase.
- `request.rs` — request state with `send()` async method.
2. **Register the module** in the parent provider's `mod.rs`.
3. **Add enum variants** in:
- `video_generation_draft.rs` — `VideoGenerationDraftRequest` enum + `estimate_cost` + `finalize`
(skip if provider has no draft phase)
- `video_generation_request.rs` — `VideoGenerationRequest` enum + `estimate_cost` + `send_request`
4. **Wire into the builder** in `generate_video_request_builder.rs`:
- Add the `(Provider, Model)` pair to `use_new_builder()` returning `true`
- Add the dispatch arm in `build2()`
5. **Tests**: each `build.rs` and `cost.rs` should have comprehensive tests. `request.rs`
should have `#[ignore]` live API tests for manual verification.
@@ -15,7 +15,7 @@ use crate::generate::generate_video::video_generation_cost_estimate::VideoGenera
/// Kept as f64 because per-second rates are fractional; rounding happens
/// once at the end after multiplying by duration × batch.
const CENTS_PER_SECOND_480P: f64 = 7.772;
const CENTS_PER_SECOND_720P: f64 = 18.5;
const CENTS_PER_SECOND_720P: f64 = 16.0;
const CENTS_PER_SECOND_1080P: f64 = 46.632;
/// USD cents per second, in hundredths of a cent, when one or more
@@ -65,6 +65,7 @@ impl ArtcraftSeedance2p0CostState {
let usd_cents = seedance_2p0_four_k_usd_cents(
self.duration_seconds,
self.batch_count,
self.has_video_reference,
);
return VideoGenerationCostEstimate {
cost_in_credits: Some(usd_cents),
@@ -131,32 +132,32 @@ mod tests {
#[test]
fn batch_1() {
assert_eq!(cost_cents(Some(RouterResolution::SevenTwentyP), 4, 1), 74);
assert_eq!(cost_cents(Some(RouterResolution::SevenTwentyP), 5, 1), 93);
assert_eq!(cost_cents(Some(RouterResolution::SevenTwentyP), 6, 1), 111);
assert_eq!(cost_cents(Some(RouterResolution::SevenTwentyP), 10, 1), 185);
assert_eq!(cost_cents(Some(RouterResolution::SevenTwentyP), 15, 1), 278);
assert_eq!(cost_cents(Some(RouterResolution::SevenTwentyP), 4, 1), 64);
assert_eq!(cost_cents(Some(RouterResolution::SevenTwentyP), 5, 1), 80);
assert_eq!(cost_cents(Some(RouterResolution::SevenTwentyP), 6, 1), 96);
assert_eq!(cost_cents(Some(RouterResolution::SevenTwentyP), 10, 1), 160);
assert_eq!(cost_cents(Some(RouterResolution::SevenTwentyP), 15, 1), 240);
}
#[test]
fn batch_2() {
assert_eq!(cost_cents(Some(RouterResolution::SevenTwentyP), 4, 2), 148);
assert_eq!(cost_cents(Some(RouterResolution::SevenTwentyP), 5, 2), 185);
assert_eq!(cost_cents(Some(RouterResolution::SevenTwentyP), 15, 2), 555);
assert_eq!(cost_cents(Some(RouterResolution::SevenTwentyP), 4, 2), 128);
assert_eq!(cost_cents(Some(RouterResolution::SevenTwentyP), 5, 2), 160);
assert_eq!(cost_cents(Some(RouterResolution::SevenTwentyP), 15, 2), 480);
}
#[test]
fn batch_3() {
assert_eq!(cost_cents(Some(RouterResolution::SevenTwentyP), 4, 3), 222);
assert_eq!(cost_cents(Some(RouterResolution::SevenTwentyP), 5, 3), 278);
assert_eq!(cost_cents(Some(RouterResolution::SevenTwentyP), 15, 3), 833);
assert_eq!(cost_cents(Some(RouterResolution::SevenTwentyP), 4, 3), 192);
assert_eq!(cost_cents(Some(RouterResolution::SevenTwentyP), 5, 3), 240);
assert_eq!(cost_cents(Some(RouterResolution::SevenTwentyP), 15, 3), 720);
}
#[test]
fn batch_4() {
assert_eq!(cost_cents(Some(RouterResolution::SevenTwentyP), 4, 4), 296);
assert_eq!(cost_cents(Some(RouterResolution::SevenTwentyP), 5, 4), 370);
assert_eq!(cost_cents(Some(RouterResolution::SevenTwentyP), 15, 4), 1110);
assert_eq!(cost_cents(Some(RouterResolution::SevenTwentyP), 4, 4), 256);
assert_eq!(cost_cents(Some(RouterResolution::SevenTwentyP), 5, 4), 320);
assert_eq!(cost_cents(Some(RouterResolution::SevenTwentyP), 15, 4), 960);
}
#[test]
@@ -242,10 +243,10 @@ mod tests {
#[test]
fn explicit_4k_without_video_reference() {
assert_eq!(artcraft_4k_cents(4, 1, false), 370);
assert_eq!(artcraft_4k_cents(5, 1, false), 463);
assert_eq!(artcraft_4k_cents(10, 1, false), 925);
assert_eq!(artcraft_4k_cents(15, 1, false), 1388);
assert_eq!(artcraft_4k_cents(4, 1, false), 347);
assert_eq!(artcraft_4k_cents(5, 1, false), 433);
assert_eq!(artcraft_4k_cents(10, 1, false), 866);
assert_eq!(artcraft_4k_cents(15, 1, false), 1299);
}
#[test]
@@ -480,74 +481,4 @@ mod tests {
.cost_in_usd_cents
.unwrap()
}
// ── Video reference deltas ──
//
// References price on the with-reference rate card; the delta must be positive at every resolution and duration.
mod video_reference_deltas {
use enums::common::generation::common_resolution::CommonResolution;
use super::super::ArtcraftSeedance2p0CostState;
#[test]
fn refs_cost_more_at_480p() {
assert_ref_delta(CommonResolution::FourEightyP, 5, 39, 45, 6);
assert_ref_delta(CommonResolution::FourEightyP, 10, 78, 89, 11);
assert_ref_delta(CommonResolution::FourEightyP, 15, 117, 133, 16);
}
#[test]
fn refs_cost_more_at_720p() {
assert_ref_delta(CommonResolution::SevenTwentyP, 5, 93, 111, 18);
assert_ref_delta(CommonResolution::SevenTwentyP, 10, 185, 221, 36);
assert_ref_delta(CommonResolution::SevenTwentyP, 15, 278, 331, 53);
}
#[test]
fn refs_cost_more_at_1080p() {
assert_ref_delta(CommonResolution::TenEightyP, 5, 233, 256, 23);
assert_ref_delta(CommonResolution::TenEightyP, 10, 466, 511, 45);
assert_ref_delta(CommonResolution::TenEightyP, 15, 699, 767, 68);
}
#[test]
fn refs_cost_more_at_4k() {
assert_ref_delta(CommonResolution::FourK, 5, 463, 569, 106);
assert_ref_delta(CommonResolution::FourK, 10, 925, 1138, 213);
assert_ref_delta(CommonResolution::FourK, 15, 1388, 1707, 319);
}
/// Price the same generation with and without a reference video; pin
/// both prices and the delta, in USD cents AND credits (credits equal
/// cents, and both must show references costing more).
fn assert_ref_delta(
resolution: CommonResolution,
duration_seconds: u16,
expected_no_ref: u64,
expected_with_ref: u64,
expected_delta: u64,
) {
let no_ref = ArtcraftSeedance2p0CostState {
resolution, duration_seconds, batch_count: 1, has_video_reference: false,
}.estimate_cost();
let with_ref = ArtcraftSeedance2p0CostState {
resolution, duration_seconds, batch_count: 1, has_video_reference: true,
}.estimate_cost();
let no_ref_cents = no_ref.cost_in_usd_cents.unwrap();
let with_ref_cents = with_ref.cost_in_usd_cents.unwrap();
assert_eq!(no_ref_cents, expected_no_ref);
assert_eq!(with_ref_cents, expected_with_ref);
assert_eq!(with_ref_cents - no_ref_cents, expected_delta);
assert!(with_ref_cents > no_ref_cents, "references must cost more");
let no_ref_credits = no_ref.cost_in_credits.unwrap();
let with_ref_credits = with_ref.cost_in_credits.unwrap();
assert_eq!(no_ref_credits, expected_no_ref);
assert_eq!(with_ref_credits, expected_with_ref);
assert_eq!(with_ref_credits - no_ref_credits, expected_delta);
}
}
}
@@ -1,5 +1,6 @@
use enums::common::generation::common_resolution::CommonResolution;
use crate::generate::generate_video::providers::artcraft::seedance_common::seedance_2p0_four_k_usd_cents;
use crate::generate::generate_video::providers::artcraft::seedance_2p0_bp::request::ArtcraftSeedance2p0BytePlusRequestState;
use crate::generate::generate_video::video_generation_cost_estimate::VideoGenerationCostEstimate;
@@ -11,24 +12,6 @@ const CENTS_PER_SECOND_480P: f64 = 10.0;
const CENTS_PER_SECOND_720P: f64 = 25.0;
const CENTS_PER_SECOND_1080P: f64 = 50.0;
/// USD cents per second, in hundredths of a cent, when one or more
/// reference videos are attached. Held as integer hundredths so the math is
/// exact; rounded up to whole cents once, after multiplying by
/// duration × batch.
/// 480p: 10.20 ¢/s
/// 720p: 25.70 ¢/s
/// 1080p: 57.80 ¢/s
/// 4K: 119.00 ¢/s
const WITH_VIDEO_REFERENCE_CENTI_CENTS_PER_SECOND_480P: u64 = 1_020;
const WITH_VIDEO_REFERENCE_CENTI_CENTS_PER_SECOND_720P: u64 = 2_570;
const WITH_VIDEO_REFERENCE_CENTI_CENTS_PER_SECOND_1080P: u64 = 5_780;
const WITH_VIDEO_REFERENCE_CENTI_CENTS_PER_SECOND_4K: u64 = 11_900;
/// 4K output price with no reference videos, in hundredths of a USD cent
/// per second (95.00 ¢/s), rounded up to whole cents after multiplying by
/// duration × batch.
const CENTI_CENTS_PER_SECOND_4K: u64 = 9_500;
pub struct ArtcraftSeedance2p0BytePlusCostState {
pub resolution: CommonResolution,
pub duration_seconds: u16,
@@ -49,24 +32,12 @@ impl ArtcraftSeedance2p0BytePlusCostState {
}
pub fn estimate_cost(&self) -> VideoGenerationCostEstimate {
if self.has_video_reference {
let usd_cents = self.with_video_reference_usd_cents();
return VideoGenerationCostEstimate {
cost_in_credits: Some(usd_cents),
cost_in_usd_cents: Some(usd_cents),
is_free: false,
is_unlimited: false,
is_rate_limited: false,
has_watermark: false,
failures_are_refunded: None,
};
}
if self.resolution == CommonResolution::FourK {
let total_centi_cents = CENTI_CENTS_PER_SECOND_4K
* self.duration_seconds as u64
* self.batch_count as u64;
let usd_cents = total_centi_cents.div_ceil(100);
let usd_cents = seedance_2p0_four_k_usd_cents(
self.duration_seconds,
self.batch_count,
self.has_video_reference,
);
return VideoGenerationCostEstimate {
cost_in_credits: Some(usd_cents),
cost_in_usd_cents: Some(usd_cents),
@@ -96,22 +67,6 @@ impl ArtcraftSeedance2p0BytePlusCostState {
failures_are_refunded: None,
}
}
/// Price when one or more reference videos are attached.
fn with_video_reference_usd_cents(&self) -> u64 {
let centi_cents_per_second = match self.resolution {
CommonResolution::FourEightyP => WITH_VIDEO_REFERENCE_CENTI_CENTS_PER_SECOND_480P,
CommonResolution::TenEightyP => WITH_VIDEO_REFERENCE_CENTI_CENTS_PER_SECOND_1080P,
CommonResolution::FourK => WITH_VIDEO_REFERENCE_CENTI_CENTS_PER_SECOND_4K,
// Everything else (including 720p) prices at 720p.
_ => WITH_VIDEO_REFERENCE_CENTI_CENTS_PER_SECOND_720P,
};
let seconds = self.duration_seconds as u64 * self.batch_count as u64;
// Round up to whole cents.
(centi_cents_per_second * seconds).div_ceil(100)
}
}
#[cfg(test)]
@@ -224,20 +179,18 @@ mod tests {
#[test]
fn explicit_4k_without_video_reference() {
// 95.00 ¢/s card, rounded up to whole cents.
assert_eq!(artcraft_4k_cents(4, 1, false), 380);
assert_eq!(artcraft_4k_cents(5, 1, false), 475);
assert_eq!(artcraft_4k_cents(10, 1, false), 950);
assert_eq!(artcraft_4k_cents(15, 1, false), 1425);
assert_eq!(artcraft_4k_cents(4, 1, false), 347);
assert_eq!(artcraft_4k_cents(5, 1, false), 433);
assert_eq!(artcraft_4k_cents(10, 1, false), 866);
assert_eq!(artcraft_4k_cents(15, 1, false), 1299);
}
#[test]
fn explicit_4k_with_video_reference() {
// 119.00 ¢/s with-reference card, rounded up to whole cents.
assert_eq!(artcraft_4k_cents(4, 1, true), 476);
assert_eq!(artcraft_4k_cents(5, 1, true), 595);
assert_eq!(artcraft_4k_cents(10, 1, true), 1190);
assert_eq!(artcraft_4k_cents(15, 1, true), 1785);
assert_eq!(artcraft_4k_cents(4, 1, true), 416);
assert_eq!(artcraft_4k_cents(5, 1, true), 519);
assert_eq!(artcraft_4k_cents(10, 1, true), 1038);
assert_eq!(artcraft_4k_cents(15, 1, true), 1557);
}
}
@@ -290,74 +243,4 @@ mod tests {
fn cost_cents(resolution: Option<RouterResolution>, duration_seconds: u16, video_batch_count: u16) -> u64 {
build_cost(resolution, duration_seconds, video_batch_count).cost_in_usd_cents.unwrap()
}
// ── Video reference deltas ──
//
// References price on the with-reference rate card (10.20/25.70/57.80/113.80 ¢/s); the delta must be positive at every resolution and duration.
mod video_reference_deltas {
use enums::common::generation::common_resolution::CommonResolution;
use super::super::ArtcraftSeedance2p0BytePlusCostState;
#[test]
fn refs_cost_more_at_480p() {
assert_ref_delta(CommonResolution::FourEightyP, 5, 50, 51, 1);
assert_ref_delta(CommonResolution::FourEightyP, 10, 100, 102, 2);
assert_ref_delta(CommonResolution::FourEightyP, 15, 150, 153, 3);
}
#[test]
fn refs_cost_more_at_720p() {
assert_ref_delta(CommonResolution::SevenTwentyP, 5, 125, 129, 4);
assert_ref_delta(CommonResolution::SevenTwentyP, 10, 250, 257, 7);
assert_ref_delta(CommonResolution::SevenTwentyP, 15, 375, 386, 11);
}
#[test]
fn refs_cost_more_at_1080p() {
assert_ref_delta(CommonResolution::TenEightyP, 5, 250, 289, 39);
assert_ref_delta(CommonResolution::TenEightyP, 10, 500, 578, 78);
assert_ref_delta(CommonResolution::TenEightyP, 15, 750, 867, 117);
}
#[test]
fn refs_cost_more_at_4k() {
assert_ref_delta(CommonResolution::FourK, 5, 475, 595, 120);
assert_ref_delta(CommonResolution::FourK, 10, 950, 1190, 240);
assert_ref_delta(CommonResolution::FourK, 15, 1425, 1785, 360);
}
/// Price the same generation with and without a reference video; pin
/// both prices and the delta, in USD cents AND credits (credits equal
/// cents, and both must show references costing more).
fn assert_ref_delta(
resolution: CommonResolution,
duration_seconds: u16,
expected_no_ref: u64,
expected_with_ref: u64,
expected_delta: u64,
) {
let no_ref = ArtcraftSeedance2p0BytePlusCostState {
resolution, duration_seconds, batch_count: 1, has_video_reference: false,
}.estimate_cost();
let with_ref = ArtcraftSeedance2p0BytePlusCostState {
resolution, duration_seconds, batch_count: 1, has_video_reference: true,
}.estimate_cost();
let no_ref_cents = no_ref.cost_in_usd_cents.unwrap();
let with_ref_cents = with_ref.cost_in_usd_cents.unwrap();
assert_eq!(no_ref_cents, expected_no_ref);
assert_eq!(with_ref_cents, expected_with_ref);
assert_eq!(with_ref_cents - no_ref_cents, expected_delta);
assert!(with_ref_cents > no_ref_cents, "references must cost more");
let no_ref_credits = no_ref.cost_in_credits.unwrap();
let with_ref_credits = with_ref.cost_in_credits.unwrap();
assert_eq!(no_ref_credits, expected_no_ref);
assert_eq!(with_ref_credits, expected_with_ref);
assert_eq!(with_ref_credits - no_ref_credits, expected_delta);
}
}
}
@@ -9,20 +9,10 @@ use crate::generate::generate_video::providers::artcraft::seedance_2p0_bp_fast::
const CENTS_PER_SECOND_480P: f64 = 9.0;
const CENTS_PER_SECOND_720P: f64 = 20.0;
/// USD cents per second, in hundredths of a cent, when one or more
/// reference videos are attached. Held as integer hundredths so the math is
/// exact; rounded up to whole cents once, after multiplying by
/// duration × batch.
/// 480p: 9.65 ¢/s
/// 720p: 20.50 ¢/s
const WITH_VIDEO_REFERENCE_CENTI_CENTS_PER_SECOND_480P: u64 = 965;
const WITH_VIDEO_REFERENCE_CENTI_CENTS_PER_SECOND_720P: u64 = 2_050;
pub struct ArtcraftSeedance2p0BytePlusFastCostState {
pub resolution: CommonResolution,
pub duration_seconds: u16,
pub batch_count: u16,
pub has_video_reference: bool,
}
impl ArtcraftSeedance2p0BytePlusFastCostState {
@@ -31,26 +21,10 @@ impl ArtcraftSeedance2p0BytePlusFastCostState {
.unwrap_or(CommonResolution::SevenTwentyP);
let duration_seconds = request.request.duration_seconds.unwrap_or(5);
let batch_count = request.request.video_batch_count.unwrap_or(1);
let has_video_reference = request.request.reference_video_media_tokens
.as_ref()
.is_some_and(|tokens| !tokens.is_empty());
Self { resolution, duration_seconds, batch_count, has_video_reference }
Self { resolution, duration_seconds, batch_count }
}
pub fn estimate_cost(&self) -> VideoGenerationCostEstimate {
if self.has_video_reference {
let usd_cents = self.with_video_reference_usd_cents();
return VideoGenerationCostEstimate {
cost_in_credits: Some(usd_cents),
cost_in_usd_cents: Some(usd_cents),
is_free: false,
is_unlimited: false,
is_rate_limited: false,
has_watermark: false,
failures_are_refunded: None,
};
}
let cents_per_second = match self.resolution {
CommonResolution::FourEightyP => CENTS_PER_SECOND_480P,
_ => CENTS_PER_SECOND_720P,
@@ -68,20 +42,6 @@ impl ArtcraftSeedance2p0BytePlusFastCostState {
failures_are_refunded: None,
}
}
/// Price when one or more reference videos are attached.
fn with_video_reference_usd_cents(&self) -> u64 {
let centi_cents_per_second = match self.resolution {
CommonResolution::FourEightyP => WITH_VIDEO_REFERENCE_CENTI_CENTS_PER_SECOND_480P,
// Everything else (including 720p) prices at 720p.
_ => WITH_VIDEO_REFERENCE_CENTI_CENTS_PER_SECOND_720P,
};
let seconds = self.duration_seconds as u64 * self.batch_count as u64;
// Round up to whole cents.
(centi_cents_per_second * seconds).div_ceil(100)
}
}
#[cfg(test)]
@@ -65,18 +65,18 @@ mod tests {
#[test]
fn without_video_reference() {
assert_eq!(cents(RouterResolution::FourEightyP, 4, 1, false), 15);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 1, false), 18);
assert_eq!(cents(RouterResolution::FourEightyP, 10, 1, false), 36);
assert_eq!(cents(RouterResolution::FourEightyP, 15, 1, false), 54);
assert_eq!(cents(RouterResolution::FourEightyP, 4, 1, false), 14);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 1, false), 17);
assert_eq!(cents(RouterResolution::FourEightyP, 10, 1, false), 33);
assert_eq!(cents(RouterResolution::FourEightyP, 15, 1, false), 50);
}
#[test]
fn with_video_reference() {
assert_eq!(cents(RouterResolution::FourEightyP, 4, 1, true), 18);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 1, true), 23);
assert_eq!(cents(RouterResolution::FourEightyP, 10, 1, true), 45);
assert_eq!(cents(RouterResolution::FourEightyP, 15, 1, true), 68);
assert_eq!(cents(RouterResolution::FourEightyP, 4, 1, true), 17);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 1, true), 21);
assert_eq!(cents(RouterResolution::FourEightyP, 10, 1, true), 42);
assert_eq!(cents(RouterResolution::FourEightyP, 15, 1, true), 63);
}
}
@@ -85,18 +85,18 @@ mod tests {
#[test]
fn without_video_reference() {
assert_eq!(cents(RouterResolution::SevenTwentyP, 4, 1, false), 37);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 1, false), 46);
assert_eq!(cents(RouterResolution::SevenTwentyP, 10, 1, false), 91);
assert_eq!(cents(RouterResolution::SevenTwentyP, 15, 1, false), 137);
assert_eq!(cents(RouterResolution::SevenTwentyP, 4, 1, false), 35);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 1, false), 44);
assert_eq!(cents(RouterResolution::SevenTwentyP, 10, 1, false), 88);
assert_eq!(cents(RouterResolution::SevenTwentyP, 15, 1, false), 131);
}
#[test]
fn with_video_reference() {
assert_eq!(cents(RouterResolution::SevenTwentyP, 4, 1, true), 44);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 1, true), 55);
assert_eq!(cents(RouterResolution::SevenTwentyP, 10, 1, true), 110);
assert_eq!(cents(RouterResolution::SevenTwentyP, 15, 1, true), 165);
assert_eq!(cents(RouterResolution::SevenTwentyP, 4, 1, true), 42);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 1, true), 53);
assert_eq!(cents(RouterResolution::SevenTwentyP, 10, 1, true), 105);
assert_eq!(cents(RouterResolution::SevenTwentyP, 15, 1, true), 158);
}
#[test]
@@ -112,31 +112,31 @@ mod tests {
/// apply). Once, batch 8 executed in full but billed as batch 4.
#[test]
fn every_batch_size_720p_5s() {
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 1, false), 46);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 2, false), 91);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 3, false), 137);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 4, false), 182);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 5, false), 228);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 6, false), 273);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 7, false), 319);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 8, false), 364);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 1, false), 44);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 2, false), 88);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 3, false), 131);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 4, false), 175);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 5, false), 219);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 6, false), 262);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 7, false), 306);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 8, false), 349);
}
#[test]
fn every_batch_size_480p_5s() {
assert_eq!(cents(RouterResolution::FourEightyP, 5, 1, false), 18);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 2, false), 36);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 3, false), 54);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 4, false), 71);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 5, false), 89);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 6, false), 107);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 7, false), 125);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 8, false), 142);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 1, false), 17);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 2, false), 33);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 3, false), 50);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 4, false), 66);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 5, false), 82);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 6, false), 99);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 7, false), 115);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 8, false), 131);
}
#[test]
fn batch_eight_with_video_reference() {
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 8, true), 438);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 8, true), 419);
}
#[test]
@@ -1,5 +1,6 @@
use enums::common::generation::common_resolution::CommonResolution;
use crate::generate::generate_video::providers::artcraft::seedance_common::seedance_2p0_four_k_usd_cents;
use crate::generate::generate_video::providers::artcraft::seedance_2p0_bpu::request::ArtcraftSeedance2p0BytePlusUltraRequestState;
use crate::generate::generate_video::video_generation_cost_estimate::VideoGenerationCostEstimate;
@@ -11,24 +12,6 @@ const CENTS_PER_SECOND_480P: f64 = 10.0;
const CENTS_PER_SECOND_720P: f64 = 25.0;
const CENTS_PER_SECOND_1080P: f64 = 50.0;
/// USD cents per second, in hundredths of a cent, when one or more
/// reference videos are attached. Held as integer hundredths so the math is
/// exact; rounded up to whole cents once, after multiplying by
/// duration × batch.
/// 480p: 10.20 ¢/s
/// 720p: 25.70 ¢/s
/// 1080p: 57.80 ¢/s
/// 4K: 119.00 ¢/s
const WITH_VIDEO_REFERENCE_CENTI_CENTS_PER_SECOND_480P: u64 = 1_020;
const WITH_VIDEO_REFERENCE_CENTI_CENTS_PER_SECOND_720P: u64 = 2_570;
const WITH_VIDEO_REFERENCE_CENTI_CENTS_PER_SECOND_1080P: u64 = 5_780;
const WITH_VIDEO_REFERENCE_CENTI_CENTS_PER_SECOND_4K: u64 = 11_900;
/// 4K output price with no reference videos, in hundredths of a USD cent
/// per second (95.00 ¢/s), rounded up to whole cents after multiplying by
/// duration × batch.
const CENTI_CENTS_PER_SECOND_4K: u64 = 9_500;
pub struct ArtcraftSeedance2p0BytePlusUltraCostState {
pub resolution: CommonResolution,
pub duration_seconds: u16,
@@ -49,24 +32,12 @@ impl ArtcraftSeedance2p0BytePlusUltraCostState {
}
pub fn estimate_cost(&self) -> VideoGenerationCostEstimate {
if self.has_video_reference {
let usd_cents = self.with_video_reference_usd_cents();
return VideoGenerationCostEstimate {
cost_in_credits: Some(usd_cents),
cost_in_usd_cents: Some(usd_cents),
is_free: false,
is_unlimited: false,
is_rate_limited: false,
has_watermark: false,
failures_are_refunded: None,
};
}
if self.resolution == CommonResolution::FourK {
let total_centi_cents = CENTI_CENTS_PER_SECOND_4K
* self.duration_seconds as u64
* self.batch_count as u64;
let usd_cents = total_centi_cents.div_ceil(100);
let usd_cents = seedance_2p0_four_k_usd_cents(
self.duration_seconds,
self.batch_count,
self.has_video_reference,
);
return VideoGenerationCostEstimate {
cost_in_credits: Some(usd_cents),
cost_in_usd_cents: Some(usd_cents),
@@ -96,22 +67,6 @@ impl ArtcraftSeedance2p0BytePlusUltraCostState {
failures_are_refunded: None,
}
}
/// Price when one or more reference videos are attached.
fn with_video_reference_usd_cents(&self) -> u64 {
let centi_cents_per_second = match self.resolution {
CommonResolution::FourEightyP => WITH_VIDEO_REFERENCE_CENTI_CENTS_PER_SECOND_480P,
CommonResolution::TenEightyP => WITH_VIDEO_REFERENCE_CENTI_CENTS_PER_SECOND_1080P,
CommonResolution::FourK => WITH_VIDEO_REFERENCE_CENTI_CENTS_PER_SECOND_4K,
// Everything else (including 720p) prices at 720p.
_ => WITH_VIDEO_REFERENCE_CENTI_CENTS_PER_SECOND_720P,
};
let seconds = self.duration_seconds as u64 * self.batch_count as u64;
// Round up to whole cents.
(centi_cents_per_second * seconds).div_ceil(100)
}
}
#[cfg(test)]
@@ -224,20 +179,18 @@ mod tests {
#[test]
fn explicit_4k_without_video_reference() {
// 95.00 ¢/s card, rounded up to whole cents.
assert_eq!(artcraft_4k_cents(4, 1, false), 380);
assert_eq!(artcraft_4k_cents(5, 1, false), 475);
assert_eq!(artcraft_4k_cents(10, 1, false), 950);
assert_eq!(artcraft_4k_cents(15, 1, false), 1425);
assert_eq!(artcraft_4k_cents(4, 1, false), 347);
assert_eq!(artcraft_4k_cents(5, 1, false), 433);
assert_eq!(artcraft_4k_cents(10, 1, false), 866);
assert_eq!(artcraft_4k_cents(15, 1, false), 1299);
}
#[test]
fn explicit_4k_with_video_reference() {
// 119.00 ¢/s with-reference card, rounded up to whole cents.
assert_eq!(artcraft_4k_cents(4, 1, true), 476);
assert_eq!(artcraft_4k_cents(5, 1, true), 595);
assert_eq!(artcraft_4k_cents(10, 1, true), 1190);
assert_eq!(artcraft_4k_cents(15, 1, true), 1785);
assert_eq!(artcraft_4k_cents(4, 1, true), 416);
assert_eq!(artcraft_4k_cents(5, 1, true), 519);
assert_eq!(artcraft_4k_cents(10, 1, true), 1038);
assert_eq!(artcraft_4k_cents(15, 1, true), 1557);
}
}
@@ -290,74 +243,4 @@ mod tests {
fn cost_cents(resolution: Option<RouterResolution>, duration_seconds: u16, video_batch_count: u16) -> u64 {
build_cost(resolution, duration_seconds, video_batch_count).cost_in_usd_cents.unwrap()
}
// ── Video reference deltas ──
//
// References price on the with-reference rate card (10.20/25.70/57.80/113.80 ¢/s); the delta must be positive at every resolution and duration.
mod video_reference_deltas {
use enums::common::generation::common_resolution::CommonResolution;
use super::super::ArtcraftSeedance2p0BytePlusUltraCostState;
#[test]
fn refs_cost_more_at_480p() {
assert_ref_delta(CommonResolution::FourEightyP, 5, 50, 51, 1);
assert_ref_delta(CommonResolution::FourEightyP, 10, 100, 102, 2);
assert_ref_delta(CommonResolution::FourEightyP, 15, 150, 153, 3);
}
#[test]
fn refs_cost_more_at_720p() {
assert_ref_delta(CommonResolution::SevenTwentyP, 5, 125, 129, 4);
assert_ref_delta(CommonResolution::SevenTwentyP, 10, 250, 257, 7);
assert_ref_delta(CommonResolution::SevenTwentyP, 15, 375, 386, 11);
}
#[test]
fn refs_cost_more_at_1080p() {
assert_ref_delta(CommonResolution::TenEightyP, 5, 250, 289, 39);
assert_ref_delta(CommonResolution::TenEightyP, 10, 500, 578, 78);
assert_ref_delta(CommonResolution::TenEightyP, 15, 750, 867, 117);
}
#[test]
fn refs_cost_more_at_4k() {
assert_ref_delta(CommonResolution::FourK, 5, 475, 595, 120);
assert_ref_delta(CommonResolution::FourK, 10, 950, 1190, 240);
assert_ref_delta(CommonResolution::FourK, 15, 1425, 1785, 360);
}
/// Price the same generation with and without a reference video; pin
/// both prices and the delta, in USD cents AND credits (credits equal
/// cents, and both must show references costing more).
fn assert_ref_delta(
resolution: CommonResolution,
duration_seconds: u16,
expected_no_ref: u64,
expected_with_ref: u64,
expected_delta: u64,
) {
let no_ref = ArtcraftSeedance2p0BytePlusUltraCostState {
resolution, duration_seconds, batch_count: 1, has_video_reference: false,
}.estimate_cost();
let with_ref = ArtcraftSeedance2p0BytePlusUltraCostState {
resolution, duration_seconds, batch_count: 1, has_video_reference: true,
}.estimate_cost();
let no_ref_cents = no_ref.cost_in_usd_cents.unwrap();
let with_ref_cents = with_ref.cost_in_usd_cents.unwrap();
assert_eq!(no_ref_cents, expected_no_ref);
assert_eq!(with_ref_cents, expected_with_ref);
assert_eq!(with_ref_cents - no_ref_cents, expected_delta);
assert!(with_ref_cents > no_ref_cents, "references must cost more");
let no_ref_credits = no_ref.cost_in_credits.unwrap();
let with_ref_credits = with_ref.cost_in_credits.unwrap();
assert_eq!(no_ref_credits, expected_no_ref);
assert_eq!(with_ref_credits, expected_with_ref);
assert_eq!(with_ref_credits - no_ref_credits, expected_delta);
}
}
}
@@ -9,20 +9,10 @@ use crate::generate::generate_video::providers::artcraft::seedance_2p0_bpu_fast:
const CENTS_PER_SECOND_480P: f64 = 9.0;
const CENTS_PER_SECOND_720P: f64 = 20.0;
/// USD cents per second, in hundredths of a cent, when one or more
/// reference videos are attached. Held as integer hundredths so the math is
/// exact; rounded up to whole cents once, after multiplying by
/// duration × batch.
/// 480p: 9.65 ¢/s
/// 720p: 20.50 ¢/s
const WITH_VIDEO_REFERENCE_CENTI_CENTS_PER_SECOND_480P: u64 = 965;
const WITH_VIDEO_REFERENCE_CENTI_CENTS_PER_SECOND_720P: u64 = 2_050;
pub struct ArtcraftSeedance2p0BytePlusUltraFastCostState {
pub resolution: CommonResolution,
pub duration_seconds: u16,
pub batch_count: u16,
pub has_video_reference: bool,
}
impl ArtcraftSeedance2p0BytePlusUltraFastCostState {
@@ -31,26 +21,10 @@ impl ArtcraftSeedance2p0BytePlusUltraFastCostState {
.unwrap_or(CommonResolution::SevenTwentyP);
let duration_seconds = request.request.duration_seconds.unwrap_or(5);
let batch_count = request.request.video_batch_count.unwrap_or(1);
let has_video_reference = request.request.reference_video_media_tokens
.as_ref()
.is_some_and(|tokens| !tokens.is_empty());
Self { resolution, duration_seconds, batch_count, has_video_reference }
Self { resolution, duration_seconds, batch_count }
}
pub fn estimate_cost(&self) -> VideoGenerationCostEstimate {
if self.has_video_reference {
let usd_cents = self.with_video_reference_usd_cents();
return VideoGenerationCostEstimate {
cost_in_credits: Some(usd_cents),
cost_in_usd_cents: Some(usd_cents),
is_free: false,
is_unlimited: false,
is_rate_limited: false,
has_watermark: false,
failures_are_refunded: None,
};
}
let cents_per_second = match self.resolution {
CommonResolution::FourEightyP => CENTS_PER_SECOND_480P,
_ => CENTS_PER_SECOND_720P,
@@ -68,20 +42,6 @@ impl ArtcraftSeedance2p0BytePlusUltraFastCostState {
failures_are_refunded: None,
}
}
/// Price when one or more reference videos are attached.
fn with_video_reference_usd_cents(&self) -> u64 {
let centi_cents_per_second = match self.resolution {
CommonResolution::FourEightyP => WITH_VIDEO_REFERENCE_CENTI_CENTS_PER_SECOND_480P,
// Everything else (including 720p) prices at 720p.
_ => WITH_VIDEO_REFERENCE_CENTI_CENTS_PER_SECOND_720P,
};
let seconds = self.duration_seconds as u64 * self.batch_count as u64;
// Round up to whole cents.
(centi_cents_per_second * seconds).div_ceil(100)
}
}
#[cfg(test)]
@@ -65,18 +65,18 @@ mod tests {
#[test]
fn without_video_reference() {
assert_eq!(cents(RouterResolution::FourEightyP, 4, 1, false), 15);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 1, false), 18);
assert_eq!(cents(RouterResolution::FourEightyP, 10, 1, false), 36);
assert_eq!(cents(RouterResolution::FourEightyP, 15, 1, false), 54);
assert_eq!(cents(RouterResolution::FourEightyP, 4, 1, false), 14);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 1, false), 17);
assert_eq!(cents(RouterResolution::FourEightyP, 10, 1, false), 33);
assert_eq!(cents(RouterResolution::FourEightyP, 15, 1, false), 50);
}
#[test]
fn with_video_reference() {
assert_eq!(cents(RouterResolution::FourEightyP, 4, 1, true), 18);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 1, true), 23);
assert_eq!(cents(RouterResolution::FourEightyP, 10, 1, true), 45);
assert_eq!(cents(RouterResolution::FourEightyP, 15, 1, true), 68);
assert_eq!(cents(RouterResolution::FourEightyP, 4, 1, true), 17);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 1, true), 21);
assert_eq!(cents(RouterResolution::FourEightyP, 10, 1, true), 42);
assert_eq!(cents(RouterResolution::FourEightyP, 15, 1, true), 63);
}
}
@@ -85,18 +85,18 @@ mod tests {
#[test]
fn without_video_reference() {
assert_eq!(cents(RouterResolution::SevenTwentyP, 4, 1, false), 37);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 1, false), 46);
assert_eq!(cents(RouterResolution::SevenTwentyP, 10, 1, false), 91);
assert_eq!(cents(RouterResolution::SevenTwentyP, 15, 1, false), 137);
assert_eq!(cents(RouterResolution::SevenTwentyP, 4, 1, false), 35);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 1, false), 44);
assert_eq!(cents(RouterResolution::SevenTwentyP, 10, 1, false), 88);
assert_eq!(cents(RouterResolution::SevenTwentyP, 15, 1, false), 131);
}
#[test]
fn with_video_reference() {
assert_eq!(cents(RouterResolution::SevenTwentyP, 4, 1, true), 44);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 1, true), 55);
assert_eq!(cents(RouterResolution::SevenTwentyP, 10, 1, true), 110);
assert_eq!(cents(RouterResolution::SevenTwentyP, 15, 1, true), 165);
assert_eq!(cents(RouterResolution::SevenTwentyP, 4, 1, true), 42);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 1, true), 53);
assert_eq!(cents(RouterResolution::SevenTwentyP, 10, 1, true), 105);
assert_eq!(cents(RouterResolution::SevenTwentyP, 15, 1, true), 158);
}
#[test]
@@ -112,31 +112,31 @@ mod tests {
/// apply). Once, batch 8 executed in full but billed as batch 4.
#[test]
fn every_batch_size_720p_5s() {
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 1, false), 46);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 2, false), 91);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 3, false), 137);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 4, false), 182);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 5, false), 228);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 6, false), 273);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 7, false), 319);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 8, false), 364);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 1, false), 44);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 2, false), 88);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 3, false), 131);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 4, false), 175);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 5, false), 219);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 6, false), 262);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 7, false), 306);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 8, false), 349);
}
#[test]
fn every_batch_size_480p_5s() {
assert_eq!(cents(RouterResolution::FourEightyP, 5, 1, false), 18);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 2, false), 36);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 3, false), 54);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 4, false), 71);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 5, false), 89);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 6, false), 107);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 7, false), 125);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 8, false), 142);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 1, false), 17);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 2, false), 33);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 3, false), 50);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 4, false), 66);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 5, false), 82);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 6, false), 99);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 7, false), 115);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 8, false), 131);
}
#[test]
fn batch_eight_with_video_reference() {
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 8, true), 438);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 8, true), 419);
}
#[test]
@@ -13,7 +13,7 @@ use crate::generate::generate_video::providers::artcraft::seedance_2p0_fast::req
///
/// Kept as f64 because per-second rates are fractional; rounding happens
/// once at the end after multiplying by duration * batch.
const CENTS_PER_SECOND_480P: f64 = 7.13;
const CENTS_PER_SECOND_480P: f64 = 5.181;
const CENTS_PER_SECOND_720P: f64 = 12.727;
/// USD cents per second, in hundredths of a cent, when one or more
@@ -149,25 +149,25 @@ mod tests {
#[test]
fn batch_1() {
assert_eq!(cost_cents(Some(RouterResolution::FourEightyP), 4, 1), 29);
assert_eq!(cost_cents(Some(RouterResolution::FourEightyP), 5, 1), 36);
assert_eq!(cost_cents(Some(RouterResolution::FourEightyP), 10, 1), 71);
assert_eq!(cost_cents(Some(RouterResolution::FourEightyP), 15, 1), 107);
assert_eq!(cost_cents(Some(RouterResolution::FourEightyP), 4, 1), 21);
assert_eq!(cost_cents(Some(RouterResolution::FourEightyP), 5, 1), 26);
assert_eq!(cost_cents(Some(RouterResolution::FourEightyP), 10, 1), 52);
assert_eq!(cost_cents(Some(RouterResolution::FourEightyP), 15, 1), 78);
}
#[test]
fn batch_2() {
assert_eq!(cost_cents(Some(RouterResolution::FourEightyP), 5, 2), 71);
assert_eq!(cost_cents(Some(RouterResolution::FourEightyP), 5, 2), 52);
}
#[test]
fn batch_3() {
assert_eq!(cost_cents(Some(RouterResolution::FourEightyP), 5, 3), 107);
assert_eq!(cost_cents(Some(RouterResolution::FourEightyP), 5, 3), 78);
}
#[test]
fn batch_4() {
assert_eq!(cost_cents(Some(RouterResolution::FourEightyP), 5, 4), 143);
assert_eq!(cost_cents(Some(RouterResolution::FourEightyP), 5, 4), 104);
}
}
@@ -275,76 +275,6 @@ mod tests {
assert!(b1 < b2);
assert!(b2 < b4);
}
/// A video reference must never make a generation cheaper than the same
/// generation without one, at any resolution, duration, or batch size.
#[test]
fn no_reference_cheaper_than_with_reference() {
for resolution in [RouterResolution::FourEightyP, RouterResolution::SevenTwentyP] {
for duration in 4..=15u16 {
for batch in [1, 2, 4] {
let no_ref = cost_cents(Some(resolution), duration, batch);
let with_ref = cost_cents_with_video_ref(Some(resolution), duration, batch);
assert!(
no_ref < with_ref,
"{resolution:?} {duration}s batch {batch}: no-ref {no_ref}¢ should be cheaper than with-ref {with_ref}¢",
);
}
}
}
}
/// 480p must stay cheaper than 720p in the with-reference rate card too
/// (the no-reference case is covered by [`cost_480p_cheaper_than_720p`]).
#[test]
fn cost_480p_cheaper_than_720p_with_reference() {
for duration in 4..=15u16 {
let c480 = cost_cents_with_video_ref(Some(RouterResolution::FourEightyP), duration, 1);
let c720 = cost_cents_with_video_ref(Some(RouterResolution::SevenTwentyP), duration, 1);
assert!(c480 < c720, "{duration}s with-ref: 480p ({c480}¢) should be cheaper than 720p ({c720}¢)");
}
}
/// The BytePlus variants are premium tiers: plain Fast must stay cheaper
/// at every resolution, duration, and reference configuration.
#[test]
fn fast_cheaper_than_byteplus_variants() {
let premium_models = [
RouterVideoModel::Seedance2p0BytePlusFast,
RouterVideoModel::Seedance2p0BytePlusUltraFast,
];
for premium_model in premium_models {
for resolution in [RouterResolution::FourEightyP, RouterResolution::SevenTwentyP] {
for with_video_reference in [false, true] {
for duration in 4..=15u16 {
let plain = model_cost_cents(RouterVideoModel::Seedance2p0Fast, resolution, duration, 1, with_video_reference);
let premium = model_cost_cents(premium_model, resolution, duration, 1, with_video_reference);
assert!(
plain < premium,
"{premium_model:?} {resolution:?} {duration}s ref={with_video_reference}: plain Fast ({plain}¢) should be cheaper than the premium tier ({premium}¢)",
);
}
}
}
}
}
/// BytePlus Fast and BytePlus Ultra Fast share one rate card.
#[test]
fn byteplus_fast_and_ultra_fast_price_identically() {
for resolution in [RouterResolution::FourEightyP, RouterResolution::SevenTwentyP] {
for with_video_reference in [false, true] {
for duration in 4..=15u16 {
let bp = model_cost_cents(RouterVideoModel::Seedance2p0BytePlusFast, resolution, duration, 1, with_video_reference);
let bpu = model_cost_cents(RouterVideoModel::Seedance2p0BytePlusUltraFast, resolution, duration, 1, with_video_reference);
assert_eq!(
bp, bpu,
"{resolution:?} {duration}s ref={with_video_reference}: BytePlus Fast ({bp}¢) and Ultra Fast ({bpu}¢) should price identically",
);
}
}
}
}
}
// -- Credits equal cents --
@@ -429,32 +359,4 @@ mod tests {
.cost_in_usd_cents
.unwrap()
}
/// Like [`cost_cents`], for any Fast-tier model and reference configuration.
fn model_cost_cents(
model: RouterVideoModel,
resolution: RouterResolution,
duration_seconds: u16,
video_batch_count: u16,
with_video_reference: bool,
) -> u64 {
let reference_videos = with_video_reference.then(|| VideoListRef::MediaFileTokens(vec![
MediaFileToken::new("mf_ref".to_string()),
]));
let builder = GenerateVideoRequestBuilder {
model,
provider: RouterProvider::Artcraft,
resolution: Some(resolution),
duration_seconds: Some(duration_seconds),
video_batch_count: Some(video_batch_count),
reference_videos,
..Default::default()
};
builder.build2()
.expect("build2 should succeed")
.estimate_cost()
.expect("estimate_cost should succeed")
.cost_in_usd_cents
.unwrap()
}
}
@@ -65,18 +65,18 @@ mod tests {
#[test]
fn without_video_reference() {
assert_eq!(cents(RouterResolution::FourEightyP, 4, 1, false), 14);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 1, false), 18);
assert_eq!(cents(RouterResolution::FourEightyP, 10, 1, false), 35);
assert_eq!(cents(RouterResolution::FourEightyP, 15, 1, false), 52);
assert_eq!(cents(RouterResolution::FourEightyP, 4, 1, false), 13);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 1, false), 17);
assert_eq!(cents(RouterResolution::FourEightyP, 10, 1, false), 33);
assert_eq!(cents(RouterResolution::FourEightyP, 15, 1, false), 49);
}
#[test]
fn with_video_reference() {
assert_eq!(cents(RouterResolution::FourEightyP, 4, 1, true), 18);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 1, true), 22);
assert_eq!(cents(RouterResolution::FourEightyP, 10, 1, true), 44);
assert_eq!(cents(RouterResolution::FourEightyP, 15, 1, true), 66);
assert_eq!(cents(RouterResolution::FourEightyP, 4, 1, true), 17);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 1, true), 21);
assert_eq!(cents(RouterResolution::FourEightyP, 10, 1, true), 42);
assert_eq!(cents(RouterResolution::FourEightyP, 15, 1, true), 62);
}
}
@@ -85,18 +85,18 @@ mod tests {
#[test]
fn without_video_reference() {
assert_eq!(cents(RouterResolution::SevenTwentyP, 4, 1, false), 36);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 1, false), 45);
assert_eq!(cents(RouterResolution::SevenTwentyP, 10, 1, false), 89);
assert_eq!(cents(RouterResolution::SevenTwentyP, 15, 1, false), 134);
assert_eq!(cents(RouterResolution::SevenTwentyP, 4, 1, false), 35);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 1, false), 44);
assert_eq!(cents(RouterResolution::SevenTwentyP, 10, 1, false), 87);
assert_eq!(cents(RouterResolution::SevenTwentyP, 15, 1, false), 130);
}
#[test]
fn with_video_reference() {
assert_eq!(cents(RouterResolution::SevenTwentyP, 4, 1, true), 43);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 1, true), 54);
assert_eq!(cents(RouterResolution::SevenTwentyP, 10, 1, true), 108);
assert_eq!(cents(RouterResolution::SevenTwentyP, 15, 1, true), 161);
assert_eq!(cents(RouterResolution::SevenTwentyP, 4, 1, true), 42);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 1, true), 52);
assert_eq!(cents(RouterResolution::SevenTwentyP, 10, 1, true), 104);
assert_eq!(cents(RouterResolution::SevenTwentyP, 15, 1, true), 156);
}
#[test]
@@ -112,31 +112,31 @@ mod tests {
/// apply). Once, batch 8 executed in full but billed as batch 4.
#[test]
fn every_batch_size_720p_5s() {
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 1, false), 45);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 2, false), 89);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 3, false), 134);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 4, false), 178);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 5, false), 223);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 6, false), 267);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 7, false), 312);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 8, false), 356);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 1, false), 44);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 2, false), 87);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 3, false), 130);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 4, false), 173);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 5, false), 217);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 6, false), 260);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 7, false), 303);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 8, false), 346);
}
#[test]
fn every_batch_size_480p_5s() {
assert_eq!(cents(RouterResolution::FourEightyP, 5, 1, false), 18);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 2, false), 35);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 3, false), 52);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 4, false), 69);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 5, false), 87);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 6, false), 104);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 7, false), 121);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 8, false), 138);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 1, false), 17);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 2, false), 33);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 3, false), 49);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 4, false), 65);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 5, false), 82);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 6, false), 98);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 7, false), 114);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 8, false), 130);
}
#[test]
fn batch_eight_with_video_reference() {
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 8, true), 429);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 8, true), 415);
}
#[test]
@@ -53,7 +53,7 @@ pub fn build_artcraft_seedance_2p5(mut builder: GenerateVideoRequestBuilder) ->
let mut request = build_artcraft_omni_video_request(
builder,
CommonVideoModelEnum::Seedance2p5,
SupportedResolutions::Full,
SupportedResolutions::Fast,
UltraWideSupport::Supported,
)?;
request.duration_seconds = duration_seconds;
@@ -216,15 +216,9 @@ mod tests {
}
#[test]
fn res_1080p_maps_directly() {
fn res_1080p_downgrades_to_720p() {
let req = unwrap_request(builder_with(|b| { b.resolution = Some(RouterResolution::TenEightyP); }));
assert_eq!(req.request.resolution, Some(CommonResolutionEnum::TenEightyP));
}
#[test]
fn res_4k_downgrades_to_1080p() {
let req = unwrap_request(builder_with(|b| { b.resolution = Some(RouterResolution::FourK); }));
assert_eq!(req.request.resolution, Some(CommonResolutionEnum::TenEightyP));
assert_eq!(req.request.resolution, Some(CommonResolutionEnum::SevenTwentyP));
}
}
@@ -13,7 +13,7 @@ pub struct ArtcraftSeedance2p5CostState {
pub resolution: CommonResolution,
pub duration_seconds: u16,
pub has_video_references: bool,
pub maybe_total_input_seconds: Option<u16>,
pub total_input_seconds: u16,
}
impl ArtcraftSeedance2p5CostState {
@@ -30,21 +30,20 @@ impl ArtcraftSeedance2p5CostState {
resolution,
duration_seconds,
has_video_references,
maybe_total_input_seconds: request.total_input_seconds,
total_input_seconds: request.total_input_seconds.unwrap_or(0),
}
}
pub fn estimate_cost(&self) -> VideoGenerationCostEstimate {
// Input-second clamping (the 4..=30 billing range) and the
// unknown-or-zero-input failsafe happen inside the shared pricing
// function.
let maybe_total_input_seconds = self.maybe_total_input_seconds;
// Input-second clamping (the 4..=30 billing range) happens inside the
// shared pricing function.
let total_input_seconds = self.total_input_seconds;
let usd_cents = seedance_2p5_usd_cents(
self.resolution,
self.duration_seconds,
self.has_video_references,
maybe_total_input_seconds,
total_input_seconds,
);
// ArtCraft credits: 100 credits = $1.00, so credits = cents.
@@ -92,20 +91,6 @@ mod tests {
assert_eq!(cents(Some(RouterResolution::SevenTwentyP), 30), 802);
}
#[test]
fn table_1080p() {
// 45.85869386 ¢/s, rounded up.
assert_eq!(cents(Some(RouterResolution::TenEightyP), 4), 184);
assert_eq!(cents(Some(RouterResolution::TenEightyP), 5), 230);
assert_eq!(cents(Some(RouterResolution::TenEightyP), 10), 459);
assert_eq!(cents(Some(RouterResolution::TenEightyP), 30), 1376);
}
#[test]
fn four_k_downgrades_to_1080p_and_prices_accordingly() {
assert_eq!(cents(Some(RouterResolution::FourK), 10), cents(Some(RouterResolution::TenEightyP), 10));
}
#[test]
fn none_defaults_to_720p() {
assert_eq!(cents(None, 10), cents(Some(RouterResolution::SevenTwentyP), 10));
@@ -121,16 +106,6 @@ mod tests {
assert_eq!(cents_with_video_refs(Some(RouterResolution::FourEightyP), 30, Some(10)), 290);
// 15.84362140 ¢/s × 40 = 633.74 → 634¢.
assert_eq!(cents_with_video_refs(Some(RouterResolution::SevenTwentyP), 30, Some(10)), 634);
// 27.39973680 ¢/s × 40 = 1095.99 → 1096¢.
assert_eq!(cents_with_video_refs(Some(RouterResolution::TenEightyP), 30, Some(10)), 1096);
}
#[test]
fn table_1080p_with_ten_input_seconds() {
// 27.39973680 ¢/s over (output + 10) billed seconds, rounded up.
assert_eq!(cents_with_video_refs(Some(RouterResolution::TenEightyP), 5, Some(10)), 411);
assert_eq!(cents_with_video_refs(Some(RouterResolution::TenEightyP), 10, Some(10)), 548);
assert_eq!(cents_with_video_refs(Some(RouterResolution::TenEightyP), 30, Some(10)), 1096);
}
#[test]
@@ -140,12 +115,10 @@ mod tests {
}
#[test]
fn missing_or_zero_input_seconds_bill_the_thirty_second_maximum() {
// FAILSAFE: an unmeasured (or zero) input bills the 30-second MAXIMUM,
// matching the provider client's fallback:
// 7.24279835 ¢/s × (10+30) = 289.71 → 290¢.
assert_eq!(cents_with_video_refs(Some(RouterResolution::FourEightyP), 10, None), 290);
assert_eq!(cents_with_video_refs(Some(RouterResolution::FourEightyP), 10, Some(0)), 290);
fn missing_input_seconds_bill_the_four_second_minimum() {
// No measured input still bills the 4-second total minimum:
// 7.24279835 ¢/s × (10+4) = 101.40 → 102¢.
assert_eq!(cents_with_video_refs(Some(RouterResolution::FourEightyP), 10, None), 102);
}
#[test]
@@ -53,7 +53,7 @@ pub fn build_artcraft_seedance_2p5_u(mut builder: GenerateVideoRequestBuilder) -
let mut request = build_artcraft_omni_video_request(
builder,
CommonVideoModelEnum::Seedance2p5Ultra,
SupportedResolutions::Full,
SupportedResolutions::Fast,
UltraWideSupport::Supported,
)?;
request.duration_seconds = duration_seconds;
@@ -216,15 +216,9 @@ mod tests {
}
#[test]
fn res_1080p_maps_directly() {
fn res_1080p_downgrades_to_720p() {
let req = unwrap_request(builder_with(|b| { b.resolution = Some(RouterResolution::TenEightyP); }));
assert_eq!(req.request.resolution, Some(CommonResolutionEnum::TenEightyP));
}
#[test]
fn res_4k_downgrades_to_1080p() {
let req = unwrap_request(builder_with(|b| { b.resolution = Some(RouterResolution::FourK); }));
assert_eq!(req.request.resolution, Some(CommonResolutionEnum::TenEightyP));
assert_eq!(req.request.resolution, Some(CommonResolutionEnum::SevenTwentyP));
}
}
@@ -14,7 +14,7 @@ pub struct ArtcraftSeedance2p5UltraCostState {
pub resolution: CommonResolution,
pub duration_seconds: u16,
pub has_video_references: bool,
pub maybe_total_input_seconds: Option<u16>,
pub total_input_seconds: u16,
}
impl ArtcraftSeedance2p5UltraCostState {
@@ -31,21 +31,20 @@ impl ArtcraftSeedance2p5UltraCostState {
resolution,
duration_seconds,
has_video_references,
maybe_total_input_seconds: request.total_input_seconds,
total_input_seconds: request.total_input_seconds.unwrap_or(0),
}
}
pub fn estimate_cost(&self) -> VideoGenerationCostEstimate {
// Input-second clamping (the 4..=30 billing range) and the
// unknown-or-zero-input failsafe happen inside the shared pricing
// function.
let maybe_total_input_seconds = self.maybe_total_input_seconds;
// Input-second clamping (the 4..=30 billing range) happens inside the
// shared pricing function.
let total_input_seconds = self.total_input_seconds;
let usd_cents = seedance_2p5_ultra_usd_cents(
self.resolution,
self.duration_seconds,
self.has_video_references,
maybe_total_input_seconds,
total_input_seconds,
);
// ArtCraft credits: 100 credits = $1.00, so credits = cents.
@@ -93,20 +92,6 @@ mod tests {
assert_eq!(cents(Some(RouterResolution::SevenTwentyP), 30), 947);
}
#[test]
fn table_1080p() {
// 50.10486922 ¢/s, rounded up.
assert_eq!(cents(Some(RouterResolution::TenEightyP), 4), 201);
assert_eq!(cents(Some(RouterResolution::TenEightyP), 5), 251);
assert_eq!(cents(Some(RouterResolution::TenEightyP), 10), 502);
assert_eq!(cents(Some(RouterResolution::TenEightyP), 30), 1504);
}
#[test]
fn four_k_downgrades_to_1080p_and_prices_accordingly() {
assert_eq!(cents(Some(RouterResolution::FourK), 10), cents(Some(RouterResolution::TenEightyP), 10));
}
#[test]
fn none_defaults_to_720p() {
assert_eq!(cents(None, 10), cents(Some(RouterResolution::SevenTwentyP), 10));
@@ -119,8 +104,6 @@ mod tests {
(RouterResolution::FourEightyP, 30),
(RouterResolution::SevenTwentyP, 5),
(RouterResolution::SevenTwentyP, 30),
(RouterResolution::TenEightyP, 5),
(RouterResolution::TenEightyP, 30),
] {
let ultra = cents(Some(resolution), duration);
let regular = estimate_for_model(RouterVideoModel::Seedance2p5, |b| {
@@ -141,16 +124,6 @@ mod tests {
assert_eq!(cents_with_video_refs(Some(RouterResolution::FourEightyP), 30, Some(10)), 343);
// 18.72427984 ¢/s × 40 = 748.97 → 749¢.
assert_eq!(cents_with_video_refs(Some(RouterResolution::SevenTwentyP), 30, Some(10)), 749);
// 29.93674947 ¢/s × 40 = 1197.47 → 1198¢.
assert_eq!(cents_with_video_refs(Some(RouterResolution::TenEightyP), 30, Some(10)), 1198);
}
#[test]
fn table_1080p_with_ten_input_seconds() {
// 29.93674947 ¢/s over (output + 10) billed seconds, rounded up.
assert_eq!(cents_with_video_refs(Some(RouterResolution::TenEightyP), 5, Some(10)), 450);
assert_eq!(cents_with_video_refs(Some(RouterResolution::TenEightyP), 10, Some(10)), 599);
assert_eq!(cents_with_video_refs(Some(RouterResolution::TenEightyP), 30, Some(10)), 1198);
}
#[test]
@@ -160,12 +133,10 @@ mod tests {
}
#[test]
fn missing_or_zero_input_seconds_bill_the_thirty_second_maximum() {
// FAILSAFE: an unmeasured (or zero) input bills the 30-second MAXIMUM,
// matching the provider client's fallback:
// 8.55967078 ¢/s × (10+30) = 342.39 → 343¢.
assert_eq!(cents_with_video_refs(Some(RouterResolution::FourEightyP), 10, None), 343);
assert_eq!(cents_with_video_refs(Some(RouterResolution::FourEightyP), 10, Some(0)), 343);
fn missing_input_seconds_bill_the_four_second_minimum() {
// No measured input still bills the 4-second total minimum:
// 8.55967078 ¢/s × (10+4) = 119.84 → 120¢.
assert_eq!(cents_with_video_refs(Some(RouterResolution::FourEightyP), 10, None), 120);
}
#[test]
@@ -11,19 +11,30 @@ use kinovi_web_client::generate::video::generate_seedance_2p5::{
// in hundredths of a USD cent per second so the math is exact integer arithmetic
// (no floating point), then rounded up to whole cents.
/// 4K output price, in hundredths of a USD cent per second (92.50 ¢/s).
const FOUR_K_CENTI_CENTS_PER_SECOND: u64 = 9250;
/// 4K output price, in hundredths of a USD cent per second (86.60 ¢/s).
const FOUR_K_CENTI_CENTS_PER_SECOND: u64 = 8660;
/// ArtCraft's price (USD cents) for Seedance 2.0 at 4K with no reference
/// videos attached. Each model prices reference videos through its own
/// with-reference rate card. The cost scales with duration and batch count,
/// rounded up to whole cents.
/// Extra hundredths of a USD cent per second when a reference video is attached
/// at 4K (17.20 ¢/s surcharge).
const FOUR_K_VIDEO_REFERENCE_SURCHARGE_CENTI_CENTS_PER_SECOND: u64 = 1720;
/// ArtCraft's price (USD cents) for Seedance 2.0 at 4K.
///
/// A reference video adds a per-second surcharge (4K with and without a video
/// reference are priced differently). The cost scales with duration and batch
/// count, rounded up to whole cents.
pub fn seedance_2p0_four_k_usd_cents(
duration_seconds: u16,
batch_count: u16,
has_video_reference: bool,
) -> u64 {
let mut centi_cents_per_second = FOUR_K_CENTI_CENTS_PER_SECOND;
if has_video_reference {
centi_cents_per_second += FOUR_K_VIDEO_REFERENCE_SURCHARGE_CENTI_CENTS_PER_SECOND;
}
let total_centi_cents =
FOUR_K_CENTI_CENTS_PER_SECOND * duration_seconds as u64 * batch_count as u64;
centi_cents_per_second * duration_seconds as u64 * batch_count as u64;
// Round up to whole cents.
total_centi_cents.div_ceil(100)
@@ -40,22 +51,22 @@ pub fn seedance_2p0_four_k_usd_cents(
// rate sets and helpers below.
/// Regular Mini — 480p price, USD cents per second.
const MINI_CENTS_PER_SECOND_480P: f64 = 3.45;
const MINI_CENTS_PER_SECOND_480P: f64 = 3.24074074;
/// Regular Mini — 480p reference-video surcharge, USD cents per second.
const MINI_VIDEO_REFERENCE_SURCHARGE_CENTS_PER_SECOND_480P: f64 = 0.90;
const MINI_VIDEO_REFERENCE_SURCHARGE_CENTS_PER_SECOND_480P: f64 = 0.86419753;
/// Regular Mini — 720p price, USD cents per second.
const MINI_CENTS_PER_SECOND_720P: f64 = 8.90;
const MINI_CENTS_PER_SECOND_720P: f64 = 8.64197531;
/// Regular Mini — 720p reference-video surcharge, USD cents per second.
const MINI_VIDEO_REFERENCE_SURCHARGE_CENTS_PER_SECOND_720P: f64 = 1.80;
const MINI_VIDEO_REFERENCE_SURCHARGE_CENTS_PER_SECOND_720P: f64 = 1.72839506;
/// BytePlus / BytePlus Ultra Mini — 480p price, USD cents per second.
const BYTEPLUS_MINI_CENTS_PER_SECOND_480P: f64 = 3.55;
const BYTEPLUS_MINI_CENTS_PER_SECOND_480P: f64 = 3.27160494;
/// BytePlus / BytePlus Ultra Mini — 480p reference-video surcharge, USD cents per second.
const BYTEPLUS_MINI_VIDEO_REFERENCE_SURCHARGE_CENTS_PER_SECOND_480P: f64 = 0.95;
const BYTEPLUS_MINI_VIDEO_REFERENCE_SURCHARGE_CENTS_PER_SECOND_480P: f64 = 0.87242798;
/// BytePlus / BytePlus Ultra Mini — 720p price, USD cents per second.
const BYTEPLUS_MINI_CENTS_PER_SECOND_720P: f64 = 9.10;
const BYTEPLUS_MINI_CENTS_PER_SECOND_720P: f64 = 8.72427984;
/// BytePlus / BytePlus Ultra Mini — 720p reference-video surcharge, USD cents per second.
const BYTEPLUS_MINI_VIDEO_REFERENCE_SURCHARGE_CENTS_PER_SECOND_720P: f64 = 1.85;
const BYTEPLUS_MINI_VIDEO_REFERENCE_SURCHARGE_CENTS_PER_SECOND_720P: f64 = 1.74485597;
/// ArtCraft's price (USD cents) for the regular Seedance 2.0 Mini.
///
@@ -137,56 +148,39 @@ pub fn seedance_2p5_preview_usd_cents(
const SEEDANCE_2P5_CENTS_PER_SECOND_480P: f64 = 11.76954733;
/// Seedance 2.5 — 720p price, USD cents per second.
const SEEDANCE_2P5_CENTS_PER_SECOND_720P: f64 = 26.70781893;
/// Seedance 2.5 — 1080p price, USD cents per second.
const SEEDANCE_2P5_CENTS_PER_SECOND_1080P: f64 = 45.85869386;
/// Seedance 2.5 — 480p price with video references, USD cents per second.
const SEEDANCE_2P5_VIDEO_REFERENCE_CENTS_PER_SECOND_480P: f64 = 7.24279835;
/// Seedance 2.5 — 720p price with video references, USD cents per second.
const SEEDANCE_2P5_VIDEO_REFERENCE_CENTS_PER_SECOND_720P: f64 = 15.84362140;
/// Seedance 2.5 — 1080p price with video references, USD cents per second.
const SEEDANCE_2P5_VIDEO_REFERENCE_CENTS_PER_SECOND_1080P: f64 = 27.39973680;
/// ArtCraft's price (USD cents) for Seedance 2.5.
///
/// 480p, 720p, and 1080p are offered; any other resolution prices at 720p
/// (the request planner maps unsupported resolutions before pricing, so
/// this fallback is only a failsafe). Without video references, billed
/// seconds = output duration. With video references, the per-second rate
/// drops but the billed seconds are the output duration PLUS the total
/// seconds of reference video input (clamped to the 4..=30 second billing
/// range). The fractional total is rounded UP to a whole cent. No batching.
/// Only 480p and 720p are offered; any other resolution prices at 720p.
/// Without video references, billed seconds = output duration. With video
/// references, the per-second rate drops but the billed seconds are the
/// output duration PLUS the total seconds of reference video input (clamped
/// to the 4..=30 second billing range). The fractional total is rounded UP
/// to a whole cent. No batching.
pub fn seedance_2p5_usd_cents(
resolution: CommonResolution,
duration_seconds: u16,
has_video_references: bool,
maybe_total_input_seconds: Option<u16>,
total_input_seconds: u16,
) -> u64 {
let (cents_per_second, billed_seconds) = if has_video_references {
let rate = match resolution {
CommonResolution::FourEightyP => SEEDANCE_2P5_VIDEO_REFERENCE_CENTS_PER_SECOND_480P,
CommonResolution::TenEightyP => SEEDANCE_2P5_VIDEO_REFERENCE_CENTS_PER_SECOND_1080P,
// Everything else (including 720p and unsupported resolutions) prices at 720p.
_ => SEEDANCE_2P5_VIDEO_REFERENCE_CENTS_PER_SECOND_720P,
};
// The TOTAL input duration clamps to the 4..=30 second billing range
// (three 1s videos sum to 3 and bill 4; three 3s videos bill 9).
//
// FAILSAFE: an unknown (never probed) or zero input duration bills the
// 30-second MAXIMUM, matching the provider client's own fallback. It
// must never default toward the minimum — billing 4 input seconds for
// an unmeasured input while the provider assumes 30 sells input seconds
// far below cost.
let billed_input_seconds = match maybe_total_input_seconds {
None | Some(0) => u16::from(MAX_BILLED_INPUT_SECONDS),
Some(seconds) => {
seconds.clamp(u16::from(MIN_BILLED_INPUT_SECONDS), u16::from(MAX_BILLED_INPUT_SECONDS))
}
};
let billed_input_seconds = total_input_seconds
.clamp(u16::from(MIN_BILLED_INPUT_SECONDS), u16::from(MAX_BILLED_INPUT_SECONDS));
(rate, u64::from(duration_seconds) + u64::from(billed_input_seconds))
} else {
let rate = match resolution {
CommonResolution::FourEightyP => SEEDANCE_2P5_CENTS_PER_SECOND_480P,
CommonResolution::TenEightyP => SEEDANCE_2P5_CENTS_PER_SECOND_1080P,
_ => SEEDANCE_2P5_CENTS_PER_SECOND_720P,
};
(rate, u64::from(duration_seconds))
@@ -199,56 +193,38 @@ pub fn seedance_2p5_usd_cents(
const SEEDANCE_2P5_ULTRA_CENTS_PER_SECOND_480P: f64 = 13.90946502;
/// Seedance 2.5 Ultra — 720p price, USD cents per second.
const SEEDANCE_2P5_ULTRA_CENTS_PER_SECOND_720P: f64 = 31.56378601;
/// Seedance 2.5 Ultra — 1080p price, USD cents per second.
const SEEDANCE_2P5_ULTRA_CENTS_PER_SECOND_1080P: f64 = 50.10486922;
/// Seedance 2.5 Ultra — 480p price with video references, USD cents per second.
const SEEDANCE_2P5_ULTRA_VIDEO_REFERENCE_CENTS_PER_SECOND_480P: f64 = 8.55967078;
/// Seedance 2.5 Ultra — 720p price with video references, USD cents per second.
const SEEDANCE_2P5_ULTRA_VIDEO_REFERENCE_CENTS_PER_SECOND_720P: f64 = 18.72427984;
/// Seedance 2.5 Ultra — 1080p price with video references, USD cents per second.
const SEEDANCE_2P5_ULTRA_VIDEO_REFERENCE_CENTS_PER_SECOND_1080P: f64 = 29.93674947;
/// ArtCraft's price (USD cents) for Seedance 2.5 Ultra.
///
/// 480p, 720p, and 1080p are offered; any other resolution prices at 720p
/// (the request planner maps unsupported resolutions before pricing, so
/// this fallback is only a failsafe). Without video references, billed
/// seconds = output duration. With video references, the per-second rate
/// drops but the billed seconds are the output duration PLUS the total
/// seconds of reference video input. The fractional total is rounded UP to
/// a whole cent. No batching.
/// Only 480p and 720p are offered; any other resolution prices at 720p.
/// Without video references, billed seconds = output duration. With video
/// references, the per-second rate drops but the billed seconds are the
/// output duration PLUS the total seconds of reference video input. The
/// fractional total is rounded UP to a whole cent. No batching.
pub fn seedance_2p5_ultra_usd_cents(
resolution: CommonResolution,
duration_seconds: u16,
has_video_references: bool,
maybe_total_input_seconds: Option<u16>,
total_input_seconds: u16,
) -> u64 {
let (cents_per_second, billed_seconds) = if has_video_references {
let rate = match resolution {
CommonResolution::FourEightyP => SEEDANCE_2P5_ULTRA_VIDEO_REFERENCE_CENTS_PER_SECOND_480P,
CommonResolution::TenEightyP => SEEDANCE_2P5_ULTRA_VIDEO_REFERENCE_CENTS_PER_SECOND_1080P,
// Everything else (including 720p and unsupported resolutions) prices at 720p.
_ => SEEDANCE_2P5_ULTRA_VIDEO_REFERENCE_CENTS_PER_SECOND_720P,
};
// The TOTAL input duration clamps to the 4..=30 second billing range
// (three 1s videos sum to 3 and bill 4; three 3s videos bill 9).
//
// FAILSAFE: an unknown (never probed) or zero input duration bills the
// 30-second MAXIMUM, matching the provider client's own fallback. It
// must never default toward the minimum — billing 4 input seconds for
// an unmeasured input while the provider assumes 30 sells input seconds
// far below cost.
let billed_input_seconds = match maybe_total_input_seconds {
None | Some(0) => u16::from(MAX_BILLED_INPUT_SECONDS),
Some(seconds) => {
seconds.clamp(u16::from(MIN_BILLED_INPUT_SECONDS), u16::from(MAX_BILLED_INPUT_SECONDS))
}
};
let billed_input_seconds = total_input_seconds
.clamp(u16::from(MIN_BILLED_INPUT_SECONDS), u16::from(MAX_BILLED_INPUT_SECONDS));
(rate, u64::from(duration_seconds) + u64::from(billed_input_seconds))
} else {
let rate = match resolution {
CommonResolution::FourEightyP => SEEDANCE_2P5_ULTRA_CENTS_PER_SECOND_480P,
CommonResolution::TenEightyP => SEEDANCE_2P5_ULTRA_CENTS_PER_SECOND_1080P,
_ => SEEDANCE_2P5_ULTRA_CENTS_PER_SECOND_720P,
};
(rate, u64::from(duration_seconds))
@@ -287,17 +263,37 @@ mod tests {
use super::*;
#[test]
fn four_k_base_prices() {
assert_eq!(seedance_2p0_four_k_usd_cents(4, 1), 370);
assert_eq!(seedance_2p0_four_k_usd_cents(5, 1), 463);
assert_eq!(seedance_2p0_four_k_usd_cents(10, 1), 925);
assert_eq!(seedance_2p0_four_k_usd_cents(15, 1), 1388);
fn four_k_without_video_reference() {
assert_eq!(seedance_2p0_four_k_usd_cents(4, 1, false), 347);
assert_eq!(seedance_2p0_four_k_usd_cents(5, 1, false), 433);
assert_eq!(seedance_2p0_four_k_usd_cents(10, 1, false), 866);
assert_eq!(seedance_2p0_four_k_usd_cents(15, 1, false), 1299);
}
#[test]
fn four_k_with_video_reference() {
assert_eq!(seedance_2p0_four_k_usd_cents(4, 1, true), 416);
assert_eq!(seedance_2p0_four_k_usd_cents(5, 1, true), 519);
assert_eq!(seedance_2p0_four_k_usd_cents(10, 1, true), 1038);
assert_eq!(seedance_2p0_four_k_usd_cents(15, 1, true), 1557);
}
#[test]
fn video_reference_always_costs_more() {
for &duration in &[4u16, 5, 10, 15] {
assert!(
seedance_2p0_four_k_usd_cents(duration, 1, true)
> seedance_2p0_four_k_usd_cents(duration, 1, false),
"video reference should cost more at {duration}s",
);
}
}
#[test]
fn batch_count_multiplies() {
assert_eq!(seedance_2p0_four_k_usd_cents(5, 2), 925);
assert_eq!(seedance_2p0_four_k_usd_cents(5, 4), 1850);
assert_eq!(seedance_2p0_four_k_usd_cents(5, 2, false), 866);
assert_eq!(seedance_2p0_four_k_usd_cents(5, 4, false), 1732);
assert_eq!(seedance_2p0_four_k_usd_cents(5, 2, true), 1038);
}
// ── Seedance 2.0 Mini ──
@@ -314,34 +310,34 @@ mod tests {
#[test]
fn four_eighty_p_without_video_reference() {
assert_eq!(cents(CommonResolution::FourEightyP, 4, false), 14);
assert_eq!(cents(CommonResolution::FourEightyP, 5, false), 18);
assert_eq!(cents(CommonResolution::FourEightyP, 10, false), 35);
assert_eq!(cents(CommonResolution::FourEightyP, 15, false), 52);
assert_eq!(cents(CommonResolution::FourEightyP, 4, false), 13);
assert_eq!(cents(CommonResolution::FourEightyP, 5, false), 17);
assert_eq!(cents(CommonResolution::FourEightyP, 10, false), 33);
assert_eq!(cents(CommonResolution::FourEightyP, 15, false), 49);
}
#[test]
fn four_eighty_p_with_video_reference() {
assert_eq!(cents(CommonResolution::FourEightyP, 4, true), 18);
assert_eq!(cents(CommonResolution::FourEightyP, 5, true), 22);
assert_eq!(cents(CommonResolution::FourEightyP, 10, true), 44);
assert_eq!(cents(CommonResolution::FourEightyP, 15, true), 66);
assert_eq!(cents(CommonResolution::FourEightyP, 4, true), 17);
assert_eq!(cents(CommonResolution::FourEightyP, 5, true), 21);
assert_eq!(cents(CommonResolution::FourEightyP, 10, true), 42);
assert_eq!(cents(CommonResolution::FourEightyP, 15, true), 62);
}
#[test]
fn seven_twenty_p_without_video_reference() {
assert_eq!(cents(CommonResolution::SevenTwentyP, 4, false), 36);
assert_eq!(cents(CommonResolution::SevenTwentyP, 5, false), 45);
assert_eq!(cents(CommonResolution::SevenTwentyP, 10, false), 89);
assert_eq!(cents(CommonResolution::SevenTwentyP, 15, false), 134);
assert_eq!(cents(CommonResolution::SevenTwentyP, 4, false), 35);
assert_eq!(cents(CommonResolution::SevenTwentyP, 5, false), 44);
assert_eq!(cents(CommonResolution::SevenTwentyP, 10, false), 87);
assert_eq!(cents(CommonResolution::SevenTwentyP, 15, false), 130);
}
#[test]
fn seven_twenty_p_with_video_reference() {
assert_eq!(cents(CommonResolution::SevenTwentyP, 4, true), 43);
assert_eq!(cents(CommonResolution::SevenTwentyP, 5, true), 54);
assert_eq!(cents(CommonResolution::SevenTwentyP, 10, true), 108);
assert_eq!(cents(CommonResolution::SevenTwentyP, 15, true), 161);
assert_eq!(cents(CommonResolution::SevenTwentyP, 4, true), 42);
assert_eq!(cents(CommonResolution::SevenTwentyP, 5, true), 52);
assert_eq!(cents(CommonResolution::SevenTwentyP, 10, true), 104);
assert_eq!(cents(CommonResolution::SevenTwentyP, 15, true), 156);
}
#[test]
@@ -368,9 +364,9 @@ mod tests {
fn batch_count_scales_the_total() {
// Batch is baked in before the single round-up, so batched totals can be
// a cent under N× the single price.
assert_eq!(seedance_2p0_mini_usd_cents(CommonResolution::SevenTwentyP, 5, 2, false), 89);
assert_eq!(seedance_2p0_mini_usd_cents(CommonResolution::SevenTwentyP, 5, 4, false), 178);
assert_eq!(seedance_2p0_mini_usd_cents(CommonResolution::FourEightyP, 5, 2, false), 35);
assert_eq!(seedance_2p0_mini_usd_cents(CommonResolution::SevenTwentyP, 5, 2, false), 87);
assert_eq!(seedance_2p0_mini_usd_cents(CommonResolution::SevenTwentyP, 5, 4, false), 173);
assert_eq!(seedance_2p0_mini_usd_cents(CommonResolution::FourEightyP, 5, 2, false), 33);
}
}
@@ -388,34 +384,34 @@ mod tests {
#[test]
fn four_eighty_p_without_video_reference() {
assert_eq!(cents(CommonResolution::FourEightyP, 4, false), 15);
assert_eq!(cents(CommonResolution::FourEightyP, 5, false), 18);
assert_eq!(cents(CommonResolution::FourEightyP, 10, false), 36);
assert_eq!(cents(CommonResolution::FourEightyP, 15, false), 54);
assert_eq!(cents(CommonResolution::FourEightyP, 4, false), 14);
assert_eq!(cents(CommonResolution::FourEightyP, 5, false), 17);
assert_eq!(cents(CommonResolution::FourEightyP, 10, false), 33);
assert_eq!(cents(CommonResolution::FourEightyP, 15, false), 50);
}
#[test]
fn four_eighty_p_with_video_reference() {
assert_eq!(cents(CommonResolution::FourEightyP, 4, true), 18);
assert_eq!(cents(CommonResolution::FourEightyP, 5, true), 23);
assert_eq!(cents(CommonResolution::FourEightyP, 10, true), 45);
assert_eq!(cents(CommonResolution::FourEightyP, 15, true), 68);
assert_eq!(cents(CommonResolution::FourEightyP, 4, true), 17);
assert_eq!(cents(CommonResolution::FourEightyP, 5, true), 21);
assert_eq!(cents(CommonResolution::FourEightyP, 10, true), 42);
assert_eq!(cents(CommonResolution::FourEightyP, 15, true), 63);
}
#[test]
fn seven_twenty_p_without_video_reference() {
assert_eq!(cents(CommonResolution::SevenTwentyP, 4, false), 37);
assert_eq!(cents(CommonResolution::SevenTwentyP, 5, false), 46);
assert_eq!(cents(CommonResolution::SevenTwentyP, 10, false), 91);
assert_eq!(cents(CommonResolution::SevenTwentyP, 15, false), 137);
assert_eq!(cents(CommonResolution::SevenTwentyP, 4, false), 35);
assert_eq!(cents(CommonResolution::SevenTwentyP, 5, false), 44);
assert_eq!(cents(CommonResolution::SevenTwentyP, 10, false), 88);
assert_eq!(cents(CommonResolution::SevenTwentyP, 15, false), 131);
}
#[test]
fn seven_twenty_p_with_video_reference() {
assert_eq!(cents(CommonResolution::SevenTwentyP, 4, true), 44);
assert_eq!(cents(CommonResolution::SevenTwentyP, 5, true), 55);
assert_eq!(cents(CommonResolution::SevenTwentyP, 10, true), 110);
assert_eq!(cents(CommonResolution::SevenTwentyP, 15, true), 165);
assert_eq!(cents(CommonResolution::SevenTwentyP, 4, true), 42);
assert_eq!(cents(CommonResolution::SevenTwentyP, 5, true), 53);
assert_eq!(cents(CommonResolution::SevenTwentyP, 10, true), 105);
assert_eq!(cents(CommonResolution::SevenTwentyP, 15, true), 158);
}
#[test]
@@ -443,9 +439,9 @@ mod tests {
#[test]
fn batch_count_scales_the_total() {
assert_eq!(seedance_2p0_byteplus_mini_usd_cents(CommonResolution::SevenTwentyP, 5, 2, false), 91);
assert_eq!(seedance_2p0_byteplus_mini_usd_cents(CommonResolution::SevenTwentyP, 5, 4, false), 182);
assert_eq!(seedance_2p0_byteplus_mini_usd_cents(CommonResolution::FourEightyP, 5, 2, false), 36);
assert_eq!(seedance_2p0_byteplus_mini_usd_cents(CommonResolution::SevenTwentyP, 5, 2, false), 88);
assert_eq!(seedance_2p0_byteplus_mini_usd_cents(CommonResolution::SevenTwentyP, 5, 4, false), 175);
assert_eq!(seedance_2p0_byteplus_mini_usd_cents(CommonResolution::FourEightyP, 5, 2, false), 33);
}
}
}
@@ -11,8 +11,8 @@ impl ArtcraftVeo3CostState {
pub fn from_request(request: &ArtcraftVeo3RequestState) -> Self {
Self {
duration_seconds: duration_seconds_for_cost(request.request.duration_seconds),
// Unset defaults to audio on.
generate_audio: request.request.generate_audio.unwrap_or(true),
// v1 legacy Veo 3 handler defaults generate_audio to false.
generate_audio: request.request.generate_audio.unwrap_or(false),
}
}
@@ -81,7 +81,8 @@ mod tests {
}
#[test]
fn audio_default_is_on() {
assert_eq!(cost_cents(Some(8), None), cost_cents(Some(8), Some(true)));
fn audio_default_is_off() {
// None → audio defaults to false.
assert_eq!(cost_cents(Some(8), None), cost_cents(Some(8), Some(false)));
}
}
@@ -1,32 +1,22 @@
use crate::generate::generate_video::video_generation_cost_estimate::VideoGenerationCostEstimate;
use crate::generate::generate_video::providers::artcraft::veo_3_fast::request::ArtcraftVeo3FastRequestState;
/// Per-second rates in hundredths of a US cent.
const CENTI_CENTS_PER_SECOND_AUDIO_OFF: u64 = 1_150;
const CENTI_CENTS_PER_SECOND_AUDIO_ON: u64 = 1_725;
#[derive(Clone, Debug)]
pub struct ArtcraftVeo3FastCostState {
pub duration_seconds: u64,
pub generate_audio: bool,
}
impl ArtcraftVeo3FastCostState {
pub fn from_request(request: &ArtcraftVeo3FastRequestState) -> Self {
Self {
duration_seconds: duration_seconds_for_cost(request.request.duration_seconds),
// Unset defaults to audio on.
generate_audio: request.request.generate_audio.unwrap_or(true),
// v1 legacy Veo 3 Fast handler defaults generate_audio to false.
generate_audio: request.request.generate_audio.unwrap_or(false),
}
}
pub fn estimate_cost(&self) -> VideoGenerationCostEstimate {
let rate = if self.generate_audio {
CENTI_CENTS_PER_SECOND_AUDIO_ON
} else {
CENTI_CENTS_PER_SECOND_AUDIO_OFF
};
let cost_in_usd_cents = (rate * self.duration_seconds).div_ceil(100);
// Flat per-video price: 88¢ audio off, 132¢ audio on.
let cost_in_usd_cents: u64 = if self.generate_audio { 132 } else { 88 };
VideoGenerationCostEstimate {
cost_in_credits: Some(cost_in_usd_cents),
@@ -40,16 +30,6 @@ impl ArtcraftVeo3FastCostState {
}
}
/// Mirrors Veo 3's `duration_seconds_for_cost`: s≤4 → 4, s≤6 → 6, else → 8
/// (incl. None and 7+).
fn duration_seconds_for_cost(d: Option<u16>) -> u64 {
match d {
Some(s) if s <= 4 => 4,
Some(s) if s <= 6 => 6,
_ => 8,
}
}
#[cfg(test)]
mod tests {
use crate::api::router_video_model::RouterVideoModel;
@@ -69,34 +49,22 @@ mod tests {
}
#[test]
fn audio_off_4s_is_46() { assert_eq!(cost_cents(Some(4), Some(false)), 46); }
fn audio_off_is_88() { assert_eq!(cost_cents(Some(8), Some(false)), 88); }
#[test]
fn audio_off_6s_is_69() { assert_eq!(cost_cents(Some(6), Some(false)), 69); }
fn audio_on_is_132() { assert_eq!(cost_cents(Some(8), Some(true)), 132); }
#[test]
fn audio_off_8s_is_92() { assert_eq!(cost_cents(Some(8), Some(false)), 92); }
#[test]
fn audio_on_4s_is_69() { assert_eq!(cost_cents(Some(4), Some(true)), 69); }
#[test]
fn audio_on_6s_is_104() {
// 1725 × 6 = 10350 hundredth-cents → 104 cents (rounded up).
assert_eq!(cost_cents(Some(6), Some(true)), 104);
fn audio_default_is_off() {
assert_eq!(cost_cents(Some(8), None), 88);
}
#[test]
fn audio_on_8s_is_138() { assert_eq!(cost_cents(Some(8), Some(true)), 138); }
#[test]
fn default_duration_is_8s() {
assert_eq!(cost_cents(None, Some(false)), cost_cents(Some(8), Some(false)));
fn duration_does_not_affect_cost() {
// v1 always bills 8s regardless of duration_seconds.
assert_eq!(cost_cents(Some(4), Some(false)), 88);
assert_eq!(cost_cents(Some(6), Some(false)), 88);
assert_eq!(cost_cents(Some(8), Some(false)), 88);
assert_eq!(cost_cents(None, Some(false)), 88);
}
#[test]
fn audio_default_is_on() {
assert_eq!(cost_cents(Some(8), None), cost_cents(Some(8), Some(true)));
}
}
@@ -1,4 +0,0 @@
//! Models fulfilled on first-party infrastructure; enqueued directly by
//! storyteller-web rather than routed.
pub mod minimax_h3_ultra_cost;
@@ -100,10 +100,7 @@ fn plan_output_resolution(
strategy: RequestMismatchMitigationStrategy,
) -> Result<Option<KinoviHappyHorse1p0OutputResolution>, ArtcraftRouterError> {
match resolution {
// Unset defaults to explicit 720p. Cost estimation prices unset as 720p,
// so the request must pin 720p too — never leave the resolution up to the
// provider's server-side default, or billing and supplier cost can diverge.
None => Ok(Some(KinoviHappyHorse1p0OutputResolution::SevenTwentyP)),
None => Ok(None),
Some(RouterResolution::SevenTwentyP) => Ok(Some(KinoviHappyHorse1p0OutputResolution::SevenTwentyP)),
Some(RouterResolution::TenEightyP) => Ok(Some(KinoviHappyHorse1p0OutputResolution::TenEightyP)),
@@ -335,10 +332,10 @@ mod tests {
}
#[test]
fn resolution_none_defaults_to_720p() {
fn resolution_none() {
let builder = GenerateVideoRequestBuilder { resolution: None, ..happy_horse_builder() };
let draft = unwrap_draft(build_kinovi_happy_horse_1p0(builder));
assert!(matches!(draft.resolution, Some(KinoviHappyHorse1p0OutputResolution::SevenTwentyP)));
assert!(draft.resolution.is_none());
}
#[test]
@@ -117,10 +117,7 @@ fn plan_output_resolution(
strategy: RequestMismatchMitigationStrategy,
) -> Result<Option<KinoviOutputResolution>, ArtcraftRouterError> {
match resolution {
// Unset defaults to explicit 720p. Cost estimation prices unset as 720p,
// so the request must pin 720p too — never leave the resolution up to the
// provider's server-side default, or billing and supplier cost can diverge.
None => Ok(Some(KinoviOutputResolution::SevenTwentyP)),
None => Ok(None),
// Direct mappings
Some(RouterResolution::FourEightyP) => Ok(Some(KinoviOutputResolution::FourEightyP)),
@@ -396,10 +393,10 @@ mod tests {
}
#[test]
fn resolution_none_defaults_to_720p() {
fn resolution_none() {
let builder = GenerateVideoRequestBuilder { resolution: None, ..kinovi_web_builder() };
let draft = unwrap_draft(build_kinovi_seedance_2p0(builder));
assert!(matches!(draft.resolution, Some(KinoviOutputResolution::SevenTwentyP)));
assert!(draft.resolution.is_none());
}
#[test]
@@ -2,7 +2,6 @@ use kinovi_web_client::generate::video::generate_seedance_2p0::{
GenerateSeedance2p0Request, KinoviSeedance2p0BatchCount,
KinoviSeedance2p0OutputResolution,
};
use kinovi_web_client::pricing::kinovi_cost_calculator_trait::KinoviCostCalculatorTrait;
use crate::generate::generate_video::video_generation_cost_estimate::VideoGenerationCostEstimate;
use crate::generate::generate_video::providers::kinovi::seedance_2p0::draft::KinoviSeedance2p0DraftState;
@@ -67,13 +66,8 @@ impl KinoviSeedance2p0CostState {
bitrate: None,
};
// Enterprise tier: what generations actually cost us (our discounted
// per-model credit rate at our bulk credit purchase rate).
let costs = pricing_request.calculate_enterprise_costs();
// Enterprise 720p bills fractional credits (37.9/sec). The router's
// credit field is an integer, so round to the nearest credit; the USD
// cents (the authoritative charge) are already rounded up.
let cost_in_credits = costs.total_cost.kinovi_credits.round() as u64;
let costs = pricing_request.calculate_costs();
let cost_in_credits = costs.total_cost.kinovi_credits;
let cost_in_usd_cents = costs.total_cost.usd_cents_rounded_up;
VideoGenerationCostEstimate {
@@ -103,40 +97,40 @@ mod tests {
use crate::generate::generate_video::video_generation_draft::VideoGenerationDraftRequest;
use crate::generate::generate_video::video_generation_draft_or_request::VideoGenerationDraftOrRequest;
// ── 720p pricing (enterprise discount: 37.9 credits/sec) ──
// ── 720p pricing ──
mod pricing_720p {
use super::*;
#[test]
fn cost_720p_batch_1() {
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 4, KinoviBatchCount::One), 63);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::One), 78);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 6, KinoviBatchCount::One), 94);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 7, KinoviBatchCount::One), 110);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 10, KinoviBatchCount::One), 156);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 15, KinoviBatchCount::One), 234);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 4, KinoviBatchCount::One), 66);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::One), 83);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 6, KinoviBatchCount::One), 99);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 7, KinoviBatchCount::One), 116);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 10, KinoviBatchCount::One), 165);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 15, KinoviBatchCount::One), 247);
}
#[test]
fn cost_720p_batch_2() {
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 4, KinoviBatchCount::Two), 125);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::Two), 156);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 15, KinoviBatchCount::Two), 468);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 4, KinoviBatchCount::Two), 132);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::Two), 165);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 15, KinoviBatchCount::Two), 494);
}
#[test]
fn cost_720p_batch_3() {
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 4, KinoviBatchCount::Three), 188);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::Three), 234);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 15, KinoviBatchCount::Three), 702);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 4, KinoviBatchCount::Three), 198);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::Three), 247);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 15, KinoviBatchCount::Three), 741);
}
#[test]
fn cost_720p_batch_4() {
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 4, KinoviBatchCount::Four), 250);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::Four), 312);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 15, KinoviBatchCount::Four), 936);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 4, KinoviBatchCount::Four), 264);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::Four), 330);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 15, KinoviBatchCount::Four), 988);
}
}
@@ -201,7 +195,7 @@ mod tests {
// ── 4K pricing ──
//
// Routes to the kinovi_web_client: 4K base is 200 credits/s (vs 90 at 1080p).
// Credits → cents at the enterprise rate of 243.16 credits/$1, rounded up.
// Credits → cents at 243 credits/$1, rounded up.
mod pricing_4k {
use super::*;
@@ -210,34 +204,34 @@ mod tests {
fn cost_4k_batch_1() {
assert_eq!(usd_cents(KinoviOutputResolution::FourK, 4, KinoviBatchCount::One), 330);
assert_eq!(usd_cents(KinoviOutputResolution::FourK, 5, KinoviBatchCount::One), 412);
assert_eq!(usd_cents(KinoviOutputResolution::FourK, 10, KinoviBatchCount::One), 823);
assert_eq!(usd_cents(KinoviOutputResolution::FourK, 15, KinoviBatchCount::One), 1234);
assert_eq!(usd_cents(KinoviOutputResolution::FourK, 10, KinoviBatchCount::One), 824);
assert_eq!(usd_cents(KinoviOutputResolution::FourK, 15, KinoviBatchCount::One), 1235);
}
#[test]
fn cost_4k_batch_2() {
assert_eq!(usd_cents(KinoviOutputResolution::FourK, 5, KinoviBatchCount::Two), 823);
assert_eq!(usd_cents(KinoviOutputResolution::FourK, 5, KinoviBatchCount::Two), 824);
}
#[test]
fn cost_4k_batch_3() {
assert_eq!(usd_cents(KinoviOutputResolution::FourK, 5, KinoviBatchCount::Three), 1234);
assert_eq!(usd_cents(KinoviOutputResolution::FourK, 5, KinoviBatchCount::Three), 1235);
}
#[test]
fn cost_4k_batch_4() {
assert_eq!(usd_cents(KinoviOutputResolution::FourK, 5, KinoviBatchCount::Four), 1646);
assert_eq!(usd_cents(KinoviOutputResolution::FourK, 5, KinoviBatchCount::Four), 1647);
}
}
// ── 4K: router cost must match the kinovi_web_client binding ──
//
// The router delegates to GenerateSeedance2p0Request::calculate_enterprise_costs(),
// so these assert the exact 4K numbers AND cross-check the router against the
// binding for every duration (4/5/10/15s) with and without a video reference.
// The router delegates to GenerateSeedance2p0Request::calculate_costs(), so these
// assert the exact 4K numbers AND cross-check the router against the binding for
// every duration (4/5/10/15s) with and without a video reference.
//
// 4K base = 200 credits/s; with a video reference = 240 credits/s (+40 surcharge).
// USD cents = ceil(total_credits / 243.16 * 100).
// USD cents = ceil(total_credits / 243 * 100).
mod four_k_matches_binding {
use super::*;
@@ -277,8 +271,8 @@ mod tests {
use_face_blur_hack: None,
bitrate: None,
}
.calculate_enterprise_costs();
(costs.total_cost.kinovi_credits.round() as u64, costs.total_cost.usd_cents_rounded_up)
.calculate_costs();
(costs.total_cost.kinovi_credits, costs.total_cost.usd_cents_rounded_up)
}
#[test]
@@ -286,17 +280,17 @@ mod tests {
// 200 credits/s.
assert_eq!((router(4, false).cost_in_credits, router(4, false).cost_in_usd_cents), (Some(800), Some(330)));
assert_eq!((router(5, false).cost_in_credits, router(5, false).cost_in_usd_cents), (Some(1000), Some(412)));
assert_eq!((router(10, false).cost_in_credits, router(10, false).cost_in_usd_cents), (Some(2000), Some(823)));
assert_eq!((router(15, false).cost_in_credits, router(15, false).cost_in_usd_cents), (Some(3000), Some(1234)));
assert_eq!((router(10, false).cost_in_credits, router(10, false).cost_in_usd_cents), (Some(2000), Some(824)));
assert_eq!((router(15, false).cost_in_credits, router(15, false).cost_in_usd_cents), (Some(3000), Some(1235)));
}
#[test]
fn explicit_values_with_video_reference() {
// 240 credits/s (200 base + 40 surcharge).
assert_eq!((router(4, true).cost_in_credits, router(4, true).cost_in_usd_cents), (Some(960), Some(395)));
assert_eq!((router(4, true).cost_in_credits, router(4, true).cost_in_usd_cents), (Some(960), Some(396)));
assert_eq!((router(5, true).cost_in_credits, router(5, true).cost_in_usd_cents), (Some(1200), Some(494)));
assert_eq!((router(10, true).cost_in_credits, router(10, true).cost_in_usd_cents), (Some(2400), Some(988)));
assert_eq!((router(15, true).cost_in_credits, router(15, true).cost_in_usd_cents), (Some(3600), Some(1481)));
assert_eq!((router(15, true).cost_in_credits, router(15, true).cost_in_usd_cents), (Some(3600), Some(1482)));
}
#[test]
@@ -370,11 +364,10 @@ mod tests {
};
let without = base.estimate_cost();
let with = KinoviSeedance2p0CostState { has_video_reference: true, ..base }.estimate_cost();
// Enterprise 720p surcharge is +7.58 credits/s: 189.5 -> 227.4 credits
// (22740/243.16 = 93.52 -> 94 cents).
assert_eq!(without.cost_in_credits, Some(190));
assert_eq!(with.cost_in_credits, Some(227));
assert_eq!(with.cost_in_usd_cents, Some(94));
// 720p surcharge is +8 credits/s: 200 -> 240 credits (24000/243 = 98.77 -> 99 cents).
assert_eq!(without.cost_in_credits, Some(200));
assert_eq!(with.cost_in_credits, Some(240));
assert_eq!(with.cost_in_usd_cents, Some(99));
}
// ── from_request() tests ──
@@ -390,7 +383,7 @@ mod tests {
assert_eq!(cost.duration_seconds, 5);
assert!(matches!(cost.batch_count, Some(KinoviBatchCount::One)));
assert!(!cost.has_video_reference);
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(78));
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(83));
}
#[test]
@@ -398,7 +391,7 @@ mod tests {
let req = make_request_state(None, 5, KinoviBatchCount::One, false);
let cost = KinoviSeedance2p0CostState::from_request(&req);
assert!(cost.resolution.is_none()); // None defaults to 720p pricing
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(78));
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(83));
}
#[test]
@@ -420,9 +413,9 @@ mod tests {
let req = make_request_state(Some(KinoviOutputResolution::SevenTwentyP), 5, KinoviBatchCount::One, true);
let cost = KinoviSeedance2p0CostState::from_request(&req);
assert!(cost.has_video_reference);
// Enterprise video refs add +7.58 credits/s at 720p: 227.4 credits -> 94 cents.
assert_eq!(cost.estimate_cost().cost_in_credits, Some(227));
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(94));
// Video refs add a +8 credits/s surcharge at 720p: 240 credits -> 125 cents.
assert_eq!(cost.estimate_cost().cost_in_credits, Some(240));
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(99));
}
#[test]
@@ -442,12 +435,11 @@ mod tests {
fn from_draft_720p_default() {
let draft = make_draft(5, 1, None, false);
let cost = KinoviSeedance2p0CostState::from_draft(&draft);
// Unset resolution is pinned to explicit 720p at build time.
assert!(matches!(cost.resolution, Some(KinoviOutputResolution::SevenTwentyP)));
assert!(cost.resolution.is_none()); // None defaults to 720p pricing
assert_eq!(cost.duration_seconds, 5);
assert!(matches!(cost.batch_count, Some(KinoviBatchCount::One)));
assert!(!cost.has_video_reference);
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(78));
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(83));
}
#[test]
@@ -490,9 +482,9 @@ mod tests {
let draft = make_draft(5, 1, None, true);
let cost = KinoviSeedance2p0CostState::from_draft(&draft);
assert!(cost.has_video_reference);
// Enterprise video refs add +7.58 credits/s at 720p: 227.4 credits -> 94 cents.
assert_eq!(cost.estimate_cost().cost_in_credits, Some(227));
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(94));
// Video refs add a +8 credits/s surcharge at 720p: 240 credits -> 125 cents.
assert_eq!(cost.estimate_cost().cost_in_credits, Some(240));
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(99));
}
#[test]
@@ -508,7 +500,7 @@ mod tests {
let cost = KinoviSeedance2p0CostState::from_draft(&draft);
assert_eq!(cost.duration_seconds, 15);
assert!(matches!(cost.batch_count, Some(KinoviBatchCount::Two)));
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(468));
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(494));
}
}
@@ -546,8 +538,7 @@ mod tests {
#[test]
fn credits_720p() {
// Enterprise 37.9 credits/s × 5s = 189.5, rounded to 190.
assert_eq!(credits(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::One), 190);
assert_eq!(credits(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::One), 200);
}
#[test]
@@ -118,10 +118,7 @@ fn plan_output_resolution(
strategy: RequestMismatchMitigationStrategy,
) -> Result<Option<KinoviOutputResolution>, ArtcraftRouterError> {
match resolution {
// Unset defaults to explicit 720p. Cost estimation prices unset as 720p,
// so the request must pin 720p too — never leave the resolution up to the
// provider's server-side default, or billing and supplier cost can diverge.
None => Ok(Some(KinoviOutputResolution::SevenTwentyP)),
None => Ok(None),
// Direct mappings
Some(RouterResolution::FourEightyP) => Ok(Some(KinoviOutputResolution::FourEightyP)),
@@ -424,10 +421,10 @@ mod tests {
}
#[test]
fn resolution_none_defaults_to_720p() {
fn resolution_none() {
let builder = GenerateVideoRequestBuilder { resolution: None, ..kinovi_web_fast_builder() };
let draft = unwrap_draft(build_kinovi_seedance_2p0_fast(builder));
assert!(matches!(draft.resolution, Some(KinoviOutputResolution::SevenTwentyP)));
assert!(draft.resolution.is_none());
}
#[test]
@@ -2,7 +2,6 @@ use kinovi_web_client::generate::video::generate_seedance_2p0_fast::{
GenerateSeedance2p0FastRequest, KinoviSeedance2p0FastBatchCount,
KinoviSeedance2p0FastOutputResolution,
};
use kinovi_web_client::pricing::kinovi_cost_calculator_trait::KinoviCostCalculatorTrait;
use crate::generate::generate_video::video_generation_cost_estimate::VideoGenerationCostEstimate;
use crate::generate::generate_video::providers::kinovi::seedance_2p0_fast::draft::KinoviSeedance2p0FastDraftState;
@@ -67,13 +66,8 @@ impl KinoviSeedance2p0FastCostState {
bitrate: None,
};
// Enterprise tier: what generations actually cost us (our discounted
// per-model credit rate at our bulk credit purchase rate).
let costs = pricing_request.calculate_enterprise_costs();
// Enterprise Fast credits can be fractional (e.g. 480p 5s = 52.5). The
// router's credit field is an integer, so round to the nearest credit;
// the USD cents (the authoritative charge) are already rounded up.
let cost_in_credits = costs.total_cost.kinovi_credits.round() as u64;
let costs = pricing_request.calculate_costs();
let cost_in_credits = costs.total_cost.kinovi_credits;
let cost_in_usd_cents = costs.total_cost.usd_cents_rounded_up;
VideoGenerationCostEstimate {
@@ -107,61 +101,61 @@ mod tests {
// ── Direct estimate_cost() tests ──
// These must match the reference implementation values exactly.
// -- 720p (enterprise 21 credits/sec, 243.16 credits/$1) --
// -- 720p (28 credits/sec, 243 credits/$1) --
mod pricing_720p {
use super::*;
#[test]
fn cost_720p_batch_1() {
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 4, KinoviBatchCount::One), 35);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::One), 44);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 10, KinoviBatchCount::One), 87);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 15, KinoviBatchCount::One), 130);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 4, KinoviBatchCount::One), 47);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::One), 58);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 10, KinoviBatchCount::One), 116);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 15, KinoviBatchCount::One), 173);
}
#[test]
fn cost_720p_batch_2() {
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::Two), 87);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::Two), 116);
}
#[test]
fn cost_720p_batch_3() {
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::Three), 130);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::Three), 173);
}
#[test]
fn cost_720p_batch_4() {
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::Four), 173);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::Four), 231);
}
}
// -- 480p (enterprise 10.5 credits/sec, 243.16 credits/$1) --
// -- 480p (14 credits/sec, 243 credits/$1) --
mod pricing_480p {
use super::*;
#[test]
fn cost_480p_batch_1() {
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 4, KinoviBatchCount::One), 18);
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 5, KinoviBatchCount::One), 22);
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 10, KinoviBatchCount::One), 44);
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 15, KinoviBatchCount::One), 65);
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 4, KinoviBatchCount::One), 24);
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 5, KinoviBatchCount::One), 29);
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 10, KinoviBatchCount::One), 58);
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 15, KinoviBatchCount::One), 87);
}
#[test]
fn cost_480p_batch_2() {
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 5, KinoviBatchCount::Two), 44);
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 5, KinoviBatchCount::Two), 58);
}
#[test]
fn cost_480p_batch_3() {
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 5, KinoviBatchCount::Three), 65);
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 5, KinoviBatchCount::Three), 87);
}
#[test]
fn cost_480p_batch_4() {
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 5, KinoviBatchCount::Four), 87);
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 5, KinoviBatchCount::Four), 116);
}
}
@@ -208,11 +202,10 @@ mod tests {
};
let without = base.estimate_cost();
let with = KinoviSeedance2p0FastCostState { has_video_reference: true, ..base }.estimate_cost();
// Enterprise Fast 720p surcharge is +4.5 credits/s: 105 -> 127.5 credits
// (12750/243.16 = 52.43 -> 53 cents; credits round to 128).
assert_eq!(without.cost_in_credits, Some(105));
assert_eq!(with.cost_in_credits, Some(128));
assert_eq!(with.cost_in_usd_cents, Some(53));
// Fast 720p surcharge is +6 credits/s: 140 -> 170 credits (17000/243 = 69.96 -> 70 cents).
assert_eq!(without.cost_in_credits, Some(140));
assert_eq!(with.cost_in_credits, Some(170));
assert_eq!(with.cost_in_usd_cents, Some(70));
}
// ── from_request() tests ──
@@ -228,7 +221,7 @@ mod tests {
assert_eq!(cost.duration_seconds, 5);
assert!(matches!(cost.batch_count, Some(KinoviBatchCount::One)));
assert!(!cost.has_video_reference);
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(44));
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(58));
}
#[test]
@@ -236,14 +229,14 @@ mod tests {
let req = make_request_state(None, 5, KinoviBatchCount::One, false);
let cost = KinoviSeedance2p0FastCostState::from_request(&req);
assert!(cost.resolution.is_none());
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(44));
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(58));
}
#[test]
fn from_request_480p() {
let req = make_request_state(Some(KinoviOutputResolution::FourEightyP), 5, KinoviBatchCount::One, false);
let cost = KinoviSeedance2p0FastCostState::from_request(&req);
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(22));
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(29));
}
#[test]
@@ -251,9 +244,9 @@ mod tests {
let req = make_request_state(Some(KinoviOutputResolution::SevenTwentyP), 5, KinoviBatchCount::One, true);
let cost = KinoviSeedance2p0FastCostState::from_request(&req);
assert!(cost.has_video_reference);
// Enterprise video refs add +4.5 credits/s at 720p: 127.5 credits -> 53 cents.
assert_eq!(cost.estimate_cost().cost_in_credits, Some(128));
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(53));
// Video refs add a +6 credits/s surcharge at 720p: 170 credits -> 89 cents.
assert_eq!(cost.estimate_cost().cost_in_credits, Some(170));
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(70));
}
#[test]
@@ -273,12 +266,11 @@ mod tests {
fn from_draft_720p_default() {
let draft = make_draft(5, 1, None, false);
let cost = KinoviSeedance2p0FastCostState::from_draft(&draft);
// Unset resolution is pinned to explicit 720p at build time.
assert!(matches!(cost.resolution, Some(KinoviOutputResolution::SevenTwentyP)));
assert!(cost.resolution.is_none());
assert_eq!(cost.duration_seconds, 5);
assert!(matches!(cost.batch_count, Some(KinoviBatchCount::One)));
assert!(!cost.has_video_reference);
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(44));
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(58));
}
#[test]
@@ -286,7 +278,7 @@ mod tests {
let draft = make_draft(5, 1, Some(RouterResolution::FourEightyP), false);
let cost = KinoviSeedance2p0FastCostState::from_draft(&draft);
assert!(matches!(cost.resolution, Some(KinoviOutputResolution::FourEightyP)));
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(22));
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(29));
}
#[test]
@@ -294,9 +286,9 @@ mod tests {
let draft = make_draft(5, 1, None, true);
let cost = KinoviSeedance2p0FastCostState::from_draft(&draft);
assert!(cost.has_video_reference);
// Enterprise video refs add +4.5 credits/s at 720p: 127.5 credits -> 53 cents.
assert_eq!(cost.estimate_cost().cost_in_credits, Some(128));
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(53));
// Video refs add a +6 credits/s surcharge at 720p: 170 credits -> 89 cents.
assert_eq!(cost.estimate_cost().cost_in_credits, Some(170));
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(70));
}
#[test]
@@ -312,7 +304,7 @@ mod tests {
let cost = KinoviSeedance2p0FastCostState::from_draft(&draft);
assert_eq!(cost.duration_seconds, 15);
assert!(matches!(cost.batch_count, Some(KinoviBatchCount::Two)));
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(260));
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(346));
}
}
@@ -350,14 +342,12 @@ mod tests {
#[test]
fn credits_720p() {
// Enterprise 21 credits/s × 5s = 105.
assert_eq!(credits(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::One), 105);
assert_eq!(credits(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::One), 140);
}
#[test]
fn credits_480p() {
// Enterprise 10.5 credits/s × 5s = 52.5, rounded to 53.
assert_eq!(credits(KinoviOutputResolution::FourEightyP, 5, KinoviBatchCount::One), 53);
assert_eq!(credits(KinoviOutputResolution::FourEightyP, 5, KinoviBatchCount::One), 70);
}
}
@@ -116,10 +116,7 @@ fn plan_output_resolution(
strategy: RequestMismatchMitigationStrategy,
) -> Result<Option<KinoviOutputResolution>, ArtcraftRouterError> {
match resolution {
// Unset defaults to explicit 720p. Cost estimation prices unset as 720p,
// so the request must pin 720p too — never leave the resolution up to the
// provider's server-side default, or billing and supplier cost can diverge.
None => Ok(Some(KinoviOutputResolution::SevenTwentyP)),
None => Ok(None),
// Direct mappings
Some(RouterResolution::FourEightyP) => Ok(Some(KinoviOutputResolution::FourEightyP)),
@@ -432,10 +429,10 @@ mod tests {
}
#[test]
fn resolution_none_defaults_to_720p() {
fn resolution_none() {
let builder = GenerateVideoRequestBuilder { resolution: None, ..mini_builder() };
let draft = unwrap_draft(build_kinovi_seedance_2p0_mini(builder));
assert!(matches!(draft.resolution, Some(KinoviOutputResolution::SevenTwentyP)));
assert!(draft.resolution.is_none());
}
}
@@ -2,7 +2,6 @@ use kinovi_web_client::generate::video::generate_seedance_2p0_mini::{
GenerateSeedance2p0MiniRequest, KinoviSeedance2p0MiniBatchCount,
KinoviSeedance2p0MiniOutputResolution,
};
use kinovi_web_client::pricing::kinovi_cost_calculator_trait::KinoviCostCalculatorTrait;
use crate::generate::generate_video::video_generation_cost_estimate::VideoGenerationCostEstimate;
use crate::generate::generate_video::providers::kinovi::seedance_2p0_mini::draft::KinoviSeedance2p0MiniDraftState;
@@ -67,10 +66,8 @@ impl KinoviSeedance2p0MiniCostState {
bitrate: None,
};
// Enterprise tier: what generations actually cost us (our discounted
// per-model credit rate at our bulk credit purchase rate).
let costs = pricing_request.calculate_enterprise_costs();
// Mini credits can be fractional (e.g. 480p + video ref at 4s = 15.2).
let costs = pricing_request.calculate_costs();
// Mini credits can be fractional (e.g. 480p odd durations land on 37.5).
// The router's credit field is an integer, so round to the nearest credit;
// the USD cents (the authoritative charge) are already rounded up.
let cost_in_credits = costs.total_cost.kinovi_credits.round() as u64;
@@ -111,20 +108,18 @@ mod tests {
#[test]
fn without_video_reference() {
// Enterprise 3 credits/s.
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 4, KinoviBatchCount::One, false), 5);
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 5, KinoviBatchCount::One, false), 7);
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 10, KinoviBatchCount::One, false), 13);
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 15, KinoviBatchCount::One, false), 19);
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 4, KinoviBatchCount::One, false), 13);
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 5, KinoviBatchCount::One, false), 16);
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 10, KinoviBatchCount::One, false), 31);
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 15, KinoviBatchCount::One, false), 47);
}
#[test]
fn with_video_reference() {
// Enterprise 3.8 credits/s (3 base + 0.8 surcharge).
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 4, KinoviBatchCount::One, true), 7);
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 5, KinoviBatchCount::One, true), 8);
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 10, KinoviBatchCount::One, true), 16);
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 15, KinoviBatchCount::One, true), 24);
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 4, KinoviBatchCount::One, true), 16);
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 5, KinoviBatchCount::One, true), 20);
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 10, KinoviBatchCount::One, true), 40);
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 15, KinoviBatchCount::One, true), 59);
}
}
@@ -133,20 +128,18 @@ mod tests {
#[test]
fn without_video_reference() {
// Enterprise 8 credits/s.
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 4, KinoviBatchCount::One, false), 14);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::One, false), 17);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 10, KinoviBatchCount::One, false), 33);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 15, KinoviBatchCount::One, false), 50);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 4, KinoviBatchCount::One, false), 33);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::One, false), 42);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 10, KinoviBatchCount::One, false), 83);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 15, KinoviBatchCount::One, false), 124);
}
#[test]
fn with_video_reference() {
// Enterprise 9.6 credits/s (8 base + 1.6 surcharge).
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 4, KinoviBatchCount::One, true), 16);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::One, true), 20);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 10, KinoviBatchCount::One, true), 40);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 15, KinoviBatchCount::One, true), 60);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 4, KinoviBatchCount::One, true), 40);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::One, true), 50);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 10, KinoviBatchCount::One, true), 99);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 15, KinoviBatchCount::One, true), 149);
}
}
@@ -157,18 +150,17 @@ mod tests {
#[test]
fn credits_480p() {
// Enterprise 3 credits/s (whole at every duration).
assert_eq!(credits(KinoviOutputResolution::FourEightyP, 4, KinoviBatchCount::One, false), 12);
assert_eq!(credits(KinoviOutputResolution::FourEightyP, 5, KinoviBatchCount::One, false), 15);
assert_eq!(credits(KinoviOutputResolution::FourEightyP, 10, KinoviBatchCount::One, false), 30);
assert_eq!(credits(KinoviOutputResolution::FourEightyP, 15, KinoviBatchCount::One, false), 45);
// 7.5 credits/s; odd durations are fractional (37.5 → 38, 112.5 → 113).
assert_eq!(credits(KinoviOutputResolution::FourEightyP, 4, KinoviBatchCount::One, false), 30);
assert_eq!(credits(KinoviOutputResolution::FourEightyP, 5, KinoviBatchCount::One, false), 38);
assert_eq!(credits(KinoviOutputResolution::FourEightyP, 10, KinoviBatchCount::One, false), 75);
assert_eq!(credits(KinoviOutputResolution::FourEightyP, 15, KinoviBatchCount::One, false), 113);
}
#[test]
fn credits_720p() {
// Enterprise 8 credits/s.
assert_eq!(credits(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::One, false), 40);
assert_eq!(credits(KinoviOutputResolution::SevenTwentyP, 15, KinoviBatchCount::One, false), 120);
assert_eq!(credits(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::One, false), 100);
assert_eq!(credits(KinoviOutputResolution::SevenTwentyP, 15, KinoviBatchCount::One, false), 300);
}
}
@@ -218,7 +210,7 @@ mod tests {
assert!(matches!(cost.resolution, Some(KinoviOutputResolution::SevenTwentyP)));
assert_eq!(cost.duration_seconds, 5);
assert!(!cost.has_video_reference);
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(17));
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(42));
}
#[test]
@@ -226,7 +218,7 @@ mod tests {
let req = make_request_state(Some(KinoviOutputResolution::FourEightyP), 5, KinoviBatchCount::One, true);
let cost = KinoviSeedance2p0MiniCostState::from_request(&req);
assert!(cost.has_video_reference);
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(8));
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(20));
}
#[test]
@@ -234,7 +226,7 @@ mod tests {
let req = make_request_state(None, 5, KinoviBatchCount::One, false);
let cost = KinoviSeedance2p0MiniCostState::from_request(&req);
assert!(cost.resolution.is_none());
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(17));
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(42));
}
}
@@ -248,7 +240,7 @@ mod tests {
let draft = make_draft(5, 1, Some(RouterResolution::FourEightyP), false);
let cost = KinoviSeedance2p0MiniCostState::from_draft(&draft);
assert!(matches!(cost.resolution, Some(KinoviOutputResolution::FourEightyP)));
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(7));
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(16));
}
#[test]
@@ -256,16 +248,16 @@ mod tests {
let draft = make_draft(5, 1, Some(RouterResolution::SevenTwentyP), true);
let cost = KinoviSeedance2p0MiniCostState::from_draft(&draft);
assert!(cost.has_video_reference);
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(20));
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(50));
}
#[test]
fn from_draft_batch_8() {
// Mini supports up to batch 8: 720p 5s × 8 = 320 credits → 32000/243.16 → 132¢.
// Mini supports up to batch 8: 720p 5s × 8 = 800 credits → 80000/243 → 330¢.
let draft = make_draft(5, 8, Some(RouterResolution::SevenTwentyP), false);
let cost = KinoviSeedance2p0MiniCostState::from_draft(&draft);
assert!(matches!(cost.batch_count, Some(KinoviBatchCount::Eight)));
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(132));
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(330));
}
}
@@ -144,38 +144,31 @@ fn nearest_aspect_ratio(aspect_ratio: RouterAspectRatio) -> KinoviAspectRatio {
}
}
// Seedance 2.5 supports output resolutions: 480p, 720p, and 1080p.
// 4K (and other resolutions) are NOT supported — they map to the nearest
// offered resolution or error based on strategy. This planning MUST stay in
// lockstep with the Artcraft billing twin (`SupportedResolutions::Full` in
// build_common) so billing and execution always land on the same resolution.
// Seedance 2.5 supports output resolutions: 480p and 720p only.
// 1080p (and higher) is NOT supported — downgrade to 720p or error based on strategy.
fn plan_output_resolution(
resolution: Option<RouterResolution>,
strategy: RequestMismatchMitigationStrategy,
) -> Result<Option<KinoviOutputResolution>, ArtcraftRouterError> {
match resolution {
// Unset defaults to explicit 720p. Cost estimation prices unset as 720p,
// so the request must pin 720p too — never leave the resolution up to the
// provider's server-side default, or billing and supplier cost can diverge.
None => Ok(Some(KinoviOutputResolution::SevenTwentyP)),
None => Ok(None),
// Direct mappings
Some(RouterResolution::FourEightyP) => Ok(Some(KinoviOutputResolution::FourEightyP)),
Some(RouterResolution::SevenTwentyP) => Ok(Some(KinoviOutputResolution::SevenTwentyP)),
Some(RouterResolution::TenEightyP) => Ok(Some(KinoviOutputResolution::TenEightyP)),
// 4K is not supported — handle via strategy
Some(RouterResolution::FourK) => match strategy {
// 1080p is not supported — handle via strategy
Some(RouterResolution::TenEightyP) => match strategy {
RequestMismatchMitigationStrategy::ErrorOut => {
Err(ArtcraftRouterError::Client(ClientError::ModelDoesNotSupportOption {
field: "resolution",
value: format!("{:?}", RouterResolution::FourK),
value: format!("{:?}", RouterResolution::TenEightyP),
}))
}
RequestMismatchMitigationStrategy::PayMoreUpgrade
| RequestMismatchMitigationStrategy::PayLessDowngrade => {
// 4K not available — downgrade to 1080p (highest supported)
Ok(Some(KinoviOutputResolution::TenEightyP))
// 1080p not available — downgrade to 720p (highest supported)
Ok(Some(KinoviOutputResolution::SevenTwentyP))
}
},
@@ -191,7 +184,7 @@ fn plan_output_resolution(
| RequestMismatchMitigationStrategy::PayLessDowngrade => {
Ok(Some(match unsupported {
RouterResolution::HalfK => KinoviOutputResolution::FourEightyP,
_ => KinoviOutputResolution::TenEightyP,
_ => KinoviOutputResolution::SevenTwentyP,
}))
}
},
@@ -407,41 +400,28 @@ mod tests {
}
#[test]
fn resolution_480p_720p_and_1080p() {
fn resolution_480p_and_720p() {
let builder = GenerateVideoRequestBuilder { resolution: Some(RouterResolution::FourEightyP), ..base_builder() };
assert!(matches!(unwrap_draft(build_kinovi_seedance_2p5(builder)).resolution, Some(KinoviOutputResolution::FourEightyP)));
let builder = GenerateVideoRequestBuilder { resolution: Some(RouterResolution::SevenTwentyP), ..base_builder() };
assert!(matches!(unwrap_draft(build_kinovi_seedance_2p5(builder)).resolution, Some(KinoviOutputResolution::SevenTwentyP)));
let builder = GenerateVideoRequestBuilder { resolution: Some(RouterResolution::TenEightyP), ..base_builder() };
assert!(matches!(unwrap_draft(build_kinovi_seedance_2p5(builder)).resolution, Some(KinoviOutputResolution::TenEightyP)));
}
#[test]
fn resolution_1080p_error_out_strategy_still_maps_directly() {
fn resolution_1080p_downgrades_to_720p() {
let builder = GenerateVideoRequestBuilder {
resolution: Some(RouterResolution::TenEightyP),
request_mismatch_mitigation_strategy: RequestMismatchMitigationStrategy::ErrorOut,
..base_builder()
};
assert!(matches!(unwrap_draft(build_kinovi_seedance_2p5(builder)).resolution, Some(KinoviOutputResolution::TenEightyP)));
}
#[test]
fn resolution_4k_downgrades_to_1080p() {
let builder = GenerateVideoRequestBuilder {
resolution: Some(RouterResolution::FourK),
request_mismatch_mitigation_strategy: RequestMismatchMitigationStrategy::PayLessDowngrade,
..base_builder()
};
assert!(matches!(unwrap_draft(build_kinovi_seedance_2p5(builder)).resolution, Some(KinoviOutputResolution::TenEightyP)));
assert!(matches!(unwrap_draft(build_kinovi_seedance_2p5(builder)).resolution, Some(KinoviOutputResolution::SevenTwentyP)));
}
#[test]
fn resolution_4k_error_out() {
fn resolution_1080p_error_out() {
let builder = GenerateVideoRequestBuilder {
resolution: Some(RouterResolution::FourK),
resolution: Some(RouterResolution::TenEightyP),
request_mismatch_mitigation_strategy: RequestMismatchMitigationStrategy::ErrorOut,
..base_builder()
};
@@ -2,7 +2,6 @@ use kinovi_web_client::generate::video::generate_seedance_2p5::{
GenerateSeedance2p5Request, KinoviSeedance2p5Modality, KinoviSeedance2p5OutputResolution,
MAX_BILLED_INPUT_SECONDS, MIN_BILLED_INPUT_SECONDS,
};
use kinovi_web_client::pricing::kinovi_cost_calculator_trait::KinoviCostCalculatorTrait;
use crate::api::video_list_ref::VideoListRef;
use crate::generate::generate_video::video_generation_cost_estimate::VideoGenerationCostEstimate;
@@ -74,15 +73,10 @@ impl KinoviSeedance2p5CostState {
}
};
// NB: The kinovi calculator clamps measured values and bills the
// worst-case maximum for unknown (None) or zero inputs. Zero passes
// through unclamped so that worst-case fallback applies — clamping it up
// to the minimum here would understate the cost.
// NB: The kinovi calculator clamps too; clamping here as well keeps this
// state's math correct even if it's read directly.
let total_input_seconds = self.total_input_seconds
.map(|seconds| match seconds {
0 => 0,
measured => measured.clamp(MIN_BILLED_INPUT_SECONDS, MAX_BILLED_INPUT_SECONDS),
});
.map(|seconds| seconds.clamp(MIN_BILLED_INPUT_SECONDS, MAX_BILLED_INPUT_SECONDS));
let pricing_request = GenerateSeedance2p5Request {
prompt: String::new(),
@@ -93,13 +87,9 @@ impl KinoviSeedance2p5CostState {
use_face_blur_hack: None,
};
// Enterprise tier: what generations actually cost us (our discounted
// per-model credit rate at our bulk credit purchase rate).
let costs = pricing_request.calculate_enterprise_costs();
// 2.5 bills whole credits at 480p/720p, so the rounding below is exact
// there; 1080p bills fractional credits (103.25/sec) and rounds to the
// nearest credit. The USD cents (the authoritative charge) are rounded
// up.
let costs = pricing_request.calculate_costs();
// 2.5 bills whole credits, so the rounding below is exact; the USD cents
// (the authoritative charge) are rounded up.
let cost_in_credits = costs.kinovi_credits.round() as u64;
let cost_in_usd_cents = costs.usd_cents_rounded_up;
@@ -121,8 +111,7 @@ mod tests {
use super::*;
// ── Credits without video references (26/sec at 480p, 59/sec at 720p,
// 103.25/sec at 1080p enterprise) ──
// ── Credits without video references (26/sec at 480p, 59/sec at 720p) ──
mod credits_without_video_references {
use super::*;
@@ -140,15 +129,6 @@ mod tests {
assert_eq!(credits(Some(KinoviOutputResolution::SevenTwentyP), 30, false, None), 1770);
}
#[test]
fn credits_1080p() {
// 103.25/sec enterprise; fractional totals round to the nearest credit
// (516.25 → 516, 1032.5 → 1033, 3097.5 → 3098).
assert_eq!(credits(Some(KinoviOutputResolution::TenEightyP), 5, false, None), 516);
assert_eq!(credits(Some(KinoviOutputResolution::TenEightyP), 10, false, None), 1033);
assert_eq!(credits(Some(KinoviOutputResolution::TenEightyP), 30, false, None), 3098);
}
#[test]
fn default_resolution_is_720p() {
assert_eq!(credits(None, 10, false, None), credits(Some(KinoviOutputResolution::SevenTwentyP), 10, false, None));
@@ -161,7 +141,7 @@ mod tests {
}
// ── Credits with video references (16/sec at 480p, 35/sec at 720p,
// 61.69/sec at 1080p enterprise, over output duration + input seconds) ──
// over output duration + input seconds) ──
mod credits_with_video_references {
use super::*;
@@ -170,8 +150,6 @@ mod tests {
fn thirty_second_output_with_ten_input_seconds_bills_forty() {
assert_eq!(credits(Some(KinoviOutputResolution::FourEightyP), 30, true, Some(10)), 16 * 40);
assert_eq!(credits(Some(KinoviOutputResolution::SevenTwentyP), 30, true, Some(10)), 35 * 40);
// 61.69/sec enterprise × 40 = 2467.6 → 2468 credits.
assert_eq!(credits(Some(KinoviOutputResolution::TenEightyP), 30, true, Some(10)), 2468);
}
#[test]
@@ -202,7 +180,7 @@ mod tests {
#[test]
fn usd_cents_are_rounded_up() {
// 130 credits → 13000/243.16 = 53.4627 → 54¢.
// 130 credits → 13000/243 = 53.4979 → 54¢.
let estimate = cost_state(Some(KinoviOutputResolution::FourEightyP), 5, false, None).estimate_cost();
assert_eq!(estimate.cost_in_usd_cents, Some(54));
}
@@ -134,10 +134,7 @@ fn plan_output_resolution(
strategy: RequestMismatchMitigationStrategy,
) -> Result<Option<KinoviOutputResolution>, ArtcraftRouterError> {
match resolution {
// Unset defaults to explicit 720p. Cost estimation prices unset as 720p,
// so the request must pin 720p too — never leave the resolution up to the
// provider's server-side default, or billing and supplier cost can diverge.
None => Ok(Some(KinoviOutputResolution::SevenTwentyP)),
None => Ok(None),
// Direct mappings
Some(RouterResolution::FourEightyP) => Ok(Some(KinoviOutputResolution::FourEightyP)),
@@ -442,10 +439,10 @@ mod tests {
}
#[test]
fn resolution_none_defaults_to_720p() {
fn resolution_none() {
let builder = GenerateVideoRequestBuilder { resolution: None, ..preview_builder() };
let draft = unwrap_draft(build_kinovi_seedance_2p5_preview(builder));
assert!(matches!(draft.resolution, Some(KinoviOutputResolution::SevenTwentyP)));
assert!(draft.resolution.is_none());
}
}
@@ -1,4 +1,3 @@
use kinovi_web_client::pricing::kinovi_cost_calculator_trait::KinoviCostCalculatorTrait;
use kinovi_web_client::generate::video::generate_seedance_2p5_preview::{
GenerateSeedance2p5PreviewRequest, KinoviSeedance2p5PreviewOutputResolution,
};
@@ -44,10 +43,8 @@ impl KinoviSeedance2p5PreviewCostState {
use_face_blur_hack: None,
};
// Enterprise tier: what generations actually cost us (our discounted
// per-model credit rate at our bulk credit purchase rate).
let costs = pricing_request.calculate_enterprise_costs();
// 2.5 Preview bills fractional credits (42.13/sec at 480p). The router's
let costs = pricing_request.calculate_costs();
// 2.5 Preview bills fractional credits (46.81/sec at 480p). The router's
// credit field is an integer, so round to the nearest credit; the USD
// cents (the authoritative charge) are already rounded up.
let cost_in_credits = costs.kinovi_credits.round() as u64;
@@ -78,24 +75,24 @@ mod tests {
#[test]
fn credits_480p() {
// Enterprise 42.13 credits/s: 168.52 → 169, 631.95 → 632, 1053.25 → 1053.
assert_eq!(credits(Some(KinoviOutputResolution::FourEightyP), 4), 169);
assert_eq!(credits(Some(KinoviOutputResolution::FourEightyP), 10), 421);
assert_eq!(credits(Some(KinoviOutputResolution::FourEightyP), 15), 632);
assert_eq!(credits(Some(KinoviOutputResolution::FourEightyP), 20), 843);
assert_eq!(credits(Some(KinoviOutputResolution::FourEightyP), 25), 1053);
assert_eq!(credits(Some(KinoviOutputResolution::FourEightyP), 30), 1264);
// 46.81 credits/s: 187.24 → 187, 702.15 → 702, 1170.25 → 1170.
assert_eq!(credits(Some(KinoviOutputResolution::FourEightyP), 4), 187);
assert_eq!(credits(Some(KinoviOutputResolution::FourEightyP), 10), 468);
assert_eq!(credits(Some(KinoviOutputResolution::FourEightyP), 15), 702);
assert_eq!(credits(Some(KinoviOutputResolution::FourEightyP), 20), 936);
assert_eq!(credits(Some(KinoviOutputResolution::FourEightyP), 25), 1170);
assert_eq!(credits(Some(KinoviOutputResolution::FourEightyP), 30), 1404);
}
#[test]
fn credits_720p() {
// Enterprise 84.26 credits/s: 337.04 → 337, 1263.9 → 1264, 2106.5 → 2107.
assert_eq!(credits(Some(KinoviOutputResolution::SevenTwentyP), 4), 337);
assert_eq!(credits(Some(KinoviOutputResolution::SevenTwentyP), 10), 843);
assert_eq!(credits(Some(KinoviOutputResolution::SevenTwentyP), 15), 1264);
assert_eq!(credits(Some(KinoviOutputResolution::SevenTwentyP), 20), 1685);
assert_eq!(credits(Some(KinoviOutputResolution::SevenTwentyP), 25), 2107);
assert_eq!(credits(Some(KinoviOutputResolution::SevenTwentyP), 30), 2528);
// 93.62 credits/s: 374.48 → 374, 1404.3 → 1404, 2808.6 → 2809.
assert_eq!(credits(Some(KinoviOutputResolution::SevenTwentyP), 4), 374);
assert_eq!(credits(Some(KinoviOutputResolution::SevenTwentyP), 10), 936);
assert_eq!(credits(Some(KinoviOutputResolution::SevenTwentyP), 15), 1404);
assert_eq!(credits(Some(KinoviOutputResolution::SevenTwentyP), 20), 1872);
assert_eq!(credits(Some(KinoviOutputResolution::SevenTwentyP), 25), 2341);
assert_eq!(credits(Some(KinoviOutputResolution::SevenTwentyP), 30), 2809);
}
#[test]
@@ -111,16 +108,16 @@ mod tests {
#[test]
fn cents_480p() {
// 168.52 credits → 16852/243.16 = 69.30 → 70¢; 631.95 → 259.89 → 260¢.
assert_eq!(usd_cents(Some(KinoviOutputResolution::FourEightyP), 4), 70);
assert_eq!(usd_cents(Some(KinoviOutputResolution::FourEightyP), 15), 260);
// 187.24 credits → 18724/243 = 77.05 → 78¢; 702.15 → 288.95 → 289¢.
assert_eq!(usd_cents(Some(KinoviOutputResolution::FourEightyP), 4), 78);
assert_eq!(usd_cents(Some(KinoviOutputResolution::FourEightyP), 15), 289);
}
#[test]
fn cents_720p() {
// 337.04 credits → 33704/243.16 = 138.61 → 139¢; 2527.8 → 1039.56 → 1040¢.
assert_eq!(usd_cents(Some(KinoviOutputResolution::SevenTwentyP), 4), 139);
assert_eq!(usd_cents(Some(KinoviOutputResolution::SevenTwentyP), 30), 1040);
// 374.48 credits → 37448/243 = 154.11 → 155¢; 2808.6 → 1155.80 → 1156¢.
assert_eq!(usd_cents(Some(KinoviOutputResolution::SevenTwentyP), 4), 155);
assert_eq!(usd_cents(Some(KinoviOutputResolution::SevenTwentyP), 30), 1156);
}
}
@@ -1,5 +1,4 @@
pub mod artcraft;
pub mod fal;
pub mod first_party;
pub mod grok_api;
pub mod kinovi;
pub mod kinovi;
@@ -1,24 +0,0 @@
# beeble_client
HTTP client for the Beeble SwitchX compositing API.
## API Reference
- Docs: https://developer.beeble.ai/docs
- OpenAPI: https://api.beeble.ai/developer-api-docs/openapi.json
- Auth: `x-api-key` header
## Endpoints
- `create_upload_url` — POST /v1/uploads — get a presigned PUT URL for uploading media
- `start_generation` — POST /v1/switchx/generations — start an image or video compositing job
- `get_job_status` — GET /v1/switchx/generations/{job_id} — poll job status until completed/failed
## Testing
```bash
cargo test -p beeble_client # run non-ignored tests (API shape only)
cargo test -p beeble_client -- --ignored # run live API tests (requires key, incurs costs)
```
Live tests require: `/Users/bt/Artcraft/credentials/beeble_api_key.txt`
@@ -1 +0,0 @@
AGENTS.md
@@ -0,0 +1,24 @@
# beeble_client
HTTP client for the Beeble SwitchX compositing API.
## API Reference
- Docs: https://developer.beeble.ai/docs
- OpenAPI: https://api.beeble.ai/developer-api-docs/openapi.json
- Auth: `x-api-key` header
## Endpoints
- `create_upload_url` — POST /v1/uploads — get a presigned PUT URL for uploading media
- `start_generation` — POST /v1/switchx/generations — start an image or video compositing job
- `get_job_status` — GET /v1/switchx/generations/{job_id} — poll job status until completed/failed
## Testing
```bash
cargo test -p beeble_client # run non-ignored tests (API shape only)
cargo test -p beeble_client -- --ignored # run live API tests (requires key, incurs costs)
```
Live tests require: `/Users/bt/Artcraft/credentials/beeble_api_key.txt`
+1 -1
View File
@@ -38,4 +38,4 @@ test_utils.workspace = true
test_data.workspace = true
# External Dev
tokio = { workspace = true, features = ["rt", "macros", "net", "io-util"] }
# (None yet)
@@ -1,29 +0,0 @@
/// Background treatment for the generated image. Fal's default is `Auto`.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum GptImage2p5Background {
Auto,
Transparent,
Opaque,
}
impl GptImage2p5Background {
pub fn to_str(self) -> &'static str {
match self {
GptImage2p5Background::Auto => "auto",
GptImage2p5Background::Transparent => "transparent",
GptImage2p5Background::Opaque => "opaque",
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn wire_strings_match_fal_schema() {
assert_eq!(GptImage2p5Background::Auto.to_str(), "auto");
assert_eq!(GptImage2p5Background::Transparent.to_str(), "transparent");
assert_eq!(GptImage2p5Background::Opaque.to_str(), "opaque");
}
}
@@ -1,299 +0,0 @@
use crate::requests::api::image::common::gpt_image_2_resolution::GptImage2Resolution;
use crate::requests::api::image::common::gpt_image_2p5::gpt_image_2p5_background::GptImage2p5Background;
use crate::requests::api::image::common::gpt_image_2p5::gpt_image_2p5_image_size::GptImage2p5ImageSize;
use crate::requests::api::image::common::gpt_image_2p5::gpt_image_2p5_num_images::GptImage2p5NumImages;
use crate::requests::api::image::common::gpt_image_2p5::gpt_image_2p5_output_format::GptImage2p5OutputFormat;
use crate::requests::api::image::common::gpt_image_2p5::gpt_image_2p5_pricing::{
estimate_output_image_cost, estimate_reference_images_cost, hundredths_of_cent_to_cents,
};
use crate::requests::api::image::common::gpt_image_2p5::gpt_image_2p5_quality::GptImage2p5Quality;
use crate::requests::api::image::common::gpt_image_2p5::raw::gpt_image_2p5_edit_image_input::GptImage2p5EditImageInput;
use crate::requests::traits::fal_request_cost_calculator_trait::UsdCents;
/// Fal rejects more than this many reference images.
pub const MAX_REFERENCE_IMAGES: usize = 16;
/// Parameters for a GPT Image 2.5 edit request. Identical for Flare and Sunburst; the
/// per-endpoint request types wrap this.
#[derive(Clone, Debug)]
pub struct GptImage2p5EditImageParams {
/// Text prompt describing the edit. 1 to 32,000 characters.
pub prompt: String,
/// One to sixteen reference image URLs.
pub image_urls: Vec<String>,
/// Optional mask URL indicating which part of the image to edit.
pub mask_url: Option<String>,
/// Number of images to generate.
pub num_images: GptImage2p5NumImages,
/// Output image size preset. `None` lets Fal default to `auto` (inferred from the input
/// images).
pub image_size: Option<GptImage2p5ImageSize>,
/// Optional resolution tier. When present (and the size is not `Auto`), a custom
/// width x height is computed from the preset's aspect ratio and sent instead of the
/// preset name.
pub resolution: Option<GptImage2Resolution>,
/// Quality tier. `None` lets Fal default to `high`.
pub quality: Option<GptImage2p5Quality>,
/// Background treatment. `None` lets Fal default to `auto`.
pub background: Option<GptImage2p5Background>,
/// Output format. `None` sends `png`.
pub output_format: Option<GptImage2p5OutputFormat>,
/// Compression level 0 to 100. Only sent for `jpeg` and `webp`.
pub output_compression: Option<u8>,
}
impl GptImage2p5EditImageParams {
/// Fal's default when `image_size` is omitted.
pub const DEFAULT_IMAGE_SIZE: GptImage2p5ImageSize = GptImage2p5ImageSize::Auto;
/// Fal's default when `quality` is omitted.
pub const DEFAULT_QUALITY: GptImage2p5Quality = GptImage2p5Quality::High;
pub fn to_raw_input(&self) -> GptImage2p5EditImageInput {
let output_format = self.output_format.unwrap_or(GptImage2p5OutputFormat::Png);
let output_compression = if output_format.supports_compression() {
self.output_compression.map(|c| c.min(100))
} else {
None
};
GptImage2p5EditImageInput {
prompt: self.prompt.clone(),
image_urls: self.image_urls.clone(),
mask_url: self.mask_url.clone(),
image_size: self.image_size.map(|size| size.to_raw_param(self.resolution)),
background: self.background.map(|b| b.to_str().to_string()),
quality: self.quality.map(|q| q.to_str().to_string()),
num_images: Some(self.num_images.to_u8()),
output_format: Some(output_format.to_str().to_string()),
output_compression,
}
}
/// Estimated cost in whole cents, rounded up per image.
///
/// Each output image is charged for rendering plus an allowance for reading the reference
/// images (the mask is not counted). With no explicit size the estimate uses the
/// conservative `Auto` dimensions.
pub fn estimate_cost_in_cents(&self) -> UsdCents {
let quality = self.quality.unwrap_or(Self::DEFAULT_QUALITY);
let (width, height) = self.image_size
.unwrap_or(Self::DEFAULT_IMAGE_SIZE)
.estimated_output_dimensions(self.resolution);
let hundredths_per_image = estimate_output_image_cost(quality, width, height)
+ estimate_reference_images_cost(self.image_urls.len());
hundredths_of_cent_to_cents(hundredths_per_image) * self.num_images.to_u64()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::requests::api::image::common::gpt_image_2p5::raw::gpt_image_2p5_image_size_param::GptImage2p5ImageSizeParam;
use GptImage2Resolution::*;
use GptImage2p5ImageSize::*;
use GptImage2p5NumImages::*;
use GptImage2p5Quality::{Low, Medium, High, XHigh, Max};
const IMAGE_URL: &str = "https://example.com/image.png";
mod to_raw_input_tests {
use super::*;
#[test]
fn minimal_request_serializes_to_expected_json() {
let raw = make_params(1, One, None, None, None).to_raw_input();
let json = serde_json::to_value(&raw).unwrap();
assert_eq!(json, serde_json::json!({
"prompt": "test",
"image_urls": [IMAGE_URL],
"num_images": 1,
"output_format": "png",
}));
}
#[test]
fn full_request_serializes_to_expected_json() {
let params = GptImage2p5EditImageParams {
prompt: "add a hat".to_string(),
image_urls: vec!["https://example.com/a.png".to_string(), "https://example.com/b.png".to_string()],
mask_url: Some("https://example.com/mask.png".to_string()),
num_images: Two,
image_size: Some(Portrait4x3),
resolution: Some(OneK),
quality: Some(Max),
background: Some(GptImage2p5Background::Opaque),
output_format: Some(GptImage2p5OutputFormat::Jpeg),
output_compression: Some(90),
};
let json = serde_json::to_value(params.to_raw_input()).unwrap();
assert_eq!(json, serde_json::json!({
"prompt": "add a hat",
"image_urls": ["https://example.com/a.png", "https://example.com/b.png"],
"mask_url": "https://example.com/mask.png",
"image_size": { "width": 768, "height": 1024 },
"background": "opaque",
"quality": "max",
"num_images": 2,
"output_format": "jpeg",
"output_compression": 90,
}));
}
#[test]
fn auto_size_sends_auto_preset_even_with_resolution() {
let raw = make_params(1, One, None, Some(Auto), Some(TwoK)).to_raw_input();
match raw.image_size.unwrap() {
GptImage2p5ImageSizeParam::Preset(s) => assert_eq!(s, "auto"),
GptImage2p5ImageSizeParam::Custom(_) => panic!("expected preset"),
}
}
#[test]
fn resolution_without_size_is_not_sent() {
let raw = make_params(1, One, None, None, Some(TwoK)).to_raw_input();
assert!(raw.image_size.is_none());
}
#[test]
fn compression_dropped_for_png() {
let mut params = make_params(1, One, None, None, None);
params.output_compression = Some(50);
assert!(params.to_raw_input().output_compression.is_none());
}
}
mod cost_tests {
use super::*;
// (size, resolution, [low, medium, high, xhigh, max]) — expected cents per image with
// one reference image. Pinned from the model in `gpt_image_2p5_pricing`.
const GRID_ONE_REFERENCE: &[(GptImage2p5ImageSize, Option<GptImage2Resolution>, [u64; 5])] = &[
// 1:1
(Square, None, [2, 3, 7, 11, 22]), // 1024x1024
(Square, Some(OneK), [2, 3, 7, 11, 22]), // 1024x1024
(Square, Some(TwoK), [2, 3, 10, 16, 35]), // 2048x2048
(Square, Some(ThreeK), [3, 4, 14, 23, 51]), // 2880x2880
(Square, Some(FourK), [3, 4, 14, 23, 51]), // 2880x2880 (pixel cap)
(SquareHd, None, [2, 3, 10, 16, 35]), // 2048x2048
(SquareHd, Some(OneK), [2, 3, 7, 11, 22]), // 1024x1024
(SquareHd, Some(TwoK), [2, 3, 10, 16, 35]), // 2048x2048
(SquareHd, Some(ThreeK), [3, 4, 14, 23, 51]), // 2880x2880
(SquareHd, Some(FourK), [3, 4, 14, 23, 51]), // 2880x2880 (pixel cap)
// 4:3
(Landscape4x3, None, [2, 2, 5, 8, 16]), // 1024x768
(Landscape4x3, Some(OneK), [2, 2, 5, 8, 16]), // 1024x768
(Landscape4x3, Some(TwoK), [2, 3, 7, 12, 25]), // 2048x1536
(Landscape4x3, Some(ThreeK), [2, 4, 11, 19, 40]), // 3072x2304
(Landscape4x3, Some(FourK), [3, 4, 12, 21, 45]), // 3312x2480 (pixel cap)
(Portrait4x3, None, [2, 2, 5, 8, 16]), // 768x1024
(Portrait4x3, Some(OneK), [2, 2, 5, 8, 16]), // 768x1024
(Portrait4x3, Some(TwoK), [2, 3, 7, 12, 25]), // 1536x2048
(Portrait4x3, Some(ThreeK), [2, 4, 11, 19, 40]), // 2304x3072
(Portrait4x3, Some(FourK), [3, 4, 12, 21, 45]), // 2480x3312 (pixel cap)
// 16:9
(Landscape16x9, None, [2, 2, 5, 8, 17]), // 1920x1080
(Landscape16x9, Some(OneK), [2, 2, 4, 6, 12]), // 1088x608
(Landscape16x9, Some(TwoK), [2, 2, 6, 9, 18]), // 2048x1152
(Landscape16x9, Some(ThreeK), [2, 3, 8, 14, 30]), // 3072x1728
(Landscape16x9, Some(FourK), [2, 4, 11, 19, 41]), // 3840x2160
(Portrait16x9, None, [2, 2, 5, 8, 17]), // 1080x1920
(Portrait16x9, Some(OneK), [2, 2, 4, 6, 12]), // 608x1088
(Portrait16x9, Some(TwoK), [2, 2, 6, 9, 18]), // 1152x2048
(Portrait16x9, Some(ThreeK), [2, 3, 8, 14, 30]), // 1728x3072
(Portrait16x9, Some(FourK), [2, 4, 11, 19, 41]), // 2160x3840
// Auto always prices at the conservative 3840x2160
(Auto, None, [2, 4, 11, 19, 41]),
(Auto, Some(OneK), [2, 4, 11, 19, 41]),
(Auto, Some(FourK), [2, 4, 11, 19, 41]),
];
const ALL_QUALITIES: [GptImage2p5Quality; 5] = [Low, Medium, High, XHigh, Max];
#[test]
fn exhaustive_grid_with_one_reference_image() {
for &(size, resolution, expected) in GRID_ONE_REFERENCE {
for (quality, expected) in ALL_QUALITIES.iter().zip(expected) {
let actual = make_params(1, One, Some(*quality), Some(size), resolution).estimate_cost_in_cents();
assert_eq!(actual, expected, "{size:?} {resolution:?} {quality:?}");
}
}
}
#[test]
fn batch_scales_linearly_across_grid() {
for &(size, resolution, _) in GRID_ONE_REFERENCE {
let per_image = make_params(1, One, Some(High), Some(size), resolution).estimate_cost_in_cents();
for (num, n) in [(Two, 2), (Three, 3), (Four, 4)] {
let actual = make_params(1, num, Some(High), Some(size), resolution).estimate_cost_in_cents();
assert_eq!(actual, per_image * n, "{size:?} {resolution:?} x{n}");
}
}
}
#[test]
fn more_reference_images_never_cost_less() {
for &(size, resolution, _) in GRID_ONE_REFERENCE {
let mut previous = 0;
for refs in 1..=16 {
let cost = make_params(refs, One, Some(High), Some(size), resolution).estimate_cost_in_cents();
assert!(cost >= previous, "{size:?} {resolution:?} {refs} refs: {cost} < {previous}");
previous = cost;
}
}
}
#[test]
fn defaults_to_high_quality_auto_size() {
// 3840x2160 high = 1001 + one reference image 80 = 1081 hundredths => 11 cents
assert_eq!(make_params(1, One, None, None, None).estimate_cost_in_cents(), 11);
assert_eq!(make_params(1, One, Some(High), Some(Auto), None).estimate_cost_in_cents(), 11);
}
#[test]
fn reference_images_add_to_cost() {
// Square high = 529 hundredths; each reference image adds 80.
assert_eq!(make_params(1, One, Some(High), Some(Square), None).estimate_cost_in_cents(), 7); // 609
assert_eq!(make_params(3, One, Some(High), Some(Square), None).estimate_cost_in_cents(), 8); // 769
assert_eq!(make_params(16, One, Some(High), Some(Square), None).estimate_cost_in_cents(), 19); // 1809
}
#[test]
fn batch_multiplies_per_image_cents() {
assert_eq!(make_params(1, One, Some(High), Some(Square), None).estimate_cost_in_cents(), 7);
assert_eq!(make_params(1, Two, Some(High), Some(Square), None).estimate_cost_in_cents(), 14);
assert_eq!(make_params(1, Three, Some(High), Some(Square), None).estimate_cost_in_cents(), 21);
assert_eq!(make_params(1, Four, Some(High), Some(Square), None).estimate_cost_in_cents(), 28);
}
}
fn make_params(
num_reference_images: usize,
num_images: GptImage2p5NumImages,
quality: Option<GptImage2p5Quality>,
image_size: Option<GptImage2p5ImageSize>,
resolution: Option<GptImage2Resolution>,
) -> GptImage2p5EditImageParams {
GptImage2p5EditImageParams {
prompt: "test".to_string(),
image_urls: vec![IMAGE_URL.to_string(); num_reference_images],
mask_url: None,
num_images,
image_size,
resolution,
quality,
background: None,
output_format: None,
output_compression: None,
}
}
}
@@ -1,169 +0,0 @@
use crate::requests::api::image::common::gpt_image_2_resolution::{
compute_custom_image_size, GptImage2AspectRatio, GptImage2Resolution,
};
use crate::requests::api::image::common::gpt_image_2p5::raw::gpt_image_2p5_image_size_param::GptImage2p5ImageSizeParam;
/// Output image size preset. Both text-to-image and edit accept the same set, including
/// `Auto` (text-to-image: model picks; edit: inferred from the input images).
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum GptImage2p5ImageSize {
SquareHd,
Square,
Portrait4x3,
Portrait16x9,
Landscape4x3,
Landscape16x9,
Auto,
}
/// Conservative dimensions assumed for `Auto` when estimating cost: the largest canonical
/// size Fal publishes pricing for.
pub const AUTO_SIZE_ESTIMATED_DIMENSIONS: (u32, u32) = (3840, 2160);
impl GptImage2p5ImageSize {
/// Build the wire `image_size` value.
///
/// With a resolution tier, a concrete `{width, height}` is computed from the preset's
/// aspect ratio. `Auto` has no aspect ratio, so it is always sent as the `"auto"` preset
/// and any resolution tier is ignored.
pub fn to_raw_param(self, resolution: Option<GptImage2Resolution>) -> GptImage2p5ImageSizeParam {
match (self.to_aspect_ratio(), resolution) {
(Some(aspect), Some(resolution)) => {
GptImage2p5ImageSizeParam::Custom(compute_custom_image_size(aspect, resolution))
}
_ => GptImage2p5ImageSizeParam::Preset(self.to_preset_str().to_string()),
}
}
/// The output dimensions we expect Fal to render, used for cost estimation.
pub fn estimated_output_dimensions(self, resolution: Option<GptImage2Resolution>) -> (u32, u32) {
match (self.to_aspect_ratio(), resolution) {
(Some(aspect), Some(resolution)) => {
let custom = compute_custom_image_size(aspect, resolution);
(custom.width, custom.height)
}
_ => self.preset_dimensions(),
}
}
pub fn to_preset_str(self) -> &'static str {
match self {
GptImage2p5ImageSize::SquareHd => "square_hd",
GptImage2p5ImageSize::Square => "square",
GptImage2p5ImageSize::Portrait4x3 => "portrait_4_3",
GptImage2p5ImageSize::Portrait16x9 => "portrait_16_9",
GptImage2p5ImageSize::Landscape4x3 => "landscape_4_3",
GptImage2p5ImageSize::Landscape16x9 => "landscape_16_9",
GptImage2p5ImageSize::Auto => "auto",
}
}
/// `None` for `Auto`, which carries no aspect ratio.
pub fn to_aspect_ratio(self) -> Option<GptImage2AspectRatio> {
match self {
GptImage2p5ImageSize::SquareHd => Some(GptImage2AspectRatio::SquareHd),
GptImage2p5ImageSize::Square => Some(GptImage2AspectRatio::Square),
GptImage2p5ImageSize::Portrait4x3 => Some(GptImage2AspectRatio::Portrait4x3),
GptImage2p5ImageSize::Portrait16x9 => Some(GptImage2AspectRatio::Portrait16x9),
GptImage2p5ImageSize::Landscape4x3 => Some(GptImage2AspectRatio::Landscape4x3),
GptImage2p5ImageSize::Landscape16x9 => Some(GptImage2AspectRatio::Landscape16x9),
GptImage2p5ImageSize::Auto => None,
}
}
/// Dimensions assumed for a preset sent without a resolution tier. These match the
/// assumptions used by the GPT Image 2 bindings; `Auto` uses the conservative maximum.
fn preset_dimensions(self) -> (u32, u32) {
match self {
GptImage2p5ImageSize::SquareHd => (2048, 2048),
GptImage2p5ImageSize::Square => (1024, 1024),
GptImage2p5ImageSize::Portrait4x3 => (768, 1024),
GptImage2p5ImageSize::Portrait16x9 => (1080, 1920),
GptImage2p5ImageSize::Landscape4x3 => (1024, 768),
GptImage2p5ImageSize::Landscape16x9 => (1920, 1080),
GptImage2p5ImageSize::Auto => AUTO_SIZE_ESTIMATED_DIMENSIONS,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use GptImage2p5ImageSize::*;
const ALL_SIZES: &[GptImage2p5ImageSize] = &[
SquareHd, Square, Portrait4x3, Portrait16x9, Landscape4x3, Landscape16x9, Auto,
];
#[test]
fn wire_strings_match_fal_schema() {
assert_eq!(SquareHd.to_preset_str(), "square_hd");
assert_eq!(Square.to_preset_str(), "square");
assert_eq!(Portrait4x3.to_preset_str(), "portrait_4_3");
assert_eq!(Portrait16x9.to_preset_str(), "portrait_16_9");
assert_eq!(Landscape4x3.to_preset_str(), "landscape_4_3");
assert_eq!(Landscape16x9.to_preset_str(), "landscape_16_9");
assert_eq!(Auto.to_preset_str(), "auto");
}
#[test]
fn preset_without_resolution_sends_preset_string() {
for &size in ALL_SIZES {
match size.to_raw_param(None) {
GptImage2p5ImageSizeParam::Preset(s) => assert_eq!(s, size.to_preset_str()),
GptImage2p5ImageSizeParam::Custom(_) => panic!("{size:?} should be a preset"),
}
}
}
#[test]
fn preset_with_resolution_sends_custom_dimensions() {
match Landscape16x9.to_raw_param(Some(GptImage2Resolution::TwoK)) {
GptImage2p5ImageSizeParam::Custom(c) => {
assert_eq!(c.width, 2048);
assert_eq!(c.height, 1152);
}
GptImage2p5ImageSizeParam::Preset(_) => panic!("expected custom"),
}
}
#[test]
fn auto_with_resolution_falls_back_to_auto_preset() {
match Auto.to_raw_param(Some(GptImage2Resolution::TwoK)) {
GptImage2p5ImageSizeParam::Preset(s) => assert_eq!(s, "auto"),
GptImage2p5ImageSizeParam::Custom(_) => panic!("Auto must never send custom dimensions"),
}
}
#[test]
fn estimated_dimensions_without_resolution() {
assert_eq!(Square.estimated_output_dimensions(None), (1024, 1024));
assert_eq!(SquareHd.estimated_output_dimensions(None), (2048, 2048));
assert_eq!(Landscape4x3.estimated_output_dimensions(None), (1024, 768));
assert_eq!(Portrait4x3.estimated_output_dimensions(None), (768, 1024));
assert_eq!(Landscape16x9.estimated_output_dimensions(None), (1920, 1080));
assert_eq!(Portrait16x9.estimated_output_dimensions(None), (1080, 1920));
assert_eq!(Auto.estimated_output_dimensions(None), (3840, 2160));
}
#[test]
fn estimated_dimensions_with_resolution_match_wire_dimensions() {
for &size in ALL_SIZES {
if size == Auto {
continue;
}
for res in [GptImage2Resolution::OneK, GptImage2Resolution::TwoK, GptImage2Resolution::ThreeK, GptImage2Resolution::FourK] {
let (w, h) = size.estimated_output_dimensions(Some(res));
match size.to_raw_param(Some(res)) {
GptImage2p5ImageSizeParam::Custom(c) => assert_eq!((c.width, c.height), (w, h), "{size:?} {res:?}"),
GptImage2p5ImageSizeParam::Preset(_) => panic!("{size:?} {res:?} should be custom"),
}
}
}
}
#[test]
fn auto_ignores_resolution_for_estimation() {
assert_eq!(Auto.estimated_output_dimensions(Some(GptImage2Resolution::OneK)), (3840, 2160));
}
}

Some files were not shown because too many files have changed in this diff Show More