§
    ­¸j&,  ã                  ó>  — d 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ZddlmZ dd	lmZmZ dd
lmZmZ ddlmZ ddlmZ  e¦   «         Zdd„Z edd¬¦  «         G d„ de¦  «        ¦   «         Z G d„ dej        ¦  «        Z G d„ dee         ¦  «        ZdS )u&   Direct PyTorch â†’ OpenVINO IR export.é    )Úannotations)ÚCallable)Ú	dataclass)ÚPath)ÚAnyN)Únn)Úappend_backbone_markerÚresolve_export_stem)ÚExportConfigÚExporter)ÚExportGraph)Ú
get_loggerÚreturnÚNonec                 óT   — 	 ddl } dS # t          $ r}t          d¦  «        |‚d}~ww xY w)a�  Verify that ``openvino`` is importable.

    Shared by :class:`OpenVINOExporter` and :class:`~rfdetr.export._openvino.inference.OpenVINOInference`
    so both surface the same actionable message and tests can monkeypatch a single choke point instead
    of relying on ``openvino`` actually being absent from the environment.

    Raises:
        ImportError: If ``openvino`` cannot be imported.
    r   NzMOpenVINO requires `openvino`. Install it with: pip install "rfdetr[openvino]")ÚopenvinoÚImportError)r   Úerrors     úp/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/rfdetr/export/_openvino/exporter.pyÚ_check_openvino_availabler      sJ   € ðvØˆˆˆˆˆøÝð vð vð vÝÐiÑjÔjÐpuÐuøøøøðvøøøs   ‚ ˆ
'’"¢'T)ÚfrozenÚslotsc                  ó"   — e Zd ZU dZdZded<   dS )ÚOpenVINOConfigz§Settings for ``format="openvino"``.

    Attributes:
        precision: ``"float32"``, ``"float16"``, or ``None`` to keep OpenVINO's own FP16 compression default.
    Nz
str | NoneÚ	precision)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   Ú__annotations__© ó    r   r   r   +   s/   € € € € € € ðð ð !€IÐ Ð Ð Ñ Ð Ð r"   r   c                  ó,   ‡ — e Zd ZdZdˆ fd„Zdd
„Zˆ xZS )ÚModelWrapperaÄ  Normalize an export-mode RF-DETR forward into a plain tensor tuple for ``openvino.convert_model``.

    The wrapped *model* must already be switched into export mode by the caller (see
    :class:`OpenVINOExporter`) -- ``forward_export`` always returns a
    tuple of tensors for the full detector (``(dets, labels)`` / ``(dets, labels, masks)`` /
    ``(dets, labels, keypoints)``), and the backbone-only export graph
    (:class:`rfdetr.export._backend._BackboneExport`) returns a plain list of tensors. A dict output
    only reaches this wrapper when the caller forgot the mode-switch -- that is a caller bug, not a
    shape this wrapper can flatten, so it raises instead of silently dropping keys.
    Úmodelú	nn.Moduler   r   c                óV   •— t          ¦   «                              ¦   «          || _        d S )N)ÚsuperÚ__init__r%   )Úselfr%   Ú	__class__s     €r   r)   zModelWrapper.__init__B   s$   ø€ Ý‰Œ×ÒÑÔÐØˆŒ
ˆ
ˆ
r"   Úxútorch.Tensorútuple[torch.Tensor, ...]c                ó*  — |                       |¦  «        }t          |t          t          f¦  «        rt          |¦  «        S t          |t          ¦  «        r t          dt          |¦  «        › d�¦  «        ‚t          dt          |¦  «        ›�¦  «        ‚)Nz:OpenVINO export received a dict-valued model output (keys=zœ); this means the model was not switched into export mode before wrapping (forward_export always returns a tuple/list). Call model.export() before wrapping.z3Unsupported model output type for OpenVINO export: )	r%   Ú
isinstanceÚlistÚtupleÚdictÚNotImplementedErrorÚsortedÚ	TypeErrorÚtype)r*   r,   Úoutputs      r   ÚforwardzModelWrapper.forwardF   s˜   € Ø—’˜A‘”ˆÝ�f�t¥U˜mÑ,Ô,ð 	!Ý˜‘=”=Ð Ý�f�dÑ#Ô#ð 	Ý%ðUÍVÐTZÉ^Ì^ð Uð Uð Uñô ð õ
 Ð^ÍdÐSYÉlÌlÐ^Ð^Ñ_Ô_Ð_r"   )r%   r&   r   r   )r,   r-   r   r.   )r   r   r   r   r)   r9   Ú__classcell__)r+   s   @r   r$   r$   6   sc   ø€ € € € € ð	ð 	ðð ð ð ð ð ð
`ð 
`ð 
`ð 
`ð 
`ð 
`ð 
`ð 
`r"   r$   c                  ój   — e Zd ZdZeZddiZdZdZdZ	dZ
dZd!d
„Zd"d„Zd#d„Zd$d„Zd%d„Zd&d„Zd'd„Zd S )(ÚOpenVINOExportera”  Convert a prepared graph straight to OpenVINO IR, with no ONNX step in between.

    The conversion runs as a short sequence of steps, each its own method: import OpenVINO's converters, create
    the output directory, resolve the artifact name, translate *precision* into OpenVINO's compression flag,
    wrap the graph for tracing, then convert and save the ``.xml``/``.bin`` pair.

    Note:
        Output tensor names in the saved IR are OpenVINO-inferred, not renamed to ``dets``/``labels``/etc. --
        consumers must match outputs by **position**, mirroring the CoreML export's naming limitation.

    Examples:
        Requires the optional ``openvino`` dependency and a prepared graph, so this is documentation only
        (not a doctest):

        ```python
        OpenVINOExporter(OpenVINOConfig(variant_name="rfdetr-small"))(graph)
        # -> PosixPath('output/rfdetr-small.xml')
        ```
    r   Úopenvino_precisionr   ÚOpenVINOzR(the IR graph bakes a fixed input shape). Export one model per batch size instead.z+OpenVINO IR has no ONNX-style metadata slotr   ú-tuple[Callable[..., Any], Callable[..., Any]]c                ó6   — t          ¦   «          ddlm}m} ||fS )a­  Verify ``openvino`` is installed and return the two entry points the conversion needs.

        Imported here rather than at module scope so ``format="openvino"`` is the only export path that pays
        for the (optional, heavy) dependency.

        Returns:
            The ``(convert_model, save_model)`` pair from the ``openvino`` package.

        Raises:
            ImportError: If ``openvino`` is not installed.
        r   )Úconvert_modelÚ
save_model)r   r   rA   rB   )r*   rA   rB   s      r   Ú_import_convertersz#OpenVINOExporter._import_convertersp   s3   € õ 	"Ñ#Ô#Ð#Ø6Ð6Ð6Ð6Ð6Ð6Ð6Ð6à˜jÐ(Ð(r"   r   c                óf   — t          | j        j        ¦  «        }|                     dd¬¦  «         |S )z¡Create the configured output directory if it does not exist yet.

        Returns:
            The directory the ``.xml``/``.bin`` pair is written into.
        T)ÚparentsÚexist_ok)r   ÚconfigÚ
output_dirÚmkdir)r*   rH   s     r   Ú_prepare_output_dirz$OpenVINOExporter._prepare_output_dir�   s5   € õ ˜$œ+Ô0Ñ1Ô1ˆ
Ø×Ò °ÐÑ5Ô5Ð5ØÐr"   Úbackbone_onlyÚboolÚstrc               óÆ   — t          | j        j        | j        j        |rdnd¬¦  «        \  }}t	          ||t          | j        j        p| j        j        ¦  «        ¬¦  «        S )zìResolve the filename stem the ``.xml`` and its companion ``.bin`` share.

        Args:
            backbone_only: Whether the graph is a backbone-only export.

        Returns:
            The artifact name, without extension.
        Úbackbone_modelÚinference_model)Údefault)rK   Únamed)r
   rG   Úvariant_nameÚoutput_namer	   rL   )r*   rK   ÚstemÚ_s       r   Ú_resolve_export_namez%OpenVINOExporter._resolve_export_name‹   st   € õ &ØŒKÔ$ØŒKÔ#Ø(5ÐLÐ$Ð$Ð;Lð
ñ 
ô 
‰ˆˆaõ
 &ØØ'Ý�t”{Ô/ÐJ°4´;Ô3JÑKÔKð
ñ 
ô 
ð 	
r"   c                ób   — | j         j        }|�|dk    rdS |dk    rdS t          d|›�¦  «        ‚)a?  Translate the configured *precision* into ``save_model``'s ``compress_to_fp16`` flag.

        ``compress_to_fp16`` controls IR *storage* precision only -- execution precision still depends on the
        compiled device and is not guaranteed to match eager PyTorch on non-CPU devices. ``None`` keeps
        OpenVINO's own compressing default, which ``"float16"`` states explicitly.

        Returns:
            Whether weights are stored compressed to FP16.

        Raises:
            ValueError: If *precision* is not ``"float32"``, ``"float16"``, or ``None``.
        NÚfloat16TÚfloat32Fz5precision must be 'float32', 'float16', or None, got )rG   r   Ú
ValueError)r*   r   s     r   Ú_resolve_compress_to_fp16z*OpenVINOExporter._resolve_compress_to_fp16Ÿ   sK   € ð ”KÔ)ˆ	ØÐ 	¨YÒ 6Ð 6Ø�4Ø˜	Ò!Ð!Ø�5ÝÐ^ÐQZÐ^Ð^Ñ_Ô_Ð_r"   Úgraphr   ú!tuple[ModelWrapper, torch.Tensor]c                ón  — | j         j        rAt                               d¦  «         t                               d|j        j        › �¦  «         |j                             ¦   «                              ¦   «         }t          |¦  «        }|                     ¦   «          ||j                             ¦   «         fS )aÐ  Announce the conversion, then move the graph onto CPU and wrap it for ``convert_model``.

        ``convert_model`` traces on CPU, and :class:`ModelWrapper` normalizes the export-mode forward's
        tuple/list output into the plain tensor tuple the converter accepts.

        Args:
            graph: The prepared model and its graph metadata.

        Returns:
            The wrapped model and the example input tensor, both on CPU and in eval mode.
        z*Converting PyTorch model to OpenVINO IR...zInput shape: )
rG   ÚverboseÚloggerÚinfoÚinput_tensorsÚshaper%   ÚevalÚcpur$   )r*   r]   r%   Úwrapped_models       r   Ú_prepare_module_for_tracingz,OpenVINOExporter._prepare_module_for_tracing³   sž   € ð Œ;Ôð 	EÝ�KŠKÐDÑEÔEÐEÝ�KŠKÐC¨Ô(;Ô(AÐCÐCÑDÔDÐDà”× Ò Ñ"Ô"×&Ò&Ñ(Ô(ˆÝ$ UÑ+Ô+ˆØ×ÒÑÔÐØ˜eÔ1×5Ò5Ñ7Ô7Ð7Ð7r"   Ú
convertersrg   r$   rc   r-   Ú
output_xmlÚcompress_to_fp16r   c               óp  — |\  }}	 t          j        ¦   «         5   |||¬¦  «        }ddd¦  «         n# 1 swxY w Y    ||t          |¦  «        |¬¦  «         dS # t          t          t
          t          f$ r ‚ t          $ r2}	t           	                    d¦  «         t          d|	› �¦  «        |	‚d}	~	ww xY w)aç  Trace *wrapped_model* into an IR graph and write it to *output_xml* (plus its ``.bin``).

        Args:
            converters: The ``(convert_model, save_model)`` pair from :meth:`_import_converters`.
            wrapped_model: The CPU, eval-mode module to trace.
            input_tensors: Example input the conversion traces with.
            output_xml: Destination path for the IR graph; the weights land beside it as ``.bin``.
            compress_to_fp16: Whether to store the weights compressed to FP16.

        Raises:
            ImportError: If ``convert_model``'s lazy submodule imports fail on a partial/ABI-mismatched install.
            NotImplementedError: If the model was not switched into export mode first (see :class:`ModelWrapper`).
            TypeError: If the model's forward returns an output type :class:`ModelWrapper` cannot wrap.
            ValueError: If the conversion rejects an argument.
            RuntimeError: If conversion or saving otherwise fails.
        )Úexample_inputN©rk   zOpenVINO export failedz'Failed to export model to OpenVINO IR: )ÚtorchÚno_gradrM   r   r4   r6   r[   Ú	Exceptionra   Ú	exceptionÚRuntimeError)
r*   ri   rg   rc   rj   rk   rA   rB   Úov_modelÚes
             r   Ú_convert_and_savez"OpenVINOExporter._convert_and_saveÈ   s1  € ð2 %/Ñ!ˆ�zð	UÝ”‘”ð Uð UØ(˜=¨ÀmÐTÑTÔT�ðUð Uð Uñ Uô Uð Uð Uð Uð Uð Uð Uøøøð Uð Uð Uð UàˆJ�x¥ Z¡¤ÐCSÐTÑTÔTÐTÐTÐTøÝÕ0µ)½ZÐHð 	ð 	ð 	ð Ýð 	Uð 	Uð 	UÝ×ÒÐ5Ñ6Ô6Ð6ÝÐLÈÐLÐLÑMÔMÐSTÐTøøøøð	Uøøøs2   ‡A š4¨A ´8¸A »8¼A Á'B5Â-B0Â0B5c                óÞ  — |                       ¦   «         }|                      ¦   «         }|                      |j        ¬¦  «        }||› d�z  }||› d�z  }|                      ¦   «         }|                      |¦  «        \  }}	|                      |||	||¬¦  «         | j        j        r:t           
                    d|› �¦  «         t           
                    d|› �¦  «         t          |¦  «        S )zAWrite the ``.xml``/``.bin`` IR pair and return the ``.xml`` path.)rK   z.xmlz.binrn   u   âœ“ OpenVINO IR model saved to u   âœ“ Model binary saved to )rC   rJ   rW   rK   r\   rh   rv   rG   r`   ra   rb   rM   )
r*   r]   ri   rH   Úexport_namerj   Ú
output_binrk   rg   rc   s
             r   Ú_convertzOpenVINOExporter._convertñ   sý   € à×,Ò,Ñ.Ô.ˆ
Ø×-Ò-Ñ/Ô/ˆ
Ø×/Ò/¸eÔ>QÐ/ÑRÔRˆØ [Ð"6Ð"6Ð"6Ñ6ˆ
Ø [Ð"6Ð"6Ð"6Ñ6ˆ
Ø×9Ò9Ñ;Ô;Ðà'+×'GÒ'GÈÑ'NÔ'NÑ$ˆ�}Ø×Ò˜z¨=¸-ÈÐfvÐÑwÔwÐwàŒ;Ôð 	CÝ�KŠKÐF¸*ÐFÐFÑGÔGÐGÝ�KŠKÐA°ZÐAÐAÑBÔBÐBÝ�:‰ŒÐr"   N)r   r?   )r   r   )rK   rL   r   rM   )r   rL   )r]   r   r   r^   )ri   r?   rg   r$   rc   r-   rj   r   rk   rL   r   r   )r]   r   r   rM   )r   r   r   r   r   Úconfig_classÚsetting_namesÚformatÚdisplay_nameÚdynamic_batch_reasonÚ	pip_extraÚnotes_reasonrC   rJ   rW   r\   rh   rv   rz   r!   r"   r   r<   r<   S   sß   € € € € € ðð ð( "€LØ Ð"6Ð7€MØ€FØ€LØoÐØ€IØ@€Lð)ð )ð )ð )ð"ð ð ð ð
ð 
ð 
ð 
ð(`ð `ð `ð `ð(8ð 8ð 8ð 8ð*'Uð 'Uð 'Uð 'UðRð ð ð ð ð r"   r<   )r   r   )r   Ú
__future__r   Úcollections.abcr   Údataclassesr   Úpathlibr   Útypingr   ro   r   Úrfdetr.export._namingr	   r
   Úrfdetr.export.baser   r   Úrfdetr.export.preparer   Úrfdetr.utilities.loggerr   ra   r   r   ÚModuler$   r<   r!   r"   r   ú<module>rŒ      s¶  ðð -Ð ,à "Ð "Ð "Ð "Ð "Ð "à $Ð $Ð $Ð $Ð $Ð $Ø !Ð !Ð !Ð !Ð !Ð !Ø Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð à €€€Ø Ð Ð Ð Ð Ð à MÐ MÐ MÐ MÐ MÐ MÐ MÐ MØ 5Ð 5Ð 5Ð 5Ð 5Ð 5Ð 5Ð 5Ø -Ð -Ð -Ð -Ð -Ð -Ø .Ð .Ð .Ð .Ð .Ð .à	ˆ‰Œ€ðvð vð vð vð  €�$˜dÐ#Ñ#Ô#ð!ð !ð !ð !ð !�\ñ !ô !ñ $Ô#ð!ð`ð `ð `ð `ð `�2”9ñ `ô `ð `ð:mð mð mð mð m�x Ô/ñ mô mð mð mð mr"   