
    +jRS                    H   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mZm	Z	 ddl
mZ ddlmZmZmZ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mZ ddlmZ ddlm Z  erddl!m"Z"  ej#        dej$                  Z%ddZ& e             G d dee                      Z'dS )zgr.HTML() component.    )annotationsN)CallableSequence)partial)TYPE_CHECKINGAnyLiteralcast)document)BlockContext)	Componentserver)Button)EventListener
all_events)I18nData)set_default_buttons)Timerz<script[\s>]contentr   returnNonec                    t          | t                    r8t                              |           r t	          j        dt          d           dS dS dS )a  Warn if `content` contains a `<script>` tag.

    `gr.HTML` renders its content via the DOM's `innerHTML`, which does not
    execute `<script>` tags. Users often expect inline or `src` scripts to run,
    so we surface a warning pointing them at the `head` / `js_on_load` params.
    a  A `<script>` tag was found in the content of a `gr.HTML` component. Browsers do not execute `<script>` tags inserted via `innerHTML`, so this script will not run. Use the `head` parameter to load external libraries (e.g. `head='<script src="..."></script>'`); `head` content is injected and loaded before `js_on_load` runs. Then, if needed, put code that uses those libraries in the `js_on_load` parameter, which executes when the component renders. See https://gradio.app/guides/custom-HTML-components for details.   )
stacklevelN)
isinstancestr_SCRIPT_TAG_PATTERNsearchwarningswarnUserWarning)r   s    Z/home/wildlama/visual-decline/.venv/lib/python3.11/site-packages/gradio/components/html.py_warn_if_script_tagr#      sq     '3 
$7$>$>w$G$G 
L 	
 	
 	
 	
 	
 	

 
 
 
    c                       e Zd ZdZeZ	 dHddddddddddddddddddddddddd	dId1ZdJd3ZdJd4ZdKd6Z	dLd7Z
dMd9Zed:             ZdM fd;ZdNd=Zd> Z	 	 	 	 	 	 dOdPdDZ	 	 	 	 	 	 	 dQdRdFZdSdGZ xZS )THTMLaD  
    Creates a component with arbitrary HTML. Can include CSS and JavaScript to create highly customized and interactive components.
    Example:
        ```python
        import gradio as gr

        with gr.Blocks() as demo:
            basic_html = gr.HTML("<h2>This is a basic HTML component</h2>")

            button_set = gr.HTML(["Option 1", "Option 2", "Option 3"],
                           html_template="{{#each value}}<button class='option-btn'>{{this}}</button>{{/each}}",
                           css_template="button { margin: 5px; padding: 10px; }",
                           js_on_load="element.querySelectorAll('.option-btn').forEach(btn => { btn.addEventListener('click', () => { trigger('click', {option: btn.innerText}); }); });")
            clicked_option = gr.Textbox(label="Clicked Option")
            def on_button_click(evt: gr.EventData):
                return evt.option
            button_set.click(on_button_click, outputs=clicked_option)

        demo.launch()
        ```
    Demos: super_html
    Guides: custom-HTML-components, custom-CSS-and-JS
    Nz${value} zCelement.addEventListener('click', function() { trigger('click') });TFvalue)labelhtml_templatecss_template
js_on_loadapply_default_csseveryinputs
show_labelscale	min_widthvisibleelem_idelem_classesrenderkeypreserved_by_key
min_height
max_height	containerpadding
autoscrollbuttonsheadserver_functionsAny | Callable | Noner)   str | I18nData | Noner*   r   r+   r,   
str | Noner-   boolr.   Timer | float | Noner/   7Component | Sequence[Component] | set[Component] | Noner0   r1   
int | Noner2   r3   bool | Literal['hidden']r4   r5   list[str] | str | Noner6   r7   (int | str | tuple[int | str, ...] | Noner8   r9   r:   r;   r<   r=   r>   list[Button] | Noner?   r@   list[Callable] | Nonepropsr   c               :   t          |           || _        || _        || _        || _        || _        || _        || _        || _        || _	        || _
        | j        j        | _        t          j        | ||||||           t!          j        | ||||	|||||||||
|           t#          |d          | _        |r]|D ]\}t'          |          }t)          |dt+          |                    }t-          | ||           | j                            |           [dS dS )a  
        Parameters:
            value: The HTML content in the ${value} tag in the html_template. For example, if html_template="<p>${value}</p>" and value="Hello, world!", the component will render as `"<p>Hello, world!</p>"`.
            label: The label for this component. Is 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.
            html_template: A string representing the HTML template for this component as a JS template string and Handlebars template. The `${value}` tag will be replaced with the `value` parameter, and all other tags will be filled in with the values from `props`. This element can have children when used in a `with gr.HTML(...):` context, and the children will be rendered to replace `@children` substring, which cannot be nested inside any HTML tags.
            css_template: A string representing the CSS template for this component as a JS template string and Handlebars template. The CSS will be automatically scoped to this component, and rules outside a block will target the component's root element. The `${value}` tag will be replaced with the `value` parameter, and all other tags will be filled in with the values from `props`.
            js_on_load: A string representing the JavaScript code that will be executed when the component is loaded. The `element` variable refers to the HTML element of this component, and can be used to access children such as `element.querySelector()`. The `trigger` function can be used to trigger events, such as `trigger('click')`. The value and other props can be edited through `props`, e.g. `props.value = "new value"` which will re-render the HTML template. If `server_functions` is provided, a `server` object is also available in `js_on_load`, where each function is accessible as an async method, e.g. `server.list_files(path).then(files => ...)` or `const files = await server.list_files(path)`. The `upload` async function can be used to upload a JavaScript `File` object to the Gradio server, returning a dictionary with `path` (the server-side file path) and `url` (the public URL to access the file), e.g. `const { path, url } = await upload(file)`. The `watch` function can be used to observe prop changes when the component is an output to a Python event listener: `watch('value', () => { ... })` runs the callback after the template re-renders whenever `value` changes, or `watch(['value', 'color'], () => { ... })` to watch multiple props.`.
            apply_default_css: If True, default Gradio CSS styles will be applied to the HTML component.
            head: A raw HTML string to inject into the document `<head>` before `js_on_load` runs. Typically used for `<script>` and `<link>` tags to load third-party libraries. Scripts are deduplicated by `src` and links by `href`, so multiple components requiring the same library won't load it twice.
            every: Continuously 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.
            show_label: If True, the label will be displayed. If False, the label will be hidden.
            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.
            visible: If False, component will be hidden. If "hidden", component will be visually hidden and not take up space in the layout but still exist in the DOM
            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.
            min_height: The minimum height of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. If HTML content exceeds the height, the component will expand to fit the content.
            max_height: The maximum height of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. If content exceeds the height, the component will scroll.
            container: If True, the HTML component will be displayed in a container. Default is False.
            padding: If True, the HTML component will have a certain padding (set by the `--block-padding` CSS variable) in all directions. Default is False.
            autoscroll: If True, will automatically scroll to the bottom of the component when the content changes, unless the user has scrolled up. If False, will not scroll to the bottom when the content changes.
            buttons: A list of gr.Button() instances to show in the top right corner of the component. Custom buttons will appear in the toolbar with their configured icon and/or label, and clicking them will trigger any .click() events registered on the button.
            server_functions: A list of Python functions that can be called from `js_on_load` via the `server` object. For example, if you pass `server_functions=[my_func]`, you can call `server.my_func(arg1, arg2)` in your `js_on_load` code. Each function becomes an async method that sends the call to the Python backend and returns the result.
            props: Additional keyword arguments to pass into the HTML and CSS templates for rendering.
        )r3   r4   r5   r6   r7   r8   )r)   r.   r/   r0   r3   r4   r5   r6   r7   r8   r(   r;   r1   r2   N__name__)r#   r*   r+   r,   r-   r?   r9   r:   r<   r=   rM   	__class__rO   component_class_namer   __init__r   r   r>   r   getattrr   setattr
server_fnsappend)selfr(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rM   fn	decoratedfn_names                                 r"   rR   zHTML.__init__N   sl   | 	M****($!2	$$$
$(N$;!%-	
 	
 	
 	
 	!%-	
 	
 	
 	
" +7D99 	2& 2 2"2JJ	!"j#b''::gy111&&y1111	2 	22 2r$   r   c                    dS Nz<p>Hello</p> rW   s    r"   example_payloadzHTML.example_payload       ~r$   c                    dS r\   r]   r^   s    r"   example_valuezHTML.example_value   r`   r$   payloadc                    |S )z
        Parameters:
            payload: string corresponding to the HTML
        Returns:
            (Rarely used) passes the HTML as a `str`.
        r]   )rW   rc   s     r"   
preprocesszHTML.preprocess   s	     r$   c                $    t          |           |S )z
        Parameters:
            value: Expects a `str` consisting of valid HTML.
        Returns:
            Returns the HTML string.
        )r#   )rW   r(   s     r"   postprocesszHTML.postprocess   s     	E"""r$   dict[str, Any]c                
    ddiS )Ntypestringr]   r^   s    r"   api_infozHTML.api_info   s    !!r$   c                    dS )NFr]   r^   s    r"   skip_apizHTML.skip_api   s    ur$   c                   t          |           t          urIi t                                                      t                                          t                    }n t                                                      }| j        |d<   |S )NrQ   )rj   r&   super
get_configrQ   )rW   configrP   s     r"   rq   zHTML.get_config   s{    ::T!!''$$&&''$$T**FF
 WW''))F *.)B%&r$   namec                :   | j                             d          pd}dt          j        |           d}t          j        ||          r%t          |          }t          |j        |           S t          dt          |           j
         d| d| d| d		          )
Nr,   r'   z	(?:['"`]))
event_name'z' object has no attribute 'z'. If 'z+' is a custom event, make sure to include 'z0' (enclosed in quotes) in the js_on_load string.)__dict__getreescaper   r   r   listenerAttributeErrorrj   rO   )rW   rs   jspatterntriggers        r"   __getattr__zHTML.__getattr__   s    ]|,,2=4===9Wb!! 	3#t444G7+T222>T

# > > > >> >DH> > >
 
 	
r$   c                    dS )Nhtmlr]   r^   s    r"   get_block_namezHTML.get_block_name   s    vr$   descriptionauthortagslist[str] | Nonerepo_urlc                *   |]t          |           t          ur)t          j        ddt          |           j                  }n| j        rt          | j                  }nd}t          j        dd|                                                              d          }t          |           t          urN	 t          j
        t          j        t          |                               }n-# t          t          f$ r d}Y nw xY w|                                 }i }	| j        | j        nd|	d<   | j        t          | j                  |	d	<   |	                    | j                   ||||||ng | j        | j        | j        pd|	||p| j        pdd
}
|r||
d<   |
S )ad  Convert this HTML component to the format expected by the HTML Components Gallery
        (https://www.gradio.app/custom-components/html-gallery).

        Parameters:
            name: Display name for the component. Defaults to the class name (for subclasses) or label.
            description: Short description of what the component does.
            author: Author name.
            tags: List of tags for search/filtering.
            repo_url: URL to the source repo (GitHub or HuggingFace Spaces).
        Returns:
            A dictionary matching the HTMLComponentEntry format for the gallery.
        Nz(?<!^)(?=[A-Z]) zUntitled Componentz
[^a-z0-9]+-r'   r(   r)   )idrs   r   r   r   r*   r+   r,   default_propspython_coder?   r   )rj   r&   ry   subrO   r)   r   lowerstriptextwrapdedentinspect	getsourceOSError	TypeError_generate_constructor_coder(   updaterM   r*   r+   r,   r?   )rW   rs   r?   r   r   r   r   comp_idr   r   results              r"   _to_publish_formatzHTML._to_publish_format   s   * <Dzz%%v0#tDzz7JKK ,4:+&TZZ\\::@@EE::T!!!&og.?T

.K.KLLY' ! ! ! ! 99;;K(*/3z/E2g:!%(__M'"TZ((( & ,DD"!/ -//R*&+DI+
 
  	*!)F:s   23C& &C<;C<tokenc                z   ddl }ddlm}	m}
m} |                     ||p| j        ||||          d         |                    d                              d          }g d	}fd
|D             } |
|          }	  |ddd|          }t          |          5 }|
                    |          }ddd           n# 1 swxY w Y   n# t          $ r g }Y nw xY wfd|D             }|                    |           |                    |d                              d          }|                    dd |	d d|           |	d|          gdd          dd          dd          dd          d          }t          d|j        pd            t!          t"          |j                  S )a  Push this HTML component to the HTML Components Gallery as a pull request.

        Creates a JSON file in the `components/` directory of the dataset repo
        and opens a pull request for review.

        Parameters:
            name: Display name for the component. Defaults to the class name (for subclasses) or label.
            head: Raw HTML to inject into `<head>` (e.g. external scripts). Only needed if your component expects a `<head>` script to be added by the parent Gradio application.
            description: Short description of what the component does.
            author: Author name (e.g. your HuggingFace username).
            tags: List of tags for search/filtering.
            category: One of "input", "display", or "form".
            repo_url: URL to the source repo (GitHub or HuggingFace Spaces).
            token: HuggingFace token. If None, uses the cached token from `huggingface-cli login`.
        Returns:
            The URL of the created pull request.
        r   N)CommitOperationAddHfApihf_hub_download)rs   r?   r   r   r   r   r   r   )indentzutf-8)r   rs   r   r   r   r   c                *    i | ]}|v ||         S r]   r]   ).0kdatas     r"   
<dictcomp>z$HTML.push_to_hub.<locals>.<dictcomp>g  s$    IIIqDyy!T!Wyyyr$   )r   zgradio/custom-html-gallerydatasetzmanifest.json)repo_id	repo_typefilenamer   c                F    g | ]}|                     d           k    |S )r   )rx   )r   er   s     r"   
<listcomp>z$HTML.push_to_hub.<locals>.<listcomp>y  s-    BBB!155;;'+A+AA+A+A+Ar$   zcomponents/z.json)path_in_repopath_or_fileobjzAdd component: rs   z**z**

r   z

Author: @r   T)r   r   
operationscommit_messagecommit_description	create_przPull request created: r'   )jsonhuggingface_hubr   r   r   r   r?   dumpsencodeopenload	ExceptionrV   create_commitprintpr_urlr
   r   )rW   rs   r?   r   r   r   r   r   r   r   r   r   
json_bytesmanifest_keysmanifest_entryapimanifest_pathfmanifestmanifest_bytescommitr   r   s                        @@r"   push_to_hubzHTML.push_to_hub4  s   6 	NNNNNNNNNN&&"# ' 
 
 t*ZZQZ//66w??

 
 
 JIIImIIIe%   
	+O4#(	  M m$$ (99Q<<( ( ( ( ( ( ( ( ( ( ( ( ( ( ( 	 	 	HHH	 CBBBxBBB'''HQ77>>wGG""0""!=w!=!=!=$.   #"!0$2  	 <T&\;;jDLjj]8KjjZ^_gZhjj # 
 
" 	<v}':<<===C'''s6   C "C8C CC CC CCc                P   dg}| j         |                    d| j         d           | j        +|                    dt          | j                  d           |                    d| j         d           | j        r|                    d| j         d           | j        r|                    d	| j         d           | j                                        D ]!\  }}|                    d
| d|d           "|                    d           d	                    |          S )zIGenerate a Python constructor call string for a plain gr.HTML() instance.zgr.HTML(Nz
    value=,z
    label=z    html_template="""
z	
    """,z    css_template="""
z    js_on_load="""
z    =)
)
r(   rV   r)   r   r*   r+   r,   rM   itemsjoin)rW   linesr   vs       r"   r   zHTML._generate_constructor_code  sF   :!LL5dj555666:!LL:c$*oo:::;;;Mt/AMMMNNN 	QLLO$2COOOPPP? 	MLLKKKKLLLJ$$&& 	, 	,DAqLL***A***++++Syyr$   )N)4r(   rA   r)   rB   r*   r   r+   r   r,   rC   r-   rD   r.   rE   r/   rF   r0   rD   r1   rG   r2   rG   r3   rH   r4   rC   r5   rI   r6   rD   r7   rJ   r8   rI   r9   rG   r:   rG   r;   rD   r<   rD   r=   rD   r>   rK   r?   rC   r@   rL   rM   r   )r   r   )rc   rC   r   rC   )r(   rC   r   rC   )r   rh   )rs   r   )NNr'   r'   NN)rs   rC   r?   rC   r   r   r   r   r   r   r   rC   r   rh   )NNr'   r'   NNN)rs   rC   r?   rC   r   r   r   r   r   r   r   rC   r   rC   r   r   )r   r   )rO   
__module____qualname____doc__r   EVENTSrR   r_   rb   re   rg   rl   propertyrn   rq   r   r   r   r   r   __classcell__)rP   s   @r"   r&   r&   2   s        0 F (,j2 (,'V"&&*JN   $,0"/38<3:!%!% '+269j2 j2 j2 j2 j2 j2X            " " " "   X     

 

 

 

  
  !%#< < < < <@  !%# [( [( [( [( [(z               r$   r&   )r   r   r   r   )(r   
__future__r   r   ry   r   r   collections.abcr   r   	functoolsr   typingr   r   r	   r
   gradio_client.documentationr   gradio.blocksr   gradio.components.baser   r   gradio.components.buttonr   gradio.eventsr   r   gradio.i18nr   gradio.utilsr   gradio.componentsr   compile
IGNORECASEr   r#   r&   r]   r$   r"   <module>r      s     " " " " " "  				   . . . . . . . .       4 4 4 4 4 4 4 4 4 4 4 4 0 0 0 0 0 0 & & & & & & 4 4 4 4 4 4 4 4 + + + + + + 3 3 3 3 3 3 3 3             , , , , , , ('''''' bj"-@@ 
 
 
 
, 
m  m  m  m  m < m  m  m  m  m r$   