TerenceG commited on
Commit
2e640a4
·
verified ·
1 Parent(s): 844700f

Update handler.py

Browse files
Files changed (1) hide show
  1. handler.py +108 -35
handler.py CHANGED
@@ -5,11 +5,12 @@ import base64
5
  import io
6
  import torch.nn.functional as F
7
  import gc
 
8
 
9
  class EndpointHandler:
10
  def __init__(self, path=""):
11
- print("🚀 VerifAI Handler V4 MINIMAL - Initialisation")
12
- print("⚡ Version ultra-simplifiée")
13
 
14
  self.model = None
15
  self.processor = None
@@ -19,7 +20,6 @@ class EndpointHandler:
19
  try:
20
  print("🔄 Chargement modèle...")
21
 
22
- # Chargement simple
23
  self.processor = AutoImageProcessor.from_pretrained(self.model_name)
24
  self.model = AutoModelForImageClassification.from_pretrained(
25
  self.model_name,
@@ -27,7 +27,6 @@ class EndpointHandler:
27
  )
28
  self.model.eval()
29
 
30
- # Labels
31
  if hasattr(self.model.config, 'id2label'):
32
  self.model_labels = self.model.config.id2label
33
  else:
@@ -35,14 +34,54 @@ class EndpointHandler:
35
 
36
  print("✅ Modèle chargé")
37
  print(f"📋 Labels: {self.model_labels}")
38
- print("🎯 Handler V4 prêt!")
39
 
40
  except Exception as e:
41
  print(f"❌ Erreur: {e}")
42
  self.model = None
43
  self.processor = None
44
 
45
- def _normalize_label(self, label: str) -> str:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  """Normalise les labels"""
47
  if not isinstance(label, str):
48
  label = str(label)
@@ -65,24 +104,38 @@ class EndpointHandler:
65
  "confidence": 0.0,
66
  "class_probabilities": {"Human": 0.0, "AI Generated": 0.0},
67
  "cam_image": None,
68
- "version": "4.0-minimal",
69
- "handler_name": "VerifAI Handler V4 MINIMAL"
70
  }
71
 
72
  try:
73
- print("🔄 Traitement...")
 
 
 
 
74
 
75
- # Extraction image
76
- image_data = data.get("inputs") or data
77
  if not image_data:
78
- raise ValueError("Pas de données image")
79
 
80
- # Décodage
81
- if isinstance(image_data, str) and image_data.startswith('data:'):
82
- image_data = image_data.split(',', 1)[1]
83
 
84
- image_bytes = base64.b64decode(image_data)
85
- image = Image.open(io.BytesIO(image_bytes))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
  if image.mode != 'RGB':
88
  image = image.convert('RGB')
@@ -90,6 +143,7 @@ class EndpointHandler:
90
  # Redimensionnement si nécessaire
91
  if image.size[0] * image.size[1] > 1048576: # Plus de 1MP
92
  image = image.resize((512, 512), Image.Resampling.LANCZOS)
 
93
 
94
  print("🧠 Inférence...")
95
 
@@ -131,17 +185,23 @@ class EndpointHandler:
131
  "predicted_class_name": prediction_label,
132
  "confidence": confidence,
133
  "class_probabilities": class_probs,
134
- "cam_image": None, # Désactivé
135
  "model_info": {
136
  "model_name": self.model_name,
137
- "handler_version": "verifai-v4-minimal",
138
  "precision_mode": "fast",
139
  "raw_prediction_id": predicted_class_id,
140
  "raw_labels": self.model_labels
141
  },
142
- "version": "4.0-minimal",
143
- "handler_name": "VerifAI Handler V4 MINIMAL",
144
- "note": "Version ultra-simplifiée pour compatibilité maximale"
 
 
 
 
 
 
145
  }
146
 
147
  except Exception as e:
@@ -155,14 +215,18 @@ class EndpointHandler:
155
  "confidence": 0.0,
156
  "class_probabilities": {"Human": 0.0, "AI Generated": 0.0},
157
  "cam_image": None,
158
- "version": "4.0-minimal",
159
- "handler_name": "VerifAI Handler V4 MINIMAL"
 
 
 
 
160
  }
161
 
162
- # Test simple
163
  if __name__ == "__main__":
164
- print("🧪 TEST HANDLER V4 MINIMAL")
165
- print("=" * 40)
166
 
167
  try:
168
  handler = EndpointHandler()
@@ -170,20 +234,29 @@ if __name__ == "__main__":
170
  if handler.model is not None:
171
  print("✅ Initialisation OK")
172
 
173
- # Test
174
  test_img = Image.new('RGB', (224, 224), color='red')
175
  buffer = io.BytesIO()
176
  test_img.save(buffer, format='JPEG')
177
  test_data = base64.b64encode(buffer.getvalue()).decode('utf-8')
178
 
179
- result = handler({"inputs": test_data})
 
 
 
 
180
 
181
- print(f"📊 Statut: {result['status']}")
182
- if result['status'] == 'success':
183
- print(f"🎯 Prédiction: {result['predicted_class_name']} ({result['confidence']:.3f})")
184
- print("✅ Handler V4 MINIMAL fonctionnel!")
185
- else:
186
- print(f"❌ Erreur: {result.get('error', 'Inconnue')}")
 
 
 
 
 
187
  else:
188
  print("❌ Échec initialisation")
189
 
 
5
  import io
6
  import torch.nn.functional as F
7
  import gc
8
+ import json
9
 
10
  class EndpointHandler:
11
  def __init__(self, path=""):
12
+ print("🚀 VerifAI Handler V5 ULTRA ROBUST - Initialisation")
13
+ print("⚡ Version ultra-robuste")
14
 
15
  self.model = None
16
  self.processor = None
 
20
  try:
21
  print("🔄 Chargement modèle...")
22
 
 
23
  self.processor = AutoImageProcessor.from_pretrained(self.model_name)
24
  self.model = AutoModelForImageClassification.from_pretrained(
25
  self.model_name,
 
27
  )
28
  self.model.eval()
29
 
 
30
  if hasattr(self.model.config, 'id2label'):
31
  self.model_labels = self.model.config.id2label
32
  else:
 
34
 
35
  print("✅ Modèle chargé")
36
  print(f"📋 Labels: {self.model_labels}")
37
+ print("🎯 Handler V5 prêt!")
38
 
39
  except Exception as e:
40
  print(f"❌ Erreur: {e}")
41
  self.model = None
42
  self.processor = None
43
 
44
+ def _extract_image_data(self, data):
45
+ """Extraction robuste des données image"""
46
+ try:
47
+ # Cas 1: data est directement la string base64
48
+ if isinstance(data, str):
49
+ print("📄 Input détecté: string directe")
50
+ return data
51
+
52
+ # Cas 2: data est un dict avec clé "inputs"
53
+ if isinstance(data, dict):
54
+ print("📄 Input détecté: dictionnaire")
55
+
56
+ # Essayer "inputs"
57
+ if "inputs" in data:
58
+ return data["inputs"]
59
+
60
+ # Essayer d'autres clés communes
61
+ for key in ["image", "data", "input", "content"]:
62
+ if key in data:
63
+ return data[key]
64
+
65
+ # Si aucune clé connue, prendre la première valeur
66
+ if data:
67
+ first_value = list(data.values())[0]
68
+ print(f"🔍 Utilisation de la première valeur: {type(first_value)}")
69
+ return first_value
70
+
71
+ # Cas 3: data est une liste
72
+ if isinstance(data, list) and len(data) > 0:
73
+ print("📄 Input détecté: liste")
74
+ return data[0]
75
+
76
+ # Cas 4: autres types
77
+ print(f"📄 Input détecté: {type(data)}")
78
+ return str(data)
79
+
80
+ except Exception as e:
81
+ print(f"⚠️ Erreur extraction: {e}")
82
+ return None
83
+
84
+ def _normalize_label(self, label):
85
  """Normalise les labels"""
86
  if not isinstance(label, str):
87
  label = str(label)
 
104
  "confidence": 0.0,
105
  "class_probabilities": {"Human": 0.0, "AI Generated": 0.0},
106
  "cam_image": None,
107
+ "version": "5.0-ultra-robust",
108
+ "handler_name": "VerifAI Handler V5 ULTRA ROBUST"
109
  }
110
 
111
  try:
112
+ print("🔄 Traitement ultra-robuste...")
113
+ print(f"🔍 Type d'input reçu: {type(data)}")
114
+
115
+ # Extraction robuste des données
116
+ image_data = self._extract_image_data(data)
117
 
 
 
118
  if not image_data:
119
+ raise ValueError("Aucune donnée image trouvée")
120
 
121
+ print(f"🔍 Données extraites: {type(image_data)}, longueur: {len(str(image_data)) if image_data else 0}")
 
 
122
 
123
+ # Nettoyage du base64
124
+ if isinstance(image_data, str):
125
+ # Supprimer le préfixe data URI si présent
126
+ if image_data.startswith('data:'):
127
+ image_data = image_data.split(',', 1)[1]
128
+
129
+ # Supprimer les espaces et retours de ligne
130
+ image_data = image_data.strip().replace('\n', '').replace('\r', '').replace(' ', '')
131
+
132
+ # Décodage
133
+ try:
134
+ image_bytes = base64.b64decode(image_data)
135
+ image = Image.open(io.BytesIO(image_bytes))
136
+ print(f"✅ Image décodée: {image.size}, mode: {image.mode}")
137
+ except Exception as e:
138
+ raise ValueError(f"Erreur décodage base64: {e}")
139
 
140
  if image.mode != 'RGB':
141
  image = image.convert('RGB')
 
143
  # Redimensionnement si nécessaire
144
  if image.size[0] * image.size[1] > 1048576: # Plus de 1MP
145
  image = image.resize((512, 512), Image.Resampling.LANCZOS)
146
+ print("⚠️ Image redimensionnée")
147
 
148
  print("🧠 Inférence...")
149
 
 
185
  "predicted_class_name": prediction_label,
186
  "confidence": confidence,
187
  "class_probabilities": class_probs,
188
+ "cam_image": None,
189
  "model_info": {
190
  "model_name": self.model_name,
191
+ "handler_version": "verifai-v5-ultra-robust",
192
  "precision_mode": "fast",
193
  "raw_prediction_id": predicted_class_id,
194
  "raw_labels": self.model_labels
195
  },
196
+ "version": "5.0-ultra-robust",
197
+ "handler_name": "VerifAI Handler V5 ULTRA ROBUST",
198
+ "note": "Version ultra-robuste - gère tous les formats d'entrée",
199
+ "input_analysis": {
200
+ "original_type": str(type(data)),
201
+ "extracted_type": str(type(image_data)),
202
+ "image_size": image.size,
203
+ "image_mode": image.mode
204
+ }
205
  }
206
 
207
  except Exception as e:
 
215
  "confidence": 0.0,
216
  "class_probabilities": {"Human": 0.0, "AI Generated": 0.0},
217
  "cam_image": None,
218
+ "version": "5.0-ultra-robust",
219
+ "handler_name": "VerifAI Handler V5 ULTRA ROBUST",
220
+ "debug_info": {
221
+ "input_type": str(type(data)),
222
+ "input_content": str(data)[:100] + "..." if data else "None"
223
+ }
224
  }
225
 
226
+ # Test
227
  if __name__ == "__main__":
228
+ print("🧪 TEST HANDLER V5 ULTRA ROBUST")
229
+ print("=" * 50)
230
 
231
  try:
232
  handler = EndpointHandler()
 
234
  if handler.model is not None:
235
  print("✅ Initialisation OK")
236
 
237
+ # Test avec différents formats
238
  test_img = Image.new('RGB', (224, 224), color='red')
239
  buffer = io.BytesIO()
240
  test_img.save(buffer, format='JPEG')
241
  test_data = base64.b64encode(buffer.getvalue()).decode('utf-8')
242
 
243
+ test_cases = [
244
+ {"inputs": test_data}, # Format dict
245
+ test_data, # String directe
246
+ [test_data], # Liste
247
+ ]
248
 
249
+ for i, test_case in enumerate(test_cases, 1):
250
+ print(f"\n🔄 Test {i}: {type(test_case)}")
251
+ result = handler(test_case)
252
+
253
+ print(f"📊 Statut: {result['status']}")
254
+ if result['status'] == 'success':
255
+ print(f"🎯 Prédiction: {result['predicted_class_name']} ({result['confidence']:.3f})")
256
+ else:
257
+ print(f"❌ Erreur: {result.get('error', 'Inconnue')}")
258
+
259
+ print("\n✅ Handler V5 ULTRA ROBUST testé!")
260
  else:
261
  print("❌ Échec initialisation")
262