



'''simple docstring'''




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   (       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_=[]							):
     lowercase_					:       Optional[int]     				=					size[0] - overlap_pixels * 2
     lowercase_					:       int     				=					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
     lowercase_					:       List[str]     				=					np.ones((size_y, size_x)  ,       dtype=np.uinta							) * 255
     lowercase_					:       Union[str, Any]     				=					np.pad(SCREAMING_SNAKE_CASE_  ,       mode='linear_ramp'  ,       pad_width=SCREAMING_SNAKE_CASE_  ,       end_values=0							)

     if "l" in remove_borders:
          lowercase_					:       Tuple     				=					mask[:, overlap_pixels : mask.shape[1]]
     if "r" in remove_borders:
          lowercase_					:       Union[str, Any]     				=					mask[:, 0 : mask.shape[1] - overlap_pixels]
     if "t" in remove_borders:
          lowercase_					:       Optional[Any]     				=					mask[overlap_pixels : mask.shape[0], :]
     if "b" in remove_borders:
          lowercase_					:       List[str]     				=					mask[0 : mask.shape[0] - overlap_pixels, :]
     return mask

def _UpperCamelCase   (       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_							):
     return max(SCREAMING_SNAKE_CASE_  ,       min(SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_							)							)

def _UpperCamelCase   (       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_							):
     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   (       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_							):
     lowercase_					:       str     				=					list(SCREAMING_SNAKE_CASE_							)
     rect[0] -= overlap
     rect[1] -= overlap
     rect[2] += overlap
     rect[3] += overlap
     lowercase_					:       List[Any]     				=					clamp_rect(SCREAMING_SNAKE_CASE_  ,       [0, 0]  ,       [image_size[0], image_size[1]]							)
     return rect

def _UpperCamelCase   (       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_							):
     lowercase_					:       Union[str, Any]     				=					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(SCREAMING_SNAKE_CASE_  ,       (original_slice, 0)							)
     return result

def _UpperCamelCase   (       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_							):
     lowercase_					:       Optional[Any]     				=					(original_image_slice * 4, 0, tile.size[0], tile.size[1])
     lowercase_					:       Dict     				=					tile.crop(SCREAMING_SNAKE_CASE_							)
     return tile

def _UpperCamelCase   (       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_							):
     lowercase_					:       Any     				=					n % d
     return n - divisor


class       UpperCAmelCase__  (       snake_case_			):






   """simple docstring"""
   def __init__(self       ,				_a       ,				_a       ,				_a       ,				_a       ,				_a       ,				_a       ,				_a = 350       ,				)    ->     Any:
        super().__init__(
            vae=_a       ,				text_encoder=_a       ,				tokenizer=_a       ,				unet=_a       ,				low_res_scheduler=_a       ,				scheduler=_a       ,				max_noise_level=_a       ,				)
   def 		_lowerCamelCase (self       ,				_a       ,				_a       ,				_a       ,				_a       ,				_a       ,				_a       ,				_a       ,				**_a				)    ->     List[str]:
        torch.manual_seed(0				)
        lowercase_					:       str     				=					(
            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				),
        )
        lowercase_					:       Dict     				=					add_overlap_rect(_a       ,				_a       ,				image.size				)
        lowercase_					:       Optional[int]     				=					image.crop(_a				)
        lowercase_					:       Union[str, Any]     				=					((crop_rect[0] + ((crop_rect[2] - crop_rect[0]) / 2)) / image.size[0]) * tile.size[0]
        lowercase_					:       Tuple     				=					translated_slice_x - (original_image_slice / 2)
        lowercase_					:       Any     				=					max(0       ,				_a				)
        lowercase_					:       Dict     				=					squeeze_tile(_a       ,				_a       ,				_a       ,				_a				)
        lowercase_					:       int     				=					to_input.size
        lowercase_					:       int     				=					to_input.resize((tile_size, tile_size)       ,				Image.BICUBIC				)
        lowercase_					:       str     				=					super(_a       ,				self				).__call__(image=_a       ,				**_a				).images[0]
        lowercase_					:       Optional[Any]     				=					upscaled_tile.resize((orig_input_size[0] * 4, orig_input_size[1] * 4)       ,				Image.BICUBIC				)
        lowercase_					:       Tuple     				=					unsqueeze_tile(_a       ,				_a				)
        lowercase_					:       List[str]     				=					upscaled_tile.resize((tile.size[0] * 4, tile.size[1] * 4)       ,				Image.BICUBIC				)
        lowercase_					:       Tuple     				=					[]
        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'				)
        lowercase_					:       str     				=					Image.fromarray(
            make_transparency_mask(
                (upscaled_tile.size[0], upscaled_tile.size[1])       ,				tile_border * 4       ,				remove_borders=_a				)       ,				mode='L'       ,				)
        final_image.paste(
            _a       ,				(crop_rect_with_overlap[0] * 4, crop_rect_with_overlap[1] * 4)       ,				_a				)





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



def _UpperCamelCase   (       ):
     # Run a demo
     lowercase_					:       List[Any]     				=					'stabilityai/stable-diffusion-x4-upscaler'
     lowercase_					:       Optional[Any]     				=					StableDiffusionTiledUpscalePipeline.from_pretrained(SCREAMING_SNAKE_CASE_  ,       revision='fp16'  ,       torch_dtype=torch.floataa							)
     lowercase_					:       List[Any]     				=					pipe.to('cuda'							)
     lowercase_					:       Dict     				=					Image.open('../../docs/source/imgs/diffusers_library.jpg'							)

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

     lowercase_					:       Optional[Any]     				=					pipe(image=SCREAMING_SNAKE_CASE_  ,       prompt='Black font, white background, vector'  ,       noise_level=40  ,       callback=SCREAMING_SNAKE_CASE_							)
     final_image.save('diffusers_library.jpg'							)


if __name__ == "__main__":
 main()





'''simple docstring'''




# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import os

from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES
from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType
from ...utils.imports import is_botoa_available
from .config_args import SageMakerConfig
from .config_utils import (
    DYNAMO_BACKENDS,
    _ask_field,
    _ask_options,
    _convert_dynamo_backend,
    _convert_mixed_precision,
    _convert_sagemaker_distributed_mode,
    _convert_yes_no_to_bool,
)


if is_botoa_available():
 import botoa  # noqa: F401

def _UpperCamelCase   (       SCREAMING_SNAKE_CASE_							):
     lowercase_					:       str     				=					botoa.client('iam'							)

     lowercase_					:       Optional[int]     				=					{
         'Version': '2012-10-17',
         'Statement': [
             {'Effect': 'Allow', 'Principal': {'Service': 'sagemaker.amazonaws.com'}, 'Action': 'sts:AssumeRole'}
         ],
     }
     try:
          # create the role, associated with the chosen trust policy
          iam_client.create_role(
              RoleName=SCREAMING_SNAKE_CASE_  ,       AssumeRolePolicyDocument=json.dumps(SCREAMING_SNAKE_CASE_  ,       indent=2							)							)
          lowercase_					:       Optional[Any]     				=					{
              'Version': '2012-10-17',
              'Statement': [
                  {
                      'Effect': 'Allow',
                      'Action': [
                          'sagemaker:*',
                          'ecr:GetDownloadUrlForLayer',
                          'ecr:BatchGetImage',
                          'ecr:BatchCheckLayerAvailability',
                          'ecr:GetAuthorizationToken',
                          'cloudwatch:PutMetricData',
                          'cloudwatch:GetMetricData',
                          'cloudwatch:GetMetricStatistics',
                          'cloudwatch:ListMetrics',
                          'logs:CreateLogGroup',
                          'logs:CreateLogStream',
                          'logs:DescribeLogStreams',
                          'logs:PutLogEvents',
                          'logs:GetLogEvents',
                          's3:CreateBucket',
                          's3:ListBucket',
                          's3:GetBucketLocation',
                          's3:GetObject',
                          's3:PutObject',
                      ],
                      'Resource': '*',
                  }
              ],
          }
          # attach policy to role
          iam_client.put_role_policy(
              RoleName=SCREAMING_SNAKE_CASE_  ,       PolicyName=f'''{role_name}_policy_permission'''  ,       PolicyDocument=json.dumps(SCREAMING_SNAKE_CASE_  ,       indent=2							)  ,       )
     except iam_client.exceptions.EntityAlreadyExistsException:
          print(f'''role {role_name} already exists. Using existing one'''							)

def _UpperCamelCase   (       SCREAMING_SNAKE_CASE_							):
     lowercase_					:       List[Any]     				=					botoa.client('iam'							)
     return iam_client.get_role(RoleName=SCREAMING_SNAKE_CASE_							)["Role"]["Arn"]






def _UpperCamelCase   (       ):
     lowercase_					:       Dict     				=					_ask_options(
         'How do you want to authorize?'  ,       ['AWS Profile', 'Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) ']  ,       SCREAMING_SNAKE_CASE_  ,       )
     lowercase_					:       List[Any]     				=					None
     if credentials_configuration == 0:
          lowercase_					:       List[Any]     				=					_ask_field('Enter your AWS Profile name: [default] '  ,       default='default'							)
          lowercase_					:       Optional[int]     				=					aws_profile
     else:
          print(
              'Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with,'
              '`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`'							)
          lowercase_					:       Optional[Any]     				=					_ask_field('AWS Access Key ID: '							)
          lowercase_					:       Optional[int]     				=					aws_access_key_id

          lowercase_					:       Optional[Any]     				=					_ask_field('AWS Secret Access Key: '							)
          lowercase_					:       Optional[int]     				=					aws_secret_access_key

     lowercase_					:       Any     				=					_ask_field('Enter your AWS Region: [us-east-1]'  ,       default='us-east-1'							)
     lowercase_					:       Tuple     				=					aws_region

     lowercase_					:       int     				=					_ask_options(
         'Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?'  ,       ['Provide IAM Role name', 'Create new IAM role using credentials']  ,       SCREAMING_SNAKE_CASE_  ,       )
     if role_management == 0:
          lowercase_					:       int     				=					_ask_field('Enter your IAM role name: '							)
     else:
          lowercase_					:       Any     				=					'accelerate_sagemaker_execution_role'
          print(f'''Accelerate will create an iam role "{iam_role_name}" using the provided credentials'''							)
          _create_iam_role_for_sagemaker(SCREAMING_SNAKE_CASE_							)

     lowercase_					:       List[Any]     				=					_ask_field(
         'Do you want to use custom Docker image? [yes/NO]: '  ,       _convert_yes_no_to_bool  ,       default=SCREAMING_SNAKE_CASE_  ,       error_message='Please enter yes or no.'  ,       )
     lowercase_					:       Optional[Any]     				=					None
     if is_custom_docker_image:
          lowercase_					:       List[Any]     				=					_ask_field('Enter your Docker image: '  ,       lambda SCREAMING_SNAKE_CASE_							: str(SCREAMING_SNAKE_CASE_							).lower()							)

     lowercase_					:       Any     				=					_ask_field(
         'Do you want to provide SageMaker input channels with data locations? [yes/NO]: '  ,       _convert_yes_no_to_bool  ,       default=SCREAMING_SNAKE_CASE_  ,       error_message='Please enter yes or no.'  ,       )
     lowercase_					:       Optional[Any]     				=					None
     if is_sagemaker_inputs_enabled:
          lowercase_					:       Dict     				=					_ask_field(
              'Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): '  ,       lambda SCREAMING_SNAKE_CASE_							: str(SCREAMING_SNAKE_CASE_							).lower()  ,       )

     lowercase_					:       Dict     				=					_ask_field(
         'Do you want to enable SageMaker metrics? [yes/NO]: '  ,       _convert_yes_no_to_bool  ,       default=SCREAMING_SNAKE_CASE_  ,       error_message='Please enter yes or no.'  ,       )
     lowercase_					:       Optional[Any]     				=					None
     if is_sagemaker_metrics_enabled:
          lowercase_					:       Dict     				=					_ask_field(
              'Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): '  ,       lambda SCREAMING_SNAKE_CASE_							: str(SCREAMING_SNAKE_CASE_							).lower()  ,       )

     lowercase_					:       int     				=					_ask_options(
         'What is the distributed mode?'  ,       ['No distributed training', 'Data parallelism']  ,       _convert_sagemaker_distributed_mode  ,       )
     lowercase_					:       List[str]     				=					{}
     lowercase_					:       Optional[Any]     				=					_ask_field(
         'Do you wish to optimize your script with torch dynamo?[yes/NO]:'  ,       _convert_yes_no_to_bool  ,       default=SCREAMING_SNAKE_CASE_  ,       error_message='Please enter yes or no.'  ,       )
     if use_dynamo:
          lowercase_					:       List[Any]     				=					'dynamo_'
          lowercase_					:       List[Any]     				=					_ask_options(
              'Which dynamo backend would you like to use?'  ,       [x.lower() for x in DYNAMO_BACKENDS]  ,       _convert_dynamo_backend  ,       default=2  ,       )
          lowercase_					:       int     				=					_ask_field(
              'Do you want to customize the defaults sent to torch.compile? [yes/NO]: '  ,       _convert_yes_no_to_bool  ,       default=SCREAMING_SNAKE_CASE_  ,       error_message='Please enter yes or no.'  ,       )

          if use_custom_options:
               lowercase_					:       Union[str, Any]     				=					_ask_options(
                   'Which mode do you want to use?'  ,       SCREAMING_SNAKE_CASE_  ,       lambda SCREAMING_SNAKE_CASE_							: TORCH_DYNAMO_MODES[int(SCREAMING_SNAKE_CASE_							)]  ,       default='default'  ,       )
               lowercase_					:       Union[str, Any]     				=					_ask_field(
                   'Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: '  ,       _convert_yes_no_to_bool  ,       default=SCREAMING_SNAKE_CASE_  ,       error_message='Please enter yes or no.'  ,       )
               lowercase_					:       Tuple     				=					_ask_field(
                   'Do you want to enable dynamic shape tracing? [yes/NO]: '  ,       _convert_yes_no_to_bool  ,       default=SCREAMING_SNAKE_CASE_  ,       error_message='Please enter yes or no.'  ,       )
     lowercase_					:       List[str]     				=					'Which EC2 instance type you want to use for your training?'
     if distributed_type != SageMakerDistributedType.NO:
          lowercase_					:       Optional[Any]     				=					_ask_options(
              SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_  ,       lambda SCREAMING_SNAKE_CASE_							: SAGEMAKER_PARALLEL_EC2_INSTANCES[int(SCREAMING_SNAKE_CASE_							)]							)
     else:
          eca_instance_query += "? [ml.p3.2xlarge]:"
          lowercase_					:       Tuple     				=					_ask_field(SCREAMING_SNAKE_CASE_  ,       lambda SCREAMING_SNAKE_CASE_							: str(SCREAMING_SNAKE_CASE_							).lower()  ,       default='ml.p3.2xlarge'							)

     lowercase_					:       str     				=					1
     if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL):
          lowercase_					:       Union[str, Any]     				=					_ask_field(
              'How many machines do you want use? [1]: '  ,       SCREAMING_SNAKE_CASE_  ,       default=1  ,       )

     lowercase_					:       Any     				=					_ask_options(
         'Do you wish to use FP16 or BF16 (mixed precision)?'  ,       ['no', 'fp16', 'bf16', 'fp8']  ,       _convert_mixed_precision  ,       )

     if use_dynamo and mixed_precision == "no":
          print(
              'Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts.'							)

     return SageMakerConfig(
         image_uri=SCREAMING_SNAKE_CASE_  ,       compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER  ,       distributed_type=SCREAMING_SNAKE_CASE_  ,       use_cpu=SCREAMING_SNAKE_CASE_  ,       dynamo_config=SCREAMING_SNAKE_CASE_  ,       eca_instance_type=SCREAMING_SNAKE_CASE_  ,       profile=SCREAMING_SNAKE_CASE_  ,       region=SCREAMING_SNAKE_CASE_  ,       iam_role_name=SCREAMING_SNAKE_CASE_  ,       mixed_precision=SCREAMING_SNAKE_CASE_  ,       num_machines=SCREAMING_SNAKE_CASE_  ,       sagemaker_inputs_file=SCREAMING_SNAKE_CASE_  ,       sagemaker_metrics_file=SCREAMING_SNAKE_CASE_  ,       )




