
'''simple docstring'''






import unittest

import numpy as np
import torch
from torch import nn
from transformers import (
    CLIPImageProcessor,
    CLIPTextConfig,
    CLIPTextModelWithProjection,
    CLIPTokenizer,
    CLIPVisionConfig,
    CLIPVisionModelWithProjection,
)

from diffusers import KandinskyVaaPriorPipeline, PriorTransformer, UnCLIPScheduler
from diffusers.utils import torch_device
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps

from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()

class  UpperCAmelCase__						(       A						,	unittest.TestCase ):
    lowerCAmelCase_				    =		KandinskyVaaPriorPipeline
    lowerCAmelCase_				    =		['prompt']
    lowerCAmelCase_				    =		['prompt', 'negative_prompt']
    lowerCAmelCase_				    =		[
        'num_images_per_prompt',
        'generator',
        'num_inference_steps',
        'latents',
        'negative_prompt',
        'guidance_scale',
        'output_type',
        'return_dict',
    ]
    lowerCAmelCase_				    =		False



    @property
    def   lowerCamelCase_  (	self      :       List[Any]     ):
          return 3_2



    @property
    def   lowerCamelCase_  (	self      :       Union[str, Any]     ):
          return 3_2



    @property
    def   lowerCamelCase_  (	self      :       Optional[int]     ):
          return self.time_input_dim



    @property
    def   lowerCamelCase_  (	self      :       Tuple     ):
          return self.time_input_dim * 4



    @property
    def   lowerCamelCase_  (	self      :       Optional[int]     ):
          return 1_0_0



    @property
    def   lowerCamelCase_  (	self      :       Tuple     ):
          _lowerCamelCase				:   Tuple								=   CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"     )
          return tokenizer



    @property
    def   lowerCamelCase_  (	self      :       Tuple     ):
          torch.manual_seed(0     )
          _lowerCamelCase				:   Optional[int]								=   CLIPTextConfig(
              bos_token_id=0,eos_token_id=2,hidden_size=self.text_embedder_hidden_size,projection_dim=self.text_embedder_hidden_size,intermediate_size=3_7,layer_norm_eps=1e-05,num_attention_heads=4,num_hidden_layers=5,pad_token_id=1,vocab_size=1_0_0_0,)
          return CLIPTextModelWithProjection(__A     )



    @property
    def   lowerCamelCase_  (	self      :       Any     ):
          torch.manual_seed(0     )

          _lowerCamelCase				:   List[str]								=   {
              "num_attention_heads": 2,
              "attention_head_dim": 1_2,
              "embedding_dim": self.text_embedder_hidden_size,
              "num_layers": 1,
          }

          _lowerCamelCase				:   Any								=   PriorTransformer(**__A     )
          # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0
          _lowerCamelCase				:   Optional[Any]								=   nn.Parameter(torch.ones(model.clip_std.shape     )     )
          return model



    @property
    def   lowerCamelCase_  (	self      :       Union[str, Any]     ):
          torch.manual_seed(0     )
          _lowerCamelCase				:   Optional[int]								=   CLIPVisionConfig(
              hidden_size=self.text_embedder_hidden_size,image_size=2_2_4,projection_dim=self.text_embedder_hidden_size,intermediate_size=3_7,num_attention_heads=4,num_channels=3,num_hidden_layers=5,patch_size=1_4,)

          _lowerCamelCase				:   Any								=   CLIPVisionModelWithProjection(__A     )
          return model



    @property
    def   lowerCamelCase_  (	self      :       Tuple     ):
          _lowerCamelCase				:   Any								=   CLIPImageProcessor(
              crop_size=2_2_4,do_center_crop=__A,do_normalize=__A,do_resize=__A,image_mean=[0.48145466, 0.4578275, 0.40821073],image_std=[0.26862954, 0.26130258, 0.27577711],resample=3,size=2_2_4,)

          return image_processor



    def   lowerCamelCase_  (	self      :       Tuple     ):
          _lowerCamelCase				:   Optional[Any]								=   self.dummy_prior
          _lowerCamelCase				:   Any								=   self.dummy_image_encoder
          _lowerCamelCase				:   Any								=   self.dummy_text_encoder
          _lowerCamelCase				:   List[str]								=   self.dummy_tokenizer
          _lowerCamelCase				:   List[str]								=   self.dummy_image_processor

          _lowerCamelCase				:   Optional[Any]								=   UnCLIPScheduler(
              variance_type="fixed_small_log",prediction_type="sample",num_train_timesteps=1_0_0_0,clip_sample=__A,clip_sample_range=10.0,)

          _lowerCamelCase				:   Optional[Any]								=   {
              "prior": prior,
              "image_encoder": image_encoder,
              "text_encoder": text_encoder,
              "tokenizer": tokenizer,
              "scheduler": scheduler,
              "image_processor": image_processor,
          }

          return components



    def   lowerCamelCase_  (	self      :       int,__A      :       List[Any],__A      :       Tuple=0     ):
          if str(__A     ).startswith("mps"     ):
                _lowerCamelCase				:   Any								=   torch.manual_seed(__A     )
          else:
                _lowerCamelCase				:   Optional[int]								=   torch.Generator(device=__A     ).manual_seed(__A     )
          _lowerCamelCase				:   int								=   {
              "prompt": "horse",
              "generator": generator,
              "guidance_scale": 4.0,
              "num_inference_steps": 2,
              "output_type": "np",
          }
          return inputs



    def   lowerCamelCase_  (	self      :       Union[str, Any]     ):
          _lowerCamelCase				:   Tuple								=   "cpu"

          _lowerCamelCase				:   Any								=   self.get_dummy_components()

          _lowerCamelCase				:   int								=   self.pipeline_class(**__A     )
          _lowerCamelCase				:   str								=   pipe.to(__A     )

          pipe.set_progress_bar_config(disable=__A     )

          _lowerCamelCase				:   int								=   pipe(**self.get_dummy_inputs(__A     )     )
          _lowerCamelCase				:   Any								=   output.image_embeds

          _lowerCamelCase				:   Optional[int]								=   pipe(
              **self.get_dummy_inputs(__A     ),return_dict=__A,)[0]

          _lowerCamelCase				:   Any								=   image[0, -1_0:]
          _lowerCamelCase				:   List[str]								=   image_from_tuple[0, -1_0:]

          assert image.shape == (1, 3_2)

          _lowerCamelCase				:   str								=   np.array(
              [-0.0532, 1.7120, 0.3656, -1.0852, -0.8946, -1.1756, 0.4348, 0.2482, 0.5146, -0.1156]     )

          assert np.abs(image_slice.flatten() - expected_slice     ).max() < 1e-2
          assert np.abs(image_from_tuple_slice.flatten() - expected_slice     ).max() < 1e-2



    @skip_mps
    def   lowerCamelCase_  (	self      :       str     ):
          _lowerCamelCase				:   Tuple								=   torch_device == "cpu"
          _lowerCamelCase				:   Optional[int]								=   True
          _lowerCamelCase				:   Dict								=   False

          self._test_inference_batch_single_identical(
              test_max_difference=__A,relax_max_difference=__A,test_mean_pixel_difference=__A,)



    @skip_mps
    def   lowerCamelCase_  (	self      :       List[Any]     ):
          _lowerCamelCase				:   Union[str, Any]								=   torch_device == "cpu"
          _lowerCamelCase				:   Any								=   False

          self._test_attention_slicing_forward_pass(
              test_max_difference=__A,test_mean_pixel_difference=__A,)

'''simple docstring'''






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_       :   Any   =       re.compile(R'\s+')







def 		A_       (	_lowerCAmelCase   :    List[str]							):



      """simple docstring"""




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







def 		A_       (	_lowerCAmelCase   :    Union[str, Any]							):



      """simple docstring"""




      _lowerCamelCase				:   Union[str, Any]								=   [len(_lowerCAmelCase							) for line in example["content"].splitlines()]
      return {"line_mean": np.mean(_lowerCAmelCase							), "line_max": max(_lowerCAmelCase							)}







def 		A_       (	_lowerCAmelCase   :    int							):



      """simple docstring"""




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







def 		A_       (	_lowerCAmelCase   :    str				,	_lowerCAmelCase   :    Tuple							):



      """simple docstring"""




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







def 		A_       (	_lowerCAmelCase   :    Optional[int]				,	_lowerCAmelCase   :    Dict=5							):



      """simple docstring"""




      _lowerCamelCase				:   Optional[int]								=   ["auto-generated", "autogenerated", "automatically generated"]
      _lowerCamelCase				:   Dict								=   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 		A_       (	_lowerCAmelCase   :    List[str]				,	_lowerCAmelCase   :    Optional[Any]=5				,	_lowerCAmelCase   :    List[Any]=0.0_5							):



      """simple docstring"""




      _lowerCamelCase				:   Union[str, Any]								=   ["unit tests", "test file", "configuration file"]
      _lowerCamelCase				:   int								=   example["content"].splitlines()
      _lowerCamelCase				:   int								=   0
      _lowerCamelCase				:   Optional[Any]								=   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				:   Union[str, Any]								=   example["content"].count("\n"							)
      _lowerCamelCase				:   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 		A_       (	_lowerCAmelCase   :    int							):



      """simple docstring"""




      _lowerCamelCase				:   str								=   ["def ", "class ", "for ", "while "]
      _lowerCamelCase				:   List[str]								=   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 		A_       (	_lowerCAmelCase   :    Dict				,	_lowerCAmelCase   :    int=4							):



      """simple docstring"""




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







def 		A_       (	_lowerCAmelCase   :    List[str]							):



      """simple docstring"""




      _lowerCamelCase				:   List[Any]								=   tokenizer(example["content"]				,	truncation=_lowerCAmelCase							)["input_ids"]
      _lowerCamelCase				:   str								=   len(example["content"]							) / len(_lowerCAmelCase							)
      return {"ratio": ratio}







def 		A_       (	_lowerCAmelCase   :    Optional[Any]							):



      """simple docstring"""




      _lowerCamelCase				:   Optional[Any]								=   {}
      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 		A_       (	_lowerCAmelCase   :    Union[str, Any]				,	_lowerCAmelCase   :    Optional[Any]				,	_lowerCAmelCase   :    str							):



      """simple docstring"""




      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 		A_       (	_lowerCAmelCase   :    int							):



      """simple docstring"""




      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
UpperCAmelCase_       :   Any   =       HfArgumentParser(PreprocessingArguments)
UpperCAmelCase_       :   Optional[int]   =       parser.parse_args()
if args.num_workers is None:
 UpperCAmelCase_       :   str   =       multiprocessing.cpu_count()
UpperCAmelCase_       :   Tuple   =       AutoTokenizer.from_pretrained(args.tokenizer_dir)

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

# Run preprocessing
UpperCAmelCase_       :   Tuple   =       time.time()
UpperCAmelCase_       :   Optional[int]   =       ds.map(preprocess, num_proc=args.num_workers)
print(f'''Time to preprocess dataset: {time.time()-t_start:.2f}''')

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

# Deduplicate data and apply heuristics
UpperCAmelCase_       :   Optional[int]   =       time.time()
UpperCAmelCase_       :   int   =       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_       :   Tuple   =       time.time()
 UpperCAmelCase_,   UpperCAmelCase_       :   List[str]   =       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_       :   List[str]   =       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_       :   List[Any]   =       output_dir / 'data'
data_dir.mkdir(exist_ok=True)

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