
    it                     .   S SK rS SKrS SKrS SKrS SKrS SK	r
S SKJr  S SKJr  S SKJr  S SKJr  S SKrS SKrS SKJr  S SKJr  S SKJr  S S	KJr   S S
KJ!r"  S SK#J$r$J%r%J&r&  S SK'J(r)  S SK*J+r,  SSK-J.r.J/r/J0r0J1r1J2r2J3r3J4r4J5r5  SSK-J6r7  SSK-J8r9  \&(       a  S SK:r;\$(       d  \%(       a  S SK<r= SSK>J?r@   SSKAJBrB   SSKAJFrF  SrG S SKHJIrJ  SrKSrLSrM\K\L\M/rNSrOSrPS rQS!rRS"rSS#rT\O\P\Q\R\S\T/rU\P\Q\R/rVS$rWS%rXS&rYS'rZSS(K[J\r]  S4S)\\^   S*S4S+ jjr_ " S, S-5      r` " S. S/5      ra " S0 S15      rb " S2 S35      rcg!   Sr@ N= f! \C a!  rD\ R                  " S\D 35        SrB SrDCDNSrDCDff = f! \C a!  rD\ R                  " S\D 35        SrF SrDCDNSrDCDff = f!   SrG N= f)5    N)deepcopy)Dict)List)Optional)ComputeUnit)ReshapeFrequency)SpecializationStrategy)_logger)proto)	_HAS_TF_1	_HAS_TF_2
_HAS_TORCH)Program)ScopeSource   )_MLMODEL_EXTENSION_MLPACKAGE_EXTENSION_create_mlpackage_get_model_spec_path_has_custom_layer	_is_macos_macos_version_try_get_weights_dir_path)	load_spec)	save_spec   )ModelPackage)_MLModelProxyzFailed to load _MLModelProxy: )_MLModelAssetProxyz#Failed to load _MLModelAssetProxy: T)ImageFfloat32float16quantized_model_linear_quantization!_lookup_table_quantization_linear!_lookup_table_quantization_kmeans!_lookup_table_quantization_custom_dequantize_network_linear_quantization_symmetricz,com.github.apple.coremltools.conversion_datez#com.github.apple.coremltools.sourcez+com.github.apple.coremltools.source_dialectz$com.github.apple.coremltools.version)MLComputeDeviceoptimization_hint_inputreturnc                    U c  g[        U [        5      (       d  [        S5      eU 0 :w  a  [        5       S:  a  [	        S5      eU R                  5        H  nUS;  d  M  [	        SU 35      e   SU ;   a#  [        U S   [        5      (       d  [        S5      eS	U ;   a#  [        U S	   [        5      (       d  [        S
5      eSU ;   a$  [        U S   [        5      (       d  [        S5      egg)zB
Throws an exception if ``optimization_hint_input`` is not valid.
Nz6"optimization_hint_input" must be a dictionary or None   r   z6Optimization hints are only available on macOS >= 15.0)"allowLowPrecisionAccumulationOnGPUreshapeFrequencyspecializationStrategyz2Unrecognized key in optimization_hint dictionary: r0   zg"allowLowPrecisionAccumulationOnGPU" value of "optimization_hint_input" dictionary must be of type boolr2   zy"specializationStrategy" value of "optimization_hint_input" dictionary must be of type coremltools.SpecializationStrategyr1   zm"reshapeFrequency" value of "optimization_hint_input" dictionary must be of type coremltools.ReshapeFrequency)	
isinstancedict	TypeErrorr   
ValueErrorkeysbool_SpecializationStrategy_ReshapeFrequency)r+   ks     W/var/www/html/ai-image-ml/venv/lib/python3.13/site-packages/coremltools/models/model.py_verify_optimization_hint_inputr=   x   s7    &-t44PQQ"$)9G)CQRR$))+ 
 

 QRSQTUVV , ,/FFz DEtP P u
 	
  #:::Nef~N  BY  DZ  DZ  T  U  	U44ZH_`rHs  vG  >H  >H  H  I  	I >H4    c                   >    \ rS rSrS rS rS rS rS rS r	S r
S	rg
)_FeatureDescription   c                     Xl         g N_fd_spec)selffd_specs     r<   __init___FeatureDescription.__init__   s    r>   c                 T    SSR                  [        S U R                  5      5      -  $ )NzFeatures(%s),c                     U R                   $ rC   namexs    r<   <lambda>._FeatureDescription.__repr__.<locals>.<lambda>   s    qvvr>   )joinmaprE   rF   s    r<   __repr___FeatureDescription.__repr__   s"    -=t}})M NNNr>   c                 ,    [        U R                  5      $ rC   )lenrE   rU   s    r<   __len___FeatureDescription.__len__   s    4==!!r>   c                 ~    U R                    H   nXR                  :X  d  M  UR                  s  $    [        SU-  5      eNzNo feature with name %s.)rE   rN   shortDescriptionKeyErrorrF   keyfs      r<   __getitem___FeatureDescription.__getitem__   s8    Aff})))  1C788r>   c                 L    U R                    H  nXR                  :X  d  M    g   g)NTFrE   rN   r`   s      r<   __contains__ _FeatureDescription.__contains__   s!    Aff}  r>   c                 r    U R                    H  nXR                  :X  d  M  X#l          g    [        SU-  5      er]   )rE   rN   r^   AttributeError)rF   ra   valuerb   s       r<   __setitem___FeatureDescription.__setitem__   s5    Aff}%*"  7#=>>r>   c              #   N   #    U R                    H  nUR                  v   M     g 7frC   rf   )rF   rb   s     r<   __iter___FeatureDescription.__iter__   s     A&&L s   #%rD   N)__name__
__module____qualname____firstlineno__rH   rV   rZ   rc   rg   rl   ro   __static_attributes__ r>   r<   r@   r@      s&     O"9?r>   r@   c                   j    \ rS rSrS
S jrS\S\R                  4S jrS\S\R                  4S jr	S	r
g)MLState   r,   Nc                     Xl         g)z
Holds state for an MLModel.

The MLState class provides methods to read and write model state.

See Also
--------
ct.MLModel.predict
N	__proxy__rF   proxys     r<   rH   MLState.__init__   s	     r>   rN   c                 8    U R                   R                  U5      $ )a3  
Retrieve the value of a model state variable.

Parameters
----------
name : str
    The name of the state variable to read.

Returns
-------
numpy.ndarray
    The value of the specified state variable as a NumPy array.

Raises
------
RuntimeError
    If the state cannot be read (e.g. invalid state name).
)r|   
read_state)rF   rN   s     r<   r   MLState.read_state   s    , ~~((..r>   rk   c                 8    U R                   R                  X5      $ )a/  
Set the value of a model state variable.

Parameters
----------
name : str
    The name of the state variable to write.

value : numpy.ndarray
    The new value to assign to the state variable.

Raises
------
RuntimeError
    If the state cannot be written (e.g. invalid value, or invalid state name).
)r|   write_state)rF   rN   rk   s      r<   r   MLState.write_state   s    * ~~))$66r>   r{   r,   N)rq   rr   rs   rt   rH   str_npndarrayr   r   ru   rv   r>   r<   rx   rx      s=    
// 
/077 {{7r>   rx   c                   n    \ rS rSrSrSS jr\S\SS 4S j5       r\0 4S\	S	\
\\	4   SS 4S
 jj5       rSrg)MLModelAsset   z
A class representing a compiled model asset.

It supports two initialization methods:
- From a compiled model directory: The directory should have a '.mlmodelc' extension.
- From memory: Allows direct initialization using in-memory model data.
r,   Nc                 ^    [         b  [        U[         5      (       d  [        S5      eXl        g )Nz7The proxy parameter must be of type _MLModelAssetProxy.)r   r3   r5   r|   r}   s     r<   rH   MLModelAsset.__init__  s&    %Z?Q-R-RUVVr>   compiled_model_pathc                 .    [         R                  " U5      $ )z
Create an MLModelAsset instance from a compiled model path.

Parameters
----------
compiled_model_path : str
    The file path to the compiled model.

Returns
-------
MLModelAsset
    An instance of MLModelAsset created from the specified path.
)r   create_model_asset_from_path)clsr   s     r<   	from_pathMLModelAsset.from_path  s    $ 99:MNNr>   	spec_datablob_mappingc                 .    [         R                  " X5      $ )aV  
Create an MLModelAsset instance from in-memory data.

Parameters
----------
spec_data : bytes
    The specification data of the model.

blob_mapping : Dict[str, bytes])
    A dictionary with blob path as the key and blob data as the value.

Returns
-------
MLModelAsset
    An instance of MLModelAsset created from the provided memory data.
)r   create_model_asset_from_memory)r   r   r   s      r<   from_memoryMLModelAsset.from_memory  s    , ;;ITTr>   r{   r   )rq   rr   rs   rt   __doc__rH   classmethodr   r   bytes_Dictr   ru   rv   r>   r<   r   r      sy    
 O O 
O O&  +-UU CJ'U 
	U Ur>   r   c            
          \ rS rSrSrSSS\R                  SSS4S\\   SS4S jjr	  S5S\
S	\S
\\   S\\   4S jjr\S 5       r\R                  S 5       r\S 5       r\S 5       r\S 5       r\S 5       r\R                  S 5       r\S 5       r\R                  S 5       r\S 5       r\S 5       r\R                  S 5       rS rS rS\
4S jrS rS rS6S\\   4S jjr\S  5       r\S! 5       r S\4S" jr!S\4S# jr"S$\
SS%4S& jr#S\4S' jr$S\4S( jr%S) r&S* r'S+ r(S, r)S- r*\S.\4S/ j5       r+S0 r,\-S\.\/   4S1 j5       r0\S\\1   4S2 j5       r2\S\\1   4S3 j5       r3S4r4g)7MLModeli4  ap  
This class defines the minimal interface to a Core ML 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 Core ML 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)

    # Load a non-default function from a multifunction .mlpackage
    model = MLModel("MultifunctionModel.mlpackage", function_name="deep_features")

See Also
--------
predict
FNoptimization_hintsr,   c	                 j	  ^ S n	S[         4U4S jjm[        U[        5      (       d  [        S5      eU[        R                  :X  a(  [        5       (       a  [        5       S:  a  [        S5      e[        U5        XPl	        Xpl
        Ub  UR                  5       U l        OSU l        SU l        SU l        SU l        SU l        Ub   [        U["        5      (       d  [        S	5      eX0l        [        U[&        5      (       a  [(        R*                  R-                  [(        R*                  R/                  [(        R*                  R1                  U5      5      5      n[(        R*                  R3                  U5      (       a#  S
U l        Xl        X l        [5        U5      U l        U R7                  XXHS9u  U l        U l        U l        O[        U[>        R@                  RB                  5      (       a  T" U5      (       aS  URE                  S5      S:X  a  Uc  [G        S5      eS
U l        S
U l        [I        X5      n
Xl        [5        U
5      U l        O.[J        RL                  " [N        SS9RP                  n
[S        X5        U R7                  XXHS9u  U l        U l        U l         [(        RT                  " U
5        O[        S5      e[Y        U R:                  RZ                  R\                  5      U l/        [Y        U R:                  RZ                  R`                  5      U l1        [e        U R:                  RZ                  R\                   Vs/ s H  oRP                  PM     sn5      U l3        U R                  (       a1  U R                  (       a   [h        Rj                  " XR                  5        U R:                  RZ                  Rl                  nU R                  c  [o        U5      S:  a  Xl
        U R                  b0  U Rq                  5       (       d  U R                  S:w  a  [        S5      eU R                  bf  U Rq                  5       (       aP  U Rs                  U R                  5      n[e        UR\                   Vs/ s H  oRP                  PM     sn5      U l3        ggg! [V         a     GNf = fs  snf s  snf )a  
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.convert.html>`_.

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``.

function_name : str
    The name of the function from ``model`` to load.
    If not provided, ``function_name`` will be set to the ``defaultFunctionName`` in the proto.

optimization_hints : dict or None
    Keys are the names of the optimization hint: 'allowLowPrecisionAccumulationOnGPU', 'reshapeFrequency'
        or 'specializationStrategy'.

    - 'allowLowPrecisionAccumulationOnGPU' value must have ``bool`` type.
    - 'reshapeFrequency' value must have ``coremltools.ReshapeFrequency`` type.
    - 'specializationStrategy' must have``coremltools.SpecializationStrategy`` type.

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")

c                 z    [         R                  R                  U 5      (       a  [        R                  " U 5        g g rC   )_ospathexists_shutilrmtree)package_paths    r<   cleanup!MLModel.__init__.<locals>.cleanup  s&    xx|,,|, -r>   r,   c                 L  > U R                  S5      nUS:X  a  gUS;  a  gUS:X  a  U R                  R                  nOOUS:X  a!  U R                  R                  R                  nO(US:X  d   eU R                  R                  R                  nU H  nT" U5      (       d  M    g   g)	zG
Is this an mlprogram or is it a pipeline with at least one mlprogram?
Type	mlProgramT)pipelinepipelineClassifierpipelineRegressorFr   r   r   )
WhichOneofr   modelsr   r   )model
model_typepipeline_modelsmdoes_model_contain_mlprograms       r<   r   6MLModel.__init__.<locals>.does_model_contain_mlprogram  s     ))&1J[(#ZZ Z'"'.."7"733"'":":"C"C"J"J!%8888"'"9"9"B"B"I"I$/22 % r>   zB"compute_units" parameter must be of type: coremltools.ComputeUnit)   r   zEcoremltools.ComputeUnit.CPU_AND_NE is only available on macOS >= 13.0NFzB"mil_program" must be of type "coremltools.converters.mil.Program"T)skip_model_loadr   r   r   zMLModel 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.)suffixdeletezKExpected model to be a .mlmodel file, .mlpackage file or a Model_pb2 objectr   mainz8function_name must be "main" for non multifunction model):r8   r3   _ComputeUnitr5   
CPU_AND_NEr   r   r6   r=   compute_unitfunction_namecopyr   
is_packageis_temp_packager   _weights_dir_Program_mil_programr   r   r   abspath
expanduser
expandvarsisdirr   _get_proxy_and_specr|   _spec_framework_error_proto	Model_pb2Modelr   	Exceptionr   	_tempfileNamedTemporaryFiler   rN   
_save_specremoveOSErrorr@   descriptioninput_input_descriptionoutput_output_descriptionset_model_input_names_set_atexitregisterdefaultFunctionNamerY   _is_multifunction_get_function_description)rF   r   r   mil_programr   compute_unitsweights_dirr   r   r   filenameidefault_function_namerb   r   s                 @r<   rH   MLModel.__init__q  s   H	-	4 	2 -66`aa|666++ "W,W  	((:;)*)&8&=&=&?D#&*D#$  ":k8+L+Labb'eS!!HH$$SXX%8%89L9LU9S%TUExx~~e$$"&$)!'6$$=e$D!@D@X@Xo AY A=DNDJ(= v//5566+E22##F+{:{?R#< 
 #''+$,U@$,!$=h$G!$77?QZ_`ee5+@D@X@X AY A=DNDJ(=

8$ ]  #6djj6L6L6R6R"S#6tzz7M7M7T7T#U &)4::;Q;Q;W;W*X;Wa66;W*X&Y#??t33W&7&78 !%

 6 6 J J%#.C*Dq*H!6)))++0B0Bf0L ![\\ )d.D.D.F.F..t/A/ABA*-qww.Gw!vvw.G*HD' /G)3   +Y$ /Hs   R R+6R0
R('R(r   r   r   c                 l   [         R                  R                  U5      n[        U5      n[        (       a  U(       d  [        R
                  " 5       nUR                  U:  a  S US 4$ U R                  c  SOU R                  n0 nUbK  UR                  5        H7  u  p[        U
[        5      (       a  [        U
5      X'   M)  U
R                  X'   M9      [	        UUR                  UUS 5      US 4$ S US 4$ ! [         a5  n[        R                  " S[        U5      -   [         5        S X[4s S nA$ S nAff = f)N z_You will not be able to run predict() on this Core ML model. Underlying exception message was: )r   r   r   
_load_specr   'maximum_supported_specification_versionspecificationVersionr   itemsr3   r8   r   rN   RuntimeError	_warningswarnRuntimeWarning)rF   r   r   r   r   specificationengine_versionr   optimization_hints_str_valsr;   ves               r<   r   MLModel._get_proxy_and_specJ  s:    88&&x0"8,= +RRTN11NB ]D00"&"4"4"<B$BTBTM*,'!-.446DA!!T**9<Q369:36	 7.! %**%3 "
 
( ]D((   .<!f #	 ]--.s   C4 4
D3>*D.(D3.D3c                 V    U R                   R                  R                  R                  $ rC   r   r   metadatar^   rU   s    r<   short_descriptionMLModel.short_description  s    zz%%..???r>   c                 L    XR                   R                  R                  l        g rC   r   )rF   r   s     r<   r   r     s    ;L

''8r>   c                     U R                   $ rC   )r   rU   s    r<   input_descriptionMLModel.input_description  s    &&&r>   c                     U R                   $ rC   )r   rU   s    r<   output_descriptionMLModel.output_description  s    '''r>   c                 V    U R                   R                  R                  R                  $ rC   )r   r   r   userDefinedrU   s    r<   user_defined_metadataMLModel.user_defined_metadata  s    zz%%..:::r>   c                 V    U R                   R                  R                  R                  $ rC   r   r   r   authorrU   s    r<   r  MLModel.author  s    zz%%..555r>   c                 L    XR                   R                  R                  l        g rC   r  )rF   r  s     r<   r  r    s    17

''.r>   c                 V    U R                   R                  R                  R                  $ rC   r   r   r   licenserU   s    r<   r  MLModel.license  s    zz%%..666r>   c                 L    XR                   R                  R                  l        g rC   r  )rF   r  s     r<   r  r    s    29

''/r>   c                 V    U R                   R                  R                  R                  $ rC   r   r   r   versionStringrU   s    r<   versionMLModel.version  s    zz%%..<<<r>   c                     U R                   $ rC   )r   rU   s    r<   r   MLModel.weights_dir  s       r>   c                 L    XR                   R                  R                  l        g rC   r  )rF   version_strings     r<   r  r    s    8F

''5r>   c                 J    U R                   R                  R                  5       $ rC   )r   r   rV   rU   s    r<   rV   MLModel.__repr__  s    zz%%..00r>   c                 "    U R                  5       $ rC   )rV   rU   s    r<   __str__MLModel.__str__  s    }}r>   	save_pathc                    [         R                  R                  U5      n[         R                  R                  U5      (       aQ  [         R                  R	                  U5      (       a  [
        R                  " U5        O[         R                  " U5        U R                  (       Ga  [         R                  R                  U5      u  p#U(       d  SR                  U[        5      nO)U[        :w  a  [        SR                  [        U5      5      e[
        R                  " U R                  U5        U R                  b  [!        U R                  R"                  R%                  5        Vs/ s H   n[&        R(                  UR*                  ;   PM"     sn5      (       a  U R                  R-                  5       n[/        U5      S:  ap  [0        R2                  " U R4                  [6           US.5      n[         R                  R9                  US5      n[;        US5       nUR=                  U5        SSS5        [?        U5      n	[A        U RB                  U	5        g[A        U RB                  U5        gs  snf ! , (       d  f       NL= f)am  
Save the model to an ``.mlmodel`` format. For an MIL program, the ``save_path`` is
a package directory containing the ``mlmodel`` and weights.

Parameters
----------
save_path: Target file path / bundle directory for the model.

Examples
--------
.. sourcecode:: python

    model.save("my_model_file.mlmodel")
    loaded_model = MLModel("my_model_file.mlmodel")

z{}{}zFor an ML Program, extension must be {} (not {}). Please see https://coremltools.readme.io/docs/unified-conversion-api#target-conversion-formats to see the difference between neuralnetwork and mlprogram model types.Nr   )r  mappingz$executorch_debug_handle_mapping.jsonw)"r   r   r   r   r   r   r   r   r   splitextformatr   r   copytreer   r   all	functionsvalues_ScopeSourceEXIR_DEBUG_HANDLE_essential_scope_sources%construct_debug_handle_to_ops_mappingrY   jsondumpsr
  _METADATA_VERSIONrS   openwriter   r   r   )
rF   r$  rN   extfunctiondebug_handle_to_ops_mapping#debug_handle_to_ops_mapping_as_json&saved_debug_handle_to_ops_mapping_pathrb   saved_spec_paths
             r<   saveMLModel.save  s   " HH''	2	 88??9%%xx~~i((y)

9%???)))4ID"MM)5IJ	,, n  u  u,c 
 T..	:  ,hlhyhy  iD  iD  iK  iK  iM iM\dL22h6W6WW  iM2 2 %%KKM , 23a7:>**(,(B(BCT(U(C;7 >AXX]]!#I>: DcJa CD K 39=Otzz?3tzz9-/" KJs   ('I-I22
J c                 f    U R                   c  [        S5      eU R                   R                  5       $ )z
Returns the path for the underlying compiled ML Model.

**Important**: This path is available only for the lifetime of this Python object. If you want
the compiled model to persist, you need to make a copy.

zAThis model was not loaded or compiled with the Core ML Framework.)r|   r   get_compiled_model_pathrU   s    r<   r@  MLModel.get_compiled_model_path  s-     >>!_``~~5577r>   c                 ,    [        U R                  5      $ )z
Get a deep copy of the protobuf specification of the model.

Returns
-------
model: Model_pb2
    Protobuf specification of the model.

Examples
--------
.. sourcecode:: python

    spec = model.get_spec()

)	_deepcopyr   rU   s    r<   get_specMLModel.get_spec  s      $$r>   statec                    ^  U 4S jnT R                   (       a(  [        5       (       a  [        5       S:  a  [        S5      e[        R                  U5        T R                  (       a  T R                  T R                  UUU5      $ [        5       S:  a  [        S5      e[        (       d  [        S5      e[        R                  " 5       T R                  R                  :  aR  [        R                  " 5       n[        S[        T R                  R                  5      -   S-   [        U5      -   S	-   5      e[        T R                  5      (       a  [        S
5      eT R                  (       a  T R                  e[        S5      e)a  
Return predictions for the model.

Parameters
----------
data: dict[str, value] or list[dict[str, value]]
    Dictionary of data to use for predictions, where the keys are the names of the input features.
    For batch predictons, use a list of such dictionaries.

    The following dictionary values types are acceptable: list, array, numpy.ndarray, tensorflow.Tensor
    and torch.Tensor.

state : MLState
    Optional state object as returned by ``make_state()``.

Returns
-------
dict[str, value]
    Predictions as a dictionary where each key is the output feature name.

list[dict[str, value]]
    For batch prediction, returns a list of the above dictionaries.

Examples
--------
.. sourcecode:: python

    data = {"bedroom": 1.0, "bath": 1.0, "size": 1240}
    predictions = model.predict(data)

    data = [
        {"bedroom": 1.0, "bath": 1.0, "size": 1240},
        {"bedroom": 4.0, "bath": 2.5, "size": 2400},
    ]
    batch_predictions = model.predict(data)

c                 l   > TR                  U 5        TR                  U 5        TR                  U 5        g rC   )_verify_input_dict_convert_tensor_to_numpy+_update_float16_multiarray_input_to_float32)drF   s    r<   verify_and_convert_input_dict6MLModel.predict.<locals>.verify_and_convert_input_dict=  s-    ##A&))!,<<Q?r>   )   r   zKpredict() for .mlpackage is not supported in macOS version older than 12.0.)
   r   zCModel prediction is only supported on macOS version 10.13 or later.z9Unable to load CoreML.framework. Cannot make predictions.zThe specification has version z_ but the Core ML framework version installed only supports Core ML model specification version z
 or older.zOThis model contains a custom neural network layer, so predict is not supported.)r   r   r   r   r   _check_predict_datar|   _get_predictionsr   r   r   r   r   r   r   )rF   datarF  rM  engineVersions   `    r<   predictMLModel.predict  sW   L	@ ??y{{~/?'/I]  	##D)>>(()F)-).0 0
 (*Y  != [\\EEG**112 !. U U W4$**99:;wx -() #	#  #4::..e  ((///#$_``r>   c                     [        U 5      [        [        4;  a  [        S[        U 5       S35      e[        U 5      [        :X  a'  [	        [        S U 5      5      (       d  [        S5      eg g )Nz@"data" parameter must be either a dict or list of dict, but got .c                 &    [        U 5      [        :H  $ rC   )typer4   rO   s    r<   rQ   -MLModel._check_predict_data.<locals>.<lambda>s  s    Q4r>   z*"data" list must contain only dictionaries)rZ  listr4   r5   r+  rT   )rS  s    r<   rQ  MLModel._check_predict_datam  si    :dD\)RSWX\S]R^^_`  :c#.G*N&O&OJKK 'Pr>   c                     [        U5      [        :X  a*  U" U5        Uc  S OUR                  nU R                  X#5      $ [        U5      [        :X  d   eUb   S5       eU H  nU" U5        M     U R                  U5      $ )Nz0State can only be used for unbatched predictions)rZ  r4   r|   rU  r\  batchPredict)r~   preprocess_methodrS  rF  r   s        r<   rR  MLModel._get_predictionsw  sy    :d#!MDuE==--:%%%=T"TT=!!$ %%d++r>   c                   ^  T R                   R                  n[        UR                  5      S:X  a  [        UR                  5      S:  $ [        [        U 4S jUR                  5      5      n[        UR                  5      S:  $ )Nr   c                 6   > U R                   TR                  :H  $ rC   )rN   r   )rb   rF   s    r<   rQ   &MLModel._is_stateful.<locals>.<lambda>  s    !&&D,>,>">r>   )r   r   rY   r,  rF  r\  filter)rF   
model_descrb   s   `  r<   _is_statefulMLModel._is_stateful  sj    ZZ++
 z##$)z''(1,, >
@T@TUV177|ar>   c                 Z    [        U R                  R                  R                  5      S:  $ )Nr   )rY   r   r   r,  rU   s    r<   r   MLModel._is_multifunction  s"    4::))334q88r>   r   z$_proto.Model_pb2.FunctionDescriptionc                    ^ [        [        U4S jU R                  R                  R                  5      5      n[        U5      S:X  a  [        ST S35      e[        U5      S:X  d   ST S35       eUS   $ )Nc                 "   > U R                   T:H  $ rC   rM   )rb   r   s    r<   rQ   3MLModel._get_function_description.<locals>.<lambda>  s    !&&M"9r>   r   zfunction_name z not found in the model.r   z0Invalid proto: two functions with the same name rX  )r\  re  r   r   r,  rY   r6   )rF   r   rb   s    ` r<   r   !MLModel._get_function_description  sp     94::;Q;Q;[;[\]q6Q;~m_<TUVV1v{_N}o]^__{tr>   c                     [        5       (       a  [        5       S:  a  [        S5      eU R                  c  [        S5      e[	        U R                  R                  5       5      $ )aP  
Returns a new state object, which can be passed to the ``predict`` method.

Returns
_______
state: MLState
    Holds state for an MLModel.

State functionality is only supported on macOS 15+.

Examples
--------
.. sourcecode:: python

    state = model.make_state()
    predictions = model.predict(x, state)

See Also
--------
predict
r.   z2State functionality is only supported on macOS 15+zGThis model was not loaded with the Core ML Framework. Cannot get state.)r   r   r   r|   rx   newStaterU   s    r<   
make_stateMLModel.make_state  sO    , {{n.8PQQ>>!efft~~..011r>   c                     U R                   R                   HG  nUR                  R                  R                  R
                   H  nUR                  S:X  d  M      g   MI     g)z1Check if any input has infinite upper bound (-1).TF)r  rE   rZ  multiArrayType
shapeRange
sizeRanges
upperBound)rF   
input_spec
size_ranges      r<   _input_has_infinite_upper_bound'MLModel._input_has_infinite_upper_bound  sO    0099J(oo<<GGRR
((B. S : r>   c                    U R                   R                  S5      S:w  a  g U R                   R                  R                  nUS   n[        R
                  R                  5       n[        R
                  R                  R                  UR                  l
        [        R
                  R                  5       nUR                  R                  R                  U5        UR                  R                  R                  U5        UR                  R                  U5        UR                   R"                  nUR%                  5        GH  u  px[        R
                  R&                  R)                  5       n	U	R*                  R                   R,                  R.                  R0                  R3                  U5        U	R*                  R                  R                  U5        U	R4                  R                   R,                  R.                  R0                  R3                  U5        U	R4                  R                  R                  U5        UR0                  R3                  U	5        GM     g )Nr   r   	buildInfo)r   r   r   
attributesr   MIL_pb2	ValueTypeDataTypeSTRING
tensorTypedataTypedictionaryTypekeyTypeCopyFrom	valueTyperZ  immediateValue
dictionaryr   DictionaryValueKeyValuePairra   tensorstringsr-  appendrk   )
rF   r   ml_program_attributesbuild_info_protostr_typedict_type_str_to_strbuild_info_dictr;   r   key_pairs
             r<   _set_build_info_mil_attributes&MLModel._set_build_info_mil_attributes  s   ::  (K7 $

 4 4 ? ?0= >>++-'-~~'>'>'E'E$%~~779++33<<XF++55>>xH&&';< +99DDNN$DA~~55BBDHLL''..66==DDQGLL&&x0NN))0088??FFqINN((2""))(3 %r>   c                 ,    [        U R                  5      $ )a  
Get a deep copy of the MIL program object, if available.
It's available whenever an MLModel object is constructed using
the unified converter API [``coremltools.convert()``](https://apple.github.io/coremltools/source/coremltools.converters.mil.html#coremltools.converters._converters_entry.convert).

Returns
-------
program: coremltools.converters.mil.Program

Examples
--------
.. sourcecode:: python

    mil_prog = model._get_mil_internal()

)rC  r   rU   s    r<   _get_mil_internalMLModel._get_mil_internal  s    " **++r>   c                 H    U R                  U5        U R                  U5        g rC   )_verify_input_name_exists_verify_pil_image_modes)rF   
input_dicts     r<   rI  MLModel._verify_input_dict  s"    
 	&&z2 	$$Z0r>   c                    [         (       d  g U R                  R                  R                   GH'  nUR                  R                  S5      S:X  d  M%  UR                  UR                  S 5      n[        U[        R                  5      (       d&  Sn[        UR                  UR                  5      5      eUR                  R                  R                  [        R                   R"                  R$                  [        R                   R"                  R&                  4;   a9  UR(                  S:w  a&  Sn[        UR                  UR                  5      5      eGM)  UR                  R                  R                  [        R                   R"                  R*                  :X  a9  UR(                  S:w  a&  Sn[        UR                  UR                  5      5      eGM  UR                  R                  R                  [        R                   R"                  R,                  :X  d  GM  UR(                  S:w  d  GM  S	n[        UR                  UR                  5      5      e   g )
Nr   	imageTypezCImage input, '{}' must be of type PIL.Image.Image in the input dictRGBzKRGB/BGR image input, '{}', must be of type PIL.Image.Image with mode=='RGB'LzKGRAYSCALE image input, '{}', must be of type PIL.Image.Image with mode=='L'FzSGRAYSCALE_FLOAT16 image input, '{}', must be of type PIL.Image.Image with mode=='F')_HAS_PILr   r   r   rZ  r   getrN   r3   
_PIL_IMAGEr    r5   r)  r  
colorSpacer   FeatureTypes_pb2ImageFeatureTypeBGRr  mode	GRAYSCALEGRAYSCALE_FLOAT16)rF   r  
input_desc	input_valmsgs        r<   r  MLModel._verify_pil_image_modes  s   x**0066J))&1[@&NN:??DA	!)Z-=-=>>_C#CJJz$?@@??,,77++<<@@++<<@@<  !~~.k'

:??(CDD / OO--88..??IIJ !~~,k'

:??(CDD - OO--88..??QQR !~~,s'

:??(CDD5 7r>   c                     UR                  5        H8  nX R                  ;  d  M  Sn[        UR                  X R                  5      5      e   g )NzbProvided key "{}", in the input dict, does not match any of the model input name(s), which are: {})r7   r   r_   r)  )rF   r  given_inputerr_msgs       r<   r  !MLModel._verify_input_name_exists  sA    %??,K"="==Yw~~k;V;VWXX	 -r>   
input_datac                     U R                  5        Hg  u  p[        U[        R                  5      (       d  M&  UR                  [        R
                  :X  d  MF  UR                  [        R                  5      X'   Mi     g rC   )r   r3   r   r   dtyper"   astyper!   )r  r;   r   s      r<   rK  3MLModel._update_float16_multiarray_input_to_float32'  sK    $$&DA!S[[))agg.D ! 5
 'r>   c                 z   S n0 nU R                   R                  R                   Hh  nUR                  R                  R
                  nUR                  R                  R                  R                  U5      nUS:w  d  MZ  XcUR                  '   Mj     UR                  5        H  u  pxXs;  a  M  U" U5      X'   M     g )Nc                    [        U [        R                  5      (       a  U nU$ [        (       a?  [        U [        R
                  5      (       a   U R                  5       R                  5       nU$ [        (       d  [        (       aV  [        U [        R
                  5      (       a7  U R                  [        R                  R                  R                  5       S9nU$ [        R                  " U 5      nU$ )N)session)r3   _numpyr   r   _torchTensordetachnumpyr   r   _tfevalcompatv1Sessionarray)r  sanitized_inputs     r<   convert1MLModel._convert_tensor_to_numpy.<locals>.convert.  s    +v~~66"- #" 
; F F"-"4"4"6"<"<">
 #"	 )yyjcjj.Q.Q"-"2"23::==;P;P;R"2"S #" #),,{";""r>   INVALID_ARRAY_DATA_TYPE)
r   r   r   rZ  ru  r  ArrayDataTypeNamerN   r   )	rF   r  r  model_input_to_typesinp
type_value	type_namegiven_input_namer  s	            r<   rJ   MLModel._convert_tensor_to_numpy-  s    		#  "::))//C0099J//==BB:NI551:SXX.	 0 .8-=-=-?);+2;+?J( .@r>   c                 ,    [         R                  " 5       $ )a#  
The list of available compute devices for CoreML.

Use the method to get the list of compute devices that MLModel's predict method can use.

Some compute devices on the hardware are exclusive to the domain ML frameworks such as Vision and SoundAnalysis and
not available to Core ML framework. See also ``MLComputeDevice.get_all_compute_devices()``.

Returns
-------
The list of compute devices MLModel's predict method can use.

Examples
--------
.. sourcecode:: python

    compute_devices = coremltools.MLModel.get_available_compute_devices()

)r   get_available_compute_devices)r   s    r<   r  %MLModel.get_available_compute_devicesE  s    * ::<<r>   c                 6    U R                   R                  5       $ )a  
Retrieves the duration of the model loading process in nanoseconds.

Notes
-----
Calculates the time elapsed during the model loading process, specifically
measuring the execution time of ``[MLModel loadContentsOfURL:configuration:error:]`` method
of the Core ML framework.

Returns
-------
Optional[int]:
    The duration of the model loading process in nanoseconds.
    Returns None if duration is not available.
)r|   !get_load_duration_in_nano_secondsrU   s    r<   load_duration_in_nano_seconds%MLModel.load_duration_in_nano_seconds\  s    $ ~~??AAr>   c                 6    U R                   R                  5       $ )a9  
Retrieves the duration of the last predict operation in nanoseconds.
This method returns the time taken for the most recent prediction made by
the model, measured in nanoseconds.

Notes
-----
Calculates the time elapsed during the model predict call, specifically
measuring the execution time of ``[MLModel predictionFromFeatures:error:]``
or ``[MLModel predictionFromBatch:error:]`` method of the Core ML framework.

Returns
-------
Optional[int]:
    The duration of the last prediction operation in nanoseconds.
    Returns None if no prediction has been made yet.
)r|   )get_last_predict_duration_in_nano_secondsrU   s    r<   %last_predict_duration_in_nano_seconds-MLModel.last_predict_duration_in_nano_secondsp  s    ( ~~GGIIr>   )r|   r   r   r   r   r   r   r   r   r   r   r   r   r   )FNrC   )5rq   rr   rs   rt   r   r   ALL	_Optionalr4   rH   r   r8   r   propertyr   setterr  r  r
  r  r  r  r   rV   r"  r=  r@  rD  rx   rU  staticmethodrQ  rR  rg  r   r   rq  r{  r  r  rI  r  r  rK  rJ  r   _List_MLComputeDevicer  intr  r  ru   rv   r>   r<   r   r   4  s   :~ "&&.2WI &dOWI 
WIz ,1.22)2) $2) #4	2)
 &dO2)j @ @ M M ' ' ( ( ; ; 6 6 ]]8 8 7 7 ^^: : = = ! ! ^^G G1>.c >.B8%&Sa9W#5 Sal L L 
, 
,
 d 
 94 9
 
	/
2G 2< 46,(1E@Y 6 6 6
@0 =e4D.E = =, By~ B B& Jy~ J Jr>   r   rC   )datexitr   r2  osr   shutilr   tempfiler   warningsr   r   r   rC  typingr   r   r   r  r   r  r  r   r  coremltoolsr   r   r   r:   r	   r9   r
   loggerr   r   coremltools._depsr   r   r   &coremltools.converters.mil.mil.programr   r   $coremltools.converters.mil.mil.scoper   r.  utilsr   r   r   r   r   r   r   r   r   r   r   r   torchr  
tensorflowr  libmodelpackager   _ModelPackagelibcoremlpythonr   r   r   warningr   r  PILr    r  _MLMODEL_FULL_PRECISION_MLMODEL_HALF_PRECISION_MLMODEL_QUANTIZED_VALID_MLMODEL_PRECISION_TYPES&_QUANTIZATION_MODE_LINEAR_QUANTIZATION&_QUANTIZATION_MODE_LOOKUP_TABLE_LINEAR&_QUANTIZATION_MODE_LOOKUP_TABLE_KMEANS&_QUANTIZATION_MODE_CUSTOM_LOOKUP_TABLE_QUANTIZATION_MODE_DEQUANTIZE#_QUANTIZATION_MODE_LINEAR_SYMMETRIC_SUPPORTED_QUANTIZATION_MODES_LUT_BASED_QUANTIZATION_METADATA_CONVERSION_DATE_METADATA_SOURCE_METADATA_SOURCE_DIALECTr4  compute_devicer*   r  r4   r=   r@   rx   r   r   rv   r>   r<   <module>r     s         &     (   3 = I ) ' > > F L	 	 	 + *	?/4
 '
 $ # &  "  *@ &)L &)L &)L & 5 &F # +***!'!  +**  K 8 H :  ?IYt_ IX\ IF D:7 :7z8U 8UtPJ PJCM  
NN3A378M  
NN8<=HsH   +D1 2D: 9E$ F 1D7:E! EE!$F*FFF