




'''simple docstring'''



import unittest

from transformers import is_vision_available
from transformers.pipelines import pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
      from PIL import Image
else:






      class 				_a							:





             '''simple docstring'''






             @staticmethod
             def     UpperCamelCase_				(	*A,				**A   ):







                   '''simple docstring'''







                   pass






@is_pipeline_test
@require_vision
class 				_a							(       unittest.TestCase      ):





       '''simple docstring'''






       @require_torch
       def     UpperCamelCase_				(	self   ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					:	Union[str, Any]   =		pipeline(
                 model='hf-internal-testing/tiny-random-clip-zero-shot-image-classification',				)
             SCREAMING_SNAKE_CASE					:	Tuple   =		Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'   )
             SCREAMING_SNAKE_CASE					:	Optional[Any]   =		image_classifier(__lowercase,				candidate_labels=['a', 'b', 'c']   )

             # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across
             # python and torch versions.
             self.assertIn(
                 nested_simplify(__lowercase   ),				[
                     [{'score': 0.3_33, 'label': 'a'}, {'score': 0.3_33, 'label': 'b'}, {'score': 0.3_33, 'label': 'c'}],
                     [{'score': 0.3_33, 'label': 'a'}, {'score': 0.3_33, 'label': 'c'}, {'score': 0.3_33, 'label': 'b'}],
                 ],				)

             SCREAMING_SNAKE_CASE					:	Any   =		image_classifier([image] * 5,				candidate_labels=['A', 'B', 'C'],				batch_size=2   )
             self.assertEqual(
                 nested_simplify(__lowercase   ),				[
                     [
                         {'score': 0.3_33, 'label': ANY(__lowercase   )},
                         {'score': 0.3_33, 'label': ANY(__lowercase   )},
                         {'score': 0.3_33, 'label': ANY(__lowercase   )},
                     ],
                     [
                         {'score': 0.3_33, 'label': ANY(__lowercase   )},
                         {'score': 0.3_33, 'label': ANY(__lowercase   )},
                         {'score': 0.3_33, 'label': ANY(__lowercase   )},
                     ],
                     [
                         {'score': 0.3_33, 'label': ANY(__lowercase   )},
                         {'score': 0.3_33, 'label': ANY(__lowercase   )},
                         {'score': 0.3_33, 'label': ANY(__lowercase   )},
                     ],
                     [
                         {'score': 0.3_33, 'label': ANY(__lowercase   )},
                         {'score': 0.3_33, 'label': ANY(__lowercase   )},
                         {'score': 0.3_33, 'label': ANY(__lowercase   )},
                     ],
                     [
                         {'score': 0.3_33, 'label': ANY(__lowercase   )},
                         {'score': 0.3_33, 'label': ANY(__lowercase   )},
                         {'score': 0.3_33, 'label': ANY(__lowercase   )},
                     ],
                 ],				)







       @require_tf
       def     UpperCamelCase_				(	self   ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					:	Optional[Any]   =		pipeline(
                 model='hf-internal-testing/tiny-random-clip-zero-shot-image-classification',				framework='tf'   )
             SCREAMING_SNAKE_CASE					:	int   =		Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'   )
             SCREAMING_SNAKE_CASE					:	List[Any]   =		image_classifier(__lowercase,				candidate_labels=['a', 'b', 'c']   )

             self.assertEqual(
                 nested_simplify(__lowercase   ),				[{'score': 0.3_33, 'label': 'a'}, {'score': 0.3_33, 'label': 'b'}, {'score': 0.3_33, 'label': 'c'}],				)

             SCREAMING_SNAKE_CASE					:	Any   =		image_classifier([image] * 5,				candidate_labels=['A', 'B', 'C'],				batch_size=2   )
             self.assertEqual(
                 nested_simplify(__lowercase   ),				[
                     [
                         {'score': 0.3_33, 'label': ANY(__lowercase   )},
                         {'score': 0.3_33, 'label': ANY(__lowercase   )},
                         {'score': 0.3_33, 'label': ANY(__lowercase   )},
                     ],
                     [
                         {'score': 0.3_33, 'label': ANY(__lowercase   )},
                         {'score': 0.3_33, 'label': ANY(__lowercase   )},
                         {'score': 0.3_33, 'label': ANY(__lowercase   )},
                     ],
                     [
                         {'score': 0.3_33, 'label': ANY(__lowercase   )},
                         {'score': 0.3_33, 'label': ANY(__lowercase   )},
                         {'score': 0.3_33, 'label': ANY(__lowercase   )},
                     ],
                     [
                         {'score': 0.3_33, 'label': ANY(__lowercase   )},
                         {'score': 0.3_33, 'label': ANY(__lowercase   )},
                         {'score': 0.3_33, 'label': ANY(__lowercase   )},
                     ],
                     [
                         {'score': 0.3_33, 'label': ANY(__lowercase   )},
                         {'score': 0.3_33, 'label': ANY(__lowercase   )},
                         {'score': 0.3_33, 'label': ANY(__lowercase   )},
                     ],
                 ],				)







       @slow
       @require_torch
       def     UpperCamelCase_				(	self   ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					:	str   =		pipeline(
                 task='zero-shot-image-classification',				model='openai/clip-vit-base-patch32',				)
             # This is an image of 2 cats with remotes and no planes
             SCREAMING_SNAKE_CASE					:	Optional[Any]   =		Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'   )
             SCREAMING_SNAKE_CASE					:	Optional[int]   =		image_classifier(__lowercase,				candidate_labels=['cat', 'plane', 'remote']   )

             self.assertEqual(
                 nested_simplify(__lowercase   ),				[
                     {'score': 0.5_11, 'label': 'remote'},
                     {'score': 0.4_85, 'label': 'cat'},
                     {'score': 0.0_04, 'label': 'plane'},
                 ],				)

             SCREAMING_SNAKE_CASE					:	int   =		image_classifier([image] * 5,				candidate_labels=['cat', 'plane', 'remote'],				batch_size=2   )
             self.assertEqual(
                 nested_simplify(__lowercase   ),				[
                     [
                         {'score': 0.5_11, 'label': 'remote'},
                         {'score': 0.4_85, 'label': 'cat'},
                         {'score': 0.0_04, 'label': 'plane'},
                     ],
                 ]
                 * 5,				)







       @slow
       @require_tf
       def     UpperCamelCase_				(	self   ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					:	List[str]   =		pipeline(
                 task='zero-shot-image-classification',				model='openai/clip-vit-base-patch32',				framework='tf'   )
             # This is an image of 2 cats with remotes and no planes
             SCREAMING_SNAKE_CASE					:	str   =		Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'   )
             SCREAMING_SNAKE_CASE					:	Dict   =		image_classifier(__lowercase,				candidate_labels=['cat', 'plane', 'remote']   )
             self.assertEqual(
                 nested_simplify(__lowercase   ),				[
                     {'score': 0.5_11, 'label': 'remote'},
                     {'score': 0.4_85, 'label': 'cat'},
                     {'score': 0.0_04, 'label': 'plane'},
                 ],				)

             SCREAMING_SNAKE_CASE					:	List[str]   =		image_classifier([image] * 5,				candidate_labels=['cat', 'plane', 'remote'],				batch_size=2   )
             self.assertEqual(
                 nested_simplify(__lowercase   ),				[
                     [
                         {'score': 0.5_11, 'label': 'remote'},
                         {'score': 0.4_85, 'label': 'cat'},
                         {'score': 0.0_04, 'label': 'plane'},
                     ],
                 ]
                 * 5,				)



import re

import jax.numpy as jnp
from flax.traverse_util import flatten_dict, unflatten_dict
from jax.random import PRNGKey

from ..utils import logging


__lowercase							 =					logging.get_logger(__name__)



def lowerCamelCase  (   SCREAMING_SNAKE_CASE	):
    '''simple docstring'''







    __UpperCamelCase     :Tuple			  =		R'''\w+[.]\d+'''
    __UpperCamelCase     :List[str]			  =		re.findall(SCREAMING_SNAKE_CASE  ,			SCREAMING_SNAKE_CASE	)
    for pat in pats:
        __UpperCamelCase     :int			  =		key.replace(SCREAMING_SNAKE_CASE  ,			'''_'''.join(pat.split('''.'''	)	)	)
    return key



def lowerCamelCase  (   SCREAMING_SNAKE_CASE  ,			SCREAMING_SNAKE_CASE  ,			SCREAMING_SNAKE_CASE	):
    '''simple docstring'''







    __UpperCamelCase     :Tuple			  =		pt_tuple_key[:-1] + ('''scale''',)
    if (
        any('''norm''' in str_ for str_ in pt_tuple_key	)
        and (pt_tuple_key[-1] == "bias")
        and (pt_tuple_key[:-1] + ("bias",) not in random_flax_state_dict)
        and (pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict)
    ):
        __UpperCamelCase     :str			  =		pt_tuple_key[:-1] + ('''scale''',)
        return renamed_pt_tuple_key, pt_tensor
    elif pt_tuple_key[-1] in ["weight", "gamma"] and pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict:
        __UpperCamelCase     :Any			  =		pt_tuple_key[:-1] + ('''scale''',)
        return renamed_pt_tuple_key, pt_tensor

    # embedding
    if pt_tuple_key[-1] == "weight" and pt_tuple_key[:-1] + ("embedding",) in random_flax_state_dict:
        __UpperCamelCase     :str			  =		pt_tuple_key[:-1] + ('''embedding''',)
        return renamed_pt_tuple_key, pt_tensor

    # conv layer
    __UpperCamelCase     :List[str]			  =		pt_tuple_key[:-1] + ('''kernel''',)
    if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4:
        __UpperCamelCase     :List[Any]			  =		pt_tensor.transpose(2  ,			3  ,			1  ,			0	)
        return renamed_pt_tuple_key, pt_tensor

    # linear layer
    __UpperCamelCase     :List[str]			  =		pt_tuple_key[:-1] + ('''kernel''',)
    if pt_tuple_key[-1] == "weight":
        __UpperCamelCase     :Any			  =		pt_tensor.T
        return renamed_pt_tuple_key, pt_tensor

    # old PyTorch layer norm weight
    __UpperCamelCase     :int			  =		pt_tuple_key[:-1] + ('''weight''',)
    if pt_tuple_key[-1] == "gamma":
        return renamed_pt_tuple_key, pt_tensor

    # old PyTorch layer norm bias
    __UpperCamelCase     :int			  =		pt_tuple_key[:-1] + ('''bias''',)
    if pt_tuple_key[-1] == "beta":
        return renamed_pt_tuple_key, pt_tensor

    return pt_tuple_key, pt_tensor



def lowerCamelCase  (   SCREAMING_SNAKE_CASE  ,			SCREAMING_SNAKE_CASE  ,			SCREAMING_SNAKE_CASE=42	):
    '''simple docstring'''







    __UpperCamelCase     :Union[str, Any]			  =		{k: v.numpy() for k, v in pt_state_dict.items()}

    # Step 2: Since the model is stateless, get random Flax params
    __UpperCamelCase     :str			  =		flax_model.init_weights(PRNGKey(SCREAMING_SNAKE_CASE	)	)

    __UpperCamelCase     :int			  =		flatten_dict(SCREAMING_SNAKE_CASE	)
    __UpperCamelCase     :List[Any]			  =		{}

    # Need to change some parameters name to match Flax names
    for pt_key, pt_tensor in pt_state_dict.items():
        __UpperCamelCase     :List[Any]			  =		rename_key(SCREAMING_SNAKE_CASE	)
        __UpperCamelCase     :List[Any]			  =		tuple(renamed_pt_key.split('''.'''	)	)

        # Correctly rename weight parameters
        __UpperCamelCase  ,       __UpperCamelCase     :Any			  =		rename_key_and_reshape_tensor(SCREAMING_SNAKE_CASE  ,			SCREAMING_SNAKE_CASE  ,			SCREAMING_SNAKE_CASE	)

        if flax_key in random_flax_state_dict:
            if flax_tensor.shape != random_flax_state_dict[flax_key].shape:
                raise ValueError(
                    f"""PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape """
                    f"""{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}."""	)

        # also add unexpected weight so that warning is thrown
        __UpperCamelCase     :str			  =		jnp.asarray(SCREAMING_SNAKE_CASE	)

    return unflatten_dict(SCREAMING_SNAKE_CASE	)





