gradio-app / gradio

Build and share delightful machine learning apps, all in Python. 🌟 Star to support our work!
http://www.gradio.app
Apache License 2.0
31.16k stars 2.33k forks source link

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

Closed Hamas-ur-Rehman closed 1 week ago

Hamas-ur-Rehman commented 12 months ago

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? 🔎

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

abidlabs commented 12 months ago

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

cc @aliabid94

Hamas-ur-Rehman commented 12 months ago

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

aliabid94 commented 11 months ago

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

aliabid94 commented 11 months ago

@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.

abidlabs commented 11 months ago

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

dipam0111 commented 9 months ago

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

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

taesiri commented 7 months ago

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

taesiri commented 7 months ago

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

chintan-donda commented 7 months ago

my current workaround

Can you please provide the working example?

chintan-donda commented 7 months ago

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.

abidlabs commented 7 months ago

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

chintan-donda commented 7 months ago

Ok @abidlabs. Any working example as a workaround.

taesiri commented 7 months ago

@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.

lxysl commented 7 months ago

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 commented 7 months ago

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 commented 7 months ago

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

abidlabs commented 6 months ago

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

seshubonam commented 6 months ago

hi, any update on this.

seshubonam commented 6 months ago

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

jesenzhang commented 4 months ago

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.

hertz-pj commented 4 months ago

@abidlabs hi,any progress of this question?

marcsyp commented 2 months ago

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

abidlabs commented 1 week ago

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!