gsarti's picture
Update v 0.0.6
09bd8f1
|
raw
history blame
12.9 kB

gradio_highlightedtextbox

PyPI - Version Static Badge

Editable Gradio textarea supporting highlighting

Installation

pip install gradio_highlightedtextbox

Usage

import gradio as gr
from gradio_highlightedtextbox import HighlightedTextbox


def convert_tagged_text_to_highlighted_text(
    tagged_text: str,
    tag_id: str | list[str],
    tag_open: str | list[str],
    tag_close: str | list[str],
) -> list[tuple[str, str | None]]:
    return HighlightedTextbox.tagged_text_to_tuples(
        tagged_text, tag_id, tag_open, tag_close
    )


def convert_highlighted_text_to_tagged_text(
    highlighted_text: dict[str, str | list[tuple[str, str | None]]],
    tag_id: str | list[str],
    tag_open: str | list[str],
    tag_close: str | list[str],
) -> str:
    return HighlightedTextbox.tuples_to_tagged_text(
        highlighted_text["data"], tag_id, tag_open, tag_close
    )


initial_text = "It is not something to be ashamed of: it is no different from the <d>personal fears</d> and <tm>dislikes</tm> of other things that <t>manny peopl</t> have."

with gr.Blocks() as demo:
    gr.Markdown("### Parameters to control the highlighted textbox:")
    with gr.Row():
        tag_id = gr.Dropdown(
            choices=["Typo", "Terminology", "Disfluency"],
            value=["Typo", "Terminology", "Disfluency"],
            multiselect=True,
            allow_custom_value=True,
            label="Tag ID",
            show_label=True,
            info="Insert one or more tag IDs to use in the highlighted textbox.",
        )
        tag_open = gr.Dropdown(
            choices=["<t>", "<tm>", "<d>"],
            value=["<t>", "<tm>", "<d>"],
            multiselect=True,
            allow_custom_value=True,
            label="Tag open",
            show_label=True,
            info="Insert one or more tags to mark the beginning of a highlighted section.",
        )
        tag_close = gr.Dropdown(
            choices=["</t>", "</tm>", "</d>"],
            value=["</t>", "</tm>", "</d>"],
            multiselect=True,
            allow_custom_value=True,
            label="Tag close",
            show_label=True,
            info="Insert one or more tags to mark the end of a highlighted section.",
        )
    gr.Markdown("### Example tagged to highlight:")
    with gr.Row():
        tagged_t2h = gr.Textbox(
            initial_text,
            interactive=True,
            label="Tagged Input",
            show_label=True,
            info="Tagged text using the format above to mark spans that will be highlighted.",
        )
        high_t2h = HighlightedTextbox(
            convert_tagged_text_to_highlighted_text(
                tagged_t2h.value, tag_id.value, tag_open.value, tag_close.value
            ),
            interactive=False,
            label="Highlighted Output",
            info="Highlighted textbox intialized from the tagged input.",
            show_legend=True,
            show_label=True,
            legend_label="Legend:",
            show_legend_label=True,
        )
    gr.Markdown("### Example highlight to tagged:")
    with gr.Row():
        high_h2t = HighlightedTextbox(
            convert_tagged_text_to_highlighted_text(
                initial_text, tag_id.value, tag_open.value, tag_close.value
            ),
            interactive=True,
            label="Highlighted Input",
            info="Highlighted textbox using the format above to mark spans that will be highlighted.",
            show_legend=True,
            show_label=True,
            legend_label="Legend:",
            show_legend_label=True,
        )
        tagged_h2t = gr.Textbox(
            initial_text,
            interactive=False,
            label="Tagged Output",
            info="Tagged text intialized from the highlighted textbox.",
            show_label=True,
        )

    # Functions

    tagged_t2h.input(
        fn=convert_tagged_text_to_highlighted_text,
        inputs=[tagged_t2h, tag_id, tag_open, tag_close],
        outputs=high_t2h,
    )
    high_h2t.input(
        fn=convert_highlighted_text_to_tagged_text,
        inputs=[high_h2t, tag_id, tag_open, tag_close],
        outputs=tagged_h2t,
    )

if __name__ == "__main__":
    demo.launch()

HighlightedTextbox

Initialization

name type default description
value
str | Callable | None
"" default text to provide in textbox. If callable, the function will be called whenever the app loads to set the initial value of the component.
color_map
dict[str, str] | None
None dictionary mapping labels to colors.
show_legend
bool
False if True, will display legend.
show_legend_label
bool
False if True, will display legend label.
legend_label
str
"" label to display above legend.
combine_adjacent
bool
False if True, will combine adjacent spans with the same label.
adjacent_separator
str
"" separator to use when combining adjacent spans.
label
str | None
None component name in interface.
info
str | None
None None
every
float | None
None If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
show_label
bool | None
None if True, will display label.
container
bool
True If True, will place the component in a container - providing some extra padding around the border.
scale
int | None
None relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer.
min_width
int
160 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
bool
True If False, component will be hidden.
elem_id
str | None
None An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
autofocus
bool
False None
autoscroll
bool
True If True, will automatically scroll to the bottom of the textbox when the value changes, unless the user scrolls up. If False, will not scroll to the bottom of the textbox when the value changes.
interactive
bool
True if True, will be rendered as an editable textbox; if False, editing will be disabled. If not provided, this is inferred based on whether the component is used as an input or output.
elem_classes
list[str] | str | None
None 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
bool
True 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.
show_copy_button
bool
False If True, includes a copy button to copy the text in the textbox. Only applies if show_label is True.

Events

name description
change Triggered when the value of the HighlightedTextbox changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See .input() for a listener that is only triggered by user input.
input This listener is triggered when the user changes the value of the HighlightedTextbox.
select Event listener for when the user selects or deselects the HighlightedTextbox. Uses event data gradio.SelectData to carry value referring to the label of the HighlightedTextbox, and selected to refer to state of the HighlightedTextbox. See EventData documentation on how to use this event data
submit This listener is triggered when the user presses the Enter key while the HighlightedTextbox is focused.
focus This listener is triggered when the HighlightedTextbox is focused.
blur This listener is triggered when the HighlightedTextbox is unfocused/blurred.

User function

The impact on the users predict function varies depending on whether the component is used as an input or output for an event (or both).

  • When used as an Input, the component only impacts the input signature of the user function.
  • When used as an output, the component only impacts the return signature of the user function.

The code snippet below is accurate in cases where the component is used as both an input and an output.

  • As input: Should return, list of (word, category) tuples, or a dictionary of two keys: "text", and "highlights", which itself is.
def predict(
    value: dict
) -> list[tuple[str, str | None]] | dict | None:
    return value