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
 
 
 
 
7e8e5dd
497f4c9
 
7e8e5dd
497f4c9
 
 
 
 
 
7e8e5dd
497f4c9
 
 
 
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
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
try:
    from flask import Flask, render_template, request, jsonify, json
    from werkzeug.utils import secure_filename
    HAS_FLASK = True
except ImportError:
    HAS_FLASK = False
    Flask = render_template = request = jsonify = json = None
    def secure_filename(filename):
        import re
        filename = re.sub(r'[^A-Za-z0-9_.-]', '_', filename)
        return filename.strip('._')
import os
import sys
import uuid
import time
import logging
import threading
from PIL import Image

os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'
os.environ['OMP_NUM_THREADS'] = '1'
os.environ['OPENBLAS_NUM_THREADS'] = '1'
os.environ['MKL_NUM_THREADS'] = '1'
os.environ['VECLIB_MAXIMUM_THREADS'] = '1'
os.environ['NUMEXPR_NUM_THREADS'] = '1'

import torch
torch.set_num_threads(1)
import torchvision
from torchvision import transforms
from torch.utils.data.dataset import Dataset
import numpy as np
import cv2
cv2.setNumThreads(0)
try:
    import face_recognition
except BaseException:
    face_recognition = None
from torch import nn
from torchvision import models
import warnings
warnings.filterwarnings("ignore")

# Setup logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger(__name__)

# Base directories
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
V1_DIR = os.path.join(BASE_DIR, 'deepfake-detector-model-v1-main')
if V1_DIR not in sys.path:
    sys.path.insert(0, V1_DIR)

from src.pilot_pipeline import get_pilot_pipeline
from src.model_wrapper import DeepfakeModelWrapper

UPLOAD_FOLDER = os.path.join(BASE_DIR, 'Uploaded_Files')
os.makedirs(UPLOAD_FOLDER, exist_ok=True)

# Initialize Flask application if Flask is available
if HAS_FLASK:
    app = Flask("__main__", template_folder=os.path.join(BASE_DIR, "templates"))
    app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

    # Enforce maximum upload content length (default 50 MB)
    MAX_UPLOAD_MB = int(os.environ.get("MAX_CONTENT_LENGTH_MB", "50"))
    app.config['MAX_CONTENT_LENGTH'] = MAX_UPLOAD_MB * 1024 * 1024

    # Initialize CORS
    try:
        from flask_cors import CORS
        cors_origins_env = os.environ.get("CORS_ORIGINS", "*")
        cors_origins = [o.strip() for o in cors_origins_env.split(",") if o.strip()]
        CORS(app, resources={r"/*": {"origins": cors_origins if cors_origins_env != "*" else "*"}})
        logger.info(f"CORS initialized with allowed origins: {cors_origins_env}")
    except ImportError:
        logger.warning("flask_cors not installed; running without CORS extension.")

    # Error handler for file size exceeding MAX_CONTENT_LENGTH
    @app.errorhandler(413)
    def request_entity_too_large(error):
        return jsonify({
            "status": "error",
            "output": "ERROR",
            "confidence": 0.0,
            "error": f"Uploaded file exceeds the maximum allowed size limit of {MAX_UPLOAD_MB} MB."
        }), 413
else:
    class DummyFlask:
        config = {'UPLOAD_FOLDER': UPLOAD_FOLDER}
        def route(self, *args, **kwargs):
            return lambda f: f
        def errorhandler(self, *args, **kwargs):
            return lambda f: f
    app = DummyFlask()
    MAX_UPLOAD_MB = int(os.environ.get("MAX_CONTENT_LENGTH_MB", "50"))


# ==============================================================================
# MODEL VERIFICATION (GIT LFS DETECTION)
# ==============================================================================
def verify_model_file(path, model_name):
    """
    Verifies that the model weights file exists and is a real binary file,
    detecting whether it is merely a Git LFS pointer text file.
    """
    if not os.path.exists(path):
        raise FileNotFoundError(f"{model_name} file not found at: {path}")
    size = os.path.getsize(path)
    if size < 1024:
        with open(path, 'rb') as f:
            header = f.read(200)
        if b'git-lfs' in header or b'version https://git-lfs' in header:
            raise RuntimeError(
                f"FATAL: {model_name} at '{path}' is a Git LFS pointer text file ({size} bytes), "
                f"not the actual weights binary. Please ensure 'git lfs pull' is run during deployment."
            )
    logger.info(f"Verified {model_name} binary at: {path} ({size / (1024*1024):.2f} MB)")


# ==============================================================================
# MODEL DEFINITIONS & WRAPPERS (STRICT SEPARATION)
# ==============================================================================

# 1. Video Model Architecture (ResNeXt-50 + LSTM)
class VideoModel(nn.Module):
    def __init__(self, num_classes=2, latent_dim=2048, lstm_layers=1, hidden_dim=2048, bidirectional=False):
        super(VideoModel, self).__init__()
        model = models.resnext50_32x4d(weights=None)
        self.model = nn.Sequential(*list(model.children())[:-2])
        self.lstm = nn.LSTM(latent_dim, hidden_dim, num_layers=lstm_layers, bidirectional=bidirectional, bias=False)
        self.relu = nn.LeakyReLU()
        self.dp = nn.Dropout(0.4)
        self.linear1 = nn.Linear(2048, num_classes)
        self.avgpool = nn.AdaptiveAvgPool2d(1)

    def forward(self, x):
        batch_size, seq_length, c, h, w = x.shape
        x = x.view(batch_size * seq_length, c, h, w)
        fmap = self.model(x)
        x = self.avgpool(fmap)
        x = x.view(batch_size, seq_length, 2048)
        x_lstm, _ = self.lstm(x, None)
        return fmap, self.dp(self.linear1(x_lstm[:, -1, :]))


Model = VideoModel


class InferenceResult(dict):
    """
    Subclass of dict that allows tuple unpacking (prediction_code, confidence)
    for backward compatibility with legacy caller code.
    """
    def __iter__(self):
        code = 0 if self.get("prediction", "").lower() == "fake" else 1
        yield code
        yield self.get("confidence", 0.0)


class VideoModelWrapper:
    """Thread-safe singleton for Video Recognition Model (ResNeXt-50 + LSTM)."""
    _instance = None
    _lock = threading.Lock()

    def __new__(cls, *args, **kwargs):
        with cls._lock:
            if cls._instance is None:
                cls._instance = super(VideoModelWrapper, cls).__new__(cls)
                cls._instance._initialized = False
        return cls._instance

    def __init__(self, model_path=None):
        if self._initialized:
            return
        with self._lock:
            if self._initialized:
                return
            if model_path is None:
                model_path = os.environ.get("VIDEO_MODEL_PATH", os.path.join(BASE_DIR, "model", "df_model.pt"))
            self.model_path = os.path.abspath(model_path)
            verify_model_file(self.model_path, "VideoModel (df_model.pt)")
            self.model = VideoModel(2)
            state = torch.load(self.model_path, map_location="cpu")
            self.model.load_state_dict(state)
            logger.info(f"VideoModel successfully loaded from: {self.model_path}")
            self.model.eval()
            self.sm = nn.Softmax(dim=1)
            self._initialized = True


# Video transforms
video_im_size = 112
video_mean = [0.485, 0.456, 0.406]
video_std = [0.229, 0.224, 0.225]
video_transforms = transforms.Compose([
    transforms.ToPILImage(),
    transforms.Resize((video_im_size, video_im_size)),
    transforms.ToTensor(),
    transforms.Normalize(video_mean, video_std)
])


# ==============================================================================
# GLOBAL MODEL STATE & LAZY INITIALIZATION
# ==============================================================================
image_model_loaded = False
video_model_loaded = False
_model_init_lock = threading.Lock()

def init_models():
    """Lazily and safely initializes models in memory without premature CUDA calls."""
    global image_model_loaded, video_model_loaded
    with _model_init_lock:
        # 1. Load Video Model
        if not video_model_loaded:
            try:
                v_wrap = VideoModelWrapper()
                if v_wrap._initialized:
                    video_model_loaded = True
                    logger.info("Video Model successfully initialized and cached in memory.")
            except Exception as e:
                logger.error(f"Failed to initialize Video Model: {e}", exc_info=True)
                video_model_loaded = False

        # 2. Load Image Model
        if not image_model_loaded:
            try:
                img_wrap = DeepfakeModelWrapper()
                _ = get_pilot_pipeline()
                if img_wrap._initialized:
                    image_model_loaded = True
                    logger.info("Image Model successfully initialized and cached in memory.")
            except Exception as e:
                logger.error(f"Failed to initialize Image Model: {e}", exc_info=True)
                image_model_loaded = False

    logger.info(f"Model Initialization Status -> Video: {video_model_loaded}, Image: {image_model_loaded}")


def cleanup_stale_uploads():
    """Purges any lingering temporary upload files from previous sessions on boot."""
    try:
        count = 0
        for fname in os.listdir(UPLOAD_FOLDER):
            fpath = os.path.join(UPLOAD_FOLDER, fname)
            if os.path.isfile(fpath) and fname != ".gitkeep":
                try:
                    os.remove(fpath)
                    count += 1
                except Exception:
                    pass
        if count > 0:
            logger.info(f"Cleaned up {count} stale temporary file(s) from {UPLOAD_FOLDER}.")
    except Exception as e:
        logger.warning(f"Error purging stale uploads: {e}")


# ==============================================================================
# DIAGNOSTIC & TELEMETRY FUNCTIONS
# ==============================================================================
def log_inference_details(file_path, input_type, model_path, tensor, raw_output, prediction, confidence):
    info = {
        "file_path": file_path,
        "input_type": input_type,
        "model_path": model_path,
        "tensor_shape": getattr(tensor, "shape", None),
        "tensor_dtype": getattr(tensor, "dtype", None),
        "raw_output": raw_output,
        "prediction": prediction,
        "confidence": confidence,
    }
    logger.info(f"Inference details logged for {os.path.basename(file_path)}: pred={prediction}, conf={confidence}")


def log_diagnostic_fake_33(file_path, pil_img, wrapper, raw_logits, prob_fake, prob_real, pred_label):
    resolved_model_path = os.path.abspath(wrapper.model_path)
    inputs = wrapper.processor(images=pil_img, return_tensors="pt")
    pixel_vals = inputs["pixel_values"]
    logger.info(f"fake_33 diagnostic logged. Prediction: {pred_label}, prob_fake: {prob_fake:.6f}")


# ==============================================================================
# FILE TYPE VALIDATION
# ==============================================================================
IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".bmp"}
VIDEO_EXTENSIONS = {".mp4", ".avi", ".mov", ".mkv", ".flv", ".webm"}

def detect_file_type(file_storage, filename):
    ext = os.path.splitext(filename)[1].lower()
    mime = file_storage.mimetype or "application/octet-stream"

    header = file_storage.read(512)
    file_storage.seek(0)

    # Magic byte checks for images
    if header.startswith(b"\xff\xd8\xff"):
        return "image", "image/jpeg"
    if header.startswith(b"\x89PNG\r\n\x1a\n"):
        return "image", "image/png"
    if header.startswith(b"RIFF") and len(header) >= 12 and header[8:12] == b"WEBP":
        return "image", "image/webp"
    if header.startswith(b"BM"):
        return "image", "image/bmp"

    # Magic byte checks for videos
    if len(header) >= 12 and header[4:8] == b"ftyp":
        return "video", "video/mp4"
    if header.startswith(b"RIFF") and len(header) >= 12 and header[8:12] == b"AVI ":
        return "video", "video/x-msvideo"
    if header.startswith(b"\x1a\x45\xdf\xa3"):
        return "video", "video/webm"
    if header.startswith(b"FLV\x01"):
        return "video", "video/x-flv"

    # Fallback to extension check
    if ext in IMAGE_EXTENSIONS:
        return "image", mime
    if ext in VIDEO_EXTENSIONS:
        return "video", mime

    return "invalid", mime


# ==============================================================================
# INFERENCE PIPELINES (STRICT SEPARATION & DEVICE STRATEGY)
# ==============================================================================
def detectFakeImage(image_path, request_id=None, force_cpu=False):
    """
    Image inference function using the Vision Transformer (ViT) pipeline.
    Supports dynamic device placement, torch.inference_mode(), and robust CPU fallback.
    """
    if request_id is None:
        request_id = str(uuid.uuid4())

    init_models()

    wrapper = DeepfakeModelWrapper()
    resolved_image_model_path = os.path.abspath(wrapper.model_path)

    # Resolve target device
    target_device = torch.device("cpu")
    if not force_cpu:
        try:
            if torch.cuda.is_available():
                target_device = torch.device("cuda")
        except Exception:
            target_device = torch.device("cpu")

    # Ensure model is on target device
    try:
        wrapper.model.to(target_device)
        wrapper.device = target_device
    except Exception as de:
        logger.warning(f"[{request_id}] Could not move image model to {target_device}: {de}. Falling back to CPU.")
        target_device = torch.device("cpu")
        wrapper.model.to(target_device)
        wrapper.device = target_device

    # Diagnostic logging
    gpu_mem = "N/A"
    if target_device.type == "cuda":
        try:
            allocated = torch.cuda.memory_allocated() / (1024 * 1024)
            gpu_mem = f"{allocated:.2f} MB"
        except Exception:
            pass

    logger.info(
        f"[{request_id}] Image Inference Diagnostic -> "
        f"PyTorch: {torch.__version__}, "
        f"CUDA Available: {torch.cuda.is_available()}, "
        f"Device Count: {torch.cuda.device_count() if torch.cuda.is_available() else 0}, "
        f"Target Device: {target_device}, "
        f"Model Device: {next(wrapper.model.parameters()).device}, "
        f"GPU Memory: {gpu_mem}"
    )

    try:
        with Image.open(image_path) as raw_img:
            raw_img.verify()
        pil_img = Image.open(image_path).convert("RGB")
    except Exception as e:
        raise ValueError(f"Invalid or corrupted image file: {str(e)}")

    pipeline = get_pilot_pipeline()
    result = pipeline.process_image(pil_img)

    pred_label = result.get("predicted_label") or ("fake" if result.get("decision_state") == "FAKE" else "real")
    fake_prob = float(result.get("fake_probability", 0.0))
    real_prob = float(result.get("real_probability", 0.0))
    conf_fraction = float(result.get("confidence", max(fake_prob, real_prob)))
    confidence = round(conf_fraction * 100.0, 2)

    with torch.inference_mode():
        inputs = wrapper.processor(images=pil_img, return_tensors="pt")
        inputs_device = {k: v.to(target_device) for k, v in inputs.items()}
        outputs = wrapper.model(**inputs_device)
        raw_logits = outputs.logits.squeeze().cpu().tolist()

    tensor = inputs["pixel_values"].cpu()
    log_inference_details(
        file_path=image_path,
        input_type="image",
        model_path=resolved_image_model_path,
        tensor=tensor,
        raw_output=raw_logits,
        prediction=pred_label,
        confidence=confidence
    )

    file_base = os.path.basename(image_path).lower()
    if "fake_33" in file_base:
        log_diagnostic_fake_33(image_path, pil_img, wrapper, raw_logits, fake_prob, real_prob, pred_label.upper())

    output_str = "FAKE" if pred_label.lower() == "fake" else "REAL"

    return InferenceResult({
        "prediction": pred_label.lower(),
        "output": output_str,
        "confidence": confidence,
        "input_type": "image",
        "model_type": "image_model",
        "model_path": resolved_image_model_path,
        "device": str(target_device),
        "filename": os.path.basename(image_path),
        "request_id": request_id,
        "status": "success"
    })


def detectFakeVideo(video_path, request_id=None, force_cpu=False):
    """
    Video inference function using ResNeXt-50 + LSTM temporal pipeline.
    Supports dynamic device placement, torch.inference_mode(), and robust CPU fallback.
    """
    ext = os.path.splitext(video_path)[1].lower()
    if ext in IMAGE_EXTENSIONS:
        raise ValueError(
            f"Cannot process image file '{os.path.basename(video_path)}' with video model. "
            f"Image files must be routed to detectFakeImage."
        )

    if request_id is None:
        request_id = str(uuid.uuid4())

    init_models()

    wrapper = VideoModelWrapper()
    resolved_video_model_path = os.path.abspath(wrapper.model_path)

    # Resolve target device
    target_device = torch.device("cpu")
    if not force_cpu:
        try:
            if torch.cuda.is_available():
                target_device = torch.device("cuda")
        except Exception:
            target_device = torch.device("cpu")

    # Ensure model is on target device
    try:
        wrapper.model.to(target_device)
    except Exception as de:
        logger.warning(f"[{request_id}] Could not move video model to {target_device}: {de}. Falling back to CPU.")
        target_device = torch.device("cpu")
        wrapper.model.to(target_device)

    # Diagnostic logging
    gpu_mem = "N/A"
    if target_device.type == "cuda":
        try:
            allocated = torch.cuda.memory_allocated() / (1024 * 1024)
            gpu_mem = f"{allocated:.2f} MB"
        except Exception:
            pass

    logger.info(
        f"[{request_id}] Video Inference Diagnostic -> "
        f"PyTorch: {torch.__version__}, "
        f"CUDA Available: {torch.cuda.is_available()}, "
        f"Device Count: {torch.cuda.device_count() if torch.cuda.is_available() else 0}, "
        f"Target Device: {target_device}, "
        f"Model Device: {next(wrapper.model.parameters()).device}, "
        f"GPU Memory: {gpu_mem}"
    )

    vidObj = cv2.VideoCapture(video_path)
    frames = []
    success = True

    while success and len(frames) < 20:
        success, frame = vidObj.read()
        if success and frame is not None:
            if frame.dtype != np.uint8:
                frame = frame.astype(np.uint8)
            if len(frame.shape) == 2:
                frame = cv2.cvtColor(frame, cv2.COLOR_GRAY2RGB)
            elif frame.shape[2] == 4:
                frame = cv2.cvtColor(frame, cv2.COLOR_BGRA2BGR)
                frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            else:
                frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

            try:
                if face_recognition is not None:
                    faces = face_recognition.face_locations(frame)
                else:
                    import dlib
                    _dlib_det = dlib.get_frontal_face_detector()
                    _rects = _dlib_det(frame, 1)
                    faces = [(r.top(), r.right(), r.bottom(), r.left()) for r in _rects]
                if len(faces) > 0:
                    top, right, bottom, left = faces[0]
                    frame = frame[top:bottom, left:right, :]
            except Exception:
                pass

            frames.append(video_transforms(frame))

    vidObj.release()

    if len(frames) == 0:
        raise ValueError("No valid video frames could be decoded from the video file.")

    # Pad or stack frames to 20
    while len(frames) < 20:
        frames.append(frames[-1].clone())

    frames_tensor = torch.stack(frames[:20])
    input_5d = frames_tensor.unsqueeze(0).to(target_device)

    with torch.inference_mode():
        fmap, logits = wrapper.model(input_5d)
        probs = wrapper.sm(logits)
        _, pred_idx = torch.max(probs, 1)

    is_fake = (pred_idx.item() == 0)
    pred_label = "fake" if is_fake else "real"
    output_str = "FAKE" if is_fake else "REAL"
    confidence = round(probs[:, int(pred_idx.item())].item() * 100.0, 2)
    raw_logits = logits.squeeze().cpu().tolist()

    log_inference_details(
        file_path=video_path,
        input_type="video",
        model_path=resolved_video_model_path,
        tensor=input_5d.cpu(),
        raw_output=raw_logits,
        prediction=pred_label,
        confidence=confidence
    )

    return InferenceResult({
        "prediction": pred_label,
        "output": output_str,
        "confidence": confidence,
        "input_type": "video",
        "model_type": "video_model",
        "model_path": resolved_video_model_path,
        "device": str(target_device),
        "filename": os.path.basename(video_path),
        "request_id": request_id,
        "status": "success"
    })


# ==============================================================================
# API ROUTES & ENDPOINT SEPARATION
# ==============================================================================
def _extract_uploaded_file(req):
    for key in ["file", "image", "video", "media"]:
        if key in req.files and req.files[key].filename != "":
            return req.files[key]
    return None


@app.route('/', methods=['GET', 'POST'])
def homepage():
    wants_json = request.is_json or 'application/json' in request.headers.get('Accept', '')
    if wants_json and request.method == 'GET':
        return jsonify({
            "status": "ok",
            "service": "deepfake-detection-api",
            "message": "Deepfake Detection API is running"
        }), 200
    return render_template("index.html")


@app.route('/health', methods=['GET'])
@app.route('/api/v1/health', methods=['GET'])
def health():
    device_str = "cuda" if torch.cuda.is_available() else "cpu"
    return jsonify({
        "status": "ok",
        "service": "deepfake-detection-api",
        "image_model_loaded": bool(image_model_loaded),
        "video_model_loaded": bool(video_model_loaded),
        "device": device_str
    }), 200


@app.route('/ready', methods=['GET'])
@app.route('/api/v1/ready', methods=['GET'])
def ready():
    if image_model_loaded and video_model_loaded:
        return jsonify({
            "status": "ready",
            "service": "deepfake-detection-api",
            "image_model_loaded": True,
            "video_model_loaded": True
        }), 200
    return jsonify({
        "status": "not_ready",
        "service": "deepfake-detection-api",
        "image_model_loaded": bool(image_model_loaded),
        "video_model_loaded": bool(video_model_loaded)
    }), 503


# ------------------------------------------------------------------------------
# 1. DEDICATED IMAGE ENDPOINT: /Detect/image & /api/v1/detect/image
# ------------------------------------------------------------------------------
@app.route('/Detect/image', methods=['POST'])
@app.route('/api/v1/detect/image', methods=['POST'])
def detect_image_endpoint():
    request_id = str(uuid.uuid4())

    if not image_model_loaded:
        return jsonify({
            "status": "error",
            "output": "ERROR",
            "confidence": 0.0,
            "error": "Image detection model is not ready or failed to load. Please check /health.",
            "request_id": request_id
        }), 503

    uploaded_file = _extract_uploaded_file(request)
    if not uploaded_file:
        return jsonify({
            "status": "error",
            "output": "ERROR",
            "confidence": 0.0,
            "error": "No image file uploaded.",
            "request_id": request_id
        }), 400

    filename = secure_filename(uploaded_file.filename)
    file_type, mime = detect_file_type(uploaded_file, filename)

    if file_type == "video":
        logger.warning(f"[{request_id}] Rejected video file '{filename}' on image endpoint.")
        return jsonify({
            "status": "error",
            "output": "ERROR",
            "confidence": 0.0,
            "input_type": "video",
            "error": "Invalid input type: video file sent to image endpoint. Please use the video endpoint.",
            "request_id": request_id,
            "filename": filename
        }), 400

    if file_type != "image":
        return jsonify({
            "status": "error",
            "output": "ERROR",
            "confidence": 0.0,
            "input_type": file_type,
            "error": f"Invalid or unsupported file format for image endpoint: {mime}",
            "request_id": request_id,
            "filename": filename
        }), 400

    saved_name = f"{request_id}_{filename}"
    temp_path = os.path.join(app.config['UPLOAD_FOLDER'], saved_name)
    uploaded_file.save(temp_path)

    wants_json = request.is_json or 'application/json' in request.headers.get('Accept', '') or                  request.headers.get('X-Requested-With') == 'XMLHttpRequest' or                  request.headers.get('Sec-Fetch-Dest') != 'document'

    try:
        result = detectFakeImage(temp_path, request_id=request_id)
        result["filename"] = filename
        if wants_json:
            return jsonify(result), 200
        return render_template("index.html", data=json.dumps(result)), 200

    except ValueError as ve:
        logger.warning(f"[{request_id}] Validation error during image processing: {ve}")
        resp = {
            "status": "error",
            "output": "ERROR",
            "confidence": 0.0,
            "error": str(ve),
            "request_id": request_id,
            "filename": filename
        }
        if wants_json:
            return jsonify(resp), 400
        return render_template("index.html", data=json.dumps(resp)), 400

    except Exception as e:
        logger.error(f"[{request_id}] Unexpected error during image detection: {e}", exc_info=True)
        resp = {
            "status": "error",
            "output": "ERROR",
            "confidence": 0.0,
            "error": "An internal error occurred while processing the image. Please verify file integrity.",
            "request_id": request_id,
            "filename": filename
        }
        if wants_json:
            return jsonify(resp), 500
        return render_template("index.html", data=json.dumps(resp)), 500

    finally:
        if os.path.exists(temp_path):
            try:
                os.remove(temp_path)
            except Exception:
                pass


# ------------------------------------------------------------------------------
# 2. DEDICATED VIDEO ENDPOINT: /Detect/video & /api/v1/detect/video
# ------------------------------------------------------------------------------
@app.route('/Detect/video', methods=['POST'])
@app.route('/api/v1/detect/video', methods=['POST'])
def detect_video_endpoint():
    request_id = str(uuid.uuid4())

    if not video_model_loaded:
        return jsonify({
            "status": "error",
            "output": "ERROR",
            "confidence": 0.0,
            "error": "Video detection model is not ready or failed to load. Please check /health.",
            "request_id": request_id
        }), 503

    uploaded_file = _extract_uploaded_file(request)
    if not uploaded_file:
        return jsonify({
            "status": "error",
            "output": "ERROR",
            "confidence": 0.0,
            "error": "No video file uploaded.",
            "request_id": request_id
        }), 400

    filename = secure_filename(uploaded_file.filename)
    file_type, mime = detect_file_type(uploaded_file, filename)

    if file_type == "image":
        logger.warning(f"[{request_id}] Rejected image file '{filename}' on video endpoint.")
        return jsonify({
            "status": "error",
            "output": "ERROR",
            "confidence": 0.0,
            "input_type": "image",
            "error": "Invalid input type: image file sent to video endpoint. Please use the image endpoint.",
            "request_id": request_id,
            "filename": filename
        }), 400

    if file_type != "video":
        return jsonify({
            "status": "error",
            "output": "ERROR",
            "confidence": 0.0,
            "input_type": file_type,
            "error": f"Invalid or unsupported file format for video endpoint: {mime}",
            "request_id": request_id,
            "filename": filename
        }), 400

    saved_name = f"{request_id}_{filename}"
    temp_path = os.path.join(app.config['UPLOAD_FOLDER'], saved_name)
    uploaded_file.save(temp_path)

    wants_json = request.is_json or 'application/json' in request.headers.get('Accept', '') or                  request.headers.get('X-Requested-With') == 'XMLHttpRequest' or                  request.headers.get('Sec-Fetch-Dest') != 'document'

    try:
        result = detectFakeVideo(temp_path, request_id=request_id)
        result["filename"] = filename
        if wants_json:
            return jsonify(result), 200
        return render_template("index.html", data=json.dumps(result)), 200

    except ValueError as ve:
        logger.warning(f"[{request_id}] Validation error during video processing: {ve}")
        resp = {
            "status": "error",
            "output": "ERROR",
            "confidence": 0.0,
            "error": str(ve),
            "request_id": request_id,
            "filename": filename
        }
        if wants_json:
            return jsonify(resp), 400
        return render_template("index.html", data=json.dumps(resp)), 400

    except Exception as e:
        logger.error(f"[{request_id}] Unexpected error during video detection: {e}", exc_info=True)
        resp = {
            "status": "error",
            "output": "ERROR",
            "confidence": 0.0,
            "error": "An internal error occurred while processing the video. Please verify video format and codec.",
            "request_id": request_id,
            "filename": filename
        }
        if wants_json:
            return jsonify(resp), 500
        return render_template("index.html", data=json.dumps(resp)), 500

    finally:
        if os.path.exists(temp_path):
            try:
                os.remove(temp_path)
            except Exception:
                pass


# ------------------------------------------------------------------------------
# 3. UNIFIED /Detect ENDPOINT (AUTOROUTING & REACT COMPATIBILITY)
# ------------------------------------------------------------------------------
@app.route('/Detect', methods=['GET', 'POST'])
def DetectPage():
    if request.method == 'GET':
        return render_template("index.html")

    request_id = str(uuid.uuid4())
    uploaded_file = _extract_uploaded_file(request)

    if not uploaded_file:
        data = json.dumps({
            "output": "ERROR",
            "confidence": 0.0,
            "error": "No file uploaded.",
            "request_id": request_id
        })
        return render_template("index.html", data=data), 400

    filename = secure_filename(uploaded_file.filename)
    file_type, mime = detect_file_type(uploaded_file, filename)

    saved_name = f"{request_id}_{filename}"
    temp_path = os.path.join(app.config['UPLOAD_FOLDER'], saved_name)
    uploaded_file.save(temp_path)

    logger.info(f"[{request_id}] Unified /Detect request: file='{filename}', detected_type='{file_type}'")

    try:
        if file_type == "image":
            result = detectFakeImage(temp_path, request_id=request_id)
        elif file_type == "video":
            result = detectFakeVideo(temp_path, request_id=request_id)
        else:
            raise ValueError(f"Invalid or unsupported file format: {mime} ({filename})")

        result["filename"] = filename
        data = json.dumps(result)
        return render_template("index.html", data=data), 200

    except ValueError as ve:
        logger.warning(f"[{request_id}] Validation error in /Detect: {ve}")
        data = json.dumps({
            "output": "ERROR",
            "confidence": 0.0,
            "error": str(ve),
            "request_id": request_id,
            "filename": filename
        })
        return render_template("index.html", data=data), 400

    except Exception as e:
        logger.error(f"[{request_id}] Unexpected error in /Detect: {e}", exc_info=True)
        data = json.dumps({
            "output": "ERROR",
            "confidence": 0.0,
            "error": "An internal error occurred during detection.",
            "request_id": request_id,
            "filename": filename
        })
        return render_template("index.html", data=data), 500

    finally:
        if os.path.exists(temp_path):
            try:
                os.remove(temp_path)
            except Exception:
                pass


# ==============================================================================
# STARTUP INITIALIZATION
# ==============================================================================
cleanup_stale_uploads()
# Note: Models are initialized lazily upon first request to prevent premature CUDA initialization.


# ==============================================================================
# RUN (LOCAL / WSGI ENTRY POINT)
# ==============================================================================
if __name__ == '__main__':
    init_models()
    host = os.environ.get("HOST", "0.0.0.0")
    port = int(os.environ.get("PORT", 7860))
    logger.info(f"Starting server on {host}:{port}...")
    app.run(host=host, port=port)