Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523const fs = require('fs-extra');const path = require('path');const crypto = require('crypto');const Database = require('better-sqlite3');const imghash = require('imghash');const config = require('../config');
/** * ImageHashManager - Manages perceptual hashing of images and stores them in a database * This helps detect duplicate or similar images across different URLs */class ImageHashManager { constructor() { // Database path const dbDir = path.join(__dirname, '..', 'data'); this.dbPath = path.join(dbDir, 'image_hashes.db'); this.perceptualHashBits = this.getPerceptualHashBits(); // Initialize database this.initDatabase(); }
/** * Resolve configured perceptual hash bit length * @returns {number} */ getPerceptualHashBits() { const configuredBits = config.imageHash && Number.isInteger(config.imageHash.perceptualHashBits) ? config.imageHash.perceptualHashBits : 16;
// Keep this conservative: even number and within a practical range for imghash. if (configuredBits < 8 || configuredBits > 32 || configuredBits % 2 !== 0) { return 16; }
return configuredBits; }
/** * Initialize the SQLite database and create tables if they don't exist */ initDatabase() { try { // Ensure data directory exists (synchronously) fs.ensureDirSync(path.dirname(this.dbPath)); // Open database connection this.db = new Database(this.dbPath); // Create tables this.db.exec(` CREATE TABLE IF NOT EXISTS image_hashes ( id INTEGER PRIMARY KEY AUTOINCREMENT, url TEXT NOT NULL, perceptual_hash TEXT NOT NULL, content_hash TEXT, file_path TEXT, cached_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, metadata TEXT, alternate_urls TEXT, UNIQUE(url) ); CREATE INDEX IF NOT EXISTS idx_perceptual_hash ON image_hashes(perceptual_hash); CREATE INDEX IF NOT EXISTS idx_url ON image_hashes(url); `);
// Backward-compat: add content_hash when upgrading existing databases. const columns = this.db.prepare('PRAGMA table_info(image_hashes)').all(); const hasContentHash = columns.some(col => col.name === 'content_hash'); if (!hasContentHash) { this.db.exec('ALTER TABLE image_hashes ADD COLUMN content_hash TEXT'); }
// Create this after migration check to avoid failures on older DBs. this.db.exec('CREATE INDEX IF NOT EXISTS idx_content_hash ON image_hashes(content_hash)'); console.log('[ImageHash] Image hash database initialized'); } catch (error) { console.error('[ImageHash] Error initializing image hash database:', error); throw error; } }
/** * Calculate perceptual hash for an image file * @param {string} filePath - Path to the image file * @returns {Promise<string>} - Perceptual hash string */ async calculateHash(filePath) { try { // Use imghash to generate a perceptual hash // This creates a hash that is similar for similar-looking images const hash = await imghash.hash(filePath, this.perceptualHashBits, 'hex'); return hash; } catch (error) { console.error(`Error calculating hash for ${filePath}:`, error); throw error; } }
/** * Calculate strong content hash for exact image identity checks * @param {string} filePath - Path to image file * @returns {Promise<string>} - SHA256 hash string */ async calculateContentHash(filePath) { try { const hash = crypto.createHash('sha256');
return await new Promise((resolve, reject) => { const stream = fs.createReadStream(filePath); stream.on('error', reject); stream.on('data', chunk => hash.update(chunk)); stream.on('end', () => resolve(hash.digest('hex'))); }); } catch (error) { console.error(`Error calculating content hash for ${filePath}:`, error); throw error; } }
/** * Store image hash in the database * @param {string} url - Original URL of the image * @param {string} hash - Perceptual hash of the image * @param {string} filePath - Path to cached file * @param {Object} metadata - Optional metadata to store * @returns {boolean} - Whether the operation was successful */ storeHash(url, hash, filePath, metadata = null, contentHash = null) { try { const stmt = this.db.prepare(` INSERT INTO image_hashes (url, perceptual_hash, content_hash, file_path, metadata) VALUES (?, ?, ?, ?, ?) ON CONFLICT(url) DO UPDATE SET perceptual_hash = excluded.perceptual_hash, content_hash = excluded.content_hash, file_path = excluded.file_path, cached_at = CURRENT_TIMESTAMP, metadata = excluded.metadata `); const metadataJson = metadata ? JSON.stringify(metadata) : null; stmt.run(url, hash, contentHash, filePath, metadataJson); console.log(`Stored hash for URL: ${url.substring(0, 50)}...`); return true; } catch (error) { console.error('Error storing image hash:', error); return false; } }
/** * Process an image file and store its hash * @param {string} url - Original URL of the image * @param {string} filePath - Path to the cached image file * @param {Object} metadata - Optional metadata to store * @returns {Promise<{hash: string, stored: boolean, isDuplicate: boolean}>} */ async processImage(url, filePath, metadata = null) { try { // Check if file exists if (!await fs.pathExists(filePath)) { throw new Error(`File not found: ${filePath}`); } // Calculate perceptual hash const hash = await this.calculateHash(filePath); const contentHash = await this.calculateContentHash(filePath); // Check if this URL already exists const existingByUrl = this.getHashByUrl(url); if (existingByUrl) { console.log(`URL already in database: ${url.substring(0, 50)}...`); return { hash, stored: true, isDuplicate: false }; } // Exact duplicate check: only treat as duplicate when binary content matches. const existingByContentHash = this.getHashByContentHash(contentHash); if (existingByContentHash) { // Same image, different URL - add as alternate URL console.log(`Found exact duplicate image with content hash ${contentHash.substring(0, 12)}..., adding alternate URL`); const added = this.addAlternateUrl(existingByContentHash.url, url); return { hash, stored: added, isDuplicate: true, primaryUrl: existingByContentHash.url }; } // New image - store in database const stored = this.storeHash(url, hash, filePath, metadata, contentHash); return { hash, stored, isDuplicate: false }; } catch (error) { console.error(`Error processing image ${url}:`, error); throw error; } }
/** * Get hash for a specific URL * @param {string} url - URL to look up * @returns {Object|null} - Hash data or null if not found */ getHashByUrl(url) { try { const stmt = this.db.prepare(` SELECT * FROM image_hashes WHERE url = ? `); const result = stmt.get(url); if (result) { if (result.metadata) { result.metadata = JSON.parse(result.metadata); } if (result.alternate_urls) { result.alternate_urls = JSON.parse(result.alternate_urls); } } return result; } catch (error) { console.error('Error getting hash by URL:', error); return null; } }
/** * Get hash record by perceptual hash value * @param {string} hash - Perceptual hash to look up * @returns {Object|null} - Hash data or null if not found */ getHashByHash(hash) { try { const stmt = this.db.prepare(` SELECT * FROM image_hashes WHERE perceptual_hash = ? `); const result = stmt.get(hash); if (result) { if (result.metadata) { result.metadata = JSON.parse(result.metadata); } if (result.alternate_urls) { result.alternate_urls = JSON.parse(result.alternate_urls); } } return result; } catch (error) { console.error('Error getting hash by hash value:', error); return null; } }
/** * Get all records by perceptual hash value * @param {string} hash - Perceptual hash to look up * @returns {Array} - Hash records (possibly empty) */ getHashesByHash(hash) { try { const stmt = this.db.prepare(` SELECT * FROM image_hashes WHERE perceptual_hash = ? ORDER BY cached_at DESC `);
const results = stmt.all(hash);
return results.map(result => { if (result.metadata) { result.metadata = JSON.parse(result.metadata); } if (result.alternate_urls) { result.alternate_urls = JSON.parse(result.alternate_urls); } return result; }); } catch (error) { console.error('Error getting hashes by hash value:', error); return []; } }
/** * Get hash record by content hash value * @param {string} contentHash - SHA256 content hash to look up * @returns {Object|null} - Hash data or null if not found */ getHashByContentHash(contentHash) { try { const stmt = this.db.prepare(` SELECT * FROM image_hashes WHERE content_hash = ? `);
const result = stmt.get(contentHash);
if (result) { if (result.metadata) { result.metadata = JSON.parse(result.metadata); } if (result.alternate_urls) { result.alternate_urls = JSON.parse(result.alternate_urls); } }
return result; } catch (error) { console.error('Error getting hash by content hash value:', error); return null; } }
/** * Add an alternate URL to an existing hash record * @param {string} primaryUrl - The primary URL of the existing record * @param {string} newUrl - The new URL to add as an alternate * @returns {boolean} - Whether the operation was successful */ addAlternateUrl(primaryUrl, newUrl) { try { // Get existing record const existing = this.getHashByUrl(primaryUrl); if (!existing) { console.error(`Primary URL not found: ${primaryUrl}`); return false; } // Parse existing alternate URLs or create new array let alternateUrls = existing.alternate_urls || []; // Check if this URL is already in alternates or is the primary if (newUrl === primaryUrl || alternateUrls.includes(newUrl)) { console.log(`URL already tracked: ${newUrl.substring(0, 50)}...`); return true; } // Add new URL to alternates alternateUrls.push(newUrl); // Update database const stmt = this.db.prepare(` UPDATE image_hashes SET alternate_urls = ? WHERE url = ? `); stmt.run(JSON.stringify(alternateUrls), primaryUrl); console.log(`Added alternate URL to ${primaryUrl.substring(0, 50)}...`); console.log(` -> ${newUrl.substring(0, 50)}...`); return true; } catch (error) { console.error('Error adding alternate URL:', error); return false; } }
/** * Find similar images by comparing perceptual hashes * @param {string} hash - Perceptual hash to compare * @param {number} maxDistance - Maximum hamming distance for similarity (default: 5) * @returns {Array} - Array of similar images */ findSimilarImages(hash, maxDistance = 5) { try { const stmt = this.db.prepare(` SELECT * FROM image_hashes `); const allHashes = stmt.all(); const similar = []; // Calculate hamming distance for each hash for (const record of allHashes) { const distance = this.hammingDistance(hash, record.perceptual_hash); if (distance <= maxDistance) { similar.push({ ...record, distance, metadata: record.metadata ? JSON.parse(record.metadata) : null }); } } // Sort by distance (most similar first) similar.sort((a, b) => a.distance - b.distance); return similar; } catch (error) { console.error('Error finding similar images:', error); return []; } }
/** * Calculate hamming distance between two hash strings * @param {string} hash1 - First hash * @param {string} hash2 - Second hash * @returns {number} - Hamming distance */ hammingDistance(hash1, hash2) { if (!hash1 || !hash2 || hash1.length !== hash2.length) { return Infinity; } let distance = 0; for (let i = 0; i < hash1.length; i++) { if (hash1[i] !== hash2[i]) { distance++; } } return distance; }
/** * Get all stored hashes * @param {number} limit - Maximum number of results (optional) * @returns {Array} - Array of hash records */ getAllHashes(limit = null) { try { let query = 'SELECT * FROM image_hashes ORDER BY cached_at DESC'; if (limit) { query += ` LIMIT ${limit}`; } const stmt = this.db.prepare(query); const results = stmt.all(); return results.map(record => ({ ...record, metadata: record.metadata ? JSON.parse(record.metadata) : null, alternate_urls: record.alternate_urls ? JSON.parse(record.alternate_urls) : [] })); } catch (error) { console.error('Error getting all hashes:', error); return []; } }
/** * Delete a hash record by URL * @param {string} url - URL to delete * @returns {boolean} - Whether deletion was successful */ deleteHashByUrl(url) { try { const stmt = this.db.prepare('DELETE FROM image_hashes WHERE url = ?'); const result = stmt.run(url); return result.changes > 0; } catch (error) { console.error('Error deleting hash:', error); return false; } }
/** * Clean up hash records for files that no longer exist * @returns {Promise<number>} - Number of records cleaned up */ async cleanupOrphanedHashes() { try { const allHashes = this.getAllHashes(); let cleaned = 0; for (const record of allHashes) { if (record.file_path && !await fs.pathExists(record.file_path)) { if (this.deleteHashByUrl(record.url)) { cleaned++; } } } console.log(`[ImageHash] Cleaned up ${cleaned} orphaned hash records`); return cleaned; } catch (error) { console.error('[ImageHash] Error cleaning up orphaned hashes:', error); return 0; } }
/** * Get statistics about the hash database * @returns {Object} - Database statistics */ getStats() { try { const totalStmt = this.db.prepare('SELECT COUNT(*) as count FROM image_hashes'); const total = totalStmt.get().count; const recentStmt = this.db.prepare(` SELECT COUNT(*) as count FROM image_hashes WHERE cached_at > datetime('now', '-7 days') `); const recentWeek = recentStmt.get().count; return { totalImages: total, imagesLastWeek: recentWeek, databasePath: this.dbPath }; } catch (error) { console.error('Error getting stats:', error); return null; } }
/** * Close the database connection */ close() { if (this.db) { this.db.close(); console.log('Image hash database connection closed'); } }}
module.exports = ImageHashManager;