




# 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_     :    Optional[Any]      =			'Here is a text containing a lot of information: \'\'\'{text}\'\'\'.\n\nCan you answer this question about the text: \'{question}\''






class    __lowerCAmelCase			(	UpperCAmelCase__			):
			snake_case_				:			Union[str, Any]								=					"google/flan-t5-base"
			snake_case_				:			Optional[int]								=					(
			    "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."
			)
			snake_case_				:			Dict								=					"text_qa"
			snake_case_				:			Optional[Any]								=					AutoTokenizer
			snake_case_				:			List[Any]								=					AutoModelForSeqaSeqLM

			snake_case_				:			Dict								=					["text", "text"]
			snake_case_				:			Union[str, Any]								=					["text"]







			def UpperCamelCase      (	self   :      Dict   ,   snake_case__   :      str   ,   snake_case__   :      str				):




									"""simple docstring"""


									_UpperCAmelCase													=					QA_PROMPT.format(text=snake_case__   ,   question=snake_case__				)
									return self.pre_processor(snake_case__   ,   return_tensors="pt"				)







			def UpperCamelCase      (	self   :      str   ,   snake_case__   :      int				):




									"""simple docstring"""


									_UpperCAmelCase													=					self.model.generate(**snake_case__				)

									_UpperCAmelCase							,			_UpperCAmelCase													=					inputs["input_ids"].shape
									_UpperCAmelCase													=					output_ids.shape[0]

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







			def UpperCamelCase      (	self   :      Any   ,   snake_case__   :      Tuple				):




									"""simple docstring"""


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










import itertools
from dataclasses import dataclass
from typing import Optional

import pyarrow as pa

import datasets
from datasets.table import table_cast


lowercase_     :    Union[str, Any]      =			datasets.utils.logging.get_logger(__name__)






@dataclass
class    __lowerCAmelCase			(	datasets.BuilderConfig			):
			snake_case_				:			Optional[datasets.Features]								=					None






class    __lowerCAmelCase			(	datasets.ArrowBasedBuilder			):
			snake_case_				:			str								=					ArrowConfig







			def UpperCamelCase      (	self   :      Optional[int]				):




									"""simple docstring"""


									return datasets.DatasetInfo(features=self.config.features				)







			def UpperCamelCase      (	self   :      str   ,   snake_case__   :      Optional[int]				):




									"""simple docstring"""


									if not self.config.data_files:
															raise ValueError(F"""At least one data file must be specified, but got data_files={self.config.data_files}"""				)
									_UpperCAmelCase													=					dl_manager.download_and_extract(self.config.data_files				)
									if isinstance(snake_case__   ,   (str, list, tuple)				):
															_UpperCAmelCase													=					data_files
															if isinstance(snake_case__   ,   snake_case__				):
																					_UpperCAmelCase													=					[files]
															# Use `dl_manager.iter_files` to skip hidden files in an extracted archive
															_UpperCAmelCase													=					[dl_manager.iter_files(snake_case__				) for file in files]
															return [datasets.SplitGenerator(name=datasets.Split.TRAIN   ,   gen_kwargs={"files": files}				)]
									_UpperCAmelCase													=					[]
									for split_name, files in data_files.items():
															if isinstance(snake_case__   ,   snake_case__				):
																					_UpperCAmelCase													=					[files]
															# Use `dl_manager.iter_files` to skip hidden files in an extracted archive
															_UpperCAmelCase													=					[dl_manager.iter_files(snake_case__				) for file in files]
															# Infer features is they are stoed in the arrow schema
															if self.info.features is None:
																					for file in itertools.chain.from_iterable(snake_case__				):
																											with open(snake_case__   ,   "rb"				) as f:
																																	_UpperCAmelCase													=					datasets.Features.from_arrow_schema(pa.ipc.open_stream(snake_case__				).schema				)
																											break
															splits.append(datasets.SplitGenerator(name=snake_case__   ,   gen_kwargs={"files": files}				)				)
									return splits







			def UpperCamelCase      (	self   :      int   ,   snake_case__   :      pa.Table				):




									"""simple docstring"""


									if self.info.features is not None:
															# more expensive cast to support nested features with keys in a different order
															# allows str <-> int/float or str to Audio for example
															_UpperCAmelCase													=					table_cast(snake_case__   ,   self.info.features.arrow_schema				)
									return pa_table







			def UpperCamelCase      (	self   :      Optional[Any]   ,   snake_case__   :      int				):




									"""simple docstring"""


									for file_idx, file in enumerate(itertools.chain.from_iterable(snake_case__				)				):
															with open(snake_case__   ,   "rb"				) as f:
																					try:
																											for batch_idx, record_batch in enumerate(pa.ipc.open_stream(snake_case__				)				):
																																	_UpperCAmelCase													=					pa.Table.from_batches([record_batch]				)
																																	# Uncomment for debugging (will print the Arrow table size and elements)
																																	# logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
																																	# logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
																																	yield F"""{file_idx}_{batch_idx}""", self._cast_table(snake_case__				)
																					except ValueError as e:
																											logger.error(F"""Failed to read file '{file}' with error {type(snake_case__				)}: {e}"""				)
																											raise




