§
    ­¸jm8  ã                  ób  — U d Z ddlmZ ddlZddlmZmZ ddlmZ ddl	m
Z
 ddlmZ ddlmZmZmZmZmZmZ dd	lmZ dd
lmZ ddlmZ ddlmZ  e¦   «         Z e
dd¬¦  «         G d„ d¦  «        ¦   «         Zd%d„Zd&d„ZdZ de!d<   d'd „Z" ed!e¬"¦  «        Z# G d#„ d$eee#         ¦  «        Z$dS )(ul  The exporter interface every export format implements, and the configuration each one takes.

An exporter is constructed from its format's configuration and then called with a prepared
:class:`~rfdetr.export.prepare.ExportGraph`, so the two halves of an export â€” *what the user asked for* and *what the
model looks like* â€” stay separate and independently testable.

The base class owns everything that is the same for all seven formats: rejecting a capability the format does not have,
switching the model into its export-friendly forward exactly once, normalizing the returned path, and logging the
result. A format subclass implements :meth:`Exporter._convert` and declares its capabilities as class attributes; it
never repeats a guard.

Configuration is per format rather than one flat object, so a knob that does not apply cannot be passed: there is no
``opset_version`` on ``CoreMLConfig`` to silently ignore. Each format's configuration class lives beside the exporter
that reads it, not here â€” this module names no format, so adding one touches its own package and the registry rather
than the abstraction they share.
é    )ÚannotationsN)ÚABCÚabstractmethod)ÚMapping)Ú	dataclass)ÚPath)ÚAnyÚClassVarÚFinalÚGenericÚTypeVarÚcast)Ú_switch_to_export_mode)ÚExportGraph)Úrequire_entry)Ú
get_loggerT)ÚfrozenÚslotsc                  óˆ   — e Zd ZU dZ ed¦  «        Zded<   dZded<   dZded<   d	Z	d
ed<   d	Z
d
ed<   dZd
ed<   dZded<   dS )ÚExportConfiga¸  Settings every export format understands.

    Attributes:
        output_dir: Directory the artifact is written to.
        output_name: Full filename override (without extension), or ``None`` to derive one from *variant_name*.
        variant_name: Model variant identifier used to name the artifact when *output_name* is unset.
        backbone_only: Whether the graph is a backbone-only export, which the filename marks.
        dynamic_batch: Whether the graph carries a dynamic batch dimension.
        verbose: Whether the format's converter should log its progress.
        notes: User-supplied metadata. Only formats declaring ``supports_notes`` embed it; the rest warn and drop it.
    Úoutputr   Ú
output_dirNz
str | NoneÚoutput_nameÚvariant_nameFÚboolÚbackbone_onlyÚdynamic_batchTÚverboseÚobjectÚnotes)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   Ú__annotations__r   r   r   r   r   r    © ó    úb/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/rfdetr/export/base.pyr   r   (   s�   € € € € € € ð
ð 
ð �t˜H‘~”~€JÐ%Ð%Ð%Ñ%Ø"€KÐ"Ð"Ð"Ñ"Ø#€LÐ#Ð#Ð#Ñ#Ø€MÐÐÐÑØ€MÐÐÐÑØ€GÐÐÐÑØ€EÐÐÐÑÐÐr'   r   ÚlabelÚstrÚreasonÚreturnc                ó4   — | › d|› �                      ¦   «         S )a  Compose the message shown when a format cannot bake a dynamic batch dimension.

    Args:
        label: How the format is spelled in messages addressed to users.
        reason: Why the format cannot do it, and what to do instead.

    Returns:
        The rejection message.

    Examples:
        >>> _dynamic_batch_message("CoreML", "(fixed shapes are required). Export one per batch size instead.")
        'CoreML export does not support dynamic_batch (fixed shapes are required). Export one per batch size instead.'
    z' export does not support dynamic_batch )Úrstrip)r)   r+   s     r(   Ú_dynamic_batch_messager/   ?   s$   € ð ÐDÐD¸FÐDÐD×KÒKÑMÔMÐMr'   Úformatr   r   ÚNonec               óˆ   — |sdS t          | ¦  «        }|j        rdS t          t          |j        |j        ¦  «        ¦  «        ‚)uÑ  Raise when *format* cannot honour ``dynamic_batch``, without importing the format's dependencies.

    The exporter class rejects this too, but only once it exists â€” and constructing it means importing
    ``coremltools``/``executorch``/``openvino`` first, tens of seconds and hundreds of megabytes for a request that
    was already doomed. The registry mirrors the capability â€” and the explanation â€” precisely so the refusal can
    happen before that, with the same wording either route reaches it by.

    Args:
        format: Canonical format name.
        dynamic_batch: Whether the caller asked for a dynamic batch dimension.

    Raises:
        NotImplementedError: If *format* bakes a fixed batch size and *dynamic_batch* is set.
        ValueError: If *format* is not a known export format.

    Examples:
        >>> reject_unsupported_dynamic_batch("onnx", dynamic_batch=True)
        >>> reject_unsupported_dynamic_batch("coreml", dynamic_batch=False)
    N)r   Úsupports_dynamic_batchÚNotImplementedErrorr/   r)   Údynamic_batch_reason)r0   r   Úentrys      r(   Ú reject_unsupported_dynamic_batchr7   P   sL   € ð( ð ØˆÝ˜&Ñ!Ô!€EØÔ#ð ØˆÝ
Õ4°U´[À%ÔB\Ñ]Ô]Ñ
^Ô
^Ð^r'   )r   r   r   r   r   r   r    zFinal[tuple[str, ...]]ÚSHARED_FIELDSÚconfigúdict[str, Any]c                ó*   ‡ — ˆ fd„t           D ¦   «         S )uØ  Extract the format-independent half of *config*, ready to splat into another configuration class.

    Used by the two-stage formats to build the intermediate ONNX configuration they export through: the
    intermediate graph inherits every setting the ONNX stage understands, *notes* included â€” the two-stage formats
    have always embedded them in the ``.onnx`` they pass on, and dropping them would silently change what a
    ``format="tflite"`` export writes.

    Args:
        config: Any format's configuration.

    Returns:
        The :data:`SHARED_FIELDS` values, keyed by field name.

    Examples:
        >>> shared_settings(ExportConfig(variant_name="rfdetr-small"))["variant_name"]
        'rfdetr-small'
    c                ó2   •— i | ]}|t          ‰|¦  «        “ŒS r&   )Úgetattr)Ú.0Únamer9   s     €r(   ú
<dictcomp>z#shared_settings.<locals>.<dictcomp>Œ   s%   ø€ ÐBÐBÐB¨DˆD•'˜& $Ñ'Ô'ÐBÐBÐBr'   )r8   )r9   s   `r(   Úshared_settingsrA   z   s    ø€ ð$ CÐBÐBÐBµMÐBÑBÔBÐBr'   Ú_ConfigT)Úboundc                  ó
  — e Zd ZU dZeZded<   i Zded<   ded<   dZded	<   d
Z	ded<   d
Z
ded<   d
Zded<   dZded<   dZded<   dZded<   dZded<   ed(d„¦   «         Zed)d„¦   «         Zd*d „Zd+d!„Zd,d%„Zed-d'„¦   «         ZdS ).ÚExporteru*
  Write one export format's artifact from a prepared graph.

    Subclasses declare what their format can do as class attributes and implement :meth:`_convert`. Constructing
    an exporter validates the configuration against those capabilities, so an unsupported combination is rejected
    before the caller pays for a full forward pass through the model. A subclass may also override
    :meth:`_check_capabilities` (calling ``super()`` first) to validate settings the class attributes cannot
    express on their own â€” cross-field consistency within the format's own configuration, for example â€” raising
    ``ValueError`` for that kind of rejection, distinct from the base class's own ``NotImplementedError``.

    A subclass also owns its configuration: :attr:`config_class` names the dataclass it is constructed from, and
    :attr:`setting_names` maps that dataclass's format-specific fields onto the keyword arguments
    :meth:`rfdetr.detr.RFDETR.export` accepts. :meth:`build_config` then narrows the public method's
    union-of-every-format signature down to one format's settings without the base class knowing which formats
    exist â€” the registry is the only place that enumerates them.

    Attributes:
        config_class: The configuration dataclass :meth:`build_config` instantiates.
        setting_names: This format's configuration fields, mapped to the ``RFDETR.export`` keyword each is read
            from. Shared fields (:data:`SHARED_FIELDS`) are handled by the base class and must not be listed.
        format: The format name this exporter is registered under.
        display_name: How the format is spelled in messages addressed to users.
        supports_dynamic_batch: Whether the format can bake a dynamic batch dimension into its artifact.
        supports_notes: Whether the artifact has a metadata slot for the user's *notes*.
        experimental: Whether constructing this exporter warns that the format is work-in-progress.
        pip_extra: The ``rfdetr[...]`` extra that installs this format's dependencies, or ``None`` when it needs none.
        notes_reason: Which metadata slot the artifact lacks, named in the dropped-``notes`` warning.
        experimental_note: Extra sentence appended to the experimental warning.
        dynamic_batch_reason: Why a fixed-batch format cannot honour ``dynamic_batch``, and what to do instead. Left
            empty by formats that support it. Mirrored by the format's registry entry so the same sentence is reached
            whether the refusal happens before or after the format's module is imported.
    zClassVar[type[ExportConfig]]Úconfig_classzClassVar[Mapping[str, str]]Úsetting_nameszClassVar[str]r0   Ú Údisplay_nameFzClassVar[bool]r3   Úsupports_notesÚexperimentalNzClassVar[str | None]Ú	pip_extraz-this artifact has no ONNX-style metadata slotÚnotes_reasonÚexperimental_noter5   Úsettingsr	   r,   rB   c                óŽ   ‡— ˆfd„t           D ¦   «         }|                      ‰¦  «        }t          d | j        di |¤|¤Ž¦  «        S )aK  Build this format's configuration from :meth:`rfdetr.detr.RFDETR.export`'s flat keyword arguments.

        Settings belonging to other formats are dropped here rather than travelling down into a converter that
        would have to know to ignore them, and a keyword absent from *settings* falls back to the configuration
        dataclass's own default instead of being restated.

        Args:
            **settings: The keyword arguments ``RFDETR.export`` was called with, shared and format-specific alike.

        Returns:
            An instance of :attr:`config_class`.
        c                ó*   •— i | ]}|‰v ¯|‰|         “ŒS r&   r&   )r>   r?   rO   s     €r(   r@   z)Exporter.build_config.<locals>.<dictcomp>Í   s)   ø€ ÐUÐUÐU¨4ÀDÈHÐDTÐDT�$˜ œÐDTÐDTÐDTr'   rB   r&   )r8   Ú_format_settingsr   rF   )ÚclsrO   ÚsharedÚspecifics    `  r(   Úbuild_configzExporter.build_config¿   s[   ø€ ð VÐUÐUÐUµ=ÐUÑUÔUˆØ×'Ò'¨Ñ1Ô1ˆÝ�JÐ 0 Ô 0Ð FÐ F°6Ð F¸XÐ FÐ FÑGÔGÐGr'   úMapping[str, Any]r:   c                óN   ‡— ˆfd„| j                              ¦   «         D ¦   «         S )a²  Pick this format's own settings out of ``RFDETR.export``'s flat keyword arguments.

        The default reads :attr:`setting_names`. Override it only when a format needs to validate or derive a
        setting rather than copy it across.

        Args:
            settings: The keyword arguments ``RFDETR.export`` was called with.

        Returns:
            The format-specific keyword arguments for :attr:`config_class`.
        c                ó0   •— i | ]\  }}|‰v ¯	|‰|         “ŒS r&   r&   )r>   ÚfieldÚkeywordrO   s      €r(   r@   z-Exporter._format_settings.<locals>.<dictcomp>Þ   s0   ø€ ÐpÐpÐp©^¨U°GÐ\cÐgoÐ\oÐ\o��x Ô(Ð\oÐ\oÐ\or'   )rG   Úitems)rS   rO   s    `r(   rR   zExporter._format_settingsÑ   s/   ø€ ð qÐpÐpÐp¸sÔ?P×?VÒ?VÑ?XÔ?XÐpÑpÔpÐpr'   r9   r1   c                ó<   — || _         |                      ¦   «          dS )a  Validate *config* against this format's capabilities and keep it for the conversion.

        Args:
            config: The format's configuration.

        Raises:
            NotImplementedError: If the configuration asks for a capability the format does not have.
            ValueError: If a subclass's :meth:`_check_capabilities` override rejects the configuration for a
                format-specific reason the class attributes alone cannot express (e.g. TensorRT's dynamic-batch
                optimization-profile bounds).
        N)r9   Ú_check_capabilities)Úselfr9   s     r(   Ú__init__zExporter.__init__à   s#   € ð ˆŒØ× Ò Ñ"Ô"Ð"Ð"Ð"r'   c                ó¦  — | j         j        r5| j        s.t          t	          | j        p| j        | j        ¦  «        ¦  «        ‚| j         j        �4| j	        s-t          j        d| j        ›d| j        › d�t          d¬¦  «         | j        rH| j        p| j        }t          j        |› d| j        › �                     ¦   «         t          d¬¦  «         dS dS )uJ  Reject or warn about settings this format cannot honour.

        A subclass override should call ``super()._check_capabilities()`` first, then add its own format-specific
        checks â€” see :class:`~rfdetr.export._tensorrt.exporter.TensorRTExporter` for the one existing example.

        Raises:
            NotImplementedError: If ``dynamic_batch`` was requested and the format bakes a fixed shape.
            ValueError: A subclass override may raise this for its own format-specific validation failures; the
                base implementation never raises it itself.
        Nz#`notes` is not forwarded to format=z (z). This argument is ignored.é   )Ú
stacklevelz. export is experimental and work-in-progress. )r9   r   r3   r4   r/   rI   r0   r5   r    rJ   ÚwarningsÚwarnrM   ÚUserWarningrK   rN   Ústrip)r_   r?   s     r(   r^   zExporter._check_capabilitiesï   s  € ð Œ;Ô$ð 	¨TÔ-Hð 	Ý%Ý& tÔ'8Ð'G¸D¼KÈÔIbÑcÔcñô ð ð Œ;ÔÐ(°Ô1DÐ(ÝŒMØv°d´kÐvÐvÀtÔGXÐvÐvÐvÝØðñ ô ð ð
 Ôð 	ØÔ$Ð3¨¬ˆDÝŒMØÐ_Ð_ÀtÔG]Ð_Ð_×eÒeÑgÔgÝØðñ ô ð ð ð ð	ð 	r'   Úgraphr   r   c                óÊ   — t          |j        ¦  «         t          |                      |¦  «        ¦  «        }t                               d| j        p| j        › d|› �¦  «         |S )zÆExport *graph* and return the path to the artifact.

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

        Returns:
            Path to the exported artifact.
        zSuccessfully exported z model to: )r   Úmodelr   Ú_convertÚloggerÚinforI   r0   )r_   rh   Úpaths      r(   Ú__call__zExporter.__call__  s`   € õ 	˜uœ{Ñ+Ô+Ð+Ý�D—M’M %Ñ(Ô(Ñ)Ô)ˆÝ�ŠÐ`¨TÔ->Ð-MÀ$Ä+Ð`Ð`ÐZ^Ð`Ð`ÑaÔaÐaØˆr'   ú
Path | strc                ó   — dS )zóWrite this format's artifact and return where it landed.

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

        Returns:
            Path to the written artifact, as a :class:`~pathlib.Path` or a string.
        Nr&   )r_   rh   s     r(   rk   zExporter._convert   s   € € € r'   )rO   r	   r,   rB   )rO   rW   r,   r:   )r9   rB   r,   r1   )r,   r1   )rh   r   r,   r   )rh   r   r,   rp   )r!   r"   r#   r$   r   rF   r%   rG   rI   r3   rJ   rK   rL   rM   rN   r5   ÚclassmethodrV   rR   r`   r^   ro   r   rk   r&   r'   r(   rE   rE   ’   s  € € € € € € ðð ð@ 2>€LÐ=Ð=Ð=Ñ=Ø13€MÐ3Ð3Ð3Ñ3ØÐÐÑØ"$€LÐ$Ð$Ð$Ñ$Ø-2ÐÐ2Ð2Ð2Ñ2Ø%*€NÐ*Ð*Ð*Ñ*Ø#(€LÐ(Ð(Ð(Ñ(Ø&*€IÐ*Ð*Ð*Ñ*Ø"Q€LÐQÐQÐQÑQØ')ÐÐ)Ð)Ð)Ñ)Ø*,ÐÐ,Ð,Ð,Ñ,àðHð Hð Hñ „[ðHð" ðqð qð qñ „[ðqð#ð #ð #ð #ðð ð ð ðBð ð ð ð  ðð ð ñ „^ðð ð r'   rE   )r)   r*   r+   r*   r,   r*   )r0   r*   r   r   r,   r1   )r9   r   r,   r:   )%r$   Ú
__future__r   rd   Úabcr   r   Úcollections.abcr   Údataclassesr   Úpathlibr   Útypingr	   r
   r   r   r   r   Úrfdetr.export._backendr   Úrfdetr.export.preparer   Úrfdetr.export.registryr   Úrfdetr.utilities.loggerr   rl   r   r/   r7   r8   r%   rA   rB   rE   r&   r'   r(   ú<module>r}      s  ððð ð ð" #Ð "Ð "Ð "Ð "Ð "à €€€Ø #Ð #Ð #Ð #Ð #Ð #Ð #Ð #Ø #Ð #Ð #Ð #Ð #Ð #Ø !Ð !Ð !Ð !Ð !Ð !Ø Ð Ð Ð Ð Ð Ø ?Ð ?Ð ?Ð ?Ð ?Ð ?Ð ?Ð ?Ð ?Ð ?Ð ?Ð ?Ð ?Ð ?Ð ?Ð ?à 9Ð 9Ð 9Ð 9Ð 9Ð 9Ø -Ð -Ð -Ð -Ð -Ð -Ø 0Ð 0Ð 0Ð 0Ð 0Ð 0Ø .Ð .Ð .Ð .Ð .Ð .à	ˆ‰Œ€ð €�$˜dÐ#Ñ#Ô#ðð ð ð ð ñ ô ñ $Ô#ðð,Nð Nð Nð Nð"_ð _ð _ð _ð>)€ð ð ð ñ ðCð Cð Cð Cð* ˆ7�: \Ð2Ñ2Ô2€ðWð Wð Wð Wð Wˆs�G˜HÔ%ñ Wô Wð Wð Wð Wr'   