class_docstr: Wrapper for running CoreML models using coremltools
      
class_docstr_tok: ["Wrapper","for","running","CoreML","models","using","coremltools"]
code: def __init__(self, model_path, compute_unit, sources="packages"):
      logger.info(f"Loading {model_path}")
  
      start = time.time()
      if sources == "packages":
          assert os.path.exists(model_path) and model_path.endswith(
              ".mlpackage"
          )
  
          self.model = ct.models.MLModel(
              model_path, compute_units=ct.ComputeUnit[compute_unit]
          )
          DTYPE_MAP = {
              65552: np.float16,
              65568: np.float32,
              131104: np.int32,
          }
          self.expected_inputs = {
              input_tensor.name: {
                  "shape": tuple(
                      input_tensor.type.multiArrayType.shape
                  ),
                  "dtype": DTYPE_MAP[
                      input_tensor.type.multiArrayType.dataType
                  ],
              }
              for input_tensor in self.model._spec.description.input
          }
      elif sources == "compiled":
          assert os.path.exists(model_path) and model_path.endswith(
              ".mlmodelc"
          )
  
          self.model = ct.models.CompiledMLModel(
              model_path, ct.ComputeUnit[compute_unit]
          )
  
          # Grab expected inputs from metadata.json
          with open(
              os.path.join(model_path, "metadata.json"), "r"
          ) as f:
              config = json.load(f)[0]
  
          self.expected_inputs = {
              input_tensor["name"]: {
                  "shape": tuple(eval(input_tensor["shape"])),
                  "dtype": np.dtype(input_tensor["dataType"].lower()),
              }
              for input_tensor in config["inputSchema"]
          }
      else:
          raise ValueError(
              f"Expected `packages` or `compiled` for sources, received {sources}"
          )
  
      load_time = time.time() - start
      logger.info(f"Done. Took {load_time:.1f} seconds.")
  
      if load_time > LOAD_TIME_INFO_MSG_TRIGGER:
          logger.info(
              "Loading a CoreML model through coremltools triggers compilation every time. "
              "The Swift package we provide uses precompiled Core ML models (.mlmodelc) to avoid compile-on-load."
          )
  
file_path: ml-stable-diffusion/python_coreml_stable_diffusion/coreml_model.py
imports: import coremltools
  import logging
  import json
  import numpy
  import os
  import time
label_desc: Use image node_id 1 to create a new CoreMLModel object  with example: obj = CoreMLModel(model_path, compute_unit, sources)