





"""simple docstring"""





import numpy as np
import torch
import torch.nn as nn
from transformers import CLIPConfig, CLIPVisionModelWithProjection, PreTrainedModel

from ...utils import logging


_a							=							logging.get_logger(__name__)




class  _lowerCAmelCase  (     lowercase       ):







 """simple docstring"""







 __UpperCAmelCase     : Any       		=     CLIPConfig

 __UpperCAmelCase     : Optional[int]       		=     ["CLIPEncoderLayer"]


 def __init__(      self							:      List[Any], UpperCAmelCase__							:      CLIPConfig     ):
    super().__init__(UpperCAmelCase__     )

    __lowercase								=						CLIPVisionModelWithProjection(config.vision_config     )

    __lowercase								=						nn.Linear(config.vision_config.projection_dim, 1     )
    __lowercase								=						nn.Linear(config.vision_config.projection_dim, 1     )



 @torch.no_grad()
 def  _lowercase			(      self							:      str, UpperCAmelCase__							:      Tuple, UpperCAmelCase__							:      Optional[Any], UpperCAmelCase__							:      List[str]=0.5, UpperCAmelCase__							:      Any=0.5     ):
    __lowercase								=						self.vision_model(UpperCAmelCase__     )[0]

    __lowercase								=						self.p_head(UpperCAmelCase__     )
    __lowercase								=						nsfw_detected.flatten()
    __lowercase								=						nsfw_detected > p_threshold
    __lowercase								=						nsfw_detected.tolist()

    if any(UpperCAmelCase__     ):
       logger.warning(
           "Potential NSFW content was detected in one or more images. A black image will be returned instead."
           " Try again with a different prompt and/or seed."     )

    for idx, nsfw_detected_ in enumerate(UpperCAmelCase__     ):
       if nsfw_detected_:
          __lowercase								=						np.zeros(images[idx].shape     )

    __lowercase								=						self.w_head(UpperCAmelCase__     )
    __lowercase								=						watermark_detected.flatten()
    __lowercase								=						watermark_detected > w_threshold
    __lowercase								=						watermark_detected.tolist()

    if any(UpperCAmelCase__     ):
       logger.warning(
           "Potential watermarked content was detected in one or more images. A black image will be returned instead."
           " Try again with a different prompt and/or seed."     )

    for idx, watermark_detected_ in enumerate(UpperCAmelCase__     ):
       if watermark_detected_:
          __lowercase								=						np.zeros(images[idx].shape     )

    return images, nsfw_detected, watermark_detected







"""simple docstring"""





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.
_a							=							{'LayoutLMv2Config', 'LayoutLMv3Config'}




@is_pipeline_test
class  _lowerCAmelCase  (     unittest.TestCase       ):







 """simple docstring"""







 __UpperCAmelCase     : str       		=     MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
 __UpperCAmelCase     : str       		=     TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

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


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

    __lowercase								=						text_classifier("This is great !"     )
    self.assertEqual(nested_simplify(UpperCAmelCase__     ), [{"label": "LABEL_0", "score": 0.504}]     )

    __lowercase								=						text_classifier("This is great !", top_k=2     )
    self.assertEqual(
        nested_simplify(UpperCAmelCase__     ), [{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}]     )

    __lowercase								=						text_classifier(["This is great !", "This is bad"], top_k=2     )
    self.assertEqual(
        nested_simplify(UpperCAmelCase__     ), [
            [{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}],
            [{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}],
        ], )

    __lowercase								=						text_classifier("This is great !", top_k=1     )
    self.assertEqual(nested_simplify(UpperCAmelCase__     ), [{"label": "LABEL_0", "score": 0.504}]     )

    # Legacy behavior
    __lowercase								=						text_classifier("This is great !", return_all_scores=UpperCAmelCase__     )
    self.assertEqual(nested_simplify(UpperCAmelCase__     ), [{"label": "LABEL_0", "score": 0.504}]     )

    __lowercase								=						text_classifier("This is great !", return_all_scores=UpperCAmelCase__     )
    self.assertEqual(
        nested_simplify(UpperCAmelCase__     ), [[{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}]]     )

    __lowercase								=						text_classifier(["This is great !", "Something else"], return_all_scores=UpperCAmelCase__     )
    self.assertEqual(
        nested_simplify(UpperCAmelCase__     ), [
            [{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}],
            [{"label": "LABEL_0", "score": 0.504}, {"label": "LABEL_1", "score": 0.496}],
        ], )

    __lowercase								=						text_classifier(["This is great !", "Something else"], return_all_scores=UpperCAmelCase__     )
    self.assertEqual(
        nested_simplify(UpperCAmelCase__     ), [
            {"label": "LABEL_0", "score": 0.504},
            {"label": "LABEL_0", "score": 0.504},
        ], )


 @require_torch
 def  _lowercase			(      self							:      Dict     ):
    import torch

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

    __lowercase								=						text_classifier("This is great !"     )
    self.assertEqual(nested_simplify(UpperCAmelCase__     ), [{"label": "LABEL_0", "score": 0.504}]     )


 @require_tf
 def  _lowercase			(      self							:      Union[str, Any]     ):
    __lowercase								=						pipeline(
        task="text-classification", model="hf-internal-testing/tiny-random-distilbert", framework="tf"     )

    __lowercase								=						text_classifier("This is great !"     )
    self.assertEqual(nested_simplify(UpperCAmelCase__     ), [{"label": "LABEL_0", "score": 0.504}]     )


 @slow
 @require_torch
 def  _lowercase			(      self							:      Dict     ):
    __lowercase								=						pipeline("text-classification"     )

    __lowercase								=						text_classifier("This is great !"     )
    self.assertEqual(nested_simplify(UpperCAmelCase__     ), [{"label": "POSITIVE", "score": 1.0}]     )
    __lowercase								=						text_classifier("This is bad !"     )
    self.assertEqual(nested_simplify(UpperCAmelCase__     ), [{"label": "NEGATIVE", "score": 1.0}]     )
    __lowercase								=						text_classifier("Birds are a type of animal"     )
    self.assertEqual(nested_simplify(UpperCAmelCase__     ), [{"label": "POSITIVE", "score": 0.988}]     )


 @slow
 @require_tf
 def  _lowercase			(      self							:      Tuple     ):
    __lowercase								=						pipeline("text-classification", framework="tf"     )

    __lowercase								=						text_classifier("This is great !"     )
    self.assertEqual(nested_simplify(UpperCAmelCase__     ), [{"label": "POSITIVE", "score": 1.0}]     )
    __lowercase								=						text_classifier("This is bad !"     )
    self.assertEqual(nested_simplify(UpperCAmelCase__     ), [{"label": "NEGATIVE", "score": 1.0}]     )
    __lowercase								=						text_classifier("Birds are a type of animal"     )
    self.assertEqual(nested_simplify(UpperCAmelCase__     ), [{"label": "POSITIVE", "score": 0.988}]     )


 def  _lowercase			(      self							:      Union[str, Any], UpperCAmelCase__							:      str, UpperCAmelCase__							:      int, UpperCAmelCase__							:      Tuple     ):
    __lowercase								=						TextClassificationPipeline(model=UpperCAmelCase__, tokenizer=UpperCAmelCase__     )
    return text_classifier, ["HuggingFace is in", "This is another test"]



 def  _lowercase			(      self							:      Any, UpperCAmelCase__							:      List[Any], UpperCAmelCase__							:      str     ):
    __lowercase								=						text_classifier.model
    # Small inputs because BartTokenizer tiny has maximum position embeddings = 22
    __lowercase								=						"HuggingFace is in"
    __lowercase								=						text_classifier(UpperCAmelCase__     )

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

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

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

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




