gradio icon indicating copy to clipboard operation
gradio copied to clipboard

Unable to update gr.Examples getting AttributeError: 'Examples' object has no attribute '_id'

Open Hamas-ur-Rehman opened this issue 1 year ago • 22 comments

Describe the bug

while looking deeply for the answers myself I am frustrated and could not find the solution

so Below is some code


# Function for generating some examples
def generate_examples():    
    extracted_list = ['completion1','completion2','completion3','completion4']
    return gr.Examples.update(examples=extracted_list)


# Gradio Interface
with gr.Blocks() as demo: 
   
    with gr.Row():
        with gr.Column(scale=0.7):
            chatbot = gr.Chatbot(
                value=[[None,"Hey, can I help you get something?"],],
                height=500,
                label="Stickse Sales Assistant",
                )
            with gr.Row():
                with gr.Column(scale=0.85):
                    txt = gr.Textbox(
                        show_label=False,
                        container=False,
                        placeholder="Enter text and press enter",
                    )
                    _examples = gr.Examples(
                        examples=['mice','ants','snails', 'bees', 'moth'], 
                        inputs=txt,
                        label="Suggestions"
                        )

                with gr.Column(scale=0.15, min_width=0):
                    btn = gr.Button("Send")

        with gr.Column(scale=0.3):
            radio = gr.Dropdown(
                container=False,
                choices=['gpt-3.5-turbo','gpt-3.5-turbo-16k','gpt-3.5-turbo-0613','gpt-3.5-turbo-16k-0613'],
                label="Model",
                value='gpt-3.5-turbo-16k',
            )
            model_details = gr.Markdown(
                container=True,
                value=MODELS[radio.value], label="Model Details",)
            clear = gr.Button("Clear Conversation")

          # this is where the issue is
            s = gr.Button("UPDATE  EXAMPLES")


    
    
    radio.change(change_model_details, [radio], [model_details])
    clear.click(init_history, inputs =[],outputs = chatbot,)

    btn.click(add_text, [chatbot, txt], [chatbot, txt], queue=True).then(
            generate_response, inputs =[chatbot,radio],outputs = [chatbot])
      
    
    txt.submit(add_text, [chatbot, txt], [chatbot, txt], queue=True).then(
            generate_response, inputs =[chatbot,radio],outputs = [chatbot])
    
   # this is where I am calling the button click
    s.click(generate_examples,inputs=[],outputs = [_examples])

demo.queue()
demo.launch()

This is the issue I get on my terminal

 > python main.py
Traceback (most recent call last):
  File "D:\projects\SalesRep\main.py", line 272, in <module>
    s.click(fn=generate_examples,inputs=[],outputs = [_examples])
  File "D:\projects\SalesRep\env\Lib\site-packages\gradio\events.py", line 139, in __call__
    dep, dep_index = self.trigger.set_event_trigger(
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\projects\SalesRep\env\Lib\site-packages\gradio\blocks.py", line 285, in set_event_trigger
    "outputs": [block._id for block in outputs],
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\projects\SalesRep\env\Lib\site-packages\gradio\blocks.py", line 285, in <listcomp>
    "outputs": [block._id for block in outputs],
                ^^^^^^^^^
AttributeError: 'Examples' object has no attribute '_id'

so The gr.Examples component is what I want to update and I am unable to do it. There was a similar issue #3817 but was closed and the discussion form linked does not exist
https://github.com/gradio-app/gradio/discussions/3169

when I comment the line s.click(generate_examples,inputs=[],outputs = [_examples])

The gradio app launches else it doesnt even lauch now

Have you searched existing issues? 🔎

  • [X] I have searched and found no existing issues

Reproduction

import gradio as gr

def generate_examples():    
    extracted_list = ['completion1','completion2','completion3','completion4']
    return gr.Examples.update(examples=extracted_list)


with gr.Blocks() as demo: 
   
    with gr.Row():
        with gr.Column(scale=0.7):
            chatbot = gr.Chatbot(
                value=[[None,"Hey, can I help you get something?"],],
                height=500,
                label="Stickse Sales Assistant",
                )
            with gr.Row():
                with gr.Column(scale=0.85):
                    txt = gr.Textbox(
                        show_label=False,
                        container=False,
                        placeholder="Enter text and press enter",
                    )
                    _examples = gr.Examples(
                        examples=['mice','ants','snails', 'bees', 'moth'], 
                        inputs=txt,
                        label="Suggestions"
                        )

                with gr.Column(scale=0.15, min_width=0):
                    btn = gr.Button("Send")

        with gr.Column(scale=0.3):
            radio = gr.Dropdown(
                container=False,
                choices=['gpt-3.5-turbo','gpt-3.5-turbo-16k','gpt-3.5-turbo-0613','gpt-3.5-turbo-16k-0613'],
                label="Model",
                value='gpt-3.5-turbo-16k',
            )
           

          # this is where the issue is
            s = gr.Button("UPDATE  EXAMPLES")

    
   # this is where I am calling the button click
    # s.click(generate_examples,inputs=[],outputs = [_examples])

demo.queue()
demo.launch()

Logs

Traceback (most recent call last):
  File "D:\projects\SalesRep\main.py", line 272, in <module>
    s.click(fn=generate_examples,inputs=[],outputs = [_examples])
  File "D:\projects\SalesRep\env\Lib\site-packages\gradio\events.py", line 139, in __call__
    dep, dep_index = self.trigger.set_event_trigger(
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\projects\SalesRep\env\Lib\site-packages\gradio\blocks.py", line 285, in set_event_trigger
    "outputs": [block._id for block in outputs],
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\projects\SalesRep\env\Lib\site-packages\gradio\blocks.py", line 285, in <listcomp>
    "outputs": [block._id for block in outputs],
                ^^^^^^^^^
AttributeError: 'Examples' object has no attribute '_id'

System Info

Gradio Environment Information:
Operating System:  Windows


gradio version:  3.39.0

gradio Dependencies:
  aiofiles: 23.1.0
  aiohttp: 3.8.5
  altair: 5.0.1
  fastapi: 0.99.1
  ffmpy: 0.3.1
  gradio-client: 0.3.0
  httpx: 0.24.1
  huggingface-hub: 0.16.4
  jinja2: 3.1.2
  markdown-it-py: 2.2.0
  markupsafe: 2.1.3
  matplotlib: 3.7.2
  mdit-py-plugins: 0.3.3
  numpy: 1.25.1
  orjson: 3.9.2
  packaging: 23.1
  pandas: 2.0.3
  pillow: 10.0.0
  pydantic: 1.10.12
  pydub: 0.25.1
  python-multipart: 0.0.6
  pyyaml: 6.0.1
  requests: 2.31.0
  semantic-version: 2.10.0
  typing-extensions: 4.7.1
  uvicorn: 0.23.1
  websockets: 11.0.3


gradio_client version:  0.3.0

gradio_client Dependencies:
  fsspec: 2023.6.0
  httpx: 0.24.1
  huggingface-hub: 0.16.4
  packaging: 23.1
  requests: 2.31.0
  typing-extensions: 4.7.1
  websockets: 11.0.3

Severity

Blocking usage of gradio

Hamas-ur-Rehman avatar Jul 29 '23 12:07 Hamas-ur-Rehman

Hi @Hamas-ur-Rehman we're working on fixing #1566 which should fix this as well.

cc @aliabid94

abidlabs avatar Jul 30 '23 05:07 abidlabs

@abidlabs Is there a possible temporary workaround that I can implement?

Hamas-ur-Rehman avatar Jul 30 '23 08:07 Hamas-ur-Rehman

For now, can you have multiple predefined gr.Examples objects, and hide the visibility based on the interaction?

aliabid94 avatar Aug 01 '23 02:08 aliabid94

@abidlabs seems like there are a few issues here, most importantly that gr.Examples itself is not a Component, but a gr.Dataset wrapper - if a user wanted to update it, they would have to target the .dataset property of gr.Examples, which is not documented.

aliabid94 avatar Aug 01 '23 03:08 aliabid94

That's true we should document this, or maybe give gr.Examples() an .update() method which updates the underlying dataset

abidlabs avatar Aug 01 '23 04:08 abidlabs

@abidlabs @aliabid94 I have the same error when I try to return a gr.Dataframe

AttributeError: 'DataFrame' object has no attribute '_id'

dipam0111 avatar Oct 10 '23 03:10 dipam0111

I am also facing the same issue and would love to have the ability to update gr.Examples on the fly.

taesiri avatar Nov 28 '23 18:11 taesiri

By the way, my current workaround for this is using the select event from gr.Dataframe(). It works quite nicely.

taesiri avatar Nov 28 '23 19:11 taesiri

my current workaround

Can you please provide the working example?

chintan-donda avatar Nov 30 '23 06:11 chintan-donda

I am facing the same issue and would love to have the ability to update gr.Examples on the fly. Any working example with this issue fixed?

@abidlabs If it's fixed and closed, in which version of the Gradio lib the PR has been merged? Please suggest.

chintan-donda avatar Nov 30 '23 06:11 chintan-donda

Hi @chintan-donda this issue is still open at the moment

abidlabs avatar Nov 30 '23 06:11 abidlabs

Ok @abidlabs. Any working example as a workaround.

chintan-donda avatar Nov 30 '23 07:11 chintan-donda

@chintan-donda

In my case, it was enough to use a gr.DataFrame(). First, I update the dataframe then use the select event to feed the correct data to each component I want.

taesiri avatar Nov 30 '23 13:11 taesiri

I figured it out! First:

user_chat_bot_suggest = gr.Example(...)

def fn(...):
    return gr.Dataset.update(samples=suggests).  # suggests: List[List[str]]

then:

gr.SOMETHING.change().then(fn,
    inputs=[...],
    outputs=[user_chat_bot_suggest.dataset])

It works for me!

lxysl avatar Dec 19 '23 18:12 lxysl

Ooopse, the example texts are changed, but the inner state is the original... If you select one of the suggest after update the dataset, you will still get the original one.

lxysl avatar Dec 19 '23 18:12 lxysl

If there is any progress, please let me know, thanks!

lxysl avatar Dec 19 '23 18:12 lxysl

No progress yet, but we'll look at it once we get a chance. Related: https://github.com/gradio-app/gradio/issues/6415

abidlabs avatar Jan 05 '24 23:01 abidlabs

hi, any update on this.

seshubonam avatar Jan 22 '24 20:01 seshubonam

No progress yet, but we'll look at it once we get a chance. Related: https://github.com/gradio-app/gradio/issues/6415

found a workaround for this. will update with example code soon.

if there is an official method. would be helpful too. thanks

seshubonam avatar Jan 24 '24 09:01 seshubonam

No progress yet, but we'll look at it once we get a chance. Related: #6415

found a workaround for this. will update with example code soon.

if there is an official method. would be helpful too. thanks

Has the example code been updated?Where can I find it? Please.

jesenzhang avatar Mar 05 '24 00:03 jesenzhang

@abidlabs hi,any progress of this question?

hertz-pj avatar Mar 06 '24 01:03 hertz-pj

I am getting this error when trying to pass a list of dataframes as an output in a click function. Is this related or a separate issue? My UI code:

with gr.Tabs() as tabs:
                                        positive_dataframes = []
                                        negative_dataframes = []
                                        for i in range(10):
                                                with gr.Tab(label=f"Tab {i+1}"):
                                                        with gr.Row():
                                                                positive_df = gr.DataFrame(id=f"pos_df_{i}", label="Positive Replace")
                                                                positive_dataframes.append(positive_df)
                                                        with gr.Row():
                                                                negative_df = gr.DataFrame(id=f"neg_df_{i}", label="Negative Replace")
                                                                negative_dataframes.append(negative_df)

And my button click code:

feature_analysis_button.click(
                        fn=analyze,
                        inputs=[spectrum_feature_vectors],
                        outputs=[spectrum_analysis_results, positive_dataframes, negative_dataframes]
                )

Errors on the click with: "outputs": [block._id for block in outputs], AttributeError: 'list' object has no attribute '_id'

I'm using gradio 3.41.2 in Automatic1111

marcsyp avatar May 24 '24 15:05 marcsyp

Apologies for the long resolution on this. I am working on a PR that will allow this to happen. You can test it by doing:

pip install https://gradio-builds.s3.amazonaws.com/c2dc8a1bd9585c3170a116d12a465be9223f1310/gradio-4.37.2-py3-none-any.whl

The syntax you'll need to use is to pass in the example.dataset as the output component. There's an example in the PR if you'd like to take a look!

abidlabs avatar Jul 11 '24 22:07 abidlabs