saymaker 0.1.0

Generate images and video from Rust on SayMaker: Veo 3.1, Kling 3.0, Seedance 2.0, Nano Banana 2, GPT Image 2.5 and more with one API key
Documentation
//! Generate images and video from Rust on [SayMaker](https://saymaker.ai).
//!
//! One API key runs the whole SayMaker shelf on your own credits: Veo 3.1,
//! Kling 3.0, Seedance 2.0, MiniMax H3, Nano Banana 2, GPT Image 2.5,
//! Seedream 5.0 and more. Create a key at <https://saymaker.ai/settings/apikeys>
//! and set `SAYMAKER_API_KEY` or pass it in the options.
//!
//! ```no_run
//! let url = saymaker::generate("a paper boat at sunrise", &saymaker::Options::default())?;
//! let clip = saymaker::generate_video("a fox trotting through snow", &saymaker::VideoOptions::default())?;
//! # Ok::<(), saymaker::Error>(())
//! ```

use serde_json::{json, Value};
use std::fmt;
use std::thread::sleep;
use std::time::{Duration, Instant};

/// The service this crate talks to.
pub const BASE_URL: &str = "https://saymaker.ai";
/// Where an API key is created.
pub const KEYS_URL: &str = "https://saymaker.ai/settings/apikeys";
/// The cheapest text-to-image model.
pub const MODEL_IMAGE: &str = "saymaker-image-v1";
/// The default edit model; it takes an input image.
pub const MODEL_EDIT: &str = "nano-banana-2-lite";
/// The video model a free account can run (480p or 768p, 4 to 15 seconds).
pub const MODEL_VIDEO: &str = "minimax-h3-fast";

/// Model id -> the routing field the API expects next to it. Unlisted ids go as "kie".
pub const MODELS: &[(&str, &str)] = &[
    ("saymaker-image-v1", "kie"), ("nano-banana-2-lite", "kie"), ("nano-banana-2", "poyo"),
    ("nano-banana-pro", "poyo"), ("gpt-image-2", "poyo"), ("gpt-image-2-5-flare", "kie"),
    ("seedream-5-lite", "poyo"), ("seedream-5-pro", "kie"), ("qwen-image-3-pro", "kie"),
    ("grok-imagine-image-2-0", "poyo"), ("minimax-h3-fast", "vgenv"), ("minimax-h3", "poyo"),
    ("seedance-2", "kie"), ("seedance-2-fast", "kie"), ("seedance-2-5", "kie"), ("veo-3-1", "kie"),
    ("kling-3-0", "kie"), ("kling-3-0-turbo", "kie"), ("wan-3-0", "kie"), ("ltx-2-5-fast", "replicate"),
];

/// What went wrong, split by what to do next.
#[derive(Debug)]
pub enum Error {
    /// No API key, or the key is invalid or deleted.
    Auth(String),
    /// The account is out of credits.
    Quota(String),
    /// The model needs a paid plan or a credit pack.
    Plan(String),
    /// Another run on this account is still rendering. Free accounts run one at a time.
    Busy(String),
    /// The content filter or the model refused the prompt. Reword it.
    Rejected,
    /// The deadline passed; the run may still finish in your SayMaker history.
    Timeout,
    /// Bad input, transport failure or an unexpected answer.
    Other(String),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Auth(m) if m.contains("settings/apikeys") => write!(f, "saymaker: {m}"),
            Error::Auth(m) => write!(f, "saymaker: {m} (create a key at {KEYS_URL})"),
            Error::Quota(m) | Error::Plan(m) | Error::Busy(m) | Error::Other(m) => write!(f, "saymaker: {m}"),
            Error::Rejected => write!(f, "saymaker: the run failed; reword the prompt rather than retrying"),
            Error::Timeout => write!(f, "saymaker: deadline passed"),
        }
    }
}

impl std::error::Error for Error {}

/// Options for an image. `Default` is valid.
#[derive(Clone, Debug, Default)]
pub struct Options {
    /// Empty means the `SAYMAKER_API_KEY` environment variable.
    pub api_key: Option<String>,
    /// Defaults to `MODEL_IMAGE`, or `MODEL_EDIT` when `image_url` is set.
    pub model: Option<String>,
    /// A public http(s) url; makes the call an edit.
    pub image_url: Option<String>,
    /// "1:1", "16:9", "9:16", "4:3", "3:4".
    pub aspect_ratio: Option<String>,
    /// Defaults to 75 minutes, which covers the free-account queue.
    pub timeout: Option<Duration>,
}

/// Options for a clip. `Default` is valid.
#[derive(Clone, Debug, Default)]
pub struct VideoOptions {
    pub api_key: Option<String>,
    /// Defaults to `MODEL_VIDEO`.
    pub model: Option<String>,
    /// Optional first frame; makes the call image-to-video.
    pub image_url: Option<String>,
    /// Seconds, where the model offers a choice.
    pub duration: Option<u32>,
    /// e.g. "480p", "720p", "1080p".
    pub resolution: Option<String>,
    /// Defaults to "16:9".
    pub aspect_ratio: Option<String>,
    pub no_sound: bool,
    /// Defaults to 90 minutes.
    pub timeout: Option<Duration>,
}

/// Generate one image (or edit `opts.image_url`) and return its URL.
pub fn generate(prompt: &str, opts: &Options) -> Result<String, Error> {
    let edit = opts.image_url.clone();
    check_url(&edit)?;
    let model = opts.model.clone().unwrap_or_else(|| if edit.is_some() { MODEL_EDIT } else { MODEL_IMAGE }.into());
    let size = opts.aspect_ratio.clone().unwrap_or_else(|| if edit.is_some() { "auto" } else { "1:1" }.into());
    let mut o = json!({ "size": size, "resolution": "1K", "n": 1 });
    if let Some(u) = &edit {
        o["image_input"] = json!([u]);
    }
    let scene = if edit.is_some() { "image-to-image" } else { "text-to-image" };
    run(opts.api_key.clone(), "image", scene, &model, prompt, o, Duration::from_secs(5), opts.timeout.unwrap_or(Duration::from_secs(4500)))
}

/// Generate one clip (or animate `opts.image_url`) and return its URL. Video takes minutes.
pub fn generate_video(prompt: &str, opts: &VideoOptions) -> Result<String, Error> {
    check_url(&opts.image_url)?;
    let model = opts.model.clone().unwrap_or_else(|| MODEL_VIDEO.into());
    let mut o = json!({ "aspect_ratio": opts.aspect_ratio.clone().unwrap_or_else(|| "16:9".into()), "sound": !opts.no_sound });
    if let Some(u) = &opts.image_url {
        o["image_input"] = json!([u]);
    }
    if let Some(d) = opts.duration {
        o["duration"] = json!(d);
    }
    if let Some(r) = &opts.resolution {
        o["resolution"] = json!(r);
    }
    let scene = if opts.image_url.is_some() { "image-to-video" } else { "text-to-video" };
    run(opts.api_key.clone(), "video", scene, &model, prompt, o, Duration::from_secs(10), opts.timeout.unwrap_or(Duration::from_secs(5400)))
}

fn check_url(u: &Option<String>) -> Result<(), Error> {
    match u {
        Some(s) if !(s.starts_with("http://") || s.starts_with("https://")) => {
            Err(Error::Other("image_url must be a public http(s) url".into()))
        }
        _ => Ok(()),
    }
}

/// Which routing field a model id goes with.
pub fn provider_for(model: &str) -> &'static str {
    MODELS.iter().find(|(m, _)| *m == model).map(|(_, p)| *p).unwrap_or("kie")
}

#[allow(clippy::too_many_arguments)]
fn run(key: Option<String>, media: &str, scene: &str, model: &str, prompt: &str, options: Value, poll: Duration, timeout: Duration) -> Result<String, Error> {
    if prompt.trim().is_empty() {
        return Err(Error::Other("prompt is required".into()));
    }
    let key = key.filter(|k| !k.is_empty()).or_else(|| std::env::var("SAYMAKER_API_KEY").ok().filter(|k| !k.is_empty()))
        .ok_or_else(|| Error::Auth("an API key is required".into()))?;
    let base = std::env::var("SAYMAKER_BASE_URL").unwrap_or_else(|_| BASE_URL.into());
    let body = json!({
        "provider": provider_for(model), "mediaType": media, "model": model,
        "scene": scene, "prompt": prompt, "options": options,
    });
    let data = post(&base, &key, "/api/ai/generate", body)?;
    // A signed-out request is HTTP 200 with code 0 — only `wall` tells it apart.
    if data.get("wall").and_then(Value::as_bool).unwrap_or(false) {
        return Err(Error::Auth("an API key is required".into()));
    }
    let id = data.get("id").and_then(Value::as_str).ok_or_else(|| Error::Other("no task id".into()))?.to_string();
    // Free-account runs only reach the model on the poll that crosses the end of
    // the queue wait, so polling is what starts the work.
    let deadline = Instant::now() + timeout;
    while Instant::now() < deadline {
        sleep(poll);
        let d = match post(&base, &key, "/api/ai/query", json!({ "taskId": id })) {
            Ok(d) => d,
            Err(e @ Error::Auth(_)) => return Err(e),
            Err(_) => continue, // a dropped poll is not a failed generation
        };
        if let Some(url) = first_url(&d) {
            return Ok(url);
        }
        let status = d.get("status").and_then(Value::as_str).unwrap_or("").to_lowercase();
        if status == "failed" || status == "error" {
            return Err(Error::Rejected);
        }
    }
    Err(Error::Timeout)
}

/// The finished file: the clean image on a paid plan, else the image, else the clip.
pub fn first_url(data: &Value) -> Option<String> {
    ["cleanImages", "images", "videos"].iter().find_map(|f| data.get(*f)?.get(0)?.as_str().map(String::from))
}

fn post(base: &str, key: &str, path: &str, body: Value) -> Result<Value, Error> {
    let resp = ureq::post(&format!("{base}{path}"))
        .set("Authorization", &format!("Bearer {key}"))
        .set("User-Agent", "saymaker-rust/0.1.0")
        .send_json(body);
    let env: Value = match resp {
        Ok(r) => r.into_json().map_err(|e| Error::Other(e.to_string()))?,
        Err(ureq::Error::Status(_, r)) => r.into_json().unwrap_or(Value::Null),
        Err(e) => return Err(Error::Other(e.to_string())),
    };
    // Refusals answer HTTP 200 with code -1; the status code alone reads as success.
    if env.get("code").and_then(Value::as_i64) != Some(0) {
        return Err(classify(env.get("message").and_then(Value::as_str).unwrap_or("request refused")));
    }
    Ok(env.get("data").cloned().unwrap_or(Value::Null))
}

/// Map a refusal message to the error that says what to do next.
pub fn classify(msg: &str) -> Error {
    let low = msg.to_lowercase();
    if low.contains("is rendering") || low.contains("at once") {
        Error::Busy(msg.into())
    } else if low.contains("api key") || low.contains("no auth") {
        Error::Auth(msg.into())
    } else if low.contains("insufficient credits") {
        Error::Quota(msg.into())
    } else if low.contains("subscription") || low.contains("plan") || low.contains("sign in") {
        Error::Plan(msg.into())
    } else {
        Error::Other(msg.into())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn routes_and_classifies() {
        assert_eq!(provider_for("minimax-h3-fast"), "vgenv");
        assert_eq!(provider_for("unknown"), "kie");
        assert!(matches!(classify("insufficient credits"), Error::Quota(_)));
        assert!(matches!(classify("invalid API key"), Error::Auth(_)));
        assert!(matches!(classify("Your current run is rendering. Plans on the pricing page"), Error::Busy(_)));
        let d = json!({"images": ["m"], "cleanImages": ["c"]});
        assert_eq!(first_url(&d).as_deref(), Some("c"));
        assert_eq!(first_url(&json!({"videos": ["v"]})).as_deref(), Some("v"));
    }

    #[test]
    fn rejects_bad_input() {
        let o = Options { image_url: Some("file:///x".into()), ..Default::default() };
        assert!(generate("x", &o).is_err());
        std::env::remove_var("SAYMAKER_API_KEY");
        assert!(matches!(generate("x", &Options::default()), Err(Error::Auth(_))));
    }
}