


import json
import multiprocessing as mp
import re
from collections import defaultdict
from functools import partial
from typing import Dict, List, Optional, Set, Tuple, Type

from datasets import Dataset
from datasketch import MinHash, MinHashLSH
from dpu_utils.utils.iterators import ThreadedIterator
from tqdm import tqdm


__a	 =      re.compile("""[^A-Za-z_0-9]""")
# parameters used in DuplicationIndex
__a	 =      10
__a	 =      256
def 	_UpperCamelCase					(    lowerCAmelCase_ )    ->Optional[MinHash]:
   if len(lowerCAmelCase_ ) < MIN_NUM_TOKENS:
      return None
   UpperCAmelCase      					=  MinHash(num_perm=lowerCAmelCase_ )
   for token in set(lowerCAmelCase_ ):
      min_hash.update(token.encode() )
   return min_hash
def 	_UpperCamelCase					(    lowerCAmelCase_ )    ->Set[str]:
   return {t for t in NON_ALPHA.split(lowerCAmelCase_ ) if len(t.strip() ) > 0}






class 	__lowercase					:





      def __init__(		self    :       List[str]       ,							*,
          __lowerCamelCase    :       float = 0.85       ,							)     -> Any:






         """simple docstring"""







         UpperCAmelCase      					=  duplication_jaccard_threshold
         UpperCAmelCase      					=  NUM_PERM
         UpperCAmelCase      					=  MinHashLSH(threshold=self._duplication_jaccard_threshold       ,							num_perm=self._num_perm							)

         UpperCAmelCase      					=  defaultdict(__lowerCamelCase							)





      def 							_lowercase					(		self    :       Tuple       ,							__lowerCamelCase    :       Tuple       ,							__lowerCamelCase    :       MinHash							)     -> None:






         """simple docstring"""







         UpperCAmelCase      					=  self._index.query(__lowerCamelCase							)
         if code_key in self._index.keys:
            print(F"""Duplicate key {code_key}"""							)
            return

         self._index.insert(__lowerCamelCase       ,							__lowerCamelCase							)
         if len(__lowerCamelCase							) > 0:
            for base_duplicate in close_duplicates:
               if base_duplicate in self._duplicate_clusters:
                  self._duplicate_clusters[base_duplicate].add(__lowerCamelCase							)
                  break
            else:
               self._duplicate_clusters[close_duplicates[0]].add(__lowerCamelCase							)





      def 							_lowercase					(		self    :       Union[str, Any]							)     -> List[List[Dict]]:






         """simple docstring"""







         UpperCAmelCase      					=  []
         for base, duplicates in self._duplicate_clusters.items():
            UpperCAmelCase      					=  [base] + list(__lowerCamelCase							)
            # reformat the cluster to be a list of dict
            UpperCAmelCase      					=  [{"""base_index""": el[0], """repo_name""": el[1], """path""": el[2]} for el in cluster]
            duplicate_clusters.append(__lowerCamelCase							)
         return duplicate_clusters





      def 							_lowercase					(		self    :       Tuple       ,							__lowerCamelCase    :       Optional[int]							)     -> None:






         """simple docstring"""







         UpperCAmelCase      					=  self.get_duplicate_clusters()
         with open(__lowerCamelCase       ,							"""w"""							) as f:
            json.dump(__lowerCamelCase       ,							__lowerCamelCase							)

def 	_UpperCamelCase					(    lowerCAmelCase_ )    ->Tuple:
   UpperCAmelCase					,	UpperCAmelCase      					=  element
   UpperCAmelCase      					=  get_min_hash([t for t in NON_ALPHA.split(data["""content"""] ) if len(t.strip() ) > 0] )
   if min_hash is not None:
      return (index, data["repo_name"], data["path"]), min_hash
def 	_UpperCamelCase					(    lowerCAmelCase_ )    ->int:
   with mp.Pool() as pool:
      for data in pool.imap_unordered(
          _compute_min_hash	,    ThreadedIterator(lowerCAmelCase_	,    max_queue_size=1_0_0_0_0 )	,    chunksize=1_0_0	,    ):
         if data is not None:
            yield data
def 	_UpperCamelCase					(    lowerCAmelCase_	,    lowerCAmelCase_ )    ->Any:
   UpperCAmelCase      					=  DuplicationIndex(duplication_jaccard_threshold=lowerCAmelCase_ )

   for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(lowerCAmelCase_ ) )	,    max_queue_size=1_0_0 ) ):
      di.add(lowerCAmelCase_	,    lowerCAmelCase_ )

   # Returns a List[Cluster] where Cluster is List[str] with the filenames.
   return di.get_duplicate_clusters()
def 	_UpperCamelCase					(    lowerCAmelCase_	,    lowerCAmelCase_ )    ->float:
   UpperCAmelCase      					=  get_tokens(lowerCAmelCase_ )
   UpperCAmelCase      					=  get_tokens(lowerCAmelCase_ )
   return len(tokensa & tokensa ) / len(tokensa | tokensa )


__a	 =      None
def 	_UpperCamelCase					(    lowerCAmelCase_	,    lowerCAmelCase_ )    ->Dict:
   UpperCAmelCase      					=  []
   for elementa in cluster:
      UpperCAmelCase      					=  _shared_dataset[elementa["""base_index"""]]["""content"""]
      for elementa in extremes:
         UpperCAmelCase      					=  _shared_dataset[elementa["""base_index"""]]["""content"""]
         if jaccard_similarity(lowerCAmelCase_	,    lowerCAmelCase_ ) >= jaccard_threshold:
            elementa["copies"] += 1
            break
      else:
         UpperCAmelCase      					=  1
         extremes.append(lowerCAmelCase_ )
   return extremes
def 	_UpperCamelCase					(    lowerCAmelCase_	,    lowerCAmelCase_	,    lowerCAmelCase_ )    ->Optional[int]:
   global _shared_dataset
   UpperCAmelCase      					=  dataset
   UpperCAmelCase      					=  []
   UpperCAmelCase      					=  partial(_find_cluster_extremes_shared	,    jaccard_threshold=lowerCAmelCase_ )
   with mp.Pool() as pool:
      for extremes in tqdm(
          pool.imap_unordered(
              lowerCAmelCase_	,    lowerCAmelCase_	,    )	,    total=len(lowerCAmelCase_ )	,    ):
         extremes_list.append(lowerCAmelCase_ )
   return extremes_list







def 	_UpperCamelCase					(    lowerCAmelCase_	,    lowerCAmelCase_ = 0.85 )    ->Tuple[Type[Dataset], List[List[Dict]]]:
   UpperCAmelCase      					=  make_duplicate_clusters(lowerCAmelCase_	,    lowerCAmelCase_ )
   UpperCAmelCase      					=  {x["""base_index"""] for cluster in duplicate_clusters for x in cluster}
   UpperCAmelCase      					=  {}
   UpperCAmelCase      					=  find_extremes(lowerCAmelCase_	,    lowerCAmelCase_	,    lowerCAmelCase_ )
   for extremes in extremes_clusters:
      for element in extremes:
         UpperCAmelCase      					=  element
   UpperCAmelCase      					=  duplicate_indices - set(extreme_dict.keys() )
   UpperCAmelCase      					=  dataset.filter(lambda lowerCAmelCase_	,    lowerCAmelCase_ : idx not in remove_indices	,    with_indices=lowerCAmelCase_ )

   # update duplicate_clusters
   for cluster in duplicate_clusters:
      for element in cluster:
         UpperCAmelCase      					=  element["""base_index"""] in extreme_dict
         if element["is_extreme"]:
            UpperCAmelCase      					=  extreme_dict[element["""base_index"""]]["""copies"""]

   print(F"""Original dataset size: {len(lowerCAmelCase_ )}""" )
   print(F"""Number of duplicate clusters: {len(lowerCAmelCase_ )}""" )
   print(F"""Files in duplicate cluster: {len(lowerCAmelCase_ )}""" )
   print(F"""Unique files in duplicate cluster: {len(lowerCAmelCase_ )}""" )
   print(F"""Filtered dataset size: {len(lowerCAmelCase_ )}""" )

   return ds_filter, duplicate_clusters







from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import ResNetConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
 import tensorflow as tf

 from transformers import TFResNetForImageClassification, TFResNetModel
 from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import AutoImageProcessor






class 	__lowercase					:





      def __init__(		self    :       str       ,							__lowerCamelCase    :       Any       ,							__lowerCamelCase    :       Optional[int]=3       ,							__lowerCamelCase    :       Union[str, Any]=3_2       ,							__lowerCamelCase    :       List[str]=3       ,							__lowerCamelCase    :       Dict=1_0       ,							__lowerCamelCase    :       Optional[int]=[1_0, 2_0, 3_0, 4_0]       ,							__lowerCamelCase    :       Optional[int]=[1, 1, 2, 1]       ,							__lowerCamelCase    :       int=True       ,							__lowerCamelCase    :       str=True       ,							__lowerCamelCase    :       str="relu"       ,							__lowerCamelCase    :       str=3       ,							__lowerCamelCase    :       int=None       ,							)     -> Dict:






         """simple docstring"""







         UpperCAmelCase      					=  parent
         UpperCAmelCase      					=  batch_size
         UpperCAmelCase      					=  image_size
         UpperCAmelCase      					=  num_channels
         UpperCAmelCase      					=  embeddings_size
         UpperCAmelCase      					=  hidden_sizes
         UpperCAmelCase      					=  depths
         UpperCAmelCase      					=  is_training
         UpperCAmelCase      					=  use_labels
         UpperCAmelCase      					=  hidden_act
         UpperCAmelCase      					=  num_labels
         UpperCAmelCase      					=  scope
         UpperCAmelCase      					=  len(__lowerCamelCase							)





      def 							_lowercase					(		self    :       List[str]							)     -> Optional[Any]:






         """simple docstring"""







         UpperCAmelCase      					=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

         UpperCAmelCase      					=  None
         if self.use_labels:
            UpperCAmelCase      					=  ids_tensor([self.batch_size]       ,							self.num_labels							)

         UpperCAmelCase      					=  self.get_config()

         return config, pixel_values, labels





      def 							_lowercase					(		self    :       List[Any]							)     -> Dict:






         """simple docstring"""







         return ResNetConfig(
             num_channels=self.num_channels       ,							embeddings_size=self.embeddings_size       ,							hidden_sizes=self.hidden_sizes       ,							depths=self.depths       ,							hidden_act=self.hidden_act       ,							num_labels=self.num_labels       ,							image_size=self.image_size       ,							)





      def 							_lowercase					(		self    :       Tuple       ,							__lowerCamelCase    :       Optional[int]       ,							__lowerCamelCase    :       List[str]       ,							__lowerCamelCase    :       Tuple							)     -> str:






         """simple docstring"""







         UpperCAmelCase      					=  TFResNetModel(config=__lowerCamelCase							)
         UpperCAmelCase      					=  model(__lowerCamelCase							)
         # expected last hidden states: B, C, H // 32, W // 32
         self.parent.assertEqual(
             result.last_hidden_state.shape       ,							(self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2)       ,							)





      def 							_lowercase					(		self    :       Optional[Any]       ,							__lowerCamelCase    :       Any       ,							__lowerCamelCase    :       Optional[Any]       ,							__lowerCamelCase    :       int							)     -> Tuple:






         """simple docstring"""







         UpperCAmelCase      					=  self.num_labels
         UpperCAmelCase      					=  TFResNetForImageClassification(__lowerCamelCase							)
         UpperCAmelCase      					=  model(__lowerCamelCase       ,							labels=__lowerCamelCase							)
         self.parent.assertEqual(result.logits.shape       ,							(self.batch_size, self.num_labels)							)





      def 							_lowercase					(		self    :       Optional[int]							)     -> Tuple:






         """simple docstring"""







         UpperCAmelCase      					=  self.prepare_config_and_inputs()
         UpperCAmelCase					,	UpperCAmelCase					,	UpperCAmelCase      					=  config_and_inputs
         UpperCAmelCase      					=  {"""pixel_values""": pixel_values}
         return config, inputs_dict






@require_tf
class 	__lowercase					(	__snake_case			,       __snake_case			,       unittest.TestCase	):
      UpperCamelCase										=							(TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
      UpperCamelCase										=							(
          {'''feature-extraction''': TFResNetModel, '''image-classification''': TFResNetForImageClassification}
          if is_tf_available()
          else {}
      )

      UpperCamelCase										=							False
      UpperCamelCase										=							False
      UpperCamelCase										=							False
      UpperCamelCase										=							False
      UpperCamelCase										=							False





      def 							_lowercase					(		self    :       str							)     -> List[Any]:






         """simple docstring"""







         UpperCAmelCase      					=  TFResNetModelTester(self							)
         UpperCAmelCase      					=  ConfigTester(self       ,							config_class=__lowerCamelCase       ,							has_text_modality=__lowerCamelCase							)





      def 							_lowercase					(		self    :       str							)     -> Dict:






         """simple docstring"""







         self.create_and_test_config_common_properties()
         self.config_tester.create_and_test_config_to_json_string()
         self.config_tester.create_and_test_config_to_json_file()
         self.config_tester.create_and_test_config_from_and_save_pretrained()
         self.config_tester.create_and_test_config_with_num_labels()
         self.config_tester.check_config_can_be_init_without_params()
         self.config_tester.check_config_arguments_init()





      def 							_lowercase					(		self    :       str							)     -> Dict:






         """simple docstring"""







         return





      @unittest.skip(reason="""ResNet does not use inputs_embeds"""							)
      def 							_lowercase					(		self    :       Optional[int]							)     -> Optional[int]:






         """simple docstring"""







         pass





      @unittest.skip(reason="""ResNet does not support input and output embeddings"""							)
      def 							_lowercase					(		self    :       Union[str, Any]							)     -> Tuple:






         """simple docstring"""







         pass





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






         """simple docstring"""







         UpperCAmelCase					,	UpperCAmelCase      					=  self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
            UpperCAmelCase      					=  model_class(__lowerCamelCase							)
            UpperCAmelCase      					=  inspect.signature(model.call							)
            # signature.parameters is an OrderedDict => so arg_names order is deterministic
            UpperCAmelCase      					=  [*signature.parameters.keys()]

            UpperCAmelCase      					=  ["""pixel_values"""]
            self.assertListEqual(arg_names[:1]       ,							__lowerCamelCase							)





      def 							_lowercase					(		self    :       str							)     -> List[Any]:






         """simple docstring"""







         UpperCAmelCase      					=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*__lowerCamelCase							)





      def 							_lowercase					(		self    :       List[Any]							)     -> List[str]:






         """simple docstring"""







         def check_hidden_states_output(__lowerCamelCase    :       str       ,							__lowerCamelCase    :       Dict       ,							__lowerCamelCase    :       Union[str, Any]							):
            UpperCAmelCase      					=  model_class(__lowerCamelCase							)
            UpperCAmelCase      					=  model(**self._prepare_for_class(__lowerCamelCase       ,							__lowerCamelCase							)							)

            UpperCAmelCase      					=  outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

            UpperCAmelCase      					=  self.model_tester.num_stages
            self.assertEqual(len(__lowerCamelCase							)       ,							expected_num_stages + 1							)

            # ResNet's feature maps are of shape (batch_size, num_channels, height, width)
            self.assertListEqual(
                list(hidden_states[0].shape[-2:]							)       ,							[self.model_tester.image_size // 4, self.model_tester.image_size // 4]       ,							)

         UpperCAmelCase					,	UpperCAmelCase      					=  self.model_tester.prepare_config_and_inputs_for_common()
         UpperCAmelCase      					=  ["""basic""", """bottleneck"""]
         for model_class in self.all_model_classes:
            for layer_type in layers_type:
               UpperCAmelCase      					=  layer_type
               UpperCAmelCase      					=  True
               check_hidden_states_output(__lowerCamelCase       ,							__lowerCamelCase       ,							__lowerCamelCase							)

               # check that output_hidden_states also work using config
               del inputs_dict["output_hidden_states"]
               UpperCAmelCase      					=  True

               check_hidden_states_output(__lowerCamelCase       ,							__lowerCamelCase       ,							__lowerCamelCase							)





      def 							_lowercase					(		self    :       Union[str, Any]							)     -> int:






         """simple docstring"""







         UpperCAmelCase      					=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase							)





      @slow
      def 							_lowercase					(		self    :       Tuple							)     -> List[str]:






         """simple docstring"""







         for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            UpperCAmelCase      					=  TFResNetModel.from_pretrained(__lowerCamelCase							)
            self.assertIsNotNone(__lowerCamelCase							)

def 	_UpperCamelCase					(    )    ->int:
   UpperCAmelCase      					=  Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
   return image







@require_tf
@require_vision
class 	__lowercase					(	unittest.TestCase	):





      @cached_property
      def 							_lowercase					(		self    :       List[Any]							)     -> Dict:






         """simple docstring"""







         return (
             AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]							)
             if is_vision_available()
             else None
         )





      @slow
      def 							_lowercase					(		self    :       Dict							)     -> str:






         """simple docstring"""







         UpperCAmelCase      					=  TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]							)

         UpperCAmelCase      					=  self.default_image_processor
         UpperCAmelCase      					=  prepare_img()
         UpperCAmelCase      					=  image_processor(images=__lowerCamelCase       ,							return_tensors="""tf"""							)

         # forward pass
         UpperCAmelCase      					=  model(**__lowerCamelCase							)

         # verify the logits
         UpperCAmelCase      					=  tf.TensorShape((1, 1_0_0_0)							)
         self.assertEqual(outputs.logits.shape       ,							__lowerCamelCase							)

         UpperCAmelCase      					=  tf.constant([-11.1_069, -9.7_877, -8.3_777]							)

         self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()       ,							__lowerCamelCase       ,							atol=1e-4							)							)



