






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


SCREAMING_SNAKE_CASE__   :      Union[str, Any]				=		re.compile(r"""\s+""")

def   __lowercase       (			snake_case			):







				"""simple docstring"""






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

def   __lowercase       (			snake_case			):







				"""simple docstring"""






				__magic_name__		:List[Any]   =   [len(snake_case			) for line in example['''content'''].splitlines()]
				return {"line_mean": np.mean(snake_case			), "line_max": max(snake_case			)}

def   __lowercase       (			snake_case			):







				"""simple docstring"""






				__magic_name__		:Union[str, Any]   =   np.mean([c.isalnum() for c in example['''content''']]			)
				return {"alpha_frac": alpha_frac}

def   __lowercase       (			snake_case,	snake_case			):







				"""simple docstring"""






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

def   __lowercase       (			snake_case,	snake_case=5			):







				"""simple docstring"""






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

def   __lowercase       (			snake_case,	snake_case=5,	snake_case=0.05			):







				"""simple docstring"""






				__magic_name__		:str   =   ['''unit tests''', '''test file''', '''configuration file''']
				__magic_name__		:Optional[Any]   =   example['''content'''].splitlines()
				__magic_name__		:Any   =   0
				__magic_name__		:List[Any]   =   0
				# first test
				for _, line in zip(range(snake_case			),	snake_case			):
								for keyword in keywords:
												if keyword in line.lower():
																return {"config_or_test": True}
    # second test
				__magic_name__		:List[str]   =   example['''content'''].count('''\n'''			)
				__magic_name__		:Optional[Any]   =   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   __lowercase       (			snake_case			):







				"""simple docstring"""






				__magic_name__		:Optional[int]   =   ['''def ''', '''class ''', '''for ''', '''while ''']
				__magic_name__		:int   =   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   __lowercase       (			snake_case,	snake_case=4			):







				"""simple docstring"""






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

def   __lowercase       (			snake_case			):







				"""simple docstring"""






				__magic_name__		:List[Any]   =   tokenizer(example['''content'''],	truncation=snake_case			)['''input_ids''']
				__magic_name__		:Optional[Any]   =   len(example['''content''']			) / len(snake_case			)
				return {"ratio": ratio}

def   __lowercase       (			snake_case			):







				"""simple docstring"""






				__magic_name__		:Union[str, Any]   =   {}
				results.update(get_hash(snake_case			)			)
				results.update(line_stats(snake_case			)			)
				results.update(alpha_stats(snake_case			)			)
				results.update(char_token_ratio(snake_case			)			)
				results.update(is_autogenerated(snake_case			)			)
				results.update(is_config_or_test(snake_case			)			)
				results.update(has_no_keywords(snake_case			)			)
				results.update(has_few_assignments(snake_case			)			)
				return results

def   __lowercase       (			snake_case,	snake_case,	snake_case			):







				"""simple docstring"""






				if not check_uniques(snake_case,	snake_case			):
								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   __lowercase       (			snake_case			):







				"""simple docstring"""






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


# Settings
SCREAMING_SNAKE_CASE__   :      int				=		HfArgumentParser(PreprocessingArguments)
SCREAMING_SNAKE_CASE__   :      Union[str, Any]				=		parser.parse_args()
if args.num_workers is None:
					SCREAMING_SNAKE_CASE__   :      Tuple				=		multiprocessing.cpu_count()
SCREAMING_SNAKE_CASE__   :      List[Any]				=		AutoTokenizer.from_pretrained(args.tokenizer_dir)

# Load dataset
SCREAMING_SNAKE_CASE__   :      List[Any]				=		time.time()
SCREAMING_SNAKE_CASE__   :      List[Any]				=		load_dataset(args.dataset_name, split="""train""")
print(f"Time to load dataset: {time.time()-t_start:.2f}")

# Run preprocessing
SCREAMING_SNAKE_CASE__   :      Union[str, Any]				=		time.time()
SCREAMING_SNAKE_CASE__   :      Optional[int]				=		ds.map(preprocess, num_proc=args.num_workers)
print(f"Time to preprocess dataset: {time.time()-t_start:.2f}")

# Deduplicate hashes
SCREAMING_SNAKE_CASE__   :      int				=		set(ds.unique("""hash"""))
SCREAMING_SNAKE_CASE__   :      List[Any]				=		len(uniques) / len(ds)
print(f"Fraction of duplicates: {1-frac:.2%}")

# Deduplicate data and apply heuristics
SCREAMING_SNAKE_CASE__   :      int				=		time.time()
SCREAMING_SNAKE_CASE__   :      List[Any]				=		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:
					SCREAMING_SNAKE_CASE__   :      List[Any]				=		time.time()
					SCREAMING_SNAKE_CASE__				,       SCREAMING_SNAKE_CASE__   :      Dict				=		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
SCREAMING_SNAKE_CASE__   :      Any				=		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)

SCREAMING_SNAKE_CASE__   :      Optional[Any]				=		output_dir / """data"""
data_dir.mkdir(exist_ok=True)

SCREAMING_SNAKE_CASE__   :      Union[str, Any]				=		time.time()
for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)):
					SCREAMING_SNAKE_CASE__   :      str				=		str(data_dir / f"file-{file_number+1:012}.json")
					SCREAMING_SNAKE_CASE__   :      Tuple				=		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}")









import unittest

from transformers import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING, is_vision_available, pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
 from PIL import Image
else:






 class 						__magic_name__					:






      @staticmethod
      def 	UpperCAmelCase_				(				*_lowercase		,						**_lowercase	)->     Optional[int]:
          pass






@is_pipeline_test
@require_vision
@require_torch
class 						__magic_name__					(							unittest.TestCase				):
     UpperCamelCase_	:Optional[Any]										=      MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING






     def 	UpperCAmelCase_				(				self		,						_lowercase		,						_lowercase		,						_lowercase	)->     Union[str, Any]:
         UpperCamelCase_			  =						pipeline(
             "zero-shot-object-detection"		,						model="hf-internal-testing/tiny-random-owlvit-object-detection"	)

         UpperCamelCase_			  =						[
             {
                 "image": "./tests/fixtures/tests_samples/COCO/000000039769.png",
                 "candidate_labels": ["cat", "remote", "couch"],
             }
         ]
         return object_detector, examples






     def 	UpperCAmelCase_				(				self		,						_lowercase		,						_lowercase	)->     Union[str, Any]:
         UpperCamelCase_			  =						object_detector(examples[0]		,						threshold=0.0	)

         UpperCamelCase_			  =						len(_lowercase	)
         self.assertGreater(_lowercase		,						0	)
         self.assertEqual(
             _lowercase		,						[
                 {
                     "score": ANY(_lowercase	),
                     "label": ANY(_lowercase	),
                     "box": {"xmin": ANY(_lowercase	), "ymin": ANY(_lowercase	), "xmax": ANY(_lowercase	), "ymax": ANY(_lowercase	)},
                 }
                 for i in range(_lowercase	)
             ]		,						)






     @require_tf
     @unittest.skip("Zero Shot Object Detection not implemented in TF"	)
     def 	UpperCAmelCase_				(				self	)->     str:
         pass






     @require_torch
     def 	UpperCAmelCase_				(				self	)->     List[Any]:
         UpperCamelCase_			  =						pipeline(
             "zero-shot-object-detection"		,						model="hf-internal-testing/tiny-random-owlvit-object-detection"	)

         UpperCamelCase_			  =						object_detector(
             "./tests/fixtures/tests_samples/COCO/000000039769.png"		,						candidate_labels=["cat", "remote", "couch"]		,						threshold=0.64		,						)

         self.assertEqual(
             nested_simplify(_lowercase		,						decimals=4	)		,						[
                 {"score": 0.7_235, "label": "cat", "box": {"xmin": 204, "ymin": 167, "xmax": 232, "ymax": 190}},
                 {"score": 0.7_218, "label": "remote", "box": {"xmin": 204, "ymin": 167, "xmax": 232, "ymax": 190}},
                 {"score": 0.7_184, "label": "couch", "box": {"xmin": 204, "ymin": 167, "xmax": 232, "ymax": 190}},
                 {"score": 0.6_748, "label": "remote", "box": {"xmin": 571, "ymin": 83, "xmax": 598, "ymax": 103}},
                 {"score": 0.6_656, "label": "cat", "box": {"xmin": 571, "ymin": 83, "xmax": 598, "ymax": 103}},
                 {"score": 0.6_614, "label": "couch", "box": {"xmin": 571, "ymin": 83, "xmax": 598, "ymax": 103}},
                 {"score": 0.6_456, "label": "remote", "box": {"xmin": 494, "ymin": 105, "xmax": 521, "ymax": 127}},
                 {"score": 0.642, "label": "remote", "box": {"xmin": 67, "ymin": 274, "xmax": 93, "ymax": 297}},
                 {"score": 0.6_419, "label": "cat", "box": {"xmin": 494, "ymin": 105, "xmax": 521, "ymax": 127}},
             ]		,						)

         UpperCamelCase_			  =						object_detector(
             [
                 {
                     "image": "./tests/fixtures/tests_samples/COCO/000000039769.png",
                     "candidate_labels": ["cat", "remote", "couch"],
                 }
             ]		,						threshold=0.64		,						)

         self.assertEqual(
             nested_simplify(_lowercase		,						decimals=4	)		,						[
                 [
                     {"score": 0.7_235, "label": "cat", "box": {"xmin": 204, "ymin": 167, "xmax": 232, "ymax": 190}},
                     {"score": 0.7_218, "label": "remote", "box": {"xmin": 204, "ymin": 167, "xmax": 232, "ymax": 190}},
                     {"score": 0.7_184, "label": "couch", "box": {"xmin": 204, "ymin": 167, "xmax": 232, "ymax": 190}},
                     {"score": 0.6_748, "label": "remote", "box": {"xmin": 571, "ymin": 83, "xmax": 598, "ymax": 103}},
                     {"score": 0.6_656, "label": "cat", "box": {"xmin": 571, "ymin": 83, "xmax": 598, "ymax": 103}},
                     {"score": 0.6_614, "label": "couch", "box": {"xmin": 571, "ymin": 83, "xmax": 598, "ymax": 103}},
                     {"score": 0.6_456, "label": "remote", "box": {"xmin": 494, "ymin": 105, "xmax": 521, "ymax": 127}},
                     {"score": 0.642, "label": "remote", "box": {"xmin": 67, "ymin": 274, "xmax": 93, "ymax": 297}},
                     {"score": 0.6_419, "label": "cat", "box": {"xmin": 494, "ymin": 105, "xmax": 521, "ymax": 127}},
                 ]
             ]		,						)






     @require_torch
     @slow
     def 	UpperCAmelCase_				(				self	)->     Any:
         UpperCamelCase_			  =						pipeline("zero-shot-object-detection"	)

         UpperCamelCase_			  =						object_detector(
             "http://images.cocodataset.org/val2017/000000039769.jpg"		,						candidate_labels=["cat", "remote", "couch"]		,						)
         self.assertEqual(
             nested_simplify(_lowercase		,						decimals=4	)		,						[
                 {"score": 0.2_868, "label": "cat", "box": {"xmin": 324, "ymin": 20, "xmax": 640, "ymax": 373}},
                 {"score": 0.277, "label": "remote", "box": {"xmin": 40, "ymin": 72, "xmax": 177, "ymax": 115}},
                 {"score": 0.2_537, "label": "cat", "box": {"xmin": 1, "ymin": 55, "xmax": 315, "ymax": 472}},
                 {"score": 0.1_474, "label": "remote", "box": {"xmin": 335, "ymin": 74, "xmax": 371, "ymax": 187}},
                 {"score": 0.1_208, "label": "couch", "box": {"xmin": 4, "ymin": 0, "xmax": 642, "ymax": 476}},
             ]		,						)

         UpperCamelCase_			  =						object_detector(
             [
                 {
                     "image": "http://images.cocodataset.org/val2017/000000039769.jpg",
                     "candidate_labels": ["cat", "remote", "couch"],
                 },
                 {
                     "image": "http://images.cocodataset.org/val2017/000000039769.jpg",
                     "candidate_labels": ["cat", "remote", "couch"],
                 },
             ]		,						)
         self.assertEqual(
             nested_simplify(_lowercase		,						decimals=4	)		,						[
                 [
                     {"score": 0.2_868, "label": "cat", "box": {"xmin": 324, "ymin": 20, "xmax": 640, "ymax": 373}},
                     {"score": 0.277, "label": "remote", "box": {"xmin": 40, "ymin": 72, "xmax": 177, "ymax": 115}},
                     {"score": 0.2_537, "label": "cat", "box": {"xmin": 1, "ymin": 55, "xmax": 315, "ymax": 472}},
                     {"score": 0.1_474, "label": "remote", "box": {"xmin": 335, "ymin": 74, "xmax": 371, "ymax": 187}},
                     {"score": 0.1_208, "label": "couch", "box": {"xmin": 4, "ymin": 0, "xmax": 642, "ymax": 476}},
                 ],
                 [
                     {"score": 0.2_868, "label": "cat", "box": {"xmin": 324, "ymin": 20, "xmax": 640, "ymax": 373}},
                     {"score": 0.277, "label": "remote", "box": {"xmin": 40, "ymin": 72, "xmax": 177, "ymax": 115}},
                     {"score": 0.2_537, "label": "cat", "box": {"xmin": 1, "ymin": 55, "xmax": 315, "ymax": 472}},
                     {"score": 0.1_474, "label": "remote", "box": {"xmin": 335, "ymin": 74, "xmax": 371, "ymax": 187}},
                     {"score": 0.1_208, "label": "couch", "box": {"xmin": 4, "ymin": 0, "xmax": 642, "ymax": 476}},
                 ],
             ]		,						)






     @require_tf
     @unittest.skip("Zero Shot Object Detection not implemented in TF"	)
     def 	UpperCAmelCase_				(				self	)->     Optional[int]:
         pass






     @require_torch
     @slow
     def 	UpperCAmelCase_				(				self	)->     Optional[Any]:
         UpperCamelCase_			  =						0.2
         UpperCamelCase_			  =						pipeline("zero-shot-object-detection"	)

         UpperCamelCase_			  =						object_detector(
             "http://images.cocodataset.org/val2017/000000039769.jpg"		,						candidate_labels=["cat", "remote", "couch"]		,						threshold=_lowercase		,						)
         self.assertEqual(
             nested_simplify(_lowercase		,						decimals=4	)		,						[
                 {"score": 0.2_868, "label": "cat", "box": {"xmin": 324, "ymin": 20, "xmax": 640, "ymax": 373}},
                 {"score": 0.277, "label": "remote", "box": {"xmin": 40, "ymin": 72, "xmax": 177, "ymax": 115}},
                 {"score": 0.2_537, "label": "cat", "box": {"xmin": 1, "ymin": 55, "xmax": 315, "ymax": 472}},
             ]		,						)






     @require_torch
     @slow
     def 	UpperCAmelCase_				(				self	)->     Optional[int]:
         UpperCamelCase_			  =						2
         UpperCamelCase_			  =						pipeline("zero-shot-object-detection"	)

         UpperCamelCase_			  =						object_detector(
             "http://images.cocodataset.org/val2017/000000039769.jpg"		,						candidate_labels=["cat", "remote", "couch"]		,						top_k=_lowercase		,						)
         self.assertEqual(
             nested_simplify(_lowercase		,						decimals=4	)		,						[
                 {"score": 0.2_868, "label": "cat", "box": {"xmin": 324, "ymin": 20, "xmax": 640, "ymax": 373}},
                 {"score": 0.277, "label": "remote", "box": {"xmin": 40, "ymin": 72, "xmax": 177, "ymax": 115}},
             ]		,						)
