release
Browse files- app-dev.py +251 -0
- app.py +111 -81
app-dev.py
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import logging
|
| 3 |
+
import hashlib
|
| 4 |
+
import sys
|
| 5 |
+
import traceback
|
| 6 |
+
import copy
|
| 7 |
+
import tempfile
|
| 8 |
+
|
| 9 |
+
import cv2
|
| 10 |
+
import numpy as np
|
| 11 |
+
import torch
|
| 12 |
+
import torch.nn.functional as F
|
| 13 |
+
import gradio as gr
|
| 14 |
+
from PIL import Image, ImageFilter, ImageChops, ImageDraw
|
| 15 |
+
from huggingface_hub import hf_hub_download
|
| 16 |
+
import spaces
|
| 17 |
+
|
| 18 |
+
# --- IMPORT YOUR CUSTOM MODULES ---
|
| 19 |
+
from sam2.build_sam import build_sam2
|
| 20 |
+
from sam2.sam2_image_predictor import SAM2ImagePredictor
|
| 21 |
+
from plm_adapter_lora_with_image_input_only_text_positions import PLMLanguageAdapter
|
| 22 |
+
|
| 23 |
+
# ----------------- Configuration -----------------
|
| 24 |
+
SAM2_CONFIG = "sam2_hiera_l.yaml"
|
| 25 |
+
BASE_CKPT_NAME = "sam2_hiera_large.pt"
|
| 26 |
+
|
| 27 |
+
SQUARE_DIM = 1024
|
| 28 |
+
logging.basicConfig(level=logging.INFO)
|
| 29 |
+
|
| 30 |
+
# Refactored to store specific filenames per model choice
|
| 31 |
+
MODEL_CONFIGS = {
|
| 32 |
+
"Stage 1": {
|
| 33 |
+
"repo_id": "aadarsh99/ConvSeg-Stage1",
|
| 34 |
+
"sam_filename": "fine_tuned_sam2_batched_100000.torch",
|
| 35 |
+
"plm_filename": "fine_tuned_sam2_batched_plm_100000.torch"
|
| 36 |
+
},
|
| 37 |
+
"Stage 2 (grad-acc: 4)": {
|
| 38 |
+
"repo_id": "aadarsh99/ConvSeg-Stage2",
|
| 39 |
+
"sam_filename": "fine_tuned_sam2_batched_18000.torch",
|
| 40 |
+
"plm_filename": "fine_tuned_sam2_batched_plm_18000.torch"
|
| 41 |
+
},
|
| 42 |
+
"Stage 2 (grad-acc: 8)": {
|
| 43 |
+
"repo_id": "aadarsh99/ConvSeg-Stage2",
|
| 44 |
+
"sam_filename": "fine_tuned_sam2_batched_18000.torch",
|
| 45 |
+
"plm_filename": "fine_tuned_sam2_batched_plm_18000.torch"
|
| 46 |
+
}
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
# Dynamically create cache keys based on config
|
| 50 |
+
MODEL_CACHE = {k: {"sam": None, "plm": None} for k in MODEL_CONFIGS.keys()}
|
| 51 |
+
|
| 52 |
+
# ----------------- Helper Functions -----------------
|
| 53 |
+
def download_if_needed(repo_id, filename):
|
| 54 |
+
try:
|
| 55 |
+
logging.info(f"Checking {filename} in {repo_id}...")
|
| 56 |
+
return hf_hub_download(repo_id=repo_id, filename=filename)
|
| 57 |
+
except Exception as e:
|
| 58 |
+
raise FileNotFoundError(f"Could not find {filename} in {repo_id}. Error: {e}")
|
| 59 |
+
|
| 60 |
+
def stable_color(key: str):
|
| 61 |
+
h = int(hashlib.sha256(str(key).encode("utf-8")).hexdigest(), 16)
|
| 62 |
+
EDGE_COLORS_HEX = ["#3A86FF", "#FF006E", "#43AA8B", "#F3722C", "#8338EC", "#90BE6D"]
|
| 63 |
+
colors = [tuple(int(c.lstrip("#")[i:i+2], 16) for i in (0, 2, 4)) for c in EDGE_COLORS_HEX]
|
| 64 |
+
return colors[h % len(colors)]
|
| 65 |
+
|
| 66 |
+
def make_overlay(rgb: np.ndarray, mask: np.ndarray, key: str = "mask") -> Image.Image:
|
| 67 |
+
# Convert base to RGBA
|
| 68 |
+
base = Image.fromarray(rgb.astype(np.uint8)).convert("RGBA")
|
| 69 |
+
mask_bool = mask > 0
|
| 70 |
+
color = stable_color(key)
|
| 71 |
+
|
| 72 |
+
# Create fill layer (Semi-transparent)
|
| 73 |
+
fill_layer = Image.new("RGBA", base.size, color + (0,))
|
| 74 |
+
fill_alpha = Image.fromarray((mask_bool.astype(np.uint8) * 140), "L")
|
| 75 |
+
fill_layer.putalpha(fill_alpha)
|
| 76 |
+
|
| 77 |
+
# Create stroke/edge layer
|
| 78 |
+
m = Image.fromarray((mask_bool.astype(np.uint8) * 255), "L")
|
| 79 |
+
edges = ImageChops.difference(m.filter(ImageFilter.MaxFilter(3)), m.filter(ImageFilter.MinFilter(3)))
|
| 80 |
+
stroke_layer = Image.new("RGBA", base.size, color + (255,))
|
| 81 |
+
stroke_layer.putalpha(edges)
|
| 82 |
+
|
| 83 |
+
# Composite safely
|
| 84 |
+
out = Image.alpha_composite(base, fill_layer)
|
| 85 |
+
out = Image.alpha_composite(out, stroke_layer)
|
| 86 |
+
|
| 87 |
+
return out.convert("RGB")
|
| 88 |
+
|
| 89 |
+
def ensure_models_loaded(stage_key):
|
| 90 |
+
global MODEL_CACHE
|
| 91 |
+
if MODEL_CACHE[stage_key]["sam"] is not None:
|
| 92 |
+
return
|
| 93 |
+
|
| 94 |
+
config = MODEL_CONFIGS[stage_key]
|
| 95 |
+
repo_id = config["repo_id"]
|
| 96 |
+
|
| 97 |
+
logging.info(f"Loading {stage_key} models from {repo_id} into CPU RAM...")
|
| 98 |
+
|
| 99 |
+
# SAM2
|
| 100 |
+
# Base model is always the same
|
| 101 |
+
base_path = download_if_needed(repo_id, BASE_CKPT_NAME)
|
| 102 |
+
model = build_sam2(SAM2_CONFIG, base_path, device="cpu")
|
| 103 |
+
|
| 104 |
+
# Load specific fine-tuned checkpoint
|
| 105 |
+
final_path = download_if_needed(repo_id, config["sam_filename"])
|
| 106 |
+
sd = torch.load(final_path, map_location="cpu")
|
| 107 |
+
model.load_state_dict(sd.get("model", sd), strict=True)
|
| 108 |
+
|
| 109 |
+
# PLM
|
| 110 |
+
plm_path = download_if_needed(repo_id, config["plm_filename"])
|
| 111 |
+
plm = PLMLanguageAdapter(
|
| 112 |
+
model_name="Qwen/Qwen2.5-VL-3B-Instruct",
|
| 113 |
+
transformer_dim=model.sam_mask_decoder.transformer_dim,
|
| 114 |
+
n_sparse_tokens=0, use_dense_bias=True, use_lora=True,
|
| 115 |
+
lora_r=16, lora_alpha=32, lora_dropout=0.05,
|
| 116 |
+
dtype=torch.bfloat16, device="cpu"
|
| 117 |
+
)
|
| 118 |
+
plm_sd = torch.load(plm_path, map_location="cpu")
|
| 119 |
+
plm.load_state_dict(plm_sd["plm"], strict=True)
|
| 120 |
+
plm.eval()
|
| 121 |
+
|
| 122 |
+
MODEL_CACHE[stage_key]["sam"], MODEL_CACHE[stage_key]["plm"] = model, plm
|
| 123 |
+
|
| 124 |
+
# ----------------- GPU Inference -----------------
|
| 125 |
+
|
| 126 |
+
@spaces.GPU(duration=120)
|
| 127 |
+
def run_prediction(image_pil, text_prompt, threshold, stage_choice):
|
| 128 |
+
if image_pil is None or not text_prompt:
|
| 129 |
+
return None, None, None
|
| 130 |
+
|
| 131 |
+
ensure_models_loaded(stage_choice)
|
| 132 |
+
sam_model = MODEL_CACHE[stage_choice]["sam"]
|
| 133 |
+
plm_model = MODEL_CACHE[stage_choice]["plm"]
|
| 134 |
+
|
| 135 |
+
sam_model.to("cuda")
|
| 136 |
+
plm_model.to("cuda")
|
| 137 |
+
|
| 138 |
+
try:
|
| 139 |
+
with torch.inference_mode():
|
| 140 |
+
predictor = SAM2ImagePredictor(sam_model)
|
| 141 |
+
rgb_orig = np.array(image_pil.convert("RGB"))
|
| 142 |
+
H, W = rgb_orig.shape[:2]
|
| 143 |
+
|
| 144 |
+
# Padding math
|
| 145 |
+
scale = SQUARE_DIM / max(H, W)
|
| 146 |
+
nw, nh = int(W * scale), int(H * scale)
|
| 147 |
+
top, left = (SQUARE_DIM - nh) // 2, (SQUARE_DIM - nw) // 2
|
| 148 |
+
|
| 149 |
+
# Resize & Pad
|
| 150 |
+
rgb_sq = cv2.resize(rgb_orig, (nw, nh), interpolation=cv2.INTER_LINEAR)
|
| 151 |
+
rgb_sq = cv2.copyMakeBorder(rgb_sq, top, SQUARE_DIM-nh-top, left, SQUARE_DIM-nw-left, cv2.BORDER_CONSTANT, value=0)
|
| 152 |
+
|
| 153 |
+
predictor.set_image(rgb_sq)
|
| 154 |
+
image_emb = predictor._features["image_embed"][-1].unsqueeze(0)
|
| 155 |
+
hi = [lvl[-1].unsqueeze(0) for lvl in predictor._features["high_res_feats"]]
|
| 156 |
+
|
| 157 |
+
# PLM adapter
|
| 158 |
+
with tempfile.NamedTemporaryFile(suffix=".jpg") as tmp:
|
| 159 |
+
image_pil.save(tmp.name)
|
| 160 |
+
sp, dp = plm_model([text_prompt], image_emb.shape[2], image_emb.shape[3], [tmp.name])
|
| 161 |
+
|
| 162 |
+
# SAM2 Decoding
|
| 163 |
+
dec = sam_model.sam_mask_decoder
|
| 164 |
+
dev, dtype = next(dec.parameters()).device, next(dec.parameters()).dtype
|
| 165 |
+
|
| 166 |
+
low, scores, _, _ = dec(
|
| 167 |
+
image_embeddings=image_emb.to(dev, dtype),
|
| 168 |
+
image_pe=sam_model.sam_prompt_encoder.get_dense_pe().to(dev, dtype),
|
| 169 |
+
sparse_prompt_embeddings=sp.to(dev, dtype),
|
| 170 |
+
dense_prompt_embeddings=dp.to(dev, dtype),
|
| 171 |
+
multimask_output=True, repeat_image=False,
|
| 172 |
+
high_res_features=[h.to(dev, dtype) for h in hi]
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
# Postprocess to original dimensions
|
| 176 |
+
logits = predictor._transforms.postprocess_masks(low, (SQUARE_DIM, SQUARE_DIM))
|
| 177 |
+
best_idx = scores.argmax().item()
|
| 178 |
+
logit_crop = logits[0, best_idx, top:top+nh, left:left+nw].unsqueeze(0).unsqueeze(0)
|
| 179 |
+
logit_full = F.interpolate(logit_crop, size=(H, W), mode="bilinear", align_corners=False)[0, 0]
|
| 180 |
+
|
| 181 |
+
prob = torch.sigmoid(logit_full).float().cpu().numpy()
|
| 182 |
+
|
| 183 |
+
# Generate Heatmap
|
| 184 |
+
heatmap_cv = cv2.applyColorMap((prob * 255).astype(np.uint8), cv2.COLORMAP_JET)
|
| 185 |
+
heatmap_rgb = cv2.cvtColor(heatmap_cv, cv2.COLOR_BGR2RGB)
|
| 186 |
+
|
| 187 |
+
# Initial Overlay
|
| 188 |
+
mask = (prob > threshold).astype(np.uint8) * 255
|
| 189 |
+
overlay = make_overlay(rgb_orig, mask, key=text_prompt)
|
| 190 |
+
|
| 191 |
+
return overlay, Image.fromarray(heatmap_rgb), prob
|
| 192 |
+
|
| 193 |
+
except Exception:
|
| 194 |
+
traceback.print_exc()
|
| 195 |
+
return None, None, None
|
| 196 |
+
finally:
|
| 197 |
+
sam_model.to("cpu")
|
| 198 |
+
plm_model.to("cpu")
|
| 199 |
+
torch.cuda.empty_cache()
|
| 200 |
+
|
| 201 |
+
def update_threshold_ui(image_pil, text_prompt, threshold, cached_prob):
|
| 202 |
+
"""Instant update using CPU only."""
|
| 203 |
+
if image_pil is None or cached_prob is None:
|
| 204 |
+
return None
|
| 205 |
+
rgb_orig = np.array(image_pil.convert("RGB"))
|
| 206 |
+
mask = (cached_prob > threshold).astype(np.uint8) * 255
|
| 207 |
+
return make_overlay(rgb_orig, mask, key=text_prompt)
|
| 208 |
+
|
| 209 |
+
# ----------------- Gradio UI -----------------
|
| 210 |
+
|
| 211 |
+
with gr.Blocks(title="SAM2 + PLM Segmentation") as demo:
|
| 212 |
+
prob_state = gr.State()
|
| 213 |
+
|
| 214 |
+
gr.Markdown("# SAM2 + PLM Interactive Segmentation")
|
| 215 |
+
gr.Markdown("Select a stage, enter a prompt, and run. Adjust the slider for **instant** mask updates.")
|
| 216 |
+
|
| 217 |
+
with gr.Row():
|
| 218 |
+
with gr.Column():
|
| 219 |
+
input_image = gr.Image(type="pil", label="Input Image")
|
| 220 |
+
text_prompt = gr.Textbox(label="Text Prompt", placeholder="e.g., 'the surgical forceps'")
|
| 221 |
+
|
| 222 |
+
with gr.Row():
|
| 223 |
+
stage_select = gr.Radio(
|
| 224 |
+
choices=list(MODEL_CONFIGS.keys()),
|
| 225 |
+
value="Stage 2 (grad-acc: 8)",
|
| 226 |
+
label="Model Stage"
|
| 227 |
+
)
|
| 228 |
+
threshold_slider = gr.Slider(0.0, 1.0, value=0.5, step=0.01, label="Threshold")
|
| 229 |
+
|
| 230 |
+
run_btn = gr.Button("Run Inference", variant="primary")
|
| 231 |
+
|
| 232 |
+
with gr.Column():
|
| 233 |
+
out_overlay = gr.Image(label="Segmentation Overlay", type="pil")
|
| 234 |
+
out_heatmap = gr.Image(label="Probability Heatmap", type="pil")
|
| 235 |
+
|
| 236 |
+
# Full Pipeline
|
| 237 |
+
run_btn.click(
|
| 238 |
+
fn=run_prediction,
|
| 239 |
+
inputs=[input_image, text_prompt, threshold_slider, stage_select],
|
| 240 |
+
outputs=[out_overlay, out_heatmap, prob_state]
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
# Lightweight update on slider move
|
| 244 |
+
threshold_slider.change(
|
| 245 |
+
fn=update_threshold_ui,
|
| 246 |
+
inputs=[input_image, text_prompt, threshold_slider, prob_state],
|
| 247 |
+
outputs=[out_overlay]
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
if __name__ == "__main__":
|
| 251 |
+
demo.launch()
|
app.py
CHANGED
|
@@ -3,51 +3,36 @@ import logging
|
|
| 3 |
import hashlib
|
| 4 |
import sys
|
| 5 |
import traceback
|
| 6 |
-
import copy
|
| 7 |
import tempfile
|
| 8 |
-
|
| 9 |
import cv2
|
| 10 |
import numpy as np
|
| 11 |
import torch
|
| 12 |
import torch.nn.functional as F
|
| 13 |
import gradio as gr
|
| 14 |
-
from PIL import Image, ImageFilter, ImageChops
|
| 15 |
from huggingface_hub import hf_hub_download
|
| 16 |
import spaces
|
| 17 |
|
| 18 |
# --- IMPORT YOUR CUSTOM MODULES ---
|
|
|
|
| 19 |
from sam2.build_sam import build_sam2
|
| 20 |
from sam2.sam2_image_predictor import SAM2ImagePredictor
|
| 21 |
from plm_adapter_lora_with_image_input_only_text_positions import PLMLanguageAdapter
|
| 22 |
|
| 23 |
# ----------------- Configuration -----------------
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
SAM2_CONFIG = "sam2_hiera_l.yaml"
|
| 25 |
BASE_CKPT_NAME = "sam2_hiera_large.pt"
|
|
|
|
|
|
|
| 26 |
|
| 27 |
SQUARE_DIM = 1024
|
| 28 |
-
logging.basicConfig(level=logging.INFO)
|
| 29 |
-
|
| 30 |
-
# Refactored to store specific filenames per model choice
|
| 31 |
-
MODEL_CONFIGS = {
|
| 32 |
-
"Stage 1": {
|
| 33 |
-
"repo_id": "aadarsh99/ConvSeg-Stage1",
|
| 34 |
-
"sam_filename": "fine_tuned_sam2_batched_100000.torch",
|
| 35 |
-
"plm_filename": "fine_tuned_sam2_batched_plm_100000.torch"
|
| 36 |
-
},
|
| 37 |
-
"Stage 2 (grad-acc: 4)": {
|
| 38 |
-
"repo_id": "aadarsh99/ConvSeg-Stage2",
|
| 39 |
-
"sam_filename": "fine_tuned_sam2_batched_18000.torch",
|
| 40 |
-
"plm_filename": "fine_tuned_sam2_batched_plm_18000.torch"
|
| 41 |
-
},
|
| 42 |
-
"Stage 2 (grad-acc: 8)": {
|
| 43 |
-
"repo_id": "aadarsh99/ConvSeg-Stage2",
|
| 44 |
-
"sam_filename": "fine_tuned_sam2_batched_18000.torch",
|
| 45 |
-
"plm_filename": "fine_tuned_sam2_batched_plm_18000.torch"
|
| 46 |
-
}
|
| 47 |
-
}
|
| 48 |
|
| 49 |
-
#
|
| 50 |
-
MODEL_CACHE = {
|
| 51 |
|
| 52 |
# ----------------- Helper Functions -----------------
|
| 53 |
def download_if_needed(repo_id, filename):
|
|
@@ -59,55 +44,49 @@ def download_if_needed(repo_id, filename):
|
|
| 59 |
|
| 60 |
def stable_color(key: str):
|
| 61 |
h = int(hashlib.sha256(str(key).encode("utf-8")).hexdigest(), 16)
|
|
|
|
| 62 |
EDGE_COLORS_HEX = ["#3A86FF", "#FF006E", "#43AA8B", "#F3722C", "#8338EC", "#90BE6D"]
|
| 63 |
colors = [tuple(int(c.lstrip("#")[i:i+2], 16) for i in (0, 2, 4)) for c in EDGE_COLORS_HEX]
|
| 64 |
return colors[h % len(colors)]
|
| 65 |
|
| 66 |
def make_overlay(rgb: np.ndarray, mask: np.ndarray, key: str = "mask") -> Image.Image:
|
| 67 |
-
# Convert base to RGBA
|
| 68 |
base = Image.fromarray(rgb.astype(np.uint8)).convert("RGBA")
|
| 69 |
mask_bool = mask > 0
|
| 70 |
color = stable_color(key)
|
| 71 |
|
| 72 |
-
#
|
| 73 |
fill_layer = Image.new("RGBA", base.size, color + (0,))
|
| 74 |
fill_alpha = Image.fromarray((mask_bool.astype(np.uint8) * 140), "L")
|
| 75 |
fill_layer.putalpha(fill_alpha)
|
| 76 |
|
| 77 |
-
#
|
| 78 |
m = Image.fromarray((mask_bool.astype(np.uint8) * 255), "L")
|
| 79 |
edges = ImageChops.difference(m.filter(ImageFilter.MaxFilter(3)), m.filter(ImageFilter.MinFilter(3)))
|
| 80 |
stroke_layer = Image.new("RGBA", base.size, color + (255,))
|
| 81 |
stroke_layer.putalpha(edges)
|
| 82 |
|
| 83 |
-
# Composite
|
| 84 |
out = Image.alpha_composite(base, fill_layer)
|
| 85 |
out = Image.alpha_composite(out, stroke_layer)
|
| 86 |
-
|
| 87 |
return out.convert("RGB")
|
| 88 |
|
| 89 |
-
def ensure_models_loaded(
|
| 90 |
global MODEL_CACHE
|
| 91 |
-
if MODEL_CACHE[
|
| 92 |
return
|
| 93 |
|
| 94 |
-
|
| 95 |
-
repo_id = config["repo_id"]
|
| 96 |
-
|
| 97 |
-
logging.info(f"Loading {stage_key} models from {repo_id} into CPU RAM...")
|
| 98 |
|
| 99 |
-
# SAM2
|
| 100 |
-
|
| 101 |
-
base_path = download_if_needed(repo_id, BASE_CKPT_NAME)
|
| 102 |
model = build_sam2(SAM2_CONFIG, base_path, device="cpu")
|
| 103 |
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
sd = torch.load(final_path, map_location="cpu")
|
| 107 |
model.load_state_dict(sd.get("model", sd), strict=True)
|
| 108 |
|
| 109 |
-
# PLM
|
| 110 |
-
plm_path = download_if_needed(
|
| 111 |
plm = PLMLanguageAdapter(
|
| 112 |
model_name="Qwen/Qwen2.5-VL-3B-Instruct",
|
| 113 |
transformer_dim=model.sam_mask_decoder.transformer_dim,
|
|
@@ -119,19 +98,22 @@ def ensure_models_loaded(stage_key):
|
|
| 119 |
plm.load_state_dict(plm_sd["plm"], strict=True)
|
| 120 |
plm.eval()
|
| 121 |
|
| 122 |
-
MODEL_CACHE[
|
|
|
|
|
|
|
| 123 |
|
| 124 |
# ----------------- GPU Inference -----------------
|
| 125 |
|
| 126 |
@spaces.GPU(duration=120)
|
| 127 |
-
def run_prediction(image_pil, text_prompt, threshold
|
| 128 |
if image_pil is None or not text_prompt:
|
| 129 |
return None, None, None
|
| 130 |
|
| 131 |
-
ensure_models_loaded(
|
| 132 |
-
sam_model = MODEL_CACHE[
|
| 133 |
-
plm_model = MODEL_CACHE[
|
| 134 |
|
|
|
|
| 135 |
sam_model.to("cuda")
|
| 136 |
plm_model.to("cuda")
|
| 137 |
|
|
@@ -141,25 +123,26 @@ def run_prediction(image_pil, text_prompt, threshold, stage_choice):
|
|
| 141 |
rgb_orig = np.array(image_pil.convert("RGB"))
|
| 142 |
H, W = rgb_orig.shape[:2]
|
| 143 |
|
| 144 |
-
# Padding
|
| 145 |
scale = SQUARE_DIM / max(H, W)
|
| 146 |
nw, nh = int(W * scale), int(H * scale)
|
| 147 |
top, left = (SQUARE_DIM - nh) // 2, (SQUARE_DIM - nw) // 2
|
| 148 |
|
| 149 |
-
# Resize & Pad
|
| 150 |
rgb_sq = cv2.resize(rgb_orig, (nw, nh), interpolation=cv2.INTER_LINEAR)
|
| 151 |
rgb_sq = cv2.copyMakeBorder(rgb_sq, top, SQUARE_DIM-nh-top, left, SQUARE_DIM-nw-left, cv2.BORDER_CONSTANT, value=0)
|
| 152 |
|
|
|
|
| 153 |
predictor.set_image(rgb_sq)
|
| 154 |
image_emb = predictor._features["image_embed"][-1].unsqueeze(0)
|
| 155 |
hi = [lvl[-1].unsqueeze(0) for lvl in predictor._features["high_res_feats"]]
|
| 156 |
|
| 157 |
-
# PLM
|
| 158 |
with tempfile.NamedTemporaryFile(suffix=".jpg") as tmp:
|
| 159 |
image_pil.save(tmp.name)
|
|
|
|
| 160 |
sp, dp = plm_model([text_prompt], image_emb.shape[2], image_emb.shape[3], [tmp.name])
|
| 161 |
|
| 162 |
-
# SAM2
|
| 163 |
dec = sam_model.sam_mask_decoder
|
| 164 |
dev, dtype = next(dec.parameters()).device, next(dec.parameters()).dtype
|
| 165 |
|
|
@@ -172,19 +155,19 @@ def run_prediction(image_pil, text_prompt, threshold, stage_choice):
|
|
| 172 |
high_res_features=[h.to(dev, dtype) for h in hi]
|
| 173 |
)
|
| 174 |
|
| 175 |
-
#
|
| 176 |
logits = predictor._transforms.postprocess_masks(low, (SQUARE_DIM, SQUARE_DIM))
|
| 177 |
best_idx = scores.argmax().item()
|
|
|
|
| 178 |
logit_crop = logits[0, best_idx, top:top+nh, left:left+nw].unsqueeze(0).unsqueeze(0)
|
| 179 |
logit_full = F.interpolate(logit_crop, size=(H, W), mode="bilinear", align_corners=False)[0, 0]
|
| 180 |
|
| 181 |
prob = torch.sigmoid(logit_full).float().cpu().numpy()
|
| 182 |
|
| 183 |
-
#
|
| 184 |
heatmap_cv = cv2.applyColorMap((prob * 255).astype(np.uint8), cv2.COLORMAP_JET)
|
| 185 |
heatmap_rgb = cv2.cvtColor(heatmap_cv, cv2.COLOR_BGR2RGB)
|
| 186 |
|
| 187 |
-
# Initial Overlay
|
| 188 |
mask = (prob > threshold).astype(np.uint8) * 255
|
| 189 |
overlay = make_overlay(rgb_orig, mask, key=text_prompt)
|
| 190 |
|
|
@@ -192,55 +175,102 @@ def run_prediction(image_pil, text_prompt, threshold, stage_choice):
|
|
| 192 |
|
| 193 |
except Exception:
|
| 194 |
traceback.print_exc()
|
| 195 |
-
|
| 196 |
finally:
|
|
|
|
| 197 |
sam_model.to("cpu")
|
| 198 |
plm_model.to("cpu")
|
| 199 |
torch.cuda.empty_cache()
|
| 200 |
|
| 201 |
def update_threshold_ui(image_pil, text_prompt, threshold, cached_prob):
|
| 202 |
-
"""
|
| 203 |
if image_pil is None or cached_prob is None:
|
| 204 |
return None
|
| 205 |
rgb_orig = np.array(image_pil.convert("RGB"))
|
| 206 |
mask = (cached_prob > threshold).astype(np.uint8) * 255
|
| 207 |
return make_overlay(rgb_orig, mask, key=text_prompt)
|
| 208 |
|
| 209 |
-
# -----------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
|
| 211 |
-
with gr.Blocks(title="
|
| 212 |
prob_state = gr.State()
|
| 213 |
|
| 214 |
-
|
| 215 |
-
gr.Markdown("
|
| 216 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
with gr.Row():
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
|
| 222 |
-
with gr.
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
)
|
| 228 |
-
|
| 229 |
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 235 |
|
| 236 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
run_btn.click(
|
| 238 |
fn=run_prediction,
|
| 239 |
-
inputs=[input_image, text_prompt, threshold_slider
|
| 240 |
outputs=[out_overlay, out_heatmap, prob_state]
|
| 241 |
)
|
| 242 |
|
| 243 |
-
#
|
| 244 |
threshold_slider.change(
|
| 245 |
fn=update_threshold_ui,
|
| 246 |
inputs=[input_image, text_prompt, threshold_slider, prob_state],
|
|
@@ -248,4 +278,4 @@ with gr.Blocks(title="SAM2 + PLM Segmentation") as demo:
|
|
| 248 |
)
|
| 249 |
|
| 250 |
if __name__ == "__main__":
|
| 251 |
-
demo.launch()
|
|
|
|
| 3 |
import hashlib
|
| 4 |
import sys
|
| 5 |
import traceback
|
|
|
|
| 6 |
import tempfile
|
|
|
|
| 7 |
import cv2
|
| 8 |
import numpy as np
|
| 9 |
import torch
|
| 10 |
import torch.nn.functional as F
|
| 11 |
import gradio as gr
|
| 12 |
+
from PIL import Image, ImageFilter, ImageChops
|
| 13 |
from huggingface_hub import hf_hub_download
|
| 14 |
import spaces
|
| 15 |
|
| 16 |
# --- IMPORT YOUR CUSTOM MODULES ---
|
| 17 |
+
# Ensure these files are present in your file structure
|
| 18 |
from sam2.build_sam import build_sam2
|
| 19 |
from sam2.sam2_image_predictor import SAM2ImagePredictor
|
| 20 |
from plm_adapter_lora_with_image_input_only_text_positions import PLMLanguageAdapter
|
| 21 |
|
| 22 |
# ----------------- Configuration -----------------
|
| 23 |
+
logging.basicConfig(level=logging.INFO)
|
| 24 |
+
|
| 25 |
+
# Single Model Configuration
|
| 26 |
+
REPO_ID = "aadarsh99/ConvSeg-Stage2"
|
| 27 |
SAM2_CONFIG = "sam2_hiera_l.yaml"
|
| 28 |
BASE_CKPT_NAME = "sam2_hiera_large.pt"
|
| 29 |
+
FINE_TUNED_SAM = "fine_tuned_sam2_batched_18000.torch"
|
| 30 |
+
FINE_TUNED_PLM = "fine_tuned_sam2_batched_plm_18000.torch"
|
| 31 |
|
| 32 |
SQUARE_DIM = 1024
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
+
# Global Cache
|
| 35 |
+
MODEL_CACHE = {"sam": None, "plm": None}
|
| 36 |
|
| 37 |
# ----------------- Helper Functions -----------------
|
| 38 |
def download_if_needed(repo_id, filename):
|
|
|
|
| 44 |
|
| 45 |
def stable_color(key: str):
|
| 46 |
h = int(hashlib.sha256(str(key).encode("utf-8")).hexdigest(), 16)
|
| 47 |
+
# Bright, distinct colors for overlays
|
| 48 |
EDGE_COLORS_HEX = ["#3A86FF", "#FF006E", "#43AA8B", "#F3722C", "#8338EC", "#90BE6D"]
|
| 49 |
colors = [tuple(int(c.lstrip("#")[i:i+2], 16) for i in (0, 2, 4)) for c in EDGE_COLORS_HEX]
|
| 50 |
return colors[h % len(colors)]
|
| 51 |
|
| 52 |
def make_overlay(rgb: np.ndarray, mask: np.ndarray, key: str = "mask") -> Image.Image:
|
|
|
|
| 53 |
base = Image.fromarray(rgb.astype(np.uint8)).convert("RGBA")
|
| 54 |
mask_bool = mask > 0
|
| 55 |
color = stable_color(key)
|
| 56 |
|
| 57 |
+
# Fill layer (Semi-transparent)
|
| 58 |
fill_layer = Image.new("RGBA", base.size, color + (0,))
|
| 59 |
fill_alpha = Image.fromarray((mask_bool.astype(np.uint8) * 140), "L")
|
| 60 |
fill_layer.putalpha(fill_alpha)
|
| 61 |
|
| 62 |
+
# Stroke/Edge layer
|
| 63 |
m = Image.fromarray((mask_bool.astype(np.uint8) * 255), "L")
|
| 64 |
edges = ImageChops.difference(m.filter(ImageFilter.MaxFilter(3)), m.filter(ImageFilter.MinFilter(3)))
|
| 65 |
stroke_layer = Image.new("RGBA", base.size, color + (255,))
|
| 66 |
stroke_layer.putalpha(edges)
|
| 67 |
|
| 68 |
+
# Composite
|
| 69 |
out = Image.alpha_composite(base, fill_layer)
|
| 70 |
out = Image.alpha_composite(out, stroke_layer)
|
|
|
|
| 71 |
return out.convert("RGB")
|
| 72 |
|
| 73 |
+
def ensure_models_loaded():
|
| 74 |
global MODEL_CACHE
|
| 75 |
+
if MODEL_CACHE["sam"] is not None:
|
| 76 |
return
|
| 77 |
|
| 78 |
+
logging.info(f"Loading models from {REPO_ID}...")
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
+
# 1. Load SAM2 Base & Fine-tuned weights
|
| 81 |
+
base_path = download_if_needed(REPO_ID, BASE_CKPT_NAME)
|
|
|
|
| 82 |
model = build_sam2(SAM2_CONFIG, base_path, device="cpu")
|
| 83 |
|
| 84 |
+
sam_ckpt_path = download_if_needed(REPO_ID, FINE_TUNED_SAM)
|
| 85 |
+
sd = torch.load(sam_ckpt_path, map_location="cpu")
|
|
|
|
| 86 |
model.load_state_dict(sd.get("model", sd), strict=True)
|
| 87 |
|
| 88 |
+
# 2. Load PLM Adapter
|
| 89 |
+
plm_path = download_if_needed(REPO_ID, FINE_TUNED_PLM)
|
| 90 |
plm = PLMLanguageAdapter(
|
| 91 |
model_name="Qwen/Qwen2.5-VL-3B-Instruct",
|
| 92 |
transformer_dim=model.sam_mask_decoder.transformer_dim,
|
|
|
|
| 98 |
plm.load_state_dict(plm_sd["plm"], strict=True)
|
| 99 |
plm.eval()
|
| 100 |
|
| 101 |
+
MODEL_CACHE["sam"] = model
|
| 102 |
+
MODEL_CACHE["plm"] = plm
|
| 103 |
+
logging.info("Models loaded successfully.")
|
| 104 |
|
| 105 |
# ----------------- GPU Inference -----------------
|
| 106 |
|
| 107 |
@spaces.GPU(duration=120)
|
| 108 |
+
def run_prediction(image_pil, text_prompt, threshold=0.5):
|
| 109 |
if image_pil is None or not text_prompt:
|
| 110 |
return None, None, None
|
| 111 |
|
| 112 |
+
ensure_models_loaded()
|
| 113 |
+
sam_model = MODEL_CACHE["sam"]
|
| 114 |
+
plm_model = MODEL_CACHE["plm"]
|
| 115 |
|
| 116 |
+
# Move to GPU
|
| 117 |
sam_model.to("cuda")
|
| 118 |
plm_model.to("cuda")
|
| 119 |
|
|
|
|
| 123 |
rgb_orig = np.array(image_pil.convert("RGB"))
|
| 124 |
H, W = rgb_orig.shape[:2]
|
| 125 |
|
| 126 |
+
# Smart Resizing & Padding
|
| 127 |
scale = SQUARE_DIM / max(H, W)
|
| 128 |
nw, nh = int(W * scale), int(H * scale)
|
| 129 |
top, left = (SQUARE_DIM - nh) // 2, (SQUARE_DIM - nw) // 2
|
| 130 |
|
|
|
|
| 131 |
rgb_sq = cv2.resize(rgb_orig, (nw, nh), interpolation=cv2.INTER_LINEAR)
|
| 132 |
rgb_sq = cv2.copyMakeBorder(rgb_sq, top, SQUARE_DIM-nh-top, left, SQUARE_DIM-nw-left, cv2.BORDER_CONSTANT, value=0)
|
| 133 |
|
| 134 |
+
# Image Encoder
|
| 135 |
predictor.set_image(rgb_sq)
|
| 136 |
image_emb = predictor._features["image_embed"][-1].unsqueeze(0)
|
| 137 |
hi = [lvl[-1].unsqueeze(0) for lvl in predictor._features["high_res_feats"]]
|
| 138 |
|
| 139 |
+
# PLM Adapter (Text + Image processing)
|
| 140 |
with tempfile.NamedTemporaryFile(suffix=".jpg") as tmp:
|
| 141 |
image_pil.save(tmp.name)
|
| 142 |
+
# Qwen/PLM processes the text prompt here
|
| 143 |
sp, dp = plm_model([text_prompt], image_emb.shape[2], image_emb.shape[3], [tmp.name])
|
| 144 |
|
| 145 |
+
# SAM2 Mask Decoder
|
| 146 |
dec = sam_model.sam_mask_decoder
|
| 147 |
dev, dtype = next(dec.parameters()).device, next(dec.parameters()).dtype
|
| 148 |
|
|
|
|
| 155 |
high_res_features=[h.to(dev, dtype) for h in hi]
|
| 156 |
)
|
| 157 |
|
| 158 |
+
# Post-processing
|
| 159 |
logits = predictor._transforms.postprocess_masks(low, (SQUARE_DIM, SQUARE_DIM))
|
| 160 |
best_idx = scores.argmax().item()
|
| 161 |
+
|
| 162 |
logit_crop = logits[0, best_idx, top:top+nh, left:left+nw].unsqueeze(0).unsqueeze(0)
|
| 163 |
logit_full = F.interpolate(logit_crop, size=(H, W), mode="bilinear", align_corners=False)[0, 0]
|
| 164 |
|
| 165 |
prob = torch.sigmoid(logit_full).float().cpu().numpy()
|
| 166 |
|
| 167 |
+
# Visuals
|
| 168 |
heatmap_cv = cv2.applyColorMap((prob * 255).astype(np.uint8), cv2.COLORMAP_JET)
|
| 169 |
heatmap_rgb = cv2.cvtColor(heatmap_cv, cv2.COLOR_BGR2RGB)
|
| 170 |
|
|
|
|
| 171 |
mask = (prob > threshold).astype(np.uint8) * 255
|
| 172 |
overlay = make_overlay(rgb_orig, mask, key=text_prompt)
|
| 173 |
|
|
|
|
| 175 |
|
| 176 |
except Exception:
|
| 177 |
traceback.print_exc()
|
| 178 |
+
raise gr.Error("Inference failed. Please check logs.")
|
| 179 |
finally:
|
| 180 |
+
# Cleanup memory
|
| 181 |
sam_model.to("cpu")
|
| 182 |
plm_model.to("cpu")
|
| 183 |
torch.cuda.empty_cache()
|
| 184 |
|
| 185 |
def update_threshold_ui(image_pil, text_prompt, threshold, cached_prob):
|
| 186 |
+
"""Real-time update using CPU only (no GPU quota usage)."""
|
| 187 |
if image_pil is None or cached_prob is None:
|
| 188 |
return None
|
| 189 |
rgb_orig = np.array(image_pil.convert("RGB"))
|
| 190 |
mask = (cached_prob > threshold).astype(np.uint8) * 255
|
| 191 |
return make_overlay(rgb_orig, mask, key=text_prompt)
|
| 192 |
|
| 193 |
+
# ----------------- UI Styling & Layout -----------------
|
| 194 |
+
|
| 195 |
+
custom_css = """
|
| 196 |
+
h1 {
|
| 197 |
+
text-align: center;
|
| 198 |
+
display: block;
|
| 199 |
+
}
|
| 200 |
+
.subtitle {
|
| 201 |
+
text-align: center;
|
| 202 |
+
font-size: 1.1em;
|
| 203 |
+
margin-bottom: 20px;
|
| 204 |
+
}
|
| 205 |
+
"""
|
| 206 |
+
|
| 207 |
+
theme = gr.themes.Soft(
|
| 208 |
+
primary_hue="blue",
|
| 209 |
+
neutral_hue="slate",
|
| 210 |
+
).set(
|
| 211 |
+
button_primary_background_fill="*primary_600",
|
| 212 |
+
button_primary_background_fill_hover="*primary_700",
|
| 213 |
+
)
|
| 214 |
|
| 215 |
+
with gr.Blocks(theme=theme, css=custom_css, title="ConvSeg-Net Demo") as demo:
|
| 216 |
prob_state = gr.State()
|
| 217 |
|
| 218 |
+
# Header
|
| 219 |
+
gr.Markdown("# 🧩 Conversational Image Segmentation")
|
| 220 |
+
gr.Markdown(
|
| 221 |
+
"<div class='subtitle'>Grounding abstract concepts and physics-based reasoning into pixel-accurate masks.<br>"
|
| 222 |
+
"Powered by <b>SAM2 + Qwen2.5-VL</b></div>"
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
with gr.Row():
|
| 226 |
+
# --- Left Column: Inputs ---
|
| 227 |
+
with gr.Column(scale=1):
|
| 228 |
+
input_image = gr.Image(type="pil", label="Input Image", height=400)
|
| 229 |
|
| 230 |
+
with gr.Group():
|
| 231 |
+
text_prompt = gr.Textbox(
|
| 232 |
+
label="Conversational Prompt",
|
| 233 |
+
placeholder="e.g., Segment the object that is prone to rolling...",
|
| 234 |
+
lines=2
|
| 235 |
)
|
| 236 |
+
gr.Markdown("💡 **Tip:** The model works best when prompts start with **'Segment the...'**")
|
| 237 |
|
| 238 |
+
with gr.Accordion("⚙️ Advanced Options", open=False):
|
| 239 |
+
threshold_slider = gr.Slider(
|
| 240 |
+
0.0, 1.0, value=0.5, step=0.01,
|
| 241 |
+
label="Mask Confidence Threshold",
|
| 242 |
+
info="Adjust after running to refine the mask edges."
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
run_btn = gr.Button("🚀 Run Segmentation", variant="primary", size="lg")
|
| 246 |
+
|
| 247 |
+
# --- Right Column: Outputs ---
|
| 248 |
+
with gr.Column(scale=1):
|
| 249 |
+
out_overlay = gr.Image(label="Segmentation Result", type="pil")
|
| 250 |
+
out_heatmap = gr.Image(label="Confidence Heatmap", type="pil")
|
| 251 |
|
| 252 |
+
# --- Examples Section ---
|
| 253 |
+
gr.Markdown("### 📝 Try Examples")
|
| 254 |
+
gr.Examples(
|
| 255 |
+
examples=[
|
| 256 |
+
["./examples/bike.jpg", "Segment the mechanism requiring physical pedaling force"],
|
| 257 |
+
["./examples/luggage.jpg", "Segment the suitcase that is easiest to remove without disturbing others"],
|
| 258 |
+
["./examples/kitchen.jpg", "Segment the surface suitable for hot cookware"],
|
| 259 |
+
],
|
| 260 |
+
inputs=[input_image, text_prompt],
|
| 261 |
+
# cache_examples=True # Uncomment if you want to pre-compute these on startup
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
# --- Event Handling ---
|
| 265 |
+
|
| 266 |
+
# 1. Run Inference (GPU)
|
| 267 |
run_btn.click(
|
| 268 |
fn=run_prediction,
|
| 269 |
+
inputs=[input_image, text_prompt, threshold_slider],
|
| 270 |
outputs=[out_overlay, out_heatmap, prob_state]
|
| 271 |
)
|
| 272 |
|
| 273 |
+
# 2. Update Threshold (CPU - Instant)
|
| 274 |
threshold_slider.change(
|
| 275 |
fn=update_threshold_ui,
|
| 276 |
inputs=[input_image, text_prompt, threshold_slider, prob_state],
|
|
|
|
| 278 |
)
|
| 279 |
|
| 280 |
if __name__ == "__main__":
|
| 281 |
+
demo.queue().launch()
|