class_docstr: This class defines the minimal interface to a CoreML object in Python.
  
  At a high level, the protobuf specification consists of:
  
  - Model description: Encodes names and type information of the inputs and outputs to the model.
  - Model parameters: The set of parameters required to represent a specific instance of the model.
  - Metadata: Information about the origin, license, and author of the model.
  
  With this class, you can inspect a CoreML model, modify metadata, and make
  predictions for the purposes of testing (on select platforms).
  
  Examples
  --------
  .. sourcecode:: python
  
      # Load the model
      model = MLModel("HousePricer.mlmodel")
  
      # Set the model metadata
      model.author = "Author"
      model.license = "BSD"
      model.short_description = "Predicts the price of a house in the Seattle area."
  
      # Get the interface to the model
      model.input_description
      model.output_description
  
      # Set feature descriptions manually
      model.input_description["bedroom"] = "Number of bedrooms"
      model.input_description["bathrooms"] = "Number of bathrooms"
      model.input_description["size"] = "Size (in square feet)"
  
      # Set
      model.output_description["price"] = "Price of the house"
  
      # Make predictions
      predictions = model.predict({"bedroom": 1.0, "bath": 1.0, "size": 1240})
  
      # Get the spec of the model
      spec = model.get_spec()
  
      # Save the model
      model.save("HousePricer.mlpackage")
  
      # Load the model from the spec object
      spec = model.get_spec()
      # modify spec (e.g. rename inputs/outputs etc)
      model = MLModel(spec)
      # if model type is mlprogram, i.e. spec.WhichOneof('Type') == "mlProgram", then:
      model = MLModel(spec, weights_dir=model.weights_dir)
  
  See Also
  --------
  predict
class_docstr_tok: ["This","class","defines","the","minimal","interface","to","a","CoreML","object","in","Python",".","At","a","high","level",",","the","protobuf","specification","consists","of",":","-","Model","description",":","Encodes","names","and","type","information","of","the","inputs","and","outputs","to","the","model",".","-","Model","parameters",":","The","set","of","parameters","required","to","represent","a","specific","instance","of","the","model",".","-","Metadata",":","Information","about","the","origin",",","license",",","and","author","of","the","model",".","With","this","class",",","you","can","inspect","a","CoreML","model",",","modify","metadata",",","and","make","predictions","for","the","purposes","of","testing","(","on","select","platforms",")",".","Examples","--","--","--","--","..","sourcecode",":",":","python","#","Load","the","model","model","=","MLModel","(","``","HousePricer.mlmodel","''",")","#","Set","the","model","metadata","model.author","=","``","Author","''","model.license","=","``","BSD","''","model.short_description","=","``","Predicts","the","price","of","a","house","in","the","Seattle","area",".","''","#","Get","the","interface","to","the","model","model.input_description","model.output_description","#","Set","feature","descriptions","manually","model.input_description","[","``","bedroom","''","]","=","``","Number","of","bedrooms","''","model.input_description","[","``","bathrooms","''","]","=","``","Number","of","bathrooms","''","model.input_description","[","``","size","''","]","=","``","Size","(","in","square","feet",")","''","#","Set","model.output_description","[","``","price","''","]","=","``","Price","of","the","house","''","#","Make","predictions","predictions","=","model.predict","(","{","``","bedroom","''",":","1.0",",","``","bath","''",":","1.0",",","``","size","''",":","1240","}",")","#","Get","the","spec","of","the","model","spec","=","model.get_spec","(",")","#","Save","the","model","model.save","(","``","HousePricer.mlpackage","''",")","#","Load","the","model","from","the","spec","object","spec","=","model.get_spec","(",")","#","modify","spec","(","e.g",".","rename","inputs\/outputs","etc",")","model","=","MLModel","(","spec",")","#","if","model","type","is","mlprogram",",","i.e",".","spec.WhichOneof","(","'Type","'",")","==","``","mlProgram","''",",","then",":","model","=","MLModel","(","spec",",","weights_dir=model.weights_dir",")","See","Also","--","--","--","--","predict"]
docstr: Construct an MLModel from an ``.mlmodel``.
  
  Parameters
  ----------
  model: str or Model_pb2
  
      For an ML program (``mlprogram``), the model can be a path string (``.mlpackage``) or ``Model_pb2``.
      If it is a path string, it must point to a directory containing bundle
      artifacts (such as ``weights.bin``).
      If it is of type ``Model_pb2`` (spec), then you must also provide ``weights_dir`` if the model
      has weights, because both the proto spec and the weights are
      required to initialize and load the model.
      The proto spec for an ``mlprogram``, unlike a neural network (``neuralnetwork``),
      does not contain the weights; they are stored separately.
      If the model does not have weights, you can provide an empty ``weights_dir``.
  
      For non- ``mlprogram`` model types, the model can be a path string (``.mlmodel``)
      or type ``Model_pb2``, such as a spec object.
  
  is_temp_package: bool
      Set to ``True`` if the input model package dir is temporary and can be deleted upon interpreter termination.
  
  mil_program: coremltools.converters.mil.Program
      Set to the MIL program object, if available.
      It is available whenever an MLModel object is constructed using
      the unified converter API `coremltools.convert() <https://apple.github.io/coremltools/source/coremltools.converters.mil.html#module-coremltools.converters._converters_entry>`_.
  
  skip_model_load: bool
      Set to ``True`` to prevent Core ML Tools from calling into the Core ML framework
      to compile and load the model. In that case, the returned model object cannot
      be used to make a prediction. This flag may be used to load a newer model
      type on an older Mac, to inspect or load/save the spec.
  
      Example: Loading an ML program model type on a macOS 11, since an ML program can be
      compiled and loaded only from macOS12+.
  
      Defaults to ``False``.
  
  compute_units: coremltools.ComputeUnit
      The set of processing units the model can use to make predictions.
  
      An enum with four possible values:
          - ``coremltools.ComputeUnit.ALL``: Use all compute units available, including the
            neural engine.
          - ``coremltools.ComputeUnit.CPU_ONLY``: Limit the model to only use the CPU.
          - ``coremltools.ComputeUnit.CPU_AND_GPU``: Use both the CPU and GPU,
            but not the neural engine.
          - ``coremltools.ComputeUnit.CPU_AND_NE``: Use both the CPU and neural engine, but
            not the GPU. Available only for macOS >= 13.0.
  
  weights_dir: str
      Path to the weight directory, required when loading an MLModel of type ``mlprogram``,
      from a spec object, such as when the argument ``model`` is of type ``Model_pb2``.
  
  Notes
  -----
  Internally this maintains the following:
  
  - ``_MLModelProxy``: A pybind wrapper around
    CoreML::Python::Model (see
    `coremltools/coremlpython/CoreMLPython.mm <https://github.com/apple/coremltools/blob/main/coremlpython/CoreMLPython.mm>`_)
  
  - ``package_path`` (mlprogram only): Directory containing all artifacts (``.mlmodel``,
    weights, and so on).
  
  - ``weights_dir`` (mlprogram only): Directory containing weights inside the package_path.
  
  Examples
  --------
  .. sourcecode:: python
  
                  loaded_model = MLModel('my_model.mlmodel')
                  loaded_model = MLModel("my_model.mlpackage")
docstr_tok: ["Construct","an","MLModel","from","an","``",".mlmodel","``",".","Parameters","--","--","--","--","--","model",":","str","or","Model_pb2","For","an","ML","program","(","``","mlprogram","``",")",",","the","model","can","be","a","path","string","(","``",".mlpackage","``",")","or","``","Model_pb2","``",".","If","it","is","a","path","string",",","it","must","point","to","a","directory","containing","bundle","artifacts","(","such","as","``","weights.bin","``",")",".","If","it","is","of","type","``","Model_pb2","``","(","spec",")",",","then","you","must","also","provide","``","weights_dir","``","if","the","model","has","weights",",","because","both","the","proto","spec","and","the","weights","are","required","to","initialize","and","load","the","model",".","The","proto","spec","for","an","``","mlprogram","``",",","unlike","a","neural","network","(","``","neuralnetwork","``",")",",","does","not","contain","the","weights",";","they","are","stored","separately",".","If","the","model","does","not","have","weights",",","you","can","provide","an","empty","``","weights_dir","``",".","For","non-","``","mlprogram","``","model","types",",","the","model","can","be","a","path","string","(","``",".mlmodel","``",")","or","type","``","Model_pb2","``",",","such","as","a","spec","object",".","is_temp_package",":","bool","Set","to","``","True","``","if","the","input","model","package","dir","is","temporary","and","can","be","deleted","upon","interpreter","termination",".","mil_program",":","coremltools.converters.mil.Program","Set","to","the","MIL","program","object",",","if","available",".","It","is","available","whenever","an","MLModel","object","is","constructed","using","the","unified","converter","API","`","coremltools.convert","(",")","<","https",":","\/\/apple.github.io\/coremltools\/source\/coremltools.converters.mil.html","#","module-coremltools.converters._converters_entry",">","`","_",".","skip_model_load",":","bool","Set","to","``","True","``","to","prevent","Core","ML","Tools","from","calling","into","the","Core","ML","framework","to","compile","and","load","the","model",".","In","that","case",",","the","returned","model","object","can","not","be","used","to","make","a","prediction",".","This","flag","may","be","used","to","load","a","newer","model","type","on","an","older","Mac",",","to","inspect","or","load\/save","the","spec",".","Example",":","Loading","an","ML","program","model","type","on","a","macOS","11",",","since","an","ML","program","can","be","compiled","and","loaded","only","from","macOS12+",".","Defaults","to","``","False","``",".","compute_units",":","coremltools.ComputeUnit","The","set","of","processing","units","the","model","can","use","to","make","predictions",".","An","enum","with","four","possible","values",":","-","``","coremltools.ComputeUnit.ALL","``",":","Use","all","compute","units","available",",","including","the","neural","engine",".","-","``","coremltools.ComputeUnit.CPU_ONLY","``",":","Limit","the","model","to","only","use","the","CPU",".","-","``","coremltools.ComputeUnit.CPU_AND_GPU","``",":","Use","both","the","CPU","and","GPU",",","but","not","the","neural","engine",".","-","``","coremltools.ComputeUnit.CPU_AND_NE","``",":","Use","both","the","CPU","and","neural","engine",",","but","not","the","GPU",".","Available","only","for","macOS",">","=","13.0.","weights_dir",":","str","Path","to","the","weight","directory",",","required","when","loading","an","MLModel","of","type","``","mlprogram","``",",","from","a","spec","object",",","such","as","when","the","argument","``","model","``","is","of","type","``","Model_pb2","``",".","Notes","--","--","-","Internally","this","maintains","the","following",":","-","``","_MLModelProxy","``",":","A","pybind","wrapper","around","CoreML",":",":Python",":",":Model","(","see","`","coremltools\/coremlpython\/CoreMLPython.mm","<","https",":","\/\/github.com\/apple\/coremltools\/blob\/main\/coremlpython\/CoreMLPython.mm",">","`","_",")","-","``","package_path","``","(","mlprogram","only",")",":","Directory","containing","all","artifacts","(","``",".mlmodel","``",",","weights",",","and","so","on",")",".","-","``","weights_dir","``","(","mlprogram","only",")",":","Directory","containing","weights","inside","the","package_path",".","Examples","--","--","--","--","..","sourcecode",":",":","python","loaded_model","=","MLModel","(","'my_model.mlmodel","'",")","loaded_model","=","MLModel","(","``","my_model.mlpackage","''",")"]
code: def __init__(
      self,
      model,
      is_temp_package=False,
      mil_program=None,
      skip_model_load=False,
      compute_units=_ComputeUnit.ALL,
      weights_dir=None,
  ):
      """
      Construct an MLModel from an ``.mlmodel``.
  
      Parameters
      ----------
      model: str or Model_pb2
  
          For an ML program (``mlprogram``), the model can be a path string (``.mlpackage``) or ``Model_pb2``.
          If it is a path string, it must point to a directory containing bundle
          artifacts (such as ``weights.bin``).
          If it is of type ``Model_pb2`` (spec), then you must also provide ``weights_dir`` if the model
          has weights, because both the proto spec and the weights are
          required to initialize and load the model.
          The proto spec for an ``mlprogram``, unlike a neural network (``neuralnetwork``),
          does not contain the weights; they are stored separately.
          If the model does not have weights, you can provide an empty ``weights_dir``.
  
          For non- ``mlprogram`` model types, the model can be a path string (``.mlmodel``)
          or type ``Model_pb2``, such as a spec object.
  
      is_temp_package: bool
          Set to ``True`` if the input model package dir is temporary and can be deleted upon interpreter termination.
  
      mil_program: coremltools.converters.mil.Program
          Set to the MIL program object, if available.
          It is available whenever an MLModel object is constructed using
          the unified converter API `coremltools.convert() <https://apple.github.io/coremltools/source/coremltools.converters.mil.html#module-coremltools.converters._converters_entry>`_.
  
      skip_model_load: bool
          Set to ``True`` to prevent Core ML Tools from calling into the Core ML framework
          to compile and load the model. In that case, the returned model object cannot
          be used to make a prediction. This flag may be used to load a newer model
          type on an older Mac, to inspect or load/save the spec.
  
          Example: Loading an ML program model type on a macOS 11, since an ML program can be
          compiled and loaded only from macOS12+.
  
          Defaults to ``False``.
  
      compute_units: coremltools.ComputeUnit
          The set of processing units the model can use to make predictions.
  
          An enum with four possible values:
              - ``coremltools.ComputeUnit.ALL``: Use all compute units available, including the
                neural engine.
              - ``coremltools.ComputeUnit.CPU_ONLY``: Limit the model to only use the CPU.
              - ``coremltools.ComputeUnit.CPU_AND_GPU``: Use both the CPU and GPU,
                but not the neural engine.
              - ``coremltools.ComputeUnit.CPU_AND_NE``: Use both the CPU and neural engine, but
                not the GPU. Available only for macOS >= 13.0.
  
      weights_dir: str
          Path to the weight directory, required when loading an MLModel of type ``mlprogram``,
          from a spec object, such as when the argument ``model`` is of type ``Model_pb2``.
  
      Notes
      -----
      Internally this maintains the following:
  
      - ``_MLModelProxy``: A pybind wrapper around
        CoreML::Python::Model (see
        `coremltools/coremlpython/CoreMLPython.mm <https://github.com/apple/coremltools/blob/main/coremlpython/CoreMLPython.mm>`_)
  
      - ``package_path`` (mlprogram only): Directory containing all artifacts (``.mlmodel``,
        weights, and so on).
  
      - ``weights_dir`` (mlprogram only): Directory containing weights inside the package_path.
  
      Examples
      --------
      .. sourcecode:: python
  
                      loaded_model = MLModel('my_model.mlmodel')
                      loaded_model = MLModel("my_model.mlpackage")
  
      """
  
      def cleanup(package_path):
          if _os.path.exists(package_path):
              _shutil.rmtree(package_path)
  
      def does_model_contain_mlprogram(model) -> bool:
          """
          Is this an mlprogram or is it a pipeline with at least one mlprogram?
          """
          model_type = model.WhichOneof("Type")
  
          if model_type == "mlProgram":
              return True
          elif model_type not in (
              "pipeline",
              "pipelineClassifier",
              "pipelineRegressor",
          ):
              return False
  
          # Does this pipeline contain an mlprogram?
          if model_type == "pipeline":
              pipeline_models = model.pipeline.models
          elif model_type == "pipelineClassifier":
              pipeline_models = model.pipelineClassifier.pipeline.models
          else:
              assert model_type == "pipelineRegressor"
              pipeline_models = model.pipelineRegressor.pipeline.models
  
          for m in pipeline_models:
              if does_model_contain_mlprogram(m):
                  return True
          return False
  
      if not isinstance(compute_units, _ComputeUnit):
          raise TypeError(
              '"compute_units" parameter must be of type: coremltools.ComputeUnit'
          )
      elif (
          compute_units == _ComputeUnit.CPU_AND_NE
          and _is_macos()
          and _macos_version() < (13, 0)
      ):
          raise ValueError(
              "coremltools.ComputeUnit.CPU_AND_NE is only available on macOS >= 13.0"
          )
      self.compute_unit = compute_units
  
      self.is_package = False
      self.is_temp_package = False
      self.package_path = None
      self._weights_dir = None
      if mil_program is not None and not isinstance(
          mil_program, _Program
      ):
          raise ValueError(
              '"mil_program" must be of type "coremltools.converters.mil.Program"'
          )
      self._mil_program = mil_program
  
      if isinstance(model, str):
          model = _os.path.abspath(
              _os.path.expanduser(_os.path.expandvars(model))
          )
          if _os.path.isdir(model):
              self.is_package = True
              self.package_path = model
              self.is_temp_package = is_temp_package
              self._weights_dir = _try_get_weights_dir_path(model)
          (
              self.__proxy__,
              self._spec,
              self._framework_error,
          ) = _get_proxy_and_spec(
              model,
              compute_units,
              skip_model_load=skip_model_load,
          )
      elif isinstance(model, _Model_pb2.Model):
          if does_model_contain_mlprogram(model):
              if (
                  model.WhichOneof("Type") == "mlProgram"
                  and weights_dir is None
              ):
                  raise Exception(
                      "MLModel of type mlProgram cannot be loaded just from the model spec object. "
                      "It also needs the path to the weights file. Please provide that as well, "
                      "using the 'weights_dir' argument."
                  )
              self.is_package = True
              self.is_temp_package = True
              filename = _create_mlpackage(model, weights_dir)
              self.package_path = filename
              self._weights_dir = _try_get_weights_dir_path(filename)
          else:
              filename = _tempfile.mktemp(suffix=_MLMODEL_EXTENSION)
              _save_spec(model, filename)
  
          (
              self.__proxy__,
              self._spec,
              self._framework_error,
          ) = _get_proxy_and_spec(
              filename,
              compute_units,
              skip_model_load=skip_model_load,
          )
          try:
              _os.remove(filename)
          except OSError:
              pass
      else:
          raise TypeError(
              "Expected model to be a .mlmodel file, .mlpackage file or a Model_pb2 object"
          )
  
      self._input_description = _FeatureDescription(
          self._spec.description.input
      )
      self._output_description = _FeatureDescription(
          self._spec.description.output
      )
  
      if self.is_package and self.is_temp_package:
          _atexit.register(cleanup, self.package_path)
  
imports: import atexit
  import os
  import shutil
  import tempfile
  import warnings
  from copy import deepcopy
  import numpy
  import numpy
  from coremltools import ComputeUnit
  from coremltools._deps import _HAS_TF_1, _HAS_TF_2, _HAS_TORCH
  from coremltools.converters.mil.mil.program import Program
  from ..proto import FeatureTypes_pb2
  from ..proto import MIL_pb2
  from ..proto import Model_pb2
  from .utils import _MLMODEL_EXTENSION, _MLPACKAGE_AUTHOR_NAME, _MLPACKAGE_EXTENSION, _MODEL_FILE_NAME, _WEIGHTS_DIR_NAME, _create_mlpackage, _has_custom_layer, _is_macos, _macos_version
  from .utils import load_spec
  from .utils import save_spec
label_desc: Use image node_id 1 to create a new MLModel object  with example: obj = MLModel(model, is_temp_package, mil_program, skip_model_load, compute_units, weights_dir)