#![allow(dead_code)] //! Lightweight image indexing module for IntentForge v2 //! //! Zero-to-minimal bandwidth image search using: //! - Tier 0 (zero bandwidth): Context-only indexing from HTML metadata (alt, title, captions) //! - Tier 1 (minimal bandwidth): ThumbHash visual fingerprint from tiny thumbnails (~20 bytes) //! - Tier 2 (minimal bandwidth): Perceptual hash (dHash, 8 bytes) for deduplication //! //! No GPU, no heavy models, no image storage. Only metadata + tiny hashes stored. use anyhow::{Context, Result}; use regex::Regex; /// 64-bit perceptual hash for image deduplication #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct PerceptualHash(pub u64); impl PerceptualHash { pub fn distance(&self, other: &Self) -> u32 { (self.0 ^ other.0).count_ones() } pub fn to_hex(self) -> String { format!("{:016x}", self.0) } pub fn from_hex(hex: &str) -> Option { u64::from_str_radix(hex, 16).ok().map(Self) } } /// Compute difference hash (dHash) from a decoded image /// /// Resizes to 9x8 grayscale, compares adjacent pixels. /// Returns 64-bit hash in ~microseconds. pub fn compute_dhash(img: &image::DynamicImage) -> PerceptualHash { let gray = img .resize_exact(9, 8, image::imageops::FilterType::Nearest) .to_luma8(); let mut hash: u64 = 0; for y in 0..8u32 { for x in 0..8u32 { let left = gray.get_pixel(x, y).0[0]; let right = gray.get_pixel(x + 1, y).0[0]; if left > right { hash |= 1u64 << (y * 8 + x); } } } PerceptualHash(hash) } /// ThumbHash visual fingerprint (compact 20-30 byte representation) #[derive(Debug, Clone)] pub struct VisualFingerprint { pub thumbhash: Vec, pub width: u32, pub height: u32, } /// Extracted image metadata from HTML (zero bandwidth) #[derive(Debug, Clone)] pub struct ImageContext { pub url: String, pub alt_text: Option, pub title: Option, pub caption: Option, pub surrounding_text: Option, pub filename_keywords: Vec, } impl ImageContext { /// Build a combined text representation for embedding pub fn to_searchable_text(&self) -> String { let mut parts = Vec::new(); if let Some(alt) = &self.alt_text { let trimmed = alt.trim(); if !trimmed.is_empty() { parts.push(trimmed.to_string()); } } if let Some(title) = &self.title { let trimmed = title.trim(); if !trimmed.is_empty() && !parts.iter().any(|p| p == trimmed) { parts.push(trimmed.to_string()); } } if let Some(caption) = &self.caption { let trimmed = caption.trim(); if !trimmed.is_empty() { parts.push(trimmed.to_string()); } } if let Some(ctx) = &self.surrounding_text { let trimmed = ctx.trim(); if !trimmed.is_empty() && trimmed.len() > 10 { parts.push(trimmed.to_string()); } } if !self.filename_keywords.is_empty() { parts.push(self.filename_keywords.join(" ")); } parts.join(" ") } /// Whether this context has enough text to be useful pub fn has_meaningful_context(&self) -> bool { self.alt_text.as_ref().is_some_and(|t| t.trim().len() > 3) || self.caption.as_ref().is_some_and(|t| t.trim().len() > 10) || self .surrounding_text .as_ref() .is_some_and(|t| t.trim().len() > 20) || self.filename_keywords.len() >= 2 } } /// Extract image contexts from HTML (zero bandwidth - no image download) /// /// Parses `` tags and extracts: /// - `alt` attribute /// - `title` attribute /// - `
` if inside `
` /// - Surrounding `

` text /// - Semantic keywords from the filename/URL pub fn extract_image_contexts(html: &str, page_url: &str) -> Vec { let mut contexts = Vec::new(); // Extract full tags let img_re = match Regex::new(r#"]+>"#) { Ok(re) => re, Err(_) => return contexts, }; let src_re = Regex::new(r#"src=["']([^"']+)["']"#).unwrap(); let alt_re = Regex::new(r#"alt=["']([^"']*)["']"#).unwrap(); let title_re = Regex::new(r#"title=["']([^"']*)["']"#).unwrap(); for cap in img_re.captures_iter(html) { let tag = cap.get(0).map(|m| m.as_str()).unwrap_or(""); let url = match src_re.captures(tag) { Some(c) => c.get(1).map(|m| m.as_str()).unwrap_or(""), None => continue, }; // Skip data URIs, tracking pixels, SVGs if url.starts_with("data:") || url.contains("1x1") || url.contains("pixel") || url.contains("tracking") || url.ends_with(".svg") { continue; } let resolved = resolve_url(url, page_url); if !is_likely_image_url(&resolved) { continue; } let alt_text = alt_re.captures(tag).and_then(|c| { let val = c.get(1)?.as_str().to_string(); if val.is_empty() { None } else { Some(val) } }); let title = title_re.captures(tag).and_then(|c| { let val = c.get(1)?.as_str().to_string(); if val.is_empty() { None } else { Some(val) } }); let filename_keywords = extract_url_keywords(&resolved); contexts.push(ImageContext { url: resolved, alt_text, title, caption: None, surrounding_text: None, filename_keywords, }); } // Try to match

text to nearby images let figcaption_re = Regex::new( r#"(?s)]*>.*?]+src=["']([^"']+)["'][^>]*>.*?]*>(.*?)
.*?
"#, ) .unwrap(); for cap in figcaption_re.captures_iter(html) { let url = cap.get(1).map(|m| m.as_str()).unwrap_or(""); let caption_html = cap.get(2).map(|m| m.as_str()).unwrap_or(""); let caption = strip_tags(caption_html); let resolved = resolve_url(url, page_url); for ctx in &mut contexts { if ctx.url == resolved { ctx.caption = Some(caption.clone()); } } } // Deduplicate by URL contexts.sort_by(|a, b| a.url.cmp(&b.url)); contexts.dedup_by(|a, b| a.url == b.url); contexts } /// Generate ThumbHash from image bytes (downloads only thumbnail-sized data) /// /// The image is resized to max 100px before hashing to minimize bandwidth. /// Returns ~20-30 bytes that can reconstruct a blurry preview. pub fn generate_thumbhash(img: &image::DynamicImage) -> Vec { // Resize to tiny for ThumbHash (max 100px on longest side) let max_dim = img.width().max(img.height()); let resized = if max_dim > 100 { let scale = 100.0 / max_dim as f32; let new_w = (img.width() as f32 * scale) as u32; let new_h = (img.height() as f32 * scale) as u32; img.resize_exact(new_w, new_h, image::imageops::FilterType::Triangle) } else { img.clone() }; let rgba = resized.to_rgba8(); let w = rgba.width() as usize; let h = rgba.height() as usize; let pixels: Vec = rgba.into_raw(); thumbhash::rgba_to_thumb_hash(w, h, &pixels) } /// Download a tiny thumbnail for visual fingerprinting (minimal bandwidth) /// /// Downloads only the first ~10KB of the image, enough for a ThumbHash. pub async fn download_tiny_thumbnail( client: &reqwest::Client, url: &str, ) -> Result { let response = client .get(url) .header("Range", "bytes=0-10239") .timeout(std::time::Duration::from_secs(5)) .send() .await .with_context(|| format!("Failed to download thumbnail from {}", url))?; if !response.status().is_success() && response.status().as_u16() != 206 { anyhow::bail!( "Thumbnail download failed with status {} for {}", response.status(), url ); } let bytes = response .bytes() .await .with_context(|| format!("Failed to read thumbnail bytes from {}", url))?; let img = image::load_from_memory(&bytes) .with_context(|| format!("Failed to decode thumbnail from {}", url))?; Ok(img) } /// Batch process images: extract context + optional visual fingerprint pub struct ProcessedImage { pub context: ImageContext, pub dhash: Option, pub thumbhash: Option>, pub dimensions: Option<(u32, u32)>, } /// Resolve a potentially relative URL against a base fn resolve_url(url: &str, base_url: &str) -> String { if url.starts_with("http://") || url.starts_with("https://") { url.to_string() } else if url.starts_with("//") { format!("https:{}", url) } else if let Ok(base) = url::Url::parse(base_url) { if let Ok(resolved) = base.join(url) { resolved.to_string() } else { url.to_string() } } else { url.to_string() } } /// Check if a URL looks like an image fn is_likely_image_url(url: &str) -> bool { let lower = url.to_lowercase(); lower.ends_with(".jpg") || lower.ends_with(".jpeg") || lower.ends_with(".png") || lower.ends_with(".webp") || lower.ends_with(".gif") || lower.ends_with(".avif") || lower.contains("/image") || lower.contains("/img") || lower.contains("/photo") || lower.contains("/thumb") || lower.contains("cdn") } /// Extract semantic keywords from an image URL/filename fn extract_url_keywords(url: &str) -> Vec { // Get the filename part let path = url.split('/').next_back().unwrap_or(url); // Remove query strings and fragments let path = path.split('?').next().unwrap_or(path); let path = path.split('#').next().unwrap_or(path); // Split on common delimiters and filter let keywords: Vec = path .split(|c: char| !c.is_alphanumeric()) .filter(|s| s.len() > 2) .filter(|s| { let lower = s.to_lowercase(); // Skip common non-semantic parts !matches!( lower.as_str(), "jpg" | "jpeg" | "png" | "webp" | "gif" | "avif" | "img" | "image" | "http" | "https" | "www" | "com" | "org" | "net" | "cdn" | "uploads" | "media" | "static" | "assets" | "wp" | "content" ) }) .map(|s| s.to_lowercase()) .collect(); keywords } /// Strip HTML tags from text fn strip_tags(html: &str) -> String { let re = Regex::new(r"<[^>]+>").unwrap(); re.replace_all(html, " ").trim().to_string() } #[cfg(test)] mod tests { use super::*; #[test] fn test_extract_image_contexts_basic() { let html = r#" A sunset over mountains inline "#; let contexts = extract_image_contexts(html, "https://example.com/page"); assert_eq!(contexts.len(), 2); // Contexts are sorted by URL let photo_ctx = contexts .iter() .find(|c| c.url.contains("photo.jpg")) .unwrap(); assert_eq!( photo_ctx.alt_text, Some("A sunset over mountains".to_string()) ); let logo_ctx = contexts .iter() .find(|c| c.url.contains("logo.png")) .unwrap(); assert_eq!(logo_ctx.title, Some("Site Logo".to_string())); // Data URI excluded assert!(!contexts.iter().any(|c| c.url.starts_with("data:"))); } #[test] fn test_extract_image_contexts_figure() { let html = r#"
Sales chart
Q4 2025 Revenue Growth
"#; let contexts = extract_image_contexts(html, "https://example.com"); assert_eq!(contexts.len(), 1); assert_eq!( contexts[0].caption, Some("Q4 2025 Revenue Growth".to_string()) ); } #[test] fn test_extract_image_contexts_relative_url() { let html = r#"Hero"#; let contexts = extract_image_contexts(html, "https://blog.example.com/post/1"); assert_eq!(contexts.len(), 1); assert_eq!(contexts[0].url, "https://blog.example.com/images/hero.jpg"); } #[test] fn test_extract_url_keywords() { let keywords = extract_url_keywords( "https://cdn.example.com/uploads/2025/ai-generated-sunset-over-ocean.jpg", ); // "ai" is only 2 chars, filtered by len > 2 check assert!(!keywords.contains(&"ai".to_string())); assert!(keywords.contains(&"generated".to_string())); assert!(keywords.contains(&"sunset".to_string())); assert!(keywords.contains(&"ocean".to_string())); // File extension should be filtered assert!(!keywords.contains(&"jpg".to_string())); } #[test] fn test_image_context_to_searchable_text() { let ctx = ImageContext { url: "https://example.com/photo.jpg".to_string(), alt_text: Some("A beautiful sunset".to_string()), title: Some("Sunset Photo".to_string()), caption: Some("Taken in Hawaii, 2025".to_string()), surrounding_text: None, filename_keywords: vec!["sunset".into(), "hawaii".into()], }; let text = ctx.to_searchable_text(); assert!(text.contains("A beautiful sunset")); assert!(text.contains("Taken in Hawaii, 2025")); assert!(text.contains("sunset hawaii")); } #[test] fn test_image_context_dedup_alt_title() { let ctx = ImageContext { url: "https://example.com/photo.jpg".to_string(), alt_text: Some("Sunset".to_string()), title: Some("Sunset".to_string()), // same as alt caption: None, surrounding_text: None, filename_keywords: Vec::new(), }; let text = ctx.to_searchable_text(); // Should not duplicate "Sunset" assert_eq!(text.matches("Sunset").count(), 1); } #[test] fn test_has_meaningful_context() { let empty = ImageContext { url: "img.jpg".to_string(), alt_text: Some("ab".into()), // too short title: None, caption: None, surrounding_text: None, filename_keywords: Vec::new(), }; assert!(!empty.has_meaningful_context()); let with_alt = ImageContext { url: "img.jpg".to_string(), alt_text: Some("A dog playing in the park".into()), title: None, caption: None, surrounding_text: None, filename_keywords: Vec::new(), }; assert!(with_alt.has_meaningful_context()); } #[test] fn test_perceptual_hash_hex_roundtrip() { let hash = PerceptualHash(0xDEADBEEFCAFEBABE); let hex = hash.to_hex(); let parsed = PerceptualHash::from_hex(&hex).unwrap(); assert_eq!(hash, parsed); } #[test] fn test_perceptual_hash_distance() { let a = PerceptualHash(0xFFFFFFFFFFFFFFFF); let b = PerceptualHash(0x0000000000000000); assert_eq!(a.distance(&b), 64); let c = PerceptualHash(0xFFFFFFFFFFFFFFF0); assert_eq!(a.distance(&c), 4); } #[test] fn test_dhash_deterministic() { let img = image::RgbImage::from_fn(100, 100, |x, y| { let v = ((x + y) * 255 / 200).min(255) as u8; image::Rgb([v, v, v]) }); let dynamic = image::DynamicImage::ImageRgb8(img); let h1 = compute_dhash(&dynamic); let h2 = compute_dhash(&dynamic); assert_eq!(h1, h2); } #[test] fn test_dhash_different_images() { // Left half dark, right half bright - creates a gradient let left_dark = image::DynamicImage::ImageRgb8(image::RgbImage::from_fn(100, 100, |x, _| { if x < 50 { image::Rgb([0u8, 0, 0]) } else { image::Rgb([255u8, 255, 255]) } })); // Left half bright, right half dark - opposite gradient let right_dark = image::DynamicImage::ImageRgb8(image::RgbImage::from_fn(100, 100, |x, _| { if x < 50 { image::Rgb([255u8, 255, 255]) } else { image::Rgb([0u8, 0, 0]) } })); let h1 = compute_dhash(&left_dark); let h2 = compute_dhash(&right_dark); assert_ne!(h1, h2); } #[test] fn test_is_likely_image_url() { assert!(is_likely_image_url("https://example.com/photo.jpg")); assert!(is_likely_image_url("https://cdn.example.com/img/hero.png")); assert!(is_likely_image_url("https://example.com/image/123")); assert!(!is_likely_image_url("https://example.com/page.html")); assert!(!is_likely_image_url("https://example.com/script.js")); } #[test] fn test_extract_tracking_pixels_excluded() { let html = r#" A real photo "#; let contexts = extract_image_contexts(html, "https://example.com"); assert_eq!(contexts.len(), 1); assert_eq!(contexts[0].url, "https://example.com/real-photo.jpg"); } }