
"""simple docstring"""




# 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.
import re

from ..models.auto import AutoProcessor
from ..models.vision_encoder_decoder import VisionEncoderDecoderModel
from ..utils import is_vision_available
from .base import PipelineTool


if is_vision_available():
						from PIL import Image





class 			snake_case  (				__lowercase ):
							UpperCAmelCase__      =   '''naver-clova-ix/donut-base-finetuned-docvqa'''
							UpperCAmelCase__      =   (
							    '''This is a tool that answers a question about an document (pdf). It takes an input named `document` which '''
							    '''should be the document containing the information, as well as a `question` that is the question about the '''
							    '''document. It returns a text that contains the answer to the question.'''
							)
							UpperCAmelCase__      =   '''document_qa'''
							UpperCAmelCase__      =   AutoProcessor
							UpperCAmelCase__      =   VisionEncoderDecoderModel

							UpperCAmelCase__      =   ['''image''', '''text''']
							UpperCAmelCase__      =   ['''text''']

							def __init__(self							,							*SCREAMING_SNAKE_CASE_							,							**SCREAMING_SNAKE_CASE_     ):

									"""simple docstring"""







									if not is_vision_available():
											raise ValueError('''Pillow must be installed to use the DocumentQuestionAnsweringTool.'''     )

									super().__init__(*SCREAMING_SNAKE_CASE_							,							**SCREAMING_SNAKE_CASE_     )

							def _lowercase       (self							,							SCREAMING_SNAKE_CASE_							,							SCREAMING_SNAKE_CASE_     ):

									"""simple docstring"""







									SCREAMING_SNAKE_CASE_    			=			'''<s_docvqa><s_question>{user_input}</s_question><s_answer>'''
									SCREAMING_SNAKE_CASE_    			=			task_prompt.replace('''{user_input}'''							,							SCREAMING_SNAKE_CASE_     )
									SCREAMING_SNAKE_CASE_    			=			self.pre_processor.tokenizer(
									    SCREAMING_SNAKE_CASE_							,							add_special_tokens=SCREAMING_SNAKE_CASE_							,							return_tensors='''pt'''     ).input_ids
									SCREAMING_SNAKE_CASE_    			=			self.pre_processor(SCREAMING_SNAKE_CASE_							,							return_tensors='''pt'''     ).pixel_values

									return {"decoder_input_ids": decoder_input_ids, "pixel_values": pixel_values}

							def _lowercase       (self							,							SCREAMING_SNAKE_CASE_     ):

									"""simple docstring"""







									return self.model.generate(
									    inputs['''pixel_values'''].to(self.device     )							,							decoder_input_ids=inputs['''decoder_input_ids'''].to(self.device     )							,							max_length=self.model.decoder.config.max_position_embeddings							,							early_stopping=SCREAMING_SNAKE_CASE_							,							pad_token_id=self.pre_processor.tokenizer.pad_token_id							,							eos_token_id=self.pre_processor.tokenizer.eos_token_id							,							use_cache=SCREAMING_SNAKE_CASE_							,							num_beams=1							,							bad_words_ids=[[self.pre_processor.tokenizer.unk_token_id]]							,							return_dict_in_generate=SCREAMING_SNAKE_CASE_							,							).sequences







							def _lowercase       (self							,							SCREAMING_SNAKE_CASE_     ):

									"""simple docstring"""







									SCREAMING_SNAKE_CASE_    			=			self.pre_processor.batch_decode(SCREAMING_SNAKE_CASE_     )[0]
									SCREAMING_SNAKE_CASE_    			=			sequence.replace(self.pre_processor.tokenizer.eos_token							,							''''''     )
									SCREAMING_SNAKE_CASE_    			=			sequence.replace(self.pre_processor.tokenizer.pad_token							,							''''''     )
									SCREAMING_SNAKE_CASE_    			=			re.sub(R'''<.*?>'''							,							''''''							,							SCREAMING_SNAKE_CASE_							,							count=1     ).strip()  # remove first task start token
									SCREAMING_SNAKE_CASE_    			=			self.pre_processor.tokenajson(SCREAMING_SNAKE_CASE_     )

									return sequence["answer"]

"""simple docstring"""




import logging

import numpy as np
import pytest
from scipy.linalg import eigh

logging.basicConfig(level=logging.INFO, format='%(message)s')



def 							_lowerCamelCase			(			__a     ):
		return input_array.reshape((input_array.size, 1)     )



def 							_lowerCamelCase			(			__a,				__a,				__a     ):
		SCREAMING_SNAKE_CASE_    			=			np.nan
		for i in range(__a     ):
				SCREAMING_SNAKE_CASE_    			=			features[:, labels == i]
				SCREAMING_SNAKE_CASE_    			=			data.mean(1     )
				# Centralize the data of class i
				SCREAMING_SNAKE_CASE_    			=			data - column_reshape(__a     )
				if i > 0:
						# If covariance_sum is not None
						covariance_sum += np.dot(__a,				centered_data.T     )
				else:
						# If covariance_sum is np.nan (i.e. first loop)
						SCREAMING_SNAKE_CASE_    			=			np.dot(__a,				centered_data.T     )

		return covariance_sum / features.shape[1]



def 							_lowerCamelCase			(			__a,				__a,				__a     ):
		SCREAMING_SNAKE_CASE_    			=			features.mean(1     )
		SCREAMING_SNAKE_CASE_    			=			np.nan
		for i in range(__a     ):
				SCREAMING_SNAKE_CASE_    			=			features[:, labels == i]
				SCREAMING_SNAKE_CASE_    			=			data.shape[1]
				SCREAMING_SNAKE_CASE_    			=			data.mean(1     )
				if i > 0:
						# If covariance_sum is not None
						covariance_sum += device_data * np.dot(
						    column_reshape(__a     ) - column_reshape(__a     ),				(column_reshape(__a     ) - column_reshape(__a     )).T,				)
				else:
						# If covariance_sum is np.nan (i.e. first loop)
						SCREAMING_SNAKE_CASE_    			=			device_data * np.dot(
						    column_reshape(__a     ) - column_reshape(__a     ),				(column_reshape(__a     ) - column_reshape(__a     )).T,				)

		return covariance_sum / features.shape[1]



def 							_lowerCamelCase			(			__a,				__a     ):

		# Check if the features have been loaded
		if features.any():
				SCREAMING_SNAKE_CASE_    			=			features.mean(1     )
				# Center the dataset
				SCREAMING_SNAKE_CASE_    			=			features - np.reshape(__a,				(data_mean.size, 1)     )
				SCREAMING_SNAKE_CASE_    			=			np.dot(__a,				centered_data.T     ) / features.shape[1]
				SCREAMING_SNAKE_CASE_			,SCREAMING_SNAKE_CASE_    			=			np.linalg.eigh(__a     )
				# Take all the columns in the reverse order (-1), and then takes only the first
				SCREAMING_SNAKE_CASE_    			=			eigenvectors[:, ::-1][:, 0:dimensions]
				# Project the database on the new space
				SCREAMING_SNAKE_CASE_    			=			np.dot(filtered_eigenvectors.T,				__a     )
				logging.info('''Principal Component Analysis computed'''     )

				return projected_data
		else:
				logging.basicConfig(level=logging.ERROR,				format='''%(message)s''',				force=__a     )
				logging.error('''Dataset empty'''     )
				raise AssertionError



def 							_lowerCamelCase			(			__a,				__a,				__a,				__a     ):
		assert classes > dimensions

		# Check if features have been already loaded
		if features.any:
				SCREAMING_SNAKE_CASE_			,SCREAMING_SNAKE_CASE_    			=			eigh(
				    covariance_between_classes(__a,				__a,				__a     ),				covariance_within_classes(__a,				__a,				__a     ),				)
				SCREAMING_SNAKE_CASE_    			=			eigenvectors[:, ::-1][:, :dimensions]
				SCREAMING_SNAKE_CASE_			,SCREAMING_SNAKE_CASE_			,SCREAMING_SNAKE_CASE_    			=			np.linalg.svd(__a     )
				SCREAMING_SNAKE_CASE_    			=			svd_matrix[:, 0:dimensions]
				SCREAMING_SNAKE_CASE_    			=			np.dot(filtered_svd_matrix.T,				__a     )
				logging.info('''Linear Discriminant Analysis computed'''     )

				return projected_data
		else:
				logging.basicConfig(level=logging.ERROR,				format='''%(message)s''',				force=__a     )
				logging.error('''Dataset empty'''     )
				raise AssertionError



def 							_lowerCamelCase			(			):
		# Create dummy dataset with 2 classes and 3 features
		SCREAMING_SNAKE_CASE_    			=			np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]]     )
		SCREAMING_SNAKE_CASE_    			=			np.array([0, 0, 0, 1, 1]     )
		SCREAMING_SNAKE_CASE_    			=			2
		SCREAMING_SNAKE_CASE_    			=			2

		# Assert that the function raises an AssertionError if dimensions > classes
		with pytest.raises(__a     ) as error_info:
				SCREAMING_SNAKE_CASE_    			=			linear_discriminant_analysis(
				    __a,				__a,				__a,				__a     )
				if isinstance(__a,				np.ndarray     ):
						raise AssertionError(
						    '''Did not raise AssertionError for dimensions > classes'''     )
				assert error_info.type is AssertionError



def 							_lowerCamelCase			(			):
		SCREAMING_SNAKE_CASE_    			=			np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]     )
		SCREAMING_SNAKE_CASE_    			=			2
		SCREAMING_SNAKE_CASE_    			=			np.array([[6.9_2_8_2_0_3_2_3, 8.6_6_0_2_5_4_0_4, 1_0.3_9_2_3_0_4_8_5], [3.0, 3.0, 3.0]]     )

		with pytest.raises(__a     ) as error_info:
				SCREAMING_SNAKE_CASE_    			=			principal_component_analysis(__a,				__a     )
				if not np.allclose(__a,				__a     ):
						raise AssertionError
				assert error_info.type is AssertionError


if __name__ == "__main__":
						import doctest

						doctest.testmod()