




"""simple docstring"""





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    (			UpperCamelCase							)			->			Optional[MinHash]:


			"""simple docstring"""
			if len(UpperCamelCase							) < MIN_NUM_TOKENS:
						return None
			__UpperCAmelCase	: Dict		=					MinHash(num_perm=UpperCamelCase							)
			for token in set(UpperCamelCase							):
						min_hash.update(token.encode()							)
			return min_hash

def 					_UpperCamelCase    (			UpperCamelCase							)			->			Set[str]:


			"""simple docstring"""
			return {t for t in NON_ALPHA.split(UpperCamelCase							) if len(t.strip()							) > 0}



class      A				:


			def __init__(      self      :    List[Any]      ,  *,
			    UpperCamelCase_      :    float = 0.85      ,  ):


						"""simple docstring"""




						__UpperCAmelCase	: Optional[Any]		=					duplication_jaccard_threshold
						__UpperCAmelCase	: List[Any]		=					NUM_PERM
						__UpperCAmelCase	: Union[str, Any]		=					MinHashLSH(threshold=self._duplication_jaccard_threshold      ,  num_perm=self._num_perm)

						__UpperCAmelCase	: Optional[int]		=					defaultdict(UpperCamelCase_)


			def       a_     (      self      :    str      ,  UpperCamelCase_      :    Tuple      ,  UpperCamelCase_      :    MinHash):


						"""simple docstring"""




						__UpperCAmelCase	: Optional[Any]		=					self._index.query(UpperCamelCase_)
						if code_key in self._index.keys:
									print(F"Duplicate key {code_key}")
									return

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


			def       a_     (      self      :    Optional[Any]):


						"""simple docstring"""




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


			def       a_     (      self      :    List[str]      ,  UpperCamelCase_      :    int):


						"""simple docstring"""




						__UpperCAmelCase	: Tuple		=					self.get_duplicate_clusters()
						with open(UpperCamelCase_      ,  "w") as f:
									json.dump(UpperCamelCase_      ,  UpperCamelCase_)






def 					_UpperCamelCase    (			UpperCamelCase							)			->			Tuple:


			"""simple docstring"""
			__UpperCAmelCase	: Optional[int]		=					element
			__UpperCAmelCase	: Optional[Any]		=					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    (			UpperCamelCase							)			->			Optional[Any]:


			"""simple docstring"""
			with mp.Pool() as pool:
						for data in pool.imap_unordered(
						    _compute_min_hash				,       ThreadedIterator(UpperCamelCase				,       max_queue_size=1_0000							)				,       chunksize=100				,       ):
									if data is not None:
												yield data

def 					_UpperCamelCase    (			UpperCamelCase				,       UpperCamelCase							)			->			int:


			"""simple docstring"""
			__UpperCAmelCase	: Optional[int]		=					DuplicationIndex(duplication_jaccard_threshold=UpperCamelCase							)

			for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(UpperCamelCase							)							)				,       max_queue_size=100							)							):
						di.add(UpperCamelCase				,       UpperCamelCase							)

			# Returns a List[Cluster] where Cluster is List[str] with the filenames.
			return di.get_duplicate_clusters()

def 					_UpperCamelCase    (			UpperCamelCase				,       UpperCamelCase							)			->			float:


			"""simple docstring"""
			__UpperCAmelCase	: Optional[Any]		=					get_tokens(UpperCamelCase							)
			__UpperCAmelCase	: List[str]		=					get_tokens(UpperCamelCase							)
			return len(tokensa & tokensa							) / len(tokensa | tokensa							)


A   =       None

def 					_UpperCamelCase    (			UpperCamelCase				,       UpperCamelCase							)			->			str:


			"""simple docstring"""
			__UpperCAmelCase	: Optional[Any]		=					[]
			for elementa in cluster:
						__UpperCAmelCase	: List[str]		=					_shared_dataset[elementa["base_index"]]["content"]
						for elementa in extremes:
									__UpperCAmelCase	: Any		=					_shared_dataset[elementa["base_index"]]["content"]
									if jaccard_similarity(UpperCamelCase				,       UpperCamelCase							) >= jaccard_threshold:
												elementa["copies"] += 1
												break
						else:
									__UpperCAmelCase	: Union[str, Any]		=					1
									extremes.append(UpperCamelCase							)
			return extremes

def 					_UpperCamelCase    (			UpperCamelCase				,       UpperCamelCase				,       UpperCamelCase							)			->			Tuple:


			"""simple docstring"""
			global _shared_dataset
			__UpperCAmelCase	: Dict		=					dataset
			__UpperCAmelCase	: List[Any]		=					[]
			__UpperCAmelCase	: List[Any]		=					partial(_find_cluster_extremes_shared				,       jaccard_threshold=UpperCamelCase							)
			with mp.Pool() as pool:
						for extremes in tqdm(
						    pool.imap_unordered(
						        UpperCamelCase				,       UpperCamelCase				,       )				,       total=len(UpperCamelCase							)				,       ):
									extremes_list.append(UpperCamelCase							)
			return extremes_list





def 					_UpperCamelCase    (			UpperCamelCase				,       UpperCamelCase = 0.85							)			->			Tuple[Type[Dataset], List[List[Dict]]]:


			"""simple docstring"""
			__UpperCAmelCase	: List[str]		=					make_duplicate_clusters(UpperCamelCase				,       UpperCamelCase							)
			__UpperCAmelCase	: Optional[int]		=					{x["base_index"] for cluster in duplicate_clusters for x in cluster}
			__UpperCAmelCase	: int		=					{}
			__UpperCAmelCase	: Optional[int]		=					find_extremes(UpperCamelCase				,       UpperCamelCase				,       UpperCamelCase							)
			for extremes in extremes_clusters:
						for element in extremes:
									__UpperCAmelCase	: Union[str, Any]		=					element
			__UpperCAmelCase	: Optional[int]		=					duplicate_indices - set(extreme_dict.keys()							)
			__UpperCAmelCase	: List[str]		=					dataset.filter(lambda UpperCamelCase				,       UpperCamelCase							: idx not in remove_indices				,       with_indices=UpperCamelCase							)

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

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

			return ds_filter, duplicate_clusters








"""simple docstring"""





import json
import logging
import os
import socket

import git
import numpy as np
import torch


logging.basicConfig(
    format="""%(asctime)s - %(levelname)s - %(name)s - PID: %(process)d -  %(message)s""",
    datefmt="""%m/%d/%Y %H:%M:%S""",
    level=logging.INFO,
)
A   =       logging.getLogger(__name__)

def 					_UpperCamelCase    (			UpperCamelCase							)			->			Any:


			"""simple docstring"""
			__UpperCAmelCase	: Optional[Any]		=					git.Repo(search_parent_directories=UpperCamelCase							)
			__UpperCAmelCase	: Any		=					{
			    "repo_id": str(UpperCamelCase							),
			    "repo_sha": str(repo.head.object.hexsha							),
			    "repo_branch": str(repo.active_branch							),
			}

			with open(os.path.join(UpperCamelCase				,       "git_log.json"							)				,       "w"							) as f:
						json.dump(UpperCamelCase				,       UpperCamelCase				,       indent=4							)

def 					_UpperCamelCase    (			UpperCamelCase							)			->			str:


			"""simple docstring"""
			if params.n_gpu <= 0:
						__UpperCAmelCase	: str		=					0
						__UpperCAmelCase	: Dict		=					-1
						__UpperCAmelCase	: Tuple		=					True
						__UpperCAmelCase	: List[str]		=					False
						return

			assert torch.cuda.is_available()

			logger.info("Initializing GPUs"							)
			if params.n_gpu > 1:
						assert params.local_rank != -1

						__UpperCAmelCase	: Optional[int]		=					int(os.environ["WORLD_SIZE"]							)
						__UpperCAmelCase	: Union[str, Any]		=					int(os.environ["N_GPU_NODE"]							)
						__UpperCAmelCase	: Optional[int]		=					int(os.environ["RANK"]							)

						# number of nodes / node ID
						__UpperCAmelCase	: int		=					params.world_size // params.n_gpu_per_node
						__UpperCAmelCase	: Optional[int]		=					params.global_rank // params.n_gpu_per_node
						__UpperCAmelCase	: Tuple		=					True

						assert params.n_nodes == int(os.environ["N_NODES"]							)
						assert params.node_id == int(os.environ["NODE_RANK"]							)

			# local job (single GPU)
			else:
						assert params.local_rank == -1

						__UpperCAmelCase	: Union[str, Any]		=					1
						__UpperCAmelCase	: Dict		=					0
						__UpperCAmelCase	: List[Any]		=					0
						__UpperCAmelCase	: Tuple		=					0
						__UpperCAmelCase	: Any		=					1
						__UpperCAmelCase	: str		=					1
						__UpperCAmelCase	: Dict		=					False

			# sanity checks
			assert params.n_nodes >= 1
			assert 0 <= params.node_id < params.n_nodes
			assert 0 <= params.local_rank <= params.global_rank < params.world_size
			assert params.world_size == params.n_nodes * params.n_gpu_per_node

			# define whether this is the master process / if we are in multi-node distributed mode
			__UpperCAmelCase	: Union[str, Any]		=					params.node_id == 0 and params.local_rank == 0
			__UpperCAmelCase	: Dict		=					params.n_nodes > 1

			# summary
			__UpperCAmelCase	: Any		=					f"--- Global rank: {params.global_rank} - "
			logger.info(PREFIX + "Number of nodes: %i" % params.n_nodes							)
			logger.info(PREFIX + "Node ID        : %i" % params.node_id							)
			logger.info(PREFIX + "Local rank     : %i" % params.local_rank							)
			logger.info(PREFIX + "World size     : %i" % params.world_size							)
			logger.info(PREFIX + "GPUs per node  : %i" % params.n_gpu_per_node							)
			logger.info(PREFIX + "Master         : %s" % str(params.is_master							)							)
			logger.info(PREFIX + "Multi-node     : %s" % str(params.multi_node							)							)
			logger.info(PREFIX + "Multi-GPU      : %s" % str(params.multi_gpu							)							)
			logger.info(PREFIX + "Hostname       : %s" % socket.gethostname()							)

			# set GPU device
			torch.cuda.set_device(params.local_rank							)

			# initialize multi-GPU
			if params.multi_gpu:
						logger.info("Initializing PyTorch distributed"							)
						torch.distributed.init_process_group(
						    init_method="env://"				,       backend="nccl"				,       )





def 					_UpperCamelCase    (			UpperCamelCase							)			->			Tuple:


			"""simple docstring"""
			np.random.seed(args.seed							)
			torch.manual_seed(args.seed							)
			if args.n_gpu > 0:
						torch.cuda.manual_seed_all(args.seed							)


