Spaces:
Build error
Build error
Download src/image_search/mod.rs from LuckyMod/intentforge: direct link, hf CLI and curl.
- Browser
- Download file 15.9 kB
-
https://huggingface.co/spaces/LuckyMod/intentforge/resolve/main/src/image_search/mod.rs
- Command line
-
hf download hf://spaces/LuckyMod/intentforge/src/image_search/mod.rs
-
curl -L -o mod.rs https://huggingface.co/spaces/LuckyMod/intentforge/resolve/main/src/image_search/mod.rs
15.9 kB
| //! External image search providers for IntentForge v2 | |
| //! | |
| //! Provides concurrent image search from: | |
| //! - **Pixabay** β 100 req/60s, free API key, high-quality stock photos | |
| //! - **Pexels** β 200 req/hour (20k/month), free API key, curated photos | |
| //! | |
| //! Both providers are queried concurrently with rate limiting and caching. | |
| //! Results are deduplicated and merged with local Meilisearch image results. | |
| use anyhow::{Context, Result}; | |
| use futures::future::join_all; | |
| use reqwest::StatusCode; | |
| use serde::{Deserialize, Serialize}; | |
| use std::collections::HashSet; | |
| use std::sync::Arc; | |
| use tokio::sync::Mutex; | |
| use tokio::time::{sleep, Duration, Instant}; | |
| /// Unified image result from any provider | |
| pub struct ImageResult { | |
| pub id: String, | |
| pub title: String, | |
| pub url: String, | |
| pub source: String, | |
| pub photographer: Option<String>, | |
| pub thumbnail_url: Option<String>, | |
| pub width: Option<u32>, | |
| pub height: Option<u32>, | |
| pub avg_color: Option<String>, | |
| pub tags: Vec<String>, | |
| } | |
| /// Configuration for the image search service | |
| pub struct ImageSearchConfig { | |
| pub pixabay_api_key: Option<String>, | |
| pub pexels_api_key: Option<String>, | |
| pub search_limit: usize, | |
| pub cache_ttl_secs: u64, | |
| } | |
| impl ImageSearchConfig { | |
| pub fn from_app_config(config: &crate::config::ImageSearchConfig) -> Self { | |
| let pixabay_key = std::env::var("PIXABAY_API_KEY") | |
| .ok() | |
| .or_else(|| config.pixabay_api_key.clone()); | |
| let pexels_key = std::env::var("PEXELS_API_KEY") | |
| .ok() | |
| .or_else(|| config.pexels_api_key.clone()); | |
| Self { | |
| pixabay_api_key: pixabay_key, | |
| pexels_api_key: pexels_key, | |
| search_limit: config.search_limit, | |
| cache_ttl_secs: config.cache_ttl_secs, | |
| } | |
| } | |
| } | |
| // ββ Rate limiter ββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| /// Token-bucket rate limiter for per-provider request throttling. | |
| struct RateLimiter { | |
| /// Maximum tokens (requests) in the bucket | |
| max_tokens: u32, | |
| /// Current available tokens | |
| tokens: Mutex<f64>, | |
| /// Refill rate (tokens per second) | |
| refill_rate: f64, | |
| /// Last refill timestamp | |
| last_refill: Mutex<Instant>, | |
| } | |
| impl RateLimiter { | |
| fn new(max_tokens: u32, refill_interval_secs: f64) -> Self { | |
| Self { | |
| max_tokens, | |
| tokens: Mutex::new(max_tokens as f64), | |
| refill_rate: max_tokens as f64 / refill_interval_secs, | |
| last_refill: Mutex::new(Instant::now()), | |
| } | |
| } | |
| /// Acquire a token, waiting if necessary. | |
| async fn acquire(&self) { | |
| loop { | |
| let mut tokens = self.tokens.lock().await; | |
| let mut last = self.last_refill.lock().await; | |
| let now = Instant::now(); | |
| let elapsed = now.duration_since(*last).as_secs_f64(); | |
| *tokens = (*tokens + elapsed * self.refill_rate).min(self.max_tokens as f64); | |
| *last = now; | |
| if *tokens >= 1.0 { | |
| *tokens -= 1.0; | |
| return; | |
| } | |
| let deficit = 1.0 - *tokens; | |
| let wait_secs = deficit / self.refill_rate; | |
| drop(tokens); | |
| drop(last); | |
| sleep(Duration::from_secs_f64(wait_secs.max(0.01))).await; | |
| } | |
| } | |
| } | |
| // ββ Pixabay βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| /// Pixabay API response | |
| struct PixabayResponse { | |
| total: u64, | |
| total_hits: u64, | |
| hits: Vec<PixabayHit>, | |
| } | |
| struct PixabayHit { | |
| id: u64, | |
| page_url: String, | |
| tags: String, | |
| preview_url: String, | |
| preview_width: u32, | |
| preview_height: u32, | |
| webformat_url: String, | |
| webformat_width: u32, | |
| webformat_height: u32, | |
| user: String, | |
| user_image_url: String, | |
| } | |
| pub struct PixabayClient { | |
| client: reqwest::Client, | |
| api_key: String, | |
| rate_limiter: RateLimiter, | |
| } | |
| impl PixabayClient { | |
| pub fn new(client: reqwest::Client, api_key: String) -> Self { | |
| Self { | |
| client, | |
| api_key, | |
| // Pixabay: 100 requests per 60 seconds | |
| rate_limiter: RateLimiter::new(100, 60.0), | |
| } | |
| } | |
| pub async fn search(&self, query: &str, limit: usize) -> Result<Vec<ImageResult>> { | |
| self.rate_limiter.acquire().await; | |
| let per_page = limit.clamp(3, 200); | |
| let url = format!( | |
| "https://pixabay.com/api/?key={}&q={}&image_type=photo&per_page={}&safesearch=true", | |
| self.api_key, | |
| urlencoding::encode(query), | |
| per_page, | |
| ); | |
| let resp = self | |
| .client | |
| .get(&url) | |
| .timeout(Duration::from_secs(8)) | |
| .send() | |
| .await | |
| .with_context(|| "Pixabay API request failed")?; | |
| if resp.status() == StatusCode::TOO_MANY_REQUESTS { | |
| tracing::warn!("Pixabay rate limit hit, backing off"); | |
| sleep(Duration::from_secs(5)).await; | |
| return Ok(Vec::new()); | |
| } | |
| if !resp.status().is_success() { | |
| tracing::warn!("Pixabay API returned status {}", resp.status()); | |
| return Ok(Vec::new()); | |
| } | |
| let data: PixabayResponse = resp | |
| .json() | |
| .await | |
| .with_context(|| "Failed to parse Pixabay response")?; | |
| let results: Vec<ImageResult> = data | |
| .hits | |
| .into_iter() | |
| .take(limit) | |
| .map(|h| ImageResult { | |
| id: format!("pixabay_{}", h.id), | |
| title: h | |
| .tags | |
| .split(',') | |
| .next() | |
| .unwrap_or("Untitled") | |
| .trim() | |
| .to_string(), | |
| url: h.page_url, | |
| source: "pixabay".to_string(), | |
| photographer: Some(h.user), | |
| thumbnail_url: Some(h.preview_url), | |
| width: Some(h.webformat_width), | |
| height: Some(h.webformat_height), | |
| avg_color: None, | |
| tags: h.tags.split(',').map(|t| t.trim().to_string()).collect(), | |
| }) | |
| .collect(); | |
| Ok(results) | |
| } | |
| } | |
| // ββ Pexels ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| /// Pexels API response | |
| struct PexelsResponse { | |
| total_results: u64, | |
| photos: Vec<PexelsPhoto>, | |
| } | |
| struct PexelsPhoto { | |
| id: u64, | |
| width: u32, | |
| height: u32, | |
| url: String, | |
| photographer: String, | |
| avg_color: Option<String>, | |
| src: PexelsSrc, | |
| alt: Option<String>, | |
| } | |
| struct PexelsSrc { | |
| original: String, | |
| large: String, | |
| medium: String, | |
| small: String, | |
| portrait: String, | |
| landscape: String, | |
| tiny: String, | |
| } | |
| pub struct PexelsClient { | |
| client: reqwest::Client, | |
| api_key: String, | |
| rate_limiter: RateLimiter, | |
| } | |
| impl PexelsClient { | |
| pub fn new(client: reqwest::Client, api_key: String) -> Self { | |
| Self { | |
| client, | |
| api_key, | |
| // Pexels: 200 requests per hour = ~0.055 req/s refill | |
| rate_limiter: RateLimiter::new(200, 3600.0), | |
| } | |
| } | |
| pub async fn search(&self, query: &str, limit: usize) -> Result<Vec<ImageResult>> { | |
| self.rate_limiter.acquire().await; | |
| let per_page = limit.clamp(1, 80); | |
| let url = format!( | |
| "https://api.pexels.com/v1/search?query={}&per_page={}", | |
| urlencoding::encode(query), | |
| per_page, | |
| ); | |
| let resp = self | |
| .client | |
| .get(&url) | |
| .header("Authorization", &self.api_key) | |
| .timeout(Duration::from_secs(8)) | |
| .send() | |
| .await | |
| .with_context(|| "Pexels API request failed")?; | |
| if resp.status() == StatusCode::TOO_MANY_REQUESTS { | |
| tracing::warn!("Pexels rate limit hit, backing off"); | |
| sleep(Duration::from_secs(10)).await; | |
| return Ok(Vec::new()); | |
| } | |
| if resp.status() == StatusCode::FORBIDDEN { | |
| tracing::warn!("Pexels API key invalid or unauthorized"); | |
| return Ok(Vec::new()); | |
| } | |
| if !resp.status().is_success() { | |
| tracing::warn!("Pexels API returned status {}", resp.status()); | |
| return Ok(Vec::new()); | |
| } | |
| let data: PexelsResponse = resp | |
| .json() | |
| .await | |
| .with_context(|| "Failed to parse Pexels response")?; | |
| let results: Vec<ImageResult> = data | |
| .photos | |
| .into_iter() | |
| .take(limit) | |
| .map(|p| ImageResult { | |
| id: format!("pexels_{}", p.id), | |
| title: p.alt.unwrap_or_else(|| p.photographer.clone()), | |
| url: p.url, | |
| source: "pexels".to_string(), | |
| photographer: Some(p.photographer), | |
| thumbnail_url: Some(p.src.tiny), | |
| width: Some(p.width), | |
| height: Some(p.height), | |
| avg_color: p.avg_color, | |
| tags: Vec::new(), | |
| }) | |
| .collect(); | |
| Ok(results) | |
| } | |
| } | |
| // ββ Service βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| /// Aggregated image search service that fans out to all configured providers. | |
| pub struct ImageSearchService { | |
| pixabay: Option<PixabayClient>, | |
| pexels: Option<PexelsClient>, | |
| cache: Arc<Mutex<ImageCache>>, | |
| cache_ttl: Duration, | |
| } | |
| struct CacheEntry { | |
| results: Vec<ImageResult>, | |
| expires: Instant, | |
| } | |
| struct ImageCache { | |
| entries: std::collections::HashMap<String, CacheEntry>, | |
| } | |
| impl ImageSearchService { | |
| pub fn new(client: reqwest::Client, config: ImageSearchConfig) -> Self { | |
| let pixabay = config.pixabay_api_key.map(|key| { | |
| tracing::info!("Pixabay image search enabled"); | |
| PixabayClient::new(client.clone(), key) | |
| }); | |
| let pexels = config.pexels_api_key.map(|key| { | |
| tracing::info!("Pexels image search enabled"); | |
| PexelsClient::new(client.clone(), key) | |
| }); | |
| if pixabay.is_none() && pexels.is_none() { | |
| tracing::info!("No external image search API keys configured (set PIXABAY_API_KEY and/or PEXELS_API_KEY)"); | |
| } | |
| Self { | |
| pixabay, | |
| pexels, | |
| cache: Arc::new(Mutex::new(ImageCache::default())), | |
| cache_ttl: Duration::from_secs(config.cache_ttl_secs), | |
| } | |
| } | |
| /// Search all configured providers concurrently and merge results. | |
| /// Results are cached per query for `cache_ttl`. | |
| pub async fn search(&self, query: &str, limit: usize) -> Result<Vec<ImageResult>> { | |
| let cache_key = format!("{}:{}", query.to_lowercase(), limit); | |
| // Check cache | |
| { | |
| let cache = self.cache.lock().await; | |
| if let Some(entry) = cache.entries.get(&cache_key) { | |
| if Instant::now() < entry.expires { | |
| return Ok(entry.results.clone()); | |
| } | |
| } | |
| } | |
| let mut futures: Vec< | |
| std::pin::Pin<Box<dyn std::future::Future<Output = Result<Vec<ImageResult>>> + Send>>, | |
| > = Vec::new(); | |
| if let Some(ref pixabay) = self.pixabay { | |
| let q = query.to_string(); | |
| let lim = limit; | |
| futures.push(Box::pin(async move { pixabay.search(&q, lim).await })); | |
| } | |
| if let Some(ref pexels) = self.pexels { | |
| let q = query.to_string(); | |
| let lim = limit; | |
| futures.push(Box::pin(async move { pexels.search(&q, lim).await })); | |
| } | |
| let results = join_all(futures).await; | |
| let mut merged: Vec<ImageResult> = Vec::new(); | |
| let mut seen_urls = HashSet::new(); | |
| for result in results { | |
| match result { | |
| Ok(images) => { | |
| for img in images { | |
| if seen_urls.insert(img.url.clone()) { | |
| merged.push(img); | |
| } | |
| } | |
| } | |
| Err(e) => { | |
| tracing::warn!("Image search provider error: {}", e); | |
| } | |
| } | |
| } | |
| let final_results: Vec<ImageResult> = merged.into_iter().take(limit).collect(); | |
| // Update cache | |
| { | |
| let mut cache = self.cache.lock().await; | |
| cache.entries.insert( | |
| cache_key, | |
| CacheEntry { | |
| results: final_results.clone(), | |
| expires: Instant::now() + self.cache_ttl, | |
| }, | |
| ); | |
| // Evict expired entries lazily | |
| cache.entries.retain(|_, v| Instant::now() < v.expires); | |
| } | |
| Ok(final_results) | |
| } | |
| } | |
| mod tests { | |
| use super::*; | |
| fn test_image_result_structure() { | |
| let img = ImageResult { | |
| id: "test_1".to_string(), | |
| title: "Test".to_string(), | |
| url: "https://example.com".to_string(), | |
| source: "pixabay".to_string(), | |
| photographer: Some("User".to_string()), | |
| thumbnail_url: Some("https://example.com/thumb.jpg".to_string()), | |
| width: Some(800), | |
| height: Some(600), | |
| avg_color: None, | |
| tags: vec!["test".to_string()], | |
| }; | |
| assert_eq!(img.source, "pixabay"); | |
| assert_eq!(img.width, Some(800)); | |
| } | |
| fn test_config_from_env_fallback() { | |
| // Ensure no panic when env vars are not set | |
| std::env::remove_var("PIXABAY_API_KEY"); | |
| std::env::remove_var("PEXELS_API_KEY"); | |
| let app_config = crate::config::ImageSearchConfig::default(); | |
| let config = ImageSearchConfig::from_app_config(&app_config); | |
| assert!(config.pixabay_api_key.is_none()); | |
| assert!(config.pexels_api_key.is_none()); | |
| assert_eq!(config.search_limit, 20); | |
| assert_eq!(config.cache_ttl_secs, 86400); | |
| } | |
| async fn test_rate_limiter() { | |
| // 2 tokens per second, burst of 2 | |
| let limiter = RateLimiter::new(2, 1.0); | |
| let start = Instant::now(); | |
| // First 2 should be near-instant (burst) | |
| for _ in 0..2 { | |
| limiter.acquire().await; | |
| } | |
| let elapsed = start.elapsed(); | |
| assert!( | |
| elapsed.as_millis() < 200, | |
| "First 2 burst tokens should be fast, got {}ms", | |
| elapsed.as_millis() | |
| ); | |
| // 3rd should require waiting ~500ms | |
| limiter.acquire().await; | |
| let elapsed = start.elapsed(); | |
| assert!( | |
| elapsed.as_millis() >= 300, | |
| "3rd token should require wait, got {}ms", | |
| elapsed.as_millis() | |
| ); | |
| } | |
| } | |