o
    h5&                     @   s   d dl mZmZ d dlZddlmZmZmZm	Z	m
Z
mZmZ ddlmZmZ e
 r5d dlmZ ddlmZ e r>dd	lmZ e	 rKd dlZdd
lmZ eeZdd Zdd ZG dd deZeedddG dd deZdS )    )ListUnionN   )ExplicitEnumadd_end_docstringsis_tf_availableis_torch_availableis_vision_availableloggingrequires_backends   )Pipelinebuild_pipeline_init_args)Image)
load_image)/TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES),MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMESc                 C   s   ddt |    S )Ng      ?)npexp)_outputs r   /var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/transformers/pipelines/image_classification.pysigmoid/   s   r   c                 C   s0   t j| ddd}t | | }||jddd S )NT)axiskeepdims)r   maxr   sum)r   maxesshifted_expr   r   r   softmax4   s   r    c                   @   s   e Zd ZdZdZdZdS )ClassificationFunctionr   r    noneN)__name__
__module____qualname__SIGMOIDSOFTMAXNONEr   r   r   r   r!   ;   s    r!   T)has_image_processoraZ  
        function_to_apply (`str`, *optional*, defaults to `"default"`):
            The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:

            - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model
              has several labels, will apply the softmax function on the output.
            - `"sigmoid"`: Applies the sigmoid function on the output.
            - `"softmax"`: Applies the softmax function on the output.
            - `"none"`: Does not apply any function on the output.c                       s~   e Zd ZU dZejZeed<  fddZdddZ	dde
eee d	ed	 f f fd
dZdddZdd ZdddZ  ZS )ImageClassificationPipelinea  
    Image classification pipeline using any `AutoModelForImageClassification`. This pipeline predicts the class of an
    image.

    Example:

    ```python
    >>> from transformers import pipeline

    >>> classifier = pipeline(model="microsoft/beit-base-patch16-224-pt22k-ft22k")
    >>> classifier("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")
    [{'score': 0.442, 'label': 'macaw'}, {'score': 0.088, 'label': 'popinjay'}, {'score': 0.075, 'label': 'parrot'}, {'score': 0.073, 'label': 'parodist, lampooner'}, {'score': 0.046, 'label': 'poll, poll_parrot'}]
    ```

    Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)

    This image classification pipeline can currently be loaded from [`pipeline`] using the following task identifier:
    `"image-classification"`.

    See the list of available models on
    [huggingface.co/models](https://huggingface.co/models?filter=image-classification).
    function_to_applyc                    s>   t  j|i | t| d | | jdkrt d S t d S )Nvisiontf)super__init__r   check_model_type	frameworkr   r   )selfargskwargs	__class__r   r   r/   g   s   

z$ImageClassificationPipeline.__init__Nc                 C   sX   i }|d ur
||d< i }|d ur||d< t |trt| }|d ur'||d< |i |fS )Ntimeouttop_kr+   )
isinstancestrr!   lower)r2   r8   r+   r7   preprocess_paramspostprocess_paramsr   r   r   _sanitize_parametersp   s   

z0ImageClassificationPipeline._sanitize_parametersinputszImage.Imagec                    s6   d|v r	| d}|du rtdt j|fi |S )a	  
        Assign labels to the image(s) passed as inputs.

        Args:
            inputs (`str`, `List[str]`, `PIL.Image` or `List[PIL.Image]`):
                The pipeline handles three types of images:

                - A string containing a http link pointing to an image
                - A string containing a local path to an image
                - An image loaded in PIL directly

                The pipeline accepts either a single image or a batch of images, which must then be passed as a string.
                Images in a batch must all be in the same format: all as http links, all as local paths, or all as PIL
                images.
            function_to_apply (`str`, *optional*, defaults to `"default"`):
                The function to apply to the model outputs in order to retrieve the scores. Accepts four different
                values:

                If this argument is not specified, then it will apply the following functions according to the number
                of labels:

                - If the model has a single label, will apply the sigmoid function on the output.
                - If the model has several labels, will apply the softmax function on the output.

                Possible values are:

                - `"sigmoid"`: Applies the sigmoid function on the output.
                - `"softmax"`: Applies the softmax function on the output.
                - `"none"`: Does not apply any function on the output.
            top_k (`int`, *optional*, defaults to 5):
                The number of top labels that will be returned by the pipeline. If the provided number is higher than
                the number of labels available in the model configuration, it will default to the number of labels.
            timeout (`float`, *optional*, defaults to None):
                The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and
                the call may block forever.

        Return:
            A dictionary or a list of dictionaries containing result. If the input is a single image, will return a
            dictionary, if the input is a list of several images, will return a list of dictionaries corresponding to
            the images.

            The dictionaries contain the following keys:

            - **label** (`str`) -- The label identified by the model.
            - **score** (`int`) -- The score attributed by the model for that label.
        imagesNzICannot call the image-classification pipeline without an inputs argument!)pop
ValueErrorr.   __call__)r2   r?   r4   r5   r   r   rC   }   s
   0
z$ImageClassificationPipeline.__call__c                 C   s6   t ||d}| j|| jd}| jdkr|| j}|S )N)r7   )r@   return_tensorspt)r   image_processorr1   totorch_dtype)r2   imager7   model_inputsr   r   r   
preprocess   s
   
z&ImageClassificationPipeline.preprocessc                 C   s   | j di |}|S )Nr   )model)r2   rJ   model_outputsr   r   r   _forward   s   z$ImageClassificationPipeline._forward   c                    sX  |d u r< j jjdks j jjdkrtj}n& j jjdks$ j jjdkr(tj}nt j jdr9|d u r9 j jj}ntj	}| j jjkrH j jj}|d d } j
dkre|jtjtjfv re|tj }n| }|tjkrst|}n|tjkr}t|}n|tj	kr|}ntd|  fd	d
t|D }|jdd dd |d ur|d | }|S )Nmulti_label_classificationr   single_label_classificationr+   logitsr   rE   z+Unrecognized `function_to_apply` argument: c                    s(   g | ]\}} j jj| | d qS ))labelscore)rL   configid2labelitem).0irT   r2   r   r   
<listcomp>   s    z;ImageClassificationPipeline.postprocess.<locals>.<listcomp>c                 S   s   | d S )NrT   r   )xr   r   r   <lambda>   s    z9ImageClassificationPipeline.postprocess.<locals>.<lambda>T)keyreverse)rL   rU   problem_type
num_labelsr!   r&   r'   hasattrr+   r(   r1   dtypetorchbfloat16float16rG   float32numpyr   r    rB   	enumeratesort)r2   rM   r+   r8   outputsscoresdict_scoresr   rZ   r   postprocess   s8   






z'ImageClassificationPipeline.postprocess)NNN)N)NrO   )r#   r$   r%   __doc__r!   r(   r+   __annotations__r/   r>   r   r:   r   rC   rK   rN   rn   __classcell__r   r   r5   r   r*   A   s   
 
	(
6r*   ) typingr   r   rh   r   utilsr   r   r   r   r	   r
   r   baser   r   PILr   image_utilsr   models.auto.modeling_tf_autor   rd   models.auto.modeling_autor   
get_loggerr#   loggerr   r    r!   r*   r   r   r   r   <module>   s*   $	
