Download app.py from nexus4rd/README: direct link, hf CLI and curl.
- Browser
- Download file 2.14 kB
-
https://huggingface.co/spaces/nexus4rd/README/resolve/main/app.py
- Command line
-
hf download hf://spaces/nexus4rd/README/app.py
-
curl -L -o app.py https://huggingface.co/spaces/nexus4rd/README/resolve/main/app.py
2.14 kB
| from fastapi import FastAPI, Request, HTTPException | |
| from fastapi.responses import HTMLResponse | |
| from fastapi.templating import Jinja2Templates | |
| from pathlib import Path | |
| import os | |
| import asyncio | |
| import logging | |
| import requests | |
| from dotenv import load_dotenv | |
| from subprocess import Popen | |
| from bot import run_bot | |
| import threading | |
| logging.basicConfig(level=logging.DEBUG) | |
| load_dotenv() | |
| app = FastAPI() | |
| templates = Jinja2Templates(directory="templates") | |
| def get_css(): | |
| static_folder = Path("templates") | |
| css_file = static_folder / "output.css" | |
| if not css_file.exists(): | |
| raise HTTPException(status_code=500, detail="CSS file not found.") | |
| return css_file.read_text() | |
| def get_ngrok_tunnels(): | |
| api_key = os.getenv("NGROK_API_KEY") | |
| if not api_key: | |
| raise HTTPException(status_code=500, detail="Ngrok API key not found.") | |
| headers = { | |
| "Authorization": f"Bearer {api_key}", | |
| "Ngrok-Version": "2" | |
| } | |
| try: | |
| response = requests.get("https://api.ngrok.com/tunnels", headers=headers) | |
| response.raise_for_status() | |
| except requests.RequestException as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| tunnels = response.json().get("tunnels", []) | |
| endpoints = [tunnel.get("public_url", "").replace("tcp://", "") | |
| for tunnel in tunnels if tunnel.get("proto") == "tcp"] | |
| return endpoints | |
| def determine_port(): | |
| BASE_URL = os.getenv("BASE_URL", "https://huggingface.co/spaces/nexus4rd/ngrok") | |
| if "herokuapp.com" in BASE_URL: | |
| return int(os.environ.get("PORT", 80)) | |
| elif "hf.co" in BASE_URL: | |
| return 7860 | |
| else: | |
| return int(os.environ.get("BASE_URL_PORT", 7860)) | |
| async def startup_event(): | |
| bot_thread = threading.Thread(target=run_bot, daemon=True) | |
| bot_thread.start() | |
| async def read_root(request: Request): | |
| endpoints = get_ngrok_tunnels() | |
| css = get_css() | |
| return templates.TemplateResponse( | |
| "index.html", | |
| {"request": request, "endpoints": endpoints, "css": css} | |
| ) |