
    ;3h<                       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Zd dlZd dl	m
Z
mZ d dlmZ d dlmZ d dlmZ d dlmZmZ d dlmZ d d	lmZ d dlZd d
lmZmZ d dlmZ erd dlm Z   G d de
      Z! e        G d de!             Z" e        G d de!             Z# e        G d de!             Z$ G d d      Z% G d d      Z&y)    )annotationsN)ABCabstractmethod)Sequence)Lock)Path)TYPE_CHECKINGAny)utils)document)r   
wasm_utils)LikeData)	Componentc                  H    e Zd ZdZedd       Ze	 	 d	 	 	 	 	 	 	 dd       Zy)FlaggingCallbackz[
    An abstract class for defining the methods that any FlaggingCallback should have.
    c                     y)a  
        This method should be overridden and ensure that everything is set up correctly for flag().
        This method gets called once at the beginning of the Interface.launch() method.
        Parameters:
        components: Set of components that will provide flagged data.
        flagging_dir: A string, typically containing the path to the directory where the flagging file should be stored (provided as an argument to Interface.__init__()).
        N self
componentsflagging_dirs      O/var/www/html/audio-gradio/venv/lib/python3.12/site-packages/gradio/flagging.pysetupzFlaggingCallback.setup    s     	    Nc                     y)a  
        This method should be overridden by the FlaggingCallback subclass and may contain optional additional arguments.
        This gets called every time the <flag> button is pressed.
        Parameters:
        interface: The Interface object that is being used to launch the flagging interface.
        flag_data: The data to be flagged.
        flag_option (optional): In the case that flagging_options are provided, the flag option that is being used.
        username (optional): The username of the user that is flagging the data, if logged in.
        Returns:
        (int) The total number of samples that have been flagged.
        Nr   )r   	flag_dataflag_optionusernames       r   flagzFlaggingCallback.flag+   s    $ 	r   )r   Sequence[Component]r   strNNr   z	list[Any]r   
str | Noner   r$   returnint)__name__
__module____qualname____doc__r   r   r   r   r   r   r   r      s]        #'#	   	
 
 r   r   c                  :    e Zd ZdZd ZddZ	 	 d	 	 	 	 	 	 	 ddZy)	SimpleCSVLoggera  
    A simplified implementation of the FlaggingCallback abstract class
    provided for illustrative purposes.  Each flagged sample (both the input and output data)
    is logged to a CSV file on the machine running the gradio app.
    Example:
        import gradio as gr
        def image_classifier(inp):
            return {'cat': 0.3, 'dog': 0.7}
        demo = gr.Interface(fn=image_classifier, inputs="image", outputs="label",
                            flagging_callback=SimpleCSVLogger())
    c                     y Nr   r   s    r   __init__zSimpleCSVLogger.__init__N       r   c                N    || _         || _        t        j                  |d       y NTexist_okr   r   osmakedirsr   s      r   r   zSimpleCSVLogger.setupQ   s    $(
L40r   Nc                   | j                   }t        |      dz  }g }t        | j                  |d      D ]z  \  }}t        |      t	        j
                  |j                  t        |j                        nd      z  }	|	j                  d       |j                  |j                  ||	             | t        |ddd	      5 }
t        j                  |
      }|j                  t        j                   |             d d d        t        |d
      5 }
t#        t%        t        j&                  |
                  dz
  }d d d        |S # 1 sw Y   KxY w# 1 sw Y   S xY w)Nlog.csvFstrict Tr4   autf-8encodingnewlinerA      )r   r   zipr   client_utils!strip_invalid_filename_characterslabelr!   mkdirappendr   opencsvwriterwriterowr   sanitize_list_for_csvlenlistreader)r   r   r   r   r   log_filepathcsv_data	componentsamplesave_dircsvfilerM   
line_counts                r   r   zSimpleCSVLogger.flagV   s@    ((L)I5!$T__i!N 	Iv>>(1(CIOO$H
 NNDN)OO	 ,grB 	CgZZ(FOOE77AB	C ,1 	<WT#**W"567!;J	<	C 	C	<s   :E+EEEr   r    r   z
str | Pathr"   r#   r'   r(   r)   r*   r0   r   r   r   r   r   r,   r,   @   sD    
1 #'#	   	
 
r   r,   c                  F    e Zd ZdZdddZ	 	 	 	 ddZ	 	 d		 	 	 	 	 	 	 d
dZy)ClassicCSVLoggera  
    The classic implementation of the FlaggingCallback abstract class in gradio<5.0. Each flagged
    sample (both the input and output data) is logged to a CSV file with headers on the machine running the gradio app.
    Example:
        import gradio as gr
        def image_classifier(inp):
            return {'cat': 0.3, 'dog': 0.7}
        demo = gr.Interface(fn=image_classifier, inputs="image", outputs="label",
                            flagging_callback=ClassicCSVLogger())
    Guides: using-flagging
    c                    || _         y r.   )simplify_file_data)r   r_   s     r   r0   zClassicCSVLogger.__init__   s
    "4r   c                N    || _         || _        t        j                  |d       y r3   r6   r   s      r   r   zClassicCSVLogger.setup   s!    
 %(
L40r   Nc                   | j                   }t        |      dz  }t        |      j                          }t        | j                        D cg c]  \  }}t        |dd       xs d|  c}}g dz   }	g }
t        t        | j                  |d            D ]  \  }\  }}t        |      t        j                  t        t        |dd       xs d|             z  }t        j                  |      r|
j                  t        |             u||j                  ||      nd}| j                  rt        j                  |      }|
j                  |        |
j                  |       |
j                  ||nd       |
j                  t        t         j                   j#                                      t%        |d	dd
      5 }t'        j(                  |      }|r$|j+                  t        j,                  |	             |j+                  t        j,                  |
             d d d        t%        |d
      5 }t/        t1        t'        j2                  |                  dz
  }d d d        |S c c}}w # 1 sw Y   QxY w# 1 sw Y   S xY w)Nr:   rH   
component )r   r   	timestampFr;   flag_dirr=   r>   r?   rB   rA   rC   rD   )r   r   exists	enumerater   getattrrE   rF   rG   r!   r   is_prop_updaterJ   r   r_   simplify_file_data_in_strdatetimenowrK   rL   rM   rN   rO   rP   rQ   rR   )r   r   r   r   r   rS   is_newidxrU   headersrT   rV   rW   datarX   rM   rY   s                    r   r   zClassicCSVLogger.flag   sQ    ((L)I5,'..00 #,DOO"<
Y Iw-C:cU1CC


 (159)
 	&$C$)V >>GIw5K:cU9KLH
 ##F+F, ) NN6HN= 
 ** ::4@D%%	&& 	$H$8bAH--11345,R'B 	CgZZ(F ; ;G DEOOE77AB		C ,1 	<WT#**W"567!;J	<S
B	C 	C	<s   I,A I27+I>2I;>JT)r_   boolrZ   r"   r#   r[   r   r   r   r]   r]   w   sV    
51'1 !1 #'#	22  2 	2
 
2r   r]   c                  `    e Zd ZdZ	 	 	 d	 	 	 	 	 ddZ	 	 	 	 d	dZd
ddZ	 	 d	 	 	 	 	 	 	 ddZy)	CSVLoggera8  
    The default implementation of the FlaggingCallback abstract class in gradio>=5.0. Each flagged
    sample (both the input and output data) is logged to a CSV file with headers on the machine running
    the gradio app. Unlike ClassicCSVLogger, this implementation is concurrent-safe and it creates a new
    dataset file every time the headers of the CSV (derived from the labels of the components) change. It also
    only creates columns for "username" and "flag" if the flag_option and username are provided, respectively.

    Example:
        import gradio as gr
        def image_classifier(inp):
            return {'cat': 0.3, 'dog': 0.7}
        demo = gr.Interface(fn=image_classifier, inputs="image", outputs="label",
                            flagging_callback=CSVLogger())
    Guides: using-flagging
    Nc                    || _         || _        || _        t        j                  st               | _        yt        j                         | _        y)a  
        Parameters:
            simplify_file_data: If True, the file data will be simplified before being written to the CSV file. If CSVLogger is being used to cache examples, this is set to False to preserve the original FileData class
            verbose: If True, prints messages to the console about the dataset file creation
            dataset_file_name: The name of the dataset file to be created (should end in ".csv"). If None, the dataset file will be named "dataset1.csv" or the next available number.
        N)	r_   verbosedataset_file_namer   IS_WASMr   
contextlibnullcontextlock)r   r_   rw   rx   s       r   r0   zCSVLogger.__init__   sB     #5!2$,,DF 		2<2H2H2J 		r   c                @    || _         t        |      | _        d| _        y )NT)r   r   r   
first_timer   s      r   r   zCSVLogger.setup   s    
 % .r   c           	         t        j                  | j                  d       |g }t        | j                        D cg c]  \  }}t        |dd       xs d|  c}}|z   dgz   }t        j                  |      }t        t        | j                        j                  d            }| j                  r| j                  | j                  z  | _        n|r	 t        |d       }t        t        j                   d	|j"                        d
         }t%        |dd      5 }t'        j(                  |      }	t+        |	d       }
d d d        
|k7  r|dz   }| j                  d| dz  | _        n|| _        n| j                  dz  | _        t        | j                        j/                         st%        | j                  ddd      5 }t'        j0                  |      }|j3                  t        j                  |             d d d        | j4                  rt7        d| j                         y y | j4                  rt7        d| j                         y y c c}}w # 1 sw Y   xY w# t,        $ r | j                  dz  | _        Y w xY w# 1 sw Y   xY w)NTr4   rH   rb   rc   zdataset*.csvc                Z    t        t        j                  d| j                        d         S )N\d+r   )r&   refindallstem)fs    r   <lambda>z0CSVLogger._create_dataset_file.<locals>.<lambda>  s     RZZ5OPQ5R1S r   )keyr   r   r=   r?   rf   rD   datasetz.csvzdataset1.csvwzCreated dataset file at:zUsing existing dataset file at:)r7   r8   r   rh   r   ri   r   rO   rQ   r   globrx   dataset_filepathmaxr&   r   r   r   rK   rL   rR   next	Exceptionrg   rM   rN   rw   print)r   additional_headersro   rU   rp   dataset_fileslatest_file
latest_numrX   rR   existing_headersnew_numrM   s                r   _create_dataset_filezCSVLogger._create_dataset_file   sn   
D%%5%!# '0&@"C 	7D1Gz#5GG !	!  	 --g6T$"3"3499.IJ!!$($5$58N8N$ND!K!!'S !FK4D4D!Ea!HI
+rGD : ZZ0F'+FD'9$: $w.(1nG,0,=,=''RV@W,WD),7D) %)$5$5$FD!D))*113%%sB FG, ; ;G DE	F
 ||0$2G2GH \\3T5J5JK W*: :  K(,(9(9N(J%KF Fs<   IAI! "I2I! :JII! !J JJc                   | j                   rAg }||j                  d       ||j                  d       | j                  |       d| _         g }t        t	        | j
                  |d            D ]  \  }\  }}| j                  t        j                  t        t        |dd       xs d|             z  }	t        j                  |      r|j                  t        |             v||j                  ||	      nd	}
| j                  rt        j                  |
      }
|j                  |
        ||j                  |       ||j                  |       |j                  t        t         j                   j#                                      | j$                  5  t'        | j(                  d
d	d      5 }t+        j,                  |      }|j/                  t        j0                  |             d d d        t'        | j(                  d      5 }t3        t5        t+        j6                  |                  dz
  }d d d        d d d        S # 1 sw Y   ]xY w# 1 sw Y   xY w# 1 sw Y   S xY w)Nr   r   )r   Fr;   rH   rb   rd   r=   r>   r?   rf   rC   rD   )r~   rJ   r   rh   rE   r   r   rF   rG   r!   ri   r   rj   r   r_   rk   rl   rm   r|   rK   r   rL   rM   rN   rO   rP   rQ   rR   )r   r   r   r   r   rT   ro   rU   rV   rW   rq   rX   rM   rY   s                 r   r   zCSVLogger.flag(  s@    ??!#&"))&1#"))*5%%9K%L#DO(159)
 	&$C$)V !!@@	7D9Oz#=OP  ##F+F, ) NN6HN= 
 ** ::4@D%'	&* "OOK(OOH%H--11345YY 	@%%sB GG, ; ;H EF	G
 d++g> @' cjj&9!:;a?
@	@ G G
@ @	@ s<   I"4:I
.I"+I8I"
I	I"I	I""I,)TTN)r_   rs   rw   rs   rx   r$   rZ   r.   )r   zlist[str] | Noner"   r#   )r'   r(   r)   r*   r0   r   r   r   r   r   r   ru   ru      s    $ $((,	
 
 
 &	
&' !2Ln #'#	44  4 	4
 
4r   ru   c                  .    e Zd ZdZd ZddZ	 	 	 	 ddZy)ChatCSVLoggerz
    Flagging callback for chat conversations.
    Flagged conversations and like/dislike reactions are logged to a CSV file on the machine running the gradio app.
    c                     y r.   r   r/   s    r   r0   zChatCSVLogger.__init__e  r1   r   c                @    || _         t        j                  |d       y r3   )r   r7   r8   )r   r   s     r   r   zChatCSVLogger.setuph  s    (
L40r   c                b   | j                   }t        |      dz  }t        |      j                          }|j                  du rdn|j                  du rdn|j                  }t	        j
                  |      |j                  |t        t        j                  j                               g}t        |ddd	      5 }|r(t        j                  |      }	|	j                  g d
       t        j                  |      }	|	j                  t        j                  |             d d d        y # 1 sw Y   y xY w)Nr:   TLikeFDisliker>   r?   r=   r@   )conversationindexvaluer   rc   )r   r   rg   likedjsondumpsr   r!   rl   rm   rK   rL   rM   rN   r   rO   )
r   	like_datamessagesr   rS   rn   feedbackrT   rX   rM   s
             r   r   zChatCSVLogger.flagl  s
   
 ((L)I5,'..00 $&  %'  	 JJx OO!!%%'(	
 ,grB 	CgG, WXZZ(FOOE77AB	C 	C 	Cs   8A$D%%D.N)r   r!   )r   r   r   rQ   r[   r   r   r   r   r   _  s+    
1CC Cr   r   c                  8    e Zd ZdZ	 d	 	 	 	 	 	 	 ddZddZd Zy)	
FlagMethodz
    Helper class that contains the flagging options and calls the flagging method. Also
    provides visual feedback to the user when flag is clicked.
    c                J    || _         || _        || _        d| _        || _        y )NFlag)flagging_callbackrH   r   r'   visual_feedback)r   r   rH   r   r   s        r   r0   zFlagMethod.__init__  s)     "3

.r   c                H   	 | j                   j                  t        |      | j                  |j                         | j                  sy t        j                  d       | j                         S # t
        $ r)}t        d|        | j                  rY d }~yY d }~_d }~ww xY w)N)r   r   zError while flagging: zError!g?)r   r   rQ   r   r   r   r   r   timesleepreset)r   requestr   es       r   __call__zFlagMethod.__call__  s    	 ""''YTZZ'BRBR (  ##

3zz|  	 *1#./## $	 s   ;A/ /	B!8BB!c                D    t        j                  | j                  d      S )NT)r   interactive)grButtonrH   r/   s    r   r   zFlagMethod.reset  s    yytzzt<<r   Nrr   )r   r   rH   r!   r   r$   r   rs   )r   z
gr.Request)r'   r(   r)   r*   r0   r   r   r   r   r   r   r     sA     !%/+/ / 	/
 /=r   r   )'
__future__r   rz   rL   rl   r   r7   r   r   abcr   r   collections.abcr   multiprocessingr   pathlibr   typingr	   r
   gradio_clientr   rF   gradio_client.documentationr   gradior   r   gradio.eventsr   gradio.componentsr   r   r,   r]   ru   r   r   r   r   r   <module>r      s    "  
   	 	  # $    % / 0  $ "+"s "J 
3& 3 3l 
K' K K\ 
U  U Up)C )CX"= "=r   