


import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError

from transformers import AutoImageProcessor, ViTImageProcessor
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test


sys.path.append(str(Path(__file__).parent.parent / "utils"))

from test_module.custom_image_processing import CustomImageProcessor  # noqa E402


_snake_case  :	Union[str, Any]			      =       get_tests_dir("fixtures")

class        a	(unittest.TestCase   ):




							"""simple docstring"""


							def 					__snake_case      (							self :						Any       )			->					Union[str, Any]:
														__snake_case	:    Any											=     mock.Mock()
														__snake_case	:    List[str]											=     500
														__snake_case	:    List[str]											=     {}
														__snake_case	:    Optional[Any]											=     HTTPError
														__snake_case	:    str											=     {}

														# Download this model to make sure it's in the cache.
														__snake_case	:    List[Any]											=     ViTImageProcessor.from_pretrained("hf-internal-testing/tiny-random-vit"       )
														# Under the mock environment we get a 500 error when trying to reach the model.
														with mock.patch("requests.Session.request"					,			return_value=__A       ) as mock_head:
																					__snake_case	:    Optional[Any]											=     ViTImageProcessor.from_pretrained("hf-internal-testing/tiny-random-vit"       )
																					# This check we did call the fake head request
																					mock_head.assert_called()

							def 					__snake_case      (							self :						Dict       )			->					List[str]:
														__snake_case	:    str											=     ViTImageProcessor.from_pretrained(
														    "https://huggingface.co/hf-internal-testing/tiny-random-vit/resolve/main/preprocessor_config.json"       )






							def 					__snake_case      (							self :						List[Any]       )			->					Optional[int]:



														with self.assertRaises(__A       ):
																					# config is in subfolder, the following should not work without specifying the subfolder
																					__snake_case	:    Union[str, Any]											=     AutoImageProcessor.from_pretrained("hf-internal-testing/stable-diffusion-all-variants"       )

														__snake_case	:    List[str]											=     AutoImageProcessor.from_pretrained(
														    "hf-internal-testing/stable-diffusion-all-variants"					,			subfolder="feature_extractor"       )

														self.assertIsNotNone(__A       )

@is_staging_test
class        a	(unittest.TestCase   ):




							"""simple docstring"""


							@classmethod
							def 					__snake_case      (							cls :						int       )			->					str:
														__snake_case	:    Optional[int]											=     TOKEN
														HfFolder.save_token(__A       )

							@classmethod
							def 					__snake_case      (							cls :						Optional[int]       )			->					Optional[Any]:



														try:
																					delete_repo(token=cls._token					,			repo_id="test-image-processor"       )
														except HTTPError:
																					pass

														try:
																					delete_repo(token=cls._token					,			repo_id="valid_org/test-image-processor-org"       )
														except HTTPError:
																					pass

														try:
																					delete_repo(token=cls._token					,			repo_id="test-dynamic-image-processor"       )
														except HTTPError:
																					pass

							def 					__snake_case      (							self :						Tuple       )			->					List[str]:
														__snake_case	:    Tuple											=     ViTImageProcessor.from_pretrained(__A       )
														image_processor.push_to_hub("test-image-processor"					,			use_auth_token=self._token       )

														__snake_case	:    int											=     ViTImageProcessor.from_pretrained(F'{USER}/test-image-processor'       )
														for k, v in image_processor.__dict__.items():
																					self.assertEqual(__A					,			getattr(__A					,			__A       )       )

														# Reset repo
														delete_repo(token=self._token					,			repo_id="test-image-processor"       )

														# Push to hub via save_pretrained
														with tempfile.TemporaryDirectory() as tmp_dir:
																					image_processor.save_pretrained(
																					    __A					,			repo_id="test-image-processor"					,			push_to_hub=__A					,			use_auth_token=self._token       )

														__snake_case	:    str											=     ViTImageProcessor.from_pretrained(F'{USER}/test-image-processor'       )
														for k, v in image_processor.__dict__.items():
																					self.assertEqual(__A					,			getattr(__A					,			__A       )       )

							def 					__snake_case      (							self :						int       )			->					Optional[int]:
														__snake_case	:    Union[str, Any]											=     ViTImageProcessor.from_pretrained(__A       )
														image_processor.push_to_hub("valid_org/test-image-processor"					,			use_auth_token=self._token       )

														__snake_case	:    Union[str, Any]											=     ViTImageProcessor.from_pretrained("valid_org/test-image-processor"       )
														for k, v in image_processor.__dict__.items():
																					self.assertEqual(__A					,			getattr(__A					,			__A       )       )

														# Reset repo
														delete_repo(token=self._token					,			repo_id="valid_org/test-image-processor"       )

														# Push to hub via save_pretrained
														with tempfile.TemporaryDirectory() as tmp_dir:
																					image_processor.save_pretrained(
																					    __A					,			repo_id="valid_org/test-image-processor-org"					,			push_to_hub=__A					,			use_auth_token=self._token       )

														__snake_case	:    str											=     ViTImageProcessor.from_pretrained("valid_org/test-image-processor-org"       )
														for k, v in image_processor.__dict__.items():
																					self.assertEqual(__A					,			getattr(__A					,			__A       )       )






							def 					__snake_case      (							self :						Optional[Any]       )			->					int:
														CustomImageProcessor.register_for_auto_class()
														__snake_case	:    Optional[Any]											=     CustomImageProcessor.from_pretrained(__A       )

														image_processor.push_to_hub("test-dynamic-image-processor"					,			use_auth_token=self._token       )

														# This has added the proper auto_map field to the config
														self.assertDictEqual(
														    image_processor.auto_map					,			{"AutoImageProcessor": "custom_image_processing.CustomImageProcessor"}					,			)

														__snake_case	:    Union[str, Any]											=     AutoImageProcessor.from_pretrained(
														    F'{USER}/test-dynamic-image-processor'					,			trust_remote_code=__A       )
														# Can't make an isinstance check because the new_image_processor is from the CustomImageProcessor class of a dynamic module
														self.assertEqual(new_image_processor.__class__.__name__					,			"CustomImageProcessor"       )





import unittest

from transformers import (
    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TextClassificationPipeline,
    pipeline,
)
from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow

from .test_pipelines_common import ANY


# These 2 model types require different inputs than those of the usual text models.
_snake_case  :	Dict			      =       {"LayoutLMv2Config", "LayoutLMv3Config"}

@is_pipeline_test
class        a	(unittest.TestCase   ):




							"""simple docstring"""


							__UpperCAmelCase					:							Union[str, Any]  						=						MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
							__UpperCAmelCase					:							Optional[int]  						=						TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

							if model_mapping is not None:
														__UpperCAmelCase					:							Optional[int]  						=						{config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
							if tf_model_mapping is not None:
														__UpperCAmelCase					:							Any  						=						{
														    config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
														}

							@require_torch
							def 					__snake_case      (							self :						str       )			->					str:
														__snake_case	:    Dict											=     pipeline(
														    task="text-classification"					,			model="hf-internal-testing/tiny-random-distilbert"					,			framework="pt"       )

														__snake_case	:    Optional[Any]											=     text_classifier("This is great !"       )
														self.assertEqual(nested_simplify(lowerCamelCase       )					,			[{"label": "LABEL_0", "score": 0.5_04}]       )

														__snake_case	:    Any											=     text_classifier("This is great !"					,			top_k=2       )
														self.assertEqual(
														    nested_simplify(lowerCamelCase       )					,			[{"label": "LABEL_0", "score": 0.5_04}, {"label": "LABEL_1", "score": 0.4_96}]       )

														__snake_case	:    int											=     text_classifier(["This is great !", "This is bad"]					,			top_k=2       )
														self.assertEqual(
														    nested_simplify(lowerCamelCase       )					,			[
														        [{"label": "LABEL_0", "score": 0.5_04}, {"label": "LABEL_1", "score": 0.4_96}],
														        [{"label": "LABEL_0", "score": 0.5_04}, {"label": "LABEL_1", "score": 0.4_96}],
														    ]					,			)

														__snake_case	:    List[str]											=     text_classifier("This is great !"					,			top_k=1       )
														self.assertEqual(nested_simplify(lowerCamelCase       )					,			[{"label": "LABEL_0", "score": 0.5_04}]       )

														# Legacy behavior
														__snake_case	:    Dict											=     text_classifier("This is great !"					,			return_all_scores=lowerCamelCase       )
														self.assertEqual(nested_simplify(lowerCamelCase       )					,			[{"label": "LABEL_0", "score": 0.5_04}]       )

														__snake_case	:    Any											=     text_classifier("This is great !"					,			return_all_scores=lowerCamelCase       )
														self.assertEqual(
														    nested_simplify(lowerCamelCase       )					,			[[{"label": "LABEL_0", "score": 0.5_04}, {"label": "LABEL_1", "score": 0.4_96}]]       )

														__snake_case	:    Tuple											=     text_classifier(["This is great !", "Something else"]					,			return_all_scores=lowerCamelCase       )
														self.assertEqual(
														    nested_simplify(lowerCamelCase       )					,			[
														        [{"label": "LABEL_0", "score": 0.5_04}, {"label": "LABEL_1", "score": 0.4_96}],
														        [{"label": "LABEL_0", "score": 0.5_04}, {"label": "LABEL_1", "score": 0.4_96}],
														    ]					,			)

														__snake_case	:    Tuple											=     text_classifier(["This is great !", "Something else"]					,			return_all_scores=lowerCamelCase       )
														self.assertEqual(
														    nested_simplify(lowerCamelCase       )					,			[
														        {"label": "LABEL_0", "score": 0.5_04},
														        {"label": "LABEL_0", "score": 0.5_04},
														    ]					,			)

							@require_torch
							def 					__snake_case      (							self :						Optional[int]       )			->					List[Any]:
														import torch

														__snake_case	:    Dict											=     pipeline(
														    task="text-classification"					,			model="hf-internal-testing/tiny-random-distilbert"					,			framework="pt"					,			device=torch.device("cpu"       )					,			)

														__snake_case	:    Optional[int]											=     text_classifier("This is great !"       )
														self.assertEqual(nested_simplify(lowerCamelCase       )					,			[{"label": "LABEL_0", "score": 0.5_04}]       )

							@require_tf
							def 					__snake_case      (							self :						Any       )			->					Tuple:
														__snake_case	:    List[Any]											=     pipeline(
														    task="text-classification"					,			model="hf-internal-testing/tiny-random-distilbert"					,			framework="tf"       )

														__snake_case	:    str											=     text_classifier("This is great !"       )
														self.assertEqual(nested_simplify(lowerCamelCase       )					,			[{"label": "LABEL_0", "score": 0.5_04}]       )

							@slow
							@require_torch
							def 					__snake_case      (							self :						int       )			->					int:
														__snake_case	:    Dict											=     pipeline("text-classification"       )

														__snake_case	:    Dict											=     text_classifier("This is great !"       )
														self.assertEqual(nested_simplify(lowerCamelCase       )					,			[{"label": "POSITIVE", "score": 1.0}]       )
														__snake_case	:    int											=     text_classifier("This is bad !"       )
														self.assertEqual(nested_simplify(lowerCamelCase       )					,			[{"label": "NEGATIVE", "score": 1.0}]       )
														__snake_case	:    str											=     text_classifier("Birds are a type of animal"       )
														self.assertEqual(nested_simplify(lowerCamelCase       )					,			[{"label": "POSITIVE", "score": 0.9_88}]       )

							@slow
							@require_tf
							def 					__snake_case      (							self :						List[Any]       )			->					str:
														__snake_case	:    Optional[Any]											=     pipeline("text-classification"					,			framework="tf"       )

														__snake_case	:    Any											=     text_classifier("This is great !"       )
														self.assertEqual(nested_simplify(lowerCamelCase       )					,			[{"label": "POSITIVE", "score": 1.0}]       )
														__snake_case	:    Optional[int]											=     text_classifier("This is bad !"       )
														self.assertEqual(nested_simplify(lowerCamelCase       )					,			[{"label": "NEGATIVE", "score": 1.0}]       )
														__snake_case	:    Any											=     text_classifier("Birds are a type of animal"       )
														self.assertEqual(nested_simplify(lowerCamelCase       )					,			[{"label": "POSITIVE", "score": 0.9_88}]       )

							def 					__snake_case      (							self :						str					,			lowerCamelCase :						Tuple					,			lowerCamelCase :						Any					,			lowerCamelCase :						Union[str, Any]       )			->					List[Any]:
														__snake_case	:    Union[str, Any]											=     TextClassificationPipeline(model=lowerCamelCase					,			tokenizer=lowerCamelCase       )
														return text_classifier, ["HuggingFace is in", "This is another test"]






							def 					__snake_case      (							self :						List[str]					,			lowerCamelCase :						Optional[Any]					,			lowerCamelCase :						Tuple       )			->					str:
														__snake_case	:    Tuple											=     text_classifier.model
														# Small inputs because BartTokenizer tiny has maximum position embeddings = 22
														__snake_case	:    Any											=     "HuggingFace is in"
														__snake_case	:    Tuple											=     text_classifier(lowerCamelCase       )

														self.assertEqual(nested_simplify(lowerCamelCase       )					,			[{"label": ANY(lowerCamelCase       ), "score": ANY(lowerCamelCase       )}]       )
														self.assertTrue(outputs[0]["label"] in model.config.idalabel.values()       )

														__snake_case	:    Union[str, Any]											=     ["HuggingFace is in ", "Paris is in France"]
														__snake_case	:    Union[str, Any]											=     text_classifier(lowerCamelCase       )
														self.assertEqual(
														    nested_simplify(lowerCamelCase       )					,			[{"label": ANY(lowerCamelCase       ), "score": ANY(lowerCamelCase       )}, {"label": ANY(lowerCamelCase       ), "score": ANY(lowerCamelCase       )}]					,			)
														self.assertTrue(outputs[0]["label"] in model.config.idalabel.values()       )
														self.assertTrue(outputs[1]["label"] in model.config.idalabel.values()       )

														# Forcing to get all results with `top_k=None`
														# This is NOT the legacy format
														__snake_case	:    str											=     text_classifier(lowerCamelCase					,			top_k=lowerCamelCase       )
														__snake_case	:    int											=     len(model.config.idalabel.values()       )
														self.assertEqual(
														    nested_simplify(lowerCamelCase       )					,			[[{"label": ANY(lowerCamelCase       ), "score": ANY(lowerCamelCase       )}] * N, [{"label": ANY(lowerCamelCase       ), "score": ANY(lowerCamelCase       )}] * N]					,			)

														__snake_case	:    Optional[int]											=     {"text": "HuggingFace is in ", "text_pair": "Paris is in France"}
														__snake_case	:    Optional[Any]											=     text_classifier(lowerCamelCase       )
														self.assertEqual(
														    nested_simplify(lowerCamelCase       )					,			{"label": ANY(lowerCamelCase       ), "score": ANY(lowerCamelCase       )}					,			)
														self.assertTrue(outputs["label"] in model.config.idalabel.values()       )

														# This might be used a text pair, but tokenizer + pipe interaction
														# makes it hard to understand that it's not using the pair properly
														# https://github.com/huggingface/transformers/issues/17305
														# We disabled this usage instead as it was outputting wrong outputs.
														__snake_case	:    Any											=     [["HuggingFace is in ", "Paris is in France"]]
														with self.assertRaises(lowerCamelCase       ):
																					text_classifier(lowerCamelCase       )

														# This used to be valid for doing text pairs
														# We're keeping it working because of backward compatibility
														__snake_case	:    List[Any]											=     text_classifier([[["HuggingFace is in ", "Paris is in France"]]]       )
														self.assertEqual(
														    nested_simplify(lowerCamelCase       )					,			[{"label": ANY(lowerCamelCase       ), "score": ANY(lowerCamelCase       )}]					,			)
														self.assertTrue(outputs[0]["label"] in model.config.idalabel.values()       )

