Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cancel events from other events #2433

Merged
merged 19 commits into from
Oct 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 87 additions & 3 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,90 @@
# Upcoming Release
# Upcoming Release

## New Features:

### Cancelling Running Events
Running events can be cancelled when other events are triggered! To test this feature, pass the `cancels` parameter to the event listener.
For this feature to work, the queue must be enabled.

![cancel_on_change_rl](https://user-images.githubusercontent.com/41651716/195952623-61a606bd-e82b-4e1a-802e-223154cb8727.gif)

Code:
```python
import time
import gradio as gr

def fake_diffusion(steps):
for i in range(steps):
time.sleep(1)
yield str(i)

def long_prediction(*args, **kwargs):
time.sleep(10)
return 42


with gr.Blocks() as demo:
with gr.Row():
with gr.Column():
n = gr.Slider(1, 10, value=9, step=1, label="Number Steps")
run = gr.Button()
output = gr.Textbox(label="Iterative Output")
stop = gr.Button(value="Stop Iterating")
with gr.Column():
prediction = gr.Number(label="Expensive Calculation")
run_pred = gr.Button(value="Run Expensive Calculation")
with gr.Column():
cancel_on_change = gr.Textbox(label="Cancel Iteration and Expensive Calculation on Change")

click_event = run.click(fake_diffusion, n, output)
stop.click(fn=None, inputs=None, outputs=None, cancels=[click_event])
pred_event = run_pred.click(fn=long_prediction, inputs=None, outputs=prediction)

cancel_on_change.change(None, None, None, cancels=[click_event, pred_event])


demo.queue(concurrency_count=1, max_size=20).launch()
```

For interfaces, a stop button will be added automatically if the function uses a `yield` statement.

```python
import gradio as gr
import time

def iteration(steps):
for i in range(steps):
time.sleep(0.5)
yield i

gr.Interface(iteration,
inputs=gr.Slider(minimum=1, maximum=10, step=1, value=5),
outputs=gr.Number()).queue().launch()
```

![stop_interface_rl](https://user-images.githubusercontent.com/41651716/195952883-e7ca4235-aae3-4852-8f28-96d01d0c5822.gif)


## Bug Fixes:
No changes to highlight.

## Documentation Changes:
No changes to highlight.

## Testing and Infrastructure Changes:
No changes to highlight.

## Breaking Changes:
No changes to highlight.

## Full Changelog:
* Enable running events to be cancelled from other events by [@freddyaboulton](https://github.com/freddyaboulton) in [PR 2433](https://github.com/gradio-app/gradio/pull/2433)

## Contributors Shoutout:
No changes to highlight.


# Version 3.5

## Bug Fixes:

Expand Down Expand Up @@ -42,8 +128,6 @@ No changes to highlight.
* Fix embedded interfaces on touch screen devices by [@aliabd](https://github.com/aliabd) in [PR 2457](https://github.com/gradio-app/gradio/pull/2457)
* Upload all demos to spaces by [@aliabd](https://github.com/aliabd) in [PR 2281](https://github.com/gradio-app/gradio/pull/2281)



## Contributors Shoutout:
No changes to highlight.

Expand Down
49 changes: 49 additions & 0 deletions demo/cancel_events/run.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import time
import gradio as gr


def fake_diffusion(steps):
for i in range(steps):
print(f"Current step: {i}")
time.sleep(1)
yield str(i)


def long_prediction(*args, **kwargs):
time.sleep(10)
return 42


with gr.Blocks() as demo:
with gr.Row():
with gr.Column():
n = gr.Slider(1, 10, value=9, step=1, label="Number Steps")
run = gr.Button()
output = gr.Textbox(label="Iterative Output")
stop = gr.Button(value="Stop Iterating")
with gr.Column():
textbox = gr.Textbox(label="Prompt")
prediction = gr.Number(label="Expensive Calculation")
run_pred = gr.Button(value="Run Expensive Calculation")
with gr.Column():
cancel_on_change = gr.Textbox(label="Cancel Iteration and Expensive Calculation on Change")
cancel_on_submit = gr.Textbox(label="Cancel Iteration and Expensive Calculation on Submit")
echo = gr.Textbox(label="Echo")
with gr.Row():
with gr.Column():
image = gr.Image(source="webcam", tool="editor", label="Cancel on edit", interactive=True)
with gr.Column():
video = gr.Video(source="webcam", label="Cancel on play", interactive=True)

click_event = run.click(fake_diffusion, n, output)
stop.click(fn=None, inputs=None, outputs=None, cancels=[click_event])
pred_event = run_pred.click(fn=long_prediction, inputs=[textbox], outputs=prediction)

cancel_on_change.change(None, None, None, cancels=[click_event, pred_event])
cancel_on_submit.submit(lambda s: s, cancel_on_submit, echo, cancels=[click_event, pred_event])
image.edit(None, None, None, cancels=[click_event, pred_event])
video.play(None, None, None, cancels=[click_event, pred_event])


if __name__ == "__main__":
demo.queue(concurrency_count=2, max_size=20).launch()
19 changes: 18 additions & 1 deletion gradio/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,8 @@ def set_event_trigger(
js: Optional[str] = None,
no_target: bool = False,
queue: Optional[bool] = None,
) -> None:
cancels: List[int] | None = None,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add cancels to docstring below

) -> Dict[str, Any]:
"""
Adds an event to the component's dependencies.
Parameters:
Expand Down Expand Up @@ -166,6 +167,7 @@ def set_event_trigger(
"api_name": api_name,
"scroll_to_output": scroll_to_output,
"show_progress": show_progress,
"cancels": cancels if cancels else [],
}
if api_name is not None:
dependency["documentation"] = [
Expand All @@ -179,6 +181,7 @@ def set_event_trigger(
],
]
Context.root_block.dependencies.append(dependency)
return dependency

def get_config(self):
return {
Expand Down Expand Up @@ -1062,6 +1065,20 @@ def reverse(text):
if self.enable_queue and not hasattr(self, "_queue"):
self.queue()

for dep in self.dependencies:
for i in dep["cancels"]:
queue_status = self.dependencies[i]["queue"]
if queue_status is False or (
queue_status is None and not self.enable_queue
):
raise ValueError(
"In order to cancel an event, the queue for that event must be enabled! "
"You may get this error by either 1) passing a function that uses the yield keyword "
"into an interface without enabling the queue or 2) defining an event that cancels "
"another event without enabling the queue. Both can be solved by calling .queue() "
"before .launch()"
)

self.config = self.get_config_file()
self.share = share
self.encrypt = encrypt
Expand Down
Loading