Compare commits

...
Author SHA1 Message Date
Brandon Thomas 779bfb16a6 check 2026-03-16 17:13:36 -04:00
Brandon Thomas b29c1cc186 update API types 2026-03-16 17:12:01 -04:00
Brandon Thomas 2c9598a6c8 text to video 2026-03-16 16:59:32 -04:00
Brandon Thomas 4e4b080fdb update API 2026-03-16 16:48:48 -04:00
Brandon Thomas c8af69a7de requests 2026-03-16 16:36:14 -04:00
Brandon Thomas b9bdbcc017 api keys 2026-03-16 16:05:57 -04:00
Brandon Thomas 337ee74de5 Muapi client base 2026-03-16 16:03:18 -04:00
32 changed files with 986 additions and 7 deletions
Generated
+23
View File
@@ -7229,6 +7229,29 @@ dependencies = [
"thiserror 1.0.63",
]
[[package]]
name = "muapi_client"
version = "0.0.1"
dependencies = [
"chrono",
"cloudflare_errors",
"env",
"env_logger 0.11.9",
"errors",
"log",
"rand 0.9.2",
"serde",
"serde_derive",
"serde_json",
"test_data",
"testing",
"tokio",
"url",
"workspace-build-acceleration",
"wreq",
"wreq-util",
]
[[package]]
name = "muda"
version = "0.17.1"
+2
View File
@@ -16,6 +16,7 @@ members = [
"crates/api_clients/midjourney_client",
"crates/api_clients/openai_sora_client",
"crates/api_clients/openart_client",
"crates/api_clients/muapi_client",
"crates/api_clients/seedance2pro",
"crates/api_clients/runwayml_client",
"crates/api_clients/thumbnail_generator",
@@ -240,6 +241,7 @@ memory_store = { path = "crates/lib/caching/memory_store" }
midjourney_client = { path = "crates/api_clients/midjourney_client" }
mimetypes = { path = "crates/lib/files/mimetypes" }
openai_sora_client = { path = "crates/api_clients/openai_sora_client" }
muapi_client = { path = "crates/api_clients/muapi_client" }
seedance2pro = { path = "crates/api_clients/seedance2pro" }
primitives = { path = "crates/lib/data/primitives" }
shared_service_components = { path = "crates/lib/shared_service_components" }
@@ -0,0 +1,33 @@
[package]
name = "muapi_client"
edition = "2024"
version = "0.0.1"
publish = false
[package.metadata.cargo-udeps.ignore]
normal = ["workspace-build-acceleration"]
[lib]
name = "muapi_client"
path = "src/lib.rs"
[dependencies]
workspace-build-acceleration.workspace = true
errors.workspace = true
chrono.workspace = true
cloudflare_errors.workspace = true
log.workspace = true
rand.workspace = true
serde.workspace = true
serde_derive.workspace = true
serde_json.workspace = true
wreq-util.workspace = true
wreq.workspace = true
url.workspace = true
[dev-dependencies]
env.workspace = true
env_logger.workspace = true
test_data = { path = "../../lib/test_data" }
testing = { path = "../../lib/testing" }
tokio = { version = "1", features = ["full"] }
@@ -0,0 +1 @@
pub mod request_id;
@@ -0,0 +1,24 @@
/// ID for a prediction request in the Muapi API.
#[derive(Clone, Debug)]
pub struct RequestId(String);
impl RequestId {
pub fn new(value: String) -> Self {
RequestId(value)
}
pub fn from_str(value: &str) -> Self {
RequestId(value.to_string())
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl std::fmt::Display for RequestId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
@@ -0,0 +1,2 @@
pub mod muapi_api_key;
pub mod muapi_session;
@@ -0,0 +1,20 @@
/// An API key is the credential required to interact with the Muapi API.
#[derive(Clone)]
pub struct MuapiApiKey {
api_key: String,
}
impl MuapiApiKey {
pub fn new(api_key: String) -> Self {
MuapiApiKey { api_key }
}
pub fn as_str(&self) -> &str {
&self.api_key
}
pub fn to_string(&self) -> String {
self.api_key.clone()
}
}
@@ -0,0 +1,19 @@
use crate::creds::muapi_api_key::MuapiApiKey;
/// Holds the full session data needed to make authenticated requests to Muapi.
#[derive(Clone)]
pub struct MuapiSession {
pub api_key: MuapiApiKey,
}
impl MuapiSession {
pub fn new(api_key: MuapiApiKey) -> Self {
MuapiSession { api_key }
}
pub fn from_api_key_string(api_key: String) -> Self {
MuapiSession {
api_key: MuapiApiKey::new(api_key),
}
}
}
@@ -0,0 +1,4 @@
pub mod muapi_client_error;
pub mod muapi_error;
pub mod muapi_generic_api_error;
pub mod muapi_specific_api_error;
@@ -0,0 +1,26 @@
use std::error::Error;
use std::fmt::{Display, Formatter};
#[derive(Debug)]
pub enum MuapiClientError {
/// No API key is present in the session.
NoApiKeyPresent,
/// Error parsing a URL.
UrlParseError(url::ParseError),
/// An error was encountered in building the Wreq client.
WreqClientError(wreq::Error),
}
impl Error for MuapiClientError {}
impl Display for MuapiClientError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::NoApiKeyPresent => write!(f, "No API key present in the session."),
Self::UrlParseError(err) => write!(f, "URL parse error: {}", err),
Self::WreqClientError(err) => write!(f, "Wreq client error (during client creation): {}", err),
}
}
}
@@ -0,0 +1,61 @@
use crate::error::muapi_client_error::MuapiClientError;
use crate::error::muapi_generic_api_error::MuapiGenericApiError;
use crate::error::muapi_specific_api_error::MuapiSpecificApiError;
use cloudflare_errors::cloudflare_error::CloudflareError;
use std::error::Error;
#[derive(Debug)]
pub enum MuapiError {
Client(MuapiClientError),
ApiSpecific(MuapiSpecificApiError),
ApiGeneric(MuapiGenericApiError),
}
impl MuapiError {
pub fn is_having_downtime_issues(&self) -> bool {
match self {
Self::ApiGeneric(MuapiGenericApiError::CloudflareError(CloudflareError::BadGateway502)) => true,
Self::ApiGeneric(MuapiGenericApiError::CloudflareError(CloudflareError::GatewayTimeout504)) => true,
Self::ApiGeneric(MuapiGenericApiError::CloudflareError(CloudflareError::TimeoutOccurred524)) => true,
Self::ApiGeneric(MuapiGenericApiError::UncategorizedBadResponseWithStatusAndBody { status_code, body: _ }) => {
match status_code.as_u16() {
502 => true,
504 => true,
524 => true,
_ => false,
}
},
_ => false,
}
}
}
impl Error for MuapiError {}
impl std::fmt::Display for MuapiError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Client(e) => write!(f, "MuapiClientError: {:?}", e),
Self::ApiSpecific(e) => write!(f, "MuapiSpecificApiError: {:?}", e),
Self::ApiGeneric(e) => write!(f, "MuapiGenericApiError: {:?}", e),
}
}
}
impl From<MuapiClientError> for MuapiError {
fn from(error: MuapiClientError) -> Self {
Self::Client(error)
}
}
impl From<MuapiSpecificApiError> for MuapiError {
fn from(error: MuapiSpecificApiError) -> Self {
Self::ApiSpecific(error)
}
}
impl From<MuapiGenericApiError> for MuapiError {
fn from(error: MuapiGenericApiError) -> Self {
Self::ApiGeneric(error)
}
}
@@ -0,0 +1,41 @@
use cloudflare_errors::cloudflare_error::CloudflareError;
use std::error::Error;
use std::fmt::{Display, Formatter};
use wreq::StatusCode;
#[derive(Debug)]
pub enum MuapiGenericApiError {
/// Specific Cloudflare errors.
CloudflareError(CloudflareError),
/// serde_json::Error, likely from JSON deserialization schema mismatch.
/// Includes the original body.
SerdeResponseParseErrorWithBody(serde_json::Error, String),
/// serde_json::Error on a non-200 (error) response.
/// Includes the original body.
SerdeParseErrorWithBodyOnNon200(serde_json::Error, String),
/// An uncategorized bad HTTP response with status code and body.
UncategorizedBadResponseWithStatusAndBody {
status_code: StatusCode,
body: String,
},
/// An uncaught error from the HTTP client.
WreqError(wreq::Error),
}
impl Error for MuapiGenericApiError {}
impl Display for MuapiGenericApiError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::CloudflareError(err) => write!(f, "Cloudflare error: {}", err),
Self::SerdeResponseParseErrorWithBody(err, body) => write!(f, "Failed to parse response body: {:?}. Body: {}", err, body),
Self::SerdeParseErrorWithBodyOnNon200(err, body) => write!(f, "Failed to parse non-200 response body: {:?}. Body: {}", err, body),
Self::UncategorizedBadResponseWithStatusAndBody { status_code, body } => write!(f, "Uncategorized bad response: status code {}, body: {}", status_code, body),
Self::WreqError(err) => write!(f, "Wreq client error: {}", err),
}
}
}
@@ -0,0 +1,18 @@
use std::error::Error;
use std::fmt::{Display, Formatter};
#[derive(Debug)]
pub enum MuapiSpecificApiError {
/// Invalid API key.
InvalidApiKey,
}
impl Error for MuapiSpecificApiError {}
impl Display for MuapiSpecificApiError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::InvalidApiKey => write!(f, "Unauthorized: invalid API key."),
}
}
}
@@ -0,0 +1,8 @@
#[cfg(test)]
pub (crate) mod test_utils;
pub mod api_types;
pub mod creds;
pub mod error;
pub mod requests;
pub mod utils;
@@ -0,0 +1,3 @@
pub mod poll_prediction_result;
pub mod seedance_2p0_image_to_video;
pub mod seedance_2p0_text_to_video;
@@ -0,0 +1,2 @@
pub mod poll_prediction_result;
mod request_types;
@@ -0,0 +1,142 @@
use crate::api_types::request_id::RequestId;
use crate::creds::muapi_session::MuapiSession;
use crate::error::muapi_client_error::MuapiClientError;
use crate::error::muapi_error::MuapiError;
use crate::error::muapi_generic_api_error::MuapiGenericApiError;
use crate::requests::poll_prediction_result::request_types::*;
use log::info;
use wreq::Client;
const PREDICTIONS_BASE_URL: &str = "https://api.muapi.ai/api/v1/predictions";
// --- Public types ---
/// The lifecycle status of a prediction.
#[derive(Debug, Clone, PartialEq)]
pub enum PredictionStatus {
/// The task is queued and has not started yet.
Pending,
/// The task is actively being processed.
Processing,
/// The task finished successfully. `outputs` will be populated.
Completed,
/// The task failed. `error` will contain the reason.
Failed,
/// An unrecognised status string was returned by the server.
Unknown(String),
}
impl PredictionStatus {
fn from_str(s: &str) -> Self {
match s {
"pending" => Self::Pending,
"processing" => Self::Processing,
"completed" => Self::Completed,
"failed" => Self::Failed,
other => Self::Unknown(other.to_string()),
}
}
pub fn is_terminal(&self) -> bool {
matches!(self, Self::Completed | Self::Failed)
}
}
// --- Args & response ---
pub struct PollPredictionResultArgs<'a> {
pub session: &'a MuapiSession,
/// The request_id returned from a submission endpoint.
pub request_id: &'a RequestId,
}
pub struct PollPredictionResultApiResponse {
/// The current status of the prediction.
pub status: PredictionStatus,
/// Output URLs. Populated when `status` is `Completed`.
pub output_urls: Option<Vec<String>>,
/// Error message. Populated when `status` is `Failed`.
pub error: Option<String>,
}
// --- Implementation ---
pub async fn poll_prediction_result(
args: PollPredictionResultArgs<'_>,
) -> Result<PollPredictionResultApiResponse, MuapiError> {
let url = format!("{}/{}/result", PREDICTIONS_BASE_URL, args.request_id.as_str());
info!("Polling Muapi prediction result: {}", url);
let api_key = args.session.api_key.as_str();
let client = Client::builder()
.build()
.map_err(|err| MuapiClientError::WreqClientError(err))?;
let response = client.get(&url)
.header("Content-Type", "application/json")
.header("x-api-key", api_key)
.send()
.await
.map_err(|err| MuapiGenericApiError::WreqError(err))?;
let status = response.status();
let response_body = response.text()
.await
.map_err(|err| MuapiGenericApiError::WreqError(err))?;
info!("Muapi poll response status: {}, body: {}", status, response_body);
if !status.is_success() {
return Err(MuapiGenericApiError::UncategorizedBadResponseWithStatusAndBody {
status_code: status,
body: response_body,
}.into());
}
let parsed: PollPredictionResultResponse = serde_json::from_str(&response_body)
.map_err(|err| MuapiGenericApiError::SerdeResponseParseErrorWithBody(err, response_body))?;
let output_urls = parsed.outputs.and_then(|urls| if urls.is_empty() { None } else { Some(urls) });
Ok(PollPredictionResultApiResponse {
status: PredictionStatus::from_str(&parsed.status),
output_urls,
error: parsed.error,
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_utils::get_test_api_key::get_test_api_key;
use crate::test_utils::setup_test_logging::setup_test_logging;
use errors::AnyhowResult;
use log::LevelFilter;
#[tokio::test]
#[ignore] // manually test — requires real API key and a valid request_id
async fn test_poll_prediction_result() -> AnyhowResult<()> {
setup_test_logging(LevelFilter::Trace);
let session = get_test_api_key()?;
let request_id = RequestId::from_str("5fd7f575-4b9e-4c0a-b7f7-0eb036027b81"); // Corgi shiba I2V
let request_id = RequestId::from_str("8a4b578b-4514-443f-b444-4fb3bc5c2cbb"); // Cat TTV
let request_id = RequestId::from_str("82d622b1-8911-4cac-8362-e18efaa743ed"); // Corgi I2V
let request_id = RequestId::from_str("671c2dee-2ca9-47d7-a12e-d16610b1b365"); // Corgi TTV #1
let request_id = RequestId::from_str("8c5303f6-b602-433c-bae8-2d3ef915b7bb"); // Corgi TTV #2
let result = poll_prediction_result(PollPredictionResultArgs {
session: &session,
request_id: &request_id,
}).await?;
println!("Status: {:?}", result.status);
println!("Output URLs: {:?}", result.output_urls);
println!("Error: {:?}", result.error);
assert_eq!(1, 2); // NB: Intentional failure to inspect output.
Ok(())
}
}
@@ -0,0 +1,8 @@
use serde_derive::Deserialize;
#[derive(Deserialize, Debug)]
pub(super) struct PollPredictionResultResponse {
pub status: String,
pub outputs: Option<Vec<String>>,
pub error: Option<String>,
}
@@ -0,0 +1,2 @@
pub mod seedance_2p0_image_to_video;
mod request_types;
@@ -0,0 +1,19 @@
use serde_derive::{Deserialize, Serialize};
// --- Request ---
#[derive(Serialize, Debug)]
pub(super) struct Seedance2p0I2vRequest {
pub prompt: String,
pub images_list: Vec<String>,
pub aspect_ratio: &'static str,
pub duration: u8,
pub quality: &'static str,
}
// --- Response ---
#[derive(Deserialize, Debug)]
pub(super) struct Seedance2p0I2vResponse {
pub request_id: String,
}
@@ -0,0 +1,221 @@
use crate::api_types::request_id::RequestId;
use crate::creds::muapi_session::MuapiSession;
use crate::error::muapi_client_error::MuapiClientError;
use crate::error::muapi_error::MuapiError;
use crate::error::muapi_generic_api_error::MuapiGenericApiError;
use crate::requests::seedance_2p0_image_to_video::request_types::*;
use log::info;
use wreq::Client;
const SEEDANCE_2P0_I2V_URL: &str = "https://api.muapi.ai/api/v1/seedance-v2.0-i2v";
// --- Public enums ---
/// Video aspect ratio.
#[derive(Debug, Clone, Copy)]
pub enum AspectRatio {
/// 16:9 landscape
Landscape16x9,
/// 9:16 portrait
Portrait9x16,
/// 4:3 standard
Standard4x3,
/// 3:4 portrait
Portrait3x4,
}
impl AspectRatio {
fn as_str(&self) -> &'static str {
match self {
Self::Landscape16x9 => "16:9",
Self::Portrait9x16 => "9:16",
Self::Standard4x3 => "4:3",
Self::Portrait3x4 => "3:4",
}
}
}
/// Video duration.
#[derive(Debug, Clone, Copy)]
pub enum Duration {
/// 5 seconds
FiveSeconds,
/// 10 seconds
TenSeconds,
/// 15 seconds
FifteenSeconds,
}
impl Duration {
fn as_u8(&self) -> u8 {
match self {
Self::FiveSeconds => 5,
Self::TenSeconds => 10,
Self::FifteenSeconds => 15,
}
}
}
/// Video quality tier.
#[derive(Debug, Clone, Copy)]
pub enum Quality {
Basic,
High,
}
impl Quality {
fn as_str(&self) -> &'static str {
match self {
Self::Basic => "basic",
Self::High => "high",
}
}
}
// --- Args & response ---
pub struct Seedance2p0ImageToVideoArgs<'a> {
pub session: &'a MuapiSession,
/// The prompt describing the desired video.
pub prompt: String,
/// One or more image URLs to use as input frames.
pub image_urls: Vec<String>,
/// The aspect ratio for the output video.
pub aspect_ratio: AspectRatio,
/// Duration of the generated video.
pub duration: Duration,
/// Quality tier.
pub quality: Quality,
}
impl std::fmt::Debug for Seedance2p0ImageToVideoArgs<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Seedance2p0ImageToVideoArgs")
.field("prompt", &self.prompt)
.field("image_urls", &self.image_urls)
.field("aspect_ratio", &self.aspect_ratio)
.field("duration", &self.duration)
.field("quality", &self.quality)
.finish()
}
}
#[derive(Debug)]
pub struct Seedance2p0ImageToVideoResponse {
/// The request ID used to poll for results.
pub request_id: RequestId,
}
// --- Implementation ---
pub async fn seedance_2p0_image_to_video(
args: Seedance2p0ImageToVideoArgs<'_>,
) -> Result<Seedance2p0ImageToVideoResponse, MuapiError> {
info!("Submitting Seedance 2.0 i2v task to Muapi: {:?}", args);
let request_body = Seedance2p0I2vRequest {
prompt: args.prompt,
images_list: args.image_urls,
aspect_ratio: args.aspect_ratio.as_str(),
duration: args.duration.as_u8(),
quality: args.quality.as_str(),
};
info!("Muapi request body: {:?}", request_body);
let api_key = args.session.api_key.as_str();
let client = Client::builder()
.build()
.map_err(|err| MuapiClientError::WreqClientError(err))?;
let response = client.post(SEEDANCE_2P0_I2V_URL)
.header("Content-Type", "application/json")
.header("x-api-key", api_key)
.json(&request_body)
.send()
.await
.map_err(|err| MuapiGenericApiError::WreqError(err))?;
let status = response.status();
let response_body = response.text()
.await
.map_err(|err| MuapiGenericApiError::WreqError(err))?;
info!("Muapi response status: {}, body: {}", status, response_body);
if !status.is_success() {
return Err(MuapiGenericApiError::UncategorizedBadResponseWithStatusAndBody {
status_code: status,
body: response_body,
}.into());
}
let parsed: Seedance2p0I2vResponse = serde_json::from_str(&response_body)
.map_err(|err| MuapiGenericApiError::SerdeResponseParseErrorWithBody(err, response_body))?;
Ok(Seedance2p0ImageToVideoResponse {
request_id: RequestId::new(parsed.request_id),
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_utils::get_test_api_key::get_test_api_key;
use crate::test_utils::setup_test_logging::setup_test_logging;
use errors::AnyhowResult;
use log::LevelFilter;
use test_data::web::image_urls::*;
#[tokio::test]
#[ignore] // manually test — requires real API key
async fn test_seedance_2p0_image_to_video() -> AnyhowResult<()> {
setup_test_logging(LevelFilter::Trace);
let session = get_test_api_key()?;
let args = Seedance2p0ImageToVideoArgs {
session: &session,
prompt: "The dog barks and runs across the lake's pier, tail wagging.".to_string(),
image_urls: vec![
JUNO_AT_LAKE_IMAGE_URL.to_string(),
],
aspect_ratio: AspectRatio::Landscape16x9,
duration: Duration::FiveSeconds,
quality: Quality::High,
};
let result = seedance_2p0_image_to_video(args).await?;
println!("Result: {:?}", result);
println!("Request ID: {}", result.request_id);
assert!(!result.request_id.as_str().is_empty());
assert_eq!(1, 2); // NB: Intentional failure to inspect output.
Ok(())
}
#[tokio::test]
#[ignore] // manually test — requires real API key
async fn test_seedance_2p0_image_to_video_portrait() -> AnyhowResult<()> {
setup_test_logging(LevelFilter::Trace);
let session = get_test_api_key()?;
let args = Seedance2p0ImageToVideoArgs {
session: &session,
prompt: "The corgi and shiba swim through the treasure-filled ocean, bubbles rising around them.".to_string(),
image_urls: vec![
TALL_CORGI_SHIBA_TREASURE_OCEAN_URL.to_string(),
],
aspect_ratio: AspectRatio::Portrait9x16,
duration: Duration::FiveSeconds,
quality: Quality::High,
};
let result = seedance_2p0_image_to_video(args).await?;
println!("Result: {:?}", result);
println!("Request ID: {}", result.request_id);
assert!(!result.request_id.as_str().is_empty());
assert_eq!(1, 2); // NB: Intentional failure to inspect output.
Ok(())
}
}
@@ -0,0 +1,2 @@
pub mod seedance_2p0_text_to_video;
mod request_types;
@@ -0,0 +1,18 @@
use serde_derive::{Deserialize, Serialize};
// --- Request ---
#[derive(Serialize, Debug)]
pub(super) struct Seedance2p0T2vRequest {
pub prompt: String,
pub aspect_ratio: &'static str,
pub duration: u8,
pub quality: &'static str,
}
// --- Response ---
#[derive(Deserialize, Debug)]
pub(super) struct Seedance2p0T2vResponse {
pub request_id: String,
}
@@ -0,0 +1,209 @@
use crate::api_types::request_id::RequestId;
use crate::creds::muapi_session::MuapiSession;
use crate::error::muapi_client_error::MuapiClientError;
use crate::error::muapi_error::MuapiError;
use crate::error::muapi_generic_api_error::MuapiGenericApiError;
use crate::requests::seedance_2p0_text_to_video::request_types::*;
use log::info;
use wreq::Client;
const SEEDANCE_2P0_T2V_URL: &str = "https://api.muapi.ai/api/v1/seedance-v2.0-t2v";
// --- Public enums ---
/// Video aspect ratio.
#[derive(Debug, Clone, Copy)]
pub enum AspectRatio {
/// 16:9 landscape
Landscape16x9,
/// 9:16 portrait
Portrait9x16,
/// 4:3 standard
Standard4x3,
/// 3:4 portrait
Portrait3x4,
}
impl AspectRatio {
fn as_str(&self) -> &'static str {
match self {
Self::Landscape16x9 => "16:9",
Self::Portrait9x16 => "9:16",
Self::Standard4x3 => "4:3",
Self::Portrait3x4 => "3:4",
}
}
}
/// Video duration.
#[derive(Debug, Clone, Copy)]
pub enum Duration {
/// 5 seconds
FiveSeconds,
/// 10 seconds
TenSeconds,
/// 15 seconds
FifteenSeconds,
}
impl Duration {
fn as_u8(&self) -> u8 {
match self {
Self::FiveSeconds => 5,
Self::TenSeconds => 10,
Self::FifteenSeconds => 15,
}
}
}
/// Video quality tier.
#[derive(Debug, Clone, Copy)]
pub enum Quality {
Basic,
High,
}
impl Quality {
fn as_str(&self) -> &'static str {
match self {
Self::Basic => "basic",
Self::High => "high",
}
}
}
// --- Args & response ---
pub struct Seedance2p0TextToVideoArgs<'a> {
pub session: &'a MuapiSession,
/// The prompt describing the desired video.
pub prompt: String,
/// The aspect ratio for the output video.
pub aspect_ratio: AspectRatio,
/// Duration of the generated video.
pub duration: Duration,
/// Quality tier.
pub quality: Quality,
}
impl std::fmt::Debug for Seedance2p0TextToVideoArgs<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Seedance2p0TextToVideoArgs")
.field("prompt", &self.prompt)
.field("aspect_ratio", &self.aspect_ratio)
.field("duration", &self.duration)
.field("quality", &self.quality)
.finish()
}
}
#[derive(Debug)]
pub struct Seedance2p0TextToVideoResponse {
/// The request ID used to poll for results.
pub request_id: RequestId,
}
// --- Implementation ---
pub async fn seedance_2p0_text_to_video(
args: Seedance2p0TextToVideoArgs<'_>,
) -> Result<Seedance2p0TextToVideoResponse, MuapiError> {
info!("Submitting Seedance 2.0 t2v task to Muapi: {:?}", args);
let request_body = Seedance2p0T2vRequest {
prompt: args.prompt,
aspect_ratio: args.aspect_ratio.as_str(),
duration: args.duration.as_u8(),
quality: args.quality.as_str(),
};
info!("Muapi request body: {:?}", request_body);
let api_key = args.session.api_key.as_str();
let client = Client::builder()
.build()
.map_err(|err| MuapiClientError::WreqClientError(err))?;
let response = client.post(SEEDANCE_2P0_T2V_URL)
.header("Content-Type", "application/json")
.header("x-api-key", api_key)
.json(&request_body)
.send()
.await
.map_err(|err| MuapiGenericApiError::WreqError(err))?;
let status = response.status();
let response_body = response.text()
.await
.map_err(|err| MuapiGenericApiError::WreqError(err))?;
info!("Muapi response status: {}, body: {}", status, response_body);
if !status.is_success() {
return Err(MuapiGenericApiError::UncategorizedBadResponseWithStatusAndBody {
status_code: status,
body: response_body,
}.into());
}
let parsed: Seedance2p0T2vResponse = serde_json::from_str(&response_body)
.map_err(|err| MuapiGenericApiError::SerdeResponseParseErrorWithBody(err, response_body))?;
Ok(Seedance2p0TextToVideoResponse {
request_id: RequestId::new(parsed.request_id),
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_utils::get_test_api_key::get_test_api_key;
use crate::test_utils::setup_test_logging::setup_test_logging;
use errors::AnyhowResult;
use log::LevelFilter;
#[tokio::test]
#[ignore] // manually test — requires real API key
async fn test_seedance_2p0_text_to_video_landscape() -> AnyhowResult<()> {
setup_test_logging(LevelFilter::Trace);
let session = get_test_api_key()?;
let args = Seedance2p0TextToVideoArgs {
session: &session,
prompt: "A corgi walks past a lighthouse on the shore. In the background, mossy rocks and rolling green hills dot the landscape. The sand is black, and the air is full of fog and mist".to_string(),
aspect_ratio: AspectRatio::Landscape16x9,
duration: Duration::FiveSeconds,
quality: Quality::High,
};
let result = seedance_2p0_text_to_video(args).await?;
println!("Result: {:?}", result);
println!("Request ID: {}", result.request_id);
assert!(!result.request_id.as_str().is_empty());
assert_eq!(1, 2); // NB: Intentional failure to inspect output.
Ok(())
}
#[tokio::test]
#[ignore] // manually test — requires real API key
async fn test_seedance_2p0_text_to_video_portrait() -> AnyhowResult<()> {
setup_test_logging(LevelFilter::Trace);
let session = get_test_api_key()?;
let args = Seedance2p0TextToVideoArgs {
session: &session,
prompt: "A cat sits on a windowsill watching rain fall outside. Lightning flashes and the cat's eyes widen.".to_string(),
aspect_ratio: AspectRatio::Portrait9x16,
duration: Duration::TenSeconds,
quality: Quality::Basic,
};
let result = seedance_2p0_text_to_video(args).await?;
println!("Result: {:?}", result);
println!("Request ID: {}", result.request_id);
assert!(!result.request_id.as_str().is_empty());
assert_eq!(1, 2); // NB: Intentional failure to inspect output.
Ok(())
}
}
@@ -0,0 +1,10 @@
use crate::creds::muapi_session::MuapiSession;
use errors::AnyhowResult;
use std::fs::read_to_string;
#[cfg(test)]
pub fn get_test_api_key() -> AnyhowResult<MuapiSession> {
let api_key = read_to_string("/Users/bt/Artcraft/credentials/muapi_api_key.txt")?;
let api_key = api_key.trim().to_string();
Ok(MuapiSession::from_api_key_string(api_key))
}
@@ -0,0 +1,5 @@
#[cfg(test)]
pub (crate) mod get_test_api_key;
#[cfg(test)]
pub (crate) mod setup_test_logging;
@@ -0,0 +1,52 @@
use chrono::Local;
use env_logger::Builder;
use log::{debug, error, info, trace, warn, LevelFilter};
use std::io::Write;
const RUST_LOG: &str = "RUST_LOG";
pub fn setup_test_logging(level: LevelFilter) {
let level_str = get_level_str(level);
println!("Previous log level: {:?}", env::var(RUST_LOG));
let is_unsafe = env::set_var(RUST_LOG, level_str);
if is_unsafe.is_none() {
println!("Unsafely setting Rust Log Level...");
unsafe { std::env::set_var(RUST_LOG, level_str) }
}
println!("Log level: {:?}", env::var(RUST_LOG));
Builder::new()
.is_test(true)
.format(|buf, record| {
writeln!(buf,
"{} [{}] - {}",
Local::now().format("%H:%M:%S%.6f"),
record.level(),
record.args()
)
})
.filter(None, level)
.filter_level(level)
.init();
trace!("Test trace log");
debug!("Test debug log");
info!("Test info log");
warn!("Test warn log");
error!("Test error log");
}
fn get_level_str(level: LevelFilter) -> &'static str {
match level {
LevelFilter::Error => "error",
LevelFilter::Warn => "warn",
LevelFilter::Info => "info",
LevelFilter::Debug => "debug",
LevelFilter::Trace => "trace",
LevelFilter::Off => "off",
}
}
@@ -0,0 +1,2 @@
pub const FIREFOX_USER_AGENT: &str =
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:147.0) Gecko/20100101 Firefox/147.0";
@@ -0,0 +1 @@
pub mod common_headers;
@@ -31,7 +31,6 @@ wreq.workspace = true
url.workspace = true
[dev-dependencies]
chrono.workspace = true
env.workspace = true
env_logger.workspace = true
testing = { path = "../../lib/testing" }
@@ -14,10 +14,17 @@ pub enum Seedance2ProError {
impl Seedance2ProError {
pub fn is_having_downtime_issues(&self) -> bool {
match self {
Self::ApiGeneric(Seedance2ProGenericApiError::Http502ErrorBadGateway(_)) => true,
Self::ApiGeneric(Seedance2ProGenericApiError::CloudflareError(CloudflareError::BadGateway502)) => true,
Self::ApiGeneric(Seedance2ProGenericApiError::CloudflareError(CloudflareError::GatewayTimeout504)) => true,
Self::ApiGeneric(Seedance2ProGenericApiError::CloudflareError(CloudflareError::TimeoutOccurred524)) => true,
Self::ApiGeneric(Seedance2ProGenericApiError::UncategorizedBadResponseWithStatusAndBody { status_code, body: _ }) => {
match status_code.as_u16() {
502 => true,
504 => true,
524 => true,
_ => false,
}
},
_ => false,
}
}
@@ -8,10 +8,6 @@ pub enum Seedance2ProGenericApiError {
/// Specific Cloudflare errors.
CloudflareError(CloudflareError),
/// HTTP 502 Bad Gateway.
/// We preserve the message for debugging.
Http502ErrorBadGateway(String),
/// serde_json::Error, likely from JSON deserialization schema mismatch.
/// Includes the original body.
SerdeResponseParseErrorWithBody(serde_json::Error, String),
@@ -39,7 +35,6 @@ impl Display for Seedance2ProGenericApiError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::CloudflareError(err) => write!(f, "Cloudflare error: {}", err),
Self::Http502ErrorBadGateway(msg) => write!(f, "HTTP 502 Bad Gateway: {}", msg),
Self::SerdeResponseParseErrorWithBody(err, body) => write!(f, "Failed to parse response body: {:?}. Body: {}", err, body),
Self::SerdeParseErrorWithBodyOnNon200(err, body) => write!(f, "Failed to parse non-200 response body: {:?}. Body: {}", err, body),
Self::UncategorizedBadResponse(msg) => write!(f, "Uncategorized bad response: {}", msg),