






import ast
import os
import re
import shutil
import tempfile
import unittest
from unittest import mock

import torch

from accelerate.test_utils.examples import compare_against_test
from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow
from accelerate.utils import write_basic_config


# DataLoaders built from `test_samples/MRPC` for quick testing
# Should mock `{script_name}.get_dataloaders` via:
# @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders)

UpperCamelCase			    =     [
    '''cross_validation.py''',
    '''gradient_accumulation.py''',
    '''local_sgd.py''',
    '''multi_process_metrics.py''',
    '''memory.py''',
    '''automatic_gradient_accumulation.py''',
    '''fsdp_with_peak_mem_tracking.py''',
    '''deepspeed_with_config_support.py''',
    '''megatron_lm_gpt_pretraining.py''',
]



class 				__UpperCAmelCase		(unittest.TestCase   ):







			def 							UpperCamelCase				(     self:  Tuple				,     UpperCAmelCase_:  str				,     UpperCAmelCase_:  bool				,     UpperCAmelCase_:  str = None				,     UpperCAmelCase_:  list = None					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  None
									_SCREAMING_SNAKE_CASE     				=  os.path.abspath(os.path.join("""examples"""				,     """by_feature"""					)					)
									_SCREAMING_SNAKE_CASE     				=  os.path.abspath("""examples"""					)
									for item in os.listdir(UpperCAmelCase_					):
															if item not in EXCLUDE_EXAMPLES:
																					_SCREAMING_SNAKE_CASE     				=  os.path.join(UpperCAmelCase_				,     UpperCAmelCase_					)
																					if os.path.isfile(UpperCAmelCase_					) and ".py" in item_path:
																											with self.subTest(
																											    tested_script=UpperCAmelCase_				,     feature_script=UpperCAmelCase_				,     tested_section="""main()""" if parser_only else """training_function()"""				,     ):
																																	_SCREAMING_SNAKE_CASE     				=  compare_against_test(
																																	    os.path.join(UpperCAmelCase_				,     UpperCAmelCase_					)				,     UpperCAmelCase_				,     UpperCAmelCase_				,     UpperCAmelCase_					)
																																	_SCREAMING_SNAKE_CASE     				=  """\n""".join(UpperCAmelCase_					)
																																	if special_strings is not None:
																																							for string in special_strings:
																																													_SCREAMING_SNAKE_CASE     				=  diff.replace(UpperCAmelCase_				,     """"""					)
																																	self.assertEqual(UpperCAmelCase_				,     """"""					)







			def 							UpperCamelCase				(     self:  List[str]					):







									'''simple docstring'''




									self.one_complete_example("""complete_nlp_example.py"""				,     UpperCAmelCase_					)
									self.one_complete_example("""complete_nlp_example.py"""				,     UpperCAmelCase_					)







			def 							UpperCamelCase				(     self:  Dict					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  os.path.abspath(os.path.join("""examples"""				,     """cv_example.py"""					)					)
									_SCREAMING_SNAKE_CASE     				=  [
									    """ """ * 16 + """{\n\n""",
									    """ """ * 20 + """\"accuracy\": eval_metric[\"accuracy\"],\n\n""",
									    """ """ * 20 + """\"f1\": eval_metric[\"f1\"],\n\n""",
									    """ """ * 20 + """\"train_loss\": total_loss.item() / len(train_dataloader),\n\n""",
									    """ """ * 20 + """\"epoch\": epoch,\n\n""",
									    """ """ * 16 + """},\n\n""",
									    """ """ * 16 + """step=epoch,\n""",
									    """ """ * 12,
									    """ """ * 8 + """for step, batch in enumerate(active_dataloader):\n""",
									]
									self.one_complete_example("""complete_cv_example.py"""				,     UpperCAmelCase_				,     UpperCAmelCase_				,     UpperCAmelCase_					)
									self.one_complete_example("""complete_cv_example.py"""				,     UpperCAmelCase_				,     UpperCAmelCase_				,     UpperCAmelCase_					)



@mock.patch.dict(os.environ	,{"TESTING_MOCKED_DATALOADERS": "1"}   )
class 				__UpperCAmelCase		(_UpperCAmelCase   ):
			__snake_case    :				Any									=							False







			@classmethod
			def 							UpperCamelCase				(     cls:  List[Any]					):







									'''simple docstring'''




									super().setUpClass()
									_SCREAMING_SNAKE_CASE     				=  tempfile.mkdtemp()
									_SCREAMING_SNAKE_CASE     				=  os.path.join(cls._tmpdir				,     """default_config.yml"""					)

									write_basic_config(save_location=cls.configPath					)
									_SCREAMING_SNAKE_CASE     				=  ["""accelerate""", """launch""", """--config_file""", cls.configPath]







			@classmethod
			def 							UpperCamelCase				(     cls:  Optional[Any]					):







									'''simple docstring'''




									super().tearDownClass()
									shutil.rmtree(cls._tmpdir					)







			def 							UpperCamelCase				(     self:  int					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  F'\n        examples/by_feature/checkpointing.py\n        --checkpointing_steps epoch\n        --output_dir {self.tmpdir}\n        '.split()
									run_command(self._launch_args + testargs					)
									self.assertTrue(os.path.exists(os.path.join(self.tmpdir				,     """epoch_0"""					)					)					)







			def 							UpperCamelCase				(     self:  int					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  F'\n        examples/by_feature/checkpointing.py\n        --checkpointing_steps 1\n        --output_dir {self.tmpdir}\n        '.split()
									_SCREAMING_SNAKE_CASE     				=  run_command(self._launch_args + testargs					)
									self.assertTrue(os.path.exists(os.path.join(self.tmpdir				,     """step_2"""					)					)					)







			def 							UpperCamelCase				(     self:  Optional[int]					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  F'\n        examples/by_feature/checkpointing.py\n        --resume_from_checkpoint {os.path.join(self.tmpdir				,     "epoch_0"					)}\n        '.split()
									_SCREAMING_SNAKE_CASE     				=  run_command(self._launch_args + testargs				,     return_stdout=UpperCAmelCase_					)
									self.assertNotIn("""epoch 0:"""				,     UpperCAmelCase_					)
									self.assertIn("""epoch 1:"""				,     UpperCAmelCase_					)







			def 							UpperCamelCase				(     self:  Union[str, Any]					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  F'\n        examples/by_feature/checkpointing.py\n        --resume_from_checkpoint {os.path.join(self.tmpdir				,     "step_2"					)}\n        '.split()
									_SCREAMING_SNAKE_CASE     				=  run_command(self._launch_args + testargs				,     return_stdout=UpperCAmelCase_					)
									if torch.cuda.is_available():
															_SCREAMING_SNAKE_CASE     				=  torch.cuda.device_count()
									else:
															_SCREAMING_SNAKE_CASE     				=  1
									if num_processes > 1:
															self.assertNotIn("""epoch 0:"""				,     UpperCAmelCase_					)
															self.assertIn("""epoch 1:"""				,     UpperCAmelCase_					)
									else:
															self.assertIn("""epoch 0:"""				,     UpperCAmelCase_					)
															self.assertIn("""epoch 1:"""				,     UpperCAmelCase_					)







			@slow
			def 							UpperCamelCase				(     self:  Optional[int]					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  """
        examples/by_feature/cross_validation.py
        --num_folds 2
        """.split()
									with mock.patch.dict(os.environ				,     {"""TESTING_MOCKED_DATALOADERS""": """0"""}					):
															_SCREAMING_SNAKE_CASE     				=  run_command(self._launch_args + testargs				,     return_stdout=UpperCAmelCase_					)
															_SCREAMING_SNAKE_CASE     				=  re.findall("""({.+})"""				,     UpperCAmelCase_					)
															_SCREAMING_SNAKE_CASE     				=  [r for r in results if """accuracy""" in r][-1]
															_SCREAMING_SNAKE_CASE     				=  ast.literal_eval(UpperCAmelCase_					)
															self.assertGreaterEqual(results["""accuracy"""]				,     0.75					)







			def 							UpperCamelCase				(     self:  List[Any]					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  ["""examples/by_feature/multi_process_metrics.py"""]
									run_command(self._launch_args + testargs					)







			@require_trackers
			@mock.patch.dict(os.environ				,     {"""WANDB_MODE""": """offline"""}					)
			def 							UpperCamelCase				(     self:  str					):







									'''simple docstring'''




									with tempfile.TemporaryDirectory() as tmpdir:
															_SCREAMING_SNAKE_CASE     				=  F'\n            examples/by_feature/tracking.py\n            --with_tracking\n            --project_dir {tmpdir}\n            '.split()
															run_command(self._launch_args + testargs					)
															self.assertTrue(os.path.exists(os.path.join(UpperCAmelCase_				,     """tracking"""					)					)					)







			def 							UpperCamelCase				(     self:  Any					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  ["""examples/by_feature/gradient_accumulation.py"""]
									run_command(self._launch_args + testargs					)







			def 							UpperCamelCase				(     self:  Union[str, Any]					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  ["""examples/by_feature/local_sgd.py"""]
									run_command(self._launch_args + testargs					)









# 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 				__UpperCAmelCase		(_UpperCAmelCase   ):
			__snake_case    :				Dict									=							"naver-clova-ix/donut-base-finetuned-docvqa"
			__snake_case    :				Dict									=							(
			    "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."
			)
			__snake_case    :				Dict									=							"document_qa"
			__snake_case    :				Any									=							AutoProcessor
			__snake_case    :				int									=							VisionEncoderDecoderModel

			__snake_case    :				Union[str, Any]									=							["image", "text"]
			__snake_case    :				Optional[int]									=							["text"]







			def __init__(     self:  List[Any]				,     *UpperCAmelCase_:  Optional[int]				,     **UpperCAmelCase_:  List[str]					):







									'''simple docstring'''




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

									super().__init__(*UpperCAmelCase_				,     **UpperCAmelCase_					)







			def 							UpperCamelCase				(     self:  Optional[int]				,     UpperCAmelCase_:  "Image"				,     UpperCAmelCase_:  str					):







									'''simple docstring'''




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

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







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







									'''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=UpperCAmelCase_				,     pad_token_id=self.pre_processor.tokenizer.pad_token_id				,     eos_token_id=self.pre_processor.tokenizer.eos_token_id				,     use_cache=UpperCAmelCase_				,     num_beams=1				,     bad_words_ids=[[self.pre_processor.tokenizer.unk_token_id]]				,     return_dict_in_generate=UpperCAmelCase_				,     ).sequences







			def 							UpperCamelCase				(     self:  Dict				,     UpperCAmelCase_:  Tuple					):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE     				=  self.pre_processor.batch_decode(UpperCAmelCase_					)[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"""<.*?>"""				,     """"""				,     UpperCAmelCase_				,     count=1					).strip()  # remove first task start token
									_SCREAMING_SNAKE_CASE     				=  self.pre_processor.tokenajson(UpperCAmelCase_					)

									return sequence["answer"]

