abidlabs's picture
abidlabs HF Staff
Process-executor check with two replicas
3b9376c verified
Raw History Blame Contribute Delete
2.17 kB
"""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()