





"""simple docstring"""





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 AutoFeatureExtractor, WavaVecaFeatureExtractor
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_feature_extraction import CustomFeatureExtractor  # noqa E402


lowerCAmelCase__     			=			get_tests_dir('''fixtures''')





class        _lowerCamelCase      (       unittest.TestCase ):


						def     snake_case_   (self		) ->   int:
								# A mock response for an HTTP head request to emulate server down
								UpperCamelCase   =	mock.Mock()
								UpperCamelCase   =	5_00
								UpperCamelCase   =	{}
								UpperCamelCase   =	HTTPError
								UpperCamelCase   =	{}

								# Download this model to make sure it's in the cache.
								UpperCamelCase   =	WavaVecaFeatureExtractor.from_pretrained("hf-internal-testing/tiny-random-wav2vec2"		)
								# 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:
										UpperCamelCase   =	WavaVecaFeatureExtractor.from_pretrained("hf-internal-testing/tiny-random-wav2vec2"		)
										# This check we did call the fake head request
										mock_head.assert_called()




						def     snake_case_   (self		) ->   str:
								# This test is for deprecated behavior and can be removed in v5
								UpperCamelCase   =	WavaVecaFeatureExtractor.from_pretrained(
								    "https://huggingface.co/hf-internal-testing/tiny-random-wav2vec2/resolve/main/preprocessor_config.json"		)





@is_staging_test
class        _lowerCamelCase      (       unittest.TestCase ):


						@classmethod
						def     snake_case_   (cls		) ->   Union[str, Any]:
								UpperCamelCase   =	TOKEN
								HfFolder.save_token(__a		)


						@classmethod
						def     snake_case_   (cls		) ->   Optional[Any]:
								try:
										delete_repo(token=cls._token   ,							repo_id="test-feature-extractor"		)
								except HTTPError:
										pass

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

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


						def     snake_case_   (self		) ->   Union[str, Any]:
								UpperCamelCase   =	WavaVecaFeatureExtractor.from_pretrained(__a		)
								feature_extractor.push_to_hub("test-feature-extractor"   ,							use_auth_token=self._token		)

								UpperCamelCase   =	WavaVecaFeatureExtractor.from_pretrained(F"{USER}/test-feature-extractor"		)
								for k, v in feature_extractor.__dict__.items():
										self.assertEqual(__a   ,							getattr(__a   ,							__a		)		)

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

								# Push to hub via save_pretrained
								with tempfile.TemporaryDirectory() as tmp_dir:
										feature_extractor.save_pretrained(
										    __a   ,							repo_id="test-feature-extractor"   ,							push_to_hub=__a   ,							use_auth_token=self._token		)

								UpperCamelCase   =	WavaVecaFeatureExtractor.from_pretrained(F"{USER}/test-feature-extractor"		)
								for k, v in feature_extractor.__dict__.items():
										self.assertEqual(__a   ,							getattr(__a   ,							__a		)		)


						def     snake_case_   (self		) ->   Dict:
								UpperCamelCase   =	WavaVecaFeatureExtractor.from_pretrained(__a		)
								feature_extractor.push_to_hub("valid_org/test-feature-extractor"   ,							use_auth_token=self._token		)

								UpperCamelCase   =	WavaVecaFeatureExtractor.from_pretrained("valid_org/test-feature-extractor"		)
								for k, v in feature_extractor.__dict__.items():
										self.assertEqual(__a   ,							getattr(__a   ,							__a		)		)

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

								# Push to hub via save_pretrained
								with tempfile.TemporaryDirectory() as tmp_dir:
										feature_extractor.save_pretrained(
										    __a   ,							repo_id="valid_org/test-feature-extractor-org"   ,							push_to_hub=__a   ,							use_auth_token=self._token		)

								UpperCamelCase   =	WavaVecaFeatureExtractor.from_pretrained("valid_org/test-feature-extractor-org"		)
								for k, v in feature_extractor.__dict__.items():
										self.assertEqual(__a   ,							getattr(__a   ,							__a		)		)




						def     snake_case_   (self		) ->   Optional[Any]:
								CustomFeatureExtractor.register_for_auto_class()
								UpperCamelCase   =	CustomFeatureExtractor.from_pretrained(__a		)

								feature_extractor.push_to_hub("test-dynamic-feature-extractor"   ,							use_auth_token=self._token		)

								# This has added the proper auto_map field to the config
								self.assertDictEqual(
								    feature_extractor.auto_map   ,							{"AutoFeatureExtractor": "custom_feature_extraction.CustomFeatureExtractor"}   ,							)

								UpperCamelCase   =	AutoFeatureExtractor.from_pretrained(
								    F"{USER}/test-dynamic-feature-extractor"   ,							trust_remote_code=__a		)
								# Can't make an isinstance check because the new_feature_extractor is from the CustomFeatureExtractor class of a dynamic module
								self.assertEqual(new_feature_extractor.__class__.__name__   ,							"CustomFeatureExtractor"		)







"""simple docstring"""





import unittest

from huggingface_hub import hf_hub_download

from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor
from transformers.pipelines import VideoClassificationPipeline, pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_decord,
    require_tf,
    require_torch,
    require_torch_or_tf,
    require_vision,
)

from .test_pipelines_common import ANY





@is_pipeline_test
@require_torch_or_tf
@require_vision
@require_decord
class        _lowerCamelCase      (       unittest.TestCase ):
						UpperCAmelCase_ =			MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING


						def     snake_case_   (self   ,							__a   ,							__a   ,							__a		) ->   str:
								UpperCamelCase   =	hf_hub_download(
								    repo_id="nateraw/video-demo"   ,							filename="archery.mp4"   ,							repo_type="dataset"		)
								UpperCamelCase   =	VideoClassificationPipeline(model=__a   ,							image_processor=__a   ,							top_k=2		)
								UpperCamelCase   =	[
								    example_video_filepath,
								    "https://huggingface.co/datasets/nateraw/video-demo/resolve/main/archery.mp4",
								]
								return video_classifier, examples


						def     snake_case_   (self   ,							__a   ,							__a		) ->   str:
								for example in examples:
										UpperCamelCase   =	video_classifier(__a		)

										self.assertEqual(
										    __a   ,							[
										        {"score": ANY(__a		), "label": ANY(__a		)},
										        {"score": ANY(__a		), "label": ANY(__a		)},
										    ]   ,							)


						@require_torch
						def     snake_case_   (self		) ->   int:
								UpperCamelCase   =	"hf-internal-testing/tiny-random-VideoMAEForVideoClassification"
								UpperCamelCase   =	VideoMAEFeatureExtractor(
								    size={"shortest_edge": 10}   ,							crop_size={"height": 10, "width": 10}		)
								UpperCamelCase   =	pipeline(
								    "video-classification"   ,							model=__a   ,							feature_extractor=__a   ,							frame_sampling_rate=4		)

								UpperCamelCase   =	hf_hub_download(repo_id="nateraw/video-demo"   ,							filename="archery.mp4"   ,							repo_type="dataset"		)
								UpperCamelCase   =	video_classifier(__a   ,							top_k=2		)
								self.assertEqual(
								    nested_simplify(__a   ,							decimals=4		)   ,							[{"score": 0.5199, "label": "LABEL_0"}, {"score": 0.4801, "label": "LABEL_1"}]   ,							)

								UpperCamelCase   =	video_classifier(
								    [
								        video_file_path,
								        video_file_path,
								    ]   ,							top_k=2   ,							)
								self.assertEqual(
								    nested_simplify(__a   ,							decimals=4		)   ,							[
								        [{"score": 0.5199, "label": "LABEL_0"}, {"score": 0.4801, "label": "LABEL_1"}],
								        [{"score": 0.5199, "label": "LABEL_0"}, {"score": 0.4801, "label": "LABEL_1"}],
								    ]   ,							)




						@require_tf
						def     snake_case_   (self		) ->   Optional[Any]:
								pass






