Compare commits

..
Author SHA1 Message Date
Brandon Thomas a1795e2b94 move assets out of build 2026-07-02 01:10:15 -04:00
Brandon Thomas 9de8fb8979 tauri frontend - read from omni api (#1710) 2026-07-01 23:20:11 -04:00
Brandon Thomas a61fcd50ed tauri omni client (#1709) 2026-07-01 16:31:23 -04:00
Brandon Thomas c16db8793c dashboard - change icon; group sidebar (#1708) 2026-06-30 11:05:18 -04:00
Brandon Thomas b3311d1574 payment informatics 4 (#1707) 2026-06-30 10:40:28 -04:00
Brandon Thomas 35add74498 payment informatics 3 (#1706) 2026-06-30 08:19:52 -04:00
Brandon Thomas d99da56df0 payment informatics #2 (#1705) 2026-06-29 21:21:26 -04:00
Brandon Thomas 3e4f998599 payments informatics (part 1) (#1704) 2026-06-29 17:49:28 -04:00
Brandon Thomas 3bccac5b2e block usernames that look like tokens (#1703) 2026-06-27 19:47:56 -04:00
Brandon Thomas aa9e862ff2 grok fixes (#1702) 2026-06-27 13:52:51 -04:00
BFlat db871126df Webapp/website (promptbox): full editing controls in fullscreen focus mode (#1701)
Add a footer to the fullscreen prompt modal (desktop lib + webapp) so
focus mode is a complete editing surface, not just the textarea:

- Model selector, always-on reference-image row, and a Done button
  (closes the modal) instead of Generate.
- Video: also surfaces the input-mode (keyframe/reference) picker and
  the @Characters button (seedance_2p0). Shared image-row / character /
  input-mode elements are reused inline and in the modal (DRY).
- Webapp: model selector + leftToolbar + image row in the footer.

Layout: editor area is flex-1/min-h-0/overflow-hidden with the image row
and footer shrink-0, so the editor takes only the leftover space and
scrolls internally — resizing the window shorter no longer overflows.
MentionTextarea gains a `style` prop so the modal can cap resize/height.
2026-06-26 23:16:35 +07:00
BFlat aaff33955e Webapp/website: Promptbox fullscreen "focus mode" + 3D & tooltip fixes (#1700)
### Fullscreen focus mode (desktop + webapp)
- Added a top-right expand icon on every prompt editor that opens a
"Prompt" focus-mode overlay (blurred backdrop, `max-w-4xl` centered
card) for more prompting space.
- Same editor state — overlay binds to the same value + onChange, so
text/@-mentions persist. Auto-focuses with the caret at the end on open.
- Editor fills full height; @-mention dropdown no longer clipped; closes
on Esc / backdrop click.
- Reused `@storyteller/ui-modal`; shared `PromptFullscreenModal` +
button + `useFullscreenPrompt` hook across all 5 desktop promptboxes,
mirrored in the webapp's own PromptBox.

### 3D editor
- Model selector now renders inside the promptbox (was standalone on the
canvas).
- Pose button hides on deselect; pressing "Done" keeps it (flips back to
"Enter Pose Mode") while the character is still selected.
- Drag and drop into folders fix within gallery modal - doesn't close
immediately unless on 3D editor page.

### Tooltips & expand
- Fixed top-left menu tooltips getting stuck open after a tab change.
- Reworked image promptbox auto-grow/expand into a shared
`useAutoGrowEditorHeight` hook (no per-render style writes) with a
smooth height transition.
2026-06-26 21:54:29 +07:00
Tanish Manku ad5ae7968f Fix login modal: stop Reveal motion wrappers from stealing input focus (#1698)
Reveal/RevealGroup called `motion(as)` inside the render body. Unlike
the cached `motion.div` accessor, calling `motion()` as a function
returns a brand-new component type on every invocation. So each
re-render produced a different element type at that position, React
unmounted and remounted the whole subtree, and any focused <input>
inside (the login/signup/forgot-password forms) lost focus on every
keystroke — you could only type one character at a time.

Cache one motion component per element type via a module-level map so
the component reference stays stable across renders. React now
reconciles in place and focus is preserved.

Verified with a Playwright A/B test on the login form: before the fix
typing "test@example.com" left only "t" with focus on <body> (1 blur
mid-type); after the fix the full value is retained, focus stays on the
input, zero blurs.
2026-06-25 13:48:53 -07:00
Brandon Thomas fef83ad271 mini models in api gateway (#1697) 2026-06-25 15:33:51 -04:00
BFlatandClaude 864cfb5faf Fix image refs not attaching when selected from a folder in gallery modal (#1696)
handleUseSelected only searched groupedItems (root library), so picks
made
while browsing inside a folder — which live in folderGroupedItems —
resolved
to nothing and an empty array was passed to onUseSelected. Search both
sources, deduping by id, so folder selections attach correctly.

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-25 20:38:53 +07:00
Brandon Thomas 2aed062790 seedance mini client (#1695) 2026-06-25 07:45:25 -04:00
Brandon Thomas 4d5f8e9c21 router 4k (#1693) 2026-06-24 17:18:37 -04:00
Brandon Thomas 98f9504bdd video models list refactor (#1692) 2026-06-24 13:56:56 -04:00
Brandon Thomas 7ff72d2ecc seedance 4k (#1691) 2026-06-24 12:45:11 -04:00
bflatastic 10eb062b6f seedance 2.1 -> 2.5 text + uncomment sidebar edit page 2026-06-24 22:52:32 +07:00
Brandon Thomas 3b225a7c6d omni api: status endpoint, api docs, etc (#1690) 2026-06-24 00:24:26 -04:00
435 changed files with 20901 additions and 2654 deletions
@@ -0,0 +1,25 @@
{
"db_name": "MySQL",
"query": "\nSELECT token AS `token: UserToken`\nFROM users\nWHERE email_address = ?\nLIMIT 1\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "token: UserToken",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | UNIQUE_KEY | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 128
}
}
],
"parameters": {
"Right": 1
},
"nullable": [
false
]
},
"hash": "0d2eadc64240b9ce5348b3b238b0ae6229df21697c952b08e930d03f97414cf4"
}
@@ -0,0 +1,58 @@
{
"db_name": "MySQL",
"query": "\nSELECT\n payment_occurred_at AS `payment_occurred_at!: DateTime<Utc>`,\n amount_usd_cents,\n event_type AS `event_type!: PaymentEventType`,\n maybe_credits_granted AS `maybe_credits_granted: u32`\nFROM user_spend_events\nWHERE maybe_user_token = ?\n AND payments_namespace = ?\n AND is_production = TRUE\nORDER BY payment_occurred_at ASC\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "payment_occurred_at!: DateTime<Utc>",
"type_info": {
"type": "Timestamp",
"flags": "NOT_NULL | MULTIPLE_KEY | BINARY | NO_DEFAULT_VALUE",
"char_set": 63,
"max_size": 19
}
},
{
"ordinal": 1,
"name": "amount_usd_cents",
"type_info": {
"type": "LongLong",
"flags": "NOT_NULL | NO_DEFAULT_VALUE",
"char_set": 63,
"max_size": 20
}
},
{
"ordinal": 2,
"name": "event_type!: PaymentEventType",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | MULTIPLE_KEY | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 128
}
},
{
"ordinal": 3,
"name": "maybe_credits_granted: u32",
"type_info": {
"type": "Long",
"flags": "UNSIGNED",
"char_set": 63,
"max_size": 10
}
}
],
"parameters": {
"Right": 2
},
"nullable": [
false,
false,
false,
true
]
},
"hash": "1c997019b7ed18059bc08d857918c3ce3f5e6ed56d358894cbc496d345566519"
}
@@ -0,0 +1,36 @@
{
"db_name": "MySQL",
"query": "\nSELECT\n stripe_customer_id AS `stripe_customer_id!`,\n user_token AS `user_token!: UserToken`\nFROM user_stripe_customer_links\nWHERE payments_namespace = 'artcraft'\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "stripe_customer_id!",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | UNIQUE_KEY | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 1020
}
},
{
"ordinal": 1,
"name": "user_token!: UserToken",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | MULTIPLE_KEY | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 128
}
}
],
"parameters": {
"Right": 0
},
"nullable": [
false,
false
]
},
"hash": "2d49cfbafc29bce35f3e03135054c7521fb0182663aefa971245f91f33a6fc49"
}
@@ -0,0 +1,12 @@
{
"db_name": "MySQL",
"query": "\nINSERT INTO user_spend_events\nSET\n token = ?,\n payments_namespace = ?,\n maybe_user_token = ?,\n event_type = ?,\n amount_usd_cents = ?,\n maybe_credits_granted = ?,\n maybe_user_subscription_token = ?,\n maybe_wallet_ledger_entry_token = ?,\n payment_source = ?,\n source_object_id = ?,\n maybe_stripe_customer_id = ?,\n maybe_stripe_invoice_id = ?,\n maybe_stripe_payment_intent_id = ?,\n maybe_stripe_charge_id = ?,\n maybe_stripe_event_id = ?,\n is_production = ?,\n payment_occurred_at = ?\nON DUPLICATE KEY UPDATE token = token\n ",
"describe": {
"columns": [],
"parameters": {
"Right": 17
},
"nullable": []
},
"hash": "3e5a71cedc31cc656177c8331c2de1d1d2d2eb310aabeb7e6238943b073f6998"
}
@@ -0,0 +1,12 @@
{
"db_name": "MySQL",
"query": "\nINSERT INTO user_spend_summaries\nSET\n payments_namespace = ?,\n user_token = ?,\n lifetime_gross_spend_usd_cents = ?,\n lifetime_subscription_spend_usd_cents = ?,\n lifetime_credits_spend_usd_cents = ?,\n lifetime_refund_usd_cents = ?,\n lifetime_net_spend_usd_cents = ?,\n lifetime_payment_count = ?,\n lifetime_refund_count = ?,\n first_payment_at = ?,\n first_spend_usd_cents = ?,\n last_payment_at = ?,\n last_spend_usd_cents = ?,\n days_since_first_payment = ?,\n days_since_last_payment = ?,\n net_spend_7d_usd_cents = ?,\n net_spend_prev_7d_usd_cents = ?,\n net_spend_14d_usd_cents = ?,\n net_spend_prev_14d_usd_cents = ?,\n net_spend_30d_usd_cents = ?,\n net_spend_prev_30d_usd_cents = ?,\n net_spend_60d_usd_cents = ?,\n net_spend_90d_usd_cents = ?,\n net_spend_this_year_usd_cents = ?,\n avg_weekly_net_spend_4w_usd_cents = ?,\n avg_weekly_net_spend_12w_usd_cents = ?,\n active_weeks_in_last_4 = ?,\n active_weeks_in_last_8 = ?,\n active_weeks_in_last_12 = ?,\n active_weeks_in_last_24 = ?,\n active_weeks_in_last_52 = ?,\n consecutive_active_weeks = ?,\n consecutive_inactive_weeks = ?,\n weeks_since_last_spend = ?,\n is_active_subscriber = ?,\n maybe_subscription_interval = ?,\n maybe_reengagement_score = ?\nON DUPLICATE KEY UPDATE\n lifetime_gross_spend_usd_cents = VALUES(lifetime_gross_spend_usd_cents),\n lifetime_subscription_spend_usd_cents = VALUES(lifetime_subscription_spend_usd_cents),\n lifetime_credits_spend_usd_cents = VALUES(lifetime_credits_spend_usd_cents),\n lifetime_refund_usd_cents = VALUES(lifetime_refund_usd_cents),\n lifetime_net_spend_usd_cents = VALUES(lifetime_net_spend_usd_cents),\n lifetime_payment_count = VALUES(lifetime_payment_count),\n lifetime_refund_count = VALUES(lifetime_refund_count),\n first_payment_at = VALUES(first_payment_at),\n first_spend_usd_cents = VALUES(first_spend_usd_cents),\n last_payment_at = VALUES(last_payment_at),\n last_spend_usd_cents = VALUES(last_spend_usd_cents),\n days_since_first_payment = VALUES(days_since_first_payment),\n days_since_last_payment = VALUES(days_since_last_payment),\n net_spend_7d_usd_cents = VALUES(net_spend_7d_usd_cents),\n net_spend_prev_7d_usd_cents = VALUES(net_spend_prev_7d_usd_cents),\n net_spend_14d_usd_cents = VALUES(net_spend_14d_usd_cents),\n net_spend_prev_14d_usd_cents = VALUES(net_spend_prev_14d_usd_cents),\n net_spend_30d_usd_cents = VALUES(net_spend_30d_usd_cents),\n net_spend_prev_30d_usd_cents = VALUES(net_spend_prev_30d_usd_cents),\n net_spend_60d_usd_cents = VALUES(net_spend_60d_usd_cents),\n net_spend_90d_usd_cents = VALUES(net_spend_90d_usd_cents),\n net_spend_this_year_usd_cents = VALUES(net_spend_this_year_usd_cents),\n avg_weekly_net_spend_4w_usd_cents = VALUES(avg_weekly_net_spend_4w_usd_cents),\n avg_weekly_net_spend_12w_usd_cents = VALUES(avg_weekly_net_spend_12w_usd_cents),\n active_weeks_in_last_4 = VALUES(active_weeks_in_last_4),\n active_weeks_in_last_8 = VALUES(active_weeks_in_last_8),\n active_weeks_in_last_12 = VALUES(active_weeks_in_last_12),\n active_weeks_in_last_24 = VALUES(active_weeks_in_last_24),\n active_weeks_in_last_52 = VALUES(active_weeks_in_last_52),\n consecutive_active_weeks = VALUES(consecutive_active_weeks),\n consecutive_inactive_weeks = VALUES(consecutive_inactive_weeks),\n weeks_since_last_spend = VALUES(weeks_since_last_spend),\n is_active_subscriber = VALUES(is_active_subscriber),\n maybe_subscription_interval = VALUES(maybe_subscription_interval),\n maybe_reengagement_score = VALUES(maybe_reengagement_score)\n ",
"describe": {
"columns": [],
"parameters": {
"Right": 37
},
"nullable": []
},
"hash": "41cf2f8d64aa36fb930cc1bf8a46d37e0987b743438b44e1c55859fc6b6ee6a0"
}
@@ -0,0 +1,124 @@
{
"db_name": "MySQL",
"query": "\nSELECT\n s.user_token AS `user_token!: UserToken`,\n u.username AS `username!`,\n u.display_name AS `display_name!`,\n u.email_gravatar_hash AS `email_gravatar_hash!`,\n s.maybe_reengagement_score AS `reengagement_score!: u32`,\n s.lifetime_net_spend_usd_cents,\n s.last_payment_at AS `maybe_last_payment_at: DateTime<Utc>`,\n s.days_since_last_payment AS `maybe_days_since_last_payment: u32`,\n s.weeks_since_last_spend AS `maybe_weeks_since_last_spend: u32`,\n s.is_active_subscriber AS `is_active_subscriber: bool`\nFROM user_spend_summaries s\nJOIN users u ON u.token = s.user_token\nWHERE s.payments_namespace = ?\n AND s.maybe_reengagement_score > 0\nORDER BY s.maybe_reengagement_score DESC, s.id ASC\nLIMIT ? OFFSET ?\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "user_token!: UserToken",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 128
}
},
{
"ordinal": 1,
"name": "username!",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | UNIQUE_KEY | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 80
}
},
{
"ordinal": 2,
"name": "display_name!",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 80
}
},
{
"ordinal": 3,
"name": "email_gravatar_hash!",
"type_info": {
"type": "String",
"flags": "NOT_NULL | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 128
}
},
{
"ordinal": 4,
"name": "reengagement_score!: u32",
"type_info": {
"type": "Long",
"flags": "UNSIGNED",
"char_set": 63,
"max_size": 10
}
},
{
"ordinal": 5,
"name": "lifetime_net_spend_usd_cents",
"type_info": {
"type": "LongLong",
"flags": "NOT_NULL | UNSIGNED",
"char_set": 63,
"max_size": 20
}
},
{
"ordinal": 6,
"name": "maybe_last_payment_at: DateTime<Utc>",
"type_info": {
"type": "Timestamp",
"flags": "BINARY",
"char_set": 63,
"max_size": 19
}
},
{
"ordinal": 7,
"name": "maybe_days_since_last_payment: u32",
"type_info": {
"type": "Long",
"flags": "UNSIGNED",
"char_set": 63,
"max_size": 10
}
},
{
"ordinal": 8,
"name": "maybe_weeks_since_last_spend: u32",
"type_info": {
"type": "Long",
"flags": "UNSIGNED",
"char_set": 63,
"max_size": 10
}
},
{
"ordinal": 9,
"name": "is_active_subscriber: bool",
"type_info": {
"type": "Tiny",
"flags": "NOT_NULL",
"char_set": 63,
"max_size": 1
}
}
],
"parameters": {
"Right": 3
},
"nullable": [
false,
false,
false,
false,
true,
false,
true,
true,
true,
false
]
},
"hash": "5b1954301fc16703a04e2f63fd85c28bf2283bc1ecb5624107686dad0dfe364f"
}
@@ -0,0 +1,146 @@
{
"db_name": "MySQL",
"query": "\nSELECT\n payments_namespace AS `payments_namespace!: PaymentsNamespace`,\n user_token AS `user_token!: UserToken`,\n spend_date AS `spend_date!: NaiveDate`,\n subscription_spend_usd_cents,\n credits_spend_usd_cents,\n gross_spend_usd_cents,\n refund_usd_cents,\n net_spend_usd_cents,\n payment_count,\n credits_granted,\n created_at AS `created_at: DateTime<Utc>`,\n updated_at AS `updated_at: DateTime<Utc>`\nFROM user_daily_spends\nWHERE user_token = ?\n AND payments_namespace = ?\nORDER BY spend_date DESC\nLIMIT ? OFFSET ?\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "payments_namespace!: PaymentsNamespace",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 128
}
},
{
"ordinal": 1,
"name": "user_token!: UserToken",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | MULTIPLE_KEY | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 128
}
},
{
"ordinal": 2,
"name": "spend_date!: NaiveDate",
"type_info": {
"type": "Date",
"flags": "NOT_NULL | BINARY | NO_DEFAULT_VALUE",
"char_set": 63,
"max_size": 10
}
},
{
"ordinal": 3,
"name": "subscription_spend_usd_cents",
"type_info": {
"type": "LongLong",
"flags": "NOT_NULL | UNSIGNED",
"char_set": 63,
"max_size": 20
}
},
{
"ordinal": 4,
"name": "credits_spend_usd_cents",
"type_info": {
"type": "LongLong",
"flags": "NOT_NULL | UNSIGNED",
"char_set": 63,
"max_size": 20
}
},
{
"ordinal": 5,
"name": "gross_spend_usd_cents",
"type_info": {
"type": "LongLong",
"flags": "NOT_NULL | UNSIGNED",
"char_set": 63,
"max_size": 20
}
},
{
"ordinal": 6,
"name": "refund_usd_cents",
"type_info": {
"type": "LongLong",
"flags": "NOT_NULL | UNSIGNED",
"char_set": 63,
"max_size": 20
}
},
{
"ordinal": 7,
"name": "net_spend_usd_cents",
"type_info": {
"type": "LongLong",
"flags": "NOT_NULL",
"char_set": 63,
"max_size": 20
}
},
{
"ordinal": 8,
"name": "payment_count",
"type_info": {
"type": "Long",
"flags": "NOT_NULL | UNSIGNED",
"char_set": 63,
"max_size": 10
}
},
{
"ordinal": 9,
"name": "credits_granted",
"type_info": {
"type": "LongLong",
"flags": "NOT_NULL | UNSIGNED",
"char_set": 63,
"max_size": 20
}
},
{
"ordinal": 10,
"name": "created_at: DateTime<Utc>",
"type_info": {
"type": "Timestamp",
"flags": "NOT_NULL | BINARY | TIMESTAMP",
"char_set": 63,
"max_size": 19
}
},
{
"ordinal": 11,
"name": "updated_at: DateTime<Utc>",
"type_info": {
"type": "Timestamp",
"flags": "NOT_NULL | BINARY | TIMESTAMP | ON_UPDATE_NOW",
"char_set": 63,
"max_size": 19
}
}
],
"parameters": {
"Right": 4
},
"nullable": [
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false
]
},
"hash": "77dca63cffdd18957cbc4be6b7d982a2599a2c06df07f8e34501a032cd688ead"
}
@@ -0,0 +1,113 @@
{
"db_name": "MySQL",
"query": "\nSELECT\n maybe_user_token AS `user_token!: UserToken`,\n payments_namespace AS `payments_namespace!: PaymentsNamespace`,\n CAST(SUM(CASE WHEN amount_usd_cents > 0\n AND event_type IN ('subscription_initial', 'subscription_renewal', 'subscription_proration_upgrade')\n THEN amount_usd_cents ELSE 0 END) AS UNSIGNED) AS `subscription_spend_usd_cents!: u64`,\n CAST(SUM(CASE WHEN amount_usd_cents > 0 AND event_type = 'credit_pack_purchase'\n THEN amount_usd_cents ELSE 0 END) AS UNSIGNED) AS `credits_spend_usd_cents!: u64`,\n CAST(SUM(CASE WHEN amount_usd_cents > 0 THEN amount_usd_cents ELSE 0 END) AS UNSIGNED) AS `gross_spend_usd_cents!: u64`,\n CAST(SUM(CASE WHEN amount_usd_cents < 0 THEN -amount_usd_cents ELSE 0 END) AS UNSIGNED) AS `refund_usd_cents!: u64`,\n CAST(SUM(amount_usd_cents) AS SIGNED) AS `net_spend_usd_cents!: i64`,\n CAST(SUM(CASE WHEN amount_usd_cents > 0 THEN 1 ELSE 0 END) AS UNSIGNED) AS `payment_count!: u64`,\n CAST(COALESCE(SUM(maybe_credits_granted), 0) AS UNSIGNED) AS `credits_granted!: u64`\nFROM user_spend_events\nWHERE maybe_user_token IS NOT NULL\n AND is_production = TRUE\n AND payment_occurred_at >= ?\n AND payment_occurred_at < ?\nGROUP BY maybe_user_token, payments_namespace\nHAVING SUM(CASE WHEN amount_usd_cents <> 0 THEN 1 ELSE 0 END) > 0\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "user_token!: UserToken",
"type_info": {
"type": "VarString",
"flags": "MULTIPLE_KEY | BINARY",
"char_set": 224,
"max_size": 128
}
},
{
"ordinal": 1,
"name": "payments_namespace!: PaymentsNamespace",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | MULTIPLE_KEY | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 128
}
},
{
"ordinal": 2,
"name": "subscription_spend_usd_cents!: u64",
"type_info": {
"type": "LongLong",
"flags": "UNSIGNED | BINARY",
"char_set": 63,
"max_size": 21
}
},
{
"ordinal": 3,
"name": "credits_spend_usd_cents!: u64",
"type_info": {
"type": "LongLong",
"flags": "UNSIGNED | BINARY",
"char_set": 63,
"max_size": 21
}
},
{
"ordinal": 4,
"name": "gross_spend_usd_cents!: u64",
"type_info": {
"type": "LongLong",
"flags": "UNSIGNED | BINARY",
"char_set": 63,
"max_size": 21
}
},
{
"ordinal": 5,
"name": "refund_usd_cents!: u64",
"type_info": {
"type": "LongLong",
"flags": "UNSIGNED | BINARY",
"char_set": 63,
"max_size": 21
}
},
{
"ordinal": 6,
"name": "net_spend_usd_cents!: i64",
"type_info": {
"type": "LongLong",
"flags": "BINARY",
"char_set": 63,
"max_size": 21
}
},
{
"ordinal": 7,
"name": "payment_count!: u64",
"type_info": {
"type": "LongLong",
"flags": "UNSIGNED | BINARY",
"char_set": 63,
"max_size": 21
}
},
{
"ordinal": 8,
"name": "credits_granted!: u64",
"type_info": {
"type": "LongLong",
"flags": "NOT_NULL | UNSIGNED | BINARY",
"char_set": 63,
"max_size": 21
}
}
],
"parameters": {
"Right": 2
},
"nullable": [
true,
false,
true,
true,
true,
true,
true,
true,
false
]
},
"hash": "83fc05a3594b379482745f851cd5a22786adde9968dd70490c91100cf21f8023"
}
@@ -0,0 +1,443 @@
{
"db_name": "MySQL",
"query": "\nSELECT\n payments_namespace AS `payments_namespace!: PaymentsNamespace`,\n user_token AS `user_token!: UserToken`,\n lifetime_gross_spend_usd_cents,\n lifetime_subscription_spend_usd_cents,\n lifetime_credits_spend_usd_cents,\n lifetime_refund_usd_cents,\n lifetime_net_spend_usd_cents,\n lifetime_payment_count,\n lifetime_refund_count,\n first_payment_at AS `maybe_first_payment_at: DateTime<Utc>`,\n first_spend_usd_cents,\n last_payment_at AS `maybe_last_payment_at: DateTime<Utc>`,\n last_spend_usd_cents,\n days_since_first_payment AS `maybe_days_since_first_payment: u32`,\n days_since_last_payment AS `maybe_days_since_last_payment: u32`,\n net_spend_7d_usd_cents,\n net_spend_prev_7d_usd_cents,\n net_spend_14d_usd_cents,\n net_spend_prev_14d_usd_cents,\n net_spend_30d_usd_cents,\n net_spend_prev_30d_usd_cents,\n net_spend_60d_usd_cents,\n net_spend_90d_usd_cents,\n net_spend_this_year_usd_cents,\n avg_weekly_net_spend_4w_usd_cents,\n avg_weekly_net_spend_12w_usd_cents,\n active_weeks_in_last_4,\n active_weeks_in_last_8,\n active_weeks_in_last_12,\n active_weeks_in_last_24,\n active_weeks_in_last_52,\n consecutive_active_weeks,\n consecutive_inactive_weeks,\n weeks_since_last_spend AS `maybe_weeks_since_last_spend: u32`,\n is_active_subscriber AS `is_active_subscriber: bool`,\n maybe_subscription_interval,\n maybe_reengagement_score AS `maybe_reengagement_score: u32`,\n created_at AS `created_at: DateTime<Utc>`,\n updated_at AS `updated_at: DateTime<Utc>`\nFROM user_spend_summaries\nWHERE payments_namespace = ?\n AND user_token = ?\nLIMIT 1\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "payments_namespace!: PaymentsNamespace",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | MULTIPLE_KEY | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 128
}
},
{
"ordinal": 1,
"name": "user_token!: UserToken",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 128
}
},
{
"ordinal": 2,
"name": "lifetime_gross_spend_usd_cents",
"type_info": {
"type": "LongLong",
"flags": "NOT_NULL | UNSIGNED",
"char_set": 63,
"max_size": 20
}
},
{
"ordinal": 3,
"name": "lifetime_subscription_spend_usd_cents",
"type_info": {
"type": "LongLong",
"flags": "NOT_NULL | UNSIGNED",
"char_set": 63,
"max_size": 20
}
},
{
"ordinal": 4,
"name": "lifetime_credits_spend_usd_cents",
"type_info": {
"type": "LongLong",
"flags": "NOT_NULL | UNSIGNED",
"char_set": 63,
"max_size": 20
}
},
{
"ordinal": 5,
"name": "lifetime_refund_usd_cents",
"type_info": {
"type": "LongLong",
"flags": "NOT_NULL | UNSIGNED",
"char_set": 63,
"max_size": 20
}
},
{
"ordinal": 6,
"name": "lifetime_net_spend_usd_cents",
"type_info": {
"type": "LongLong",
"flags": "NOT_NULL | UNSIGNED",
"char_set": 63,
"max_size": 20
}
},
{
"ordinal": 7,
"name": "lifetime_payment_count",
"type_info": {
"type": "Long",
"flags": "NOT_NULL | UNSIGNED",
"char_set": 63,
"max_size": 10
}
},
{
"ordinal": 8,
"name": "lifetime_refund_count",
"type_info": {
"type": "Long",
"flags": "NOT_NULL | UNSIGNED",
"char_set": 63,
"max_size": 10
}
},
{
"ordinal": 9,
"name": "maybe_first_payment_at: DateTime<Utc>",
"type_info": {
"type": "Timestamp",
"flags": "BINARY",
"char_set": 63,
"max_size": 19
}
},
{
"ordinal": 10,
"name": "first_spend_usd_cents",
"type_info": {
"type": "LongLong",
"flags": "NOT_NULL | UNSIGNED",
"char_set": 63,
"max_size": 20
}
},
{
"ordinal": 11,
"name": "maybe_last_payment_at: DateTime<Utc>",
"type_info": {
"type": "Timestamp",
"flags": "BINARY",
"char_set": 63,
"max_size": 19
}
},
{
"ordinal": 12,
"name": "last_spend_usd_cents",
"type_info": {
"type": "LongLong",
"flags": "NOT_NULL | UNSIGNED",
"char_set": 63,
"max_size": 20
}
},
{
"ordinal": 13,
"name": "maybe_days_since_first_payment: u32",
"type_info": {
"type": "Long",
"flags": "UNSIGNED",
"char_set": 63,
"max_size": 10
}
},
{
"ordinal": 14,
"name": "maybe_days_since_last_payment: u32",
"type_info": {
"type": "Long",
"flags": "UNSIGNED",
"char_set": 63,
"max_size": 10
}
},
{
"ordinal": 15,
"name": "net_spend_7d_usd_cents",
"type_info": {
"type": "LongLong",
"flags": "NOT_NULL",
"char_set": 63,
"max_size": 20
}
},
{
"ordinal": 16,
"name": "net_spend_prev_7d_usd_cents",
"type_info": {
"type": "LongLong",
"flags": "NOT_NULL",
"char_set": 63,
"max_size": 20
}
},
{
"ordinal": 17,
"name": "net_spend_14d_usd_cents",
"type_info": {
"type": "LongLong",
"flags": "NOT_NULL",
"char_set": 63,
"max_size": 20
}
},
{
"ordinal": 18,
"name": "net_spend_prev_14d_usd_cents",
"type_info": {
"type": "LongLong",
"flags": "NOT_NULL",
"char_set": 63,
"max_size": 20
}
},
{
"ordinal": 19,
"name": "net_spend_30d_usd_cents",
"type_info": {
"type": "LongLong",
"flags": "NOT_NULL",
"char_set": 63,
"max_size": 20
}
},
{
"ordinal": 20,
"name": "net_spend_prev_30d_usd_cents",
"type_info": {
"type": "LongLong",
"flags": "NOT_NULL",
"char_set": 63,
"max_size": 20
}
},
{
"ordinal": 21,
"name": "net_spend_60d_usd_cents",
"type_info": {
"type": "LongLong",
"flags": "NOT_NULL",
"char_set": 63,
"max_size": 20
}
},
{
"ordinal": 22,
"name": "net_spend_90d_usd_cents",
"type_info": {
"type": "LongLong",
"flags": "NOT_NULL",
"char_set": 63,
"max_size": 20
}
},
{
"ordinal": 23,
"name": "net_spend_this_year_usd_cents",
"type_info": {
"type": "LongLong",
"flags": "NOT_NULL",
"char_set": 63,
"max_size": 20
}
},
{
"ordinal": 24,
"name": "avg_weekly_net_spend_4w_usd_cents",
"type_info": {
"type": "LongLong",
"flags": "NOT_NULL",
"char_set": 63,
"max_size": 20
}
},
{
"ordinal": 25,
"name": "avg_weekly_net_spend_12w_usd_cents",
"type_info": {
"type": "LongLong",
"flags": "NOT_NULL",
"char_set": 63,
"max_size": 20
}
},
{
"ordinal": 26,
"name": "active_weeks_in_last_4",
"type_info": {
"type": "Tiny",
"flags": "NOT_NULL | UNSIGNED",
"char_set": 63,
"max_size": 3
}
},
{
"ordinal": 27,
"name": "active_weeks_in_last_8",
"type_info": {
"type": "Tiny",
"flags": "NOT_NULL | UNSIGNED",
"char_set": 63,
"max_size": 3
}
},
{
"ordinal": 28,
"name": "active_weeks_in_last_12",
"type_info": {
"type": "Tiny",
"flags": "NOT_NULL | UNSIGNED",
"char_set": 63,
"max_size": 3
}
},
{
"ordinal": 29,
"name": "active_weeks_in_last_24",
"type_info": {
"type": "Tiny",
"flags": "NOT_NULL | UNSIGNED",
"char_set": 63,
"max_size": 3
}
},
{
"ordinal": 30,
"name": "active_weeks_in_last_52",
"type_info": {
"type": "Tiny",
"flags": "NOT_NULL | UNSIGNED",
"char_set": 63,
"max_size": 3
}
},
{
"ordinal": 31,
"name": "consecutive_active_weeks",
"type_info": {
"type": "Long",
"flags": "NOT_NULL | UNSIGNED",
"char_set": 63,
"max_size": 10
}
},
{
"ordinal": 32,
"name": "consecutive_inactive_weeks",
"type_info": {
"type": "Long",
"flags": "NOT_NULL | UNSIGNED",
"char_set": 63,
"max_size": 10
}
},
{
"ordinal": 33,
"name": "maybe_weeks_since_last_spend: u32",
"type_info": {
"type": "Long",
"flags": "UNSIGNED",
"char_set": 63,
"max_size": 10
}
},
{
"ordinal": 34,
"name": "is_active_subscriber: bool",
"type_info": {
"type": "Tiny",
"flags": "NOT_NULL",
"char_set": 63,
"max_size": 1
}
},
{
"ordinal": 35,
"name": "maybe_subscription_interval",
"type_info": {
"type": "VarString",
"flags": "BINARY",
"char_set": 224,
"max_size": 64
}
},
{
"ordinal": 36,
"name": "maybe_reengagement_score: u32",
"type_info": {
"type": "Long",
"flags": "UNSIGNED",
"char_set": 63,
"max_size": 10
}
},
{
"ordinal": 37,
"name": "created_at: DateTime<Utc>",
"type_info": {
"type": "Timestamp",
"flags": "NOT_NULL | BINARY | TIMESTAMP",
"char_set": 63,
"max_size": 19
}
},
{
"ordinal": 38,
"name": "updated_at: DateTime<Utc>",
"type_info": {
"type": "Timestamp",
"flags": "NOT_NULL | BINARY | TIMESTAMP | ON_UPDATE_NOW",
"char_set": 63,
"max_size": 19
}
}
],
"parameters": {
"Right": 2
},
"nullable": [
false,
false,
false,
false,
false,
false,
false,
false,
false,
true,
false,
true,
false,
true,
true,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
true,
false,
true,
true,
false,
false
]
},
"hash": "9715e4dc2ec6e596fdb91ecc50a2b80f63494bbc0c9df6c0a57ede2360716869"
}
@@ -0,0 +1,12 @@
{
"db_name": "MySQL",
"query": "\nINSERT INTO user_daily_spends\nSET\n user_token = ?,\n payments_namespace = ?,\n spend_date = ?,\n subscription_spend_usd_cents = ?,\n credits_spend_usd_cents = ?,\n gross_spend_usd_cents = ?,\n refund_usd_cents = ?,\n net_spend_usd_cents = ?,\n payment_count = ?,\n credits_granted = ?\nON DUPLICATE KEY UPDATE\n subscription_spend_usd_cents = VALUES(subscription_spend_usd_cents),\n credits_spend_usd_cents = VALUES(credits_spend_usd_cents),\n gross_spend_usd_cents = VALUES(gross_spend_usd_cents),\n refund_usd_cents = VALUES(refund_usd_cents),\n net_spend_usd_cents = VALUES(net_spend_usd_cents),\n payment_count = VALUES(payment_count),\n credits_granted = VALUES(credits_granted)\n ",
"describe": {
"columns": [],
"parameters": {
"Right": 10
},
"nullable": []
},
"hash": "b7a5fea76da70c03b8744c985940a5bcdabdb3316aa407c5ca883bca863ee633"
}
@@ -0,0 +1,25 @@
{
"db_name": "MySQL",
"query": "\nSELECT DISTINCT maybe_user_token AS `user_token!: UserToken`\nFROM user_spend_events\nWHERE maybe_user_token IS NOT NULL\n AND is_production = TRUE\n AND payments_namespace = ?\n AND maybe_user_token > ?\nORDER BY maybe_user_token\nLIMIT ?\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "user_token!: UserToken",
"type_info": {
"type": "VarString",
"flags": "MULTIPLE_KEY | BINARY",
"char_set": 224,
"max_size": 128
}
}
],
"parameters": {
"Right": 3
},
"nullable": [
true
]
},
"hash": "bcd07050d5557bf59d6b2691478763b5b067447d295b002f6e766209ea077f42"
}
@@ -0,0 +1,25 @@
{
"db_name": "MySQL",
"query": "\nSELECT DISTINCT payments_namespace AS `payments_namespace!: PaymentsNamespace`\nFROM user_spend_events\nWHERE maybe_user_token IS NOT NULL\n AND is_production = TRUE\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "payments_namespace!: PaymentsNamespace",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | MULTIPLE_KEY | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 128
}
}
],
"parameters": {
"Right": 0
},
"nullable": [
false
]
},
"hash": "cf8c702126bba73cd3abc2ed7202962b6da773460505222a75408dab1d26b70f"
}
@@ -0,0 +1,212 @@
{
"db_name": "MySQL",
"query": "\nSELECT\n e.token AS `token!: UserSpendEventToken`,\n e.payments_namespace AS `payments_namespace!`,\n e.maybe_user_token AS `maybe_user_token: UserToken`,\n u.username AS `maybe_username?`,\n u.display_name AS `maybe_display_name?`,\n u.email_gravatar_hash AS `maybe_email_gravatar_hash?`,\n e.event_type AS `event_type!`,\n e.amount_usd_cents,\n e.maybe_credits_granted AS `maybe_credits_granted: u32`,\n e.payment_source AS `payment_source!`,\n e.source_object_id AS `maybe_source_object_id`,\n e.maybe_stripe_invoice_id,\n e.maybe_stripe_payment_intent_id,\n e.maybe_stripe_charge_id,\n e.maybe_stripe_customer_id,\n e.is_production AS `is_production: bool`,\n e.payment_occurred_at AS `payment_occurred_at!: DateTime<Utc>`,\n e.created_at AS `created_at!: DateTime<Utc>`\nFROM user_spend_events e\nLEFT JOIN users u ON u.token = e.maybe_user_token\nWHERE (? IS NULL OR e.payments_namespace = ?)\nORDER BY e.payment_occurred_at DESC, e.id DESC\nLIMIT ? OFFSET ?\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "token!: UserSpendEventToken",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | UNIQUE_KEY | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 128
}
},
{
"ordinal": 1,
"name": "payments_namespace!",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | MULTIPLE_KEY | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 128
}
},
{
"ordinal": 2,
"name": "maybe_user_token: UserToken",
"type_info": {
"type": "VarString",
"flags": "MULTIPLE_KEY | BINARY",
"char_set": 224,
"max_size": 128
}
},
{
"ordinal": 3,
"name": "maybe_username?",
"type_info": {
"type": "VarString",
"flags": "UNIQUE_KEY | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 80
}
},
{
"ordinal": 4,
"name": "maybe_display_name?",
"type_info": {
"type": "VarString",
"flags": "BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 80
}
},
{
"ordinal": 5,
"name": "maybe_email_gravatar_hash?",
"type_info": {
"type": "String",
"flags": "BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 128
}
},
{
"ordinal": 6,
"name": "event_type!",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | MULTIPLE_KEY | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 128
}
},
{
"ordinal": 7,
"name": "amount_usd_cents",
"type_info": {
"type": "LongLong",
"flags": "NOT_NULL | NO_DEFAULT_VALUE",
"char_set": 63,
"max_size": 20
}
},
{
"ordinal": 8,
"name": "maybe_credits_granted: u32",
"type_info": {
"type": "Long",
"flags": "UNSIGNED",
"char_set": 63,
"max_size": 10
}
},
{
"ordinal": 9,
"name": "payment_source!",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | MULTIPLE_KEY | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 64
}
},
{
"ordinal": 10,
"name": "maybe_source_object_id",
"type_info": {
"type": "VarString",
"flags": "BINARY",
"char_set": 224,
"max_size": 1020
}
},
{
"ordinal": 11,
"name": "maybe_stripe_invoice_id",
"type_info": {
"type": "VarString",
"flags": "MULTIPLE_KEY | BINARY",
"char_set": 224,
"max_size": 1020
}
},
{
"ordinal": 12,
"name": "maybe_stripe_payment_intent_id",
"type_info": {
"type": "VarString",
"flags": "BINARY",
"char_set": 224,
"max_size": 1020
}
},
{
"ordinal": 13,
"name": "maybe_stripe_charge_id",
"type_info": {
"type": "VarString",
"flags": "BINARY",
"char_set": 224,
"max_size": 1020
}
},
{
"ordinal": 14,
"name": "maybe_stripe_customer_id",
"type_info": {
"type": "VarString",
"flags": "MULTIPLE_KEY | BINARY",
"char_set": 224,
"max_size": 1020
}
},
{
"ordinal": 15,
"name": "is_production: bool",
"type_info": {
"type": "Tiny",
"flags": "NOT_NULL",
"char_set": 63,
"max_size": 1
}
},
{
"ordinal": 16,
"name": "payment_occurred_at!: DateTime<Utc>",
"type_info": {
"type": "Timestamp",
"flags": "NOT_NULL | MULTIPLE_KEY | BINARY | NO_DEFAULT_VALUE",
"char_set": 63,
"max_size": 19
}
},
{
"ordinal": 17,
"name": "created_at!: DateTime<Utc>",
"type_info": {
"type": "Timestamp",
"flags": "NOT_NULL | BINARY | TIMESTAMP",
"char_set": 63,
"max_size": 19
}
}
],
"parameters": {
"Right": 4
},
"nullable": [
false,
false,
true,
true,
true,
true,
false,
false,
true,
false,
true,
true,
true,
true,
true,
false,
false,
false
]
},
"hash": "d5d3a59ea4885868b26168cd305f6168a1e62fe9f8fa663063591335c645b927"
}
@@ -0,0 +1,80 @@
{
"db_name": "MySQL",
"query": "\nSELECT\n wle.maybe_entity_ref AS `stripe_object_id!`,\n wle.entry_type AS `entry_type!`,\n wle.token AS `ledger_token!: WalletLedgerEntryToken`,\n w.owner_user_token AS `owner_user_token!: UserToken`,\n wle.credits_delta AS `credits_delta!`,\n wle.created_at AS `created_at!: DateTime<Utc>`\nFROM wallet_ledger_entries wle\nJOIN wallets w ON w.token = wle.wallet_token\nWHERE w.wallet_namespace = 'artcraft'\n AND wle.entry_type IN ('credit_banked', 'credit_monthly')\n AND wle.created_at >= ?\n AND (wle.maybe_entity_ref LIKE 'pi\\_%' OR wle.maybe_entity_ref LIKE 'in\\_%')\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "stripe_object_id!",
"type_info": {
"type": "VarString",
"flags": "BINARY",
"char_set": 224,
"max_size": 1020
}
},
{
"ordinal": 1,
"name": "entry_type!",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 128
}
},
{
"ordinal": 2,
"name": "ledger_token!: WalletLedgerEntryToken",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | UNIQUE_KEY | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 128
}
},
{
"ordinal": 3,
"name": "owner_user_token!: UserToken",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | MULTIPLE_KEY | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 128
}
},
{
"ordinal": 4,
"name": "credits_delta!",
"type_info": {
"type": "Long",
"flags": "NOT_NULL",
"char_set": 63,
"max_size": 11
}
},
{
"ordinal": 5,
"name": "created_at!: DateTime<Utc>",
"type_info": {
"type": "Timestamp",
"flags": "NOT_NULL | BINARY | TIMESTAMP",
"char_set": 63,
"max_size": 19
}
}
],
"parameters": {
"Right": 1
},
"nullable": [
true,
false,
false,
false,
false,
false
]
},
"hash": "de69f3d564830f8fff90f754d13982de623fcda50118d261466eeaf034de5ecb"
}
@@ -0,0 +1,157 @@
{
"db_name": "MySQL",
"query": "\nSELECT\n s.user_token AS `user_token!: UserToken`,\n u.username AS `username!`,\n u.display_name AS `display_name!`,\n u.email_gravatar_hash AS `email_gravatar_hash!`,\n s.lifetime_net_spend_usd_cents,\n s.net_spend_7d_usd_cents,\n s.net_spend_14d_usd_cents,\n s.net_spend_30d_usd_cents,\n s.net_spend_60d_usd_cents,\n s.net_spend_90d_usd_cents,\n s.net_spend_this_year_usd_cents,\n s.is_active_subscriber AS `is_active_subscriber: bool`,\n s.maybe_reengagement_score AS `maybe_reengagement_score: u32`\nFROM user_spend_summaries s\nJOIN users u ON u.token = s.user_token\nWHERE s.payments_namespace = ?\nORDER BY\n (CASE ?\n WHEN '7d' THEN s.net_spend_7d_usd_cents\n WHEN '14d' THEN s.net_spend_14d_usd_cents\n WHEN '30d' THEN s.net_spend_30d_usd_cents\n WHEN '60d' THEN s.net_spend_60d_usd_cents\n WHEN '90d' THEN s.net_spend_90d_usd_cents\n WHEN '1y' THEN s.net_spend_this_year_usd_cents\n ELSE CAST(s.lifetime_net_spend_usd_cents AS SIGNED)\n END) DESC,\n s.id ASC\nLIMIT ? OFFSET ?\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "user_token!: UserToken",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 128
}
},
{
"ordinal": 1,
"name": "username!",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | UNIQUE_KEY | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 80
}
},
{
"ordinal": 2,
"name": "display_name!",
"type_info": {
"type": "VarString",
"flags": "NOT_NULL | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 80
}
},
{
"ordinal": 3,
"name": "email_gravatar_hash!",
"type_info": {
"type": "String",
"flags": "NOT_NULL | BINARY | NO_DEFAULT_VALUE",
"char_set": 224,
"max_size": 128
}
},
{
"ordinal": 4,
"name": "lifetime_net_spend_usd_cents",
"type_info": {
"type": "LongLong",
"flags": "NOT_NULL | UNSIGNED",
"char_set": 63,
"max_size": 20
}
},
{
"ordinal": 5,
"name": "net_spend_7d_usd_cents",
"type_info": {
"type": "LongLong",
"flags": "NOT_NULL",
"char_set": 63,
"max_size": 20
}
},
{
"ordinal": 6,
"name": "net_spend_14d_usd_cents",
"type_info": {
"type": "LongLong",
"flags": "NOT_NULL",
"char_set": 63,
"max_size": 20
}
},
{
"ordinal": 7,
"name": "net_spend_30d_usd_cents",
"type_info": {
"type": "LongLong",
"flags": "NOT_NULL",
"char_set": 63,
"max_size": 20
}
},
{
"ordinal": 8,
"name": "net_spend_60d_usd_cents",
"type_info": {
"type": "LongLong",
"flags": "NOT_NULL",
"char_set": 63,
"max_size": 20
}
},
{
"ordinal": 9,
"name": "net_spend_90d_usd_cents",
"type_info": {
"type": "LongLong",
"flags": "NOT_NULL",
"char_set": 63,
"max_size": 20
}
},
{
"ordinal": 10,
"name": "net_spend_this_year_usd_cents",
"type_info": {
"type": "LongLong",
"flags": "NOT_NULL",
"char_set": 63,
"max_size": 20
}
},
{
"ordinal": 11,
"name": "is_active_subscriber: bool",
"type_info": {
"type": "Tiny",
"flags": "NOT_NULL",
"char_set": 63,
"max_size": 1
}
},
{
"ordinal": 12,
"name": "maybe_reengagement_score: u32",
"type_info": {
"type": "Long",
"flags": "UNSIGNED",
"char_set": 63,
"max_size": 10
}
}
],
"parameters": {
"Right": 4
},
"nullable": [
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
false,
true
]
},
"hash": "f6db2f3bf8695fa8431db209576328154b8ac20aa6e899739095b6206bb38944"
}
@@ -0,0 +1,47 @@
{
"db_name": "MySQL",
"query": "\nSELECT\n maybe_stripe_subscription_status,\n maybe_stripe_recurring_interval,\n subscription_expires_at AS `subscription_expires_at!: DateTime<Utc>`\nFROM user_subscriptions\nWHERE user_token = ?\n AND subscription_namespace = ?\nORDER BY subscription_expires_at DESC\nLIMIT 1\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "maybe_stripe_subscription_status",
"type_info": {
"type": "VarString",
"flags": "MULTIPLE_KEY | BINARY",
"char_set": 224,
"max_size": 128
}
},
{
"ordinal": 1,
"name": "maybe_stripe_recurring_interval",
"type_info": {
"type": "VarString",
"flags": "BINARY",
"char_set": 224,
"max_size": 128
}
},
{
"ordinal": 2,
"name": "subscription_expires_at!: DateTime<Utc>",
"type_info": {
"type": "Timestamp",
"flags": "NOT_NULL | MULTIPLE_KEY | BINARY | TIMESTAMP",
"char_set": 63,
"max_size": 19
}
}
],
"parameters": {
"Right": 2
},
"nullable": [
true,
true,
false
]
},
"hash": "f74615faa4321ec4d583829997e12cb8ae152afefd2574385c120c63278893d2"
}
Generated
+32
View File
@@ -3049,6 +3049,8 @@ dependencies = [
"futures 0.3.32",
"log",
"mysql_queries",
"reqwest 0.12.23",
"rustls 0.23.36",
"serde",
"serde_derive",
"serde_json",
@@ -13702,6 +13704,36 @@ dependencies = [
"url",
]
[[package]]
name = "user-spend-analytics-job"
version = "0.0.1"
dependencies = [
"actix-web",
"actix_helpers",
"anyhow",
"bootstrap",
"chrono",
"concurrency",
"easyenv",
"enums",
"errors",
"jobs_common",
"log",
"mysql_queries",
"pager",
"rootly_client",
"rootly_config",
"serde",
"serde_derive",
"serde_json",
"server_environment",
"shared_env_var_config",
"sqlx",
"tokens",
"tokio",
"workspace-build-acceleration",
]
[[package]]
name = "user_input_common"
version = "0.0.1"
+1
View File
@@ -136,6 +136,7 @@ members = [
"crates/service/job/grok_api_job",
"crates/service/job/seedance2_pro_job",
"crates/service/job/video_thumbnail_job",
"crates/service/job/user_spend_analytics_job",
"crates/service/job/worldlabs_job",
"crates/service/web/dummy_service",
"crates/service/web/storyteller_web",
@@ -0,0 +1,5 @@
-- noinspection SqlDialectInspectionForFile
-- noinspection SqlNoDataSourceInspectionForFile
-- noinspection SqlResolveForFile
DROP TABLE IF EXISTS user_spend_events;
@@ -0,0 +1,103 @@
-- noinspection SqlDialectInspectionForFile
-- noinspection SqlNoDataSourceInspectionForFile
-- noinspection SqlResolveForFile
-- Append-only ledger of real money movements (USD cents), one row per settled
-- event. Derived from settled Stripe webhooks (invoice.paid, payment_intent.
-- succeeded / checkout.session.completed, charge.refunded, charge.dispute.*),
-- NOT from every webhook. Idempotent via uq_source_object so retries never
-- double-count. We always work in USD via Stripe, so there are no currency or
-- fee columns.
CREATE TABLE user_spend_events (
-- Replication only.
id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
-- Effective public primary key. Token prefix "spend_".
token VARCHAR(32) NOT NULL,
-- Multi-site segregation. Reuses the existing PaymentsNamespace enum.
payments_namespace VARCHAR(32) NOT NULL,
-- Who paid. Nullable so we can record money we can't yet attribute and
-- backfill -- but expect this set ~always.
maybe_user_token VARCHAR(32) DEFAULT NULL,
-- PaymentEventType enum. Splits subscription vs credit-pack revenue:
-- 'subscription_initial' -- first paid invoice of a new subscription
-- 'subscription_renewal' -- recurring paid invoice (monthly, or annual once/yr)
-- 'subscription_proration_upgrade' -- mid-cycle upgrade proration charge (positive)
-- 'subscription_proration_downgrade' -- mid-cycle downgrade proration credit (rare as a settled event)
-- 'credit_pack_purchase' -- one-time credit pack (the ~10x-volume case)
-- 'refund' -- refund (amount negative)
-- 'chargeback' -- dispute/chargeback (amount negative)
-- 'manual_adjustment' -- staff/console correction (payment_source = 'manual')
-- 'subscription_monthly_refill' -- OPTIONAL non-revenue event for annual-plan
-- monthly credit refills (amount 0)
event_type VARCHAR(32) NOT NULL,
-- ========== MONEY ==========
-- USD cents. SIGNED: refunds/chargebacks negative; refills are 0. BIGINT so
-- downstream lifetime sums never overflow.
amount_usd_cents BIGINT NOT NULL,
-- For credit-pack purchases / subscription grants/refills: how many of OUR
-- credits this granted. Lets us correlate dollars-in vs credits-granted vs
-- credits-used. NULL for refunds/chargebacks.
maybe_credits_granted INTEGER UNSIGNED DEFAULT NULL,
-- ========== INTERNAL LINKAGE ==========
-- The subscription this payment belongs to, if any (-> user_subscriptions.token).
maybe_user_subscription_token VARCHAR(32) DEFAULT NULL,
-- The credit-grant ledger entry this produced, if any
-- (-> wallet_ledger_entries.token). Ties a dollar event to its credit effect.
maybe_wallet_ledger_entry_token VARCHAR(32) DEFAULT NULL,
-- ========== SOURCE / PROVIDER ==========
-- PaymentSource enum: 'stripe' or 'manual'. (USD/Stripe only for the
-- foreseeable future; 'manual' covers staff/console adjustments.)
payment_source VARCHAR(16) NOT NULL,
-- The authoritative object this row represents -- the dedup anchor. NULLABLE.
-- For Stripe: invoice id (subscriptions), payment_intent id (one-time), or
-- refund/dispute id (refunds). For payment_source='manual' (no provider
-- object) leave it NULL. MySQL allows multiple NULLs in a unique index, so
-- manual rows freely duplicate, while any present id is still deduped.
source_object_id VARCHAR(255) DEFAULT NULL,
-- Convenience copies for joins/forensics (255 + utf8mb4_bin for Stripe IDs).
maybe_stripe_customer_id VARCHAR(255) DEFAULT NULL,
maybe_stripe_invoice_id VARCHAR(255) DEFAULT NULL,
maybe_stripe_payment_intent_id VARCHAR(255) DEFAULT NULL,
maybe_stripe_charge_id VARCHAR(255) DEFAULT NULL,
-- The webhook event that caused this row (provenance only).
maybe_stripe_event_id VARCHAR(255) DEFAULT NULL,
-- Stripe livemode. Keep test-mode money out of dashboards.
is_production BOOLEAN NOT NULL DEFAULT FALSE,
-- ========== TIMESTAMPS ==========
-- When the money actually moved (Stripe settlement time). Bin/aggregate on
-- THIS, not created_at (which is when we ingested the webhook).
payment_occurred_at TIMESTAMP NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
-- ========== INDICES ==========
PRIMARY KEY (id),
UNIQUE KEY (token),
-- Idempotency: one row per settled object. NULL source_object_id rows (manual)
-- are exempt -- MySQL treats each NULL in a unique index as distinct.
UNIQUE KEY uq_source_object (payment_source, source_object_id),
KEY idx_user_occurred (maybe_user_token, payment_occurred_at),
KEY idx_occurred (payment_occurred_at),
KEY idx_namespace_occurred (payments_namespace, payment_occurred_at),
KEY idx_event_type (event_type),
KEY idx_stripe_customer (maybe_stripe_customer_id),
KEY idx_stripe_invoice (maybe_stripe_invoice_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
@@ -0,0 +1,5 @@
-- noinspection SqlDialectInspectionForFile
-- noinspection SqlNoDataSourceInspectionForFile
-- noinspection SqlResolveForFile
DROP TABLE IF EXISTS user_daily_spends;
@@ -0,0 +1,44 @@
-- noinspection SqlDialectInspectionForFile
-- noinspection SqlNoDataSourceInspectionForFile
-- noinspection SqlResolveForFile
-- Per-user, per-day spend rollup (L1). Net = gross - refunds. Subscription vs
-- credit-pack splits expose the revenue mix per day without touching the event
-- table. Sparsely populated -- no row for days with zero spend and zero refunds.
-- Derived from (and fully rebuildable from) user_spend_events.
CREATE TABLE user_daily_spends (
-- Replication only.
id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
user_token VARCHAR(32) NOT NULL,
payments_namespace VARCHAR(32) NOT NULL,
-- Reporting day. Bins user_spend_events.payment_occurred_at in a FIXED tz
-- (UTC). DATE, not TIMESTAMP.
spend_date DATE NOT NULL,
-- Revenue mix (subset of gross). Category totals can never go negative, so
-- they're UNSIGNED.
subscription_spend_usd_cents BIGINT UNSIGNED NOT NULL DEFAULT 0,
credits_spend_usd_cents BIGINT UNSIGNED NOT NULL DEFAULT 0,
gross_spend_usd_cents BIGINT UNSIGNED NOT NULL DEFAULT 0, -- sum of positive amounts (UNSIGNED)
refund_usd_cents BIGINT UNSIGNED NOT NULL DEFAULT 0, -- refund/chargeback magnitude (UNSIGNED)
-- NET is the ONE field here that must be SIGNED: a single day can net negative
-- when refunds (often of an earlier day's purchase) exceed that day's purchases.
net_spend_usd_cents BIGINT NOT NULL DEFAULT 0, -- gross - refund (SIGNED)
payment_count INT UNSIGNED NOT NULL DEFAULT 0, -- # positive money events
credits_granted BIGINT UNSIGNED NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
-- ========== INDICES ==========
PRIMARY KEY (id),
UNIQUE KEY uq_user_day (user_token, payments_namespace, spend_date),
-- "Top spenders / spend in a date range": filter by date, then group by user.
KEY idx_day_user_net (user_token, payments_namespace, spend_date, net_spend_usd_cents),
KEY idx_user_day (user_token, spend_date)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
@@ -0,0 +1,5 @@
-- noinspection SqlDialectInspectionForFile
-- noinspection SqlNoDataSourceInspectionForFile
-- noinspection SqlResolveForFile
DROP TABLE IF EXISTS user_spend_summaries;
@@ -0,0 +1,95 @@
-- noinspection SqlDialectInspectionForFile
-- noinspection SqlNoDataSourceInspectionForFile
-- noinspection SqlResolveForFile
-- Per-user spend summary (L2). Lifetime/recency facts are event-maintained (they
-- only grow); sliding windows and weekly-rhythm metrics are job-maintained (they
-- shift even on days a user doesn't pay). Powers churn / dip / re-engagement
-- dashboards in O(1). Derived from (and fully rebuildable from) user_spend_events
-- and user_daily_spends.
CREATE TABLE user_spend_summaries (
-- Replication only.
id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
payments_namespace VARCHAR(32) NOT NULL,
user_token VARCHAR(32) NOT NULL,
-- ===== Lifetime (event-maintained) =====
-- Gross / category / refund totals are UNSIGNED. Lifetime net is UNSIGNED too:
-- over a lifetime you can never refund more than was paid.
lifetime_gross_spend_usd_cents BIGINT UNSIGNED NOT NULL DEFAULT 0,
lifetime_subscription_spend_usd_cents BIGINT UNSIGNED NOT NULL DEFAULT 0, -- revenue mix split
lifetime_credits_spend_usd_cents BIGINT UNSIGNED NOT NULL DEFAULT 0, -- revenue mix split
lifetime_refund_usd_cents BIGINT UNSIGNED NOT NULL DEFAULT 0,
lifetime_net_spend_usd_cents BIGINT UNSIGNED NOT NULL DEFAULT 0, -- gross - refund
-- Event COUNTS (not money): number of payment events vs refund/chargeback
-- events over the user's lifetime. Both event-maintained.
lifetime_payment_count INT UNSIGNED NOT NULL DEFAULT 0, -- # of positive money events
lifetime_refund_count INT UNSIGNED NOT NULL DEFAULT 0, -- # of refund/chargeback events
first_payment_at TIMESTAMP NULL DEFAULT NULL,
first_spend_usd_cents BIGINT UNSIGNED NOT NULL DEFAULT 0, -- amount of the first payment
last_payment_at TIMESTAMP NULL DEFAULT NULL,
last_spend_usd_cents BIGINT UNSIGNED NOT NULL DEFAULT 0, -- amount of the most recent payment
days_since_first_payment INT UNSIGNED DEFAULT NULL, -- job-refreshed
days_since_last_payment INT UNSIGNED DEFAULT NULL, -- job-refreshed
-- ===== Sliding NET spend windows -- SIGNED, a window can net negative
-- (job-refreshed from user_daily_spends) =====
-- "prev" = the equally-sized window immediately before, for WoW/MoM deltas.
net_spend_7d_usd_cents BIGINT NOT NULL DEFAULT 0,
net_spend_prev_7d_usd_cents BIGINT NOT NULL DEFAULT 0,
net_spend_14d_usd_cents BIGINT NOT NULL DEFAULT 0, -- bi-weekly
net_spend_prev_14d_usd_cents BIGINT NOT NULL DEFAULT 0,
net_spend_30d_usd_cents BIGINT NOT NULL DEFAULT 0,
net_spend_prev_30d_usd_cents BIGINT NOT NULL DEFAULT 0,
net_spend_60d_usd_cents BIGINT NOT NULL DEFAULT 0,
net_spend_90d_usd_cents BIGINT NOT NULL DEFAULT 0,
net_spend_this_year_usd_cents BIGINT NOT NULL DEFAULT 0,
-- ===== Weekly cadence / rhythm (job-refreshed) -- for the sales team =====
-- A "week" is Mon-Sun UTC. These let sales spot users breaking their habit.
-- Per-user weekly baselines at two horizons: 4w is responsive (recent norm),
-- 12w is stable (established norm). 4w well below 12w is itself a cooling-off
-- signal. Mean weekly NET spend over the trailing window (calendar weeks,
-- zero-spend weeks included). SIGNED, like the window nets.
avg_weekly_net_spend_4w_usd_cents BIGINT NOT NULL DEFAULT 0,
avg_weekly_net_spend_12w_usd_cents BIGINT NOT NULL DEFAULT 0,
-- How many of the last N calendar weeks had any net spend -- a regularity
-- measure at several horizons.
active_weeks_in_last_4 TINYINT UNSIGNED NOT NULL DEFAULT 0, -- 0..4
active_weeks_in_last_8 TINYINT UNSIGNED NOT NULL DEFAULT 0, -- 0..8
active_weeks_in_last_12 TINYINT UNSIGNED NOT NULL DEFAULT 0, -- 0..12
active_weeks_in_last_24 TINYINT UNSIGNED NOT NULL DEFAULT 0, -- 0..24
active_weeks_in_last_52 TINYINT UNSIGNED NOT NULL DEFAULT 0, -- 0..52
consecutive_active_weeks INT UNSIGNED NOT NULL DEFAULT 0, -- current "streak"
consecutive_inactive_weeks INT UNSIGNED NOT NULL DEFAULT 0, -- current "dip" length
-- Recency in weeks. Subsumes the entire "is_active_spender_last_N_weeks"
-- family: "active in the last N weeks" == (weeks_since_last_spend < N). So we
-- intentionally store NO is_active_* booleans (redundant + poor index
-- selectivity); we index this field instead and range-query any N. NULL = never spent.
weeks_since_last_spend INT UNSIGNED DEFAULT NULL,
-- ===== Flags =====
is_active_subscriber BOOLEAN NOT NULL DEFAULT FALSE, -- from user_subscriptions
maybe_subscription_interval VARCHAR(16) DEFAULT NULL, -- 'month' / 'year' (annual plans behave differently)
-- Optional precomputed re-engagement priority (job-set).
maybe_reengagement_score INT UNSIGNED DEFAULT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
-- ========== INDICES ==========
PRIMARY KEY (id),
UNIQUE KEY uq_user (payments_namespace, user_token),
KEY idx_lifetime (payments_namespace, lifetime_net_spend_usd_cents),
KEY idx_last_payment_at (payments_namespace, last_payment_at),
KEY idx_first_payment_at (payments_namespace, first_payment_at),
KEY idx_spend_7d (payments_namespace, net_spend_7d_usd_cents),
KEY idx_spend_30d (payments_namespace, net_spend_30d_usd_cents),
KEY idx_reengagement (payments_namespace, maybe_reengagement_score),
-- Sort / range-filter by recency. idx_weeks_since_last_spend also powers every
-- "active in the last N weeks" query (weeks_since_last_spend < N).
KEY idx_weeks_since_last_spend (payments_namespace, weeks_since_last_spend),
KEY idx_days_since_last_payment (payments_namespace, days_since_last_payment)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
@@ -0,0 +1,47 @@
-- noinspection SqlDialectInspectionForFile
-- noinspection SqlNoDataSourceInspectionForFile
-- noinspection SqlResolveForFile
-- NB: This is a manually squashed view of all the CREATE and ALTER statements,
-- with comments attached to the fields for centralized documentation.
-- Per-user, per-day spend rollup (L1). Net = gross - refunds. Subscription vs
-- credit-pack splits expose the revenue mix per day without touching the event
-- table. Sparsely populated -- no row for days with zero spend and zero refunds.
-- Derived from (and fully rebuildable from) user_spend_events.
CREATE TABLE user_daily_spends (
-- Replication only.
id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
user_token VARCHAR(32) NOT NULL,
payments_namespace VARCHAR(32) NOT NULL,
-- Reporting day. Bins user_spend_events.payment_occurred_at in a FIXED tz
-- (UTC). DATE, not TIMESTAMP.
spend_date DATE NOT NULL,
-- Revenue mix (subset of gross). Category totals can never go negative, so
-- they're UNSIGNED.
subscription_spend_usd_cents BIGINT UNSIGNED NOT NULL DEFAULT 0,
credits_spend_usd_cents BIGINT UNSIGNED NOT NULL DEFAULT 0,
gross_spend_usd_cents BIGINT UNSIGNED NOT NULL DEFAULT 0, -- sum of positive amounts (UNSIGNED)
refund_usd_cents BIGINT UNSIGNED NOT NULL DEFAULT 0, -- refund/chargeback magnitude (UNSIGNED)
-- NET is the ONE field here that must be SIGNED: a single day can net negative
-- when refunds (often of an earlier day's purchase) exceed that day's purchases.
net_spend_usd_cents BIGINT NOT NULL DEFAULT 0, -- gross - refund (SIGNED)
payment_count INT UNSIGNED NOT NULL DEFAULT 0, -- # positive money events
credits_granted BIGINT UNSIGNED NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
-- ========== INDICES ==========
PRIMARY KEY (id),
UNIQUE KEY uq_user_day (user_token, payments_namespace, spend_date),
-- "Top spenders / spend in a date range": filter by date, then group by user.
KEY idx_day_user_net (user_token, payments_namespace, spend_date, net_spend_usd_cents),
KEY idx_user_day (user_token, spend_date)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
@@ -0,0 +1,106 @@
-- noinspection SqlDialectInspectionForFile
-- noinspection SqlNoDataSourceInspectionForFile
-- noinspection SqlResolveForFile
-- NB: This is a manually squashed view of all the CREATE and ALTER statements,
-- with comments attached to the fields for centralized documentation.
-- Append-only ledger of real money movements (USD cents), one row per settled
-- event. Derived from settled Stripe webhooks (invoice.paid, payment_intent.
-- succeeded / checkout.session.completed, charge.refunded, charge.dispute.*),
-- NOT from every webhook. Idempotent via uq_source_object so retries never
-- double-count. We always work in USD via Stripe, so there are no currency or
-- fee columns.
CREATE TABLE user_spend_events (
-- Replication only.
id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
-- Effective public primary key. Token prefix "spend_".
token VARCHAR(32) NOT NULL,
-- Multi-site segregation. Reuses the existing PaymentsNamespace enum.
payments_namespace VARCHAR(32) NOT NULL,
-- Who paid. Nullable so we can record money we can't yet attribute and
-- backfill -- but expect this set ~always.
maybe_user_token VARCHAR(32) DEFAULT NULL,
-- PaymentEventType enum. Splits subscription vs credit-pack revenue:
-- 'subscription_initial' -- first paid invoice of a new subscription
-- 'subscription_renewal' -- recurring paid invoice (monthly, or annual once/yr)
-- 'subscription_proration_upgrade' -- mid-cycle upgrade proration charge (positive)
-- 'subscription_proration_downgrade' -- mid-cycle downgrade proration credit (rare as a settled event)
-- 'credit_pack_purchase' -- one-time credit pack (the ~10x-volume case)
-- 'refund' -- refund (amount negative)
-- 'chargeback' -- dispute/chargeback (amount negative)
-- 'manual_adjustment' -- staff/console correction (payment_source = 'manual')
-- 'subscription_monthly_refill' -- OPTIONAL non-revenue event for annual-plan
-- monthly credit refills (amount 0)
event_type VARCHAR(32) NOT NULL,
-- ========== MONEY ==========
-- USD cents. SIGNED: refunds/chargebacks negative; refills are 0. BIGINT so
-- downstream lifetime sums never overflow.
amount_usd_cents BIGINT NOT NULL,
-- For credit-pack purchases / subscription grants/refills: how many of OUR
-- credits this granted. Lets us correlate dollars-in vs credits-granted vs
-- credits-used. NULL for refunds/chargebacks.
maybe_credits_granted INTEGER UNSIGNED DEFAULT NULL,
-- ========== INTERNAL LINKAGE ==========
-- The subscription this payment belongs to, if any (-> user_subscriptions.token).
maybe_user_subscription_token VARCHAR(32) DEFAULT NULL,
-- The credit-grant ledger entry this produced, if any
-- (-> wallet_ledger_entries.token). Ties a dollar event to its credit effect.
maybe_wallet_ledger_entry_token VARCHAR(32) DEFAULT NULL,
-- ========== SOURCE / PROVIDER ==========
-- PaymentSource enum: 'stripe' or 'manual'. (USD/Stripe only for the
-- foreseeable future; 'manual' covers staff/console adjustments.)
payment_source VARCHAR(16) NOT NULL,
-- The authoritative object this row represents -- the dedup anchor. NULLABLE.
-- For Stripe: invoice id (subscriptions), payment_intent id (one-time), or
-- refund/dispute id (refunds). For payment_source='manual' (no provider
-- object) leave it NULL. MySQL allows multiple NULLs in a unique index, so
-- manual rows freely duplicate, while any present id is still deduped.
source_object_id VARCHAR(255) DEFAULT NULL,
-- Convenience copies for joins/forensics (255 + utf8mb4_bin for Stripe IDs).
maybe_stripe_customer_id VARCHAR(255) DEFAULT NULL,
maybe_stripe_invoice_id VARCHAR(255) DEFAULT NULL,
maybe_stripe_payment_intent_id VARCHAR(255) DEFAULT NULL,
maybe_stripe_charge_id VARCHAR(255) DEFAULT NULL,
-- The webhook event that caused this row (provenance only).
maybe_stripe_event_id VARCHAR(255) DEFAULT NULL,
-- Stripe livemode. Keep test-mode money out of dashboards.
is_production BOOLEAN NOT NULL DEFAULT FALSE,
-- ========== TIMESTAMPS ==========
-- When the money actually moved (Stripe settlement time). Bin/aggregate on
-- THIS, not created_at (which is when we ingested the webhook).
payment_occurred_at TIMESTAMP NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
-- ========== INDICES ==========
PRIMARY KEY (id),
UNIQUE KEY (token),
-- Idempotency: one row per settled object. NULL source_object_id rows (manual)
-- are exempt -- MySQL treats each NULL in a unique index as distinct.
UNIQUE KEY uq_source_object (payment_source, source_object_id),
KEY idx_user_occurred (maybe_user_token, payment_occurred_at),
KEY idx_occurred (payment_occurred_at),
KEY idx_namespace_occurred (payments_namespace, payment_occurred_at),
KEY idx_event_type (event_type),
KEY idx_stripe_customer (maybe_stripe_customer_id),
KEY idx_stripe_invoice (maybe_stripe_invoice_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
@@ -0,0 +1,98 @@
-- noinspection SqlDialectInspectionForFile
-- noinspection SqlNoDataSourceInspectionForFile
-- noinspection SqlResolveForFile
-- NB: This is a manually squashed view of all the CREATE and ALTER statements,
-- with comments attached to the fields for centralized documentation.
-- Per-user spend summary (L2). Lifetime/recency facts are event-maintained (they
-- only grow); sliding windows and weekly-rhythm metrics are job-maintained (they
-- shift even on days a user doesn't pay). Powers churn / dip / re-engagement
-- dashboards in O(1). Derived from (and fully rebuildable from) user_spend_events
-- and user_daily_spends.
CREATE TABLE user_spend_summaries (
-- Replication only.
id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
payments_namespace VARCHAR(32) NOT NULL,
user_token VARCHAR(32) NOT NULL,
-- ===== Lifetime (event-maintained) =====
-- Gross / category / refund totals are UNSIGNED. Lifetime net is UNSIGNED too:
-- over a lifetime you can never refund more than was paid.
lifetime_gross_spend_usd_cents BIGINT UNSIGNED NOT NULL DEFAULT 0,
lifetime_subscription_spend_usd_cents BIGINT UNSIGNED NOT NULL DEFAULT 0, -- revenue mix split
lifetime_credits_spend_usd_cents BIGINT UNSIGNED NOT NULL DEFAULT 0, -- revenue mix split
lifetime_refund_usd_cents BIGINT UNSIGNED NOT NULL DEFAULT 0,
lifetime_net_spend_usd_cents BIGINT UNSIGNED NOT NULL DEFAULT 0, -- gross - refund
-- Event COUNTS (not money): number of payment events vs refund/chargeback
-- events over the user's lifetime. Both event-maintained.
lifetime_payment_count INT UNSIGNED NOT NULL DEFAULT 0, -- # of positive money events
lifetime_refund_count INT UNSIGNED NOT NULL DEFAULT 0, -- # of refund/chargeback events
first_payment_at TIMESTAMP NULL DEFAULT NULL,
first_spend_usd_cents BIGINT UNSIGNED NOT NULL DEFAULT 0, -- amount of the first payment
last_payment_at TIMESTAMP NULL DEFAULT NULL,
last_spend_usd_cents BIGINT UNSIGNED NOT NULL DEFAULT 0, -- amount of the most recent payment
days_since_first_payment INT UNSIGNED DEFAULT NULL, -- job-refreshed
days_since_last_payment INT UNSIGNED DEFAULT NULL, -- job-refreshed
-- ===== Sliding NET spend windows -- SIGNED, a window can net negative
-- (job-refreshed from user_daily_spends) =====
-- "prev" = the equally-sized window immediately before, for WoW/MoM deltas.
net_spend_7d_usd_cents BIGINT NOT NULL DEFAULT 0,
net_spend_prev_7d_usd_cents BIGINT NOT NULL DEFAULT 0,
net_spend_14d_usd_cents BIGINT NOT NULL DEFAULT 0, -- bi-weekly
net_spend_prev_14d_usd_cents BIGINT NOT NULL DEFAULT 0,
net_spend_30d_usd_cents BIGINT NOT NULL DEFAULT 0,
net_spend_prev_30d_usd_cents BIGINT NOT NULL DEFAULT 0,
net_spend_60d_usd_cents BIGINT NOT NULL DEFAULT 0,
net_spend_90d_usd_cents BIGINT NOT NULL DEFAULT 0,
net_spend_this_year_usd_cents BIGINT NOT NULL DEFAULT 0,
-- ===== Weekly cadence / rhythm (job-refreshed) -- for the sales team =====
-- A "week" is Mon-Sun UTC. These let sales spot users breaking their habit.
-- Per-user weekly baselines at two horizons: 4w is responsive (recent norm),
-- 12w is stable (established norm). 4w well below 12w is itself a cooling-off
-- signal. Mean weekly NET spend over the trailing window (calendar weeks,
-- zero-spend weeks included). SIGNED, like the window nets.
avg_weekly_net_spend_4w_usd_cents BIGINT NOT NULL DEFAULT 0,
avg_weekly_net_spend_12w_usd_cents BIGINT NOT NULL DEFAULT 0,
-- How many of the last N calendar weeks had any net spend -- a regularity
-- measure at several horizons.
active_weeks_in_last_4 TINYINT UNSIGNED NOT NULL DEFAULT 0, -- 0..4
active_weeks_in_last_8 TINYINT UNSIGNED NOT NULL DEFAULT 0, -- 0..8
active_weeks_in_last_12 TINYINT UNSIGNED NOT NULL DEFAULT 0, -- 0..12
active_weeks_in_last_24 TINYINT UNSIGNED NOT NULL DEFAULT 0, -- 0..24
active_weeks_in_last_52 TINYINT UNSIGNED NOT NULL DEFAULT 0, -- 0..52
consecutive_active_weeks INT UNSIGNED NOT NULL DEFAULT 0, -- current "streak"
consecutive_inactive_weeks INT UNSIGNED NOT NULL DEFAULT 0, -- current "dip" length
-- Recency in weeks. Subsumes the entire "is_active_spender_last_N_weeks"
-- family: "active in the last N weeks" == (weeks_since_last_spend < N). So we
-- intentionally store NO is_active_* booleans (redundant + poor index
-- selectivity); we index this field instead and range-query any N. NULL = never spent.
weeks_since_last_spend INT UNSIGNED DEFAULT NULL,
-- ===== Flags =====
is_active_subscriber BOOLEAN NOT NULL DEFAULT FALSE, -- from user_subscriptions
maybe_subscription_interval VARCHAR(16) DEFAULT NULL, -- 'month' / 'year' (annual plans behave differently)
-- Optional precomputed re-engagement priority (job-set).
maybe_reengagement_score INT UNSIGNED DEFAULT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
-- ========== INDICES ==========
PRIMARY KEY (id),
UNIQUE KEY uq_user (payments_namespace, user_token),
KEY idx_lifetime (payments_namespace, lifetime_net_spend_usd_cents),
KEY idx_last_payment_at (payments_namespace, last_payment_at),
KEY idx_first_payment_at (payments_namespace, first_payment_at),
KEY idx_spend_7d (payments_namespace, net_spend_7d_usd_cents),
KEY idx_spend_30d (payments_namespace, net_spend_30d_usd_cents),
KEY idx_reengagement (payments_namespace, maybe_reengagement_score),
-- Sort / range-filter by recency. idx_weeks_since_last_spend also powers every
-- "active in the last N weeks" query (weeks_since_last_spend < N).
KEY idx_weeks_since_last_spend (payments_namespace, weeks_since_last_spend),
KEY idx_days_since_last_payment (payments_namespace, days_since_last_payment)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
+2
View File
@@ -138,6 +138,7 @@ RUN SQLX_OFFLINE=true \
$HOME/.cargo/bin/cargo build \
--release \
--bin storyteller-web \
--bin user-spend-analytics-job \
--bin seedance2-pro-job \
--bin worldlabs-job \
--bin video-thumbnail-job \
@@ -190,6 +191,7 @@ COPY --from=builder /tmp/target/release/analytics-job /
COPY --from=builder /tmp/target/release/email-sender-job /
COPY --from=builder /tmp/target/release/es-update-job /
COPY --from=builder /tmp/target/release/grok-api-job /
COPY --from=builder /tmp/target/release/user-spend-analytics-job /
# Legacy apps:
# COPY --from=builder /tmp/target/release/tts-download-job /
@@ -5,3 +5,6 @@ pub mod user_referrals;
pub mod user_stripe_data;
pub mod wallet_ledger_entries;
pub mod wallets;
pub mod user_daily_spends;
pub mod user_spend_summaries;
pub mod user_spend_events;
@@ -0,0 +1 @@
pub mod user_daily_spends_list;
@@ -0,0 +1,41 @@
use chrono::{DateTime, NaiveDate, Utc};
use serde_derive::{Deserialize, Serialize};
use tokens::tokens::users::UserToken;
use utoipa::{IntoParams, ToSchema};
pub const MODERATOR_USER_DAILY_SPENDS_PATH: &str =
"/v1/moderation/user_daily_spends/user/{user_token}";
#[derive(Deserialize, IntoParams)]
pub struct ModeratorUserDailySpendsQueryParams {
/// Page size (default 200, max 5000).
pub limit: Option<u32>,
/// Row offset for pagination. Pass `next_offset` from the previous page.
pub offset: Option<u64>,
/// Payments namespace. Defaults to `artcraft`.
pub payments_namespace: Option<String>,
}
#[derive(Serialize, ToSchema)]
pub struct ModeratorUserDailySpendsResponse {
pub success: bool,
pub user_token: UserToken,
pub records: Vec<UserDailySpendEntry>,
/// Offset for the next page, or `None` if this was the last page.
pub maybe_next_offset: Option<u64>,
}
#[derive(Serialize, ToSchema)]
pub struct UserDailySpendEntry {
pub payments_namespace: String,
pub spend_date: NaiveDate,
pub subscription_spend_usd_cents: u64,
pub credits_spend_usd_cents: u64,
pub gross_spend_usd_cents: u64,
pub refund_usd_cents: u64,
pub net_spend_usd_cents: i64,
pub payment_count: u32,
pub credits_granted: u64,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
@@ -0,0 +1,46 @@
use chrono::{DateTime, Utc};
use serde_derive::{Deserialize, Serialize};
use tokens::tokens::user_spend_events::UserSpendEventToken;
use tokens::tokens::users::UserToken;
use utoipa::{IntoParams, ToSchema};
pub const MODERATOR_LIST_USER_SPEND_EVENTS_PATH: &str =
"/v1/moderation/user_spend_events/list";
#[derive(Deserialize, IntoParams)]
pub struct ModeratorListUserSpendEventsQueryParams {
/// Row offset for pagination (page size is fixed at 200). Pass `next_offset` from the previous page.
pub offset: Option<u64>,
/// Optional namespace filter (e.g. `artcraft`). Omit to return all namespaces.
pub payments_namespace: Option<String>,
}
#[derive(Serialize, ToSchema)]
pub struct ModeratorListUserSpendEventsResponse {
pub success: bool,
pub events: Vec<UserSpendEventListEntry>,
/// Offset for the next page, or `None` if this was the last page.
pub maybe_next_offset: Option<u64>,
}
#[derive(Serialize, ToSchema)]
pub struct UserSpendEventListEntry {
pub token: UserSpendEventToken,
pub payments_namespace: String,
pub maybe_user_token: Option<UserToken>,
pub maybe_username: Option<String>,
pub maybe_display_name: Option<String>,
pub maybe_email_gravatar_hash: Option<String>,
pub event_type: String,
pub amount_usd_cents: i64,
pub maybe_credits_granted: Option<u32>,
pub payment_source: String,
pub maybe_source_object_id: Option<String>,
pub maybe_stripe_invoice_id: Option<String>,
pub maybe_stripe_payment_intent_id: Option<String>,
pub maybe_stripe_charge_id: Option<String>,
pub maybe_stripe_customer_id: Option<String>,
pub is_production: bool,
pub payment_occurred_at: DateTime<Utc>,
pub created_at: DateTime<Utc>,
}
@@ -0,0 +1,69 @@
use chrono::{DateTime, Utc};
use serde_derive::{Deserialize, Serialize};
use tokens::tokens::users::UserToken;
use utoipa::{IntoParams, ToSchema};
pub const MODERATOR_GET_USER_SPEND_SUMMARY_PATH: &str =
"/v1/moderation/user_spend_summaries/summary/{user_token}";
#[derive(Deserialize, IntoParams)]
pub struct ModeratorGetUserSpendSummaryQueryParams {
/// Payments namespace. Defaults to `artcraft`.
pub payments_namespace: Option<String>,
}
#[derive(Serialize, ToSchema)]
pub struct ModeratorGetUserSpendSummaryResponse {
pub success: bool,
/// `None` if the user has no spend summary row.
pub maybe_summary: Option<UserSpendSummaryView>,
}
/// The full `user_spend_summaries` record for a user.
#[derive(Serialize, ToSchema)]
pub struct UserSpendSummaryView {
pub payments_namespace: String,
pub user_token: UserToken,
pub lifetime_gross_spend_usd_cents: u64,
pub lifetime_subscription_spend_usd_cents: u64,
pub lifetime_credits_spend_usd_cents: u64,
pub lifetime_refund_usd_cents: u64,
pub lifetime_net_spend_usd_cents: u64,
pub lifetime_payment_count: u32,
pub lifetime_refund_count: u32,
pub maybe_first_payment_at: Option<DateTime<Utc>>,
pub first_spend_usd_cents: u64,
pub maybe_last_payment_at: Option<DateTime<Utc>>,
pub last_spend_usd_cents: u64,
pub maybe_days_since_first_payment: Option<u32>,
pub maybe_days_since_last_payment: Option<u32>,
pub net_spend_7d_usd_cents: i64,
pub net_spend_prev_7d_usd_cents: i64,
pub net_spend_14d_usd_cents: i64,
pub net_spend_prev_14d_usd_cents: i64,
pub net_spend_30d_usd_cents: i64,
pub net_spend_prev_30d_usd_cents: i64,
pub net_spend_60d_usd_cents: i64,
pub net_spend_90d_usd_cents: i64,
pub net_spend_this_year_usd_cents: i64,
pub avg_weekly_net_spend_4w_usd_cents: i64,
pub avg_weekly_net_spend_12w_usd_cents: i64,
pub active_weeks_in_last_4: u8,
pub active_weeks_in_last_8: u8,
pub active_weeks_in_last_12: u8,
pub active_weeks_in_last_24: u8,
pub active_weeks_in_last_52: u8,
pub consecutive_active_weeks: u32,
pub consecutive_inactive_weeks: u32,
pub maybe_weeks_since_last_spend: Option<u32>,
pub is_active_subscriber: bool,
pub maybe_subscription_interval: Option<String>,
pub maybe_reengagement_score: Option<u32>,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
@@ -0,0 +1,3 @@
pub mod get_summary;
pub mod reengagement_list;
pub mod top_users_list;
@@ -0,0 +1,37 @@
use chrono::{DateTime, Utc};
use serde_derive::{Deserialize, Serialize};
use tokens::tokens::users::UserToken;
use utoipa::{IntoParams, ToSchema};
pub const MODERATOR_REENGAGEMENT_LIST_PATH: &str =
"/v1/moderation/user_spend_summaries/reengagement_list";
#[derive(Deserialize, IntoParams)]
pub struct ModeratorReengagementListQueryParams {
/// Row offset for pagination (page size is fixed at 200). Pass `next_offset` from the previous page.
pub offset: Option<u64>,
/// Payments namespace. Defaults to `artcraft`.
pub payments_namespace: Option<String>,
}
#[derive(Serialize, ToSchema)]
pub struct ModeratorReengagementListResponse {
pub success: bool,
pub candidates: Vec<ReengagementCandidateEntry>,
/// Offset for the next page, or `None` if this was the last page.
pub maybe_next_offset: Option<u64>,
}
#[derive(Serialize, ToSchema)]
pub struct ReengagementCandidateEntry {
pub user_token: UserToken,
pub username: String,
pub display_name: String,
pub email_gravatar_hash: String,
pub reengagement_score: u32,
pub lifetime_net_spend_usd_cents: u64,
pub maybe_last_payment_at: Option<DateTime<Utc>>,
pub maybe_days_since_last_payment: Option<u32>,
pub maybe_weeks_since_last_spend: Option<u32>,
pub is_active_subscriber: bool,
}
@@ -0,0 +1,77 @@
use serde_derive::{Deserialize, Serialize};
use tokens::tokens::users::UserToken;
use utoipa::{IntoParams, ToSchema};
pub const MODERATOR_TOP_USERS_LIST_PATH: &str =
"/v1/moderation/user_spend_summaries/top_users_list";
/// Net-spend window that selects which column `top_users_list` sorts by.
#[derive(Deserialize, Serialize, Clone, Copy, ToSchema)]
pub enum TopUsersWindow {
#[serde(rename = "7d")]
SevenDays,
#[serde(rename = "14d")]
FourteenDays,
#[serde(rename = "30d")]
ThirtyDays,
#[serde(rename = "60d")]
SixtyDays,
#[serde(rename = "90d")]
NinetyDays,
#[serde(rename = "1y")]
OneYear,
#[serde(rename = "lifetime")]
Lifetime,
}
impl TopUsersWindow {
/// The `window` key the `list_top_users_by_net_spend` query matches on.
pub fn as_query_key(self) -> &'static str {
match self {
TopUsersWindow::SevenDays => "7d",
TopUsersWindow::FourteenDays => "14d",
TopUsersWindow::ThirtyDays => "30d",
TopUsersWindow::SixtyDays => "60d",
TopUsersWindow::NinetyDays => "90d",
TopUsersWindow::OneYear => "1y",
TopUsersWindow::Lifetime => "lifetime",
}
}
}
#[derive(Deserialize, IntoParams)]
pub struct ModeratorTopUsersListQueryParams {
/// Sort window: `7d`, `14d`, `30d`, `60d`, `90d`, `1y`, or `lifetime` (default).
pub window: Option<TopUsersWindow>,
/// Row offset for pagination (page size is fixed at 200). Pass `next_offset` from the previous page.
pub offset: Option<u64>,
/// Payments namespace. Defaults to `artcraft`.
pub payments_namespace: Option<String>,
}
#[derive(Serialize, ToSchema)]
pub struct ModeratorTopUsersListResponse {
pub success: bool,
/// The window that was sorted by (echo of the request).
pub window: String,
pub users: Vec<TopUserEntry>,
/// Offset for the next page, or `None` if this was the last page.
pub maybe_next_offset: Option<u64>,
}
#[derive(Serialize, ToSchema)]
pub struct TopUserEntry {
pub user_token: UserToken,
pub username: String,
pub display_name: String,
pub email_gravatar_hash: String,
pub lifetime_net_spend_usd_cents: u64,
pub net_spend_7d_usd_cents: i64,
pub net_spend_14d_usd_cents: i64,
pub net_spend_30d_usd_cents: i64,
pub net_spend_60d_usd_cents: i64,
pub net_spend_90d_usd_cents: i64,
pub net_spend_this_year_usd_cents: i64,
pub is_active_subscriber: bool,
pub maybe_reengagement_score: Option<u32>,
}
@@ -0,0 +1,131 @@
use serde_derive::{Deserialize, Serialize};
/// Forward-compatible, self-contained API-client copy of the server's `CommonAspectRatio` enum.
///
/// Serialized as a string. Any value this client build does not recognize is preserved
/// verbatim in [`Unknown`], so newer server variants never break deserialization and
/// still round-trip back to the original string.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(from = "String", into = "String")]
pub enum ApiClientAspectRatio {
Auto,
Square,
WideThreeByTwo,
WideFourByThree,
WideFiveByFour,
WideSixteenByNine,
WideTwentyOneByNine,
TallTwoByThree,
TallThreeByFour,
TallFourByFive,
TallNineBySixteen,
TallNineByTwentyOne,
Wide,
Tall,
Auto2k,
Auto3k,
Auto4k,
SquareHd,
/// A value not known to this client build (preserved as-is).
Unknown(String),
}
impl From<String> for ApiClientAspectRatio {
fn from(value: String) -> Self {
match value.as_str() {
"auto" => Self::Auto,
"square" => Self::Square,
"wide_three_by_two" => Self::WideThreeByTwo,
"wide_four_by_three" => Self::WideFourByThree,
"wide_five_by_four" => Self::WideFiveByFour,
"wide_sixteen_by_nine" => Self::WideSixteenByNine,
"wide_twenty_one_by_nine" => Self::WideTwentyOneByNine,
"tall_two_by_three" => Self::TallTwoByThree,
"tall_three_by_four" => Self::TallThreeByFour,
"tall_four_by_five" => Self::TallFourByFive,
"tall_nine_by_sixteen" => Self::TallNineBySixteen,
"tall_nine_by_twenty_one" => Self::TallNineByTwentyOne,
"wide" => Self::Wide,
"tall" => Self::Tall,
"auto_2k" => Self::Auto2k,
"auto_3k" => Self::Auto3k,
"auto_4k" => Self::Auto4k,
"square_hd" => Self::SquareHd,
_ => Self::Unknown(value),
}
}
}
impl From<ApiClientAspectRatio> for String {
fn from(value: ApiClientAspectRatio) -> Self {
match value {
ApiClientAspectRatio::Auto => "auto".to_string(),
ApiClientAspectRatio::Square => "square".to_string(),
ApiClientAspectRatio::WideThreeByTwo => "wide_three_by_two".to_string(),
ApiClientAspectRatio::WideFourByThree => "wide_four_by_three".to_string(),
ApiClientAspectRatio::WideFiveByFour => "wide_five_by_four".to_string(),
ApiClientAspectRatio::WideSixteenByNine => "wide_sixteen_by_nine".to_string(),
ApiClientAspectRatio::WideTwentyOneByNine => "wide_twenty_one_by_nine".to_string(),
ApiClientAspectRatio::TallTwoByThree => "tall_two_by_three".to_string(),
ApiClientAspectRatio::TallThreeByFour => "tall_three_by_four".to_string(),
ApiClientAspectRatio::TallFourByFive => "tall_four_by_five".to_string(),
ApiClientAspectRatio::TallNineBySixteen => "tall_nine_by_sixteen".to_string(),
ApiClientAspectRatio::TallNineByTwentyOne => "tall_nine_by_twenty_one".to_string(),
ApiClientAspectRatio::Wide => "wide".to_string(),
ApiClientAspectRatio::Tall => "tall".to_string(),
ApiClientAspectRatio::Auto2k => "auto_2k".to_string(),
ApiClientAspectRatio::Auto3k => "auto_3k".to_string(),
ApiClientAspectRatio::Auto4k => "auto_4k".to_string(),
ApiClientAspectRatio::SquareHd => "square_hd".to_string(),
ApiClientAspectRatio::Unknown(other) => other,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn known_variant_round_trips() {
let parsed: ApiClientAspectRatio = serde_json::from_str("\"auto\"").unwrap();
assert_eq!(parsed, ApiClientAspectRatio::Auto);
assert_eq!(serde_json::to_string(&parsed).unwrap(), "\"auto\"");
}
#[test]
fn unknown_value_is_preserved_and_round_trips() {
let parsed: ApiClientAspectRatio = serde_json::from_str("\"zzz_not_a_real_value\"").unwrap();
assert_eq!(parsed, ApiClientAspectRatio::Unknown("zzz_not_a_real_value".to_string()));
assert_eq!(serde_json::to_string(&parsed).unwrap(), "\"zzz_not_a_real_value\"");
}
#[test]
fn every_known_variant_round_trips() {
let all = [
(ApiClientAspectRatio::Auto, "auto"),
(ApiClientAspectRatio::Square, "square"),
(ApiClientAspectRatio::WideThreeByTwo, "wide_three_by_two"),
(ApiClientAspectRatio::WideFourByThree, "wide_four_by_three"),
(ApiClientAspectRatio::WideFiveByFour, "wide_five_by_four"),
(ApiClientAspectRatio::WideSixteenByNine, "wide_sixteen_by_nine"),
(ApiClientAspectRatio::WideTwentyOneByNine, "wide_twenty_one_by_nine"),
(ApiClientAspectRatio::TallTwoByThree, "tall_two_by_three"),
(ApiClientAspectRatio::TallThreeByFour, "tall_three_by_four"),
(ApiClientAspectRatio::TallFourByFive, "tall_four_by_five"),
(ApiClientAspectRatio::TallNineBySixteen, "tall_nine_by_sixteen"),
(ApiClientAspectRatio::TallNineByTwentyOne, "tall_nine_by_twenty_one"),
(ApiClientAspectRatio::Wide, "wide"),
(ApiClientAspectRatio::Tall, "tall"),
(ApiClientAspectRatio::Auto2k, "auto_2k"),
(ApiClientAspectRatio::Auto3k, "auto_3k"),
(ApiClientAspectRatio::Auto4k, "auto_4k"),
(ApiClientAspectRatio::SquareHd, "square_hd"),
];
for (variant, s) in all {
assert_eq!(String::from(variant.clone()), s, "serialize mismatch for {:?}", variant);
let parsed: ApiClientAspectRatio = serde_json::from_str(&format!("\"{}\"", s)).unwrap();
assert_eq!(parsed, variant);
}
}
}
@@ -0,0 +1,67 @@
use serde_derive::{Deserialize, Serialize};
/// Forward-compatible, self-contained API-client copy of the server's `CommonBitrate` enum.
///
/// Serialized as a string. Any value this client build does not recognize is preserved
/// verbatim in [`Unknown`], so newer server variants never break deserialization and
/// still round-trip back to the original string.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(from = "String", into = "String")]
pub enum ApiClientBitrate {
Normal,
High,
/// A value not known to this client build (preserved as-is).
Unknown(String),
}
impl From<String> for ApiClientBitrate {
fn from(value: String) -> Self {
match value.as_str() {
"normal" => Self::Normal,
"high" => Self::High,
_ => Self::Unknown(value),
}
}
}
impl From<ApiClientBitrate> for String {
fn from(value: ApiClientBitrate) -> Self {
match value {
ApiClientBitrate::Normal => "normal".to_string(),
ApiClientBitrate::High => "high".to_string(),
ApiClientBitrate::Unknown(other) => other,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn known_variant_round_trips() {
let parsed: ApiClientBitrate = serde_json::from_str("\"normal\"").unwrap();
assert_eq!(parsed, ApiClientBitrate::Normal);
assert_eq!(serde_json::to_string(&parsed).unwrap(), "\"normal\"");
}
#[test]
fn unknown_value_is_preserved_and_round_trips() {
let parsed: ApiClientBitrate = serde_json::from_str("\"zzz_not_a_real_value\"").unwrap();
assert_eq!(parsed, ApiClientBitrate::Unknown("zzz_not_a_real_value".to_string()));
assert_eq!(serde_json::to_string(&parsed).unwrap(), "\"zzz_not_a_real_value\"");
}
#[test]
fn every_known_variant_round_trips() {
let all = [
(ApiClientBitrate::Normal, "normal"),
(ApiClientBitrate::High, "high"),
];
for (variant, s) in all {
assert_eq!(String::from(variant.clone()), s, "serialize mismatch for {:?}", variant);
let parsed: ApiClientBitrate = serde_json::from_str(&format!("\"{}\"", s)).unwrap();
assert_eq!(parsed, variant);
}
}
}
@@ -0,0 +1,83 @@
use serde_derive::{Deserialize, Serialize};
/// Forward-compatible, self-contained API-client copy of the server's `GenerationProvider` enum.
///
/// Serialized as a string. Any value this client build does not recognize is preserved
/// verbatim in [`Unknown`], so newer server variants never break deserialization and
/// still round-trip back to the original string.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(from = "String", into = "String")]
pub enum ApiClientGenerationProvider {
Artcraft,
Fal,
Grok,
Midjourney,
Sora,
WorldLabs,
/// A value not known to this client build (preserved as-is).
Unknown(String),
}
impl From<String> for ApiClientGenerationProvider {
fn from(value: String) -> Self {
match value.as_str() {
"artcraft" => Self::Artcraft,
"fal" => Self::Fal,
"grok" => Self::Grok,
"midjourney" => Self::Midjourney,
"sora" => Self::Sora,
"world_labs" => Self::WorldLabs,
_ => Self::Unknown(value),
}
}
}
impl From<ApiClientGenerationProvider> for String {
fn from(value: ApiClientGenerationProvider) -> Self {
match value {
ApiClientGenerationProvider::Artcraft => "artcraft".to_string(),
ApiClientGenerationProvider::Fal => "fal".to_string(),
ApiClientGenerationProvider::Grok => "grok".to_string(),
ApiClientGenerationProvider::Midjourney => "midjourney".to_string(),
ApiClientGenerationProvider::Sora => "sora".to_string(),
ApiClientGenerationProvider::WorldLabs => "world_labs".to_string(),
ApiClientGenerationProvider::Unknown(other) => other,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn known_variant_round_trips() {
let parsed: ApiClientGenerationProvider = serde_json::from_str("\"artcraft\"").unwrap();
assert_eq!(parsed, ApiClientGenerationProvider::Artcraft);
assert_eq!(serde_json::to_string(&parsed).unwrap(), "\"artcraft\"");
}
#[test]
fn unknown_value_is_preserved_and_round_trips() {
let parsed: ApiClientGenerationProvider = serde_json::from_str("\"zzz_not_a_real_value\"").unwrap();
assert_eq!(parsed, ApiClientGenerationProvider::Unknown("zzz_not_a_real_value".to_string()));
assert_eq!(serde_json::to_string(&parsed).unwrap(), "\"zzz_not_a_real_value\"");
}
#[test]
fn every_known_variant_round_trips() {
let all = [
(ApiClientGenerationProvider::Artcraft, "artcraft"),
(ApiClientGenerationProvider::Fal, "fal"),
(ApiClientGenerationProvider::Grok, "grok"),
(ApiClientGenerationProvider::Midjourney, "midjourney"),
(ApiClientGenerationProvider::Sora, "sora"),
(ApiClientGenerationProvider::WorldLabs, "world_labs"),
];
for (variant, s) in all {
assert_eq!(String::from(variant.clone()), s, "serialize mismatch for {:?}", variant);
let parsed: ApiClientGenerationProvider = serde_json::from_str(&format!("\"{}\"", s)).unwrap();
assert_eq!(parsed, variant);
}
}
}
@@ -0,0 +1,139 @@
use serde_derive::{Deserialize, Serialize};
/// Forward-compatible, self-contained API-client copy of the server's `CommonImageModel` enum.
///
/// Serialized as a string. Any value this client build does not recognize is preserved
/// verbatim in [`Unknown`], so newer server variants never break deserialization and
/// still round-trip back to the original string.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(from = "String", into = "String")]
pub enum ApiClientImageModel {
Flux1Dev,
Flux1Schnell,
FluxPro11,
FluxPro11Ultra,
GptImage1,
GptImage1p5,
GptImage2,
GrokImagineImage,
GrokImagineImageQuality,
Midjourney7,
Midjourney7Niji,
Midjourney8,
NanoBanana,
NanoBanana2,
NanoBananaPro,
Seedream4,
Seedream4p5,
Seedream5Lite,
QwenEdit2511Angles,
Flux2LoraAngles,
/// A value not known to this client build (preserved as-is).
Unknown(String),
}
impl From<String> for ApiClientImageModel {
fn from(value: String) -> Self {
match value.as_str() {
"flux_1_dev" => Self::Flux1Dev,
"flux_1_schnell" => Self::Flux1Schnell,
"flux_pro_1p1" => Self::FluxPro11,
"flux_pro_1p1_ultra" => Self::FluxPro11Ultra,
"gpt_image_1" => Self::GptImage1,
"gpt_image_1p5" => Self::GptImage1p5,
"gpt_image_2" => Self::GptImage2,
"grok_imagine_image" => Self::GrokImagineImage,
"grok_imagine_image_q" => Self::GrokImagineImageQuality,
"midjourney_7" => Self::Midjourney7,
"midjourney_7_niji" => Self::Midjourney7Niji,
"midjourney_8" => Self::Midjourney8,
"nano_banana" => Self::NanoBanana,
"nano_banana_2" => Self::NanoBanana2,
"nano_banana_pro" => Self::NanoBananaPro,
"seedream_4" => Self::Seedream4,
"seedream_4p5" => Self::Seedream4p5,
"seedream_5_lite" => Self::Seedream5Lite,
"qwen_edit_2511_angles" => Self::QwenEdit2511Angles,
"flux_2_lora_angles" => Self::Flux2LoraAngles,
_ => Self::Unknown(value),
}
}
}
impl From<ApiClientImageModel> for String {
fn from(value: ApiClientImageModel) -> Self {
match value {
ApiClientImageModel::Flux1Dev => "flux_1_dev".to_string(),
ApiClientImageModel::Flux1Schnell => "flux_1_schnell".to_string(),
ApiClientImageModel::FluxPro11 => "flux_pro_1p1".to_string(),
ApiClientImageModel::FluxPro11Ultra => "flux_pro_1p1_ultra".to_string(),
ApiClientImageModel::GptImage1 => "gpt_image_1".to_string(),
ApiClientImageModel::GptImage1p5 => "gpt_image_1p5".to_string(),
ApiClientImageModel::GptImage2 => "gpt_image_2".to_string(),
ApiClientImageModel::GrokImagineImage => "grok_imagine_image".to_string(),
ApiClientImageModel::GrokImagineImageQuality => "grok_imagine_image_q".to_string(),
ApiClientImageModel::Midjourney7 => "midjourney_7".to_string(),
ApiClientImageModel::Midjourney7Niji => "midjourney_7_niji".to_string(),
ApiClientImageModel::Midjourney8 => "midjourney_8".to_string(),
ApiClientImageModel::NanoBanana => "nano_banana".to_string(),
ApiClientImageModel::NanoBanana2 => "nano_banana_2".to_string(),
ApiClientImageModel::NanoBananaPro => "nano_banana_pro".to_string(),
ApiClientImageModel::Seedream4 => "seedream_4".to_string(),
ApiClientImageModel::Seedream4p5 => "seedream_4p5".to_string(),
ApiClientImageModel::Seedream5Lite => "seedream_5_lite".to_string(),
ApiClientImageModel::QwenEdit2511Angles => "qwen_edit_2511_angles".to_string(),
ApiClientImageModel::Flux2LoraAngles => "flux_2_lora_angles".to_string(),
ApiClientImageModel::Unknown(other) => other,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn known_variant_round_trips() {
let parsed: ApiClientImageModel = serde_json::from_str("\"flux_1_dev\"").unwrap();
assert_eq!(parsed, ApiClientImageModel::Flux1Dev);
assert_eq!(serde_json::to_string(&parsed).unwrap(), "\"flux_1_dev\"");
}
#[test]
fn unknown_value_is_preserved_and_round_trips() {
let parsed: ApiClientImageModel = serde_json::from_str("\"zzz_not_a_real_value\"").unwrap();
assert_eq!(parsed, ApiClientImageModel::Unknown("zzz_not_a_real_value".to_string()));
assert_eq!(serde_json::to_string(&parsed).unwrap(), "\"zzz_not_a_real_value\"");
}
#[test]
fn every_known_variant_round_trips() {
let all = [
(ApiClientImageModel::Flux1Dev, "flux_1_dev"),
(ApiClientImageModel::Flux1Schnell, "flux_1_schnell"),
(ApiClientImageModel::FluxPro11, "flux_pro_1p1"),
(ApiClientImageModel::FluxPro11Ultra, "flux_pro_1p1_ultra"),
(ApiClientImageModel::GptImage1, "gpt_image_1"),
(ApiClientImageModel::GptImage1p5, "gpt_image_1p5"),
(ApiClientImageModel::GptImage2, "gpt_image_2"),
(ApiClientImageModel::GrokImagineImage, "grok_imagine_image"),
(ApiClientImageModel::GrokImagineImageQuality, "grok_imagine_image_q"),
(ApiClientImageModel::Midjourney7, "midjourney_7"),
(ApiClientImageModel::Midjourney7Niji, "midjourney_7_niji"),
(ApiClientImageModel::Midjourney8, "midjourney_8"),
(ApiClientImageModel::NanoBanana, "nano_banana"),
(ApiClientImageModel::NanoBanana2, "nano_banana_2"),
(ApiClientImageModel::NanoBananaPro, "nano_banana_pro"),
(ApiClientImageModel::Seedream4, "seedream_4"),
(ApiClientImageModel::Seedream4p5, "seedream_4p5"),
(ApiClientImageModel::Seedream5Lite, "seedream_5_lite"),
(ApiClientImageModel::QwenEdit2511Angles, "qwen_edit_2511_angles"),
(ApiClientImageModel::Flux2LoraAngles, "flux_2_lora_angles"),
];
for (variant, s) in all {
assert_eq!(String::from(variant.clone()), s, "serialize mismatch for {:?}", variant);
let parsed: ApiClientImageModel = serde_json::from_str(&format!("\"{}\"", s)).unwrap();
assert_eq!(parsed, variant);
}
}
}
@@ -0,0 +1,147 @@
use serde_derive::{Deserialize, Serialize};
/// Forward-compatible, self-contained API-client copy of the server's `ModelCreator` enum.
///
/// Serialized as a string. Any value this client build does not recognize is preserved
/// verbatim in [`Unknown`], so newer server variants never break deserialization and
/// still round-trip back to the original string.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(from = "String", into = "String")]
pub enum ApiClientModelCreator {
Alibaba,
ArtCraft,
BlackForestLabs,
Bytedance,
Fal,
Google,
Grok,
Hailuo,
Higgsfield,
Kling,
Krea,
Midjourney,
OpenAi,
OpenArt,
Recraft,
Replicate,
Runway,
Stability,
Tencent,
TensorArt,
Vidu,
WorldLabs,
/// A value not known to this client build (preserved as-is).
Unknown(String),
}
impl From<String> for ApiClientModelCreator {
fn from(value: String) -> Self {
match value.as_str() {
"alibaba" => Self::Alibaba,
"artcraft" => Self::ArtCraft,
"black_forest_labs" => Self::BlackForestLabs,
"bytedance" => Self::Bytedance,
"fal" => Self::Fal,
"google" => Self::Google,
"grok" => Self::Grok,
"hailuo" => Self::Hailuo,
"higgsfield" => Self::Higgsfield,
"kling" => Self::Kling,
"krea" => Self::Krea,
"midjourney" => Self::Midjourney,
"open_ai" => Self::OpenAi,
"open_art" => Self::OpenArt,
"recraft" => Self::Recraft,
"replicate" => Self::Replicate,
"runway" => Self::Runway,
"stability" => Self::Stability,
"tencent" => Self::Tencent,
"tensor_art" => Self::TensorArt,
"vidu" => Self::Vidu,
"world_labs" => Self::WorldLabs,
_ => Self::Unknown(value),
}
}
}
impl From<ApiClientModelCreator> for String {
fn from(value: ApiClientModelCreator) -> Self {
match value {
ApiClientModelCreator::Alibaba => "alibaba".to_string(),
ApiClientModelCreator::ArtCraft => "artcraft".to_string(),
ApiClientModelCreator::BlackForestLabs => "black_forest_labs".to_string(),
ApiClientModelCreator::Bytedance => "bytedance".to_string(),
ApiClientModelCreator::Fal => "fal".to_string(),
ApiClientModelCreator::Google => "google".to_string(),
ApiClientModelCreator::Grok => "grok".to_string(),
ApiClientModelCreator::Hailuo => "hailuo".to_string(),
ApiClientModelCreator::Higgsfield => "higgsfield".to_string(),
ApiClientModelCreator::Kling => "kling".to_string(),
ApiClientModelCreator::Krea => "krea".to_string(),
ApiClientModelCreator::Midjourney => "midjourney".to_string(),
ApiClientModelCreator::OpenAi => "open_ai".to_string(),
ApiClientModelCreator::OpenArt => "open_art".to_string(),
ApiClientModelCreator::Recraft => "recraft".to_string(),
ApiClientModelCreator::Replicate => "replicate".to_string(),
ApiClientModelCreator::Runway => "runway".to_string(),
ApiClientModelCreator::Stability => "stability".to_string(),
ApiClientModelCreator::Tencent => "tencent".to_string(),
ApiClientModelCreator::TensorArt => "tensor_art".to_string(),
ApiClientModelCreator::Vidu => "vidu".to_string(),
ApiClientModelCreator::WorldLabs => "world_labs".to_string(),
ApiClientModelCreator::Unknown(other) => other,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn known_variant_round_trips() {
let parsed: ApiClientModelCreator = serde_json::from_str("\"alibaba\"").unwrap();
assert_eq!(parsed, ApiClientModelCreator::Alibaba);
assert_eq!(serde_json::to_string(&parsed).unwrap(), "\"alibaba\"");
}
#[test]
fn unknown_value_is_preserved_and_round_trips() {
let parsed: ApiClientModelCreator = serde_json::from_str("\"zzz_not_a_real_value\"").unwrap();
assert_eq!(parsed, ApiClientModelCreator::Unknown("zzz_not_a_real_value".to_string()));
assert_eq!(serde_json::to_string(&parsed).unwrap(), "\"zzz_not_a_real_value\"");
}
#[test]
fn every_known_variant_round_trips() {
let all = [
(ApiClientModelCreator::Alibaba, "alibaba"),
(ApiClientModelCreator::ArtCraft, "artcraft"),
(ApiClientModelCreator::BlackForestLabs, "black_forest_labs"),
(ApiClientModelCreator::Bytedance, "bytedance"),
(ApiClientModelCreator::Fal, "fal"),
(ApiClientModelCreator::Google, "google"),
(ApiClientModelCreator::Grok, "grok"),
(ApiClientModelCreator::Hailuo, "hailuo"),
(ApiClientModelCreator::Higgsfield, "higgsfield"),
(ApiClientModelCreator::Kling, "kling"),
(ApiClientModelCreator::Krea, "krea"),
(ApiClientModelCreator::Midjourney, "midjourney"),
(ApiClientModelCreator::OpenAi, "open_ai"),
(ApiClientModelCreator::OpenArt, "open_art"),
(ApiClientModelCreator::Recraft, "recraft"),
(ApiClientModelCreator::Replicate, "replicate"),
(ApiClientModelCreator::Runway, "runway"),
(ApiClientModelCreator::Stability, "stability"),
(ApiClientModelCreator::Tencent, "tencent"),
(ApiClientModelCreator::TensorArt, "tensor_art"),
(ApiClientModelCreator::Vidu, "vidu"),
(ApiClientModelCreator::WorldLabs, "world_labs"),
];
for (variant, s) in all {
assert_eq!(String::from(variant.clone()), s, "serialize mismatch for {:?}", variant);
let parsed: ApiClientModelCreator = serde_json::from_str(&format!("\"{}\"", s)).unwrap();
assert_eq!(parsed, variant);
}
}
}
@@ -0,0 +1,71 @@
use serde_derive::{Deserialize, Serialize};
/// Forward-compatible, self-contained API-client copy of the server's `CommonQuality` enum.
///
/// Serialized as a string. Any value this client build does not recognize is preserved
/// verbatim in [`Unknown`], so newer server variants never break deserialization and
/// still round-trip back to the original string.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(from = "String", into = "String")]
pub enum ApiClientQuality {
High,
Medium,
Low,
/// A value not known to this client build (preserved as-is).
Unknown(String),
}
impl From<String> for ApiClientQuality {
fn from(value: String) -> Self {
match value.as_str() {
"high" => Self::High,
"medium" => Self::Medium,
"low" => Self::Low,
_ => Self::Unknown(value),
}
}
}
impl From<ApiClientQuality> for String {
fn from(value: ApiClientQuality) -> Self {
match value {
ApiClientQuality::High => "high".to_string(),
ApiClientQuality::Medium => "medium".to_string(),
ApiClientQuality::Low => "low".to_string(),
ApiClientQuality::Unknown(other) => other,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn known_variant_round_trips() {
let parsed: ApiClientQuality = serde_json::from_str("\"high\"").unwrap();
assert_eq!(parsed, ApiClientQuality::High);
assert_eq!(serde_json::to_string(&parsed).unwrap(), "\"high\"");
}
#[test]
fn unknown_value_is_preserved_and_round_trips() {
let parsed: ApiClientQuality = serde_json::from_str("\"zzz_not_a_real_value\"").unwrap();
assert_eq!(parsed, ApiClientQuality::Unknown("zzz_not_a_real_value".to_string()));
assert_eq!(serde_json::to_string(&parsed).unwrap(), "\"zzz_not_a_real_value\"");
}
#[test]
fn every_known_variant_round_trips() {
let all = [
(ApiClientQuality::High, "high"),
(ApiClientQuality::Medium, "medium"),
(ApiClientQuality::Low, "low"),
];
for (variant, s) in all {
assert_eq!(String::from(variant.clone()), s, "serialize mismatch for {:?}", variant);
let parsed: ApiClientQuality = serde_json::from_str(&format!("\"{}\"", s)).unwrap();
assert_eq!(parsed, variant);
}
}
}
@@ -0,0 +1,91 @@
use serde_derive::{Deserialize, Serialize};
/// Forward-compatible, self-contained API-client copy of the server's `CommonResolution` enum.
///
/// Serialized as a string. Any value this client build does not recognize is preserved
/// verbatim in [`Unknown`], so newer server variants never break deserialization and
/// still round-trip back to the original string.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(from = "String", into = "String")]
pub enum ApiClientResolution {
OneK,
TwoK,
ThreeK,
FourK,
HalfK,
FourEightyP,
SevenTwentyP,
TenEightyP,
/// A value not known to this client build (preserved as-is).
Unknown(String),
}
impl From<String> for ApiClientResolution {
fn from(value: String) -> Self {
match value.as_str() {
"one_k" => Self::OneK,
"two_k" => Self::TwoK,
"three_k" => Self::ThreeK,
"four_k" => Self::FourK,
"half_k" => Self::HalfK,
"four_eighty_p" => Self::FourEightyP,
"seven_twenty_p" => Self::SevenTwentyP,
"ten_eighty_p" => Self::TenEightyP,
_ => Self::Unknown(value),
}
}
}
impl From<ApiClientResolution> for String {
fn from(value: ApiClientResolution) -> Self {
match value {
ApiClientResolution::OneK => "one_k".to_string(),
ApiClientResolution::TwoK => "two_k".to_string(),
ApiClientResolution::ThreeK => "three_k".to_string(),
ApiClientResolution::FourK => "four_k".to_string(),
ApiClientResolution::HalfK => "half_k".to_string(),
ApiClientResolution::FourEightyP => "four_eighty_p".to_string(),
ApiClientResolution::SevenTwentyP => "seven_twenty_p".to_string(),
ApiClientResolution::TenEightyP => "ten_eighty_p".to_string(),
ApiClientResolution::Unknown(other) => other,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn known_variant_round_trips() {
let parsed: ApiClientResolution = serde_json::from_str("\"one_k\"").unwrap();
assert_eq!(parsed, ApiClientResolution::OneK);
assert_eq!(serde_json::to_string(&parsed).unwrap(), "\"one_k\"");
}
#[test]
fn unknown_value_is_preserved_and_round_trips() {
let parsed: ApiClientResolution = serde_json::from_str("\"zzz_not_a_real_value\"").unwrap();
assert_eq!(parsed, ApiClientResolution::Unknown("zzz_not_a_real_value".to_string()));
assert_eq!(serde_json::to_string(&parsed).unwrap(), "\"zzz_not_a_real_value\"");
}
#[test]
fn every_known_variant_round_trips() {
let all = [
(ApiClientResolution::OneK, "one_k"),
(ApiClientResolution::TwoK, "two_k"),
(ApiClientResolution::ThreeK, "three_k"),
(ApiClientResolution::FourK, "four_k"),
(ApiClientResolution::HalfK, "half_k"),
(ApiClientResolution::FourEightyP, "four_eighty_p"),
(ApiClientResolution::SevenTwentyP, "seven_twenty_p"),
(ApiClientResolution::TenEightyP, "ten_eighty_p"),
];
for (variant, s) in all {
assert_eq!(String::from(variant.clone()), s, "serialize mismatch for {:?}", variant);
let parsed: ApiClientResolution = serde_json::from_str(&format!("\"{}\"", s)).unwrap();
assert_eq!(parsed, variant);
}
}
}
@@ -0,0 +1,191 @@
use serde_derive::{Deserialize, Serialize};
/// Forward-compatible, self-contained API-client copy of the server's `CommonVideoModel` enum.
///
/// Serialized as a string. Any value this client build does not recognize is preserved
/// verbatim in [`Unknown`], so newer server variants never break deserialization and
/// still round-trip back to the original string.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(from = "String", into = "String")]
pub enum ApiClientVideoModel {
GrokVideo,
GrokImagineVideo,
GrokImagineVideo1p5,
Kling16Pro,
Kling21Pro,
Kling21Master,
Kling2p5TurboPro,
Kling2p6Pro,
Kling3p0Standard,
Kling3p0Pro,
HappyHorse1p0,
Seedance10Lite,
Seedance1p5Pro,
Seedance2p0,
Seedance2p0Fast,
Seedance2p0BytePlus,
Seedance2p0BytePlusFast,
Seedance2p0Ultra,
Seedance2p0UltraFast,
Seedance2p0BytePlusUltra,
Seedance2p0BytePlusUltraFast,
Seedance2p0Mini,
Seedance2p0BytePlusMini,
Seedance2p0BytePlusUltraMini,
Sora2,
Sora2Pro,
Veo2,
Veo3,
Veo3Fast,
Veo3p1,
Veo3p1Fast,
PreviewModel,
PreviewModelFast,
/// A value not known to this client build (preserved as-is).
Unknown(String),
}
impl From<String> for ApiClientVideoModel {
fn from(value: String) -> Self {
match value.as_str() {
"grok_video" => Self::GrokVideo,
"grok_imagine_video" => Self::GrokImagineVideo,
"grok_imagine_video_1p5" => Self::GrokImagineVideo1p5,
"kling_1p6_pro" => Self::Kling16Pro,
"kling_2p1_pro" => Self::Kling21Pro,
"kling_2p1_master" => Self::Kling21Master,
"kling_2p5_turbo_pro" => Self::Kling2p5TurboPro,
"kling_2p6_pro" => Self::Kling2p6Pro,
"kling_3p0_standard" => Self::Kling3p0Standard,
"kling_3p0_pro" => Self::Kling3p0Pro,
"happy_horse_1p0" => Self::HappyHorse1p0,
"seedance_1p0_lite" => Self::Seedance10Lite,
"seedance_1p5_pro" => Self::Seedance1p5Pro,
"seedance_2p0" => Self::Seedance2p0,
"seedance_2p0_fast" => Self::Seedance2p0Fast,
"seedance_2p0_bp" => Self::Seedance2p0BytePlus,
"seedance_2p0_bp_fast" => Self::Seedance2p0BytePlusFast,
"seedance_2p0_u" => Self::Seedance2p0Ultra,
"seedance_2p0_u_fast" => Self::Seedance2p0UltraFast,
"seedance_2p0_bpu" => Self::Seedance2p0BytePlusUltra,
"seedance_2p0_bpu_fast" => Self::Seedance2p0BytePlusUltraFast,
"seedance_2p0_mini" => Self::Seedance2p0Mini,
"seedance_2p0_bp_mini" => Self::Seedance2p0BytePlusMini,
"seedance_2p0_bpu_mini" => Self::Seedance2p0BytePlusUltraMini,
"sora_2" => Self::Sora2,
"sora_2_pro" => Self::Sora2Pro,
"veo_2" => Self::Veo2,
"veo_3" => Self::Veo3,
"veo_3_fast" => Self::Veo3Fast,
"veo_3p1" => Self::Veo3p1,
"veo_3p1_fast" => Self::Veo3p1Fast,
"preview_model" => Self::PreviewModel,
"preview_model_fast" => Self::PreviewModelFast,
_ => Self::Unknown(value),
}
}
}
impl From<ApiClientVideoModel> for String {
fn from(value: ApiClientVideoModel) -> Self {
match value {
ApiClientVideoModel::GrokVideo => "grok_video".to_string(),
ApiClientVideoModel::GrokImagineVideo => "grok_imagine_video".to_string(),
ApiClientVideoModel::GrokImagineVideo1p5 => "grok_imagine_video_1p5".to_string(),
ApiClientVideoModel::Kling16Pro => "kling_1p6_pro".to_string(),
ApiClientVideoModel::Kling21Pro => "kling_2p1_pro".to_string(),
ApiClientVideoModel::Kling21Master => "kling_2p1_master".to_string(),
ApiClientVideoModel::Kling2p5TurboPro => "kling_2p5_turbo_pro".to_string(),
ApiClientVideoModel::Kling2p6Pro => "kling_2p6_pro".to_string(),
ApiClientVideoModel::Kling3p0Standard => "kling_3p0_standard".to_string(),
ApiClientVideoModel::Kling3p0Pro => "kling_3p0_pro".to_string(),
ApiClientVideoModel::HappyHorse1p0 => "happy_horse_1p0".to_string(),
ApiClientVideoModel::Seedance10Lite => "seedance_1p0_lite".to_string(),
ApiClientVideoModel::Seedance1p5Pro => "seedance_1p5_pro".to_string(),
ApiClientVideoModel::Seedance2p0 => "seedance_2p0".to_string(),
ApiClientVideoModel::Seedance2p0Fast => "seedance_2p0_fast".to_string(),
ApiClientVideoModel::Seedance2p0BytePlus => "seedance_2p0_bp".to_string(),
ApiClientVideoModel::Seedance2p0BytePlusFast => "seedance_2p0_bp_fast".to_string(),
ApiClientVideoModel::Seedance2p0Ultra => "seedance_2p0_u".to_string(),
ApiClientVideoModel::Seedance2p0UltraFast => "seedance_2p0_u_fast".to_string(),
ApiClientVideoModel::Seedance2p0BytePlusUltra => "seedance_2p0_bpu".to_string(),
ApiClientVideoModel::Seedance2p0BytePlusUltraFast => "seedance_2p0_bpu_fast".to_string(),
ApiClientVideoModel::Seedance2p0Mini => "seedance_2p0_mini".to_string(),
ApiClientVideoModel::Seedance2p0BytePlusMini => "seedance_2p0_bp_mini".to_string(),
ApiClientVideoModel::Seedance2p0BytePlusUltraMini => "seedance_2p0_bpu_mini".to_string(),
ApiClientVideoModel::Sora2 => "sora_2".to_string(),
ApiClientVideoModel::Sora2Pro => "sora_2_pro".to_string(),
ApiClientVideoModel::Veo2 => "veo_2".to_string(),
ApiClientVideoModel::Veo3 => "veo_3".to_string(),
ApiClientVideoModel::Veo3Fast => "veo_3_fast".to_string(),
ApiClientVideoModel::Veo3p1 => "veo_3p1".to_string(),
ApiClientVideoModel::Veo3p1Fast => "veo_3p1_fast".to_string(),
ApiClientVideoModel::PreviewModel => "preview_model".to_string(),
ApiClientVideoModel::PreviewModelFast => "preview_model_fast".to_string(),
ApiClientVideoModel::Unknown(other) => other,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn known_variant_round_trips() {
let parsed: ApiClientVideoModel = serde_json::from_str("\"grok_video\"").unwrap();
assert_eq!(parsed, ApiClientVideoModel::GrokVideo);
assert_eq!(serde_json::to_string(&parsed).unwrap(), "\"grok_video\"");
}
#[test]
fn unknown_value_is_preserved_and_round_trips() {
let parsed: ApiClientVideoModel = serde_json::from_str("\"zzz_not_a_real_value\"").unwrap();
assert_eq!(parsed, ApiClientVideoModel::Unknown("zzz_not_a_real_value".to_string()));
assert_eq!(serde_json::to_string(&parsed).unwrap(), "\"zzz_not_a_real_value\"");
}
#[test]
fn every_known_variant_round_trips() {
let all = [
(ApiClientVideoModel::GrokVideo, "grok_video"),
(ApiClientVideoModel::GrokImagineVideo, "grok_imagine_video"),
(ApiClientVideoModel::GrokImagineVideo1p5, "grok_imagine_video_1p5"),
(ApiClientVideoModel::Kling16Pro, "kling_1p6_pro"),
(ApiClientVideoModel::Kling21Pro, "kling_2p1_pro"),
(ApiClientVideoModel::Kling21Master, "kling_2p1_master"),
(ApiClientVideoModel::Kling2p5TurboPro, "kling_2p5_turbo_pro"),
(ApiClientVideoModel::Kling2p6Pro, "kling_2p6_pro"),
(ApiClientVideoModel::Kling3p0Standard, "kling_3p0_standard"),
(ApiClientVideoModel::Kling3p0Pro, "kling_3p0_pro"),
(ApiClientVideoModel::HappyHorse1p0, "happy_horse_1p0"),
(ApiClientVideoModel::Seedance10Lite, "seedance_1p0_lite"),
(ApiClientVideoModel::Seedance1p5Pro, "seedance_1p5_pro"),
(ApiClientVideoModel::Seedance2p0, "seedance_2p0"),
(ApiClientVideoModel::Seedance2p0Fast, "seedance_2p0_fast"),
(ApiClientVideoModel::Seedance2p0BytePlus, "seedance_2p0_bp"),
(ApiClientVideoModel::Seedance2p0BytePlusFast, "seedance_2p0_bp_fast"),
(ApiClientVideoModel::Seedance2p0Ultra, "seedance_2p0_u"),
(ApiClientVideoModel::Seedance2p0UltraFast, "seedance_2p0_u_fast"),
(ApiClientVideoModel::Seedance2p0BytePlusUltra, "seedance_2p0_bpu"),
(ApiClientVideoModel::Seedance2p0BytePlusUltraFast, "seedance_2p0_bpu_fast"),
(ApiClientVideoModel::Seedance2p0Mini, "seedance_2p0_mini"),
(ApiClientVideoModel::Seedance2p0BytePlusMini, "seedance_2p0_bp_mini"),
(ApiClientVideoModel::Seedance2p0BytePlusUltraMini, "seedance_2p0_bpu_mini"),
(ApiClientVideoModel::Sora2, "sora_2"),
(ApiClientVideoModel::Sora2Pro, "sora_2_pro"),
(ApiClientVideoModel::Veo2, "veo_2"),
(ApiClientVideoModel::Veo3, "veo_3"),
(ApiClientVideoModel::Veo3Fast, "veo_3_fast"),
(ApiClientVideoModel::Veo3p1, "veo_3p1"),
(ApiClientVideoModel::Veo3p1Fast, "veo_3p1_fast"),
(ApiClientVideoModel::PreviewModel, "preview_model"),
(ApiClientVideoModel::PreviewModelFast, "preview_model_fast"),
];
for (variant, s) in all {
assert_eq!(String::from(variant.clone()), s, "serialize mismatch for {:?}", variant);
let parsed: ApiClientVideoModel = serde_json::from_str(&format!("\"{}\"", s)).unwrap();
assert_eq!(parsed, variant);
}
}
}
@@ -0,0 +1,8 @@
pub mod api_client_aspect_ratio;
pub mod api_client_bitrate;
pub mod api_client_generation_provider;
pub mod api_client_image_model;
pub mod api_client_model_creator;
pub mod api_client_quality;
pub mod api_client_resolution;
pub mod api_client_video_model;
@@ -0,0 +1 @@
pub mod generation;
@@ -0,0 +1 @@
pub mod common_enums;
@@ -1 +1,2 @@
pub mod generate;
pub mod models;
@@ -0,0 +1 @@
pub mod omni_gen_list_image_models;
@@ -0,0 +1,237 @@
//! Self-contained, forward-compatible binding for `GET /v1/omni_gen/models/image`.
//!
//! IMPORTANT: This module deliberately does NOT reuse any types from
//! `artcraft_api_defs`. Client builds may be deployed in the wild long after the
//! server's models, enums, and response shapes have changed, so every request /
//! response type is copied here and made permissive:
//! - Unknown JSON fields are ignored (serde default behavior).
//! - Missing collection/flag fields default rather than fail (`serde(default)`).
//! - Every string-valued enum has an `Unknown(String)` catch-all so new server
//! variants deserialize instead of erroring.
use serde_derive::{Deserialize, Serialize};
use crate::credentials::storyteller_credential_set::StorytellerCredentialSet;
use crate::datatypes::common_enums::generation::api_client_aspect_ratio::ApiClientAspectRatio;
use crate::datatypes::common_enums::generation::api_client_generation_provider::ApiClientGenerationProvider;
use crate::datatypes::common_enums::generation::api_client_image_model::ApiClientImageModel;
use crate::datatypes::common_enums::generation::api_client_model_creator::ApiClientModelCreator;
use crate::datatypes::common_enums::generation::api_client_quality::ApiClientQuality;
use crate::datatypes::common_enums::generation::api_client_resolution::ApiClientResolution;
use crate::error::storyteller_error::StorytellerError;
use crate::utils::api_host::ApiHost;
use crate::utils::basic_json_get_request::basic_json_get_request;
pub const OMNI_GEN_IMAGE_MODELS_PATH: &str = "/v1/omni_gen/models/image";
/// Arguments for [`omni_gen_list_image_models`].
pub struct OmniGenListImageModelsArgs<'a> {
pub api_host: &'a ApiHost,
pub maybe_creds: Option<&'a StorytellerCredentialSet>,
/// Which provider's models to list. `None` lets the server default (artcraft).
pub provider: Option<OmniGenImageModelsProvider>,
}
/// List available image models.
pub async fn omni_gen_list_image_models(
args: OmniGenListImageModelsArgs<'_>,
) -> Result<OmniGenImageModelsResponse, StorytellerError> {
let path = match args.provider {
Some(provider) => format!("{}?provider={}", OMNI_GEN_IMAGE_MODELS_PATH, provider.as_query_value()),
None => OMNI_GEN_IMAGE_MODELS_PATH.to_string(),
};
Ok(basic_json_get_request(args.api_host, &path, args.maybe_creds).await?)
}
/// The provider filter for the models endpoint (a client-supplied request value).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OmniGenImageModelsProvider {
/// Only models available through ArtCraft.
Artcraft,
/// All known models across all providers.
All,
}
impl OmniGenImageModelsProvider {
pub fn as_query_value(self) -> &'static str {
match self {
Self::Artcraft => "artcraft",
Self::All => "all",
}
}
}
impl Default for OmniGenImageModelsProvider {
fn default() -> Self {
Self::Artcraft
}
}
// ============================ Response types ============================
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct OmniGenImageModelsResponse {
#[serde(default)]
pub success: bool,
#[serde(default)]
pub models: Vec<OmniGenImageModelDetails>,
#[serde(default)]
pub providers: Vec<OmniGenImageModelProviderDetails>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct OmniGenImageModelProviderDetails {
pub provider: ApiClientGenerationProvider,
#[serde(default)]
pub models: Vec<OmniGenImageProviderModelDetails>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct OmniGenImageProviderModelDetails {
pub model: ApiClientImageModel,
#[serde(default)]
pub overrides: Option<OmniGenImageModelDetails>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct OmniGenImageModelDetails {
pub model: ApiClientImageModel,
#[serde(default)]
pub model_creator: Option<ApiClientModelCreator>,
#[serde(default)]
pub full_name: Option<String>,
#[serde(default)]
pub text_prompt_supported: Option<bool>,
#[serde(default)]
pub text_prompt_max_length: Option<u16>,
#[serde(default)]
pub negative_text_prompt_supported: Option<bool>,
#[serde(default)]
pub negative_text_prompt_max_length: Option<u16>,
#[serde(default)]
pub image_refs_supported: Option<bool>,
#[serde(default)]
pub image_refs_max: Option<u16>,
#[serde(default)]
pub has_fixed_editing_aspect_ratio: Option<bool>,
#[serde(default)]
pub aspect_ratio_options: Option<Vec<ApiClientAspectRatio>>,
#[serde(default)]
pub aspect_ratio_default: Option<ApiClientAspectRatio>,
#[serde(default)]
pub aspect_ratio_default_when_editing: Option<ApiClientAspectRatio>,
#[serde(default)]
pub resolution_options: Option<Vec<ApiClientResolution>>,
#[serde(default)]
pub resolution_default: Option<ApiClientResolution>,
#[serde(default)]
pub quality_options: Option<Vec<ApiClientQuality>>,
#[serde(default)]
pub default_quality: Option<ApiClientQuality>,
#[serde(default)]
pub batch_size_min: Option<u16>,
#[serde(default)]
pub batch_size_max: Option<u16>,
#[serde(default)]
pub batch_size_options: Option<Vec<u16>>,
#[serde(default)]
pub batch_size_default: Option<u16>,
#[serde(default)]
pub is_disabled: Option<bool>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn response_tolerates_unknown_fields_and_variants() {
let json = r#"{
"success": true,
"models": [
{
"model": "brand_new_image_model",
"model_creator": "some_new_studio",
"aspect_ratio_options": ["square", "some_new_ratio"],
"surprise_new_field": 123
}
],
"providers": [
{ "provider": "new_provider", "models": [ { "model": "nano_banana_pro" } ] }
],
"another_unexpected_top_level_field": "ignored"
}"#;
let resp: OmniGenImageModelsResponse = serde_json::from_str(json).unwrap();
assert!(resp.success);
assert_eq!(resp.models.len(), 1);
assert_eq!(resp.models[0].model, ApiClientImageModel::Unknown("brand_new_image_model".to_string()));
assert_eq!(resp.models[0].model_creator, Some(ApiClientModelCreator::Unknown("some_new_studio".to_string())));
let ratios = resp.models[0].aspect_ratio_options.as_ref().unwrap();
assert_eq!(ratios[0], ApiClientAspectRatio::Square);
assert_eq!(ratios[1], ApiClientAspectRatio::Unknown("some_new_ratio".to_string()));
assert_eq!(resp.models[0].is_disabled, None);
assert_eq!(resp.providers[0].provider, ApiClientGenerationProvider::Unknown("new_provider".to_string()));
assert_eq!(resp.providers[0].models[0].model, ApiClientImageModel::NanoBananaPro);
}
#[test]
fn empty_object_uses_defaults() {
let resp: OmniGenImageModelsResponse = serde_json::from_str("{}").unwrap();
assert!(!resp.success);
assert!(resp.models.is_empty());
assert!(resp.providers.is_empty());
}
}
/// Live tests that hit real servers. All `#[ignore]` so they never run by default.
/// Run explicitly, e.g.:
/// cargo test -p artcraft_client omni_gen_list_image_models::live_tests -- --ignored --nocapture
#[cfg(test)]
mod live_tests {
mod localhost {
use super::super::{omni_gen_list_image_models, OmniGenListImageModelsArgs};
use crate::utils::api_host::ApiHost;
#[tokio::test]
#[ignore] // live: hits http://localhost:12345
async fn list_image_models() {
let api_host = ApiHost::Localhost { port: 12345 };
let response = omni_gen_list_image_models(OmniGenListImageModelsArgs {
api_host: &api_host,
maybe_creds: None,
provider: None,
})
.await
.expect("request should succeed");
println!("[localhost] image models response: {:#?}", response);
assert!(response.success);
assert!(!response.models.is_empty(), "expected at least one image model");
}
}
mod production {
use super::super::{omni_gen_list_image_models, OmniGenListImageModelsArgs};
use crate::utils::api_host::ApiHost;
#[tokio::test]
#[ignore] // live: hits https://api.storyteller.ai
async fn list_image_models() {
let api_host = ApiHost::Storyteller;
let response = omni_gen_list_image_models(OmniGenListImageModelsArgs {
api_host: &api_host,
maybe_creds: None,
provider: None,
})
.await
.expect("request should succeed");
println!("[production] image models response: {:#?}", response);
assert!(response.success);
assert!(!response.models.is_empty(), "expected at least one image model");
}
}
}
@@ -0,0 +1,2 @@
pub mod image;
pub mod video;
@@ -0,0 +1 @@
pub mod omni_gen_list_video_models;
@@ -0,0 +1,291 @@
//! Self-contained, forward-compatible binding for `GET /v1/omni_gen/models/video`.
//!
//! IMPORTANT: This module deliberately does NOT reuse any types from
//! `artcraft_api_defs`. Client builds may be deployed in the wild long after the
//! server's models, enums, and response shapes have changed, so every request /
//! response type is copied here and made permissive:
//! - Unknown JSON fields are ignored (serde default behavior).
//! - Missing collection/flag fields default rather than fail (`serde(default)`).
//! - Every string-valued enum has an `Unknown(String)` catch-all so new server
//! variants deserialize instead of erroring.
use serde_derive::{Deserialize, Serialize};
use crate::credentials::storyteller_credential_set::StorytellerCredentialSet;
use crate::error::storyteller_error::StorytellerError;
use crate::utils::api_host::ApiHost;
use crate::utils::basic_json_get_request::basic_json_get_request;
use crate::datatypes::common_enums::generation::api_client_aspect_ratio::ApiClientAspectRatio;
use crate::datatypes::common_enums::generation::api_client_bitrate::ApiClientBitrate;
use crate::datatypes::common_enums::generation::api_client_generation_provider::ApiClientGenerationProvider;
use crate::datatypes::common_enums::generation::api_client_model_creator::ApiClientModelCreator;
use crate::datatypes::common_enums::generation::api_client_quality::ApiClientQuality;
use crate::datatypes::common_enums::generation::api_client_resolution::ApiClientResolution;
use crate::datatypes::common_enums::generation::api_client_video_model::ApiClientVideoModel;
pub const OMNI_GEN_VIDEO_MODELS_PATH: &str = "/v1/omni_gen/models/video";
/// Arguments for [`omni_gen_list_video_models`].
pub struct OmniGenListVideoModelsArgs<'a> {
pub api_host: &'a ApiHost,
pub maybe_creds: Option<&'a StorytellerCredentialSet>,
/// Which provider's models to list. `None` lets the server default (artcraft).
pub provider: Option<OmniGenVideoModelsProvider>,
}
/// List available video models.
pub async fn omni_gen_list_video_models(
args: OmniGenListVideoModelsArgs<'_>,
) -> Result<OmniGenVideoModelsResponse, StorytellerError> {
let path = match args.provider {
Some(provider) => format!("{}?provider={}", OMNI_GEN_VIDEO_MODELS_PATH, provider.as_query_value()),
None => OMNI_GEN_VIDEO_MODELS_PATH.to_string(),
};
Ok(basic_json_get_request(args.api_host, &path, args.maybe_creds).await?)
}
/// The provider filter for the models endpoint (a client-supplied request value).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OmniGenVideoModelsProvider {
/// Only models available through ArtCraft.
Artcraft,
/// All known models across all providers.
All,
}
impl OmniGenVideoModelsProvider {
pub fn as_query_value(self) -> &'static str {
match self {
Self::Artcraft => "artcraft",
Self::All => "all",
}
}
}
impl Default for OmniGenVideoModelsProvider {
fn default() -> Self {
Self::Artcraft
}
}
// ============================ Response types ============================
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct OmniGenVideoModelsResponse {
#[serde(default)]
pub success: bool,
#[serde(default)]
pub models: Vec<OmniGenVideoModelDetails>,
#[serde(default)]
pub providers: Vec<OmniGenVideoModelProviderDetails>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct OmniGenVideoModelProviderDetails {
pub provider: ApiClientGenerationProvider,
#[serde(default)]
pub models: Vec<OmniGenVideoProviderModelDetails>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct OmniGenVideoProviderModelDetails {
pub model: ApiClientVideoModel,
#[serde(default)]
pub overrides: Option<OmniGenVideoModelDetails>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct OmniGenVideoModelDetails {
pub model: ApiClientVideoModel,
#[serde(default)]
pub model_creator: Option<ApiClientModelCreator>,
#[serde(default)]
pub full_name: Option<String>,
#[serde(default)]
pub extra_info: Option<String>,
#[serde(default)]
pub extra_info_short: Option<String>,
#[serde(default)]
pub text_to_video_supported: Option<bool>,
#[serde(default)]
pub text_prompt_supported: Option<bool>,
#[serde(default)]
pub text_prompt_max_length: Option<u16>,
#[serde(default)]
pub negative_text_prompt_supported: Option<bool>,
#[serde(default)]
pub negative_text_prompt_max_length: Option<u16>,
#[serde(default)]
pub starting_keyframe_supported: Option<bool>,
#[serde(default)]
pub starting_keyframe_required: Option<bool>,
#[serde(default)]
pub ending_keyframe_supported: Option<bool>,
#[serde(default)]
pub image_references_supported: Option<bool>,
#[serde(default)]
pub image_references_max: Option<u16>,
#[serde(default)]
pub video_references_supported: Option<bool>,
#[serde(default)]
pub video_references_max: Option<u16>,
#[serde(default)]
pub video_references_max_total_duration_seconds: Option<u16>,
#[serde(default)]
pub audio_references_supported: Option<bool>,
#[serde(default)]
pub audio_references_max: Option<u16>,
#[serde(default)]
pub audio_references_max_total_duration_seconds: Option<u16>,
#[serde(default)]
pub character_references_supported: Option<bool>,
#[serde(default)]
pub character_references_max: Option<u16>,
#[serde(default)]
pub show_generate_with_sound_toggle: Option<bool>,
#[serde(default)]
pub aspect_ratio_options: Option<Vec<ApiClientAspectRatio>>,
#[serde(default)]
pub aspect_ratio_default: Option<ApiClientAspectRatio>,
#[serde(default)]
pub resolution_options: Option<Vec<ApiClientResolution>>,
#[serde(default)]
pub resolution_default: Option<ApiClientResolution>,
#[serde(default)]
pub bitrate_options: Option<Vec<ApiClientBitrate>>,
#[serde(default)]
pub bitrate_default: Option<ApiClientBitrate>,
#[serde(default)]
pub quality_options: Option<Vec<ApiClientQuality>>,
#[serde(default)]
pub default_quality: Option<ApiClientQuality>,
#[serde(default)]
pub duration_seconds_min: Option<u16>,
#[serde(default)]
pub duration_seconds_max: Option<u16>,
#[serde(default)]
pub duration_seconds_max_with_image_references: Option<u16>,
#[serde(default)]
pub duration_seconds_options: Option<Vec<u16>>,
#[serde(default)]
pub duration_seconds_default: Option<u16>,
#[serde(default)]
pub batch_size_min: Option<u16>,
#[serde(default)]
pub batch_size_max: Option<u16>,
#[serde(default)]
pub batch_size_options: Option<Vec<u16>>,
#[serde(default)]
pub batch_size_default: Option<u16>,
#[serde(default)]
pub is_disabled: Option<bool>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unknown_enum_value_is_preserved_and_round_trips() {
let known: ApiClientVideoModel = serde_json::from_str("\"seedance_2p0\"").unwrap();
assert_eq!(known, ApiClientVideoModel::Seedance2p0);
assert_eq!(serde_json::to_string(&known).unwrap(), "\"seedance_2p0\"");
// A value this build has never heard of does NOT fail — it is captured verbatim.
let unknown: ApiClientVideoModel = serde_json::from_str("\"future_model_9000\"").unwrap();
assert_eq!(unknown, ApiClientVideoModel::Unknown("future_model_9000".to_string()));
// ...and serializes back to exactly what came in.
assert_eq!(serde_json::to_string(&unknown).unwrap(), "\"future_model_9000\"");
}
#[test]
fn response_tolerates_unknown_fields_and_variants() {
let json = r#"{
"success": true,
"models": [
{
"model": "brand_new_model",
"model_creator": "some_new_studio",
"aspect_ratio_options": ["wide_sixteen_by_nine", "some_new_ratio"],
"surprise_new_field": 123
}
],
"providers": [
{ "provider": "new_provider", "models": [ { "model": "seedance_2p0" } ] }
],
"another_unexpected_top_level_field": "ignored"
}"#;
let resp: OmniGenVideoModelsResponse = serde_json::from_str(json).unwrap();
assert!(resp.success);
assert_eq!(resp.models.len(), 1);
assert_eq!(resp.models[0].model, ApiClientVideoModel::Unknown("brand_new_model".to_string()));
assert_eq!(resp.models[0].model_creator, Some(ApiClientModelCreator::Unknown("some_new_studio".to_string())));
let ratios = resp.models[0].aspect_ratio_options.as_ref().unwrap();
assert_eq!(ratios[0], ApiClientAspectRatio::WideSixteenByNine);
assert_eq!(ratios[1], ApiClientAspectRatio::Unknown("some_new_ratio".to_string()));
assert_eq!(resp.models[0].is_disabled, None); // missing optional -> None
assert_eq!(resp.providers[0].provider, ApiClientGenerationProvider::Unknown("new_provider".to_string()));
assert_eq!(resp.providers[0].models[0].model, ApiClientVideoModel::Seedance2p0);
}
#[test]
fn empty_object_uses_defaults() {
let resp: OmniGenVideoModelsResponse = serde_json::from_str("{}").unwrap();
assert!(!resp.success);
assert!(resp.models.is_empty());
assert!(resp.providers.is_empty());
}
}
/// Live tests that hit real servers. All `#[ignore]` so they never run by default.
/// Run explicitly, e.g.:
/// cargo test -p artcraft_client omni_gen_list_video_models::live_tests -- --ignored --nocapture
#[cfg(test)]
mod live_tests {
mod localhost {
use super::super::{omni_gen_list_video_models, OmniGenListVideoModelsArgs};
use crate::utils::api_host::ApiHost;
#[tokio::test]
#[ignore] // live: hits http://localhost:12345
async fn list_video_models() {
let api_host = ApiHost::Localhost { port: 12345 };
let response = omni_gen_list_video_models(OmniGenListVideoModelsArgs {
api_host: &api_host,
maybe_creds: None,
provider: None,
})
.await
.expect("request should succeed");
println!("[localhost] video models response: {:#?}", response);
assert!(response.success);
assert!(!response.models.is_empty(), "expected at least one video model");
}
}
mod production {
use super::super::{omni_gen_list_video_models, OmniGenListVideoModelsArgs};
use crate::utils::api_host::ApiHost;
#[tokio::test]
#[ignore] // live: hits https://api.storyteller.ai
async fn list_video_models() {
let api_host = ApiHost::Storyteller;
let response = omni_gen_list_video_models(OmniGenListVideoModelsArgs {
api_host: &api_host,
maybe_creds: None,
provider: None,
})
.await
.expect("request should succeed");
println!("[production] video models response: {:#?}", response);
assert!(response.success);
assert!(!response.models.is_empty(), "expected at least one video model");
}
}
}
@@ -1,6 +1,7 @@
//! An API client for Artcraft / Storyteller / FakeYou
pub mod credentials;
pub mod datatypes;
pub mod endpoints;
pub mod error;
pub mod recipes;
@@ -65,6 +65,15 @@ pub enum RouterVideoModel {
#[serde(rename = "seedance_2p0_bpu_fast")]
Seedance2p0BytePlusUltraFast,
#[serde(rename = "seedance_2p0_mini")]
Seedance2p0Mini,
#[serde(rename = "seedance_2p0_bp_mini")]
Seedance2p0BytePlusMini,
#[serde(rename = "seedance_2p0_bpu_mini")]
Seedance2p0BytePlusUltraMini,
#[serde(rename = "happy_horse_1p0")]
HappyHorse1p0,
@@ -95,3 +104,23 @@ pub enum RouterVideoModel {
#[serde(rename = "preview_model_fast")]
PreviewModelFast,
}
#[cfg(test)]
mod tests {
use super::*;
fn assert_serde_round_trip(model: RouterVideoModel, expected: &str) {
let json = serde_json::to_string(&model).unwrap();
assert_eq!(json, format!("\"{expected}\""));
let parsed: RouterVideoModel = serde_json::from_str(&json).unwrap();
// RouterVideoModel isn't PartialEq, so round-trip back to the wire form.
assert_eq!(serde_json::to_string(&parsed).unwrap(), json);
}
#[test]
fn seedance_2p0_mini_variants_serialize() {
assert_serde_round_trip(RouterVideoModel::Seedance2p0Mini, "seedance_2p0_mini");
assert_serde_round_trip(RouterVideoModel::Seedance2p0BytePlusMini, "seedance_2p0_bp_mini");
assert_serde_round_trip(RouterVideoModel::Seedance2p0BytePlusUltraMini, "seedance_2p0_bpu_mini");
}
}
@@ -32,6 +32,9 @@ use crate::generate::generate_video::providers::artcraft::seedance_2p0_bp::build
use crate::generate::generate_video::providers::artcraft::seedance_2p0_bp_fast::build::build_artcraft_seedance_2p0_bp_fast;
use crate::generate::generate_video::providers::artcraft::seedance_2p0_bpu::build::build_artcraft_seedance_2p0_bpu;
use crate::generate::generate_video::providers::artcraft::seedance_2p0_bpu_fast::build::build_artcraft_seedance_2p0_bpu_fast;
use crate::generate::generate_video::providers::artcraft::seedance_2p0_mini::build::build_artcraft_seedance_2p0_mini;
use crate::generate::generate_video::providers::artcraft::seedance_2p0_bp_mini::build::build_artcraft_seedance_2p0_bp_mini;
use crate::generate::generate_video::providers::artcraft::seedance_2p0_bpu_mini::build::build_artcraft_seedance_2p0_bpu_mini;
use crate::generate::generate_video::providers::artcraft::sora_2::build::build_artcraft_sora_2;
use crate::generate::generate_video::providers::artcraft::sora_2_pro::build::build_artcraft_sora_2_pro;
use crate::generate::generate_video::providers::artcraft::veo_2::build::build_artcraft_veo_2;
@@ -62,6 +65,7 @@ use crate::generate::generate_video::providers::fal::veo_3_fast::build::build_fa
use crate::generate::generate_video::providers::fal::veo_3p1::build::build_fal_veo_3p1;
use crate::generate::generate_video::providers::fal::veo_3p1_fast::build::build_fal_veo_3p1_fast;
use crate::generate::generate_video::providers::kinovi::seedance_2p0_fast::build::build_kinovi_seedance_2p0_fast;
use crate::generate::generate_video::providers::kinovi::seedance_2p0_mini::build::build_kinovi_seedance_2p0_mini;
use crate::generate::generate_video::video_generation_draft_or_request::VideoGenerationDraftOrRequest;
/// RouterProvider-agnostic video generation request. Distilled by `build2()` into a
@@ -176,6 +180,9 @@ impl GenerateVideoRequestBuilder {
(RouterProvider::Artcraft, RouterVideoModel::Seedance2p0BytePlusFast) => build_artcraft_seedance_2p0_bp_fast(self),
(RouterProvider::Artcraft, RouterVideoModel::Seedance2p0BytePlusUltra) => build_artcraft_seedance_2p0_bpu(self),
(RouterProvider::Artcraft, RouterVideoModel::Seedance2p0BytePlusUltraFast) => build_artcraft_seedance_2p0_bpu_fast(self),
(RouterProvider::Artcraft, RouterVideoModel::Seedance2p0Mini) => build_artcraft_seedance_2p0_mini(self),
(RouterProvider::Artcraft, RouterVideoModel::Seedance2p0BytePlusMini) => build_artcraft_seedance_2p0_bp_mini(self),
(RouterProvider::Artcraft, RouterVideoModel::Seedance2p0BytePlusUltraMini) => build_artcraft_seedance_2p0_bpu_mini(self),
(RouterProvider::Artcraft, RouterVideoModel::PreviewModel) => build_artcraft_preview_model(self),
(RouterProvider::Artcraft, RouterVideoModel::PreviewModelFast) => build_artcraft_preview_model_fast(self),
(RouterProvider::Artcraft, RouterVideoModel::Seedance10Lite) => build_artcraft_seedance_1p0_lite(self),
@@ -214,6 +221,9 @@ impl GenerateVideoRequestBuilder {
(RouterProvider::Seedance2Pro, RouterVideoModel::HappyHorse1p0) => build_kinovi_happy_horse_1p0(self),
(RouterProvider::Seedance2Pro, RouterVideoModel::Seedance2p0) => build_kinovi_seedance_2p0(self),
(RouterProvider::Seedance2Pro, RouterVideoModel::Seedance2p0Fast) => build_kinovi_seedance_2p0_fast(self),
(RouterProvider::Seedance2Pro, RouterVideoModel::Seedance2p0Mini) => build_kinovi_seedance_2p0_mini(self),
(RouterProvider::Seedance2Pro, RouterVideoModel::Seedance2p0BytePlusMini) => build_kinovi_seedance_2p0_mini(self),
(RouterProvider::Seedance2Pro, RouterVideoModel::Seedance2p0BytePlusUltraMini) => build_kinovi_seedance_2p0_mini(self),
_ => self.unsupported_provider_and_model(),
}
}
@@ -21,6 +21,8 @@ use crate::generate::generate_video::providers::artcraft::resolve::{
pub enum SupportedResolutions {
/// 480p, 720p, 1080p
Full,
/// 480p, 720p, 1080p, 4K
FullWith4k,
/// 480p, 720p only (1080p downgrades to 720p)
Fast,
/// 720p, 1080p only (480p upgrades)
@@ -157,7 +159,7 @@ fn plan_output_resolution(
None => Ok(None),
Some(RouterResolution::FourEightyP) => match supported {
SupportedResolutions::Full | SupportedResolutions::Fast => {
SupportedResolutions::Full | SupportedResolutions::FullWith4k | SupportedResolutions::Fast => {
Ok(Some(CommonResolutionEnum::FourEightyP))
}
SupportedResolutions::NoFourEightyP => match strategy {
@@ -175,7 +177,7 @@ fn plan_output_resolution(
Some(RouterResolution::SevenTwentyP) => Ok(Some(CommonResolutionEnum::SevenTwentyP)),
Some(RouterResolution::TenEightyP) => match supported {
SupportedResolutions::Full | SupportedResolutions::NoFourEightyP => {
SupportedResolutions::Full | SupportedResolutions::FullWith4k | SupportedResolutions::NoFourEightyP => {
Ok(Some(CommonResolutionEnum::TenEightyP))
}
SupportedResolutions::Fast => match strategy {
@@ -189,6 +191,20 @@ fn plan_output_resolution(
},
},
// 4K is only available on models flagged `FullWith4k` (the non-Fast Seedance
// 2.0 family). Other models error out or fall back to their best resolution.
Some(RouterResolution::FourK) => match (supported, strategy) {
(SupportedResolutions::FullWith4k, _) => Ok(Some(CommonResolutionEnum::FourK)),
(_, RequestMismatchMitigationStrategy::ErrorOut) => {
Err(ArtcraftRouterError::Client(ClientError::ModelDoesNotSupportOption {
field: "resolution",
value: format!("{:?}", RouterResolution::FourK),
}))
}
(SupportedResolutions::Fast, _) => Ok(Some(CommonResolutionEnum::SevenTwentyP)),
(_, _) => Ok(Some(CommonResolutionEnum::TenEightyP)),
},
Some(unsupported) => match strategy {
RequestMismatchMitigationStrategy::ErrorOut => {
Err(ArtcraftRouterError::Client(ClientError::ModelDoesNotSupportOption {
@@ -14,7 +14,7 @@ use crate::generate::generate_video::video_generation_request::VideoGenerationRe
///
/// Same constraints as the v1 variant — xAI v1.5 still supports only 480p
/// and 720p and no 21:9 ultra-wide. The on-wire model identifier is
/// `grok-imagine-video-1.5-preview`; the cost calculator in
/// `grok-imagine-video-1.5`; the cost calculator in
/// [`super::cost`] keys off that to apply the v1.5 pricing tier (with a 5%
/// ArtCraft markup on top of the upstream rates).
pub fn build_artcraft_grok_imagine_video_1p5(
@@ -23,7 +23,7 @@ pub fn build_artcraft_grok_imagine_video_1p5(
let request = build_artcraft_omni_video_request(
builder,
CommonVideoModelEnum::GrokImagineVideo1p5,
SupportedResolutions::Fast,
SupportedResolutions::Full,
UltraWideSupport::Unsupported,
)?;
@@ -34,7 +34,7 @@ pub fn build_artcraft_grok_imagine_video_1p5(
{
return Err(ArtcraftRouterError::Client(ClientError::ModelDoesNotSupportOption {
field: "image_inputs",
value: "text-to-video isn't supported by grok-imagine-video-1.5-preview; supply a start_frame or at least one reference image".to_string(),
value: "text-to-video isn't supported by grok-imagine-video-1.5; supply a start_frame or at least one reference image".to_string(),
}));
}
@@ -113,10 +113,10 @@ mod tests {
}
#[test]
fn res_1080p_downgrades_to_720p() {
// SupportedResolutions::Fast caps at 720p (Grok Imagine doesn't render 1080p output).
fn res_1080p_is_supported() {
// Grok Imagine 1.5 produces genuine 1080p output.
let req = unwrap_request(make_builder(|b| { b.resolution = Some(RouterResolution::TenEightyP); }));
assert_eq!(req.request.resolution, Some(CommonResolutionEnum::SevenTwentyP));
assert_eq!(req.request.resolution, Some(CommonResolutionEnum::TenEightyP));
}
#[test]
@@ -71,7 +71,7 @@ impl ArtcraftGrokImagineVideo1p5CostState {
if self.input_image_count == 0 {
return Err(ArtcraftRouterError::Client(ClientError::ModelDoesNotSupportOption {
field: "image_inputs",
value: "text-to-video isn't supported by grok-imagine-video-1.5-preview; supply a start_frame or at least one reference image".to_string(),
value: "text-to-video isn't supported by grok-imagine-video-1.5; supply a start_frame or at least one reference image".to_string(),
}));
}
@@ -99,8 +99,9 @@ impl ArtcraftGrokImagineVideo1p5CostState {
fn build_equivalent_grok_request(&self) -> GrokVideoGenerationRequest {
let resolution = Some(match self.resolution {
CommonResolution::FourEightyP => GrokResolution::FourEightyP,
// Grok Imagine caps at 720p (and our build step downgrades higher
// tiers via SupportedResolutions::Fast); price anything else as 720p.
CommonResolution::TenEightyP => GrokResolution::TenEightyP,
// Grok Imagine 1.5 tops out at 1080p (the build step downgrades higher
// tiers via SupportedResolutions::Full); price anything else as 720p.
_ => GrokResolution::SevenTwentyP,
});
@@ -119,7 +120,7 @@ impl ArtcraftGrokImagineVideo1p5CostState {
GrokVideoGenerationRequest {
prompt: String::new(),
model: Some(GrokVideoModel::GrokImagineVideo1p5Preview),
model: Some(GrokVideoModel::GrokImagineVideo1p5),
image,
reference_images,
aspect_ratio: None,
@@ -317,12 +318,13 @@ mod tests {
}
#[test]
fn ten_eighty_p_request_clamps_to_720p_pricing() {
fn ten_eighty_p_prices_higher_than_720p() {
// Grok Imagine 1.5 now renders genuine 1080p ($0.25/s vs $0.14/s @ 720p).
let p1080 = build_cost_via_builder(Some(RouterResolution::TenEightyP), 10, 1)
.cost_in_usd_cents.unwrap();
let p720 = build_cost_via_builder(Some(RouterResolution::SevenTwentyP), 10, 1)
.cost_in_usd_cents.unwrap();
assert_eq!(p1080, p720);
assert!(p1080 > p720, "1080p ({p1080}) should cost more than 720p ({p720})");
}
}
@@ -20,7 +20,7 @@ impl ArtcraftGrokImagineVideo1p5RequestState {
{
return Err(ArtcraftRouterError::Client(ClientError::ModelDoesNotSupportOption {
field: "image_inputs",
value: "text-to-video isn't supported by grok-imagine-video-1.5-preview; supply a start_frame or at least one reference image".to_string(),
value: "text-to-video isn't supported by grok-imagine-video-1.5; supply a start_frame or at least one reference image".to_string(),
}));
}
@@ -1,4 +1,5 @@
pub(crate) mod build_common;
pub(crate) mod seedance_common;
#[cfg(test)]
mod parity_tests;
pub mod grok_imagine_video;
@@ -25,6 +26,9 @@ pub mod seedance_2p0_bp;
pub mod seedance_2p0_bp_fast;
pub mod seedance_2p0_bpu;
pub mod seedance_2p0_bpu_fast;
pub mod seedance_2p0_mini;
pub mod seedance_2p0_bp_mini;
pub mod seedance_2p0_bpu_mini;
pub mod sora_2;
pub mod sora_2_pro;
pub mod veo_2;
@@ -13,7 +13,7 @@ pub fn build_artcraft_seedance_2p0(builder: GenerateVideoRequestBuilder) -> Resu
let request = build_artcraft_omni_video_request(
builder,
CommonVideoModelEnum::Seedance2p0,
SupportedResolutions::Full,
SupportedResolutions::FullWith4k,
UltraWideSupport::Supported,
)?;
let state = ArtcraftSeedance2p0RequestState { request };
@@ -105,6 +105,12 @@ mod tests {
assert_eq!(req.request.resolution, Some(CommonResolutionEnum::TenEightyP));
}
#[test]
fn res_4k() {
let req = unwrap_request(make_builder(|b| { b.resolution = Some(RouterResolution::FourK); }));
assert_eq!(req.request.resolution, Some(CommonResolutionEnum::FourK));
}
#[test]
fn none_stays_none() {
let req = unwrap_request(make_builder(|_| {}));
@@ -1,7 +1,8 @@
use enums::common::generation::common_resolution::CommonResolution;
use crate::generate::generate_video::video_generation_cost_estimate::VideoGenerationCostEstimate;
use crate::generate::generate_video::providers::artcraft::seedance_common::seedance_2p0_four_k_usd_cents;
use crate::generate::generate_video::providers::artcraft::seedance_2p0::request::ArtcraftSeedance2p0RequestState;
use crate::generate::generate_video::video_generation_cost_estimate::VideoGenerationCostEstimate;
// ── Pricing constants ──
//
@@ -47,6 +48,23 @@ impl ArtcraftSeedance2p0CostState {
}
pub fn estimate_cost(&self) -> VideoGenerationCostEstimate {
if self.resolution == CommonResolution::FourK {
let usd_cents = seedance_2p0_four_k_usd_cents(
self.duration_seconds,
self.batch_count,
self.has_video_reference,
);
return VideoGenerationCostEstimate {
cost_in_credits: Some(usd_cents),
cost_in_usd_cents: Some(usd_cents),
is_free: false,
is_unlimited: false,
is_rate_limited: false,
has_watermark: false,
failures_are_refunded: None,
};
}
let cents_per_second = match self.resolution {
CommonResolution::FourEightyP => CENTS_PER_SECOND_480P,
CommonResolution::TenEightyP => CENTS_PER_SECOND_1080P,
@@ -71,8 +89,8 @@ impl ArtcraftSeedance2p0CostState {
#[cfg(test)]
mod tests {
use crate::api::router_resolution::RouterResolution;
use crate::api::router_provider::RouterProvider;
use crate::api::router_resolution::RouterResolution;
use crate::generate::generate_video::generate_video_request_builder::GenerateVideoRequestBuilder;
// -- 720p pricing --
@@ -157,6 +175,40 @@ mod tests {
}
}
// -- 4K pricing --
mod four_k_pricing {
use enums::common::generation::common_resolution::CommonResolution;
fn artcraft_4k_cents(duration_seconds: u16, batch_count: u16, has_video_reference: bool) -> u64 {
super::super::ArtcraftSeedance2p0CostState {
resolution: CommonResolution::FourK,
duration_seconds,
batch_count,
has_video_reference,
}
.estimate_cost()
.cost_in_usd_cents
.unwrap()
}
#[test]
fn explicit_4k_without_video_reference() {
assert_eq!(artcraft_4k_cents(4, 1, false), 347);
assert_eq!(artcraft_4k_cents(5, 1, false), 433);
assert_eq!(artcraft_4k_cents(10, 1, false), 866);
assert_eq!(artcraft_4k_cents(15, 1, false), 1299);
}
#[test]
fn explicit_4k_with_video_reference() {
assert_eq!(artcraft_4k_cents(4, 1, true), 416);
assert_eq!(artcraft_4k_cents(5, 1, true), 519);
assert_eq!(artcraft_4k_cents(10, 1, true), 1038);
assert_eq!(artcraft_4k_cents(15, 1, true), 1557);
}
}
// -- Relative pricing --
mod relative_pricing_tests {
@@ -171,6 +223,13 @@ mod tests {
assert!(c720 < c1080);
}
#[test]
fn cost_4k_more_expensive_than_1080p() {
let c1080 = cost_cents(Some(RouterResolution::TenEightyP), 5, 1);
let c4k = cost_cents(Some(RouterResolution::FourK), 5, 1);
assert!(c4k > c1080);
}
#[test]
fn cost_scales_with_duration() {
let c4 = cost_cents(Some(RouterResolution::SevenTwentyP), 4, 1);
@@ -201,6 +260,7 @@ mod tests {
Some(RouterResolution::FourEightyP),
Some(RouterResolution::SevenTwentyP),
Some(RouterResolution::TenEightyP),
Some(RouterResolution::FourK),
None,
];
for res in resolutions {
@@ -13,7 +13,7 @@ pub fn build_artcraft_seedance_2p0_bp(builder: GenerateVideoRequestBuilder) -> R
let request = build_artcraft_omni_video_request(
builder,
CommonVideoModelEnum::Seedance2p0BytePlus,
SupportedResolutions::Full,
SupportedResolutions::FullWith4k,
UltraWideSupport::Supported,
)?;
let state = ArtcraftSeedance2p0BytePlusRequestState { request };
@@ -101,6 +101,12 @@ mod tests {
assert_eq!(req.request.resolution, Some(CommonResolutionEnum::TenEightyP));
}
#[test]
fn res_4k() {
let req = unwrap_request(make_builder(|b| { b.resolution = Some(RouterResolution::FourK); }));
assert_eq!(req.request.resolution, Some(CommonResolutionEnum::FourK));
}
#[test]
fn none_stays_none() {
let req = unwrap_request(make_builder(|_| {}));
@@ -1,7 +1,8 @@
use enums::common::generation::common_resolution::CommonResolution;
use crate::generate::generate_video::video_generation_cost_estimate::VideoGenerationCostEstimate;
use crate::generate::generate_video::providers::artcraft::seedance_common::seedance_2p0_four_k_usd_cents;
use crate::generate::generate_video::providers::artcraft::seedance_2p0_bp::request::ArtcraftSeedance2p0BytePlusRequestState;
use crate::generate::generate_video::video_generation_cost_estimate::VideoGenerationCostEstimate;
/// USD cents per second by resolution:
/// 480p: $0.10/s = 10.0 ¢/s
@@ -15,6 +16,7 @@ pub struct ArtcraftSeedance2p0BytePlusCostState {
pub resolution: CommonResolution,
pub duration_seconds: u16,
pub batch_count: u16,
pub has_video_reference: bool,
}
impl ArtcraftSeedance2p0BytePlusCostState {
@@ -23,10 +25,30 @@ impl ArtcraftSeedance2p0BytePlusCostState {
.unwrap_or(CommonResolution::SevenTwentyP);
let duration_seconds = request.request.duration_seconds.unwrap_or(5);
let batch_count = request.request.video_batch_count.unwrap_or(1);
Self { resolution, duration_seconds, batch_count }
let has_video_reference = request.request.reference_video_media_tokens
.as_ref()
.is_some_and(|tokens| !tokens.is_empty());
Self { resolution, duration_seconds, batch_count, has_video_reference }
}
pub fn estimate_cost(&self) -> VideoGenerationCostEstimate {
if self.resolution == CommonResolution::FourK {
let usd_cents = seedance_2p0_four_k_usd_cents(
self.duration_seconds,
self.batch_count,
self.has_video_reference,
);
return VideoGenerationCostEstimate {
cost_in_credits: Some(usd_cents),
cost_in_usd_cents: Some(usd_cents),
is_free: false,
is_unlimited: false,
is_rate_limited: false,
has_watermark: false,
failures_are_refunded: None,
};
}
let cents_per_second = match self.resolution {
CommonResolution::FourEightyP => CENTS_PER_SECOND_480P,
CommonResolution::TenEightyP => CENTS_PER_SECOND_1080P,
@@ -49,9 +71,9 @@ impl ArtcraftSeedance2p0BytePlusCostState {
#[cfg(test)]
mod tests {
use crate::api::router_provider::RouterProvider;
use crate::api::router_resolution::RouterResolution;
use crate::api::router_video_model::RouterVideoModel;
use crate::api::router_provider::RouterProvider;
use crate::generate::generate_video::generate_video_request_builder::GenerateVideoRequestBuilder;
mod pricing_720p {
@@ -125,6 +147,38 @@ mod tests {
}
}
mod four_k_pricing {
use enums::common::generation::common_resolution::CommonResolution;
fn artcraft_4k_cents(duration_seconds: u16, batch_count: u16, has_video_reference: bool) -> u64 {
super::super::ArtcraftSeedance2p0BytePlusCostState {
resolution: CommonResolution::FourK,
duration_seconds,
batch_count,
has_video_reference,
}
.estimate_cost()
.cost_in_usd_cents
.unwrap()
}
#[test]
fn explicit_4k_without_video_reference() {
assert_eq!(artcraft_4k_cents(4, 1, false), 347);
assert_eq!(artcraft_4k_cents(5, 1, false), 433);
assert_eq!(artcraft_4k_cents(10, 1, false), 866);
assert_eq!(artcraft_4k_cents(15, 1, false), 1299);
}
#[test]
fn explicit_4k_with_video_reference() {
assert_eq!(artcraft_4k_cents(4, 1, true), 416);
assert_eq!(artcraft_4k_cents(5, 1, true), 519);
assert_eq!(artcraft_4k_cents(10, 1, true), 1038);
assert_eq!(artcraft_4k_cents(15, 1, true), 1557);
}
}
mod relative_pricing_tests {
use super::*;
@@ -0,0 +1,225 @@
use enums::common::generation::common_video_model::CommonVideoModel as CommonVideoModelEnum;
use crate::errors::artcraft_router_error::ArtcraftRouterError;
use crate::generate::generate_video::generate_video_request_builder::GenerateVideoRequestBuilder;
use crate::generate::generate_video::providers::artcraft::build_common::{
build_artcraft_omni_video_request, SupportedResolutions, UltraWideSupport,
};
use crate::generate::generate_video::providers::artcraft::seedance_2p0_bp_mini::request::ArtcraftSeedance2p0BytePlusMiniRequestState;
use crate::generate::generate_video::video_generation_draft_or_request::VideoGenerationDraftOrRequest;
use crate::generate::generate_video::video_generation_request::VideoGenerationRequest;
pub fn build_artcraft_seedance_2p0_bp_mini(builder: GenerateVideoRequestBuilder) -> Result<VideoGenerationDraftOrRequest, ArtcraftRouterError> {
// Seedance 2.0 Mini supports 480p and 720p only (higher resolutions downgrade
// to 720p), and all six aspect ratios including 21:9.
let request = build_artcraft_omni_video_request(
builder,
CommonVideoModelEnum::Seedance2p0BytePlusMini,
SupportedResolutions::Fast,
UltraWideSupport::Supported,
)?;
let state = ArtcraftSeedance2p0BytePlusMiniRequestState { request };
Ok(VideoGenerationDraftOrRequest::Request(VideoGenerationRequest::ArtcraftSeedance2p0BytePlusMini(state)))
}
#[cfg(test)]
mod tests {
use enums::common::generation::common_aspect_ratio::CommonAspectRatio as CommonAspectRatioEnum;
use enums::common::generation::common_resolution::CommonResolution as CommonResolutionEnum;
use enums::common::generation::common_video_model::CommonVideoModel as CommonVideoModelEnum;
use enums::common::generation::common_bitrate::CommonBitrate as CommonBitrateEnum;
use tokens::tokens::characters::CharacterToken;
use tokens::tokens::media_files::MediaFileToken;
use crate::api::character_list_ref::CharacterListRef;
use crate::api::router_aspect_ratio::RouterAspectRatio;
use crate::api::router_bitrate::RouterBitrate;
use crate::api::router_resolution::RouterResolution;
use crate::api::router_video_model::RouterVideoModel;
use crate::api::image_list_ref::ImageListRef;
use crate::api::image_ref::ImageRef;
use crate::api::router_provider::RouterProvider;
use crate::client::request_mismatch_mitigation_strategy::RequestMismatchMitigationStrategy;
use crate::generate::generate_video::generate_video_request_builder::GenerateVideoRequestBuilder;
use crate::generate::generate_video::video_generation_draft_or_request::VideoGenerationDraftOrRequest;
use crate::generate::generate_video::video_generation_request::VideoGenerationRequest;
use super::*;
mod field_conversions {
use super::*;
#[test]
fn prompt_is_passed_through() {
let req = unwrap_request(builder_with(|b| { b.prompt = Some("test".to_string()); }));
assert_eq!(req.request.prompt, Some("test".to_string()));
}
#[test]
fn model_is_correct() {
let req = unwrap_request(builder_with(|_| {}));
assert!(matches!(req.request.model, Some(CommonVideoModelEnum::Seedance2p0BytePlusMini)));
}
#[test]
fn duration_passed_through() {
let req = unwrap_request(builder_with(|b| { b.duration_seconds = Some(10); }));
assert_eq!(req.request.duration_seconds, Some(10));
}
#[test]
fn duration_clamped_to_max() {
let req = unwrap_request(builder_with(|b| { b.duration_seconds = Some(99); }));
assert_eq!(req.request.duration_seconds, Some(15));
}
#[test]
fn batch_count_passed_through() {
let req = unwrap_request(builder_with(|b| { b.video_batch_count = Some(4); }));
assert_eq!(req.request.video_batch_count, Some(4));
}
#[test]
fn batch_count_clamped_to_platform_max() {
// The ArtCraft platform caps batch at 4 and downgrades higher requests.
let req = unwrap_request(builder_with(|b| { b.video_batch_count = Some(8); }));
assert_eq!(req.request.video_batch_count, Some(4));
}
#[test]
fn bitrate_passed_through() {
let req = unwrap_request(builder_with(|b| { b.bitrate = Some(RouterBitrate::High); }));
assert_eq!(req.request.bitrate, Some(CommonBitrateEnum::High));
}
}
mod aspect_ratio_tests {
use super::*;
#[test]
fn wide() {
let req = unwrap_request(builder_with(|b| { b.aspect_ratio = Some(RouterAspectRatio::WideSixteenByNine); }));
assert_eq!(req.request.aspect_ratio, Some(CommonAspectRatioEnum::WideSixteenByNine));
}
#[test]
fn ultra_wide() {
let req = unwrap_request(builder_with(|b| { b.aspect_ratio = Some(RouterAspectRatio::WideTwentyOneByNine); }));
assert_eq!(req.request.aspect_ratio, Some(CommonAspectRatioEnum::WideTwentyOneByNine));
}
#[test]
fn tall() {
let req = unwrap_request(builder_with(|b| { b.aspect_ratio = Some(RouterAspectRatio::TallNineBySixteen); }));
assert_eq!(req.request.aspect_ratio, Some(CommonAspectRatioEnum::TallNineBySixteen));
}
#[test]
fn square() {
let req = unwrap_request(builder_with(|b| { b.aspect_ratio = Some(RouterAspectRatio::Square); }));
assert_eq!(req.request.aspect_ratio, Some(CommonAspectRatioEnum::Square));
}
}
mod resolution_tests {
use super::*;
#[test]
fn res_480p() {
let req = unwrap_request(builder_with(|b| { b.resolution = Some(RouterResolution::FourEightyP); }));
assert_eq!(req.request.resolution, Some(CommonResolutionEnum::FourEightyP));
}
#[test]
fn res_720p() {
let req = unwrap_request(builder_with(|b| { b.resolution = Some(RouterResolution::SevenTwentyP); }));
assert_eq!(req.request.resolution, Some(CommonResolutionEnum::SevenTwentyP));
}
#[test]
fn res_1080p_downgrades_to_720p() {
let req = unwrap_request(builder_with(|b| { b.resolution = Some(RouterResolution::TenEightyP); }));
assert_eq!(req.request.resolution, Some(CommonResolutionEnum::SevenTwentyP));
}
#[test]
fn res_1080p_error_out() {
let result = build_artcraft_seedance_2p0_bp_mini(GenerateVideoRequestBuilder {
model: RouterVideoModel::Seedance2p0BytePlusMini,
provider: RouterProvider::Artcraft,
resolution: Some(RouterResolution::TenEightyP),
request_mismatch_mitigation_strategy: RequestMismatchMitigationStrategy::ErrorOut,
..Default::default()
});
assert!(result.is_err());
}
#[test]
fn none_stays_none() {
let req = unwrap_request(builder_with(|_| {}));
assert!(req.request.resolution.is_none());
}
}
mod media_token_tests {
use super::*;
#[test]
fn start_frame_token_passed_through() {
let token = MediaFileToken::new("mf_start".to_string());
let req = unwrap_request(builder_with(|b| { b.start_frame = Some(ImageRef::MediaFileToken(token.clone())); }));
assert_eq!(req.request.start_frame_image_media_token, Some(token));
}
#[test]
fn url_start_frame_rejected() {
let result = build_artcraft_seedance_2p0_bp_mini(GenerateVideoRequestBuilder {
model: RouterVideoModel::Seedance2p0BytePlusMini,
provider: RouterProvider::Artcraft,
start_frame: Some(ImageRef::Url("https://example.com".to_string())),
..Default::default()
});
assert!(result.is_err());
}
#[test]
fn reference_image_tokens_passed_through() {
let tokens = vec![
MediaFileToken::new("mf_a".to_string()),
MediaFileToken::new("mf_b".to_string()),
];
let req = unwrap_request(builder_with(|b| { b.reference_images = Some(ImageListRef::MediaFileTokens(tokens.clone())); }));
assert_eq!(req.request.reference_image_media_tokens, Some(tokens));
}
#[test]
fn character_tokens_passed_through() {
let tokens = vec![
CharacterToken::new("char_a".to_string()),
CharacterToken::new("char_b".to_string()),
];
let req = unwrap_request(builder_with(|b| { b.reference_character_tokens = Some(CharacterListRef::CharacterTokens(tokens.clone())); }));
assert_eq!(req.request.reference_character_tokens, Some(tokens));
}
}
fn builder_with(f: impl FnOnce(&mut GenerateVideoRequestBuilder)) -> GenerateVideoRequestBuilder {
let mut builder = GenerateVideoRequestBuilder {
model: RouterVideoModel::Seedance2p0BytePlusMini,
provider: RouterProvider::Artcraft,
duration_seconds: Some(5),
video_batch_count: Some(1),
..Default::default()
};
f(&mut builder);
builder
}
fn unwrap_request(builder: GenerateVideoRequestBuilder) -> ArtcraftSeedance2p0BytePlusMiniRequestState {
let result = build_artcraft_seedance_2p0_bp_mini(builder).expect("build should succeed");
match result {
VideoGenerationDraftOrRequest::Request(VideoGenerationRequest::ArtcraftSeedance2p0BytePlusMini(state)) => state,
_ => panic!("expected ArtcraftSeedance2p0BytePlusMini request"),
}
}
}
@@ -0,0 +1,176 @@
use enums::common::generation::common_resolution::CommonResolution;
use crate::generate::generate_video::video_generation_cost_estimate::VideoGenerationCostEstimate;
use crate::generate::generate_video::providers::artcraft::seedance_common::seedance_2p0_byteplus_mini_usd_cents;
use crate::generate::generate_video::providers::artcraft::seedance_2p0_bp_mini::request::ArtcraftSeedance2p0BytePlusMiniRequestState;
pub struct ArtcraftSeedance2p0BytePlusMiniCostState {
pub resolution: CommonResolution,
pub duration_seconds: u16,
pub batch_count: u16,
pub has_video_reference: bool,
}
impl ArtcraftSeedance2p0BytePlusMiniCostState {
pub fn from_request(request: &ArtcraftSeedance2p0BytePlusMiniRequestState) -> Self {
let resolution = request.request.resolution
.unwrap_or(CommonResolution::SevenTwentyP);
let duration_seconds = request.request.duration_seconds.unwrap_or(5);
let batch_count = request.request.video_batch_count.unwrap_or(1);
let has_video_reference = request.request.reference_video_media_tokens
.as_ref()
.is_some_and(|tokens| !tokens.is_empty());
Self { resolution, duration_seconds, batch_count, has_video_reference }
}
pub fn estimate_cost(&self) -> VideoGenerationCostEstimate {
// BytePlus / BytePlus Ultra Mini share a higher-margin rate set; see
// seedance_common::seedance_2p0_byteplus_mini_usd_cents.
let usd_cents = seedance_2p0_byteplus_mini_usd_cents(
self.resolution,
self.duration_seconds,
self.batch_count,
self.has_video_reference,
);
// ArtCraft credits: 100 credits = $1.00, so credits = cents.
VideoGenerationCostEstimate {
cost_in_credits: Some(usd_cents),
cost_in_usd_cents: Some(usd_cents),
is_free: false,
is_unlimited: false,
is_rate_limited: false,
has_watermark: false,
failures_are_refunded: None,
}
}
}
#[cfg(test)]
mod tests {
use tokens::tokens::media_files::MediaFileToken;
use crate::api::router_resolution::RouterResolution;
use crate::api::router_video_model::RouterVideoModel;
use crate::api::router_provider::RouterProvider;
use crate::api::video_list_ref::VideoListRef;
use crate::generate::generate_video::generate_video_request_builder::GenerateVideoRequestBuilder;
use crate::generate::generate_video::video_generation_cost_estimate::VideoGenerationCostEstimate;
// Every combination, driven through the full build pipeline. These prices are
// the supplier's per-combo cost plus a 5% margin, rounded up to whole cents.
mod pricing_480p {
use super::*;
#[test]
fn without_video_reference() {
assert_eq!(cents(RouterResolution::FourEightyP, 4, 1, false), 14);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 1, false), 17);
assert_eq!(cents(RouterResolution::FourEightyP, 10, 1, false), 33);
assert_eq!(cents(RouterResolution::FourEightyP, 15, 1, false), 50);
}
#[test]
fn with_video_reference() {
assert_eq!(cents(RouterResolution::FourEightyP, 4, 1, true), 17);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 1, true), 21);
assert_eq!(cents(RouterResolution::FourEightyP, 10, 1, true), 42);
assert_eq!(cents(RouterResolution::FourEightyP, 15, 1, true), 63);
}
}
mod pricing_720p {
use super::*;
#[test]
fn without_video_reference() {
assert_eq!(cents(RouterResolution::SevenTwentyP, 4, 1, false), 35);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 1, false), 44);
assert_eq!(cents(RouterResolution::SevenTwentyP, 10, 1, false), 88);
assert_eq!(cents(RouterResolution::SevenTwentyP, 15, 1, false), 131);
}
#[test]
fn with_video_reference() {
assert_eq!(cents(RouterResolution::SevenTwentyP, 4, 1, true), 42);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 1, true), 53);
assert_eq!(cents(RouterResolution::SevenTwentyP, 10, 1, true), 105);
assert_eq!(cents(RouterResolution::SevenTwentyP, 15, 1, true), 158);
}
#[test]
fn none_defaults_to_720p() {
assert_eq!(cents_no_ref(None, 5, 1), cents(RouterResolution::SevenTwentyP, 5, 1, false));
}
}
mod credits_tests {
use super::*;
#[test]
fn credits_equal_usd_cents_all_combos() {
let resolutions = [
Some(RouterResolution::FourEightyP),
Some(RouterResolution::SevenTwentyP),
None,
];
for res in resolutions {
for dur in [4u16, 5, 10, 15] {
for batch in [1u16, 2, 4] {
for has_ref in [false, true] {
let cost = build_cost(res, dur, batch, has_ref);
assert_eq!(cost.cost_in_credits, cost.cost_in_usd_cents);
}
}
}
}
}
}
fn build_cost(
resolution: Option<RouterResolution>,
duration_seconds: u16,
video_batch_count: u16,
with_video_reference: bool,
) -> VideoGenerationCostEstimate {
let reference_videos = with_video_reference.then(|| {
VideoListRef::MediaFileTokens(vec![MediaFileToken::new("mf_ref".to_string())])
});
let builder = GenerateVideoRequestBuilder {
model: RouterVideoModel::Seedance2p0BytePlusMini,
provider: RouterProvider::Artcraft,
resolution,
duration_seconds: Some(duration_seconds),
video_batch_count: Some(video_batch_count),
reference_videos,
..Default::default()
};
builder.build2()
.expect("build2 should succeed")
.estimate_cost()
.expect("estimate_cost should succeed")
}
fn cents(
resolution: RouterResolution,
duration_seconds: u16,
video_batch_count: u16,
with_video_reference: bool,
) -> u64 {
build_cost(Some(resolution), duration_seconds, video_batch_count, with_video_reference)
.cost_in_usd_cents
.unwrap()
}
fn cents_no_ref(
resolution: Option<RouterResolution>,
duration_seconds: u16,
video_batch_count: u16,
) -> u64 {
build_cost(resolution, duration_seconds, video_batch_count, false)
.cost_in_usd_cents
.unwrap()
}
}
@@ -0,0 +1,3 @@
pub mod build;
pub mod cost;
pub mod request;
@@ -0,0 +1,86 @@
use artcraft_api_defs::omni_gen::cost_and_generate_requests::omni_gen_video_cost_and_generate_request::OmniGenVideoCostAndGenerateRequest;
use crate::client::router_artcraft_client::RouterArtcraftClient;
use crate::errors::artcraft_router_error::ArtcraftRouterError;
use crate::generate::generate_video::generate_video_response::GenerateVideoResponse;
use crate::generate::generate_video::providers::artcraft::request_common::send_artcraft_omni_video_request;
#[derive(Clone, Debug)]
pub struct ArtcraftSeedance2p0BytePlusMiniRequestState {
pub request: OmniGenVideoCostAndGenerateRequest,
}
impl ArtcraftSeedance2p0BytePlusMiniRequestState {
pub async fn send(&self, client: &RouterArtcraftClient) -> Result<GenerateVideoResponse, ArtcraftRouterError> {
send_artcraft_omni_video_request(&self.request, client).await
}
}
#[cfg(test)]
mod tests {
use crate::api::router_aspect_ratio::RouterAspectRatio;
use crate::api::router_resolution::RouterResolution;
use crate::api::router_video_model::RouterVideoModel;
use crate::api::router_provider::RouterProvider;
use crate::client::router_artcraft_client::RouterArtcraftClient;
use crate::client::router_client::RouterClient;
use crate::generate::generate_video::generate_video_request_builder::GenerateVideoRequestBuilder;
use crate::generate::generate_video::generate_video_response::GenerateVideoResponse;
use crate::generate::generate_video::video_generation_draft_or_request::VideoGenerationDraftOrRequest;
use artcraft_client::credentials::storyteller_credential_set::StorytellerCredentialSet;
use artcraft_client::utils::api_host::ApiHost;
#[tokio::test]
#[ignore] // manually run — fires a real API request and incurs cost
async fn text_to_video() {
let response = run_pipeline(GenerateVideoRequestBuilder {
prompt: Some("A corgi running through a field of wildflowers at sunset.".to_string()),
aspect_ratio: Some(RouterAspectRatio::WideSixteenByNine),
..mini_builder()
}).await;
assert!(matches!(response, GenerateVideoResponse::Artcraft(_)));
assert_eq!(1, 2, "Inspect output above");
}
#[tokio::test]
#[ignore] // manually run — fires a real API request and incurs cost
async fn res_480p() {
let response = run_pipeline(GenerateVideoRequestBuilder {
prompt: Some("A shiba inu playing in autumn leaves.".to_string()),
resolution: Some(RouterResolution::FourEightyP),
..mini_builder()
}).await;
assert!(matches!(response, GenerateVideoResponse::Artcraft(_)));
assert_eq!(1, 2, "Inspect output above");
}
fn mini_builder() -> GenerateVideoRequestBuilder {
GenerateVideoRequestBuilder {
model: RouterVideoModel::Seedance2p0BytePlusMini,
provider: RouterProvider::Artcraft,
duration_seconds: Some(4),
video_batch_count: Some(1),
..Default::default()
}
}
fn get_artcraft_client() -> RouterClient {
let cookies = std::fs::read_to_string("/Users/bt/Artcraft/credentials/artcraft_cookies.txt")
.expect("Failed to read artcraft cookies");
let cookies = cookies.trim().to_string();
let credentials = StorytellerCredentialSet::parse_multi_cookie_header(&cookies)
.expect("Failed to parse cookies")
.expect("No credentials found");
RouterClient::Artcraft(RouterArtcraftClient::new(ApiHost::Storyteller, credentials))
}
async fn run_pipeline(builder: GenerateVideoRequestBuilder) -> GenerateVideoResponse {
let client = get_artcraft_client();
let draft_or_request = builder.build2().expect("build2 should succeed");
let request = match draft_or_request {
VideoGenerationDraftOrRequest::Request(r) => r,
_ => panic!("expected Request variant (Artcraft skips draft)"),
};
request.send_request(&client).await.expect("send_request should succeed")
}
}
@@ -13,7 +13,7 @@ pub fn build_artcraft_seedance_2p0_bpu(builder: GenerateVideoRequestBuilder) ->
let request = build_artcraft_omni_video_request(
builder,
CommonVideoModelEnum::Seedance2p0BytePlusUltra,
SupportedResolutions::Full,
SupportedResolutions::FullWith4k,
UltraWideSupport::Supported,
)?;
let state = ArtcraftSeedance2p0BytePlusUltraRequestState { request };
@@ -101,6 +101,12 @@ mod tests {
assert_eq!(req.request.resolution, Some(CommonResolutionEnum::TenEightyP));
}
#[test]
fn res_4k() {
let req = unwrap_request(make_builder(|b| { b.resolution = Some(RouterResolution::FourK); }));
assert_eq!(req.request.resolution, Some(CommonResolutionEnum::FourK));
}
#[test]
fn none_stays_none() {
let req = unwrap_request(make_builder(|_| {}));
@@ -1,7 +1,8 @@
use enums::common::generation::common_resolution::CommonResolution;
use crate::generate::generate_video::video_generation_cost_estimate::VideoGenerationCostEstimate;
use crate::generate::generate_video::providers::artcraft::seedance_common::seedance_2p0_four_k_usd_cents;
use crate::generate::generate_video::providers::artcraft::seedance_2p0_bpu::request::ArtcraftSeedance2p0BytePlusUltraRequestState;
use crate::generate::generate_video::video_generation_cost_estimate::VideoGenerationCostEstimate;
/// USD cents per second by resolution:
/// 480p: $0.10/s = 10.0 ¢/s
@@ -15,6 +16,7 @@ pub struct ArtcraftSeedance2p0BytePlusUltraCostState {
pub resolution: CommonResolution,
pub duration_seconds: u16,
pub batch_count: u16,
pub has_video_reference: bool,
}
impl ArtcraftSeedance2p0BytePlusUltraCostState {
@@ -23,10 +25,30 @@ impl ArtcraftSeedance2p0BytePlusUltraCostState {
.unwrap_or(CommonResolution::SevenTwentyP);
let duration_seconds = request.request.duration_seconds.unwrap_or(5);
let batch_count = request.request.video_batch_count.unwrap_or(1);
Self { resolution, duration_seconds, batch_count }
let has_video_reference = request.request.reference_video_media_tokens
.as_ref()
.is_some_and(|tokens| !tokens.is_empty());
Self { resolution, duration_seconds, batch_count, has_video_reference }
}
pub fn estimate_cost(&self) -> VideoGenerationCostEstimate {
if self.resolution == CommonResolution::FourK {
let usd_cents = seedance_2p0_four_k_usd_cents(
self.duration_seconds,
self.batch_count,
self.has_video_reference,
);
return VideoGenerationCostEstimate {
cost_in_credits: Some(usd_cents),
cost_in_usd_cents: Some(usd_cents),
is_free: false,
is_unlimited: false,
is_rate_limited: false,
has_watermark: false,
failures_are_refunded: None,
};
}
let cents_per_second = match self.resolution {
CommonResolution::FourEightyP => CENTS_PER_SECOND_480P,
CommonResolution::TenEightyP => CENTS_PER_SECOND_1080P,
@@ -49,9 +71,9 @@ impl ArtcraftSeedance2p0BytePlusUltraCostState {
#[cfg(test)]
mod tests {
use crate::api::router_provider::RouterProvider;
use crate::api::router_resolution::RouterResolution;
use crate::api::router_video_model::RouterVideoModel;
use crate::api::router_provider::RouterProvider;
use crate::generate::generate_video::generate_video_request_builder::GenerateVideoRequestBuilder;
mod pricing_720p {
@@ -125,6 +147,38 @@ mod tests {
}
}
mod four_k_pricing {
use enums::common::generation::common_resolution::CommonResolution;
fn artcraft_4k_cents(duration_seconds: u16, batch_count: u16, has_video_reference: bool) -> u64 {
super::super::ArtcraftSeedance2p0BytePlusUltraCostState {
resolution: CommonResolution::FourK,
duration_seconds,
batch_count,
has_video_reference,
}
.estimate_cost()
.cost_in_usd_cents
.unwrap()
}
#[test]
fn explicit_4k_without_video_reference() {
assert_eq!(artcraft_4k_cents(4, 1, false), 347);
assert_eq!(artcraft_4k_cents(5, 1, false), 433);
assert_eq!(artcraft_4k_cents(10, 1, false), 866);
assert_eq!(artcraft_4k_cents(15, 1, false), 1299);
}
#[test]
fn explicit_4k_with_video_reference() {
assert_eq!(artcraft_4k_cents(4, 1, true), 416);
assert_eq!(artcraft_4k_cents(5, 1, true), 519);
assert_eq!(artcraft_4k_cents(10, 1, true), 1038);
assert_eq!(artcraft_4k_cents(15, 1, true), 1557);
}
}
mod relative_pricing_tests {
use super::*;
@@ -0,0 +1,225 @@
use enums::common::generation::common_video_model::CommonVideoModel as CommonVideoModelEnum;
use crate::errors::artcraft_router_error::ArtcraftRouterError;
use crate::generate::generate_video::generate_video_request_builder::GenerateVideoRequestBuilder;
use crate::generate::generate_video::providers::artcraft::build_common::{
build_artcraft_omni_video_request, SupportedResolutions, UltraWideSupport,
};
use crate::generate::generate_video::providers::artcraft::seedance_2p0_bpu_mini::request::ArtcraftSeedance2p0BytePlusUltraMiniRequestState;
use crate::generate::generate_video::video_generation_draft_or_request::VideoGenerationDraftOrRequest;
use crate::generate::generate_video::video_generation_request::VideoGenerationRequest;
pub fn build_artcraft_seedance_2p0_bpu_mini(builder: GenerateVideoRequestBuilder) -> Result<VideoGenerationDraftOrRequest, ArtcraftRouterError> {
// Seedance 2.0 Mini supports 480p and 720p only (higher resolutions downgrade
// to 720p), and all six aspect ratios including 21:9.
let request = build_artcraft_omni_video_request(
builder,
CommonVideoModelEnum::Seedance2p0BytePlusUltraMini,
SupportedResolutions::Fast,
UltraWideSupport::Supported,
)?;
let state = ArtcraftSeedance2p0BytePlusUltraMiniRequestState { request };
Ok(VideoGenerationDraftOrRequest::Request(VideoGenerationRequest::ArtcraftSeedance2p0BytePlusUltraMini(state)))
}
#[cfg(test)]
mod tests {
use enums::common::generation::common_aspect_ratio::CommonAspectRatio as CommonAspectRatioEnum;
use enums::common::generation::common_resolution::CommonResolution as CommonResolutionEnum;
use enums::common::generation::common_video_model::CommonVideoModel as CommonVideoModelEnum;
use enums::common::generation::common_bitrate::CommonBitrate as CommonBitrateEnum;
use tokens::tokens::characters::CharacterToken;
use tokens::tokens::media_files::MediaFileToken;
use crate::api::character_list_ref::CharacterListRef;
use crate::api::router_aspect_ratio::RouterAspectRatio;
use crate::api::router_bitrate::RouterBitrate;
use crate::api::router_resolution::RouterResolution;
use crate::api::router_video_model::RouterVideoModel;
use crate::api::image_list_ref::ImageListRef;
use crate::api::image_ref::ImageRef;
use crate::api::router_provider::RouterProvider;
use crate::client::request_mismatch_mitigation_strategy::RequestMismatchMitigationStrategy;
use crate::generate::generate_video::generate_video_request_builder::GenerateVideoRequestBuilder;
use crate::generate::generate_video::video_generation_draft_or_request::VideoGenerationDraftOrRequest;
use crate::generate::generate_video::video_generation_request::VideoGenerationRequest;
use super::*;
mod field_conversions {
use super::*;
#[test]
fn prompt_is_passed_through() {
let req = unwrap_request(builder_with(|b| { b.prompt = Some("test".to_string()); }));
assert_eq!(req.request.prompt, Some("test".to_string()));
}
#[test]
fn model_is_correct() {
let req = unwrap_request(builder_with(|_| {}));
assert!(matches!(req.request.model, Some(CommonVideoModelEnum::Seedance2p0BytePlusUltraMini)));
}
#[test]
fn duration_passed_through() {
let req = unwrap_request(builder_with(|b| { b.duration_seconds = Some(10); }));
assert_eq!(req.request.duration_seconds, Some(10));
}
#[test]
fn duration_clamped_to_max() {
let req = unwrap_request(builder_with(|b| { b.duration_seconds = Some(99); }));
assert_eq!(req.request.duration_seconds, Some(15));
}
#[test]
fn batch_count_passed_through() {
let req = unwrap_request(builder_with(|b| { b.video_batch_count = Some(4); }));
assert_eq!(req.request.video_batch_count, Some(4));
}
#[test]
fn batch_count_clamped_to_platform_max() {
// The ArtCraft platform caps batch at 4 and downgrades higher requests.
let req = unwrap_request(builder_with(|b| { b.video_batch_count = Some(8); }));
assert_eq!(req.request.video_batch_count, Some(4));
}
#[test]
fn bitrate_passed_through() {
let req = unwrap_request(builder_with(|b| { b.bitrate = Some(RouterBitrate::High); }));
assert_eq!(req.request.bitrate, Some(CommonBitrateEnum::High));
}
}
mod aspect_ratio_tests {
use super::*;
#[test]
fn wide() {
let req = unwrap_request(builder_with(|b| { b.aspect_ratio = Some(RouterAspectRatio::WideSixteenByNine); }));
assert_eq!(req.request.aspect_ratio, Some(CommonAspectRatioEnum::WideSixteenByNine));
}
#[test]
fn ultra_wide() {
let req = unwrap_request(builder_with(|b| { b.aspect_ratio = Some(RouterAspectRatio::WideTwentyOneByNine); }));
assert_eq!(req.request.aspect_ratio, Some(CommonAspectRatioEnum::WideTwentyOneByNine));
}
#[test]
fn tall() {
let req = unwrap_request(builder_with(|b| { b.aspect_ratio = Some(RouterAspectRatio::TallNineBySixteen); }));
assert_eq!(req.request.aspect_ratio, Some(CommonAspectRatioEnum::TallNineBySixteen));
}
#[test]
fn square() {
let req = unwrap_request(builder_with(|b| { b.aspect_ratio = Some(RouterAspectRatio::Square); }));
assert_eq!(req.request.aspect_ratio, Some(CommonAspectRatioEnum::Square));
}
}
mod resolution_tests {
use super::*;
#[test]
fn res_480p() {
let req = unwrap_request(builder_with(|b| { b.resolution = Some(RouterResolution::FourEightyP); }));
assert_eq!(req.request.resolution, Some(CommonResolutionEnum::FourEightyP));
}
#[test]
fn res_720p() {
let req = unwrap_request(builder_with(|b| { b.resolution = Some(RouterResolution::SevenTwentyP); }));
assert_eq!(req.request.resolution, Some(CommonResolutionEnum::SevenTwentyP));
}
#[test]
fn res_1080p_downgrades_to_720p() {
let req = unwrap_request(builder_with(|b| { b.resolution = Some(RouterResolution::TenEightyP); }));
assert_eq!(req.request.resolution, Some(CommonResolutionEnum::SevenTwentyP));
}
#[test]
fn res_1080p_error_out() {
let result = build_artcraft_seedance_2p0_bpu_mini(GenerateVideoRequestBuilder {
model: RouterVideoModel::Seedance2p0BytePlusUltraMini,
provider: RouterProvider::Artcraft,
resolution: Some(RouterResolution::TenEightyP),
request_mismatch_mitigation_strategy: RequestMismatchMitigationStrategy::ErrorOut,
..Default::default()
});
assert!(result.is_err());
}
#[test]
fn none_stays_none() {
let req = unwrap_request(builder_with(|_| {}));
assert!(req.request.resolution.is_none());
}
}
mod media_token_tests {
use super::*;
#[test]
fn start_frame_token_passed_through() {
let token = MediaFileToken::new("mf_start".to_string());
let req = unwrap_request(builder_with(|b| { b.start_frame = Some(ImageRef::MediaFileToken(token.clone())); }));
assert_eq!(req.request.start_frame_image_media_token, Some(token));
}
#[test]
fn url_start_frame_rejected() {
let result = build_artcraft_seedance_2p0_bpu_mini(GenerateVideoRequestBuilder {
model: RouterVideoModel::Seedance2p0BytePlusUltraMini,
provider: RouterProvider::Artcraft,
start_frame: Some(ImageRef::Url("https://example.com".to_string())),
..Default::default()
});
assert!(result.is_err());
}
#[test]
fn reference_image_tokens_passed_through() {
let tokens = vec![
MediaFileToken::new("mf_a".to_string()),
MediaFileToken::new("mf_b".to_string()),
];
let req = unwrap_request(builder_with(|b| { b.reference_images = Some(ImageListRef::MediaFileTokens(tokens.clone())); }));
assert_eq!(req.request.reference_image_media_tokens, Some(tokens));
}
#[test]
fn character_tokens_passed_through() {
let tokens = vec![
CharacterToken::new("char_a".to_string()),
CharacterToken::new("char_b".to_string()),
];
let req = unwrap_request(builder_with(|b| { b.reference_character_tokens = Some(CharacterListRef::CharacterTokens(tokens.clone())); }));
assert_eq!(req.request.reference_character_tokens, Some(tokens));
}
}
fn builder_with(f: impl FnOnce(&mut GenerateVideoRequestBuilder)) -> GenerateVideoRequestBuilder {
let mut builder = GenerateVideoRequestBuilder {
model: RouterVideoModel::Seedance2p0BytePlusUltraMini,
provider: RouterProvider::Artcraft,
duration_seconds: Some(5),
video_batch_count: Some(1),
..Default::default()
};
f(&mut builder);
builder
}
fn unwrap_request(builder: GenerateVideoRequestBuilder) -> ArtcraftSeedance2p0BytePlusUltraMiniRequestState {
let result = build_artcraft_seedance_2p0_bpu_mini(builder).expect("build should succeed");
match result {
VideoGenerationDraftOrRequest::Request(VideoGenerationRequest::ArtcraftSeedance2p0BytePlusUltraMini(state)) => state,
_ => panic!("expected ArtcraftSeedance2p0BytePlusUltraMini request"),
}
}
}
@@ -0,0 +1,176 @@
use enums::common::generation::common_resolution::CommonResolution;
use crate::generate::generate_video::video_generation_cost_estimate::VideoGenerationCostEstimate;
use crate::generate::generate_video::providers::artcraft::seedance_common::seedance_2p0_byteplus_mini_usd_cents;
use crate::generate::generate_video::providers::artcraft::seedance_2p0_bpu_mini::request::ArtcraftSeedance2p0BytePlusUltraMiniRequestState;
pub struct ArtcraftSeedance2p0BytePlusUltraMiniCostState {
pub resolution: CommonResolution,
pub duration_seconds: u16,
pub batch_count: u16,
pub has_video_reference: bool,
}
impl ArtcraftSeedance2p0BytePlusUltraMiniCostState {
pub fn from_request(request: &ArtcraftSeedance2p0BytePlusUltraMiniRequestState) -> Self {
let resolution = request.request.resolution
.unwrap_or(CommonResolution::SevenTwentyP);
let duration_seconds = request.request.duration_seconds.unwrap_or(5);
let batch_count = request.request.video_batch_count.unwrap_or(1);
let has_video_reference = request.request.reference_video_media_tokens
.as_ref()
.is_some_and(|tokens| !tokens.is_empty());
Self { resolution, duration_seconds, batch_count, has_video_reference }
}
pub fn estimate_cost(&self) -> VideoGenerationCostEstimate {
// BytePlus / BytePlus Ultra Mini share a higher-margin rate set; see
// seedance_common::seedance_2p0_byteplus_mini_usd_cents.
let usd_cents = seedance_2p0_byteplus_mini_usd_cents(
self.resolution,
self.duration_seconds,
self.batch_count,
self.has_video_reference,
);
// ArtCraft credits: 100 credits = $1.00, so credits = cents.
VideoGenerationCostEstimate {
cost_in_credits: Some(usd_cents),
cost_in_usd_cents: Some(usd_cents),
is_free: false,
is_unlimited: false,
is_rate_limited: false,
has_watermark: false,
failures_are_refunded: None,
}
}
}
#[cfg(test)]
mod tests {
use tokens::tokens::media_files::MediaFileToken;
use crate::api::router_resolution::RouterResolution;
use crate::api::router_video_model::RouterVideoModel;
use crate::api::router_provider::RouterProvider;
use crate::api::video_list_ref::VideoListRef;
use crate::generate::generate_video::generate_video_request_builder::GenerateVideoRequestBuilder;
use crate::generate::generate_video::video_generation_cost_estimate::VideoGenerationCostEstimate;
// Every combination, driven through the full build pipeline. These prices are
// the supplier's per-combo cost plus a 5% margin, rounded up to whole cents.
mod pricing_480p {
use super::*;
#[test]
fn without_video_reference() {
assert_eq!(cents(RouterResolution::FourEightyP, 4, 1, false), 14);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 1, false), 17);
assert_eq!(cents(RouterResolution::FourEightyP, 10, 1, false), 33);
assert_eq!(cents(RouterResolution::FourEightyP, 15, 1, false), 50);
}
#[test]
fn with_video_reference() {
assert_eq!(cents(RouterResolution::FourEightyP, 4, 1, true), 17);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 1, true), 21);
assert_eq!(cents(RouterResolution::FourEightyP, 10, 1, true), 42);
assert_eq!(cents(RouterResolution::FourEightyP, 15, 1, true), 63);
}
}
mod pricing_720p {
use super::*;
#[test]
fn without_video_reference() {
assert_eq!(cents(RouterResolution::SevenTwentyP, 4, 1, false), 35);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 1, false), 44);
assert_eq!(cents(RouterResolution::SevenTwentyP, 10, 1, false), 88);
assert_eq!(cents(RouterResolution::SevenTwentyP, 15, 1, false), 131);
}
#[test]
fn with_video_reference() {
assert_eq!(cents(RouterResolution::SevenTwentyP, 4, 1, true), 42);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 1, true), 53);
assert_eq!(cents(RouterResolution::SevenTwentyP, 10, 1, true), 105);
assert_eq!(cents(RouterResolution::SevenTwentyP, 15, 1, true), 158);
}
#[test]
fn none_defaults_to_720p() {
assert_eq!(cents_no_ref(None, 5, 1), cents(RouterResolution::SevenTwentyP, 5, 1, false));
}
}
mod credits_tests {
use super::*;
#[test]
fn credits_equal_usd_cents_all_combos() {
let resolutions = [
Some(RouterResolution::FourEightyP),
Some(RouterResolution::SevenTwentyP),
None,
];
for res in resolutions {
for dur in [4u16, 5, 10, 15] {
for batch in [1u16, 2, 4] {
for has_ref in [false, true] {
let cost = build_cost(res, dur, batch, has_ref);
assert_eq!(cost.cost_in_credits, cost.cost_in_usd_cents);
}
}
}
}
}
}
fn build_cost(
resolution: Option<RouterResolution>,
duration_seconds: u16,
video_batch_count: u16,
with_video_reference: bool,
) -> VideoGenerationCostEstimate {
let reference_videos = with_video_reference.then(|| {
VideoListRef::MediaFileTokens(vec![MediaFileToken::new("mf_ref".to_string())])
});
let builder = GenerateVideoRequestBuilder {
model: RouterVideoModel::Seedance2p0BytePlusUltraMini,
provider: RouterProvider::Artcraft,
resolution,
duration_seconds: Some(duration_seconds),
video_batch_count: Some(video_batch_count),
reference_videos,
..Default::default()
};
builder.build2()
.expect("build2 should succeed")
.estimate_cost()
.expect("estimate_cost should succeed")
}
fn cents(
resolution: RouterResolution,
duration_seconds: u16,
video_batch_count: u16,
with_video_reference: bool,
) -> u64 {
build_cost(Some(resolution), duration_seconds, video_batch_count, with_video_reference)
.cost_in_usd_cents
.unwrap()
}
fn cents_no_ref(
resolution: Option<RouterResolution>,
duration_seconds: u16,
video_batch_count: u16,
) -> u64 {
build_cost(resolution, duration_seconds, video_batch_count, false)
.cost_in_usd_cents
.unwrap()
}
}
@@ -0,0 +1,3 @@
pub mod build;
pub mod cost;
pub mod request;
@@ -0,0 +1,86 @@
use artcraft_api_defs::omni_gen::cost_and_generate_requests::omni_gen_video_cost_and_generate_request::OmniGenVideoCostAndGenerateRequest;
use crate::client::router_artcraft_client::RouterArtcraftClient;
use crate::errors::artcraft_router_error::ArtcraftRouterError;
use crate::generate::generate_video::generate_video_response::GenerateVideoResponse;
use crate::generate::generate_video::providers::artcraft::request_common::send_artcraft_omni_video_request;
#[derive(Clone, Debug)]
pub struct ArtcraftSeedance2p0BytePlusUltraMiniRequestState {
pub request: OmniGenVideoCostAndGenerateRequest,
}
impl ArtcraftSeedance2p0BytePlusUltraMiniRequestState {
pub async fn send(&self, client: &RouterArtcraftClient) -> Result<GenerateVideoResponse, ArtcraftRouterError> {
send_artcraft_omni_video_request(&self.request, client).await
}
}
#[cfg(test)]
mod tests {
use crate::api::router_aspect_ratio::RouterAspectRatio;
use crate::api::router_resolution::RouterResolution;
use crate::api::router_video_model::RouterVideoModel;
use crate::api::router_provider::RouterProvider;
use crate::client::router_artcraft_client::RouterArtcraftClient;
use crate::client::router_client::RouterClient;
use crate::generate::generate_video::generate_video_request_builder::GenerateVideoRequestBuilder;
use crate::generate::generate_video::generate_video_response::GenerateVideoResponse;
use crate::generate::generate_video::video_generation_draft_or_request::VideoGenerationDraftOrRequest;
use artcraft_client::credentials::storyteller_credential_set::StorytellerCredentialSet;
use artcraft_client::utils::api_host::ApiHost;
#[tokio::test]
#[ignore] // manually run — fires a real API request and incurs cost
async fn text_to_video() {
let response = run_pipeline(GenerateVideoRequestBuilder {
prompt: Some("A corgi running through a field of wildflowers at sunset.".to_string()),
aspect_ratio: Some(RouterAspectRatio::WideSixteenByNine),
..mini_builder()
}).await;
assert!(matches!(response, GenerateVideoResponse::Artcraft(_)));
assert_eq!(1, 2, "Inspect output above");
}
#[tokio::test]
#[ignore] // manually run — fires a real API request and incurs cost
async fn res_480p() {
let response = run_pipeline(GenerateVideoRequestBuilder {
prompt: Some("A shiba inu playing in autumn leaves.".to_string()),
resolution: Some(RouterResolution::FourEightyP),
..mini_builder()
}).await;
assert!(matches!(response, GenerateVideoResponse::Artcraft(_)));
assert_eq!(1, 2, "Inspect output above");
}
fn mini_builder() -> GenerateVideoRequestBuilder {
GenerateVideoRequestBuilder {
model: RouterVideoModel::Seedance2p0BytePlusUltraMini,
provider: RouterProvider::Artcraft,
duration_seconds: Some(4),
video_batch_count: Some(1),
..Default::default()
}
}
fn get_artcraft_client() -> RouterClient {
let cookies = std::fs::read_to_string("/Users/bt/Artcraft/credentials/artcraft_cookies.txt")
.expect("Failed to read artcraft cookies");
let cookies = cookies.trim().to_string();
let credentials = StorytellerCredentialSet::parse_multi_cookie_header(&cookies)
.expect("Failed to parse cookies")
.expect("No credentials found");
RouterClient::Artcraft(RouterArtcraftClient::new(ApiHost::Storyteller, credentials))
}
async fn run_pipeline(builder: GenerateVideoRequestBuilder) -> GenerateVideoResponse {
let client = get_artcraft_client();
let draft_or_request = builder.build2().expect("build2 should succeed");
let request = match draft_or_request {
VideoGenerationDraftOrRequest::Request(r) => r,
_ => panic!("expected Request variant (Artcraft skips draft)"),
};
request.send_request(&client).await.expect("send_request should succeed")
}
}
@@ -0,0 +1,225 @@
use enums::common::generation::common_video_model::CommonVideoModel as CommonVideoModelEnum;
use crate::errors::artcraft_router_error::ArtcraftRouterError;
use crate::generate::generate_video::generate_video_request_builder::GenerateVideoRequestBuilder;
use crate::generate::generate_video::providers::artcraft::build_common::{
build_artcraft_omni_video_request, SupportedResolutions, UltraWideSupport,
};
use crate::generate::generate_video::providers::artcraft::seedance_2p0_mini::request::ArtcraftSeedance2p0MiniRequestState;
use crate::generate::generate_video::video_generation_draft_or_request::VideoGenerationDraftOrRequest;
use crate::generate::generate_video::video_generation_request::VideoGenerationRequest;
pub fn build_artcraft_seedance_2p0_mini(builder: GenerateVideoRequestBuilder) -> Result<VideoGenerationDraftOrRequest, ArtcraftRouterError> {
// Seedance 2.0 Mini supports 480p and 720p only (higher resolutions downgrade
// to 720p), and all six aspect ratios including 21:9.
let request = build_artcraft_omni_video_request(
builder,
CommonVideoModelEnum::Seedance2p0Mini,
SupportedResolutions::Fast,
UltraWideSupport::Supported,
)?;
let state = ArtcraftSeedance2p0MiniRequestState { request };
Ok(VideoGenerationDraftOrRequest::Request(VideoGenerationRequest::ArtcraftSeedance2p0Mini(state)))
}
#[cfg(test)]
mod tests {
use enums::common::generation::common_aspect_ratio::CommonAspectRatio as CommonAspectRatioEnum;
use enums::common::generation::common_resolution::CommonResolution as CommonResolutionEnum;
use enums::common::generation::common_video_model::CommonVideoModel as CommonVideoModelEnum;
use enums::common::generation::common_bitrate::CommonBitrate as CommonBitrateEnum;
use tokens::tokens::characters::CharacterToken;
use tokens::tokens::media_files::MediaFileToken;
use crate::api::character_list_ref::CharacterListRef;
use crate::api::router_aspect_ratio::RouterAspectRatio;
use crate::api::router_bitrate::RouterBitrate;
use crate::api::router_resolution::RouterResolution;
use crate::api::router_video_model::RouterVideoModel;
use crate::api::image_list_ref::ImageListRef;
use crate::api::image_ref::ImageRef;
use crate::api::router_provider::RouterProvider;
use crate::client::request_mismatch_mitigation_strategy::RequestMismatchMitigationStrategy;
use crate::generate::generate_video::generate_video_request_builder::GenerateVideoRequestBuilder;
use crate::generate::generate_video::video_generation_draft_or_request::VideoGenerationDraftOrRequest;
use crate::generate::generate_video::video_generation_request::VideoGenerationRequest;
use super::*;
mod field_conversions {
use super::*;
#[test]
fn prompt_is_passed_through() {
let req = unwrap_request(builder_with(|b| { b.prompt = Some("test".to_string()); }));
assert_eq!(req.request.prompt, Some("test".to_string()));
}
#[test]
fn model_is_correct() {
let req = unwrap_request(builder_with(|_| {}));
assert!(matches!(req.request.model, Some(CommonVideoModelEnum::Seedance2p0Mini)));
}
#[test]
fn duration_passed_through() {
let req = unwrap_request(builder_with(|b| { b.duration_seconds = Some(10); }));
assert_eq!(req.request.duration_seconds, Some(10));
}
#[test]
fn duration_clamped_to_max() {
let req = unwrap_request(builder_with(|b| { b.duration_seconds = Some(99); }));
assert_eq!(req.request.duration_seconds, Some(15));
}
#[test]
fn batch_count_passed_through() {
let req = unwrap_request(builder_with(|b| { b.video_batch_count = Some(4); }));
assert_eq!(req.request.video_batch_count, Some(4));
}
#[test]
fn batch_count_clamped_to_platform_max() {
// The ArtCraft platform caps batch at 4 and downgrades higher requests.
let req = unwrap_request(builder_with(|b| { b.video_batch_count = Some(8); }));
assert_eq!(req.request.video_batch_count, Some(4));
}
#[test]
fn bitrate_passed_through() {
let req = unwrap_request(builder_with(|b| { b.bitrate = Some(RouterBitrate::High); }));
assert_eq!(req.request.bitrate, Some(CommonBitrateEnum::High));
}
}
mod aspect_ratio_tests {
use super::*;
#[test]
fn wide() {
let req = unwrap_request(builder_with(|b| { b.aspect_ratio = Some(RouterAspectRatio::WideSixteenByNine); }));
assert_eq!(req.request.aspect_ratio, Some(CommonAspectRatioEnum::WideSixteenByNine));
}
#[test]
fn ultra_wide() {
let req = unwrap_request(builder_with(|b| { b.aspect_ratio = Some(RouterAspectRatio::WideTwentyOneByNine); }));
assert_eq!(req.request.aspect_ratio, Some(CommonAspectRatioEnum::WideTwentyOneByNine));
}
#[test]
fn tall() {
let req = unwrap_request(builder_with(|b| { b.aspect_ratio = Some(RouterAspectRatio::TallNineBySixteen); }));
assert_eq!(req.request.aspect_ratio, Some(CommonAspectRatioEnum::TallNineBySixteen));
}
#[test]
fn square() {
let req = unwrap_request(builder_with(|b| { b.aspect_ratio = Some(RouterAspectRatio::Square); }));
assert_eq!(req.request.aspect_ratio, Some(CommonAspectRatioEnum::Square));
}
}
mod resolution_tests {
use super::*;
#[test]
fn res_480p() {
let req = unwrap_request(builder_with(|b| { b.resolution = Some(RouterResolution::FourEightyP); }));
assert_eq!(req.request.resolution, Some(CommonResolutionEnum::FourEightyP));
}
#[test]
fn res_720p() {
let req = unwrap_request(builder_with(|b| { b.resolution = Some(RouterResolution::SevenTwentyP); }));
assert_eq!(req.request.resolution, Some(CommonResolutionEnum::SevenTwentyP));
}
#[test]
fn res_1080p_downgrades_to_720p() {
let req = unwrap_request(builder_with(|b| { b.resolution = Some(RouterResolution::TenEightyP); }));
assert_eq!(req.request.resolution, Some(CommonResolutionEnum::SevenTwentyP));
}
#[test]
fn res_1080p_error_out() {
let result = build_artcraft_seedance_2p0_mini(GenerateVideoRequestBuilder {
model: RouterVideoModel::Seedance2p0Mini,
provider: RouterProvider::Artcraft,
resolution: Some(RouterResolution::TenEightyP),
request_mismatch_mitigation_strategy: RequestMismatchMitigationStrategy::ErrorOut,
..Default::default()
});
assert!(result.is_err());
}
#[test]
fn none_stays_none() {
let req = unwrap_request(builder_with(|_| {}));
assert!(req.request.resolution.is_none());
}
}
mod media_token_tests {
use super::*;
#[test]
fn start_frame_token_passed_through() {
let token = MediaFileToken::new("mf_start".to_string());
let req = unwrap_request(builder_with(|b| { b.start_frame = Some(ImageRef::MediaFileToken(token.clone())); }));
assert_eq!(req.request.start_frame_image_media_token, Some(token));
}
#[test]
fn url_start_frame_rejected() {
let result = build_artcraft_seedance_2p0_mini(GenerateVideoRequestBuilder {
model: RouterVideoModel::Seedance2p0Mini,
provider: RouterProvider::Artcraft,
start_frame: Some(ImageRef::Url("https://example.com".to_string())),
..Default::default()
});
assert!(result.is_err());
}
#[test]
fn reference_image_tokens_passed_through() {
let tokens = vec![
MediaFileToken::new("mf_a".to_string()),
MediaFileToken::new("mf_b".to_string()),
];
let req = unwrap_request(builder_with(|b| { b.reference_images = Some(ImageListRef::MediaFileTokens(tokens.clone())); }));
assert_eq!(req.request.reference_image_media_tokens, Some(tokens));
}
#[test]
fn character_tokens_passed_through() {
let tokens = vec![
CharacterToken::new("char_a".to_string()),
CharacterToken::new("char_b".to_string()),
];
let req = unwrap_request(builder_with(|b| { b.reference_character_tokens = Some(CharacterListRef::CharacterTokens(tokens.clone())); }));
assert_eq!(req.request.reference_character_tokens, Some(tokens));
}
}
fn builder_with(f: impl FnOnce(&mut GenerateVideoRequestBuilder)) -> GenerateVideoRequestBuilder {
let mut builder = GenerateVideoRequestBuilder {
model: RouterVideoModel::Seedance2p0Mini,
provider: RouterProvider::Artcraft,
duration_seconds: Some(5),
video_batch_count: Some(1),
..Default::default()
};
f(&mut builder);
builder
}
fn unwrap_request(builder: GenerateVideoRequestBuilder) -> ArtcraftSeedance2p0MiniRequestState {
let result = build_artcraft_seedance_2p0_mini(builder).expect("build should succeed");
match result {
VideoGenerationDraftOrRequest::Request(VideoGenerationRequest::ArtcraftSeedance2p0Mini(state)) => state,
_ => panic!("expected ArtcraftSeedance2p0Mini request"),
}
}
}
@@ -0,0 +1,176 @@
use enums::common::generation::common_resolution::CommonResolution;
use crate::generate::generate_video::video_generation_cost_estimate::VideoGenerationCostEstimate;
use crate::generate::generate_video::providers::artcraft::seedance_common::seedance_2p0_mini_usd_cents;
use crate::generate::generate_video::providers::artcraft::seedance_2p0_mini::request::ArtcraftSeedance2p0MiniRequestState;
pub struct ArtcraftSeedance2p0MiniCostState {
pub resolution: CommonResolution,
pub duration_seconds: u16,
pub batch_count: u16,
pub has_video_reference: bool,
}
impl ArtcraftSeedance2p0MiniCostState {
pub fn from_request(request: &ArtcraftSeedance2p0MiniRequestState) -> Self {
let resolution = request.request.resolution
.unwrap_or(CommonResolution::SevenTwentyP);
let duration_seconds = request.request.duration_seconds.unwrap_or(5);
let batch_count = request.request.video_batch_count.unwrap_or(1);
let has_video_reference = request.request.reference_video_media_tokens
.as_ref()
.is_some_and(|tokens| !tokens.is_empty());
Self { resolution, duration_seconds, batch_count, has_video_reference }
}
pub fn estimate_cost(&self) -> VideoGenerationCostEstimate {
// Seedance 2.0 Mini is priced uniformly across its variants; see
// seedance_common::seedance_2p0_mini_usd_cents.
let usd_cents = seedance_2p0_mini_usd_cents(
self.resolution,
self.duration_seconds,
self.batch_count,
self.has_video_reference,
);
// ArtCraft credits: 100 credits = $1.00, so credits = cents.
VideoGenerationCostEstimate {
cost_in_credits: Some(usd_cents),
cost_in_usd_cents: Some(usd_cents),
is_free: false,
is_unlimited: false,
is_rate_limited: false,
has_watermark: false,
failures_are_refunded: None,
}
}
}
#[cfg(test)]
mod tests {
use tokens::tokens::media_files::MediaFileToken;
use crate::api::router_resolution::RouterResolution;
use crate::api::router_video_model::RouterVideoModel;
use crate::api::router_provider::RouterProvider;
use crate::api::video_list_ref::VideoListRef;
use crate::generate::generate_video::generate_video_request_builder::GenerateVideoRequestBuilder;
use crate::generate::generate_video::video_generation_cost_estimate::VideoGenerationCostEstimate;
// Every combination, driven through the full build pipeline. These prices are
// the supplier's per-combo cost plus a 5% margin, rounded up to whole cents.
mod pricing_480p {
use super::*;
#[test]
fn without_video_reference() {
assert_eq!(cents(RouterResolution::FourEightyP, 4, 1, false), 13);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 1, false), 17);
assert_eq!(cents(RouterResolution::FourEightyP, 10, 1, false), 33);
assert_eq!(cents(RouterResolution::FourEightyP, 15, 1, false), 49);
}
#[test]
fn with_video_reference() {
assert_eq!(cents(RouterResolution::FourEightyP, 4, 1, true), 17);
assert_eq!(cents(RouterResolution::FourEightyP, 5, 1, true), 21);
assert_eq!(cents(RouterResolution::FourEightyP, 10, 1, true), 42);
assert_eq!(cents(RouterResolution::FourEightyP, 15, 1, true), 62);
}
}
mod pricing_720p {
use super::*;
#[test]
fn without_video_reference() {
assert_eq!(cents(RouterResolution::SevenTwentyP, 4, 1, false), 35);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 1, false), 44);
assert_eq!(cents(RouterResolution::SevenTwentyP, 10, 1, false), 87);
assert_eq!(cents(RouterResolution::SevenTwentyP, 15, 1, false), 130);
}
#[test]
fn with_video_reference() {
assert_eq!(cents(RouterResolution::SevenTwentyP, 4, 1, true), 42);
assert_eq!(cents(RouterResolution::SevenTwentyP, 5, 1, true), 52);
assert_eq!(cents(RouterResolution::SevenTwentyP, 10, 1, true), 104);
assert_eq!(cents(RouterResolution::SevenTwentyP, 15, 1, true), 156);
}
#[test]
fn none_defaults_to_720p() {
assert_eq!(cents_no_ref(None, 5, 1), cents(RouterResolution::SevenTwentyP, 5, 1, false));
}
}
mod credits_tests {
use super::*;
#[test]
fn credits_equal_usd_cents_all_combos() {
let resolutions = [
Some(RouterResolution::FourEightyP),
Some(RouterResolution::SevenTwentyP),
None,
];
for res in resolutions {
for dur in [4u16, 5, 10, 15] {
for batch in [1u16, 2, 4] {
for has_ref in [false, true] {
let cost = build_cost(res, dur, batch, has_ref);
assert_eq!(cost.cost_in_credits, cost.cost_in_usd_cents);
}
}
}
}
}
}
fn build_cost(
resolution: Option<RouterResolution>,
duration_seconds: u16,
video_batch_count: u16,
with_video_reference: bool,
) -> VideoGenerationCostEstimate {
let reference_videos = with_video_reference.then(|| {
VideoListRef::MediaFileTokens(vec![MediaFileToken::new("mf_ref".to_string())])
});
let builder = GenerateVideoRequestBuilder {
model: RouterVideoModel::Seedance2p0Mini,
provider: RouterProvider::Artcraft,
resolution,
duration_seconds: Some(duration_seconds),
video_batch_count: Some(video_batch_count),
reference_videos,
..Default::default()
};
builder.build2()
.expect("build2 should succeed")
.estimate_cost()
.expect("estimate_cost should succeed")
}
fn cents(
resolution: RouterResolution,
duration_seconds: u16,
video_batch_count: u16,
with_video_reference: bool,
) -> u64 {
build_cost(Some(resolution), duration_seconds, video_batch_count, with_video_reference)
.cost_in_usd_cents
.unwrap()
}
fn cents_no_ref(
resolution: Option<RouterResolution>,
duration_seconds: u16,
video_batch_count: u16,
) -> u64 {
build_cost(resolution, duration_seconds, video_batch_count, false)
.cost_in_usd_cents
.unwrap()
}
}
@@ -0,0 +1,3 @@
pub mod build;
pub mod cost;
pub mod request;
@@ -0,0 +1,86 @@
use artcraft_api_defs::omni_gen::cost_and_generate_requests::omni_gen_video_cost_and_generate_request::OmniGenVideoCostAndGenerateRequest;
use crate::client::router_artcraft_client::RouterArtcraftClient;
use crate::errors::artcraft_router_error::ArtcraftRouterError;
use crate::generate::generate_video::generate_video_response::GenerateVideoResponse;
use crate::generate::generate_video::providers::artcraft::request_common::send_artcraft_omni_video_request;
#[derive(Clone, Debug)]
pub struct ArtcraftSeedance2p0MiniRequestState {
pub request: OmniGenVideoCostAndGenerateRequest,
}
impl ArtcraftSeedance2p0MiniRequestState {
pub async fn send(&self, client: &RouterArtcraftClient) -> Result<GenerateVideoResponse, ArtcraftRouterError> {
send_artcraft_omni_video_request(&self.request, client).await
}
}
#[cfg(test)]
mod tests {
use crate::api::router_aspect_ratio::RouterAspectRatio;
use crate::api::router_resolution::RouterResolution;
use crate::api::router_video_model::RouterVideoModel;
use crate::api::router_provider::RouterProvider;
use crate::client::router_artcraft_client::RouterArtcraftClient;
use crate::client::router_client::RouterClient;
use crate::generate::generate_video::generate_video_request_builder::GenerateVideoRequestBuilder;
use crate::generate::generate_video::generate_video_response::GenerateVideoResponse;
use crate::generate::generate_video::video_generation_draft_or_request::VideoGenerationDraftOrRequest;
use artcraft_client::credentials::storyteller_credential_set::StorytellerCredentialSet;
use artcraft_client::utils::api_host::ApiHost;
#[tokio::test]
#[ignore] // manually run — fires a real API request and incurs cost
async fn text_to_video() {
let response = run_pipeline(GenerateVideoRequestBuilder {
prompt: Some("A corgi running through a field of wildflowers at sunset.".to_string()),
aspect_ratio: Some(RouterAspectRatio::WideSixteenByNine),
..mini_builder()
}).await;
assert!(matches!(response, GenerateVideoResponse::Artcraft(_)));
assert_eq!(1, 2, "Inspect output above");
}
#[tokio::test]
#[ignore] // manually run — fires a real API request and incurs cost
async fn res_480p() {
let response = run_pipeline(GenerateVideoRequestBuilder {
prompt: Some("A shiba inu playing in autumn leaves.".to_string()),
resolution: Some(RouterResolution::FourEightyP),
..mini_builder()
}).await;
assert!(matches!(response, GenerateVideoResponse::Artcraft(_)));
assert_eq!(1, 2, "Inspect output above");
}
fn mini_builder() -> GenerateVideoRequestBuilder {
GenerateVideoRequestBuilder {
model: RouterVideoModel::Seedance2p0Mini,
provider: RouterProvider::Artcraft,
duration_seconds: Some(4),
video_batch_count: Some(1),
..Default::default()
}
}
fn get_artcraft_client() -> RouterClient {
let cookies = std::fs::read_to_string("/Users/bt/Artcraft/credentials/artcraft_cookies.txt")
.expect("Failed to read artcraft cookies");
let cookies = cookies.trim().to_string();
let credentials = StorytellerCredentialSet::parse_multi_cookie_header(&cookies)
.expect("Failed to parse cookies")
.expect("No credentials found");
RouterClient::Artcraft(RouterArtcraftClient::new(ApiHost::Storyteller, credentials))
}
async fn run_pipeline(builder: GenerateVideoRequestBuilder) -> GenerateVideoResponse {
let client = get_artcraft_client();
let draft_or_request = builder.build2().expect("build2 should succeed");
let request = match draft_or_request {
VideoGenerationDraftOrRequest::Request(r) => r,
_ => panic!("expected Request variant (Artcraft skips draft)"),
};
request.send_request(&client).await.expect("send_request should succeed")
}
}
@@ -13,7 +13,7 @@ pub fn build_artcraft_seedance_2p0_u(builder: GenerateVideoRequestBuilder) -> Re
let request = build_artcraft_omni_video_request(
builder,
CommonVideoModelEnum::Seedance2p0Ultra,
SupportedResolutions::Full,
SupportedResolutions::FullWith4k,
UltraWideSupport::Supported,
)?;
let state = ArtcraftSeedance2p0UltraRequestState { request };
@@ -105,6 +105,12 @@ mod tests {
assert_eq!(req.request.resolution, Some(CommonResolutionEnum::TenEightyP));
}
#[test]
fn res_4k() {
let req = unwrap_request(make_builder(|b| { b.resolution = Some(RouterResolution::FourK); }));
assert_eq!(req.request.resolution, Some(CommonResolutionEnum::FourK));
}
#[test]
fn none_stays_none() {
let req = unwrap_request(make_builder(|_| {}));
@@ -1,7 +1,8 @@
use enums::common::generation::common_resolution::CommonResolution;
use crate::generate::generate_video::video_generation_cost_estimate::VideoGenerationCostEstimate;
use crate::generate::generate_video::providers::artcraft::seedance_common::seedance_2p0_four_k_usd_cents;
use crate::generate::generate_video::providers::artcraft::seedance_2p0_u::request::ArtcraftSeedance2p0UltraRequestState;
use crate::generate::generate_video::video_generation_cost_estimate::VideoGenerationCostEstimate;
// ── Pricing constants ──
@@ -13,6 +14,7 @@ pub struct ArtcraftSeedance2p0UltraCostState {
pub resolution: CommonResolution,
pub duration_seconds: u16,
pub batch_count: u16,
pub has_video_reference: bool,
}
impl ArtcraftSeedance2p0UltraCostState {
@@ -21,11 +23,31 @@ impl ArtcraftSeedance2p0UltraCostState {
.unwrap_or(CommonResolution::SevenTwentyP);
let duration_seconds = request.request.duration_seconds.unwrap_or(5);
let batch_count = request.request.video_batch_count.unwrap_or(1);
let has_video_reference = request.request.reference_video_media_tokens
.as_ref()
.is_some_and(|tokens| !tokens.is_empty());
Self { resolution, duration_seconds, batch_count }
Self { resolution, duration_seconds, batch_count, has_video_reference }
}
pub fn estimate_cost(&self) -> VideoGenerationCostEstimate {
if self.resolution == CommonResolution::FourK {
let usd_cents = seedance_2p0_four_k_usd_cents(
self.duration_seconds,
self.batch_count,
self.has_video_reference,
);
return VideoGenerationCostEstimate {
cost_in_credits: Some(usd_cents),
cost_in_usd_cents: Some(usd_cents),
is_free: false,
is_unlimited: false,
is_rate_limited: false,
has_watermark: false,
failures_are_refunded: None,
};
}
let cents_per_second = match self.resolution {
CommonResolution::FourEightyP => CENTS_PER_SECOND_480P,
CommonResolution::TenEightyP => CENTS_PER_SECOND_1080P,
@@ -49,9 +71,9 @@ impl ArtcraftSeedance2p0UltraCostState {
#[cfg(test)]
mod tests {
use crate::api::router_provider::RouterProvider;
use crate::api::router_resolution::RouterResolution;
use crate::api::router_video_model::RouterVideoModel;
use crate::api::router_provider::RouterProvider;
use crate::generate::generate_video::generate_video_request_builder::GenerateVideoRequestBuilder;
mod pricing_720p {
@@ -122,6 +144,38 @@ mod tests {
}
}
mod four_k_pricing {
use enums::common::generation::common_resolution::CommonResolution;
fn artcraft_4k_cents(duration_seconds: u16, batch_count: u16, has_video_reference: bool) -> u64 {
super::super::ArtcraftSeedance2p0UltraCostState {
resolution: CommonResolution::FourK,
duration_seconds,
batch_count,
has_video_reference,
}
.estimate_cost()
.cost_in_usd_cents
.unwrap()
}
#[test]
fn explicit_4k_without_video_reference() {
assert_eq!(artcraft_4k_cents(4, 1, false), 347);
assert_eq!(artcraft_4k_cents(5, 1, false), 433);
assert_eq!(artcraft_4k_cents(10, 1, false), 866);
assert_eq!(artcraft_4k_cents(15, 1, false), 1299);
}
#[test]
fn explicit_4k_with_video_reference() {
assert_eq!(artcraft_4k_cents(4, 1, true), 416);
assert_eq!(artcraft_4k_cents(5, 1, true), 519);
assert_eq!(artcraft_4k_cents(10, 1, true), 1038);
assert_eq!(artcraft_4k_cents(15, 1, true), 1557);
}
}
mod relative_pricing {
use super::*;
@@ -0,0 +1,328 @@
//! Shared pricing for the Seedance 2.0 family of ArtCraft providers.
//!
//! ArtCraft credits equal USD cents (100 credits = $1.00).
use enums::common::generation::common_resolution::CommonResolution;
// 4K is priced uniformly across the non-Fast Seedance 2.0 models. Rates are held
// in hundredths of a USD cent per second so the math is exact integer arithmetic
// (no floating point), then rounded up to whole cents.
/// 4K output price, in hundredths of a USD cent per second (86.60 ¢/s).
const FOUR_K_CENTI_CENTS_PER_SECOND: u64 = 8660;
/// Extra hundredths of a USD cent per second when a reference video is attached
/// at 4K (17.20 ¢/s surcharge).
const FOUR_K_VIDEO_REFERENCE_SURCHARGE_CENTI_CENTS_PER_SECOND: u64 = 1720;
/// ArtCraft's user-facing price (USD cents) for Seedance 2.0 at 4K.
///
/// A reference video adds a per-second surcharge (4K with and without a video
/// reference are priced differently). The cost scales with duration and batch
/// count, rounded up to whole cents.
pub fn seedance_2p0_four_k_usd_cents(
duration_seconds: u16,
batch_count: u16,
has_video_reference: bool,
) -> u64 {
let mut centi_cents_per_second = FOUR_K_CENTI_CENTS_PER_SECOND;
if has_video_reference {
centi_cents_per_second += FOUR_K_VIDEO_REFERENCE_SURCHARGE_CENTI_CENTS_PER_SECOND;
}
let total_centi_cents =
centi_cents_per_second * duration_seconds as u64 * batch_count as u64;
// Round up to whole cents.
total_centi_cents.div_ceil(100)
}
// ── Seedance 2.0 Mini pricing ──
//
// Mini offers only 480p and 720p. The rates below are the per-second USER price
// in USD cents (margin already included); a reference video adds a per-second
// surcharge. Rates are fractional, so the total is rounded UP to a whole cent
// once at the end (after multiplying by duration × batch).
//
// The regular Mini and the BytePlus / BytePlus Ultra Minis carry DIFFERENT
// margins, so they have separate rate sets and helpers below.
/// Regular Mini — 480p price, USD cents per second.
const MINI_CENTS_PER_SECOND_480P: f64 = 3.24074074;
/// Regular Mini — 480p reference-video surcharge, USD cents per second.
const MINI_VIDEO_REFERENCE_SURCHARGE_CENTS_PER_SECOND_480P: f64 = 0.86419753;
/// Regular Mini — 720p price, USD cents per second.
const MINI_CENTS_PER_SECOND_720P: f64 = 8.64197531;
/// Regular Mini — 720p reference-video surcharge, USD cents per second.
const MINI_VIDEO_REFERENCE_SURCHARGE_CENTS_PER_SECOND_720P: f64 = 1.72839506;
/// BytePlus / BytePlus Ultra Mini — 480p price, USD cents per second.
const BYTEPLUS_MINI_CENTS_PER_SECOND_480P: f64 = 3.27160494;
/// BytePlus / BytePlus Ultra Mini — 480p reference-video surcharge, USD cents per second.
const BYTEPLUS_MINI_VIDEO_REFERENCE_SURCHARGE_CENTS_PER_SECOND_480P: f64 = 0.87242798;
/// BytePlus / BytePlus Ultra Mini — 720p price, USD cents per second.
const BYTEPLUS_MINI_CENTS_PER_SECOND_720P: f64 = 8.72427984;
/// BytePlus / BytePlus Ultra Mini — 720p reference-video surcharge, USD cents per second.
const BYTEPLUS_MINI_VIDEO_REFERENCE_SURCHARGE_CENTS_PER_SECOND_720P: f64 = 1.74485597;
/// ArtCraft's user-facing price (USD cents) for the regular Seedance 2.0 Mini.
///
/// Only 480p and 720p are offered; any other resolution prices at 720p. A
/// reference video adds the per-second surcharge. The fractional total is
/// rounded UP to a whole cent.
pub fn seedance_2p0_mini_usd_cents(
resolution: CommonResolution,
duration_seconds: u16,
batch_count: u16,
has_video_reference: bool,
) -> u64 {
mini_usd_cents(
resolution,
duration_seconds,
batch_count,
has_video_reference,
MINI_CENTS_PER_SECOND_480P,
MINI_VIDEO_REFERENCE_SURCHARGE_CENTS_PER_SECOND_480P,
MINI_CENTS_PER_SECOND_720P,
MINI_VIDEO_REFERENCE_SURCHARGE_CENTS_PER_SECOND_720P,
)
}
/// ArtCraft's user-facing price (USD cents) for the Seedance 2.0 BytePlus Mini
/// and BytePlus Ultra Mini (which share the same rates — a higher margin than
/// the regular Mini).
///
/// Only 480p and 720p are offered; any other resolution prices at 720p. A
/// reference video adds the per-second surcharge. The fractional total is
/// rounded UP to a whole cent.
pub fn seedance_2p0_byteplus_mini_usd_cents(
resolution: CommonResolution,
duration_seconds: u16,
batch_count: u16,
has_video_reference: bool,
) -> u64 {
mini_usd_cents(
resolution,
duration_seconds,
batch_count,
has_video_reference,
BYTEPLUS_MINI_CENTS_PER_SECOND_480P,
BYTEPLUS_MINI_VIDEO_REFERENCE_SURCHARGE_CENTS_PER_SECOND_480P,
BYTEPLUS_MINI_CENTS_PER_SECOND_720P,
BYTEPLUS_MINI_VIDEO_REFERENCE_SURCHARGE_CENTS_PER_SECOND_720P,
)
}
#[allow(clippy::too_many_arguments)]
fn mini_usd_cents(
resolution: CommonResolution,
duration_seconds: u16,
batch_count: u16,
has_video_reference: bool,
cents_per_second_480p: f64,
video_reference_surcharge_per_second_480p: f64,
cents_per_second_720p: f64,
video_reference_surcharge_per_second_720p: f64,
) -> u64 {
let (base_per_second, video_reference_surcharge_per_second) = match resolution {
CommonResolution::FourEightyP => (cents_per_second_480p, video_reference_surcharge_per_second_480p),
// Everything else (including 720p and unsupported resolutions) prices at 720p.
_ => (cents_per_second_720p, video_reference_surcharge_per_second_720p),
};
let mut cents_per_second = base_per_second;
if has_video_reference {
cents_per_second += video_reference_surcharge_per_second;
}
(cents_per_second * duration_seconds as f64 * batch_count as f64).ceil() as u64
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn four_k_without_video_reference() {
assert_eq!(seedance_2p0_four_k_usd_cents(4, 1, false), 347);
assert_eq!(seedance_2p0_four_k_usd_cents(5, 1, false), 433);
assert_eq!(seedance_2p0_four_k_usd_cents(10, 1, false), 866);
assert_eq!(seedance_2p0_four_k_usd_cents(15, 1, false), 1299);
}
#[test]
fn four_k_with_video_reference() {
assert_eq!(seedance_2p0_four_k_usd_cents(4, 1, true), 416);
assert_eq!(seedance_2p0_four_k_usd_cents(5, 1, true), 519);
assert_eq!(seedance_2p0_four_k_usd_cents(10, 1, true), 1038);
assert_eq!(seedance_2p0_four_k_usd_cents(15, 1, true), 1557);
}
#[test]
fn video_reference_always_costs_more() {
for &duration in &[4u16, 5, 10, 15] {
assert!(
seedance_2p0_four_k_usd_cents(duration, 1, true)
> seedance_2p0_four_k_usd_cents(duration, 1, false),
"video reference should cost more at {duration}s",
);
}
}
#[test]
fn batch_count_multiplies() {
assert_eq!(seedance_2p0_four_k_usd_cents(5, 2, false), 866);
assert_eq!(seedance_2p0_four_k_usd_cents(5, 4, false), 1732);
assert_eq!(seedance_2p0_four_k_usd_cents(5, 2, true), 1038);
}
// ── Seedance 2.0 Mini ──
//
// Every combination (480p/720p × with/without video reference × 4/5/10/15s)
// at batch 1. These are the supplier's per-combo cost plus a 5% margin,
// rounded up to whole cents.
mod mini {
use super::*;
fn cents(res: CommonResolution, dur: u16, has_ref: bool) -> u64 {
seedance_2p0_mini_usd_cents(res, dur, 1, has_ref)
}
#[test]
fn four_eighty_p_without_video_reference() {
assert_eq!(cents(CommonResolution::FourEightyP, 4, false), 13);
assert_eq!(cents(CommonResolution::FourEightyP, 5, false), 17);
assert_eq!(cents(CommonResolution::FourEightyP, 10, false), 33);
assert_eq!(cents(CommonResolution::FourEightyP, 15, false), 49);
}
#[test]
fn four_eighty_p_with_video_reference() {
assert_eq!(cents(CommonResolution::FourEightyP, 4, true), 17);
assert_eq!(cents(CommonResolution::FourEightyP, 5, true), 21);
assert_eq!(cents(CommonResolution::FourEightyP, 10, true), 42);
assert_eq!(cents(CommonResolution::FourEightyP, 15, true), 62);
}
#[test]
fn seven_twenty_p_without_video_reference() {
assert_eq!(cents(CommonResolution::SevenTwentyP, 4, false), 35);
assert_eq!(cents(CommonResolution::SevenTwentyP, 5, false), 44);
assert_eq!(cents(CommonResolution::SevenTwentyP, 10, false), 87);
assert_eq!(cents(CommonResolution::SevenTwentyP, 15, false), 130);
}
#[test]
fn seven_twenty_p_with_video_reference() {
assert_eq!(cents(CommonResolution::SevenTwentyP, 4, true), 42);
assert_eq!(cents(CommonResolution::SevenTwentyP, 5, true), 52);
assert_eq!(cents(CommonResolution::SevenTwentyP, 10, true), 104);
assert_eq!(cents(CommonResolution::SevenTwentyP, 15, true), 156);
}
#[test]
fn video_reference_always_costs_more() {
for res in [CommonResolution::FourEightyP, CommonResolution::SevenTwentyP] {
for dur in [4u16, 5, 10, 15] {
assert!(
cents(res, dur, true) > cents(res, dur, false),
"video ref should cost more at {res:?} {dur}s",
);
}
}
}
#[test]
fn unsupported_resolution_prices_at_720p() {
assert_eq!(
seedance_2p0_mini_usd_cents(CommonResolution::TenEightyP, 5, 1, false),
seedance_2p0_mini_usd_cents(CommonResolution::SevenTwentyP, 5, 1, false),
);
}
#[test]
fn batch_count_scales_the_total() {
// Batch is baked in before the single round-up, so batched totals can be
// a cent under N× the single price.
assert_eq!(seedance_2p0_mini_usd_cents(CommonResolution::SevenTwentyP, 5, 2, false), 87);
assert_eq!(seedance_2p0_mini_usd_cents(CommonResolution::SevenTwentyP, 5, 4, false), 173);
assert_eq!(seedance_2p0_mini_usd_cents(CommonResolution::FourEightyP, 5, 2, false), 33);
}
}
// ── Seedance 2.0 BytePlus / BytePlus Ultra Mini ──
//
// Same combinations as the regular Mini, but at a higher margin (6% vs 5%),
// so the prices are equal-or-higher than the regular Mini.
mod byteplus_mini {
use super::*;
fn cents(res: CommonResolution, dur: u16, has_ref: bool) -> u64 {
seedance_2p0_byteplus_mini_usd_cents(res, dur, 1, has_ref)
}
#[test]
fn four_eighty_p_without_video_reference() {
assert_eq!(cents(CommonResolution::FourEightyP, 4, false), 14);
assert_eq!(cents(CommonResolution::FourEightyP, 5, false), 17);
assert_eq!(cents(CommonResolution::FourEightyP, 10, false), 33);
assert_eq!(cents(CommonResolution::FourEightyP, 15, false), 50);
}
#[test]
fn four_eighty_p_with_video_reference() {
assert_eq!(cents(CommonResolution::FourEightyP, 4, true), 17);
assert_eq!(cents(CommonResolution::FourEightyP, 5, true), 21);
assert_eq!(cents(CommonResolution::FourEightyP, 10, true), 42);
assert_eq!(cents(CommonResolution::FourEightyP, 15, true), 63);
}
#[test]
fn seven_twenty_p_without_video_reference() {
assert_eq!(cents(CommonResolution::SevenTwentyP, 4, false), 35);
assert_eq!(cents(CommonResolution::SevenTwentyP, 5, false), 44);
assert_eq!(cents(CommonResolution::SevenTwentyP, 10, false), 88);
assert_eq!(cents(CommonResolution::SevenTwentyP, 15, false), 131);
}
#[test]
fn seven_twenty_p_with_video_reference() {
assert_eq!(cents(CommonResolution::SevenTwentyP, 4, true), 42);
assert_eq!(cents(CommonResolution::SevenTwentyP, 5, true), 53);
assert_eq!(cents(CommonResolution::SevenTwentyP, 10, true), 105);
assert_eq!(cents(CommonResolution::SevenTwentyP, 15, true), 158);
}
#[test]
fn never_cheaper_than_regular_mini() {
for res in [CommonResolution::FourEightyP, CommonResolution::SevenTwentyP] {
for dur in [4u16, 5, 10, 15] {
for has_ref in [false, true] {
assert!(
seedance_2p0_byteplus_mini_usd_cents(res, dur, 1, has_ref)
>= seedance_2p0_mini_usd_cents(res, dur, 1, has_ref),
"byteplus mini (6%) should be >= regular mini (5%) at {res:?} {dur}s ref={has_ref}",
);
}
}
}
}
#[test]
fn unsupported_resolution_prices_at_720p() {
assert_eq!(
seedance_2p0_byteplus_mini_usd_cents(CommonResolution::TenEightyP, 5, 1, false),
seedance_2p0_byteplus_mini_usd_cents(CommonResolution::SevenTwentyP, 5, 1, false),
);
}
#[test]
fn batch_count_scales_the_total() {
assert_eq!(seedance_2p0_byteplus_mini_usd_cents(CommonResolution::SevenTwentyP, 5, 2, false), 88);
assert_eq!(seedance_2p0_byteplus_mini_usd_cents(CommonResolution::SevenTwentyP, 5, 4, false), 175);
assert_eq!(seedance_2p0_byteplus_mini_usd_cents(CommonResolution::FourEightyP, 5, 2, false), 33);
}
}
}
@@ -28,11 +28,11 @@ use crate::generate::generate_video::video_generation_request::VideoGenerationRe
/// the only material differences are the `model` identifier on the wire and
/// the steeper pricing in the cost calculator (see `cost.rs`).
///
/// xAI's grok-imagine-video-1.5-preview accepts:
/// xAI's grok-imagine-video-1.5 accepts:
/// - `image` (single source image, image-to-video mode) OR `reference_images`
/// (multi-image reference-to-video). These two are mutually exclusive per
/// xAI's API.
/// - Aspect ratio, resolution (480p/720p), duration (1–15s), prompt.
/// - Aspect ratio, resolution (480p/720p/1080p), duration (1–15s), prompt.
///
/// Fields that Grok DOESN'T accept (`end_frame`, `reference_videos`,
/// `reference_audio`, and `MediaFileToken`-style image refs) are silently
@@ -78,7 +78,7 @@ pub fn build_grok_api_grok_imagine_video_1p5(
if image.is_none() && reference_images.is_none() {
return Err(ArtcraftRouterError::Client(ClientError::ModelDoesNotSupportOption {
field: "image_inputs",
value: "text-to-video isn't supported by grok-imagine-video-1.5-preview; supply a start_frame or at least one reference image".to_string(),
value: "text-to-video isn't supported by grok-imagine-video-1.5; supply a start_frame or at least one reference image".to_string(),
}));
}
@@ -86,7 +86,7 @@ pub fn build_grok_api_grok_imagine_video_1p5(
prompt,
// Pin to the 1.5 preview identifier so the grok_api_client cost
// calculator picks the v1.5 pricing tier (see VideoModel::pricing_tier).
model: Some(GrokVideoModel::GrokImagineVideo1p5Preview),
model: Some(GrokVideoModel::GrokImagineVideo1p5),
image,
reference_images,
aspect_ratio,
@@ -146,10 +146,11 @@ fn plan_resolution(
None => None,
Some(RouterResolution::FourEightyP) => Some(GrokResolution::FourEightyP),
Some(RouterResolution::SevenTwentyP) => Some(GrokResolution::SevenTwentyP),
Some(RouterResolution::TenEightyP)
| Some(RouterResolution::TwoK)
Some(RouterResolution::TenEightyP) => Some(GrokResolution::TenEightyP),
// 2K/3K/4K aren't produced — cap at the model's max of 1080p.
Some(RouterResolution::TwoK)
| Some(RouterResolution::ThreeK)
| Some(RouterResolution::FourK) => Some(GrokResolution::SevenTwentyP),
| Some(RouterResolution::FourK) => Some(GrokResolution::TenEightyP),
Some(RouterResolution::HalfK) | Some(RouterResolution::OneK) => {
Some(GrokResolution::FourEightyP)
}
@@ -279,7 +280,7 @@ mod tests {
let req = unwrap_request(make_builder(|_| {}));
assert_eq!(
req.request.model,
Some(GrokVideoModel::GrokImagineVideo1p5Preview),
Some(GrokVideoModel::GrokImagineVideo1p5),
);
}
@@ -289,7 +290,7 @@ mod tests {
// calculator in grok_api_client keys off this string.
let req = unwrap_request(make_builder(|_| {}));
let model = req.request.model.as_ref().expect("model should be set");
assert_eq!(model.as_str(), "grok-imagine-video-1.5-preview");
assert_eq!(model.as_str(), "grok-imagine-video-1.5");
}
}
@@ -417,15 +418,15 @@ mod tests {
}
#[test]
fn res_1080p_clamps_to_720p() {
fn res_1080p_maps_to_1080p() {
let req = unwrap_request(make_builder(|b| { b.resolution = Some(RouterResolution::TenEightyP); }));
assert_eq!(req.request.resolution, Some(GrokResolution::SevenTwentyP));
assert_eq!(req.request.resolution, Some(GrokResolution::TenEightyP));
}
#[test]
fn res_4k_clamps_to_720p() {
fn res_4k_caps_to_1080p() {
let req = unwrap_request(make_builder(|b| { b.resolution = Some(RouterResolution::FourK); }));
assert_eq!(req.request.resolution, Some(GrokResolution::SevenTwentyP));
assert_eq!(req.request.resolution, Some(GrokResolution::TenEightyP));
}
#[test]
@@ -542,7 +543,7 @@ mod tests {
assert_eq!(req.request.resolution, Some(GrokResolution::SevenTwentyP));
assert_eq!(req.request.aspect_ratio, Some(GrokAspectRatio::Landscape16x9));
assert_eq!(req.request.duration, Some(5));
assert_eq!(req.request.model, Some(GrokVideoModel::GrokImagineVideo1p5Preview));
assert_eq!(req.request.model, Some(GrokVideoModel::GrokImagineVideo1p5));
}
#[test]
@@ -660,7 +661,7 @@ mod tests {
assert_eq!(req.request.aspect_ratio, Some(GrokAspectRatio::Landscape16x9));
assert_eq!(req.request.duration, Some(8));
// Still pinned to the 1.5 model regardless of kitchen-sink inputs.
assert_eq!(req.request.model, Some(GrokVideoModel::GrokImagineVideo1p5Preview));
assert_eq!(req.request.model, Some(GrokVideoModel::GrokImagineVideo1p5));
}
}
@@ -21,13 +21,13 @@ impl GrokApiGrokImagineVideo1p5CostState {
if self.request.request.image.is_none() && self.request.request.reference_images.is_none() {
return Err(ArtcraftRouterError::Client(ClientError::ModelDoesNotSupportOption {
field: "image_inputs",
value: "text-to-video isn't supported by grok-imagine-video-1.5-preview; supply a start_frame or at least one reference image".to_string(),
value: "text-to-video isn't supported by grok-imagine-video-1.5; supply a start_frame or at least one reference image".to_string(),
}));
}
// grok_api_client's calculator picks the v1.5 pricing tier from the
// request's `model` field (see VideoModel::pricing_tier). The build step
// sets `model = Some(GrokImagineVideo1p5Preview)`, so this returns the
// sets `model = Some(GrokImagineVideo1p5)`, so this returns the
// v1.5 rates:
// Output: 80 mills/s @ 480p, 140 mills/s @ 720p
// Input: 10 mills per source image
@@ -205,10 +205,11 @@ mod tests {
}
#[test]
fn ten_eighty_p_request_clamps_to_720p_pricing() {
fn ten_eighty_p_prices_higher_than_720p() {
// Grok Imagine 1.5 now renders genuine 1080p ($0.25/s vs $0.14/s @ 720p).
let p1080 = cost_cents(Some(RouterResolution::TenEightyP), 10, None, None);
let p720 = cost_cents(Some(RouterResolution::SevenTwentyP), 10, None, None);
assert_eq!(p1080, p720);
assert!(p1080 > p720, "1080p ({p1080}) should cost more than 720p ({p720})");
}
}
@@ -305,7 +306,7 @@ mod tests {
fn estimate_cost_returns_err_when_no_image_sources() {
let request = GrokVideoGenerationRequest {
prompt: "text only".to_string(),
model: Some(GrokVideoModel::GrokImagineVideo1p5Preview),
model: Some(GrokVideoModel::GrokImagineVideo1p5),
image: None,
reference_images: None,
aspect_ratio: None,
@@ -15,7 +15,7 @@ use crate::generate::generate_video::generate_video_response::{
#[derive(Clone, Debug)]
pub struct GrokApiGrokImagineVideo1p5RequestState {
/// The fully-resolved Grok request body, with `model` set to
/// `VideoModel::GrokImagineVideo1p5Preview`. Doesn't carry the API key —
/// `VideoModel::GrokImagineVideo1p5`. Doesn't carry the API key —
/// that gets borrowed at send time from the router client.
pub request: GrokVideoGenerationRequest,
}
@@ -27,7 +27,7 @@ impl GrokApiGrokImagineVideo1p5RequestState {
if self.request.image.is_none() && self.request.reference_images.is_none() {
return Err(ArtcraftRouterError::Client(ClientError::ModelDoesNotSupportOption {
field: "image_inputs",
value: "text-to-video isn't supported by grok-imagine-video-1.5-preview; supply a start_frame or at least one reference image".to_string(),
value: "text-to-video isn't supported by grok-imagine-video-1.5; supply a start_frame or at least one reference image".to_string(),
}));
}
@@ -77,7 +77,7 @@ mod tests {
..grok_builder()
};
let request = unwrap_request(builder);
assert_eq!(request.request.model, Some(VideoModel::GrokImagineVideo1p5Preview));
assert_eq!(request.request.model, Some(VideoModel::GrokImagineVideo1p5));
}
// ── Live API tests (manual) ──
@@ -1,5 +1,6 @@
pub mod happy_horse_1p0;
pub mod seedance_2p0;
pub mod seedance_2p0_fast;
pub mod seedance_2p0_mini;
pub(crate) mod resolve;
pub(crate) mod upload;
@@ -111,7 +111,7 @@ fn nearest_aspect_ratio(aspect_ratio: RouterAspectRatio) -> KinoviAspectRatio {
}
}
// Seedance 2.0 Pro supports output resolutions: 480p, 720p, 1080p.
// Seedance 2.0 Pro supports output resolutions: 480p, 720p, 1080p, 4K.
fn plan_output_resolution(
resolution: Option<RouterResolution>,
strategy: RequestMismatchMitigationStrategy,
@@ -123,6 +123,7 @@ fn plan_output_resolution(
Some(RouterResolution::FourEightyP) => Ok(Some(KinoviOutputResolution::FourEightyP)),
Some(RouterResolution::SevenTwentyP) => Ok(Some(KinoviOutputResolution::SevenTwentyP)),
Some(RouterResolution::TenEightyP) => Ok(Some(KinoviOutputResolution::TenEightyP)),
Some(RouterResolution::FourK) => Ok(Some(KinoviOutputResolution::FourK)),
// Mismatches
Some(unsupported) => match strategy {
@@ -376,6 +377,16 @@ mod tests {
assert!(matches!(draft.resolution, Some(KinoviOutputResolution::TenEightyP)));
}
#[test]
fn resolution_4k() {
let builder = GenerateVideoRequestBuilder {
resolution: Some(RouterResolution::FourK),
..seedance2pro_builder()
};
let draft = unwrap_draft(build_kinovi_seedance_2p0(builder));
assert!(matches!(draft.resolution, Some(KinoviOutputResolution::FourK)));
}
#[test]
fn resolution_none() {
let builder = GenerateVideoRequestBuilder { resolution: None, ..seedance2pro_builder() };
@@ -386,7 +397,7 @@ mod tests {
#[test]
fn unsupported_resolution_error_out() {
let builder = GenerateVideoRequestBuilder {
resolution: Some(RouterResolution::FourK),
resolution: Some(RouterResolution::ThreeK),
request_mismatch_mitigation_strategy: RequestMismatchMitigationStrategy::ErrorOut,
..seedance2pro_builder()
};
@@ -396,7 +407,7 @@ mod tests {
#[test]
fn unsupported_resolution_rounds_up() {
let builder = GenerateVideoRequestBuilder {
resolution: Some(RouterResolution::FourK),
resolution: Some(RouterResolution::ThreeK),
request_mismatch_mitigation_strategy: RequestMismatchMitigationStrategy::PayMoreUpgrade,
..seedance2pro_builder()
};
@@ -175,6 +175,121 @@ mod tests {
}
}
// ── 4K pricing ──
//
// Routes to the seedance2pro_client: 4K base is 200 credits/s (vs 90 at 1080p).
// Credits → cents at 243 credits/$1, rounded up.
mod pricing_4k {
use super::*;
#[test]
fn cost_4k_batch_1() {
assert_eq!(usd_cents(KinoviOutputResolution::FourK, 4, KinoviBatchCount::One), 330);
assert_eq!(usd_cents(KinoviOutputResolution::FourK, 5, KinoviBatchCount::One), 412);
assert_eq!(usd_cents(KinoviOutputResolution::FourK, 10, KinoviBatchCount::One), 824);
assert_eq!(usd_cents(KinoviOutputResolution::FourK, 15, KinoviBatchCount::One), 1235);
}
#[test]
fn cost_4k_batch_2() {
assert_eq!(usd_cents(KinoviOutputResolution::FourK, 5, KinoviBatchCount::Two), 824);
}
#[test]
fn cost_4k_batch_4() {
assert_eq!(usd_cents(KinoviOutputResolution::FourK, 5, KinoviBatchCount::Four), 1647);
}
}
// ── 4K: router cost must match the seedance2pro_client binding ──
//
// The router delegates to GenerateSeedance2p0Request::calculate_costs(), so these
// assert the exact 4K numbers AND cross-check the router against the binding for
// every duration (4/5/10/15s) with and without a video reference.
//
// 4K base = 200 credits/s; with a video reference = 240 credits/s (+40 surcharge).
// USD cents = ceil(total_credits / 243 * 100).
mod four_k_matches_binding {
use super::*;
use seedance2pro_client::generate::video::generate_seedance_2p0::GenerateSeedance2p0Request;
/// Router-side 4K cost (batch 1) for a duration / video-reference combo.
fn router(duration_seconds: u8, has_video_reference: bool) -> VideoGenerationCostEstimate {
KinoviSeedance2p0CostState {
resolution: Some(KinoviOutputResolution::FourK),
duration_seconds,
batch_count: Some(KinoviBatchCount::One),
has_video_reference,
}
.estimate_cost()
}
/// The seedance2pro_client binding's own 4K cost for the same inputs.
/// Returns (kinovi_credits, usd_cents_rounded_up).
fn binding(duration_seconds: u8, has_video_reference: bool) -> (u64, u64) {
let reference_video_urls = if has_video_reference {
Some(vec!["pricing-placeholder".to_string()])
} else {
None
};
let costs = GenerateSeedance2p0Request {
output_resolution: Some(KinoviOutputResolution::FourK),
duration_seconds,
batch_count: Some(KinoviBatchCount::One),
reference_video_urls,
prompt: String::new(),
aspect_ratio: None,
start_frame_url: None,
end_frame_url: None,
reference_image_urls: None,
reference_audio_urls: None,
character_ids: None,
use_face_blur_hack: None,
bitrate: None,
}
.calculate_costs();
(costs.total_cost.kinovi_credits, costs.total_cost.usd_cents_rounded_up)
}
#[test]
fn explicit_values_without_video_reference() {
// 200 credits/s.
assert_eq!((router(4, false).cost_in_credits, router(4, false).cost_in_usd_cents), (Some(800), Some(330)));
assert_eq!((router(5, false).cost_in_credits, router(5, false).cost_in_usd_cents), (Some(1000), Some(412)));
assert_eq!((router(10, false).cost_in_credits, router(10, false).cost_in_usd_cents), (Some(2000), Some(824)));
assert_eq!((router(15, false).cost_in_credits, router(15, false).cost_in_usd_cents), (Some(3000), Some(1235)));
}
#[test]
fn explicit_values_with_video_reference() {
// 240 credits/s (200 base + 40 surcharge).
assert_eq!((router(4, true).cost_in_credits, router(4, true).cost_in_usd_cents), (Some(960), Some(396)));
assert_eq!((router(5, true).cost_in_credits, router(5, true).cost_in_usd_cents), (Some(1200), Some(494)));
assert_eq!((router(10, true).cost_in_credits, router(10, true).cost_in_usd_cents), (Some(2400), Some(988)));
assert_eq!((router(15, true).cost_in_credits, router(15, true).cost_in_usd_cents), (Some(3600), Some(1482)));
}
#[test]
fn router_matches_binding_for_every_duration_and_video_ref() {
for &duration in &[4u8, 5, 10, 15] {
for &has_ref in &[false, true] {
let r = router(duration, has_ref);
let (b_credits, b_cents) = binding(duration, has_ref);
assert_eq!(
r.cost_in_credits, Some(b_credits),
"credits differ at {duration}s has_video_reference={has_ref}",
);
assert_eq!(
r.cost_in_usd_cents, Some(b_cents),
"usd cents differ at {duration}s has_video_reference={has_ref}",
);
}
}
}
}
// ── Relative pricing ──
mod relative_pricing_tests {
@@ -189,6 +304,13 @@ mod tests {
assert!(c720 < c1080, "720p ({}) should be cheaper than 1080p ({})", c720, c1080);
}
#[test]
fn cost_1080p_cheaper_than_4k() {
let c1080 = usd_cents(KinoviOutputResolution::TenEightyP, 5, KinoviBatchCount::One);
let c4k = usd_cents(KinoviOutputResolution::FourK, 5, KinoviBatchCount::One);
assert!(c1080 < c4k, "1080p ({}) should be cheaper than 4K ({})", c1080, c4k);
}
#[test]
fn cost_scales_with_duration() {
let c4 = usd_cents(KinoviOutputResolution::SevenTwentyP, 4, KinoviBatchCount::One);
@@ -306,6 +428,24 @@ mod tests {
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(31));
}
#[test]
fn from_draft_4k() {
let draft = make_draft(5, 1, Some(RouterResolution::FourK), false);
let cost = KinoviSeedance2p0CostState::from_draft(&draft);
assert!(matches!(cost.resolution, Some(KinoviOutputResolution::FourK)));
assert_eq!(cost.estimate_cost().cost_in_credits, Some(1000));
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(412));
}
#[test]
fn from_draft_4k_with_video_reference() {
let draft = make_draft(5, 1, Some(RouterResolution::FourK), true);
let cost = KinoviSeedance2p0CostState::from_draft(&draft);
// 4K base 200 + video-ref surcharge 40 = 240 credits/s -> 1200 credits for 5s.
assert_eq!(cost.estimate_cost().cost_in_credits, Some(1200));
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(494));
}
#[test]
fn from_draft_1080p_batch_4() {
let draft = make_draft(5, 4, Some(RouterResolution::TenEightyP), false);
@@ -388,6 +528,11 @@ mod tests {
fn credits_1080p() {
assert_eq!(credits(KinoviOutputResolution::TenEightyP, 5, KinoviBatchCount::One), 450);
}
#[test]
fn credits_4k() {
assert_eq!(credits(KinoviOutputResolution::FourK, 5, KinoviBatchCount::One), 1000);
}
}
// ── Helpers ──
@@ -0,0 +1,510 @@
use seedance2pro_client::generate::video::generate_seedance_2p0_mini::{
KinoviSeedance2p0MiniAspectRatio as KinoviAspectRatio,
KinoviSeedance2p0MiniBitrate as KinoviBitrate,
KinoviSeedance2p0MiniBatchCount as KinoviBatchCount,
KinoviSeedance2p0MiniOutputResolution as KinoviOutputResolution,
};
use crate::api::router_aspect_ratio::RouterAspectRatio;
use crate::api::router_bitrate::RouterBitrate;
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_video::generate_video_request_builder::GenerateVideoRequestBuilder;
use crate::generate::generate_video::providers::kinovi::seedance_2p0_mini::draft::{KinoviSeedance2p0MiniDraftState, KinoviSeedance2p0MiniRemainingItems};
use crate::generate::generate_video::video_generation_draft::VideoGenerationDraftRequest;
use crate::generate::generate_video::video_generation_draft_or_request::VideoGenerationDraftOrRequest;
pub fn build_kinovi_seedance_2p0_mini(builder: GenerateVideoRequestBuilder) -> Result<VideoGenerationDraftOrRequest, ArtcraftRouterError> {
let draft = do_build_kinovi_seedance_2p0_mini(builder)?;
Ok(VideoGenerationDraftOrRequest::Draft(VideoGenerationDraftRequest::KinoviSeedance2p0Mini(draft)))
}
fn do_build_kinovi_seedance_2p0_mini(mut builder: GenerateVideoRequestBuilder) -> Result<KinoviSeedance2p0MiniDraftState, ArtcraftRouterError> {
let strategy = builder.request_mismatch_mitigation_strategy;
let aspect_ratio = plan_aspect_ratio(builder.aspect_ratio.take(), strategy)?;
let resolution = plan_output_resolution(builder.resolution.take(), strategy)?;
let batch_count = plan_batch_count(builder.video_batch_count.take(), strategy)?;
let duration_seconds = plan_duration(builder.duration_seconds.take(), strategy)?;
let bitrate = plan_bitrate(builder.bitrate.take());
let prompt = builder.prompt.take().unwrap_or_default();
let unhandled_request_state = KinoviSeedance2p0MiniRemainingItems {
start_frame: builder.start_frame.take(),
end_frame: builder.end_frame.take(),
reference_images: builder.reference_images.take(),
reference_videos: builder.reference_videos.take(),
reference_audio: builder.reference_audio.take(),
reference_character_tokens: builder.reference_character_tokens.take(),
};
Ok(KinoviSeedance2p0MiniDraftState {
aspect_ratio,
resolution,
batch_count,
duration_seconds,
bitrate,
prompt,
unhandled_request_state: Some(unhandled_request_state),
})
}
// ── Plan helpers ──
// Seedance 2.0 Mini supports all six aspect ratios:
// 16:9, 21:9, 9:16, 1:1, 4:3, 3:4. All supported ratios cost the same, so
// both upgrade and downgrade pick the nearest match.
fn plan_aspect_ratio(
aspect_ratio: Option<RouterAspectRatio>,
strategy: RequestMismatchMitigationStrategy,
) -> Result<KinoviAspectRatio, ArtcraftRouterError> {
match aspect_ratio {
// No preference or auto — default to landscape
None
| Some(RouterAspectRatio::Auto)
| Some(RouterAspectRatio::Auto2k)
| Some(RouterAspectRatio::Auto4k) => Ok(KinoviAspectRatio::Landscape16x9),
// Direct mappings
Some(RouterAspectRatio::WideSixteenByNine) | Some(RouterAspectRatio::Wide) => {
Ok(KinoviAspectRatio::Landscape16x9)
}
Some(RouterAspectRatio::TallNineBySixteen) | Some(RouterAspectRatio::Tall) => {
Ok(KinoviAspectRatio::Portrait9x16)
}
Some(RouterAspectRatio::Square) | Some(RouterAspectRatio::SquareHd) => {
Ok(KinoviAspectRatio::Square1x1)
}
Some(RouterAspectRatio::WideFourByThree) => Ok(KinoviAspectRatio::Standard4x3),
Some(RouterAspectRatio::TallThreeByFour) => Ok(KinoviAspectRatio::Portrait3x4),
Some(RouterAspectRatio::WideTwentyOneByNine) => Ok(KinoviAspectRatio::UltraWide21x9),
// Mismatches — apply strategy
Some(unsupported) => match strategy {
RequestMismatchMitigationStrategy::ErrorOut => {
Err(ArtcraftRouterError::Client(ClientError::ModelDoesNotSupportOption {
field: "aspect_ratio",
value: format!("{:?}", unsupported),
}))
}
RequestMismatchMitigationStrategy::PayMoreUpgrade
| RequestMismatchMitigationStrategy::PayLessDowngrade => {
Ok(nearest_aspect_ratio(unsupported))
}
},
}
}
/// Pick the nearest supported aspect ratio by AR value (width / height).
fn nearest_aspect_ratio(aspect_ratio: RouterAspectRatio) -> KinoviAspectRatio {
match aspect_ratio {
RouterAspectRatio::WideFiveByFour => KinoviAspectRatio::Standard4x3, // 1.25, nearest 1.33
RouterAspectRatio::WideThreeByTwo => KinoviAspectRatio::Standard4x3, // 1.50, nearest 1.33
RouterAspectRatio::TallFourByFive => KinoviAspectRatio::Portrait3x4, // 0.80, nearest 0.75
RouterAspectRatio::TallTwoByThree => KinoviAspectRatio::Portrait3x4, // 0.67, nearest 0.75
RouterAspectRatio::TallNineByTwentyOne => KinoviAspectRatio::Portrait9x16, // 0.43, nearest 0.56
_ => KinoviAspectRatio::Square1x1,
}
}
// Seedance 2.0 Mini supports output resolutions: 480p and 720p only.
// 1080p (and higher) is NOT supported — downgrade to 720p or error based on strategy.
fn plan_output_resolution(
resolution: Option<RouterResolution>,
strategy: RequestMismatchMitigationStrategy,
) -> Result<Option<KinoviOutputResolution>, ArtcraftRouterError> {
match resolution {
None => Ok(None),
// Direct mappings
Some(RouterResolution::FourEightyP) => Ok(Some(KinoviOutputResolution::FourEightyP)),
Some(RouterResolution::SevenTwentyP) => Ok(Some(KinoviOutputResolution::SevenTwentyP)),
// 1080p is not supported for Mini — handle via strategy
Some(RouterResolution::TenEightyP) => match strategy {
RequestMismatchMitigationStrategy::ErrorOut => {
Err(ArtcraftRouterError::Client(ClientError::ModelDoesNotSupportOption {
field: "resolution",
value: format!("{:?}", RouterResolution::TenEightyP),
}))
}
RequestMismatchMitigationStrategy::PayMoreUpgrade
| RequestMismatchMitigationStrategy::PayLessDowngrade => {
// 1080p not available — downgrade to 720p (highest supported)
Ok(Some(KinoviOutputResolution::SevenTwentyP))
}
},
// Other unsupported resolutions
Some(unsupported) => match strategy {
RequestMismatchMitigationStrategy::ErrorOut => {
Err(ArtcraftRouterError::Client(ClientError::ModelDoesNotSupportOption {
field: "resolution",
value: format!("{:?}", unsupported),
}))
}
RequestMismatchMitigationStrategy::PayMoreUpgrade
| RequestMismatchMitigationStrategy::PayLessDowngrade => {
Ok(Some(match unsupported {
RouterResolution::HalfK => KinoviOutputResolution::FourEightyP,
_ => KinoviOutputResolution::SevenTwentyP,
}))
}
},
}
}
// Seedance 2.0 Mini supports batch counts of 1–8.
fn plan_batch_count(
video_batch_count: Option<u16>,
strategy: RequestMismatchMitigationStrategy,
) -> Result<KinoviBatchCount, ArtcraftRouterError> {
let count = video_batch_count.unwrap_or(1);
match count {
0 => Err(ArtcraftRouterError::Client(ClientError::UserRequestedZeroGenerations)),
1 => Ok(KinoviBatchCount::One),
2 => Ok(KinoviBatchCount::Two),
3 => Ok(KinoviBatchCount::Three),
4 => Ok(KinoviBatchCount::Four),
5 => Ok(KinoviBatchCount::Five),
6 => Ok(KinoviBatchCount::Six),
7 => Ok(KinoviBatchCount::Seven),
8 => Ok(KinoviBatchCount::Eight),
// Over the maximum of 8.
_ => match strategy {
RequestMismatchMitigationStrategy::ErrorOut => {
Err(ArtcraftRouterError::Client(ClientError::ModelDoesNotSupportOption {
field: "video_batch_count",
value: format!("{}", count),
}))
}
RequestMismatchMitigationStrategy::PayMoreUpgrade
| RequestMismatchMitigationStrategy::PayLessDowngrade => Ok(KinoviBatchCount::Eight),
},
}
}
// Seedance 2.0 Mini supports duration of 4–15 seconds.
fn plan_duration(
duration_seconds: Option<u16>,
strategy: RequestMismatchMitigationStrategy,
) -> Result<u8, ArtcraftRouterError> {
const MIN: u16 = 4;
const MAX: u16 = 15;
const DEFAULT: u8 = 5;
match duration_seconds {
None => Ok(DEFAULT),
Some(d) if d >= MIN && d <= MAX => Ok(d as u8),
Some(d) => match strategy {
RequestMismatchMitigationStrategy::ErrorOut => {
Err(ArtcraftRouterError::Client(ClientError::ModelDoesNotSupportOption {
field: "duration_seconds",
value: format!("{}", d),
}))
}
_ => Ok(d.clamp(MIN, MAX) as u8),
},
}
}
// Seedance 2.0 Mini bitrate: "standard" (default, field omitted) or "high".
// Bitrate does not affect cost. `Normal` and unset both map to standard (None);
// only `High` requests the higher bitrate.
fn plan_bitrate(bitrate: Option<RouterBitrate>) -> Option<KinoviBitrate> {
match bitrate {
Some(RouterBitrate::High) => Some(KinoviBitrate::High),
Some(RouterBitrate::Normal) | None => None,
}
}
#[cfg(test)]
mod tests {
use seedance2pro_client::generate::video::generate_seedance_2p0_mini::{
KinoviSeedance2p0MiniAspectRatio as KinoviAspectRatio,
KinoviSeedance2p0MiniBatchCount as KinoviBatchCount,
KinoviSeedance2p0MiniOutputResolution as KinoviOutputResolution,
};
use tokens::tokens::characters::CharacterToken;
use tokens::tokens::media_files::MediaFileToken;
use crate::api::audio_list_ref::AudioListRef;
use crate::api::character_list_ref::CharacterListRef;
use crate::api::router_aspect_ratio::RouterAspectRatio;
use crate::api::router_resolution::RouterResolution;
use crate::api::router_video_model::RouterVideoModel;
use crate::api::image_list_ref::ImageListRef;
use crate::api::image_ref::ImageRef;
use crate::api::router_provider::RouterProvider;
use crate::api::video_list_ref::VideoListRef;
use crate::client::request_mismatch_mitigation_strategy::RequestMismatchMitigationStrategy;
use crate::generate::generate_video::generate_video_request_builder::GenerateVideoRequestBuilder;
use crate::generate::generate_video::providers::kinovi::seedance_2p0_mini::draft::KinoviSeedance2p0MiniDraftState;
use crate::generate::generate_video::video_generation_draft::VideoGenerationDraftRequest;
use crate::generate::generate_video::video_generation_draft_or_request::VideoGenerationDraftOrRequest;
use super::*;
mod materialized_field_conversions {
use super::*;
#[test]
fn prompt_is_passed_through() {
let draft = unwrap_draft(build_kinovi_seedance_2p0_mini(mini_builder()));
assert_eq!(draft.prompt, "a cat dancing");
}
#[test]
fn prompt_defaults_to_empty() {
let builder = GenerateVideoRequestBuilder { prompt: None, ..mini_builder() };
let draft = unwrap_draft(build_kinovi_seedance_2p0_mini(builder));
assert_eq!(draft.prompt, "");
}
#[test]
fn duration_seconds_converted() {
let builder = GenerateVideoRequestBuilder { duration_seconds: Some(10), ..mini_builder() };
let draft = unwrap_draft(build_kinovi_seedance_2p0_mini(builder));
assert_eq!(draft.duration_seconds, 10);
}
#[test]
fn duration_defaults_to_5() {
let builder = GenerateVideoRequestBuilder { duration_seconds: None, ..mini_builder() };
let draft = unwrap_draft(build_kinovi_seedance_2p0_mini(builder));
assert_eq!(draft.duration_seconds, 5);
}
#[test]
fn duration_clamped_to_max() {
let builder = GenerateVideoRequestBuilder { duration_seconds: Some(99), ..mini_builder() };
let draft = unwrap_draft(build_kinovi_seedance_2p0_mini(builder));
assert_eq!(draft.duration_seconds, 15);
}
}
mod batch_count_conversions {
use super::*;
#[test]
fn batch_counts_one_through_eight() {
let expected = [
(1u16, KinoviBatchCount::One),
(2, KinoviBatchCount::Two),
(3, KinoviBatchCount::Three),
(4, KinoviBatchCount::Four),
(5, KinoviBatchCount::Five),
(6, KinoviBatchCount::Six),
(7, KinoviBatchCount::Seven),
(8, KinoviBatchCount::Eight),
];
for (count, variant) in expected {
let builder = GenerateVideoRequestBuilder { video_batch_count: Some(count), ..mini_builder() };
let draft = unwrap_draft(build_kinovi_seedance_2p0_mini(builder));
assert!(
std::mem::discriminant(&draft.batch_count) == std::mem::discriminant(&variant),
"batch {count} mapped wrong",
);
}
}
#[test]
fn batch_over_max_downgrades_to_eight() {
let builder = GenerateVideoRequestBuilder {
video_batch_count: Some(12),
request_mismatch_mitigation_strategy: RequestMismatchMitigationStrategy::PayLessDowngrade,
..mini_builder()
};
let draft = unwrap_draft(build_kinovi_seedance_2p0_mini(builder));
assert!(matches!(draft.batch_count, KinoviBatchCount::Eight));
}
#[test]
fn batch_over_max_error_out() {
let builder = GenerateVideoRequestBuilder {
video_batch_count: Some(12),
request_mismatch_mitigation_strategy: RequestMismatchMitigationStrategy::ErrorOut,
..mini_builder()
};
assert!(build_kinovi_seedance_2p0_mini(builder).is_err());
}
#[test]
fn batch_zero_errors() {
let builder = GenerateVideoRequestBuilder { video_batch_count: Some(0), ..mini_builder() };
assert!(build_kinovi_seedance_2p0_mini(builder).is_err());
}
}
mod aspect_ratio_conversions {
use super::*;
#[test]
fn aspect_ratio_wide() {
let builder = GenerateVideoRequestBuilder { aspect_ratio: Some(RouterAspectRatio::WideSixteenByNine), ..mini_builder() };
let draft = unwrap_draft(build_kinovi_seedance_2p0_mini(builder));
assert!(matches!(draft.aspect_ratio, KinoviAspectRatio::Landscape16x9));
}
#[test]
fn aspect_ratio_ultra_wide() {
let builder = GenerateVideoRequestBuilder { aspect_ratio: Some(RouterAspectRatio::WideTwentyOneByNine), ..mini_builder() };
let draft = unwrap_draft(build_kinovi_seedance_2p0_mini(builder));
assert!(matches!(draft.aspect_ratio, KinoviAspectRatio::UltraWide21x9));
}
#[test]
fn aspect_ratio_tall() {
let builder = GenerateVideoRequestBuilder { aspect_ratio: Some(RouterAspectRatio::TallNineBySixteen), ..mini_builder() };
let draft = unwrap_draft(build_kinovi_seedance_2p0_mini(builder));
assert!(matches!(draft.aspect_ratio, KinoviAspectRatio::Portrait9x16));
}
#[test]
fn aspect_ratio_square() {
let builder = GenerateVideoRequestBuilder { aspect_ratio: Some(RouterAspectRatio::Square), ..mini_builder() };
let draft = unwrap_draft(build_kinovi_seedance_2p0_mini(builder));
assert!(matches!(draft.aspect_ratio, KinoviAspectRatio::Square1x1));
}
#[test]
fn aspect_ratio_four_by_three() {
let builder = GenerateVideoRequestBuilder { aspect_ratio: Some(RouterAspectRatio::WideFourByThree), ..mini_builder() };
let draft = unwrap_draft(build_kinovi_seedance_2p0_mini(builder));
assert!(matches!(draft.aspect_ratio, KinoviAspectRatio::Standard4x3));
}
#[test]
fn aspect_ratio_three_by_four() {
let builder = GenerateVideoRequestBuilder { aspect_ratio: Some(RouterAspectRatio::TallThreeByFour), ..mini_builder() };
let draft = unwrap_draft(build_kinovi_seedance_2p0_mini(builder));
assert!(matches!(draft.aspect_ratio, KinoviAspectRatio::Portrait3x4));
}
#[test]
fn aspect_ratio_defaults_to_landscape() {
let builder = GenerateVideoRequestBuilder { aspect_ratio: None, ..mini_builder() };
let draft = unwrap_draft(build_kinovi_seedance_2p0_mini(builder));
assert!(matches!(draft.aspect_ratio, KinoviAspectRatio::Landscape16x9));
}
}
mod resolution_conversions {
use super::*;
#[test]
fn resolution_480p() {
let builder = GenerateVideoRequestBuilder { resolution: Some(RouterResolution::FourEightyP), ..mini_builder() };
let draft = unwrap_draft(build_kinovi_seedance_2p0_mini(builder));
assert!(matches!(draft.resolution, Some(KinoviOutputResolution::FourEightyP)));
}
#[test]
fn resolution_720p() {
let builder = GenerateVideoRequestBuilder { resolution: Some(RouterResolution::SevenTwentyP), ..mini_builder() };
let draft = unwrap_draft(build_kinovi_seedance_2p0_mini(builder));
assert!(matches!(draft.resolution, Some(KinoviOutputResolution::SevenTwentyP)));
}
#[test]
fn resolution_1080p_downgrades_to_720p() {
let builder = GenerateVideoRequestBuilder {
resolution: Some(RouterResolution::TenEightyP),
request_mismatch_mitigation_strategy: RequestMismatchMitigationStrategy::PayLessDowngrade,
..mini_builder()
};
let draft = unwrap_draft(build_kinovi_seedance_2p0_mini(builder));
assert!(matches!(draft.resolution, Some(KinoviOutputResolution::SevenTwentyP)));
}
#[test]
fn resolution_1080p_error_out() {
let builder = GenerateVideoRequestBuilder {
resolution: Some(RouterResolution::TenEightyP),
request_mismatch_mitigation_strategy: RequestMismatchMitigationStrategy::ErrorOut,
..mini_builder()
};
assert!(build_kinovi_seedance_2p0_mini(builder).is_err());
}
#[test]
fn resolution_none() {
let builder = GenerateVideoRequestBuilder { resolution: None, ..mini_builder() };
let draft = unwrap_draft(build_kinovi_seedance_2p0_mini(builder));
assert!(draft.resolution.is_none());
}
}
mod unhandled_request_state {
use super::*;
#[test]
fn media_refs_placed_in_unhandled() {
let builder = GenerateVideoRequestBuilder {
start_frame: Some(ImageRef::Url("https://example.com/start.jpg".to_string())),
end_frame: Some(ImageRef::Url("https://example.com/end.jpg".to_string())),
reference_images: Some(ImageListRef::Urls(vec!["https://example.com/ref.jpg".to_string()])),
reference_videos: Some(VideoListRef::Urls(vec!["https://example.com/vid.mp4".to_string()])),
reference_audio: Some(AudioListRef::Urls(vec!["https://example.com/audio.mp3".to_string()])),
reference_character_tokens: Some(CharacterListRef::CharacterTokens(vec![
CharacterToken::new("char_abc".to_string()),
])),
..mini_builder()
};
let draft = unwrap_draft(build_kinovi_seedance_2p0_mini(builder));
let remaining = draft.unhandled_request_state.unwrap();
assert!(remaining.start_frame.is_some());
assert!(remaining.end_frame.is_some());
assert!(remaining.reference_images.is_some());
assert!(remaining.reference_videos.is_some());
assert!(remaining.reference_audio.is_some());
assert!(remaining.reference_character_tokens.is_some());
}
#[test]
fn start_frame_media_token_placed_in_unhandled() {
let builder = GenerateVideoRequestBuilder {
start_frame: Some(ImageRef::MediaFileToken(MediaFileToken::new("mf_test123".to_string()))),
..mini_builder()
};
let draft = unwrap_draft(build_kinovi_seedance_2p0_mini(builder));
let remaining = draft.unhandled_request_state.unwrap();
assert!(matches!(remaining.start_frame, Some(ImageRef::MediaFileToken(t)) if t.as_str() == "mf_test123"));
}
#[test]
fn empty_refs_are_none_in_unhandled() {
let draft = unwrap_draft(build_kinovi_seedance_2p0_mini(mini_builder()));
let remaining = draft.unhandled_request_state.unwrap();
assert!(remaining.start_frame.is_none());
assert!(remaining.end_frame.is_none());
assert!(remaining.reference_images.is_none());
assert!(remaining.reference_videos.is_none());
assert!(remaining.reference_audio.is_none());
assert!(remaining.reference_character_tokens.is_none());
}
}
// ── Helpers ──
fn mini_builder() -> GenerateVideoRequestBuilder {
GenerateVideoRequestBuilder {
model: RouterVideoModel::Seedance2p0Mini,
provider: RouterProvider::Seedance2Pro,
prompt: Some("a cat dancing".to_string()),
duration_seconds: Some(5),
video_batch_count: Some(1),
..Default::default()
}
}
fn unwrap_draft(result: Result<VideoGenerationDraftOrRequest, ArtcraftRouterError>) -> KinoviSeedance2p0MiniDraftState {
match result.expect("build should succeed") {
VideoGenerationDraftOrRequest::Draft(
VideoGenerationDraftRequest::KinoviSeedance2p0Mini(draft)
) => draft,
_ => panic!("expected KinoviSeedance2p0Mini draft"),
}
}
}
@@ -0,0 +1,378 @@
use seedance2pro_client::generate::video::generate_seedance_2p0_mini::{
GenerateSeedance2p0MiniRequest, KinoviSeedance2p0MiniBatchCount,
KinoviSeedance2p0MiniOutputResolution,
};
use crate::generate::generate_video::video_generation_cost_estimate::VideoGenerationCostEstimate;
use crate::generate::generate_video::providers::kinovi::seedance_2p0_mini::draft::KinoviSeedance2p0MiniDraftState;
use crate::generate::generate_video::providers::kinovi::seedance_2p0_mini::request::KinoviSeedance2p0MiniRequestState;
pub struct KinoviSeedance2p0MiniCostState {
pub resolution: Option<KinoviSeedance2p0MiniOutputResolution>,
pub duration_seconds: u8,
pub batch_count: Option<KinoviSeedance2p0MiniBatchCount>,
pub has_video_reference: bool,
}
impl KinoviSeedance2p0MiniCostState {
pub fn from_request(request: &KinoviSeedance2p0MiniRequestState) -> Self {
Self {
resolution: request.request.output_resolution,
duration_seconds: request.request.duration_seconds,
batch_count: request.request.batch_count,
has_video_reference: request.request.reference_video_urls
.as_ref()
.is_some_and(|urls| !urls.is_empty()),
}
}
pub fn from_draft(draft: &KinoviSeedance2p0MiniDraftState) -> Self {
let has_video_reference = draft.unhandled_request_state
.as_ref()
.and_then(|rem| rem.reference_videos.as_ref())
.is_some();
Self {
resolution: draft.resolution,
duration_seconds: draft.duration_seconds,
batch_count: Some(draft.batch_count),
has_video_reference,
}
}
pub fn estimate_cost(&self) -> VideoGenerationCostEstimate {
let pricing_request = GenerateSeedance2p0MiniRequest {
output_resolution: self.resolution,
duration_seconds: self.duration_seconds,
batch_count: self.batch_count,
// PRESENCE of reference videos changes the price (per-second
// surcharge); the URL contents don't.
reference_video_urls: if self.has_video_reference {
Some(vec!["pricing-placeholder".to_string()])
} else {
None
},
// No impact on price
prompt: String::new(),
aspect_ratio: None,
start_frame_url: None,
end_frame_url: None,
reference_image_urls: None,
reference_audio_urls: None,
character_ids: None,
use_face_blur_hack: None,
bitrate: None,
};
let costs = pricing_request.calculate_costs();
// Mini credits can be fractional (e.g. 480p odd durations land on 37.5).
// The router's credit field is an integer, so round to the nearest credit;
// the USD cents (the authoritative charge) are already rounded up.
let cost_in_credits = costs.total_cost.kinovi_credits.round() as u64;
let cost_in_usd_cents = costs.total_cost.usd_cents_rounded_up;
VideoGenerationCostEstimate {
cost_in_credits: Some(cost_in_credits),
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,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::api::router_resolution::RouterResolution;
use seedance2pro_client::generate::video::generate_seedance_2p0_mini::{
KinoviSeedance2p0MiniOutputResolution as KinoviOutputResolution,
KinoviSeedance2p0MiniBatchCount as KinoviBatchCount,
};
use crate::api::router_video_model::RouterVideoModel;
use crate::api::router_provider::RouterProvider;
use crate::api::video_list_ref::VideoListRef;
use crate::generate::generate_video::generate_video_request_builder::GenerateVideoRequestBuilder;
use crate::generate::generate_video::video_generation_draft::VideoGenerationDraftRequest;
use crate::generate::generate_video::video_generation_draft_or_request::VideoGenerationDraftOrRequest;
// ── USD cents: every combination (480p/720p × with/without video ref) ──
mod pricing_480p {
use super::*;
#[test]
fn without_video_reference() {
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 4, KinoviBatchCount::One, false), 13);
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 5, KinoviBatchCount::One, false), 16);
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 10, KinoviBatchCount::One, false), 31);
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 15, KinoviBatchCount::One, false), 47);
}
#[test]
fn with_video_reference() {
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 4, KinoviBatchCount::One, true), 16);
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 5, KinoviBatchCount::One, true), 20);
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 10, KinoviBatchCount::One, true), 40);
assert_eq!(usd_cents(KinoviOutputResolution::FourEightyP, 15, KinoviBatchCount::One, true), 59);
}
}
mod pricing_720p {
use super::*;
#[test]
fn without_video_reference() {
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 4, KinoviBatchCount::One, false), 33);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::One, false), 42);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 10, KinoviBatchCount::One, false), 83);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 15, KinoviBatchCount::One, false), 124);
}
#[test]
fn with_video_reference() {
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 4, KinoviBatchCount::One, true), 40);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::One, true), 50);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 10, KinoviBatchCount::One, true), 99);
assert_eq!(usd_cents(KinoviOutputResolution::SevenTwentyP, 15, KinoviBatchCount::One, true), 149);
}
}
// ── Credits (mini bills fractional credits, rounded for the integer field) ──
mod credits_tests {
use super::*;
#[test]
fn credits_480p() {
// 7.5 credits/s; odd durations are fractional (37.5 → 38, 112.5 → 113).
assert_eq!(credits(KinoviOutputResolution::FourEightyP, 4, KinoviBatchCount::One, false), 30);
assert_eq!(credits(KinoviOutputResolution::FourEightyP, 5, KinoviBatchCount::One, false), 38);
assert_eq!(credits(KinoviOutputResolution::FourEightyP, 10, KinoviBatchCount::One, false), 75);
assert_eq!(credits(KinoviOutputResolution::FourEightyP, 15, KinoviBatchCount::One, false), 113);
}
#[test]
fn credits_720p() {
assert_eq!(credits(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::One, false), 100);
assert_eq!(credits(KinoviOutputResolution::SevenTwentyP, 15, KinoviBatchCount::One, false), 300);
}
}
// ── Relative pricing ──
mod relative_pricing_tests {
use super::*;
#[test]
fn cost_480p_cheaper_than_720p() {
let c480 = usd_cents(KinoviOutputResolution::FourEightyP, 5, KinoviBatchCount::One, false);
let c720 = usd_cents(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::One, false);
assert!(c480 < c720, "480p ({c480}) should be cheaper than 720p ({c720})");
}
#[test]
fn video_reference_costs_more() {
for res in [KinoviOutputResolution::FourEightyP, KinoviOutputResolution::SevenTwentyP] {
for dur in [4u8, 5, 10, 15] {
let without = usd_cents(res, dur, KinoviBatchCount::One, false);
let with = usd_cents(res, dur, KinoviBatchCount::One, true);
assert!(with > without, "video ref should cost more at {res:?} {dur}s");
}
}
}
#[test]
fn cost_scales_with_duration_and_batch() {
let c4 = usd_cents(KinoviOutputResolution::SevenTwentyP, 4, KinoviBatchCount::One, false);
let c15 = usd_cents(KinoviOutputResolution::SevenTwentyP, 15, KinoviBatchCount::One, false);
assert!(c4 < c15);
let b1 = usd_cents(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::One, false);
let b4 = usd_cents(KinoviOutputResolution::SevenTwentyP, 5, KinoviBatchCount::Four, false);
assert!(b1 < b4);
}
}
// ── from_request() ──
mod from_request_tests {
use super::*;
#[test]
fn from_request_720p() {
let req = make_request_state(Some(KinoviOutputResolution::SevenTwentyP), 5, KinoviBatchCount::One, false);
let cost = KinoviSeedance2p0MiniCostState::from_request(&req);
assert!(matches!(cost.resolution, Some(KinoviOutputResolution::SevenTwentyP)));
assert_eq!(cost.duration_seconds, 5);
assert!(!cost.has_video_reference);
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(42));
}
#[test]
fn from_request_480p_with_video_reference() {
let req = make_request_state(Some(KinoviOutputResolution::FourEightyP), 5, KinoviBatchCount::One, true);
let cost = KinoviSeedance2p0MiniCostState::from_request(&req);
assert!(cost.has_video_reference);
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(20));
}
#[test]
fn from_request_none_defaults_to_720p() {
let req = make_request_state(None, 5, KinoviBatchCount::One, false);
let cost = KinoviSeedance2p0MiniCostState::from_request(&req);
assert!(cost.resolution.is_none());
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(42));
}
}
// ── from_draft() ──
mod from_draft_tests {
use super::*;
#[test]
fn from_draft_480p() {
let draft = make_draft(5, 1, Some(RouterResolution::FourEightyP), false);
let cost = KinoviSeedance2p0MiniCostState::from_draft(&draft);
assert!(matches!(cost.resolution, Some(KinoviOutputResolution::FourEightyP)));
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(16));
}
#[test]
fn from_draft_with_video_reference() {
let draft = make_draft(5, 1, Some(RouterResolution::SevenTwentyP), true);
let cost = KinoviSeedance2p0MiniCostState::from_draft(&draft);
assert!(cost.has_video_reference);
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(50));
}
#[test]
fn from_draft_batch_8() {
// Mini supports up to batch 8: 720p 5s × 8 = 800 credits → 80000/243 → 330¢.
let draft = make_draft(5, 8, Some(RouterResolution::SevenTwentyP), false);
let cost = KinoviSeedance2p0MiniCostState::from_draft(&draft);
assert!(matches!(cost.batch_count, Some(KinoviBatchCount::Eight)));
assert_eq!(cost.estimate_cost().cost_in_usd_cents, Some(330));
}
}
// ── Cross-check: from_draft matches from_request ──
mod cross_check_tests {
use super::*;
#[test]
fn draft_and_request_produce_same_cost() {
let draft = make_draft(10, 2, Some(RouterResolution::FourEightyP), true);
let req = make_request_state(Some(KinoviOutputResolution::FourEightyP), 10, KinoviBatchCount::Two, true);
let draft_cost = KinoviSeedance2p0MiniCostState::from_draft(&draft).estimate_cost();
let req_cost = KinoviSeedance2p0MiniCostState::from_request(&req).estimate_cost();
assert_eq!(draft_cost.cost_in_usd_cents, req_cost.cost_in_usd_cents);
assert_eq!(draft_cost.cost_in_credits, req_cost.cost_in_credits);
}
}
// ── Helpers ──
fn usd_cents(
resolution: KinoviOutputResolution,
duration_seconds: u8,
batch_count: KinoviBatchCount,
has_video_reference: bool,
) -> u64 {
KinoviSeedance2p0MiniCostState {
resolution: Some(resolution),
duration_seconds,
batch_count: Some(batch_count),
has_video_reference,
}
.estimate_cost()
.cost_in_usd_cents
.unwrap()
}
fn credits(
resolution: KinoviOutputResolution,
duration_seconds: u8,
batch_count: KinoviBatchCount,
has_video_reference: bool,
) -> u64 {
KinoviSeedance2p0MiniCostState {
resolution: Some(resolution),
duration_seconds,
batch_count: Some(batch_count),
has_video_reference,
}
.estimate_cost()
.cost_in_credits
.unwrap()
}
/// Build a draft via the builder to test from_draft().
fn make_draft(
duration_seconds: u16,
video_batch_count: u16,
resolution: Option<RouterResolution>,
with_video_ref: bool,
) -> KinoviSeedance2p0MiniDraftState {
let reference_videos = if with_video_ref {
Some(VideoListRef::Urls(vec!["https://example.com/video.mp4".to_string()]))
} else {
None
};
let builder = GenerateVideoRequestBuilder {
model: RouterVideoModel::Seedance2p0Mini,
provider: RouterProvider::Seedance2Pro,
resolution,
reference_videos,
duration_seconds: Some(duration_seconds),
video_batch_count: Some(video_batch_count),
..Default::default()
};
match builder.build2().expect("build2 should succeed") {
VideoGenerationDraftOrRequest::Draft(
VideoGenerationDraftRequest::KinoviSeedance2p0Mini(draft)
) => draft,
_ => panic!("expected KinoviSeedance2p0Mini draft"),
}
}
/// Build a request state for from_request() tests.
fn make_request_state(
resolution: Option<KinoviOutputResolution>,
duration_seconds: u8,
batch_count: KinoviBatchCount,
with_video_ref: bool,
) -> KinoviSeedance2p0MiniRequestState {
let reference_video_urls = if with_video_ref {
Some(vec!["https://cdn.seedance2-pro.com/video.mp4".to_string()])
} else {
None
};
KinoviSeedance2p0MiniRequestState {
request: GenerateSeedance2p0MiniRequest {
prompt: "test".to_string(),
aspect_ratio: None,
output_resolution: resolution,
duration_seconds,
batch_count: Some(batch_count),
start_frame_url: None,
end_frame_url: None,
reference_image_urls: None,
reference_video_urls,
reference_audio_urls: None,
character_ids: None,
use_face_blur_hack: None,
bitrate: None,
},
}
}
}
@@ -0,0 +1,99 @@
use seedance2pro_client::generate::video::generate_seedance_2p0_mini::{
GenerateSeedance2p0MiniRequest, KinoviSeedance2p0MiniAspectRatio, KinoviSeedance2p0MiniBitrate,
KinoviSeedance2p0MiniBatchCount, KinoviSeedance2p0MiniOutputResolution,
};
use crate::api::audio_list_ref::AudioListRef;
use crate::api::character_list_ref::CharacterListRef;
use crate::api::image_list_ref::ImageListRef;
use crate::api::image_ref::ImageRef;
use crate::api::video_list_ref::VideoListRef;
use crate::errors::artcraft_router_error::ArtcraftRouterError;
use crate::generate::generate_video::providers::kinovi::resolve::{
audio_list_ref_into_urls_or_tokens, image_list_ref_into_urls_or_tokens,
resolve_and_upload_list, resolve_and_upload_single, resolve_character_tokens,
video_list_ref_into_urls_or_tokens,
};
use crate::generate::generate_video::providers::kinovi::seedance_2p0_mini::request::KinoviSeedance2p0MiniRequestState;
use crate::generate::generate_video::video_generation_draft_context::VideoGenerationDraftContext;
#[derive(Debug, Clone)]
pub struct KinoviSeedance2p0MiniDraftState {
pub prompt: String,
pub aspect_ratio: KinoviSeedance2p0MiniAspectRatio,
pub resolution: Option<KinoviSeedance2p0MiniOutputResolution>,
pub duration_seconds: u8,
pub batch_count: KinoviSeedance2p0MiniBatchCount,
pub bitrate: Option<KinoviSeedance2p0MiniBitrate>,
pub unhandled_request_state: Option<KinoviSeedance2p0MiniRemainingItems>,
}
#[derive(Debug, Clone)]
pub struct KinoviSeedance2p0MiniRemainingItems {
pub start_frame: Option<ImageRef>,
pub end_frame: Option<ImageRef>,
pub reference_images: Option<ImageListRef>,
pub reference_videos: Option<VideoListRef>,
pub reference_audio: Option<AudioListRef>,
pub reference_character_tokens: Option<CharacterListRef>,
}
impl KinoviSeedance2p0MiniDraftState {
pub async fn to_request(
&mut self,
draft_context: &VideoGenerationDraftContext<'_>,
) -> Result<KinoviSeedance2p0MiniRequestState, ArtcraftRouterError> {
let client = draft_context.get_seedance2pro_client_ref()?;
let session = &client.session;
let mut start_frame_url = None;
let mut end_frame_url = None;
let mut reference_image_urls = None;
let mut reference_video_urls = None;
let mut reference_audio_urls = None;
let mut character_ids = None;
if let Some(remaining) = self.unhandled_request_state.take() {
let map = draft_context.media_file_to_artcraft_url_map;
start_frame_url = resolve_and_upload_single(session, remaining.start_frame, map).await?;
end_frame_url = resolve_and_upload_single(session, remaining.end_frame, map).await?;
reference_image_urls = resolve_and_upload_list(
session, remaining.reference_images.map(image_list_ref_into_urls_or_tokens), map,
).await?;
reference_video_urls = resolve_and_upload_list(
session, remaining.reference_videos.map(video_list_ref_into_urls_or_tokens), map,
).await?;
reference_audio_urls = resolve_and_upload_list(
session, remaining.reference_audio.map(audio_list_ref_into_urls_or_tokens), map,
).await?;
character_ids = resolve_character_tokens(
remaining.reference_character_tokens.as_ref(),
draft_context,
)?;
}
let request = GenerateSeedance2p0MiniRequest {
prompt: self.prompt.clone(),
aspect_ratio: Some(self.aspect_ratio),
output_resolution: self.resolution,
duration_seconds: self.duration_seconds,
batch_count: Some(self.batch_count),
start_frame_url,
end_frame_url,
reference_image_urls,
reference_video_urls,
reference_audio_urls,
character_ids,
use_face_blur_hack: None,
bitrate: self.bitrate,
};
Ok(KinoviSeedance2p0MiniRequestState { request })
}
}
@@ -0,0 +1,4 @@
pub mod build;
pub mod draft;
pub mod request;
pub mod cost;
@@ -0,0 +1,37 @@
use seedance2pro_client::generate::video::generate_seedance_2p0_mini::{
generate_seedance_2p0_mini, GenerateSeedance2p0MiniArgs, GenerateSeedance2p0MiniRequest,
};
use crate::client::router_seedance2pro_client::RouterSeedance2ProClient;
use crate::errors::artcraft_router_error::ArtcraftRouterError;
use crate::errors::provider_error::ProviderError;
use crate::generate::generate_video::generate_video_response::{GenerateVideoResponse, Seedance2proVideoResponsePayload};
#[derive(Debug, Clone)]
pub struct KinoviSeedance2p0MiniRequestState {
/// Final materialized request; ready to fire.
pub request: GenerateSeedance2p0MiniRequest,
}
impl KinoviSeedance2p0MiniRequestState {
pub async fn send(&self, client: &RouterSeedance2ProClient) -> Result<GenerateVideoResponse, ArtcraftRouterError> {
let session = &client.session;
let args = GenerateSeedance2p0MiniArgs {
session,
host_override: None,
request: self.request.clone(),
};
let response = generate_seedance_2p0_mini(args)
.await
.map_err(|err| ArtcraftRouterError::Provider(ProviderError::Seedance2Pro(err)))?;
Ok(GenerateVideoResponse::Seedance2Pro(Seedance2proVideoResponsePayload {
order_id: response.order_id,
task_id: response.task_id,
maybe_order_ids: response.order_ids,
maybe_task_ids: response.task_ids,
}))
}
}
@@ -7,6 +7,8 @@ use crate::generate::generate_video::providers::kinovi::seedance_2p0::cost::Kino
use crate::generate::generate_video::providers::kinovi::seedance_2p0::draft::KinoviSeedance2p0DraftState;
use crate::generate::generate_video::providers::kinovi::seedance_2p0_fast::cost::KinoviSeedance2p0FastCostState;
use crate::generate::generate_video::providers::kinovi::seedance_2p0_fast::draft::KinoviSeedance2p0FastDraftState;
use crate::generate::generate_video::providers::kinovi::seedance_2p0_mini::cost::KinoviSeedance2p0MiniCostState;
use crate::generate::generate_video::providers::kinovi::seedance_2p0_mini::draft::KinoviSeedance2p0MiniDraftState;
use crate::generate::generate_video::video_generation_draft_context::VideoGenerationDraftContext;
use crate::generate::generate_video::video_generation_request::VideoGenerationRequest;
@@ -18,6 +20,7 @@ pub enum VideoGenerationDraftRequest {
KinoviHappyHorse1p0(KinoviHappyHorse1p0DraftState),
KinoviSeedance2p0(KinoviSeedance2p0DraftState),
KinoviSeedance2p0Fast(KinoviSeedance2p0FastDraftState),
KinoviSeedance2p0Mini(KinoviSeedance2p0MiniDraftState),
}
impl VideoGenerationDraftRequest {
@@ -27,6 +30,7 @@ impl VideoGenerationDraftRequest {
Self::KinoviHappyHorse1p0(_) => RouterProvider::Seedance2Pro,
Self::KinoviSeedance2p0(_) => RouterProvider::Seedance2Pro,
Self::KinoviSeedance2p0Fast(_) => RouterProvider::Seedance2Pro,
Self::KinoviSeedance2p0Mini(_) => RouterProvider::Seedance2Pro,
}
}
@@ -36,6 +40,7 @@ impl VideoGenerationDraftRequest {
VideoGenerationDraftRequest::KinoviHappyHorse1p0(draft) => Ok(KinoviHappyHorse1p0CostState::from_draft(draft).estimate_cost()),
VideoGenerationDraftRequest::KinoviSeedance2p0(draft) => Ok(KinoviSeedance2p0CostState::from_draft(draft).estimate_cost()),
VideoGenerationDraftRequest::KinoviSeedance2p0Fast(draft) => Ok(KinoviSeedance2p0FastCostState::from_draft(draft).estimate_cost()),
VideoGenerationDraftRequest::KinoviSeedance2p0Mini(draft) => Ok(KinoviSeedance2p0MiniCostState::from_draft(draft).estimate_cost()),
}
}
@@ -55,6 +60,10 @@ impl VideoGenerationDraftRequest {
let result = draft.to_request(&draft_context).await?;
Ok(VideoGenerationRequest::KinoviSeedance2p0Fast(result))
},
VideoGenerationDraftRequest::KinoviSeedance2p0Mini(mut draft) => {
let result = draft.to_request(&draft_context).await?;
Ok(VideoGenerationRequest::KinoviSeedance2p0Mini(result))
},
}
}
}
@@ -47,6 +47,12 @@ use crate::generate::generate_video::providers::artcraft::seedance_2p0_bpu::cost
use crate::generate::generate_video::providers::artcraft::seedance_2p0_bpu::request::ArtcraftSeedance2p0BytePlusUltraRequestState;
use crate::generate::generate_video::providers::artcraft::seedance_2p0_bpu_fast::cost::ArtcraftSeedance2p0BytePlusUltraFastCostState;
use crate::generate::generate_video::providers::artcraft::seedance_2p0_bpu_fast::request::ArtcraftSeedance2p0BytePlusUltraFastRequestState;
use crate::generate::generate_video::providers::artcraft::seedance_2p0_mini::cost::ArtcraftSeedance2p0MiniCostState;
use crate::generate::generate_video::providers::artcraft::seedance_2p0_mini::request::ArtcraftSeedance2p0MiniRequestState;
use crate::generate::generate_video::providers::artcraft::seedance_2p0_bp_mini::cost::ArtcraftSeedance2p0BytePlusMiniCostState;
use crate::generate::generate_video::providers::artcraft::seedance_2p0_bp_mini::request::ArtcraftSeedance2p0BytePlusMiniRequestState;
use crate::generate::generate_video::providers::artcraft::seedance_2p0_bpu_mini::cost::ArtcraftSeedance2p0BytePlusUltraMiniCostState;
use crate::generate::generate_video::providers::artcraft::seedance_2p0_bpu_mini::request::ArtcraftSeedance2p0BytePlusUltraMiniRequestState;
use crate::generate::generate_video::providers::artcraft::sora_2::cost::ArtcraftSora2CostState;
use crate::generate::generate_video::providers::artcraft::sora_2::request::ArtcraftSora2RequestState;
use crate::generate::generate_video::providers::artcraft::sora_2_pro::cost::ArtcraftSora2ProCostState;
@@ -107,6 +113,8 @@ use crate::generate::generate_video::providers::kinovi::seedance_2p0::cost::Kino
use crate::generate::generate_video::providers::kinovi::seedance_2p0::request::KinoviSeedance2p0RequestState;
use crate::generate::generate_video::providers::kinovi::seedance_2p0_fast::cost::KinoviSeedance2p0FastCostState;
use crate::generate::generate_video::providers::kinovi::seedance_2p0_fast::request::KinoviSeedance2p0FastRequestState;
use crate::generate::generate_video::providers::kinovi::seedance_2p0_mini::cost::KinoviSeedance2p0MiniCostState;
use crate::generate::generate_video::providers::kinovi::seedance_2p0_mini::request::KinoviSeedance2p0MiniRequestState;
#[derive(Clone, Debug)]
pub enum VideoGenerationRequest {
@@ -132,6 +140,9 @@ pub enum VideoGenerationRequest {
ArtcraftSeedance2p0BytePlusFast(ArtcraftSeedance2p0BytePlusFastRequestState),
ArtcraftSeedance2p0BytePlusUltra(ArtcraftSeedance2p0BytePlusUltraRequestState),
ArtcraftSeedance2p0BytePlusUltraFast(ArtcraftSeedance2p0BytePlusUltraFastRequestState),
ArtcraftSeedance2p0Mini(ArtcraftSeedance2p0MiniRequestState),
ArtcraftSeedance2p0BytePlusMini(ArtcraftSeedance2p0BytePlusMiniRequestState),
ArtcraftSeedance2p0BytePlusUltraMini(ArtcraftSeedance2p0BytePlusUltraMiniRequestState),
ArtcraftSora2(ArtcraftSora2RequestState),
ArtcraftSora2Pro(ArtcraftSora2ProRequestState),
ArtcraftVeo2(ArtcraftVeo2RequestState),
@@ -162,6 +173,7 @@ pub enum VideoGenerationRequest {
KinoviHappyHorse1p0(KinoviHappyHorse1p0RequestState),
KinoviSeedance2p0(KinoviSeedance2p0RequestState),
KinoviSeedance2p0Fast(KinoviSeedance2p0FastRequestState),
KinoviSeedance2p0Mini(KinoviSeedance2p0MiniRequestState),
}
impl VideoGenerationRequest {
@@ -190,6 +202,9 @@ impl VideoGenerationRequest {
Self::ArtcraftSeedance2p0BytePlusFast(_) => RouterProvider::Artcraft,
Self::ArtcraftSeedance2p0BytePlusUltra(_) => RouterProvider::Artcraft,
Self::ArtcraftSeedance2p0BytePlusUltraFast(_) => RouterProvider::Artcraft,
Self::ArtcraftSeedance2p0Mini(_) => RouterProvider::Artcraft,
Self::ArtcraftSeedance2p0BytePlusMini(_) => RouterProvider::Artcraft,
Self::ArtcraftSeedance2p0BytePlusUltraMini(_) => RouterProvider::Artcraft,
Self::ArtcraftSora2(_) => RouterProvider::Artcraft,
Self::ArtcraftSora2Pro(_) => RouterProvider::Artcraft,
Self::ArtcraftVeo2(_) => RouterProvider::Artcraft,
@@ -220,6 +235,7 @@ impl VideoGenerationRequest {
Self::KinoviHappyHorse1p0(_) => RouterProvider::Seedance2Pro,
Self::KinoviSeedance2p0(_) => RouterProvider::Seedance2Pro,
Self::KinoviSeedance2p0Fast(_) => RouterProvider::Seedance2Pro,
Self::KinoviSeedance2p0Mini(_) => RouterProvider::Seedance2Pro,
}
}
@@ -248,6 +264,9 @@ impl VideoGenerationRequest {
VideoGenerationRequest::ArtcraftSeedance2p0BytePlusFast(request) => Ok(ArtcraftSeedance2p0BytePlusFastCostState::from_request(request).estimate_cost()),
VideoGenerationRequest::ArtcraftSeedance2p0BytePlusUltra(request) => Ok(ArtcraftSeedance2p0BytePlusUltraCostState::from_request(request).estimate_cost()),
VideoGenerationRequest::ArtcraftSeedance2p0BytePlusUltraFast(request) => Ok(ArtcraftSeedance2p0BytePlusUltraFastCostState::from_request(request).estimate_cost()),
VideoGenerationRequest::ArtcraftSeedance2p0Mini(request) => Ok(ArtcraftSeedance2p0MiniCostState::from_request(request).estimate_cost()),
VideoGenerationRequest::ArtcraftSeedance2p0BytePlusMini(request) => Ok(ArtcraftSeedance2p0BytePlusMiniCostState::from_request(request).estimate_cost()),
VideoGenerationRequest::ArtcraftSeedance2p0BytePlusUltraMini(request) => Ok(ArtcraftSeedance2p0BytePlusUltraMiniCostState::from_request(request).estimate_cost()),
VideoGenerationRequest::ArtcraftSora2(request) => Ok(ArtcraftSora2CostState::from_request(request).estimate_cost()),
VideoGenerationRequest::ArtcraftSora2Pro(request) => Ok(ArtcraftSora2ProCostState::from_request(request).estimate_cost()),
VideoGenerationRequest::ArtcraftVeo2(request) => Ok(ArtcraftVeo2CostState::from_request(request).estimate_cost()),
@@ -278,6 +297,7 @@ impl VideoGenerationRequest {
VideoGenerationRequest::KinoviHappyHorse1p0(request) => Ok(KinoviHappyHorse1p0CostState::from_request(request).estimate_cost()),
VideoGenerationRequest::KinoviSeedance2p0(request) => Ok(KinoviSeedance2p0CostState::from_request(request).estimate_cost()),
VideoGenerationRequest::KinoviSeedance2p0Fast(request) => Ok(KinoviSeedance2p0FastCostState::from_request(request).estimate_cost()),
VideoGenerationRequest::KinoviSeedance2p0Mini(request) => Ok(KinoviSeedance2p0MiniCostState::from_request(request).estimate_cost()),
}
}
@@ -373,6 +393,18 @@ impl VideoGenerationRequest {
let client_ref = client.get_artcraft_client_ref()?;
request.send(client_ref).await
},
VideoGenerationRequest::ArtcraftSeedance2p0Mini(request) => {
let client_ref = client.get_artcraft_client_ref()?;
request.send(client_ref).await
},
VideoGenerationRequest::ArtcraftSeedance2p0BytePlusMini(request) => {
let client_ref = client.get_artcraft_client_ref()?;
request.send(client_ref).await
},
VideoGenerationRequest::ArtcraftSeedance2p0BytePlusUltraMini(request) => {
let client_ref = client.get_artcraft_client_ref()?;
request.send(client_ref).await
},
VideoGenerationRequest::ArtcraftSora2(request) => {
let client_ref = client.get_artcraft_client_ref()?;
request.send(client_ref).await
@@ -493,6 +525,10 @@ impl VideoGenerationRequest {
let client_ref = client.get_seedance2pro_client_ref()?;
request.send(client_ref).await
},
VideoGenerationRequest::KinoviSeedance2p0Mini(request) => {
let client_ref = client.get_seedance2pro_client_ref()?;
request.send(client_ref).await
},
}
}
}
@@ -134,7 +134,7 @@ mod tests {
},
}).await;
let err = result.unwrap_err();
assert!(matches!(err, GrokError::ApiSpecific(GrokSpecificApiError::NotFound)),
assert!(matches!(err, GrokError::ApiSpecific(GrokSpecificApiError::NotFound { .. })),
"expected NotFound, got: {:?}", err);
Ok(())
}
@@ -103,12 +103,12 @@ pub async fn upload_file(args: UploadFileArgs<'_>) -> Result<UploadFileSuccess,
let req = args.request;
if req.file_bytes.is_empty() {
return Err(crate::error::grok_specific_api_error::GrokSpecificApiError::BadRequest(
return Err(GrokClientError::InvalidRequest(
"upload_file: file_bytes is empty".to_string(),
).into());
}
if req.file_bytes.len() as u64 > MAX_FILE_BYTES {
return Err(crate::error::grok_specific_api_error::GrokSpecificApiError::BadRequest(
return Err(GrokClientError::InvalidRequest(
format!("upload_file: file_bytes is {} bytes, exceeds xAI's 50 MB limit", req.file_bytes.len()),
).into());
}
@@ -192,7 +192,7 @@ mod tests {
},
}).await;
let err = result.unwrap_err();
assert!(matches!(err, GrokError::ApiSpecific(GrokSpecificApiError::BadRequest(_))));
assert!(matches!(err, GrokError::Client(GrokClientError::InvalidRequest(_))));
}
#[tokio::test]
@@ -210,7 +210,7 @@ mod tests {
},
}).await;
let err = result.unwrap_err();
assert!(matches!(err, GrokError::ApiSpecific(GrokSpecificApiError::BadRequest(_))));
assert!(matches!(err, GrokError::Client(GrokClientError::InvalidRequest(_))));
}
// ── Public Request shape — must not leak api_key OR file_bytes ──
@@ -105,7 +105,7 @@ pub async fn image_edit(args: ImageEditArgs<'_>) -> Result<ImageEditSuccess, Gro
let req = args.request;
if req.source_images.is_empty() {
return Err(GrokSpecificApiError::BadRequest(
return Err(GrokClientError::InvalidRequest(
"image_edit requires at least one source image".to_string(),
).into());
}
@@ -311,7 +311,7 @@ mod tests {
},
}).await;
let err = result.unwrap_err();
assert!(matches!(err, GrokError::ApiSpecific(GrokSpecificApiError::BadRequest(_))));
assert!(matches!(err, GrokError::Client(GrokClientError::InvalidRequest(_))));
}
#[test]
@@ -10,15 +10,15 @@ use crate::api::types::video_types::video_resolution::VideoResolution;
// Output: 480p $0.05/sec, 720p $0.07/sec
// Input: $0.01/sec (source video) + $0.002/img (source images)
//
// grok-imagine-video-1.5-preview (v1.5)
// Output: 480p $0.08/sec, 720p $0.14/sec
// grok-imagine-video-1.5 (v1.5)
// Output: 480p $0.08/sec, 720p $0.14/sec, 1080p $0.25/sec
// Input: $0.01/img (source images)
//
// In mills (1¢ = 10 mills):
//
// v1 output: 480p 50 mills/sec, 720p 70 mills/sec
// v1 input: 10 mills/sec (video), 2 mills/img
// v1.5 output: 480p 80 mills/sec, 720p 140 mills/sec
// v1.5 output: 480p 80 mills/sec, 720p 140 mills/sec, 1080p 250 mills/sec
// v1.5 input: 10 mills/img
//
// video_generation has NO input video — only optional input images. xAI
@@ -78,17 +78,20 @@ fn output_mills_per_second_for_tier(
tier: VideoModelPricingTier,
) -> UsdMills {
match (tier, resolution) {
(VideoModelPricingTier::V1, VideoResolution::FourEightyP) => 50,
(VideoModelPricingTier::V1, VideoResolution::SevenTwentyP) => 70,
(VideoModelPricingTier::V1p5Preview, VideoResolution::FourEightyP) => 80,
(VideoModelPricingTier::V1p5Preview, VideoResolution::SevenTwentyP) => 140,
(VideoModelPricingTier::V1, VideoResolution::FourEightyP) => 50,
(VideoModelPricingTier::V1, VideoResolution::SevenTwentyP) => 70,
// v1 doesn't produce 1080p output (it downsizes to 720p); price at 720p.
(VideoModelPricingTier::V1, VideoResolution::TenEightyP) => 70,
(VideoModelPricingTier::V1p5, VideoResolution::FourEightyP) => 80,
(VideoModelPricingTier::V1p5, VideoResolution::SevenTwentyP) => 140,
(VideoModelPricingTier::V1p5, VideoResolution::TenEightyP) => 250,
}
}
fn input_mills_per_image(tier: VideoModelPricingTier) -> UsdMills {
match tier {
VideoModelPricingTier::V1 => INPUT_MILLS_PER_IMAGE,
VideoModelPricingTier::V1p5Preview => INPUT_MILLS_PER_IMAGE_V1P5,
VideoModelPricingTier::V1p5 => INPUT_MILLS_PER_IMAGE_V1P5,
}
}
@@ -303,7 +306,7 @@ mod tests {
reference_images: Option<Vec<VideoImageSource>>,
) -> VideoGenerationRequest {
let mut req = make_request(duration, resolution, image, reference_images);
req.model = Some(VideoModel::GrokImagineVideo1p5Preview);
req.model = Some(VideoModel::GrokImagineVideo1p5);
req
}
@@ -323,6 +326,22 @@ mod tests {
assert_eq!(req.calculate_cost_in_cents(), 70);
}
#[test]
fn five_seconds_1080p_text_only() {
// 250 × 5 = 1250 mills = $1.25
let req = make_v1p5_request(Some(5), Some(VideoResolution::TenEightyP), None, None);
assert_eq!(req.calculate_cost_in_mills(), 1250);
assert_eq!(req.calculate_cost_in_cents(), 125);
}
#[test]
fn five_seconds_1080p_one_source_image() {
// 250 × 5 + 10 = 1260 mills = $1.26
let req = make_v1p5_request(Some(5), Some(VideoResolution::TenEightyP), Some(url_source()), None);
assert_eq!(req.calculate_cost_in_mills(), 1260);
assert_eq!(req.calculate_cost_in_cents(), 126);
}
#[test]
fn five_seconds_720p_one_source_image() {
// 140 × 5 + 10 × 1 = 710 mills = 71¢
@@ -348,7 +367,7 @@ mod tests {
// canonical 1.5 variant exactly.
let canonical = {
let mut req = make_v1p5_request(Some(5), Some(VideoResolution::SevenTwentyP), Some(url_source()), None);
req.model = Some(VideoModel::GrokImagineVideo1p5Preview);
req.model = Some(VideoModel::GrokImagineVideo1p5);
req.calculate_cost_in_mills()
};
let via_alias = {
@@ -396,6 +415,12 @@ mod tests {
// 720p with reference images
( 5, VideoResolution::SevenTwentyP, false, 2, 720),
( 5, VideoResolution::SevenTwentyP, false, 3, 730),
// 1080p (250 mills/sec)
( 1, VideoResolution::TenEightyP, false, 0, 250),
( 5, VideoResolution::TenEightyP, false, 0, 1250),
(15, VideoResolution::TenEightyP, false, 0, 3750),
( 5, VideoResolution::TenEightyP, true, 0, 1260),
( 5, VideoResolution::TenEightyP, false, 2, 1270),
];
#[test]

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