mirror of
https://github.com/storytold/artcraft.git
synced 2026-11-06 06:14:52 -05:00
Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
27c463e33d | ||
|
|
ed57c6de47 | ||
|
|
74207e3520 | ||
|
|
60be62cb71 | ||
|
|
976f2ae757 | ||
|
|
f667353898 | ||
|
|
0fa098dd38 | ||
|
|
ce13ae68cb | ||
|
|
393672988e | ||
|
|
8d13d84109 | ||
|
|
44ff9ce338 | ||
|
|
bde7760080 | ||
|
|
e3f48033f9 | ||
|
|
915728e9c7 | ||
|
|
58d6d7f72e | ||
|
|
b55aa0d2cb | ||
|
|
ce8b7e4637 | ||
|
|
4975440053 | ||
|
|
f3442f3146 | ||
|
|
ac613b007b | ||
|
|
47aa6a6c06 | ||
|
|
da6a6c8441 |
+135
@@ -0,0 +1,135 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
# 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,96 +0,0 @@
|
||||
# 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.
|
||||
@@ -0,0 +1,5 @@
|
||||
-- noinspection SqlDialectInspectionForFile
|
||||
-- noinspection SqlNoDataSourceInspectionForFile
|
||||
-- noinspection SqlResolveForFile
|
||||
|
||||
DROP TABLE IF EXISTS mcp_sessions;
|
||||
@@ -0,0 +1,65 @@
|
||||
-- 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;
|
||||
@@ -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,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
@@ -0,0 +1 @@
|
||||
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,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/`).
|
||||
@@ -0,0 +1 @@
|
||||
AGENTS.md
|
||||
@@ -0,0 +1,65 @@
|
||||
-- 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;
|
||||
@@ -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,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
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
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.
|
||||
@@ -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.
|
||||
@@ -0,0 +1 @@
|
||||
AGENTS.md
|
||||
@@ -7,6 +7,7 @@ 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;
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
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,
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
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,
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
use serde_derive::Serialize;
|
||||
use utoipa::ToSchema;
|
||||
|
||||
// ── POST /v1/mcp/session/{token}/delete ──
|
||||
|
||||
#[derive(Serialize, ToSchema)]
|
||||
pub struct DeleteMcpSessionSuccessResponse {
|
||||
pub success: bool,
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
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>,
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
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;
|
||||
@@ -0,0 +1,22 @@
|
||||
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,
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
use serde_derive::Serialize;
|
||||
use utoipa::ToSchema;
|
||||
|
||||
// ── POST /v1/mcp/session/revoke ──
|
||||
|
||||
#[derive(Serialize, ToSchema)]
|
||||
pub struct RevokeMcpSessionSuccessResponse {
|
||||
pub success: bool,
|
||||
}
|
||||
+32
@@ -14,6 +14,14 @@ 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),
|
||||
}
|
||||
@@ -27,6 +35,14 @@ 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),
|
||||
}
|
||||
}
|
||||
@@ -41,6 +57,14 @@ 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,
|
||||
}
|
||||
}
|
||||
@@ -73,6 +97,14 @@ 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);
|
||||
|
||||
+8
@@ -16,6 +16,8 @@ pub enum ApiClientImageModel {
|
||||
GptImage1p5,
|
||||
GptImage2,
|
||||
GrokImagineImage,
|
||||
GptImage2p5Flare,
|
||||
GptImage2p5Sunburst,
|
||||
GrokImagineImageQuality,
|
||||
Midjourney7,
|
||||
Midjourney7Niji,
|
||||
@@ -42,6 +44,8 @@ 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,
|
||||
@@ -70,6 +74,8 @@ 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(),
|
||||
@@ -116,6 +122,8 @@ 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,6 +19,10 @@ 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")]
|
||||
@@ -87,4 +91,14 @@ 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");
|
||||
}
|
||||
}
|
||||
|
||||
+8
@@ -16,6 +16,8 @@ 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;
|
||||
@@ -36,6 +38,8 @@ 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;
|
||||
@@ -116,6 +120,8 @@ 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),
|
||||
@@ -137,6 +143,8 @@ 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),
|
||||
|
||||
+40
@@ -19,6 +19,10 @@ 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;
|
||||
@@ -59,6 +63,10 @@ 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;
|
||||
@@ -92,6 +100,8 @@ pub enum ImageGenerationRequest {
|
||||
ArtcraftGptImage1(ArtcraftGptImage1RequestState),
|
||||
ArtcraftGptImage1p5(ArtcraftGptImage1p5RequestState),
|
||||
ArtcraftGptImage2(ArtcraftGptImage2RequestState),
|
||||
ArtcraftGptImage2p5Flare(ArtcraftGptImage2p5FlareRequestState),
|
||||
ArtcraftGptImage2p5Sunburst(ArtcraftGptImage2p5SunburstRequestState),
|
||||
ArtcraftNanoBanana(ArtcraftNanoBananaRequestState),
|
||||
ArtcraftNanoBanana2(ArtcraftNanoBanana2RequestState),
|
||||
ArtcraftNanoBananaPro(ArtcraftNanoBananaProRequestState),
|
||||
@@ -114,6 +124,8 @@ pub enum ImageGenerationRequest {
|
||||
FalGptImage1(FalGptImage1RequestState),
|
||||
FalGptImage1p5(FalGptImage1p5RequestState),
|
||||
FalGptImage2(FalGptImage2RequestState),
|
||||
FalGptImage2p5Flare(FalGptImage2p5FlareRequestState),
|
||||
FalGptImage2p5Sunburst(FalGptImage2p5SunburstRequestState),
|
||||
FalNanoBanana(FalNanoBananaRequestState),
|
||||
FalNanoBanana2(FalNanoBanana2RequestState),
|
||||
FalNanoBananaPro(FalNanoBananaProRequestState),
|
||||
@@ -140,6 +152,8 @@ 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,
|
||||
@@ -161,6 +175,8 @@ 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,
|
||||
@@ -201,6 +217,12 @@ 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())
|
||||
}
|
||||
@@ -249,6 +271,8 @@ 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()),
|
||||
@@ -296,6 +320,14 @@ 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
|
||||
@@ -379,6 +411,14 @@ 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()?;
|
||||
|
||||
+290
@@ -0,0 +1,290 @@
|
||||
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 }
|
||||
}
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
pub mod build;
|
||||
pub mod cost;
|
||||
pub mod request;
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
pub mod build;
|
||||
pub mod cost;
|
||||
pub mod request;
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
+3
@@ -8,6 +8,9 @@ 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;
|
||||
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
//! 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;
|
||||
+330
@@ -0,0 +1,330 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
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))
|
||||
}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
pub mod build;
|
||||
pub mod cost;
|
||||
pub mod request;
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
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(),
|
||||
)
|
||||
}
|
||||
}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
pub mod build;
|
||||
pub mod cost;
|
||||
pub mod request;
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
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(),
|
||||
)
|
||||
}
|
||||
}
|
||||
+3
@@ -6,6 +6,9 @@ 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;
|
||||
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
+1
@@ -0,0 +1 @@
|
||||
AGENTS.md
|
||||
+25
-25
@@ -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 = 16.0;
|
||||
const CENTS_PER_SECOND_720P: f64 = 18.5;
|
||||
const CENTS_PER_SECOND_1080P: f64 = 46.632;
|
||||
|
||||
/// USD cents per second, in hundredths of a cent, when one or more
|
||||
@@ -131,32 +131,32 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn batch_1() {
|
||||
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);
|
||||
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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_2() {
|
||||
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);
|
||||
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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_3() {
|
||||
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);
|
||||
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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_4() {
|
||||
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);
|
||||
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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -242,10 +242,10 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn explicit_4k_without_video_reference() {
|
||||
assert_eq!(artcraft_4k_cents(4, 1, false), 358);
|
||||
assert_eq!(artcraft_4k_cents(5, 1, false), 447);
|
||||
assert_eq!(artcraft_4k_cents(10, 1, false), 893);
|
||||
assert_eq!(artcraft_4k_cents(15, 1, false), 1340);
|
||||
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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -499,9 +499,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn refs_cost_more_at_720p() {
|
||||
assert_ref_delta(CommonResolution::SevenTwentyP, 5, 80, 111, 31);
|
||||
assert_ref_delta(CommonResolution::SevenTwentyP, 10, 160, 221, 61);
|
||||
assert_ref_delta(CommonResolution::SevenTwentyP, 15, 240, 331, 91);
|
||||
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]
|
||||
@@ -513,9 +513,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn refs_cost_more_at_4k() {
|
||||
assert_ref_delta(CommonResolution::FourK, 5, 447, 569, 122);
|
||||
assert_ref_delta(CommonResolution::FourK, 10, 893, 1138, 245);
|
||||
assert_ref_delta(CommonResolution::FourK, 15, 1340, 1707, 367);
|
||||
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
|
||||
|
||||
+106
-8
@@ -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 = 6.40;
|
||||
const CENTS_PER_SECOND_480P: f64 = 7.13;
|
||||
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), 26);
|
||||
assert_eq!(cost_cents(Some(RouterResolution::FourEightyP), 5, 1), 32);
|
||||
assert_eq!(cost_cents(Some(RouterResolution::FourEightyP), 10, 1), 64);
|
||||
assert_eq!(cost_cents(Some(RouterResolution::FourEightyP), 15, 1), 96);
|
||||
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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_2() {
|
||||
assert_eq!(cost_cents(Some(RouterResolution::FourEightyP), 5, 2), 64);
|
||||
assert_eq!(cost_cents(Some(RouterResolution::FourEightyP), 5, 2), 71);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_3() {
|
||||
assert_eq!(cost_cents(Some(RouterResolution::FourEightyP), 5, 3), 96);
|
||||
assert_eq!(cost_cents(Some(RouterResolution::FourEightyP), 5, 3), 107);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_4() {
|
||||
assert_eq!(cost_cents(Some(RouterResolution::FourEightyP), 5, 4), 128);
|
||||
assert_eq!(cost_cents(Some(RouterResolution::FourEightyP), 5, 4), 143);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -275,6 +275,76 @@ 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 --
|
||||
@@ -359,4 +429,32 @@ 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()
|
||||
}
|
||||
}
|
||||
|
||||
+9
-3
@@ -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::Fast,
|
||||
SupportedResolutions::Full,
|
||||
UltraWideSupport::Supported,
|
||||
)?;
|
||||
request.duration_seconds = duration_seconds;
|
||||
@@ -216,9 +216,15 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn res_1080p_downgrades_to_720p() {
|
||||
fn res_1080p_maps_directly() {
|
||||
let req = unwrap_request(builder_with(|b| { b.resolution = Some(RouterResolution::TenEightyP); }));
|
||||
assert_eq!(req.request.resolution, Some(CommonResolutionEnum::SevenTwentyP));
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+24
@@ -92,6 +92,20 @@ 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));
|
||||
@@ -107,6 +121,16 @@ 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]
|
||||
|
||||
+9
-3
@@ -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::Fast,
|
||||
SupportedResolutions::Full,
|
||||
UltraWideSupport::Supported,
|
||||
)?;
|
||||
request.duration_seconds = duration_seconds;
|
||||
@@ -216,9 +216,15 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn res_1080p_downgrades_to_720p() {
|
||||
fn res_1080p_maps_directly() {
|
||||
let req = unwrap_request(builder_with(|b| { b.resolution = Some(RouterResolution::TenEightyP); }));
|
||||
assert_eq!(req.request.resolution, Some(CommonResolutionEnum::SevenTwentyP));
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+26
@@ -93,6 +93,20 @@ 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));
|
||||
@@ -105,6 +119,8 @@ 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| {
|
||||
@@ -125,6 +141,16 @@ 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]
|
||||
|
||||
+34
-19
@@ -11,8 +11,8 @@ 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 (89.30 ¢/s).
|
||||
const FOUR_K_CENTI_CENTS_PER_SECOND: u64 = 8930;
|
||||
/// 4K output price, in hundredths of a USD cent per second (92.50 ¢/s).
|
||||
const FOUR_K_CENTI_CENTS_PER_SECOND: u64 = 9250;
|
||||
|
||||
/// ArtCraft's price (USD cents) for Seedance 2.0 at 4K with no reference
|
||||
/// videos attached. Each model prices reference videos through its own
|
||||
@@ -137,19 +137,24 @@ 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.
|
||||
///
|
||||
/// 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.
|
||||
/// 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.
|
||||
pub fn seedance_2p5_usd_cents(
|
||||
resolution: CommonResolution,
|
||||
duration_seconds: u16,
|
||||
@@ -159,6 +164,7 @@ pub fn seedance_2p5_usd_cents(
|
||||
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,
|
||||
};
|
||||
@@ -180,6 +186,7 @@ pub fn seedance_2p5_usd_cents(
|
||||
} 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))
|
||||
@@ -192,18 +199,24 @@ 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.
|
||||
///
|
||||
/// 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.
|
||||
/// 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.
|
||||
pub fn seedance_2p5_ultra_usd_cents(
|
||||
resolution: CommonResolution,
|
||||
duration_seconds: u16,
|
||||
@@ -213,6 +226,7 @@ pub fn seedance_2p5_ultra_usd_cents(
|
||||
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,
|
||||
};
|
||||
@@ -234,6 +248,7 @@ pub fn seedance_2p5_ultra_usd_cents(
|
||||
} 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))
|
||||
@@ -273,16 +288,16 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn four_k_base_prices() {
|
||||
assert_eq!(seedance_2p0_four_k_usd_cents(4, 1), 358);
|
||||
assert_eq!(seedance_2p0_four_k_usd_cents(5, 1), 447);
|
||||
assert_eq!(seedance_2p0_four_k_usd_cents(10, 1), 893);
|
||||
assert_eq!(seedance_2p0_four_k_usd_cents(15, 1), 1340);
|
||||
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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_count_multiplies() {
|
||||
assert_eq!(seedance_2p0_four_k_usd_cents(5, 2), 893);
|
||||
assert_eq!(seedance_2p0_four_k_usd_cents(5, 4), 1786);
|
||||
assert_eq!(seedance_2p0_four_k_usd_cents(5, 2), 925);
|
||||
assert_eq!(seedance_2p0_four_k_usd_cents(5, 4), 1850);
|
||||
}
|
||||
|
||||
// ── Seedance 2.0 Mini ──
|
||||
|
||||
+6
-3
@@ -100,7 +100,10 @@ fn plan_output_resolution(
|
||||
strategy: RequestMismatchMitigationStrategy,
|
||||
) -> Result<Option<KinoviHappyHorse1p0OutputResolution>, ArtcraftRouterError> {
|
||||
match resolution {
|
||||
None => Ok(None),
|
||||
// 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)),
|
||||
|
||||
Some(RouterResolution::SevenTwentyP) => Ok(Some(KinoviHappyHorse1p0OutputResolution::SevenTwentyP)),
|
||||
Some(RouterResolution::TenEightyP) => Ok(Some(KinoviHappyHorse1p0OutputResolution::TenEightyP)),
|
||||
@@ -332,10 +335,10 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolution_none() {
|
||||
fn resolution_none_defaults_to_720p() {
|
||||
let builder = GenerateVideoRequestBuilder { resolution: None, ..happy_horse_builder() };
|
||||
let draft = unwrap_draft(build_kinovi_happy_horse_1p0(builder));
|
||||
assert!(draft.resolution.is_none());
|
||||
assert!(matches!(draft.resolution, Some(KinoviHappyHorse1p0OutputResolution::SevenTwentyP)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+6
-3
@@ -117,7 +117,10 @@ fn plan_output_resolution(
|
||||
strategy: RequestMismatchMitigationStrategy,
|
||||
) -> Result<Option<KinoviOutputResolution>, ArtcraftRouterError> {
|
||||
match resolution {
|
||||
None => Ok(None),
|
||||
// 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)),
|
||||
|
||||
// Direct mappings
|
||||
Some(RouterResolution::FourEightyP) => Ok(Some(KinoviOutputResolution::FourEightyP)),
|
||||
@@ -393,10 +396,10 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolution_none() {
|
||||
fn resolution_none_defaults_to_720p() {
|
||||
let builder = GenerateVideoRequestBuilder { resolution: None, ..kinovi_web_builder() };
|
||||
let draft = unwrap_draft(build_kinovi_seedance_2p0(builder));
|
||||
assert!(draft.resolution.is_none());
|
||||
assert!(matches!(draft.resolution, Some(KinoviOutputResolution::SevenTwentyP)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+59
-50
@@ -2,6 +2,7 @@ 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;
|
||||
@@ -66,8 +67,13 @@ impl KinoviSeedance2p0CostState {
|
||||
bitrate: None,
|
||||
};
|
||||
|
||||
let costs = pricing_request.calculate_costs();
|
||||
let cost_in_credits = costs.total_cost.kinovi_credits;
|
||||
// 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 cost_in_usd_cents = costs.total_cost.usd_cents_rounded_up;
|
||||
|
||||
VideoGenerationCostEstimate {
|
||||
@@ -97,40 +103,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 ──
|
||||
// ── 720p pricing (enterprise discount: 37.9 credits/sec) ──
|
||||
|
||||
mod pricing_720p {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn cost_720p_batch_1() {
|
||||
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);
|
||||
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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cost_720p_batch_2() {
|
||||
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);
|
||||
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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cost_720p_batch_3() {
|
||||
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);
|
||||
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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cost_720p_batch_4() {
|
||||
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);
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -195,7 +201,7 @@ mod tests {
|
||||
// ── 4K pricing ──
|
||||
//
|
||||
// Routes to the kinovi_web_client: 4K base is 200 credits/s (vs 90 at 1080p).
|
||||
// Credits → cents at 243 credits/$1, rounded up.
|
||||
// Credits → cents at the enterprise rate of 243.16 credits/$1, rounded up.
|
||||
|
||||
mod pricing_4k {
|
||||
use super::*;
|
||||
@@ -204,34 +210,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), 824);
|
||||
assert_eq!(usd_cents(KinoviOutputResolution::FourK, 15, KinoviBatchCount::One), 1235);
|
||||
assert_eq!(usd_cents(KinoviOutputResolution::FourK, 10, KinoviBatchCount::One), 823);
|
||||
assert_eq!(usd_cents(KinoviOutputResolution::FourK, 15, KinoviBatchCount::One), 1234);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cost_4k_batch_2() {
|
||||
assert_eq!(usd_cents(KinoviOutputResolution::FourK, 5, KinoviBatchCount::Two), 824);
|
||||
assert_eq!(usd_cents(KinoviOutputResolution::FourK, 5, KinoviBatchCount::Two), 823);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cost_4k_batch_3() {
|
||||
assert_eq!(usd_cents(KinoviOutputResolution::FourK, 5, KinoviBatchCount::Three), 1235);
|
||||
assert_eq!(usd_cents(KinoviOutputResolution::FourK, 5, KinoviBatchCount::Three), 1234);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cost_4k_batch_4() {
|
||||
assert_eq!(usd_cents(KinoviOutputResolution::FourK, 5, KinoviBatchCount::Four), 1647);
|
||||
assert_eq!(usd_cents(KinoviOutputResolution::FourK, 5, KinoviBatchCount::Four), 1646);
|
||||
}
|
||||
}
|
||||
|
||||
// ── 4K: router cost must match the kinovi_web_client binding ──
|
||||
//
|
||||
// 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.
|
||||
// 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.
|
||||
//
|
||||
// 4K base = 200 credits/s; with a video reference = 240 credits/s (+40 surcharge).
|
||||
// USD cents = ceil(total_credits / 243 * 100).
|
||||
// USD cents = ceil(total_credits / 243.16 * 100).
|
||||
|
||||
mod four_k_matches_binding {
|
||||
use super::*;
|
||||
@@ -271,8 +277,8 @@ mod tests {
|
||||
use_face_blur_hack: None,
|
||||
bitrate: None,
|
||||
}
|
||||
.calculate_costs();
|
||||
(costs.total_cost.kinovi_credits, costs.total_cost.usd_cents_rounded_up)
|
||||
.calculate_enterprise_costs();
|
||||
(costs.total_cost.kinovi_credits.round() as u64, costs.total_cost.usd_cents_rounded_up)
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -280,17 +286,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(824)));
|
||||
assert_eq!((router(15, false).cost_in_credits, router(15, false).cost_in_usd_cents), (Some(3000), Some(1235)));
|
||||
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)));
|
||||
}
|
||||
|
||||
#[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(396)));
|
||||
assert_eq!((router(4, true).cost_in_credits, router(4, true).cost_in_usd_cents), (Some(960), Some(395)));
|
||||
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(1482)));
|
||||
assert_eq!((router(15, true).cost_in_credits, router(15, true).cost_in_usd_cents), (Some(3600), Some(1481)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -364,10 +370,11 @@ mod tests {
|
||||
};
|
||||
let without = base.estimate_cost();
|
||||
let with = KinoviSeedance2p0CostState { has_video_reference: true, ..base }.estimate_cost();
|
||||
// 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));
|
||||
// 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));
|
||||
}
|
||||
|
||||
// ── from_request() tests ──
|
||||
@@ -383,7 +390,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(83));
|
||||
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(78));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -391,7 +398,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(83));
|
||||
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(78));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -413,9 +420,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);
|
||||
// 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));
|
||||
// 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));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -435,11 +442,12 @@ mod tests {
|
||||
fn from_draft_720p_default() {
|
||||
let draft = make_draft(5, 1, None, false);
|
||||
let cost = KinoviSeedance2p0CostState::from_draft(&draft);
|
||||
assert!(cost.resolution.is_none()); // None defaults to 720p pricing
|
||||
// Unset resolution is pinned to explicit 720p at build time.
|
||||
assert!(matches!(cost.resolution, Some(KinoviOutputResolution::SevenTwentyP)));
|
||||
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(83));
|
||||
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(78));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -482,9 +490,9 @@ mod tests {
|
||||
let draft = make_draft(5, 1, None, true);
|
||||
let cost = KinoviSeedance2p0CostState::from_draft(&draft);
|
||||
assert!(cost.has_video_reference);
|
||||
// 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));
|
||||
// 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));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -500,7 +508,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(494));
|
||||
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(468));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -538,7 +546,8 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn credits_720p() {
|
||||
assert_eq!(credits(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::One), 200);
|
||||
// Enterprise 37.9 credits/s × 5s = 189.5, rounded to 190.
|
||||
assert_eq!(credits(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::One), 190);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+6
-3
@@ -118,7 +118,10 @@ fn plan_output_resolution(
|
||||
strategy: RequestMismatchMitigationStrategy,
|
||||
) -> Result<Option<KinoviOutputResolution>, ArtcraftRouterError> {
|
||||
match resolution {
|
||||
None => Ok(None),
|
||||
// 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)),
|
||||
|
||||
// Direct mappings
|
||||
Some(RouterResolution::FourEightyP) => Ok(Some(KinoviOutputResolution::FourEightyP)),
|
||||
@@ -421,10 +424,10 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolution_none() {
|
||||
fn resolution_none_defaults_to_720p() {
|
||||
let builder = GenerateVideoRequestBuilder { resolution: None, ..kinovi_web_fast_builder() };
|
||||
let draft = unwrap_draft(build_kinovi_seedance_2p0_fast(builder));
|
||||
assert!(draft.resolution.is_none());
|
||||
assert!(matches!(draft.resolution, Some(KinoviOutputResolution::SevenTwentyP)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+47
-37
@@ -2,6 +2,7 @@ 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;
|
||||
@@ -66,8 +67,13 @@ impl KinoviSeedance2p0FastCostState {
|
||||
bitrate: None,
|
||||
};
|
||||
|
||||
let costs = pricing_request.calculate_costs();
|
||||
let cost_in_credits = costs.total_cost.kinovi_credits;
|
||||
// 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 cost_in_usd_cents = costs.total_cost.usd_cents_rounded_up;
|
||||
|
||||
VideoGenerationCostEstimate {
|
||||
@@ -101,61 +107,61 @@ mod tests {
|
||||
// ── Direct estimate_cost() tests ──
|
||||
// These must match the reference implementation values exactly.
|
||||
|
||||
// -- 720p (28 credits/sec, 243 credits/$1) --
|
||||
// -- 720p (enterprise 21 credits/sec, 243.16 credits/$1) --
|
||||
|
||||
mod pricing_720p {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn cost_720p_batch_1() {
|
||||
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);
|
||||
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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cost_720p_batch_2() {
|
||||
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::Two), 116);
|
||||
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::Two), 87);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cost_720p_batch_3() {
|
||||
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::Three), 173);
|
||||
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::Three), 130);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cost_720p_batch_4() {
|
||||
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::Four), 231);
|
||||
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::Four), 173);
|
||||
}
|
||||
}
|
||||
|
||||
// -- 480p (14 credits/sec, 243 credits/$1) --
|
||||
// -- 480p (enterprise 10.5 credits/sec, 243.16 credits/$1) --
|
||||
|
||||
mod pricing_480p {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn cost_480p_batch_1() {
|
||||
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);
|
||||
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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cost_480p_batch_2() {
|
||||
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 5, KinoviBatchCount::Two), 58);
|
||||
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 5, KinoviBatchCount::Two), 44);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cost_480p_batch_3() {
|
||||
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 5, KinoviBatchCount::Three), 87);
|
||||
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 5, KinoviBatchCount::Three), 65);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cost_480p_batch_4() {
|
||||
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 5, KinoviBatchCount::Four), 116);
|
||||
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 5, KinoviBatchCount::Four), 87);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -202,10 +208,11 @@ mod tests {
|
||||
};
|
||||
let without = base.estimate_cost();
|
||||
let with = KinoviSeedance2p0FastCostState { has_video_reference: true, ..base }.estimate_cost();
|
||||
// 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));
|
||||
// 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));
|
||||
}
|
||||
|
||||
// ── from_request() tests ──
|
||||
@@ -221,7 +228,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(58));
|
||||
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(44));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -229,14 +236,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(58));
|
||||
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(44));
|
||||
}
|
||||
|
||||
#[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(29));
|
||||
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(22));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -244,9 +251,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);
|
||||
// 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));
|
||||
// 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));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -266,11 +273,12 @@ mod tests {
|
||||
fn from_draft_720p_default() {
|
||||
let draft = make_draft(5, 1, None, false);
|
||||
let cost = KinoviSeedance2p0FastCostState::from_draft(&draft);
|
||||
assert!(cost.resolution.is_none());
|
||||
// Unset resolution is pinned to explicit 720p at build time.
|
||||
assert!(matches!(cost.resolution, Some(KinoviOutputResolution::SevenTwentyP)));
|
||||
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(58));
|
||||
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(44));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -278,7 +286,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(29));
|
||||
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(22));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -286,9 +294,9 @@ mod tests {
|
||||
let draft = make_draft(5, 1, None, true);
|
||||
let cost = KinoviSeedance2p0FastCostState::from_draft(&draft);
|
||||
assert!(cost.has_video_reference);
|
||||
// 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));
|
||||
// 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));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -304,7 +312,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(346));
|
||||
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(260));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -342,12 +350,14 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn credits_720p() {
|
||||
assert_eq!(credits(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::One), 140);
|
||||
// Enterprise 21 credits/s × 5s = 105.
|
||||
assert_eq!(credits(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::One), 105);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn credits_480p() {
|
||||
assert_eq!(credits(KinoviOutputResolution::FourEightyP, 5, KinoviBatchCount::One), 70);
|
||||
// Enterprise 10.5 credits/s × 5s = 52.5, rounded to 53.
|
||||
assert_eq!(credits(KinoviOutputResolution::FourEightyP, 5, KinoviBatchCount::One), 53);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+6
-3
@@ -116,7 +116,10 @@ fn plan_output_resolution(
|
||||
strategy: RequestMismatchMitigationStrategy,
|
||||
) -> Result<Option<KinoviOutputResolution>, ArtcraftRouterError> {
|
||||
match resolution {
|
||||
None => Ok(None),
|
||||
// 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)),
|
||||
|
||||
// Direct mappings
|
||||
Some(RouterResolution::FourEightyP) => Ok(Some(KinoviOutputResolution::FourEightyP)),
|
||||
@@ -429,10 +432,10 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolution_none() {
|
||||
fn resolution_none_defaults_to_720p() {
|
||||
let builder = GenerateVideoRequestBuilder { resolution: None, ..mini_builder() };
|
||||
let draft = unwrap_draft(build_kinovi_seedance_2p0_mini(builder));
|
||||
assert!(draft.resolution.is_none());
|
||||
assert!(matches!(draft.resolution, Some(KinoviOutputResolution::SevenTwentyP)));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+40
-32
@@ -2,6 +2,7 @@ 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;
|
||||
@@ -66,8 +67,10 @@ impl KinoviSeedance2p0MiniCostState {
|
||||
bitrate: None,
|
||||
};
|
||||
|
||||
let costs = pricing_request.calculate_costs();
|
||||
// Mini credits can be fractional (e.g. 480p odd durations land on 37.5).
|
||||
// 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).
|
||||
// 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;
|
||||
@@ -108,18 +111,20 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn without_video_reference() {
|
||||
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);
|
||||
// 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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_video_reference() {
|
||||
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);
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -128,18 +133,20 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn without_video_reference() {
|
||||
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);
|
||||
// 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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_video_reference() {
|
||||
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);
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,17 +157,18 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn credits_480p() {
|
||||
// 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);
|
||||
// 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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn credits_720p() {
|
||||
assert_eq!(credits(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::One, false), 100);
|
||||
assert_eq!(credits(KinoviOutputResolution::SevenTwentyP, 15, KinoviBatchCount::One, false), 300);
|
||||
// Enterprise 8 credits/s.
|
||||
assert_eq!(credits(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::One, false), 40);
|
||||
assert_eq!(credits(KinoviOutputResolution::SevenTwentyP, 15, KinoviBatchCount::One, false), 120);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -210,7 +218,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(42));
|
||||
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(17));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -218,7 +226,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(20));
|
||||
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(8));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -226,7 +234,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(42));
|
||||
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(17));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -240,7 +248,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(16));
|
||||
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(7));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -248,16 +256,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(50));
|
||||
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(20));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_draft_batch_8() {
|
||||
// Mini supports up to batch 8: 720p 5s × 8 = 800 credits → 80000/243 → 330¢.
|
||||
// Mini supports up to batch 8: 720p 5s × 8 = 320 credits → 32000/243.16 → 132¢.
|
||||
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(330));
|
||||
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(132));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+34
-14
@@ -144,31 +144,38 @@ fn nearest_aspect_ratio(aspect_ratio: RouterAspectRatio) -> KinoviAspectRatio {
|
||||
}
|
||||
}
|
||||
|
||||
// Seedance 2.5 supports output resolutions: 480p and 720p only.
|
||||
// 1080p (and higher) is NOT supported — downgrade to 720p or error based on strategy.
|
||||
// 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.
|
||||
fn plan_output_resolution(
|
||||
resolution: Option<RouterResolution>,
|
||||
strategy: RequestMismatchMitigationStrategy,
|
||||
) -> Result<Option<KinoviOutputResolution>, ArtcraftRouterError> {
|
||||
match resolution {
|
||||
None => Ok(None),
|
||||
// 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)),
|
||||
|
||||
// Direct mappings
|
||||
Some(RouterResolution::FourEightyP) => Ok(Some(KinoviOutputResolution::FourEightyP)),
|
||||
Some(RouterResolution::SevenTwentyP) => Ok(Some(KinoviOutputResolution::SevenTwentyP)),
|
||||
Some(RouterResolution::TenEightyP) => Ok(Some(KinoviOutputResolution::TenEightyP)),
|
||||
|
||||
// 1080p is not supported — handle via strategy
|
||||
Some(RouterResolution::TenEightyP) => match strategy {
|
||||
// 4K is not supported — handle via strategy
|
||||
Some(RouterResolution::FourK) => match strategy {
|
||||
RequestMismatchMitigationStrategy::ErrorOut => {
|
||||
Err(ArtcraftRouterError::Client(ClientError::ModelDoesNotSupportOption {
|
||||
field: "resolution",
|
||||
value: format!("{:?}", RouterResolution::TenEightyP),
|
||||
value: format!("{:?}", RouterResolution::FourK),
|
||||
}))
|
||||
}
|
||||
RequestMismatchMitigationStrategy::PayMoreUpgrade
|
||||
| RequestMismatchMitigationStrategy::PayLessDowngrade => {
|
||||
// 1080p not available — downgrade to 720p (highest supported)
|
||||
Ok(Some(KinoviOutputResolution::SevenTwentyP))
|
||||
// 4K not available — downgrade to 1080p (highest supported)
|
||||
Ok(Some(KinoviOutputResolution::TenEightyP))
|
||||
}
|
||||
},
|
||||
|
||||
@@ -184,7 +191,7 @@ fn plan_output_resolution(
|
||||
| RequestMismatchMitigationStrategy::PayLessDowngrade => {
|
||||
Ok(Some(match unsupported {
|
||||
RouterResolution::HalfK => KinoviOutputResolution::FourEightyP,
|
||||
_ => KinoviOutputResolution::SevenTwentyP,
|
||||
_ => KinoviOutputResolution::TenEightyP,
|
||||
}))
|
||||
}
|
||||
},
|
||||
@@ -400,28 +407,41 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolution_480p_and_720p() {
|
||||
fn resolution_480p_720p_and_1080p() {
|
||||
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_downgrades_to_720p() {
|
||||
fn resolution_1080p_error_out_strategy_still_maps_directly() {
|
||||
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::SevenTwentyP)));
|
||||
assert!(matches!(unwrap_draft(build_kinovi_seedance_2p5(builder)).resolution, Some(KinoviOutputResolution::TenEightyP)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolution_1080p_error_out() {
|
||||
fn resolution_4k_error_out() {
|
||||
let builder = GenerateVideoRequestBuilder {
|
||||
resolution: Some(RouterResolution::TenEightyP),
|
||||
resolution: Some(RouterResolution::FourK),
|
||||
request_mismatch_mitigation_strategy: RequestMismatchMitigationStrategy::ErrorOut,
|
||||
..base_builder()
|
||||
};
|
||||
|
||||
+23
-6
@@ -2,6 +2,7 @@ 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;
|
||||
@@ -92,9 +93,13 @@ impl KinoviSeedance2p5CostState {
|
||||
use_face_blur_hack: None,
|
||||
};
|
||||
|
||||
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.
|
||||
// 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 cost_in_credits = costs.kinovi_credits.round() as u64;
|
||||
let cost_in_usd_cents = costs.usd_cents_rounded_up;
|
||||
|
||||
@@ -116,7 +121,8 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
// ── Credits without video references (26/sec at 480p, 59/sec at 720p) ──
|
||||
// ── Credits without video references (26/sec at 480p, 59/sec at 720p,
|
||||
// 103.25/sec at 1080p enterprise) ──
|
||||
|
||||
mod credits_without_video_references {
|
||||
use super::*;
|
||||
@@ -134,6 +140,15 @@ 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));
|
||||
@@ -146,7 +161,7 @@ mod tests {
|
||||
}
|
||||
|
||||
// ── Credits with video references (16/sec at 480p, 35/sec at 720p,
|
||||
// over output duration + input seconds) ──
|
||||
// 61.69/sec at 1080p enterprise, over output duration + input seconds) ──
|
||||
|
||||
mod credits_with_video_references {
|
||||
use super::*;
|
||||
@@ -155,6 +170,8 @@ 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]
|
||||
@@ -185,7 +202,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn usd_cents_are_rounded_up() {
|
||||
// 130 credits → 13000/243 = 53.4979 → 54¢.
|
||||
// 130 credits → 13000/243.16 = 53.4627 → 54¢.
|
||||
let estimate = cost_state(Some(KinoviOutputResolution::FourEightyP), 5, false, None).estimate_cost();
|
||||
assert_eq!(estimate.cost_in_usd_cents, Some(54));
|
||||
}
|
||||
|
||||
+6
-3
@@ -134,7 +134,10 @@ fn plan_output_resolution(
|
||||
strategy: RequestMismatchMitigationStrategy,
|
||||
) -> Result<Option<KinoviOutputResolution>, ArtcraftRouterError> {
|
||||
match resolution {
|
||||
None => Ok(None),
|
||||
// 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)),
|
||||
|
||||
// Direct mappings
|
||||
Some(RouterResolution::FourEightyP) => Ok(Some(KinoviOutputResolution::FourEightyP)),
|
||||
@@ -439,10 +442,10 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolution_none() {
|
||||
fn resolution_none_defaults_to_720p() {
|
||||
let builder = GenerateVideoRequestBuilder { resolution: None, ..preview_builder() };
|
||||
let draft = unwrap_draft(build_kinovi_seedance_2p5_preview(builder));
|
||||
assert!(draft.resolution.is_none());
|
||||
assert!(matches!(draft.resolution, Some(KinoviOutputResolution::SevenTwentyP)));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+25
-22
@@ -1,3 +1,4 @@
|
||||
use kinovi_web_client::pricing::kinovi_cost_calculator_trait::KinoviCostCalculatorTrait;
|
||||
use kinovi_web_client::generate::video::generate_seedance_2p5_preview::{
|
||||
GenerateSeedance2p5PreviewRequest, KinoviSeedance2p5PreviewOutputResolution,
|
||||
};
|
||||
@@ -43,8 +44,10 @@ impl KinoviSeedance2p5PreviewCostState {
|
||||
use_face_blur_hack: None,
|
||||
};
|
||||
|
||||
let costs = pricing_request.calculate_costs();
|
||||
// 2.5 Preview bills fractional credits (46.81/sec at 480p). The router's
|
||||
// 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
|
||||
// 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;
|
||||
@@ -75,24 +78,24 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn credits_480p() {
|
||||
// 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);
|
||||
// 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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn credits_720p() {
|
||||
// 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);
|
||||
// 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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -108,16 +111,16 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn cents_480p() {
|
||||
// 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);
|
||||
// 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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cents_720p() {
|
||||
// 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);
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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,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`
|
||||
@@ -0,0 +1 @@
|
||||
AGENTS.md
|
||||
@@ -38,4 +38,4 @@ test_utils.workspace = true
|
||||
test_data.workspace = true
|
||||
|
||||
# External Dev
|
||||
# (None yet)
|
||||
tokio = { workspace = true, features = ["rt", "macros", "net", "io-util"] }
|
||||
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
/// 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");
|
||||
}
|
||||
}
|
||||
+299
@@ -0,0 +1,299 @@
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
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));
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
/// Number of images to generate per request.
|
||||
///
|
||||
/// Fal accepts 1 to 10; we expose the same 1 to 4 range as the other image bindings, which
|
||||
/// is what the ArtCraft batch UI offers. Add variants here if a larger batch is ever needed.
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum GptImage2p5NumImages {
|
||||
One,
|
||||
Two,
|
||||
Three,
|
||||
Four,
|
||||
}
|
||||
|
||||
impl GptImage2p5NumImages {
|
||||
pub fn to_u8(self) -> u8 {
|
||||
match self {
|
||||
GptImage2p5NumImages::One => 1,
|
||||
GptImage2p5NumImages::Two => 2,
|
||||
GptImage2p5NumImages::Three => 3,
|
||||
GptImage2p5NumImages::Four => 4,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_u64(self) -> u64 {
|
||||
self.to_u8() as u64
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn counts() {
|
||||
assert_eq!(GptImage2p5NumImages::One.to_u8(), 1);
|
||||
assert_eq!(GptImage2p5NumImages::Two.to_u8(), 2);
|
||||
assert_eq!(GptImage2p5NumImages::Three.to_u8(), 3);
|
||||
assert_eq!(GptImage2p5NumImages::Four.to_u8(), 4);
|
||||
assert_eq!(GptImage2p5NumImages::Four.to_u64(), 4);
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
/// Output file format. Fal's default is `Png`.
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum GptImage2p5OutputFormat {
|
||||
Jpeg,
|
||||
Png,
|
||||
Webp,
|
||||
}
|
||||
|
||||
impl GptImage2p5OutputFormat {
|
||||
pub fn to_str(self) -> &'static str {
|
||||
match self {
|
||||
GptImage2p5OutputFormat::Jpeg => "jpeg",
|
||||
GptImage2p5OutputFormat::Png => "png",
|
||||
GptImage2p5OutputFormat::Webp => "webp",
|
||||
}
|
||||
}
|
||||
|
||||
/// Fal only honours `output_compression` for lossy formats.
|
||||
pub fn supports_compression(self) -> bool {
|
||||
match self {
|
||||
GptImage2p5OutputFormat::Jpeg | GptImage2p5OutputFormat::Webp => true,
|
||||
GptImage2p5OutputFormat::Png => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn wire_strings_match_fal_schema() {
|
||||
assert_eq!(GptImage2p5OutputFormat::Jpeg.to_str(), "jpeg");
|
||||
assert_eq!(GptImage2p5OutputFormat::Png.to_str(), "png");
|
||||
assert_eq!(GptImage2p5OutputFormat::Webp.to_str(), "webp");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_lossy_formats_support_compression() {
|
||||
assert!(GptImage2p5OutputFormat::Jpeg.supports_compression());
|
||||
assert!(GptImage2p5OutputFormat::Webp.supports_compression());
|
||||
assert!(!GptImage2p5OutputFormat::Png.supports_compression());
|
||||
}
|
||||
}
|
||||
+275
@@ -0,0 +1,275 @@
|
||||
//! Cost model for GPT Image 2.5 (Flare and Sunburst share it).
|
||||
//!
|
||||
//! Fal bills by token: output image tokens at $30.00 / 1M, input image tokens at $8.00 / 1M,
|
||||
//! text tokens at $5.00 / 1M input, rounded up to $0.0001. Rather than count tokens, we fit
|
||||
//! the canonical per-image price table Fal publishes:
|
||||
//!
|
||||
//! | Size | low | medium | high | xhigh | max |
|
||||
//! |-----------|----------|----------|----------|----------|----------|
|
||||
//! | 1024x768 | $0.00402 | $0.00903 | $0.03612 | $0.06420 | $0.14445 |
|
||||
//! | 1024x1024 | $0.00588 | $0.01317 | $0.05268 | $0.09366 | $0.21072 |
|
||||
//! | 1024x1536 | $0.00474 | $0.01029 | $0.04116 | $0.07377 | $0.16464 |
|
||||
//! | 1920x1080 | $0.00441 | $0.01029 | $0.03960 | $0.07041 | $0.15840 |
|
||||
//! | 2560x1440 | $0.00615 | $0.01434 | $0.05529 | $0.09828 | $0.22110 |
|
||||
//! | 3840x2160 | $0.01113 | $0.02595 | $0.10008 | $0.17790 | $0.40026 |
|
||||
//!
|
||||
//! Dividing by the output token price shows the structure: at `low` quality an image costs a
|
||||
//! per-aspect-ratio base (~158 tokens for 1:1, ~106 for 4:3, ~101 for 3:2, ~72 for 16:9) plus
|
||||
//! 36 tokens per megapixel, and each higher quality tier multiplies the token count by a
|
||||
//! constant (medium 7/3, high 9, xhigh 16, max 36). The three 16:9 rows pin the slope and the
|
||||
//! multipliers exactly; the other rows pin their bases.
|
||||
//!
|
||||
//! The estimate never undershoots the published table and is within 8% above it at every
|
||||
//! canonical size (see tests). Prompt text tokens are not modelled: a few hundred tokens at
|
||||
//! $5 / 1M is well under $0.002.
|
||||
|
||||
use crate::requests::api::image::common::gpt_image_2p5::gpt_image_2p5_quality::GptImage2p5Quality;
|
||||
use crate::requests::traits::fal_request_cost_calculator_trait::UsdCents;
|
||||
|
||||
/// Cost in hundredths of a US cent ($0.0001), the granularity Fal rounds GPT Image 2.5 to.
|
||||
pub type UsdHundredthsOfCent = u64;
|
||||
|
||||
/// $30.00 per 1M output image tokens.
|
||||
const OUTPUT_IMAGE_TOKEN_USD: f64 = 30.0 / 1_000_000.0;
|
||||
|
||||
/// $8.00 per 1M input image tokens.
|
||||
const INPUT_IMAGE_TOKEN_USD: f64 = 8.0 / 1_000_000.0;
|
||||
|
||||
/// Output tokens per megapixel at `low` quality, fitted from the 16:9 rows of the table.
|
||||
const LOW_QUALITY_OUTPUT_TOKENS_PER_MEGAPIXEL: f64 = 36.0;
|
||||
|
||||
/// Fal does not publish input image token counts. This is a conservative allowance per
|
||||
/// reference image on edit requests, comparable to a high-detail 1024x1024 vision input.
|
||||
const ESTIMATED_INPUT_TOKENS_PER_REFERENCE_IMAGE: f64 = 1_000.0;
|
||||
|
||||
/// Estimated cost of rendering one output image of the given size at the given quality.
|
||||
pub fn estimate_output_image_cost(quality: GptImage2p5Quality, width: u32, height: u32) -> UsdHundredthsOfCent {
|
||||
let megapixels = width as f64 * height as f64 / 1_000_000.0;
|
||||
let low_quality_tokens = low_quality_base_tokens(width, height)
|
||||
+ LOW_QUALITY_OUTPUT_TOKENS_PER_MEGAPIXEL * megapixels;
|
||||
let tokens = low_quality_tokens * quality_token_multiplier(quality);
|
||||
usd_to_hundredths_of_cent(tokens * OUTPUT_IMAGE_TOKEN_USD)
|
||||
}
|
||||
|
||||
/// Estimated cost of the reference (input) images attached to an edit request.
|
||||
pub fn estimate_reference_images_cost(num_reference_images: usize) -> UsdHundredthsOfCent {
|
||||
let tokens = num_reference_images as f64 * ESTIMATED_INPUT_TOKENS_PER_REFERENCE_IMAGE;
|
||||
usd_to_hundredths_of_cent(tokens * INPUT_IMAGE_TOKEN_USD)
|
||||
}
|
||||
|
||||
/// Round up to whole cents.
|
||||
pub fn hundredths_of_cent_to_cents(hundredths: UsdHundredthsOfCent) -> UsdCents {
|
||||
hundredths.div_ceil(100)
|
||||
}
|
||||
|
||||
/// Token count multiplier for each quality tier relative to `low`.
|
||||
fn quality_token_multiplier(quality: GptImage2p5Quality) -> f64 {
|
||||
match quality {
|
||||
GptImage2p5Quality::Low => 1.0,
|
||||
GptImage2p5Quality::Medium => 7.0 / 3.0,
|
||||
// `auto` lets the model choose; `high` is the documented default so we price it there.
|
||||
GptImage2p5Quality::High | GptImage2p5Quality::Auto => 9.0,
|
||||
GptImage2p5Quality::XHigh => 16.0,
|
||||
GptImage2p5Quality::Max => 36.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-image base token count at `low` quality, which depends on the aspect ratio family.
|
||||
/// Fitted from the canonical table: 1:1 => 158, 4:3 => 106, 3:2 => 101, 16:9 => 72.
|
||||
fn low_quality_base_tokens(width: u32, height: u32) -> f64 {
|
||||
let long_edge = width.max(height) as f64;
|
||||
let short_edge = width.min(height).max(1) as f64;
|
||||
let ratio = long_edge / short_edge;
|
||||
if ratio < 1.25 {
|
||||
158.0 // ~1:1
|
||||
} else if ratio < 1.42 {
|
||||
106.0 // ~4:3 (1.333)
|
||||
} else if ratio < 1.60 {
|
||||
101.0 // ~3:2 (1.5)
|
||||
} else {
|
||||
72.0 // ~16:9 (1.778) and wider
|
||||
}
|
||||
}
|
||||
|
||||
fn usd_to_hundredths_of_cent(usd: f64) -> UsdHundredthsOfCent {
|
||||
// Small epsilon so values that are exactly on a boundary in decimal don't round up
|
||||
// because of binary float noise.
|
||||
(usd * 10_000.0 - 1e-6).ceil().max(0.0) as u64
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use GptImage2p5Quality::*;
|
||||
|
||||
const ALL_QUALITIES: [GptImage2p5Quality; 5] = [Low, Medium, High, XHigh, Max];
|
||||
|
||||
/// Fal's published canonical table, in hundredths of a cent: (width, height, [low, medium, high, xhigh, max]).
|
||||
const FAL_PUBLISHED_TABLE: &[(u32, u32, [u64; 5])] = &[
|
||||
(1024, 768, [ 40, 90, 361, 642, 1444]),
|
||||
(1024, 1024, [ 59, 132, 527, 937, 2107]),
|
||||
(1024, 1536, [ 47, 103, 412, 738, 1646]),
|
||||
(1920, 1080, [ 44, 103, 396, 704, 1584]),
|
||||
(2560, 1440, [ 62, 143, 553, 983, 2211]),
|
||||
(3840, 2160, [111, 260, 1001, 1779, 4003]),
|
||||
];
|
||||
|
||||
/// What our model produces at the canonical sizes, in hundredths of a cent. Pinned so a
|
||||
/// change to the fit is a deliberate, visible diff.
|
||||
const MODEL_TABLE: &[(u32, u32, [u64; 5])] = &[
|
||||
(1024, 768, [ 41, 95, 363, 645, 1451]),
|
||||
(1024, 1024, [ 59, 138, 529, 940, 2115]),
|
||||
(1024, 1536, [ 48, 111, 426, 757, 1703]),
|
||||
(1920, 1080, [ 44, 103, 396, 704, 1584]),
|
||||
(2560, 1440, [ 62, 144, 553, 983, 2211]),
|
||||
(3840, 2160, [112, 260, 1001, 1779, 4003]),
|
||||
];
|
||||
|
||||
mod canonical_table_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn model_matches_pinned_values() {
|
||||
for &(w, h, expected) in MODEL_TABLE {
|
||||
for (quality, expected) in ALL_QUALITIES.iter().zip(expected) {
|
||||
let actual = estimate_output_image_cost(*quality, w, h);
|
||||
assert_eq!(actual, expected, "{w}x{h} {quality:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_never_undershoots_fal_published_prices() {
|
||||
for &(w, h, published) in FAL_PUBLISHED_TABLE {
|
||||
for (quality, published) in ALL_QUALITIES.iter().zip(published) {
|
||||
let actual = estimate_output_image_cost(*quality, w, h);
|
||||
assert!(actual >= published, "{w}x{h} {quality:?}: model {actual} < published {published}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_is_within_eight_percent_of_fal_published_prices() {
|
||||
for &(w, h, published) in FAL_PUBLISHED_TABLE {
|
||||
for (quality, published) in ALL_QUALITIES.iter().zip(published) {
|
||||
let actual = estimate_output_image_cost(*quality, w, h);
|
||||
let ceiling = published * 108 / 100 + 1;
|
||||
assert!(actual <= ceiling, "{w}x{h} {quality:?}: model {actual} > {ceiling} (published {published})");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sixteen_by_nine_rows_are_exact() {
|
||||
// The 16:9 rows pin the slope and the quality multipliers, so they should reproduce
|
||||
// exactly (the 1080p low row is the only one with a fractional base).
|
||||
assert_eq!(estimate_output_image_cost(High, 1920, 1080), 396);
|
||||
assert_eq!(estimate_output_image_cost(High, 2560, 1440), 553);
|
||||
assert_eq!(estimate_output_image_cost(High, 3840, 2160), 1001);
|
||||
assert_eq!(estimate_output_image_cost(Max, 3840, 2160), 4003);
|
||||
}
|
||||
}
|
||||
|
||||
mod quality_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn auto_is_priced_as_high() {
|
||||
for &(w, h, _) in FAL_PUBLISHED_TABLE {
|
||||
assert_eq!(
|
||||
estimate_output_image_cost(Auto, w, h),
|
||||
estimate_output_image_cost(High, w, h),
|
||||
"{w}x{h}",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn higher_quality_costs_strictly_more() {
|
||||
for &(w, h, _) in FAL_PUBLISHED_TABLE {
|
||||
for pair in ALL_QUALITIES.windows(2) {
|
||||
let lower = estimate_output_image_cost(pair[0], w, h);
|
||||
let higher = estimate_output_image_cost(pair[1], w, h);
|
||||
assert!(lower < higher, "{w}x{h}: {:?} ({lower}) should be < {:?} ({higher})", pair[0], pair[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mod dimension_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn more_pixels_at_same_aspect_costs_more() {
|
||||
let sizes_16x9 = [(1088, 608), (1920, 1080), (2048, 1152), (2560, 1440), (3072, 1728), (3840, 2160)];
|
||||
for pair in sizes_16x9.windows(2) {
|
||||
let smaller = estimate_output_image_cost(High, pair[0].0, pair[0].1);
|
||||
let larger = estimate_output_image_cost(High, pair[1].0, pair[1].1);
|
||||
assert!(smaller < larger, "{:?} ({smaller}) should be < {:?} ({larger})", pair[0], pair[1]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn orientation_does_not_change_cost() {
|
||||
assert_eq!(estimate_output_image_cost(High, 1024, 768), estimate_output_image_cost(High, 768, 1024));
|
||||
assert_eq!(estimate_output_image_cost(High, 1920, 1080), estimate_output_image_cost(High, 1080, 1920));
|
||||
assert_eq!(estimate_output_image_cost(High, 1024, 1536), estimate_output_image_cost(High, 1536, 1024));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aspect_family_bases() {
|
||||
assert_eq!(low_quality_base_tokens(1024, 1024), 158.0);
|
||||
assert_eq!(low_quality_base_tokens(2048, 2048), 158.0);
|
||||
assert_eq!(low_quality_base_tokens(1024, 768), 106.0);
|
||||
assert_eq!(low_quality_base_tokens(768, 1024), 106.0);
|
||||
assert_eq!(low_quality_base_tokens(1024, 1536), 101.0);
|
||||
assert_eq!(low_quality_base_tokens(1920, 1080), 72.0);
|
||||
assert_eq!(low_quality_base_tokens(1088, 608), 72.0);
|
||||
assert_eq!(low_quality_base_tokens(3000, 1000), 72.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_k_square_high_quality() {
|
||||
// 158 + 36 * 4.194304 = 308.99 tokens * 9 * $0.00003 = $0.08343 => 835 hundredths
|
||||
assert_eq!(estimate_output_image_cost(High, 2048, 2048), 835);
|
||||
}
|
||||
}
|
||||
|
||||
mod reference_image_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn reference_images_cost_eighty_hundredths_each() {
|
||||
// 1,000 tokens * $8 / 1M = $0.008 per image
|
||||
assert_eq!(estimate_reference_images_cost(0), 0);
|
||||
assert_eq!(estimate_reference_images_cost(1), 80);
|
||||
assert_eq!(estimate_reference_images_cost(3), 240);
|
||||
assert_eq!(estimate_reference_images_cost(16), 1280);
|
||||
}
|
||||
}
|
||||
|
||||
mod rounding_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn cents_round_up() {
|
||||
assert_eq!(hundredths_of_cent_to_cents(0), 0);
|
||||
assert_eq!(hundredths_of_cent_to_cents(1), 1);
|
||||
assert_eq!(hundredths_of_cent_to_cents(99), 1);
|
||||
assert_eq!(hundredths_of_cent_to_cents(100), 1);
|
||||
assert_eq!(hundredths_of_cent_to_cents(101), 2);
|
||||
assert_eq!(hundredths_of_cent_to_cents(1001), 11);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usd_conversion_rounds_up_without_float_noise() {
|
||||
assert_eq!(usd_to_hundredths_of_cent(0.0), 0);
|
||||
assert_eq!(usd_to_hundredths_of_cent(0.0001), 1);
|
||||
assert_eq!(usd_to_hundredths_of_cent(0.00588), 59);
|
||||
assert_eq!(usd_to_hundredths_of_cent(0.005881), 59);
|
||||
assert_eq!(usd_to_hundredths_of_cent(0.00589), 59);
|
||||
assert_eq!(usd_to_hundredths_of_cent(0.005901), 60);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
/// Quality tier. Higher tiers spend more output image tokens (more detail, more latency).
|
||||
/// Fal's default is `High`.
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum GptImage2p5Quality {
|
||||
/// Let the model choose. Priced as `High` since that is the documented default.
|
||||
Auto,
|
||||
Low,
|
||||
Medium,
|
||||
High,
|
||||
XHigh,
|
||||
Max,
|
||||
}
|
||||
|
||||
impl GptImage2p5Quality {
|
||||
pub fn to_str(self) -> &'static str {
|
||||
match self {
|
||||
GptImage2p5Quality::Auto => "auto",
|
||||
GptImage2p5Quality::Low => "low",
|
||||
GptImage2p5Quality::Medium => "medium",
|
||||
GptImage2p5Quality::High => "high",
|
||||
GptImage2p5Quality::XHigh => "xhigh",
|
||||
GptImage2p5Quality::Max => "max",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn wire_strings_match_fal_schema() {
|
||||
assert_eq!(GptImage2p5Quality::Auto.to_str(), "auto");
|
||||
assert_eq!(GptImage2p5Quality::Low.to_str(), "low");
|
||||
assert_eq!(GptImage2p5Quality::Medium.to_str(), "medium");
|
||||
assert_eq!(GptImage2p5Quality::High.to_str(), "high");
|
||||
assert_eq!(GptImage2p5Quality::XHigh.to_str(), "xhigh");
|
||||
assert_eq!(GptImage2p5Quality::Max.to_str(), "max");
|
||||
}
|
||||
}
|
||||
+318
@@ -0,0 +1,318 @@
|
||||
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, 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_text_to_image_input::GptImage2p5TextToImageInput;
|
||||
use crate::requests::traits::fal_request_cost_calculator_trait::UsdCents;
|
||||
|
||||
/// Parameters for a GPT Image 2.5 text-to-image request. Identical for Flare and Sunburst;
|
||||
/// the per-endpoint request types wrap this.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GptImage2p5TextToImageParams {
|
||||
/// Text prompt describing the image to generate. 1 to 32,000 characters.
|
||||
pub prompt: String,
|
||||
|
||||
/// Number of images to generate.
|
||||
pub num_images: GptImage2p5NumImages,
|
||||
|
||||
/// Output image size preset. `None` lets Fal default to `landscape_4_3`.
|
||||
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 GptImage2p5TextToImageParams {
|
||||
/// Fal's default when `image_size` is omitted.
|
||||
pub const DEFAULT_IMAGE_SIZE: GptImage2p5ImageSize = GptImage2p5ImageSize::Landscape4x3;
|
||||
|
||||
/// Fal's default when `quality` is omitted.
|
||||
pub const DEFAULT_QUALITY: GptImage2p5Quality = GptImage2p5Quality::High;
|
||||
|
||||
pub fn to_raw_input(&self) -> GptImage2p5TextToImageInput {
|
||||
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
|
||||
};
|
||||
|
||||
GptImage2p5TextToImageInput {
|
||||
prompt: self.prompt.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.
|
||||
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);
|
||||
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};
|
||||
|
||||
mod to_raw_input_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn minimal_request_only_sends_required_and_defaulted_fields() {
|
||||
let raw = make_params(One, None, None, None).to_raw_input();
|
||||
assert_eq!(raw.prompt, "test");
|
||||
assert!(raw.image_size.is_none());
|
||||
assert!(raw.background.is_none());
|
||||
assert!(raw.quality.is_none());
|
||||
assert_eq!(raw.num_images, Some(1));
|
||||
assert_eq!(raw.output_format.as_deref(), Some("png"));
|
||||
assert!(raw.output_compression.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn minimal_request_serializes_to_expected_json() {
|
||||
let raw = make_params(One, None, None, None).to_raw_input();
|
||||
let json = serde_json::to_value(&raw).unwrap();
|
||||
assert_eq!(json, serde_json::json!({
|
||||
"prompt": "test",
|
||||
"num_images": 1,
|
||||
"output_format": "png",
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_request_serializes_to_expected_json() {
|
||||
let params = GptImage2p5TextToImageParams {
|
||||
prompt: "a corgi".to_string(),
|
||||
num_images: Three,
|
||||
image_size: Some(Landscape16x9),
|
||||
resolution: Some(TwoK),
|
||||
quality: Some(XHigh),
|
||||
background: Some(GptImage2p5Background::Transparent),
|
||||
output_format: Some(GptImage2p5OutputFormat::Webp),
|
||||
output_compression: Some(80),
|
||||
};
|
||||
let json = serde_json::to_value(params.to_raw_input()).unwrap();
|
||||
assert_eq!(json, serde_json::json!({
|
||||
"prompt": "a corgi",
|
||||
"image_size": { "width": 2048, "height": 1152 },
|
||||
"background": "transparent",
|
||||
"quality": "xhigh",
|
||||
"num_images": 3,
|
||||
"output_format": "webp",
|
||||
"output_compression": 80,
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preset_without_resolution() {
|
||||
let raw = make_params(One, None, Some(Square), None).to_raw_input();
|
||||
match raw.image_size.unwrap() {
|
||||
GptImage2p5ImageSizeParam::Preset(s) => assert_eq!(s, "square"),
|
||||
GptImage2p5ImageSizeParam::Custom(_) => panic!("expected preset"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_size_sends_auto_preset() {
|
||||
let raw = make_params(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() {
|
||||
// No preset means no aspect ratio to derive dimensions from; let Fal default.
|
||||
let raw = make_params(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(One, None, None, None);
|
||||
params.output_format = Some(GptImage2p5OutputFormat::Png);
|
||||
params.output_compression = Some(50);
|
||||
assert!(params.to_raw_input().output_compression.is_none());
|
||||
|
||||
params.output_format = None;
|
||||
assert!(params.to_raw_input().output_compression.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compression_kept_for_jpeg_and_clamped() {
|
||||
let mut params = make_params(One, None, None, None);
|
||||
params.output_format = Some(GptImage2p5OutputFormat::Jpeg);
|
||||
params.output_compression = Some(50);
|
||||
assert_eq!(params.to_raw_input().output_compression, Some(50));
|
||||
|
||||
params.output_compression = Some(200);
|
||||
assert_eq!(params.to_raw_input().output_compression, Some(100));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_qualities_serialize() {
|
||||
for quality in [GptImage2p5Quality::Auto, Low, Medium, High, XHigh, Max] {
|
||||
let raw = make_params(One, Some(quality), None, None).to_raw_input();
|
||||
assert_eq!(raw.quality.as_deref(), Some(quality.to_str()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mod cost_tests {
|
||||
use super::*;
|
||||
|
||||
// (size, resolution, [low, medium, high, xhigh, max]) — expected cents per image.
|
||||
// Pinned from the model in `gpt_image_2p5_pricing`; a change here must be deliberate.
|
||||
const GRID: &[(GptImage2p5ImageSize, Option<GptImage2Resolution>, [u64; 5])] = &[
|
||||
// 1:1
|
||||
(Square, None, [1, 2, 6, 10, 22]), // 1024x1024
|
||||
(Square, Some(OneK), [1, 2, 6, 10, 22]), // 1024x1024
|
||||
(Square, Some(TwoK), [1, 3, 9, 15, 34]), // 2048x2048
|
||||
(Square, Some(ThreeK), [2, 4, 13, 22, 50]), // 2880x2880
|
||||
(Square, Some(FourK), [2, 4, 13, 22, 50]), // 2880x2880 (pixel cap)
|
||||
(SquareHd, None, [1, 3, 9, 15, 34]), // 2048x2048
|
||||
(SquareHd, Some(OneK), [1, 2, 6, 10, 22]), // 1024x1024
|
||||
(SquareHd, Some(TwoK), [1, 3, 9, 15, 34]), // 2048x2048
|
||||
(SquareHd, Some(ThreeK), [2, 4, 13, 22, 50]), // 2880x2880
|
||||
(SquareHd, Some(FourK), [2, 4, 13, 22, 50]), // 2880x2880 (pixel cap)
|
||||
// 4:3
|
||||
(Landscape4x3, None, [1, 1, 4, 7, 15]), // 1024x768
|
||||
(Landscape4x3, Some(OneK), [1, 1, 4, 7, 15]), // 1024x768
|
||||
(Landscape4x3, Some(TwoK), [1, 2, 6, 11, 24]), // 2048x1536
|
||||
(Landscape4x3, Some(ThreeK), [2, 3, 10, 18, 39]), // 3072x2304
|
||||
(Landscape4x3, Some(FourK), [2, 3, 11, 20, 44]), // 3312x2480 (pixel cap)
|
||||
(Portrait4x3, None, [1, 1, 4, 7, 15]), // 768x1024
|
||||
(Portrait4x3, Some(OneK), [1, 1, 4, 7, 15]), // 768x1024
|
||||
(Portrait4x3, Some(TwoK), [1, 2, 6, 11, 24]), // 1536x2048
|
||||
(Portrait4x3, Some(ThreeK), [2, 3, 10, 18, 39]), // 2304x3072
|
||||
(Portrait4x3, Some(FourK), [2, 3, 11, 20, 44]), // 2480x3312 (pixel cap)
|
||||
// 16:9
|
||||
(Landscape16x9, None, [1, 2, 4, 8, 16]), // 1920x1080
|
||||
(Landscape16x9, Some(OneK), [1, 1, 3, 5, 11]), // 1088x608
|
||||
(Landscape16x9, Some(TwoK), [1, 2, 5, 8, 17]), // 2048x1152
|
||||
(Landscape16x9, Some(ThreeK), [1, 2, 8, 13, 29]), // 3072x1728
|
||||
(Landscape16x9, Some(FourK), [2, 3, 11, 18, 41]), // 3840x2160
|
||||
(Portrait16x9, None, [1, 2, 4, 8, 16]), // 1080x1920
|
||||
(Portrait16x9, Some(OneK), [1, 1, 3, 5, 11]), // 608x1088
|
||||
(Portrait16x9, Some(TwoK), [1, 2, 5, 8, 17]), // 1152x2048
|
||||
(Portrait16x9, Some(ThreeK), [1, 2, 8, 13, 29]), // 1728x3072
|
||||
(Portrait16x9, Some(FourK), [2, 3, 11, 18, 41]), // 2160x3840
|
||||
// Auto always prices at the conservative 3840x2160
|
||||
(Auto, None, [2, 3, 11, 18, 41]),
|
||||
(Auto, Some(OneK), [2, 3, 11, 18, 41]),
|
||||
(Auto, Some(FourK), [2, 3, 11, 18, 41]),
|
||||
];
|
||||
|
||||
const ALL_QUALITIES: [GptImage2p5Quality; 5] = [Low, Medium, High, XHigh, Max];
|
||||
|
||||
#[test]
|
||||
fn exhaustive_grid() {
|
||||
for &(size, resolution, expected) in GRID {
|
||||
for (quality, expected) in ALL_QUALITIES.iter().zip(expected) {
|
||||
let actual = make_params(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 {
|
||||
let per_image = make_params(One, Some(High), Some(size), resolution).estimate_cost_in_cents();
|
||||
for (num, n) in [(Two, 2), (Three, 3), (Four, 4)] {
|
||||
let actual = make_params(num, Some(High), Some(size), resolution).estimate_cost_in_cents();
|
||||
assert_eq!(actual, per_image * n, "{size:?} {resolution:?} x{n}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn higher_resolution_never_costs_less() {
|
||||
for size in [Square, SquareHd, Landscape4x3, Portrait4x3, Landscape16x9, Portrait16x9] {
|
||||
let tiers = [OneK, TwoK, ThreeK, FourK];
|
||||
for pair in tiers.windows(2) {
|
||||
let lower = make_params(One, Some(High), Some(size), Some(pair[0])).estimate_cost_in_cents();
|
||||
let higher = make_params(One, Some(High), Some(size), Some(pair[1])).estimate_cost_in_cents();
|
||||
assert!(lower <= higher, "{size:?} {:?} ({lower}) should be <= {:?} ({higher})", pair[0], pair[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn defaults_to_high_quality_landscape_4x3() {
|
||||
// 1024x768 high = 363 hundredths => 4 cents
|
||||
assert_eq!(make_params(One, None, None, None).estimate_cost_in_cents(), 4);
|
||||
assert_eq!(make_params(One, Some(High), Some(Landscape4x3), None).estimate_cost_in_cents(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolution_without_size_prices_at_default_aspect() {
|
||||
assert_eq!(
|
||||
make_params(One, Some(High), None, Some(TwoK)).estimate_cost_in_cents(),
|
||||
make_params(One, Some(High), Some(Landscape4x3), Some(TwoK)).estimate_cost_in_cents(),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_multiplies_per_image_cents() {
|
||||
let per_image = make_params(One, Some(High), Some(Square), None).estimate_cost_in_cents();
|
||||
assert_eq!(per_image, 6);
|
||||
assert_eq!(make_params(Two, Some(High), Some(Square), None).estimate_cost_in_cents(), 12);
|
||||
assert_eq!(make_params(Three, Some(High), Some(Square), None).estimate_cost_in_cents(), 18);
|
||||
assert_eq!(make_params(Four, Some(High), Some(Square), None).estimate_cost_in_cents(), 24);
|
||||
}
|
||||
}
|
||||
|
||||
fn make_params(
|
||||
num_images: GptImage2p5NumImages,
|
||||
quality: Option<GptImage2p5Quality>,
|
||||
image_size: Option<GptImage2p5ImageSize>,
|
||||
resolution: Option<GptImage2Resolution>,
|
||||
) -> GptImage2p5TextToImageParams {
|
||||
GptImage2p5TextToImageParams {
|
||||
prompt: "test".to_string(),
|
||||
num_images,
|
||||
image_size,
|
||||
resolution,
|
||||
quality,
|
||||
background: None,
|
||||
output_format: None,
|
||||
output_compression: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
//! Types shared by the four GPT Image 2.5 endpoints (Flare / Sunburst, text-to-image / edit).
|
||||
//!
|
||||
//! All four endpoints accept the same parameters and are priced from the same token table;
|
||||
//! only the Fal endpoint path differs. The per-endpoint request types under `text/` and
|
||||
//! `edit/` are thin wrappers around the params structs defined here.
|
||||
//!
|
||||
//! GPT Image 2.5 shares GPT Image 2's dimension constraints (multiples of 16, max edge 3840,
|
||||
//! aspect <= 3:1, 655,360 <= pixels <= 8,294,400), so the resolution tiers and custom size
|
||||
//! calculator in `gpt_image_2_resolution` are reused as-is.
|
||||
|
||||
pub mod gpt_image_2p5_text_to_image_params;
|
||||
pub mod gpt_image_2p5_edit_image_params;
|
||||
pub mod gpt_image_2p5_image_size;
|
||||
pub mod gpt_image_2p5_quality;
|
||||
pub mod gpt_image_2p5_background;
|
||||
pub mod gpt_image_2p5_output_format;
|
||||
pub mod gpt_image_2p5_num_images;
|
||||
pub mod gpt_image_2p5_pricing;
|
||||
pub mod raw;
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use crate::requests::api::image::common::gpt_image_2p5::raw::gpt_image_2p5_image_size_param::GptImage2p5ImageSizeParam;
|
||||
|
||||
/// Wire shape for `openai/gpt-image-2.5/{flare,sunburst}/edit`.
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct GptImage2p5EditImageInput {
|
||||
/// 1 to 32,000 characters.
|
||||
pub prompt: String,
|
||||
|
||||
/// Reference images. At most 16.
|
||||
pub image_urls: Vec<String>,
|
||||
|
||||
/// Mask indicating which part of the image to edit.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub mask_url: Option<String>,
|
||||
|
||||
/// square_hd, square, portrait_4_3, portrait_16_9, landscape_4_3, landscape_16_9, auto
|
||||
/// OR a custom { width, height } object.
|
||||
/// Default: "auto" (inferred from the input images)
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub image_size: Option<GptImage2p5ImageSizeParam>,
|
||||
|
||||
/// "auto", "transparent", "opaque"
|
||||
/// Default: "auto"
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub background: Option<String>,
|
||||
|
||||
/// "auto", "low", "medium", "high", "xhigh", "max"
|
||||
/// Default: "high"
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub quality: Option<String>,
|
||||
|
||||
/// 1 - 10
|
||||
/// Default: 1
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub num_images: Option<u8>,
|
||||
|
||||
/// "jpeg", "png", "webp"
|
||||
/// Default: "png"
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub output_format: Option<String>,
|
||||
|
||||
/// 0 - 100. Only honoured for "jpeg" and "webp".
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub output_compression: Option<u8>,
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Response shape shared by all four GPT Image 2.5 endpoints.
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct GptImage2p5ImageOutput {
|
||||
pub images: Vec<GptImage2p5ImageFile>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct GptImage2p5ImageFile {
|
||||
pub url: String,
|
||||
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub content_type: Option<String>,
|
||||
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub file_name: Option<String>,
|
||||
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub file_size: Option<u64>,
|
||||
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub width: Option<u32>,
|
||||
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub height: Option<u32>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn deserializes_fal_example_response() {
|
||||
let json = r#"{"images":[{"file_name":"EnWrO3XWjPE0nxBDpaQrj.png","width":1024,"height":1024,"content_type":"image/png","url":"https://v3b.fal.media/files/b/0a869129/EnWrO3XWjPE0nxBDpaQrj.png"}]}"#;
|
||||
let output: GptImage2p5ImageOutput = serde_json::from_str(json).unwrap();
|
||||
assert_eq!(output.images.len(), 1);
|
||||
assert_eq!(output.images[0].url, "https://v3b.fal.media/files/b/0a869129/EnWrO3XWjPE0nxBDpaQrj.png");
|
||||
assert_eq!(output.images[0].width, Some(1024));
|
||||
assert_eq!(output.images[0].content_type.as_deref(), Some("image/png"));
|
||||
assert_eq!(output.images[0].file_size, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserializes_url_only_file() {
|
||||
let json = r#"{"images":[{"url":"https://example.com/a.png"}]}"#;
|
||||
let output: GptImage2p5ImageOutput = serde_json::from_str(json).unwrap();
|
||||
assert_eq!(output.images[0].url, "https://example.com/a.png");
|
||||
assert_eq!(output.images[0].width, None);
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use crate::requests::api::image::common::gpt_image_2_resolution::CustomImageSize;
|
||||
|
||||
/// The `image_size` field is either a preset name (e.g. `"square"`, `"auto"`) or an explicit
|
||||
/// `{ width, height }` object.
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
#[serde(untagged)]
|
||||
pub enum GptImage2p5ImageSizeParam {
|
||||
Preset(String),
|
||||
Custom(CustomImageSize),
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use crate::requests::api::image::common::gpt_image_2p5::raw::gpt_image_2p5_image_size_param::GptImage2p5ImageSizeParam;
|
||||
|
||||
/// Wire shape for `openai/gpt-image-2.5/{flare,sunburst}/text-to-image`.
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct GptImage2p5TextToImageInput {
|
||||
/// 1 to 32,000 characters.
|
||||
pub prompt: String,
|
||||
|
||||
/// square_hd, square, portrait_4_3, portrait_16_9, landscape_4_3, landscape_16_9, auto
|
||||
/// OR a custom { width, height } object.
|
||||
/// Default: "landscape_4_3"
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub image_size: Option<GptImage2p5ImageSizeParam>,
|
||||
|
||||
/// "auto", "transparent", "opaque"
|
||||
/// Default: "auto"
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub background: Option<String>,
|
||||
|
||||
/// "auto", "low", "medium", "high", "xhigh", "max"
|
||||
/// Default: "high"
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub quality: Option<String>,
|
||||
|
||||
/// 1 - 10
|
||||
/// Default: 1
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub num_images: Option<u8>,
|
||||
|
||||
/// "jpeg", "png", "webp"
|
||||
/// Default: "png"
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub output_format: Option<String>,
|
||||
|
||||
/// 0 - 100. Only honoured for "jpeg" and "webp".
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub output_compression: Option<u8>,
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
//! Over-the-wire request and response shapes for the GPT Image 2.5 endpoints.
|
||||
|
||||
pub mod gpt_image_2p5_text_to_image_input;
|
||||
pub mod gpt_image_2p5_edit_image_input;
|
||||
pub mod gpt_image_2p5_image_output;
|
||||
pub mod gpt_image_2p5_image_size_param;
|
||||
@@ -1 +1,2 @@
|
||||
pub mod gpt_image_2_resolution;
|
||||
pub mod gpt_image_2p5;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user