Update app.py
Browse files1234565 unmodified lines121314151617188 unmodified lines2728293031323334353615 unmodified lines5253545556575837 unmodified lines969798991001011021031041051061071081091101119 unmodified lines1211221231241251261278 unmodified lines1361371381391401411421 unmodified line1441451461471481491501511521531541554 unmodified lines1601611621631641651661671681691701711721731741751761771781795 unmodified lines18518618718818919019119219316 unmodified lines2102112122132142152162172182192202212222232242252262272282292302312324 unmodified lines2372382392402412422432442452462472482492502512522531 unmodified line255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292#!/usr/bin/env python3"""π₯ Triple Hybrid API + Gradio UI - HF Spaces Optimized"""import os5 unmodified linesimport loggingimport warningsfrom pathlib import Pathfrom typing import List, Union, Optionalimport torchimport torch.nn as nn8 unmodified linesimport gradio as grimport spacesfrom fastapi import FastAPI, Request, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom contextlib import asynccontextmanagerfrom ultralytics import YOLOimport open_clipfrom peft import PeftModel15 unmodified linesCONFIG = Config()# ===================== MODEL DEFINITION =====================class ProjectionHead(nn.Module):def __init__(self, in_dim=1024, hidden_dim=512, out_dim=256, dropout=0.1):super().__init__()37 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)9 unmodified linesexcept:pass# fallback raw bytescommon_sizes = [50, 60, 64, 70, 80, 96, 100, 128]for size in common_sizes:expected = size * size * 48 unmodified lines# ===================== MODEL MANAGER =====================class ModelManager:_instance = Nonedef __new__(cls):if cls._instance is None:cls._instance = super().__new__(cls)1 unmodified linereturn cls._instancedef 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)4 unmodified linesmodel_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:5 unmodified linesbest_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 image16 unmodified linesreturn {"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):4 unmodified linesresult = 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()1 unmodified linereturn "\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 uvicornuvicorn.run(app, host="0.0.0.0", port=7860)1234565 unmodified lines121314151617188 unmodified lines27282930313215 unmodified lines4849505152535437 unmodified lines92939495969798991001011021031041059 unmodified lines1151161171181191208 unmodified lines1291301311321331341 unmodified line1361371381391401411421431441454 unmodified lines1501511521531541551561571581591601611621631641651661675 unmodified lines17317417517617717817918018116 unmodified lines1981992002012022032042052062072082092102112122132142152162172182192202214 unmodified lines2262272282292302312322332342352362372382392402412422431 unmodified line245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279#!/usr/bin/env python3"""π₯ Icon Challenge Solver - Optimized for HF Spaces"""import os5 unmodified linesimport loggingimport warningsfrom pathlib import Pathfrom typing import List, Unionimport torchimport torch.nn as nn8 unmodified linesimport gradio as grimport spacesfrom ultralytics import YOLOimport open_clipfrom peft import PeftModel15 unmodified linesCONFIG = Config()# ===================== MODEL CLASSES =====================class ProjectionHead(nn.Module):def __init__(self, in_dim=1024, hidden_dim=512, out_dim=256, dropout=0.1):super().__init__()37 unmodified linesembedding = self.projection(features)return F.normalize(embedding, p=2, dim=1)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)),])# ===================== UTILS =====================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)9 unmodified linesexcept:passcommon_sizes = [50, 60, 64, 70, 80, 96, 100, 128]for size in common_sizes:expected = size * size * 48 unmodified lines# ===================== MODEL MANAGER =====================class ModelManager:_instance = Nonedef __new__(cls):if cls._instance is None:cls._instance = super().__new__(cls)1 unmodified linereturn cls._instancedef init(self):if self.initialized: returnlogger.info("Loading models on GPU...")self.yolo = YOLO(CONFIG.yolo_model_path).to(CONFIG.device)config_path = Path(CONFIG.lora_model_dir) / "config.json"with open(config_path) as f:model_config = json.load(f)4 unmodified linesmodel_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("β Models loaded!")# (Copy fungsi yolo_detect_and_crop, extract_embedding, match_options dari kode sebelumnya)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:5 unmodified linesbest_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 image16 unmodified linesreturn {"predicted_index": best_idx,"confidence": float(probs[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()# ===================== 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!", None# Convert ke PILif isinstance(challenge_img, np.ndarray):4 unmodified linesresult = 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})")# Cleanupgc.collect()if torch.cuda.is_available():torch.cuda.empty_cache()1 unmodified linereturn "\n".join(lines), options_pil[best_idx]except Exception as e:logger.error(str(e))return f"β Error: {str(e)}", None# ===================== GRADIO INTERFACE =====================with gr.Blocks(title="π₯ Icon Challenge Solver", theme=gr.themes.Soft()) as demo:gr.Markdown("# π₯ Icon Challenge Solver\n**YOLO + SigLIP LoRA Hybrid**")with gr.Row():with gr.Column(scale=1):challenge_input = gr.Image(label="πΌοΈ Challenge Image", 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)]solve_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")# Launch (HF Spaces akan handle ini otomatis)demo.launch()
app.py+45-58