AdarshDRC commited on
Commit
607b376
·
verified ·
1 Parent(s): fb44492

Create ai_manager.py

Browse files
Files changed (1) hide show
  1. src/services/ai_manager.py +341 -0
src/services/ai_manager.py ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import base64
3
+ import functools
4
+ import io
5
+ import threading
6
+ import traceback
7
+ import hashlib
8
+
9
+ import cv2
10
+ import numpy as np
11
+ import torch
12
+ import torch.nn.functional as F
13
+ from PIL import Image
14
+ from transformers import AutoImageProcessor, AutoModel, AutoProcessor
15
+ from ultralytics import YOLO
16
+ import insightface
17
+ from insightface.app import FaceAnalysis
18
+
19
+ from src.core.config import (
20
+ MAX_IMAGE_SIZE, MAX_CROPS, YOLO_PERSON_CLASS_ID,
21
+ YOLO_MIN_CROP_PX, YOLO_CONF_THRESHOLD,
22
+ DET_SIZE_PRIMARY, DET_SCALES, IOU_DEDUP_THRESHOLD,
23
+ MIN_FACE_SIZE, MAX_FACES_PER_IMAGE, FACE_QUALITY_GATE,
24
+ FACE_DIM, ADAFACE_DIM, FUSED_FACE_DIM,
25
+ FACE_CROP_THUMB_SIZE, FACE_CROP_QUALITY,
26
+ FACE_CROP_PADDING, ADAFACE_CROP_PADDING,
27
+ INFERENCE_CACHE_SIZE, ENABLE_ADAFACE, HF_TOKEN,
28
+ )
29
+
30
+ def _resize_pil(img: Image.Image, max_side: int = MAX_IMAGE_SIZE) -> Image.Image:
31
+ w, h = img.size
32
+ if max(w, h) <= max_side:
33
+ return img
34
+ scale = max_side / max(w, h)
35
+ return img.resize((int(w * scale), int(h * scale)), Image.LANCZOS)
36
+
37
+ def _crop_to_b64(img_bgr: np.ndarray, x1: int, y1: int, x2: int, y2: int) -> str:
38
+ H, W = img_bgr.shape[:2]
39
+ w, h = x2 - x1, y2 - y1
40
+ pad_x = int(w * FACE_CROP_PADDING)
41
+ pad_y = int(h * FACE_CROP_PADDING)
42
+ cx1, cy1 = max(0, x1 - pad_x), max(0, y1 - pad_y)
43
+ cx2, cy2 = min(W, x2 + pad_x), min(H, y2 + pad_y)
44
+ crop = img_bgr[cy1:cy2, cx1:cx2]
45
+ if crop.size == 0:
46
+ return ""
47
+ pil = Image.fromarray(crop[:, :, ::-1]).resize((FACE_CROP_THUMB_SIZE, FACE_CROP_THUMB_SIZE), Image.LANCZOS)
48
+ buf = io.BytesIO()
49
+ pil.save(buf, format="JPEG", quality=FACE_CROP_QUALITY)
50
+ return base64.b64encode(buf.getvalue()).decode()
51
+
52
+ def _face_crop_for_adaface(img_bgr: np.ndarray, x1: int, y1: int, x2: int, y2: int) -> np.ndarray | None:
53
+ H, W = img_bgr.shape[:2]
54
+ w, h = x2 - x1, y2 - y1
55
+ pad_x = int(w * ADAFACE_CROP_PADDING)
56
+ pad_y = int(h * ADAFACE_CROP_PADDING)
57
+ cx1, cy1 = max(0, x1 - pad_x), max(0, y1 - pad_y)
58
+ cx2, cy2 = min(W, x2 + pad_x), min(H, y2 + pad_y)
59
+ crop = img_bgr[cy1:cy2, cx1:cx2]
60
+ if crop.size == 0:
61
+ return None
62
+ rgb = crop[:, :, ::-1].copy()
63
+ pil = Image.fromarray(rgb).resize((112, 112), Image.LANCZOS)
64
+ arr = np.array(pil, dtype=np.float32) / 255.0
65
+ arr = (arr - 0.5) / 0.5
66
+ return arr.transpose(2, 0, 1)
67
+
68
+ def _clahe_enhance(bgr: np.ndarray) -> np.ndarray:
69
+ lab = cv2.cvtColor(bgr, cv2.COLOR_BGR2LAB)
70
+ l_ch, a_ch, b_ch = cv2.split(lab)
71
+ clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
72
+ l_eq = clahe.apply(l_ch)
73
+ return cv2.cvtColor(cv2.merge([l_eq, a_ch, b_ch]), cv2.COLOR_LAB2BGR)
74
+
75
+ def _iou(box_a: list, box_b: list) -> float:
76
+ xa, ya = max(box_a[0], box_b[0]), max(box_a[1], box_b[1])
77
+ xb, yb = min(box_a[2], box_b[2]), min(box_a[3], box_b[3])
78
+ inter = max(0, xb - xa) * max(0, yb - ya)
79
+ if inter == 0:
80
+ return 0.0
81
+ area_a = (box_a[2] - box_a[0]) * (box_a[3] - box_a[1])
82
+ area_b = (box_b[2] - box_b[0]) * (box_b[3] - box_b[1])
83
+ return inter / (area_a + area_b - inter)
84
+
85
+ def _dedup_faces(faces_list: list, iou_thresh: float = IOU_DEDUP_THRESHOLD) -> list:
86
+ if not faces_list:
87
+ return []
88
+ faces_list = sorted(faces_list, key=lambda f: float(f.det_score), reverse=True)
89
+ kept = []
90
+ for face in faces_list:
91
+ b = face.bbox.astype(int)
92
+ box = [b[0], b[1], b[2], b[3]]
93
+ if not any(_iou(box, [k.bbox.astype(int)[i] for i in range(4)]) > iou_thresh for k in kept):
94
+ kept.append(face)
95
+ return kept
96
+
97
+ class AIModelManager:
98
+ def __init__(self):
99
+ self.device = "cuda" if torch.cuda.is_available() else "cpu"
100
+ self.siglip_processor = AutoProcessor.from_pretrained("google/siglip-base-patch16-224", use_fast=True)
101
+ self.siglip_model = AutoModel.from_pretrained("google/siglip-base-patch16-224").to(self.device).eval()
102
+ self.dinov2_processor = AutoImageProcessor.from_pretrained("facebook/dinov2-base")
103
+ self.dinov2_model = AutoModel.from_pretrained("facebook/dinov2-base").to(self.device).eval()
104
+
105
+ if self.device == "cuda":
106
+ self.siglip_model = self.siglip_model.half()
107
+ self.dinov2_model = self.dinov2_model.half()
108
+
109
+ self.yolo = YOLO("yolo11n-seg.pt")
110
+
111
+ self.face_app = FaceAnalysis(name="buffalo_l", providers=["CUDAExecutionProvider", "CPUExecutionProvider"] if self.device == "cuda" else ["CPUExecutionProvider"])
112
+ self.face_app.prepare(ctx_id=0 if self.device == "cuda" else -1, det_size=DET_SIZE_PRIMARY)
113
+ self.face_app.get(np.zeros((112, 112, 3), dtype=np.uint8))
114
+
115
+ self.adaface_model = None
116
+ self._load_adaface()
117
+
118
+ self._face_lock = threading.Lock()
119
+ self._cache_lock = threading.Lock()
120
+ self._cache: dict[str, list] = {}
121
+
122
+ def _load_adaface(self) -> None:
123
+ if not ENABLE_ADAFACE:
124
+ return
125
+ import os
126
+ import sys
127
+ REPO_ID = "minchul/cvlface_adaface_ir50_ms1mv2"
128
+ CACHE_PATH = os.path.expanduser("~/.cvlface_cache/minchul/cvlface_adaface_ir50_ms1mv2")
129
+ try:
130
+ from huggingface_hub import hf_hub_download
131
+ from transformers import AutoModel as _HFAutoModel
132
+ os.makedirs(CACHE_PATH, exist_ok=True)
133
+ hf_hub_download(repo_id=REPO_ID, filename="files.txt", token=HF_TOKEN, local_dir=CACHE_PATH, local_dir_use_symlinks=False)
134
+ with open(os.path.join(CACHE_PATH, "files.txt")) as f:
135
+ extra = [x.strip() for x in f.read().split("\n") if x.strip()]
136
+ for fname in extra + ["config.json", "wrapper.py", "model.safetensors"]:
137
+ if not os.path.exists(os.path.join(CACHE_PATH, fname)):
138
+ hf_hub_download(repo_id=REPO_ID, filename=fname, token=HF_TOKEN, local_dir=CACHE_PATH, local_dir_use_symlinks=False)
139
+ cwd = os.getcwd()
140
+ os.chdir(CACHE_PATH)
141
+ sys.path.insert(0, CACHE_PATH)
142
+ try:
143
+ model = _HFAutoModel.from_pretrained(CACHE_PATH, trust_remote_code=True, token=HF_TOKEN)
144
+ finally:
145
+ os.chdir(cwd)
146
+ if CACHE_PATH in sys.path:
147
+ sys.path.remove(CACHE_PATH)
148
+ self.adaface_model = model.to(self.device).eval()
149
+ except Exception as e:
150
+ self.adaface_model = None
151
+
152
+ def _adaface_embed(self, face_arr_chw: np.ndarray | None) -> np.ndarray | None:
153
+ if self.adaface_model is None or face_arr_chw is None:
154
+ return None
155
+ try:
156
+ t = torch.from_numpy(face_arr_chw).unsqueeze(0).to(self.device)
157
+ if self.device == "cuda":
158
+ t = t.half()
159
+ with torch.no_grad():
160
+ out = self.adaface_model(t)
161
+ emb = out if isinstance(out, torch.Tensor) else out.embedding
162
+ return F.normalize(emb.float(), p=2, dim=1)[0].cpu().numpy()
163
+ except Exception:
164
+ return None
165
+
166
+ def _embed_crops_batch(self, crops: list[Image.Image]) -> list[np.ndarray]:
167
+ if not crops:
168
+ return []
169
+ with torch.no_grad():
170
+ sig_in = self.siglip_processor(images=crops, return_tensors="pt", padding=True)
171
+ sig_in = {k: v.to(self.device) for k, v in sig_in.items()}
172
+ if self.device == "cuda":
173
+ sig_in = {k: v.half() if v.dtype == torch.float32 else v for k, v in sig_in.items()}
174
+ sig_out = self.siglip_model.get_image_features(**sig_in)
175
+ if hasattr(sig_out, "image_embeds"):
176
+ sig_out = sig_out.image_embeds
177
+ elif hasattr(sig_out, "pooler_output"):
178
+ sig_out = sig_out.pooler_output
179
+ elif hasattr(sig_out, "last_hidden_state"):
180
+ sig_out = sig_out.last_hidden_state[:, 0, :]
181
+ elif isinstance(sig_out, tuple):
182
+ sig_out = sig_out[0]
183
+ sig_vecs = F.normalize(sig_out.float(), p=2, dim=1).cpu()
184
+
185
+ dino_in = self.dinov2_processor(images=crops, return_tensors="pt")
186
+ dino_in = {k: v.to(self.device) for k, v in dino_in.items()}
187
+ if self.device == "cuda":
188
+ dino_in = {k: v.half() if v.dtype == torch.float32 else v for k, v in dino_in.items()}
189
+ dino_out = self.dinov2_model(**dino_in)
190
+ dino_vecs = F.normalize(dino_out.last_hidden_state[:, 0, :].float(), p=2, dim=1).cpu()
191
+
192
+ fused = F.normalize(torch.cat([sig_vecs, dino_vecs], dim=1), p=2, dim=1)
193
+ return [fused[i].numpy() for i in range(len(crops))]
194
+
195
+ def _detect_and_encode_faces(self, img_np: np.ndarray) -> list[dict]:
196
+ if self.face_app is None:
197
+ return []
198
+ try:
199
+ if img_np.dtype != np.uint8:
200
+ img_np = (img_np * 255).astype(np.uint8)
201
+ bgr = img_np[:, :, ::-1].copy() if img_np.shape[2] == 3 else img_np.copy()
202
+ bgr_enhanced = _clahe_enhance(bgr)
203
+
204
+ all_raw_faces = []
205
+ H, W = bgr.shape[:2]
206
+
207
+ for scale in DET_SCALES:
208
+ scale_w, scale_h = min(W, scale[0]), min(H, scale[1])
209
+ bgr_scaled = bgr_enhanced if scale_w == W and scale_h == H else cv2.resize(bgr_enhanced, (scale_w, scale_h))
210
+ try:
211
+ self.face_app.det_model.input_size = scale
212
+ with self._face_lock:
213
+ faces_at_scale = self.face_app.get(bgr_scaled)
214
+ sx, sy = W / scale_w, H / scale_h
215
+ for f in faces_at_scale:
216
+ if sx != 1.0 or sy != 1.0:
217
+ f.bbox[0] *= sx; f.bbox[1] *= sy; f.bbox[2] *= sx; f.bbox[3] *= sy
218
+ all_raw_faces.extend(faces_at_scale)
219
+ except Exception:
220
+ pass
221
+
222
+ bgr_flip = cv2.flip(bgr_enhanced, 1)
223
+ try:
224
+ self.face_app.det_model.input_size = DET_SIZE_PRIMARY
225
+ with self._face_lock:
226
+ faces_flip = self.face_app.get(bgr_flip)
227
+ for f in faces_flip:
228
+ x1, y1, x2, y2 = f.bbox
229
+ f.bbox[0], f.bbox[2] = W - x2, W - x1
230
+ all_raw_faces.extend(faces_flip)
231
+ except Exception:
232
+ pass
233
+
234
+ self.face_app.det_model.input_size = DET_SIZE_PRIMARY
235
+ faces = _dedup_faces(all_raw_faces)
236
+
237
+ results, accepted = [], 0
238
+ for face in faces:
239
+ if accepted >= MAX_FACES_PER_IMAGE:
240
+ break
241
+ bbox_raw = face.bbox.astype(int)
242
+ x1, y1, x2, y2 = bbox_raw
243
+ x1, y1 = max(0, x1), max(0, y1)
244
+ x2, y2 = min(bgr.shape[1], x2), min(bgr.shape[0], y2)
245
+ w, h = x2 - x1, y2 - y1
246
+ if w < MIN_FACE_SIZE or h < MIN_FACE_SIZE:
247
+ continue
248
+ det_score = float(face.det_score) if hasattr(face, "det_score") else 1.0
249
+ if det_score < FACE_QUALITY_GATE or face.embedding is None:
250
+ continue
251
+
252
+ arcface_vec = face.embedding.astype(np.float32)
253
+ n = np.linalg.norm(arcface_vec)
254
+ if n > 0:
255
+ arcface_vec = arcface_vec / n
256
+
257
+ face_chw = _face_crop_for_adaface(bgr, x1, y1, x2, y2)
258
+ adaface_vec = self._adaface_embed(face_chw)
259
+
260
+ fused_raw = np.concatenate([arcface_vec, adaface_vec]) if adaface_vec is not None else np.concatenate([arcface_vec, np.zeros(ADAFACE_DIM, dtype=np.float32)])
261
+ n2 = np.linalg.norm(fused_raw)
262
+ final_vec = (fused_raw / n2) if n2 > 0 else fused_raw
263
+
264
+ results.append({
265
+ "type": "face", "vector": final_vec, "face_idx": accepted,
266
+ "bbox": [int(x1), int(y1), int(w), int(h)],
267
+ "face_crop": _crop_to_b64(bgr, x1, y1, x2, y2),
268
+ "det_score": det_score, "face_width_px": int(w),
269
+ })
270
+ accepted += 1
271
+ return results
272
+ except Exception:
273
+ return []
274
+
275
+ def process_image_bytes(self, image_bytes: bytes, detect_faces: bool = True) -> list[dict]:
276
+ file_hash = hashlib.md5(image_bytes[:65536]).hexdigest()
277
+ cache_key = f"{file_hash}_{detect_faces}"
278
+
279
+ with self._cache_lock:
280
+ if cache_key in self._cache:
281
+ return list(self._cache[cache_key])
282
+
283
+ extracted = []
284
+ original_pil = Image.open(io.BytesIO(image_bytes)).convert("RGB")
285
+ img_np = np.array(original_pil)
286
+ faces_found = False
287
+
288
+ if detect_faces and hasattr(self, 'face_app') and self.face_app is not None:
289
+ face_results = self._detect_and_encode_faces(img_np)
290
+ if face_results:
291
+ faces_found = True
292
+ extracted.extend(face_results)
293
+
294
+ crops: list[Image.Image] = []
295
+ yolo_results = getattr(self, 'yolo', lambda x, **kwargs: [])(original_pil, conf=YOLO_CONF_THRESHOLD, verbose=False)
296
+
297
+ for r in yolo_results:
298
+ if r.masks is not None:
299
+ for seg_idx, mask_xy in enumerate(r.masks.xy):
300
+ cls_id = int(r.boxes.cls[seg_idx].item())
301
+ if faces_found and cls_id == YOLO_PERSON_CLASS_ID:
302
+ continue
303
+ polygon = np.array(mask_xy, dtype=np.int32)
304
+ if len(polygon) < 3:
305
+ continue
306
+ x, y, w, h = cv2.boundingRect(polygon)
307
+ if w < YOLO_MIN_CROP_PX or h < YOLO_MIN_CROP_PX:
308
+ continue
309
+ crops.append(original_pil.crop((x, y, x + w, y + h)))
310
+ if len(crops) >= MAX_CROPS:
311
+ break
312
+ elif r.boxes is not None:
313
+ for box in r.boxes:
314
+ cls_id = int(box.cls.item())
315
+ if faces_found and cls_id == YOLO_PERSON_CLASS_ID:
316
+ continue
317
+ x1, y1, x2, y2 = box.xyxy[0].tolist()
318
+ if (x2 - x1) < YOLO_MIN_CROP_PX or (y2 - y1) < YOLO_MIN_CROP_PX:
319
+ continue
320
+ crops.append(original_pil.crop((x1, y1, x2, y2)))
321
+ if len(crops) >= MAX_CROPS:
322
+ break
323
+
324
+ all_crops = [_resize_pil(c, MAX_IMAGE_SIZE) for c in [original_pil] + crops]
325
+ obj_vecs = self._embed_crops_batch(all_crops)
326
+ extracted.extend({"type": "object", "vector": v} for v in obj_vecs)
327
+
328
+ with self._cache_lock:
329
+ if len(self._cache) >= INFERENCE_CACHE_SIZE:
330
+ oldest = next(iter(self._cache))
331
+ del self._cache[oldest]
332
+ self._cache[cache_key] = list(extracted)
333
+
334
+ return extracted
335
+
336
+ async def process_image_bytes_async(self, image_bytes: bytes, detect_faces: bool = True) -> list[dict]:
337
+ loop = asyncio.get_event_loop()
338
+ return await loop.run_in_executor(
339
+ None,
340
+ functools.partial(self.process_image_bytes, image_bytes, detect_faces),
341
+ )