
import gzip
import hashlib
import json
import multiprocessing
import os
import re
import shutil
import time
from pathlib import Path

import numpy as np
from arguments import PreprocessingArguments
from datasets import load_dataset
from minhash_deduplication import deduplicate_dataset

from transformers import AutoTokenizer, HfArgumentParser


lowerCAmelCase__     						=			re.compile(r'\s+')






def 				__lowerCamelCase		(						lowerCAmelCase__     ):
       return {"hash": hashlib.mda(re.sub(lowerCAmelCase__     ,  ''     ,  example['content']     ).encode('utf-8'     )     ).hexdigest()}






def 				__lowerCamelCase		(						lowerCAmelCase__     ):
       lowerCAmelCase__					     = [len(lowerCAmelCase__     ) for line in example['content'].splitlines()]
       return {"line_mean": np.mean(lowerCAmelCase__     ), "line_max": max(lowerCAmelCase__     )}






def 				__lowerCamelCase		(						lowerCAmelCase__     ):
       lowerCAmelCase__					     = np.mean([c.isalnum() for c in example['content']]     )
       return {"alpha_frac": alpha_frac}






def 				__lowerCamelCase		(						lowerCAmelCase__     ,  lowerCAmelCase__     ):
       if example["hash"] in uniques:
              uniques.remove(example['hash']     )
              return True
       else:
              return False






def 				__lowerCamelCase		(						lowerCAmelCase__     ,  lowerCAmelCase__=5     ):
       lowerCAmelCase__					     = ['auto-generated', 'autogenerated', 'automatically generated']
       lowerCAmelCase__					     = example['content'].splitlines()
       for _, line in zip(range(lowerCAmelCase__     )     ,  lowerCAmelCase__     ):
              for keyword in keywords:
                     if keyword in line.lower():
                            return {"autogenerated": True}
       else:
              return {"autogenerated": False}






def 				__lowerCamelCase		(						lowerCAmelCase__     ,  lowerCAmelCase__=5     ,  lowerCAmelCase__=0.0_5     ):
       lowerCAmelCase__					     = ['unit tests', 'test file', 'configuration file']
       lowerCAmelCase__					     = example['content'].splitlines()
       lowerCAmelCase__					     = 0
       lowerCAmelCase__					     = 0
       # first test
       for _, line in zip(range(lowerCAmelCase__     )     ,  lowerCAmelCase__     ):
              for keyword in keywords:
                     if keyword in line.lower():
                            return {"config_or_test": True}
    # second test
       lowerCAmelCase__					     = example['content'].count('\n'     )
       lowerCAmelCase__					     = int(coeff * nlines     )
       for line in lines:
              count_config += line.lower().count('config'     )
              count_test += line.lower().count('test'     )
              if count_config > threshold or count_test > threshold:
                     return {"config_or_test": True}
       return {"config_or_test": False}






def 				__lowerCamelCase		(						lowerCAmelCase__     ):
       lowerCAmelCase__					     = ['def ', 'class ', 'for ', 'while ']
       lowerCAmelCase__					     = example['content'].splitlines()
       for line in lines:
              for keyword in keywords:
                     if keyword in line.lower():
                            return {"has_no_keywords": False}
       return {"has_no_keywords": True}






def 				__lowerCamelCase		(						lowerCAmelCase__     ,  lowerCAmelCase__=4     ):
       lowerCAmelCase__					     = example['content'].splitlines()
       lowerCAmelCase__					     = 0
       for line in lines:
              counter += line.lower().count('='     )
              if counter > minimum:
                     return {"has_few_assignments": False}
       return {"has_few_assignments": True}






def 				__lowerCamelCase		(						lowerCAmelCase__     ):
       lowerCAmelCase__					     = tokenizer(example['content']     ,  truncation=lowerCAmelCase__     )['input_ids']
       lowerCAmelCase__					     = len(example['content']     ) / len(lowerCAmelCase__     )
       return {"ratio": ratio}






def 				__lowerCamelCase		(						lowerCAmelCase__     ):
       lowerCAmelCase__					     = {}
       results.update(get_hash(lowerCAmelCase__     )     )
       results.update(line_stats(lowerCAmelCase__     )     )
       results.update(alpha_stats(lowerCAmelCase__     )     )
       results.update(char_token_ratio(lowerCAmelCase__     )     )
       results.update(is_autogenerated(lowerCAmelCase__     )     )
       results.update(is_config_or_test(lowerCAmelCase__     )     )
       results.update(has_no_keywords(lowerCAmelCase__     )     )
       results.update(has_few_assignments(lowerCAmelCase__     )     )
       return results






def 				__lowerCamelCase		(						lowerCAmelCase__     ,  lowerCAmelCase__     ,  lowerCAmelCase__     ):
       if not check_uniques(lowerCAmelCase__     ,  lowerCAmelCase__     ):
              return False
       elif example["autogenerated"]:
              return False
       elif example["line_max"] > args.line_max:
              return False
       elif example["line_mean"] > args.line_mean:
              return False
       elif example["alpha_frac"] < args.alpha_frac:
              return False
       elif example["ratio"] < args.min_token_ratio:
              return False
       elif example["config_or_test"] and np.random.rand() <= args.filter_proba:
              return False
       elif example["has_no_keywords"] and np.random.rand() <= args.filter_proba:
              return False
       elif example["has_few_assignments"]:
              return False
       else:
              return True






def 				__lowerCamelCase		(						lowerCAmelCase__     ):
       with open(lowerCAmelCase__     ,  'rb'     ) as f_in:
              with gzip.open(str(lowerCAmelCase__     ) + '.gz'     ,  'wb'     ,  compresslevel=6     ) as f_out:
                     shutil.copyfileobj(lowerCAmelCase__     ,  lowerCAmelCase__     )
       os.unlink(lowerCAmelCase__     )


# Settings
lowerCAmelCase__     						=			HfArgumentParser(PreprocessingArguments)
lowerCAmelCase__     						=			parser.parse_args()
if args.num_workers is None:
    lowerCAmelCase__     						=			multiprocessing.cpu_count()
lowerCAmelCase__     						=			AutoTokenizer.from_pretrained(args.tokenizer_dir)

# Load dataset
lowerCAmelCase__     						=			time.time()
lowerCAmelCase__     						=			load_dataset(args.dataset_name, split='train')
print(F'Time to load dataset: {time.time()-t_start:.2f}')

# Run preprocessing
lowerCAmelCase__     						=			time.time()
lowerCAmelCase__     						=			ds.map(preprocess, num_proc=args.num_workers)
print(F'Time to preprocess dataset: {time.time()-t_start:.2f}')

# Deduplicate hashes
lowerCAmelCase__     						=			set(ds.unique('hash'))
lowerCAmelCase__     						=			len(uniques) / len(ds)
print(F'Fraction of duplicates: {1-frac:.2%}')

# Deduplicate data and apply heuristics
lowerCAmelCase__     						=			time.time()
lowerCAmelCase__     						=			ds.filter(filter, fn_kwargs={'uniques': uniques, 'args': args})
print(F'Time to filter dataset: {time.time()-t_start:.2f}')
print(F'Size of filtered dataset: {len(ds_filter)}')

# Deduplicate with minhash and jaccard similarity
if args.near_deduplication:
    lowerCAmelCase__     						=			time.time()
    lowerCAmelCase__						,		lowerCAmelCase__     						=			deduplicate_dataset(ds_filter, args.jaccard_threshold)
    print(F'Time to deduplicate dataset: {time.time()-t_start:.2f}')
    print(F'Size of deduplicate dataset: {len(ds_filter)}')

# Save data in batches of samples_per_file
lowerCAmelCase__     						=			Path(args.output_dir)
output_dir.mkdir(exist_ok=True)

# save duplicate_clusters in the output_dir as artifacts
# not sure it is the right place the save it
if args.near_deduplication:
    with open(output_dir / 'duplicate_clusters.json', 'w') as f:
        json.dump(duplicate_clusters, f)

lowerCAmelCase__     						=			output_dir / 'data'
data_dir.mkdir(exist_ok=True)

lowerCAmelCase__     						=			time.time()
for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)):
    lowerCAmelCase__     						=			str(data_dir / F'file-{file_number+1:012}.json')
    lowerCAmelCase__     						=			min(len(ds_filter), index + args.samples_per_file)
    ds_filter.select(list(range(index, end_index))).to_json(file_path)
    compress_file(file_path)



print(F'Time to save dataset: {time.time()-t_start:.2f}')

from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import convert_to_rgb, normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    OPENAI_CLIP_MEAN,
    OPENAI_CLIP_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
    import PIL


lowerCAmelCase__     						=			logging.get_logger(__name__)
class     a_			(						SCREAMING_SNAKE_CASE						):






 '''simple docstring'''






 UpperCAmelCase_     			= ['pixel_values']




 def __init__(      self :  Tuple      ,   lowercase__ :  bool = True      ,   lowercase__ :  Dict[str, int] = None      ,   lowercase__ :  PILImageResampling = PILImageResampling.BICUBIC      ,   lowercase__ :  bool = True      ,   lowercase__ :  Union[int, float] = 1 / 255      ,   lowercase__ :  bool = True      ,   lowercase__ :  Optional[Union[float, List[float]]] = None      ,   lowercase__ :  Optional[Union[float, List[float]]] = None      ,   lowercase__ :  bool = True      ,   **lowercase__ :  List[Any]      ,   ):







        '''simple docstring'''



        super().__init__(**lowercase__)
        lowerCAmelCase__					     = size if size is not None else {'height': 384, 'width': 384}
        lowerCAmelCase__					     = get_size_dict(lowercase__      ,   default_to_square=lowercase__)

        lowerCAmelCase__					     = do_resize
        lowerCAmelCase__					     = size
        lowerCAmelCase__					     = resample
        lowerCAmelCase__					     = do_rescale
        lowerCAmelCase__					     = rescale_factor
        lowerCAmelCase__					     = do_normalize
        lowerCAmelCase__					     = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
        lowerCAmelCase__					     = image_std if image_std is not None else OPENAI_CLIP_STD
        lowerCAmelCase__					     = do_convert_rgb




 def 		__snake_case						(      self :  List[str]      ,   lowercase__ :  np.ndarray      ,   lowercase__ :  Dict[str, int]      ,   lowercase__ :  PILImageResampling = PILImageResampling.BICUBIC      ,   lowercase__ :  Optional[Union[str, ChannelDimension]] = None      ,   **lowercase__ :  Dict      ,   ):







        '''simple docstring'''



        lowerCAmelCase__					     = get_size_dict(lowercase__      ,   default_to_square=lowercase__)
        if "height" not in size or "width" not in size:
               raise ValueError(F"""The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}""")
        lowerCAmelCase__					     = (size['height'], size['width'])
        return resize(lowercase__      ,   size=lowercase__      ,   resample=lowercase__      ,   data_format=lowercase__      ,   **lowercase__)




 def 		__snake_case						(      self :  List[str]      ,   lowercase__ :  np.ndarray      ,   lowercase__ :  Union[int, float]      ,   lowercase__ :  Optional[Union[str, ChannelDimension]] = None      ,   **lowercase__ :  Union[str, Any]      ,   ):







        '''simple docstring'''



        return rescale(lowercase__      ,   scale=lowercase__      ,   data_format=lowercase__      ,   **lowercase__)




 def 		__snake_case						(      self :  Optional[Any]      ,   lowercase__ :  np.ndarray      ,   lowercase__ :  Union[float, List[float]]      ,   lowercase__ :  Union[float, List[float]]      ,   lowercase__ :  Optional[Union[str, ChannelDimension]] = None      ,   **lowercase__ :  Any      ,   ):







        '''simple docstring'''



        return normalize(lowercase__      ,   mean=lowercase__      ,   std=lowercase__      ,   data_format=lowercase__      ,   **lowercase__)




 def 		__snake_case						(      self :  Any      ,   lowercase__ :  ImageInput      ,   lowercase__ :  Optional[bool] = None      ,   lowercase__ :  Optional[Dict[str, int]] = None      ,   lowercase__ :  PILImageResampling = None      ,   lowercase__ :  Optional[bool] = None      ,   lowercase__ :  Optional[float] = None      ,   lowercase__ :  Optional[bool] = None      ,   lowercase__ :  Optional[Union[float, List[float]]] = None      ,   lowercase__ :  Optional[Union[float, List[float]]] = None      ,   lowercase__ :  Optional[Union[str, TensorType]] = None      ,   lowercase__ :  bool = None      ,   lowercase__ :  ChannelDimension = ChannelDimension.FIRST      ,   **lowercase__ :  Dict      ,   ):







        '''simple docstring'''



        lowerCAmelCase__					     = do_resize if do_resize is not None else self.do_resize
        lowerCAmelCase__					     = resample if resample is not None else self.resample
        lowerCAmelCase__					     = do_rescale if do_rescale is not None else self.do_rescale
        lowerCAmelCase__					     = rescale_factor if rescale_factor is not None else self.rescale_factor
        lowerCAmelCase__					     = do_normalize if do_normalize is not None else self.do_normalize
        lowerCAmelCase__					     = image_mean if image_mean is not None else self.image_mean
        lowerCAmelCase__					     = image_std if image_std is not None else self.image_std
        lowerCAmelCase__					     = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

        lowerCAmelCase__					     = size if size is not None else self.size
        lowerCAmelCase__					     = get_size_dict(lowercase__      ,   default_to_square=lowercase__)

        lowerCAmelCase__					     = make_list_of_images(lowercase__)

        if not valid_images(lowercase__):
               raise ValueError(
                   'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '
                   'torch.Tensor, tf.Tensor or jax.ndarray.')

        if do_resize and size is None or resample is None:
               raise ValueError('Size and resample must be specified if do_resize is True.')

        if do_rescale and rescale_factor is None:
               raise ValueError('Rescale factor must be specified if do_rescale is True.')

        if do_normalize and (image_mean is None or image_std is None):
               raise ValueError('Image mean and std must be specified if do_normalize is True.')

        # PIL RGBA images are converted to RGB
        if do_convert_rgb:
               lowerCAmelCase__					     = [convert_to_rgb(lowercase__) for image in images]

        # All transformations expect numpy arrays.
        lowerCAmelCase__					     = [to_numpy_array(lowercase__) for image in images]

        if do_resize:
               lowerCAmelCase__					     = [self.resize(image=lowercase__      ,   size=lowercase__      ,   resample=lowercase__) for image in images]

        if do_rescale:
               lowerCAmelCase__					     = [self.rescale(image=lowercase__      ,   scale=lowercase__) for image in images]

        if do_normalize:
               lowerCAmelCase__					     = [self.normalize(image=lowercase__      ,   mean=lowercase__      ,   std=lowercase__) for image in images]

        lowerCAmelCase__					     = [to_channel_dimension_format(lowercase__      ,   lowercase__) for image in images]

        lowerCAmelCase__					     = BatchFeature(data={'pixel_values': images}      ,   tensor_type=lowercase__)

        return encoded_outputs
