mirror of
https://github.com/storytold/artcraft.git
synced 2026-11-04 13:28:06 -05:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
27c463e33d | ||
|
|
ed57c6de47 | ||
|
|
74207e3520 | ||
|
|
60be62cb71 |
@@ -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,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,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
|
||||
+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
|
||||
@@ -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;
|
||||
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
use crate::error::fal_error_plus::FalErrorPlus;
|
||||
use crate::requests::api::image::common::gpt_image_2p5::gpt_image_2p5_edit_image_params::GptImage2p5EditImageParams;
|
||||
use crate::requests::api::image::common::gpt_image_2p5::raw::gpt_image_2p5_edit_image_input::GptImage2p5EditImageInput;
|
||||
use crate::requests::api::image::common::gpt_image_2p5::raw::gpt_image_2p5_image_output::GptImage2p5ImageOutput;
|
||||
use crate::requests::traits::fal_endpoint_trait::FalEndpoint;
|
||||
|
||||
/// GPT Image 2.5 Flare image edit.
|
||||
///
|
||||
/// Flare and Sunburst take the same parameters (see `GptImage2p5EditImageParams`);
|
||||
/// this type only selects the endpoint.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GptImage2p5FlareEditImageRequest {
|
||||
pub params: GptImage2p5EditImageParams,
|
||||
}
|
||||
|
||||
impl FalEndpoint for GptImage2p5FlareEditImageRequest {
|
||||
const ENDPOINT: &str = "openai/gpt-image-2.5/flare/edit";
|
||||
|
||||
type RawRequest = GptImage2p5EditImageInput;
|
||||
type RawResponse = GptImage2p5ImageOutput;
|
||||
|
||||
fn to_raw_request(&self) -> Result<Self::RawRequest, FalErrorPlus> {
|
||||
Ok(self.params.to_raw_input())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::creds::fal_api_key::FalApiKey;
|
||||
use crate::requests::api::image::common::gpt_image_2_resolution::GptImage2Resolution;
|
||||
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_quality::GptImage2p5Quality;
|
||||
use crate::requests::api::image::common::gpt_image_2p5::raw::gpt_image_2p5_image_size_param::GptImage2p5ImageSizeParam;
|
||||
use errors::AnyhowResult;
|
||||
use std::fs::read_to_string;
|
||||
use test_data::web::image_urls::{ERNEST_SCARED_STUPID_IMAGE_URL, GHOST_IMAGE_URL, TREX_SKELETON_IMAGE_URL};
|
||||
|
||||
#[test]
|
||||
fn endpoint() {
|
||||
assert_eq!(GptImage2p5FlareEditImageRequest::ENDPOINT, "openai/gpt-image-2.5/flare/edit");
|
||||
assert_eq!(GptImage2p5FlareEditImageRequest::get_endpoint(), "openai/gpt-image-2.5/flare/edit");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn to_raw_request_delegates_to_params() {
|
||||
let request = GptImage2p5FlareEditImageRequest {
|
||||
params: GptImage2p5EditImageParams {
|
||||
prompt: "test".to_string(),
|
||||
image_urls: vec!["https://example.com/image.png".to_string()],
|
||||
mask_url: Some("https://example.com/mask.png".to_string()),
|
||||
num_images: GptImage2p5NumImages::Two,
|
||||
image_size: Some(GptImage2p5ImageSize::Square),
|
||||
resolution: Some(GptImage2Resolution::TwoK),
|
||||
quality: Some(GptImage2p5Quality::Low),
|
||||
background: None,
|
||||
output_format: Some(GptImage2p5OutputFormat::Png),
|
||||
output_compression: None,
|
||||
},
|
||||
};
|
||||
let raw = request.to_raw_request().unwrap();
|
||||
assert_eq!(raw.prompt, "test");
|
||||
assert_eq!(raw.image_urls, vec!["https://example.com/image.png".to_string()]);
|
||||
assert_eq!(raw.mask_url.as_deref(), Some("https://example.com/mask.png"));
|
||||
assert_eq!(raw.num_images, Some(2));
|
||||
assert_eq!(raw.quality.as_deref(), Some("low"));
|
||||
match raw.image_size.unwrap() {
|
||||
GptImage2p5ImageSizeParam::Custom(c) => assert_eq!((c.width, c.height), (2048, 2048)),
|
||||
GptImage2p5ImageSizeParam::Preset(_) => panic!("expected custom"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore] // manually test — requires real API key, incurs costs
|
||||
async fn test_edit_image_queue() -> AnyhowResult<()> {
|
||||
let secret = read_to_string("/Users/bt/Artcraft/credentials/fal_api_key.txt")?;
|
||||
let api_key = FalApiKey::from_str(&secret);
|
||||
|
||||
let request = GptImage2p5FlareEditImageRequest {
|
||||
params: GptImage2p5EditImageParams {
|
||||
prompt: "add the ghost and scared man to the image of the t-rex skeleton, make it look spooky but friendly".to_string(),
|
||||
image_urls: vec![
|
||||
GHOST_IMAGE_URL.to_string(),
|
||||
TREX_SKELETON_IMAGE_URL.to_string(),
|
||||
ERNEST_SCARED_STUPID_IMAGE_URL.to_string(),
|
||||
],
|
||||
mask_url: None,
|
||||
num_images: GptImage2p5NumImages::Two,
|
||||
image_size: None,
|
||||
resolution: None,
|
||||
quality: None,
|
||||
background: None,
|
||||
output_format: None,
|
||||
output_compression: None,
|
||||
},
|
||||
};
|
||||
|
||||
let result = request.send_queue_request(&api_key).await?;
|
||||
println!("Request ID: {}", result.request_id);
|
||||
assert!(!result.request_id.is_empty());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore] // manually test — requires real API key, incurs costs
|
||||
async fn test_edit_image_webhook() -> AnyhowResult<()> {
|
||||
let secret = read_to_string("/Users/bt/Artcraft/credentials/fal_api_key.txt")?;
|
||||
let api_key = FalApiKey::from_str(&secret);
|
||||
|
||||
let request = GptImage2p5FlareEditImageRequest {
|
||||
params: GptImage2p5EditImageParams {
|
||||
prompt: "make the ghost wear a top hat".to_string(),
|
||||
image_urls: vec![GHOST_IMAGE_URL.to_string()],
|
||||
mask_url: None,
|
||||
num_images: GptImage2p5NumImages::One,
|
||||
image_size: Some(GptImage2p5ImageSize::Square),
|
||||
resolution: None,
|
||||
quality: Some(GptImage2p5Quality::High),
|
||||
background: None,
|
||||
output_format: Some(GptImage2p5OutputFormat::Png),
|
||||
output_compression: None,
|
||||
},
|
||||
};
|
||||
|
||||
let result = request.send_webhook_request(
|
||||
&api_key,
|
||||
"https://example.com/webhook",
|
||||
).await?;
|
||||
println!("Request ID: {:?}", result.request_id);
|
||||
assert!(result.request_id.is_some());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// NB: Pricing tests are in cost.rs
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
use crate::requests::api::image::edit::gpt_image_2p5_flare_edit_image::api::GptImage2p5FlareEditImageRequest;
|
||||
use crate::requests::traits::fal_request_cost_calculator_trait::{FalRequestCostCalculator, UsdCents};
|
||||
|
||||
impl FalRequestCostCalculator for GptImage2p5FlareEditImageRequest {
|
||||
/// Flare and Sunburst are priced identically; see `gpt_image_2p5_pricing` for the model.
|
||||
fn calculate_cost_in_cents(&self) -> UsdCents {
|
||||
self.params.estimate_cost_in_cents()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::requests::api::image::common::gpt_image_2_resolution::GptImage2Resolution;
|
||||
use crate::requests::api::image::common::gpt_image_2p5::gpt_image_2p5_edit_image_params::GptImage2p5EditImageParams;
|
||||
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_quality::GptImage2p5Quality;
|
||||
use GptImage2Resolution::*;
|
||||
use GptImage2p5ImageSize::*;
|
||||
use GptImage2p5NumImages::*;
|
||||
use GptImage2p5Quality::{Low, Medium, High, XHigh, Max};
|
||||
|
||||
// (num_reference_images, size, quality, num_images, expected_cents)
|
||||
const PRESET_CASES: &[(usize, GptImage2p5ImageSize, GptImage2p5Quality, GptImage2p5NumImages, u64)] = &[
|
||||
(1, Square, Low, One, 2),
|
||||
(1, Square, High, One, 7),
|
||||
(1, Square, High, Four, 28),
|
||||
(1, Square, Max, One, 22),
|
||||
(1, Landscape4x3, High, One, 5),
|
||||
(1, Landscape16x9, High, One, 5),
|
||||
(3, Landscape16x9, High, One, 7),
|
||||
(1, SquareHd, High, One, 10),
|
||||
(1, Auto, High, One, 11),
|
||||
(4, Auto, XHigh, Two, 42),
|
||||
];
|
||||
|
||||
// (num_reference_images, size, resolution, quality, num_images, expected_cents)
|
||||
const RESOLUTION_CASES: &[(usize, GptImage2p5ImageSize, GptImage2Resolution, GptImage2p5Quality, GptImage2p5NumImages, u64)] = &[
|
||||
(1, Square, OneK, High, One, 7),
|
||||
(1, Square, TwoK, High, One, 10),
|
||||
(1, Square, FourK, High, One, 14),
|
||||
(1, Landscape16x9, OneK, High, One, 4),
|
||||
(1, Landscape16x9, FourK, High, One, 11),
|
||||
(2, Portrait4x3, ThreeK, Medium, Three, 15),
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn defaults_to_high_quality_auto_size() {
|
||||
assert_eq!(make_request(1, One, None, None, None).calculate_cost_in_cents(), 11);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preset_costs() {
|
||||
for &(refs, size, quality, num, expected) in PRESET_CASES {
|
||||
let actual = make_request(refs, num, Some(quality), Some(size), None).calculate_cost_in_cents();
|
||||
assert_eq!(actual, expected, "{refs} refs {size:?} {quality:?} {num:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolution_costs() {
|
||||
for &(refs, size, res, quality, num, expected) in RESOLUTION_CASES {
|
||||
let actual = make_request(refs, num, Some(quality), Some(size), Some(res)).calculate_cost_in_cents();
|
||||
assert_eq!(actual, expected, "{refs} refs {size:?} {res:?} {quality:?} {num:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matches_shared_params_estimate() {
|
||||
let request = make_request(2, Three, Some(XHigh), Some(Portrait16x9), Some(ThreeK));
|
||||
assert_eq!(request.calculate_cost_in_cents(), request.params.estimate_cost_in_cents());
|
||||
}
|
||||
|
||||
fn make_request(
|
||||
num_reference_images: usize,
|
||||
num_images: GptImage2p5NumImages,
|
||||
quality: Option<GptImage2p5Quality>,
|
||||
image_size: Option<GptImage2p5ImageSize>,
|
||||
resolution: Option<GptImage2Resolution>,
|
||||
) -> GptImage2p5FlareEditImageRequest {
|
||||
GptImage2p5FlareEditImageRequest {
|
||||
params: GptImage2p5EditImageParams {
|
||||
prompt: "test".to_string(),
|
||||
image_urls: vec!["https://example.com/image.png".to_string(); num_reference_images],
|
||||
mask_url: None,
|
||||
num_images,
|
||||
image_size,
|
||||
resolution,
|
||||
quality,
|
||||
background: None,
|
||||
output_format: None,
|
||||
output_compression: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
pub mod api;
|
||||
mod cost;
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
use crate::error::fal_error_plus::FalErrorPlus;
|
||||
use crate::requests::api::image::common::gpt_image_2p5::gpt_image_2p5_edit_image_params::GptImage2p5EditImageParams;
|
||||
use crate::requests::api::image::common::gpt_image_2p5::raw::gpt_image_2p5_edit_image_input::GptImage2p5EditImageInput;
|
||||
use crate::requests::api::image::common::gpt_image_2p5::raw::gpt_image_2p5_image_output::GptImage2p5ImageOutput;
|
||||
use crate::requests::traits::fal_endpoint_trait::FalEndpoint;
|
||||
|
||||
/// GPT Image 2.5 Sunburst image edit.
|
||||
///
|
||||
/// Flare and Sunburst take the same parameters (see `GptImage2p5EditImageParams`);
|
||||
/// this type only selects the endpoint.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GptImage2p5SunburstEditImageRequest {
|
||||
pub params: GptImage2p5EditImageParams,
|
||||
}
|
||||
|
||||
impl FalEndpoint for GptImage2p5SunburstEditImageRequest {
|
||||
const ENDPOINT: &str = "openai/gpt-image-2.5/sunburst/edit";
|
||||
|
||||
type RawRequest = GptImage2p5EditImageInput;
|
||||
type RawResponse = GptImage2p5ImageOutput;
|
||||
|
||||
fn to_raw_request(&self) -> Result<Self::RawRequest, FalErrorPlus> {
|
||||
Ok(self.params.to_raw_input())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::creds::fal_api_key::FalApiKey;
|
||||
use crate::requests::api::image::common::gpt_image_2_resolution::GptImage2Resolution;
|
||||
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_quality::GptImage2p5Quality;
|
||||
use crate::requests::api::image::common::gpt_image_2p5::raw::gpt_image_2p5_image_size_param::GptImage2p5ImageSizeParam;
|
||||
use errors::AnyhowResult;
|
||||
use std::fs::read_to_string;
|
||||
use test_data::web::image_urls::{ERNEST_SCARED_STUPID_IMAGE_URL, GHOST_IMAGE_URL, TREX_SKELETON_IMAGE_URL};
|
||||
|
||||
#[test]
|
||||
fn endpoint() {
|
||||
assert_eq!(GptImage2p5SunburstEditImageRequest::ENDPOINT, "openai/gpt-image-2.5/sunburst/edit");
|
||||
assert_eq!(GptImage2p5SunburstEditImageRequest::get_endpoint(), "openai/gpt-image-2.5/sunburst/edit");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn to_raw_request_delegates_to_params() {
|
||||
let request = GptImage2p5SunburstEditImageRequest {
|
||||
params: GptImage2p5EditImageParams {
|
||||
prompt: "test".to_string(),
|
||||
image_urls: vec!["https://example.com/image.png".to_string()],
|
||||
mask_url: Some("https://example.com/mask.png".to_string()),
|
||||
num_images: GptImage2p5NumImages::Two,
|
||||
image_size: Some(GptImage2p5ImageSize::Square),
|
||||
resolution: Some(GptImage2Resolution::TwoK),
|
||||
quality: Some(GptImage2p5Quality::Low),
|
||||
background: None,
|
||||
output_format: Some(GptImage2p5OutputFormat::Png),
|
||||
output_compression: None,
|
||||
},
|
||||
};
|
||||
let raw = request.to_raw_request().unwrap();
|
||||
assert_eq!(raw.prompt, "test");
|
||||
assert_eq!(raw.image_urls, vec!["https://example.com/image.png".to_string()]);
|
||||
assert_eq!(raw.mask_url.as_deref(), Some("https://example.com/mask.png"));
|
||||
assert_eq!(raw.num_images, Some(2));
|
||||
assert_eq!(raw.quality.as_deref(), Some("low"));
|
||||
match raw.image_size.unwrap() {
|
||||
GptImage2p5ImageSizeParam::Custom(c) => assert_eq!((c.width, c.height), (2048, 2048)),
|
||||
GptImage2p5ImageSizeParam::Preset(_) => panic!("expected custom"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore] // manually test — requires real API key, incurs costs
|
||||
async fn test_edit_image_queue() -> AnyhowResult<()> {
|
||||
let secret = read_to_string("/Users/bt/Artcraft/credentials/fal_api_key.txt")?;
|
||||
let api_key = FalApiKey::from_str(&secret);
|
||||
|
||||
let request = GptImage2p5SunburstEditImageRequest {
|
||||
params: GptImage2p5EditImageParams {
|
||||
prompt: "add the ghost and scared man to the image of the t-rex skeleton, make it look spooky but friendly".to_string(),
|
||||
image_urls: vec![
|
||||
GHOST_IMAGE_URL.to_string(),
|
||||
TREX_SKELETON_IMAGE_URL.to_string(),
|
||||
ERNEST_SCARED_STUPID_IMAGE_URL.to_string(),
|
||||
],
|
||||
mask_url: None,
|
||||
num_images: GptImage2p5NumImages::Two,
|
||||
image_size: None,
|
||||
resolution: None,
|
||||
quality: None,
|
||||
background: None,
|
||||
output_format: None,
|
||||
output_compression: None,
|
||||
},
|
||||
};
|
||||
|
||||
let result = request.send_queue_request(&api_key).await?;
|
||||
println!("Request ID: {}", result.request_id);
|
||||
assert!(!result.request_id.is_empty());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore] // manually test — requires real API key, incurs costs
|
||||
async fn test_edit_image_webhook() -> AnyhowResult<()> {
|
||||
let secret = read_to_string("/Users/bt/Artcraft/credentials/fal_api_key.txt")?;
|
||||
let api_key = FalApiKey::from_str(&secret);
|
||||
|
||||
let request = GptImage2p5SunburstEditImageRequest {
|
||||
params: GptImage2p5EditImageParams {
|
||||
prompt: "make the ghost wear a top hat".to_string(),
|
||||
image_urls: vec![GHOST_IMAGE_URL.to_string()],
|
||||
mask_url: None,
|
||||
num_images: GptImage2p5NumImages::One,
|
||||
image_size: Some(GptImage2p5ImageSize::Square),
|
||||
resolution: None,
|
||||
quality: Some(GptImage2p5Quality::High),
|
||||
background: None,
|
||||
output_format: Some(GptImage2p5OutputFormat::Png),
|
||||
output_compression: None,
|
||||
},
|
||||
};
|
||||
|
||||
let result = request.send_webhook_request(
|
||||
&api_key,
|
||||
"https://example.com/webhook",
|
||||
).await?;
|
||||
println!("Request ID: {:?}", result.request_id);
|
||||
assert!(result.request_id.is_some());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// NB: Pricing tests are in cost.rs
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
use crate::requests::api::image::edit::gpt_image_2p5_sunburst_edit_image::api::GptImage2p5SunburstEditImageRequest;
|
||||
use crate::requests::traits::fal_request_cost_calculator_trait::{FalRequestCostCalculator, UsdCents};
|
||||
|
||||
impl FalRequestCostCalculator for GptImage2p5SunburstEditImageRequest {
|
||||
/// Flare and Sunburst are priced identically; see `gpt_image_2p5_pricing` for the model.
|
||||
fn calculate_cost_in_cents(&self) -> UsdCents {
|
||||
self.params.estimate_cost_in_cents()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::requests::api::image::common::gpt_image_2_resolution::GptImage2Resolution;
|
||||
use crate::requests::api::image::common::gpt_image_2p5::gpt_image_2p5_edit_image_params::GptImage2p5EditImageParams;
|
||||
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_quality::GptImage2p5Quality;
|
||||
use GptImage2Resolution::*;
|
||||
use GptImage2p5ImageSize::*;
|
||||
use GptImage2p5NumImages::*;
|
||||
use GptImage2p5Quality::{Low, Medium, High, XHigh, Max};
|
||||
|
||||
// (num_reference_images, size, quality, num_images, expected_cents)
|
||||
const PRESET_CASES: &[(usize, GptImage2p5ImageSize, GptImage2p5Quality, GptImage2p5NumImages, u64)] = &[
|
||||
(1, Square, Low, One, 2),
|
||||
(1, Square, High, One, 7),
|
||||
(1, Square, High, Four, 28),
|
||||
(1, Square, Max, One, 22),
|
||||
(1, Landscape4x3, High, One, 5),
|
||||
(1, Landscape16x9, High, One, 5),
|
||||
(3, Landscape16x9, High, One, 7),
|
||||
(1, SquareHd, High, One, 10),
|
||||
(1, Auto, High, One, 11),
|
||||
(4, Auto, XHigh, Two, 42),
|
||||
];
|
||||
|
||||
// (num_reference_images, size, resolution, quality, num_images, expected_cents)
|
||||
const RESOLUTION_CASES: &[(usize, GptImage2p5ImageSize, GptImage2Resolution, GptImage2p5Quality, GptImage2p5NumImages, u64)] = &[
|
||||
(1, Square, OneK, High, One, 7),
|
||||
(1, Square, TwoK, High, One, 10),
|
||||
(1, Square, FourK, High, One, 14),
|
||||
(1, Landscape16x9, OneK, High, One, 4),
|
||||
(1, Landscape16x9, FourK, High, One, 11),
|
||||
(2, Portrait4x3, ThreeK, Medium, Three, 15),
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn defaults_to_high_quality_auto_size() {
|
||||
assert_eq!(make_request(1, One, None, None, None).calculate_cost_in_cents(), 11);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preset_costs() {
|
||||
for &(refs, size, quality, num, expected) in PRESET_CASES {
|
||||
let actual = make_request(refs, num, Some(quality), Some(size), None).calculate_cost_in_cents();
|
||||
assert_eq!(actual, expected, "{refs} refs {size:?} {quality:?} {num:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolution_costs() {
|
||||
for &(refs, size, res, quality, num, expected) in RESOLUTION_CASES {
|
||||
let actual = make_request(refs, num, Some(quality), Some(size), Some(res)).calculate_cost_in_cents();
|
||||
assert_eq!(actual, expected, "{refs} refs {size:?} {res:?} {quality:?} {num:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matches_shared_params_estimate() {
|
||||
let request = make_request(2, Three, Some(XHigh), Some(Portrait16x9), Some(ThreeK));
|
||||
assert_eq!(request.calculate_cost_in_cents(), request.params.estimate_cost_in_cents());
|
||||
}
|
||||
|
||||
fn make_request(
|
||||
num_reference_images: usize,
|
||||
num_images: GptImage2p5NumImages,
|
||||
quality: Option<GptImage2p5Quality>,
|
||||
image_size: Option<GptImage2p5ImageSize>,
|
||||
resolution: Option<GptImage2Resolution>,
|
||||
) -> GptImage2p5SunburstEditImageRequest {
|
||||
GptImage2p5SunburstEditImageRequest {
|
||||
params: GptImage2p5EditImageParams {
|
||||
prompt: "test".to_string(),
|
||||
image_urls: vec!["https://example.com/image.png".to_string(); num_reference_images],
|
||||
mask_url: None,
|
||||
num_images,
|
||||
image_size,
|
||||
resolution,
|
||||
quality,
|
||||
background: None,
|
||||
output_format: None,
|
||||
output_compression: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
pub mod api;
|
||||
mod cost;
|
||||
@@ -3,5 +3,7 @@ pub mod flux_1_schnell_edit_image;
|
||||
pub mod gpt_image_1_edit_image;
|
||||
pub mod gpt_image_1p5_edit_image;
|
||||
pub mod gpt_image_2_edit_image;
|
||||
pub mod gpt_image_2p5_flare_edit_image;
|
||||
pub mod gpt_image_2p5_sunburst_edit_image;
|
||||
pub mod nano_banana_2_edit_image;
|
||||
pub mod nano_banana_pro_edit_image;
|
||||
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
use crate::error::fal_error_plus::FalErrorPlus;
|
||||
use crate::requests::api::image::common::gpt_image_2p5::gpt_image_2p5_text_to_image_params::GptImage2p5TextToImageParams;
|
||||
use crate::requests::api::image::common::gpt_image_2p5::raw::gpt_image_2p5_image_output::GptImage2p5ImageOutput;
|
||||
use crate::requests::api::image::common::gpt_image_2p5::raw::gpt_image_2p5_text_to_image_input::GptImage2p5TextToImageInput;
|
||||
use crate::requests::traits::fal_endpoint_trait::FalEndpoint;
|
||||
|
||||
/// GPT Image 2.5 Flare text-to-image.
|
||||
///
|
||||
/// Flare and Sunburst take the same parameters (see `GptImage2p5TextToImageParams`);
|
||||
/// this type only selects the endpoint.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GptImage2p5FlareTextToImageRequest {
|
||||
pub params: GptImage2p5TextToImageParams,
|
||||
}
|
||||
|
||||
impl FalEndpoint for GptImage2p5FlareTextToImageRequest {
|
||||
const ENDPOINT: &str = "openai/gpt-image-2.5/flare/text-to-image";
|
||||
|
||||
type RawRequest = GptImage2p5TextToImageInput;
|
||||
type RawResponse = GptImage2p5ImageOutput;
|
||||
|
||||
fn to_raw_request(&self) -> Result<Self::RawRequest, FalErrorPlus> {
|
||||
Ok(self.params.to_raw_input())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::creds::fal_api_key::FalApiKey;
|
||||
use crate::requests::api::image::common::gpt_image_2_resolution::GptImage2Resolution;
|
||||
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_quality::GptImage2p5Quality;
|
||||
use crate::requests::api::image::common::gpt_image_2p5::raw::gpt_image_2p5_image_size_param::GptImage2p5ImageSizeParam;
|
||||
use errors::AnyhowResult;
|
||||
use std::fs::read_to_string;
|
||||
|
||||
#[test]
|
||||
fn endpoint() {
|
||||
assert_eq!(GptImage2p5FlareTextToImageRequest::ENDPOINT, "openai/gpt-image-2.5/flare/text-to-image");
|
||||
assert_eq!(GptImage2p5FlareTextToImageRequest::get_endpoint(), "openai/gpt-image-2.5/flare/text-to-image");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn to_raw_request_delegates_to_params() {
|
||||
let request = GptImage2p5FlareTextToImageRequest {
|
||||
params: GptImage2p5TextToImageParams {
|
||||
prompt: "test".to_string(),
|
||||
num_images: GptImage2p5NumImages::Two,
|
||||
image_size: Some(GptImage2p5ImageSize::Landscape16x9),
|
||||
resolution: Some(GptImage2Resolution::TwoK),
|
||||
quality: Some(GptImage2p5Quality::Medium),
|
||||
background: None,
|
||||
output_format: Some(GptImage2p5OutputFormat::Jpeg),
|
||||
output_compression: Some(75),
|
||||
},
|
||||
};
|
||||
let raw = request.to_raw_request().unwrap();
|
||||
assert_eq!(raw.prompt, "test");
|
||||
assert_eq!(raw.num_images, Some(2));
|
||||
assert_eq!(raw.quality.as_deref(), Some("medium"));
|
||||
assert_eq!(raw.output_format.as_deref(), Some("jpeg"));
|
||||
assert_eq!(raw.output_compression, Some(75));
|
||||
match raw.image_size.unwrap() {
|
||||
GptImage2p5ImageSizeParam::Custom(c) => assert_eq!((c.width, c.height), (2048, 1152)),
|
||||
GptImage2p5ImageSizeParam::Preset(_) => panic!("expected custom"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore] // manually test — requires real API key, incurs costs
|
||||
async fn test_text_to_image_queue() -> AnyhowResult<()> {
|
||||
let secret = read_to_string("/Users/bt/Artcraft/credentials/fal_api_key.txt")?;
|
||||
let api_key = FalApiKey::from_str(&secret);
|
||||
|
||||
let request = GptImage2p5FlareTextToImageRequest {
|
||||
params: GptImage2p5TextToImageParams {
|
||||
prompt: "an anime girl riding on the back of a t-rex".to_string(),
|
||||
num_images: GptImage2p5NumImages::One,
|
||||
image_size: None,
|
||||
resolution: None,
|
||||
quality: None,
|
||||
background: None,
|
||||
output_format: None,
|
||||
output_compression: None,
|
||||
},
|
||||
};
|
||||
|
||||
let result = request.send_queue_request(&api_key).await?;
|
||||
println!("Request ID: {}", result.request_id);
|
||||
assert!(!result.request_id.is_empty());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore] // manually test — requires real API key, incurs costs
|
||||
async fn test_text_to_image_webhook() -> AnyhowResult<()> {
|
||||
let secret = read_to_string("/Users/bt/Artcraft/credentials/fal_api_key.txt")?;
|
||||
let api_key = FalApiKey::from_str(&secret);
|
||||
|
||||
let request = GptImage2p5FlareTextToImageRequest {
|
||||
params: GptImage2p5TextToImageParams {
|
||||
prompt: "a corgi wearing sunglasses at the beach".to_string(),
|
||||
num_images: GptImage2p5NumImages::Two,
|
||||
image_size: Some(GptImage2p5ImageSize::Landscape16x9),
|
||||
resolution: None,
|
||||
quality: Some(GptImage2p5Quality::High),
|
||||
background: None,
|
||||
output_format: Some(GptImage2p5OutputFormat::Png),
|
||||
output_compression: None,
|
||||
},
|
||||
};
|
||||
|
||||
let result = request.send_webhook_request(
|
||||
&api_key,
|
||||
"https://example.com/webhook",
|
||||
).await?;
|
||||
println!("Request ID: {:?}", result.request_id);
|
||||
assert!(result.request_id.is_some());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// NB: Pricing tests are in cost.rs
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
use crate::requests::api::image::text::gpt_image_2p5_flare_text_to_image::api::GptImage2p5FlareTextToImageRequest;
|
||||
use crate::requests::traits::fal_request_cost_calculator_trait::{FalRequestCostCalculator, UsdCents};
|
||||
|
||||
impl FalRequestCostCalculator for GptImage2p5FlareTextToImageRequest {
|
||||
/// Flare and Sunburst are priced identically; see `gpt_image_2p5_pricing` for the model.
|
||||
fn calculate_cost_in_cents(&self) -> UsdCents {
|
||||
self.params.estimate_cost_in_cents()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::requests::api::image::common::gpt_image_2_resolution::GptImage2Resolution;
|
||||
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_quality::GptImage2p5Quality;
|
||||
use crate::requests::api::image::common::gpt_image_2p5::gpt_image_2p5_text_to_image_params::GptImage2p5TextToImageParams;
|
||||
use GptImage2Resolution::*;
|
||||
use GptImage2p5ImageSize::*;
|
||||
use GptImage2p5NumImages::*;
|
||||
use GptImage2p5Quality::{Low, Medium, High, XHigh, Max};
|
||||
|
||||
// (size, quality, num_images, expected_cents)
|
||||
const PRESET_CASES: &[(GptImage2p5ImageSize, GptImage2p5Quality, GptImage2p5NumImages, u64)] = &[
|
||||
(Square, Low, One, 1),
|
||||
(Square, High, One, 6),
|
||||
(Square, High, Four, 24),
|
||||
(Square, Max, One, 22),
|
||||
(Landscape4x3, High, One, 4),
|
||||
(Landscape16x9, High, One, 4),
|
||||
(Landscape16x9, XHigh, Two, 16),
|
||||
(SquareHd, High, One, 9),
|
||||
(Auto, High, One, 11),
|
||||
];
|
||||
|
||||
// (size, resolution, quality, num_images, expected_cents)
|
||||
const RESOLUTION_CASES: &[(GptImage2p5ImageSize, GptImage2Resolution, GptImage2p5Quality, GptImage2p5NumImages, u64)] = &[
|
||||
(Square, OneK, High, One, 6),
|
||||
(Square, TwoK, High, One, 9),
|
||||
(Square, FourK, High, One, 13),
|
||||
(Landscape16x9, OneK, High, One, 3),
|
||||
(Landscape16x9, FourK, High, One, 11),
|
||||
(Portrait4x3, ThreeK, Medium, Three, 9),
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn defaults_to_high_quality_landscape_4x3() {
|
||||
assert_eq!(make_request(One, None, None, None).calculate_cost_in_cents(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preset_costs() {
|
||||
for &(size, quality, num, expected) in PRESET_CASES {
|
||||
let actual = make_request(num, Some(quality), Some(size), None).calculate_cost_in_cents();
|
||||
assert_eq!(actual, expected, "{size:?} {quality:?} {num:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolution_costs() {
|
||||
for &(size, res, quality, num, expected) in RESOLUTION_CASES {
|
||||
let actual = make_request(num, Some(quality), Some(size), Some(res)).calculate_cost_in_cents();
|
||||
assert_eq!(actual, expected, "{size:?} {res:?} {quality:?} {num:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matches_shared_params_estimate() {
|
||||
let request = make_request(Three, Some(XHigh), Some(Portrait16x9), Some(ThreeK));
|
||||
assert_eq!(request.calculate_cost_in_cents(), request.params.estimate_cost_in_cents());
|
||||
}
|
||||
|
||||
fn make_request(
|
||||
num_images: GptImage2p5NumImages,
|
||||
quality: Option<GptImage2p5Quality>,
|
||||
image_size: Option<GptImage2p5ImageSize>,
|
||||
resolution: Option<GptImage2Resolution>,
|
||||
) -> GptImage2p5FlareTextToImageRequest {
|
||||
GptImage2p5FlareTextToImageRequest {
|
||||
params: GptImage2p5TextToImageParams {
|
||||
prompt: "test".to_string(),
|
||||
num_images,
|
||||
image_size,
|
||||
resolution,
|
||||
quality,
|
||||
background: None,
|
||||
output_format: None,
|
||||
output_compression: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
pub mod api;
|
||||
mod cost;
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
use crate::error::fal_error_plus::FalErrorPlus;
|
||||
use crate::requests::api::image::common::gpt_image_2p5::gpt_image_2p5_text_to_image_params::GptImage2p5TextToImageParams;
|
||||
use crate::requests::api::image::common::gpt_image_2p5::raw::gpt_image_2p5_image_output::GptImage2p5ImageOutput;
|
||||
use crate::requests::api::image::common::gpt_image_2p5::raw::gpt_image_2p5_text_to_image_input::GptImage2p5TextToImageInput;
|
||||
use crate::requests::traits::fal_endpoint_trait::FalEndpoint;
|
||||
|
||||
/// GPT Image 2.5 Sunburst text-to-image.
|
||||
///
|
||||
/// Flare and Sunburst take the same parameters (see `GptImage2p5TextToImageParams`);
|
||||
/// this type only selects the endpoint.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GptImage2p5SunburstTextToImageRequest {
|
||||
pub params: GptImage2p5TextToImageParams,
|
||||
}
|
||||
|
||||
impl FalEndpoint for GptImage2p5SunburstTextToImageRequest {
|
||||
const ENDPOINT: &str = "openai/gpt-image-2.5/sunburst/text-to-image";
|
||||
|
||||
type RawRequest = GptImage2p5TextToImageInput;
|
||||
type RawResponse = GptImage2p5ImageOutput;
|
||||
|
||||
fn to_raw_request(&self) -> Result<Self::RawRequest, FalErrorPlus> {
|
||||
Ok(self.params.to_raw_input())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::creds::fal_api_key::FalApiKey;
|
||||
use crate::requests::api::image::common::gpt_image_2_resolution::GptImage2Resolution;
|
||||
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_quality::GptImage2p5Quality;
|
||||
use crate::requests::api::image::common::gpt_image_2p5::raw::gpt_image_2p5_image_size_param::GptImage2p5ImageSizeParam;
|
||||
use errors::AnyhowResult;
|
||||
use std::fs::read_to_string;
|
||||
|
||||
#[test]
|
||||
fn endpoint() {
|
||||
assert_eq!(GptImage2p5SunburstTextToImageRequest::ENDPOINT, "openai/gpt-image-2.5/sunburst/text-to-image");
|
||||
assert_eq!(GptImage2p5SunburstTextToImageRequest::get_endpoint(), "openai/gpt-image-2.5/sunburst/text-to-image");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn to_raw_request_delegates_to_params() {
|
||||
let request = GptImage2p5SunburstTextToImageRequest {
|
||||
params: GptImage2p5TextToImageParams {
|
||||
prompt: "test".to_string(),
|
||||
num_images: GptImage2p5NumImages::Two,
|
||||
image_size: Some(GptImage2p5ImageSize::Landscape16x9),
|
||||
resolution: Some(GptImage2Resolution::TwoK),
|
||||
quality: Some(GptImage2p5Quality::Medium),
|
||||
background: None,
|
||||
output_format: Some(GptImage2p5OutputFormat::Jpeg),
|
||||
output_compression: Some(75),
|
||||
},
|
||||
};
|
||||
let raw = request.to_raw_request().unwrap();
|
||||
assert_eq!(raw.prompt, "test");
|
||||
assert_eq!(raw.num_images, Some(2));
|
||||
assert_eq!(raw.quality.as_deref(), Some("medium"));
|
||||
assert_eq!(raw.output_format.as_deref(), Some("jpeg"));
|
||||
assert_eq!(raw.output_compression, Some(75));
|
||||
match raw.image_size.unwrap() {
|
||||
GptImage2p5ImageSizeParam::Custom(c) => assert_eq!((c.width, c.height), (2048, 1152)),
|
||||
GptImage2p5ImageSizeParam::Preset(_) => panic!("expected custom"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore] // manually test — requires real API key, incurs costs
|
||||
async fn test_text_to_image_queue() -> AnyhowResult<()> {
|
||||
let secret = read_to_string("/Users/bt/Artcraft/credentials/fal_api_key.txt")?;
|
||||
let api_key = FalApiKey::from_str(&secret);
|
||||
|
||||
let request = GptImage2p5SunburstTextToImageRequest {
|
||||
params: GptImage2p5TextToImageParams {
|
||||
prompt: "an anime girl riding on the back of a t-rex".to_string(),
|
||||
num_images: GptImage2p5NumImages::One,
|
||||
image_size: None,
|
||||
resolution: None,
|
||||
quality: None,
|
||||
background: None,
|
||||
output_format: None,
|
||||
output_compression: None,
|
||||
},
|
||||
};
|
||||
|
||||
let result = request.send_queue_request(&api_key).await?;
|
||||
println!("Request ID: {}", result.request_id);
|
||||
assert!(!result.request_id.is_empty());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore] // manually test — requires real API key, incurs costs
|
||||
async fn test_text_to_image_webhook() -> AnyhowResult<()> {
|
||||
let secret = read_to_string("/Users/bt/Artcraft/credentials/fal_api_key.txt")?;
|
||||
let api_key = FalApiKey::from_str(&secret);
|
||||
|
||||
let request = GptImage2p5SunburstTextToImageRequest {
|
||||
params: GptImage2p5TextToImageParams {
|
||||
prompt: "a corgi wearing sunglasses at the beach".to_string(),
|
||||
num_images: GptImage2p5NumImages::Two,
|
||||
image_size: Some(GptImage2p5ImageSize::Landscape16x9),
|
||||
resolution: None,
|
||||
quality: Some(GptImage2p5Quality::High),
|
||||
background: None,
|
||||
output_format: Some(GptImage2p5OutputFormat::Png),
|
||||
output_compression: None,
|
||||
},
|
||||
};
|
||||
|
||||
let result = request.send_webhook_request(
|
||||
&api_key,
|
||||
"https://example.com/webhook",
|
||||
).await?;
|
||||
println!("Request ID: {:?}", result.request_id);
|
||||
assert!(result.request_id.is_some());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// NB: Pricing tests are in cost.rs
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
use crate::requests::api::image::text::gpt_image_2p5_sunburst_text_to_image::api::GptImage2p5SunburstTextToImageRequest;
|
||||
use crate::requests::traits::fal_request_cost_calculator_trait::{FalRequestCostCalculator, UsdCents};
|
||||
|
||||
impl FalRequestCostCalculator for GptImage2p5SunburstTextToImageRequest {
|
||||
/// Flare and Sunburst are priced identically; see `gpt_image_2p5_pricing` for the model.
|
||||
fn calculate_cost_in_cents(&self) -> UsdCents {
|
||||
self.params.estimate_cost_in_cents()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::requests::api::image::common::gpt_image_2_resolution::GptImage2Resolution;
|
||||
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_quality::GptImage2p5Quality;
|
||||
use crate::requests::api::image::common::gpt_image_2p5::gpt_image_2p5_text_to_image_params::GptImage2p5TextToImageParams;
|
||||
use GptImage2Resolution::*;
|
||||
use GptImage2p5ImageSize::*;
|
||||
use GptImage2p5NumImages::*;
|
||||
use GptImage2p5Quality::{Low, Medium, High, XHigh, Max};
|
||||
|
||||
// (size, quality, num_images, expected_cents)
|
||||
const PRESET_CASES: &[(GptImage2p5ImageSize, GptImage2p5Quality, GptImage2p5NumImages, u64)] = &[
|
||||
(Square, Low, One, 1),
|
||||
(Square, High, One, 6),
|
||||
(Square, High, Four, 24),
|
||||
(Square, Max, One, 22),
|
||||
(Landscape4x3, High, One, 4),
|
||||
(Landscape16x9, High, One, 4),
|
||||
(Landscape16x9, XHigh, Two, 16),
|
||||
(SquareHd, High, One, 9),
|
||||
(Auto, High, One, 11),
|
||||
];
|
||||
|
||||
// (size, resolution, quality, num_images, expected_cents)
|
||||
const RESOLUTION_CASES: &[(GptImage2p5ImageSize, GptImage2Resolution, GptImage2p5Quality, GptImage2p5NumImages, u64)] = &[
|
||||
(Square, OneK, High, One, 6),
|
||||
(Square, TwoK, High, One, 9),
|
||||
(Square, FourK, High, One, 13),
|
||||
(Landscape16x9, OneK, High, One, 3),
|
||||
(Landscape16x9, FourK, High, One, 11),
|
||||
(Portrait4x3, ThreeK, Medium, Three, 9),
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn defaults_to_high_quality_landscape_4x3() {
|
||||
assert_eq!(make_request(One, None, None, None).calculate_cost_in_cents(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preset_costs() {
|
||||
for &(size, quality, num, expected) in PRESET_CASES {
|
||||
let actual = make_request(num, Some(quality), Some(size), None).calculate_cost_in_cents();
|
||||
assert_eq!(actual, expected, "{size:?} {quality:?} {num:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolution_costs() {
|
||||
for &(size, res, quality, num, expected) in RESOLUTION_CASES {
|
||||
let actual = make_request(num, Some(quality), Some(size), Some(res)).calculate_cost_in_cents();
|
||||
assert_eq!(actual, expected, "{size:?} {res:?} {quality:?} {num:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matches_shared_params_estimate() {
|
||||
let request = make_request(Three, Some(XHigh), Some(Portrait16x9), Some(ThreeK));
|
||||
assert_eq!(request.calculate_cost_in_cents(), request.params.estimate_cost_in_cents());
|
||||
}
|
||||
|
||||
fn make_request(
|
||||
num_images: GptImage2p5NumImages,
|
||||
quality: Option<GptImage2p5Quality>,
|
||||
image_size: Option<GptImage2p5ImageSize>,
|
||||
resolution: Option<GptImage2Resolution>,
|
||||
) -> GptImage2p5SunburstTextToImageRequest {
|
||||
GptImage2p5SunburstTextToImageRequest {
|
||||
params: GptImage2p5TextToImageParams {
|
||||
prompt: "test".to_string(),
|
||||
num_images,
|
||||
image_size,
|
||||
resolution,
|
||||
quality,
|
||||
background: None,
|
||||
output_format: None,
|
||||
output_compression: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
pub mod api;
|
||||
mod cost;
|
||||
@@ -3,5 +3,7 @@ pub mod flux_1_schnell_text_to_image;
|
||||
pub mod gpt_image_1_text_to_image;
|
||||
pub mod gpt_image_1p5_text_to_image;
|
||||
pub mod gpt_image_2_text_to_image;
|
||||
pub mod gpt_image_2p5_flare_text_to_image;
|
||||
pub mod gpt_image_2p5_sunburst_text_to_image;
|
||||
pub mod nano_banana_2_text_to_image;
|
||||
pub mod nano_banana_pro_text_to_image;
|
||||
|
||||
@@ -1,18 +1,30 @@
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use reqwest::IntoUrl;
|
||||
use reqwest::{IntoUrl, Url};
|
||||
use serde::{de::DeserializeOwned, Serialize};
|
||||
use log::info;
|
||||
use log::{debug, info};
|
||||
|
||||
use crate::error::fal_error::FalError;
|
||||
use crate::requests::core_api::queue::Queue;
|
||||
use crate::requests::core_api::queue_response::QueueResponse;
|
||||
use crate::requests::core_api::webhook_response::WebhookResponse;
|
||||
|
||||
/// Host for synchronous ("run and wait") requests.
|
||||
const DEFAULT_SYNC_BASE_URL: &str = "https://fal.run";
|
||||
|
||||
/// Host for the asynchronous queue API (polling and webhooks).
|
||||
const DEFAULT_QUEUE_BASE_URL: &str = "https://queue.fal.run";
|
||||
|
||||
/// A request to the FAL API.
|
||||
///
|
||||
/// Originally from the vendored `fal` crate (`fal::request::FalRequest`).
|
||||
/// Copied here so `fal_client` can be independent of the vendored crate.
|
||||
///
|
||||
/// NB: `reqwest::RequestBuilder::json()` already sets `Content-Type: application/json`.
|
||||
/// Do NOT add another `Content-Type` header after it: `RequestBuilder::header()` *appends*,
|
||||
/// so the request would carry two `Content-Type` headers. Fal's workers then treat the body
|
||||
/// as opaque bytes and fail every job with
|
||||
/// "Input should be a valid dictionary or object to extract fields from" (2026-09-08 outage).
|
||||
#[derive(Debug)]
|
||||
pub struct FalRequest<Params: Serialize, Response: DeserializeOwned> {
|
||||
/// The Reqwest Client to use to make requests
|
||||
@@ -24,6 +36,10 @@ pub struct FalRequest<Params: Serialize, Response: DeserializeOwned> {
|
||||
/// The API key to use to make the request.
|
||||
/// If not provided, the `FAL_API_KEY` environment variable will be used.
|
||||
pub api_key: Option<String>,
|
||||
/// Base URL for synchronous requests (`send`). Defaults to `https://fal.run`.
|
||||
pub sync_base_url: String,
|
||||
/// Base URL for queue requests. Defaults to `https://queue.fal.run`.
|
||||
pub queue_base_url: String,
|
||||
phantom: PhantomData<Response>,
|
||||
}
|
||||
|
||||
@@ -34,6 +50,8 @@ impl<Params: Serialize, Response: DeserializeOwned> FalRequest<Params, Response>
|
||||
endpoint: endpoint.into(),
|
||||
params,
|
||||
api_key: std::env::var("FAL_API_KEY").ok(),
|
||||
sync_base_url: DEFAULT_SYNC_BASE_URL.to_string(),
|
||||
queue_base_url: DEFAULT_QUEUE_BASE_URL.to_string(),
|
||||
phantom: PhantomData,
|
||||
}
|
||||
}
|
||||
@@ -50,11 +68,23 @@ impl<Params: Serialize, Response: DeserializeOwned> FalRequest<Params, Response>
|
||||
self
|
||||
}
|
||||
|
||||
/// Override the host used for synchronous requests (tests, proxies).
|
||||
pub fn with_sync_base_url(mut self, base_url: impl Into<String>) -> Self {
|
||||
self.sync_base_url = base_url.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Override the host used for queue requests (tests, proxies).
|
||||
pub fn with_queue_base_url(mut self, base_url: impl Into<String>) -> Self {
|
||||
self.queue_base_url = base_url.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Send the request and wait for the response
|
||||
pub async fn send(self) -> Result<Response, FalError> {
|
||||
let response = self
|
||||
.client
|
||||
.post(format!("https://fal.run/{}", self.endpoint))
|
||||
.post(format!("{}/{}", self.sync_base_url, self.endpoint))
|
||||
.json(&self.params)
|
||||
.header(
|
||||
"Authorization",
|
||||
@@ -65,7 +95,6 @@ impl<Params: Serialize, Response: DeserializeOwned> FalRequest<Params, Response>
|
||||
)
|
||||
),
|
||||
)
|
||||
.header("Content-Type", "application/json")
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
@@ -85,10 +114,9 @@ impl<Params: Serialize, Response: DeserializeOwned> FalRequest<Params, Response>
|
||||
|
||||
let response = self
|
||||
.client
|
||||
.post(format!("https://queue.fal.run/{}", self.endpoint))
|
||||
.post(format!("{}/{}", self.queue_base_url, self.endpoint))
|
||||
.json(&self.params)
|
||||
.header("Authorization", format!("Key {}", &key))
|
||||
.header("Content-Type", "application/json")
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
@@ -103,14 +131,22 @@ impl<Params: Serialize, Response: DeserializeOwned> FalRequest<Params, Response>
|
||||
}
|
||||
|
||||
/// Submit the request to the Fal queue with a webhook callback URL.
|
||||
///
|
||||
/// NB: The `fal_webhook` query value MUST be percent-encoded. Since Fal's 2026-09-08 gateway
|
||||
/// change, a raw `fal_webhook=https://host/path` value is silently ignored: the job completes
|
||||
/// but no webhook is ever delivered. `query_pairs_mut` encodes it for us.
|
||||
pub async fn queue_webhook<U: IntoUrl>(self, url: U) -> Result<WebhookResponse, FalError> {
|
||||
let key = self
|
||||
.api_key
|
||||
.expect("No fal API key provided, and FAL_API_KEY environment variable is not set");
|
||||
|
||||
let url_encoded = url.into_url()?;
|
||||
let webhook_url = url.into_url()?;
|
||||
|
||||
let request_url = format!("https://queue.fal.run/{}?fal_webhook={}", self.endpoint, url_encoded);
|
||||
let mut request_url = Url::parse(&format!("{}/{}", self.queue_base_url, self.endpoint))
|
||||
.map_err(|err| FalError::Other(format!("invalid fal queue url: {}", err)))?;
|
||||
request_url
|
||||
.query_pairs_mut()
|
||||
.append_pair("fal_webhook", webhook_url.as_str());
|
||||
|
||||
info!("Sending request to FAL queue webhook: {}", request_url);
|
||||
|
||||
@@ -119,7 +155,6 @@ impl<Params: Serialize, Response: DeserializeOwned> FalRequest<Params, Response>
|
||||
.post(request_url)
|
||||
.json(&self.params)
|
||||
.header("Authorization", format!("Key {}", &key))
|
||||
.header("Content-Type", "application/json")
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
@@ -141,10 +176,9 @@ impl<Params: Serialize, Response: DeserializeOwned> FalRequest<Params, Response>
|
||||
|
||||
let response = self
|
||||
.client
|
||||
.post(format!("https://queue.fal.run/{}", self.endpoint))
|
||||
.post(format!("{}/{}", self.queue_base_url, self.endpoint))
|
||||
.json(&self.params)
|
||||
.header("Authorization", format!("Key {}", &key))
|
||||
.header("Content-Type", "application/json")
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
@@ -155,10 +189,298 @@ impl<Params: Serialize, Response: DeserializeOwned> FalRequest<Params, Response>
|
||||
|
||||
let body = response.text().await?;
|
||||
|
||||
println!("Queue response: {}", body);
|
||||
debug!("Queue response: {}", body);
|
||||
|
||||
let payload: QueueResponse = serde_json::from_str(&body)?;
|
||||
|
||||
Ok(payload)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
use super::*;
|
||||
|
||||
const API_KEY: &str = "test-key-id:test-key-secret";
|
||||
const ENDPOINT: &str = "fal-ai/nano-banana-pro";
|
||||
const WEBHOOK_URL: &str = "https://example.com/v1/webhooks/fal";
|
||||
|
||||
const QUEUE_RESPONSE_BODY: &str = r#"{
|
||||
"status": "IN_QUEUE",
|
||||
"request_id": "01a082d7-767c-7fb3-bae3-ce9cd1d0a360",
|
||||
"response_url": "https://queue.fal.run/fal-ai/nano-banana-pro/requests/01a082d7",
|
||||
"status_url": "https://queue.fal.run/fal-ai/nano-banana-pro/requests/01a082d7/status",
|
||||
"cancel_url": "https://queue.fal.run/fal-ai/nano-banana-pro/requests/01a082d7/cancel"
|
||||
}"#;
|
||||
|
||||
const SYNC_RESPONSE_BODY: &str = r#"{"ok": true}"#;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct SyncOutput {
|
||||
ok: bool,
|
||||
}
|
||||
|
||||
/// Regression tests for the 2026-09-08 fal outage: a second `Content-Type` header made fal
|
||||
/// treat the JSON body as binary, failing every job with
|
||||
/// "Input should be a valid dictionary or object to extract fields from".
|
||||
mod single_content_type_header_tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn queue_sends_exactly_one_json_content_type() {
|
||||
let (base_url, captured) = spawn_capture_server(QUEUE_RESPONSE_BODY).await;
|
||||
|
||||
let queue = new_request()
|
||||
.with_queue_base_url(base_url)
|
||||
.queue()
|
||||
.await
|
||||
.expect("queue should succeed");
|
||||
|
||||
assert_eq!(queue.payload.request_id, "01a082d7-767c-7fb3-bae3-ce9cd1d0a360");
|
||||
assert_single_json_content_type_with_params(&captured.await.unwrap());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn queue_webhook_sends_exactly_one_json_content_type() {
|
||||
let (base_url, captured) = spawn_capture_server(QUEUE_RESPONSE_BODY).await;
|
||||
|
||||
let response = new_request()
|
||||
.with_queue_base_url(base_url)
|
||||
.queue_webhook(WEBHOOK_URL)
|
||||
.await
|
||||
.expect("queue_webhook should succeed");
|
||||
|
||||
assert_eq!(response.request_id.as_deref(), Some("01a082d7-767c-7fb3-bae3-ce9cd1d0a360"));
|
||||
|
||||
let raw = captured.await.unwrap();
|
||||
assert!(raw.request_line.contains("fal_webhook="), "webhook url missing: {}", raw.request_line);
|
||||
assert_single_json_content_type_with_params(&raw);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn queue_request_sends_exactly_one_json_content_type() {
|
||||
let (base_url, captured) = spawn_capture_server(QUEUE_RESPONSE_BODY).await;
|
||||
|
||||
let response = new_request()
|
||||
.with_queue_base_url(base_url)
|
||||
.queue_request()
|
||||
.await
|
||||
.expect("queue_request should succeed");
|
||||
|
||||
assert_eq!(response.request_id, "01a082d7-767c-7fb3-bae3-ce9cd1d0a360");
|
||||
assert_single_json_content_type_with_params(&captured.await.unwrap());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn send_sends_exactly_one_json_content_type() {
|
||||
let (base_url, captured) = spawn_capture_server(SYNC_RESPONSE_BODY).await;
|
||||
|
||||
let response = new_request()
|
||||
.with_sync_base_url(base_url)
|
||||
.send()
|
||||
.await
|
||||
.expect("send should succeed");
|
||||
|
||||
assert!(response.ok);
|
||||
assert_single_json_content_type_with_params(&captured.await.unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
/// Regression tests for the 2026-09-09 webhook silence: Fal ignores an unencoded
|
||||
/// `fal_webhook` value, so the callback URL must be percent-encoded in the query string.
|
||||
mod webhook_url_encoding_tests {
|
||||
use super::*;
|
||||
|
||||
const ENCODED_WEBHOOK_URL: &str = "https%3A%2F%2Fexample.com%2Fv1%2Fwebhooks%2Ffal";
|
||||
|
||||
#[tokio::test]
|
||||
async fn webhook_url_is_percent_encoded_in_query_string() {
|
||||
let (base_url, captured) = spawn_capture_server(QUEUE_RESPONSE_BODY).await;
|
||||
|
||||
new_request()
|
||||
.with_queue_base_url(base_url)
|
||||
.queue_webhook(WEBHOOK_URL)
|
||||
.await
|
||||
.expect("queue_webhook should succeed");
|
||||
|
||||
let raw = captured.await.unwrap();
|
||||
assert!(
|
||||
raw.request_line.contains(&format!("?fal_webhook={}", ENCODED_WEBHOOK_URL)),
|
||||
"webhook url not percent-encoded: {}", raw.request_line,
|
||||
);
|
||||
assert!(
|
||||
!raw.request_line.contains("fal_webhook=https://"),
|
||||
"webhook url sent raw: {}", raw.request_line,
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn encoded_webhook_url_decodes_back_to_the_original() {
|
||||
let (base_url, captured) = spawn_capture_server(QUEUE_RESPONSE_BODY).await;
|
||||
|
||||
new_request()
|
||||
.with_queue_base_url(base_url)
|
||||
.queue_webhook(WEBHOOK_URL)
|
||||
.await
|
||||
.expect("queue_webhook should succeed");
|
||||
|
||||
let raw = captured.await.unwrap();
|
||||
let path_and_query = raw.request_line.split_whitespace().nth(1).expect("request target");
|
||||
let parsed = Url::parse(&format!("http://localhost{}", path_and_query)).unwrap();
|
||||
let decoded = parsed.query_pairs()
|
||||
.find(|(k, _)| k == "fal_webhook")
|
||||
.map(|(_, v)| v.into_owned())
|
||||
.expect("fal_webhook param");
|
||||
assert_eq!(decoded, WEBHOOK_URL);
|
||||
}
|
||||
}
|
||||
|
||||
mod base_url_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn defaults_point_at_fal() {
|
||||
let request = new_request();
|
||||
assert_eq!(request.sync_base_url, "https://fal.run");
|
||||
assert_eq!(request.queue_base_url, "https://queue.fal.run");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn queue_path_is_base_url_plus_endpoint() {
|
||||
let (base_url, captured) = spawn_capture_server(QUEUE_RESPONSE_BODY).await;
|
||||
|
||||
new_request()
|
||||
.with_queue_base_url(base_url)
|
||||
.queue_request()
|
||||
.await
|
||||
.expect("queue_request should succeed");
|
||||
|
||||
let raw = captured.await.unwrap();
|
||||
assert!(
|
||||
raw.request_line.starts_with(&format!("POST /{} HTTP/1.1", ENDPOINT)),
|
||||
"unexpected request line: {}",
|
||||
raw.request_line
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Helpers ----
|
||||
|
||||
/// Everything the fake fal server observed on the wire.
|
||||
struct CapturedRequest {
|
||||
request_line: String,
|
||||
/// Header (name lowercased, value) pairs in wire order.
|
||||
headers: Vec<(String, String)>,
|
||||
body: String,
|
||||
}
|
||||
|
||||
fn new_request() -> FalRequest<Value, SyncOutput> {
|
||||
FalRequest::new(ENDPOINT, test_params()).with_api_key(API_KEY)
|
||||
}
|
||||
|
||||
fn test_params() -> Value {
|
||||
json!({
|
||||
"prompt": "a corgi wearing sunglasses at the beach",
|
||||
"num_images": 1,
|
||||
"output_format": "png"
|
||||
})
|
||||
}
|
||||
|
||||
fn assert_single_json_content_type_with_params(raw: &CapturedRequest) {
|
||||
let content_types: Vec<&str> = raw
|
||||
.headers
|
||||
.iter()
|
||||
.filter(|(name, _)| name == "content-type")
|
||||
.map(|(_, value)| value.as_str())
|
||||
.collect();
|
||||
|
||||
assert_eq!(
|
||||
content_types,
|
||||
vec!["application/json"],
|
||||
"expected exactly one Content-Type header, got {:?}",
|
||||
content_types
|
||||
);
|
||||
|
||||
let authorization = header_value(raw, "authorization");
|
||||
assert_eq!(authorization, Some(format!("Key {}", API_KEY)));
|
||||
|
||||
let body: Value = serde_json::from_str(&raw.body).expect("body must be JSON");
|
||||
assert!(body.is_object(), "fal requires a JSON object body, got {}", body);
|
||||
assert_eq!(body, test_params());
|
||||
}
|
||||
|
||||
fn header_value(raw: &CapturedRequest, name: &str) -> Option<String> {
|
||||
raw
|
||||
.headers
|
||||
.iter()
|
||||
.find(|(n, _)| n == name)
|
||||
.map(|(_, v)| v.clone())
|
||||
}
|
||||
|
||||
/// Bind a one-shot HTTP/1.1 server on localhost. It records the raw request it receives,
|
||||
/// replies `200 OK` with `response_body`, and hands the capture back through the JoinHandle.
|
||||
async fn spawn_capture_server(response_body: &'static str) -> (String, JoinHandle<CapturedRequest>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind localhost");
|
||||
let base_url = format!("http://{}", listener.local_addr().unwrap());
|
||||
|
||||
let handle = tokio::spawn(async move {
|
||||
let (mut socket, _) = listener.accept().await.expect("accept");
|
||||
|
||||
let mut buffer = Vec::new();
|
||||
let header_end = loop {
|
||||
let mut chunk = [0u8; 4096];
|
||||
let n = socket.read(&mut chunk).await.expect("read");
|
||||
assert!(n > 0, "connection closed before headers finished");
|
||||
buffer.extend_from_slice(&chunk[..n]);
|
||||
if let Some(pos) = find_header_end(&buffer) {
|
||||
break pos;
|
||||
}
|
||||
};
|
||||
|
||||
let head = String::from_utf8_lossy(&buffer[..header_end]).to_string();
|
||||
let mut lines = head.split("\r\n");
|
||||
let request_line = lines.next().unwrap_or_default().to_string();
|
||||
let headers: Vec<(String, String)> = lines
|
||||
.filter_map(|line| line.split_once(':'))
|
||||
.map(|(name, value)| (name.trim().to_ascii_lowercase(), value.trim().to_string()))
|
||||
.collect();
|
||||
|
||||
let content_length: usize = headers
|
||||
.iter()
|
||||
.find(|(name, _)| name == "content-length")
|
||||
.and_then(|(_, value)| value.parse().ok())
|
||||
.expect("reqwest sends Content-Length for a JSON body");
|
||||
|
||||
let body_start = header_end + 4;
|
||||
while buffer.len() < body_start + content_length {
|
||||
let mut chunk = [0u8; 4096];
|
||||
let n = socket.read(&mut chunk).await.expect("read body");
|
||||
assert!(n > 0, "connection closed before body finished");
|
||||
buffer.extend_from_slice(&chunk[..n]);
|
||||
}
|
||||
let body = String::from_utf8_lossy(&buffer[body_start..body_start + content_length]).to_string();
|
||||
|
||||
let response = format!(
|
||||
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
|
||||
response_body.len(),
|
||||
response_body
|
||||
);
|
||||
socket.write_all(response.as_bytes()).await.expect("write response");
|
||||
socket.shutdown().await.ok();
|
||||
|
||||
CapturedRequest { request_line, headers, body }
|
||||
});
|
||||
|
||||
(base_url, handle)
|
||||
}
|
||||
|
||||
fn find_header_end(buffer: &[u8]) -> Option<usize> {
|
||||
buffer.windows(4).position(|window| window == b"\r\n\r\n")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
# support-tool
|
||||
|
||||
Production support CLI for debugging and manual operations against external services.
|
||||
|
||||
## Building & Running
|
||||
|
||||
```bash
|
||||
cargo build -p support-tool
|
||||
cargo run -p support-tool -- kinovi_web generate_video --prompt "A corgi at the lake"
|
||||
```
|
||||
|
||||
## Environment
|
||||
|
||||
Requires a `.env-support-tool-secrets` file (or env vars) with:
|
||||
|
||||
- `SEEDANCE2PRO_COOKIES` — session cookies for Kinovi/KinoviWeb API auth
|
||||
- `ARTCRAFT_COOKIES` — session cookies for ArtCraft API auth (format: `session=...; visitor=...`)
|
||||
|
||||
## Architecture
|
||||
|
||||
- Entry point: `src/main.rs` → normalizes args (underscores optional) → dispatches
|
||||
- Top-level commands in `src/commands/run.rs` (`TopLevelCommand` enum)
|
||||
- Each top-level command has its own module with `dispatch.rs`, `state.rs`, `subcommands/`
|
||||
- Subcommands use `#[derive(Args)]` for their argument structs
|
||||
- All subcommand `run()` functions are `async fn` returning `anyhow::Result<()>`
|
||||
|
||||
## Adding a New Subcommand (to kinovi_web)
|
||||
|
||||
1. Create `src/commands/kinovi_web/subcommands/my_command.rs`
|
||||
2. Add `pub mod my_command;` to `subcommands/mod.rs`
|
||||
3. Add the name to `SUBCOMMAND_NAMES` in `dispatch.rs`
|
||||
4. Add a variant to `KinoviWebCommand` enum in `dispatch.rs`
|
||||
5. Add a match arm in `dispatch.rs::run()`
|
||||
|
||||
## Utilities
|
||||
|
||||
- `src/utils/parse_video_model.rs` — shared parser for loose video model names → `CommonVideoModel`
|
||||
- `src/utils/normalize_subcommands.rs` — underscore-insensitive arg normalizer
|
||||
|
||||
## Conventions
|
||||
|
||||
- Use `log::info!()` for status output, never `println!` (except for final results)
|
||||
- Use `anyhow::anyhow!()` for ad-hoc errors
|
||||
- Get `KinoviWebSession` from `state.cookies` via `from_cookies_string()`
|
||||
- Get `StorytellerCredentialSet` from `state.creds` (parsed from ARTCRAFT_COOKIES)
|
||||
- External crates used: `artcraft_client` (media file download, omni API), `kinovi_web_client` (Kinovi direct), `artcraft_api_defs` (request types)
|
||||
|
||||
## Subcommands
|
||||
|
||||
### kinovi_web (direct Kinovi API)
|
||||
|
||||
- `kinovi_web find_job --token <order_id>` — search for a job across all pages
|
||||
- `kinovi_web failed_job_histogram` — histogram of failure reasons
|
||||
- `kinovi_web generate_video --prompt <text_or_file> [--model seedance2p0] [--start_frame_media_token mf_xxx] [--localhost] [--download_path /tmp/media_files]`
|
||||
|
||||
### artcraft (omni API)
|
||||
|
||||
- `artcraft generate_video --prompt <text_or_file> [--model seedance2p0] [--start_frame_media_token mf_xxx] [--duration 5] [--localhost]`
|
||||
@@ -1,58 +0,0 @@
|
||||
# support-tool
|
||||
|
||||
Production support CLI for debugging and manual operations against external services.
|
||||
|
||||
## Building & Running
|
||||
|
||||
```bash
|
||||
cargo build -p support-tool
|
||||
cargo run -p support-tool -- kinovi_web generate_video --prompt "A corgi at the lake"
|
||||
```
|
||||
|
||||
## Environment
|
||||
|
||||
Requires a `.env-support-tool-secrets` file (or env vars) with:
|
||||
|
||||
- `SEEDANCE2PRO_COOKIES` — session cookies for Kinovi/KinoviWeb API auth
|
||||
- `ARTCRAFT_COOKIES` — session cookies for ArtCraft API auth (format: `session=...; visitor=...`)
|
||||
|
||||
## Architecture
|
||||
|
||||
- Entry point: `src/main.rs` → normalizes args (underscores optional) → dispatches
|
||||
- Top-level commands in `src/commands/run.rs` (`TopLevelCommand` enum)
|
||||
- Each top-level command has its own module with `dispatch.rs`, `state.rs`, `subcommands/`
|
||||
- Subcommands use `#[derive(Args)]` for their argument structs
|
||||
- All subcommand `run()` functions are `async fn` returning `anyhow::Result<()>`
|
||||
|
||||
## Adding a New Subcommand (to kinovi_web)
|
||||
|
||||
1. Create `src/commands/kinovi_web/subcommands/my_command.rs`
|
||||
2. Add `pub mod my_command;` to `subcommands/mod.rs`
|
||||
3. Add the name to `SUBCOMMAND_NAMES` in `dispatch.rs`
|
||||
4. Add a variant to `KinoviWebCommand` enum in `dispatch.rs`
|
||||
5. Add a match arm in `dispatch.rs::run()`
|
||||
|
||||
## Utilities
|
||||
|
||||
- `src/utils/parse_video_model.rs` — shared parser for loose video model names → `CommonVideoModel`
|
||||
- `src/utils/normalize_subcommands.rs` — underscore-insensitive arg normalizer
|
||||
|
||||
## Conventions
|
||||
|
||||
- Use `log::info!()` for status output, never `println!` (except for final results)
|
||||
- Use `anyhow::anyhow!()` for ad-hoc errors
|
||||
- Get `KinoviWebSession` from `state.cookies` via `from_cookies_string()`
|
||||
- Get `StorytellerCredentialSet` from `state.creds` (parsed from ARTCRAFT_COOKIES)
|
||||
- External crates used: `artcraft_client` (media file download, omni API), `kinovi_web_client` (Kinovi direct), `artcraft_api_defs` (request types)
|
||||
|
||||
## Subcommands
|
||||
|
||||
### kinovi_web (direct Kinovi API)
|
||||
|
||||
- `kinovi_web find_job --token <order_id>` — search for a job across all pages
|
||||
- `kinovi_web failed_job_histogram` — histogram of failure reasons
|
||||
- `kinovi_web generate_video --prompt <text_or_file> [--model seedance2p0] [--start_frame_media_token mf_xxx] [--localhost] [--download_path /tmp/media_files]`
|
||||
|
||||
### artcraft (omni API)
|
||||
|
||||
- `artcraft generate_video --prompt <text_or_file> [--model seedance2p0] [--start_frame_media_token mf_xxx] [--duration 5] [--localhost]`
|
||||
@@ -0,0 +1 @@
|
||||
AGENTS.md
|
||||
+2
@@ -14,6 +14,8 @@ pub fn tauri_image_model_to_common_model_type(model: TauriImageModel) -> CommonM
|
||||
TauriImageModel::GptImage1 => CommonModelType::GptImage1,
|
||||
TauriImageModel::GptImage1p5 => CommonModelType::GptImage1p5,
|
||||
TauriImageModel::GptImage2 => CommonModelType::GptImage2,
|
||||
TauriImageModel::GptImage2p5Flare => CommonModelType::GptImage2p5Flare,
|
||||
TauriImageModel::GptImage2p5Sunburst => CommonModelType::GptImage2p5Sunburst,
|
||||
TauriImageModel::Gemini25Flash => CommonModelType::NanoBanana,
|
||||
TauriImageModel::NanoBanana => CommonModelType::NanoBanana,
|
||||
TauriImageModel::NanoBanana2 => CommonModelType::NanoBanana2,
|
||||
|
||||
+2
@@ -14,6 +14,8 @@ pub fn tauri_image_model_to_enums_model(model: TauriImageModel) -> Option<Common
|
||||
TauriImageModel::GptImage1 => Some(CommonImageModel::GptImage1),
|
||||
TauriImageModel::GptImage1p5 => Some(CommonImageModel::GptImage1p5),
|
||||
TauriImageModel::GptImage2 => Some(CommonImageModel::GptImage2),
|
||||
TauriImageModel::GptImage2p5Flare => Some(CommonImageModel::GptImage2p5Flare),
|
||||
TauriImageModel::GptImage2p5Sunburst => Some(CommonImageModel::GptImage2p5Sunburst),
|
||||
TauriImageModel::NanoBanana => Some(CommonImageModel::NanoBanana),
|
||||
TauriImageModel::NanoBanana2 => Some(CommonImageModel::NanoBanana2),
|
||||
TauriImageModel::NanoBananaPro => Some(CommonImageModel::NanoBananaPro),
|
||||
|
||||
+2
@@ -13,6 +13,8 @@ pub fn tauri_image_model_to_generation_model(model: TauriImageModel) -> Generati
|
||||
TauriImageModel::GptImage1 => GenerationModel::GptImage1,
|
||||
TauriImageModel::GptImage1p5 => GenerationModel::GptImage1p5,
|
||||
TauriImageModel::GptImage2 => GenerationModel::GptImage2,
|
||||
TauriImageModel::GptImage2p5Flare => GenerationModel::GptImage2p5Flare,
|
||||
TauriImageModel::GptImage2p5Sunburst => GenerationModel::GptImage2p5Sunburst,
|
||||
TauriImageModel::Gemini25Flash => GenerationModel::NanoBanana,
|
||||
TauriImageModel::NanoBanana => GenerationModel::NanoBanana,
|
||||
TauriImageModel::NanoBanana2 => GenerationModel::NanoBanana2,
|
||||
|
||||
+2
@@ -14,6 +14,8 @@ pub fn tauri_image_model_to_router_model(model: TauriImageModel) -> Option<Route
|
||||
TauriImageModel::GptImage1 => Some(RouterImageModel::GptImage1), // Text-to-Image
|
||||
TauriImageModel::GptImage1p5 => Some(RouterImageModel::GptImage1p5), // Text-to-Image
|
||||
TauriImageModel::GptImage2 => Some(RouterImageModel::GptImage2), // Text-to-Image
|
||||
TauriImageModel::GptImage2p5Flare => Some(RouterImageModel::GptImage2p5Flare), // Text-to-Image
|
||||
TauriImageModel::GptImage2p5Sunburst => Some(RouterImageModel::GptImage2p5Sunburst), // Text-to-Image
|
||||
TauriImageModel::NanoBanana => Some(RouterImageModel::NanoBanana), // Text-to-Image
|
||||
TauriImageModel::NanoBanana2 => Some(RouterImageModel::NanoBanana2), // Text-to-Image
|
||||
TauriImageModel::NanoBananaPro => Some(RouterImageModel::NanoBananaPro), // Text-to-Image
|
||||
|
||||
@@ -85,6 +85,8 @@ impl TaskEnqueueSuccess{
|
||||
Some(GenerationModel::GptImage1) => Some(TaskModelType::GptImage1),
|
||||
Some(GenerationModel::GptImage1p5) => Some(TaskModelType::GptImage1p5),
|
||||
Some(GenerationModel::GptImage2) => Some(TaskModelType::GptImage2),
|
||||
Some(GenerationModel::GptImage2p5Flare) => Some(TaskModelType::GptImage2p5Flare),
|
||||
Some(GenerationModel::GptImage2p5Sunburst) => Some(TaskModelType::GptImage2p5Sunburst),
|
||||
Some(GenerationModel::Seedream4) => Some(TaskModelType::Seedream4),
|
||||
Some(GenerationModel::Seedream4p5) => Some(TaskModelType::Seedream4p5),
|
||||
Some(GenerationModel::Seedream5Lite) => Some(TaskModelType::Seedream5Lite),
|
||||
|
||||
+2
@@ -48,6 +48,8 @@ fn image_model_to_common_model_type(model: RouterImageModel) -> Option<CommonMod
|
||||
RouterImageModel::GptImage1 => Some(CommonModelType::GptImage1),
|
||||
RouterImageModel::GptImage1p5 => Some(CommonModelType::GptImage1p5),
|
||||
RouterImageModel::GptImage2 => Some(CommonModelType::GptImage2),
|
||||
RouterImageModel::GptImage2p5Flare => Some(CommonModelType::GptImage2p5Flare),
|
||||
RouterImageModel::GptImage2p5Sunburst => Some(CommonModelType::GptImage2p5Sunburst),
|
||||
RouterImageModel::NanoBanana => Some(CommonModelType::NanoBanana),
|
||||
RouterImageModel::NanoBanana2 => Some(CommonModelType::NanoBanana2),
|
||||
RouterImageModel::NanoBananaPro => Some(CommonModelType::NanoBananaPro),
|
||||
|
||||
@@ -32,6 +32,10 @@ pub enum TauriImageModel {
|
||||
GptImage1p5,
|
||||
#[serde(rename = "gpt_image_2")]
|
||||
GptImage2,
|
||||
#[serde(rename = "gpt_image_2p5_flare")]
|
||||
GptImage2p5Flare,
|
||||
#[serde(rename = "gpt_image_2p5_sunburst")]
|
||||
GptImage2p5Sunburst,
|
||||
#[serde(rename = "gemini_25_flash")]
|
||||
Gemini25Flash,
|
||||
#[serde(rename = "nano_banana")]
|
||||
|
||||
@@ -191,6 +191,8 @@ pub enum ListImageModelsImageModel {
|
||||
GptImage1p5,
|
||||
GptImage2,
|
||||
GrokImagineImage,
|
||||
GptImage2p5Flare,
|
||||
GptImage2p5Sunburst,
|
||||
GrokImagineImageQuality,
|
||||
Midjourney7,
|
||||
Midjourney7Niji,
|
||||
@@ -216,6 +218,8 @@ impl From<ApiClientImageModel> for ListImageModelsImageModel {
|
||||
ApiClientImageModel::GptImage1 => Self::GptImage1,
|
||||
ApiClientImageModel::GptImage1p5 => Self::GptImage1p5,
|
||||
ApiClientImageModel::GptImage2 => Self::GptImage2,
|
||||
ApiClientImageModel::GptImage2p5Flare => Self::GptImage2p5Flare,
|
||||
ApiClientImageModel::GptImage2p5Sunburst => Self::GptImage2p5Sunburst,
|
||||
ApiClientImageModel::GrokImagineImage => Self::GrokImagineImage,
|
||||
ApiClientImageModel::GrokImagineImageQuality => Self::GrokImagineImageQuality,
|
||||
ApiClientImageModel::Midjourney7 => Self::Midjourney7,
|
||||
@@ -244,6 +248,8 @@ impl From<ListImageModelsImageModel> for String {
|
||||
ListImageModelsImageModel::GptImage1 => "gpt_image_1".to_string(),
|
||||
ListImageModelsImageModel::GptImage1p5 => "gpt_image_1p5".to_string(),
|
||||
ListImageModelsImageModel::GptImage2 => "gpt_image_2".to_string(),
|
||||
ListImageModelsImageModel::GptImage2p5Flare => "gpt_image_2p5_flare".to_string(),
|
||||
ListImageModelsImageModel::GptImage2p5Sunburst => "gpt_image_2p5_sunburst".to_string(),
|
||||
ListImageModelsImageModel::GrokImagineImage => "grok_imagine_image".to_string(),
|
||||
ListImageModelsImageModel::GrokImagineImageQuality => "grok_imagine_image_q".to_string(),
|
||||
ListImageModelsImageModel::Midjourney7 => "midjourney_7".to_string(),
|
||||
|
||||
@@ -43,6 +43,10 @@ pub enum GenerationModel {
|
||||
GptImage1p5,
|
||||
#[serde(rename = "gpt_image_2")]
|
||||
GptImage2,
|
||||
#[serde(rename = "gpt_image_2p5_flare")]
|
||||
GptImage2p5Flare,
|
||||
#[serde(rename = "gpt_image_2p5_sunburst")]
|
||||
GptImage2p5Sunburst,
|
||||
#[serde(rename = "grok_image")]
|
||||
GrokImage,
|
||||
#[serde(rename = "gemini_25_flash")]
|
||||
|
||||
+2
@@ -298,6 +298,8 @@ fn task_model_type_to_generation_model(model: TaskModelType) -> Option<Generatio
|
||||
TaskModelType::GptImage1 => Some(GenerationModel::GptImage1),
|
||||
TaskModelType::GptImage1p5 => Some(GenerationModel::GptImage1p5),
|
||||
TaskModelType::GptImage2 => Some(GenerationModel::GptImage2),
|
||||
TaskModelType::GptImage2p5Flare => Some(GenerationModel::GptImage2p5Flare),
|
||||
TaskModelType::GptImage2p5Sunburst => Some(GenerationModel::GptImage2p5Sunburst),
|
||||
TaskModelType::NanoBanana => Some(GenerationModel::NanoBanana),
|
||||
TaskModelType::NanoBanana2 => Some(GenerationModel::NanoBanana2),
|
||||
TaskModelType::NanoBananaPro => Some(GenerationModel::NanoBananaPro),
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
# Pager Crate
|
||||
|
||||
Alerting/paging system that sends notifications via Rootly.
|
||||
|
||||
## Key Types
|
||||
|
||||
- `Pager` - Main client, cloneable. Has `enqueue_page()` and `shutdown_worker()`
|
||||
- `PagerBuilder` - Constructs a Pager with optional background worker
|
||||
- `NotificationDetails` - Alert payload with title, description, urgency, HTTP context, entity tokens
|
||||
- `NotificationDetailsBuilder` - Fluent builder for constructing notifications
|
||||
- `NotificationUrgency` - High, Medium, Low
|
||||
|
||||
## Building Notifications
|
||||
|
||||
```rust
|
||||
let notification = NotificationDetailsBuilder::from_title("Something happened".to_string())
|
||||
.set_description(Some("Details...".to_string()))
|
||||
.set_urgency(Some(NotificationUrgency::High))
|
||||
.set_http_method(Some("POST".to_string()))
|
||||
.set_http_path(Some("/v1/endpoint".to_string()))
|
||||
.set_inference_job_token(Some(job_token.to_string()))
|
||||
.build();
|
||||
```
|
||||
|
||||
For errors, use `from_error()` which auto-populates title and description from the error:
|
||||
|
||||
```rust
|
||||
NotificationDetailsBuilder::from_error(&err)
|
||||
.set_title("Custom title".to_string())
|
||||
.set_urgency(Some(NotificationUrgency::Medium))
|
||||
.build()
|
||||
```
|
||||
|
||||
## Deduplication
|
||||
|
||||
`NotificationDetails::to_deduplication_key()` generates a SHA-256 hash for dedup. Same title + HTTP context + hour = same key.
|
||||
|
||||
## Worker Thread
|
||||
|
||||
The pager worker uses `Condvar::wait()` (blocking). It MUST run on a dedicated OS thread, not a tokio task.
|
||||
@@ -1,40 +0,0 @@
|
||||
# Pager Crate
|
||||
|
||||
Alerting/paging system that sends notifications via Rootly.
|
||||
|
||||
## Key Types
|
||||
|
||||
- `Pager` - Main client, cloneable. Has `enqueue_page()` and `shutdown_worker()`
|
||||
- `PagerBuilder` - Constructs a Pager with optional background worker
|
||||
- `NotificationDetails` - Alert payload with title, description, urgency, HTTP context, entity tokens
|
||||
- `NotificationDetailsBuilder` - Fluent builder for constructing notifications
|
||||
- `NotificationUrgency` - High, Medium, Low
|
||||
|
||||
## Building Notifications
|
||||
|
||||
```rust
|
||||
let notification = NotificationDetailsBuilder::from_title("Something happened".to_string())
|
||||
.set_description(Some("Details...".to_string()))
|
||||
.set_urgency(Some(NotificationUrgency::High))
|
||||
.set_http_method(Some("POST".to_string()))
|
||||
.set_http_path(Some("/v1/endpoint".to_string()))
|
||||
.set_inference_job_token(Some(job_token.to_string()))
|
||||
.build();
|
||||
```
|
||||
|
||||
For errors, use `from_error()` which auto-populates title and description from the error:
|
||||
|
||||
```rust
|
||||
NotificationDetailsBuilder::from_error(&err)
|
||||
.set_title("Custom title".to_string())
|
||||
.set_urgency(Some(NotificationUrgency::Medium))
|
||||
.build()
|
||||
```
|
||||
|
||||
## Deduplication
|
||||
|
||||
`NotificationDetails::to_deduplication_key()` generates a SHA-256 hash for dedup. Same title + HTTP context + hour = same key.
|
||||
|
||||
## Worker Thread
|
||||
|
||||
The pager worker uses `Condvar::wait()` (blocking). It MUST run on a dedicated OS thread, not a tokio task.
|
||||
Symlink
+1
@@ -0,0 +1 @@
|
||||
AGENTS.md
|
||||
@@ -0,0 +1,79 @@
|
||||
# mysql_queries
|
||||
|
||||
SQLx-based MySQL queries for the storyteller-web backend and background jobs.
|
||||
|
||||
## Building
|
||||
|
||||
```
|
||||
SQLX_OFFLINE=true cargo check -p mysql_queries
|
||||
```
|
||||
|
||||
The `SQLX_OFFLINE=true` env var is **required** for compilation. This crate uses the sqlx
|
||||
offline cache (`.sqlx/` directory at the workspace root) to validate queries at compile time
|
||||
without a live database connection.
|
||||
|
||||
## Query Style
|
||||
|
||||
### Prefer `sqlx::query!` and `sqlx::query_as!` macros
|
||||
|
||||
Always use the compile-time checked `sqlx::query!` and `sqlx::query_as!` macros over the
|
||||
runtime `sqlx::query()` and `sqlx::query_as()` functions. The macros validate SQL syntax,
|
||||
column names, and parameter types against the offline cache at compile time.
|
||||
|
||||
```rust
|
||||
// PREFERRED: compile-time checked
|
||||
sqlx::query!(
|
||||
r#"INSERT INTO my_table SET token = ?, name = ?"#,
|
||||
token,
|
||||
name,
|
||||
)
|
||||
.execute(args.mysql_executor)
|
||||
.await?;
|
||||
|
||||
// AVOID: runtime only, no compile-time checking
|
||||
sqlx::query(r#"INSERT INTO my_table SET token = ?, name = ?"#)
|
||||
.bind(token)
|
||||
.bind(name)
|
||||
.execute(args.mysql_executor)
|
||||
.await?;
|
||||
```
|
||||
|
||||
Use runtime `sqlx::query()` only when:
|
||||
- The query involves a table not yet in the offline cache and you cannot run `cargo sqlx prepare`
|
||||
- The query is dynamically constructed (rare)
|
||||
- SELECT queries for new tables where column type metadata isn't cached yet
|
||||
|
||||
### Offline Cache
|
||||
|
||||
When adding new queries for **existing tables**, the `.sqlx/` cache should already have the
|
||||
schema metadata. For **new tables**, you may need to:
|
||||
|
||||
1. Run the migration against a real database
|
||||
2. Run `cargo sqlx prepare` to regenerate the cache
|
||||
3. Or manually create cache entries for simple INSERT/UPDATE queries (they only need parameter count)
|
||||
|
||||
### 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`.
|
||||
|
||||
### Error Types
|
||||
|
||||
New queries should return `Result<T, sqlx::Error>` instead of the legacy `AnyhowResult<T>`.
|
||||
The `AnyhowResult` pattern is being phased out.
|
||||
|
||||
### Transaction Support
|
||||
|
||||
Use the executor-generic `Args` pattern for queries that need to work inside transactions:
|
||||
|
||||
```rust
|
||||
pub struct MyQueryArgs<'a, 'c: 'a, E>
|
||||
where E: 'a + Executor<'c, Database = MySql>
|
||||
{
|
||||
pub field: &'a str,
|
||||
pub mysql_executor: E,
|
||||
pub phantom: PhantomData<&'c E>,
|
||||
}
|
||||
```
|
||||
|
||||
This allows the same query function to accept both `&MySqlPool` and `&mut Transaction`.
|
||||
@@ -1,79 +0,0 @@
|
||||
# mysql_queries
|
||||
|
||||
SQLx-based MySQL queries for the storyteller-web backend and background jobs.
|
||||
|
||||
## Building
|
||||
|
||||
```
|
||||
SQLX_OFFLINE=true cargo check -p mysql_queries
|
||||
```
|
||||
|
||||
The `SQLX_OFFLINE=true` env var is **required** for compilation. This crate uses the sqlx
|
||||
offline cache (`.sqlx/` directory at the workspace root) to validate queries at compile time
|
||||
without a live database connection.
|
||||
|
||||
## Query Style
|
||||
|
||||
### Prefer `sqlx::query!` and `sqlx::query_as!` macros
|
||||
|
||||
Always use the compile-time checked `sqlx::query!` and `sqlx::query_as!` macros over the
|
||||
runtime `sqlx::query()` and `sqlx::query_as()` functions. The macros validate SQL syntax,
|
||||
column names, and parameter types against the offline cache at compile time.
|
||||
|
||||
```rust
|
||||
// PREFERRED: compile-time checked
|
||||
sqlx::query!(
|
||||
r#"INSERT INTO my_table SET token = ?, name = ?"#,
|
||||
token,
|
||||
name,
|
||||
)
|
||||
.execute(args.mysql_executor)
|
||||
.await?;
|
||||
|
||||
// AVOID: runtime only, no compile-time checking
|
||||
sqlx::query(r#"INSERT INTO my_table SET token = ?, name = ?"#)
|
||||
.bind(token)
|
||||
.bind(name)
|
||||
.execute(args.mysql_executor)
|
||||
.await?;
|
||||
```
|
||||
|
||||
Use runtime `sqlx::query()` only when:
|
||||
- The query involves a table not yet in the offline cache and you cannot run `cargo sqlx prepare`
|
||||
- The query is dynamically constructed (rare)
|
||||
- SELECT queries for new tables where column type metadata isn't cached yet
|
||||
|
||||
### Offline Cache
|
||||
|
||||
When adding new queries for **existing tables**, the `.sqlx/` cache should already have the
|
||||
schema metadata. For **new tables**, you may need to:
|
||||
|
||||
1. Run the migration against a real database
|
||||
2. Run `cargo sqlx prepare` to regenerate the cache
|
||||
3. Or manually create cache entries for simple INSERT/UPDATE queries (they only need parameter count)
|
||||
|
||||
### 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`.
|
||||
|
||||
### Error Types
|
||||
|
||||
New queries should return `Result<T, sqlx::Error>` instead of the legacy `AnyhowResult<T>`.
|
||||
The `AnyhowResult` pattern is being phased out.
|
||||
|
||||
### Transaction Support
|
||||
|
||||
Use the executor-generic `Args` pattern for queries that need to work inside transactions:
|
||||
|
||||
```rust
|
||||
pub struct MyQueryArgs<'a, 'c: 'a, E>
|
||||
where E: 'a + Executor<'c, Database = MySql>
|
||||
{
|
||||
pub field: &'a str,
|
||||
pub mysql_executor: E,
|
||||
pub phantom: PhantomData<&'c E>,
|
||||
}
|
||||
```
|
||||
|
||||
This allows the same query function to accept both `&MySqlPool` and `&mut Transaction`.
|
||||
@@ -0,0 +1 @@
|
||||
AGENTS.md
|
||||
@@ -0,0 +1,26 @@
|
||||
# Enums Crate
|
||||
|
||||
Database-backed enums stored as VARCHAR fields in MySQL.
|
||||
|
||||
## Adding a New Enum
|
||||
|
||||
1. Create file: `src/by_table/{table_name}/{field_name}.rs`
|
||||
2. Define the enum with required derives:
|
||||
```rust
|
||||
#[cfg_attr(test, derive(EnumIter, EnumCount))]
|
||||
#[derive(Clone, Copy, Eq, PartialEq, Hash, Ord, PartialOrd, Deserialize, Serialize, ToSchema)]
|
||||
pub enum MyEnum { ... }
|
||||
```
|
||||
3. Implement `to_str()` and `from_str()` manually
|
||||
4. Add macros: `impl_enum_display_and_debug_using_to_str!(MyEnum);` and `impl_mysql_enum_coders!(MyEnum);`
|
||||
5. Add to parent `mod.rs`
|
||||
6. Write tests: serialization, round-trip, `all_variants()` count
|
||||
|
||||
## Rules
|
||||
|
||||
- **NEVER change existing variant string values** - they are stored in the database
|
||||
- New variants CAN be added freely - but be very careful about the Tauri API callers
|
||||
ingesting new values. Make sure to pair the client with variants with an "Unknown(String)"
|
||||
catch-all / future-proof bucket.
|
||||
- All string values must be snake_case
|
||||
- Use `#[serde(rename = "snake_case_value")]` on each variant
|
||||
@@ -1,26 +0,0 @@
|
||||
# Enums Crate
|
||||
|
||||
Database-backed enums stored as VARCHAR fields in MySQL.
|
||||
|
||||
## Adding a New Enum
|
||||
|
||||
1. Create file: `src/by_table/{table_name}/{field_name}.rs`
|
||||
2. Define the enum with required derives:
|
||||
```rust
|
||||
#[cfg_attr(test, derive(EnumIter, EnumCount))]
|
||||
#[derive(Clone, Copy, Eq, PartialEq, Hash, Ord, PartialOrd, Deserialize, Serialize, ToSchema)]
|
||||
pub enum MyEnum { ... }
|
||||
```
|
||||
3. Implement `to_str()` and `from_str()` manually
|
||||
4. Add macros: `impl_enum_display_and_debug_using_to_str!(MyEnum);` and `impl_mysql_enum_coders!(MyEnum);`
|
||||
5. Add to parent `mod.rs`
|
||||
6. Write tests: serialization, round-trip, `all_variants()` count
|
||||
|
||||
## Rules
|
||||
|
||||
- **NEVER change existing variant string values** - they are stored in the database
|
||||
- New variants CAN be added freely - but be very careful about the Tauri API callers
|
||||
ingesting new values. Make sure to pair the client with variants with an "Unknown(String)"
|
||||
catch-all / future-proof bucket.
|
||||
- All string values must be snake_case
|
||||
- Use `#[serde(rename = "snake_case_value")]` on each variant
|
||||
+1
@@ -0,0 +1 @@
|
||||
AGENTS.md
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user