Strictly adhere to PEP-8 standards, ensuring code is clean, well-structured, and follows Python's style guide for readability.
Use appropriate modules like typing for type hints, ensuring code clarity, maintainability, and leveraging Python's standard libraries effectively.
Focus on time, space, robustness, scalability; write optimized, efficient code that can handle large datasets and scale seamlessly.
Implement comprehensive error handling, catching exceptions gracefully, providing meaningful error messages, and ensuring code robustness under unexpected conditions.
Ensure the developer agent writes advanced, maintainable Python code, balancing performance and readability while adhering to best practices.
t
TASK: we have generalised below code , best generalised , scalable, robustness,
import os
import torch
import warnings
import requests
import PIL
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from transformers import CLIPProcessor, CLIPModel, YolosImageProcessor, YolosForObjectDetection
warnings.simplefilter("ignore")
os.environ["TOKENIZERS_PARALLELISM"] = "true"
DETECTION_MODEL_NAME = "hustvl/yolos-tiny"
MULTIMODAL_MODEL_NAME = "openai/clip-vit-base-patch16"
det_image_processor = YolosImageProcessor.from_pretrained(DETECTION_MODEL_NAME)
det_model = YolosForObjectDetection.from_pretrained(DETECTION_MODEL_NAME)
mm_model = CLIPModel.from_pretrained(MULTIMODAL_MODEL_NAME)
mm_processor = CLIPProcessor.from_pretrained(MULTIMODAL_MODEL_NAME)
url = "https://i.pinimg.com/736x/1b/51/42/1b5142c269f2e9a356202af3f5569a87.jpg"
image = Image.open(requests.get(url, stream=True).raw)
def extract_list_images_detected(image, prob):
"""
The function extract_list_images_detected takes an image and a probability threshold as input,
performs object detection on the image using a pre-trained model, and returns a list of cropped
images of the detected objects along with their corresponding scores.
code
Assistant
Args:
:param image: The `image` parameter is the input image from which you want to extract the detected
images. It should be a PIL image object
:param prob: The parameter "prob" is the probability threshold for filtering out the detected
objects. It is used to determine which objects are considered significant enough to be included in
the final list of images. Objects with a probability score higher than the threshold will be
included, while objects with a lower score will be filtered out
Returns:
images_list: returns a list of cropped out images.
scores: returns a list of confidence scores corresponding scores.
"""
inputs = det_image_processor(images=image, return_tensors="pt")
outputs = det_model(**inputs)
logits = outputs.logits
bboxes = outputs.pred_boxes
probas = outputs.logits.softmax(-1)[0, :, :-1]
keep = probas.max(-1).values > prob
outs = det_image_processor.post_process(outputs, torch.tensor(image.size[::-1]).unsqueeze(0))
bboxes_scaled = outs[0]['boxes'][keep].detach().numpy()
labels = outs[0]['labels'][keep].detach().numpy()
scores = outs[0]['scores'][keep].detach().numpy()
images_list = []
for i,j in enumerate(bboxes_scaled):
xmin = int(j[0])
ymin = int(j[1])
xmax = int(j[2])
ymax = int(j[3])
im_arr = np.array(image)
roi = im_arr[ymin:ymax, xmin:xmax]
roi_im = Image.fromarray(roi)
images_list.append(roi_im)
return images_list, scores
def extract_image_with_description(images_list, text, scores):
"""
The function extract_image_with_description takes a list of images, a text description, and
scores, and returns the image with the highest score.
code
Args:
images_list: The `images_list` parameter is a list of images. Each image can be represented
as a file path or a URL
text: The `text` parameter is a string that represents the description or caption of the
image
scores: The "scores" parameter is a list of scores corresponding to each image in the
"images_list". These scores represent the confidence or relevance of each image to the given text
Returns:
the image with the highest score (PIL.Image) and its corresponding score.
"""
input_ = mm_processor(text = [text], images=images_list , return_tensors="pt", padding=True)
output = mm_model(**input_)
logits_per_image = output.logits_per_text
probs = logits_per_image.softmax(-1)
l_idx = np.argsort(probs[-1].detach().numpy())[::-1][0:1]
final_ims = []
for i,j in enumerate(images_list):
param_dict = {}
if i in l_idx:
param_dict['image'] = images_list[i]
param_dict['score'] = probs[-1].detach().numpy()[i]
final_ims.append(param_dict)
fi = sorted(final_ims, key=lambda item: item.get("score"), reverse=True)
return fi[0]['image'], fi[0]['score']
list_rois, conf_scores = extract_list_images_detected(image, prob=0.85)
plt.imshow(image)
plt.axis("off")
plt.tight_layout()
TEXT_DESC = ["Man carrying a green bag", "man riding a bicycle", "yellow colored taxi car", "red colored bus"]
images_list = []
for txt in TEXT_DESC:
img_dict = {}
img, score = extract_image_with_description(list_rois, txt, conf_scores)
img_dict['image'] = img
img_dict['description'] = txt
img_dict['conf-score'] = score
images_list.append(img_dict)
fig = plt.figure(figsize=(10, 20))
for i in range(len(images_list)):
plt.subplot(1, len(images_list), i + 1)
plt.imshow(images_list[i]['image'])
plt.title(images_list[i]['description'])
plt.xlabel("confidence-score:" + str(round(images_list[i]['conf-score'], 3)))
plt.xticks(ticks=[])
plt.yticks(ticks=[])
plt.tight_layout()
plt.show()
Certainly! Below is the refactored version of your code adhering to PEP-8 standards, utilizing type hints from the typing module, optimized for performance and scalability, and incorporating comprehensive error handling. The code is organized into a class structure to enhance maintainability and scalability.
python
import os
import warnings
from typing import List, Tuple, Dict
import matplotlib.pyplot as plt
import numpy as np
import requests
import torch
from PIL import Image, UnidentifiedImageError
from transformers import (
CLIPProcessor,
CLIPModel,
YolosImageProcessor,
YolosForObjectDetection,
)
# Suppress warnings
warnings.simplefilter("ignore")
os.environ["TOKENIZERS_PARALLELISM"] = "true"
# Constants for model names and URLs
DETECTION_MODEL_NAME = "hustvl/yolos-tiny"
MULTIMODAL_MODEL_NAME = "openai/clip-vit-base-patch16"
IMAGE_URL = "https://i.pinimg.com/736x/1b/51/42/1b5142c269f2e9a356202af3f5569a87.jpg"
TEXT_DESCRIPTIONS = [
"Man carrying a green bag",
"man riding a bicycle",
"yellow colored taxi car",
"red colored bus",
]
class ImageProcessorPipeline:
"""
A pipeline for object detection and multimodal processing using pre-trained models.
"""
def __init__(
self,
detection_model_name: str = DETECTION_MODEL_NAME,
multimodal_model_name: str = MULTIMODAL_MODEL_NAME,
detection_threshold: float = 0.85,
) -> None:
"""
Initialize the pipeline with specified models and threshold.
:param detection_model_name: Pre-trained detection model name.
:param multimodal_model_name: Pre-trained multimodal model name.
:param detection_threshold: Probability threshold for object detection.
"""
self.detection_threshold = detection_threshold
try:
self.det_image_processor = YolosImageProcessor.from_pretrained(
detection_model_name
)
self.det_model = YolosForObjectDetection.from_pretrained(
detection_model_name
)
self.mm_model = CLIPModel.from_pretrained(multimodal_model_name)
self.mm_processor = CLIPProcessor.from_pretrained(multimodal_model_name)
except Exception as e:
raise RuntimeError(f"Failed to load models: {e}")
def load_image_from_url(self, url: str) -> Image.Image:
"""
Load an image from a given URL.
:param url: URL of the image to load.
:return: PIL Image object.
:raises ValueError: If the image cannot be loaded.
"""
try:
response = requests.get(url, stream=True)
response.raise_for_status()
image = Image.open(response.raw).convert("RGB")
return image
except (requests.HTTPError, UnidentifiedImageError) as e:
raise ValueError(f"Failed to load image from URL: {e}")
def extract_detected_objects(
self, image: Image.Image
) -> Tuple[List[Image.Image], np.ndarray]:
"""
Perform object detection on the image and extract cropped objects with scores.
:param image: PIL Image object.
:return: Tuple of list of cropped images and their confidence scores.
"""
try:
inputs = self.det_image_processor(images=image, return_tensors="pt")
with torch.no_grad():
outputs = self.det_model(**inputs)
logits = outputs.logits
probas = logits.softmax(-1)[0, :, :-1]
keep = probas.max(-1).values > self.detection_threshold
outs = self.det_image_processor.post_process(
outputs, torch.tensor(image.size[::-1]).unsqueeze(0)
)
bboxes_scaled = outs[0]["boxes"][keep].detach().cpu().numpy()
scores = outs[0]["scores"][keep].detach().cpu().numpy()
images_list = self._crop_images(image, bboxes_scaled)
return images_list, scores
except Exception as e:
raise RuntimeError(f"Object detection failed: {e}")
@staticmethod
def _crop_images(
image: Image.Image, bboxes: np.ndarray
) -> List[Image.Image]:
"""
Crop regions of interest from the image based on bounding boxes.
:param image: PIL Image object.
:param bboxes: Numpy array of bounding boxes.
:return: List of cropped PIL Image objects.
"""
image_np = np.array(image)
cropped_images = []
for bbox in bboxes:
xmin, ymin, xmax, ymax = map(int, bbox)
roi = image_np[ymin:ymax, xmin:xmax]
cropped_image = Image.fromarray(roi)
cropped_images.append(cropped_image)
return cropped_images
def get_best_matching_image(
self, images: List[Image.Image], text: str
) -> Tuple[Image.Image, float]:
"""
Find the image that best matches the given text description.
:param images: List of PIL Image objects.
:param text: Text description to match.
:return: Tuple of best matching image and its score.
"""
try:
inputs = self.mm_processor(
text=[text], images=images, return_tensors="pt", padding=True
)
with torch.no_grad():
outputs = self.mm_model(**inputs)
logits_per_text = outputs.logits_per_text
probs = logits_per_text.softmax(dim=-1).cpu().numpy()[0]
if not probs.size:
raise ValueError("No probabilities returned from the model.")
best_idx = np.argmax(probs)
best_image = images[best_idx]
best_score = float(probs[best_idx])
return best_image, best_score
except Exception as e:
raise RuntimeError(f"Multimodal processing failed: {e}")
def process(
self, url: str, text_descriptions: List[str]
) -> List[Dict[str, object]]:
"""
Process the image from URL and extract images matching the text descriptions.
:param url: URL of the image to process.
:param text_descriptions: List of text descriptions to match.
:return: List of dictionaries containing matched images, descriptions, and scores.
"""
try:
image = self.load_image_from_url(url)
detected_images, scores = self.extract_detected_objects(image)
if not detected_images:
raise ValueError("No objects detected with the specified threshold.")
matched_images = []
for description in text_descriptions:
img, score = self.get_best_matching_image(detected_images, description)
matched_images.append(
{
"image": img,
"description": description,
"confidence_score": score,
}
)
return matched_images, image
except Exception as e:
raise RuntimeError(f"Processing failed: {e}")
@staticmethod
def display_results(
original_image: Image.Image, matched_images: List[Dict[str, object]]
) -> None:
"""
Display the original image and the matched images with descriptions and scores.
:param original_image: The original PIL Image object.
:param matched_images: List of dictionaries with matched images and metadata.
"""
try:
plt.figure(figsize=(15, 7))
plt.subplot(1, len(matched_images) + 1, 1)
plt.imshow(original_image)
plt.title("Original Image")
plt.axis("off")
for idx, img_dict in enumerate(matched_images, start=2):
plt.subplot(1, len(matched_images) + 1, idx)
plt.imshow(img_dict["image"])
plt.title(img_dict["description"])
plt.xlabel(f"Confidence: {img_dict['confidence_score']:.3f}")
plt.axis("off")
plt.tight_layout()
plt.show()
except Exception as e:
raise RuntimeError(f"Displaying results failed: {e}")
def main() -> None:
"""
Main function to execute the image processing pipeline.
"""
pipeline = ImageProcessorPipeline(
detection_model_name=DETECTION_MODEL_NAME,
multimodal_model_name=MULTIMODAL_MODEL_NAME,
detection_threshold=0.85,
)
try:
matched_images, original_image = pipeline.process(
url=IMAGE_URL, text_descriptions=TEXT_DESCRIPTIONS
)
pipeline.display_results(original_image, matched_images)
except Exception as error:
print(f"An error occurred: {error}")
if __name__ == "__main__":
main()
Key Improvements and Features
PEP-8 Compliance
Naming Conventions: Used descriptive variable and function names with snake_case.
Line Length: Ensured lines do not exceed 79 characters where feasible.
Imports: Organized imports into standard library, third-party, and local modules, removing unnecessary imports.
Type Hints and Documentation
Added type hints to all functions and methods for better readability and maintainability.
Included comprehensive docstrings for classes and methods explaining their purpose, parameters, and return types.
Error Handling
Wrapped critical sections with try-except blocks to gracefully handle exceptions.
Provided meaningful error messages to aid in debugging and user feedback.
Modular Design
Encapsulated functionality within the ImageProcessorPipeline class to promote reusability and scalability.
Broke down complex functions into smaller, single-responsibility methods.
Performance Optimizations
Utilized torch.no_grad() to prevent unnecessary gradient computations during inference, saving memory and computational resources.
Converted tensors to CPU and detached them from the computation graph immediately after processing.
Scalability and Maintainability
Allowed easy modification of model names and detection thresholds through class initialization parameters.
Facilitated adding more functionalities or modifying existing ones without affecting other parts of the code.
User Feedback and Logging
While not implemented here, integrating a logging framework (like Python’s built-in logging module) can further enhance debugging and monitoring capabilities.
Visualization Enhancements
Included the original image alongside matched images for better context.
Displayed confidence scores with three decimal places for precision.
How to Use
Dependencies:
Ensure you have the necessary libraries installed. You can install them using pip:
Execution:
Save the script to a Python file, for example, image_processor.py, and run it using:
bash
python image_processor.py
Customization:
IMAGE_URL: Change the IMAGE_URL variable to process a different image.
TEXT_DESCRIPTIONS: Modify the TEXT_DESCRIPTIONS list to include different descriptions you want to match against the detected objects.
Detection Threshold: Adjust the detection_threshold parameter in the ImageProcessorPipeline initialization to be more or less strict in object detection.
Potential Enhancements
Batch Processing: Modify the pipeline to handle multiple images in batches for improved efficiency when processing large datasets.
Asynchronous Requests: Utilize asynchronous programming (e.g., asyncio) to handle image loading and processing concurrently.
Logging: Integrate a logging mechanism to record events, errors, and other runtime information systematically.
Configuration Files: Use configuration files (like YAML or JSON) to manage model names, thresholds, and other parameters, enhancing flexibility.
Unit Testing: Develop unit tests for each module to ensure reliability and facilitate future modifications.
This refactored code provides a robust, scalable, and maintainable foundation for your image processing tasks, adhering to best practices and Python’s coding standards.