face-recognition-revastco / admin_cache.py
doksd's picture
Update admin_cache.py
b0661f0 verified
Raw History Blame Contribute Delete
35.5 kB
"""
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("""
<div style='background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 1.5rem; border-radius: 10px; margin-bottom: 2rem;'>
<h3 style='color: white; margin: 0;'>Cache Management & Pre-warming System</h3>
<p style='color: rgba(255,255,255,0.9); margin: 0.5rem 0 0 0;'>
Manage persistent cache, pre-warm recognition models, and monitor system status
</p>
</div>
""", unsafe_allow_html=True)
# Initialize cache manager
cache_mgr = get_cache_manager()
# Tabs for different sections
tab1, tab2, tab3 = st.tabs(["πŸ“Š Cache Status", "πŸš€ Pre-warming", "βš™οΈ Management"])
# ========================================================================
# TAB 1: CACHE STATUS
# ========================================================================
with tab1:
st.header("πŸ“Š Cache Status Overview")
# Get all cache info
all_caches = cache_mgr.get_all_caches_info()
total_size = cache_mgr.get_total_cache_size()
# Summary metrics
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("Total Caches", len(all_caches))
with col2:
st.metric("Total Size", f"{total_size:.2f} MB")
with col3:
valid_caches = sum(1 for mode in all_caches.keys() if cache_mgr.is_cache_valid(mode))
st.metric("Valid Caches", valid_caches)
with col4:
outdated = len(all_caches) - valid_caches
st.metric("Outdated Caches", outdated)
st.markdown("---")
# Detailed cache information
if all_caches:
st.subheader("πŸ“¦ Cache Details")
mode_display = {
"standard": "🟒 Standard Mode",
"accurate": "πŸ”΅ Accurate Mode (3 Models)",
"hardmode": "🟠 HardMode (4-5 Models)",
"extreme": "πŸ”΄ Extreme Mode (5+ Models + FAISS)"
}
for mode, info in all_caches.items():
with st.expander(f"{mode_display.get(mode, mode.upper())} - {info.get('size_mb', 0):.2f} MB", expanded=True):
col1, col2 = st.columns(2)
with col1:
st.write("**Basic Information:**")
st.write(f"- **Created:** {info.get('created_at', 'Unknown')}")
st.write(f"- **Embeddings:** {info.get('num_embeddings', 0)}")
st.write(f"- **Size:** {info.get('size_mb', 0):.2f} MB")
st.write(f"- **Dataset Hash:** `{info.get('dataset_hash', 'Unknown')}`")
with col2:
st.write("**Status:**")
is_valid = cache_mgr.is_cache_valid(mode)
if is_valid:
st.success("βœ… Valid - Up to date")
else:
st.warning("⚠️ Outdated - Dataset changed")
# Extra info
extra = info.get('extra_info', {})
if extra:
st.write("**Configuration:**")
if 'models' in extra:
st.write(f"- Models: {', '.join(extra['models'])}")
if 'detector' in extra:
st.write(f"- Detector: {extra['detector']}")
if 'processing_time' in extra:
st.write(f"- Processing Time: {extra['processing_time']/60:.2f} min")
else:
st.info("ℹ️ No caches found. Use the Pre-warming tab to create caches.")
# ========================================================================
# TAB 2: PRE-WARMING
# ========================================================================
with tab2:
st.header("πŸš€ Cache Pre-warming")
st.markdown("""
Pre-warm cache untuk setiap mode recognition. Cache akan disimpan secara persistent
dan tidak akan hilang saat rebuild aplikasi.
""")
st.warning("⚠️ **Perhatian:** Pre-warming membutuhkan waktu lama. Pastikan Anda memiliki waktu cukup sebelum memulai.")
# Mode selection
mode_options = {
"standard": {
"name": "🟒 Standard Mode",
"description": "Single model (Facenet512) - Fastest",
"time": "5-8 minutes",
"function": prewarm_standard_mode
},
"accurate": {
"name": "πŸ”΅ Accurate Mode",
"description": "3 models ensemble - High accuracy",
"time": "12-20 minutes",
"function": prewarm_accurate_mode
},
"hardmode": {
"name": "🟠 HardMode",
"description": "4-5 models ensemble - Maximum accuracy",
"time": "20-30 minutes",
"function": prewarm_hardmode
},
"extreme": {
"name": "πŸ”΄ Extreme Mode",
"description": "5+ models + FAISS - Ultimate performance",
"time": "25-35 minutes",
"function": prewarm_extreme_mode
}
}
col1, col2 = st.columns([2, 1])
with col1:
for mode, config in mode_options.items():
with st.container():
st.subheader(config["name"])
st.write(f"πŸ“ {config['description']}")
st.write(f"⏱️ Estimated time: {config['time']}")
# Check if cache exists
cache_info = cache_mgr.get_cache_info(mode)
if cache_info:
is_valid = cache_mgr.is_cache_valid(mode)
if is_valid:
st.success(f"βœ… Cache exists and valid ({cache_info.get('size_mb', 0):.2f} MB)")
else:
st.warning("⚠️ Cache exists but outdated (dataset changed)")
else:
st.info("ℹ️ No cache found for this mode")
# Pre-warm button
button_key = f"prewarm_{mode}"
if st.button(f"πŸš€ Pre-warm {config['name']}", key=button_key, use_container_width=True):
with st.spinner(f"Processing {config['name']}..."):
config["function"]()
st.markdown("---")
with col2:
st.info("""
**πŸ’‘ Tips:**
1. Pre-warm mode yang paling sering Anda gunakan terlebih dahulu
2. Cache disimpan di folder `persistent_cache` dan tidak akan hilang saat rebuild
3. Jika dataset berubah, cache akan otomatis dideteksi sebagai outdated
4. Monitor terminal/console untuk melihat progress detail
""")
# ========================================================================
# TAB 3: MANAGEMENT
# ========================================================================
with tab3:
st.header("βš™οΈ Cache Management")
col1, col2 = st.columns(2)
with col1:
st.subheader("πŸ—‘οΈ Delete Specific Cache")
all_caches = cache_mgr.get_all_caches_info()
if all_caches:
mode_to_delete = st.selectbox(
"Select cache to delete:",
options=list(all_caches.keys()),
format_func=lambda x: f"{x.upper()} - {all_caches[x].get('size_mb', 0):.2f} MB"
)
if st.button("πŸ—‘οΈ Delete Selected Cache", type="secondary"):
success, msg = cache_mgr.delete_cache(mode_to_delete)
if success:
st.success(msg)
time.sleep(1)
st.rerun()
else:
st.error(msg)
else:
st.info("ℹ️ No caches to delete")
with col2:
st.subheader("🧹 Delete All Caches")
st.warning("⚠️ **Warning:** This will delete all cached embeddings!")
confirm = st.checkbox("I understand this will delete all caches")
if st.button("🧹 Delete All Caches", type="primary", disabled=not confirm):
with st.spinner("Deleting all caches..."):
success, msg = cache_mgr.delete_all_caches()
if success:
st.success(msg)
time.sleep(1)
st.rerun()
else:
st.error(msg)
st.markdown("---")
# ============================================================================
# RECOGNITION RESULTS MANAGEMENT
# ============================================================================
st.subheader("πŸ“Š Recognition Results Management")
col1, col2 = st.columns([2, 1])
with col1:
st.write("Manage saved recognition results (persist across rebuilds)")
with col2:
if st.button("πŸ”„ Refresh Results"):
st.rerun()
# Get all recognition results
success, results_list, msg = cache_mgr.get_all_recognition_results()
if success and results_list:
st.success(f"βœ… {msg}")
# Display results in table
st.write("**πŸ“‹ Saved Recognition Results:**")
for result in results_list:
with st.expander(f"🎯 Result {result['result_id']} - {result['mode'].upper()} mode ({result['num_matches']} matches)"):
col1, col2, col3 = st.columns([2, 2, 1])
with col1:
st.write(f"**Saved:** {result['saved_at'][:19]}")
with col2:
st.write(f"**Mode:** {result['mode']}")
with col3:
st.write(f"**Matches:** {result['num_matches']}")
# Delete button
if st.button(f"πŸ—‘οΈ Delete", key=f"del_{result['result_id']}"):
with st.spinner("Deleting result..."):
del_success, del_msg = cache_mgr.delete_recognition_result(result['result_id'])
if del_success:
st.success(f"βœ… {del_msg}")
time.sleep(1)
st.rerun()
else:
st.error(f"❌ {del_msg}")
# Clear all results button
st.write("---")
st.warning("⚠️ **Danger Zone: Delete All Results**")
confirm_clear_results = st.checkbox("I want to delete ALL recognition results", key="confirm_clear_results")
if st.button("🧹 Clear All Recognition Results", type="primary", disabled=not confirm_clear_results):
with st.spinner("Clearing all recognition results..."):
success, msg = cache_mgr.clear_all_recognition_results()
if success:
st.success(f"βœ… {msg}")
time.sleep(1)
st.rerun()
else:
st.error(f"❌ {msg}")
else:
st.info("ℹ️ No recognition results found")
st.markdown("---")
# System information
st.subheader("πŸ“Š System Information")
col1, col2, col3 = st.columns(3)
with col1:
st.write("**Cache Directory:**")
st.code(cache_mgr.cache_dir)
with col2:
st.write("**Metadata File:**")
st.code(cache_mgr.metadata_file)
with col3:
st.write("**Total Storage Used:**")
st.code(f"{cache_mgr.get_total_cache_size():.2f} MB")
# Show raw metadata
with st.expander("πŸ” View Raw Metadata"):
st.json(cache_mgr.metadata)
# ============================================================================
# MAIN APP
# ============================================================================
def main():
"""Main application"""
# Check authentication
if not is_admin_logged_in():
admin_login_page()
else:
admin_dashboard()
if __name__ == "__main__":
# When running this file directly (e.g. `streamlit run admin_cache.py`),
# set the page config here so it's the first Streamlit command.
try:
st.set_page_config(
page_title="FaceMatch Admin - Cache Management",
page_icon="πŸ”§",
layout="wide",
initial_sidebar_state="expanded"
)
except Exception:
# If Streamlit has already been configured by a parent app, ignore.
pass
main()