Update app.py
Browse files123456781 unmodified line1011121314151614 unmodified lines31323334353637383940414222 unmodified lines6566676869707111 unmodified lines838485868788899091922 unmodified lines959697989910010143 unmodified lines1451461471481491501511521531541551561571581591601613 unmodified lines16516616716816917017127 unmodified lines19920020120220320420525 unmodified lines23123223323423523623745 unmodified lines28328428528628728828929029129211 unmodified lines30430530630730830931031131231331431531631731831932032132213 unmodified lines33633733833934034134234334434510 unmodified lines35635735835936036136231 unmodified lines394395396397398399#!/usr/bin/env python3"""π₯ Icon Challenge Solver - FIXED for HF Spaces"""import osimport ioimport re1 unmodified lineimport base64import jsonimport loggingimport warningsfrom pathlib import Pathfrom typing import List, Union14 unmodified linesimport open_clipfrom peft import PeftModelwarnings.filterwarnings("ignore")logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")logger = logging.getLogger(__name__)# ===================== CONFIG =====================# FIX: Gunakan absolute path berdasarkan lokasi file script iniBASE_DIR = Path(__file__).resolve().parentclass Config:22 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)11 unmodified linesself.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.'):2 unmodified linescleaned[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']43 unmodified lineslogger.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}")3 unmodified lineslogger.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:27 unmodified lineslogger.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!")25 unmodified lineslogger.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')45 unmodified linesbest_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):13 unmodified linesif 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"]10 unmodified linesmarker = "β " 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()123456789101112131415161718192021222324252627282930313233341 unmodified line36373839404114 unmodified lines56575859606162636465666768697022 unmodified lines93949596979811 unmodified lines1101111121131141151161171182 unmodified lines12112212312412512612743 unmodified lines1711721731741751761771781791801811821831841851863 unmodified lines19019119219319419519627 unmodified lines22422522622722822925 unmodified lines25525625725825926045 unmodified lines30630730830931031131231331411 unmodified lines32632732832933033133233333433533633733833934034134213 unmodified lines35635735835936036136210 unmodified lines37337437537637737831 unmodified lines410411412413414#!/usr/bin/env python3"""π₯ Icon Challenge Solver - FINAL FIX HF Spaces"""# ===================== ASYNCIO WARNING FIX =====================import asyncioimport sys# Patch: Suppress "Exception ignored in BaseEventLoop.__del__" on Python 3.12# Ini terjadi karena Gradio/Ultralytics membuat event loop tanpa close eksplisit_original_event_loop_del = asyncio.BaseEventLoop.__del__def _safe_event_loop_del(self):try:if not self.is_closed():self.close()except (ValueError, OSError, RuntimeError):passexcept Exception:passasyncio.BaseEventLoop.__del__ = _safe_event_loop_del# Suppress warningsimport warningswarnings.filterwarnings("ignore", category=ResourceWarning)warnings.filterwarnings("ignore", message="Exception ignored in.*BaseEventLoop.*")warnings.filterwarnings("ignore")# ===================== IMPORTS =====================import osimport ioimport re1 unmodified lineimport base64import jsonimport loggingfrom pathlib import Pathfrom typing import List, Union14 unmodified linesimport open_clipfrom peft import PeftModel# ===================== ENV SETUP =====================os.environ["PYTHONASYNCIODEBUG"] = "0"os.environ["GRADIO_ANALYTICS_ENABLED"] = "0"os.environ["YOLO_CONFIG_DIR"] = "/tmp/Ultralytics"logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")logger = logging.getLogger(__name__)# ===================== CONFIG =====================BASE_DIR = Path(__file__).resolve().parentclass Config:22 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)11 unmodified linesself.backbone = backboneself.projection = ProjectionHead()# Load projection weightsif 'projection' in head_state:proj_dict = head_state['projection']cleaned = {}for k, v in proj_dict.items():if k.startswith('projection.'):2 unmodified linescleaned[k] = vself.projection.load_state_dict(cleaned, strict=False)# Find weight dengan berbagai kemungkinan keyweight = Noneif 'arc_margin' in head_state and 'weight' in head_state['arc_margin']:weight = head_state['arc_margin']['weight']43 unmodified lineslogger.info(f"Base directory: {BASE_DIR}")logger.info("Loading models on GPU...")# YOLOyolo_path = Path(CONFIG.yolo_model_path)logger.info(f"Looking for YOLO at: {yolo_path} (exists: {yolo_path.exists()})")if not yolo_path.exists():alt_path = BASE_DIR / "best.pt"if alt_path.exists():yolo_path = alt_pathelse:raise FileNotFoundError(f"YOLO not found: {yolo_path}")self.yolo = YOLO(str(yolo_path)).to(CONFIG.device)logger.info(f"β YOLO loaded: {yolo_path}")3 unmodified lineslogger.info(f"Looking for LoRA at: {lora_base} (exists: {lora_base.exists()})")if not lora_base.exists():alt_lora = BASE_DIR / "icon_model_hybrid"if alt_lora.exists():lora_base = alt_loraelse:27 unmodified lineslogger.info("β LoRA adapter loaded")except Exception as e:logger.error(f"LoRA load failed: {e}")model_with_lora = backbonelogger.warning("β οΈ Using backbone without LoRA!")25 unmodified lineslogger.info("β All models loaded successfully!")def yolo_detect_and_crop(self, image: Image.Image) -> Image.Image:if image.mode != 'RGB':image = image.convert('RGB')45 unmodified linesbest_idx = int(np.argmax(similarities))sim_scaled = similarities * 10sim_max = np.max(sim_scaled)exp_sim = np.exp(sim_scaled - sim_max)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:try:manager.init()except Exception as e:logger.error(f"Model init failed: {e}", exc_info=True)return f"β Model initialization failed: {str(e)}", Nonetry: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)elif isinstance(challenge_img, str):13 unmodified linesif any(o is None for o in options_pil):return "β Format gambar option tidak valid!", Nonechallenge_crop = manager.yolo_detect_and_crop(challenge_img)result = manager.match_options(challenge_crop, options_pil)best_idx = result["predicted_index"]10 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()31 unmodified linesgr.Markdown("---\nMade with β€οΈ for Icon Challenge")if __name__ == "__main__":demo.launch()
app.py+40-25