yaya36095 commited on
Commit
54240fb
·
verified ·
1 Parent(s): 8b1e242

Update handler.py

Browse files
Files changed (1) hide show
  1. handler.py +18 -4
handler.py CHANGED
@@ -1,7 +1,7 @@
1
  import base64
2
  import io
3
  import os
4
- from typing import Dict, Any
5
 
6
  import torch
7
  from PIL import Image
@@ -81,11 +81,14 @@ class EndpointHandler:
81
  # --------------------------------------------------
82
  # 3) الدالة الرئيسة
83
  # --------------------------------------------------
84
- def __call__(self, data: Any) -> Dict[str, float]:
85
  """
86
  يدعم:
87
  • Widget (PIL.Image)
88
  • REST (base64 فى data["inputs"] أو data["image"])
 
 
 
89
  """
90
  img: Image.Image | None = None
91
 
@@ -99,10 +102,21 @@ class EndpointHandler:
99
  img = self._decode_b64(payload)
100
 
101
  if img is None:
102
- return {"error": "No image provided"}
103
 
104
  with torch.no_grad():
105
  logits = self.model(self._img_to_tensor(img))
106
  probs = torch.nn.functional.softmax(logits.squeeze(0), dim=0)
107
 
108
- return {self.labels[i]: float(probs[i]) for i in range(len(self.labels))}
 
 
 
 
 
 
 
 
 
 
 
 
1
  import base64
2
  import io
3
  import os
4
+ from typing import Dict, Any, List
5
 
6
  import torch
7
  from PIL import Image
 
81
  # --------------------------------------------------
82
  # 3) الدالة الرئيسة
83
  # --------------------------------------------------
84
+ def __call__(self, data: Any) -> List[Dict[str, Any]]:
85
  """
86
  يدعم:
87
  • Widget (PIL.Image)
88
  • REST (base64 فى data["inputs"] أو data["image"])
89
+
90
+ يعيد:
91
+ • مصفوفة من القواميس بتنسيق [{label: string, score: number}, ...]
92
  """
93
  img: Image.Image | None = None
94
 
 
102
  img = self._decode_b64(payload)
103
 
104
  if img is None:
105
+ return [{"label": "error", "score": 1.0}]
106
 
107
  with torch.no_grad():
108
  logits = self.model(self._img_to_tensor(img))
109
  probs = torch.nn.functional.softmax(logits.squeeze(0), dim=0)
110
 
111
+ # تحويل النتائج إلى التنسيق المطلوب: Array<label: string, score:number>
112
+ results = []
113
+ for i, label in enumerate(self.labels):
114
+ results.append({
115
+ "label": label,
116
+ "score": float(probs[i])
117
+ })
118
+
119
+ # ترتيب النتائج تنازلياً حسب درجة الثقة
120
+ results.sort(key=lambda x: x["score"], reverse=True)
121
+
122
+ return results