File size: 2,172 Bytes
3b9376c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | """Process-executor check on Spaces with two replicas of the app."""
import os
import subprocess
import sys
import time
# The Space installs Gradio 6.29.1; this app needs the PR's build, which a
# Space's build step cannot see, so install it here once and start again
if not os.environ.get("PR_GRADIO_INSTALLED"):
here = os.path.dirname(os.path.abspath(__file__))
subprocess.check_call(
[
sys.executable,
"-m",
"pip",
"install",
"--no-cache-dir",
f"{here}/wheels/gradio_client-2.7.2-py3-none-any.whl",
f"{here}/wheels/gradio-6.30.0-py3-none-any.whl",
]
)
os.environ["PR_GRADIO_INSTALLED"] = "1"
os.execv(sys.executable, [sys.executable, *sys.argv])
# Two processes run the app's events; the gateway sends each session to one
os.environ.setdefault("GRADIO_PROCESS_REPLICAS", "2")
import gradio as gr
def echo(x: str) -> str:
return f"{x[::-1]} (pid {os.getpid()})"
def count(n: int) -> tuple[int, str]:
return n + 1, f"count {n + 1} (pid {os.getpid()})"
def slow(x: str) -> str:
time.sleep(3)
return f"{x} done (pid {os.getpid()})"
def info() -> str:
return (
f"gradio {gr.__version__} (PR commit {open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'PR_COMMIT')).read().strip()}); executor "
f"{'process' if getattr(demo, '_process_worker', None) else 'thread'}; "
f"ssr {getattr(demo, 'ssr_mode', None)}; pid {os.getpid()}"
)
with gr.Blocks() as demo:
gr.Markdown(
"Two replicas of this app serve its events. Each session stays on the "
"process that first served it; `/gradio_api/processes` lists them."
)
counter = gr.State(0)
text = gr.Textbox(label="input")
out = gr.Textbox(label="output")
gr.Button("echo").click(echo, text, out, api_name="echo")
gr.Button("count").click(count, counter, [counter, out], api_name="count")
gr.Button("slow (3 s, one at a time per replica)").click(
slow, text, out, api_name="slow", concurrency_limit=1
)
gr.Button("info").click(info, None, out, api_name="info")
demo.launch()
|