Skip to content

Commit 204eb45

Browse files
committed
async-function-support
- add async function support to Blocks
1 parent 9c1cef5 commit 204eb45

3 files changed

Lines changed: 228 additions & 194 deletions

File tree

gradio/blocks.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,16 @@
11
from __future__ import annotations
22

33
import getpass
4+
import inspect
45
import os
56
import sys
67
import time
78
import warnings
89
import webbrowser
910
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple
1011

12+
from fastapi.concurrency import run_in_threadpool
13+
1114
from gradio import encryptor, networking, queueing, strings, utils
1215
from gradio.context import Context
1316
from gradio.deprecation import check_deprecated_parameters
@@ -286,7 +289,7 @@ def render(self):
286289
if Context.block is not None:
287290
Context.block.children.extend(self.children)
288291

289-
def process_api(
292+
async def process_api(
290293
self,
291294
data: PredictBody,
292295
username: str = None,
@@ -316,7 +319,11 @@ def process_api(
316319
else:
317320
processed_input = raw_input
318321
start = time.time()
319-
predictions = block_fn.fn(*processed_input)
322+
323+
if inspect.iscoroutinefunction(block_fn.fn):
324+
predictions = await block_fn.fn(*processed_input)
325+
else:
326+
predictions = await run_in_threadpool(block_fn.fn, *processed_input)
320327
duration = time.time() - start
321328
block_fn.total_runtime += duration
322329
block_fn.total_runs += 1

gradio/networking.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,12 @@
1616
import uvicorn
1717

1818
from gradio import queueing
19-
from gradio.routes import create_app
19+
from gradio.routes import App
2020
from gradio.tunneling import create_tunnel
2121

2222
if TYPE_CHECKING: # Only import for type checking (to avoid circular imports).
2323
from gradio.blocks import Blocks
2424

25-
2625
# By default, the local server will try to open on localhost, port 7860.
2726
# If that is not available, then it will try 7861, 7862, ... 7959.
2827
INITIAL_PORT_VALUE = int(os.getenv("GRADIO_SERVER_PORT", "7860"))
@@ -139,8 +138,7 @@ def start_server(
139138
else:
140139
path_to_local_server = "http://{}:{}/".format(url_host_name, port)
141140

142-
app = create_app()
143-
app = configure_app(app, blocks)
141+
app = App.create_app(blocks)
144142

145143
if app.blocks.enable_queue:
146144
if blocks.auth is not None or app.blocks.encrypt:

0 commit comments

Comments
 (0)