U
    9%eA                     @   s   d dl mZ ddlmZmZmZmZ ddlmZm	Z	 e rRd dl
mZ ddlmZ e rdddlmZ eeZeeG d	d
 d
e	ZdS )    )Union   )add_end_docstringsis_torch_availableis_vision_availablelogging   )PIPELINE_INIT_ARGSPipeline)Image)
load_image)1MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING_NAMESc                       sd   e Zd ZdZ fddZdddZdedef ed fd	d
ZdddZ	dd Z
dddZ  ZS )VisualQuestionAnsweringPipelinea  
    Visual Question Answering pipeline using a `AutoModelForVisualQuestionAnswering`. This pipeline is currently only
    available in PyTorch.

    Example:

    ```python
    >>> from transformers import pipeline

    >>> oracle = pipeline(model="dandelin/vilt-b32-finetuned-vqa")
    >>> image_url = "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/lena.png"
    >>> oracle(question="What is she wearing ?", image=image_url)
    [{'score': 0.948, 'answer': 'hat'}, {'score': 0.009, 'answer': 'fedora'}, {'score': 0.003, 'answer': 'clothes'}, {'score': 0.003, 'answer': 'sun hat'}, {'score': 0.002, 'answer': 'nothing'}]

    >>> oracle(question="What is she wearing ?", image=image_url, top_k=1)
    [{'score': 0.948, 'answer': 'hat'}]

    >>> oracle(question="Is this a person ?", image=image_url, top_k=1)
    [{'score': 0.993, 'answer': 'yes'}]

    >>> oracle(question="Is this a man ?", image=image_url, top_k=1)
    [{'score': 0.996, 'answer': 'no'}]
    ```

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

    This visual question answering pipeline can currently be loaded from [`pipeline`] using the following task
    identifiers: `"visual-question-answering", "vqa"`.

    The models that this pipeline can use are models that have been fine-tuned on a visual question answering task. See
    the up-to-date list of available models on
    [huggingface.co/models](https://huggingface.co/models?filter=visual-question-answering).
    c                    s   t  j|| | t d S N)super__init__Zcheck_model_typer   )selfargskwargs	__class__ o/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/transformers/pipelines/visual_question_answering.pyr   6   s    z(VisualQuestionAnsweringPipeline.__init__Nc                 K   sT   i i  }}|d k	r||d< |d k	r*||d< |d k	r:||d< |d k	rJ||d< |i |fS )Npadding
truncationtimeouttop_kr   )r   r   r   r   r   r   Zpreprocess_paramsZpostprocess_paramsr   r   r   _sanitize_parameters:   s    
z4VisualQuestionAnsweringPipeline._sanitize_parameterszImage.Imageimagequestionc                    s>   t |tjtfr&t |tr&||d}n|}t j|f|}|S )aS  
        Answers open-ended questions about images. The pipeline accepts several types of inputs which are detailed
        below:

        - `pipeline(image=image, question=question)`
        - `pipeline({"image": image, "question": question})`
        - `pipeline([{"image": image, "question": question}])`
        - `pipeline([{"image": image, "question": question}, {"image": image, "question": question}])`

        Args:
            image (`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. If given a single image, it can be
                broadcasted to multiple questions.
            question (`str`, `List[str]`):
                The question(s) asked. If given a single question, it can be broadcasted to multiple images.
            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 the result. 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.
        r   )
isinstancer   strr   __call__)r   r   r    r   inputsresultsr   r   r   r#   F   s
    "z(VisualQuestionAnsweringPipeline.__call__Fc                 C   sF   t |d |d}| j|d | j||d}| j|| jd}|| |S )Nr   )r   r    )return_tensorsr   r   )Zimagesr&   )r   	tokenizer	frameworkZimage_processorupdate)r   r$   r   r   r   r   model_inputsZimage_featuresr   r   r   
preprocessu   s       
z*VisualQuestionAnsweringPipeline.preprocessc                 C   s*   | j  r| j jf |}n| j f |}|S r   )modelcan_generategenerate)r   r*   model_outputsr   r   r   _forward~   s    
z(VisualQuestionAnsweringPipeline._forward   c                    s    j  r fdd|D S | j jjkr4 j jj} jdkr\|j d }||\}}ntd j |	 }|	 } fddt
||D S d S )Nc                    s$   g | ]}d  j j|dd iqS )answerT)Zskip_special_tokens)r'   decodestrip).0Z
output_idsr   r   r   
<listcomp>   s   z?VisualQuestionAnsweringPipeline.postprocess.<locals>.<listcomp>ptr   zUnsupported framework: c                    s$   g | ]\}}| j jj| d qS ))scorer2   )r,   configZid2label)r5   r9   Z_idr6   r   r   r7      s     )r,   r-   r:   Z
num_labelsr(   ZlogitsZsigmoidZtopk
ValueErrortolistzip)r   r/   r   ZprobsZscoresZidsr   r6   r   postprocess   s    



z+VisualQuestionAnsweringPipeline.postprocess)NNNN)N)FFN)r1   )__name__
__module____qualname____doc__r   r   r   r"   r#   r+   r0   r>   __classcell__r   r   r   r   r      s   "
/
	r   N)typingr   utilsr   r   r   r   baser	   r
   ZPILr   Zimage_utilsr   Zmodels.auto.modeling_autor   Z
get_loggerr?   loggerr   r   r   r   r   <module>   s   
