


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.
_UpperCAmelCase			:  Union[str, Any]     ={"""LayoutLMv2Config""", """LayoutLMv3Config"""}







@is_pipeline_test
class 				snake_case__(							unittest.TestCase							):







						'''simple docstring'''




						SCREAMING_SNAKE_CASE__      :  List[str]					=							MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
						SCREAMING_SNAKE_CASE__      :  Optional[int]					=							TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

						if model_mapping is not None:
												SCREAMING_SNAKE_CASE__      :  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:
												SCREAMING_SNAKE_CASE__      :  str					=							{
												    config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
												}




						@require_torch
						def 						lowercase_ (				self							)					->    Optional[int]:
										lowerCAmelCase_ :      Optional[int]    				=				pipeline(
										    task='''text-classification'''   ,						model='''hf-internal-testing/tiny-random-distilbert'''   ,						framework='''pt'''							)

										lowerCAmelCase_ :      List[Any]    				=				text_classifier('''This is great !'''							)
										self.assertEqual(nested_simplify(__lowercase							)   ,						[{'''label''': '''LABEL_0''', '''score''': 0.5_04}]							)

										lowerCAmelCase_ :      Tuple    				=				text_classifier('''This is great !'''   ,						top_k=2							)
										self.assertEqual(
										    nested_simplify(__lowercase							)   ,						[{'''label''': '''LABEL_0''', '''score''': 0.5_04}, {'''label''': '''LABEL_1''', '''score''': 0.4_96}]							)

										lowerCAmelCase_ :      Optional[int]    				=				text_classifier(['''This is great !''', '''This is bad''']   ,						top_k=2							)
										self.assertEqual(
										    nested_simplify(__lowercase							)   ,						[
										        [{'''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}],
										    ]   ,						)

										lowerCAmelCase_ :      Optional[int]    				=				text_classifier('''This is great !'''   ,						top_k=1							)
										self.assertEqual(nested_simplify(__lowercase							)   ,						[{'''label''': '''LABEL_0''', '''score''': 0.5_04}]							)

										# Legacy behavior
										lowerCAmelCase_ :      Union[str, Any]    				=				text_classifier('''This is great !'''   ,						return_all_scores=__lowercase							)
										self.assertEqual(nested_simplify(__lowercase							)   ,						[{'''label''': '''LABEL_0''', '''score''': 0.5_04}]							)

										lowerCAmelCase_ :      int    				=				text_classifier('''This is great !'''   ,						return_all_scores=__lowercase							)
										self.assertEqual(
										    nested_simplify(__lowercase							)   ,						[[{'''label''': '''LABEL_0''', '''score''': 0.5_04}, {'''label''': '''LABEL_1''', '''score''': 0.4_96}]]							)

										lowerCAmelCase_ :      Optional[int]    				=				text_classifier(['''This is great !''', '''Something else''']   ,						return_all_scores=__lowercase							)
										self.assertEqual(
										    nested_simplify(__lowercase							)   ,						[
										        [{'''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}],
										    ]   ,						)

										lowerCAmelCase_ :      List[Any]    				=				text_classifier(['''This is great !''', '''Something else''']   ,						return_all_scores=__lowercase							)
										self.assertEqual(
										    nested_simplify(__lowercase							)   ,						[
										        {'''label''': '''LABEL_0''', '''score''': 0.5_04},
										        {'''label''': '''LABEL_0''', '''score''': 0.5_04},
										    ]   ,						)




						@require_torch
						def 						lowercase_ (				self							)					->    Optional[Any]:
										import torch

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

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




						@require_tf
						def 						lowercase_ (				self							)					->    int:
										lowerCAmelCase_ :      Optional[int]    				=				pipeline(
										    task='''text-classification'''   ,						model='''hf-internal-testing/tiny-random-distilbert'''   ,						framework='''tf'''							)

										lowerCAmelCase_ :      List[Any]    				=				text_classifier('''This is great !'''							)
										self.assertEqual(nested_simplify(__lowercase							)   ,						[{'''label''': '''LABEL_0''', '''score''': 0.5_04}]							)




						@slow
						@require_torch
						def 						lowercase_ (				self							)					->    str:
										lowerCAmelCase_ :      Dict    				=				pipeline('''text-classification'''							)

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




						@slow
						@require_tf
						def 						lowercase_ (				self							)					->    int:
										lowerCAmelCase_ :      Optional[Any]    				=				pipeline('''text-classification'''   ,						framework='''tf'''							)

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




						def 						lowercase_ (				self   ,						__lowercase   ,						__lowercase   ,						__lowercase							)					->    Optional[int]:
										lowerCAmelCase_ :      Tuple    				=				TextClassificationPipeline(model=__lowercase   ,						tokenizer=__lowercase							)
										return text_classifier, ["HuggingFace is in", "This is another test"]




						def 						lowercase_ (				self   ,						__lowercase   ,						__lowercase							)					->    Dict:
										lowerCAmelCase_ :      Optional[Any]    				=				text_classifier.model
										# Small inputs because BartTokenizer tiny has maximum position embeddings = 22
										lowerCAmelCase_ :      List[str]    				=				'''HuggingFace is in'''
										lowerCAmelCase_ :      Union[str, Any]    				=				text_classifier(__lowercase							)

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

										lowerCAmelCase_ :      str    				=				['''HuggingFace is in ''', '''Paris is in France''']
										lowerCAmelCase_ :      Optional[int]    				=				text_classifier(__lowercase							)
										self.assertEqual(
										    nested_simplify(__lowercase							)   ,						[{'''label''': ANY(__lowercase							), '''score''': ANY(__lowercase							)}, {'''label''': ANY(__lowercase							), '''score''': ANY(__lowercase							)}]   ,						)
										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
										lowerCAmelCase_ :      Any    				=				text_classifier(__lowercase   ,						top_k=__lowercase							)
										lowerCAmelCase_ :      str    				=				len(model.config.idalabel.values()							)
										self.assertEqual(
										    nested_simplify(__lowercase							)   ,						[[{'''label''': ANY(__lowercase							), '''score''': ANY(__lowercase							)}] * N, [{'''label''': ANY(__lowercase							), '''score''': ANY(__lowercase							)}] * N]   ,						)

										lowerCAmelCase_ :      Any    				=				{'''text''': '''HuggingFace is in ''', '''text_pair''': '''Paris is in France'''}
										lowerCAmelCase_ :      List[Any]    				=				text_classifier(__lowercase							)
										self.assertEqual(
										    nested_simplify(__lowercase							)   ,						{'''label''': ANY(__lowercase							), '''score''': ANY(__lowercase							)}   ,						)
										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.
										lowerCAmelCase_ :      int    				=				[['''HuggingFace is in ''', '''Paris is in France''']]
										with self.assertRaises(__lowercase							):
														text_classifier(__lowercase							)

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










import copy
from dataclasses import dataclass, field
from typing import ClassVar, Dict

from ..features import Audio, Features, Value
from .base import TaskTemplate







@dataclass(frozen=UpperCAmelCase__							)
class 				snake_case__(							UpperCAmelCase__							):







						'''simple docstring'''




						SCREAMING_SNAKE_CASE__      :  str					=							field(default="""automatic-speech-recognition""",						metadata={"""include_in_asdict_even_if_is_default""": True}							)
						SCREAMING_SNAKE_CASE__      :  ClassVar[Features]					=							Features({"""audio""": Audio()}							)
						SCREAMING_SNAKE_CASE__      :  ClassVar[Features]					=							Features({"""transcription""": Value("""string"""							)}							)
						SCREAMING_SNAKE_CASE__      :  str					=							"audio"
						SCREAMING_SNAKE_CASE__      :  str					=							"transcription"




						def 						lowercase_ (				self   ,						__lowercase							)					->    int:
										if self.audio_column not in features:
														raise ValueError(f"""Column {self.audio_column} is not present in features."""							)
										if not isinstance(features[self.audio_column]   ,						__lowercase							):
														raise ValueError(f"""Column {self.audio_column} is not an Audio type."""							)
										lowerCAmelCase_ :      List[str]    				=				copy.deepcopy(self							)
										lowerCAmelCase_ :      Optional[Any]    				=				self.input_schema.copy()
										lowerCAmelCase_ :      Optional[Any]    				=				features[self.audio_column]
										lowerCAmelCase_ :      List[str]    				=				input_schema
										return task_template




						@property
						def 						lowercase_ (				self							)					->    Dict[str, str]:
										return {self.audio_column: "audio", self.transcription_column: "transcription"}