§
    ­¸j#â  ã                  óP  — U d Z ddlmZ ddlZddlZddlZddlZddlZddlm	Z	 ddl
mZ ddlmZmZmZ ddlZddlmZ ddlmZ dd	lmZmZ dd
lmZ ddlmZ  e¦   «         Zh d£Zded<   dZ ded<    e!h d£¦  «        Z"ded<   dZ#ded<   d>d„Z$d?d!„Z%d@d"„Z& ej'        ¦   «         Z(ej)        dAd$„¦   «         Z*ej)        dAd%„¦   «         Z+ej)        dBd(„¦   «         Z,e#fdCd.„Z-dDd0„Z.e#fdEd3„Z/dFd5„Z0dGd7„Z1 e	d8d8¬9¦  «         G d:„ d;e¦  «        ¦   «         Z2 G d<„ d=ee2         ¦  «        Z3dS )Hu¿  ONNX â†’ TFLite conversion using the ``onnx2tf`` library.

``onnx2tf`` (PINTO0309) converts an ONNX graph to TFLite.  **Version 2.4.0 or later is required** â€” earlier 1.x releases
cannot lower three op patterns in the RF-DETR graph (constant Expand, 1-D TopK, rank-3 Tile). Although the onnx2tf 2.x
default backend is ``flatbuffer_direct``, RF-DETR unconditionally forces ``tflite_backend="tf_converter"`` to avoid a
runtime error in the TFLite TopK_V2 kernel (``flatbuffer_direct`` trips a "k > internal dimension" check at
``AllocateTensors()`` time).  ``Erf`` and ``GeLU`` activations are replaced with TFLite-native pseudo-operators
(``replace_to_pseudo_operators=["Erf", "GeLU"]``) so the produced model does not require the TensorFlow Flex delegate at
inference time.

GridSample rewrite
------------------
RF-DETR's deformable cross-attention uses :func:`torch.nn.functional.grid_sample` once per decoder layer (6 calls
total).  ``onnx2tf``'s built-in GridSample handler lowers the op to ``tf.gather_nd(batch_dims=1)``, which TFLite's
``GatherNd`` kernel does not support â€” the kernel silently accepts the call during ``AllocateTensors()`` but produces
numerically wrong output at inference time, causing all detection scores to collapse from ~0.6 to ~0.1. The
``replace_to_pseudo_operators=["GridSample"]`` pseudo-op path also produces numerically wrong logit magnitudes in both
FP32 and FP16 (the pseudo-op itself is broken, not a quantization issue).  An earlier ONNX-level rewrite using
``GatherElements(axis=2)`` was lowered to ``tf.gather_nd(batch_dims=2)``, which TFLite does not support and crashes with
index out-of-bounds at inference time.

Before invoking ``onnx2tf``, :func:`_replace_gridsample_for_tflite` rewrites every ``GridSample`` node in the ONNX graph
into an equivalent bilinear sampling subgraph built from ``Gather(axis=0)`` on a transposed and flattened
``(N*(H+2)*(W+2), C)`` image tensor.  ``onnx2tf`` lowers ``Gather(axis=0)`` to TFLite's ``GATHER`` op with no
``batch_dims`` â€” the only TFLite gather path that is unconditionally supported, neither crashing on
``AllocateTensors()`` nor producing wrong values.

Import order
------------
TensorFlow must be imported before ONNX's C extension or the conversion deadlocks, so :class:`TFLiteExporter` calls
:func:`~rfdetr.export._backend.preload_tensorflow_before_onnx` before it touches ONNX â€” see there for why.

The converter uses the ``onnx2tf`` Python API directly (rather than shelling out to the CLI) to:

* Apply a compatibility shim for older ``onnx2tf`` releases that call
  :func:`numpy.load` on pickled data without ``allow_pickle=True``.
* Redirect the legacy ``download_test_image_data()`` validation hook to locally prepared data when an ``onnx2tf``
  version exposes it. Releases 2.4.0â€“2.4.3 do not expose this hook, so the patch is currently inert.
* Put the running interpreter's script directory on ``PATH`` (:func:`_interpreter_scripts_on_path`) so the bare
  ``onnxsim`` console script that ``onnx2tf`` shells out to resolves under a non-activated virtual environment.

INT8 quantization
-----------------
``quantization="int8"`` produces a **dynamic-range** INT8 model (INT8 weights, float activations, roughly 4x smaller
than FP32, no calibration data needed), built from the ``onnx2tf`` SavedModel.

Static (full-integer) INT8 is not supported and raises ``ValueError``: RF-DETR's transformer activations do not survive
8-bit post-training quantization.  Because dynamic-range quantization derives its weight scales from the weights
themselves, *calibration_data* cannot change the INT8 artifact â€” TFLite only consumes representative data through
``representative_dataset``, which this path never sets.

Note:
    The resulting ``.tflite`` model expects the same input normalization as the ONNX model: ImageNet mean/std
    (``mean=[0.485, 0.456, 0.406]``, ``std=[0.229, 0.224, 0.225]``).  The caller is responsible for applying this
    normalization at inference time.

Note:
    Segmentation models additionally emit a ``masks`` output.  FP32, FP16, and dynamic-range INT8 all match the PyTorch
    baseline closely (INT8 mask fidelity is marginally lower).  Verified on the non-plus segmentation
    variants: Nano, Small, Medium, Large, and Preview.

Note:
    Keypoint models additionally emit a rank-4 ``keypoints`` output.  FP32 matches the ONNX model within ``3.2e-3`` on
    every output, verified with a static batch of 1 at 576x576 on ``RFDETRKeypointPreview`` (pretrained, and a
    1-class, 4-keypoint schema).
é    )ÚannotationsN)Ú	dataclass)ÚPath)ÚAnyÚ	GeneratorÚcast)ÚNDArray)Ú_bilinear_resize_half_pixel)ÚExportConfigÚExporter)ÚExportGraph)Ú
get_logger>   NÚfp16Úfp32Úint8zset[str | None]Ú_VALID_QUANTIZATIONSé   ÚintÚ_DEFAULT_CALIB_SAMPLES>   ú.bmpú.jpgú.pngú.jpegú.webpzfrozenset[str]Ú_IMAGE_EXTENSIONSéd   Ú_DEFAULT_DIR_CALIB_SAMPLESÚnoder   ÚgraphÚindexÚreturnÚNonec          
     óÈ  ‡]‡^‡_‡`‡a‡b‡c‡d‡e‡f‡g‡h‡i‡j‡k‡l‡m— ddl Šeddl}ddlŠ`| j        d         }| j        d         }| j        d         }| j                             dd¦  «        }| j                             dd¦  «        }| j                             dd¦  «        }	|dk    s|dk    s|	dk    rt          d	|›d
|›d|	› �¦  «        ‚|j        �t          |j        ¦  «        dk    rt          d|j        › �¦  «        ‚|j        �t          |j        ¦  «        dk    rt          d|j        › �¦  «        ‚d|› �ŠidgŠj‰ej        dfd£ˆ`ˆiˆjfd„Šk‰ej        dfd¤ˆ`ˆeˆiˆjfd„Š_g Šdd¥d¦ˆ`ˆdfd"„Šgt          |j        j        ¦  «        Šat          |j        j        ¦  «        }
 ‰_ ‰ej        d¦  «        ‰ej        d#¦  «        } ‰_ ‰ej        d¦  «        ‰ej        d$¦  «        } ‰_ ‰ej        d%¦  «        ‰ej        d&¦  «        } ‰_ ‰ej        d'¦  «        ‰ej        d(¦  «        Šm ‰_ ‰ej        d)¦  «        ‰ej        d*¦  «        Šf ‰_ ‰ej        d+¦  «        ‰ej        d,¦  «        } ‰_ ‰ej        d-¦  «        ‰ej        d.¦  «        } ‰_dg‰ej        d/¦  «        Š] ‰_d0g‰ej        d1¦  «        } ‰_d2g‰ej        d3¦  «        Šc ‰kd4‰ej        dg¬5¦  «        } ‰gd6|g|g¦  «          ‰kd7‰ej        dg¬5¦  «        } ‰gd6|g|g¦  «         d§ˆ_ˆeˆgˆkfd;„} ||dd<¦  «        } ||dd=¦  «        } ||d%d>¦  «        } ||d0d?¦  «        } ||dd@¦  «        } ||d%dA¦  «        } ‰kdB‰ej        ¬C¦  «        } ‰gdD||g|g¦  «          ‰kdE‰ej        ¬C¦  «        Šh ‰gdD||g‰hg¦  «          ‰kdF‰ej        ¬C¦  «        } ‰gdG|‰hg|g¦  «          ‰kdH‰ej        ¬C¦  «        } ‰gdG||g|g¦  «          ‰kdI‰ej        ¬C¦  «        } ‰gdJ|g|gdK|
i¦  «          ‰kdL‰ej        ¬C¦  «        } ‰gdJ|g|gdK|
i¦  «          ‰kdM‰ej        ¬C¦  «        } ‰gdJ‰hg|gdK|
i¦  «          ‰kdN‰ej        ¬C¦  «        }  ‰gdJ|g| gdK|
i¦  «          ‰kdO‰ej        ¬C¦  «        }! ‰gdP||g|!g¦  «          ‰kdQ‰ej        ¬C¦  «        }" ‰gdP||g|"g¦  «          ‰kdR‰ej        ¬C¦  «        }# ‰gdS|‰fg|#g¦  «          ‰kdT‰ej        ¬C¦  «        }$ ‰gdS| ‰fg|$g¦  «         d¨ˆ]ˆeˆgˆkfdV„}% |%|dW¦  «        }& |%|dX¦  «        }' |%|dY¦  «        }( |%|dZ¦  «        }) |%|d[¦  «        }* ‰kd\‰ej        d%g¬5¦  «        }+ ‰gd]|*|'g|+gd^di¦  «          ‰kd_‰ej        dg¬5¦  «        }, ‰gd]|&|(|)|'g|,gd^di¦  «          ‰_g d`¢‰ej        da¦  «        }- ‰kdb¦  «        }. ‰gdc||-g|.g¦  «          ‰kdd¦  «        }/ ‰gde|.g|/gdfg dg¢i¦  «          ‰kdh¦  «        Šb ‰gdi|/|+g‰bg¦  «          ‰kdj¦  «        }0 ‰gdk| ‰_dg‰ej        dl¦  «         ‰_dg‰ej        dm¦  «        |g|0g¦  «          ‰kdn¦  «        }1 ‰gdo|0|g|1g¦  «          ‰kdp¦  «        }2 ‰gdk| ‰_dg‰ej        dq¦  «         ‰_d%g‰ej        dr¦  «        |g|2g¦  «          ‰kds¦  «        }3 ‰gdo|2|g|3g¦  «          ‰kdt¦  «        }4 ‰gdD|1‰fg|4g¦  «          ‰kdu¦  «        }5 ‰gdG|4|!g|5g¦  «          ‰kdv¦  «        }6 ‰gdS|5|g|6g¦  «          ‰kdw¦  «        }7 ‰gdD|3‰fg|7g¦  «          ‰kdx¦  «        }8 ‰gdG|7|"g|8g¦  «          ‰kdy¦  «        }9 ‰gdS|8|g|9g¦  «          ‰kdz¦  «        }: ‰gd{|6g|:g¦  «          ‰kd|¦  «        }; ‰gd{|9g|;g¦  «          ‰kd}¦  «        }< ‰gdD|:‰fg|<g¦  «          ‰kd~¦  «        }= ‰gdD|;‰fg|=g¦  «          ‰kd¦  «        }> ‰gdS|6|:g|>g¦  «          ‰kd€¦  «        }? ‰gdS|9|;g|?g¦  «          ‰kd�¦  «        }@ ‰gdS‰f|>g|@g¦  «          ‰kd‚¦  «        }A ‰gdS‰f|?g|Ag¦  «         d©ˆaˆeˆfˆgˆkˆmfd…„}B |B|:|#d†¦  «        }C |B|<|#d‡¦  «        }D |B|;|$dˆ¦  «        }E |B|=|$d‰¦  «        }F ‰kdŠ‰ej        ¬C¦  «        }G ‰gd‹|||g|Gg¦  «          ‰kdŒ‰ej        ¬C¦  «        }H ‰gdG|G|g|Hg¦  «          ‰_g d�¢‰ej        dŽ¦  «        }I ‰kd�‰ej        ¬C¦  «        Š^ ‰gdi|H|Ig‰^g¦  «         dªˆ^ˆcˆeˆgˆhˆkfd’„}J |J|C|Ed“¦  «        }K |J|D|Ed”¦  «        }L |J|C|Fd•¦  «        }M |J|D|Fd–¦  «        }Nd«ˆbˆgˆkfd˜„}O |O|Kd“¦  «        }P |O|Ld”¦  «        }Q |O|Md•¦  «        }R |O|Nd–¦  «        }S ‰_d2dg‰ej        d™¦  «        Šld¬ˆgˆkˆlfd�„}T |T|P|@|Ad“¦  «        }U |T|Q|>|Ad”¦  «        }V |T|R|@|?d•¦  «        }W |T|S|>|?d–¦  «        }X ‰kdž¦  «        }Y ‰gdD|U|Vg|Yg¦  «          ‰kdŸ¦  «        }Z ‰gdD|Y|Wg|Zg¦  «          ‰kd ¦  «        }[ ‰gdD|Z|Xg|[g¦  «          ‰kd¡¦  «        }\ ‰gdi|[|,g|\g¦  «          ‰gde|\g|gdfg d¢¢i¦  «         | j                             ¦   «          | j                             ¦   «          |j                             ‰d¦  «         dS )­u”  Rewrite one GridSample ONNX node into a TFLite-safe bilinear subgraph.

    Replaces ``GridSample(im, grid)`` with an equivalent bilinear sampling subgraph that performs four
    ``Gather(axis=0)`` lookups on a transposed and flattened ``(N*(H+2)*(W+2), C)`` image tensor.  ``onnx2tf`` lowers
    ``Gather(axis=0)`` to TFLite's ``GATHER`` op with no ``batch_dims`` â€” the only TFLite gather path that is
    unconditionally supported, neither crashing on ``AllocateTensors()`` nor producing wrong values. Per-sample batch
    offsets are added to the flat index so that a single rank-1 ``Gather`` covers the entire batch.

    The replacement is mathematically identical to PyTorch's ``F.grid_sample`` for ``mode="bilinear"``,
    ``padding_mode="zeros"``, ``align_corners=0``.  Out-of-bounds sample positions are clamped to the zero-padded
    border, which has the same effect as PyTorch's zero padding.

    Shape-dependent values are computed at runtime via ONNX Shape/Gather/ Concat/Cast ops so the subgraph works for any
    static or dynamic input shape.

    Args:
        node: The ``gs.Node`` to replace (must be a ``GridSample`` node).
        graph: The ``gs.Graph`` that owns *node*.
        index: Unique integer suffix used to namespace tensor/constant names.

    Raises:
        NotImplementedError: If the node has unsupported attributes.
        ValueError: If ``im`` or ``grid`` are not rank-4 tensors.
    r   Né   ÚmodeÚbilinearÚpadding_modeÚzerosÚalign_cornerszgGridSample TFLite patch only supports mode='bilinear', padding_mode='zeros', align_corners=0; got mode=z, padding_mode=z, align_corners=é   z9GridSample TFLite patch requires rank-4 im; got im.shape=z=GridSample TFLite patch requires rank-4 grid; got grid.shape=Ú_gsreplÚnameÚstrÚdtyper   Úshapeúlist[int] | Noner!   c                óp   •— ‰dxx         dz  cc<   ‰                      ‰› d‰d         › d| › �||¬¦  «        S )Nr   r$   Ú_©r.   r/   )ÚVariable)r,   r.   r/   ÚgsÚpfxÚuids      €€€ún/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/rfdetr/export/_tflite/exporter.pyÚvz%_replace_single_gridsample.<locals>.vŸ   sJ   ø€ ØˆAˆˆŒ�!‰ˆˆ‰Ø�{Š{˜cÐ3Ð3 C¨¤FÐ3Ð3¨TÐ3Ð3¸5Èˆ{ÑNÔNÐNó    Ú Úvalc                óŒ   •— ‰dxx         dz  cc<   ‰                      ‰› d‰d         › d|› � ‰j        | |¬¦  «        ¦  «        S )Nr   r$   r2   Ú_c_©r.   )ÚConstantÚarray)r<   r.   r,   r5   Únpr6   r7   s      €€€€r8   Úcz%_replace_single_gridsample.<locals>.c£   sW   ø€ ØˆAˆˆŒ�!‰ˆˆ‰Ø�{Š{˜cÐ5Ð5 C¨¤FÐ5Ð5¨tÐ5Ð5°x°r´xÀÈ5Ð7QÑ7QÔ7QÑRÔRÐRr:   ÚkindÚinsú	list[Any]ÚoutsÚattrsúdict[str, Any] | Noner"   c                ód   •— ‰                      ‰                     | |||pi ¬¦  «        ¦  «         d S )N)ÚopÚinputsÚoutputsrH   )ÚappendÚNode)rD   rE   rG   rH   r5   Únodess       €€r8   rK   z&_replace_single_gridsample.<locals>.op©   s3   ø€ Ø�Š�R—W’W ¨S¸$ÀeÀkÈr�WÑRÔRÑSÔSÐSÐSÐSr:   Úzero_iÚone_ié   Útwo_ig        Úzero_fg      ð?Úone_fg       @Útwo_fg      à?Úhalf_fÚax0_1dé   Úax3_1déÿÿÿÿÚneg1_1dÚim_shaper3   ÚShapeÚ
grid_shapeÚshape_tÚaxis_idxr   c                óš   •—  ‰|‰j         ¬¦  «        } ‰d|  ‰ ‰j         |¦  «        ‰j         d|› d|› �¦  «        g|gddi¦  «         |S )Nr?   ÚGatherÚir2   Úaxisr   ©Úint64)ra   rb   r,   ÚresultrC   rB   rK   r9   s       €€€€r8   Ú
gather_dimz._replace_single_gridsample.<locals>.gather_dimÅ   sq   ø€ Ø��4˜rœxÐ(Ñ(Ô(ˆØ
ˆˆ8�g˜q˜q  ¤¨(Ñ!3Ô!3°R´XÐ?TÀ8Ð?TÐ?TÈdÐ?TÐ?TÑUÔUÐVÐY_ÐX`ÐciÐklÐbmÑnÔnÐnØˆr:   ÚNÚCÚHÚWÚH_outÚW_outÚpHr?   ÚAddÚpWÚpH_pWÚMulÚN_pH_pWÚW_fÚCastÚtoÚH_fÚpW_fÚpH_fÚW_halfÚDivÚH_halfÚpW_max_fÚSubÚpH_max_fÚscalar_tc                óP   •—  ‰|‰j         dg¬¦  «        } ‰d| ‰g|g¦  «         |S )z@Promote a 0-D int64 scalar to a 1-D [1] int64 vector for Concat.r$   r3   Ú	Unsqueezerg   )rƒ   r,   ri   rY   rB   rK   r9   s      €€€€r8   Úunsq0z)_replace_single_gridsample.<locals>.unsq0õ   s=   ø€ à��4˜rœx°¨sÐ3Ñ3Ô3ˆØ
ˆˆ;˜ 6Ð*¨V¨HÑ5Ô5Ð5Øˆr:   ÚN_1dÚC_1dÚH_out_1dÚW_out_1dÚ
N_pH_pW_1dÚ
flat_shapeÚConcatrf   Ú
nhwc_shape)r   r   r$   r$   r   r   r$   r$   ÚpadsÚim_padÚPadÚim_nhwcÚ	TransposeÚperm)r   rS   rZ   r$   Úim_flatÚReshapeÚgx_rawÚSliceÚs0_gxÚe1_gxÚgxÚSqueezeÚgy_rawÚs1_gyÚe2_gyÚgyÚgxp1ÚpxrÚpxÚgyp1ÚpyrÚpyÚx0_fÚFloorÚy0_fÚx1_fÚy1_fÚwx1Úwy1Úwx0Úwy0Úcoord_fÚ	clamp_maxc                óÐ   •—  ‰
d|› �¦  «        } ‰	d| ‰g|g¦  «          ‰
d|› �¦  «        } ‰	d|‰|g|g¦  «          ‰
d|› �‰j         ¬¦  «        } ‰	d|g|gd‰i¦  «         |S )	NÚsh_rr   Úcl_ÚClipÚca_r?   rx   ry   rg   )r°   r±   r,   ÚshiftedÚclippedÚcast_intÚi64rB   rV   rK   r9   rU   s         €€€€€€r8   Úint_shifted_clampedz7_replace_single_gridsample.<locals>.int_shifted_clampedE  s    ø€ Ø�!�L˜$�L�L‘/”/ˆØ
ˆˆ5�7˜EÐ" W IÑ.Ô.Ð.Ø�!�L˜$�L�L‘/”/ˆØ
ˆˆ6�G˜V YÐ/°'°Ñ;Ô;Ð;Ø�1�\˜4�\�\¨¬Ð2Ñ2Ô2ˆØ
ˆˆ6�G�9˜x˜j¨4°¨+Ñ6Ô6Ð6Øˆr:   Úx0cÚx1cÚy0cÚy1cÚbatch_rangeÚRangeÚbatch_offset_flat)r\   r$   r$   Úbatch_offset_shapeÚbatch_offsetÚxcÚycc                ó0  •—  ‰d|› �‰	j         ¬¦  «        } ‰
d|‰g|g¦  «          ‰d|› �‰	j         ¬¦  «        } ‰
d|| g|g¦  «          ‰d|› �‰	j         ¬¦  «        } ‰
d|‰g|g¦  «          ‰d|› �‰	j         ¬¦  «        } ‰
d|‰g|g¦  «         |S )	NÚypw_r?   ru   Úlocal_rr   Úglob_Úgidx_r–   rg   )rÅ   rÆ   r,   ÚypwÚlocalÚ
global_idxÚflat1drÄ   r]   rB   rK   ÚpW_tr9   s          €€€€€€r8   Úflat_global_indexz5_replace_single_gridsample.<locals>.flat_global_indexb  sâ   ø€ Øˆa��t�� R¤XÐ.Ñ.Ô.ˆØ
ˆˆ5�2�t�*˜s˜eÑ$Ô$Ð$Ø��/˜4�/�/¨¬Ð2Ñ2Ô2ˆØ
ˆˆ5�3˜�)˜e˜WÑ%Ô%Ð%Ø�Q�~˜t�~�~¨R¬XÐ6Ñ6Ô6ˆ
Ø
ˆˆ5�5˜,Ð'¨*¨Ñ6Ô6Ð6Ø��>˜4�>�>¨¬Ð2Ñ2Ô2ˆØ
ˆˆ9�z 7Ð+¨f¨XÑ6Ô6Ð6Øˆr:   ÚaaÚbaÚabÚbbÚgidxc                óJ   •—  ‰d|› �¦  «        } ‰d‰| g|gddi¦  «         |S )NÚsamp_rd   rf   r   © )rÖ   r,   Úsampledr•   rK   r9   s      €€€r8   Úgather_flatz/_replace_single_gridsample.<locals>.gather_flatt  s=   ø€ Ø�!�N˜D�N�NÑ#Ô#ˆØ
ˆˆ8�g˜t�_ w i°&¸!°Ñ=Ô=Ð=Øˆr:   Úwflat_shapeÚgatheredÚwxÚwyc                ó¼   •—  ‰d|› �¦  «        } ‰d||g|g¦  «          ‰d|› �¦  «        } ‰d|‰	g|g¦  «          ‰d|› �¦  «        } ‰d| |g|g¦  «         |S )NÚw2d_ru   Úwflat_r–   Úc_rÙ   )
rÝ   rÞ   rß   r,   Úw_2dÚw_flatÚout_contribrK   r9   rÜ   s
          €€€r8   Úcontribz+_replace_single_gridsample.<locals>.contrib‚  s–   ø€ Øˆq�˜��ÑÔˆØ
ˆˆ5�2�r�(˜T˜FÑ#Ô#Ð#Ø��?˜D�?�?Ñ#Ô#ˆØ
ˆˆ9�t˜[Ð)¨F¨8Ñ4Ô4Ð4Ø�a˜˜T˜˜‘n”nˆØ
ˆˆ5�8˜VÐ$ { mÑ4Ô4Ð4ØÐr:   Ús1Ús2ÚtotalÚ
total_nhwc)r   rZ   r$   rS   )r,   r-   r.   r   r/   r0   r!   r   )r<   r   r.   r   r,   r-   r!   r   ©N)
rD   r-   rE   rF   rG   rF   rH   rI   r!   r"   )ra   r   rb   r   r,   r-   r!   r   )rƒ   r   r,   r-   r!   r   )r°   r   r±   r   r,   r-   r!   r   )rÅ   r   rÆ   r   r,   r-   r!   r   )rÖ   r   r,   r-   r!   r   )
rÝ   r   rÞ   r   rß   r   r,   r-   r!   r   )ÚnumpyÚonnxÚonnx_graphsurgeonrL   rM   rH   ÚgetÚNotImplementedErrorr/   ÚlenÚ
ValueErrorÚfloat32r   ÚTensorProtoÚINT64ÚFLOATrh   ÚclearrP   Úextend)nr   r   r    rî   ÚimÚgridÚoutr%   r'   r)   Úf32rQ   rR   rT   rW   rX   r[   Ú
im_shape_tÚgrid_shape_trj   ÚN_tÚC_tÚH_tÚW_tÚH_out_tÚW_out_tÚpH_tÚpH_pW_tÚ	N_pH_pW_trw   rz   r{   r|   r}   r   r€   r‚   r†   r‡   rˆ   r‰   rŠ   r‹   Úflat_shape_tÚnhwc_shape_tr�   r�   r’   r—   r›   r�   r    r¡   r¢   r£   r¤   r¥   r¦   r§   r©   rª   r«   r¬   r­   r®   r¯   r»   r¼   r½   r¾   r¿   rÀ   rÂ   rÃ   rÑ   Úgidx_aaÚgidx_baÚgidx_abÚgidx_bbrÛ   ÚsaaÚsbaÚsabÚsbbrç   ÚcaaÚcbaÚcabÚcbbrè   ré   rê   rë   rY   rÄ   rC   r5   rº   r•   r]   rP   rB   rV   rK   rÐ   r6   r7   r9   rÜ   rU   sn                                                                                                @@@@@@@@@@@@@@@@@r8   Ú_replace_single_gridsampler  k   sh  øøøøøøøøøøøøøøøøø€ ð2 ÐÐÐØ€K€K€KØ"Ð"Ð"Ð"à	Œ�QŒ€BØŒ;�qŒ>€DØ
Œ,�qŒ/€CàŒ:�>Š>˜& *Ñ-Ô-€DØ”:—>’> .°'Ñ:Ô:€LØ”J—N’N ?°AÑ6Ô6€MàˆzÒÐ˜\¨WÒ4Ð4¸ÈÒ8JÐ8JÝ!ð_àð_ð _à/;ð_ð _àO\ð_ð _ñ
ô 
ð 	
ð 
„xÐ�3˜rœx™=œ=¨AÒ-Ð-ÝÐ_ÐUWÔU]Ð_Ð_Ñ`Ô`Ð`Ø„zÐ�S ¤™_œ_°Ò1Ð1ÝÐeÐY]ÔYcÐeÐeÑfÔfÐfà
�EÐ
Ð
€CØ�S€Cà"$¤*Èð Oð Oð Oð Oð Oð Oð Oð Oð Oð "$¤¸ð Sð Sð Sð Sð Sð Sð Sð Sð Sð Sð €EðTð Tð Tð Tð Tð Tð Tð Tõ ˆdÔÔ$Ñ
%Ô
%€CÝ
ˆdÔÔ$Ñ
%Ô
%€Cð ˆQˆxˆrŒx˜‰{Œ{˜BœH hÑ/Ô/€FØˆAˆhˆbŒh�q‰kŒk˜2œ8 WÑ-Ô-€EØˆAˆhˆbŒh�q‰kŒk˜2œ8 WÑ-Ô-€EàˆQˆzˆrŒz˜#‰Œ ¤
¨HÑ5Ô5€FØˆAˆjˆbŒj˜‰oŒo˜rœz¨7Ñ3Ô3€EØˆAˆjˆbŒj˜‰oŒo˜rœz¨7Ñ3Ô3€EØˆQˆzˆrŒz˜#‰Œ ¤
¨HÑ5Ô5€FàˆQ�ˆs�B”H˜hÑ'Ô'€FØˆQ�ˆs�B”H˜hÑ'Ô'€FØˆa���b”h 	Ñ*Ô*€Gð
 ��: R¤X°a°SÐ9Ñ9Ô9€JØ€B€w���z�lÑ#Ô#Ð#Ø�1�\¨¬¸!¸Ð=Ñ=Ô=€LØ€B€w��˜˜Ñ'Ô'Ð'ðð ð ð ð ð ð ð ð ð ˆ*�Z  CÑ
(Ô
(€CØ
ˆ*�Z  CÑ
(Ô
(€CØ
ˆ*�Z  CÑ
(Ô
(€CØ
ˆ*�Z  CÑ
(Ô
(€CØˆj˜ q¨'Ñ2Ô2€GØˆj˜ q¨'Ñ2Ô2€Gð ˆ1ˆT˜œÐ"Ñ"Ô"€DØ€B€uˆs�Eˆl˜T˜FÑ#Ô#Ð#Øˆ1ˆT˜œÐ"Ñ"Ô"€DØ€B€uˆs�Eˆl˜T˜FÑ#Ô#Ð#Øˆa�˜rœxÐ(Ñ(Ô(€GØ€B€uˆt�Tˆl˜W˜IÑ&Ô&Ð&ð ��) 2¤8Ð,Ñ,Ô,€IØ€B€uˆs�Gˆn˜y˜kÑ*Ô*Ð*ð ˆ!ˆE˜œÐ
$Ñ
$Ô
$€CØ€B€v�ˆu�s�e˜d C˜[Ñ)Ô)Ð)Ø
ˆ!ˆE˜œÐ
$Ñ
$Ô
$€CØ€B€v�ˆu�s�e˜d C˜[Ñ)Ô)Ð)Øˆ1ˆV˜2œ:Ð&Ñ&Ô&€DØ€B€v�ˆv˜�v  c˜{Ñ+Ô+Ð+Øˆ1ˆV˜2œ:Ð&Ñ&Ô&€DØ€B€v�ˆv˜�v  c˜{Ñ+Ô+Ð+àˆQˆx˜rœzÐ*Ñ*Ô*€FØ€B€uˆs�Eˆl˜V˜HÑ%Ô%Ð%ØˆQˆx˜rœzÐ*Ñ*Ô*€FØ€B€uˆs�Eˆl˜V˜HÑ%Ô%Ð%àˆq� 2¤:Ð.Ñ.Ô.€HØ€B€uˆt�Uˆm˜h˜ZÑ(Ô(Ð(Øˆq� 2¤:Ð.Ñ.Ô.€HØ€B€uˆt�Uˆm˜h˜ZÑ(Ô(Ð(ðð ð ð ð ð ð ð ð ð ˆ5��fÑÔ€DØˆ5��fÑÔ€DØˆu�W˜jÑ)Ô)€HØˆu�W˜jÑ)Ô)€HØ��y ,Ñ/Ô/€Jð �1�\¨¬¸!¸Ð=Ñ=Ô=€LØ€B€x�*˜dÐ# l ^°f¸a°[ÑAÔAÐAð �1�\¨¬¸!¸Ð=Ñ=Ô=€LØ€B€x�$˜ (¨DÐ1°L°>ÀFÈAÀ;ÑOÔOÐOð ˆ1Ð%Ð%Ð% r¤x°Ñ8Ô8€DØˆQˆx‰[Œ[€FØ€B€uˆr�4ˆj˜6˜(Ñ#Ô#Ð#Øˆa�	‰lŒl€GØ€B€{�V�H˜w˜i¨&°,°,°,Ð)?Ñ@Ô@Ð@Øˆa�	‰lŒl€GØ€B€y�7˜LÐ)¨G¨9Ñ5Ô5Ð5ð ˆQˆx‰[Œ[€FØ€B€w��q�q˜!˜˜bœh¨Ñ0Ô0°!°!°Q°C¸¼À7Ñ2KÔ2KÈVÐTÐW]ÐV^Ñ_Ô_Ð_Ø	
ˆˆ4‰Œ€BØ€B€y�6˜6Ð" R DÑ)Ô)Ð)àˆQˆx‰[Œ[€FØ€B€w��q�q˜!˜˜bœh¨Ñ0Ô0°!°!°Q°C¸¼À7Ñ2KÔ2KÈVÐTÐW]ÐV^Ñ_Ô_Ð_Ø	
ˆˆ4‰Œ€BØ€B€y�6˜6Ð" R DÑ)Ô)Ð)ð ˆ1ˆV‰9Œ9€DØ€B€uˆr�5ˆk˜D˜6Ñ"Ô"Ð"Ø
ˆ!ˆE‰(Œ(€CØ€B€uˆt�Vˆn˜s˜eÑ$Ô$Ð$Ø	
ˆˆ4‰Œ€BØ€B€uˆs�Fˆm˜b˜TÑ"Ô"Ð"àˆ1ˆV‰9Œ9€DØ€B€uˆr�5ˆk˜D˜6Ñ"Ô"Ð"Ø
ˆ!ˆE‰(Œ(€CØ€B€uˆt�Vˆn˜s˜eÑ$Ô$Ð$Ø	
ˆˆ4‰Œ€BØ€B€uˆs�Fˆm˜b˜TÑ"Ô"Ð"ð ˆ1ˆV‰9Œ9€DØ€B€w���t�fÑÔÐØˆ1ˆV‰9Œ9€DØ€B€w���t�fÑÔÐØˆ1ˆV‰9Œ9€DØ€B€uˆt�Uˆm˜d˜VÑ$Ô$Ð$Øˆ1ˆV‰9Œ9€DØ€B€uˆt�Uˆm˜d˜VÑ$Ô$Ð$à
ˆ!ˆE‰(Œ(€CØ€B€uˆr�4ˆj˜3˜%Ñ Ô Ð Ø
ˆ!ˆE‰(Œ(€CØ€B€uˆr�4ˆj˜3˜%Ñ Ô Ð Ø
ˆ!ˆE‰(Œ(€CØ€B€uˆu�cˆl˜S˜EÑ"Ô"Ð"Ø
ˆ!ˆE‰(Œ(€CØ€B€uˆu�cˆl˜S˜EÑ"Ô"Ð"ðð ð ð ð ð ð ð ð ð ð ð Ð
˜d H¨eÑ
4Ô
4€CØ
Ð
˜d H¨eÑ
4Ô
4€CØ
Ð
˜d H¨eÑ
4Ô
4€CØ
Ð
˜d H¨eÑ
4Ô
4€Cð
 �!�M¨¬Ð2Ñ2Ô2€KØ€B€w�˜˜eÐ$ { mÑ4Ô4Ð4Ø˜Ð-°R´XÐ>Ñ>Ô>ÐØ€B€uˆ{˜GÐ$Ð'8Ð&9Ñ:Ô:Ð:Ø˜˜:˜:˜: r¤xÐ1EÑFÔFÐØ�1�^¨2¬8Ð4Ñ4Ô4€LØ€B€yÐ$Ð&8Ð9¸L¸>ÑJÔJÐJð	ð 	ð 	ð 	ð 	ð 	ð 	ð 	ð 	ð 	ð 	ð  Ð  S¨$Ñ/Ô/€GØÐ  S¨$Ñ/Ô/€GØÐ  S¨$Ñ/Ô/€GØÐ  S¨$Ñ/Ô/€Gðð ð ð ð ð ð ð ð
 ˆ+�g˜tÑ
$Ô
$€CØ
ˆ+�g˜tÑ
$Ô
$€CØ
ˆ+�g˜tÑ
$Ô
$€CØ
ˆ+�g˜tÑ
$Ô
$€Cð �!�R˜�G˜RœX }Ñ5Ô5€Kðð ð ð ð ð ð ð ð ˆ'�#�s˜C Ñ
&Ô
&€CØ
ˆ'�#�s˜C Ñ
&Ô
&€CØ
ˆ'�#�s˜C Ñ
&Ô
&€CØ
ˆ'�#�s˜C Ñ
&Ô
&€Cà	
ˆˆ4‰Œ€BØ€B€uˆs�Cˆj˜2˜$ÑÔÐØ	
ˆˆ4‰Œ€BØ€B€uˆr�3ˆi˜"˜ÑÔÐØˆAˆg‰JŒJ€EØ€B€uˆr�3ˆi˜%˜Ñ!Ô!Ð!ð ��<‘”€JØ€B€y�5˜,Ð'¨*¨Ñ6Ô6Ð6Ø€B€{�Z�L 3 %¨&°,°,°,Ð)?Ñ@Ô@Ð@ð 	„K×ÒÑÔÐØ„L×ÒÑÔÐØ	„K×Ò�uÑÔÐÐÐr:   Ú	onnx_pathr   Ú
output_dirc                óÂ  — 	 ddl }ddl}ddl}n"# t          $ r}t          d¦  «        |‚d}~ww xY w|                     t          | ¦  «        ¦  «        }|j                             |¦  «        }|                     |¦  «        }d„ |j	        D ¦   «         }|st                               d¦  «         | S t                               dt          |¦  «        ¦  «         t          |¦  «        D ]\  }}	t          |	||¬¦  «         Œ|                     ¦   «                              ¦   «          	 |j                             |                     |¦  «        ¦  «        }
|j                             |
¦  «         n%# t*          $ r}t-          d|› �¦  «        |‚d}~ww xY w|| j        d	z   z  }|                     |
t          |¦  «        ¦  «         t                               d
|¦  «         |S )uÂ  Rewrite every GridSample node in *onnx_path* to use TFLite-safe ops.

    ``onnx2tf``'s built-in GridSample handler lowers to ``tf.gather_nd(batch_dims=1)``, which TFLite's ``GatherNd``
    kernel does not support â€” the kernel silently accepts the model during ``AllocateTensors()`` but produces
    numerically wrong output at inference time.  The ``replace_to_pseudo_operators=["GridSample"]`` pseudo-op path also
    produces wrong logit magnitudes in both FP32 and FP16 (the pseudo-op itself is broken, independent of quantization).
    This function rewrites the ONNX graph *before* calling ``onnx2tf.convert()``, replacing each ``GridSample`` node
    with an equivalent bilinear subgraph that performs four ``Gather(axis=0)`` lookups on a transposed and flattened
    ``(N*(H+2)*(W+2), C)`` image tensor.  ``onnx2tf`` lowers ``Gather(axis=0)`` to TFLite's ``GATHER`` op with no
    ``batch_dims`` â€” the only TFLite gather path that is unconditionally supported.

    Only ``mode="bilinear"``, ``padding_mode="zeros"``, ``align_corners=0`` nodes are patched â€” the only variant emitted
    by RF-DETR's exporter.

    Args:
        onnx_path: Path to the source ``.onnx`` file.
        output_dir: Directory where the patched ``.onnx`` is written.  Must
            already exist.

    Returns:
        Path to the patched ``.onnx`` file if any ``GridSample`` nodes were found; *onnx_path* unchanged if the graph
        contains no such nodes.

    Raises:
        ImportError: If ``onnx`` or ``onnx_graphsurgeon`` are not available.
        NotImplementedError: If a ``GridSample`` node has unsupported attrs.
        RuntimeError: If the patched graph fails ONNX shape-inference or
            model validation.
    r   Nzronnx and onnx_graphsurgeon are required for the GridSample TFLite patch.  Install with: pip install rfdetr[tflite]c                ó(   — g | ]}|j         d k    ¯|‘ŒS )Ú
GridSample)rK   )Ú.0Úns     r8   ú
<listcomp>z2_replace_gridsample_for_tflite.<locals>.<listcomp>Î  s$   € Ð?Ð?Ð?�a¨!¬$°,Ò*>Ð*>�Ð*>Ð*>Ð*>r:   z6No GridSample nodes found; skipping TFLite-safe patch.uG   Patching %d GridSample node(s) â†’ TFLite-safe Gather(axis=0) subgraph.)r    z1GridSample ONNX patch produced an invalid graph: z_gs_patched.onnxz$GridSample-patched ONNX saved to: %s)rî   Úonnx.shape_inferencerï   ÚImportErrorÚloadr-   Úshape_inferenceÚinfer_shapesÚimport_onnxrP   ÚloggerÚdebugÚinforò   Ú	enumerater  ÚcleanupÚtoposortÚexport_onnxÚcheckerÚcheck_modelÚ	ExceptionÚRuntimeErrorÚstemÚsave)r  r  rî   r5   ÚexcÚmodelr   Úgs_nodesre   r   ÚpatchedÚout_paths               r8   Ú_replace_gridsample_for_tfliter8  ¢  s  € ð<ØˆˆˆØ#Ð#Ð#Ð#Ø&Ð&Ð&Ð&Ð&øÝð ð ð Ýð?ñ
ô 
ð ð	øøøøðøøøð �IŠI•c˜)‘n”nÑ%Ô%€EØÔ ×-Ò-¨eÑ4Ô4€EØ�NŠN˜5Ñ!Ô!€Eà?Ð?˜5œ;Ð?Ñ?Ô?€HØð Ý�ŠÐMÑNÔNÐNØÐå
‡K‚KØQÝˆH‰Œñô ð õ ˜XÑ&Ô&ð 9ð 9‰ˆˆ4Ý" 4¨°aÐ8Ñ8Ô8Ð8Ð8à	‡M‚M�O„O×ÒÑÔÐð_ØÔ&×3Ò3°B·N²NÀ5Ñ4IÔ4IÑJÔJˆØŒ× Ò  Ñ)Ô)Ð)Ð)øÝð _ð _ð _ÝÐTÈsÐTÐTÑUÔUÐ[^Ð^øøøøð_øøøð ˜Yœ^Ð.@Ñ@ÑA€HØ‡I‚Iˆg•s˜8‘}”}Ñ%Ô%Ð%Ý
‡L‚LÐ7¸ÑBÔBÐBØ€Os)   ‚ �
.™)©.Ä'AE/ Å/
FÅ9FÆFc                 ó<  — 	 ddl } n"# t          $ r}t          d¦  «        |‚d}~ww xY wddlm} ddlm} ddl }ddlm} 	  |d¦  «        }n!# |$ r t          |dd¦  «        }|€Y dS Y nw xY w|€J ‚ ||¦  «         |d	¦  «        k     rt          d
|› d�¦  «        ‚dS )uI  Verify that a compatible ``onnx2tf`` package is importable.

    onnx2tf 2.4.0 or later is required â€” earlier 1.x releases cannot lower the constant ``Expand``, 1-D ``TopK``, and
    rank-3 ``Tile`` ops present in RF-DETR's ONNX graph.

    Raises:
        ImportError: If ``onnx2tf`` cannot be imported or is below 2.4.0.
    r   Nznonnx2tf is not installed. TFLite export requires the tflite extra. Install it with: pip install rfdetr[tflite])ÚPackageNotFoundError)Úversion)ÚVersionÚonnx2tfÚ__version__z2.4.0zonnx2tf z± is installed but RF-DETR requires >= 2.4.0. Earlier 1.x releases cannot lower the Expand, TopK, and Tile ops in RF-DETR's ONNX graph. Upgrade with: pip install 'onnx2tf>=2.4.0')r=  r!  Úimportlib.metadatar:  r;  Úpackaging.versionr<  Úgetattr)r=  r3  Ú_PkgNotFoundÚ_pkg_versionÚ_onnx2tf_modÚ_VersionÚ	installeds          r8   Ú_check_onnx2tf_availablerG  è  sL  € ðØˆˆˆˆøÝð ð ð Ýð:ñ
ô 
ð ð	øøøøðøøøð HÐGÐGÐGÐGÐGØ:Ð:Ð:Ð:Ð:Ð:à"Ð"Ð"Ð"Ø5Ð5Ð5Ð5Ð5Ð5ðØ , ¨YÑ 7Ô 7ˆ	ˆ	øØð ð ð õ ˜L¨-¸Ñ>Ô>ˆ	ØÐØˆFˆFð Ððøøøð Ð Ð Ð Ø€x�	ÑÔ˜X˜X gÑ.Ô.Ò.Ð.ÝðR�yð Rð Rð Rñ
ô 
ð 	
ð /Ð.s"   ‚ ‡
&‘!¡&Á A ÁA*Á)A*úGenerator[None, None, None]c               #  óÐ   ‡K  — t           5  t          j        Šdˆfd„} | t          _        	 dV — ‰t          _        n# ‰t          _        w xY w	 ddd¦  «         dS # 1 swxY w Y   dS )uT  Temporarily patch :func:`numpy.load` to set ``allow_pickle=True``.

    ``onnx2tf`` 1.x calls ``np.load()`` on its bundled calibration data without passing ``allow_pickle=True``.  NumPy â‰¥
    1.16.3 defaults that flag to ``False`` and raises :class:`ValueError` for pickled files.

    This context manager monkey-patches ``np.load`` for the duration of the ``onnx2tf`` conversion and restores the
    original afterwards.  Because ``np.load`` is process-global, the patch/restore cycle is guarded by a module-level
    lock so it is safe when multiple conversions run on separate threads.
    Úargsr   Úkwargsr!   c                 ó@   •— |                      dd¦  «          ‰| i |¤ŽS )NÚallow_pickleT)Ú
setdefault)rJ  rK  Ú_original_loads     €r8   Ú_patched_loadz*_numpy_allow_pickle.<locals>._patched_load%  s.   ø€ Ø×Ò˜n¨dÑ3Ô3Ð3Ø!�> 4Ð2¨6Ð2Ð2Ð2r:   N)rJ  r   rK  r   r!   r   )Ú_NUMPY_LOAD_PATCH_LOCKrB   r"  )rP  rO  s    @r8   Ú_numpy_allow_picklerR    sÍ   øè è € õ 
 ð %ð %Ýœˆð	3ð 	3ð 	3ð 	3ð 	3ð 	3ð  �Œð	%ØˆEˆEˆEà$�BŒGˆGø�n�BŒGÐ$Ð$Ð$Ð$ˆGð%ð %ð %ñ %ô %ð %ð %ð %ð %ð %ð %ð %øøøð %ð %ð %ð %ð %ð %s%   ‹A«<¯A¼A
Á
AÁAÁ"Ac               #  ó  ‡K  — g Št           j        rTt          t           j        ¦  «        } |                      ¦   «         r'‰                     t          | j        ¦  «        ¦  «         t          j        d¦  «        }|r6t          |¦  «                             ¦   «         r‰                     |¦  «         t          t                               ‰¦  «        ¦  «        Št          j                             dd¦  «        }dt          j        v }|r|                     t          j        ¦  «        ng }ˆfd„|D ¦   «         }t          j                             ‰|z   ¦  «        }‰r||k    rdV — dS t$                               d‰› d�¦  «         |t          j        d<   	 dV — |r|t          j        d<   dS t          j                             dd¦  «         dS # |r|t          j        d<   w t          j                             dd¦  «         w xY w)a   Temporarily put the running interpreter's script directory first on ``PATH``.

    ``onnx2tf`` simplifies the ONNX graph by shelling out to the bare ``onnxsim`` console script.  The lookup relies on
    ``PATH``, so it fails whenever RF-DETR runs under a virtual environment that was never *activated*:
    calling ``<venv>/bin/python`` by absolute path (the norm for subprocess-driven tooling, IDE run
    configurations, and desktop app integrations) leaves the venv's ``bin`` / ``Scripts`` directory
    off ``PATH`` even though ``onnxsim`` is installed there.

    Prepending the interpreter's own script directory makes the subprocess lookup resolve to the ``onnxsim``
    installed by the ``rfdetr[tflite]`` extra, matching the interpreter that is driving the export. Candidate
    directories already present in ``PATH`` are moved to the front and duplicate preferred-directory entries are
    removed.

    Yields:
        ``None``.  ``PATH`` is restored to its previous value on exit, including on exception.

    Note:
        ``os.environ`` is process-global, so this is not safe against concurrent mutation of ``PATH`` from other
        threads.  Restore is unconditional rather than merged, so a concurrent ``PATH`` edit made inside the context
        is lost.
    ÚscriptsÚPATHr;   c                ó   •— g | ]}|‰v¯|‘Œ	S rÙ   rÙ   )r  ÚentryÚscripts_dirss     €r8   r  z0_interpreter_scripts_on_path.<locals>.<listcomp>U  s#   ø€ ÐIÐIÐI˜5¨u¸LÐ/HÐ/H�Ð/HÐ/HÐ/Hr:   NzPrepending z2 to PATH so onnx2tf's onnxsim subprocess resolves.)ÚsysÚ
executabler   Úis_absoluterN   r-   ÚparentÚ	sysconfigÚget_pathÚlistÚdictÚfromkeysÚosÚenvironrð   ÚsplitÚpathsepÚjoinr&  r'  Úpop)Úexecutable_pathÚsysconfig_scriptsÚoriginal_pathÚpath_was_setÚentriesÚ	remainingÚupdated_pathrX  s          @r8   Ú_interpreter_scripts_on_pathro  0  sò  øè è € ð. !€LÝ
„~ð =Ý�sœ~Ñ.Ô.ˆØ×&Ò&Ñ(Ô(ð 	=Ø×Ò¥ OÔ$:Ñ ;Ô ;Ñ<Ô<Ð<å!Ô*¨9Ñ5Ô5ÐØð /�TÐ"3Ñ4Ô4×@Ò@ÑBÔBð /Ø×ÒÐ-Ñ.Ô.Ð.å�Ÿš lÑ3Ô3Ñ4Ô4€LÝ”J—N’N 6¨2Ñ.Ô.€MØ�RœZÐ'€LØ1>ÐFˆm×!Ò!¥"¤*Ñ-Ô-Ð-ÀB€GØIÐIÐIÐI GÐIÑIÔI€IÝ”:—?’? <°)Ñ#;Ñ<Ô<€Làð ˜<¨=Ò8Ð8ØˆˆˆØˆå
‡L‚LÐ_˜|Ð_Ð_Ð_Ñ`Ô`Ð`Ø%…B„JˆvÑð)Øˆˆˆàð 	)Ø!.�BŒJ�vÑÐÐåŒJ�NŠN˜6 4Ñ(Ô(Ð(Ð(Ð(øð ð 	)Ø!.�BŒJ�vÑÐåŒJ�NŠN˜6 4Ñ(Ô(Ð(Ð(øøøs   ÆG Ç4HÚnpy_pathr-   c              #  ó  ‡ K  — dˆ fd„}i }ddg}|D ]W}t           j                             |¦  «        }|r4t          |d¦  «        r$t	          |d¦  «        ||<   t          |d|¦  «         ŒX	 dV — |                     ¦   «         D ]7\  }}t           j                             |¦  «        }|rt          |d|¦  «         Œ8dS # |                     ¦   «         D ]7\  }}t           j                             |¦  «        }|rt          |d|¦  «         Œ8w xY w)	a$  Redirect onnx2tf's legacy validation-data download when the hook exists.

    ``download_test_image_data`` is absent from every released onnx2tf 2.x version this project supports
    (verified through 2.6.8); the ``hasattr`` guard is retained defensively in case a future 2.x release
    (still matching the ``<3.0.0`` pin) reintroduces it. This is an output-validation hook, not an INT8
    calibration path: RF-DETR never passes ``output_integer_quantized_tflite``.

    Args:
        npy_path: Path to locally prepared NHWC validation data.
    r!   úNDArray[np.float32]c                 óv   •— t          t          t          j                 t          j        ‰ d¬¦  «        ¦  «        S )NF)rM  )r   r	   rB   rô   r"  )rp  s   €r8   Ú_replacementz0_patch_validation_download.<locals>._replacementt  s+   ø€ õ
 •G�BœJÔ'­¬°ÈÐ)NÑ)NÔ)NÑOÔOÐOr:   zonnx2tf.utils.common_functionszonnx2tf.onnx2tfÚdownload_test_image_dataN)r!   rr  )rY  Úmodulesrð   ÚhasattrrA  ÚsetattrÚitems)rp  rt  Ú	originalsrv  Úmod_nameÚmodÚoriginals   `      r8   Ú_patch_validation_downloadr~  g  sn  øè è € ðPð Pð Pð Pð Pð Pð !#€Ià(Øð€Gð ð Cð CˆÝŒk�oŠo˜hÑ'Ô'ˆØð 	C•7˜3Ð :Ñ;Ô;ð 	CÝ")¨#Ð/IÑ"JÔ"JˆI�hÑÝ�CÐ3°\ÑBÔBÐBøðCØˆˆˆà"+§/¢/Ñ"3Ô"3ð 	Cð 	CÑˆH�hÝ”+—/’/ (Ñ+Ô+ˆCØð CÝ˜Ð7¸ÑBÔBÐBøð	Cð 	Cø )§/¢/Ñ"3Ô"3ð 	Cð 	CÑˆH�hÝ”+—/’/ (Ñ+Ô+ˆCØð CÝ˜Ð7¸ÑBÔBÐBøð	Cøøøs   Á+B= Â=ADÚ	image_dirÚheightÚwidthÚ
max_imagesrr  c                óZ  — ddl m} |                      ¦   «         st          d| › �¦  «        ‚t	          d„ |                      ¦   «         D ¦   «         ¦  «        }|s't          d| › dt	          t          ¦  «        › �¦  «        ‚|d|…         }t                               dt          |¦  «        › d	| › d
|› d|› d�	¦  «         g }|D ]÷}	 | 
                    |¦  «        5 }|                     d¦  «        }	ddd¦  «         n# 1 swxY w Y   t          j        |	t          j        ¬¦  «                             ddd¦  «        t          j        d¦  «        z  }
t!          |
||¦  «                             ddd¦  «        }|                     |¦  «         ŒË# t$          $ r  t                               d|› �¦  «         Y Œôw xY w|st          d| › �¦  «        ‚t                               dt          |¦  «        › d�¦  «         t          j        |¦  «                             t          j        d¬¦  «        S )a  Load images from a directory and prepare them for calibration.

    Images are loaded, resized to ``(height, width)``, converted to ``float32`` in ``[0, 1]``, and stacked into an NHWC
    array.

    Args:
        image_dir: Directory containing image files (JPEG, PNG, etc.).
        height: Target image height matching the model input.
        width: Target image width matching the model input.
        max_images: Maximum number of images to load.  Files are sorted
            alphabetically and the first *max_images* are used.

    Returns:
        A ``float32`` NumPy array of shape ``(N, height, width, 3)`` with pixel values in ``[0, 1]``.

    Raises:
        FileNotFoundError: If *image_dir* does not exist or contains no
            supported image files.
    r   )ÚImagez'Calibration image directory not found: c              3  óZ   K  — | ]&}|j                              ¦   «         t          v ¯"|V — Œ'd S rì   )ÚsuffixÚlowerr   )r  Úps     r8   ú	<genexpr>z+_load_calibration_images.<locals>.<genexpr>­  s9   è è € ÐaÐa˜q¸1¼8¿>º>Ñ;KÔ;KÕO`Ð;`Ð;`˜Ð;`Ð;`Ð;`Ð;`ÐaÐar:   z"No supported image files found in z. Supported extensions: NzLoading z calibration images from z (resizing to Úxú)ÚRGBr?   rS   r$   g     ào@zSkipping unreadable image: zNo readable images found in zLoaded z calibration imagesF)Úcopy)ÚPILr„  Úis_dirÚFileNotFoundErrorÚsortedÚiterdirr   r&  r(  rò   ÚopenÚconvertrB   Úasarrayrô   Ú	transposer
   rN   r/  r'  ÚstackÚastype)r  r€  r�  r‚  r„  Úimage_pathsÚarraysÚimg_pathÚ_imgÚimgÚchwÚimage_arrays               r8   Ú_load_calibration_imagesr   �  sš  € ð2 ÐÐÐÐÐà×ÒÑÔð WÝÐ UÈ)Ð UÐ UÑVÔVÐVåÐaÐa I×$5Ò$5Ñ$7Ô$7ÐaÑaÔaÑaÔa€Kàð 
ÝØo°ÐoÐoÕTZÕ[lÑTmÔTmÐoÐoñ
ô 
ð 	
ð ˜k˜z˜kÔ*€KÝ
‡K‚KÐp�3˜{Ñ+Ô+ÐpÐpÀiÐpÐpÐ_eÐpÐpÐhmÐpÐpÐpÑqÔqÐqà(*€FØð ð ˆð	Ø—’˜HÑ%Ô%ð *¨Ø—l’l 5Ñ)Ô)�ð*ð *ð *ñ *ô *ð *ð *ð *ð *ð *ð *øøøð *ð *ð *ð *õ
 ”*˜S­¬
Ð3Ñ3Ô3×=Ò=¸aÀÀAÑFÔFÍÌÐTYÑIZÔIZÑZˆCÝ5°c¸6À5ÑIÔI×SÒSÐTUÐWXÐZ[Ñ\Ô\ˆKØ�MŠM˜+Ñ&Ô&Ð&Ð&øÝð 	ð 	ð 	Ý�LŠLÐA°xÐAÐAÑBÔBÐBØˆHð	øøøð ð LÝÐ J¸yÐ JÐ JÑKÔKÐKå
‡K‚KÐ:�#˜f™+œ+Ð:Ð:Ð:Ñ;Ô;Ð;ÝŒ8�FÑÔ×"Ò"¥2¤:°EÐ"Ñ:Ô:Ð:s7   ÃFÃC=Ã1FÃ=D	ÄFÄD	ÄBFÆ'F8Æ7F8útuple[str, list[int]]c                ó  — 	 ddl }n"# t          $ r}t          d¦  «        |‚d}~ww xY w|                     t          | ¦  «        ¦  «        }|j        j        d         }|j        }d„ |j        j        j	        j
        D ¦   «         }||fS )zùRead the first input tensor's name and shape from an ONNX model.

    Args:
        onnx_path: Path to the ``.onnx`` file.

    Returns:
        A ``(name, dims)`` tuple where *dims* is the NCHW shape list, e.g. ``("input", [1, 3, 560, 560])``.
    r   Nzkonnx is not installed. TFLite export requires the tflite extra. Install it with: pip install rfdetr[tflite]c                ó   — g | ]	}|j         ‘Œ
S rÙ   )Ú	dim_value)r  Úds     r8   r  z(_get_onnx_input_info.<locals>.<listcomp>á  s   € Ð@Ð@Ð@˜AˆAŒKÐ@Ð@Ð@r:   )rî   r!  r"  r-   r   Úinputr,   ÚtypeÚtensor_typer/   Údim)r  rî   r3  r4  Úinpr,   Údimss          r8   Ú_get_onnx_input_infor¬  Í  s¤   € ðØˆˆˆˆøÝð ð ð Ýð:ñ
ô 
ð ð	øøøøðøøøð �IŠI•c˜)‘n”nÑ%Ô%€EØ
Œ+Ô
˜AÔ
€CØŒ8€DØ@Ð@ ¤Ô!5Ô!;Ô!?Ð@Ñ@Ô@€DØ�ˆ:Ðs   ‚ ‡
&‘!¡&Úcalibration_dataú3str | os.PathLike[str] | NDArray[np.float32] | Nonec                óì  — |€«t          | ¦  «        \  }}|\  }}}}t          j                             t          |||¦  «                             t          j        ¦  «        }	|dz  }
t          j        t          |
¦  «        |	¦  «         t           
                    d|	j        › d|
› �¦  «         �nFt          |t          j        ¦  «        rJ|dz  }
t          j        t          |
¦  «        |¦  «         t                               d|j        › �¦  «         nât          |¦  «        }|                     ¦   «         ryt          | ¦  «        \  }}|\  }}}}t#          ||||¬¦  «        }	|dz  }
t          j        t          |
¦  «        |	¦  «         t                               d|	j        › d|
› �¦  «         nF|                     ¦   «         r |}
t                               d|
› �¦  «         nt'          d	|› �¦  «        ‚|
S )
uå  Prepare a ``.npy`` data file for onnx2tf's conditional legacy validation hook.

    The returned path points to an NHWC float32 array with pixel values in ``[0, 1]``. Generated or reformatted data is
    saved as ``_rfdetr_calib_data.npy`` in *output_dir*; an existing ``.npy`` path is returned unchanged. The data is
    offered to onnx2tf's conditional legacy validation hook and does not influence the generated ``.tflite`` models.

    Args:
        onnx_path: Path to the source ``.onnx`` file, read for the input tensor's
            NCHW shape (random data generation, and the target resolution when loading images from a directory).
        calibration_data: One of:

            * ``None`` â€” generate random data.  Adequate for every quantization
              mode, INT8 included: INT8 is dynamic-range, so no calibration is involved.
            * A **directory path** containing JPEG/PNG images â€” images are
              loaded, resized to the model input resolution, and converted to the correct format automatically.
            * A path to a ``.npy`` file containing an array of shape
              ``(N, H, W, 3)``, dtype float32, values in ``[0, 1]``.
            * A :class:`numpy.ndarray` with the same constraints.
        output_dir: Directory where a temporary ``.npy`` file may be
            written when *calibration_data* is ``None``, a directory, or an ndarray.
        max_images: Maximum number of images to load when
            *calibration_data* is a directory path.  Ignored for other calibration data formats.

    Returns:
        Path to the ``.npy`` calibration data file.

    Raises:
        FileNotFoundError: If *calibration_data* is a path that does not
            exist, or a directory with no supported images.
    Nz_rfdetr_calib_data.npyz)Generated random calibration data: shape=z, saved to z(Using provided calibration array: shape=)r€  r�  r‚  z6Prepared calibration data from image directory: shape=zUsing calibration data from: z!Calibration data path not found: )r¬  rB   ÚrandomÚrandr   r˜  rô   r2  r-   r&  r'  r/   Ú
isinstanceÚndarrayr(  r   r�  r   Úis_filer�  )r  r­  r  r‚  r2   Ú
input_dimsrC   ÚhÚwÚcalibrp  Ú	data_pathÚ_cs                r8   Ú_prepare_calibration_datar»  å  sõ  € ðH ÐÝ,¨YÑ7Ô7‰ˆˆ:à‰
ˆˆ1ˆa�å”	—’Õ5°q¸!¸QÑ?Ô?×FÒFÅrÄzÑRÔRˆØÐ 8Ñ8ˆÝ
Œ•�H‘”˜uÑ%Ô%Ð%Ý�ŠÐcÀÄÐcÐcÐYaÐcÐcÑdÔdÐdÑdÝ	Ð$¥b¤jÑ	1Ô	1ð UØÐ 8Ñ8ˆÝ
Œ•�H‘”Ð/Ñ0Ô0Ð0Ý�ŠÐWÐ?OÔ?UÐWÐWÑXÔXÐXÐXåÐ)Ñ*Ô*ˆ	Ø×ÒÑÔð 	Uå0°Ñ;Ô;‰MˆAˆzØ$‰KˆAˆr�1�aÝ,¨Y¸qÈÐV`ÐaÑaÔaˆEØ!Ð$<Ñ<ˆHÝŒG•C˜‘M”M 5Ñ)Ô)Ð)Ý�KŠKÐsÐQVÔQ\ÐsÐsÐiqÐsÐsÑtÔtÐtÐtØ×ÒÑ Ô ð 	UØ ˆHÝ�KŠKÐB¸ÐBÐBÑCÔCÐCÐCå#Ð$SÈ	Ð$SÐ$SÑTÔTÐTà€Or:   Ú
model_stemc                ó�   — dD ]B\  }}| |› d|› d�z  }|                      ¦   «         r|                     | |› d|› d�z  ¦  «         ŒCdS )u¯  Rename onnx2tf's hardcoded ``_float32``/``_float16`` outputs to the ``_fp32``/``_fp16`` tokens.

    ``onnx2tf`` always writes ``{model_stem}_float32.tflite`` and ``{model_stem}_float16.tflite`` â€” that
    naming is internal to the library and not configurable. Rename both (when present) so the RF-DETR
    export surface uses the same ``fp32``/``fp16`` vocabulary as the ONNX/CoreML/ExecuTorch/TensorRT
    backends. Missing files (e.g. onnx2tf skipped one precision on a given run) are silently ignored.

    Args:
        output_dir: Directory onnx2tf wrote its ``.tflite`` outputs to.
        model_stem: Stem of the (possibly GridSample-patched) ONNX file passed to onnx2tf.
    ))rô   r   )Úfloat16r   r2   z.tfliteN)r´  Úreplace)r  r¼  Ú	old_tokenÚ	new_tokenÚold_paths        r8   Ú_rename_precision_outputsrÃ  )  s‚   € ð !Kð Nð NÑˆ	�9Ø :Ð BÐ B°	Ð BÐ BÐ BÑBˆØ×ÒÑÔð 	NØ×Ò˜Z¨ZÐ*LÐ*L¸)Ð*LÐ*LÐ*LÑLÑMÔMÐMøðNð Nr:   Úsaved_model_dirc                óò   — ddl }|j        j                             t	          | ¦  «        ¦  «        }|j        j        j        g|_        | |› d�z  }|                     | 	                    ¦   «         ¦  «         |S )aÀ  Build a dynamic-range INT8 TFLite model from the onnx2tf SavedModel.

    Dynamic-range quantization stores weights as INT8 and keeps activations in float, so it needs no calibration data.

    Args:
        saved_model_dir: Directory holding the SavedModel ``onnx2tf`` wrote.
        model_stem: Stem of the source ONNX file, used to name the output.

    Returns:
        Path to the written ``{model_stem}_dynamic_range_quant.tflite`` file.
    r   Nz_dynamic_range_quant.tflite)
Ú
tensorflowÚliteÚTFLiteConverterÚfrom_saved_modelr-   ÚOptimizeÚDEFAULTÚoptimizationsÚwrite_bytesr”  )rÄ  r¼  ÚtfÚ	converterr7  s        r8   Ú_quantize_dynamic_rangerÐ  ;  s{   € ð ÐÐÐà”Ô'×8Ò8½¸_Ñ9MÔ9MÑNÔN€IØ!œwÔ/Ô7Ð8€IÔØ JÐ!KÐ!KÐ!KÑK€HØ×Ò˜×*Ò*Ñ,Ô,Ñ-Ô-Ð-Ø€Or:   T)ÚfrozenÚslotsc                  óT   — e Zd ZU dZdZded<   dZded<   dZded	<   d
Zded<   dd„Z	dS )ÚTFLiteConfigaÕ  Settings for ``format="tflite"``, which converts an ONNX export rather than the model directly.

    Attributes:
        opset_version: ONNX opset the intermediate graph targets.
        quantization: Quantization mode; ``"int8"`` additionally writes a dynamic-range model.
        calibration_data: Data written to a scratch file beside the artifacts but not consumed by the conversion.
        max_images: Maximum images read from a *calibration_data* directory.
    é   r   Úopset_versionNz
str | NoneÚquantizationr   r­  r   r‚  r!   c                óF   — ddl m} |                     | | j        ¬¦  «        S )aF  Return the configuration for the ONNX export this format converts from.

        Returns:
            An :class:`~rfdetr.export._onnx.exporter.OnnxConfig` carrying the settings the intermediate graph needs.

        Examples:
            >>> TFLiteConfig(quantization="int8").onnx_stage().opset_version
            17
        r   )Ú
OnnxConfig)rÖ  )Úrfdetr.export._onnx.exporterrÙ  ÚderiverÖ  )ÚselfrÙ  s     r8   Ú
onnx_stagezTFLiteConfig.onnx_stage`  s2   € ð 	<Ð;Ð;Ð;Ð;Ð;à× Ò  °TÔ5GÐ ÑHÔHÐHr:   )r!   r   )
Ú__name__Ú
__module__Ú__qualname__Ú__doc__rÖ  Ú__annotations__r×  r­  r‚  rÝ  rÙ   r:   r8   rÔ  rÔ  P  s�   € € € € € € ðð ð €MÐÐÐÑØ#€LÐ#Ð#Ð#Ñ#Ø ÐÐ Ð Ð Ñ Ø€JÐÐÐÑðIð Ið Ið Ið Ið Ir:   rÔ  c                  ó€   — e Zd ZdZeZdddddœZdZd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%d„ZdS )&ÚTFLiteExportera  Export to TFLite by running an ONNX export first and converting its output with ``onnx2tf``.

    Owning the ONNX stage is what makes the TensorFlow preload correct: it has to happen before anything imports
    ONNX's C extension, and that is this exporter's first statement rather than a special case in the caller.

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

        ```python
        TFLiteExporter(TFLiteConfig(variant_name="rfdetr-small"))(graph)
        # -> PosixPath('output/rfdetr-small_gs_patched_fp32.tflite')
        ```
    rÖ  r×  r­  r‚  )rÖ  r×  r­  r‚  ÚtfliteÚTFLiteTzOUpstream dependency instabilities (onnx2tf, ai_edge_litert) may affect results.r   r   r!   r   c                ó®   — ddl m}  |¦   «          ddlm}   || j                             ¦   «         ¦  «        |¦  «        }|                      |¦  «        S )zêExport to ONNX, convert to TFLite, and return the converted artifact's path.

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

        Returns:
            Path to the primary ``.tflite`` artifact.
        r   ©Úpreload_tensorflow_before_onnx)ÚOnnxExporter)Úrfdetr.export._backendré  rÚ  rê  ÚconfigrÝ  Úconvert_onnx)rÜ  r   ré  rê  r  s        r8   Ú_convertzTFLiteExporter._convert�  su   € ð 	JÐIÐIÐIÐIÐIð
 	'Ð&Ñ(Ô(Ð(à=Ð=Ð=Ð=Ð=Ð=à:�L�L ¤×!7Ò!7Ñ!9Ô!9Ñ:Ô:¸5ÑAÔAˆ	Ø× Ò  Ñ+Ô+Ð+r:   r  ústr | os.PathLike[str]c                ó²  — t          |¦  «        }t          | j        j        ¦  «        }|                      |¦  «         |                      ¦   «          |                     dd¬¦  «         |                      ||¦  «        }|                      ||¦  «        }|                      |||¦  «         |j	        }t          ||¦  «         |                      ||¦  «        S )uý  Convert an already-exported ONNX model to TFLite via ``onnx2tf``.

        Requires ``onnx2tf >= 2.4.0``.  Uses the Python API with a NumPy compatibility shim.  This is the entry
        point for converting an ``.onnx`` file that was produced earlier â€” :meth:`_convert` runs the ONNX stage
        itself and then calls this method with its output.

        The artifacts land in ``self.config.output_dir``.  ``onnx2tf`` creates ``{stem}_float32.tflite`` and
        ``{stem}_float16.tflite`` (its own hardcoded naming); both are renamed to ``{stem}_fp32.tflite`` /
        ``{stem}_fp16.tflite`` to match the naming used by the other export backends.  When
        ``quantization="int8"`` a ``{stem}_dynamic_range_quant.tflite`` is additionally written.

        Args:
            onnx_path: Path to the source ``.onnx`` file.

        Returns:
            Path to the primary artifact.  ``onnx2tf`` always writes both an FP32 and FP16 model (renamed to
            ``{stem}_fp32.tflite`` / ``{stem}_fp16.tflite``); ``quantization="int8"`` adds
            ``{stem}_dynamic_range_quant.tflite``. The returned path is the dynamic-range file for ``int8``,
            otherwise the fp32 file.

        Raises:
            FileNotFoundError: If *onnx_path* does not exist or the configured
                *calibration_data* points to a missing file.
            ImportError: If ``onnx2tf`` is not installed.
            ValueError: If the configured *quantization* is not a recognized mode.
            RuntimeError: If the conversion fails.

        Note:
            This method is **not thread-safe**. It globally monkey-patches :func:`numpy.load` (via
            :func:`_numpy_allow_pickle`), ``onnx2tf.download_test_image_data`` when available (via
            :func:`_patch_validation_download`), and ``os.environ["PATH"]`` (via
            :func:`_interpreter_scripts_on_path`) for the duration of the conversion. Concurrent calls from
            multiple threads will interfere with each other. Run conversion in a subprocess if isolation is
            required.

            ``tf_converter`` backend is forced unconditionally (overriding onnx2tf's 2.x ``flatbuffer_direct``
            default) to avoid a runtime error in the TFLite TopK_V2 kernel.  ``Erf`` and ``GeLU`` ops are
            substituted with TFLite-native pseudo-operators to avoid a missing TensorFlow Flex delegate at
            inference time.

            Segmentation models additionally emit a ``masks`` output, decoded by
            :func:`rfdetr.export._tflite.inference._run_inference`.  Verified on the non-plus segmentation
            variants (Nano, Small, Medium, Large, Preview).

        Examples:
            Requires the optional ``onnx2tf`` dependency and an exported ``.onnx``, so this is documentation
            only (not a doctest):

            ```python
            TFLiteExporter(TFLiteConfig(output_dir=Path("output"))).convert_onnx("output/rfdetr-small.onnx")
            # -> PosixPath('output/rfdetr-small_gs_patched_fp32.tflite')
            ```
        T)ÚparentsÚexist_ok)r   rì  r  Ú_validate_onnx_sourceÚ_prepare_onnx2tfÚmkdirÚ_rewrite_gridsampleÚ_prepare_calibrationÚ_run_onnx2tfr1  rÃ  Ú_resolve_primary_output)rÜ  r  r  Úcalib_npy_pathr¼  s        r8   rí  zTFLiteExporter.convert_onnx¥  sÔ   € õl ˜‘O”Oˆ	Ý˜$œ+Ô0Ñ1Ô1ˆ
à×"Ò" 9Ñ-Ô-Ð-Ø×ÒÑÔÐà×Ò °ÐÑ5Ô5Ð5à×,Ò,¨Y¸
ÑCÔCˆ	Ø×2Ò2°9¸jÑIÔIˆØ×Ò˜) Z°Ñ@Ô@Ð@ð
 ”^ˆ
õ 	" *¨jÑ9Ô9Ð9à×+Ò+¨J¸
ÑCÔCÐCr:   r"   c           	     óð   — |                      ¦   «         st          d|› �¦  «        ‚| j        j        t          vr<t          d| j        j        ›dt          d„ t          D ¦   «         ¦  «        › d�¦  «        ‚dS )a@  Reject a missing source model or an unrecognized quantization mode.

        Args:
            onnx_path: Path to the source ``.onnx`` file.

        Raises:
            FileNotFoundError: If *onnx_path* is not an existing file.
            ValueError: If the configured *quantization* is not a recognized mode.
        zONNX model not found: zUnsupported quantization mode z. Choose from: c              3  ó   K  — | ]}|®|V — Œ	d S rì   rÙ   )r  Úqs     r8   r‰  z7TFLiteExporter._validate_onnx_source.<locals>.<genexpr>  s"   è è € Ð&XÐ&X¨QÈ!È- qÈ-È-È-È-Ð&XÐ&Xr:   zG. Static / full-integer INT8 is not supported; 'int8' is dynamic-range.N)r´  r�  rì  r×  r   ró   r‘  )rÜ  r  s     r8   ró  z$TFLiteExporter._validate_onnx_sourceô  s¢   € ð × Ò Ñ"Ô"ð 	JÝ#Ð$H¸YÐ$HÐ$HÑIÔIÐIàŒ;Ô#Õ+?Ð?Ð?ÝðX°´Ô1Ið Xð XÝ &Ð&XÐ&XÕ2FÐ&XÑ&XÔ&XÑ XÔ XðXð Xð Xñô ð ð @Ð?r:   c                ód   — ddl m}  |¦   «          t          ¦   «          ddlm} ddlmc m} ~~dS )zÈLoad TensorFlow ahead of ONNX, verify ``onnx2tf``, and import the submodules the patches target.

        Raises:
            ImportError: If ``onnx2tf`` cannot be imported or is below 2.4.0.
        r   rè  N)rë  ré  rG  Úonnx2tf.onnx2tfr=  Úonnx2tf.utils.common_functionsÚutilsÚcommon_functions)rÜ  ré  rD  Ú_onnx2tf_commons       r8   rô  zTFLiteExporter._prepare_onnx2tf  sj   € ð 	JÐIÐIÐIÐIÐIà&Ð&Ñ(Ô(Ð(å Ñ"Ô"Ð"ð 	/Ð.Ð.Ð.Ð.Ð.Ø@Ð@Ð@Ð@Ð@Ð@Ð@Ð@Ð@à˜/˜/˜/r:   r  c                óŒ   — 	 t          ||¦  «        S # t          $ r'}t                               d|¦  «         |cY d}~S d}~ww xY w)a´  Rewrite the graph's GridSample nodes into TFLite-safe ops, tolerating a missing ONNX toolchain.

        Args:
            onnx_path: Path to the source ``.onnx`` file.
            output_dir: Directory the patched ``.onnx`` is written to.

        Returns:
            Path to the patched ``.onnx``, or *onnx_path* unchanged when the graph has no ``GridSample``
            nodes or the rewrite's dependencies are unavailable.
        uÍ   GridSample TFLite patch skipped â€” onnx/onnx_graphsurgeon not available (%s). TFLite inference may produce incorrect scores if the model contains GridSample nodes. Install with: pip install rfdetr[tflite]N)r8  r!  r&  Úwarning)rÜ  r  r  r3  s       r8   rö  z"TFLiteExporter._rewrite_gridsample   sm   € ð"		Ý1°)¸ZÑHÔHÐHøÝð 	ð 	ð 	Ý�NŠNð;ð ñ	ô ð ð ÐÐÐÐÐÐøøøøð	øøøs   ‚ ’
Aœ>¸A¾Ac                ó¼   — | j         j        �*| j         j        dk    rt                               d¦  «         t          || j         j        || j         j        ¬¦  «        S )a  Write the ``.npy`` onnx2tf's conditional validation hook reads, and note when INT8 ignores it.

        Args:
            onnx_path: Path to the ``.onnx`` file the input shape is read from.
            output_dir: Directory a generated or reformatted ``.npy`` is written to.

        Returns:
            Path to the ``.npy`` calibration data file.

        Raises:
            FileNotFoundError: If the configured *calibration_data* is a path that does not exist, or a
                directory with no supported images.
        Nr   ztThe provided calibration data has no effect on the generated INT8 model: dynamic-range quantization does not use it.)r‚  )rì  r­  r×  r&  r(  r»  r‚  )rÜ  r  r  s      r8   r÷  z#TFLiteExporter._prepare_calibration<  sf   € ð Œ;Ô'Ð3¸¼Ô8PÐTZÒ8ZÐ8ZÝ�KŠKð>ñô ð õ
 )Ø�t”{Ô3°ZÈDÌKÔLbð
ñ 
ô 
ð 	
r:   rú  c           
     óô  — | j         j        rdnd}t                               d| j         j        ›d|›d|› �¦  «         	 t          ¦   «         5  t          t          |¦  «        ¦  «        5  t          ¦   «         5  ddl	m
} t          |¦  «        t          |¦  «        d| j         j         |d	d
gdœ}	  |di |¤ddi¤Ž n2# t          $ r% t                               d¦  «          |di |¤Ž Y nw xY wddd¦  «         n# 1 swxY w Y   ddd¦  «         n# 1 swxY w Y   ddd¦  «         dS # 1 swxY w Y   dS # t          $ r5}t                               d|› �¦  «         t          d|› �¦  «        |‚d}~ww xY w)a˜  Run ``onnx2tf.convert`` under the three process-global patches the conversion needs.

        Args:
            onnx_path: Path to the ``.onnx`` file handed to ``onnx2tf``.
            output_dir: Directory ``onnx2tf`` writes its artifacts to.
            calib_npy_path: Path the conditional validation hook is redirected to.

        Raises:
            RuntimeError: If ``onnx2tf.convert`` fails.
        r(  Úerroru)   Converting ONNX â†’ TFLite (quantization=z, verbosity=z): r   )r”  TÚErfÚGeLU)Úinput_onnx_file_pathÚoutput_folder_pathÚoutput_signaturedefsÚnon_verboseÚ	verbosityÚreplace_to_pseudo_operatorsÚtflite_backendÚtf_converteru”   onnx2tf does not support tflite_backend= â€” proceeding with default backend. If TFLite inference produces wrong results, upgrade to onnx2tf>=2.4.0.Nzonnx2tf conversion failed: rÙ   )rì  Úverboser&  r(  r×  rR  r~  r-   ro  r=  r”  Ú	TypeErrorr  r/  r  r0  )rÜ  r  r  rú  r  r”  Úconvert_kwargsr3  s           r8   rø  zTFLiteExporter._run_onnx2tfT  sÉ  € ð #œkÔ1Ð>�F�F°wˆ	Ý�Šð¸¼Ô8Pð ð Ð`ið ð Øðð ñ	
ô 	
ð 	
ð
5	Mõ $Ñ%Ô%ð'.ð '.å*­3¨~Ñ+>Ô+>Ñ?Ô?ð'.ð '.õ -Ñ.Ô.ð'.ð '.ð
 ,Ð+Ð+Ð+Ð+Ð+õ -0°	©N¬NÝ*-¨j©/¬/Ø,0Ø'+¤{Ô':Ð#:Ø!*ð 5:¸6°?ð2ð 2�ð0.Ø�GÐLÐL˜nÐLÐL¸^ÐLÐLÐLÐLÐLøÝ ð .ð .ð .Ý—N’Nð5ñô ð ð
 �GÐ-Ð-˜nÐ-Ð-Ð-Ð-Ð-ð.øøøðC'.ð '.ð '.ñ '.ô '.ð '.ð '.ð '.ð '.ð '.ð '.øøøð '.ð '.ð '.ð '.ð '.ð '.ð '.ñ '.ô '.ð '.ð '.ð '.ð '.ð '.ð '.øøøð '.ð '.ð '.ð '.ð '.ð '.ð '.ñ '.ô '.ð '.ð '.ð '.ð '.ð '.ð '.ð '.øøøð '.ð '.ð '.ð '.ð '.ð '.øõR ð 	Mð 	Mð 	MÝ�LŠLÐ<°sÐ<Ð<Ñ=Ô=Ð=ÝÐB¸SÐBÐBÑCÔCÈÐLøøøøð	Møøøs§   ¿D8 ÁD+Á*DÁ97C<Â1B>Â=C<Â>,C-	Ã*C<Ã,C-	Ã-C<Ã0DÃ<D Ä DÄD ÄDÄD+ÄD	ÄD+ÄD	ÄD+ÄD8 Ä+D/Ä/D8 Ä2D/Ä3D8 Ä8
E7Å0E2Å2E7r¼  r-   c                óä  — | j         j        dk    r/t          ||¦  «        }t                               d|› �¦  «         |S ||› d�z  }|                     ¦   «         swt          |                     |› d�¦  «        ¦  «        }|r;|d         }t                               d||› d�z  › d|› d|› d	|j	        › d
�	¦  «         nt          d|› d|› �¦  «        ‚t                               d|› �¦  «         |S )u;  Pick the artifact the export returns, building the dynamic-range model for ``int8``.

        Args:
            output_dir: Directory ``onnx2tf`` wrote its artifacts to.
            model_stem: Stem of the (possibly GridSample-patched) ONNX file passed to ``onnx2tf``.

        Returns:
            The dynamic-range file for ``quantization="int8"``, otherwise the fp32 file â€” falling back to any
            ``{model_stem}_*.tflite`` when the fp32 file is absent.

        Raises:
            RuntimeError: If no ``.tflite`` matching *model_stem* was written.
        r   zTFLite model exported to: z_fp32.tflitez	_*.tfliter   zExpected TFLite output z not found; searched for 'z_*.tflite' in z and using z\ instead. The returned model may have a different dtype (e.g. int8) than the caller expects.z0onnx2tf completed but no .tflite file matching 'z_*.tflite' was found in )rì  r×  rÐ  r&  r(  r´  r‘  Úglobr  r,   r0  )rÜ  r  r¼  ÚprimaryÚtflite_filess        r8   rù  z&TFLiteExporter._resolve_primary_outputœ  sZ  € ð Œ;Ô# vÒ-Ð-å-¨j¸*ÑEÔEˆGÝ�KŠKÐ>°WÐ>Ð>Ñ?Ô?Ð?ØˆNà *Ð:Ð:Ð:Ñ:ˆà�ŠÑ Ô ð 	õ " *§/¢/°ZÐ2JÐ2JÐ2JÑ"KÔ"KÑLÔLˆLØð 
Ø& qœ/�Ý—’ði¨j¸jÐ;VÐ;VÐ;VÑ.Vð ið iØ%/ðið iØ?Iðið iØV]ÔVbðið ið iñô ð ð õ #ØwÀzÐwÐwÐkuÐwÐwñô ð õ 	�ŠÐ:°Ð:Ð:Ñ;Ô;Ð;Øˆr:   N)r   r   r!   r   )r  rï  r!   r   )r  r   r!   r"   ©r!   r"   ©r  r   r  r   r!   r   )r  r   r  r   rú  r   r!   r"   )r  r   r¼  r-   r!   r   )rÞ  rß  rà  rá  rÔ  Úconfig_classÚsetting_namesÚformatÚdisplay_nameÚsupports_dynamic_batchÚsupports_notesÚexperimentalÚexperimental_noteÚ	pip_extrarî  rí  ró  rô  rö  r÷  rø  rù  rÙ   r:   r8   rä  rä  q  s  € € € € € ðð ð  €Là(Ø&Ø.Ø"ð	ð €Mð €FØ€LØ!ÐØ€NØ€LØiÐØ€Ið,ð ,ð ,ð ,ð*MDð MDð MDð MDð^ð ð ð ð(*ð *ð *ð *ð0ð ð ð ð8
ð 
ð 
ð 
ð0FMð FMð FMð FMðP(ð (ð (ð (ð (ð (r:   rä  )r   r   r   r   r    r   r!   r"   r  r  )r!   rH  )rp  r-   r!   rH  )
r  r   r€  r   r�  r   r‚  r   r!   rr  )r  r   r!   r¡  )
r  r   r­  r®  r  r   r‚  r   r!   r   )r  r   r¼  r-   r!   r"   )rÄ  r   r¼  r-   r!   r   )4rá  Ú
__future__r   Ú
contextlibrb  rY  r]  Ú	threadingÚdataclassesr   Úpathlibr   Útypingr   r   r   rí   rB   Únumpy.typingr	   Úrfdetr.export._resizer
   Úrfdetr.export.baser   r   Úrfdetr.export.preparer   Úrfdetr.utilities.loggerr   r&  r   râ  r   Ú	frozensetr   r   r  r8  rG  ÚLockrQ  ÚcontextmanagerrR  ro  r~  r   r¬  r»  rÃ  rÐ  rÔ  rä  rÙ   r:   r8   ú<module>r3     sc  ððAð Að AðF #Ð "Ð "Ð "Ð "Ð "à Ð Ð Ð Ø 	€	€	€	Ø 
€
€
€
Ø Ð Ð Ð Ø Ð Ð Ð Ø !Ð !Ð !Ð !Ð !Ð !Ø Ð Ð Ð Ð Ð Ø 'Ð 'Ð 'Ð 'Ð 'Ð 'Ð 'Ð 'Ð 'Ð 'à Ð Ð Ð Ø  Ð  Ð  Ð  Ð  Ð  à =Ð =Ð =Ð =Ð =Ð =Ø 5Ð 5Ð 5Ð 5Ð 5Ð 5Ð 5Ð 5Ø -Ð -Ð -Ð -Ð -Ð -Ø .Ð .Ð .Ð .Ð .Ð .à	ˆ‰Œ€ð )GÐ(FÐ(FÐ Ð FÐ FÐ FÑ Fð !Ð Ð  Ð  Ð  Ñ  ð %. IÐ.XÐ.XÐ.XÑ$YÔ$YÐ Ð YÐ YÐ YÑ Yð #&Ð Ð %Ð %Ð %Ñ %ðtð tð tð tðn	Cð Cð Cð CðL'
ð '
ð '
ð '
ðX (˜œÑ)Ô)Ð ð Ôð%ð %ð %ñ Ôð%ð0 Ôð3)ð 3)ð 3)ñ Ôð3)ðl Ôð$Cð $Cð $Cñ Ôð$CðV 1ð	;;ð ;;ð ;;ð ;;ð ;;ð|ð ð ð ð8 1ð	Að Að Að Að AðHNð Nð Nð Nð$ð ð ð ð* €�$˜dÐ#Ñ#Ô#ðIð Ið Ið Ið I�<ñ Iô Iñ $Ô#ðIð@Sð Sð Sð Sð S�X˜lÔ+ñ Sô Sð Sð Sð Sr:   