Spaces:
Sleeping
Sleeping
File size: 19,982 Bytes
dfdcd97 a3ee867 23fa119 b066832 fd55cab b066832 eefe5b4 b066832 eba2946 b066832 23fa119 b066832 23fa119 b066832 23fa119 b066832 23fa119 b066832 eba2946 b066832 eba2946 23fa119 eba2946 b066832 eba2946 b066832 eba2946 23fa119 b066832 23fa119 eba2946 23fa119 eba2946 23fa119 b066832 23fa119 b066832 eba2946 b066832 eba2946 23fa119 c95f3e0 3cd1243 b066832 6facde6 23fa119 b066832 23fa119 b066832 23fa119 6facde6 23fa119 6facde6 23fa119 6facde6 b066832 23fa119 b066832 23fa119 b066832 eba2946 6facde6 b066832 eba2946 6facde6 23fa119 b066832 23fa119 eba2946 23fa119 eba2946 23fa119 b066832 23fa119 e0d4d2f 23fa119 6facde6 3d6a9c7 b066832 72f4c5c 23fa119 b066832 23fa119 b066832 6facde6 23fa119 b066832 6facde6 23fa119 b066832 23fa119 eba2946 23fa119 6facde6 23fa119 6facde6 23fa119 6facde6 23fa119 6facde6 eefe5b4 23fa119 eba2946 23fa119 b066832 6facde6 e0d4d2f b066832 23fa119 b066832 23fa119 b066832 23fa119 b066832 23fa119 b066832 eba2946 b066832 eba2946 b066832 23fa119 b066832 23fa119 eefe5b4 6facde6 23fa119 b066832 23fa119 b066832 23fa119 b066832 23fa119 b066832 23fa119 b066832 23fa119 eba2946 b066832 6facde6 23fa119 b066832 eba2946 23fa119 eba2946 b066832 23fa119 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 |
import gradio as gr
import torch
from transformers import AutoProcessor, AutoModel # Keep CLIP for potential future use or if FastSAM's text prompt isn't enough
from PIL import Image, ImageDraw, ImageFont
import numpy as np
import random
import os
import wget # To download weights
import traceback # For detailed error printing
# --- Configuration & Model Loading ---
# Device Selection
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
# Force CPU if CUDA fails or isn't desired (sometimes needed on Spaces free tier)
# DEVICE = "cpu"
print(f"Using device: {DEVICE}")
# --- CLIP Setup (Kept in case needed, but FastSAM's method is primary now) ---
CLIP_MODEL_ID = "openai/clip-vit-base-patch32"
clip_processor = None
clip_model = None
def load_clip_model():
global clip_processor, clip_model
if clip_processor is None:
try:
print(f"Loading CLIP processor: {CLIP_MODEL_ID}...")
clip_processor = AutoProcessor.from_pretrained(CLIP_MODEL_ID)
print("CLIP processor loaded.")
except Exception as e:
print(f"Error loading CLIP processor: {e}")
return False # Indicate failure
if clip_model is None:
try:
print(f"Loading CLIP model: {CLIP_MODEL_ID}...")
clip_model = AutoModel.from_pretrained(CLIP_MODEL_ID).to(DEVICE)
print(f"CLIP model loaded to {DEVICE}.")
except Exception as e:
print(f"Error loading CLIP model: {e}")
return False # Indicate failure
return True # Indicate success
# --- FastSAM Setup ---
FASTSAM_CHECKPOINT = "FastSAM-s.pt"
FASTSAM_CHECKPOINT_URL = f"https://huggingface.co/CASIA-IVA-Lab/FastSAM-s/resolve/main/{FASTSAM_CHECKPOINT}"
fastsam_model = None
fastsam_lib_imported = False # Flag to check if import worked
def check_and_import_fastsam():
global fastsam_lib_imported
if not fastsam_lib_imported:
try:
from fastsam import FastSAM, FastSAMPrompt
globals()['FastSAM'] = FastSAM # Make classes available globally
globals()['FastSAMPrompt'] = FastSAMPrompt
fastsam_lib_imported = True
print("fastsam library imported successfully.")
except ImportError:
print("Error: 'fastsam' library not found or import failed.")
print("Please ensure 'fastsam' is installed correctly (pip install fastsam).")
fastsam_lib_imported = False
except Exception as e:
print(f"An unexpected error occurred during fastsam import: {e}")
traceback.print_exc()
fastsam_lib_imported = False
return fastsam_lib_imported
def download_fastsam_weights():
if not os.path.exists(FASTSAM_CHECKPOINT):
print(f"Downloading FastSAM weights: {FASTSAM_CHECKPOINT} from {FASTSAM_CHECKPOINT_URL}...")
try:
wget.download(FASTSAM_CHECKPOINT_URL, FASTSAM_CHECKPOINT)
print("FastSAM weights downloaded.")
except Exception as e:
print(f"Error downloading FastSAM weights: {e}")
print("Please ensure the URL is correct and reachable, or manually place the weights file.")
if os.path.exists(FASTSAM_CHECKPOINT):
try: os.remove(FASTSAM_CHECKPOINT)
except OSError: pass
return False
return os.path.exists(FASTSAM_CHECKPOINT)
def load_fastsam_model():
global fastsam_model
if fastsam_model is None:
if not check_and_import_fastsam():
print("Cannot load FastSAM model because the library couldn't be imported.")
return False # Indicate failure
if download_fastsam_weights():
try:
print(f"Loading FastSAM model: {FASTSAM_CHECKPOINT}...")
fastsam_model = FastSAM(FASTSAM_CHECKPOINT)
# The FastSAM model itself doesn't need explicit .to(DEVICE)
# It seems to handle device selection internally or via the prompt process
print(f"FastSAM model loaded.")
return True # Indicate success
except Exception as e:
print(f"Error loading FastSAM model: {e}")
traceback.print_exc()
else:
print("FastSAM weights not found or download failed. Cannot load model.")
return fastsam_model is not None # Return True if already loaded or loaded successfully
# --- Processing Functions ---
# (Keep run_clip_zero_shot and run_fastsam_segmentation as they were for the other tabs)
# CLIP Zero-Shot Classification Function
def run_clip_zero_shot(image: Image.Image, text_labels: str):
# Load CLIP if needed
if clip_model is None or clip_processor is None:
if not load_clip_model():
return "Error: CLIP Model could not be loaded. Check logs.", None
if image is None: return "Please upload an image.", None
if not text_labels: return {}, image # Return empty dict, show image
labels = [label.strip() for label in text_labels.split(',') if label.strip()]
if not labels: return {}, image
print(f"Running CLIP zero-shot classification with labels: {labels}")
try:
if image.mode != "RGB": image = image.convert("RGB")
inputs = clip_processor(text=labels, images=image, return_tensors="pt", padding=True).to(DEVICE)
with torch.no_grad():
outputs = clip_model(**inputs)
probs = outputs.logits_per_image.softmax(dim=1)
print("CLIP processing complete.")
confidences = {labels[i]: float(probs[0, i].item()) for i in range(len(labels))}
return confidences, image
except Exception as e:
print(f"Error during CLIP processing: {e}")
traceback.print_exc()
return f"An error occurred during CLIP: {e}", image
# FastSAM Everything Segmentation Function (for the second tab)
def run_fastsam_segmentation(image_pil: Image.Image, conf_threshold: float = 0.4, iou_threshold: float = 0.9):
if not load_fastsam_model():
return "Error: FastSAM Model not loaded. Check logs."
if not fastsam_lib_imported:
return "Error: FastSAM library not available."
if image_pil is None: return "Please upload an image."
print("Running FastSAM 'segment everything'...")
try:
if image_pil.mode != "RGB": image_pil = image_pil.convert("RGB")
image_np_rgb = np.array(image_pil)
everything_results = fastsam_model(
image_np_rgb, device=DEVICE, retina_masks=True, imgsz=640,
conf=conf_threshold, iou=iou_threshold,
)
prompt_process = FastSAMPrompt(image_np_rgb, everything_results, device=DEVICE)
ann = prompt_process.everything_prompt()
print(f"FastSAM 'everything' found {len(ann[0]['masks']) if ann and ann[0] and 'masks' in ann[0] else 0} masks.")
# Plotting
output_image = image_pil.copy()
if ann and ann[0] is not None and 'masks' in ann[0] and len(ann[0]['masks']) > 0:
masks = ann[0]['masks'].cpu().numpy()
overlay = Image.new('RGBA', output_image.size, (0, 0, 0, 0))
draw = ImageDraw.Draw(overlay)
for mask in masks:
color = (random.randint(50, 255), random.randint(50, 255), random.randint(50, 255), 128)
mask_image = Image.fromarray((mask * 255).astype(np.uint8), mode='L')
draw.bitmap((0, 0), mask_image, fill=color)
output_image = Image.alpha_composite(output_image.convert('RGBA'), overlay).convert('RGB')
print("FastSAM 'everything' processing complete.")
return output_image
except Exception as e:
print(f"Error during FastSAM 'everything' processing: {e}")
traceback.print_exc()
return f"An error occurred during FastSAM 'everything': {e}"
# --- NEW: Text-Prompted Segmentation Function ---
def run_text_prompted_segmentation(image_pil: Image.Image, text_prompts: str, conf_threshold: float = 0.4, iou_threshold: float = 0.9):
"""Segments objects based on text prompts."""
if not load_fastsam_model():
return "Error: FastSAM Model not loaded. Check logs.", "No prompts provided."
if not fastsam_lib_imported:
return "Error: FastSAM library not available.", "FastSAM library error."
if image_pil is None:
return "Please upload an image.", "No image provided."
if not text_prompts:
return image_pil, "Please enter text prompts (e.g., 'person, dog')." # Return original image and message
prompts = [p.strip() for p in text_prompts.split(',') if p.strip()]
if not prompts:
return image_pil, "No valid text prompts entered."
print(f"Running FastSAM text-prompted segmentation for: {prompts}")
try:
if image_pil.mode != "RGB":
image_pil = image_pil.convert("RGB")
image_np_rgb = np.array(image_pil)
# 1. Run FastSAM once to get all potential results
# NOTE: We might optimize later, but this is the standard way FastSAMPrompt works.
everything_results = fastsam_model(
image_np_rgb, device=DEVICE, retina_masks=True, imgsz=640,
conf=conf_threshold, iou=iou_threshold, verbose=False # Less console spam
)
# 2. Create the prompt processor
prompt_process = FastSAMPrompt(image_np_rgb, everything_results, device=DEVICE)
# 3. Use text_prompt for each prompt and collect masks
all_matching_masks = []
found_prompts = []
for text in prompts:
print(f" Processing prompt: '{text}'")
# Ann is a list of dictionaries, one per image. We have one image.
# Each dict can have 'masks', 'bboxes', 'points'.
# text_prompt filters 'everything_results' based on CLIP-like similarity.
# It might return multiple masks if multiple instances match the text.
ann = prompt_process.text_prompt(text=text)
if ann and ann[0] is not None and 'masks' in ann[0] and len(ann[0]['masks']) > 0:
num_found = len(ann[0]['masks'])
print(f" Found {num_found} mask(s) matching '{text}'.")
found_prompts.append(f"{text} ({num_found})")
masks = ann[0]['masks'].cpu().numpy() # Get masks as numpy array (N, H, W)
all_matching_masks.extend(masks) # Add the numpy arrays to the list
else:
print(f" No masks found matching '{text}'.")
found_prompts.append(f"{text} (0)")
# 4. Plot the collected masks
output_image = image_pil.copy()
status_message = f"Found segments for: {', '.join(found_prompts)}" if found_prompts else "No matching segments found for any prompt."
if not all_matching_masks:
print("No matching masks found for any prompt.")
return output_image, status_message # Return original image if nothing matched
# Convert list of (H, W) masks to a single (N, H, W) array for consistent processing
masks_np = np.stack(all_matching_masks, axis=0) # Shape (TotalMasks, H, W)
overlay = Image.new('RGBA', output_image.size, (0, 0, 0, 0))
draw = ImageDraw.Draw(overlay)
for i in range(masks_np.shape[0]):
mask = masks_np[i] # Shape (H, W), boolean
color = (random.randint(50, 255), random.randint(50, 255), random.randint(50, 255), 150) # RGBA with slightly more alpha
mask_image = Image.fromarray((mask * 255).astype(np.uint8), mode='L')
draw.bitmap((0, 0), mask_image, fill=color)
output_image = Image.alpha_composite(output_image.convert('RGBA'), overlay).convert('RGB')
print("FastSAM text-prompted processing complete.")
return output_image, status_message
except Exception as e:
print(f"Error during FastSAM text-prompted processing: {e}")
traceback.print_exc()
return f"An error occurred: {e}", "Error during processing."
# --- Gradio Interface ---
print("Attempting to preload models...")
# load_clip_model() # Load CLIP lazily if needed
load_fastsam_model() # Load FastSAM eagerly
print("Preloading finished (or attempted).")
with gr.Blocks(theme=gr.themes.Soft()) as demo:
gr.Markdown("# CLIP & FastSAM Demo")
gr.Markdown("Explore Zero-Shot Classification, 'Segment Everything', and Text-Prompted Segmentation.")
with gr.Tabs():
# --- CLIP Tab (No changes) ---
with gr.TabItem("CLIP Zero-Shot Classification"):
# ... (keep the existing layout and logic for CLIP) ...
gr.Markdown("Upload an image and provide comma-separated candidate labels (e.g., 'cat, dog, car'). CLIP will predict the probability of the image matching each label.")
with gr.Row():
with gr.Column(scale=1):
clip_input_image = gr.Image(type="pil", label="Input Image")
clip_text_labels = gr.Textbox(label="Comma-Separated Labels", placeholder="e.g., astronaut, moon, dog playing fetch")
clip_button = gr.Button("Run CLIP Classification", variant="primary")
with gr.Column(scale=1):
clip_output_label = gr.Label(label="Classification Probabilities")
clip_output_image_display = gr.Image(type="pil", label="Input Image Preview")
clip_button.click(
run_clip_zero_shot,
inputs=[clip_input_image, clip_text_labels],
outputs=[clip_output_label, clip_output_image_display]
)
gr.Examples(
examples=[
["examples/astronaut.jpg", "astronaut, moon, rover, mountain"],
["examples/dog_bike.jpg", "dog, bicycle, person, park, grass"],
["examples/clip_logo.png", "logo, text, graphics, abstract art"],
],
inputs=[clip_input_image, clip_text_labels],
outputs=[clip_output_label, clip_output_image_display], fn=run_clip_zero_shot, cache_examples=False,
)
# --- FastSAM Everything Tab (No changes) ---
with gr.TabItem("FastSAM Segment Everything"):
# ... (keep the existing layout and logic for segment everything) ...
gr.Markdown("Upload an image. FastSAM will attempt to segment all objects/regions in the image.")
with gr.Row():
with gr.Column(scale=1):
fastsam_input_image_all = gr.Image(type="pil", label="Input Image", elem_id="fastsam_input_all") # Unique elem_id if needed
with gr.Row():
fastsam_conf_all = gr.Slider(minimum=0.1, maximum=1.0, value=0.4, step=0.05, label="Confidence Threshold")
fastsam_iou_all = gr.Slider(minimum=0.1, maximum=1.0, value=0.9, step=0.05, label="IoU Threshold")
fastsam_button_all = gr.Button("Run FastSAM Segmentation", variant="primary")
with gr.Column(scale=1):
fastsam_output_image_all = gr.Image(type="pil", label="Segmented Image", elem_id="fastsam_output_all")
fastsam_button_all.click(
run_fastsam_segmentation,
inputs=[fastsam_input_image_all, fastsam_conf_all, fastsam_iou_all],
outputs=[fastsam_output_image_all]
)
gr.Examples(
examples=[
["examples/dogs.jpg", 0.4, 0.9],
["examples/fruits.jpg", 0.5, 0.8],
["examples/lion.jpg", 0.45, 0.9],
],
inputs=[fastsam_input_image_all, fastsam_conf_all, fastsam_iou_all],
outputs=[fastsam_output_image_all], fn=run_fastsam_segmentation, cache_examples=False,
)
# --- NEW: Text-Prompted Segmentation Tab ---
with gr.TabItem("Text-Prompted Segmentation"):
gr.Markdown("Upload an image and provide comma-separated text prompts (e.g., 'person, dog, backpack'). FastSAM + CLIP (internally) will segment only the objects matching the text.")
with gr.Row():
with gr.Column(scale=1):
prompt_input_image = gr.Image(type="pil", label="Input Image")
prompt_text_input = gr.Textbox(label="Comma-Separated Text Prompts", placeholder="e.g., glasses, watch, t-shirt")
with gr.Row(): # Reuse confidence/IoU sliders if desired
prompt_conf = gr.Slider(minimum=0.1, maximum=1.0, value=0.4, step=0.05, label="Confidence Threshold")
prompt_iou = gr.Slider(minimum=0.1, maximum=1.0, value=0.9, step=0.05, label="IoU Threshold")
prompt_button = gr.Button("Segment by Text", variant="primary")
with gr.Column(scale=1):
prompt_output_image = gr.Image(type="pil", label="Text-Prompted Segmentation")
prompt_status_message = gr.Textbox(label="Status", interactive=False) # To show which prompts matched
prompt_button.click(
run_text_prompted_segmentation,
inputs=[prompt_input_image, prompt_text_input, prompt_conf, prompt_iou],
outputs=[prompt_output_image, prompt_status_message] # Map to image and status box
)
gr.Examples(
examples=[
["examples/dog_bike.jpg", "person, bicycle", 0.4, 0.9],
["examples/astronaut.jpg", "person, helmet", 0.35, 0.9],
["examples/dogs.jpg", "dog", 0.4, 0.9], # Should find multiple dogs
["examples/fruits.jpg", "banana, apple", 0.5, 0.8],
["examples/teacher.jpg", "person, glasses, blackboard", 0.4, 0.9], # Download this image or use another one with glasses/blackboard
],
inputs=[prompt_input_image, prompt_text_input, prompt_conf, prompt_iou],
outputs=[prompt_output_image, prompt_status_message],
fn=run_text_prompted_segmentation,
cache_examples=False,
)
# Ensure example images exist or are downloaded
# (Keep the existing example download logic, maybe add teacher.jpg if used in examples)
if not os.path.exists("examples"):
os.makedirs("examples")
print("Created 'examples' directory. Attempting to download sample images...")
example_files = {
"astronaut.jpg": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d1/Astronaut_-_St._Jean_Bay.jpg/640px-Astronaut_-_St._Jean_Bay.jpg",
"dog_bike.jpg": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio/outputs_multimodal.jpg",
"clip_logo.png": "https://raw.githubusercontent.com/openai/CLIP/main/CLIP.png",
"dogs.jpg": "https://raw.githubusercontent.com/ultralytics/assets/main/im/image8.jpg",
"fruits.jpg": "https://raw.githubusercontent.com/ultralytics/assets/main/im/image9.jpg",
"lion.jpg": "https://huggingface.co/spaces/gradio/image-segmentation/resolve/main/images/lion.jpg",
"teacher.jpg": "https://images.pexels.com/photos/848117/pexels-photo-848117.jpeg?auto=compress&cs=tinysrgb&w=600" # Example with glasses/board
}
for filename, url in example_files.items():
filepath = os.path.join("examples", filename)
if not os.path.exists(filepath):
try:
print(f"Downloading {filename}...")
wget.download(url, filepath)
except Exception as e:
print(f"Could not download {filename} from {url}: {e}")
print("Example image download attempt finished.")
# Launch the Gradio app
if __name__ == "__main__":
demo.launch(debug=True) # debug=True is helpful locally |