Download app.py from conabe511/luna: direct link, hf CLI and curl.
- Browser
- Download file 5.81 kB
-
https://huggingface.co/spaces/conabe511/luna/resolve/main/app.py
- Command line
-
hf download hf://spaces/conabe511/luna/app.py
-
curl -L -o app.py https://huggingface.co/spaces/conabe511/luna/resolve/main/app.py
5.81 kB
| import asyncio | |
| import os | |
| import subprocess | |
| import tarfile | |
| import time | |
| import urllib.request | |
| from pathlib import Path | |
| import httpx | |
| import spaces | |
| import gradio as gr | |
| import websockets | |
| from starlette.responses import RedirectResponse, StreamingResponse | |
| from starlette.background import BackgroundTask | |
| from starlette.routing import Route, WebSocketRoute | |
| CODE_VERSION = "4.128.0" | |
| CODE_PORT = 8080 | |
| CODE_BACKEND = f"http://127.0.0.1:{CODE_PORT}" | |
| CODE_DIR = Path.home() / ".code-server" | |
| METHODS = ["GET", "POST", "PUT", "DELETE", "PATCH"] | |
| def ensure_code_server(): | |
| name = f"code-server-{CODE_VERSION}-linux-amd64" | |
| binary = CODE_DIR / name / "bin" / "code-server" | |
| if binary.exists(): | |
| return str(binary) | |
| CODE_DIR.mkdir(parents=True, exist_ok=True) | |
| url = f"https://github.com/coder/code-server/releases/download/v{CODE_VERSION}/{name}.tar.gz" | |
| archive = CODE_DIR / f"{name}.tar.gz" | |
| urllib.request.urlretrieve(url, archive) | |
| with tarfile.open(archive, "r:gz") as tar: | |
| tar.extractall(CODE_DIR, filter="data") | |
| archive.unlink() | |
| return str(binary) | |
| def start_code_server(): | |
| binary = ensure_code_server() | |
| workspace = Path.home() / "workspace" | |
| workspace.mkdir(parents=True, exist_ok=True) | |
| password = os.environ.get("CODE_SERVER_PASSWORD") | |
| if not password: | |
| raise RuntimeError("CODE_SERVER_PASSWORD must be configured as a Space secret") | |
| env = dict(os.environ, PASSWORD=password) | |
| subprocess.Popen( | |
| [binary, "--bind-addr", f"127.0.0.1:{CODE_PORT}", "--auth", "password", | |
| "--disable-telemetry", "--disable-update-check", str(workspace)], | |
| env=env, | |
| ) | |
| for _ in range(120): | |
| try: | |
| httpx.get(CODE_BACKEND, timeout=1.0) | |
| return | |
| except Exception: | |
| time.sleep(0.5) | |
| # ZeroGPU requires the app to launch through Gradio with at least one | |
| # @spaces.GPU function, or the Space never reaches RUNNING. | |
| def health(): | |
| out = subprocess.run(["nvidia-smi"], capture_output=True, text=True) | |
| return out.stdout or out.stderr | |
| with gr.Blocks() as demo: | |
| gr.Markdown( | |
| "code-server: `/code/`\n\n" | |
| "---\n" | |
| "Made with love by latemate\n" | |
| "Updated by @conabe511" | |
| ) | |
| btn = gr.Button("health check") | |
| box = gr.Textbox() | |
| btn.click(health, outputs=box) | |
| client = httpx.AsyncClient(base_url=CODE_BACKEND, timeout=None) | |
| HOP_BY_HOP = {"transfer-encoding", "connection", "keep-alive", "content-length"} | |
| def strip(path): | |
| return path[len("/code"):] or "/" | |
| async def code_http(request): | |
| if request.url.path == "/code": | |
| return RedirectResponse("/code/") | |
| url = httpx.URL(path=strip(request.url.path), query=request.url.query.encode()) | |
| content = request.stream() if request.method in ("POST", "PUT", "PATCH", "DELETE") else None | |
| headers = [(k, v) for k, v in request.headers.raw] | |
| headers.append((b"x-forwarded-proto", b"https")) | |
| upstream = client.build_request(request.method, url, headers=headers, content=content) | |
| resp = await client.send(upstream, stream=True) | |
| out = {k.decode(): v.decode() for k, v in resp.headers.raw if k.decode().lower() not in HOP_BY_HOP} | |
| return StreamingResponse(resp.aiter_raw(), status_code=resp.status_code, | |
| headers=out, background=BackgroundTask(resp.aclose)) | |
| async def code_ws(websocket): | |
| subprotocols = websocket.scope.get("subprotocols") or [] | |
| await websocket.accept(subprotocol=subprotocols[0] if subprotocols else None) | |
| target = f"ws://127.0.0.1:{CODE_PORT}{strip(websocket.url.path)}" | |
| if websocket.url.query: | |
| target += "?" + websocket.url.query | |
| fwd = {} | |
| if websocket.headers.get("cookie"): | |
| fwd["cookie"] = websocket.headers["cookie"] | |
| kwargs = dict(subprotocols=subprotocols or None, max_size=None, open_timeout=30) | |
| try: | |
| try: | |
| upstream = await websockets.connect(target, additional_headers=fwd, **kwargs) | |
| except TypeError: | |
| upstream = await websockets.connect(target, extra_headers=fwd, **kwargs) | |
| except Exception: | |
| try: | |
| await websocket.close() | |
| except Exception: | |
| pass | |
| return | |
| async def client_to_upstream(): | |
| try: | |
| while True: | |
| msg = await websocket.receive() | |
| if msg["type"] == "websocket.disconnect": | |
| break | |
| if msg.get("bytes") is not None: | |
| await upstream.send(msg["bytes"]) | |
| elif msg.get("text") is not None: | |
| await upstream.send(msg["text"]) | |
| except Exception: | |
| pass | |
| finally: | |
| await upstream.close() | |
| async def upstream_to_client(): | |
| try: | |
| async for message in upstream: | |
| if isinstance(message, (bytes, bytearray)): | |
| await websocket.send_bytes(message) | |
| else: | |
| await websocket.send_text(message) | |
| except Exception: | |
| pass | |
| finally: | |
| try: | |
| await websocket.close() | |
| except Exception: | |
| pass | |
| await asyncio.gather(client_to_upstream(), upstream_to_client()) | |
| if __name__ == "__main__": | |
| start_code_server() | |
| demo.launch( | |
| server_name="0.0.0.0", | |
| server_port=int(os.environ.get("PORT", "7860")), | |
| ssr_mode=False, | |
| prevent_thread_lock=True, | |
| ) | |
| # Insert before Gradio's own catch-all routes. | |
| demo.app.router.routes[0:0] = [ | |
| WebSocketRoute("/code", code_ws), | |
| WebSocketRoute("/code/{path:path}", code_ws), | |
| Route("/code", code_http, methods=METHODS), | |
| Route("/code/{path:path}", code_http, methods=METHODS), | |
| ] | |
| demo.block_thread() |