from __future__ import annotations import mimetypes import os from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from urllib.parse import unquote, urlparse ROOT = Path(__file__).resolve().parent DEFAULT_STATIC_ROOT = ROOT / "dist" if (ROOT / "dist" / "app.html").is_file() else ROOT STATIC_ROOT = Path(os.environ.get("STATIC_ROOT", DEFAULT_STATIC_ROOT)).resolve() APP_FILE = STATIC_ROOT / "app.html" PORT = int(os.environ.get("PORT", "7860")) APP_ROUTES = {"", "devices", "accelerators", "systems", "models", "compare", "bounds"} class Handler(SimpleHTTPRequestHandler): def do_GET(self) -> None: self.serve_app_request(include_body=True) def do_HEAD(self) -> None: self.serve_app_request(include_body=False) def serve_app_request(self, include_body: bool) -> None: parsed = urlparse(self.path) path = unquote(parsed.path).lstrip("/") candidate = (STATIC_ROOT / path).resolve() if path.startswith("assets/") and candidate.is_file() and STATIC_ROOT in candidate.parents: self.send_file(candidate, include_body=include_body) return route = path.split("/", 1)[0] if route in APP_ROUTES: self.send_file(APP_FILE, include_body=include_body) return if "." in Path(path).name and not candidate.exists(): self.send_error(404, "File not found") return self.send_file(APP_FILE, include_body=include_body) def send_file(self, path: Path, include_body: bool = True) -> None: content_type = mimetypes.guess_type(path.name)[0] or "application/octet-stream" data = path.read_bytes() self.send_response(200) self.send_header("Content-Type", content_type) self.send_header("Content-Length", str(len(data))) self.send_header("Cache-Control", "no-cache") self.end_headers() if include_body: self.wfile.write(data) if __name__ == "__main__": server = ThreadingHTTPServer(("0.0.0.0", PORT), Handler) print(f"Serving Local Frontier on :{PORT}", flush=True) server.serve_forever()