Update app.py
Browse files12345632 unmodified lines39404142434445464748495047 unmodified lines98991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861877 unmodified lines19519619719819920020113 unmodified lines2152162172182192202211 unmodified line22322422522622722822923 unmodified lines253254255256257#!/usr/bin/env python3"""π₯ Icon Challenge Solver - Optimized for HF Spaces"""import os32 unmodified linesclass Config:device = "cuda" if torch.cuda.is_available() else "cpu"yolo_model_path = "./yolo/best.pt"yolo_conf = 0.25yolo_img_size = 640yolo_min_crop_size = 32yolo_min_conf = 0.3lora_model_dir = "./icon_model_hybrid"model_name = "ViT-L-16-SigLIP-256"CONFIG = Config()47 unmodified linesT.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),])# ===================== UTILS =====================def decode_image_advanced(data: Union[str, bytes], filename: str = "image") -> Image.Image:if isinstance(data, str):clean = data.strip().replace("\n", "").replace("\r", "").replace(" ", "")clean = re.sub(r"^data:image/[a-zA-Z0-9.+-]+;base64,", "", clean)missing = len(clean) % 4if missing:clean += '=' * (4 - missing)raw_bytes = base64.b64decode(clean, validate=False)else:raw_bytes = datatry:return Image.open(io.BytesIO(raw_bytes)).convert("RGB")except:passcommon_sizes = [50, 60, 64, 70, 80, 96, 100, 128]for size in common_sizes:expected = size * size * 4if len(raw_bytes) >= expected:try:arr = np.frombuffer(raw_bytes[:expected], dtype=np.uint8).reshape((size, size, 4))return Image.fromarray(arr[:, :, :3])except:continueraise 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()7 unmodified linesif challenge_img is None or any(o is None for o in options):return "β Semua gambar harus diisi!", None# Convert ke PILif isinstance(challenge_img, np.ndarray):challenge_img = Image.fromarray(challenge_img)options_pil = [Image.fromarray(opt) if isinstance(opt, np.ndarray) else opt for opt in options]13 unmodified linesmarker = "β " if i == best_idx else " "lines.append(f"{marker} Option {i+1}: {s['probability']:.4f} ({s['similarity']:.4f})")# Cleanupgc.collect()if torch.cuda.is_available():torch.cuda.empty_cache()1 unmodified linereturn "\n".join(lines), options_pil[best_idx]except Exception as e:logger.error(str(e))return f"β Error: {str(e)}", None23 unmodified linesgr.Markdown("---\nMade with β€οΈ for Icon Challenge")# Launch (HF Spaces akan handle ini otomatis)demo.launch()12345632 unmodified lines3940414243444546474849505147 unmodified lines991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152167 unmodified lines22422522622722822913 unmodified lines2432442452462472481 unmodified line25025125225325425525623 unmodified lines280281282283#!/usr/bin/env python3"""π₯ Icon Challenge Solver - FINAL FIX HF Spaces"""import os32 unmodified linesclass Config:device = "cuda" if torch.cuda.is_available() else "cpu"yolo_model_path = "./yolo/best.pt"lora_model_dir = "./icon_model_hybrid"adapter_subdir = "lora_adapter"model_name = "ViT-L-16-SigLIP-256"yolo_conf = 0.25yolo_img_size = 640yolo_min_crop_size = 32yolo_min_conf = 0.3CONFIG = Config()47 unmodified linesT.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),])# ===================== 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...")# YOLOyolo_path = Path(CONFIG.yolo_model_path)if yolo_path.exists():self.yolo = YOLO(str(yolo_path)).to(CONFIG.device)logger.info(f"β YOLO loaded: {yolo_path}")else:raise FileNotFoundError(f"YOLO not found: {yolo_path}")# Configlora_base = Path(CONFIG.lora_model_dir)config_path = lora_base / "config.json"if not config_path.exists():raise FileNotFoundError(f"config.json not found in {lora_base}")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 Adapteradapter_dir = lora_base / CONFIG.adapter_subdirpeft_path = str(adapter_dir) if adapter_dir.exists() else str(lora_base)logger.info(f"Loading LoRA from: {peft_path}")model_with_lora = PeftModel.from_pretrained(backbone, peft_path, is_trainable=False)# Head Weightshead_candidates = [lora_base / "head_weights.pt",lora_base / "weights.pt"]head_state = Nonefor hpath in head_candidates:if hpath.exists():head_state = torch.load(hpath, map_location=CONFIG.device)logger.info(f"β Head weights loaded: {hpath}")breakif head_state is None:raise FileNotFoundError("head_weights.pt or weights.pt not found!")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("β All models loaded successfully!")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()7 unmodified linesif challenge_img is None or any(o is None for o in options):return "β Semua gambar harus diisi!", Noneif isinstance(challenge_img, np.ndarray):challenge_img = Image.fromarray(challenge_img)options_pil = [Image.fromarray(opt) if isinstance(opt, np.ndarray) else opt for opt in options]13 unmodified linesmarker = "β " if i == best_idx else " "lines.append(f"{marker} Option {i+1}: {s['probability']:.4f} ({s['similarity']:.4f})")gc.collect()if torch.cuda.is_available():torch.cuda.empty_cache()1 unmodified linereturn "\n".join(lines), options_pil[best_idx]except Exception as e:logger.error(str(e), exc_info=True)return f"β Error: {str(e)}", None23 unmodified linesgr.Markdown("---\nMade with β€οΈ for Icon Challenge")demo.launch()
app.py+91-65