""" Cache Manager - Persistent Storage for Face Recognition Cache Manages persistent storage of embeddings and cache across rebuilds Thread-safe for concurrent access in multi-user environments Storage Backends: - Local File System (default) - Hugging Face Dataset (for HF Spaces deployment) """ import os import json import pickle import hashlib import time from datetime import datetime from typing import Dict, Any, Optional, List import shutil from threading import Lock, RLock # Check if we should use HF Dataset storage (for HF Spaces) USE_HF_DATASET = os.getenv("USE_HF_DATASET", "0") == "1" if USE_HF_DATASET: try: from hf_dataset_storage import HFDatasetStorage HF_STORAGE_AVAILABLE = True print("📦 HF Dataset storage enabled!") except ImportError: HF_STORAGE_AVAILABLE = False print("⚠️ HF Dataset storage not available, using local storage") else: HF_STORAGE_AVAILABLE = False print("📁 Using local file system storage") # Conditional imports for file locking (platform-specific) try: import fcntl # For file locking on Unix/Linux/Mac FCNTL_AVAILABLE = True except ImportError: FCNTL_AVAILABLE = False try: import msvcrt # For file locking on Windows MSVCRT_AVAILABLE = True except ImportError: MSVCRT_AVAILABLE = False class CacheManager: """Manages persistent cache storage for face recognition embeddings - Thread-safe""" def __init__(self, cache_dir="persistent_cache"): self.cache_dir = cache_dir self.metadata_file = os.path.join(cache_dir, "cache_metadata.json") # Thread-safe locks for concurrent access self._file_lock = RLock() # Reentrant lock for same-thread re-entry self._metadata_lock = Lock() # Separate lock for metadata operations # Initialize HF Dataset storage if enabled if USE_HF_DATASET and HF_STORAGE_AVAILABLE: try: self.hf_storage = HFDatasetStorage() self.use_hf_storage = True print(f"✅ HF Dataset storage initialized: {self.hf_storage.dataset_repo}") except Exception as e: print(f"⚠️ Failed to initialize HF storage: {e}") self.hf_storage = None self.use_hf_storage = False else: self.hf_storage = None self.use_hf_storage = False # Create cache directory if not exists os.makedirs(cache_dir, exist_ok=True) # Initialize metadata self.metadata = self._load_metadata() def _load_metadata(self) -> Dict: """Load cache metadata with file locking""" with self._metadata_lock: if os.path.exists(self.metadata_file): try: # Use file locking to prevent concurrent read/write issues with open(self.metadata_file, 'r', encoding='utf-8') as f: self._lock_file(f, shared=True) # Shared lock for reading data = json.load(f) self._unlock_file(f) return data except Exception as e: print(f"⚠️ Error loading metadata: {e}, using default") return self._create_default_metadata() return self._create_default_metadata() def _create_default_metadata(self) -> Dict: """Create default metadata structure""" return { "version": "1.0", "created_at": datetime.now().isoformat(), "caches": {}, "last_modified": datetime.now().isoformat() } def _save_metadata(self): """Save metadata to file with exclusive locking""" with self._metadata_lock: self.metadata["last_modified"] = datetime.now().isoformat() # Write to temporary file first, then rename (atomic operation) temp_file = self.metadata_file + ".tmp" try: with open(temp_file, 'w', encoding='utf-8') as f: self._lock_file(f, shared=False) # Exclusive lock for writing json.dump(self.metadata, f, indent=2, ensure_ascii=False) f.flush() os.fsync(f.fileno()) # Ensure data is written to disk self._unlock_file(f) # Atomic rename if os.path.exists(self.metadata_file): os.replace(temp_file, self.metadata_file) else: os.rename(temp_file, self.metadata_file) except Exception as e: print(f"⚠️ Error saving metadata: {e}") if os.path.exists(temp_file): try: os.remove(temp_file) except: pass raise def _lock_file(self, file_obj, shared=False): """Cross-platform file locking with fallback""" # Check if file locking is available if not FCNTL_AVAILABLE and not MSVCRT_AVAILABLE: # No file locking available - skip (best effort) return try: if os.name == 'nt' and MSVCRT_AVAILABLE: # Windows # Windows file locking mode = msvcrt.LK_NBLCK if not shared else msvcrt.LK_NBRLCK msvcrt.locking(file_obj.fileno(), mode, 1) elif FCNTL_AVAILABLE: # Unix/Linux/Mac # Unix file locking mode = fcntl.LOCK_EX if not shared else fcntl.LOCK_SH fcntl.flock(file_obj.fileno(), mode | fcntl.LOCK_NB) except (IOError, OSError): # Lock failed, retry after short delay time.sleep(0.1) try: if os.name == 'nt' and MSVCRT_AVAILABLE: msvcrt.locking(file_obj.fileno(), mode, 1) elif FCNTL_AVAILABLE: fcntl.flock(file_obj.fileno(), mode) except: pass # Best effort locking def _unlock_file(self, file_obj): """Cross-platform file unlocking with fallback""" # Check if file locking is available if not FCNTL_AVAILABLE and not MSVCRT_AVAILABLE: return try: if os.name == 'nt' and MSVCRT_AVAILABLE: # Windows msvcrt.locking(file_obj.fileno(), msvcrt.LK_UNLCK, 1) elif FCNTL_AVAILABLE: # Unix/Linux/Mac fcntl.flock(file_obj.fileno(), fcntl.LOCK_UN) except: pass # Best effort unlocking def _get_cache_key(self, mode: str, dataset_hash: str) -> str: """Generate unique cache key""" return f"{mode}_{dataset_hash}" def _compute_dataset_hash(self) -> str: """Compute hash of current dataset""" try: with open('students_data.json', 'r', encoding='utf-8') as f: data = json.load(f) # Create hash from student data data_str = json.dumps(data, sort_keys=True) return hashlib.md5(data_str.encode()).hexdigest()[:16] except: return "unknown" def save_cache(self, mode: str, embeddings_data: Any, extra_info: Dict = None, is_incremental: bool = False): """ Save embeddings cache to persistent storage (thread-safe) Supports INCREMENTAL SAVING for progressive updates Auto-detects storage backend (HF Dataset or local file) Args: mode: Recognition mode (standard, accurate, hardmode, extreme) embeddings_data: The embeddings dictionary to cache extra_info: Additional information about the cache is_incremental: If True, this is an incremental save (won't update 'created_at') """ # Use HF Dataset storage if enabled if self.use_hf_storage: try: print(f"💾 Saving cache to HF Dataset...") success, msg = self.hf_storage.save_cache(mode, embeddings_data, extra_info) if success: # Update local metadata for tracking num_embeddings = len(embeddings_data) if isinstance(embeddings_data, dict) else 0 if is_incremental and mode in self.metadata["caches"]: created_at = self.metadata["caches"][mode].get("created_at", datetime.now().isoformat()) else: created_at = datetime.now().isoformat() self.metadata["caches"][mode] = { "storage": "hf_dataset", "dataset_repo": self.hf_storage.dataset_repo, "created_at": created_at, "last_updated": datetime.now().isoformat(), "num_embeddings": num_embeddings, "is_complete": not is_incremental, "extra_info": extra_info or {} } self._save_metadata() print(f"✅ {msg}") return success, msg except Exception as e: print(f"⚠️ HF Dataset save failed, trying local fallback: {e}") # Continue to local storage fallback # Local file storage (original implementation) with self._file_lock: try: dataset_hash = self._compute_dataset_hash() cache_key = self._get_cache_key(mode, dataset_hash) cache_file = os.path.join(self.cache_dir, f"{cache_key}.pkl") # Write to temporary file first temp_cache_file = cache_file + ".tmp" # Save embeddings using pickle with open(temp_cache_file, 'wb') as f: pickle.dump(embeddings_data, f, protocol=pickle.HIGHEST_PROTOCOL) f.flush() os.fsync(f.fileno()) # Atomic rename if os.path.exists(cache_file): os.replace(temp_cache_file, cache_file) else: os.rename(temp_cache_file, cache_file) # Update metadata file_size = os.path.getsize(cache_file) / (1024 * 1024) num_embeddings = len(embeddings_data) if isinstance(embeddings_data, dict) else 0 # For incremental saves, preserve creation time if is_incremental and mode in self.metadata["caches"]: created_at = self.metadata["caches"][mode].get("created_at", datetime.now().isoformat()) else: created_at = datetime.now().isoformat() self.metadata["caches"][mode] = { "cache_key": cache_key, "cache_file": cache_file, "dataset_hash": dataset_hash, "created_at": created_at, "last_updated": datetime.now().isoformat(), "size_mb": file_size, "num_embeddings": num_embeddings, "extra_info": extra_info or {}, "is_complete": not is_incremental # Track if this is a complete cache } self._save_metadata() save_type = "incrementally" if is_incremental else "completely" return True, f"Cache saved {save_type}: {cache_key} ({num_embeddings} embeddings, {file_size:.2f}MB)" except Exception as e: # Cleanup temporary file if 'temp_cache_file' in locals() and os.path.exists(temp_cache_file): try: os.remove(temp_cache_file) except: pass return False, f"Error saving cache: {str(e)}" def load_cache(self, mode: str, ignore_hash_check: bool = False) -> tuple[bool, Any, str]: """ Load embeddings cache from persistent storage (thread-safe) Auto-detects storage backend (HF Dataset or local file) Args: mode: Recognition mode (standard, accurate, hardmode, extreme) ignore_hash_check: If True, skip dataset hash validation (useful for recovery) Returns: (success, embeddings_data, message) """ # Try HF Dataset storage first if enabled if self.use_hf_storage: try: print(f"📥 Loading cache from HF Dataset...") success, cache_data, msg = self.hf_storage.load_cache(mode) if success: print(f"✅ {msg}") return True, cache_data, msg else: print(f"⚠️ HF Dataset load failed: {msg}") print(f" Trying local storage fallback...") except Exception as e: print(f"⚠️ HF Dataset load error: {e}") print(f" Trying local storage fallback...") # Local file storage (original implementation) with self._file_lock: try: # Reload metadata to get latest state self.metadata = self._load_metadata() print(f"📂 Loading cache from local storage for mode: {mode}") print(f" Available cache modes: {list(self.metadata['caches'].keys())}") if mode not in self.metadata["caches"]: print(f" ❌ No cache metadata found for mode: {mode}") return False, None, f"No cache found for mode: {mode}" cache_info = self.metadata["caches"][mode] cache_file = cache_info["cache_file"] print(f" Cache file: {cache_file}") print(f" File exists: {os.path.exists(cache_file)}") if not os.path.exists(cache_file): print(f" ❌ Cache file not found on disk") return False, None, f"Cache file not found: {cache_file}" # Check if dataset has changed (optional) if not ignore_hash_check: current_hash = self._compute_dataset_hash() cached_hash = cache_info["dataset_hash"] print(f" Current hash: {current_hash}") print(f" Cached hash: {cached_hash}") if cached_hash != current_hash: print(f" ⚠️ Dataset hash mismatch - cache may be outdated") # Don't fail, just warn # return False, None, "Dataset has changed, cache is outdated" # Load embeddings with retry logic max_retries = 3 for attempt in range(max_retries): try: with open(cache_file, 'rb') as f: embeddings_data = pickle.load(f) print(f" ✅ Cache loaded successfully!") break except Exception as e: print(f" ⚠️ Load attempt {attempt+1} failed: {str(e)[:50]}") if attempt < max_retries - 1: time.sleep(0.5) # Wait before retry continue else: raise e num_items = len(embeddings_data) if isinstance(embeddings_data, dict) else \ (len(embeddings_data.get('embeddings', {})) if isinstance(embeddings_data, dict) else 0) return True, embeddings_data, f"Cache loaded successfully ({num_items} embeddings)" except Exception as e: print(f" ❌ Error loading cache: {str(e)}") import traceback traceback.print_exc() return False, None, f"Error loading cache: {str(e)}" def get_cache_info(self, mode: str) -> Optional[Dict]: """Get information about cached mode""" return self.metadata["caches"].get(mode) def get_all_caches_info(self) -> Dict: """Get information about all cached modes""" return self.metadata["caches"] def delete_cache(self, mode: str) -> tuple[bool, str]: """Delete cache for specific mode (thread-safe)""" with self._file_lock: try: # Reload metadata self.metadata = self._load_metadata() if mode not in self.metadata["caches"]: return False, f"No cache found for mode: {mode}" cache_info = self.metadata["caches"][mode] cache_file = cache_info["cache_file"] # Delete cache file with retry if os.path.exists(cache_file): max_retries = 3 for attempt in range(max_retries): try: os.remove(cache_file) break except Exception as e: if attempt < max_retries - 1: time.sleep(0.5) continue else: raise e # Remove from metadata del self.metadata["caches"][mode] self._save_metadata() return True, f"Cache deleted successfully: {mode}" except Exception as e: return False, f"Error deleting cache: {str(e)}" def delete_all_caches(self) -> tuple[bool, str]: """Delete all caches""" try: deleted_count = 0 errors = [] for mode in list(self.metadata["caches"].keys()): success, msg = self.delete_cache(mode) if success: deleted_count += 1 else: errors.append(msg) if errors: return False, f"Deleted {deleted_count} caches, but encountered errors: {'; '.join(errors)}" return True, f"All caches deleted successfully ({deleted_count} caches)" except Exception as e: return False, f"Error deleting all caches: {str(e)}" def get_total_cache_size(self) -> float: """Get total size of all caches in MB""" total_size = 0 for cache_info in self.metadata["caches"].values(): total_size += cache_info.get("size_mb", 0) return total_size def is_cache_valid(self, mode: str) -> bool: """Check if cache is valid for current dataset""" if mode not in self.metadata["caches"]: return False cache_info = self.metadata["caches"][mode] current_hash = self._compute_dataset_hash() return cache_info["dataset_hash"] == current_hash # ============================================================================ # PROGRESS TRACKING & RESUME CAPABILITY # ============================================================================ def save_processing_progress(self, mode: str, processed_files: List[str]) -> tuple[bool, str]: """ Save list of files that have been processed (for resume capability) Args: mode: Recognition mode processed_files: List of filenames that have been successfully processed Returns: (success, message) """ with self._file_lock: try: progress_file = os.path.join(self.cache_dir, f"progress_{mode}.json") temp_file = progress_file + ".tmp" progress_data = { "mode": mode, "processed_files": processed_files, "last_updated": datetime.now().isoformat(), "total_processed": len(processed_files) } with open(temp_file, 'w', encoding='utf-8') as f: json.dump(progress_data, f, indent=2, ensure_ascii=False) f.flush() os.fsync(f.fileno()) # Atomic rename if os.path.exists(progress_file): os.replace(temp_file, progress_file) else: os.rename(temp_file, progress_file) return True, f"Progress saved: {len(processed_files)} files" except Exception as e: if 'temp_file' in locals() and os.path.exists(temp_file): try: os.remove(temp_file) except: pass return False, f"Error saving progress: {str(e)}" def load_processing_progress(self, mode: str) -> tuple[bool, List[str], str]: """ Load list of files that have been processed (for resume) Args: mode: Recognition mode Returns: (success, processed_files, message) """ with self._file_lock: try: progress_file = os.path.join(self.cache_dir, f"progress_{mode}.json") if not os.path.exists(progress_file): return True, [], "No progress file found (starting from scratch)" with open(progress_file, 'r', encoding='utf-8') as f: progress_data = json.load(f) processed_files = progress_data.get("processed_files", []) return True, processed_files, f"Loaded progress: {len(processed_files)} files already processed" except Exception as e: return False, [], f"Error loading progress: {str(e)}" def clear_processing_progress(self, mode: str) -> tuple[bool, str]: """ Clear processing progress file Args: mode: Recognition mode Returns: (success, message) """ with self._file_lock: try: progress_file = os.path.join(self.cache_dir, f"progress_{mode}.json") if os.path.exists(progress_file): os.remove(progress_file) return True, "Progress cleared" else: return True, "No progress to clear" except Exception as e: return False, f"Error clearing progress: {str(e)}" # ============================================================================ # PERSISTENT RECOGNITION RESULTS STORAGE # ============================================================================ def save_recognition_result(self, result_data: Dict) -> tuple[bool, str]: """ Save recognition result to persistent storage Results persist across app rebuilds and can only be deleted via admin panel Args: result_data: Dictionary containing recognition result data - timestamp: When recognition was performed - matches: List of matched faces - image_bytes: Uploaded image as bytes - mode: Recognition mode used - etc. Returns: (success, message) """ with self._file_lock: try: results_dir = os.path.join(self.cache_dir, "recognition_results") os.makedirs(results_dir, exist_ok=True) # Generate unique ID for this result timestamp = datetime.now().isoformat() result_id = hashlib.md5(timestamp.encode()).hexdigest()[:12] # Add metadata result_data['result_id'] = result_id result_data['saved_at'] = timestamp # Save result to file result_file = os.path.join(results_dir, f"result_{result_id}.pkl") temp_file = result_file + ".tmp" with open(temp_file, 'wb') as f: pickle.dump(result_data, f, protocol=pickle.HIGHEST_PROTOCOL) f.flush() os.fsync(f.fileno()) # Atomic rename if os.path.exists(result_file): os.replace(temp_file, result_file) else: os.rename(temp_file, result_file) # Update metadata if "recognition_results" not in self.metadata: self.metadata["recognition_results"] = {} self.metadata["recognition_results"][result_id] = { "result_file": result_file, "saved_at": timestamp, "mode": result_data.get('mode', 'unknown'), "num_matches": len(result_data.get('matches', [])) } self._save_metadata() return True, f"Result saved successfully: {result_id}" except Exception as e: # Cleanup temp file if 'temp_file' in locals() and os.path.exists(temp_file): try: os.remove(temp_file) except: pass return False, f"Error saving result: {str(e)}" def load_latest_recognition_result(self) -> tuple[bool, Optional[Dict], str]: """ Load the most recent recognition result Returns: (success, result_data, message) """ with self._file_lock: try: if "recognition_results" not in self.metadata or not self.metadata["recognition_results"]: return False, None, "No recognition results found" # Get most recent result results = self.metadata["recognition_results"] latest_id = max(results.keys(), key=lambda k: results[k]['saved_at']) latest_info = results[latest_id] result_file = latest_info["result_file"] if not os.path.exists(result_file): return False, None, f"Result file not found: {result_file}" # Load result with file locking with open(result_file, 'rb') as f: self._lock_file(f, shared=True) result_data = pickle.load(f) self._unlock_file(f) return True, result_data, f"Loaded result: {latest_id}" except Exception as e: return False, None, f"Error loading result: {str(e)}" def get_all_recognition_results(self) -> tuple[bool, List[Dict], str]: """ Get list of all recognition results (metadata only, no image data) Returns: (success, results_list, message) """ try: if "recognition_results" not in self.metadata or not self.metadata["recognition_results"]: return True, [], "No recognition results found" results_list = [] for result_id, result_info in self.metadata["recognition_results"].items(): results_list.append({ 'result_id': result_id, 'saved_at': result_info['saved_at'], 'mode': result_info.get('mode', 'unknown'), 'num_matches': result_info.get('num_matches', 0) }) # Sort by date (newest first) results_list.sort(key=lambda x: x['saved_at'], reverse=True) return True, results_list, f"Found {len(results_list)} result(s)" except Exception as e: return False, [], f"Error getting results: {str(e)}" def delete_recognition_result(self, result_id: str) -> tuple[bool, str]: """ Delete a specific recognition result (admin only) Args: result_id: ID of result to delete Returns: (success, message) """ with self._file_lock: try: if "recognition_results" not in self.metadata or result_id not in self.metadata["recognition_results"]: return False, f"Result not found: {result_id}" result_info = self.metadata["recognition_results"][result_id] result_file = result_info["result_file"] # Delete file if os.path.exists(result_file): os.remove(result_file) # Remove from metadata del self.metadata["recognition_results"][result_id] self._save_metadata() return True, f"Result deleted: {result_id}" except Exception as e: return False, f"Error deleting result: {str(e)}" def clear_all_recognition_results(self) -> tuple[bool, str]: """ Clear all recognition results (admin only) Returns: (success, message) """ with self._file_lock: try: results_dir = os.path.join(self.cache_dir, "recognition_results") if os.path.exists(results_dir): # Remove all result files for filename in os.listdir(results_dir): if filename.startswith('result_') and filename.endswith('.pkl'): file_path = os.path.join(results_dir, filename) os.remove(file_path) # Clear metadata if "recognition_results" in self.metadata: del self.metadata["recognition_results"] self._save_metadata() return True, "All recognition results cleared" except Exception as e: return False, f"Error clearing results: {str(e)}" # Global cache manager instance _cache_manager = None def get_cache_manager() -> CacheManager: """Get global cache manager instance""" global _cache_manager if _cache_manager is None: _cache_manager = CacheManager() return _cache_manager