





"""simple docstring"""




from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from transformers import CLIPImageProcessor, CLIPVisionModel

from ...models import PriorTransformer
from ...pipelines import DiffusionPipeline
from ...schedulers import HeunDiscreteScheduler
from ...utils import (
    BaseOutput,
    is_accelerate_available,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .renderer import ShapERenderer


lowerCamelCase_     :						List[Any]						=					logging.get_logger(__name__)  # pylint: disable=invalid-name

lowerCamelCase_     :						Tuple						=					'\n    Examples:\n        ```py\n        >>> from PIL import Image\n        >>> import torch\n        >>> from diffusers import DiffusionPipeline\n        >>> from diffusers.utils import export_to_gif, load_image\n\n        >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")\n\n        >>> repo = "openai/shap-e-img2img"\n        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n        >>> pipe = pipe.to(device)\n\n        >>> guidance_scale = 3.0\n        >>> image_url = "https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png"\n        >>> image = load_image(image_url).convert("RGB")\n\n        >>> images = pipe(\n        ...     image,\n        ...     guidance_scale=guidance_scale,\n        ...     num_inference_steps=64,\n        ...     frame_size=256,\n        ... ).images\n\n        >>> gif_path = export_to_gif(images[0], "corgi_3d.gif")\n        ```\n'

@dataclass
class  _UpperCAmelCase  (   UpperCAmelCase__		):



      '''simple docstring'''
      lowercase_      : Union[PIL.Image.Image, np.ndarray]


class  _UpperCAmelCase  (   UpperCAmelCase__		):



      '''simple docstring'''

      def __init__(     self					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      ):

        """simple docstring"""

        super().__init__()

        self.register_modules(
            prior=snake_case_					,      image_encoder=snake_case_					,      image_processor=snake_case_					,      scheduler=snake_case_					,      renderer=snake_case_					,      )

      def 					lowerCamelCase_			(     self					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_  ):

        """simple docstring"""

        if latents is None:
          A_  :       List[Any]										=  randn_tensor(snake_case_					,      generator=snake_case_					,      device=snake_case_					,      dtype=snake_case_  )
        else:
          if latents.shape != shape:
            raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {shape}"""  )
          A_  :       Any										=  latents.to(snake_case_  )

        A_  :       str										=  latents * scheduler.init_noise_sigma
        return latents

      def 					lowerCamelCase_			(     self					,      snake_case_=0  ):

        """simple docstring"""

        if is_accelerate_available():
          from accelerate import cpu_offload
        else:
          raise ImportError('Please install accelerate via `pip install accelerate`'  )

        A_  :       Any										=  torch.device(F"""cuda:{gpu_id}"""  )

        A_  :       Optional[Any]										=  [self.image_encoder, self.prior]
        for cpu_offloaded_model in models:
          if cpu_offloaded_model is not None:
            cpu_offload(snake_case_					,      snake_case_  )

      @property
      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        if self.device != torch.device('meta'  ) or not hasattr(self.image_encoder					,      '_hf_hook'  ):
          return self.device
        for module in self.image_encoder.modules():
          if (
              hasattr(snake_case_					,      '_hf_hook'  )
              and hasattr(module._hf_hook					,      'execution_device'  )
              and module._hf_hook.execution_device is not None
          ):
            return torch.device(module._hf_hook.execution_device  )
        return self.device

      def 					lowerCamelCase_			(     self					,      snake_case_					,      snake_case_					,      snake_case_					,      snake_case_					,      ):

        """simple docstring"""

        if isinstance(snake_case_					,      snake_case_  ) and isinstance(image[0]					,      torch.Tensor  ):
          A_  :       List[Any]										=  torch.cat(snake_case_					,      axis=0  ) if image[0].ndim == 4 else torch.stack(snake_case_					,      axis=0  )

        if not isinstance(snake_case_					,      torch.Tensor  ):
          A_  :       str										=  self.image_processor(snake_case_					,      return_tensors='pt'  ).pixel_values[0].unsqueeze(0  )

        A_  :       Union[str, Any]										=  image.to(dtype=self.image_encoder.dtype					,      device=snake_case_  )

        A_  :       Any										=  self.image_encoder(snake_case_  )['last_hidden_state']
        A_  :       List[Any]										=  image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

        A_  :       List[str]										=  image_embeds.repeat_interleave(snake_case_					,      dim=0  )

        if do_classifier_free_guidance:
          A_  :       Tuple										=  torch.zeros_like(snake_case_  )

          # For classifier free guidance, we need to do two forward passes.
          # Here we concatenate the unconditional and text embeddings into a single batch
          # to avoid doing two forward passes
          A_  :       str										=  torch.cat([negative_image_embeds, image_embeds]  )

        return image_embeds

      @torch.no_grad()
      @replace_example_docstring(snake_case_  )
      def __call__(     self					,      snake_case_					,      snake_case_ = 1					,      snake_case_ = 2_5					,      snake_case_ = None					,      snake_case_ = None					,      snake_case_ = 4.0					,      snake_case_ = 6_4					,      snake_case_ = "pil"					,      snake_case_ = True					,      ):

        """simple docstring"""

        if isinstance(snake_case_					,      PIL.Image.Image  ):
          A_  :       Any										=  1
        elif isinstance(snake_case_					,      torch.Tensor  ):
          A_  :       Any										=  image.shape[0]
        elif isinstance(snake_case_					,      snake_case_  ) and isinstance(image[0]					,      (torch.Tensor, PIL.Image.Image)  ):
          A_  :       Union[str, Any]										=  len(snake_case_  )
        else:
          raise ValueError(
              F"""`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(snake_case_  )}"""  )

        A_  :       Any										=  self._execution_device

        A_  :       Optional[int]										=  batch_size * num_images_per_prompt

        A_  :       int										=  guidance_scale > 1.0
        A_  :       Optional[int]										=  self._encode_image(snake_case_					,      snake_case_					,      snake_case_					,      snake_case_  )

        # prior

        self.scheduler.set_timesteps(snake_case_					,      device=snake_case_  )
        A_  :       int										=  self.scheduler.timesteps

        A_  :       Tuple										=  self.prior.config.num_embeddings
        A_  :       List[str]										=  self.prior.config.embedding_dim

        A_  :       int										=  self.prepare_latents(
            (batch_size, num_embeddings * embedding_dim)					,      image_embeds.dtype					,      snake_case_					,      snake_case_					,      snake_case_					,      self.scheduler					,      )

        # YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim
        A_  :       List[str]										=  latents.reshape(latents.shape[0]					,      snake_case_					,      snake_case_  )

        for i, t in enumerate(self.progress_bar(snake_case_  )  ):
          # expand the latents if we are doing classifier free guidance
          A_  :       str										=  torch.cat([latents] * 2  ) if do_classifier_free_guidance else latents
          A_  :       List[Any]										=  self.scheduler.scale_model_input(snake_case_					,      snake_case_  )

          A_  :       Union[str, Any]										=  self.prior(
              snake_case_					,      timestep=snake_case_					,      proj_embedding=snake_case_					,      ).predicted_image_embedding

          # remove the variance
          A_						,       A_  :       Tuple										=  noise_pred.split(
              scaled_model_input.shape[2]					,      dim=2  )  # batch_size, num_embeddings, embedding_dim

          if do_classifier_free_guidance is not None:
            A_						,       A_  :       List[Any]										=  noise_pred.chunk(2  )
            A_  :       List[Any]										=  noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

          A_  :       List[Any]										=  self.scheduler.step(
              snake_case_					,      timestep=snake_case_					,      sample=snake_case_					,      ).prev_sample

        if output_type == "latent":
          return ShapEPipelineOutput(images=snake_case_  )

        A_  :       Optional[Any]										=  []
        for i, latent in enumerate(snake_case_  ):
          print()
          A_  :       str										=  self.renderer.decode(
              latent[None, :]					,      snake_case_					,      size=snake_case_					,      ray_batch_size=4_0_9_6					,      n_coarse_samples=6_4					,      n_fine_samples=1_2_8					,      )

          images.append(snake_case_  )

        A_  :       Union[str, Any]										=  torch.stack(snake_case_  )

        if output_type not in ["np", "pil"]:
          raise ValueError(F"""Only the output types `pil` and `np` are supported not output_type={output_type}"""  )

        A_  :       str										=  images.cpu().numpy()

        if output_type == "pil":
          A_  :       Optional[Any]										=  [self.numpy_to_pil(snake_case_  ) for image in images]

        # Offload last model to CPU
        if hasattr(self					,      'final_offload_hook'  ) and self.final_offload_hook is not None:
          self.final_offload_hook.offload()

        if not return_dict:
          return (images,)

        return ShapEPipelineOutput(images=snake_case_  )






"""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


lowerCamelCase_     :						Any						=					re.compile(r'\s+')





def 						UpperCAmelCase__		(     _UpperCAmelCase					):






  """simple docstring"""





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





def 						UpperCAmelCase__		(     _UpperCAmelCase					):






  """simple docstring"""





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





def 						UpperCAmelCase__		(     _UpperCAmelCase					):






  """simple docstring"""





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





def 						UpperCAmelCase__		(     _UpperCAmelCase ,					_UpperCAmelCase					):






  """simple docstring"""





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





def 						UpperCAmelCase__		(     _UpperCAmelCase ,					_UpperCAmelCase=5					):






  """simple docstring"""





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





def 						UpperCAmelCase__		(     _UpperCAmelCase ,					_UpperCAmelCase=5 ,					_UpperCAmelCase=0.05					):






  """simple docstring"""





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






  """simple docstring"""





  A_  :       List[Any]										=  ['def ', 'class ', 'for ', 'while ']
  A_  :       Tuple										=  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 						UpperCAmelCase__		(     _UpperCAmelCase ,					_UpperCAmelCase=4					):






  """simple docstring"""





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





def 						UpperCAmelCase__		(     _UpperCAmelCase					):






  """simple docstring"""





  A_  :       Optional[Any]										=  tokenizer(example['content'] ,					truncation=_UpperCAmelCase					)['input_ids']
  A_  :       Dict										=  len(example['content']					) / len(_UpperCAmelCase					)
  return {"ratio": ratio}





def 						UpperCAmelCase__		(     _UpperCAmelCase					):






  """simple docstring"""





  A_  :       Any										=  {}
  results.update(get_hash(_UpperCAmelCase					)					)
  results.update(line_stats(_UpperCAmelCase					)					)
  results.update(alpha_stats(_UpperCAmelCase					)					)
  results.update(char_token_ratio(_UpperCAmelCase					)					)
  results.update(is_autogenerated(_UpperCAmelCase					)					)
  results.update(is_config_or_test(_UpperCAmelCase					)					)
  results.update(has_no_keywords(_UpperCAmelCase					)					)
  results.update(has_few_assignments(_UpperCAmelCase					)					)
  return results





def 						UpperCAmelCase__		(     _UpperCAmelCase ,					_UpperCAmelCase ,					_UpperCAmelCase					):






  """simple docstring"""





  if not check_uniques(_UpperCAmelCase ,					_UpperCAmelCase					):
    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 						UpperCAmelCase__		(     _UpperCAmelCase					):






  """simple docstring"""





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


# Settings
lowerCamelCase_     :						Optional[int]						=					HfArgumentParser(PreprocessingArguments)
lowerCamelCase_     :						Optional[Any]						=					parser.parse_args()
if args.num_workers is None:
   lowerCamelCase_     :						int						=					multiprocessing.cpu_count()
lowerCamelCase_     :						Tuple						=					AutoTokenizer.from_pretrained(args.tokenizer_dir)

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

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

# Deduplicate hashes
lowerCamelCase_     :						int						=					set(ds.unique('hash'))
lowerCamelCase_     :						Union[str, Any]						=					len(uniques) / len(ds)
print(F"Fraction of duplicates: {1-frac:.2%}")

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

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