



from __future__ import annotations

import math
import random
from typing import Any





class 		UpperCAmelCase						:





   def __init__(	self			):
         _lowerCAmelCase 			=  []
         _lowerCAmelCase 			=  0
         _lowerCAmelCase 			=  0





   def 	__lowerCAmelCase							(	self			):
         return self.head == self.tail





   def 	__lowerCAmelCase							(	self       ,     _lowerCAmelCase			):
         self.data.append(_lowerCAmelCase			)
         _lowerCAmelCase 			=  self.tail + 1





   def 	__lowerCAmelCase							(	self			):
         _lowerCAmelCase 			=  self.data[self.head]
         _lowerCAmelCase 			=  self.head + 1
         return ret





   def 	__lowerCAmelCase							(	self			):
         return self.tail - self.head





   def 	__lowerCAmelCase							(	self			):
         print(self.data			)
         print('''**************'''			)
         print(self.data[self.head : self.tail]			)






class 		UpperCAmelCase						:





   def __init__(	self       ,     _lowerCAmelCase			):
         _lowerCAmelCase 			=  data
         _lowerCAmelCase 			=  None
         _lowerCAmelCase 			=  None
         _lowerCAmelCase 			=  1





   def 	__lowerCAmelCase							(	self			):
         return self.data





   def 	__lowerCAmelCase							(	self			):
         return self.left





   def 	__lowerCAmelCase							(	self			):
         return self.right





   def 	__lowerCAmelCase							(	self			):
         return self.height





   def 	__lowerCAmelCase							(	self       ,     _lowerCAmelCase			):
         _lowerCAmelCase 			=  data





   def 	__lowerCAmelCase							(	self       ,     _lowerCAmelCase			):
         _lowerCAmelCase 			=  node





   def 	__lowerCAmelCase							(	self       ,     _lowerCAmelCase			):
         _lowerCAmelCase 			=  node





   def 	__lowerCAmelCase							(	self       ,     _lowerCAmelCase			):
         _lowerCAmelCase 			=  height






def 							UpperCAmelCase__		(				_SCREAMING_SNAKE_CASE   :	MyNode | None				)->int:
      if node is None:
            return 0
      return node.get_height()
def 							UpperCAmelCase__		(				_SCREAMING_SNAKE_CASE   :	int     ,				_SCREAMING_SNAKE_CASE   :	int				)->int:
      if a > b:
            return a
      return b
def 							UpperCAmelCase__		(				_SCREAMING_SNAKE_CASE   :	MyNode				)->MyNode:
      print('''left rotation node:'''     ,				node.get_data()				)
      _lowerCAmelCase 			=  node.get_left()
      assert ret is not None
      node.set_left(ret.get_right()				)
      ret.set_right(_SCREAMING_SNAKE_CASE				)
      _lowerCAmelCase 			=  my_max(get_height(node.get_right()				)     ,				get_height(node.get_left()				)				) + 1
      node.set_height(_SCREAMING_SNAKE_CASE				)
      _lowerCAmelCase 			=  my_max(get_height(ret.get_right()				)     ,				get_height(ret.get_left()				)				) + 1
      ret.set_height(_SCREAMING_SNAKE_CASE				)
      return ret
def 							UpperCAmelCase__		(				_SCREAMING_SNAKE_CASE   :	MyNode				)->MyNode:
      print('''right rotation node:'''     ,				node.get_data()				)
      _lowerCAmelCase 			=  node.get_right()
      assert ret is not None
      node.set_right(ret.get_left()				)
      ret.set_left(_SCREAMING_SNAKE_CASE				)
      _lowerCAmelCase 			=  my_max(get_height(node.get_right()				)     ,				get_height(node.get_left()				)				) + 1
      node.set_height(_SCREAMING_SNAKE_CASE				)
      _lowerCAmelCase 			=  my_max(get_height(ret.get_right()				)     ,				get_height(ret.get_left()				)				) + 1
      ret.set_height(_SCREAMING_SNAKE_CASE				)
      return ret
def 							UpperCAmelCase__		(				_SCREAMING_SNAKE_CASE   :	MyNode				)->MyNode:
      _lowerCAmelCase 			=  node.get_left()
      assert left_child is not None
      node.set_left(left_rotation(_SCREAMING_SNAKE_CASE				)				)
      return right_rotation(_SCREAMING_SNAKE_CASE				)
def 							UpperCAmelCase__		(				_SCREAMING_SNAKE_CASE   :	MyNode				)->MyNode:
      _lowerCAmelCase 			=  node.get_right()
      assert right_child is not None
      node.set_right(right_rotation(_SCREAMING_SNAKE_CASE				)				)
      return left_rotation(_SCREAMING_SNAKE_CASE				)
def 							UpperCAmelCase__		(				_SCREAMING_SNAKE_CASE   :	MyNode | None     ,				_SCREAMING_SNAKE_CASE   :	Any				)->MyNode | None:
      if node is None:
            return MyNode(_SCREAMING_SNAKE_CASE				)
      if data < node.get_data():
            node.set_left(insert_node(node.get_left()     ,				_SCREAMING_SNAKE_CASE				)				)
            if (
                get_height(node.get_left()				) - get_height(node.get_right()				) == 2
            ):  # an unbalance detected
                  _lowerCAmelCase 			=  node.get_left()
                  assert left_child is not None
                  if (
                      data < left_child.get_data()
                  ):  # new node is the left child of the left child
                        _lowerCAmelCase 			=  right_rotation(_SCREAMING_SNAKE_CASE				)
                  else:
                        _lowerCAmelCase 			=  lr_rotation(_SCREAMING_SNAKE_CASE				)
      else:
            node.set_right(insert_node(node.get_right()     ,				_SCREAMING_SNAKE_CASE				)				)
            if get_height(node.get_right()				) - get_height(node.get_left()				) == 2:
                  _lowerCAmelCase 			=  node.get_right()
                  assert right_child is not None
                  if data < right_child.get_data():
                        _lowerCAmelCase 			=  rl_rotation(_SCREAMING_SNAKE_CASE				)
                  else:
                        _lowerCAmelCase 			=  left_rotation(_SCREAMING_SNAKE_CASE				)
      _lowerCAmelCase 			=  my_max(get_height(node.get_right()				)     ,				get_height(node.get_left()				)				) + 1
      node.set_height(_SCREAMING_SNAKE_CASE				)
      return node
def 							UpperCAmelCase__		(				_SCREAMING_SNAKE_CASE   :	MyNode				)->Any:
      while True:
            _lowerCAmelCase 			=  root.get_right()
            if right_child is None:
                  break
            _lowerCAmelCase 			=  right_child
      return root.get_data()
def 							UpperCAmelCase__		(				_SCREAMING_SNAKE_CASE   :	MyNode				)->Any:
      while True:
            _lowerCAmelCase 			=  root.get_left()
            if left_child is None:
                  break
            _lowerCAmelCase 			=  left_child
      return root.get_data()
def 							UpperCAmelCase__		(				_SCREAMING_SNAKE_CASE   :	MyNode     ,				_SCREAMING_SNAKE_CASE   :	Any				)->MyNode | None:
      _lowerCAmelCase 			=  root.get_left()
      _lowerCAmelCase 			=  root.get_right()
      if root.get_data() == data:
            if left_child is not None and right_child is not None:
                  _lowerCAmelCase 			=  get_left_most(_SCREAMING_SNAKE_CASE				)
                  root.set_data(_SCREAMING_SNAKE_CASE				)
                  root.set_right(del_node(_SCREAMING_SNAKE_CASE     ,				_SCREAMING_SNAKE_CASE				)				)
            elif left_child is not None:
                  _lowerCAmelCase 			=  left_child
            elif right_child is not None:
                  _lowerCAmelCase 			=  right_child
            else:
                  return None
      elif root.get_data() > data:
            if left_child is None:
                  print('''No such data'''				)
                  return root
            else:
                  root.set_left(del_node(_SCREAMING_SNAKE_CASE     ,				_SCREAMING_SNAKE_CASE				)				)
      else:  # root.get_data() < data
            if right_child is None:
                  return root
            else:
                  root.set_right(del_node(_SCREAMING_SNAKE_CASE     ,				_SCREAMING_SNAKE_CASE				)				)

      if get_height(_SCREAMING_SNAKE_CASE				) - get_height(_SCREAMING_SNAKE_CASE				) == 2:
            assert right_child is not None
            if get_height(right_child.get_right()				) > get_height(right_child.get_left()				):
                  _lowerCAmelCase 			=  left_rotation(_SCREAMING_SNAKE_CASE				)
            else:
                  _lowerCAmelCase 			=  rl_rotation(_SCREAMING_SNAKE_CASE				)
      elif get_height(_SCREAMING_SNAKE_CASE				) - get_height(_SCREAMING_SNAKE_CASE				) == -2:
            assert left_child is not None
            if get_height(left_child.get_left()				) > get_height(left_child.get_right()				):
                  _lowerCAmelCase 			=  right_rotation(_SCREAMING_SNAKE_CASE				)
            else:
                  _lowerCAmelCase 			=  lr_rotation(_SCREAMING_SNAKE_CASE				)
      _lowerCAmelCase 			=  my_max(get_height(root.get_right()				)     ,				get_height(root.get_left()				)				) + 1
      root.set_height(_SCREAMING_SNAKE_CASE				)
      return root





class 		UpperCAmelCase						:





   def __init__(	self			):
         _lowerCAmelCase 			=  None





   def 	__lowerCAmelCase							(	self			):
         return get_height(self.root			)





   def 	__lowerCAmelCase							(	self       ,     _lowerCAmelCase			):
         print('''insert:''' + str(_lowerCAmelCase			)			)
         _lowerCAmelCase 			=  insert_node(self.root       ,     _lowerCAmelCase			)





   def 	__lowerCAmelCase							(	self       ,     _lowerCAmelCase			):
         print('''delete:''' + str(_lowerCAmelCase			)			)
         if self.root is None:
               print('''Tree is empty!'''			)
               return
         _lowerCAmelCase 			=  del_node(self.root       ,     _lowerCAmelCase			)





   def __str__(	self       ,     ):  # a level traversale, gives a more intuitive look on the tree
         _lowerCAmelCase 			=  ''''''
         _lowerCAmelCase 			=  MyQueue()
         q.push(self.root			)
         _lowerCAmelCase 			=  self.get_height()
         if layer == 0:
               return output
         _lowerCAmelCase 			=  0
         while not q.is_empty():
               _lowerCAmelCase 			=  q.pop()
               _lowerCAmelCase 			=  ''' ''' * int(math.pow(2       ,     layer - 1			)			)
               output += space
               if node is None:
                     output += "*"
                     q.push(_lowerCAmelCase			)
                     q.push(_lowerCAmelCase			)
               else:
                     output += str(node.get_data()			)
                     q.push(node.get_left()			)
                     q.push(node.get_right()			)
               output += space
               _lowerCAmelCase 			=  cnt + 1
               for i in range(100			):
                     if cnt == math.pow(2       ,     _lowerCAmelCase			) - 1:
                           _lowerCAmelCase 			=  layer - 1
                           if layer == 0:
                                 output += "\n*************************************"
                                 return output
                           output += "\n"
                           break
         output += "\n*************************************"
         return output






def 							UpperCAmelCase__		(				)->None:
      import doctest

      doctest.testmod()


if __name__ == "__main__":
    _test()
    UpperCAmelCase_									=							AVLtree()
    UpperCAmelCase_									=							list(range(1_0))
    random.shuffle(lst)
    for i in lst:
        t.insert(i)
        print(str(t))
    random.shuffle(lst)
    for i in lst:
        t.del_node(i)
        print(str(t))




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


UpperCAmelCase_									=							re.compile("[^A-Za-z_0-9]")
# parameters used in DuplicationIndex
UpperCAmelCase_									=							1_0
UpperCAmelCase_									=							2_5_6
def 							UpperCAmelCase__		(				_SCREAMING_SNAKE_CASE   :	List[str]				)->Optional[MinHash]:
      if len(_SCREAMING_SNAKE_CASE				) < MIN_NUM_TOKENS:
            return None
      _lowerCAmelCase 			=  MinHash(num_perm=_SCREAMING_SNAKE_CASE				)
      for token in set(_SCREAMING_SNAKE_CASE				):
            min_hash.update(token.encode()				)
      return min_hash
def 							UpperCAmelCase__		(				_SCREAMING_SNAKE_CASE   :	str				)->Set[str]:
      return {t for t in NON_ALPHA.split(_SCREAMING_SNAKE_CASE				) if len(t.strip()				) > 0}





class 		UpperCAmelCase						:





   def __init__(	self       ,     *,
       _lowerCAmelCase = 0.85       ,     ):
         _lowerCAmelCase 			=  duplication_jaccard_threshold
         _lowerCAmelCase 			=  NUM_PERM
         _lowerCAmelCase 			=  MinHashLSH(threshold=self._duplication_jaccard_threshold       ,     num_perm=self._num_perm			)

         _lowerCAmelCase 			=  defaultdict(_lowerCAmelCase			)





   def 	__lowerCAmelCase							(	self       ,     _lowerCAmelCase       ,     _lowerCAmelCase			):
         _lowerCAmelCase 			=  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 	__lowerCAmelCase							(	self			):
         _lowerCAmelCase 			=  []
         for base, duplicates in self._duplicate_clusters.items():
               _lowerCAmelCase 			=  [base] + list(_lowerCAmelCase			)
               # reformat the cluster to be a list of dict
               _lowerCAmelCase 			=  [{'''base_index''': el[0], '''repo_name''': el[1], '''path''': el[2]} for el in cluster]
               duplicate_clusters.append(_lowerCAmelCase			)
         return duplicate_clusters





   def 	__lowerCAmelCase							(	self       ,     _lowerCAmelCase			):
         _lowerCAmelCase 			=  self.get_duplicate_clusters()
         with open(_lowerCAmelCase       ,     '''w'''			) as f:
               json.dump(_lowerCAmelCase       ,     _lowerCAmelCase			)






def 							UpperCAmelCase__		(				_SCREAMING_SNAKE_CASE   :	str				)->Optional[Any]:
      _lowerCAmelCase			,   _lowerCAmelCase 			=  element
      _lowerCAmelCase 			=  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__		(				_SCREAMING_SNAKE_CASE   :	Type[Dataset]				)->Any:
      with mp.Pool() as pool:
            for data in pool.imap_unordered(
                _compute_min_hash     ,				ThreadedIterator(_SCREAMING_SNAKE_CASE     ,				max_queue_size=1_0_0_0_0				)     ,				chunksize=1_0_0     ,				):
                  if data is not None:
                        yield data
def 							UpperCAmelCase__		(				_SCREAMING_SNAKE_CASE   :	Type[Dataset]     ,				_SCREAMING_SNAKE_CASE   :	float				)->str:
      _lowerCAmelCase 			=  DuplicationIndex(duplication_jaccard_threshold=_SCREAMING_SNAKE_CASE				)

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

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


UpperCAmelCase_									=							None
def 							UpperCAmelCase__		(				_SCREAMING_SNAKE_CASE   :	Optional[Any]     ,				_SCREAMING_SNAKE_CASE   :	Any				)->List[Any]:
      _lowerCAmelCase 			=  []
      for elementa in cluster:
            _lowerCAmelCase 			=  _shared_dataset[elementa['''base_index''']]['''content''']
            for elementa in extremes:
                  _lowerCAmelCase 			=  _shared_dataset[elementa['''base_index''']]['''content''']
                  if jaccard_similarity(_SCREAMING_SNAKE_CASE     ,				_SCREAMING_SNAKE_CASE				) >= jaccard_threshold:
                        elementa["copies"] += 1
                        break
            else:
                  _lowerCAmelCase 			=  1
                  extremes.append(_SCREAMING_SNAKE_CASE				)
      return extremes
def 							UpperCAmelCase__		(				_SCREAMING_SNAKE_CASE   :	List[Any]     ,				_SCREAMING_SNAKE_CASE   :	Tuple     ,				_SCREAMING_SNAKE_CASE   :	str				)->Tuple:
      global _shared_dataset
      _lowerCAmelCase 			=  dataset
      _lowerCAmelCase 			=  []
      _lowerCAmelCase 			=  partial(_find_cluster_extremes_shared     ,				jaccard_threshold=_SCREAMING_SNAKE_CASE				)
      with mp.Pool() as pool:
            for extremes in tqdm(
                pool.imap_unordered(
                    _SCREAMING_SNAKE_CASE     ,				_SCREAMING_SNAKE_CASE     ,				)     ,				total=len(_SCREAMING_SNAKE_CASE				)     ,				):
                  extremes_list.append(_SCREAMING_SNAKE_CASE				)
      return extremes_list


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

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

      print(f'''Original dataset size: {len(_SCREAMING_SNAKE_CASE				)}'''				)
      print(f'''Number of duplicate clusters: {len(_SCREAMING_SNAKE_CASE				)}'''				)
      print(f'''Files in duplicate cluster: {len(_SCREAMING_SNAKE_CASE				)}'''				)
      print(f'''Unique files in duplicate cluster: {len(_SCREAMING_SNAKE_CASE				)}'''				)
      print(f'''Filtered dataset size: {len(_SCREAMING_SNAKE_CASE				)}'''				)

      return ds_filter, duplicate_clusters