o
    2h                     @   s   d dl Z d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlm	Z	 d dlm
Z
 d d	lmZ 	dd
dZdd Zdd Zdd Zdd ZdS )    N)backend)treeconvert_spec_to_tensor)get_input_signature)make_tf_tensor_spec)DEFAULT_ENDPOINT_NAME)ExportArchive)io_utilsc                    s  | dsJ d| ddl}ddlm ddlm  ddlm |dur(|nd}|du r2t| }t d	krddl	}d fdd	t
|trUt|dkrU|d }tdd |}|}	|| j}
t|
jdkrzt
|	ttfrz| |	 }n| |	}dd t|	D }fddt|D }|j||d}t|}t|j|D ]\}}dd |jD }||}| | qnut dv rtt|}t| |fi |}||}t|| nUt dkr1ddl}tdd |}t|}t | dr| !  t"# " t"j$d|j%j&d |j%'| |}||}t|| W d   n	1 s+w   Y  nt(d|)|| |rIt*+d| d dS dS )a	  Export the model as an OpenVINO IR artifact for inference.

    This method exports the model to the OpenVINO IR format,
    which includes two files:
    a `.xml` file containing the model structure and a `.bin` file
    containing the weights.
    The exported model contains only the forward pass
    (i.e., the model's `call()` method), and can be deployed with the
    OpenVINO Runtime for fast inference on CPU and other Intel hardware.

    Args:
        filepath: `str` or `pathlib.Path`. Path to the output `.xml` file.
        The corresponding `.bin` file will be saved alongside it.
        verbose: Optional `bool`. Whether to print a confirmation message
        after export. If `None`, it uses the default verbosity configured
        by the backend.
        input_signature: Optional. Specifies the shape and dtype of the
        model inputs. If not provided, it will be inferred.
        **kwargs: Additional keyword arguments.

     Example:

    ```python
    import keras

    # Define or load a Keras model
    model = keras.models.Sequential([
        keras.layers.Input(shape=(128,)),
        keras.layers.Dense(64, activation="relu"),
        keras.layers.Dense(10)
    ])

    # Export to OpenVINO IR
    model.export("model.xml", format="openvino")
    ```
    z.xmlzCThe OpenVINO export requires the filepath to end with '.xml'. Got: r   N)opset14)OPENVINO_DTYPES)OpenVINOKerasTensorTopenvino c                    s   t | ttfr fddt| D S t | tr#fdd|  D S t | rGt| j }t| j}j	||d}|
  |dS tdt|  )Nc                    s"   g | ]\}} | | qS  r   ).0ie)parameterize_inputsprefixr   T/var/www/html/chatgem/venv/lib/python3.10/site-packages/keras/src/export/openvino.py
<listcomp>I   s    z@export_openvino.<locals>.parameterize_inputs.<locals>.<listcomp>c                    s   i | ]
\}}| ||qS r   r   )r   kv)r   r   r   
<dictcomp>N   s    z@export_openvino.<locals>.parameterize_inputs.<locals>.<dictcomp>)shapedtyper   zUnknown input type: )
isinstancelisttuple	enumeratedictitemsstrr   r   	parameterset_friendly_nameoutput	TypeErrortype)inputsr   ov_typeov_shapeparamr   r   ov_opsetr   )r   r   r   G   s   



z,export_openvino.<locals>.parameterize_inputs   c                 S      t | ddS Nr/   )replace_none_numberr   xr   r   r   <lambda>\       z!export_openvino.<locals>.<lambda>c                 S   s   g | ]}|j  qS r   )r&   get_node)r   pr   r   r   r   e   s    z#export_openvino.<locals>.<listcomp>c                    s   g | ]}  |jqS r   )resultr&   )r   r)r.   r   r   r   f   s    )results
parametersc                 S   s   g | ]
}|d u r
dn|qS )Nr   )r   dimr   r   r   r   k   s    )
tensorflowjaxtorchc                 S   r0   r1   r   r3   r   r   r   r5   z   r6   evalignore)categoryzW`export_openvino` is only compatible with OpenVINO, TensorFlow, JAX and Torch backends.zSaved OpenVINO IR at 'z'.)r   ),endswithr   openvino.runtimer   keras.src.backend.openvino.corer   r   r   r   inspectr   r   lenr   map_structure	signaturecallr<   r   flattenModelzipr)   r   PartialShaper7   set_partial_shaper   get_concrete_fnconvert_model	set_namesrA   hasattrrB   warningscatch_warningsfilterwarningsjitTracerWarningtraceNotImplementedError	serializer
   	print_msg)modelfilepathverboseinput_signaturekwargsovactual_verboserH   sample_inputsparamsrK   outputsr<   r;   ov_model
flat_specsov_inputspecdynamic_shape_dimsdynamic_shaper)   decorated_fnrA   tracedr   r-   r   export_openvino   s   '





rq   c                 c   s    t | tr$|  D ]\}}t |tttfrt|E d H  q
|V  q
d S t | ttfr9| D ]	}t|E d H  q-d S t| drG| jrG| jV  d S dV  d S )Nnameinput)r   r!   r"   r   r   collect_namesrU   rr   )	structurer   r   r   r   r   rt      s   

rt   c                 C   sB   t t|}t| j|D ]\}}| | |j|h qd S )N)r   rt   rO   r)   r7   r%   tensorrT   )r_   r)   namesrk   rr   r   r   r   rT      s
   rT   c                 C   sv   |   } d| vrd| d< d| vrddd| d< | d dur!td| d d dur-td| d d	 dur9td
| S )N	is_staticTjax2tf_kwargsF)
enable_xlanative_serializationzB`is_static` must be `True` in `kwargs` when using the jax backend.rz   zU`enable_xla` must be `False` in `kwargs['jax2tf_kwargs']` when using the jax backend.r{   z_`native_serialization` must be `False` in `kwargs['jax2tf_kwargs']` when using the jax backend.)copy
ValueError)rc   r   r   r   _check_jax_kwargs   s(   
r~   c                 K   sN   t   dkr
t|}t }|jt| |fi | t   dkr"|  |tS )Nr@   r?   )r   r~   r	   track_and_add_endpointr   _filter_and_track_resources_get_concrete_fn)r_   rb   rc   export_archiver   r   r   rR      s   
rR   )NN)rV   	keras.srcr   r   keras.src.export.export_utilsr   r   r   keras.src.export.saved_modelr   r	   keras.src.utilsr
   rq   rt   rT   r~   rR   r   r   r   r   <module>   s     
 