
    ^j%                        d 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 dZdd
ZddZddZ	 	 	 	 	 	 	 	 ddZ	 	 	 	 	 	 	 	 	 	 ddZy# e$ r dZdZdZ	dZd	ZY 8w xY w)z4Rich console helper for the training callback stack.    )annotations)Any)ConsoleGroup)Live)TableTNFc                    t         t        d      t        | dg       D ];  }t        d t	        |      j
                  D              s)t        |dd      }|9|c S  t        d      S )u  Return a Rich Console appropriate for the current training context.

    When a ``RichProgressBar`` callback is active, its ``_console`` is the Rich global
    singleton that owns the Live progress display.  Printing through that same console
    instance ensures output appears correctly above the progress bars rather than
    conflicting with the Live display's cursor positioning (particularly on Windows).

    Falls back to ``Console(force_terminal=True)`` for plain-terminal and TQDM contexts.

    Args:
        trainer: The PTL Trainer (or any object with a ``callbacks`` attribute).

    Returns:
        A Rich ``Console`` instance suitable for printing metric tables.

    Note:
        Reads ``RichProgressBar._console``, a private PTL attribute. When ``_console`` is
        ``None`` (outside an active fit/validate/test stage) or the attribute is renamed in a
        future PTL release, the function silently falls back to ``Console(force_terminal=True)``
        — a fresh console with an empty live stack that may reintroduce cursor conflicts on
        Windows. Subclasses and theme wrappers of ``RichProgressBar`` are matched via MRO.
    NzT_get_rich_console called when Rich is not installed; check _IS_RICH_AVAILABLE first.	callbacksc              3  :   K   | ]  }|j                   d k(    yw)RichProgressBarN)__name__).0clss     c/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/rfdetr/utilities/console.py	<genexpr>z$_get_rich_console.<locals>.<genexpr>7   s     MSs||00Ms   _consoleT)force_terminal)r   RuntimeErrorgetattranytype__mro__)trainercb
cb_consoles      r   _get_rich_consoler      sr    . b
 	
 g{B/ "MDH<L<LMM Z6J%!!	"
 $''    c                @    t        | dg       }t        d |D              S )zReturn whether the trainer has a Lightning progress bar callback.

    Args:
        trainer: The PTL Trainer (or any object with a ``callbacks`` attribute).

    Returns:
        ``True`` when any callback class name ends with ``"ProgressBar"``.
    r
   c              3  f   K   | ])  }|j                   j                  j                  d        + yw)ProgressBarN)	__class__r   endswith)r   callbacks     r   r   z$_has_progress_bar.<locals>.<genexpr>H   s'     ]xx!!**33MB]s   /1)r   r   )r   r
   s     r   _has_progress_barr$   >   s$     b1I]S\]]]r   c           
     <  8 d'd}d| }d| }dd ||d         fd ||d         fd	 ||d
         fgfd| |||         fgfdd ||d         fd ||d         fd ||d         fgfg}d|v r+|j                  dd ||d         fd ||d         fgf       |D 	
cg c]  \  }}|D ]	  \  }	}
|	|
f  }}	}}}
|D 	
cg c]&  \  }	}
t        t        |	      t        |
            dz   ( c}
}	8d}|D ]e  \  }}t        |      }t        8|||z          |dz
  z   }t        |      dz   }||kD  r&t	        ||z
        D ]  }8|||z  z   xx   dz  cc<    ||z  }g g }d}|D ]/  \  }}t        |      }|j                  |||z   dz
  |f       ||z  }1 |dd D ch c]  \  }}}|
 }}}}t        |      }d(8fd}d}d}d}d}d\  }}d}d \  }} d!}!d"}"d#\  }#}$}%d$\  }&}'}(t        8      |z   dz
  })|  d%}*|*j                  |)dz         }+|},t        |      D ]0  \  }-\  }	}.}|,| ||	|.      z  z  },|,|-t        |      dz
  k  r|n|z  },2 |}/|D ]$  \  }	}.}|/|j                   ||	|.            |z   z  }/& |}0t        8      D ]!  \  }-}1|0||1z  z  }0|-|dz
  k  s|0|-|v r|!n|"z  }0# |0| z  }0|}2t        |      D ]"  \  }-\  }3}|2|3j                  8|-         |z   z  }2$ |#}4t        8      D ]  \  }-}1|4||1z  z  }4|4|-|dz
  k  r|%n|$z  }4 |}5t        |      D ]"  \  }-\  }}6|5|6j                  8|-         |z   z  }5$ |&}7t        8      D ]  \  }-}1|7||1z  z  }7|7|-|dz
  k  r|(n|'z  }7 d&j                  |+|,|/|0|2|4|5|7g      S c c}
}	}}w c c}
}	w c c}}}w ))u(  Render the overall metrics table with merged group-header cells.

    Uses only plain Unicode box-drawing characters (no ANSI colour codes) so the output renders correctly in both
    terminals and Jupyter/Colab notebook widgets.

    Args:
        title_pfx: Capitalised split name used in the title (e.g. ``"Val"``).
        overall: Ordered mapping of metric label → scalar value.
        max_dets: Maximum detection count used for the mAR column label.

    Returns:
        Multi-line plain-text string ready to pass to ``console.print()``.
    c                     | | k7  s| dk  ry| dS Nr   u   —z.4f vs    r   _fmtz$_render_overall_merged.<locals>._fmtZ       6QUCr   @zmAR @mAPz50:95z	mAP 50:9550zmAP 5075zmAP 75mARzF1 sweepF1Prec	PrecisionRecallzsegm mAP 50:95zsegm mAPzsegm mAP 50   r      Nc                2    t        | |dz          || z
  z   S )z:Return merged cell width for columns start..end inclusive.r7   )sum)startendwidthss     r   grp_wz%_render_overall_merged.<locals>.grp_w   s"    6%#'*+sU{;;r   u   ━u   ─u   ┃u   │)u   ┏u   ┓u   ┳)u   ┡u   ┩u   ╇u   ┯)u   ├u   ┤u   ┼)u   └u   ┘u   ┴u    — Overall Metrics
r*   floatreturnstr)r;   intr<   rD   rB   rD   )appendmaxlenr:   rangecenter	enumeratejoin)9	title_pfxoverallmax_detsr+   mar_lblmar_keygroups_colssr*   flatcolgrpnccell_wneededkspansr;   r<   grp_endsnr>   heavy_horizontallight_horizontalheavy_verticallight_verticaltop_left_cornertop_right_corner
top_t_downtransition_lefttransition_right
group_joinsubgroup_joinmid_left	mid_right	mid_crossbottom_left_cornerbottom_right_cornerbottom_t_upinner_wtitle
title_liner1ier2r3wr4subr5r6valr7r=   s9                                                           @r   _render_overall_mergedr   K   s"   
 (nGhZ G $w{345tGH-./tGH-./	
 
'4 01234tGDM*+gk2344 123	
7F& 7"d7+;#<=>4 678	
 :@"Q"QgaD"QDAqAq6"Q6"QD"Q=ABTQSVSV,q0BF
C 	TYVC#(+,Q7SAF?6F?+ *sQV|$)$*r	 )+E
C 	TYc38a<-.r	
 */s44sA4H4D	A< NN(4%O%J(4%O%JM%8"Hi;N8+[&kAo!Gk-.Egk*J	B!%( E9Aq!
q!,,
AE
Q.j4DDE 
B 7	1c
cjjq!%667 
B&! A1
""q1u9X*=@BA 
B	B  58C
cjj#n445 
B&! 41
""
1q1u9i)34 
B  58As
cjj#n445 
B&! @1
""
QQYk,??@ 99j"b"b"b"=>>[ #RB& 5s   %N	
+N#Nc                
   t         J dd}|g}|rt        J t        |  dddd      }|j                  ddd       |j                  d	d
       |j                  dd
       |j                  dd
       |j                  dd
       |j                  dd
       |D ]H  }|j                  |d    ||d          ||d          ||d          ||d          ||d                J |j	                  |       t        | S )a  Build a single Rich renderable for overall and per-class metric tables.

    Args:
        title_pfx: Split label (e.g. ``"Val"`` or ``"Test"``).
        overall_rendered: Pre-rendered overall table string.
        per_class: Per-class dicts with keys ``name``, ``ap``, ``ar``,
            ``f1``, ``precision``, ``recall``; skipped when empty.

    Returns:
        Rich ``Group`` renderable containing the overall table and, when present,
        the per-class table.
    c                     | | k7  s| dk  ry| dS r'   r(   r)   s    r   r+   z'_build_summary_renderable.<locals>._fmt   r,   r   u    — Per-class Metricsz	bold cyanT)rq   title_styleshow_headerheader_styleClassdim)styleno_wrapzAP 50:95right)justifyARr2   r4   r5   nameaparf1	precisionrecallr@   )r   r   
add_columnadd_rowrE   )rL   overall_rendered	per_classr+   renderablestablerows          r   _build_summary_renderabler      s9   " 
 //K   K56#$	
 	t<W5w/w/g673 	CMMFSYSYSYS%&S]#	 	5!+r   c                J    t         sy| j                  t        |||             y)a  Print overall and per-class metric tables to ``console``.

    Args:
        console: Rich ``Console`` instance to print to.
        title_pfx: Split label (e.g. ``"Val"`` or ``"Test"``).
        overall_rendered: Pre-rendered overall table string.
        per_class: Per-class dicts with keys ``name``, ``ap``, ``ar``,
            ``f1``, ``precision``, ``recall``; skipped when empty.
    N)_IS_RICH_AVAILABLEprintr   )consolerL   r   r   s       r   _render_summary_tablesr     s!     MM+I7GSTr   )r   r   rB   r   )r   r   rB   bool)rL   rC   rM   zdict[str, float]rN   rD   rB   rC   )rL   rC   r   rC   r   list[dict[str, Any]]rB   r   )
r   r   rL   rC   r   rC   r   r   rB   None)__doc__
__future__r   typingr   rich.consoler   r   	rich.liver   
rich.tabler   r   ImportErrorr   r$   r   r   r   r(   r   r   <module>r      s    ; " +  !(H
^B?J222 $2 	2jUUU U $	U
 
Uk  GEDEs   A AA