Spaces:
Build error
Build error
Download tools/classify_entities.py from arashx07/Final_Assignment_Template: direct link, hf CLI and curl.
- Browser
- Download file 5.79 kB
-
https://huggingface.co/spaces/arashx07/Final_Assignment_Template/resolve/main/tools/classify_entities.py
- Command line
-
hf download hf://spaces/arashx07/Final_Assignment_Template/tools/classify_entities.py
-
curl -L -o classify_entities.py https://huggingface.co/spaces/arashx07/Final_Assignment_Template/resolve/main/tools/classify_entities.py
5.79 kB
| 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") | |