Update app.py
Browse files12345629 unmodified lines3637383940414243444516 unmodified lines62636465666768697071727374757677787980818283848523 unmodified lines1091101111121131141151161171181191201211221231241251261272 unmodified lines1301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771783 unmodified lines18218318418518618718818919019119219319419519619719819920020120220320420511 unmodified lines21721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724831 unmodified lines280281282283#!/usr/bin/env python3"""π₯ Icon Challenge Solver - FINAL FIX HF Spaces"""import os29 unmodified lineslogger = logging.getLogger(__name__)# ===================== CONFIG =====================class 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.2516 unmodified linesself.skip = nn.Linear(in_dim, out_dim)def forward(self, x):if x.shape[0] <= 1:self.train(False)residual = self.skip(x)x = self.layer1(x)x = self.bn1(x)x = self.act(x)x = self.dropout(x)x = self.layer2(x)x = self.bn2(x)return F.normalize(x + residual, p=2, dim=1)class IconClassifier(nn.Module):def __init__(self, backbone, head_state, num_classes=21):super().__init__()self.backbone = backboneself.projection = ProjectionHead()self.weight = nn.Parameter(head_state['arc_margin']['weight'])self.projection.load_state_dict(head_state['projection'])self.s = 30.0def forward(self, x):23 unmodified linesreturn 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}")2 unmodified linesmodel_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:3 unmodified linesif 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 {11 unmodified lines# ===================== MAIN FUNCTION =====================@spaces.GPU(request_timeout=180, enable=True)def solve_gradio(challenge_img, *options):if not manager.initialized:manager.init()try:if 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]challenge_crop = manager.yolo_detect_and_crop(challenge_img)result = manager.match_options(challenge_crop, options_pil)best_idx = result["predicted_index"]lines = ["π― HASIL\n",f"β Best Option: {best_idx + 1}",f"Confidence: {result['confidence']:.4f} ({result['confidence']*100:.2f}%)",f"Class: {result['predicted_class']}\n","π Skor Semua Opsi:"]for i in range(8):s = result["all_scores"][f"option_{i}"]marker = "β " 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()31 unmodified linesgr.Markdown("---\nMade with β€οΈ for Icon Challenge")demo.launch()12345629 unmodified lines3637383940414243444546474816 unmodified lines656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311423 unmodified lines1381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751762 unmodified lines1791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492503 unmodified lines25425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129211 unmodified lines30430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136231 unmodified lines394395396397398399#!/usr/bin/env python3"""π₯ Icon Challenge Solver - FIXED for HF Spaces"""import os29 unmodified lineslogger = logging.getLogger(__name__)# ===================== CONFIG =====================# FIX: Gunakan absolute path berdasarkan lokasi file script iniBASE_DIR = Path(__file__).resolve().parentclass Config:device = "cuda" if torch.cuda.is_available() else "cpu"yolo_model_path = BASE_DIR / "yolo" / "best.pt"lora_model_dir = BASE_DIR / "icon_model_hybrid"adapter_subdir = "lora_adapter"model_name = "ViT-L-16-SigLIP-256"yolo_conf = 0.2516 unmodified linesself.skip = nn.Linear(in_dim, out_dim)def forward(self, x):# FIX: Handle batch size 1 untuk BatchNormif x.shape[0] <= 1:self.train(False)residual = self.skip(x)out = self.layer1(x)out = self.bn1(out)out = self.act(out)out = self.dropout(out)out = self.layer2(out)out = self.bn2(out)return F.normalize(out + residual, p=2, dim=1)class IconClassifier(nn.Module):def __init__(self, backbone, head_state, num_classes=21):super().__init__()self.backbone = backboneself.projection = ProjectionHead()# FIX: Load projection weights dengan strict=False untuk handle key mismatchif 'projection' in head_state:proj_dict = head_state['projection']# Handle case kalau key-nya ada prefix 'projection.'cleaned = {}for k, v in proj_dict.items():if k.startswith('projection.'):cleaned[k[11:]] = velse:cleaned[k] = vself.projection.load_state_dict(cleaned, strict=False)# FIX: Handle arc_margin weight dengan berbagai kemungkinan key nameweight = Noneif 'arc_margin' in head_state and 'weight' in head_state['arc_margin']:weight = head_state['arc_margin']['weight']elif 'weight' in head_state:weight = head_state['weight']elif 'fc.weight' in head_state:weight = head_state['fc.weight']if weight is None:logger.warning("Head weight not found, initializing random!")weight = torch.randn(num_classes, 256)self.weight = nn.Parameter(weight)self.s = 30.0def forward(self, x):23 unmodified linesreturn cls._instancedef init(self):if self.initialized:returnlogger.info(f"Working directory: {os.getcwd()}")logger.info(f"Base directory: {BASE_DIR}")logger.info("Loading models on GPU...")# FIX: Check YOLO path dengan absolute pathyolo_path = Path(CONFIG.yolo_model_path)logger.info(f"Looking for YOLO at: {yolo_path} (exists: {yolo_path.exists()})")if not yolo_path.exists():# Fallback: cari di cwd jugaalt_path = Path("yolo") / "best.pt"if alt_path.exists():yolo_path = alt_pathelse:raise FileNotFoundError(f"YOLO not found: {yolo_path} or {alt_path}")self.yolo = YOLO(str(yolo_path)).to(CONFIG.device)logger.info(f"β YOLO loaded: {yolo_path}")# Configlora_base = Path(CONFIG.lora_model_dir)logger.info(f"Looking for LoRA at: {lora_base} (exists: {lora_base.exists()})")if not lora_base.exists():alt_lora = Path("icon_model_hybrid")if alt_lora.exists():lora_base = alt_loraelse:raise FileNotFoundError(f"LoRA dir not found: {lora_base}")config_path = lora_base / "config.json"if not config_path.exists():raise FileNotFoundError(f"config.json not found in {lora_base}")2 unmodified linesmodel_config = json.load(f)num_classes = model_config.get('num_classes') or len(model_config.get('class_to_idx', {}))logger.info(f"Num classes: {num_classes}")# Backbonelogger.info(f"Loading backbone: {CONFIG.model_name}")backbone, _, _ = open_clip.create_model_and_transforms(CONFIG.model_name, pretrained='webli')backbone = backbone.visual.to(CONFIG.device)logger.info("β Backbone loaded")# 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}")try:model_with_lora = PeftModel.from_pretrained(backbone, peft_path, is_trainable=False)logger.info("β LoRA adapter loaded")except Exception as e:logger.error(f"LoRA load failed: {e}")# Fallback: gunakan backbone tanpa LoRAmodel_with_lora = backbonelogger.warning("β οΈ Using backbone without LoRA!")# Head Weightshead_candidates = [lora_base / "head_weights.pt",lora_base / "weights.pt",lora_base / "classifier.pt",lora_base / "model.pt"]head_state = Nonehead_path = Nonefor hpath in head_candidates:if hpath.exists():head_state = torch.load(hpath, map_location=CONFIG.device)head_path = hpathlogger.info(f"β Head weights loaded: {hpath}")breakif head_state is None:raise FileNotFoundError(f"Head weights not found! Tried: {head_candidates}")self.inference_model = IconClassifier(model_with_lora, head_state, num_classes).to(CONFIG.device).eval()logger.info("β IconClassifier created")self.idx_to_class = {int(k): v for k, v in model_config.get('idx_to_class', {}).items()}self.class_to_idx = {v: int(k) for k, v in self.idx_to_class.items()}self.initialized = Truelogger.info("β All models loaded successfully!")def yolo_detect_and_crop(self, image: Image.Image) -> Image.Image:# FIX: Handle PIL Image dengan berbagai modeif image.mode != 'RGB':image = image.convert('RGB')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:3 unmodified linesif 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:cropped = img_np[y1:y2, x1:x2]return Image.fromarray(cropped)return imagedef extract_embedding(self, image: Image.Image) -> torch.Tensor:if image.mode != 'RGB':image = image.convert('RGB')img_tensor = custom_preprocess(image).unsqueeze(0).to(CONFIG.device)with torch.no_grad(), autocast():emb = self.inference_model.get_embedding(img_tensor)return embdef match_options(self, challenge_crop: Image.Image, options: List[Image.Image]):challenge_emb = self.extract_embedding(challenge_crop)option_embs = []for opt in options:option_embs.append(self.extract_embedding(opt))option_stack = torch.cat(option_embs, dim=0)similarities = (challenge_emb @ option_stack.T).squeeze(0).cpu().numpy()best_idx = int(np.argmax(similarities))# FIX: Temperature scaling yang lebih stabilsim_scaled = similarities * 10sim_max = np.max(sim_scaled)exp_sim = np.exp(sim_scaled - sim_max) # Numerical stabilityprobs = exp_sim / exp_sim.sum()return {11 unmodified lines# ===================== MAIN FUNCTION =====================@spaces.GPU(request_timeout=180, enable=True)def solve_gradio(challenge_img, *options):# FIX: Inisialisasi dengan try-except yang lebih detailif not manager.initialized:try:manager.init()except Exception as e:logger.error(f"Model init failed: {e}", exc_info=True)return f"β Model initialization failed: {str(e)}\n\nCek path model di HF Spaces!", Nonetry:if challenge_img is None or any(o is None for o in options):return "β Semua gambar harus diisi!", None# FIX: Handle berbagai input format (numpy, PIL, path)if isinstance(challenge_img, np.ndarray):challenge_img = Image.fromarray(challenge_img)elif isinstance(challenge_img, str):challenge_img = Image.open(challenge_img)options_pil = []for opt in options:if isinstance(opt, np.ndarray):options_pil.append(Image.fromarray(opt))elif isinstance(opt, str):options_pil.append(Image.open(opt))elif isinstance(opt, Image.Image):options_pil.append(opt)else:options_pil.append(None)if any(o is None for o in options_pil):return "β Format gambar option tidak valid!", None# YOLO cropchallenge_crop = manager.yolo_detect_and_crop(challenge_img)# Matchresult = manager.match_options(challenge_crop, options_pil)best_idx = result["predicted_index"]lines = ["π― HASIL\n",f"β Best Option: {best_idx + 1}",f"Confidence: {result['confidence']:.4f} ({result['confidence']*100:.2f}%)",f"Class: {result['predicted_class']}\n","π Skor Semua Opsi:"]for i in range(len(options_pil)):s = result["all_scores"][f"option_{i}"]marker = "β " if i == best_idx else " "lines.append(f"{marker} Option {i+1}: {s['probability']:.4f} ({s['similarity']:.4f})")# FIX: Cleanup VRAM setelah inferencegc.collect()if torch.cuda.is_available():torch.cuda.empty_cache()31 unmodified linesgr.Markdown("---\nMade with β€οΈ for Icon Challenge")# FIX: Gunakan if __name__ guard untuk HF Spacesif __name__ == "__main__":demo.launch()
app.py+156-40