Update app.py
Browse files12345629 unmodified lines3637383940414246 unmodified lines899091929394957 unmodified lines10310410510610710810911011111212 unmodified lines12512612712812913027 unmodified lines15815916016116216316412 unmodified lines1771781791801811821831841859 unmodified lines19519619719819920020120218 unmodified lines2212222232242252262272282292302312322332342352362372382392401 unmodified line24224324424524624724824925025125225325425525625725825926026126226326420 unmodified lines28528628728828929029129229329429513 unmodified lines30931031131231331431531631731831932032114 unmodified lines33633733833934034134234334434534611 unmodified lines358359360361362363364365366367368369370#!/usr/bin/env python3"""π₯ Icon Challenge Solver - 100% Exact LoRA Inference Match"""# ===================== ASYNCIO WARNING FIX =====================29 unmodified linesimport torchvision.transforms as Timport numpy as npfrom PIL import Imageimport cv2import gradio as gr46 unmodified linesself.skip = nn.Linear(in_dim, out_dim)def forward(self, x):# EXACT: self.eval() bukan self.train(False)if x.shape[0] <= 1:self.eval()residual = self.skip(x)7 unmodified lines# ===================== ICON MATCHER (EXACT MATCH REFERENSI) =====================class IconMatcher(nn.Module):"""100% match dengan IconMatcherCPU dari referensi,cuma ditambah .to(device) dan path resolution."""def __init__(self, lora_path, head_path, device='cuda'):super().__init__()backbone, _, _ = open_clip.create_model_and_transforms(12 unmodified linesfeatures = self.backbone(x)return self.projection(features)# ===================== MODEL MANAGER =====================class ModelManager:_instance = None27 unmodified linesif not lora_base.exists():raise FileNotFoundError(f"LoRA dir not found")# Cek adapter subdir atau langsung rootadapter_dir = lora_base / CONFIG.adapter_subdirlora_path = str(adapter_dir) if adapter_dir.exists() else str(lora_base)logger.info(f"LoRA path: {lora_path}")12 unmodified linesif head_path is None:raise FileNotFoundError(f"Head weights not found in {lora_base}")# --- Load IconMatcher (EXACT MATCH REFERENSI) ---self.matcher = IconMatcher(lora_path, head_path, device=CONFIG.device).eval()logger.info("β IconMatcher loaded (100% exact with reference)")# --- Config untuk class names ---config_path = lora_base / "config.json"9 unmodified linesself.initialized = Truelogger.info("β All models ready!")# --- YOLO: Detect + Crop ---def yolo_detect_and_crop(self, image: Image.Image) -> Image.Image:if image.mode != 'RGB':image = image.convert('RGB')18 unmodified linesh, 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 image# --- INFERENCE: 100% EXACT MATCH REFERENSI ---def match_options(self, challenge_crop: Image.Image, options: List[Image.Image]):"""EXACT MATCH dengan:imgs = [Image.open(p).convert('RGB') for p in [target_path] + option_paths]batch = torch.stack([preprocess(img) for img in imgs])embs = model(batch)scores = torch.mm(embs[0:1], embs[1:].t()).squeeze(0)"""# 1. Siapkan semua image (challenge + 8 options)imgs = [challenge_crop] + optionspil_imgs = []for img in imgs:1 unmodified lineimg = img.convert('RGB')pil_imgs.append(img)# 2. Preprocess & stack (EXACT: torch.stack + preprocess)tensors = [preprocess(img) for img in pil_imgs]batch = torch.stack(tensors).to(CONFIG.device)# 3. Forward sekali untuk semua (EXACT: model(batch))with torch.no_grad():embs = self.matcher(batch)# 4. Similarity (EXACT: torch.mm(embs[0:1], embs[1:].t()).squeeze(0))scores = torch.mm(embs[0:1], embs[1:].t()).squeeze(0)best_idx = int(torch.argmax(scores).item())max_score = float(scores.max().item())# 5. Buat probability dari scores untuk display (optional, nggak di referensi tapi buat UI)# Karena embedding sudah L2 normalized, scores = cosine similarity [-1, 1]# Kita convert ke "probability-like" dengan softmax(scores * 10) seperti sebelumnya# tapi INFERENCE UTAMA tetap pakai torch.mm exact di atasprobs = torch.softmax(scores * 10, dim=0).cpu().numpy()return {20 unmodified linesmanager.init()except Exception as e:logger.error(f"Init failed: {e}", exc_info=True)return f"β Init failed: {e}", Nonetry:if 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):13 unmodified linesoptions_pil.append(None)if any(o is None for o in options_pil):return "β Format option tidak valid!", None# YOLO cropchallenge_crop = manager.yolo_detect_and_crop(challenge_img)# Inference (EXACT MATCH REFERENSI)result = manager.match_options(challenge_crop, options_pil)best_idx = result["predicted_index"]lines = [14 unmodified linesif torch.cuda.is_available():torch.cuda.empty_cache()return "\n".join(lines), options_pil[best_idx]except Exception as e:logger.error(str(e), exc_info=True)return f"β Error: {str(e)}", None# ===================== GRADIO UI =====================11 unmodified linessolve_btn = gr.Button("π Solve Challenge", variant="primary", size="large")with gr.Row():result_text = gr.Textbox(label="π Result", lines=14, interactive=False)best_image = gr.Image(label="π Best Match")solve_btn.click(fn=solve_gradio,inputs=[challenge_input] + opt_inputs,outputs=[result_text, best_image])gr.Markdown("---\nMade with β€οΈ for Icon Challenge")12345629 unmodified lines3637383940414246 unmodified lines8990919293947 unmodified lines10210310410510610712 unmodified lines12012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115227 unmodified lines18018118218318418512 unmodified lines1981992002012022032042052069 unmodified lines21621721821922022122222322422522618 unmodified lines2452462472482492502512522532542552562572582592602612622632641 unmodified line26626726826927027127227327427527627727827928028120 unmodified lines30230330430530630730830931031131213 unmodified lines32632732832933033133233333433533633733814 unmodified lines35335435535635735835936036136236336411 unmodified lines376377378379380381382383384385386387388389390391392#!/usr/bin/env python3"""π₯ Icon Challenge Solver - YOLO Crop + Denoise Display"""# ===================== ASYNCIO WARNING FIX =====================29 unmodified linesimport torchvision.transforms as Timport numpy as npfrom PIL import Image, ImageFilterimport cv2import gradio as gr46 unmodified linesself.skip = nn.Linear(in_dim, out_dim)def forward(self, x):if x.shape[0] <= 1:self.eval()residual = self.skip(x)7 unmodified lines# ===================== ICON MATCHER (EXACT MATCH REFERENSI) =====================class IconMatcher(nn.Module):def __init__(self, lora_path, head_path, device='cuda'):super().__init__()backbone, _, _ = open_clip.create_model_and_transforms(12 unmodified linesfeatures = self.backbone(x)return self.projection(features)# ===================== DENOISE + SHARPEN PIPELINE =====================def denoise_and_sharpen(crop_np: np.ndarray) -> np.ndarray:"""Hilangkan blur/pasir (noise) dari hasil crop YOLO.Pipeline: Denoise -> Sharpen -> Contrast boost."""# 1. Non-local Means Denoising (hilangin pasir/noise)denoised = cv2.fastNlMeansDenoisingColored(crop_np, None, 10, 10, 7, 21)# 2. Bilateral filter (edge-preserving smoothing, hapus sisa noise)smooth = cv2.bilateralFilter(denoised, d=5, sigmaColor=50, sigmaSpace=50)# 3. Unsharp Mask (sharpening)gaussian = cv2.GaussianBlur(smooth, (0, 0), sigmaX=2.5)sharpened = cv2.addWeighted(smooth, 1.5, gaussian, -0.5, 0)# 4. CLAHE (Contrast Limited Adaptive Histogram Equalization)# Convert ke LAB, apply CLAHE di channel L, balikin ke RGBlab = cv2.cvtColor(sharpened, cv2.COLOR_RGB2LAB)l, a, b = cv2.split(lab)clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))l = clahe.apply(l)lab = cv2.merge([l, a, b])enhanced = cv2.cvtColor(lab, cv2.COLOR_LAB2RGB)return enhanced# ===================== MODEL MANAGER =====================class ModelManager:_instance = None27 unmodified linesif not lora_base.exists():raise FileNotFoundError(f"LoRA dir not found")adapter_dir = lora_base / CONFIG.adapter_subdirlora_path = str(adapter_dir) if adapter_dir.exists() else str(lora_base)logger.info(f"LoRA path: {lora_path}")12 unmodified linesif head_path is None:raise FileNotFoundError(f"Head weights not found in {lora_base}")# --- Load IconMatcher ---self.matcher = IconMatcher(lora_path, head_path, device=CONFIG.device).eval()logger.info("β IconMatcher loaded")# --- Config untuk class names ---config_path = lora_base / "config.json"9 unmodified linesself.initialized = Truelogger.info("β All models ready!")# --- YOLO: Detect + Crop + Denoise ---def yolo_detect_and_crop(self, image: Image.Image) -> tuple[Image.Image, Image.Image]:"""Returns: (raw_crop, denoised_crop)"""if image.mode != 'RGB':image = image.convert('RGB')18 unmodified linesh, 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:raw_crop = img_np[y1:y2, x1:x2]raw_pil = Image.fromarray(raw_crop)# Denoise + sharpenenhanced = denoise_and_sharpen(raw_crop)enhanced_pil = Image.fromarray(enhanced)return raw_pil, enhanced_pil# Kalau YOLO gagal detect, return original 2xreturn image, image# --- INFERENCE: 100% EXACT MATCH REFERENSI ---def match_options(self, challenge_crop: Image.Image, options: List[Image.Image]):imgs = [challenge_crop] + optionspil_imgs = []for img in imgs:1 unmodified lineimg = img.convert('RGB')pil_imgs.append(img)tensors = [preprocess(img) for img in pil_imgs]batch = torch.stack(tensors).to(CONFIG.device)with torch.no_grad():embs = self.matcher(batch)scores = torch.mm(embs[0:1], embs[1:].t()).squeeze(0)best_idx = int(torch.argmax(scores).item())max_score = float(scores.max().item())probs = torch.softmax(scores * 10, dim=0).cpu().numpy()return {20 unmodified linesmanager.init()except Exception as e:logger.error(f"Init failed: {e}", exc_info=True)return f"β Init failed: {e}", None, Nonetry:if challenge_img is None or any(o is None for o in options):return "β Semua gambar harus diisi!", None, None# Convert ke PILif isinstance(challenge_img, np.ndarray):13 unmodified linesoptions_pil.append(None)if any(o is None for o in options_pil):return "β Format option tidak valid!", None, None# YOLO crop + denoiseraw_crop, denoised_crop = manager.yolo_detect_and_crop(challenge_img)# Inference pakai denoised cropresult = manager.match_options(denoised_crop, options_pil)best_idx = result["predicted_index"]lines = [14 unmodified linesif torch.cuda.is_available():torch.cuda.empty_cache()# Return 3 output: text, best match, denoised cropreturn "\n".join(lines), options_pil[best_idx], denoised_cropexcept Exception as e:logger.error(str(e), exc_info=True)return f"β Error: {str(e)}", None, None# ===================== GRADIO UI =====================11 unmodified linessolve_btn = gr.Button("π Solve Challenge", variant="primary", size="large")with gr.Row():with gr.Column():result_text = gr.Textbox(label="π Result", lines=14, interactive=False)with gr.Column():best_image = gr.Image(label="π Best Match")with gr.Column():crop_image = gr.Image(label="π§ YOLO Crop (Denoised + Sharpened)", height=240)solve_btn.click(fn=solve_gradio,inputs=[challenge_input] + opt_inputs,outputs=[result_text, best_image, crop_image])gr.Markdown("---\nMade with β€οΈ for Icon Challenge")
app.py+63-41