
    g"                     
   d dl mZmZ ddlmZmZmZmZ ddlm	Z	m
Z
  e            rd dlmZ ddlmZ  e            rddlmZ dd	lmZ  ej        e          Z e e
d
d
                     G d de	                      ZdS )    )ListUnion   )add_end_docstringsis_torch_availableis_vision_availablelogging   )Pipelinebuild_pipeline_init_args)Image)
load_image)1MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING_NAMES)
KeyDatasetT)has_tokenizerhas_image_processorc                        e Zd ZdZ fdZddZ	 ddedeed         ee         df         deeee         f         f fd	Z	ddZ
d ZddZ x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                 n     t                      j        |i | |                     t                     d S N)super__init__check_model_typer   )selfargskwargs	__class__s      l/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/pipelines/visual_question_answering.pyr   z(VisualQuestionAnsweringPipeline.__init__7   s:    $)&)))OPPPPP    Nc                 L    i i }}|||d<   |||d<   |||d<   |||d<   |i |fS )Npadding
truncationtimeouttop_k )r   r$   r!   r"   r#   r   preprocess_paramspostprocess_paramss           r   _sanitize_parametersz4VisualQuestionAnsweringPipeline._sanitize_parameters;   s_    02B-+2i(!.8l++2i(*/w' "&888r   imagezImage.Imager   questionc                    t          t                    }t          t                    ot          d D                       }t          t                    ot          d D                       }t          t          j        t
          f          rt          t
                    rd}n|s|r$t          t
                    rfdD             }nbt          t          j        t
          f          r|rfdD             }n0|s|r)|r'g }D ]}	D ]}
|                    |
|	d            |}n	 } t                      j        |fi |}|S )a	  
        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`, `List[PIL.Image]` or `KeyDataset`):
                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.
                For dataset: the passed in dataset must be of type `transformers.pipelines.pt_utils.KeyDataset`
                Example:
                ```python
                >>> from transformers.pipelines.pt_utils import KeyDataset
                >>> from datasets import load_dataset

                >>> dataset = load_dataset("detection-datasets/coco")
                >>> oracle(image=KeyDataset(dataset, "image"), question="What's in this image?")

                ```
            question (`str`, `List[str]`):
                The question(s) asked. If given a single question, it can be broadcasted to multiple images.
                If multiple images and questions are given, each and every question will be broadcasted to all images
                (same effect as a Cartesian product)
            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.
        c              3   X   K   | ]%}t          |t          j        t          f          V  &d S r   )
isinstancer   str.0items     r   	<genexpr>z;VisualQuestionAnsweringPipeline.__call__.<locals>.<genexpr>{   s5      8p8pbfD5;X[J\9]9]8p8p8p8p8p8pr   c              3   @   K   | ]}t          |t                    V  d S r   )r-   r.   r/   s     r   r2   z;VisualQuestionAnsweringPipeline.__call__.<locals>.<genexpr>|   s.      >j>jY]z$PS?T?T>j>j>j>j>j>jr   r)   r*   c                     g | ]}|d S r4   r%   )r0   imr*   s     r   
<listcomp>z<VisualQuestionAnsweringPipeline.__call__.<locals>.<listcomp>   s!    JJJb99JJJr   c                     g | ]}|d S r6   r%   )r0   qr)   s     r   r8   z<VisualQuestionAnsweringPipeline.__call__.<locals>.<listcomp>   s!    HHH!155HHHr   )	r-   r   listallr   r.   appendr   __call__)r   r)   r*   r   
is_datasetis_image_batchis_question_batchinputsquestion_image_pairsr:   r7   resultsr   s    ``         r   r>   z(VisualQuestionAnsweringPipeline.__call__G   s   f  z22
#E400pS8p8pjo8p8p8p5p5p&x66j3>j>jai>j>j>j;j;jeek3/00 	Z#5N5N 	$(;;FF 	
 	
8S0I0I 	JJJJEJJJFFS122 	7H 	HHHHxHHHFF 	
 	0A 	#%  N N N NB(//"!0L0LMMMMN)FF F"%''"644V44r   Fc                 (   t          |d         |          }|                     |d         | j        ||          }|                     || j                  }| j        dk    r|                    | j                  }|                    |           |S )Nr)   )r#   r*   )return_tensorsr!   r"   )imagesrF   pt)r   	tokenizer	frameworkimage_processortotorch_dtypeupdate)r   rB   r!   r"   r#   r)   model_inputsimage_featuress           r   
preprocessz*VisualQuestionAnsweringPipeline.preprocess   s    6'?G<<<~~:>!	 & 
 
 --U4>-ZZ>T!!+..t/?@@NN+++r   c                     | j                                         r#d|vr
| j        |d<    | j         j        di ||}n | j         di |}|S )Ngeneration_configr%   )modelcan_generaterS   generate)r   rO   generate_kwargsmodel_outputss       r   _forwardz(VisualQuestionAnsweringPipeline._forward   so    :""$$ 	7"/997;7M 34/DJ/RR,R/RRMM&DJ6666Mr      c                      j                                         r fd|D             S | j         j        j        k    r j         j        j        } j        dk    r8|j                                        d         }|                    |          \  }}nt          d j                   |	                                }|	                                } fdt          ||          D             S )Nc                 p    g | ]2}d j                             |d                                          i3S )answerT)skip_special_tokens)rI   decodestrip)r0   
output_idsr   s     r   r8   z?VisualQuestionAnsweringPipeline.postprocess.<locals>.<listcomp>   sP        4>00QU0VV\\^^_  r   rH   r   zUnsupported framework: c                 J    g | ]\  }}|j         j        j        |         d  S ))scorer]   )rT   configid2label)r0   rc   _idr   s      r   r8   z?VisualQuestionAnsweringPipeline.postprocess.<locals>.<listcomp>   s5    sssT^TY[^etz/@/I#/NOOsssr   )rT   rU   rd   
num_labelsrJ   logitssigmoidtopk
ValueErrortolistzip)r   rX   r$   probsscoresidss   `     r   postprocessz+VisualQuestionAnsweringPipeline.postprocess   s    :""$$ 	t   "/   
 tz(333
)4~%%%,4466q9#jj// !K4>!K!KLLL]]__F**,,Cssssbeflnqbrbrssssr   )NNNNr   )FFN)rZ   )__name__
__module____qualname____doc__r   r(   r   r.   r   r>   rQ   rY   rq   __classcell__)r   s   @r   r   r      s          DQ Q Q Q Q
9 
9 
9 
9 +/L L]Cm)<d3iUVL T#Y'L L L L L L\   	 	 	t t t t t t t tr   r   N)typingr   r   utilsr   r   r   r	   baser   r   PILr   image_utilsr   models.auto.modeling_autor   pt_utilsr   
get_loggerrr   loggerr   r%   r   r   <module>r      sJ           X X X X X X X X X X X X 4 4 4 4 4 4 4 4  )(((((( %]]]]]]$$$$$$		H	%	% ,,4UYZZZ[[lt lt lt lt lth lt lt \[lt lt ltr   