





# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer
from .base import PipelineTool


__lowercase				    =      """Here is a text containing a lot of information: '''{text}'''.

Can you answer this question about the text: '{question}'"""

class 	__snake_case					(      _a ):






    '''simple docstring'''
    _lowerCAmelCase  =						"""google/flan-t5-base"""
    _lowerCAmelCase  =						(
        """This is a tool that answers questions related to a text. It takes two arguments named `text`, which is the """
        """text where to find the answer, and `question`, which is the question, and returns the answer to the question."""
    )
    _lowerCAmelCase  =						"""text_qa"""
    _lowerCAmelCase  =						AutoTokenizer
    _lowerCAmelCase  =						AutoModelForSeqaSeqLM

    _lowerCAmelCase  =						["""text""", """text"""]
    _lowerCAmelCase  =						["""text"""]





    def 						A		( self    :		List[Any]      ,    snake_case    :		str      ,    snake_case    :		str				):

      """simple docstring"""





      __lowerCAmelCase								=					QA_PROMPT.format(text=snake_case      ,    question=snake_case				)
      return self.pre_processor(snake_case      ,    return_tensors='''pt'''				)





    def 						A		( self    :		Union[str, Any]      ,    snake_case    :		Optional[Any]				):

      """simple docstring"""





      __lowerCAmelCase								=					self.model.generate(**snake_case				)

      __lowerCAmelCase						,    __lowerCAmelCase								=					inputs['''input_ids'''].shape
      __lowerCAmelCase								=					output_ids.shape[0]

      return output_ids.reshape(snake_case      ,    out_b // in_b      ,    *output_ids.shape[1:]				)[0][0]





    def 						A		( self    :		Union[str, Any]      ,    snake_case    :		List[str]				):

      """simple docstring"""





      return self.pre_processor.decode(snake_case      ,    skip_special_tokens=snake_case      ,    clean_up_tokenization_spaces=snake_case				)







import json
import os
import tempfile

import datasets
from datasets.arrow_writer import ArrowWriter
from datasets.features import ArrayaD
from utils import generate_examples, get_duration


__lowercase				    =      (30, 487)
__lowercase				    =      (36, 1_024)
__lowercase				    =      (100, 100)
__lowercase				    =      100

__lowercase				    =      datasets.Features(
    {"""text""": ArrayaD(SHAPE_TEST_1, dtype="""float32"""), """image""": ArrayaD(SHAPE_TEST_2, dtype="""float32""")}
)

__lowercase    ,							__lowercase				    =      os.path.split(__file__)
__lowercase				    =      os.path.join(RESULTS_BASEPATH, """results""", RESULTS_FILENAME.replace(""".py""", """.json"""))


@get_duration
def        __SCREAMING_SNAKE_CASE	(				__lowercase:		Any  ,				__lowercase:		Optional[Any]  ,				__lowercase:		List[Any]):



  '''simple docstring'''






  with ArrowWriter(features=__lowercase  ,				path=os.path.join(__lowercase  ,				'''beta.arrow''')) as writer:
    for key, record in dummy_data:
      __lowerCAmelCase								=					my_features.encode_example(__lowercase)
      writer.write(__lowercase)
    __lowerCAmelCase						,    __lowerCAmelCase								=					writer.finalize()


@get_duration
def        __SCREAMING_SNAKE_CASE	(				__lowercase:		str  ,				__lowercase:		str):



  '''simple docstring'''






  __lowerCAmelCase								=					datasets.Dataset.from_file(
      filename=os.path.join(__lowercase  ,				'''beta.arrow''')  ,				info=datasets.DatasetInfo(features=__lowercase))
  for _ in dataset:
    pass


@get_duration
def        __SCREAMING_SNAKE_CASE	(				__lowercase:		Tuple  ,				__lowercase:		str):



  '''simple docstring'''






  __lowerCAmelCase								=					datasets.Dataset.from_file(
      filename=os.path.join(__lowercase  ,				'''beta.arrow''')  ,				info=datasets.DatasetInfo(features=__lowercase))
  dataset.set_format('''numpy''')
  for _ in dataset:
    pass


@get_duration
def        __SCREAMING_SNAKE_CASE	(				__lowercase:		str  ,				__lowercase:		Dict):



  '''simple docstring'''






  __lowerCAmelCase								=					10
  __lowerCAmelCase								=					datasets.Dataset.from_file(
      filename=os.path.join(__lowercase  ,				'''beta.arrow''')  ,				info=datasets.DatasetInfo(features=__lowercase))
  for i in range(0  ,				len(__lowercase)  ,				__lowercase):
    __lowerCAmelCase								=					dataset[i : i + batch_size]


@get_duration
def        __SCREAMING_SNAKE_CASE	(				__lowercase:		List[Any]  ,				__lowercase:		Union[str, Any]):



  '''simple docstring'''






  __lowerCAmelCase								=					10
  __lowerCAmelCase								=					datasets.Dataset.from_file(
      filename=os.path.join(__lowercase  ,				'''beta.arrow''')  ,				info=datasets.DatasetInfo(features=__lowercase))
  dataset.set_format('''numpy''')
  for i in range(0  ,				len(__lowercase)  ,				__lowercase):
    __lowerCAmelCase								=					dataset[i : i + batch_size]


@get_duration
def        __SCREAMING_SNAKE_CASE	(				__lowercase:		Union[str, Any]  ,				__lowercase:		str):



  '''simple docstring'''






  __lowerCAmelCase								=					datasets.Dataset.from_file(
      filename=os.path.join(__lowercase  ,				'''beta.arrow''')  ,				info=datasets.DatasetInfo(features=__lowercase))
  for col in feats:
    __lowerCAmelCase								=					dataset[col]


@get_duration
def        __SCREAMING_SNAKE_CASE	(				__lowercase:		Optional[int]  ,				__lowercase:		Optional[Any]):



  '''simple docstring'''






  __lowerCAmelCase								=					datasets.Dataset.from_file(
      filename=os.path.join(__lowercase  ,				'''beta.arrow''')  ,				info=datasets.DatasetInfo(features=__lowercase))
  dataset.set_format('''numpy''')
  for col in feats:
    __lowerCAmelCase								=					dataset[col]


def        __SCREAMING_SNAKE_CASE	(				):



  '''simple docstring'''






  __lowerCAmelCase								=					{}
  __lowerCAmelCase								=					(
      read_unformated,
      read_formatted_as_numpy,
      read_batch_unformated,
      read_batch_formatted_as_numpy,
      read_col_unformated,
      read_col_formatted_as_numpy,
  )
  with tempfile.TemporaryDirectory() as tmp_dir:
    __lowerCAmelCase								=					datasets.Features({'''image''': ArrayaD(__lowercase  ,				dtype='''float32''')})
    __lowerCAmelCase								=					generate_examples(features=__lowercase  ,				num_examples=__lowercase)
    __lowerCAmelCase								=					write(__lowercase  ,				__lowercase  ,				__lowercase)
    for read_func in read_functions:
      __lowerCAmelCase								=					read_func(__lowercase  ,				__lowercase)

  with tempfile.TemporaryDirectory() as tmp_dir:
    # don't use fixed length for fair comparison
    # feats = datasets.Features(
    #     {"image": datasets.Sequence(datasets.Sequence(datasets.Value("float32"), SPEED_TEST_SHAPE[1]), SPEED_TEST_SHAPE[0])}
    # )
    __lowerCAmelCase								=					datasets.Features({'''image''': datasets.Sequence(datasets.Sequence(datasets.Value('''float32''')))})
    __lowerCAmelCase								=					generate_examples(
        features=__lowercase  ,				num_examples=__lowercase  ,				seq_shapes={'''image''': SPEED_TEST_SHAPE})
    __lowerCAmelCase								=					write(__lowercase  ,				__lowercase  ,				__lowercase)
    for read_func in read_functions:
      __lowerCAmelCase								=					read_func(__lowercase  ,				__lowercase)

  with tempfile.TemporaryDirectory() as tmp_dir:
    # don't use fixed length for fair comparison
    # feats = datasets.Features(
    #     {"image": datasets.Sequence(datasets.Value("float32"), SPEED_TEST_SHAPE[0] * SPEED_TEST_SHAPE[1])}
    # )
    __lowerCAmelCase								=					datasets.Features({'''image''': datasets.Sequence(datasets.Value('''float32'''))})
    __lowerCAmelCase								=					generate_examples(
        features=__lowercase  ,				num_examples=__lowercase  ,				seq_shapes={'''image''': [SPEED_TEST_SHAPE[0] * SPEED_TEST_SHAPE[1]]}  ,				)
    __lowerCAmelCase								=					write(__lowercase  ,				__lowercase  ,				__lowercase)
    for read_func in read_functions:
      __lowerCAmelCase								=					read_func(__lowercase  ,				__lowercase)

  with open(__lowercase  ,				'''wb''') as f:
    f.write(json.dumps(__lowercase).encode('''utf-8'''))


if __name__ == "__main__":  # useful to run the profiler
      benchmark_array_xd()
