File size: 5,032 Bytes
395115f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import FastAPI, HTTPException, File, UploadFile
from fastapi.middleware.cors import CORSMiddleware
import torch
import torchvision.transforms as transforms
from PIL import Image
import numpy as np
import json
import base64
from io import BytesIO
import uvicorn

app = FastAPI(title="VerifAI GradCAM API Simple", description="API simplifiée pour la détection d'images IA")

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

class SimpleAIDetector:
    def __init__(self):
        self.device = torch.device('cpu')  # Utiliser CPU pour éviter les problèmes GPU
        self.transform = transforms.Compose([
            transforms.Resize((224, 224)),
            transforms.ToTensor(),
            transforms.Normalize(mean=[0.485, 0.456, 0.406], 
                               std=[0.229, 0.224, 0.225])
        ])
    
    def _preprocess_image(self, image):
        """Prétraite l'image"""
        if isinstance(image, str):
            if image.startswith('data:image'):
                header, data = image.split(',', 1)
                image_data = base64.b64decode(data)
                image = Image.open(BytesIO(image_data))
            else:
                image = Image.open(image)
        
        if image.mode != 'RGB':
            image = image.convert('RGB')
        
        return image
    
    def predict_simple(self, image):
        """Prédiction simple sans modèle complexe"""
        try:
            # Prétraitement
            processed_image = self._preprocess_image(image)
            
            # Simulation d'une prédiction (remplacez par votre modèle réel)
            # Pour l'instant, on fait une prédiction basée sur la variance des couleurs
            img_array = np.array(processed_image)
            color_variance = np.var(img_array)
            
            # Logique simple : plus de variance = plus probable d'être réel
            if color_variance > 1000:
                prediction = 0  # Real
                confidence = min(0.9, color_variance / 2000)
            else:
                prediction = 1  # AI-Generated
                confidence = min(0.9, 1 - color_variance / 2000)
            
            # Créer une "carte de saillance" simple (gradient coloré)
            height, width = img_array.shape[:2]
            gradient = np.zeros((height, width, 3), dtype=np.uint8)
            for i in range(height):
                for j in range(width):
                    gradient[i, j] = [int(255 * i / height), int(255 * j / width), 128]
            
            # Convertir en base64
            pil_image = Image.fromarray(gradient)
            buffer = BytesIO()
            pil_image.save(buffer, format='PNG')
            cam_base64 = base64.b64encode(buffer.getvalue()).decode()
            
            result = {
                'prediction': prediction,
                'confidence': confidence,
                'class_probabilities': {
                    'Real': 1 - prediction if prediction == 0 else 1 - confidence,
                    'AI-Generated': prediction if prediction == 1 else confidence
                },
                'cam_image': f"data:image/png;base64,{cam_base64}",
                'status': 'success',
                'note': 'Version simplifiée pour test'
            }
            
            return result
            
        except Exception as e:
            return {'status': 'error', 'message': str(e)}

# Initialiser le détecteur
detector = SimpleAIDetector()

@app.get("/")
async def root():
    return {
        "message": "VerifAI GradCAM API Simple", 
        "status": "running",
        "version": "1.0-simple"
    }

@app.get("/health")
async def health():
    return {"status": "healthy", "device": str(detector.device)}

@app.post("/predict")
async def predict_image(file: UploadFile = File(...)):
    """Endpoint pour analyser une image"""
    try:
        # Lire l'image
        image_data = await file.read()
        image = Image.open(BytesIO(image_data))
        
        # Analyser
        result = detector.predict_simple(image)
        
        return result
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/predict-base64")
async def predict_base64(data: dict):
    """Endpoint pour analyser une image en base64"""
    try:
        if 'image' not in data:
            raise HTTPException(status_code=400, detail="Champ 'image' requis")
        
        image_b64 = data['image']
        
        # Analyser
        result = detector.predict_simple(image_b64)
        
        return result
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=7860)