
    ;3h`                       d Z ddlmZ ddlZddlmZmZ ddlmZm	Z	m
Z
mZmZ ddlZddlZddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ erddlZddlZddlmZ ddl m!Z! d Z"d Z# G d de      Z$ e        G d de             Z%y)zgr.Dataframe() component    )annotationsN)CallableSequence)TYPE_CHECKINGAnyLiteralOptionalUnion)document)	Component)GradioModel)Events)I18nDataStyler)Timerc                 V    dd l } | j                  j                  d      }t        |      S )Nr   polars)importlib.utilutil	find_specbool)	importlibspecs     [/var/www/html/audio-gradio/venv/lib/python3.12/site-packages/gradio/components/dataframe.py_is_polars_availabler       s#    >>##H-D:    c                     dd l } | S )Nr   )r   )pls    r   _import_polarsr    '   s
    Ir   c                  0    e Zd ZU ded<   ded<   dZded<   y)DataframeDataz	list[Any]headersz-Union[list[list[Any]], list[tuple[Any, ...]]]dataNz(Optional[dict[str, Optional[list[Any]]]]metadata)__name__
__module____qualname____annotations__r%    r   r   r"   r"   -   s    
779=H6=r   r"   c                       e Zd ZdZej
                  ej                  ej                  gZe	Z
	 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	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZ	 	 	 	 ddZe	 	 	 	 dd       Z	 	 	 	 ddZe	 	 	 	 dd       Ze	 	 	 	 d d       Z	 	 	 	 d!dZe	 d	 	 	 	 	 d"d       Zed#d$d       Zed%d       Z	 	 d&dZd'dZd'dZ xZS )(	Dataframez
    This component displays a table of value spreadsheet-like component. Can be used to display data as an output component, or as an input to collect data from the user.
    Demos: filter_records, matrix_transpose, tax_calculator, sort_records
    N)   dynamicstrpandasi     TvalueFnone)r#   	row_count	col_countdatatypetypelatex_delimiterslabel
show_labeleveryinputs
max_heightscale	min_widthinteractivevisibleelem_idelem_classesrenderkeypreserved_by_keywrapline_breakscolumn_widthsshow_fullscreen_buttonshow_copy_buttonshow_row_numbers	max_charsshow_searchpinned_columnsstatic_columnsc                  || _         | j                  |      | _        |xs g | _        | j                  ||rt	        |      nd      | _        | j                  r0t        | j
                  t              r| j
                  d   df| _        | j                  || j
                  d          ||n2t        d| j
                  d   dz         D  cg c]  } t        |        c} | _        || _        g d}!||!vrt        d| d|!       |d	k(  rt               st        d
      || _        |ddddg}|| _        || _        || _        |xs g D "cg c]@  }"t        |"t              r)|"j)                  d      s|"j)                  d      s|"dk(  r|"n|" dB c}"| _        || _        || _        || _        || _        || _        || _        |It        |t              r9|d   dk(  r1|| j
                  d   kD  rt        d| d| j
                  d    d      t8        #| u  ||
||	||||||||||       |dk(  rd| _        y|dk(  rd| _        y|dk(  rd| _        yd| _        yc c} w c c}"w )a0  
        Parameters:
            value: Default value to display in the DataFrame. Supports pandas, numpy, polars, and list of lists. If a Styler is provided, it will be used to set the displayed value in the DataFrame (e.g. to set precision of numbers) if the `interactive` is False. If a Callable function is provided, the function will be called whenever the app loads to set the initial value of the component.
            headers: List of str header names. These are used to set the column headers of the dataframe if the value does not have headers. If None, no headers are shown.
            row_count: Limit number of rows for input and decide whether user can create new rows or delete existing rows. The first element of the tuple is an `int`, the row count; the second should be 'fixed' or 'dynamic', the new row behaviour. If an `int` is passed the rows default to 'dynamic'
            col_count: Limit number of columns for input and decide whether user can create new columns or delete existing columns. The first element of the tuple is an `int`, the number of columns; the second should be 'fixed' or 'dynamic', the new column behaviour. If an `int` is passed the columns default to 'dynamic'
            datatype: Datatype of values in sheet. Can be provided per column as a list of strings, or for the entire sheet as a single string. Valid datatypes are "str", "number", "bool", "date", and "markdown".
            type: Type of value to be returned by component. "pandas" for pandas dataframe, "numpy" for numpy array, "polars" for polars dataframe, or "array" for a Python list of lists.
            label: the label for this component. Appears above the component and is also used as the header if there are a table of examples for this component. If None and used in a `gr.Interface`, the label will be the name of the parameter this component is assigned to.
            latex_delimiters: A list of dicts of the form {"left": open delimiter (str), "right": close delimiter (str), "display": whether to display in newline (bool)} that will be used to render LaTeX expressions. If not provided, `latex_delimiters` is set to `[{ "left": "$$", "right": "$$", "display": True }]`, so only expressions enclosed in $$ delimiters will be rendered as LaTeX, and in a new line. Pass in an empty list to disable LaTeX rendering. For more information, see the [KaTeX documentation](https://katex.org/docs/autorender.html). Only applies to columns whose datatype is "markdown".
            label: the label for this component. Appears above the component and is also used as the header if there are a table of examples for this component. If None and used in a `gr.Interface`, the label will be the name of the parameter this component is assigned to.
            show_label: if True, will display label.
            every: Continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.
            inputs: Components that are used as inputs to calculate `value` if `value` is a function (has no effect otherwise). `value` is recalculated any time the inputs change.
            max_height: The maximum height of the dataframe, specified in pixels if a number is passed, or in CSS units if a string is passed. If more rows are created than can fit in the height, a scrollbar will appear.
            scale: relative size compared to adjacent Components. For example if Components A and B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide as B. Should be an integer. scale applies in Rows, and to top-level Components in Blocks where fill_height=True.
            min_width: minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first.
            interactive: if True, will allow users to edit the dataframe; if False, can only be used to display data. If not provided, this is inferred based on whether the component is used as an input or output.
            visible: If False, component will be hidden.
            elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
            elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles.
            render: If False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.
            key: in a gr.render, Components with the same key across re-renders are treated as the same component, not a new component. Properties set in 'preserved_by_key' are not reset across a re-render.
            preserved_by_key: A list of parameters from this component's constructor. Inside a gr.render() function, if a component is re-rendered with the same key, these (and only these) parameters will be preserved in the UI (if they have been changed by the user or an event listener) instead of re-rendered based on the values provided during constructor.
            wrap: If True, the text in table cells will wrap when appropriate. If False and the `column_width` parameter is not set, the column widths will expand based on the cell contents and the table may need to be horizontally scrolled. If `column_width` is set, then any overflow text will be hidden.
            line_breaks: If True (default), will enable Github-flavored Markdown line breaks in chatbot messages. If False, single new lines will be ignored. Only applies for columns of type "markdown."
            column_widths: An optional list representing the width of each column. The elements of the list should be in the format "100px" (ints are also accepted and converted to pixel values) or "10%". The percentage width is calculated based on the viewport width of the table. If not provided, the column widths will be automatically determined based on the content of the cells.
            show_fullscreen_button: If True, will show a button to view the values in the table in fullscreen mode.
            show_copy_button: If True, will show a button to copy the table data to the clipboard.
            show_row_numbers: If True, will display row numbers in a separate column.
            max_chars: Maximum number of characters to display in each cell before truncating (single-clicking a cell value will still reveal the full content). If None, no truncation is applied.
            show_search: Show a search input in the toolbar. If "search", a search input is shown. If "filter", a search input and filter buttons are shown. If "none", no search input is shown.
            pinned_columns: If provided, will pin the specified number of columns from the left.
            static_columns: List of column indices (int) that should not be editable. Only applies when interactive=True. When specified, col_count is automatically set to "fixed" and columns cannot be inserted or deleted.
           r   fixedNr-   )r0   numpyarrayr   z$Invalid value for parameter `type`: z. Please choose from one of: r   zCPolars is not installed. Please install using `pip install polars`.z$$T)leftrightdisplaypx%autozpinned_columns (z-) cannot exceed the total number of columns (z) when using fixed columns)r9   r;   r<   r:   r>   r?   r@   rA   rB   rC   rD   rE   rF   r2   r0   za pandas dataframerU   za list of listsrT   za numpy arrayza polars dataframe)rG   _Dataframe__process_countsr4   rP   lenr5   
isinstancetuple_Dataframe__validate_headersranger/   r#   r6   
ValueErrorr   ImportErrorr7   r8   r=   rH   endswithrI   rJ   rK   rL   rM   rN   rO   super__init___value_description)$selfr2   r#   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   ivalid_typesw	__class__s$                                      r   rf   zDataframe.__init__>   s   d 	..y9,2..ws7|A
 :dnne#D"nnQ/9DN):; " #(DNN1,=,A#BDQ#a&D 	
 !<{"6tf<YZeYfg  8$8$:U  	#)- NO 0$& $)r

  !S!D!QZZ_V  3b
 '=# 0 0"&,&9e,!'!22">"22_`d`n`nop`q_r  sM  N  	!#%- 	 	
$ x ! 	 w # 	 w ! 	 & 	s E&
s   IAIc                   ddl }| j                  dk(  rb|j                  : |j                  |j                  g gk(  rg n|j                  |j                        S  |j                  |j                        S | j                  dk(  rjt               }|j                  9|j                  |j                  g gk(  rg n|j                  |j                        S |j                  |j                        S | j                  dk(  rt        j                  |j                        S | j                  dk(  r|j                  S t        d	t        | j                        z   d
z         )a  
        Parameters:
            payload: the uploaded spreadsheet data as an object with `headers` and `data` attributes. Note that sorting the columns in the browser will not affect the values passed to this function.
        Returns:
            Passes the uploaded spreadsheet data as a `pandas.DataFrame`, `numpy.array`, `polars.DataFrame`, or native 2D Python `list[list]` depending on `type`
        r   Nr0   columnsr   )schemarT   rU   zUnknown type: z;. Please choose from: 'pandas', 'numpy', 'array', 'polars'.)
r0   r7   r#   	DataFramer$   r    nprU   rb   r/   )rh   payloadpdr   s       r   
preprocesszDataframe.preprocess   s+    	99 *#r||!,,2$.BGLL#OO 
 $r||GLL1199 #%F*''!,,2$.BGLL (   ''559988GLL))YY'!<< dii.!OP r   c                n   ddl }ddlm} | yt        | |j                        r| j
                  S t        | |      r| j                  j
                  S t        | t        j                        r| j                  dk(  S t               r.t        | t               j                        r| j                         S t        | t              r@t        |       dkD  r$t        | d   t              rt        | d         dk(  S t        |       dk(  S t        | t              r#d| v rt        | d         dk(  S t        |       dk(  S y)zI
        Checks if the value of the dataframe provided is empty.
        r   Nr   Tr$   F)r0   pandas.io.formats.styler   r^   rq   emptyr$   rr   ndarraysizer   r    is_emptylistr]   dict)r2   rt   r   s      r   r{   zDataframe.is_empty	  s     	2=eR\\*;;v&::###rzz*::?"!#
5.:J:T:T(U>>##t$5zA~*U1Xt"<58}))u:?"t$5=)Q..u:?"r   c                :   ddl }ddlm} |g S t        ||j                        rt        |j                        S t        ||      rt        |j                  j                        S t        |t              r%t         |j                  |      j                        S t               r3t        |t               j                        rt        |j                        S t        |t              r|j                  dg       S t        |t
        t        j                  f      rg S g S )z
        Returns the headers of the dataframes based on the value provided. For values
        that do not have headers, an empty list is returned.
        r   Nr   r#   )r0   rw   r   r^   rq   r|   ro   r$   r/   read_csvr   r    r}   getrr   ry   )rh   r2   rt   r   s       r   get_headerszDataframe.get_headers/  s      	2=IeR\\*&&v&

**++s#E*2233!#
5.:J:T:T(U&&t$99Y++bjj12I	r   c                d   ddl }ddlm} t        | t              r| j                  dg g      S t        | t        |j                  f      r7t        | t              r |j                  |       } | j                  d      d   S t        | |      rm| j                  }t        | dg       }t        |j                        D cg c]  \  }}||vs| }}}|j                  dd|f   }|j                  d      d   S t               rOt        | t!               j                        r1| j                         }t#        t%        |j'                                }	|	S t        | t(        j*                  t"        f      rt        | t(        j*                        r| j-                         } t        | t"              st/        d      t        | d   t"              s=t        | d   t0              r| D 
cg c]  }
t#        |
       c}
S | D 
cg c]  }
|
g c}
S | S t/        d	t3        |        d
      c c}}w c c}
w c c}
w )zR
        Gets the cell data (as a list of lists) from the value provided.
        r   Nr   r$   splitorienthidden_columnsz"output cannot be converted to listzCannot process value of type z in gr.Dataframe)r0   rw   r   r^   r}   r   r/   rq   r   to_dictr$   getattr	enumeratero   ilocr   r    r|   zipvaluesrr   ry   tolistrb   r_   r7   )r2   rt   r   dfr   ri   _visible_colsdf_dictr$   vs              r   get_cell_datazDataframe.get_cell_dataR  s    	2eT"99VbT**ec2<<01%%#E*===088v&$zzB$U,<bAN'

3aq7NL  L)B::W:-f55!#
5.:J:T:T(UmmoGW^^-./DK

D12%,eT* !EFFeAh-eAh.-23DG33%*+++L/U}<LM )  4+s   >H"H""H(;
H-c           	         ddl m} t        | |      r8t        j	                  | t        | dg       D cg c]  }t        |       c}      S t        | t              r| j                  dd      S yc c}w )z<
        Gets the metadata from the value provided.
        r   r   r   r%   N)	rw   r   r^   r,   _Dataframe__extract_metadatar   intr}   r   )r2   r   cs      r   get_metadatazDataframe.get_metadata  sh     	3eV$//7G(LM1AM  t$99Z..	 Ns   A.
c                   ddl }ddlm} t        ||      r@t	        j
                  |j                        t	        j
                  d      k  rt        d      t        ||      r!| j                  rt        j                  d       | j                  |      xs | j                  }| j                  |      rg n| j                  |      }t        |      dk(  rt!        |g d      S t        |      t        |d         kD  r|dt        |d          }n\t        |      t        |d         k  rBg |t#        t        |      dz   t        |d         dz         D cg c]  }t%        |       c}}| j'                  |      }t!        |||      S c c}w )	a  
        Parameters:
            value: Expects data in any of these formats: `pandas.DataFrame`, `pandas.Styler`, `numpy.array`, `polars.DataFrame`, `list[list]`, `list`, or a `dict` with keys 'data' (and optionally 'headers'), or `str` path to a csv, which is rendered as the spreadsheet.
        Returns:
            the uploaded spreadsheet data as an object with `headers` and `data` keys and optional `metadata` key
        r   Nr   z1.5.0zStyler objects are only supported in pandas version 1.5.0 or higher. Please try: `pip install --upgrade pandas` to use this feature.zeCannot display Styler object in interactive mode. Will display as a regular pandas dataframe instead.)r#   r$   r%   r-   )r0   rw   r   r^   semantic_versionVersion__version__rb   r@   warningswarnr   r#   r{   r   r]   r"   ra   r/   r   )rh   r2   rt   r   r#   r$   ri   r%   s           r   postprocesszDataframe.postprocess  ss   $ 	2eV$)9)A)ANN*
$$W-*.  W  eV$)9)9MMw ""5)9T\\]]5)rt/A/A%/Ht9> rDIIw<#d1g,&nDG-G\CQL("'Gq(8#d1g,:J"KLQ#a&LG $$U+
 	
 Ms   F
c           	        | j                         j                  d d       }|j                  dg       }i }|D ]D  }|j                  dg       D ]-  }dj                  d |j                  dg       D              ||<   / F |t	        |      n	t	               }g g d}|d   D ]  }	g }
g }|	D cg c]  }|d   d	k(  s| }}t        |      D cg c]  \  }}||vr| }}}|D ]:  }|
j                  |d
          |j                  |j                  |d   d             < |d
   j                  |
       |d   j                  |        |S c c}w c c}}w )N	cellstyle	selectorsz; c              3  0   K   | ]  \  }}| d |   yw)z: Nr*   ).0propr2   s      r   	<genexpr>z/Dataframe.__extract_metadata.<locals>.<genexpr>  s$      1+64tfBug&1s   props)display_valuestylingbodyr7   tdr   id r   )_compute
_translater   joinsetr   append)r   hidden_cols
style_datacell_styles
style_dictstyleselectorhidden_cols_setr%   rowrow_displayrow_stylingcellcellscol_idxs                  r   __extract_metadatazDataframe.__extract_metadata  s    [[]--dD9
 nn["5
  	E!IIk26 '+yy 1:?))GR:P1 (
8$	
 /:.E#k*35%'B7f% 	4CKK '*BdT&\T-ATBEB &/u%5!GT/1 E 
  C""4#89"":>>$t*b#ABC _%,,[9Y&&{3	4   Cs   *E
8E
Ec                X    | |dfS t        | t        t        f      rt        |       dfS | S )Nr.   )r^   r   float)countdefaults     r   __process_countszDataframe.__process_counts  s4    =Y''ec5\*J	**Lr   c                \    | *t        |       |k7  rt        d| dt        |        d      y y )Nz^The length of the headers list must be equal to the col_count int.
The column count is set to z but `headers` has z= items. Check the values passed to `col_count` and `headers`.)r]   rb   )r#   r5   s     r   __validate_headerszDataframe.__validate_headers  sK    3w<9#<..7[8KCPWL> ZHI  $=r   c                    dd l }|y| j                  |      } |j                  |j                  |j                        }|j                  d      j                  d      d   S )	Nr   r   rn      )nr   r   r$   )r0   r   rq   r$   r#   headr   )rh   r2   rt   value_df_datavalue_dfs        r   process_examplezDataframe.process_example  sa     	=((/2<< 2 2M<Q<QR}}q}!)))9&AAr   c                    ddgddggdS Nabfoobar)r#   r$   r*   rh   s    r   example_payloadzDataframe.example_payload      :/?@@r   c                    ddgddggdS r   r*   r   s    r   example_valuezDataframe.example_value  r   r   )N)>r2   zdpd.DataFrame | Styler | np.ndarray | pl.DataFrame | list | list[list] | dict | str | Callable | Noner#   list[str] | Noner4   zint | tuple[int, str]r5   zint | tuple[int, str] | Noner6   zLiteral['str', 'number', 'bool', 'date', 'markdown', 'html', 'image'] | Sequence[Literal['str', 'number', 'bool', 'date', 'markdown', 'html']]r7   z-Literal['pandas', 'numpy', 'array', 'polars']r8   z"list[dict[str, str | bool]] | Noner9   zstr | I18nData | Noner:   bool | Noner;   zTimer | float | Noner<   z7Component | Sequence[Component] | set[Component] | Noner=   z	int | strr>   
int | Noner?   r   r@   r   rA   r   rB   z
str | NonerC   list[str] | str | NonerD   r   rE   z(int | str | tuple[int | str, ...] | NonerF   r   rG   r   rH   r   rI   zlist[str | int] | NonerJ   r   rK   r   rL   r   rM   r   rN   z#Literal['none', 'search', 'filter']rO   r   rP   list[int] | None)rs   r"   returnz5pd.DataFrame | np.ndarray | pl.DataFrame | list[list])r2   Ypd.DataFrame | Styler | np.ndarray | pl.DataFrame | list | list[list] | dict | str | Noner   r   )r2   r   r   z	list[str])r2   r   r   zlist[list[Any]])r2   r   r   zdict[str, list[list]] | None)r2   r   r   r"   )r   r   r   r   r   zdict[str, list[list]])rR   )r   ztuple[int, str])r#   r   r5   r   )r2   r   )r   r   )r&   r'   r(   __doc__r   changeinputselectEVENTSr"   
data_modelrf   ru   staticmethodr{   r   r   r   r   r   r\   r`   r   r   r   __classcell__)rl   s   @r   r,   r,   3   sC   
 mmV\\6==9FJ c
 %)+926 >F?C'+"&&*JN # #'"/38<3: 04',!&!& $;A%)+/[c
	c
 "c
 )c
 0c
 
!c
( <)c
* =+c
, %-c
.  /c
0 $1c
2 H3c
4 5c
6 7c
8 9c
: !;c
< =c
> ?c
@ -Ac
B Cc
D 6Ec
F 1Gc
H Ic
J Kc
L .Mc
N !%Oc
P Qc
R Sc
T Uc
V 9Wc
X #Yc
Z )[c
J$$$	>$L ## 
# #J!! 
!F 00 
0 0d  
& 00
0
 
0
d 48!1	 @    BB(AAr   r,   )&r   
__future__r   r   collections.abcr   r   typingr   r   r   r	   r
   rT   rr   r   gradio_client.documentationr   gradio.components.baser   gradio.data_classesr   gradio.eventsr   gradio.i18nr   r0   rt   r   r   rw   r   gradio.componentsr   r   r    r"   r,   r*   r   r   <module>r      sz     "  .    0 , +    .'>K > 
gA	 gA gAr   