Spaces:
Build error
Build error
File size: 5,791 Bytes
6715b3e | 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 | from typing import List, Union, Dict
import os
from PIL import Image
from transformers import CLIPProcessor, CLIPModel
import torch
# Load the CLIP model and processor once when the module is imported
# Using a common pre-trained model
MODEL_NAME = "openai/clip-vit-base-patch32"
# Revert to use_fast=False to avoid '_valid_processor_keys' error with padding/truncation
processor = CLIPProcessor.from_pretrained(MODEL_NAME, use_fast=False)
model = CLIPModel.from_pretrained(MODEL_NAME)
# Determine device
device = "cuda" if torch.cuda.is_available() else ("mps" if torch.backends.mps.is_available() else "cpu")
model.to(device)
def classify_entities(image_paths_or_crops: List[Union[str, Image.Image]],
candidate_labels: List[str],
batch_size: int = 8) -> List[List[Dict[str, Union[str, float]]]] :
"""Classifies objects in cropped regions or image paths against candidate labels using CLIP.
Args:
image_paths_or_crops: A list of either file paths to images or PIL Image objects.
candidate_labels: A list of strings representing the categories to classify against
(e.g., ['a photo of a cat', 'a photo of a dog']).
batch_size: Number of images to process in a single batch.
Returns:
A list of lists of dictionaries. Each inner list corresponds to an input image/crop,
and contains dictionaries with 'label' and 'score' for each candidate label.
Example: [[{'label': 'cat', 'score': 0.9}, {'label': 'dog', 'score': 0.1}], ...]
"""
if not image_paths_or_crops:
return []
if not candidate_labels:
raise ValueError("Candidate labels must be provided for classification.")
all_classifications = []
for i in range(0, len(image_paths_or_crops), batch_size):
batch_items = image_paths_or_crops[i:i+batch_size]
images_to_process = []
for item in batch_items:
if isinstance(item, str):
if not os.path.exists(item):
print(f"Warning: Image path {item} not found. Skipping.")
# Add a placeholder for skipped items to maintain result structure if needed
# For now, just skipping it means the output list will be shorter
continue
try:
img = Image.open(item).convert("RGB")
images_to_process.append(img)
except Exception as e:
print(f"Error opening or processing image {item}: {e}. Skipping.")
continue
elif isinstance(item, Image.Image):
images_to_process.append(item.convert("RGB"))
else:
print(f"Warning: Invalid item type {type(item)}. Skipping.")
continue
if not images_to_process:
continue
try:
# Re-add padding and truncation as they are generally needed for text batching
inputs = processor(text=candidate_labels, images=images_to_process,
return_tensors="pt", padding=True, truncation=True).to(device)
with torch.no_grad():
outputs = model(**inputs)
logits_per_image = outputs.logits_per_image # this is the image-text similarity score
probs = logits_per_image.softmax(dim=1) # we can take the softmax to get probabilities
batch_results = []
for j in range(len(images_to_process)):
image_scores = []
for k, label in enumerate(candidate_labels):
image_scores.append({"label": label, "score": float(probs[j, k].item())})
# Sort by score descending
image_scores.sort(key=lambda x: x['score'], reverse=True)
batch_results.append(image_scores)
all_classifications.extend(batch_results)
except Exception as e:
print(f"Error during CLIP processing batch starting at index {i}: {e}")
# Add empty results for this batch to maintain structure, or handle error as needed
for _ in images_to_process: # Ensure one result per attempted image in batch
all_classifications.append([{"label": "error", "score": 0.0}])
item_count = len(image_paths_or_crops)
print(f"Classified {len(all_classifications)} items (expected {item_count}) against {len(candidate_labels)} labels.")
return all_classifications
# Example usage (for testing):
# if __name__ == '__main__':
# # Create dummy image files for testing
# import numpy as np
# os.makedirs("temp_test_images", exist_ok=True)
# dummy_image_path1 = "temp_test_images/dummy_clip_1.png"
# dummy_image_path2 = "temp_test_images/dummy_clip_2.png"
# cv2.imwrite(dummy_image_path1, np.random.randint(0, 255, size=(100, 100, 3), dtype=np.uint8))
# pil_img = Image.fromarray(np.random.randint(0, 255, size=(120, 120, 3), dtype=np.uint8))
# labels_to_test = ["a photo of a dog", "a drawing of a cat", "a landscape scene", "a red car"]
# classifications = classify_entities(
# [dummy_image_path1, pil_img, "non_existent_image.jpg"],
# candidate_labels=labels_to_test
# )
# for i, result_set in enumerate(classifications):
# print(f"Results for image {i+1}:")
# for res in result_set:
# print(f" Label: {res['label']}, Score: {res['score']:.4f}")
# if os.path.exists(dummy_image_path1): os.remove(dummy_image_path1)
# if os.path.exists(dummy_image_path2): os.remove(dummy_image_path2) # was never created, but good practice
# if os.path.exists("temp_test_images"): os.rmdir("temp_test_images")
|