StillWorking commited on
Commit
0bde491
Β·
verified Β·
1 Parent(s): c119f0b

Upload backend/main.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. backend/main.py +188 -0
backend/main.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ main.py β€” Sentinel-AI
3
+ =========================
4
+ FastAPI application entry point.
5
+
6
+ Start the server (loopback by default; use --host 0.0.0.0 only with
7
+ SENTINEL_API_KEY and a TLS reverse proxy):
8
+ uvicorn main:app --host 127.0.0.1 --port 8000 --reload
9
+
10
+ Swagger UI: http://localhost:8000/docs
11
+ ReDoc: http://localhost:8000/redoc
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import os
17
+ from contextlib import asynccontextmanager
18
+ from pathlib import Path
19
+
20
+ from dotenv import load_dotenv
21
+
22
+ # Load .env β€” check backend dir first, then fall back to project root.
23
+ _backend_env = Path(__file__).parent / ".env"
24
+ _root_env = Path(__file__).parent.parent / ".env"
25
+
26
+ # Load backend .env first (takes precedence), then root .env as fallback.
27
+ load_dotenv(_backend_env)
28
+ load_dotenv(_root_env)
29
+
30
+ from fastapi import FastAPI
31
+ from fastapi.middleware.cors import CORSMiddleware
32
+
33
+ from api.routes.analyze import router as analyze_router
34
+ from api.routes.generate import router as generate_router
35
+ from api.routes.search import router as search_router
36
+ from api.schemas import HealthResponse
37
+ from core.faiss_store import (
38
+ get_faiss_order,
39
+ get_index,
40
+ get_metadata,
41
+ warm_attribute_index,
42
+ )
43
+ from core.models import (
44
+ detector_ready,
45
+ embedder_ready,
46
+ load_adaface,
47
+ load_face_detector,
48
+ )
49
+ from core.paths import resolve_path
50
+ from core.security import install_security
51
+
52
+
53
+ def _cors_origins() -> list[str]:
54
+ """
55
+ Read CORS_ORIGINS as a comma-separated list.
56
+
57
+ Defaults to the local Vite dev server. Set ``CORS_ORIGINS=*`` to allow
58
+ every origin (the old hard-coded behaviour) when explicitly desired.
59
+ """
60
+ raw = os.getenv(
61
+ "CORS_ORIGINS",
62
+ "http://localhost:5173,http://127.0.0.1:5173,"
63
+ "http://localhost:3000,http://127.0.0.1:3000,"
64
+ "http://localhost:8080,http://127.0.0.1:8080,"
65
+ "http://localhost:4173,http://127.0.0.1:4173",
66
+ )
67
+ origins = [origin.strip() for origin in raw.split(",") if origin.strip()]
68
+ return origins or ["http://localhost:5173"]
69
+
70
+
71
+ # ─────────────────────────────────────────────────────────────────────────────
72
+ # Lifespan: warm-up all heavy singletons at startup
73
+ # ─────────────────────────────────────────────────────────────────────────────
74
+
75
+ @asynccontextmanager
76
+ async def lifespan(app: FastAPI):
77
+ """Load models and FAISS index once at startup."""
78
+ print("[Sentinel-AI] Warming up models and index ...")
79
+
80
+ # 1. Initialise cascadeflow harness β€” must run before any cascadeflow.run() scope
81
+ import cascadeflow
82
+
83
+ cf_report = cascadeflow.init(mode="enforce")
84
+ version = getattr(cascadeflow, "__version__", "unknown")
85
+ print(
86
+ f" [OK] cascadeflow {version} "
87
+ f"mode={cf_report.mode} instrumented={cf_report.instrumented}"
88
+ )
89
+
90
+ # 2. Load local CV models (MTCNN detector + AdaFace embedder)
91
+ try:
92
+ load_face_detector()
93
+ print(" [OK] MTCNN face detector loaded")
94
+ except Exception as exc:
95
+ print(f" [FAIL] MTCNN detector not available: {exc}")
96
+
97
+ try:
98
+ load_adaface()
99
+ print(" [OK] AdaFace embedder loaded")
100
+ except Exception as exc:
101
+ print(f" [FAIL] AdaFace not available: {exc}")
102
+
103
+ # 3. Load FAISS index + metadata into RAM and build the vectorised
104
+ # attribute matrix used by semantic search (one-off, ~8 MB).
105
+ try:
106
+ idx = get_index()
107
+ get_metadata()
108
+ get_faiss_order()
109
+ warm_attribute_index()
110
+ print(f" [OK] FAISS index loaded ({idx.ntotal:,} vectors)")
111
+ print(" [OK] Attribute index warmed")
112
+ except FileNotFoundError as exc:
113
+ print(f" [FAIL] {exc}")
114
+ except Exception as exc:
115
+ print(f" [FAIL] Attribute index warm-up failed: {exc}")
116
+
117
+ # 4. Pre-warm provider clients (validates keys, keeps first request fast)
118
+ from core.gemini_agent import warm_providers
119
+
120
+ warmed = warm_providers()
121
+ if warmed:
122
+ print(f" [OK] LLM clients warmed: {', '.join(warmed)}")
123
+ else:
124
+ print(" [WARN] No cloud LLM clients configured; using offline fallbacks")
125
+
126
+ print("[Sentinel-AI] Ready.")
127
+ yield
128
+ print("[Sentinel-AI] Shutting down.")
129
+
130
+
131
+ # ─────────────────────────────────────────────────────────────────────────────
132
+ # App
133
+ # ─────────────────────────────────────────────────────────────────────────────
134
+
135
+ app = FastAPI(
136
+ title="Sentinel-AI",
137
+ description=(
138
+ "Hybrid edge-cloud security agent. "
139
+ "Detects faces via MTCNN, embeds them with AdaFace, "
140
+ "searches 200k CelebA vectors in FAISS, and drafts alerts with Gemini."
141
+ ),
142
+ version="1.0.0",
143
+ docs_url="/docs",
144
+ redoc_url="/redoc",
145
+ lifespan=lifespan,
146
+ )
147
+
148
+ # Install security *before* CORS: Starlette makes the last-added middleware
149
+ # outermost, and CORS must wrap auth so preflight OPTIONS requests are answered.
150
+ install_security(app)
151
+
152
+ app.add_middleware(
153
+ CORSMiddleware,
154
+ allow_origins=_cors_origins(),
155
+ allow_methods=["GET", "POST", "OPTIONS"],
156
+ allow_headers=["Content-Type", "Authorization", "X-API-Key"],
157
+ )
158
+
159
+ # ── Routers ───────────────────────────────────────────────────────────────────
160
+ app.include_router(analyze_router, prefix="/api/v1", tags=["Inference"])
161
+ app.include_router(search_router, prefix="/api/v1", tags=["Search"])
162
+ app.include_router(generate_router, prefix="/api/v1", tags=["Generation"])
163
+
164
+
165
+ # ── Health check ──────────────────────────────────────────────────────────────
166
+ @app.get("/health", response_model=HealthResponse, tags=["System"])
167
+ async def health() -> HealthResponse:
168
+ """Liveness probe with real index/model readiness telemetry."""
169
+ index_path = resolve_path(
170
+ os.getenv("FAISS_INDEX_PATH"),
171
+ "./index_artifacts/celeb_index.faiss",
172
+ )
173
+ index_ready = index_path.exists()
174
+ index_vectors: int | None = None
175
+ if index_ready:
176
+ try:
177
+ index_vectors = int(get_index().ntotal)
178
+ except Exception:
179
+ index_ready = False
180
+
181
+ return HealthResponse(
182
+ status="ok",
183
+ index_ready=index_ready,
184
+ index_vectors=index_vectors,
185
+ detector_ready=detector_ready(),
186
+ embedder_ready=embedder_ready(),
187
+ model=os.getenv("GEMINI_MODEL", "gemini-2.5-flash"),
188
+ )