Ë
    ÜÓ^jC  ã                   óÎ   — d dl Z d dlZd dlZddlmZ ddlmZmZm	Z	 ddl
mZmZmZmZmZ  e«       rd dlZddlmZmZ  G d„ d	e«      Z e ed
¬«      «       G d„ de«      «       Zy)é    Né   )ÚGenerationConfig)Úadd_end_docstringsÚis_torch_availableÚrequires_backendsé   )ÚArgumentHandlerÚDatasetÚPipelineÚPipelineExceptionÚbuild_pipeline_init_args)Ú,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMESÚ0MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMESc                   ó   — e Zd ZdZdd„Zy)Ú%TableQuestionAnsweringArgumentHandlerzB
    Handles arguments for the TableQuestionAnsweringPipeline
    Nc                 ó  — t        | d«       dd l}|€t        d«      ‚|�€t        |t        «      r&|j                  d«      �|j                  d«      �|g}nàt        |t        «      r€t        |«      dkD  rrt        d„ |D «       «      st        dd„ |D «       › �«      ‚|d   j                  d«      �|d   j                  d«      �|}npt        d	|d   j                  «       › d
�«      ‚t        �t        |t        «      st        |t        j                  «      r|S t        dt        |«      › d�«      ‚||dœg}|D ]C  }t        |d   |j                  «      rŒ|d   €t        d«      ‚|j                  |d   «      |d<   ŒE |S )NÚpandasr   z(Keyword argument `table` cannot be None.ÚqueryÚtablec              3   ó<   K  — | ]  }t        |t        «      –— Œ y ­w©N)Ú
isinstanceÚdict©Ú.0Úds     úz/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/pipelines/table_question_answering.pyú	<genexpr>zATableQuestionAnsweringArgumentHandler.__call__.<locals>.<genexpr>-   s   è ø€ Ò>°1œ: a¬×.Ñ>ùs   ‚z:Keyword argument `table` should be a list of dict, but is c              3   ó2   K  — | ]  }t        |«      –— Œ y ­wr   )Útyper   s     r   r   zATableQuestionAnsweringArgumentHandler.__call__.<locals>.<genexpr>/   s   è ø€ ÒUmÐbcÔVZÐ[\×V]ÑUmùs   ‚z‹If keyword argument `table` is a list of dictionaries, each dictionary should have a `table` and `query` key, but only dictionary has keys z `table` and `query` keys.zZInvalid input. Keyword argument `table` should be either of type `dict` or `list`, but is ú))r   r   zTable cannot be None.)r   r   Ú
ValueErrorr   r   ÚgetÚlistÚlenÚallÚkeysr
   ÚtypesÚGeneratorTyper    Ú	DataFrame)Úselfr   r   ÚkwargsÚpdÚtqa_pipeline_inputsÚtqa_pipeline_inputs          r   Ú__call__z.TableQuestionAnsweringArgumentHandler.__call__   s©  € ô 	˜$ Ô)Ûàˆ=ÜÐGÓHÐHØ‰]Ü˜%¤Ô&¨5¯9©9°WÓ+=Ð+IÈeÏiÉiÐX_ÓN`ÐNlØ', gÑ#Ü˜E¤4Ô(¬S°«Z¸!ª^ÜÑ>¸Ô>Ô>Ü$ØTÑUmÐglÔUmÐTnÐoóð ð ˜‘8—<‘< Ó(Ð4¸¸q¹¿¹ÀgÓ9NÐ9ZØ*/Ñ'ä$ðJØJOÐPQÉ(Ï-É-Ë/ÐIZÐZtðvóð ô Ð$¬°E¼7Ô)CÄzÐRWÔY^×YlÑYlÔGmØ�ä ðÜ˜u›+˜ að)óð ð
 .3¸UÑ#CÐ"DÐà"5ò 	XÐÜÐ0°Ñ9¸2¿<¹<ÕHØ% gÑ.Ð6Ü$Ð%<Ó=Ð=à.0¯l©lÐ;MÈgÑ;VÓ.WÐ" 7Ò+ð	Xð #Ð"ó    )NN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r0   © r1   r   r   r      s   „ ñô-#r1   r   T)Úhas_tokenizerc                   óŽ   ‡ — e Zd ZdZdZdZdZdZdZdZ	 e
d¬«      Z e«       fˆ fd„	Zd„ Zd	„ Zˆ fd
„Zdd„Zdd„Zdd„Zd„ Zˆ xZS )ÚTableQuestionAnsweringPipelineaÌ  
    Table Question Answering pipeline using a `ModelForTableQuestionAnswering`. This pipeline is only available in
    PyTorch.

    Unless the model you're using explicitly sets these generation parameters in its configuration files
    (`generation_config.json`), the following default values will be used:
    - max_new_tokens: 256

    Example:

    ```python
    >>> from transformers import pipeline

    >>> oracle = pipeline(model="google/tapas-base-finetuned-wtq")
    >>> table = {
    ...     "Repository": ["Transformers", "Datasets", "Tokenizers"],
    ...     "Stars": ["36542", "4512", "3934"],
    ...     "Contributors": ["651", "77", "34"],
    ...     "Programming language": ["Python", "Python", "Rust, Python and NodeJS"],
    ... }
    >>> oracle(query="How many stars does the transformers repository have?", table=table)
    {'answer': 'AVERAGE > 36542', 'coordinates': [(0, 1)], 'cells': ['36542'], 'aggregator': 'AVERAGE'}
    ```

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

    This tabular question answering pipeline can currently be loaded from [`pipeline`] using the following task
    identifier: `"table-question-answering"`.

    The models that this pipeline can use are models that have been fine-tuned on a tabular question answering task.
    See the up-to-date list of available models on
    [huggingface.co/models](https://huggingface.co/models?filter=table-question-answering).
    ztable,queryTFé   )Úmax_new_tokensc                 ó–  •— t        ‰| �  di |¤Ž || _        t        j                  «       }|j                  t        «       | j                  |«       t        | j                  j                  dd «      xr! t        | j                  j                  dd «      | _        t        | j                  j                  d«      rd| _        y d | _        y )NÚaggregation_labelsÚnum_aggregation_labelsÚtapasr6   )ÚsuperÚ__init__Ú_args_parserr   ÚcopyÚupdater   Úcheck_model_typeÚgetattrÚmodelÚconfigÚ	aggregateÚhasattrr    )r+   Úargs_parserr,   ÚmappingÚ	__class__s       €r   rA   z'TableQuestionAnsweringPipeline.__init__}   s£   ø€ Ü‰ÑÑ"˜6Ò"Ø'ˆÔäB×GÑGÓIˆØ�‰ÔCÔDØ×Ñ˜gÔ&ä  §¡×!2Ñ!2Ð4HÈ$ÓOò 
ÔT[Ø�J‰J×ÑÐ7¸óU
ˆŒô  ' t§z¡z×'8Ñ'8Ð:NÔO�Gˆ�	ÐUYˆ�	r1   c                 ó&   —  | j                   di |¤ŽS )Nr6   )rG   )r+   Úinputss     r   Úbatch_inferencez.TableQuestionAnsweringPipeline.batch_inferenceŠ   s   € Øˆt�z‰zÑ#˜FÑ#Ð#r1   c           	      ó  — g }g }d}|d   j                   d   }|d   j                  | j                  «      }|d   j                  | j                  «      }|d   j                  | j                  «      }d}	t        |«      D �]+  }
|��'|	dd…df   }t	        j
                  |j                  «       j                  «       «      }||
   }	t        |j                   d   «      D ]{  }|	dd…df   j                  «       |   }|	dd…df   j                  «       |   dz
  }|	dd…df   j                  «       |   dz
  }|dk\  sŒ]|dk\  sŒc|dk(  sŒit        |||f   «      ||<   Œ} t        j                  |«      j                  t        j                  «      j                  | j                  «      |	dd…df<   ||
   }||
   }||
   }	| j                  |j                  d«      |j                  d«      |	j                  d«      ¬	«      }|j                   }| j"                  r|j%                  |j&                  «       |j%                  |«       t        j(                  j+                  |¬
«      }|j,                  |j                  t        j.                  «      j                  |j,                  j                  «      z  }t1        j2                  t4        «      }t7        |j9                  «       j                  «       «      D ]�  \  }}|	dd…df   j                  «       |   }|	dd…df   j                  «       |   dz
  }|	dd…df   j                  «       |   dz
  }|dk\  sŒ`|dk\  sŒf|dk(  sŒl|||f   j%                  |«       Œƒ |D �ci c],  }|t	        j:                  ||   «      j=                  «       dkD  “Œ. }}�Œ. t        j>                  tA        |«      d«      }| j"                  s|fS |t        j>                  tA        |«      d«      fS c c}w )zµ
        Inference used for models that need to process sequences in a sequential fashion, like the SQA models which
        handle conversational query related to a table.
        NÚ	input_idsr   Úattention_maskÚtoken_type_idsé   r   r   )rR   rS   rT   )Úlogitsg      à?)!ÚshapeÚtoÚdeviceÚrangeÚnpÚ
zeros_likeÚcpuÚnumpyÚtolistÚintÚtorchÚ
from_numpyr    ÚlongrG   Ú	unsqueezerV   rI   ÚappendÚlogits_aggregationÚdistributionsÚ	BernoulliÚprobsÚfloat32ÚcollectionsÚdefaultdictr$   Ú	enumerateÚsqueezeÚarrayÚmeanÚcatÚtuple)r+   rO   Ú
all_logitsÚall_aggregationsÚprev_answersÚ
batch_sizerR   rS   rT   Útoken_type_ids_exampleÚindexÚprev_labels_exampleÚmodel_labelsÚiÚ
segment_idÚcol_idÚrow_idÚinput_ids_exampleÚattention_mask_exampleÚoutputsrV   Údist_per_tokenÚprobabilitiesÚcoords_to_probsÚpÚcolÚrowÚkeyÚlogits_batchs                                r   Úsequential_inferencez3TableQuestionAnsweringPipeline.sequential_inference�   sí  € ð
 ˆ
ØÐØˆØ˜KÑ(×.Ñ.¨qÑ1ˆ
à˜;Ñ'×*Ñ*¨4¯;©;Ó7ˆ	ØÐ 0Ñ1×4Ñ4°T·[±[ÓAˆØÐ 0Ñ1×4Ñ4°T·[±[ÓAˆØ!%Ðä˜:Ó&ó .	iˆEð Ñ'Ø&<ºQÀ¸TÑ&BÐ#Ü!Ÿ}™}Ð-@×-DÑ-DÓ-F×-LÑ-LÓ-NÓO�à)7¸Ñ)>Ð&Ü˜|×1Ñ1°!Ñ4Ó5ò N�AØ!7º¸1¸Ñ!=×!DÑ!DÓ!FÀqÑ!I�JØ3²A°q°DÑ9×@Ñ@ÓBÀ1ÑEÈÑI�FØ3²A°q°DÑ9×@Ñ@ÓBÀ1ÑEÈÑI�Fà “{ v°£{°zÀQ³Ü*-¨l¸FÀFÐ;KÑ.LÓ*M˜ QšðNô 05×/?Ñ/?ÀÓ/M×/RÑ/RÔSX×S]ÑS]Ó/^×/aÑ/aÐbf×bmÑbmÓ/nÐ&¢q¨! tÑ,à )¨%Ñ 0ÐØ%3°EÑ%:Ð"Ø%3°EÑ%:Ð"Ø—j‘jØ+×5Ñ5°aÓ8Ø5×?Ñ?ÀÓBØ5×?Ñ?ÀÓBð !ó ˆGð
 —^‘^ˆFà�~Š~Ø ×'Ñ'¨×(BÑ(BÔCà×Ñ˜fÔ%ä"×0Ñ0×:Ñ:À&Ð:ÓIˆNØ*×0Ñ0Ð3I×3NÑ3NÌuÏ}É}Ó3]×3`Ñ3`Ø×$Ñ$×+Ñ+ó4ñ ˆMô *×5Ñ5´dÓ;ˆOÜ! -×"7Ñ"7Ó"9×"@Ñ"@Ó"BÓCò :‘��1Ø3²A°q°DÑ9×@Ñ@ÓBÀ1ÑE�
Ø,ªQ°¨TÑ2×9Ñ9Ó;¸AÑ>ÀÑB�Ø,ªQ°¨TÑ2×9Ñ9Ó;¸AÑ>ÀÑB�Ø˜!“8  q£¨Z¸1«_Ø# S¨# JÑ/×6Ñ6°qÕ9ð:ð YhÖhÐQT˜C¤§¡¨/¸#Ñ*>Ó!?×!DÑ!DÓ!FÈÑ!LÑLÐhˆLÒhð].	iô` —y‘y¤ zÓ!2°AÓ6ˆà&*§n¢n�ˆÐo¸<ÌÏÉÔSXÐYiÓSjÐlmÓInÐ:oÐoùò	 is   Í91O>c                 ór   •—  | j                   |i |¤Ž}t        ‰| �  |fi |¤Ž}t        |«      dk(  r|d   S |S )a  
        Answers queries according to a table. The pipeline accepts several types of inputs which are detailed below:

        - `pipeline(table, query)`
        - `pipeline(table, [query])`
        - `pipeline(table=table, query=query)`
        - `pipeline(table=table, query=[query])`
        - `pipeline({"table": table, "query": query})`
        - `pipeline({"table": table, "query": [query]})`
        - `pipeline([{"table": table, "query": query}, {"table": table, "query": query}])`

        The `table` argument should be a dict or a DataFrame built from that dict, containing the whole table:

        Example:

        ```python
        data = {
            "actors": ["brad pitt", "leonardo di caprio", "george clooney"],
            "age": ["56", "45", "59"],
            "number of movies": ["87", "53", "69"],
            "date of birth": ["7 february 1967", "10 june 1996", "28 november 1967"],
        }
        ```

        This dictionary can be passed in as such, or can be converted to a pandas DataFrame:

        Example:

        ```python
        import pandas as pd

        table = pd.DataFrame.from_dict(data)
        ```

        Args:
            table (`pd.DataFrame` or `Dict`):
                Pandas DataFrame or dictionary that will be converted to a DataFrame containing all the table values.
                See above for an example of dictionary.
            query (`str` or `list[str]`):
                Query or list of queries that will be sent to the model alongside the table.
            sequential (`bool`, *optional*, defaults to `False`):
                Whether to do inference sequentially or as a batch. Batching is faster, but models like SQA require the
                inference to be done sequentially to extract relations within sequences, given their conversational
                nature.
            padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):
                Activates and controls padding. Accepts the following values:

                - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
                  sequence if provided).
                - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
                  acceptable input length for the model if that argument is not provided.
                - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
                  lengths).

            truncation (`bool`, `str` or [`TapasTruncationStrategy`], *optional*, defaults to `False`):
                Activates and controls truncation. Accepts the following values:

                - `True` or `'drop_rows_to_fit'`: Truncate to a maximum length specified with the argument `max_length`
                  or to the maximum acceptable input length for the model if that argument is not provided. This will
                  truncate row by row, removing rows from the table.
                - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths
                  greater than the model maximum admissible input size).


        Return:
            A dictionary or a list of dictionaries containing results: Each result is a dictionary with the following
            keys:

            - **answer** (`str`) -- The answer of the query given the table. If there is an aggregator, the answer will
              be preceded by `AGGREGATOR >`.
            - **coordinates** (`list[tuple[int, int]]`) -- Coordinates of the cells of the answers.
            - **cells** (`list[str]`) -- List of strings made up of the answer cell values.
            - **aggregator** (`str`) -- If the model has an aggregator, this returns the aggregator.
        r   r   )rB   r@   r0   r%   )r+   Úargsr,   Úpipeline_inputsÚresultsrM   s        €r   r0   z'TableQuestionAnsweringPipeline.__call__Ð   sL   ø€ ðV ,˜$×+Ñ+¨TÐ<°VÑ<ˆä‘'Ñ" ?Ñ=°fÑ=ˆÜˆw‹<˜1ÒØ˜1‘:ÐØˆr1   c                 óÌ   — i }|�||d<   |�||d<   i }|�||d<   t        | dd «      �| j                  |d<   t        | dd «      �| j                  |d<   | j                  |d<   ||i fS )NÚpaddingÚ
truncationÚ
sequentialÚassistant_modelÚassistant_tokenizerÚ	tokenizer)rF   r“   r•   r”   )r+   r’   r�   r‘   r,   Úpreprocess_paramsÚforward_paramss          r   Ú_sanitize_parametersz3TableQuestionAnsweringPipeline._sanitize_parameters"  sœ   € ØÐØÐØ+2Ð˜iÑ(ØÐ!Ø.8Ð˜lÑ+àˆØÐ!Ø+5ˆN˜<Ñ(ä�4Ð*¨DÓ1Ð=Ø04×0DÑ0DˆNÐ,Ñ-Ü�4Ð.°Ó5ÐAØ*.¯.©.ˆN˜;Ñ'Ø48×4LÑ4LˆNÐ0Ñ1à  .°"Ð4Ð4r1   c                 óÎ   — |€| j                   dk(  rd}nd}|d   |d   }}|j                  rt        d«      ‚|�|dk(  rt        d«      ‚| j                  ||d	||¬
«      }||d<   |S )Nr?   Údrop_rows_to_fitÚdo_not_truncater   r   ztable is emptyÚ zquery is emptyÚpt)Úreturn_tensorsr‘   r�   )r    Úemptyr"   r•   )r+   Úpipeline_inputr�   r‘   r   r   rO   s          r   Ú
preprocessz)TableQuestionAnsweringPipeline.preprocess5  s‚   € ØÐØ�y‰y˜GÒ#Ø/‘
à.�
à% gÑ.°¸wÑ0GˆuˆØ�;Š;ÜÐ-Ó.Ð.Øˆ=˜E RšKÜÐ-Ó.Ð.Ø—‘  u¸TÈjÐbi�ÓjˆØˆˆw‰Øˆr1   c                 ó  — |j                  d«      }| j                  dk(  r(|r | j                  di |¤Ž}nD | j                  di |¤Ž}n1d|vr| j                  |d<    | j
                  j                  di |¤|¤Ž}|||dœ}|S )Nr   r?   Úgeneration_config)Úmodel_inputsr   r�   r6   )Úpopr    rŠ   rP   r£   rG   Úgenerate)r+   r¤   r’   Úgenerate_kwargsr   r�   Úmodel_outputss          r   Ú_forwardz'TableQuestionAnsweringPipeline._forwardE  s—   € Ø× Ñ  Ó)ˆà�9‰9˜ÒÙØ3˜$×3Ñ3ÑC°lÑC‘à.˜$×.Ñ.Ñ>°Ñ>‘ð #¨/Ñ9Ø7;×7MÑ7M�Ð 3Ñ4à)�d—j‘j×)Ñ)ÑL¨LÐL¸OÑLˆGØ)5ÀÐRYÑZˆØÐr1   c                 ój  — |d   }|d   }|d   }| j                   dk(  �r¹| j                  r´|d d \  }}| j                  j                  |||«      }|\  }}	t	        |	«      D �
�ci c])  \  }
}|
| j
                  j                  j                  |   “Œ+ }}
}| j
                  j                  j                  }t	        |	«      D �
�ci c]  \  }
}||k7  sŒ|
||
   dz   “Œ }}
}n*|d   }| j                  j                  ||«      }|d   }i }i }g }t	        |«      D ]�  \  }}|D �cg c]  }|j                  |   ‘Œ }}|j                  |d«      }|j                  |d«      }|d	j                  |«      z   ||D �cg c]  }|j                  |   ‘Œ c}d
œ}|r||d<   |j                  |«       Œ’ t        «      dk(  rMt        d| j
                  j                  d«      ‚| j                  j!                  |d¬«      D �cg c]  }d|i‘Œ }}t        |«      dkD  r|S |d   S c c}}
w c c}}
w c c}w c c}w c c}w )Nr¤   r   r�   r?   r   z > r   rœ   z, )ÚanswerÚcoordinatesÚcellsÚ
aggregatorzTable question answeringzEmpty answerT)Úskip_special_tokensr«   r   )r    rI   r•   Úconvert_logits_to_predictionsrm   rG   rH   r=   Úno_aggregation_label_indexÚiatr#   Újoinre   r%   r   Úname_or_pathÚbatch_decode)r+   r¨   rO   r   r�   rV   Ú
logits_aggÚpredictionsÚanswer_coordinates_batchÚagg_predictionsr{   ÚpredÚaggregatorsÚno_agg_label_indexÚaggregators_prefixÚanswersrx   r¬   Ú
coordinater­   r®   Úaggregator_prefixr«   s                          r   Úpostprocessz*TableQuestionAnsweringPipeline.postprocessV  sc  € Ø˜~Ñ.ˆØ˜gÑ&ˆØ 	Ñ*ˆØ�9‰9˜ÓØ�~Š~Ø%,¨R¨a [Ñ"�˜
Ø"Ÿn™n×JÑJÈ6ÐSYÐ[eÓf�Ø<GÑ9Ð(¨/Ü\eÐfuÓ\v×wÑQXÐQRÐTX˜q $§*¡*×"3Ñ"3×"FÑ"FÀtÑ"LÑLÐw�Ñwà%)§Z¡Z×%6Ñ%6×%QÑ%QÐ"ä=FÀÓ=W÷&Ù29°!°TÐ[_ÐcuÓ[u�A�{ 1‘~¨Ñ-Ñ-ð&Ð"ò &ð ! ™�Ø"Ÿn™n×JÑJÈ6ÐSYÓZ�Ø+6°q©>Ð(Ø �Ø%'Ð"ØˆGÜ&/Ð0HÓ&Iò 'Ñ"��{ØALÖM°:˜Ÿ™ :Ó.ÐM�ÐMØ(Ÿ_™_¨U°BÓ7�
Ø$6×$:Ñ$:¸5À"Ó$EÐ!à/°$·)±)¸EÓ2BÑBØ#.ØFQÖR¸
˜eŸi™i¨
Ó3ÒRñ�ñ
 Ø+5�F˜<Ñ(à—‘˜vÕ&ð'ô �6‹{˜aÒÜ'Ð(BÀDÇJÁJ×D[ÑD[Ð]kÓlÐlà8<¿¹×8SÑ8SÐT[ÐquÐ8SÓ8vÖw¨f˜ &Ò)ÐwˆGÐwä˜g›,¨Ò*ˆwÐ:°¸±
Ð:ùó? xùó&ùò Nùò Sùò xs$   Á$.HÃH ÃH Ä!H&Å5H+
Ç8H0)NNN)TN)F)r2   r3   r4   r5   Údefault_input_namesÚ_pipeline_calls_generateÚ_load_processorÚ_load_image_processorÚ_load_feature_extractorÚ_load_tokenizerr   Ú_default_generation_configr   rA   rP   rŠ   r0   r˜   r¡   r©   rÁ   Ú__classcell__)rM   s   @r   r9   r9   M   sr   ø„ ñ ðD (Ðà#ÐØ€OØ!ÐØ#ÐØ€Oá!1Øô"Ðñ $IÓ#Jõ Zò$òApôFPód5ó&ó ö"(;r1   r9   )rk   r(   r^   r[   Ú
generationr   Úutilsr   r   r   Úbaser	   r
   r   r   r   ra   Úmodels.auto.modeling_autor   r   r   r9   r6   r1   r   ú<module>rÎ      sk   ðÛ Û ã å )÷ñ ÷
 bÕ añ ÔÛ÷ô2#¨Oô 2#ñj Ñ,¸4Ô@ÓAôp; Xó p;ó Bñp;r1   