Update app.py
Browse files126 unmodified lines127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209126 unmodified linesraise ValueError(f"Cannot decode {filename}")# ===================== MODEL MANAGER =====================class ModelManager:_instance = Nonedef __new__(cls):if cls._instance is None:cls._instance = super().__new__(cls)cls._instance.initialized = Falsereturn cls._instancedef init(self):if self.initialized: returnlogger.info("Loading models on GPU...")self.yolo = YOLO(CONFIG.yolo_model_path).to(CONFIG.device)config_path = Path(CONFIG.lora_model_dir) / "config.json"with open(config_path) as f:model_config = json.load(f)num_classes = model_config.get('num_classes') or len(model_config.get('class_to_idx', {}))backbone, _, _ = open_clip.create_model_and_transforms(CONFIG.model_name, pretrained='webli')backbone = backbone.visual.to(CONFIG.device)model_with_lora = PeftModel.from_pretrained(backbone, CONFIG.lora_model_dir)head_state = torch.load(Path(CONFIG.lora_model_dir) / "head_weights.pt", map_location=CONFIG.device)self.inference_model = IconClassifier(model_with_lora, head_state, num_classes).to(CONFIG.device).eval()self.idx_to_class = {int(k): v for k, v in model_config.get('idx_to_class', {}).items()}self.initialized = Truelogger.info("✅ Models loaded!")# (Copy fungsi yolo_detect_and_crop, extract_embedding, match_options dari kode sebelumnya)def yolo_detect_and_crop(self, image: Image.Image) -> Image.Image:img_np = np.array(image)img_bgr = cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR)results = self.yolo(img_bgr, conf=CONFIG.yolo_conf, imgsz=CONFIG.yolo_img_size, verbose=False)best_box = Nonebest_conf = 0for result in results:if result.boxes is None: continuefor box in result.boxes:conf = float(box.conf[0])if conf > best_conf:best_conf = confbest_box = box.xyxy[0].cpu().numpy().astype(int)if best_box is not None and best_conf >= CONFIG.yolo_min_conf:x1, y1, x2, y2 = best_boxh, w = img_np.shape[:2]x1, y1, x2, y2 = max(0,x1), max(0,y1), min(w,x2), min(h,y2)if (x2-x1) >= CONFIG.yolo_min_crop_size and (y2-y1) >= CONFIG.yolo_min_crop_size:return Image.fromarray(img_np[y1:y2, x1:x2])return imagedef extract_embedding(self, image: Image.Image) -> torch.Tensor:img_tensor = custom_preprocess(image).unsqueeze(0).to(CONFIG.device)with torch.no_grad(), autocast():return self.inference_model.get_embedding(img_tensor)def match_options(self, challenge_crop: Image.Image, options: List[Image.Image]):challenge_emb = self.extract_embedding(challenge_crop)option_embs = [self.extract_embedding(opt) for opt in options]option_stack = torch.cat(option_embs, dim=0)similarities = (challenge_emb @ option_stack.T).squeeze(0).cpu().numpy()best_idx = int(np.argmax(similarities))exp_sim = np.exp(similarities * 10)probs = exp_sim / exp_sim.sum()return {"predicted_index": best_idx,"confidence": float(probs[best_idx]),"all_scores": {f"option_{i}": {"similarity": float(similarities[i]),"probability": float(probs[i])} for i in range(len(options))},"predicted_class": self.idx_to_class.get(best_idx, "unknown")}manager = ModelManager()126 unmodified lines127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187126 unmodified linesraise ValueError(f"Cannot decode {filename}")# ===================== MODEL MANAGER =====================def init(self):if self.initialized: returnlogger.info("Loading models on GPU...")# YOLOyolo_path = Path(CONFIG.yolo_model_path)if yolo_path.exists():self.yolo = YOLO(str(yolo_path)).to(CONFIG.device)else:logger.error(f"YOLO not found: {yolo_path}")raise FileNotFoundError(f"YOLO model not found at {yolo_path}")# Load config dari root icon_model_hybridlora_root = Path(CONFIG.lora_model_dir)config_path = lora_root / "config.json"if not config_path.exists():raise FileNotFoundError(f"Config not found: {config_path}")with open(config_path) as f:model_config = json.load(f)num_classes = model_config.get('num_classes') or len(model_config.get('class_to_idx', {}))# Backbonebackbone, _, _ = open_clip.create_model_and_transforms(CONFIG.model_name, pretrained='webli')backbone = backbone.visual.to(CONFIG.device)# LoRA Adapter (subfolder)adapter_path = lora_root / "lora_adapter"if not (adapter_path / "adapter_config.json").exists():raise FileNotFoundError(f"Adapter config not found in {adapter_path}")model_with_lora = PeftModel.from_pretrained(backbone,str(adapter_path), # ← penting: point ke folder yang ada adapter_config.jsonis_trainable=False)# Head weightshead_path = lora_root / "head_weights.pt" # sesuaikan nama kalau bedaif not head_path.exists():# coba cari weights.pthead_path = lora_root / "weights.pt"if not head_path.exists():raise FileNotFoundError(f"Head weights not found in {lora_root}")head_state = torch.load(head_path, map_location=CONFIG.device)self.inference_model = IconClassifier(model_with_lora, head_state, num_classes).to(CONFIG.device).eval()self.idx_to_class = {int(k): v for k, v in model_config.get('idx_to_class', {}).items()}self.initialized = Truelogger.info("✅ Models loaded successfully!")manager = ModelManager()
app.py+43-65