import os import re import subprocess import time import gradio as gr import spaces def download_binaries(): if not os.path.exists("./ttyd"): subprocess.run( ["curl", "-sL", "-o", "./ttyd", "https://github.com/tsl0922/ttyd/releases/download/1.7.7/ttyd.x86_64"], check=True ) os.chmod("./ttyd", 0o755) if not os.path.exists("./cloudflared"): subprocess.run( ["curl", "-sL", "-o", "./cloudflared", "https://github.com/cloudflare/cloudflared/releases/download/2024.6.1/cloudflared-linux-amd64"], check=True ) os.chmod("./cloudflared", 0o755) download_binaries() @spaces.GPU(duration=120) def start_terminal(): subprocess.run("pkill -9 ttyd; pkill -9 cloudflared", shell=True) ttyd_proc = subprocess.Popen( ["./ttyd", "-p", "7681", "-W", "bash"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL ) cf_proc = subprocess.Popen( ["./cloudflared", "tunnel", "--url", "http://127.0.0.1:7681"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True ) tunnel_url = None start_time = time.time() while time.time() - start_time < 30: line = cf_proc.stdout.readline() if not line: continue match = re.search(r"https://[a-zA-Z0-9-]+\.trycloudflare\.com", line) if match: tunnel_url = match.group(0) break if not tunnel_url: yield "failed to establish tunnel. check logs.", "" return iframe_html = ( f'
' f' ' f' open full screen in new tab ↗' f' ' f'
' f'' ) status_msg = f"active tunnel: {tunnel_url} (slice valid for ~110s)" # instant stream to gradio UI yield status_msg, iframe_html # maintain the gpu slice for 110 seconds run_start = time.time() while time.time() - run_start < 110: time.sleep(1) if ttyd_proc.poll() is not None or cf_proc.poll() is not None: break ttyd_proc.terminate() cf_proc.terminate() yield "slice expired. click button below to acquire next slice.", "" with gr.Blocks(title="zerogpu terminal") as demo: gr.Markdown("### zerogpu rtx 6000 blackwell bash terminal") launch_btn = gr.Button("launch gpu bash", variant="primary") status_box = gr.Textbox(label="status") terminal_display = gr.HTML(label="terminal") launch_btn.click( start_terminal, outputs=[status_box, terminal_display] ) demo.launch(server_name="0.0.0.0", server_port=7860)