§
    ­¸jÎJ  ã                  ó2  — U d Z ddlmZ ddlZddlZddlZddlmZ ddlm	Z	m
Z
 e	rddlmZ  ej        d¦  «        ZdZd4d„Z	 ddlZdZded<   n# e$ r dZY nw xY wedœd5d„Zd6d„Zd7d„Zd8d!„Zd9d$„Zd:d'„Zd;d(„Zd<d/„Z	 	 d=d>d0„Z	 d?d@d1„ZdAd2„Z	 	 d=d>d3„Z dS )Bu\  Post-training metrics plotting utilities.

Reads the ``metrics.csv`` written by PTL's ``CSVLogger`` (always present after a ``build_trainer``-based run) and builds
seaborn figures grouped by metric type (Loss, AP@0.50, AP@0.50:0.95, AR).

Loss panel shows aggregate and component loss scalars. AP/AR panels show all ``train/``, ``val/``, and ``test/``
columns for each group â€” both the base and EMA series when EMA is enabled, so both are visible in the legend.

Usage::

    from rfdetr.visualize.training import plot_metrics
    fig = plot_metrics("output/rfdetr_base/metrics.csv")
    plt.show(fig)
é    )ÚannotationsN)ÚPath)ÚTYPE_CHECKINGÚAny)ÚFigurez_\d+$é   Ú
matplotlibr   ÚreturnÚNonec                óò   — |                       ¦   «                              ¦   «         dk    rdS t          j                             d¦  «        s|                      ¦   «         rdS |                      d¦  «         dS )a  Switch matplotlib to the non-interactive ``Agg`` backend only when safe.

    Forcing ``Agg`` unconditionally would break inline rendering in notebooks, so the switch is skipped when a display
    is available or matplotlib is already in interactive mode.
    ÚaggNÚDISPLAYÚAgg)Úget_backendÚlowerÚosÚenvironÚgetÚis_interactiveÚuse)r	   s    úi/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/rfdetr/visualize/training.pyÚ_ensure_headless_backendr   $   sr   € ð ×ÒÑÔ×%Ò%Ñ'Ô'¨5Ò0Ð0ØˆÝ	„z‡~‚~�iÑ Ô ð  J×$=Ò$=Ñ$?Ô$?ð ØˆØ‡N‚N�5ÑÔÐÐÐó    TÚboolÚ_IS_SEABORN_AVAILABLEF)Ú	n_columnsÚaxr   Úintc               óÆ   — |                       ¦   «         \  }}|sdS |                      ||ddt          |t          dt	          |¦  «        ¦  «        ¦  «        dd¬¦  «         dS )z<Place a compact multi-column legend below a matplotlib axes.Nzupper center)g      à?g
×£p=
Ç¿é   é	   T)ÚlocÚbbox_to_anchorÚncolÚfontsizeÚframeon)Úget_legend_handles_labelsÚlegendÚminÚmaxÚlen)r   r   ÚhandlesÚlabelss       r   Ú_place_legend_below_axesr.   9   sx   € à×2Ò2Ñ4Ô4�O€GˆVØð ØˆØ‡I‚IØØØØ#Ý��C ¥3 v¡;¤;Ñ/Ô/Ñ0Ô0ØØð ñ ô ð ð ð r   ÚcolumnÚstrútuple[str, str]c                óP   — |                       d¦  «        \  }}}|r|dv r||fS d| fS )zBSplit a CSVLogger metric column into split prefix and metric name.ú/>   ÚvalÚtestÚtrainÚ )Ú	partition)r/   ÚsplitÚ	separatorÚmetric_names       r   Ú_split_metric_columnr<   I   sD   € à$*×$4Ò$4°SÑ$9Ô$9Ñ!€Eˆ9�kØð "�UÐ6Ð6Ð6Ø�kÐ!Ð!Øˆvˆ:Ðr   r9   c                ó&   — | dk    rdS | dk    rdS dS )z2Return the plotting line style for a metric split.r6   ú:r5   z-.ú-© )r9   s    r   Ú_line_style_for_splitrA   Q   s%   € à�ÒÐØˆsØ�‚€ØˆtØˆ3r   Úraw_dfÚepoch_dfÚmetric_columnsú	list[str]c                óÒ  — 	 ddl m} n"# t          $ r}t          d¦  «        |‚d}~ww xY w|j        d                              ¦   «                              dg ¦  «        }i }|D �]}t          |¦  «        \  }	}
|
|vr,|r%|t          |¦  «        t          |¦  «        z           nd||
<   ||
         }t          |	¦  «        }t          ryddl
}|d|g                              |g¬¦  «        }|j        sN	 |                     |d|| d	||d
|¬¦	  «	         Œ­# t          $ r! |                     |d|| d||d
|¬¦	  «	         Y Œ×w xY wŒÜ|                      |d         ||         d
|||¬¦  «         �ŒdS )u  Plot columns with color by metric name and line style by split.

    When seaborn is installed, draws mean Â± 1 std-dev bands computed from within-epoch step-level rows in ``raw_df``.
    Falls back to epoch-averaged lines from ``epoch_df`` when seaborn is absent.
    r   NúYmatplotlib is required for training metric plots. Install it with: pip install matplotlibzaxes.prop_cycleÚcolorÚC0Úepoch)Úsubset)Úsdr    g333333û?)	ÚdataÚxÚyr   ÚerrorbarrH   Ú	linestyleÚ	linewidthÚlabelrL   )	rM   rN   rO   r   ÚcirH   rQ   rR   rS   )rR   rQ   rH   rS   )Úmatplotlib.pyplotÚpyplotÚImportErrorÚrcParamsÚby_keyr   r<   r+   rA   r   ÚseabornÚdropnaÚemptyÚlineplotÚ	TypeErrorÚplot)r   rB   rC   rD   ÚpltÚexcÚcolor_cycleÚmetric_colorsr/   r9   r;   rH   rQ   ÚsnsÚcol_datas                  r   Ú_plot_columns_on_axesrf   Z   s   € ðØ'Ð'Ð'Ð'Ð'Ð'Ð'øÝð ð ð ÝØgñ
ô 
àð	øøøøðøøøð
 ”,Ð0Ô1×8Ò8Ñ:Ô:×>Ò>¸wÈÑKÔK€KØ$&€Mà ð -ñ -ˆÝ1°&Ñ9Ô9Ñˆˆ{Ø˜mÐ+Ð+Ø_jÐ)t¨µS¸Ñ5GÔ5GÍ#ÈkÑJZÔJZÑ5ZÔ)[Ð)[ÐptˆM˜+Ñ&Ø˜kÔ*ˆÝ)¨%Ñ0Ô0ˆ	å ð &	Ø!Ð!Ð!Ð!à˜w¨Ð/Ô0×7Ò7À¸xÐ7ÑHÔHˆHØ”>ð ðØ—L’LØ%Ø!Ø ØØ!*Ø#Ø"+Ø"%Ø$ð !ñ 
ô 
ð 
ð 
øõ !ð ð ð à—L’LØ%Ø!Ø ØØØ#Ø"+Ø"%Ø$ð !ñ 
ô 
ð 
ð 
ð 
ðøøøðð6 �GŠGØ˜Ô!Ø˜Ô ØØ#ØØð ñ ô ð ñ ðM-ð -s"   ‚	 ‰
(“#£(Ã0DÄ(D:Ä9D:Údfúdict[str, list[str]]c                óÄ  ‡ ‡— d$ˆ fd„}d%d„Šˆˆ fd	„‰ j         D ¦   «         }d
„  |dd¦  «        D ¦   «         } |dd¦  «        }d„  |ddd¦  «        D ¦   «         }d„  |dd¦  «        D ¦   «         }d„  |dd¦  «        D ¦   «         } |dd¦  «        } |dd¦  «        }	 |dd¦  «        }
 |dd d!¦  «        }|||||||	||
|d"œ
}d#„ |                     ¦   «         D ¦   «         S )&a  Build plot groups from numeric PTL CSVLogger metrics.

    Args:
        df: DataFrame-like object with metric columns.

    Returns:
        Non-empty metric groups keyed by subplot title.

    Raises:
        AttributeError: If ``df`` does not provide DataFrame-like columns.
    Úpatternsr0   r
   rE   c                 ó6   •‡ ‡— dŠˆˆ ˆfd„‰j         D ¦   «         S )zLReturn split-prefixed columns whose name contains any of the given patterns.)útrain/úval/útest/c                óÎ   •‡— g | ]`Š‰                      ‰¦  «        ¯t          ˆfd „‰D ¦   «         ¦  «        ¯2‰‰                              ¦   «                              ¦   «         ¯^‰‘ŒaS )c              3  ó    •K  — | ]}|‰v V — Œ	d S ©Nr@   )Ú.0ÚpÚcs     €r   ú	<genexpr>zG_build_metric_groups.<locals>._split_cols.<locals>.<listcomp>.<genexpr>«   s'   øè è € ÐC]ÐC]ÈqÀAÈÀFÐC]ÐC]ÐC]ÐC]ÐC]ÐC]r   )Ú
startswithÚanyÚnotna)rr   rt   rg   rj   Úprefixess    @€€€r   ú
<listcomp>z=_build_metric_groups.<locals>._split_cols.<locals>.<listcomp>ª   s‡   øø€ ð 
ð 
ð 
Ø Q§\¢\°(Ñ%;Ô%;ð
Ý@CÐC]ÐC]ÐC]ÐC]ÐT\ÐC]ÑC]ÔC]Ñ@]Ô@]ð
ØbdÐefÔbg×bmÒbmÑboÔbo×bsÒbsÑbuÔbuð
Øð
ð 
ð 
r   )Úcolumns)rj   ry   rg   s   `@€r   Ú_split_colsz)_build_metric_groups.<locals>._split_cols§   sA   øøø€ à.ˆð
ð 
ð 
ð 
ð 
ð 
Ø”zð
ñ 
ô 
ð 	
r   Únamer   c                óÖ   — | dv rdS |                       dd¬¦  «        d                              ¦   «         }t                               |¦  «        rdS d|v p|                     d¦  «        S )	z0Return whether a metric column is a loss scalar.>   ÚsteprJ   Fr3   r    )ÚmaxsplitéÿÿÿÿÚlossÚkp_)Úrsplitr   Ú_AUXILIARY_LOSS_SUFFIX_REÚsearchrv   )r}   Úleafs     r   Ú_is_loss_colz*_build_metric_groups.<locals>._is_loss_col®   so   € àÐ$Ð$Ð$Ø�5Ø�{Š{˜3¨ˆ{Ñ+Ô+¨BÔ/×5Ò5Ñ7Ô7ˆÝ$×+Ò+¨DÑ1Ô1ð 	Ø�5Ø˜ˆ~Ð7 §¢°Ñ!7Ô!7Ð7r   c                óœ   •— g | ]H} ‰t          |¦  «        ¦  «        ¯‰|                              ¦   «                              ¦   «         ¯F|‘ŒIS r@   )r0   rx   rw   )rr   r}   rˆ   rg   s     €€r   rz   z(_build_metric_groups.<locals>.<listcomp>·   sM   ø€ ÐcÐcÐc˜$°°½SÀ¹Y¼YÑ0GÔ0GÐcÈBÈtÌHÏNÊNÑL\ÔL\×L`ÒL`ÑLbÔLbÐc�ÐcÐcÐcr   c                ó"   — g | ]}d |v¯d|v¯
|‘ŒS )Ú	mAP_50_95ÚmAP_75r@   ©rr   rt   s     r   rz   z(_build_metric_groups.<locals>.<listcomp>¸   s/   € ÐuÐuÐu˜aÈ+Ð]^ÐJ^ÐJ^ÐckÐstÐctÐct˜ÐctÐctÐctr   ÚmAP_50Ú
ema_mAP_50rŒ   Ú
ema_mAP_75c                ó"   — g | ]}d |vsd|v ¯
|‘ŒS )rŽ   r‹   r@   r�   s     r   rz   z(_build_metric_groups.<locals>.<listcomp>º   s6   € ð ð ð ØÈÐXYÐHYÐHYÐ]hÐlmÐ]mÐ]mˆÐ]mÐ]mÐ]mr   r‹   Úema_mAP_50_95z/AP/c                ó   — g | ]}d |v¯|‘Œ	S )Ú	keypoint_r@   r�   s     r   rz   z(_build_metric_groups.<locals>.<listcomp>½   s#   € ÐVÐVÐV˜1ÀÐTUÐAUÐAU�QÐAUÐAUÐAUr   ÚmARÚema_mARc                ó"   — g | ]}d |v¯d|v¯
|‘ŒS )Ú	map_50_95Úmap_75r@   r�   s     r   rz   z(_build_metric_groups.<locals>.<listcomp>¾   s6   € ð ð ð ØÈKÐ_`ÐL`ÐL`ÐemÐuvÐevÐevˆÐevÐevÐevr   Úkeypoint_map_50Úema_keypoint_map_50Úkeypoint_map_75Úema_keypoint_map_75Úkeypoint_map_50_95Úema_keypoint_map_50_95Úkeypoint_mARÚema_keypoint_mARÚF1Ú	precisionÚrecall)
ÚLossúDetection AP@0.50úDetection AP@0.50:0.95úDetection AP@0.75zDetection ARúKeypoint AP@0.50úKeypoint AP@0.50:0.95úKeypoint AP@0.75zKeypoint ARzF1 / Precision / Recallc                ó   — i | ]
\  }}|¯||“ŒS r@   r@   )rr   r}   r{   s      r   ú
<dictcomp>z(_build_metric_groups.<locals>.<dictcomp>Ò   s#   € ÐPÐPÐP™m˜d GÈÐPˆD�'ÐPÐPÐPr   )rj   r0   r
   rE   )r}   r0   r
   r   )r{   Úitems)rg   r|   Ú	loss_colsÚdetection_map_50Údetection_map_75Údetection_map_50_95Údetection_marrš   rœ   rž   Úkeypoint_marÚf1_precision_recallÚmetric_groupsrˆ   s   `            @r   Ú_build_metric_groupsr·   š   s¢  øø€ ð
ð 
ð 
ð 
ð 
ð 
ð8ð 8ð 8ð 8ð dÐcÐcÐcÐc "¤*ÐcÑcÔc€IØuÐu ; ;¨x¸Ñ#FÔ#FÐuÑuÔuÐØ"�{ 8¨\Ñ:Ô:Ððð Ø�;˜{¨O¸VÑDÔDðñ ô Ðð WÐV  ¨E°9Ñ =Ô =ÐVÑVÔV€Mðð Ø�;Ð0Ð2GÑHÔHðñ ô €Oð "�kÐ"3Ð5JÑKÔK€OØ$˜Ð%9Ð;SÑTÔTÐØ�;˜~Ð/AÑBÔB€LØ%˜+ d¨K¸ÑBÔBÐð Ø-Ø"5Ø-Ø%Ø+Ø!3Ø+Ø#Ø#6ð+ð +€Mð QÐP¨}×/BÒ/BÑ/DÔ/DÐPÑPÔPÐPr   Úmetrics_csvútuple[Any, Any]c                ó²  — 	 ddl }n"# t          $ r}t          d¦  «        |‚d}~ww xY wt          | ¦  «        }|                     ¦   «         st	          d|› �¦  «        ‚|                     |¦  «        }d|j        vrt          d¦  «        ‚t          |¦  «        }| 	                    d¦  «         
                    d¬¦  «                             ¦   «         }||fS )	aR  Read a PTL CSVLogger metrics file and return both step-level and epoch-averaged DataFrames.

    Returns:
        A ``(raw_df, epoch_df)`` pair where ``raw_df`` contains every logged row
        (one per training step or validation epoch) and ``epoch_df`` is the per-epoch
        mean used for column detection and log-scale checks.
    r   NzQpandas is required for training metric plots. Install it with: pip install pandaszmetrics.csv not found: rJ   z/metrics.csv does not contain an 'epoch' column.T)Únumeric_only)ÚpandasrW   r   ÚexistsÚFileNotFoundErrorÚread_csvr{   Ú
ValueErrorÚ%_drop_trailing_validation_only_epochsÚgroupbyÚmeanÚreset_index)r¸   Úpdra   Úcsv_pathrg   rB   rC   s          r   Ú_read_metrics_csvrÇ   Õ   sø   € ðxØÐÐÐÐøÝð xð xð xÝÐmÑnÔnÐtwÐwøøøøðxøøøõ �KÑ Ô €HØ�?Š?ÑÔð FÝÐ D¸(Ð DÐ DÑEÔEÐEà	�Š�XÑ	Ô	€BØ�b”jÐ Ð ÝÐJÑKÔKÐKÝ2°2Ñ6Ô6€FØ�~Š~˜gÑ&Ô&×+Ò+¸Ð+Ñ>Ô>×JÒJÑLÔL€HØ�8ÐÐs   ‚ ‡
&‘!¡&c                óh  — d„ | j         D ¦   «         }d„ | j         D ¦   «         }|r|s| S | |                              ¦   «                              d¬¦  «        s| S | }t          |¦  «        dk    rÄ|d         j        d         }|d         |k    }|j        |         }|j        |          j        r|S ||                              ¦   «                              d¬¦  «        }||                              ¦   «                              d¬¦  «        }|s|s|S |j        |          }t          |¦  «        dk    °Ä|S )a�  Remove post-fit validation rows that Lightning logs as a synthetic final epoch.

    The Roboflow finetune demos run ``trainer.validate(...)`` after ``trainer.fit(...)`` to write a final metrics JSON.
    PTL appends that validation pass to the same ``CSVLogger`` file using ``epoch == max_epochs``. That row is useful as
    a standalone final validation result, but it is not part of the training curve and can create a misleading last-
    epoch jump in plots. Only trailing epochs with validation/test metrics and no training metrics are removed, and only
    when the CSV also contains real training rows. Pure validation CSV files are preserved.
    c                óV   — g | ]&}t          |¦  «                             d ¦  «        ¯$|‘Œ'S )rl   ©r0   rv   ©rr   r/   s     r   rz   z9_drop_trailing_validation_only_epochs.<locals>.<listcomp>÷   s1   € ÐYÐYÐY ½¸F¹¼×8NÒ8NÈxÑ8XÔ8XÐY�VÐYÐYÐYr   c                óV   — g | ]&}t          |¦  «                             d ¦  «        ¯$|‘Œ'S ))rm   rn   rÊ   rË   s     r   rz   z9_drop_trailing_validation_only_epochs.<locals>.<listcomp>ø   s2   € ÐaÐaÐa˜vµs¸6±{´{×7MÒ7MÐN_Ñ7`Ô7`Ða�FÐaÐaÐar   N©Úaxisr   rJ   r�   )r{   rx   rw   r+   Úilocr"   r\   )	rg   Útrain_columnsÚeval_columnsÚcleanedÚ
last_epochÚ
epoch_maskÚ
epoch_rowsÚhas_train_metricsÚhas_eval_metricss	            r   rÁ   rÁ   î   s[  € ð ZÐY¨"¬*ÐYÑYÔY€MØaÐa¨¬ÐaÑaÔa€LØð  ð Øˆ	ØˆmÔ×"Ò"Ñ$Ô$×(Ò(¨dÐ(Ñ3Ô3ð Øˆ	à€GÝ
ˆg‰,Œ,˜Ò
Ð
Ø˜WÔ%Ô*¨2Ô.ˆ
Ø˜WÔ%¨Ò3ˆ
Ø”[ Ô,ˆ
ØŒ;˜
�{Ô#Ô)ð 	ØˆNØ& }Ô5×;Ò;Ñ=Ô=×AÒAÀtÐAÑLÔLÐØ% lÔ3×9Ò9Ñ;Ô;×?Ò?ÀTÐ?ÑJÔJÐØð 	Ð$4ð 	ØˆNØ”+˜z˜kÔ*ˆõ ˆg‰,Œ,˜Ò
Ð
ð €Nr   r¶   ÚtitleÚoutput_pathú
str | NoneÚloss_log_scaler   c               ó°  — 	 ddl }t          |¦  «         ddlm} n"# t          $ r}t	          d¦  «        |‚d}~ww xY w|st          d¦  «        ‚t          |¦  «        }	|	dk    rdnd}
|	|
z   dz
  |
z  }|                     ||
dd|z  fd	¬
¦  «        \  }}|                     ¦   «         }t          | 
                    ¦   «         ¦  «        D ]ê\  }\  }}||         }t          || ||¦  «         |                     |dd¬¦  «         |                     dd¬¦  «         |                     |d¬¦  «         |                     dd¬¦  «         |dk    rV|rT||         }|dk                         d¬¦  «        rt#          j        dt&          d¬¦  «         n|                     d¦  «         t+          |¦  «         Œët-          |	t          |¦  «        ¦  «        D ]}||                              d	¦  «         Œ|                     |d¬¦  «         |                     ¦   «          d|v r|                     |	dk    rdnd¬¦  «         |�|                     |dd¬¦  «         |S ) z#Build a figure for grouped metrics.r   NrG   zDmetrics.csv does not contain any supported non-empty metric columns.r    é   é   é   F)ÚfigsizeÚsqueezeé   Úbold©r%   Ú
fontweightÚEpoché   ©r%   Tç333333Ó?©Úalphar¥   rÍ   zvloss_log_scale=True was requested, but at least one loss value is non-positive; using linear scale for the Loss panel.)Ú
stacklevelÚlogé   ç¸…ëQ¸Î?g¸…ëQ¸¾?©Úbottomé–   Útight©ÚdpiÚbbox_inches)r	   r   rU   rV   rW   rÀ   r+   ÚsubplotsÚflattenÚ	enumerater®   rf   Ú	set_titleÚ
set_xlabelÚ
set_ylabelÚgridrw   ÚwarningsÚwarnÚUserWarningÚ
set_yscaler.   ÚrangeÚset_visibleÚsuptitleÚtight_layoutÚsubplots_adjustÚsavefig)rB   rC   r¶   rØ   rÙ   rÛ   r	   r`   ra   Ún_groupsÚn_colsÚn_rowsÚfigÚaxesÚ	axes_flatÚidxÚsubplot_titleÚmetric_listr   Ú
group_datas                       r   Ú_plot_metric_groupsr    sÈ  € ðØÐÐÐå  Ñ,Ô,Ð,Ø'Ð'Ð'Ð'Ð'Ð'Ð'øÝð ð ð ÝØgñ
ô 
àð	øøøøðøøøð
 ð aÝÐ_Ñ`Ô`Ð`å�=Ñ!Ô!€HØ˜a’-�-ˆQˆQ Q€FØ˜Ñ !Ñ#¨Ñ.€Fà—’˜V V°b¸!¸f¹*Ð5EÈu�ÑUÔU�I€CˆØ—’‘”€Iå-6°}×7JÒ7JÑ7LÔ7LÑ-MÔ-Mð %ð %Ñ)ˆÑ)ˆm˜[Ø�sŒ^ˆÝ˜b &¨(°KÑ@Ô@Ð@Ø
�Š�]¨R¸FˆÑCÔCÐCØ
�Š�g¨ˆÑ+Ô+Ð+Ø
�Š�m¨bˆÑ1Ô1Ð1Ø
�Š�˜CˆÑ Ô Ð Ø˜FÒ"Ð" ~Ð"Ø! +Ô.ˆJØ˜a’×$Ò$¨$Ð$Ñ/Ô/ð %Ý”ð=åØ ð	ñ ô ð ð ð —’˜eÑ$Ô$Ð$Ý  Ñ$Ô$Ð$Ð$å�X�s 9™~œ~Ñ.Ô.ð *ð *ˆØ�#Œ×"Ò" 5Ñ)Ô)Ð)Ð)à‡L‚L� €LÑ$Ô$Ð$Ø×ÒÑÔÐØ�ÐÐØ×Ò¨8°qª=¨= 4 4¸dÐÑCÔCÐCØÐØ�Š�K S°gˆÑ>Ô>Ð>Ø€Jó   ‚ œ
;¦6¶;c                óŠ   — t          | ¦  «        \  }}t          |¦  «        }t          ||d|v r
d|d         ini d||¬¦  «        S )uE  Plot aggregate and component training losses from a PTL ``metrics.csv`` file.

    Reads the CSV written by PyTorch Lightning's ``CSVLogger``, groups loss columns
    (aggregate loss, per-component scalars, and keypoint NLL terms) into a single panel,
    and renders an optional seaborn error-band overlay when seaborn is installed.

    Args:
        metrics_csv: Path to the ``metrics.csv`` written by PTL's ``CSVLogger``.
        output_path: Optional filesystem path to save the rendered figure (PNG, PDF, â€¦).
            When ``None`` the figure is returned but not written to disk.
        loss_log_scale: When ``True``, the loss y-axis uses a logarithmic scale.
            Useful when loss components span several orders of magnitude.

    Returns:
        A ``matplotlib.figure.Figure`` containing the loss panel.

    Raises:
        FileNotFoundError: When ``metrics_csv`` does not exist.
        ImportError: When ``pandas`` or ``matplotlib`` is not installed.
        ValueError: When ``metrics_csv`` contains no loss columns.

    Examples:
        .. code-block:: python

            from rfdetr.visualize.training import plot_loss_metrics
            fig = plot_loss_metrics("output/rfdetr_small/metrics.csv")
            fig = plot_loss_metrics("output/rfdetr_small/metrics.csv", output_path="loss.png", loss_log_scale=True)
    r¥   zRF-DETR Loss Metrics©rØ   rÙ   rÛ   ©rÇ   r·   r  )r¸   rÙ   rÛ   rB   rC   Úgroupss         r   Úplot_loss_metricsr  K  se   € õB )¨Ñ5Ô5Ñ€FˆHÝ! (Ñ+Ô+€FÝØØØ$*¨fÐ$4Ð$4ˆ�˜”Ð Ð ¸"Ø$ØØ%ðñ ô ð r   c                óÈ   — t          | ¦  «        \  }}t          |¦  «        }d„ |                     ¦   «         D ¦   «         }|st          d¦  «        ‚t	          ||||¬¦  «        S )uø  Plot train/val/test detection and keypoint mAP metrics from a PTL ``metrics.csv`` file.

    Reads the CSV written by PyTorch Lightning's ``CSVLogger``, selects all AP-family
    columns (AP@0.50, AP@0.75, AP@0.50:0.95 for both detection and keypoints), and renders
    them in a single combined panel.  EMA series are included when present so both live and
    EMA metric trajectories are visible in the legend.

    Args:
        metrics_csv: Path to the ``metrics.csv`` written by PTL's ``CSVLogger``.
        output_path: Optional filesystem path to save the rendered figure (PNG, PDF, â€¦).
            When ``None`` the figure is returned but not written to disk.

    Returns:
        A ``matplotlib.figure.Figure`` containing the combined mAP panel.

    Raises:
        FileNotFoundError: When ``metrics_csv`` does not exist.
        ImportError: When ``pandas`` or ``matplotlib`` is not installed.
        ValueError: When ``metrics_csv`` contains no supported mAP metric columns.

    Examples:
        .. code-block:: python

            from rfdetr.visualize.training import plot_map_metrics
            fig = plot_map_metrics("output/rfdetr_small/metrics.csv")
            fig = plot_map_metrics("output/rfdetr_small/metrics.csv", output_path="map.png")
    c                ó*   — g | ]\  }}|d v ¯	|D ]}|‘ŒŒS )>   r©   r«   r¦   r¨   rª   r§   r@   )rr   Ú
group_namer{   r/   s       r   rz   z$plot_map_metrics.<locals>.<listcomp>™  sW   € ð ð ð áˆJ˜Øð
ð
ð 
ð ð
ð 
ð ð 	ð
ð 
ð 
ð 
r   zHmetrics.csv does not contain any supported non-empty mAP metric columns.)rÙ   )rÇ   r·   r®   rÀ   Ú_plot_map_columns)r¸   rÙ   rB   rC   r¶   Úmap_columnss         r   Úplot_map_metricsr  x  s~   € õ> )¨Ñ5Ô5Ñ€FˆHÝ(¨Ñ2Ô2€Mðð à#0×#6Ò#6Ñ#8Ô#8ðñ ô €Kð ð eÝÐcÑdÔdÐdÝ˜V X¨{ÈÐTÑTÔTÐTr   c               ó6  — 	 ddl }t          |¦  «         ddlm} n"# t          $ r}t	          d¦  «        |‚d}~ww xY w|                     d¬¦  «        \  }}t          || ||¦  «         |                     ddd¬	¦  «         |                     d
d¬¦  «         | 	                    dd¬¦  «         | 
                    dd¬¦  «         t          |¦  «         |                     ¦   «          |                     d¬¦  «         |�|                     |dd¬¦  «         |S )z;Plot mAP metrics on a single axes with line style by split.r   NzTmatplotlib is required for mAP metric plots. Install it with: pip install matplotlib)rÞ   é   )rà   zRF-DETR mAP Metricsrâ   rã   rä   ræ   rç   rè   ÚmAPTré   rê   rï   rð   rò   ró   rô   )r	   r   rU   rV   rW   r÷   rf   rú   rû   rü   rý   r.   r  r  r  )	rB   rC   rD   rÙ   r	   r`   ra   r  r   s	            r   r  r  ¬  sO  € ðØÐÐÐå  Ñ,Ô,Ð,Ø'Ð'Ð'Ð'Ð'Ð'Ð'øÝð ð ð ÝØbñ
ô 
àð	øøøøðøøøð
 �lŠl 7ˆlÑ+Ô+�G€CˆÝ˜"˜f h°Ñ?Ô?Ð?à‡L‚LÐ&°À€LÑGÔGÐGØ‡M‚M�' B€MÑ'Ô'Ð'Ø‡M‚M�% "€MÑ%Ô%Ð%Ø‡G‚GˆD˜€GÑÔÐÝ˜RÑ Ô Ð Ø×ÒÑÔÐØ×Ò˜tÐÑ$Ô$Ð$ØÐØ�Š�K S°gˆÑ>Ô>Ð>Ø€Jr  c                ón   — t          | ¦  «        \  }}t          |¦  «        }t          |||d||¬¦  «        S )uï  Read a PTL ``CSVLogger`` metrics file and build a training plot.

    The figure contains one subplot per metric group (loss, detection metrics,
    keypoint metrics, and F1/precision/recall), arranged in a 2-column grid.
    Only groups with at least one non-NaN column are shown.

    When seaborn is installed, each series is drawn as mean Â± 1 std-dev band
    computed from the within-epoch step-level rows logged by PTL's
    ``CSVLogger``.  Metrics recorded only once per epoch (e.g. ``val/mAP_50``)
    show a plain line because their per-epoch std is zero.  When seaborn is
    absent the plot falls back to epoch-averaged lines.

    Args:
        metrics_csv: Path to the ``metrics.csv`` file produced by
            ``CSVLogger``.
        output_path: Optional destination for the PNG file. If omitted, the
            figure is returned without saving.
        loss_log_scale: If ``True``, use a logarithmic y-axis for the Loss
            panel when all loss values are positive.

    Returns:
        The matplotlib figure. The figure is left open so notebook cells can
        display it inline.

    Raises:
        ImportError: If ``matplotlib`` or ``pandas`` are not installed.
        FileNotFoundError: If ``metrics_csv`` does not exist.
    zRF-DETR Training Metricsr  r  )r¸   rÙ   rÛ   rB   rC   r¶   s         r   Úplot_metricsr#  Ç  sM   € õB )¨Ñ5Ô5Ñ€FˆHÝ(¨Ñ2Ô2€MÝØØØØ(ØØ%ðñ ô ð r   )r	   r   r
   r   )r   r   r   r   r
   r   )r/   r0   r
   r1   )r9   r0   r
   r0   )
r   r   rB   r   rC   r   rD   rE   r
   r   )rg   r   r
   rh   )r¸   r0   r
   r¹   )rg   r   r
   r   )rB   r   rC   r   r¶   rh   rØ   r0   rÙ   rÚ   rÛ   r   r
   r   )NF)r¸   r0   rÙ   rÚ   rÛ   r   r
   r   rq   )r¸   r0   rÙ   rÚ   r
   r   )
rB   r   rC   r   rD   rE   rÙ   rÚ   r
   r   )!Ú__doc__Ú
__future__r   r   Úrerþ   Úpathlibr   Útypingr   r   Úmatplotlib.figurer   Úcompiler…   Ú_LEGEND_COLUMNSr   rZ   r   Ú__annotations__rW   r.   r<   rA   rf   r·   rÇ   rÁ   r  r  r  r  r#  r@   r   r   ú<module>r-     s8  ððð ð ð #Ð "Ð "Ð "Ð "Ð "à 	€	€	€	Ø 	€	€	€	Ø €€€Ø Ð Ð Ð Ð Ð Ø %Ð %Ð %Ð %Ð %Ð %Ð %Ð %àð )Ø(Ð(Ð(Ð(Ð(Ð(à&˜BœJ xÑ0Ô0Ð Ø€ð
ð 
ð 
ð 
ð"Ø€N€N€Nà"&ÐÐ&Ð&Ð&Ñ&Ð&øØð "ð "ð "Ø!ÐÐÐð"øøøð ;Jð ð ð ð ð ð ð ð ð ð ðð ð ð ð=ð =ð =ð =ð@8Qð 8Qð 8Qð 8Qðvð ð ð ð2ð ð ð ð>;ð ;ð ;ð ;ð@ #Ø ð*ð *ð *ð *ð *ð^ #ð1Uð 1Uð 1Uð 1Uð 1Uðhð ð ð ð: #Ø ð*ð *ð *ð *ð *ð *ð *s   ÁA ÁAÁA