File size: 1,055 Bytes
dc382c8
 
d56b9d9
dc382c8
 
 
 
 
d56b9d9
dc382c8
d56b9d9
 
 
 
 
 
 
 
dc382c8
d56b9d9
dc382c8
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from huggingface_hub import InferenceClient
from os import path, unlink, getenv
from PIL.Image import Image
import pandas as pd
from pandas import DataFrame
from utils import save_image_to_temp_file


def image_classification(client: InferenceClient, image: Image) -> DataFrame:
    try:
        temp_file_path = save_image_to_temp_file(image) # Needed because InferenceClient does not accept PIL Images directly.
        classifications = client.image_classification(temp_file_path, model=getenv("IMAGE_CLASSIFICATION_MODEL"))
        return pd.DataFrame({
                                "Label": classification.label,
                                "Probability": f"{classification.score:.2%}"
                            }
                            for classification
                            in classifications)
    finally:
        if temp_file_path and path.exists(temp_file_path): # Clean up temporary file.
            try:
                unlink(temp_file_path)
            except Exception:
                pass # Ignore clean-up errors.