Following this instruction :
1. Strictly adhere to PEP-8 standards, ensuring code is clean, well-structured, and follows Python's style guide for readability.
2. Use appropriate modules like `typing` for type hints, ensuring code clarity, maintainability, and leveraging Python's standard libraries effectively.
3. Focus on time, space, robustness, scalability; write optimized, efficient code that can handle large datasets and scale seamlessly.
4. Implement comprehensive error handling, catching exceptions gracefully, providing meaningful error messages, and ensuring code robustness under unexpected conditions.
5. Ensure the developer agent writes advanced, maintainable Python code, balancing performance and readability while adhering to best practices.
 t 


TASK: we have generalised pipeline Training, evaluation,inference( from test data) , save plots training , evaluation,inference in the plots(plotly module and save html)
save the weights of in the folder, 

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.
    
    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.
    
    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()