Skip to content

Commit

Permalink
Merge branch 'main' into delete-state
Browse files Browse the repository at this point in the history
  • Loading branch information
abidlabs committed Mar 29, 2024
2 parents 0193c96 + f42d3e2 commit 81af45b
Show file tree
Hide file tree
Showing 10 changed files with 78 additions and 24 deletions.
5 changes: 5 additions & 0 deletions .changeset/angry-towns-mate.md
@@ -0,0 +1,5 @@
---
"gradio": patch
---

fix:logout route deleting cookie fix
5 changes: 5 additions & 0 deletions .changeset/green-brooms-work.md
@@ -0,0 +1,5 @@
---
"gradio": patch
---

feat:Suppress printing "Running on local URL:" when quiet is set
3 changes: 2 additions & 1 deletion .changeset/sixty-paths-push.md
@@ -1,5 +1,6 @@
---
"@gradio/multimodaltextbox": patch
"gradio": patch
---

feat:Fix how files are processed in `gr.ChatInterface`
feat:Paste Images into MultimodalTextbox
5 changes: 5 additions & 0 deletions .changeset/strong-hornets-push.md
@@ -0,0 +1,5 @@
---
"gradio": patch
---

feat:Make internal event handlers of gr.Interface and gr.ChatInterface async
2 changes: 1 addition & 1 deletion gradio/blocks.py
Expand Up @@ -2137,7 +2137,7 @@ def reverse(text):
if self.local_url.startswith("https") or self.is_colab
else "http"
)
if not wasm_utils.IS_WASM and not self.is_colab:
if not wasm_utils.IS_WASM and not self.is_colab and not quiet:
print(
strings.en["RUNNING_LOCALLY_SEPARATED"].format(
self.protocol, self.server_name, self.server_port
Expand Down
24 changes: 13 additions & 11 deletions gradio/chat_interface.py
Expand Up @@ -29,7 +29,7 @@
from gradio.layouts import Accordion, Group, Row
from gradio.routes import Request
from gradio.themes import ThemeClass as Theme
from gradio.utils import SyncToAsyncIterator, async_iteration
from gradio.utils import SyncToAsyncIterator, async_iteration, async_lambda


@document()
Expand Down Expand Up @@ -378,7 +378,7 @@ def _setup_events(self) -> None:
show_api=False,
queue=False,
).then(
lambda x: x,
async_lambda(lambda x: x),
[self.saved_input],
[self.textbox],
show_api=False,
Expand All @@ -387,7 +387,7 @@ def _setup_events(self) -> None:

if self.clear_btn:
self.clear_btn.click(
lambda: ([], [], None),
async_lambda(lambda: ([], [], None)),
None,
[self.chatbot, self.chatbot_state, self.saved_input],
queue=False,
Expand All @@ -401,17 +401,19 @@ def _setup_stop_events(
if self.submit_btn:
for event_trigger in event_triggers:
event_trigger(
lambda: (
Button(visible=False),
Button(visible=True),
async_lambda(
lambda: (
Button(visible=False),
Button(visible=True),
)
),
None,
[self.submit_btn, self.stop_btn],
show_api=False,
queue=False,
)
event_to_cancel.then(
lambda: (Button(visible=True), Button(visible=False)),
async_lambda(lambda: (Button(visible=True), Button(visible=False))),
None,
[self.submit_btn, self.stop_btn],
show_api=False,
Expand All @@ -420,14 +422,14 @@ def _setup_stop_events(
else:
for event_trigger in event_triggers:
event_trigger(
lambda: Button(visible=True),
async_lambda(lambda: Button(visible=True)),
None,
[self.stop_btn],
show_api=False,
queue=False,
)
event_to_cancel.then(
lambda: Button(visible=False),
async_lambda(lambda: Button(visible=False)),
None,
[self.stop_btn],
show_api=False,
Expand Down Expand Up @@ -471,7 +473,7 @@ def _append_multimodal_history(
if message["text"] is not None and isinstance(message["text"], str):
history.append([message["text"], response])

def _display_input(
async def _display_input(
self, message: str | dict[str, list], history: list[list[str | tuple | None]]
) -> tuple[list[list[str | tuple | None]], list[list[str | tuple | None]]]:
if self.multimodal and isinstance(message, dict):
Expand Down Expand Up @@ -631,7 +633,7 @@ async def _examples_stream_fn(
async for response in generator:
yield [[message, response]]

def _delete_prev_fn(
async def _delete_prev_fn(
self,
message: str | dict[str, list],
history: list[list[str | tuple | None]],
Expand Down
20 changes: 14 additions & 6 deletions gradio/interface.py
Expand Up @@ -701,14 +701,16 @@ def attach_submit_events(
if _stop_btn:
extra_output = [_submit_btn, _stop_btn]

def cleanup():
async def cleanup():
return [Button(visible=True), Button(visible=False)]

predict_event = on(
triggers,
lambda: (
Button(visible=False),
Button(visible=True),
utils.async_lambda(
lambda: (
Button(visible=False),
Button(visible=True),
)
),
inputs=None,
outputs=[_submit_btn, _stop_btn],
Expand Down Expand Up @@ -827,7 +829,9 @@ def attach_flagging_events(
)
flag_method = FlagMethod(self.flagging_callback, label, value)
flag_btn.click(
lambda: Button(value="Saving...", interactive=False),
utils.async_lambda(
lambda: Button(value="Saving...", interactive=False)
),
None,
flag_btn,
queue=False,
Expand All @@ -842,7 +846,11 @@ def attach_flagging_events(
show_api=False,
)
_clear_btn.click(
flag_method.reset, None, flag_btn, queue=False, show_api=False
utils.async_lambda(flag_method.reset),
None,
flag_btn,
queue=False,
show_api=False,
)

def render_examples(self):
Expand Down
7 changes: 4 additions & 3 deletions gradio/routes.py
Expand Up @@ -37,7 +37,7 @@
import httpx
import markupsafe
import orjson
from fastapi import BackgroundTasks, Depends, FastAPI, HTTPException, Response, status
from fastapi import BackgroundTasks, Depends, FastAPI, HTTPException, status
from fastapi.responses import (
FileResponse,
HTMLResponse,
Expand Down Expand Up @@ -331,7 +331,8 @@ def login(form_data: OAuth2PasswordRequestForm = Depends()):
else:

@app.get("/logout")
def logout(response: Response, user: str = Depends(get_current_user)):
def logout(user: str = Depends(get_current_user)):
response = RedirectResponse(url="/", status_code=status.HTTP_302_FOUND)
response.delete_cookie(key=f"access-token-{app.cookie_id}", path="/")
response.delete_cookie(
key=f"access-token-unsecure-{app.cookie_id}", path="/"
Expand All @@ -340,7 +341,7 @@ def logout(response: Response, user: str = Depends(get_current_user)):
for token in list(app.tokens.keys()):
if app.tokens[token] == user:
del app.tokens[token]
return RedirectResponse(url="/", status_code=status.HTTP_302_FOUND)
return response

###############
# Main Routes
Expand Down
13 changes: 13 additions & 0 deletions gradio/utils.py
Expand Up @@ -26,6 +26,7 @@
from abc import ABC, abstractmethod
from collections import OrderedDict
from contextlib import contextmanager
from functools import wraps
from io import BytesIO
from numbers import Number
from pathlib import Path
Expand Down Expand Up @@ -1245,3 +1246,15 @@ def simplify_file_data_in_str(s):
if isinstance(payload, str):
return payload
return json.dumps(payload)


def async_lambda(f: Callable) -> Callable:
"""Turn a function into an async function.
Useful for internal event handlers defined as lambda functions used in the codebase
"""

@wraps(f)
async def function_wrapper(*args, **kwargs):
return f(*args, **kwargs)

return function_wrapper
18 changes: 16 additions & 2 deletions js/multimodaltextbox/shared/MultimodalTextbox.svelte
Expand Up @@ -35,6 +35,8 @@
export let root: string;
export let file_types: string[] | null = null;
let upload_component: Upload;
let hidden_upload: HTMLInputElement;
let el: HTMLTextAreaElement | HTMLInputElement;
let can_scroll: boolean;
let previous_scroll_top = 0;
Expand Down Expand Up @@ -172,8 +174,6 @@
value = value;
}
let hidden_upload: HTMLInputElement;
function handle_upload_click(): void {
if (hidden_upload) {
hidden_upload.click();
Expand All @@ -183,13 +183,26 @@
async function handle_submit(): Promise<void> {
dispatch("submit");
}
function handle_paste(event: ClipboardEvent): void {
if (!event.clipboardData) return;
const items = event.clipboardData.items;
for (let index in items) {
const item = items[index];
if (item.kind === "file" && item.type.includes("image")) {
const blob = item.getAsFile();
if (blob) upload_component.load_files([blob]);
}
}
}
</script>

<!-- svelte-ignore a11y-autofocus -->
<label class:container>
<BlockTitle {show_label} {info}>{label}</BlockTitle>
<div class="input-container">
<Upload
bind:this={upload_component}
on:load={handle_upload}
filetype={accept_file_types}
{root}
Expand Down Expand Up @@ -268,6 +281,7 @@
on:select={handle_select}
on:focus
on:scroll={handle_scroll}
on:paste={handle_paste}
style={text_align ? "text-align: " + text_align : ""}
/>
</Upload>
Expand Down

0 comments on commit 81af45b

Please sign in to comment.