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'