Démo avec Gradio#

Ce notebook présente, à travers un exemple, la bibliothèque gradio qui permet de créer des interfaces de démo très simplement.

Interface de détection d’objets#

Pour cet exemple, nous utilisons un modèle de détection d’objets dans une image, entraîné sur les 80 classes du dataset COCO. Nous utilisons le modèle DETR de Meta (facebook/detr-resnet-50).

Implémentation#

Tout d’abord, construisons notre pipeline à l’aide de la bibliothèque transformers de Hugging Face.

from PIL import Image
import matplotlib.pyplot as plt
from transformers import pipeline
import cv2
import numpy as np
/home/aquilae/anaconda3/envs/dev/lib/python3.11/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html
  from .autonotebook import tqdm as notebook_tqdm
detector = pipeline("object-detection", "facebook/detr-resnet-50")
Some weights of the model checkpoint at facebook/detr-resnet-50 were not used when initializing DetrForObjectDetection: ['model.backbone.conv_encoder.model.layer1.0.downsample.1.num_batches_tracked', 'model.backbone.conv_encoder.model.layer2.0.downsample.1.num_batches_tracked', 'model.backbone.conv_encoder.model.layer3.0.downsample.1.num_batches_tracked', 'model.backbone.conv_encoder.model.layer4.0.downsample.1.num_batches_tracked']
- This IS expected if you are initializing DetrForObjectDetection from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).
- This IS NOT expected if you are initializing DetrForObjectDetection from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).
image = Image.open('images/coco3.jpg')
plt.imshow(image)
plt.axis('off')
plt.show()
../_images/f8ca149eec73faa44fab501414ad0c54b0f117ac45531e14e2c21ed30faa5b64.png

Procédons à la détection et dessinons les boîtes. Pour avoir un résultat clair, nous n’allons entourer que les personnes. Vous pouvez enlever ce filtre si vous le souhaitez.

def draw_boxes(image,output):
  cv_image = np.array(image)
  for bbox in output:
    box = bbox['box']
    label = bbox['label']
    if (label!="person"):
      continue
    cv2.rectangle(cv_image, (box['xmin'], box['ymin']), (box['xmax'], box['ymax']), (0, 0, 255), 1)
    cv2.putText(cv_image, label, (box['xmin'], box['ymin'] - 10), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 255), 1, cv2.LINE_AA)
  return cv_image

output = detector(image)
cv_image=draw_boxes(image,output)
plt.imshow(cv_image)
plt.axis('off')
plt.show()
../_images/d8ed6e499f6b26631be8d7c3db3a085bc0e0065870d9824c9b4b5713cb68ae4f.png

Démo Gradio#

C’est maintenant le moment de construire notre démo avec Gradio. L’idée est d’avoir une interface qui prend une image en entrée et renvoie la même image avec les personnes entourées.

import gradio as gr
def get_pipeline_prediction(pil_image):
  pipeline_output = detector(pil_image)
  processed_image = draw_boxes(pil_image,pipeline_output)
  return processed_image
demo = gr.Interface(
  fn=get_pipeline_prediction,
  inputs=gr.Image(label="Image d'entrée",type="pil"),
  outputs=gr.Image(label="Image avec les personnes détectées",type="pil")
)
IMPORTANT: You are using gradio version 4.24.0, however version 4.29.0 is available, please upgrade.
--------
demo.launch()
Running on local URL:  http://127.0.0.1:7860

To create a public link, set `share=True` in `launch()`.

Et voilà, vous avez construit votre propre démo. Il est possible de la partager en activant le paramètre share=True de la méthode launch(). Cependant, il faudra garder votre notebook actif, sinon la démo disparaîtra. Pour créer une démo qui ne vous oblige pas à garder votre PC allumé, vous pouvez créer un space sur le site de Hugging Face (voir notebook 1).

Note : Bien sûr, Gradio possède plus de fonctionnalités que cela. Je vous invite à consulter la documentation et les différents tutoriels si vous avez un besoin particulier.