File size: 35,501 Bytes
3ef9ecb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a386e74
 
 
 
 
3ef9ecb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5bccb15
3ef9ecb
 
 
 
 
 
 
 
 
8b9e6c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ef9ecb
763f484
3ef9ecb
 
763f484
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b0661f0
 
763f484
 
b0661f0
 
763f484
 
b0661f0
 
 
 
763f484
b0661f0
763f484
 
b0661f0
763f484
 
b0661f0
763f484
 
b0661f0
763f484
67bee2c
b0661f0
 
763f484
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67bee2c
763f484
 
 
67bee2c
763f484
 
 
 
 
67bee2c
763f484
 
67bee2c
763f484
 
67bee2c
 
763f484
 
67bee2c
 
 
 
 
 
763f484
67bee2c
763f484
 
67bee2c
763f484
 
67bee2c
 
 
 
763f484
 
 
67bee2c
 
 
 
 
 
 
 
 
 
763f484
 
 
 
 
67bee2c
 
763f484
 
67bee2c
763f484
67bee2c
 
763f484
 
 
 
 
 
b0661f0
763f484
 
 
 
 
 
 
 
 
 
b0661f0
 
 
 
 
 
 
763f484
b0661f0
763f484
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ef9ecb
763f484
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b0661f0
 
 
 
 
763f484
 
 
 
 
 
 
 
 
 
 
 
 
3ef9ecb
 
763f484
b0661f0
763f484
 
b0661f0
 
 
 
763f484
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ef9ecb
 
67bee2c
 
3ef9ecb
 
 
763f484
3ef9ecb
 
 
763f484
 
 
 
 
 
 
 
3ef9ecb
 
67bee2c
 
3ef9ecb
 
 
763f484
3ef9ecb
 
 
763f484
 
 
 
 
 
 
 
3ef9ecb
 
67bee2c
 
3ef9ecb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ae6cf0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ef9ecb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a386e74
 
 
 
 
 
 
 
 
 
 
 
 
3ef9ecb
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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
"""
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()