






from __future__ import annotations

from statistics import mean






def 				lowerCamelCase__      (    __lowerCamelCase			:     list[int]  ,		__lowerCamelCase			:     list[int]  ,		__lowerCamelCase			:     int		):
  __UpperCAmelCase							:	Optional[Any]           =  [0] * no_of_processes
  __UpperCAmelCase							:	int           =  [0] * no_of_processes

  # Initialize remaining_time to waiting_time.

  for i in range(__lowerCamelCase		):
    __UpperCAmelCase							:	Optional[int]           =  burst_time[i]
  __UpperCAmelCase							:	list[int]           =  []

  __UpperCAmelCase							:	Dict           =  0
  __UpperCAmelCase							:	Optional[Any]           =  0

  # When processes are not completed,
  # A process whose arrival time has passed \
  # and has remaining execution time is put into the ready_process.
  # The shortest process in the ready_process, target_process is executed.

  while completed != no_of_processes:
    __UpperCAmelCase							:	Optional[int]           =  []
    __UpperCAmelCase							:	Tuple           =  -1

    for i in range(__lowerCamelCase		):
      if (arrival_time[i] <= total_time) and (remaining_time[i] > 0):
        ready_process.append(__lowerCamelCase		)

    if len(__lowerCamelCase		) > 0:
      __UpperCAmelCase							:	List[str]           =  ready_process[0]
      for i in ready_process:
        if remaining_time[i] < remaining_time[target_process]:
          __UpperCAmelCase							:	Union[str, Any]           =  i
      total_time += burst_time[target_process]
      completed += 1
      __UpperCAmelCase							:	List[Any]           =  0
      __UpperCAmelCase							:	Tuple           =  (
          total_time - arrival_time[target_process] - burst_time[target_process]
      )
    else:
      total_time += 1

  return waiting_time






def 				lowerCamelCase__      (    __lowerCamelCase			:     list[int]  ,		__lowerCamelCase			:     int  ,		__lowerCamelCase			:     list[int]		):
  __UpperCAmelCase							:	Optional[int]           =  [0] * no_of_processes
  for i in range(__lowerCamelCase		):
    __UpperCAmelCase							:	Union[str, Any]           =  burst_time[i] + waiting_time[i]
  return turn_around_time


if __name__ == "__main__":
       print("[TEST CASE 01]")

       a		:       Dict			     = 4
       a		:       Tuple			     = [2, 5, 3, 7]
       a		:       str			     = [0, 0, 0, 0]
       a		:       str			     = calculate_waitingtime(arrival_time, burst_time, no_of_processes)
       a		:       int			     = calculate_turnaroundtime(
           burst_time, no_of_processes, waiting_time
       )

       # Printing the Result
       print("PID\tBurst Time\tArrival Time\tWaiting Time\tTurnaround Time")
       for i, process_id in enumerate(list(range(1, 5))):
              print(
                  f"""{process_id}\t{burst_time[i]}\t\t\t{arrival_time[i]}\t\t\t\t"""
                  f"""{waiting_time[i]}\t\t\t\t{turn_around_time[i]}"""
              )
       print(f"""\nAverage waiting time = {mean(waiting_time):.5f}""")
       print(f"""Average turnaround time = {mean(turn_around_time):.5f}""")










import argparse
import io

import requests
import torch
from omegaconf import OmegaConf

from diffusers import AutoencoderKL
from diffusers.pipelines.stable_diffusion.convert_from_ckpt import (
    assign_to_checkpoint,
    conv_attn_to_linear,
    create_vae_diffusers_config,
    renew_vae_attention_paths,
    renew_vae_resnet_paths,
)






def 				lowerCamelCase__      (    __lowerCamelCase			:     Dict  ,		__lowerCamelCase			:     int		):
  __UpperCAmelCase							:	List[Any]           =  checkpoint

  __UpperCAmelCase							:	Tuple           =  {}

  __UpperCAmelCase							:	Dict           =  vae_state_dict["""encoder.conv_in.weight"""]
  __UpperCAmelCase							:	Optional[Any]           =  vae_state_dict["""encoder.conv_in.bias"""]
  __UpperCAmelCase							:	Dict           =  vae_state_dict["""encoder.conv_out.weight"""]
  __UpperCAmelCase							:	Union[str, Any]           =  vae_state_dict["""encoder.conv_out.bias"""]
  __UpperCAmelCase							:	List[Any]           =  vae_state_dict["""encoder.norm_out.weight"""]
  __UpperCAmelCase							:	Tuple           =  vae_state_dict["""encoder.norm_out.bias"""]

  __UpperCAmelCase							:	Dict           =  vae_state_dict["""decoder.conv_in.weight"""]
  __UpperCAmelCase							:	Tuple           =  vae_state_dict["""decoder.conv_in.bias"""]
  __UpperCAmelCase							:	Optional[int]           =  vae_state_dict["""decoder.conv_out.weight"""]
  __UpperCAmelCase							:	Optional[int]           =  vae_state_dict["""decoder.conv_out.bias"""]
  __UpperCAmelCase							:	Optional[Any]           =  vae_state_dict["""decoder.norm_out.weight"""]
  __UpperCAmelCase							:	Union[str, Any]           =  vae_state_dict["""decoder.norm_out.bias"""]

  __UpperCAmelCase							:	Optional[int]           =  vae_state_dict["""quant_conv.weight"""]
  __UpperCAmelCase							:	int           =  vae_state_dict["""quant_conv.bias"""]
  __UpperCAmelCase							:	Union[str, Any]           =  vae_state_dict["""post_quant_conv.weight"""]
  __UpperCAmelCase							:	Any           =  vae_state_dict["""post_quant_conv.bias"""]

  # Retrieves the keys for the encoder down blocks only
  __UpperCAmelCase							:	int           =  len({""".""".join(layer.split("""."""		)[:3]		) for layer in vae_state_dict if """encoder.down""" in layer}		)
  __UpperCAmelCase							:	Optional[Any]           =  {
      layer_id: [key for key in vae_state_dict if f"""down.{layer_id}""" in key] for layer_id in range(__lowerCamelCase		)
  }

  # Retrieves the keys for the decoder up blocks only
  __UpperCAmelCase							:	Dict           =  len({""".""".join(layer.split("""."""		)[:3]		) for layer in vae_state_dict if """decoder.up""" in layer}		)
  __UpperCAmelCase							:	Optional[int]           =  {
      layer_id: [key for key in vae_state_dict if f"""up.{layer_id}""" in key] for layer_id in range(__lowerCamelCase		)
  }

  for i in range(__lowerCamelCase		):
    __UpperCAmelCase							:	List[Any]           =  [key for key in down_blocks[i] if f"""down.{i}""" in key and f"""down.{i}.downsample""" not in key]

    if f"""encoder.down.{i}.downsample.conv.weight""" in vae_state_dict:
      __UpperCAmelCase							:	Optional[Any]           =  vae_state_dict.pop(
          f"""encoder.down.{i}.downsample.conv.weight"""		)
      __UpperCAmelCase							:	int           =  vae_state_dict.pop(
          f"""encoder.down.{i}.downsample.conv.bias"""		)

    __UpperCAmelCase							:	Optional[int]           =  renew_vae_resnet_paths(__lowerCamelCase		)
    __UpperCAmelCase							:	Optional[Any]           =  {"""old""": f"""down.{i}.block""", """new""": f"""down_blocks.{i}.resnets"""}
    assign_to_checkpoint(__lowerCamelCase  ,		__lowerCamelCase  ,		__lowerCamelCase  ,		additional_replacements=[meta_path]  ,		config=__lowerCamelCase		)

  __UpperCAmelCase							:	Tuple           =  [key for key in vae_state_dict if """encoder.mid.block""" in key]
  __UpperCAmelCase							:	Optional[Any]           =  2
  for i in range(1  ,		num_mid_res_blocks + 1		):
    __UpperCAmelCase							:	Dict           =  [key for key in mid_resnets if f"""encoder.mid.block_{i}""" in key]

    __UpperCAmelCase							:	Tuple           =  renew_vae_resnet_paths(__lowerCamelCase		)
    __UpperCAmelCase							:	Tuple           =  {"""old""": f"""mid.block_{i}""", """new""": f"""mid_block.resnets.{i - 1}"""}
    assign_to_checkpoint(__lowerCamelCase  ,		__lowerCamelCase  ,		__lowerCamelCase  ,		additional_replacements=[meta_path]  ,		config=__lowerCamelCase		)

  __UpperCAmelCase							:	List[Any]           =  [key for key in vae_state_dict if """encoder.mid.attn""" in key]
  __UpperCAmelCase							:	str           =  renew_vae_attention_paths(__lowerCamelCase		)
  __UpperCAmelCase							:	List[str]           =  {"""old""": """mid.attn_1""", """new""": """mid_block.attentions.0"""}
  assign_to_checkpoint(__lowerCamelCase  ,		__lowerCamelCase  ,		__lowerCamelCase  ,		additional_replacements=[meta_path]  ,		config=__lowerCamelCase		)
  conv_attn_to_linear(__lowerCamelCase		)

  for i in range(__lowerCamelCase		):
    __UpperCAmelCase							:	Optional[Any]           =  num_up_blocks - 1 - i
    __UpperCAmelCase							:	Union[str, Any]           =  [
        key for key in up_blocks[block_id] if f"""up.{block_id}""" in key and f"""up.{block_id}.upsample""" not in key
    ]

    if f"""decoder.up.{block_id}.upsample.conv.weight""" in vae_state_dict:
      __UpperCAmelCase							:	int           =  vae_state_dict[
          f"""decoder.up.{block_id}.upsample.conv.weight"""
      ]
      __UpperCAmelCase							:	Dict           =  vae_state_dict[
          f"""decoder.up.{block_id}.upsample.conv.bias"""
      ]

    __UpperCAmelCase							:	Dict           =  renew_vae_resnet_paths(__lowerCamelCase		)
    __UpperCAmelCase							:	Optional[Any]           =  {"""old""": f"""up.{block_id}.block""", """new""": f"""up_blocks.{i}.resnets"""}
    assign_to_checkpoint(__lowerCamelCase  ,		__lowerCamelCase  ,		__lowerCamelCase  ,		additional_replacements=[meta_path]  ,		config=__lowerCamelCase		)

  __UpperCAmelCase							:	Tuple           =  [key for key in vae_state_dict if """decoder.mid.block""" in key]
  __UpperCAmelCase							:	Union[str, Any]           =  2
  for i in range(1  ,		num_mid_res_blocks + 1		):
    __UpperCAmelCase							:	Dict           =  [key for key in mid_resnets if f"""decoder.mid.block_{i}""" in key]

    __UpperCAmelCase							:	List[Any]           =  renew_vae_resnet_paths(__lowerCamelCase		)
    __UpperCAmelCase							:	int           =  {"""old""": f"""mid.block_{i}""", """new""": f"""mid_block.resnets.{i - 1}"""}
    assign_to_checkpoint(__lowerCamelCase  ,		__lowerCamelCase  ,		__lowerCamelCase  ,		additional_replacements=[meta_path]  ,		config=__lowerCamelCase		)

  __UpperCAmelCase							:	Dict           =  [key for key in vae_state_dict if """decoder.mid.attn""" in key]
  __UpperCAmelCase							:	List[Any]           =  renew_vae_attention_paths(__lowerCamelCase		)
  __UpperCAmelCase							:	List[str]           =  {"""old""": """mid.attn_1""", """new""": """mid_block.attentions.0"""}
  assign_to_checkpoint(__lowerCamelCase  ,		__lowerCamelCase  ,		__lowerCamelCase  ,		additional_replacements=[meta_path]  ,		config=__lowerCamelCase		)
  conv_attn_to_linear(__lowerCamelCase		)
  return new_checkpoint






def 				lowerCamelCase__      (    __lowerCamelCase			:     str  ,		__lowerCamelCase			:     str  ,		):
  # Only support V1
  __UpperCAmelCase							:	Optional[int]           =  requests.get(
      """ https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml"""		)
  __UpperCAmelCase							:	Optional[int]           =  io.BytesIO(r.content		)

  __UpperCAmelCase							:	Dict           =  OmegaConf.load(__lowerCamelCase		)
  __UpperCAmelCase							:	str           =  512
  __UpperCAmelCase							:	Any           =  """cuda""" if torch.cuda.is_available() else """cpu"""
  if checkpoint_path.endswith("""safetensors"""		):
    from safetensors import safe_open

    __UpperCAmelCase							:	List[Any]           =  {}
    with safe_open(__lowerCamelCase  ,		framework="""pt"""  ,		device="""cpu"""		) as f:
      for key in f.keys():
        __UpperCAmelCase							:	str           =  f.get_tensor(__lowerCamelCase		)
  else:
    __UpperCAmelCase							:	Optional[int]           =  torch.load(__lowerCamelCase  ,		map_location=__lowerCamelCase		)["""state_dict"""]

  # Convert the VAE model.
  __UpperCAmelCase							:	Optional[int]           =  create_vae_diffusers_config(__lowerCamelCase  ,		image_size=__lowerCamelCase		)
  __UpperCAmelCase							:	Union[str, Any]           =  custom_convert_ldm_vae_checkpoint(__lowerCamelCase  ,		__lowerCamelCase		)

  __UpperCAmelCase							:	Optional[int]           =  AutoencoderKL(**__lowerCamelCase		)
  vae.load_state_dict(__lowerCamelCase		)
  vae.save_pretrained(__lowerCamelCase		)


if __name__ == "__main__":
       a		:       List[Any]			     = argparse.ArgumentParser()

       parser.add_argument("--vae_pt_path", default=None, type=str, required=True, help="Path to the VAE.pt to convert.")
       parser.add_argument("--dump_path", default=None, type=str, required=True, help="Path to the VAE.pt to convert.")

       a		:       Optional[int]			     = parser.parse_args()

       vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)


