





import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_video_inputs


if is_torch_available():
	import torch

if is_vision_available():
	from PIL import Image

	from transformers import VivitImageProcessor




class 	UpperCamelCase_							(  unittest.TestCase     ):


							def __init__(				self     :str				,					__A     :List[Any]				,					__A     :Optional[Any]=7				,					__A     :int=3				,					__A     :int=10				,					__A     :Dict=18				,					__A     :str=30				,					__A     :Any=400				,					__A     :Dict=True				,					__A     :Any=None				,					__A     :List[str]=True				,					__A     :Dict=[0.5, 0.5, 0.5]				,					__A     :List[str]=[0.5, 0.5, 0.5]				,					__A     :List[str]=None				,					) -> List[Any]:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   size if size is not None else {"""shortest_edge""": 18}
									SCREAMING_SNAKE_CASE__								=   crop_size if crop_size is not None else {"""height""": 18, """width""": 18}

									SCREAMING_SNAKE_CASE__								=   parent
									SCREAMING_SNAKE_CASE__								=   batch_size
									SCREAMING_SNAKE_CASE__								=   num_channels
									SCREAMING_SNAKE_CASE__								=   num_frames
									SCREAMING_SNAKE_CASE__								=   image_size
									SCREAMING_SNAKE_CASE__								=   min_resolution
									SCREAMING_SNAKE_CASE__								=   max_resolution
									SCREAMING_SNAKE_CASE__								=   do_resize
									SCREAMING_SNAKE_CASE__								=   size
									SCREAMING_SNAKE_CASE__								=   do_normalize
									SCREAMING_SNAKE_CASE__								=   image_mean
									SCREAMING_SNAKE_CASE__								=   image_std
									SCREAMING_SNAKE_CASE__								=   crop_size


							def   _snake_case	(				self     :Tuple		) -> str:



									"""simple docstring"""



									return {
									    "image_mean": self.image_mean,
									    "image_std": self.image_std,
									    "do_normalize": self.do_normalize,
									    "do_resize": self.do_resize,
									    "size": self.size,
									    "crop_size": self.crop_size,
									}




@require_torch
@require_vision
class 	UpperCamelCase_							(  UpperCamelCase__					,	unittest.TestCase     ):
							lowerCamelCase_							     =       VivitImageProcessor if is_vision_available() else None


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



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   VivitImageProcessingTester(self		)


							@property
							def   _snake_case	(				self     :Optional[Any]		) -> List[Any]:



									"""simple docstring"""



									return self.image_processor_tester.prepare_image_processor_dict()


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



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   self.image_processing_class(**self.image_processor_dict		)
									self.assertTrue(hasattr(__A				,					"""image_mean"""		)		)
									self.assertTrue(hasattr(__A				,					"""image_std"""		)		)
									self.assertTrue(hasattr(__A				,					"""do_normalize"""		)		)
									self.assertTrue(hasattr(__A				,					"""do_resize"""		)		)
									self.assertTrue(hasattr(__A				,					"""do_center_crop"""		)		)
									self.assertTrue(hasattr(__A				,					"""size"""		)		)


							def   _snake_case	(				self     :Optional[Any]		) -> Dict:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   self.image_processing_class.from_dict(self.image_processor_dict		)
									self.assertEqual(image_processor.size				,					{"""shortest_edge""": 18}		)
									self.assertEqual(image_processor.crop_size				,					{"""height""": 18, """width""": 18}		)

									SCREAMING_SNAKE_CASE__								=   self.image_processing_class.from_dict(self.image_processor_dict				,					size=42				,					crop_size=84		)
									self.assertEqual(image_processor.size				,					{"""shortest_edge""": 42}		)
									self.assertEqual(image_processor.crop_size				,					{"""height""": 84, """width""": 84}		)


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



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   self.image_processing_class(**self.image_processor_dict		)
									# create random PIL videos
									SCREAMING_SNAKE_CASE__								=   prepare_video_inputs(self.image_processor_tester				,					equal_resolution=__A		)
									for video in video_inputs:
											self.assertIsInstance(__A				,					__A		)
											self.assertIsInstance(video[0]				,					Image.Image		)

									# Test not batched input
									SCREAMING_SNAKE_CASE__								=   image_processing(video_inputs[0]				,					return_tensors="""pt"""		).pixel_values
									self.assertEqual(
									    encoded_videos.shape				,					(
									        1,
									        self.image_processor_tester.num_frames,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size["""height"""],
									        self.image_processor_tester.crop_size["""width"""],
									    )				,					)

									# Test batched
									SCREAMING_SNAKE_CASE__								=   image_processing(__A				,					return_tensors="""pt"""		).pixel_values
									self.assertEqual(
									    encoded_videos.shape				,					(
									        self.image_processor_tester.batch_size,
									        self.image_processor_tester.num_frames,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size["""height"""],
									        self.image_processor_tester.crop_size["""width"""],
									    )				,					)


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



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   self.image_processing_class(**self.image_processor_dict		)
									# create random numpy tensors
									SCREAMING_SNAKE_CASE__								=   prepare_video_inputs(self.image_processor_tester				,					equal_resolution=__A				,					numpify=__A		)
									for video in video_inputs:
											self.assertIsInstance(__A				,					__A		)
											self.assertIsInstance(video[0]				,					np.ndarray		)

									# Test not batched input
									SCREAMING_SNAKE_CASE__								=   image_processing(video_inputs[0]				,					return_tensors="""pt"""		).pixel_values
									self.assertEqual(
									    encoded_videos.shape				,					(
									        1,
									        self.image_processor_tester.num_frames,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size["""height"""],
									        self.image_processor_tester.crop_size["""width"""],
									    )				,					)

									# Test batched
									SCREAMING_SNAKE_CASE__								=   image_processing(__A				,					return_tensors="""pt"""		).pixel_values
									self.assertEqual(
									    encoded_videos.shape				,					(
									        self.image_processor_tester.batch_size,
									        self.image_processor_tester.num_frames,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size["""height"""],
									        self.image_processor_tester.crop_size["""width"""],
									    )				,					)


							def   _snake_case	(				self     :int		) -> List[Any]:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=   self.image_processing_class(**self.image_processor_dict		)
									# create random PyTorch tensors
									SCREAMING_SNAKE_CASE__								=   prepare_video_inputs(self.image_processor_tester				,					equal_resolution=__A				,					torchify=__A		)
									for video in video_inputs:
											self.assertIsInstance(__A				,					__A		)
											self.assertIsInstance(video[0]				,					torch.Tensor		)

									# Test not batched input
									SCREAMING_SNAKE_CASE__								=   image_processing(video_inputs[0]				,					return_tensors="""pt"""		).pixel_values
									self.assertEqual(
									    encoded_videos.shape				,					(
									        1,
									        self.image_processor_tester.num_frames,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size["""height"""],
									        self.image_processor_tester.crop_size["""width"""],
									    )				,					)

									# Test batched
									SCREAMING_SNAKE_CASE__								=   image_processing(__A				,					return_tensors="""pt"""		).pixel_values
									self.assertEqual(
									    encoded_videos.shape				,					(
									        self.image_processor_tester.batch_size,
									        self.image_processor_tester.num_frames,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size["""height"""],
									        self.image_processor_tester.crop_size["""width"""],
									    )				,					)


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


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







def 						lowerCamelCase__      ( __A    :int		):


       """simple docstring"""




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







def 						lowerCamelCase__      ( __A    :Any		):


       """simple docstring"""




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







def 						lowerCamelCase__      ( __A    :Any		):


       """simple docstring"""




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







def 						lowerCamelCase__      ( __A    :str	,__A    :int		):


       """simple docstring"""




       if example["hash"] in uniques:
              uniques.remove(example["""hash"""]		)
              return True
       else:
              return False







def 						lowerCamelCase__      ( __A    :Optional[int]	,__A    :int=5		):


       """simple docstring"""




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







def 						lowerCamelCase__      ( __A    :int	,__A    :int=5	,__A    :str=0.05		):


       """simple docstring"""




       __snake_case       	=							["""unit tests""", """test file""", """configuration file"""]
       __snake_case       	=							example["""content"""].splitlines()
       __snake_case       	=							0
       __snake_case       	=							0
       # first test
       for _, line in zip(range(__A		)	,__A		):
              for keyword in keywords:
                     if keyword in line.lower():
                            return {"config_or_test": True}
    # second test
       __snake_case       	=							example["""content"""].count("""\n"""		)
       __snake_case       	=							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__      ( __A    :Dict		):


       """simple docstring"""




       __snake_case       	=							["""def """, """class """, """for """, """while """]
       __snake_case       	=							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__      ( __A    :Dict	,__A    :List[str]=4		):


       """simple docstring"""




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







def 						lowerCamelCase__      ( __A    :str		):


       """simple docstring"""




       __snake_case       	=							tokenizer(example["""content"""]	,truncation=__A		)["""input_ids"""]
       __snake_case       	=							len(example["""content"""]		) / len(__A		)
       return {"ratio": ratio}







def 						lowerCamelCase__      ( __A    :Optional[Any]		):


       """simple docstring"""




       __snake_case       	=							{}
       results.update(get_hash(__A		)		)
       results.update(line_stats(__A		)		)
       results.update(alpha_stats(__A		)		)
       results.update(char_token_ratio(__A		)		)
       results.update(is_autogenerated(__A		)		)
       results.update(is_config_or_test(__A		)		)
       results.update(has_no_keywords(__A		)		)
       results.update(has_few_assignments(__A		)		)
       return results







def 						lowerCamelCase__      ( __A    :int	,__A    :str	,__A    :Dict		):


       """simple docstring"""




       if not check_uniques(__A	,__A		):
              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__      ( __A    :str		):


       """simple docstring"""




       with open(__A	,"""rb"""		) as f_in:
              with gzip.open(str(__A		) + """.gz"""	,"""wb"""	,compresslevel=6		) as f_out:
                     shutil.copyfileobj(__A	,__A		)
       os.unlink(__A		)


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

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

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

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

# Deduplicate data and apply heuristics
UpperCamelCase__		 =     time.time()
UpperCamelCase__		 =     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:
    UpperCamelCase__		 =     time.time()
    UpperCamelCase__ ,UpperCamelCase__		 =     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
UpperCamelCase__		 =     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)

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

UpperCamelCase__		 =     time.time()
for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)):
    UpperCamelCase__		 =     str(data_dir / F'file-{file_number+1:012}.json')
    UpperCamelCase__		 =     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}')

