Update app.py
Browse files12345672 unmodified lines1011121314151617181920215 unmodified lines27282930313233343536373839404142432 unmodified lines46474849505152535455565758596061626364656667686970717217 unmodified lines909192939495969798991001019 unmodified lines1111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671686 unmodified lines175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596#!/usr/bin/env python3"""π₯ Triple Hybrid API + Gradio UIFastAPI backend + Gradio frontend (1 app, 2 interface)"""import os2 unmodified linesimport gcimport base64import jsonimport mathimport loggingimport warningsfrom pathlib import Pathfrom typing import List, Union, Optional, Tuplefrom dataclasses import dataclassimport torchimport torch.nn as nn5 unmodified linesimport cv2import torchvision.transforms as Tfrom fastapi import FastAPI, Request, HTTPException, File, UploadFilefrom fastapi.concurrency import run_in_threadpoolfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import HTMLResponsefrom pydantic import BaseModelfrom contextlib import asynccontextmanager# Gradioimport gradio as grimport spaces # β DITAMBAHKAN untuk HF Spaces GPUfrom ultralytics import YOLOimport open_clipfrom peft import PeftModel2 unmodified lineslogging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")logger = logging.getLogger(__name__)# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# CONFIG# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@dataclassclass Config:device: str = "cuda" if torch.cuda.is_available() else "cpu"yolo_model_path: str = "./yolo/best.pt"yolo_conf: float = 0.25yolo_img_size: int = 640yolo_min_crop_size: int = 32yolo_min_conf: float = 0.3lora_model_dir: str = "./icon_model_hybrid"model_name: str = "ViT-L-16-SigLIP-256"img_size: int = 256CONFIG = Config()# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# PROJECTION HEAD (Sesuai Training)# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββclass ProjectionHead(nn.Module):def __init__(self, in_dim=1024, hidden_dim=512, out_dim=256, dropout=0.1):super().__init__()17 unmodified linesx = 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(1024, 512, 256)self.weight = nn.Parameter(head_state['arc_margin']['weight'])self.projection.load_state_dict(head_state['projection'])self.s = 30.09 unmodified linesembedding = self.projection(features)return F.normalize(embedding, p=2, dim=1)# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# PREPROCESSING (ImageNet β sesuai training)# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββcustom_preprocess = T.Compose([T.Resize((256, 256), interpolation=T.InterpolationMode.NEAREST),T.ToTensor(),T.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),])# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# IMAGE DECODE# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ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)try:raw_bytes = base64.b64decode(clean, validate=False)except Exception as e:raise ValueError(f"Base64 decode failed: {e}")else:raw_bytes = datatry:img = Image.open(io.BytesIO(raw_bytes)).convert("RGB")return imgexcept Exception:passcommon_sizes = [50, 60, 64, 70, 80, 96, 100, 128]for size in common_sizes:expected_bytes = size * size * 4if len(raw_bytes) >= expected_bytes:try:arr = np.frombuffer(raw_bytes[:expected_bytes], dtype=np.uint8)arr = arr.reshape((size, size, 4))rgb_arr = arr[:, :, :3]return Image.fromarray(rgb_arr)except Exception:continueraise ValueError(f"Cannot decode {filename}")# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# MODEL MANAGER# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββclass ModelManager:_instance = None6 unmodified linesdef init(self):if self.initialized:returnlogger.info("=" * 60)logger.info("π₯ INITIALIZING TRIPLE HYBRID API + Gradio")logger.info("=" * 60)logger.info(f"π¦ Loading YOLO: {CONFIG.yolo_model_path}")self.yolo = YOLO(CONFIG.yolo_model_path)self.yolo.to(CONFIG.device)logger.info("β YOLO loaded")logger.info(f"π¦ Loading Hybrid LoRA from: {CONFIG.lora_model_dir}")config_path = Path(CONFIG.lora_model_dir) / "config.json"with open(config_path) as f:self.model_config = json.load(f)num_classes = self.model_config.get('num_classes')if num_classes is None:class_to_idx = self.model_config.get('class_to_idx', {})num_classes = len(class_to_idx)model_name = self.model_config.get('model_name', CONFIG.model_name)logger.info(f" Config: {num_classes} classes, {model_name}")backbone, _, _ = open_clip.create_model_and_transforms(model_name, pretrained='webli')backbone = backbone.visual.to(CONFIG.device)model_with_lora = PeftModel.from_pretrained(backbone, CONFIG.lora_model_dir)head_path = Path(CONFIG.lora_model_dir) / "head_weights.pt"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()logger.info("β Hybrid LoRA loaded")self.idx_to_class = {int(k): v for k, v in self.model_config.get('idx_to_class', {}).items()}self.class_names = [self.idx_to_class.get(i, f"class_{i}") for i in range(num_classes)]self.initialized = Truelogger.info("=" * 60)logger.info("π ALL MODELS READY!")logger.info("=" * 60)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:x1, y1, x2, y2 = best_boxh, w = img_np.shape[:2]x1, y1 = max(0, x1), max(0, y1)x2, y2 = min(w, x2), min(h, y2)crop_w = x2 - x1crop_h = y2 - y1if best_conf < CONFIG.yolo_min_conf:logger.warning(f"YOLO conf too low ({best_conf:.3f}), using full image")return imageif crop_w < CONFIG.yolo_min_crop_size or crop_h < CONFIG.yolo_min_crop_size:logger.warning(f"YOLO crop too small ({crop_w}x{crop_h}), using full image")return imagelogger.info(f"YOLO crop: ({x1},{y1})β({x2},{y2}) [{crop_w}x{crop_h}], conf={best_conf:.3f}")return Image.fromarray(img_np[y1:y2, x1:x2])else:logger.warning("YOLO: No detection, using full image")return imagedef extract_embedding(self, image: Image.Image) -> torch.Tensor:img_tensor = custom_preprocess(image).unsqueeze(0).to(CONFIG.device)with torch.no_grad():with autocast():emb = self.inference_model.get_embedding(img_tensor)return embdef match_options(self, challenge_crop: Image.Image, options: List[Image.Image]) -> dict:challenge_emb = self.extract_embedding(challenge_crop)option_embs = []for opt_img in options:emb = self.extract_embedding(opt_img)option_embs.append(emb)option_stack = torch.cat(option_embs, dim=0)similarities = (challenge_emb @ option_stack.T).squeeze(0).cpu().numpy()best_idx = int(np.argmax(similarities))best_score = float(similarities[best_idx])exp_sim = np.exp(similarities * 10)probs = exp_sim / exp_sim.sum()return {"predicted_index": best_idx,"confidence": float(probs[best_idx]),"similarity_score": best_score,"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")}# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# GRADIO FUNCTION (DITAMBAHKAN @spaces.GPU)# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@spaces.GPU() # β INI YANG DIPERLUKAN AGAR HF Spaces mendeteksi GPU usagedef solve_gradio(challenge_img, opt1, opt2, opt3, opt4, opt5, opt6, opt7, opt8):"""Gradio interface function.Input: 9 images (1 challenge + 8 options)Output: Result text + highlighted best option"""manager = ModelManager()if not manager.initialized:return "Error: Model not initialized", Nonetry:options = [opt1, opt2, opt3, opt4, opt5, opt6, opt7, opt8]# Validateif challenge_img is None:return "Error: Challenge image required", Noneif any(o is None for o in options):return "Error: All 8 options required", None# Convert numpy/PILif isinstance(challenge_img, np.ndarray):challenge_img = Image.fromarray(challenge_img)options_pil = []for i, opt in enumerate(options):if isinstance(opt, np.ndarray):opt = Image.fromarray(opt)options_pil.append(opt)# YOLO cropchallenge_crop = manager.yolo_detect_and_crop(challenge_img)# Matchresult = manager.match_options(challenge_crop, options_pil)# Format outputbest_idx = result["predicted_index"]confidence = result["confidence"]predicted_class = result["predicted_class"]lines = ["","π― RESULT","",f"Best Option: {best_idx + 1} (index {best_idx})",f"Confidence: {confidence:.4f} ({confidence*100:.2f}%)",f"Predicted Class: {predicted_class}",f"Similarity Score: {result['similarity_score']:.4f}","","π All Scores:","",]for i in range(8):score = result["all_scores"][f"option_{i}"]marker = "β " if i == best_idx else " "lines.append(f"{marker} Option {i+1}: {score['probability']:.4f} ({score['similarity']:.4f})")output_text = "\n".join(lines)# Return best option imagebest_image = options_pil[best_idx]gc.collect()if torch.cuda.is_available():torch.cuda.empty_cache()return output_text, best_imageexcept Exception as e:logger.error(f"Gradio error: {e}", exc_info=True)return f"Error: {str(e)}", None# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# BUILD GRADIO INTERFACE# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef build_gradio_interface() -> gr.Blocks:with gr.Blocks(title="π₯ Icon Challenge Solver", theme=gr.themes.Soft()) as demo:gr.Markdown("""# π₯ Icon Challenge Solver### YOLO + SigLIP LoRA HybridUpload 1 challenge image + 8 option images. The AI will:1. **YOLO**: Detect & crop the icon from challenge2. **SigLIP LoRA**: Match the crop with 8 options3. Return the best matching option""")with gr.Row():with gr.Column(scale=1):gr.Markdown("### π― Challenge Image")challenge_input = gr.Image(label="Challenge (1 image)",type="numpy",height=200)with gr.Column(scale=2):gr.Markdown("### π² Option Images (8 total)")with gr.Row():opt1 = gr.Image(label="Option 1", type="numpy", height=150)opt2 = gr.Image(label="Option 2", type="numpy", height=150)opt3 = gr.Image(label="Option 3", type="numpy", height=150)opt4 = gr.Image(label="Option 4", type="numpy", height=150)with gr.Row():opt5 = gr.Image(label="Option 5", type="numpy", height=150)opt6 = gr.Image(label="Option 6", type="numpy", height=150)opt7 = gr.Image(label="Option 7", type="numpy", height=150)opt8 = gr.Image(label="Option 8", type="numpy", height=150)with gr.Row():solve_btn = gr.Button("π Solve Challenge", variant="primary", size="lg")with gr.Row():with gr.Column(scale=1):gr.Markdown("### π Result")result_text = gr.Textbox(label="Analysis",lines=15,max_lines=20,interactive=False)with gr.Column(scale=1):gr.Markdown("### β Best Match")best_image = gr.Image(label="Best Option", height=200)# Bind buttonsolve_btn.click(fn=solve_gradio,inputs=[challenge_input, opt1, opt2, opt3, opt4, opt5, opt6, opt7, opt8],outputs=[result_text, best_image])gr.Markdown("""---**API Endpoint:** `POST /solve` (JSON or multipart)**Health Check:** `GET /health`""")return demo# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# FASTAPI APP# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@asynccontextmanagerasync def lifespan(app: FastAPI):manager = ModelManager()manager.init()yieldlogger.info("Shutting down...")gc.collect()torch.cuda.empty_cache()app = FastAPI(title="Triple Hybrid API + Gradio: YOLO + SigLIP LoRA",version="4.0.0",lifespan=lifespan)app.add_middleware(CORSMiddleware,allow_origins=["*"],allow_credentials=True,allow_methods=["*"],allow_headers=["*"],)class SolveRequest(BaseModel):challenge: stroptions: List[str]@app.get("/")async def root():return {"message": "Triple Hybrid API + Gradio: YOLO + SigLIP LoRA","endpoints": {"solve": "POST /solve","health": "GET /health","gradio": "GET /gradio"},"preprocessing": "mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)"}@app.get("/health")async def health_check():manager = ModelManager()return {"status": "healthy","yolo_loaded": hasattr(manager, 'yolo') and manager.yolo is not None,"hybrid_loaded": hasattr(manager, 'inference_model') and manager.inference_model is not None,"device": CONFIG.device,"num_classes": len(manager.idx_to_class) if hasattr(manager, 'idx_to_class') else 0}@app.post("/solve")async def solve(request: Request):manager = ModelManager()content_type = request.headers.get("content-type", "").lower()challenge_img: Optional[Image.Image] = Noneoption_imgs: List[Image.Image] = []try:if "application/json" in content_type:body = await request.json()challenge_input = body.get("challenge")options_input = body.get("options", [])if not challenge_input:raise HTTPException(400, "'challenge' wajib diisi.")if not isinstance(options_input, list) or len(options_input) != 8:raise HTTPException(400, "'options' harus list berisi tepat 8 base64 images.")challenge_img = decode_image_advanced(challenge_input, "challenge")option_imgs = [decode_image_advanced(o, f"option_{i}") for i, o in enumerate(options_input)]elif "multipart/form-data" in content_type:form = await request.form()challenge_item = form.get("challenge")if challenge_item is None:raise HTTPException(400, "Field 'challenge' wajib diisi.")if hasattr(challenge_item, "read"):content = await challenge_item.read()challenge_img = decode_image_advanced(content, "challenge")else:challenge_img = decode_image_advanced(challenge_item, "challenge")options_items = form.getlist("options") or []if len(options_items) != 8:options_items = []for i in range(1, 9):item = form.get(f"option_{i}")if item is None:breakoptions_items.append(item)if len(options_items) != 8:raise HTTPException(400, f"Harus ada tepat 8 options, ditemukan {len(options_items)}.")for i, item in enumerate(options_items):try:if hasattr(item, "read"):content = await item.read()option_imgs.append(decode_image_advanced(content, f"option_{i}"))else:option_imgs.append(decode_image_advanced(item, f"option_{i}"))except ValueError as e:raise HTTPException(400, f"Error option_{i+1}: {str(e)}")else:raise HTTPException(415, "Content-Type tidak didukung.")logger.info(f"π₯ Received: challenge({challenge_img.size}) + {len(option_imgs)} options")challenge_crop = await run_in_threadpool(manager.yolo_detect_and_crop, challenge_img)result = await run_in_threadpool(manager.match_options, challenge_crop, option_imgs)logger.info(f"β Result: Option {result['predicted_index']} (conf: {result['confidence']:.4f})")gc.collect()if torch.cuda.is_available():torch.cuda.empty_cache()return {"success": True,"predicted_index": result["predicted_index"],"confidence": result["confidence"],"similarity_score": result["similarity_score"],"predicted_class": result["predicted_class"],"all_scores": result["all_scores"],"debug": {"challenge_crop_size": challenge_crop.size,"device": CONFIG.device,"preprocessing": "mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)"}}except HTTPException:raiseexcept ValueError as e:raise HTTPException(400, str(e))except Exception as e:logger.error(f"Unexpected error: {e}", exc_info=True)raise HTTPException(500, f"Internal error: {str(e)}")# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# MOUNT GRADIO TO FASTAPI# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββgradio_app = build_gradio_interface()app = gr.mount_gradio_app(app, gradio_app, path="/gradio")if __name__ == "__main__":import uvicorn1234562 unmodified lines91011121314151617185 unmodified lines242526272829303132333435362 unmodified lines394041424344454647484950515253545556575817 unmodified lines76777879808182838485869 unmodified lines969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381396 unmodified lines146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291#!/usr/bin/env python3"""π₯ Triple Hybrid API + Gradio UI - HF Spaces Optimized"""import os2 unmodified linesimport gcimport base64import jsonimport loggingimport warningsfrom pathlib import Pathfrom typing import List, Union, Optionalimport torchimport torch.nn as nn5 unmodified linesimport cv2import torchvision.transforms as Timport gradio as grimport spacesfrom fastapi import FastAPI, Request, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom contextlib import asynccontextmanagerfrom ultralytics import YOLOimport open_clipfrom peft import PeftModel2 unmodified lineslogging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")logger = logging.getLogger(__name__)# ===================== CONFIG =====================class 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()# ===================== MODEL DEFINITION =====================class ProjectionHead(nn.Module):def __init__(self, in_dim=1024, hidden_dim=512, out_dim=256, dropout=0.1):super().__init__()17 unmodified linesx = 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.09 unmodified linesembedding = self.projection(features)return F.normalize(embedding, p=2, dim=1)# Preprocesscustom_preprocess = T.Compose([T.Resize((256, 256), interpolation=T.InterpolationMode.NEAREST),T.ToTensor(),T.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),])# ===================== IMAGE DECODE =====================def decode_image_advanced(data: Union[str, bytes], filename: str = "image") -> Image.Image:# ... (sama seperti sebelumnya, saya skip tulis ulang biar tidak terlalu panjang)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:pass# fallback raw bytescommon_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 =====================class ModelManager:_instance = None6 unmodified linesdef init(self):if self.initialized:returnlogger.info("π₯ Initializing models on GPU...")self.yolo = YOLO(CONFIG.yolo_model_path).to(CONFIG.device)# Load SigLIP + LoRAconfig_path = Path(CONFIG.lora_model_dir) / "config.json"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', {}))backbone, _, _ = open_clip.create_model_and_transforms(CONFIG.model_name, pretrained='webli')backbone = backbone.visual.to(CONFIG.device)model_with_lora = PeftModel.from_pretrained(backbone, CONFIG.lora_model_dir)head_state = torch.load(Path(CONFIG.lora_model_dir) / "head_weights.pt", 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("β All models loaded successfully!")def yolo_detect_and_crop(self, image: Image.Image) -> Image.Image:# ... (sama seperti kode lama kamu)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)# (saya asumsikan bagian ini tetap sama, copy dari kode lama kamu)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]),"similarity_score": float(similarities[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()# ===================== GRADIO FUNCTION (GPU) =====================@spaces.GPU(request_timeout=120, enable=True)def solve_gradio(challenge_img, opt1, opt2, opt3, opt4, opt5, opt6, opt7, opt8):if not manager.initialized:manager.init()try:options = [opt1, opt2, opt3, opt4, opt5, opt6, opt7, opt8]if challenge_img is None or any(o is None for o in options):return "Error: Semua gambar harus diupload!", 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]challenge_crop = manager.yolo_detect_and_crop(challenge_img)result = manager.match_options(challenge_crop, options_pil)best_idx = result["predicted_index"]lines = ["π― RESULT\n",f"Best Option: {best_idx + 1}",f"Confidence: {result['confidence']:.4f} ({result['confidence']*100:.2f}%)",f"Predicted Class: {result['predicted_class']}\n","π All Scores:"]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()return "\n".join(lines), options_pil[best_idx]except Exception as e:logger.error(f"Error: {e}", exc_info=True)return f"Runtime Error: {str(e)}", None# ===================== GRADIO UI =====================with gr.Blocks(title="Icon Challenge Solver", theme=gr.themes.Soft()) as demo:gr.Markdown("# π₯ Icon Challenge Solver\n**YOLO + SigLIP LoRA**")with gr.Row():with gr.Column(scale=1):challenge_input = gr.Image(label="Challenge Image", type="numpy", height=220)with gr.Column(scale=2):gr.Markdown("### 8 Option Images")with gr.Row():opts = [gr.Image(label=f"Option {i+1}", type="numpy", height=140) for i in range(8)]solve_btn = gr.Button("π Solve Challenge", variant="primary", size="large")with gr.Row():result_text = gr.Textbox(label="Result", lines=12, interactive=False)best_img = gr.Image(label="Best Match")solve_btn.click(fn=solve_gradio,inputs=[challenge_input] + opts,outputs=[result_text, best_img])# ===================== FASTAPI (opsional) =====================app = FastAPI(title="Icon Solver")app = gr.mount_gradio_app(app, demo, path="/")if __name__ == "__main__":import uvicorn
app.py+106-411