Emmanuel Frimpong Asante
update space
1c76223
raw
history blame
3.51 kB
# app.py
from typing import Optional
from fastapi import FastAPI, Request, HTTPException, BackgroundTasks, Depends
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
import tensorflow as tf
import os
import logging
import time
from routes.authentication import auth_router
from routes.disease_detection import disease_router
from routes.administration import dashboard_router
from services.health_monitoring_service import evaluate_health_data, send_alerts
from services.auth_service import optional_get_current_user
from services.utils import db
from huggingface_hub import login
# Setup logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
logger = logging.getLogger(__name__)
# Check GPU availability for TensorFlow
gpu_devices = tf.config.list_physical_devices('GPU')
logger.info(f"{'GPUs available' if gpu_devices else 'Using CPU'} for TensorFlow")
# Initialize FastAPI app and templates
app = FastAPI()
templates = Jinja2Templates(directory="templates")
# Mount static files if directory exists
static_dir = "static"
if os.path.isdir(static_dir):
app.mount("/static", StaticFiles(directory=static_dir), name="static")
logger.info("Mounted static directory at /static")
else:
logger.error("Static directory not found.")
raise HTTPException(status_code=500, detail="Static directory not found.")
# Load Hugging Face Token
HF_TOKEN = os.environ.get("HF_Token")
if HF_TOKEN:
login(token=HF_TOKEN, add_to_git_credential=True)
else:
logger.warning("Hugging Face token not found in environment variables.")
# Include routers for different modules
app.include_router(auth_router, prefix="/auth", tags=["Authentication"])
app.include_router(disease_router, prefix="/disease", tags=["Disease Detection"])
app.include_router(dashboard_router, prefix="/admin", tags=["Admin Dashboard"])
@app.get("/", response_class=HTMLResponse)
async def landing_page(request: Request): # current_user: Optional[str] = Depends(optional_get_current_user)):
"""
Render the landing page if not logged in, otherwise redirect to the appropriate dashboard based on user role.
"""
# if current_user:
# user_data = db.get_collection("users").find_one({"username": current_user})
# if user_data:
# user_role = user_data.get("role", "farmer")
# redirect_url = "/admin/dashboard"
# logger.info(f"Redirecting {current_user} to {redirect_url}")
# return RedirectResponse(url=redirect_url)
return templates.TemplateResponse("index.html", {"request": request})
# Health metrics for periodic monitoring
health_metrics = {
"weight_loss_percentage": 6,
"mortality_rate": 1,
"reduced_feed_intake_percentage": 12
}
def monitor_health():
"""Evaluate health data and log notifications if thresholds are crossed."""
while True:
notifications = evaluate_health_data(health_metrics)
if notifications["notifications"]:
logger.info(f"Health Notifications: {notifications['notifications']}")
send_alerts(notifications["notifications"], os.getenv("FARMER_EMAIL"))
time.sleep(3600) # Run every hour
@app.on_event("startup")
async def startup_event():
"""Initialize background health monitoring on startup."""
logger.info("Starting background health monitoring.")
BackgroundTasks().add_task(monitor_health)