Spaces:
Build error
Build error
File size: 18,806 Bytes
0ca462b | 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 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 | #![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<Self> {
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<u8>,
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<String>,
pub title: Option<String>,
pub caption: Option<String>,
pub surrounding_text: Option<String>,
pub filename_keywords: Vec<String>,
}
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 `<img>` tags and extracts:
/// - `alt` attribute
/// - `title` attribute
/// - `<figcaption>` if inside `<figure>`
/// - Surrounding `<p>` text
/// - Semantic keywords from the filename/URL
pub fn extract_image_contexts(html: &str, page_url: &str) -> Vec<ImageContext> {
let mut contexts = Vec::new();
// Extract full <img> tags
let img_re = match Regex::new(r#"<img[^>]+>"#) {
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 <figcaption> text to nearby images
let figcaption_re = Regex::new(
r#"(?s)<figure[^>]*>.*?<img[^>]+src=["']([^"']+)["'][^>]*>.*?<figcaption[^>]*>(.*?)</figcaption>.*?</figure>"#,
)
.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<u8> {
// 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<u8> = 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<image::DynamicImage> {
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<PerceptualHash>,
pub thumbhash: Option<Vec<u8>>,
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<String> {
// 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<String> = 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#"
<html><body>
<img src="https://example.com/photo.jpg" alt="A sunset over mountains" />
<img src="https://example.com/logo.png" title="Site Logo" />
<img src="data:image/png;base64,abc" alt="inline" />
</body></html>
"#;
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#"
<figure>
<img src="https://example.com/chart.png" alt="Sales chart" />
<figcaption>Q4 2025 Revenue Growth</figcaption>
</figure>
"#;
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#"<img src="/images/hero.jpg" alt="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#"
<img src="https://example.com/1x1.png" alt="" />
<img src="https://example.com/pixel.gif" alt="" />
<img src="https://example.com/tracking.jpg" alt="" />
<img src="https://example.com/real-photo.jpg" alt="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");
}
}
|