File size: 2,142 Bytes
2dcc8b0 3a838fc 19bcfa8 3a838fc cf603eb 32455f4 3a838fc 2104622 37f1b8e 1423e9b 3a838fc 32455f4 3a838fc 19bcfa8 8b63213 3a838fc 2dcc8b0 3a838fc 2dcc8b0 3a838fc 2dcc8b0 3a838fc 2104622 092612e 2104622 3a838fc 2104622 8b63213 1533000 de0bb9a 8b63213 3a838fc 19bcfa8 151cc6a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | 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))
@app.on_event("startup")
async def startup_event():
bot_thread = threading.Thread(target=run_bot, daemon=True)
bot_thread.start()
@app.get("/", response_class=HTMLResponse)
async def read_root(request: Request):
endpoints = get_ngrok_tunnels()
css = get_css()
return templates.TemplateResponse(
"index.html",
{"request": request, "endpoints": endpoints, "css": css}
) |