

from collections import Counter
from pathlib import Path
from typing import Optional, Tuple

import yaml






class  UpperCAmelCase__	( yaml.SafeLoader ):






  """simple docstring"""


  def    lowercase_	(							self		:	Optional[int]			,     __lowerCamelCase		:	int      )	->							Union[str, Any]:
       SCREAMING_SNAKE_CASE__					=					[self.constructed_objects[key_node] for key_node, _ in node.value]
       SCREAMING_SNAKE_CASE__					=					[tuple(__lowerCamelCase      ) if isinstance(__lowerCamelCase			,     __lowerCamelCase      ) else key for key in keys]
       SCREAMING_SNAKE_CASE__					=					Counter(__lowerCamelCase      )
       SCREAMING_SNAKE_CASE__					=					[key for key in counter if counter[key] > 1]
       if duplicate_keys:
            raise TypeError(f'''Got duplicate yaml keys: {duplicate_keys}'''      )







  def    lowercase_	(							self		:	Optional[Any]			,     __lowerCamelCase		:	List[Any]			,     __lowerCamelCase		:	Dict=False      )	->							Union[str, Any]:
       SCREAMING_SNAKE_CASE__					=					super().construct_mapping(__lowerCamelCase			,     deep=__lowerCamelCase      )
       self._check_no_duplicates_on_constructed_node(__lowerCamelCase      )
       return mapping



def        UpperCAmelCase_     (		_A       ):





     '''simple docstring'''




     SCREAMING_SNAKE_CASE__					=					list(readme_content.splitlines()       )
     if full_content and full_content[0] == "---" and "---" in full_content[1:]:
          SCREAMING_SNAKE_CASE__					=					full_content[1:].index('''---'''       ) + 1
          SCREAMING_SNAKE_CASE__					=					'''\n'''.join(full_content[1:sep_idx]       )
          return yamlblock, "\n".join(full_content[sep_idx + 1 :]       )

     return None, "\n".join(_A       )






class  UpperCAmelCase__	( A__ ):






  """simple docstring"""


  a     =      {"train_eval_index"}  # train-eval-index in the YAML metadata






  @classmethod
  def    lowercase_	(							cls		:	Union[str, Any]			,     __lowerCamelCase		:	Path      )	->							"DatasetMetadata":
       with open(__lowerCamelCase			,     encoding='''utf-8'''      ) as readme_file:
            SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__					=					_split_yaml_from_readme(readme_file.read()      )
       if yaml_string is not None:
            return cls.from_yaml_string(__lowerCamelCase      )
       else:
            return cls()






  def    lowercase_	(							self		:	List[Any]			,     __lowerCamelCase		:	Path      )	->							Any:
       if path.exists():
            with open(__lowerCamelCase			,     encoding='''utf-8'''      ) as readme_file:
                 SCREAMING_SNAKE_CASE__					=					readme_file.read()
       else:
            SCREAMING_SNAKE_CASE__					=					None
       SCREAMING_SNAKE_CASE__					=					self._to_readme(__lowerCamelCase      )
       with open(__lowerCamelCase			,     '''w'''			,     encoding='''utf-8'''      ) as readme_file:
            readme_file.write(__lowerCamelCase      )






  def    lowercase_	(							self		:	str			,     __lowerCamelCase		:	Optional[str] = None      )	->							str:
       if readme_content is not None:
            SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__					=					_split_yaml_from_readme(__lowerCamelCase      )
            SCREAMING_SNAKE_CASE__					=					'''---\n''' + self.to_yaml_string() + '''---\n''' + content
       else:
            SCREAMING_SNAKE_CASE__					=					'''---\n''' + self.to_yaml_string() + '''---\n'''
       return full_content






  @classmethod
  def    lowercase_	(							cls		:	str			,     __lowerCamelCase		:	str      )	->							"DatasetMetadata":
       SCREAMING_SNAKE_CASE__					=					yaml.load(__lowerCamelCase			,     Loader=_NoDuplicateSafeLoader      ) or {}

       # Convert the YAML keys to DatasetMetadata fields
       SCREAMING_SNAKE_CASE__					=					{
           (key.replace('''-'''			,     '''_'''      ) if key.replace('''-'''			,     '''_'''      ) in cls._FIELDS_WITH_DASHES else key): value
           for key, value in metadata_dict.items()
       }
       return cls(**__lowerCamelCase      )







  def    lowercase_	(							self		:	str      )	->							str:
       return yaml.safe_dump(
           {
               (key.replace('''_'''			,     '''-'''      ) if key in self._FIELDS_WITH_DASHES else key): value
               for key, value in self.items()
           }			,     sort_keys=__lowerCamelCase			,     allow_unicode=__lowerCamelCase			,     encoding='''utf-8'''			,     ).decode('''utf-8'''      )



_SCREAMING_SNAKE_CASE  :						Optional[Any]         =    {
    '''image-classification''': [],
    '''translation''': [],
    '''image-segmentation''': [],
    '''fill-mask''': [],
    '''automatic-speech-recognition''': [],
    '''token-classification''': [],
    '''sentence-similarity''': [],
    '''audio-classification''': [],
    '''question-answering''': [],
    '''summarization''': [],
    '''zero-shot-classification''': [],
    '''table-to-text''': [],
    '''feature-extraction''': [],
    '''other''': [],
    '''multiple-choice''': [],
    '''text-classification''': [],
    '''text-to-image''': [],
    '''text2text-generation''': [],
    '''zero-shot-image-classification''': [],
    '''tabular-classification''': [],
    '''tabular-regression''': [],
    '''image-to-image''': [],
    '''tabular-to-text''': [],
    '''unconditional-image-generation''': [],
    '''text-retrieval''': [],
    '''text-to-speech''': [],
    '''object-detection''': [],
    '''audio-to-audio''': [],
    '''text-generation''': [],
    '''conversational''': [],
    '''table-question-answering''': [],
    '''visual-question-answering''': [],
    '''image-to-text''': [],
    '''reinforcement-learning''': [],
    '''voice-activity-detection''': [],
    '''time-series-forecasting''': [],
    '''document-question-answering''': [],
}


if __name__ == "__main__":
       from argparse import ArgumentParser

       _SCREAMING_SNAKE_CASE  :						Any         =    ArgumentParser(usage='''Validate the yaml metadata block of a README.md file.''')
       ap.add_argument('''readme_filepath''')
       _SCREAMING_SNAKE_CASE  :						Union[str, Any]         =    ap.parse_args()

       _SCREAMING_SNAKE_CASE  :						Tuple         =    Path(args.readme_filepath)
       _SCREAMING_SNAKE_CASE  :						List[str]         =    DatasetMetadata.from_readme(readme_filepath)
       print(dataset_metadata)
       dataset_metadata.to_readme(readme_filepath)





import math
from typing import Callable, List, Optional, Union

import numpy as np
import PIL
import torch
from PIL import Image
from transformers import CLIPTextModel, CLIPTokenizer

from diffusers.models import AutoencoderKL, UNetaDConditionModel
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline
from diffusers.schedulers import DDIMScheduler, DDPMScheduler, LMSDiscreteScheduler, PNDMScheduler
def        UpperCAmelCase_     (		_A   ,	_A   ,	_A=[]       ):





     '''simple docstring'''




     SCREAMING_SNAKE_CASE__					=					size[0] - overlap_pixels * 2
     SCREAMING_SNAKE_CASE__					=					size[1] - overlap_pixels * 2
     for letter in ["l", "r"]:
          if letter in remove_borders:
               size_x += overlap_pixels
     for letter in ["t", "b"]:
          if letter in remove_borders:
               size_y += overlap_pixels
     SCREAMING_SNAKE_CASE__					=					np.ones((size_y, size_x)   ,	dtype=np.uinta       ) * 2_55
     SCREAMING_SNAKE_CASE__					=					np.pad(_A   ,	mode='''linear_ramp'''   ,	pad_width=_A   ,	end_values=0       )

     if "l" in remove_borders:
          SCREAMING_SNAKE_CASE__					=					mask[:, overlap_pixels : mask.shape[1]]
     if "r" in remove_borders:
          SCREAMING_SNAKE_CASE__					=					mask[:, 0 : mask.shape[1] - overlap_pixels]
     if "t" in remove_borders:
          SCREAMING_SNAKE_CASE__					=					mask[overlap_pixels : mask.shape[0], :]
     if "b" in remove_borders:
          SCREAMING_SNAKE_CASE__					=					mask[0 : mask.shape[0] - overlap_pixels, :]
     return mask
def        UpperCAmelCase_     (		_A   ,	_A   ,	_A       ):





     '''simple docstring'''




     return max(_A   ,	min(_A   ,	_A       )       )
def        UpperCAmelCase_     (		_A   ,	_A   ,	_A       ):





     '''simple docstring'''




     return (
         clamp(rect[0]   ,	min[0]   ,	max[0]       ),
         clamp(rect[1]   ,	min[1]   ,	max[1]       ),
         clamp(rect[2]   ,	min[0]   ,	max[0]       ),
         clamp(rect[3]   ,	min[1]   ,	max[1]       ),
     )
def        UpperCAmelCase_     (		_A   ,	_A   ,	_A       ):





     '''simple docstring'''




     SCREAMING_SNAKE_CASE__					=					list(_A       )
     rect[0] -= overlap
     rect[1] -= overlap
     rect[2] += overlap
     rect[3] += overlap
     SCREAMING_SNAKE_CASE__					=					clamp_rect(_A   ,	[0, 0]   ,	[image_size[0], image_size[1]]       )
     return rect
def        UpperCAmelCase_     (		_A   ,	_A   ,	_A   ,	_A       ):





     '''simple docstring'''




     SCREAMING_SNAKE_CASE__					=					Image.new('''RGB'''   ,	(tile.size[0] + original_slice, tile.size[1])       )
     result.paste(
         original_image.resize((tile.size[0], tile.size[1])   ,	Image.BICUBIC       ).crop(
             (slice_x, 0, slice_x + original_slice, tile.size[1])       )   ,	(0, 0)   ,	)
     result.paste(_A   ,	(original_slice, 0)       )
     return result
def        UpperCAmelCase_     (		_A   ,	_A       ):





     '''simple docstring'''




     SCREAMING_SNAKE_CASE__					=					(original_image_slice * 4, 0, tile.size[0], tile.size[1])
     SCREAMING_SNAKE_CASE__					=					tile.crop(_A       )
     return tile
def        UpperCAmelCase_     (		_A   ,	_A       ):





     '''simple docstring'''




     SCREAMING_SNAKE_CASE__					=					n % d
     return n - divisor






class  UpperCAmelCase__	( A__ ):






  """simple docstring"""


  def __init__(							self		:	int			,     __lowerCamelCase		:	AutoencoderKL			,     __lowerCamelCase		:	CLIPTextModel			,     __lowerCamelCase		:	CLIPTokenizer			,     __lowerCamelCase		:	UNetaDConditionModel			,     __lowerCamelCase		:	DDPMScheduler			,     __lowerCamelCase		:	Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]			,     __lowerCamelCase		:	int = 350			,     )	->							int:
       super().__init__(
           vae=__lowerCamelCase			,     text_encoder=__lowerCamelCase			,     tokenizer=__lowerCamelCase			,     unet=__lowerCamelCase			,     low_res_scheduler=__lowerCamelCase			,     scheduler=__lowerCamelCase			,     max_noise_level=__lowerCamelCase			,     )






  def    lowercase_	(							self		:	Tuple			,     __lowerCamelCase		:	Optional[int]			,     __lowerCamelCase		:	Tuple			,     __lowerCamelCase		:	Any			,     __lowerCamelCase		:	List[Any]			,     __lowerCamelCase		:	str			,     __lowerCamelCase		:	List[str]			,     __lowerCamelCase		:	str			,     **__lowerCamelCase		:	Tuple      )	->							Dict:
       torch.manual_seed(0      )
       SCREAMING_SNAKE_CASE__					=					(
           min(image.size[0] - (tile_size + original_image_slice)			,     x * tile_size      ),
           min(image.size[1] - (tile_size + original_image_slice)			,     y * tile_size      ),
           min(image.size[0]			,     (x + 1) * tile_size      ),
           min(image.size[1]			,     (y + 1) * tile_size      ),
       )
       SCREAMING_SNAKE_CASE__					=					add_overlap_rect(__lowerCamelCase			,     __lowerCamelCase			,     image.size      )
       SCREAMING_SNAKE_CASE__					=					image.crop(__lowerCamelCase      )
       SCREAMING_SNAKE_CASE__					=					((crop_rect[0] + ((crop_rect[2] - crop_rect[0]) / 2)) / image.size[0]) * tile.size[0]
       SCREAMING_SNAKE_CASE__					=					translated_slice_x - (original_image_slice / 2)
       SCREAMING_SNAKE_CASE__					=					max(0			,     __lowerCamelCase      )
       SCREAMING_SNAKE_CASE__					=					squeeze_tile(__lowerCamelCase			,     __lowerCamelCase			,     __lowerCamelCase			,     __lowerCamelCase      )
       SCREAMING_SNAKE_CASE__					=					to_input.size
       SCREAMING_SNAKE_CASE__					=					to_input.resize((tile_size, tile_size)			,     Image.BICUBIC      )
       SCREAMING_SNAKE_CASE__					=					super(__lowerCamelCase			,     self      ).__call__(image=__lowerCamelCase			,     **__lowerCamelCase      ).images[0]
       SCREAMING_SNAKE_CASE__					=					upscaled_tile.resize((orig_input_size[0] * 4, orig_input_size[1] * 4)			,     Image.BICUBIC      )
       SCREAMING_SNAKE_CASE__					=					unsqueeze_tile(__lowerCamelCase			,     __lowerCamelCase      )
       SCREAMING_SNAKE_CASE__					=					upscaled_tile.resize((tile.size[0] * 4, tile.size[1] * 4)			,     Image.BICUBIC      )
       SCREAMING_SNAKE_CASE__					=					[]
       if x == 0:
            remove_borders.append('''l'''      )
       elif crop_rect[2] == image.size[0]:
            remove_borders.append('''r'''      )
       if y == 0:
            remove_borders.append('''t'''      )
       elif crop_rect[3] == image.size[1]:
            remove_borders.append('''b'''      )
       SCREAMING_SNAKE_CASE__					=					Image.fromarray(
           make_transparency_mask(
               (upscaled_tile.size[0], upscaled_tile.size[1])			,     tile_border * 4			,     remove_borders=__lowerCamelCase      )			,     mode='''L'''			,     )
       final_image.paste(
           __lowerCamelCase			,     (crop_rect_with_overlap[0] * 4, crop_rect_with_overlap[1] * 4)			,     __lowerCamelCase      )







  @torch.no_grad()
  def __call__(							self		:	List[str]			,     __lowerCamelCase		:	Union[str, List[str]]			,     __lowerCamelCase		:	Union[PIL.Image.Image, List[PIL.Image.Image]]			,     __lowerCamelCase		:	int = 75			,     __lowerCamelCase		:	float = 9.0			,     __lowerCamelCase		:	int = 50			,     __lowerCamelCase		:	Optional[Union[str, List[str]]] = None			,     __lowerCamelCase		:	Optional[int] = 1			,     __lowerCamelCase		:	float = 0.0			,     __lowerCamelCase		:	Optional[torch.Generator] = None			,     __lowerCamelCase		:	Optional[torch.FloatTensor] = None			,     __lowerCamelCase		:	Optional[Callable[[int, int, torch.FloatTensor], None]] = None			,     __lowerCamelCase		:	int = 1			,     __lowerCamelCase		:	int = 128			,     __lowerCamelCase		:	int = 32			,     __lowerCamelCase		:	int = 32			,     )	->							List[Any]:
       SCREAMING_SNAKE_CASE__					=					Image.new('''RGB'''			,     (image.size[0] * 4, image.size[1] * 4)      )
       SCREAMING_SNAKE_CASE__					=					math.ceil(image.size[0] / tile_size      )
       SCREAMING_SNAKE_CASE__					=					math.ceil(image.size[1] / tile_size      )
       SCREAMING_SNAKE_CASE__					=					tcx * tcy
       SCREAMING_SNAKE_CASE__					=					0
       for y in range(__lowerCamelCase      ):
            for x in range(__lowerCamelCase      ):
                 self._process_tile(
                     __lowerCamelCase			,     __lowerCamelCase			,     __lowerCamelCase			,     __lowerCamelCase			,     __lowerCamelCase			,     __lowerCamelCase			,     __lowerCamelCase			,     prompt=__lowerCamelCase			,     num_inference_steps=__lowerCamelCase			,     guidance_scale=__lowerCamelCase			,     noise_level=__lowerCamelCase			,     negative_prompt=__lowerCamelCase			,     num_images_per_prompt=__lowerCamelCase			,     eta=__lowerCamelCase			,     generator=__lowerCamelCase			,     latents=__lowerCamelCase			,     )
                 current_count += 1
                 if callback is not None:
                      callback({'''progress''': current_count / total_tile_count, '''image''': final_image}      )
       return final_image



def        UpperCAmelCase_     (		):





     '''simple docstring'''




     SCREAMING_SNAKE_CASE__					=					'''stabilityai/stable-diffusion-x4-upscaler'''
     SCREAMING_SNAKE_CASE__					=					StableDiffusionTiledUpscalePipeline.from_pretrained(_A   ,	revision='''fp16'''   ,	torch_dtype=torch.floataa       )
     SCREAMING_SNAKE_CASE__					=					pipe.to('''cuda'''       )
     SCREAMING_SNAKE_CASE__					=					Image.open('''../../docs/source/imgs/diffusers_library.jpg'''       )

     def callback(_A       ):
          print(F'''progress: {obj["progress"]:.4f}'''       )
          obj["image"].save('''diffusers_library_progress.jpg'''       )

     SCREAMING_SNAKE_CASE__					=					pipe(image=_A   ,	prompt='''Black font, white background, vector'''   ,	noise_level=40   ,	callback=_A       )
     final_image.save('''diffusers_library.jpg'''       )


if __name__ == "__main__":
       main()


