Certainly! Below is a refactored and generalized version of your object detection pipeline. This version adheres strictly to PEP-8 standards, incorporates type hints using the typing module, and is designed with robustness, scalability, and maintainability in mind. Comprehensive error handling is included to ensure the pipeline can gracefully handle unexpected conditions. The pipeline is organized into modular components, facilitating ease of understanding and future enhancements.
Project Structure
object_detection_pipeline/
├── output/
│ ├── weights/
│ ├── plots/
│ └── logs/
├── pipeline.py
├── requirements.txt
└── README.md
Dependencies
Make sure to install the required dependencies listed in requirements.txt:
pip install -r requirements.txt
requirements.txt:
datasets
transformers
torch
numpy
matplotlib
Pillow
tqdm
requests
Pipeline Implementation
pipeline.py:
import os
import logging
from typing import Any, List, Optional, Dict, Tuple
import numpy as np
import torch
from datasets import DatasetDict, load_dataset
from transformers import (
AutoImageProcessor,
AutoModelForObjectDetection,
TrainingArguments,
Trainer,
pipeline,
)
from PIL import Image, ImageDraw
import matplotlib.pyplot as plt
from tqdm.auto import tqdm
import requests
# Configure logging
logging.basicConfig(
filename='output/logs/pipeline.log',
filemode='a',
format='%(asctime)s - %(levelname)s - %(message)s',
level=logging.INFO
)
class ObjectDetectionPipeline:
def __init__(self,
dataset_name: str,
dataset_config: Optional[str] = None,
checkpoint: str = "facebook/detr-resnet-50-dc5",
output_dir: str = "output",
cache_dir: str = "./cache",
id2label: Optional[Dict[int, str]] = None,
label2id: Optional[Dict[str, int]] = None) -> None:
"""
Initializes the Object Detection Pipeline.
:param dataset_name: Name of the dataset to load.
:param dataset_config: Configuration of the dataset (optional).
:param checkpoint: Pre-trained model checkpoint.
:param output_dir: Directory to save outputs.
:param cache_dir: Directory to cache models.
:param id2label: Mapping from label ID to label name.
:param label2id: Mapping from label name to label ID.
"""
self.dataset_name = dataset_name
self.dataset_config = dataset_config
self.checkpoint = checkpoint
self.output_dir = output_dir
self.cache_dir = cache_dir
self.id2label = id2label or {0: 'head', 1: 'helmet', 2: 'person'}
self.label2id = label2id or {v: k for k, v in self.id2label.items()}
self.dataset: Optional[DatasetDict] = None
self.image_processor = None
self.model = None
self.trainer = None
self.obj_detector = None
self._create_output_dirs()
self._load_dataset()
self._initialize_image_processor()
self._initialize_model()
def _create_output_dirs(self) -> None:
"""Creates necessary output directories."""
try:
os.makedirs(os.path.join(self.output_dir, 'weights'), exist_ok=True)
os.makedirs(os.path.join(self.output_dir, 'plots'), exist_ok=True)
os.makedirs(os.path.join(self.output_dir, 'logs'), exist_ok=True)
logging.info("Output directories created or already exist.")
except Exception as e:
logging.error(f"Failed to create output directories: {e}")
raise
def _load_dataset(self) -> None:
"""Loads the dataset using Hugging Face's `datasets` library."""
try:
self.dataset = load_dataset(self.dataset_name, self.dataset_config)
logging.info(f"Dataset '{self.dataset_name}' loaded successfully.")
except Exception as e:
logging.error(f"Failed to load dataset '{self.dataset_name}': {e}")
raise
def _initialize_image_processor(self) -> None:
"""Initializes the image processor from the checkpoint."""
try:
self.image_processor = AutoImageProcessor.from_pretrained(
self.checkpoint,
cache_dir=self.cache_dir
)
logging.info("Image processor initialized successfully.")
except Exception as e:
logging.error(f"Failed to initialize image processor: {e}")
raise
def _initialize_model(self) -> None:
"""Initializes the model for object detection."""
try:
self.model = AutoModelForObjectDetection.from_pretrained(
self.checkpoint,
id2label=self.id2label,
label2id=self.label2id,
ignore_mismatched_sizes=True,
cache_dir=self.cache_dir
)
logging.info("Model loaded successfully.")
except Exception as e:
logging.error(f"Failed to load model: {e}")
raise
@staticmethod
def draw_image_with_annotations(image: Image.Image, annotations: Dict[str, Any],
width: int, height: int) -> Image.Image:
"""
Draws bounding boxes and labels on the image.
:param image: PIL Image.
:param annotations: Dictionary containing bounding boxes and labels.
:param width: Original image width.
:param height: Original image height.
:return: Annotated PIL Image.
"""
try:
draw = ImageDraw.Draw(image)
for i in range(len(annotations["id"])):
box = annotations["bbox"][i]
category = annotations["category"][i]
x, y, w, h = box
if max(box) > 1.0:
x1, y1 = int(x), int(y)
x2, y2 = int(x + w), int(y + h)
else:
x1 = int(x * width)
y1 = int(y * height)
x2 = int((x + w) * width)
y2 = int((y + h) * height)
draw.rectangle([x1, y1, x2, y2], outline="red", width=2)
draw.text((x1, y1), category, fill="white")
logging.debug("Annotations drawn on image successfully.")
return image
except Exception as e:
logging.error(f"Error drawing annotations: {e}")
raise
def visualize_sample(self, dataset_split: str, idx: int) -> None:
"""
Visualizes a single sample from the dataset.
:param dataset_split: 'train' or 'test'.
:param idx: Index of the sample.
"""
try:
sample = self.dataset[dataset_split][idx]
image = sample["image"].copy()
width, height = sample['width'], sample['height']
annotated_image = self.draw_image_with_annotations(
image, sample['objects'], width, height
)
plt.imshow(annotated_image)
plt.axis('off')
plt.title(f"{dataset_split.capitalize()} Sample {idx}")
plt.show()
logging.info(f"Sample {idx} from '{dataset_split}' visualized successfully.")
except Exception as e:
logging.error(f"Failed to visualize sample {idx}: {e}")
raise
@staticmethod
def formatted_annotations(image_id: int, category: List[str],
area: List[float], bbox: List[List[float]]) -> List[Dict[str, Any]]:
"""
Formats annotations for the model.
:param image_id: ID of the image.
:param category: List of category names.
:param area: List of areas.
:param bbox: List of bounding boxes.
:return: List of formatted annotations.
"""
try:
annotations = []
for cat, ar, box in zip(category, area, bbox):
new_ann = {
"image_id": image_id,
"category_id": box[0], # Assuming category ID is the first element in box
"isCrowd": 0,
"area": ar,
"bbox": box,
}
annotations.append(new_ann)
logging.debug("Annotations formatted successfully.")
return annotations
except Exception as e:
logging.error(f"Error formatting annotations: {e}")
raise
def transform_examples(self, examples: Dict[str, Any]) -> Dict[str, Any]:
"""
Transforms and augments a batch of examples.
:param examples: Batch of examples.
:return: Transformed examples.
"""
try:
image_ids = examples["image_id"]
images, bboxes, area, categories = [], [], [], []
for image, objects in zip(examples["image"], examples["objects"]):
image_np = np.array(image.convert("RGB"))[:, :, ::-1]
# Apply any required transformations or augmentations here
processed = self.image_processor(images=image_np, return_tensors="pt")
images.append(processed["pixel_values"].squeeze())
bboxes.append(objects["bbox"])
area.append(objects["area"])
categories.append([self.label2id.get(cat, 0) for cat in objects["id"]])
targets = [
{"image_id": id_, "annotations": self.formatted_annotations(id_, cat_, ar_, box_)}
for id_, cat_, ar_, box_ in zip(image_ids, categories, area, bboxes)
]
processed_batch = self.image_processor(
images=images,
annotations=targets,
return_tensors="pt"
)
logging.debug("Batch transformed successfully.")
return processed_batch
except Exception as e:
logging.error(f"Error in transforming examples: {e}")
raise
def collate_fn(self, batch: List[Dict[str, Any]]) -> Dict[str, Any]:
"""
Collates a batch for the Trainer.
:param batch: List of processed examples.
:return: Collated batch.
"""
try:
pixel_values = [item["pixel_values"] for item in batch]
encoding = self.image_processor.pad(pixel_values, return_tensors="pt")
labels = [item["labels"] for item in batch]
batch_dict = {
"pixel_values": encoding["pixel_values"],
"pixel_mask": encoding["pixel_mask"],
"labels": labels,
}
logging.debug("Batch collated successfully.")
return batch_dict
except Exception as e:
logging.error(f"Error in collating batch: {e}")
raise
def setup_trainer(self,
train_dataset: Any,
eval_dataset: Any,
training_args: Optional[TrainingArguments] = None) -> None:
"""
Sets up the Trainer for training and evaluation.
:param train_dataset: Training dataset.
:param eval_dataset: Evaluation dataset.
:param training_args: Training arguments.
"""
try:
if training_args is None:
training_args = TrainingArguments(
output_dir=os.path.join(self.output_dir, "weights"),
per_device_train_batch_size=8,
num_train_epochs=3,
max_steps=1000,
fp16=True if torch.cuda.is_available() else False,
save_steps=500,
logging_steps=100,
learning_rate=1e-5,
weight_decay=1e-4,
save_total_limit=2,
remove_unused_columns=False,
push_to_hub=False,
)
self.trainer = Trainer(
model=self.model,
args=training_args,
data_collator=self.collate_fn,
train_dataset=train_dataset,
eval_dataset=eval_dataset,
tokenizer=self.image_processor,
)
logging.info("Trainer setup successfully.")
except Exception as e:
logging.error(f"Failed to set up Trainer: {e}")
raise
def train(self) -> None:
"""Trains the model."""
try:
if self.dataset is None:
raise ValueError("Dataset is not loaded.")
train_transformed = self.dataset["train"].map(
self.transform_examples,
batched=True,
remove_columns=self.dataset["train"].column_names
)
eval_transformed = self.dataset["test"].map(
self.transform_examples,
batched=True,
remove_columns=self.dataset["test"].column_names
)
self.setup_trainer(train_transformed, eval_transformed)
self.trainer.train()
self.trainer.save_model(os.path.join(self.output_dir, 'weights'))
logging.info("Model trained and saved successfully.")
except Exception as e:
logging.error(f"Training failed: {e}")
raise
def initialize_inference_pipeline(self) -> None:
"""Initializes the object detection inference pipeline."""
try:
model_path = os.path.join(self.output_dir, 'weights')
self.obj_detector = pipeline(
"object-detection",
model=model_path,
image_processor=self.image_processor,
framework="pt",
device=0 if torch.cuda.is_available() else -1
)
logging.info("Inference pipeline initialized successfully.")
except Exception as e:
logging.error(f"Failed to initialize inference pipeline: {e}")
raise
def plot_results(self, image: Image.Image, results: List[Dict[str, Any]], threshold: float = 0.7) -> Image.Image:
"""
Plots the detection results on the image.
:param image: PIL Image.
:param results: List of detection results.
:param threshold: Score threshold for displaying detections.
:return: Annotated PIL Image.
"""
try:
draw = ImageDraw.Draw(image)
for result in results:
score = result['score']
label = result['label']
box = result['box']
if score >= threshold:
x1, y1, x2, y2 = box
draw.rectangle([x1, y1, x2, y2], outline="red", width=2)
draw.text((x1, y1), f"{label}: {score:.2f}", fill="white")
logging.debug("Detection results plotted successfully.")
return image
except Exception as e:
logging.error(f"Error plotting results: {e}")
raise
def predict_and_plot(self, image: Image.Image, threshold: float = 0.7) -> None:
"""
Runs inference on an image and plots the results.
:param image: PIL Image.
:param threshold: Score threshold.
"""
try:
results = self.obj_detector(image)
annotated_image = self.plot_results(image.copy(), results, threshold)
plt.imshow(annotated_image)
plt.axis('off')
plt.show()
logging.info("Inference and plotting completed successfully.")
except Exception as e:
logging.error(f"Prediction and plotting failed: {e}")
raise
def download_image(self, url: str) -> Image.Image:
"""
Downloads an image from a URL.
:param url: URL of the image.
:return: PIL Image.
"""
try:
response = requests.get(url, stream=True)
response.raise_for_status()
image = Image.open(response.raw).convert("RGB")
logging.info(f"Image downloaded successfully from {url}.")
return image
except requests.exceptions.RequestException as e:
logging.error(f"Failed to download image from {url}: {e}")
raise
except Exception as e:
logging.error(f"Error processing downloaded image: {e}")
raise
def plot_multiple_images(self, dataset_split: str, indices: List[int], threshold: float = 0.7) -> None:
"""
Plots multiple images with their detection results.
:param dataset_split: 'train' or 'test'.
:param indices: List of indices to plot.
:param threshold: Score threshold for detections.
"""
try:
num_images = len(indices)
cols = 3
rows = (num_images + cols - 1) // cols
fig, axes = plt.subplots(rows, cols, figsize=(15, 5 * rows))
axes = axes.flatten()
for ax, idx in zip(axes, indices):
sample = self.dataset[dataset_split][idx]
image = sample["image"].copy()
results = self.obj_detector(image)
annotated_image = self.plot_results(image, results, threshold)
ax.imshow(annotated_image)
ax.axis('off')
ax.set_title(f"{dataset_split.capitalize()} Sample {idx}")
# Remove any excess subplots
for ax in axes[num_images:]:
fig.delaxes(ax)
plt.tight_layout()
plt.savefig(os.path.join(self.output_dir, 'plots', 'multiple_inferences.png'))
plt.show()
logging.info("Multiple image inferences plotted and saved successfully.")
except Exception as e:
logging.error(f"Failed to plot multiple images: {e}")
raise
def freeze_model_layers(self, layer_names: Optional[List[str]] = None) -> None:
"""
Freezes specified layers of the model to prevent them from being updated during training.
:param layer_names: List of layer name substrings to keep unfrozen. All other layers will be frozen.
"""
try:
if layer_names is None:
layer_names = ['bbox_predictor', 'class_label']
for name, param in self.model.named_parameters():
if not any(layer in name for layer in layer_names):
param.requires_grad = False
logging.info(f"Model layers frozen except for: {layer_names}")
except Exception as e:
logging.error(f"Failed to freeze model layers: {e}")
raise
def main() -> None:
"""Main function to execute the object detection pipeline."""
try:
# Initialize the pipeline
pipeline = ObjectDetectionPipeline(
dataset_name="anindya64/hardhat",
checkpoint="facebook/detr-resnet-50-dc5",
output_dir="output",
cache_dir="./cache"
)
# Visualize a sample training image
pipeline.visualize_sample(dataset_split='train', idx=10)
# Train the model
pipeline.train()
# Freeze layers after training if needed
pipeline.freeze_model_layers()
# Initialize inference pipeline
pipeline.initialize_inference_pipeline()
# Run inference on a downloaded image
sample_image_url = "https://huggingface.co/datasets/hf-vision/course-assets/raw/main/test-helmet-object-detection.jpg"
image = pipeline.download_image(sample_image_url)
pipeline.predict_and_plot(image, threshold=0.7)
# Plot multiple inferences from test dataset
pipeline.plot_multiple_images(dataset_split='test', indices=range(6), threshold=0.7)
except Exception as e:
logging.critical(f"Pipeline execution failed: {e}")
print(f"An error occurred: {e}")
if __name__ == "__main__":
main()
Explanation of the Refactored Pipeline
-
Modular Design:
- The entire pipeline is encapsulated within the
ObjectDetectionPipeline class, promoting reusability and maintainability.
- Functions are broken down into logical units such as data loading, model initialization, training, inference, and visualization.
-
PEP-8 Compliance:
- The code follows PEP-8 standards for naming conventions, indentation, line lengths, and other style guidelines.
-
Type Hints:
- Comprehensive type hints are provided using the
typing module, enhancing code readability and facilitating static type checking.
-
Error Handling:
- Each function includes try-except blocks to catch and log exceptions gracefully.
- Meaningful error messages are logged to a dedicated log file (
output/logs/pipeline.log).
-
Logging:
- The
logging module is configured to record informational, debugging, and error messages.
- Logs are saved in the
output/logs/ directory, aiding in monitoring and debugging.
-
Configuration and Flexibility:
- The pipeline accepts parameters such as dataset name, checkpoint, output directories, and label mappings, making it easily adaptable to different settings.
- Output artifacts like model weights and plots are organized into dedicated subdirectories within the
output/ folder.
-
Data Transformation and Augmentation:
- The
transform_examples method is designed to handle batch processing, making it efficient for large datasets.
- Placeholder comments are included to add any desired data augmentation techniques.
-
Training and Evaluation:
- The
Trainer from Hugging Face transformers is utilized for streamlined training and evaluation.
- Training arguments are customizable, with sensible defaults provided.
-
Inference and Visualization:
- The pipeline includes methods to perform inference on single or multiple images.
- Detection results are plotted directly on the images using
matplotlib, and the plots are also saved for future reference.
Running the Pipeline
-
Ensure Dependencies are Installed:
pip install -r requirements.txt
-
Execute the Pipeline:
python pipeline.py
This will perform the following actions:
- Initialize the pipeline and load the dataset.
- Visualize a sample training image with annotations.
- Train the model and save the weights.
- Initialize the inference pipeline.
- Download a sample image and perform inference with visualization.
- Plot multiple inference results from the test dataset.
Notes and Recommendations
-
Customization:
- You can modify the
id2label and label2id dictionaries in the ObjectDetectionPipeline constructor to suit different label sets.
- Training hyperparameters can be adjusted by passing a custom
TrainingArguments instance to the setup_trainer method.
-
Error Logs:
- Check the
output/logs/pipeline.log file for detailed logs, especially if any errors occur during execution.
-
Extensibility:
- This modular setup allows for easy addition of new functionalities, such as different data augmentations, alternative model architectures, or integration with other tools and frameworks.
-
Performance Monitoring:
- For more advanced monitoring, consider integrating tools like TensorBoard or Weights & Biases.
This refactored pipeline provides a robust foundation for object detection tasks, ensuring code quality, performance, and ease of maintenance.