Update app.py
Browse files12345648 unmodified lines55565758596061626364654 unmodified lines70717273747538 unmodified lines11411511611711811912012112212312412512612712812913013164 unmodified lines1961971981992002012022032042052062072082092102112122132142157 unmodified lines2232242252262272282292302312322332342352362372382391 unmodified line2412422432442452462472482491 unmodified line25125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228349 unmodified lines33333433533633733833934034134234334434534634722 unmodified lines3703713723733743753763772 unmodified lines3803813823833843853863873883893903913927 unmodified lines400401402403404405406407408409410411412413#!/usr/bin/env python3"""π₯ Icon Challenge Solver - YOLO Crop Fix"""import os48 unmodified lineslora_model_dir = BASE_DIR / "icon_model_hybrid"adapter_subdir = "lora_adapter"model_name = "ViT-L-16-SigLIP-256"# FIX: Threshold lebih rendah biar YOLO lebih sensitifyolo_conf = 0.15yolo_img_size = 640yolo_min_crop_size = 24yolo_min_conf = 0.15CONFIG = Config()4 unmodified linesT.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),])# ===================== PROJECTION HEAD (EXACT MATCH) =====================class ProjectionHead(nn.Module):def __init__(self, in_dim=1024, hidden_dim=512, out_dim=256, dropout=0.1):38 unmodified linesfeatures = self.backbone(x)return self.projection(features)# ===================== DENOISE + SHARPEN =====================def denoise_and_sharpen(crop_np: np.ndarray) -> np.ndarray:denoised = cv2.fastNlMeansDenoisingColored(crop_np, None, 10, 10, 7, 21)smooth = cv2.bilateralFilter(denoised, d=5, sigmaColor=50, sigmaSpace=50)gaussian = cv2.GaussianBlur(smooth, (0, 0), sigmaX=2.5)sharpened = cv2.addWeighted(smooth, 1.5, gaussian, -0.5, 0)lab = 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])return cv2.cvtColor(lab, cv2.COLOR_LAB2RGB)# ===================== MODEL MANAGER =====================class ModelManager:64 unmodified linesself.initialized = Truelogger.info("β All models ready!")# ===================== YOLO: Detect + Crop + Fallback =====================def yolo_detect_and_crop(self, image: Image.Image) -> Tuple[Image.Image, Image.Image, dict]:"""Returns: (raw_crop, denoised_crop, debug_info)Kalau YOLO gagal detect, fallback ke center crop (bukan full image)."""if image.mode != 'RGB':image = image.convert('RGB')img_np = np.array(image)img_bgr = cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR)h, w = img_np.shape[:2]# YOLO Detectresults = self.yolo(img_bgr, conf=CONFIG.yolo_conf, imgsz=CONFIG.yolo_img_size, verbose=False)best_box = None7 unmodified linesbest_conf = confbest_box = box.xyxy[0].cpu().numpy().astype(int)# FIX: Kalau YOLO detect dan validif best_box is not None and best_conf >= CONFIG.yolo_min_conf:x1, y1, x2, y2 = best_boxx1, y1, x2, y2 = max(0, x1), max(0, y1), min(w, x2), min(h, y2)cw, ch = x2 - x1, y2 - y1if cw >= CONFIG.yolo_min_crop_size and ch >= CONFIG.yolo_min_crop_size:raw_crop = img_np[y1:y2, x1:x2]raw_pil = Image.fromarray(raw_crop)enhanced = denoise_and_sharpen(raw_crop)enhanced_pil = Image.fromarray(enhanced)debug = {"detected": True,1 unmodified line"box": [int(x1), int(y1), int(x2), int(y2)],"crop_size": [cw, ch]}return raw_pil, enhanced_pil, debug# FIX: Fallback center crop (80% dari image) β JANGAN return full imagemargin_x = int(w * 0.1)margin_y = int(h * 0.1)x1, y1 = margin_x, margin_y1 unmodified lineraw_crop = img_np[y1:y2, x1:x2]raw_pil = Image.fromarray(raw_crop)enhanced = denoise_and_sharpen(raw_crop)enhanced_pil = Image.fromarray(enhanced)debug = {"detected": False,"conf": 0.0,"box": [x1, y1, x2, y2],"crop_size": [x2-x1, y2-y1],"fallback": "Center crop 80% (YOLO tidak detect icon)"}return raw_pil, enhanced_pil, debug# ===================== INFERENCE: EXACT MATCH REFERENSI =====================def match_options(self, challenge_crop: Image.Image, options: List[Image.Image]):imgs = [challenge_crop] + optionspil_imgs = []for img in imgs:if img.mode != 'RGB':img = 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())49 unmodified linesif any(o is None for o in options_pil):return "β Format option tidak valid!", None, None, None# YOLO detect + crop + denoiseraw_crop, denoised_crop, debug = manager.yolo_detect_and_crop(challenge_img)# Inference pakai denoised cropresult = manager.match_options(denoised_crop, options_pil)best_idx = result["predicted_index"]# Build result text dengan debug YOLOlines = ["π― HASIL\n",f"β Best Option: {best_idx + 1}",22 unmodified linesif torch.cuda.is_available():torch.cuda.empty_cache()# Return 4 output: text, best match, raw_crop, denoised_cropreturn "\n".join(lines), options_pil[best_idx], raw_crop, denoised_cropexcept Exception as e:logger.error(str(e), exc_info=True)2 unmodified lines# ===================== GRADIO UI =====================with gr.Blocks(title="π₯ Icon Challenge Solver", theme=gr.themes.Soft()) as demo:gr.Markdown("# π₯ Icon Challenge Solver\n**YOLO Detect β Crop β Denoise β SigLIP LoRA Match**")with gr.Row():with gr.Column(scale=1):challenge_input = gr.Image(label="πΌοΈ Challenge Image (Original)", type="numpy", height=240)with gr.Column(scale=2):gr.Markdown("### π² 8 Option Images")with gr.Row():opt_inputs = [gr.Image(label=f"Option {i+1}", type="numpy", height=130) for i in range(8)]7 unmodified lineswith gr.Row():with gr.Column():raw_crop_img = gr.Image(label="π΄ YOLO Raw Crop (Asli)", height=240)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, raw_crop_img, crop_image])gr.Markdown("---\nMade with β€οΈ for Icon Challenge")12345648 unmodified lines55565758596061626364654 unmodified lines707172737475767778798081828384858638 unmodified lines12512612712812913013113213313413513613713813914014114214314414514614714814915015164 unmodified lines2162172182192202212222232242252262272282292302312322332342352367 unmodified lines2442452462472482492502512522532542552562572582592602612622632642651 unmodified line2672682692702712722732742751 unmodified line27727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131249 unmodified lines36236336436536636736836937037137237337437537622 unmodified lines3994004014024034044054062 unmodified lines4094104114124134144154164174184194204217 unmodified lines429430431432433434435436437438439440441442#!/usr/bin/env python3"""π₯ Icon Challenge Solver - B&W Exact Pipeline"""import os48 unmodified lineslora_model_dir = BASE_DIR / "icon_model_hybrid"adapter_subdir = "lora_adapter"model_name = "ViT-L-16-SigLIP-256"yolo_conf = 0.25# FIX: imgsz [128, 224] exact dari referensiyolo_img_size = [128, 224]yolo_min_crop_size = 16yolo_min_conf = 0.25CONFIG = Config()4 unmodified linesT.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),])def preprocess_image(img: Image.Image):"""Untuk model SigLIP yang expect 3 channel:- Kalau image mode 'L' (B&W), duplicate ke 3 channel- Kalau sudah 'RGB', langsung preprocessIni BUKAN convert back ke warna, cuma replicate channel untuk model."""if img.mode != 'RGB':img = img.convert('RGB')return preprocess(img)# ===================== PROJECTION HEAD (EXACT MATCH) =====================class ProjectionHead(nn.Module):def __init__(self, in_dim=1024, hidden_dim=512, out_dim=256, dropout=0.1):38 unmodified linesfeatures = self.backbone(x)return self.projection(features)# ===================== BLACK & WHITE PIPELINE (EXACT REFERENSI) =====================def to_black_white(img_np: np.ndarray) -> np.ndarray:"""Exact pipeline dari referensi:1. Median Blur (3x3) - hapus noise2. Grayscale3. OTSU Threshold β Binary Black & White (0 atau 255)Input: RGB numpy array (H, W, 3)Output: Binary B&W numpy array (H, W) uint8"""# 1. Median Blur untuk hapus noiseblurred = cv2.medianBlur(img_np, 3)# 2. Ubah ke Grayscalegray = cv2.cvtColor(blurred, cv2.COLOR_RGB2GRAY)# 3. Thresholding OTSU β Hitam + Putih total_, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)return binary# ===================== MODEL MANAGER =====================class ModelManager:64 unmodified linesself.initialized = Truelogger.info("β All models ready!")# ===================== YOLO: Detect + Crop + B&W =====================def yolo_detect_and_crop(self, image: Image.Image) -> Tuple[Image.Image, Image.Image, dict]:"""Returns:- raw_crop: crop asli RGB (untuk display)- bw_crop: hasil B&W OTSU (mode 'L', untuk model + display)- debug_info"""if image.mode != 'RGB':image = image.convert('RGB')img_np = np.array(image) # RGBimg_bgr = cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR)# FIX: YOLO dengan imgsz [128, 224] exact dari referensiresults = self.yolo(img_bgr, conf=CONFIG.yolo_conf, imgsz=CONFIG.yolo_img_size, verbose=False)best_box = None7 unmodified linesbest_conf = confbest_box = box.xyxy[0].cpu().numpy().astype(int)h, w = img_np.shape[:2]if best_box is not None and best_conf >= CONFIG.yolo_min_conf:x1, y1, x2, y2 = best_boxx1, y1, x2, y2 = max(0, x1), max(0, y1), min(w, x2), min(h, y2)cw, ch = x2 - x1, y2 - y1if cw >= CONFIG.yolo_min_crop_size and ch >= CONFIG.yolo_min_crop_size:# Crop asli (RGB)raw_crop = img_np[y1:y2, x1:x2]raw_pil = Image.fromarray(raw_crop)# B&W Pipeline exact dari referensi userbw_np = to_black_white(raw_crop)# Simpan sebagai PIL 'L' (grayscale/B&W) - TIDAK convert back ke RGBbw_pil = Image.fromarray(bw_np, mode='L')debug = {"detected": True,1 unmodified line"box": [int(x1), int(y1), int(x2), int(y2)],"crop_size": [cw, ch]}return raw_pil, bw_pil, debug# Fallback: center crop 80% + B&Wmargin_x = int(w * 0.1)margin_y = int(h * 0.1)x1, y1 = margin_x, margin_y1 unmodified lineraw_crop = img_np[y1:y2, x1:x2]raw_pil = Image.fromarray(raw_crop)bw_np = to_black_white(raw_crop)bw_pil = Image.fromarray(bw_np, mode='L')debug = {"detected": False,"conf": 0.0,"box": [x1, y1, x2, y2],"crop_size": [x2-x1, y2-y1],"fallback": "Center crop 80% + B&W (YOLO tidak detect)"}return raw_pil, bw_pil, debug# ===================== INFERENCE: EXACT MATCH REFERENSI =====================def match_options(self, challenge_crop: Image.Image, options: List[Image.Image]):"""challenge_crop: PIL Image mode 'L' (B&W hasil OTSU)options: List PIL Image (user upload, biasanya mode 'L' B&W juga)"""# Gabungkan challenge + 8 optionsimgs = [challenge_crop] + options# Preprocess: convert ke 3-channel untuk model (duplicate L channel)# Ini BUKAN convert back ke warna, cuma replicate untuk SigLIPtensors = [preprocess_image(img) for img in imgs]batch = torch.stack(tensors).to(CONFIG.device)with torch.no_grad():embs = self.matcher(batch)# Exact match referensi: 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())49 unmodified linesif any(o is None for o in options_pil):return "β Format option tidak valid!", None, None, None# YOLO detect + crop + B&W pipelineraw_crop, bw_crop, debug = manager.yolo_detect_and_crop(challenge_img)# Inference pakai B&W crop (mode 'L')result = manager.match_options(bw_crop, options_pil)best_idx = result["predicted_index"]# Build result textlines = ["π― HASIL\n",f"β Best Option: {best_idx + 1}",22 unmodified linesif torch.cuda.is_available():torch.cuda.empty_cache()# Return: text, best match, raw crop RGB, B&W cropreturn "\n".join(lines), options_pil[best_idx], raw_crop, bw_cropexcept Exception as e:logger.error(str(e), exc_info=True)2 unmodified lines# ===================== GRADIO UI =====================with gr.Blocks(title="π₯ Icon Challenge Solver", theme=gr.themes.Soft()) as demo:gr.Markdown("# π₯ Icon Challenge Solver\n**YOLO(128Γ224) β Crop β MedianBlur β Grayscale β OTSU β SigLIP LoRA**")with gr.Row():with gr.Column(scale=1):challenge_input = gr.Image(label="πΌοΈ Challenge Image (Original)", type="numpy", height=240)with gr.Column(scale=2):gr.Markdown("### π² 8 Option Images (B&W Icons)")with gr.Row():opt_inputs = [gr.Image(label=f"Option {i+1}", type="numpy", height=130) for i in range(8)]7 unmodified lineswith gr.Row():with gr.Column():raw_crop_img = gr.Image(label="π΄ YOLO Raw Crop (RGB)", height=240)with gr.Column():bw_crop_img = gr.Image(label="β« YOLO B&W Crop (OTSU Binary)", height=240)solve_btn.click(fn=solve_gradio,inputs=[challenge_input] + opt_inputs,outputs=[result_text, best_image, raw_crop_img, bw_crop_img])gr.Markdown("---\nMade with β€οΈ for Icon Challenge")
app.py+81-52