CyberSecure / main.py
cloud450's picture
Update main.py
550d1a6 verified
Raw
History Blame Contribute Delete
1.84 kB
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from routers import predict, monitor, reports, upload, blockchain
from dotenv import load_dotenv
import os
# Load environment variables
load_dotenv()
# Trigger reload
# Configure root_path
# 1. Try explicit ROOT_PATH env var (User preference)
root_path = os.getenv("ROOT_PATH")
# 2. If not set, try auto-detecting Hugging Face Spaces (Fallback)
if not root_path:
space_id = os.getenv("SPACE_ID")
if space_id:
# SPACE_ID is usually "username/spacename"
root_path = f"/spaces/{space_id}"
print(f"Auto-detected HF Space. Setting root_path to: {root_path}")
else:
root_path = ""
app = FastAPI(
title="Network IDS API",
description="Backend API for Intrusion Detection System",
version="1.0.0",
root_path=root_path
)
# Configure CORS
# Default to ["*"] if not set. To restrict, set ALLOWED_ORIGINS="http://localhost:3000,https://my-app.hf.space"
origins_env = os.getenv("ALLOWED_ORIGINS", "*")
if origins_env == "*":
origins = ["*"]
else:
origins = [origin.strip() for origin in origins_env.split(",") if origin.strip()]
print(f"Allowed CORS Origins: {origins}")
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Routers
app.include_router(predict.router, prefix="/predict", tags=["Prediction"])
app.include_router(monitor.router, prefix="/monitor", tags=["Live Monitor"])
app.include_router(reports.router, prefix="/reports", tags=["Threat Reports"])
app.include_router(upload.router, prefix="/upload", tags=["File Upload"])
app.include_router(blockchain.router, prefix="/blockchain", tags=["Blockchain"])
@app.get("/")
def home():
return {"message": "Network IDS Backend Running!"}