-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalytics_app.py
More file actions
185 lines (146 loc) · 5.06 KB
/
analytics_app.py
File metadata and controls
185 lines (146 loc) · 5.06 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
"""
FastAPI Application for Intelligence Knowledge Graph Analytics
Standalone app for testing analytics endpoints.
In production, integrate this into your main backend/api/main.py
Author: Federico Chiaradia
Date: 2025-12-12
"""
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from neo4j import GraphDatabase
from contextlib import asynccontextmanager
import logging
from backend.api.analytics_api import router as analytics_router, initialize_analytics, _analytics
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
# Neo4j connection settings
NEO4J_URI = "bolt://localhost:7687"
NEO4J_USER = "neo4j"
NEO4J_PASSWORD = "password123" # Update if you changed it
# Global Neo4j driver
driver = None
@asynccontextmanager
async def lifespan(app: FastAPI):
"""
Lifespan context manager for startup and shutdown events.
Handles Neo4j connection lifecycle.
"""
global driver
# Startup
logger.info("Starting Intelligence Knowledge Graph API...")
try:
# Connect to Neo4j
driver = GraphDatabase.driver(NEO4J_URI, auth=(NEO4J_USER, NEO4J_PASSWORD))
# Verify connection
with driver.session() as session:
result = session.run("RETURN 1")
result.single()
logger.info(f" Connected to Neo4j at {NEO4J_URI}")
# Initialize analytics service
initialize_analytics(driver)
logger.info(" Analytics service initialized")
# Load graph from Neo4j (eager loading for better UX)
import backend.api.analytics_api as an_ap
logger.info(" Loading graph from Neo4j...")
an_ap._analytics.load_graph_from_neo4j()
node_count = an_ap._analytics.graph.number_of_nodes()
edge_count = an_ap._analytics.graph.number_of_edges()
logger.info(f" Graph loaded: {node_count} nodes, {edge_count} edges")
except Exception as e:
logger.error(f" Failed to initialize: {e}")
raise
yield
# Shutdown
logger.info("Shutting down...")
if driver:
driver.close()
logger.info(" Neo4j connection closed")
# Create FastAPI app
app = FastAPI(
title="Intelligence Knowledge Graph - Analytics API",
description="""
Advanced graph analytics for intelligence knowledge graphs.
## Features
- **PageRank Centrality** - Identify most important entities
- **Community Detection** - Discover network clusters using Louvain algorithm
- **Network Metrics** - Global graph statistics and health indicators
- **Node Analysis** - Detailed importance analysis for specific entities
- **Key Connectors** - Find bridge nodes that connect different clusters
## Authentication
Currently no authentication required (development mode).
Add API keys or OAuth for production deployment.
## Rate Limiting
Not implemented. Consider adding for production:
- 100 requests/minute per IP
- 1000 requests/hour per user
## Contact
- **Author**: Federico Chiaradia
- **GitHub**: [https://github.com/Fredbcx](https://github.com/Fredbcx)
- **LinkedIn**: [LinkedIn Profile](https://www.linkedin.com/in/federico-chiaradia-b6b814164/)
""",
version="1.0.0",
lifespan=lifespan,
docs_url="/docs",
redoc_url="/redoc"
)
# CORS middleware (for frontend development)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # In production: specify exact origins
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Include analytics router
app.include_router(analytics_router)
@app.get("/", tags=["Root"])
async def root():
"""
Root endpoint - API information and available routes.
"""
return {
"name": "Intelligence Knowledge Graph - Analytics API",
"version": "1.0.0",
"status": "operational",
"documentation": "/docs",
"endpoints": {
"health": "/analytics/health",
"pagerank": "/analytics/pagerank",
"communities": "/analytics/communities",
"metrics": "/analytics/metrics",
"node_importance": "/analytics/node/{node_id}/importance",
"connectors": "/analytics/connectors",
"refresh": "/analytics/refresh (POST)"
},
"author": "Federico Chiaradia"
}
@app.get("/health", tags=["Root"])
async def health():
"""
Simple health check for load balancers.
For detailed analytics health, use /analytics/health
"""
return {
"status": "healthy",
"service": "analytics-api"
}
if __name__ == "__main__":
import uvicorn
print("=" * 70)
print("INTELLIGENCE KNOWLEDGE GRAPH - ANALYTICS API")
print("=" * 70)
print(f"Starting server...")
print(f"API Documentation: http://localhost:8000/docs")
print(f"Alternative Docs: http://localhost:8000/redoc")
print("=" * 70)
uvicorn.run(
"analytics_app:app",
host="0.0.0.0",
port=8000,
reload=True, # Auto-reload on code changes
log_level="info"
)