Spaces:
Sleeping
Sleeping
File size: 6,496 Bytes
343eed9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 | use crate::error::{GeneratorError, Result};
use serde::{Deserialize, Serialize};
use std::path::Path;
#[derive(Debug, Clone)]
pub struct ApiRouterGenerator {
pub router_url: String,
pub api_secret: String,
pub openrouter_api_key: Option<String>,
}
#[derive(Debug, Serialize)]
struct ImageRequest {
prompt: String,
model: String,
}
#[derive(Debug, Deserialize)]
struct ImageResponse {
statut: String,
donnees: Option<ImageData>,
}
#[derive(Debug, Deserialize)]
struct ImageData {
#[serde(rename = "imageUrl")]
image_url: Option<String>,
}
impl ApiRouterGenerator {
pub fn new(router_url: String, api_secret: String, openrouter_api_key: Option<String>) -> Self {
Self {
router_url,
api_secret,
openrouter_api_key,
}
}
async fn download_image(&self, url: &str, output_path: &Path) -> Result<bool> {
let response = reqwest::get(url)
.await
.map_err(GeneratorError::RequestError)?;
let bytes = response.bytes().await.map_err(GeneratorError::RequestError)?;
std::fs::write(output_path, bytes)?;
Ok(true)
}
pub async fn generate(
&self,
prompt: &str,
output_path: &Path,
scene_index: usize,
is_last: bool,
) -> Result<bool> {
let horror_hook = if scene_index == 1 {
"SHOCKING HORROR: terrified face or lunging monster, "
} else {
""
};
let branding = if is_last {
" with 'Darkmedia-X' branding text visible"
} else {
""
};
let styled_prompt = format!(
"Dark Anime Horror, {}{}{branding}. 9:16 ratio, ink-wash, high resolution.",
horror_hook, prompt
);
let payload = ImageRequest {
prompt: styled_prompt,
model: "openai/dall-e-3".to_string(),
};
let client = reqwest::Client::new();
let url = format!("{}/api/image", self.router_url.trim_end_matches('/'));
let response = client
.post(&url)
.header("Authorization", format!("Bearer {}", self.api_secret))
.header("Content-Type", "application/json")
.json(&payload)
.timeout(std::time::Duration::from_secs(45))
.send()
.await;
match response {
Ok(resp) => {
let status = resp.status();
if status == 404 {
eprintln!(" [WARN] Router 404 — fallback direct");
return self.fallback_direct(prompt, output_path, is_last).await;
}
if !status.is_success() {
eprintln!(" [WARN] Router returned status {} — fallback direct", status);
return self.fallback_direct(prompt, output_path, is_last).await;
}
if let Ok(data) = resp.json::<ImageResponse>().await {
if data.statut == "actif" {
if let Some(image_data) = data.donnees {
if let Some(img_url) = image_data.image_url {
return self.download_image(&img_url, output_path).await;
}
}
}
}
Ok(false)
}
Err(e) => {
eprintln!(" [WARN] Router inaccessible — fallback direct: {}", e);
self.fallback_direct(prompt, output_path, is_last).await
}
}
}
async fn fallback_direct(&self, prompt: &str, output_path: &Path, is_last: bool) -> Result<bool> {
let api_key = self.openrouter_api_key.as_ref()
.ok_or_else(|| GeneratorError::ApiError("OPENROUTER_API_KEY not configured".to_string()))?;
let branding = if is_last {
" with 'Darkmedia-X' branding text visible"
} else {
""
};
let styled_prompt = format!(
"Dark Anime Cinematic Horror Style: {}{branding}. High resolution, 9:16 vertical ratio, ink-wash textures, moody lighting.",
prompt
);
let client = reqwest::Client::new();
#[derive(Serialize)]
struct OpenRouterRequest {
model: String,
prompt: String,
n: usize,
size: String,
}
let payload = OpenRouterRequest {
model: "openai/dall-e-3".to_string(),
prompt: styled_prompt,
n: 1,
size: "1024x1792".to_string(),
};
let response = client
.post("https://openrouter.ai/api/v1/images/generations")
.header("Authorization", format!("Bearer {}", api_key))
.json(&payload)
.timeout(std::time::Duration::from_secs(120))
.send()
.await?;
if !response.status().is_success() {
eprintln!(" 🔴 OpenRouter error: {} status", response.status());
if let Ok(text) = response.text().await {
eprintln!(" Response: {}", &text[..std::cmp::min(200, text.len())]);
}
return Err(GeneratorError::ApiError("OpenRouter API error".to_string()));
}
#[derive(Deserialize)]
struct OpenRouterResponse {
data: Vec<OpenRouterImage>,
}
#[derive(Deserialize)]
struct OpenRouterImage {
url: String,
}
match response.json::<OpenRouterResponse>().await {
Ok(data) => {
if let Some(img) = data.data.first() {
return self.download_image(&img.url, output_path).await;
}
Ok(false)
}
Err(e) => {
eprintln!(" 🔴 OpenRouter JSON error: {}", e);
Err(e.into())
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_api_router_new() {
let generator = ApiRouterGenerator::new(
"http://localhost:8080".to_string(),
"secret".to_string(),
Some("openrouter_key".to_string()),
);
assert_eq!(generator.router_url, "http://localhost:8080");
assert_eq!(generator.api_secret, "secret");
assert_eq!(generator.openrouter_api_key, Some("openrouter_key".to_string()));
}
}
|