File size: 1,512 Bytes
6c9d916
8e30b6a
 
 
6c9d916
 
8e30b6a
 
 
6c9d916
 
 
 
 
 
 
 
 
 
 
 
 
8e30b6a
 
6c9d916
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import io
import logging
import time
from typing import Dict, Any
from PIL import Image
from transformers import pipeline

logger = logging.getLogger(__name__)

_image_classifier = None

def _load_model():
    global _image_classifier
    if _image_classifier is None:
        logger.info("Loading capcheck/ai-image-detection model...")
        _image_classifier = pipeline(
            "image-classification",
            model="capcheck/ai-image-detection",
            device=-1 
        )
        logger.info("Image detector model loaded successfully")
    return _image_classifier

async def analyze_image(image_bytes: bytes) -> Dict[str, Any]:
    start_time = time.time()
    
    logger.info(f"Starting image analysis, size: {len(image_bytes)} bytes")
    
    try:
        image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
    except Exception as e:
        logger.error(f"Failed to parse image bytes: {str(e)}")
        raise ValueError("Invalid image format or corrupted bytes") from e
    
    classifier = _load_model()
    
    result = classifier(image)
    
    label = result[0]["label"]
    score = result[0]["score"]
    
    is_deepfake = label.lower() == "fake"
    confidence = score
    
    analysis_time = time.time() - start_time
    
    response = {
        "is_deepfake": is_deepfake,
        "confidence": round(confidence, 3),
        "analysis_time": round(analysis_time, 3),
    }
    
    logger.info(f"Image analysis completed. Result: {response}")
    return response