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
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
import base64
import gc
import io
import logging
import os
import platform
import sys
import threading
import time
import traceback
from typing import Any, Dict, Optional

import torch
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from PIL import Image
from pydantic import BaseModel

# Setup more detailed logging
logging.basicConfig(
    level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)

# Initialize FastAPI
app = FastAPI(
    title="UniversalFakeDetect API",
    description="API for Universal Fake Image Detector",
    version="1.0.0",
)

# Add CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


# Environment variables
def _get_device():
    """Select optimal device: MPS (Apple) > CUDA (NVIDIA) > CPU."""
    override = os.environ.get("DEEPSAFE_DEVICE", "").strip().lower()
    if override == "cpu":
        return torch.device("cpu")
    if override == "cuda" and torch.cuda.is_available():
        return torch.device("cuda")
    if (
        override == "mps"
        and hasattr(torch.backends, "mps")
        and torch.backends.mps.is_available()
    ):
        return torch.device("mps")
    if override:
        pass  # Invalid override, fall through to auto-detect
    if (
        platform.system() == "Darwin"
        and hasattr(torch.backends, "mps")
        and torch.backends.mps.is_available()
    ):
        return torch.device("mps")
    if torch.cuda.is_available():
        return torch.device("cuda")
    return torch.device("cpu")


DEVICE = _get_device()
USE_GPU = DEVICE.type != "cpu"
if DEVICE.type == "cuda":
    torch.backends.cudnn.benchmark = True
    torch.set_float32_matmul_precision("high")
if DEVICE.type == "cuda":
    logger.info(
        "Device: cuda (%s, %.1f GB VRAM)",
        torch.cuda.get_device_name(0),
        torch.cuda.get_device_properties(0).total_memory / 1024**3,
    )
else:
    logger.warning(
        "Device: %s (no CUDA available -- check nvidia-container-toolkit)",
        DEVICE,
    )
MODEL_PORT = int(os.environ.get("MODEL_PORT", 5003))
PRELOAD_MODEL = os.environ.get("PRELOAD_MODEL", "false").lower() == "true"
MODEL_TIMEOUT = int(
    os.environ.get("MODEL_TIMEOUT", "600")
)  # Seconds to keep model loaded
logger.info(f"Using device: {DEVICE}")
logger.info(f"CUDA available: {torch.cuda.is_available()}")
if torch.cuda.is_available():
    logger.info(f"CUDA device count: {torch.cuda.device_count()}")
    logger.info(f"CUDA device name: {torch.cuda.get_device_name(0)}")

from typing import Optional

# Define input model
from pydantic import BaseModel


class ImageInput(BaseModel):
    image_data: str  # Renamed field
    threshold: Optional[float] = 0.5


# Global variables for model
model = None
model_lock = threading.Lock()
last_used_time = 0
model_loading = False


# Download weights if not present
def download_weights():
    weights_path = "universalfakedetect/pretrained_weights/fc_weights.pth"
    if not os.path.exists("universalfakedetect/pretrained_weights"):
        os.makedirs("universalfakedetect/pretrained_weights", exist_ok=True)
        logger.info("Created pretrained_weights directory")

    if not os.path.exists(weights_path):
        logger.info("Weights file not found, downloading...")
        import urllib.request

        url = "https://github.com/WisconsinAIVision/UniversalFakeDetect/raw/main/pretrained_weights/fc_weights.pth"
        urllib.request.urlretrieve(url, weights_path)
        logger.info(f"Downloaded weights to {weights_path}")


# Load the model
def load_model():
    """Load the UniversalFakeDetect model."""
    global model, last_used_time, model_loading

    # If model is already loaded, update timestamp and return
    if model is not None:
        last_used_time = time.time()
        return model

    with model_lock:  # Thread safety for concurrent requests
        # Check again after acquiring the lock
        if model is not None:
            last_used_time = time.time()
            return model

        # Set flag to indicate model is loading
        model_loading = True

        try:
            logger.info(f"Loading UniversalFakeDetect model on {DEVICE}...")

            # List directory contents for debugging
            logger.info(f"Current directory: {os.getcwd()}")
            logger.info(f"Directory contents: {os.listdir('.')}")

            if os.path.exists("universalfakedetect"):
                logger.info(
                    f"universalfakedetect directory contents: {os.listdir('universalfakedetect')}"
                )
            else:
                logger.error("universalfakedetect directory not found!")
                model_loading = False
                return None

            # Ensure weights exist
            download_weights()
            weights_path = "universalfakedetect/pretrained_weights/fc_weights.pth"

            # Import model modules
            logger.info("Adding universalfakedetect to sys.path")
            sys.path.append(os.path.abspath("universalfakedetect"))

            logger.info("Importing get_model from models")
            try:
                # Try direct import first
                from models import get_model

                logger.info("Successfully imported get_model")
            except ImportError as e:
                logger.warning(
                    f"Direct import failed: {str(e)}, trying alternate import"
                )
                from universalfakedetect.models import get_model

                logger.info("Successfully imported get_model with alternate path")
            except Exception as e:
                logger.error(f"Error importing get_model: {str(e)}")
                logger.error(traceback.format_exc())
                model_loading = False
                return None

            # Initialize the model
            logger.info("Initializing model with CLIP:ViT-L/14")
            model = get_model("CLIP:ViT-L/14")

            # Load the weights
            logger.info(f"Loading weights from {weights_path}")
            state_dict = torch.load(weights_path, map_location="cpu")
            model.fc.load_state_dict(state_dict)

            # Move model to device and set to evaluation mode
            logger.info(f"Moving model to device: {DEVICE}")
            model.to(DEVICE)
            model.eval()

            # Update last used time
            last_used_time = time.time()

            # Clear CUDA cache to free up memory
            if USE_GPU:
                if torch.cuda.is_available():
                    torch.cuda.empty_cache()
            gc.collect()

            logger.info("Model loaded successfully!")
            model_loading = False
            return model

        except Exception as e:
            logger.error(f"Error loading model: {str(e)}")
            logger.error(traceback.format_exc())
            model_loading = False
            return None


@app.post("/unload", include_in_schema=True)
async def unload_model_endpoint():
    """Endpoint to manually unload the model."""
    global model

    if model_loading:
        return {
            "status": "loading_busy",
            "message": "Model is currently being loaded, cannot unload now.",
        }

    if model is None:
        return {"status": "not_loaded", "message": "Model is not currently loaded."}

    with model_lock:
        if model is not None:  # Check again inside lock
            logger.info(
                "Manually unloading UniversalFakeDetect model via /unload endpoint."
            )
            del model
            model = None
            # Clear CUDA cache if it was used (though DEVICE is 'cpu' here, good practice)
            if DEVICE.type == "cuda":
                if torch.cuda.is_available():
                    torch.cuda.empty_cache()
            gc.collect()
            logger.info("UniversalFakeDetect model unloaded and memory cleared.")
            return {"status": "unloaded", "message": "Model unloaded successfully."}
        else:  # Should not happen if initial check was model is not None
            return {
                "status": "already_unloaded",
                "message": "Model was already unloaded.",
            }


def unload_model_if_idle():
    """Unload model if it's been idle for too long."""
    global model

    if model is None:
        return

    if time.time() - last_used_time > MODEL_TIMEOUT:
        with model_lock:
            if model is not None and time.time() - last_used_time > MODEL_TIMEOUT:
                logger.info(
                    f"Unloading model after {MODEL_TIMEOUT} seconds of inactivity"
                )
                # Delete model and clear memory
                del model
                model = None
                # Clear CUDA cache
                if USE_GPU:
                    if torch.cuda.is_available():
                        torch.cuda.empty_cache()
                gc.collect()
                logger.info("Model unloaded and memory cleared")


# Preprocess image for inference
def preprocess_image(image_bytes):
    try:
        # Read the image
        image = Image.open(io.BytesIO(image_bytes)).convert("RGB")

        # Preprocess image
        from torchvision import transforms

        # These values are from the validate.py file in the repository
        mean = [0.48145466, 0.4578275, 0.40821073]  # CLIP values
        std = [0.26862954, 0.26130258, 0.27577711]  # CLIP values

        transform = transforms.Compose(
            [
                transforms.CenterCrop(224),
                transforms.ToTensor(),
                transforms.Normalize(mean=mean, std=std),
            ]
        )

        img_tensor = transform(image).unsqueeze(0)  # Add batch dimension
        return img_tensor.to(DEVICE)
    except Exception as e:
        logger.error(f"Error preprocessing image: {str(e)}")
        logger.error(traceback.format_exc())
        raise HTTPException(status_code=400, detail=f"Invalid image format: {str(e)}")


# Predict function
def predict(image_tensor, threshold=0.5):
    try:
        with torch.no_grad():
            # Forward pass through the model
            output = model(image_tensor).sigmoid().flatten().item()
            # The model outputs a score between 0 and 1, where higher values indicate fake images
            prediction = 1 if output >= threshold else 0

            return {
                "probability": float(output),
                "prediction": int(prediction),
                "class": "fake" if prediction == 1 else "real",
            }
    except Exception as e:
        logger.error(f"Prediction error: {str(e)}")
        logger.error(traceback.format_exc())
        raise HTTPException(status_code=500, detail=f"Prediction error: {str(e)}")


# Root endpoint
@app.get("/")
def read_root():
    return {
        "model": "UniversalFakeDetect",
        "description": "Universal Fake Image Detector that Generalizes Across Generative Models",
        "authors": "Utkarsh Ojha, Yuheng Li, Yong Jae Lee",
        "paper": "https://arxiv.org/abs/2302.10174",
        "source": "https://github.com/WisconsinAIVision/UniversalFakeDetect",
        "model_loaded": model is not None,
        "lazy_loading": not PRELOAD_MODEL,
    }


def _gpu_health_info() -> dict:
    """Return GPU metrics for the health endpoint."""
    if torch.cuda.is_available() and DEVICE.type == "cuda":
        return {
            "gpu_name": torch.cuda.get_device_name(0),
            "vram_used_mb": round(torch.cuda.memory_allocated(0) / 1024**2),
            "vram_total_mb": round(
                torch.cuda.get_device_properties(0).total_memory / 1024**2
            ),
        }
    return {}


# Health check endpoint
@app.get("/health")
def health_check():
    weights_path = "universalfakedetect/pretrained_weights/fc_weights.pth"
    model_file_exists = os.path.exists(weights_path)

    if model is not None:
        return {
            "status": "healthy",
            "device": str(DEVICE),
            "model_loaded": True,
            **_gpu_health_info(),
        }
    elif model_loading:
        return {
            "status": "loading",
            "message": "Model is being loaded",
            "device": str(DEVICE),
        }
    elif not model_file_exists:
        return {
            "status": "missing_weights",
            "message": "Model weights not found",
            "device": str(DEVICE),
        }
    else:
        return {
            "status": "not_loaded",
            "message": "Model not loaded yet",
            "device": str(DEVICE),
        }


# Prediction endpoint
@app.post("/predict")
async def predict_image(input_data: ImageInput) -> Dict[str, Any]:
    # Check if model is loaded
    global model, last_used_time

    try:
        # Load model if not already loaded
        if model is None:
            logger.info("Model not loaded. Loading model now...")
            model = load_model()
            if model is None:
                raise HTTPException(status_code=500, detail="Failed to load model")
        else:
            # Update timestamp if already loaded
            last_used_time = time.time()

        # Decode base64 image
        image_bytes = base64.b64decode(input_data.image_data)

        # Start timing
        start_time = time.time()

        # Optimize memory during inference
        if USE_GPU:
            if torch.cuda.is_available():
                torch.cuda.empty_cache()

        # Preprocess the image
        image_tensor = preprocess_image(image_bytes)

        # Get predictions
        results = predict(image_tensor, input_data.threshold)

        # Calculate inference time
        inference_time = time.time() - start_time

        # Schedule unloading after timeout - run in background
        threading.Timer(5.0, unload_model_if_idle).start()

        # Return results
        return {
            "model": "UniversalFakeDetect",
            "probability": results["probability"],
            "prediction": results["prediction"],
            "class": results["class"],
            "inference_time": inference_time,
        }
    except Exception as e:
        logger.error(f"Error during prediction: {str(e)}")
        logger.error(traceback.format_exc())
        raise HTTPException(status_code=500, detail=str(e))


# Load model on startup
@app.on_event("startup")
async def startup_event():
    """Load model on startup only if PRELOAD_MODEL is true."""
    if PRELOAD_MODEL:
        logger.info("Preloading model at startup (PRELOAD_MODEL=true)")
        try:
            load_model()
        except Exception as e:
            logger.error(f"Preloading failed: {str(e)}")
    else:
        logger.info("Model will be loaded on first request (PRELOAD_MODEL=false)")


# Run the server
if __name__ == "__main__":
    import uvicorn

    uvicorn.run("app:app", host="0.0.0.0", port=MODEL_PORT, reload=False)