eyad-ai commited on
Commit
1031221
·
verified ·
1 Parent(s): 07c533a

Delete handler.py

Browse files
Files changed (1) hide show
  1. handler.py +0 -82
handler.py DELETED
@@ -1,82 +0,0 @@
1
- import os
2
- import json
3
- import torch
4
- import torch.nn as nn
5
- from PIL import Image
6
- import io
7
- from transformers import AutoImageProcessor, AutoModel, AutoModelForImageClassification
8
-
9
- class EndpointHandler:
10
- def __init__(self, path=""):
11
- self.device = "cuda" if torch.cuda.is_available() else "cpu"
12
-
13
- # قراءة معلومات الأصناف
14
- meta_file = os.path.join(path, "meta.json")
15
- with open(meta_file, "r") as f:
16
- meta = json.load(f)
17
- self.classes = meta["classes"]
18
- self.id2label = {int(k): v for k, v in meta["id2label"].items()}
19
- self.label2id = meta["label2id"]
20
-
21
- # تحميل المعالج
22
- self.processor = AutoImageProcessor.from_pretrained(path)
23
-
24
- # تحميل الخلفية (Backbone)
25
- backbone_path = os.path.join(path, "backbone")
26
- self.backbone = AutoModel.from_pretrained(backbone_path).to(self.device)
27
- self.backbone.eval()
28
-
29
- # بناء هيكل النموذج الموحد
30
- self.model = AutoModelForImageClassification.from_pretrained(
31
- "microsoft/rad-dino",
32
- num_labels=len(self.classes),
33
- id2label=self.id2label,
34
- label2id=self.label2id
35
- )
36
-
37
- # ربط الخلفية
38
- if hasattr(self.model, 'dinov2'):
39
- self.model.dinov2 = self.backbone
40
- elif hasattr(self.model, 'backbone'):
41
- self.model.backbone = self.backbone
42
-
43
- # تحميل أوزان رأس التصنيف
44
- head_file = os.path.join(path, "classifier_head.pt")
45
- state_dict = torch.load(head_file, map_location=self.device)
46
- self.model.classifier.weight.copy_(state_dict["1.weight"])
47
- self.model.classifier.bias.copy_(state_dict["1.bias"])
48
-
49
- self.model.to(self.device)
50
- self.model.eval()
51
-
52
- def __call__(self, data):
53
- inputs = data.get("inputs", data)
54
-
55
- # معالجة الصورة القادمة أياً كانت صيغتها
56
- if isinstance(inputs, str):
57
- image = Image.open(inputs).convert("RGB")
58
- elif isinstance(inputs, Image.Image):
59
- image = inputs.convert("RGB")
60
- elif isinstance(inputs, bytes):
61
- image = Image.open(io.BytesIO(inputs)).convert("RGB")
62
- else:
63
- # إذا أرسلت كملف بايتس عبر الـ API
64
- image = Image.open(io.BytesIO(inputs)).convert("RGB")
65
-
66
- processed_inputs = self.processor(images=image, return_tensors="pt").to(self.device)
67
-
68
- with torch.no_grad():
69
- outputs = self.model(**processed_inputs)
70
- logits = outputs.logits
71
- probs = torch.softmax(logits, dim=-1)[0]
72
-
73
- results = []
74
- for idx, prob in enumerate(probs):
75
- results.append({
76
- "label": self.id2label[idx],
77
- "score": float(prob.item())
78
- })
79
-
80
- # ترتيب النتائج من الأعلى للأقل
81
- results = sorted(results, key=lambda x: x["score"], reverse=True)
82
- return results