""" FaceMatch Admin - Cache Management System Admin-only page for managing face recognition cache and pre-warming """ import streamlit as st import json import os import time import hashlib from datetime import datetime, timedelta from cache_manager import get_cache_manager import sys # Add parent directory to path to import from app.py sys.path.insert(0, os.path.dirname(__file__)) # NOTE: Do NOT call st.set_page_config() at import time. Streamlit only allows # set_page_config() to be called once and it must be the first Streamlit call # in the script. This module is imported by `app.py`, which already sets the # page config. When running this file directly (streamlit run admin_cache.py) # we'll set the page config in the __main__ block below. # ============================================================================ # AUTHENTICATION SYSTEM # ============================================================================ def load_admin_config(): """Load admin configuration with environment variable priority""" try: with open('admin_config.json', 'r', encoding='utf-8') as f: config = json.load(f) # Override with environment variables (Hugging Face Secrets) # These take priority over file-based config admin_username = os.getenv('ADMIN_USERNAME') admin_password_hash = os.getenv('ADMIN_PASSWORD_HASH') if admin_username: config['admin_username'] = admin_username elif 'fallback_admin_username' in config: config['admin_username'] = config['fallback_admin_username'] if admin_password_hash: config['admin_password_hash'] = admin_password_hash elif 'fallback_admin_password_hash' in config: config['admin_password_hash'] = config['fallback_admin_password_hash'] return config except Exception as e: st.error(f"β Admin configuration error: {e}") st.stop() def hash_password(password: str) -> str: """Hash password using SHA256""" return hashlib.sha256(password.encode()).hexdigest() def check_admin_auth(username: str, password: str) -> bool: """Check admin credentials""" config = load_admin_config() if username == config["admin_username"]: password_hash = hash_password(password) if password_hash == config["admin_password_hash"]: return True return False def is_admin_logged_in() -> bool: """Check if admin is logged in""" if 'admin_logged_in' not in st.session_state: return False if not st.session_state.admin_logged_in: return False # Check session timeout config = load_admin_config() timeout_minutes = config.get("session_timeout_minutes", 30) if 'admin_login_time' in st.session_state: login_time = st.session_state.admin_login_time current_time = datetime.now() if (current_time - login_time).total_seconds() > (timeout_minutes * 60): st.session_state.admin_logged_in = False return False return True def admin_login_page(): """Show admin login page""" st.title("π FaceMatch Admin Login") col1, col2, col3 = st.columns([1, 2, 1]) with col2: with st.form("login_form"): st.subheader("π Admin Login") username = st.text_input("Username", placeholder="Enter admin username") password = st.text_input("Password", type="password", placeholder="Enter admin password") submit = st.form_submit_button("π Login", use_container_width=True) if submit: if check_admin_auth(username, password): st.session_state.admin_logged_in = True st.session_state.admin_login_time = datetime.now() st.success("β Login successful! Redirecting...") time.sleep(1) st.rerun() else: st.error("β Invalid username or password!") st.markdown("---") st.info("π‘ **Note**: This is a protected admin area. Only authorized personnel can access cache management features.") with st.expander("π Security Information"): st.markdown(""" Hanya bisa diakses oleh icadππ€ͺπ€ͺπ€ͺ """) def admin_logout(): """Logout admin""" st.session_state.admin_logged_in = False if 'admin_login_time' in st.session_state: del st.session_state.admin_login_time st.rerun() # ============================================================================ # UTILITY FUNCTIONS (standalone to avoid import conflicts with app.py) # ============================================================================ def load_student_data_local(): """Load student data from JSON file (standalone version)""" try: with open('students_data.json', 'r', encoding='utf-8') as f: return json.load(f) except FileNotFoundError: st.error("β File students_data.json tidak ditemukan!") return {} except json.JSONDecodeError: st.error("β Error membaca students_data.json!") return {} def get_photo_path_local(filename): """Get full path to photo in foto rev directory (standalone version)""" return os.path.join('foto rev', filename) def build_faiss_index_local(embeddings_dict, model_name): """ Build FAISS index for ultra-fast similarity search (standalone version) Uses IndexFlatL2 for exact search with L2 distance (for cosine similarity after normalization) """ try: import faiss import numpy as np # Collect all embeddings for this model embedding_list = [] filename_list = [] for filename, model_embeddings in embeddings_dict.items(): if isinstance(model_embeddings, dict) and model_name in model_embeddings: embedding = model_embeddings[model_name] # Normalize for cosine similarity (FAISS uses L2 distance) embedding_normalized = embedding / np.linalg.norm(embedding) embedding_list.append(embedding_normalized) filename_list.append(filename) if not embedding_list: return None, [] # Convert to numpy array embeddings_matrix = np.array(embedding_list).astype('float32') # Build FAISS index dimension = embeddings_matrix.shape[1] index = faiss.IndexFlatL2(dimension) # L2 distance for normalized vectors = cosine distance index.add(embeddings_matrix) print(f" β FAISS index built for {model_name}: {len(filename_list)} entries, dim={dimension}") return index, filename_list except Exception as e: print(f" β οΈ FAISS indexing failed for {model_name}: {str(e)}") return None, [] # ============================================================================ # CACHE PRE-WARMING FUNCTIONS WITH INCREMENTAL SAVE & RESUME # ============================================================================ def generic_prewarm_with_logging(mode: str, models: list, detector: str, min_models: int = 1, incremental_save_interval: int = 10, enable_faiss: bool = False): """ Generic prewarm function with incremental save, resume, and detailed logging Args: mode: Cache mode name (standard, accurate, hardmode, extreme) models: List of model names to use detector: Detector backend to use min_models: Minimum number of successful models required incremental_save_interval: Save cache every N images enable_faiss: Whether to build FAISS indices (for extreme mode) """ from deepface import DeepFace import numpy as np cache_mgr = get_cache_manager() # Check for existing progress and resume print(f"\n{'='*80}") print(f"π Checking for existing progress for mode: {mode}") success_load, already_processed, msg_load = cache_mgr.load_processing_progress(mode) already_processed_set = set(already_processed) print(f" Progress load result: {msg_load}") print(f" Already processed files: {len(already_processed)}") # Try to load existing cache to resume print(f"\nπ Checking for existing cache for mode: {mode}") success_cache, cache_data, msg_cache = cache_mgr.load_cache(mode, ignore_hash_check=True) print(f" Cache load result: {msg_cache}") if success_cache: print(f" β Cache found! Extracting embeddings...") if enable_faiss and isinstance(cache_data, dict) and 'embeddings' in cache_data: embeddings_db = cache_data['embeddings'] print(f" β Extracted {len(embeddings_db)} embeddings from FAISS cache") elif not enable_faiss: embeddings_db = cache_data print(f" β Loaded {len(embeddings_db)} embeddings from cache") else: embeddings_db = {} print(f" β οΈ Cache data structure unexpected, starting fresh") else: embeddings_db = {} print(f" βΉοΈ No cache found, starting from scratch") print(f"{'='*80}\n") if already_processed: st.warning(f"π Resuming from previous progress: {len(already_processed)} files already processed") start_time = time.time() # Load student data student_data = load_student_data_local() total = len(student_data) # Filter out already processed files files_to_process = [f for f in student_data.keys() if f not in already_processed_set] remaining = len(files_to_process) if remaining == 0: st.success(f"β All {total} files already processed!") return True # Create progress tracking progress_bar = st.progress(0) status_text = st.empty() log_container = st.expander("π Processing Log", expanded=True) processed = len(already_processed) status_text.text(f"β³ Processing {remaining} remaining images (already done: {processed}/{total})...") with log_container: st.write(f"**Models:** {', '.join(models)}") st.write(f"**Detector:** {detector}") st.write(f"**Total Files:** {total}") st.write(f"**Already Processed:** {processed}") st.write(f"**Remaining:** {remaining}") st.write("---") log_area = st.empty() logs = [] for idx, filename in enumerate(files_to_process): reference_path = get_photo_path_local(filename) if not os.path.exists(reference_path): logs.append(f"β οΈ File not found: {filename}") continue try: # Update progress progress = (processed) / total progress_bar.progress(progress) status_text.text(f"β³ Processing {processed+1}/{total}: {filename}") logs.append(f"π [{processed+1}/{total}] Processing: {filename}...") log_area.text("\n".join(logs[-20:])) # Single model mode if len(models) == 1: embedding_objs = DeepFace.represent( img_path=reference_path, model_name=models[0], detector_backend=detector, enforce_detection=False, align=True ) if embedding_objs and len(embedding_objs) > 0: embeddings_db[filename] = np.array(embedding_objs[0]["embedding"]) already_processed.append(filename) processed += 1 logs.append(f" β Success! ({processed}/{total})") log_area.text("\n".join(logs[-20:])) # Multi-model mode else: model_embeddings = {} for model_name in models: try: logs.append(f" πΉ Extracting with {model_name}...") log_area.text("\n".join(logs[-20:])) embedding_objs = DeepFace.represent( img_path=reference_path, model_name=model_name, detector_backend=detector, enforce_detection=False, align=True ) if embedding_objs and len(embedding_objs) > 0: model_embeddings[model_name] = np.array(embedding_objs[0]["embedding"]) logs.append(f" β {model_name} OK") log_area.text("\n".join(logs[-20:])) except Exception as e: logs.append(f" β οΈ {model_name} failed: {str(e)[:50]}") log_area.text("\n".join(logs[-20:])) continue # Save if we have minimum required models if len(model_embeddings) >= min_models: embeddings_db[filename] = model_embeddings already_processed.append(filename) processed += 1 logs.append(f" β Success! {len(model_embeddings)}/{len(models)} models ({processed}/{total})") log_area.text("\n".join(logs[-20:])) else: logs.append(f" β οΈ Insufficient models ({len(model_embeddings)}/{len(models)}), need {min_models}") log_area.text("\n".join(logs[-20:])) # INCREMENTAL SAVE - Save cache every N images, but save progress EVERY image if processed % incremental_save_interval == 0: extra_info = { "models": models, "detector": detector, "total_images": total, "processing_time": time.time() - start_time, "progress": f"{processed}/{total}" } save_data = embeddings_db if not enable_faiss else {'embeddings': embeddings_db} success_save, msg_save = cache_mgr.save_cache(mode, save_data, extra_info, is_incremental=True) if success_save: logs.append(f" πΎ Cache saved: {processed}/{total} files") log_area.text("\n".join(logs[-20:])) # Save progress EVERY image (lightweight operation) if processed > 0 and processed % 5 == 0: # Every 5 images to avoid too many disk writes cache_mgr.save_processing_progress(mode, already_processed) print(f" π Progress saved: {processed} files") except Exception as e: error_msg = str(e)[:100] logs.append(f" β Error: {error_msg}") log_area.text("\n".join(logs[-20:])) print(f" β οΈ Skipped {filename}: {error_msg}") continue # Build FAISS indices if enabled faiss_indices = {} if enable_faiss and len(embeddings_db) > 0: status_text.text("β³ Building FAISS indices for ultra-fast search...") progress_bar.progress(0.95) logs.append("π Building FAISS indices...") log_area.text("\n".join(logs[-20:])) try: for model_name in models: try: index, filenames_list = build_faiss_index_local(embeddings_db, model_name) if index is not None: faiss_indices[model_name] = (index, filenames_list) logs.append(f" β FAISS index built for {model_name}") log_area.text("\n".join(logs[-20:])) except Exception as e: logs.append(f" β οΈ FAISS failed for {model_name}: {str(e)[:50]}") log_area.text("\n".join(logs[-20:])) continue except Exception as e: logs.append(f"β οΈ FAISS indexing failed: {str(e)[:100]}") log_area.text("\n".join(logs[-20:])) # FINAL SAVE print(f"\n{'='*80}") print(f"πΎ Final save for mode: {mode}") print(f" Total embeddings: {len(embeddings_db)}") print(f" Processing time: {(time.time() - start_time)/60:.2f} minutes") extra_info = { "models": models, "detector": detector, "total_images": total, "processing_time": time.time() - start_time, "has_faiss": len(faiss_indices) > 0 if enable_faiss else False } save_data = embeddings_db if enable_faiss: save_data = { 'embeddings': embeddings_db, 'faiss_indices': faiss_indices } success, msg = cache_mgr.save_cache(mode, save_data, extra_info, is_incremental=False) print(f" Save result: {msg}") # Clear progress tracking print(f" Clearing progress tracking...") success_clear, msg_clear = cache_mgr.clear_processing_progress(mode) print(f" Progress clear result: {msg_clear}") print(f"{'='*80}\n") progress_bar.progress(1.0) status_text.text(f"β Completed! Processed {processed}/{total} images") if success: st.success(f"β {msg}") st.success(f"β±οΈ Completed in {(time.time() - start_time)/60:.2f} minutes") st.info(f"π Successfully processed {processed}/{total} images") if enable_faiss and faiss_indices: st.info(f"π FAISS indices built for {len(faiss_indices)} models (ultra-fast search enabled)") else: st.error(f"β {msg}") return success def prewarm_standard_mode(): """Pre-warm cache for standard mode with INCREMENTAL SAVE & RESUME""" try: st.info("π Starting Standard Mode cache pre-warming...") return generic_prewarm_with_logging( mode="standard", models=['Facenet512'], detector='retinaface', min_models=1, incremental_save_interval=10, enable_faiss=False ) except Exception as e: st.error(f"β Error pre-warming standard mode: {str(e)}") import traceback st.error(traceback.format_exc()) return False def prewarm_accurate_mode(): """Pre-warm cache for accurate mode (multi-model) with INCREMENTAL SAVE & RESUME""" try: st.info("π Starting Accurate Mode cache pre-warming (3 models)...") st.warning("β οΈ This may take 12-20 minutes. Please wait...") return generic_prewarm_with_logging( mode="accurate", models=['Facenet512', 'ArcFace', 'VGG-Face'], detector='retinaface', min_models=2, incremental_save_interval=10, enable_faiss=False ) except Exception as e: st.error(f"β Error pre-warming accurate mode: {str(e)}") import traceback st.error(traceback.format_exc()) return False def prewarm_hardmode(): """Pre-warm cache for hardmode (4-5 models) with INCREMENTAL SAVE & RESUME""" try: st.info("π Starting HardMode cache pre-warming (4-5 models)...") st.warning("β οΈ This may take 20-30 minutes. Please wait...") return generic_prewarm_with_logging( mode="hardmode", models=['Facenet512', 'ArcFace', 'VGG-Face', 'OpenFace'], detector='retinaface', min_models=3, incremental_save_interval=10, enable_faiss=False ) except Exception as e: st.error(f"β Error pre-warming hardmode: {str(e)}") import traceback st.error(traceback.format_exc()) return False def prewarm_extreme_mode(): """Pre-warm cache for extreme mode (5+ models with FAISS) with INCREMENTAL SAVE & RESUME""" try: st.info("π Starting Extreme Mode cache pre-warming (5+ models + FAISS)...") st.warning("β οΈ This may take 25-35 minutes. Please wait...") return generic_prewarm_with_logging( mode="extreme", models=['Facenet512', 'ArcFace', 'VGG-Face', 'OpenFace', 'SFace'], detector='retinaface', min_models=4, incremental_save_interval=10, enable_faiss=True ) except Exception as e: st.error(f"β Error pre-warming extreme mode: {str(e)}") import traceback st.error(traceback.format_exc()) return False # ============================================================================ # MAIN ADMIN DASHBOARD # ============================================================================ def admin_dashboard(): """Main admin dashboard""" # Header with logout and back buttons col1, col2, col3 = st.columns([3, 1, 1]) with col1: st.title("π§ FaceMatch Admin Dashboard") with col2: if st.button("β Main App", use_container_width=True, help="Return to main application"): # Clear admin page query param if "page" in st.query_params: del st.query_params["page"] st.rerun() with col3: if st.button("πͺ Logout", use_container_width=True): admin_logout() st.markdown("""
Manage persistent cache, pre-warm recognition models, and monitor system status