Spaces:
Sleeping
Sleeping
Download app/main.py from coderuday21/satdetect-dev: direct link, hf CLI and curl.
- Browser
- Download file 59.9 kB
-
https://huggingface.co/spaces/coderuday21/satdetect-dev/resolve/main/app/main.py
- Command line
-
hf download hf://spaces/coderuday21/satdetect-dev/app/main.py
-
curl -L -o main.py https://huggingface.co/spaces/coderuday21/satdetect-dev/resolve/main/app/main.py
59.9 kB
import base64
import io
import json
import os
import uuid
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Optional
try:
from dotenv import load_dotenv
load_dotenv(Path(__file__).resolve().parent.parent / ".env")
except ImportError:
pass
from jose import JWTError, jwt
from sqlalchemy import text as sa_text
from fastapi import FastAPI, Depends, File, Form, HTTPException, Query, Request, UploadFile
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse, Response
from fastapi.staticfiles import StaticFiles
from starlette.exceptions import HTTPException as StarletteHTTPException
from fastapi.exception_handlers import http_exception_handler as starlette_http_exception_handler
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel, EmailStr, field_validator
from sqlalchemy.orm import Session
from PIL import Image, ImageOps
from .auth import (
ALGORITHM,
COOKIE_NAME,
COOKIE_SAMESITE,
IS_SECURE_COOKIE,
LOGIN_OTP_EXPIRE_MINUTES,
LOGIN_OTP_RESEND_SECONDS,
SECRET_KEY,
check_account_lockout,
check_ip_throttle,
consume_password_reset_token,
create_access_token,
create_login_otp,
create_password_reset_token,
get_client_ip,
get_password_hash,
get_user_by_email,
get_user_by_phone,
get_current_user,
get_or_create_guest_user,
get_user_agent,
get_user_from_token,
latest_unused_otp,
mask_email,
normalize_phone,
record_login_event,
revoke_user_sessions,
verify_login_otp,
verify_password,
)
from .database import Base, engine, get_db, DATA_DIR
from .models import User, DetectionRun, LoginHistory, PasswordResetToken, LoginOtp # noqa: F401 — LoginHistory/PasswordResetToken/LoginOtp registered on Base.metadata for create_all()
from . import dda as _dda_pkg # noqa: F401 — register DDA tables
from .dda.models import DdaZone, DdaVillage, ImageAsset, DetectionJob, RegionReview, AutoPairSchedule, AutoDetectSettings # noqa: F401
from .dda.tree.models import TreeNode, ImageLibrary, AuditLog # noqa: F401
from .dda.rbac.models import Role, Module, RolePermission, MenuItem # noqa: F401
from .dda.rbac.permissions import get_user_role_row, resolve_user_menu, user_can
from .dda.config import IS_DDA_MODE
from .dda.bootstrap import init_dda_database, setup_dda
from .notifier import send_login_otp_email, send_notification, send_password_reset_email, send_test_email
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
try:
from .dda.applog import install_app_log_handler
install_app_log_handler()
except Exception:
pass
logger.info("Importing AI Change Detection app module")
_IST = timezone(timedelta(hours=5, minutes=30))
def _isoformat_ist(dt):
"""Convert a UTC datetime to IST (GMT+5:30) and return ISO-8601 string."""
if dt is None:
return None
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
return dt.astimezone(_IST).isoformat()
# Create tables and run migrations without crashing the app (HF Spaces can restart if startup fails)
try:
logger.info("Running database initialization")
Base.metadata.create_all(bind=engine, checkfirst=True)
with engine.connect() as conn:
for col, col_type in [
("zone", "VARCHAR(128) DEFAULT ''"),
("village", "VARCHAR(128) DEFAULT ''"),
("before_full_path", "VARCHAR(512) DEFAULT ''"),
("before_thumb_path", "VARCHAR(512) DEFAULT ''"),
("after_thumb_path", "VARCHAR(512) DEFAULT ''"),
]:
try:
conn.execute(sa_text(
f"ALTER TABLE detection_runs ADD COLUMN {col} {col_type}"))
conn.commit()
except Exception:
conn.rollback()
logger.info("Database initialization complete")
init_dda_database()
except Exception as e:
import logging
logging.getLogger("uvicorn.error").warning("Startup migration skipped: %s", e)
app = FastAPI(title="AI Change Detection", version="2.4.0-dda" if IS_DDA_MODE else "2.2.0")
setup_dda(app)
def _exception_log_user(request: Request) -> tuple[str | None, str | None]:
"""Best-effort user email + role for the exception log — never raises."""
try:
from .database import SessionLocal
from .dda.dda_auth import get_user_role
token = request.cookies.get("access_token") or request.cookies.get(COOKIE_NAME)
if not token:
return None, None
db = SessionLocal()
try:
user = get_user_from_token(token, db)
if not user:
return None, None
email = user.email if user else None
role = get_user_role(db, user) if user else None
return email, role
finally:
db.close()
except Exception:
return None, None
@app.exception_handler(StarletteHTTPException)
async def _dda_http_exception_handler(request: Request, exc: StarletteHTTPException):
"""Log every deliberate HTTPException (401/404/429/...) as a handled exception."""
if IS_DDA_MODE:
try:
from .database import SessionLocal
from .dda.tree.audit_service import log_exception
db = SessionLocal()
try:
email, role = _exception_log_user(request)
log_exception(
db, exc=exc, path=request.url.path, method=request.method,
status_code=exc.status_code, handled=True,
user_email=email, user_role=role,
)
finally:
db.close()
except Exception:
logger.exception("Failed to write exception log entry")
return await starlette_http_exception_handler(request, exc)
@app.exception_handler(Exception)
async def _dda_unhandled_exception_handler(request: Request, exc: Exception):
"""Log every uncaught exception as unhandled, then return a generic 500."""
logger.exception("Unhandled exception on %s %s", request.method, request.url.path)
if IS_DDA_MODE:
try:
from .database import SessionLocal
from .dda.tree.audit_service import log_exception
db = SessionLocal()
try:
email, role = _exception_log_user(request)
log_exception(
db, exc=exc, path=request.url.path, method=request.method,
status_code=500, handled=False,
user_email=email, user_role=role,
)
finally:
db.close()
except Exception:
logger.exception("Failed to write exception log entry")
return JSONResponse(status_code=500, content={"detail": f"Internal server error: {type(exc).__name__}"})
# --- Global auth backstop ---------------------------------------------------
# Every page/API route is expected to gate itself (a per-route dependency or
# a manual check in the function body) — see the RBAC audit that found
# /api/overlay, /api/detect, and /dda/reports/{id} had silently lost theirs.
# This middleware is a defense-in-depth backstop: it rejects any request to a
# non-public path with no valid session before it ever reaches a route
# handler, so a future route that forgets its own login check still fails
# closed instead of silently serving an unauthenticated request. It only
# enforces "is logged in" — per-module/action permission checks (view/
# create/edit/delete) remain each route's own responsibility.
_PUBLIC_EXACT_PATHS = {
"/health",
"/login",
"/forgot-password",
"/reset-password",
"/favicon.ico",
"/docs",
"/redoc",
"/openapi.json",
"/api/auth/register",
"/api/auth/login",
"/api/auth/login/request-otp",
"/api/auth/login/verify-otp",
"/api/auth/login/resend-otp",
"/api/auth/logout",
"/api/auth/reset-password",
"/api/auth/forgot-password",
"/api/auth/reset-password-token",
}
_PUBLIC_PATH_PREFIXES = ("/static/",)
def _request_has_valid_session(request: Request) -> bool:
auth_header = request.headers.get("authorization", "")
token = auth_header.split(" ", 1)[1].strip() if auth_header.lower().startswith("bearer ") else None
if not token:
token = request.cookies.get(COOKIE_NAME)
if not token:
return False
from .database import SessionLocal
db = SessionLocal()
try:
user = get_user_from_token(token, db)
return bool(user) and not user.email.startswith("__guest__")
finally:
db.close()
@app.middleware("http")
async def _dda_global_auth_gate(request: Request, call_next):
if not IS_DDA_MODE or request.method == "OPTIONS":
return await call_next(request)
path = request.url.path
if path in _PUBLIC_EXACT_PATHS or path.startswith(_PUBLIC_PATH_PREFIXES):
return await call_next(request)
if _request_has_valid_session(request):
return await call_next(request)
if path.startswith("/api/"):
return JSONResponse(status_code=401, content={"detail": "Not authenticated"})
return RedirectResponse(url="/login")
@app.get("/health")
def health():
"""Health check + AdaptFormer model status (HF Spaces + diagnostics)."""
from datetime import datetime
from .model_inference import get_model_status
model = get_model_status()
payload = {
"status": "ok" if model.get("available") else "degraded",
"version": "2.4.0-dda" if IS_DDA_MODE else "2.2.1",
"appMode": "dda" if IS_DDA_MODE else "legacy",
"spaceId": os.environ.get("SPACE_ID", ""),
"server_time_ist": _isoformat_ist(datetime.now(timezone.utc)),
"adaptFormer": model,
}
if IS_DDA_MODE:
try:
from .dda.job_runner import is_job_runner_busy
from .dda.tree.image_service import count_library_images
from .database import SessionLocal
_sdb = SessionLocal()
try:
lib_count = count_library_images(_sdb)
finally:
_sdb.close()
payload["dda"] = {
"libraryImages": lib_count,
"jobRunnerBusy": is_job_runner_busy(),
}
except Exception as exc:
payload["dda"] = {"error": str(exc)[:200]}
return payload
@app.on_event("startup")
def log_startup():
logger.info("FastAPI startup event completed")
try:
from .model_inference import preload_model
preload_model()
except Exception as exc:
logger.warning("Model preload at startup failed: %s", exc)
try:
from .dda.auto_detect import start_auto_detect_scheduler
start_auto_detect_scheduler()
except Exception as exc:
logger.warning("Auto-detect scheduler failed to start: %s", exc)
# Mount static files
STATIC_DIR = Path(__file__).resolve().parent.parent / "static"
TEMPLATES_DIR = Path(__file__).resolve().parent.parent / "templates"
OVERLAYS_DIR = DATA_DIR / "overlays"
try:
OVERLAYS_DIR.mkdir(parents=True, exist_ok=True)
except Exception:
pass
THUMB_MAX_SIZE = 200 # max width or height for history thumbnails
if STATIC_DIR.exists():
app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
@app.middleware("http")
async def _static_cache_control(request: Request, call_next):
"""Long-lived cache for versioned /static assets (?v= busting on script tags)."""
response = await call_next(request)
if request.url.path.startswith("/static/"):
response.headers.setdefault(
"Cache-Control",
"public, max-age=31536000, immutable",
)
return response
templates = Jinja2Templates(directory=str(TEMPLATES_DIR))
# --- Schemas ---
class UserCreate(BaseModel):
email: EmailStr
password: str
full_name: str
phone: str = ""
country_code: str = "+91"
# Phone is kept optional so accounts can still store a mobile in Profile
# for future SMS delivery, but registration does not require it. Login
# OTP is currently delivered by email (see send_login_otp_email).
# No remember_me here — registration no longer auto-logs-in (see
# register()), so there's no session at creation time for it to apply to.
@field_validator("password")
@classmethod
def _password_strength(cls, v: str) -> str:
if len(v) < 8:
raise ValueError("Password must be at least 8 characters")
return v
@field_validator("full_name")
@classmethod
def _full_name_required(cls, v: str) -> str:
v = v.strip()
if not v:
raise ValueError("Full name is required")
return v
class UserLogin(BaseModel):
email: EmailStr
password: str
remember_me: bool = False
class OtpRequest(BaseModel):
email: EmailStr
remember_me: bool = False
class OtpVerifyRequest(BaseModel):
otpToken: str
code: str
class UserResponse(BaseModel):
id: int
email: str
full_name: str
class EmailRequest(BaseModel):
email: str
def _load_regions_json(raw_regions: Optional[str]):
try:
return json.loads(raw_regions) if raw_regions else []
except (json.JSONDecodeError, TypeError):
return []
# --- Auth routes ---
# Not remembered: short-lived JWT + a browser-session cookie (no max_age, so
# it disappears when the browser closes) — the JWT's own expiry is still a
# backstop in case the browser doesn't actually clear it.
# Remembered: both the cookie and the JWT last 30 days.
SESSION_TOKEN_EXPIRE = timedelta(days=1)
REMEMBER_ME_EXPIRE = timedelta(days=30)
def _auth_response(token: str, user: User, remember: bool = False):
"""JSON response with auth cookie so browser sends token on every request (e.g. POST /api/detect)."""
payload = {"access_token": token, "token_type": "bearer", "user": {"id": user.id, "email": user.email, "full_name": user.full_name}}
response = JSONResponse(content=payload)
cookie_kwargs = dict(
key=COOKIE_NAME,
value=token,
httponly=True,
samesite=COOKIE_SAMESITE,
secure=IS_SECURE_COOKIE,
path="/",
)
if remember:
cookie_kwargs["max_age"] = int(REMEMBER_ME_EXPIRE.total_seconds())
# else: no max_age → session cookie, cleared when the browser closes
response.set_cookie(**cookie_kwargs)
return response
@app.post("/api/auth/register")
def register(data: UserCreate, db: Session = Depends(get_db)):
email = data.email.strip().lower()
try:
phone = None
if (data.phone or "").strip():
phone = normalize_phone(data.phone, data.country_code)
if not phone:
raise HTTPException(status_code=400, detail="Enter a valid mobile number for the selected country.")
if get_user_by_phone(db, phone):
raise HTTPException(status_code=400, detail="This mobile number is already registered.")
if get_user_by_email(db, email):
raise HTTPException(status_code=400, detail="Email already registered")
hashed = get_password_hash(data.password)
user = User(
email=email,
hashed_password=hashed,
full_name=data.full_name,
phone=phone,
)
db.add(user)
db.commit()
db.refresh(user)
# Deliberately no auto-login here: account creation and signing in
# are kept as two separate, explicit steps — no cookie is set, the
# user is sent back to the sign-in form to log in themselves.
return {"ok": True, "message": "Account created. Please sign in."}
except HTTPException:
raise
except Exception as e:
logger.exception("Registration failed")
raise HTTPException(status_code=500, detail=f"Registration failed: {type(e).__name__}")
@app.post("/api/auth/login")
def login(data: UserLogin, request: Request, db: Session = Depends(get_db)):
email = data.email.strip().lower()
ip = get_client_ip(request)
ua = get_user_agent(request)
try:
# Checked before touching the User table at all, and before bcrypt
# verification (which is intentionally slow) — cheap rejection path.
if check_ip_throttle(db, ip):
record_login_event(
db, event_type="login_blocked", attempted_email=email,
failure_reason="ip_throttled", ip_address=ip, user_agent=ua,
)
raise HTTPException(status_code=429, detail="Too many attempts. Try again later.")
if check_account_lockout(db, email):
record_login_event(
db, event_type="login_blocked", attempted_email=email,
failure_reason="account_locked", ip_address=ip, user_agent=ua,
)
# Same generic message as the IP-throttle case — don't tell the
# caller which kind of lockout hit, or that the account exists.
raise HTTPException(status_code=429, detail="Too many attempts. Try again later.")
user = get_user_by_email(db, email)
if not user or not verify_password(data.password, user.hashed_password):
record_login_event(
db, event_type="login_failed", attempted_email=email,
user_id=user.id if user else None,
failure_reason="bad_password" if user else "unknown_email",
ip_address=ip, user_agent=ua,
)
raise HTTPException(status_code=401, detail="Invalid email or password")
record_login_event(
db, event_type="login_success", attempted_email=email,
user_id=user.id, ip_address=ip, user_agent=ua,
)
expires = REMEMBER_ME_EXPIRE if data.remember_me else SESSION_TOKEN_EXPIRE
token = create_access_token(data={"sub": str(user.id), "purpose": "session", "tv": int(user.token_version or 0)}, expires_delta=expires)
return _auth_response(token, user, remember=data.remember_me)
except HTTPException:
raise
except Exception as e:
logger.exception("Login failed")
raise HTTPException(status_code=500, detail=f"Login failed: {type(e).__name__}")
@app.post("/api/auth/login/request-otp")
def request_login_otp(data: OtpRequest, request: Request, db: Session = Depends(get_db)):
ip = get_client_ip(request)
ua = get_user_agent(request)
raw_email = str(data.email or "")
email = raw_email.strip().lower()
logger.info("OTP request received (raw=%r norm=%r len=%d)", raw_email, email, len(raw_email))
# NOTE: unlike the password login path, a mistyped email at "request OTP"
# is not treated as a failed sign-in attempt for throttling purposes —
# the caller hasn't tried to authenticate anything yet. We use a separate
# otp_request_blocked / otp_request_failed event so honest typos don't
# get anyone IP-throttled.
user = get_user_by_email(db, email)
if not user:
record_login_event(
db, event_type="otp_request_failed", attempted_email=email,
failure_reason="unknown_email", ip_address=ip, user_agent=ua,
)
raise HTTPException(status_code=404, detail="No account is registered with this email.")
otp_row, raw_code = create_login_otp(db, user)
_deliver_login_otp(user.email, raw_code)
pending = _otp_pending_token(user, otp_row, data.remember_me)
return {
"otpToken": pending,
"emailMasked": mask_email(user.email),
"expiresMinutes": LOGIN_OTP_EXPIRE_MINUTES,
"resendSeconds": LOGIN_OTP_RESEND_SECONDS,
}
@app.post("/api/auth/logout")
def logout(request: Request, db: Session = Depends(get_db)):
"""Record the logout, revoke the session token (and any other copy of it —
another tab, another device, or a leaked token), then clear the cookie."""
token = request.cookies.get(COOKIE_NAME)
if token:
user = get_user_from_token(token, db)
if user:
record_login_event(
db, event_type="logout", attempted_email=user.email, user_id=user.id,
ip_address=get_client_ip(request), user_agent=get_user_agent(request),
)
revoke_user_sessions(user)
db.commit()
response = JSONResponse(content={"ok": True})
response.delete_cookie(
COOKIE_NAME,
path="/",
secure=IS_SECURE_COOKIE,
samesite=COOKIE_SAMESITE,
)
return response
class PasswordReset(BaseModel):
email: str
new_password: str
@app.post("/api/auth/reset-password")
def reset_password(data: PasswordReset, db: Session = Depends(get_db)):
if len(data.new_password) < 6:
raise HTTPException(status_code=400, detail="Password must be at least 6 characters")
user = get_user_by_email(db, data.email)
if not user:
# Intentionally vague to prevent email enumeration
raise HTTPException(status_code=404, detail="No account found with that email")
user.hashed_password = get_password_hash(data.new_password)
revoke_user_sessions(user)
db.commit()
return {"ok": True, "message": "Password has been reset. You can now sign in."}
# NOTE: reset_password() above has no email verification and is kept only
# for backward compatibility with any existing caller of the base SPA's old
# flow. The DDA-mode Forgot Password page (below) uses the real token-based
# flow instead: POST /api/auth/forgot-password emails a one-time link,
# POST /api/auth/reset-password-token validates it and sets the new password.
class ForgotPasswordRequest(BaseModel):
email: str
@app.post("/api/auth/forgot-password")
def forgot_password(data: ForgotPasswordRequest, request: Request, db: Session = Depends(get_db)):
email = data.email.strip().lower()
user = get_user_by_email(db, email) if email else None
if user and not user.email.startswith("__guest__"):
raw_token = create_password_reset_token(db, user)
reset_link = f"{str(request.base_url).rstrip('/')}/reset-password?token={raw_token}"
ok, err = send_password_reset_email(user.email, reset_link)
if not ok:
logger.warning("Password reset email to %s not sent: %s", user.email, err)
# Always the same response regardless of whether the email exists or the
# send actually succeeded — anything else would let a caller enumerate
# accounts, or infer that SMTP is misconfigured.
return {"ok": True, "message": "If an account exists for that email, a reset link has been sent."}
class ResetPasswordWithToken(BaseModel):
token: str
new_password: str
@app.post("/api/auth/reset-password-token")
def reset_password_with_token(data: ResetPasswordWithToken, db: Session = Depends(get_db)):
if len(data.new_password) < 8:
raise HTTPException(status_code=400, detail="Password must be at least 8 characters")
user = consume_password_reset_token(db, data.token)
if not user:
raise HTTPException(status_code=400, detail="This reset link is invalid or has expired.")
user.hashed_password = get_password_hash(data.new_password)
revoke_user_sessions(user)
db.commit()
return {"ok": True, "message": "Password has been reset. You can now sign in."}
@app.get("/api/me")
def me(user: Optional[User] = Depends(get_current_user), db: Session = Depends(get_db)):
if not user:
raise HTTPException(status_code=401, detail="Not authenticated")
role_row = get_user_role_row(user, db)
last_login = (
db.query(LoginHistory)
.filter(LoginHistory.user_id == user.id, LoginHistory.event_type == "login_success")
.order_by(LoginHistory.created_at.desc())
.first()
)
return {
"id": user.id, "email": user.email, "full_name": user.full_name,
"phone": user.phone or "",
"role": role_row.name if role_row else (user.role or "analyst"),
"created_at": user.created_at.isoformat() if user.created_at else None,
"last_login": last_login.created_at.isoformat() if last_login else None,
}
class UpdateProfileRequest(BaseModel):
full_name: str
phone: str = ""
country_code: str = "+91"
@app.put("/api/me")
def update_me(data: UpdateProfileRequest, user: Optional[User] = Depends(get_current_user), db: Session = Depends(get_db)):
if not user:
raise HTTPException(status_code=401, detail="Not authenticated")
full_name = data.full_name.strip()
if not full_name:
raise HTTPException(status_code=400, detail="Full name is required")
phone = normalize_phone(data.phone, data.country_code)
if not phone:
raise HTTPException(status_code=400, detail="Enter a valid mobile number for the selected country.")
other = get_user_by_phone(db, phone)
if other and other.id != user.id:
raise HTTPException(status_code=400, detail="This mobile number is already registered.")
user.full_name = full_name
user.phone = phone
db.commit()
return {"ok": True, "full_name": user.full_name, "phone": user.phone}
class ChangePasswordRequest(BaseModel):
current_password: str
new_password: str
@app.post("/api/auth/change-password")
def change_password(data: ChangePasswordRequest, user: Optional[User] = Depends(get_current_user), db: Session = Depends(get_db)):
if not user:
raise HTTPException(status_code=401, detail="Not authenticated")
if not verify_password(data.current_password, user.hashed_password):
raise HTTPException(status_code=400, detail="Current password is incorrect")
if len(data.new_password) < 8:
raise HTTPException(status_code=400, detail="New password must be at least 8 characters")
user.hashed_password = get_password_hash(data.new_password)
revoke_user_sessions(user)
db.commit()
return {"ok": True, "message": "Password changed."}
class OtpResendRequest(BaseModel):
otpToken: str
def _allow_login_otp_log() -> bool:
if os.environ.get("LOGIN_OTP_LOG", "").strip().lower() in ("1", "true", "yes"):
return True
return str(os.environ.get("SPACE_ID", "")).startswith("local")
def _deliver_login_otp(email: str, raw_code: str) -> None:
"""Email the 6-digit code. Local-dev logs it if the send fails so login isn't blocked."""
ok, err = send_login_otp_email(email, raw_code, LOGIN_OTP_EXPIRE_MINUTES)
if ok:
return
logger.warning("Login OTP email to %s not sent: %s", mask_email(email), err)
if _allow_login_otp_log():
logger.warning("Login OTP for %s (email not delivered): %s", mask_email(email), raw_code)
return
raise HTTPException(status_code=503, detail="Could not send the sign-in code. Try again in a moment.")
def _otp_pending_token(user: User, otp_row: LoginOtp, remember: bool) -> str:
return create_access_token(
{
"sub": str(user.id),
"purpose": "otp_pending",
"otp": otp_row.id,
"remember": bool(remember),
},
expires_delta=timedelta(minutes=LOGIN_OTP_EXPIRE_MINUTES),
)
def _pending_otp_payload(raw_token: str) -> dict:
try:
payload = jwt.decode(raw_token, SECRET_KEY, algorithms=[ALGORITHM])
except JWTError:
raise HTTPException(status_code=401, detail="This code expired. Sign in again.")
if payload.get("purpose") != "otp_pending":
raise HTTPException(status_code=401, detail="This code expired. Sign in again.")
return payload
@app.post("/api/auth/login/verify-otp")
def verify_login_otp_route(data: OtpVerifyRequest, request: Request, db: Session = Depends(get_db)):
ip = get_client_ip(request)
ua = get_user_agent(request)
user = get_user_from_token(data.otpToken, db, allow_pending_otp=True)
if not user:
raise HTTPException(status_code=401, detail="This code expired. Sign in again.")
payload = _pending_otp_payload(data.otpToken)
try:
otp_id = int(payload.get("otp"))
except (TypeError, ValueError):
raise HTTPException(status_code=401, detail="This code expired. Sign in again.")
result = verify_login_otp(db, user, otp_id, data.code)
if result:
record_login_event(
db, event_type="login_failed", attempted_email=user.email,
user_id=user.id, failure_reason="bad_otp",
ip_address=ip, user_agent=ua,
)
if result == "expired":
raise HTTPException(status_code=401, detail="This code expired. Sign in again.")
if result == "locked":
raise HTTPException(status_code=429, detail="Too many attempts. Sign in again.")
raise HTTPException(status_code=401, detail="Invalid sign-in code.")
remember = bool(payload.get("remember"))
record_login_event(
db, event_type="login_success", attempted_email=user.email,
user_id=user.id, ip_address=ip, user_agent=ua,
)
expires = REMEMBER_ME_EXPIRE if remember else SESSION_TOKEN_EXPIRE
token = create_access_token(data={"sub": str(user.id), "purpose": "session", "tv": int(user.token_version or 0)}, expires_delta=expires)
return _auth_response(token, user, remember=remember)
@app.post("/api/auth/login/resend-otp")
def resend_login_otp(data: OtpResendRequest, request: Request, db: Session = Depends(get_db)):
user = get_user_from_token(data.otpToken, db, allow_pending_otp=True)
if not user:
raise HTTPException(status_code=401, detail="This code expired. Sign in again.")
payload = _pending_otp_payload(data.otpToken)
existing = latest_unused_otp(db, user.id)
if existing and existing.created_at:
created = existing.created_at
if created.tzinfo is None:
created = created.replace(tzinfo=timezone.utc)
wait = LOGIN_OTP_RESEND_SECONDS - (datetime.now(timezone.utc) - created).total_seconds()
if wait > 0:
raise HTTPException(
status_code=429,
detail=f"Wait {int(wait) + 1} seconds before requesting a new code.",
)
otp_row, raw_code = create_login_otp(db, user)
_deliver_login_otp(user.email, raw_code)
pending = _otp_pending_token(user, otp_row, bool(payload.get("remember")))
return {
"ok": True,
"otpToken": pending,
"emailMasked": mask_email(user.email),
"expiresMinutes": LOGIN_OTP_EXPIRE_MINUTES,
"resendSeconds": LOGIN_OTP_RESEND_SECONDS,
}
# --- Detection route ---
@app.post("/api/detect")
async def detect(
request: Request,
before: UploadFile = File(...),
after: UploadFile = File(...),
method: str = Form("AI-Based Deep Learning"),
title: str = Form("Untitled run"),
zone: str = Form(""),
village: str = Form(""),
enable_registration: bool = Form(True),
enable_normalization: bool = Form(True),
detection_sensitivity: float = Form(0.5),
min_region_area: Optional[int] = Form(None),
notify_email: Optional[str] = Form(None),
db: Session = Depends(get_db),
):
if IS_DDA_MODE:
from .dda.dda_auth import get_dda_user
from .dda.rbac.permissions import user_can
user = get_dda_user(request, db)
if not user_can(user, db, "detect", "create"):
raise HTTPException(status_code=403, detail="Missing 'create' permission on 'detect'.")
else:
user = get_or_create_guest_user(db)
MAX_UPLOAD_BYTES = 20 * 1024 * 1024 # 20 MB
def _read_upload(upload: UploadFile, field_name: str):
raw = None
try:
raw = upload.file.read()
if raw is None or len(raw) == 0:
raise HTTPException(status_code=400, detail=f"{field_name} image is empty")
if len(raw) > MAX_UPLOAD_BYTES:
raise HTTPException(status_code=400, detail="Image too large (max 20 MB)")
img = Image.open(io.BytesIO(raw))
img = ImageOps.exif_transpose(img)
return img.convert("RGB")
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=400, detail=f"Invalid {field_name} image: {e}")
finally:
try:
if raw is not None:
del raw
except Exception:
pass
before_pil = _read_upload(before, "before")
after_pil = _read_upload(after, "after")
from .dda.detect_service import clamp_detection_params
detection_sensitivity, min_region_area = clamp_detection_params(detection_sensitivity, min_region_area)
from .detection_engine import run_detection
change_mask, result_image, stats, change_regions = run_detection(
before_pil,
after_pil,
method=method,
enable_registration=enable_registration,
enable_normalization=enable_normalization,
detection_sensitivity=detection_sensitivity,
min_region_area=min_region_area,
)
# Save overlay and thumbnails for history table view
base_name = f"{user.id}_{uuid.uuid4().hex}"
overlay_filename = base_name + ".png"
overlay_path = OVERLAYS_DIR / overlay_filename
try:
overlay_path.parent.mkdir(parents=True, exist_ok=True)
except Exception:
pass
try:
Image.fromarray(result_image).save(overlay_path)
except Exception as exc:
logger.error("Failed to save overlay: %s", exc)
raise HTTPException(status_code=500, detail="Could not save result image")
relative_overlay = f"overlays/{overlay_filename}"
# Save full-resolution before image (used by the before/after slider from history)
relative_before_full = ""
relative_before_thumb = ""
relative_after_thumb = ""
try:
before_full_file = OVERLAYS_DIR / f"{base_name}_before.png"
before_pil.save(before_full_file)
relative_before_full = f"overlays/{base_name}_before.png"
before_thumb_file = OVERLAYS_DIR / f"{base_name}_before_thumb.png"
after_thumb_file = OVERLAYS_DIR / f"{base_name}_after_thumb.png"
before_thumb_pil = before_pil.copy()
before_thumb_pil.thumbnail((THUMB_MAX_SIZE, THUMB_MAX_SIZE), Image.Resampling.LANCZOS)
before_thumb_pil.save(before_thumb_file)
after_thumb_pil = after_pil.copy()
after_thumb_pil.thumbnail((THUMB_MAX_SIZE, THUMB_MAX_SIZE), Image.Resampling.LANCZOS)
after_thumb_pil.save(after_thumb_file)
relative_before_thumb = f"overlays/{base_name}_before_thumb.png"
relative_after_thumb = f"overlays/{base_name}_after_thumb.png"
except Exception as exc:
logger.warning("Failed to save thumbnails: %s", exc)
regions_serializable = [
{
"id": int(r["id"]),
"area": int(r["area"]),
"center": {"x": int(r["center"][0]), "y": int(r["center"][1])},
"bbox": {"x": int(r["bbox"][0]), "y": int(r["bbox"][1]), "w": int(r["bbox"][2]), "h": int(r["bbox"][3])},
"objectType": str(r["object_type"]),
"confidence": float(r["confidence"]),
"severity": r.get("severity", "minor"),
"subType": r.get("sub_type"),
"subTypeConfidence": float(r["sub_type_confidence"]) if r.get("sub_type_confidence") is not None else None,
"estimatedStories": r.get("estimated_stories"),
"estimatedHeightM": float(r["estimated_height_m"]) if r.get("estimated_height_m") is not None else None,
"constructionStage": r.get("construction_stage"),
}
for r in change_regions
]
total_px = int(stats["total_pixels"])
changed_px = int(stats["changed_pixels"])
unchanged_px = int(stats["unchanged_pixels"])
change_pct = float(stats["change_percentage"])
run = DetectionRun(
user_id=user.id,
title=title,
method=method,
zone=zone,
village=village,
total_pixels=total_px,
changed_pixels=changed_px,
change_percentage=change_pct,
regions_count=len(change_regions),
overlay_path=relative_overlay,
before_full_path=relative_before_full,
before_thumb_path=relative_before_thumb,
after_thumb_path=relative_after_thumb,
regions_json=json.dumps(regions_serializable),
detection_sensitivity=detection_sensitivity,
min_region_area=min_region_area,
)
db.add(run)
db.commit()
db.refresh(run)
# Read already-saved overlay for base64 (avoids re-encoding the numpy array)
overlay_b64 = base64.b64encode(overlay_path.read_bytes()).decode("utf-8")
# Send email notification if requested
notification_sent = False
notification_error = None
if notify_email and notify_email.strip():
notification_sent, notification_error = send_notification(
recipient=notify_email.strip(),
title=title,
method=method,
zone=zone,
village=village,
change_pct=change_pct,
changed_px=changed_px,
total_px=total_px,
regions=regions_serializable,
)
return {
"id": run.id,
"title": run.title,
"method": run.method,
"zone": run.zone or "",
"village": run.village or "",
"statistics": {
"totalPixels": total_px,
"changedPixels": changed_px,
"unchangedPixels": unchanged_px,
"changePercentage": change_pct,
"thresholdDebug": stats.get("threshold_debug", {}),
"params": stats.get("params", {}),
"alignmentWarning": stats.get("alignment_warning"),
"registrationOk": stats.get("params", {}).get("registration_ok"),
},
"regions": regions_serializable,
"overlayBase64Png": overlay_b64,
"overlayUrl": f"/api/overlay/{relative_overlay}",
"beforeFullUrl": f"/api/overlay/{relative_before_full}",
"beforeThumbUrl": f"/api/overlay/{relative_before_thumb}",
"afterThumbUrl": f"/api/overlay/{relative_after_thumb}",
"notificationSent": notification_sent,
"notificationError": notification_error,
"createdAt": _isoformat_ist(run.created_at),
}
@app.post("/api/notify/test")
def notify_test(
data: EmailRequest,
request: Request,
db: Session = Depends(get_db),
):
if IS_DDA_MODE:
from .dda.dda_auth import get_dda_user
get_dda_user(request, db)
else:
get_or_create_guest_user(db)
sent, error = send_test_email(data.email.strip())
if not sent:
raise HTTPException(status_code=400, detail=error or "Failed to send test email")
return {"ok": True, "message": f"Test email sent to {data.email.strip()}."}
@app.get("/api/overlay/{path:path}")
def serve_overlay(
path: str,
request: Request,
db: Session = Depends(get_db),
max_side: int | None = Query(None, ge=64, le=4096),
):
# Restrict to overlays directory
full = (OVERLAYS_DIR.parent / path).resolve()
base = OVERLAYS_DIR.parent.resolve()
try:
full.relative_to(base)
except ValueError:
raise HTTPException(404)
if not full.exists() or not full.is_file():
raise HTTPException(404)
if IS_DDA_MODE:
from .dda.dda_auth import get_dda_user
user = get_dda_user(request, db)
else:
user = get_or_create_guest_user(db)
# Result images are saved as overlays/"<owner_user_id>_<uuid>[_suffix].png"
# (see detect(), detect_service.py) — verify the requester owns the file
# (or is otherwise entitled to the run it belongs to, e.g. an
# auto-schedule run any user may view) before serving it.
from sqlalchemy import or_
run = (
db.query(DetectionRun)
.filter(or_(
DetectionRun.overlay_path == path,
DetectionRun.before_full_path == path,
DetectionRun.before_thumb_path == path,
DetectionRun.after_thumb_path == path,
DetectionRun.after_full_path == path,
))
.first()
)
if run is not None:
if IS_DDA_MODE:
from .dda.auto_detect import user_can_access_run
if not user_can_access_run(db, run.id, user.id):
raise HTTPException(404)
elif run.user_id != user.id:
raise HTTPException(404)
else:
# Not tied to a persisted run (e.g. a probability-map preview) — fall
# back to the owner-id-prefix filename convention every overlay file
# is saved with.
owner_id_str = Path(path).name.split("_", 1)[0]
if owner_id_str.isdigit() and int(owner_id_str) != user.id:
raise HTTPException(404)
# Browser viewers choke on ~50MB full overlays; downscale + cache when requested.
if max_side:
cache = full.with_name(f"{full.stem}_ms{max_side}{full.suffix}")
try:
if cache.exists() and cache.stat().st_mtime >= full.stat().st_mtime:
return FileResponse(cache, media_type="image/png")
from PIL import Image
with Image.open(full) as im:
if im.mode not in ("RGB", "RGBA"):
im = im.convert("RGBA")
w, h = im.size
longest = max(w, h)
if longest > max_side:
scale = max_side / float(longest)
im = im.resize((max(1, int(w * scale)), max(1, int(h * scale))), Image.Resampling.LANCZOS)
buf = io.BytesIO()
im.save(buf, format="PNG", optimize=True)
payload = buf.getvalue()
try:
cache.write_bytes(payload)
except Exception:
pass
return Response(content=payload, media_type="image/png")
except Exception:
pass
return FileResponse(full, media_type="image/png")
# --- History ---
@app.get("/api/history")
def history(
request: Request,
db: Session = Depends(get_db),
limit: int = Query(100, ge=1, le=200),
offset: int = Query(0, ge=0),
paged: int = Query(0, ge=0, le=1),
):
if IS_DDA_MODE:
from .dda.dda_auth import get_dda_user
from .dda.auto_detect import is_auto_schedule_job
user = get_dda_user(request, db)
auto_ids = [
j.run_id for j in (
db.query(DetectionJob)
.filter(DetectionJob.run_id.isnot(None))
.order_by(DetectionJob.id.desc())
.limit(200)
.all()
)
if is_auto_schedule_job(j)
]
from sqlalchemy import or_
filt = DetectionRun.user_id == user.id
if auto_ids:
filt = or_(filt, DetectionRun.id.in_(auto_ids))
query = db.query(DetectionRun).filter(filt)
else:
user = get_or_create_guest_user(db)
query = db.query(DetectionRun).filter(DetectionRun.user_id == user.id)
total = query.count() if paged else None
runs = query.order_by(DetectionRun.created_at.desc()).offset(offset).limit(limit).all()
items = [
{
"id": r.id,
"title": r.title,
"method": r.method,
"zone": r.zone or "",
"village": r.village or "",
"changePercentage": r.change_percentage,
"regionsCount": r.regions_count,
"totalPixels": r.total_pixels,
"changedPixels": r.changed_pixels,
"overlayUrl": f"/api/overlay/{r.overlay_path}" if r.overlay_path else None,
"beforeThumbUrl": f"/api/overlay/{r.before_thumb_path}" if (getattr(r, "before_thumb_path", None) or "").strip() else None,
"afterThumbUrl": f"/api/overlay/{r.after_thumb_path}" if (getattr(r, "after_thumb_path", None) or "").strip() else None,
"createdAt": _isoformat_ist(r.created_at),
}
for r in runs
]
if paged:
return {"items": items, "total": int(total or 0), "offset": offset, "limit": limit}
return items
@app.get("/api/history/{run_id}")
def get_run(
run_id: int,
request: Request,
db: Session = Depends(get_db),
):
"""Fetch a single run by id for opening from history (result view with slider, table, zoom)."""
if IS_DDA_MODE:
from .dda.dda_auth import get_dda_user
from .dda.auto_detect import user_can_access_run
user = get_dda_user(request, db)
run = db.query(DetectionRun).filter(DetectionRun.id == run_id).first()
if not run or not user_can_access_run(db, run.id, user.id):
raise HTTPException(status_code=404, detail="Run not found")
else:
user = get_or_create_guest_user(db)
run = db.query(DetectionRun).filter(DetectionRun.id == run_id, DetectionRun.user_id == user.id).first()
if not run:
raise HTTPException(status_code=404, detail="Run not found")
regions = _load_regions_json(run.regions_json)
if IS_DDA_MODE:
from .dda.review_service import merge_reviews
from .dda.config import get_detection_max_side
regions = merge_reviews(db, run.id, regions)
detection_max_side = get_detection_max_side()
else:
detection_max_side = None
base_path = comparison_path = ""
if IS_DDA_MODE:
job = (
db.query(DetectionJob)
.filter(DetectionJob.run_id == run.id)
.order_by(DetectionJob.id.desc())
.first()
)
if job and job.params_json:
try:
params = json.loads(job.params_json)
base_path = params.get("base_path") or ""
comparison_path = params.get("comparison_path") or ""
except (TypeError, json.JSONDecodeError):
pass
return {
"id": run.id,
"title": run.title,
"method": run.method,
"zone": run.zone or "",
"village": run.village or "",
"basePath": base_path,
"comparisonPath": comparison_path,
"statistics": {
"totalPixels": run.total_pixels,
"changedPixels": run.changed_pixels,
"unchangedPixels": run.total_pixels - run.changed_pixels,
"changePercentage": run.change_percentage,
},
"regions": regions,
"overlayUrl": f"/api/overlay/{run.overlay_path}" if run.overlay_path else None,
"beforeFullUrl": f"/api/overlay/{run.before_full_path}" if (getattr(run, "before_full_path", None) or "").strip() else None,
"beforeThumbUrl": f"/api/overlay/{run.before_thumb_path}" if (getattr(run, "before_thumb_path", None) or "").strip() else None,
"afterThumbUrl": f"/api/overlay/{run.after_thumb_path}" if (getattr(run, "after_thumb_path", None) or "").strip() else None,
"afterFullUrl": f"/api/overlay/{run.after_full_path}" if (getattr(run, "after_full_path", None) or "").strip() else None,
"createdAt": _isoformat_ist(run.created_at),
"detectionMaxSide": detection_max_side,
}
@app.post("/api/history/{run_id}/notify")
def notify_run(
run_id: int,
data: EmailRequest,
request: Request,
db: Session = Depends(get_db),
):
if IS_DDA_MODE:
from .dda.dda_auth import get_dda_user
user = get_dda_user(request, db)
else:
user = get_or_create_guest_user(db)
run = db.query(DetectionRun).filter(DetectionRun.id == run_id, DetectionRun.user_id == user.id).first()
if not run:
raise HTTPException(status_code=404, detail="Run not found")
regions = _load_regions_json(run.regions_json)
sent, error = send_notification(
recipient=data.email.strip(),
title=run.title,
method=run.method,
zone=run.zone or "",
village=run.village or "",
change_pct=float(run.change_percentage),
changed_px=int(run.changed_pixels),
total_px=int(run.total_pixels),
regions=regions,
)
if not sent:
raise HTTPException(status_code=400, detail=error or "Failed to send report email")
return {"ok": True, "message": f"Report email sent to {data.email.strip()}."}
# --- Delete history run ---
@app.delete("/api/history/{run_id}")
def delete_run(
run_id: int,
request: Request,
db: Session = Depends(get_db),
):
if IS_DDA_MODE:
from .dda.dda_auth import get_dda_user
from .dda.rbac.permissions import user_can
user = get_dda_user(request, db)
if not user_can(user, db, "reports", "delete"):
raise HTTPException(status_code=403, detail="Missing 'delete' permission on 'reports'.")
else:
user = get_or_create_guest_user(db)
run = db.query(DetectionRun).filter(DetectionRun.id == run_id, DetectionRun.user_id == user.id).first()
if not run:
raise HTTPException(status_code=404, detail="Run not found")
# Delete overlay and thumbnail files if they exist
for path_attr in ("overlay_path", "before_full_path", "before_thumb_path", "after_thumb_path", "after_full_path"):
path_val = getattr(run, path_attr, None)
if path_val:
f = OVERLAYS_DIR.parent / path_val
if f.exists():
f.unlink(missing_ok=True)
if IS_DDA_MODE:
from .dda.models import DetectionJob, RegionReview
db.query(RegionReview).filter(RegionReview.run_id == run_id).delete()
for job in db.query(DetectionJob).filter(DetectionJob.run_id == run_id).all():
job.run_id = None
db.delete(run)
db.commit()
return {"ok": True, "deleted_id": run_id}
# --- Serve SPA ---
@app.get("/dda/reports/{run_id}", response_class=HTMLResponse)
def dda_report_page(run_id: int, request: Request, db: Session = Depends(get_db)):
"""Standalone browser report (FR-05) with interactive viewer."""
if not IS_DDA_MODE:
raise HTTPException(status_code=404, detail="Not found")
_user, redirect = _dda_session_or_redirect(request, db)
if redirect:
return redirect
return templates.TemplateResponse(
request,
"report_dda.html",
{"run_id": run_id, "active_page": "reports", "menu_items": []},
headers={"Cache-Control": "no-store"},
)
# no-store on every auth page below: FileResponse otherwise sends
# Last-Modified/ETag with no Cache-Control, which lets browsers serve a
# heuristically-"fresh" copy straight from disk cache for hours without even
# a revalidation request — invisible until you edit the page and it doesn't
# show up. Also just the right default for a login/reset form regardless.
_NO_STORE_HEADERS = {"Cache-Control": "no-store"}
@app.get("/login", response_class=HTMLResponse)
def login_page():
if not IS_DDA_MODE:
raise HTTPException(status_code=404, detail="Not found")
login_file = TEMPLATES_DIR / "login_dda.html"
if not login_file.exists():
raise HTTPException(status_code=404, detail="Login template missing")
return FileResponse(login_file, headers=_NO_STORE_HEADERS)
@app.get("/forgot-password", response_class=HTMLResponse)
def forgot_password_page():
if not IS_DDA_MODE:
raise HTTPException(status_code=404, detail="Not found")
page_file = TEMPLATES_DIR / "forgot_password_dda.html"
if not page_file.exists():
raise HTTPException(status_code=404, detail="Template missing")
return FileResponse(page_file, headers=_NO_STORE_HEADERS)
@app.get("/reset-password", response_class=HTMLResponse)
def reset_password_page():
if not IS_DDA_MODE:
raise HTTPException(status_code=404, detail="Not found")
page_file = TEMPLATES_DIR / "reset_password_dda.html"
if not page_file.exists():
raise HTTPException(status_code=404, detail="Template missing")
return FileResponse(page_file, headers=_NO_STORE_HEADERS)
@app.get("/profile", response_class=HTMLResponse)
def dda_profile_page(request: Request, db: Session = Depends(get_db)):
if not IS_DDA_MODE:
raise HTTPException(status_code=404, detail="Not found")
user, redirect = _dda_session_or_redirect(request, db)
if redirect:
return redirect
menu_items = resolve_user_menu(user, db)
return templates.TemplateResponse(request, "profile_dda.html", {"active_page": "profile", "menu_items": menu_items})
def _dda_session_or_redirect(request: Request, db: Session):
"""Shared by every DDA-mode page route (Home/Library/Detect/Reports/Admin).
Deliberately not calling get_dda_user() here — it still has the
session/guest fallback until Step 7 flips it, so it would never report
"unauthenticated". Do the same JWT-via-cookie check it does for its
first branch, without the fallback, so a redirect here is meaningful
and independently testable before that flip lands.
Returns (user, None) if there's a session, or (None, RedirectResponse)
to /login if there isn't.
"""
token = request.cookies.get(COOKIE_NAME)
user = get_user_from_token(token, db) if token else None
if not user:
return None, RedirectResponse("/login")
return user, None
def _dda_admin_page_or_redirect(request: Request, db: Session):
"""Session check plus the 'admin' module's view permission — shared by the
3 RBAC admin pages. Redirects to Home (not a bare 403) if the user is
logged in but not permitted, since this is a page, not an API call."""
user, redirect = _dda_session_or_redirect(request, db)
if redirect:
return None, None, redirect
if not user_can(user, db, "admin", "view"):
return None, None, RedirectResponse("/")
return user, resolve_user_menu(user, db), None
@app.get("/", response_class=HTMLResponse)
def index(request: Request, db: Session = Depends(get_db)):
if IS_DDA_MODE:
user, redirect = _dda_session_or_redirect(request, db)
if redirect:
return redirect
menu_items = resolve_user_menu(user, db)
return templates.TemplateResponse(request, "home_dda.html", {"active_page": "home", "menu_items": menu_items})
index_file = TEMPLATES_DIR / "index.html"
if not index_file.exists():
return HTMLResponse("<h1>Satellite Change Detection</h1><p>Create <code>templates/index.html</code> and <code>static/</code>.</p>")
return FileResponse(index_file)
def _dda_module_page_or_redirect(request: Request, db: Session, module_key: str):
user, redirect = _dda_session_or_redirect(request, db)
if redirect:
return None, None, redirect
if not user_can(user, db, module_key, "view"):
return None, None, RedirectResponse("/")
return user, resolve_user_menu(user, db), None
@app.get("/library", response_class=HTMLResponse)
def dda_library_page(request: Request, db: Session = Depends(get_db)):
if not IS_DDA_MODE:
raise HTTPException(status_code=404, detail="Not found")
user, menu_items, redirect = _dda_module_page_or_redirect(request, db, "library")
if redirect:
return redirect
return templates.TemplateResponse(request, "library_dda.html", {"active_page": "library", "menu_items": menu_items})
@app.get("/detect", response_class=HTMLResponse)
def dda_detect_page(request: Request, db: Session = Depends(get_db)):
if not IS_DDA_MODE:
raise HTTPException(status_code=404, detail="Not found")
user, menu_items, redirect = _dda_module_page_or_redirect(request, db, "detect")
if redirect:
return redirect
return templates.TemplateResponse(request, "detect_dda.html", {"active_page": "detect", "menu_items": menu_items})
@app.get("/reports", response_class=HTMLResponse)
def dda_reports_page(request: Request, db: Session = Depends(get_db)):
if not IS_DDA_MODE:
raise HTTPException(status_code=404, detail="Not found")
user, menu_items, redirect = _dda_module_page_or_redirect(request, db, "reports")
if redirect:
return redirect
return templates.TemplateResponse(request, "reports_dda.html", {"active_page": "reports", "menu_items": menu_items})
@app.get("/logs", response_class=HTMLResponse)
def dda_logs_page(request: Request):
# Application Logs is now a tab on the Exception Log page (Configuration >
# Exception Log) rather than its own sidebar entry; redirect old links/bookmarks.
if not IS_DDA_MODE:
raise HTTPException(status_code=404, detail="Not found")
return RedirectResponse(url="/exception-log?tab=applogs", status_code=307)
@app.get("/audit-log", response_class=HTMLResponse)
def dda_audit_log_page(request: Request, db: Session = Depends(get_db)):
if not IS_DDA_MODE:
raise HTTPException(status_code=404, detail="Not found")
user, menu_items, redirect = _dda_module_page_or_redirect(request, db, "audit_log")
if redirect:
return redirect
return templates.TemplateResponse(request, "audit_log_dda.html", {"active_page": "audit-log", "menu_items": menu_items})
@app.get("/exception-log", response_class=HTMLResponse)
def dda_exception_log_page(request: Request, db: Session = Depends(get_db)):
if not IS_DDA_MODE:
raise HTTPException(status_code=404, detail="Not found")
user, menu_items, redirect = _dda_module_page_or_redirect(request, db, "exception_log")
if redirect:
return redirect
return templates.TemplateResponse(request, "exception_log_dda.html", {"active_page": "exception-log", "menu_items": menu_items})
@app.get("/masters/zones", response_class=HTMLResponse)
def dda_masters_zones_page(request: Request, db: Session = Depends(get_db)):
if not IS_DDA_MODE:
raise HTTPException(status_code=404, detail="Not found")
user, menu_items, redirect = _dda_module_page_or_redirect(request, db, "masters")
if redirect:
return redirect
return templates.TemplateResponse(request, "masters_zones_dda.html", {"active_page": "masters-zones", "menu_items": menu_items})
@app.get("/masters/villages", response_class=HTMLResponse)
def dda_masters_villages_page(request: Request, db: Session = Depends(get_db)):
if not IS_DDA_MODE:
raise HTTPException(status_code=404, detail="Not found")
user, menu_items, redirect = _dda_module_page_or_redirect(request, db, "masters")
if redirect:
return redirect
return templates.TemplateResponse(request, "masters_villages_dda.html", {"active_page": "masters-villages", "menu_items": menu_items})
@app.get("/admin/roles-users", response_class=HTMLResponse)
def dda_admin_roles_users_page(request: Request, db: Session = Depends(get_db)):
if not IS_DDA_MODE:
raise HTTPException(status_code=404, detail="Not found")
user, menu_items, redirect = _dda_admin_page_or_redirect(request, db)
if redirect:
return redirect
return templates.TemplateResponse(request, "admin_roles_users_dda.html", {"active_page": "admin-roles-users", "menu_items": menu_items})
@app.get("/admin/modules", response_class=HTMLResponse)
def dda_admin_modules_page(request: Request, db: Session = Depends(get_db)):
if not IS_DDA_MODE:
raise HTTPException(status_code=404, detail="Not found")
user, menu_items, redirect = _dda_admin_page_or_redirect(request, db)
if redirect:
return redirect
return templates.TemplateResponse(request, "admin_modules_dda.html", {"active_page": "admin-modules", "menu_items": menu_items})
@app.get("/admin/menu", response_class=HTMLResponse)
def dda_admin_menu_page(request: Request, db: Session = Depends(get_db)):
if not IS_DDA_MODE:
raise HTTPException(status_code=404, detail="Not found")
user, menu_items, redirect = _dda_admin_page_or_redirect(request, db)
if redirect:
return redirect
return templates.TemplateResponse(request, "admin_menu_dda.html", {"active_page": "admin-menu", "menu_items": menu_items})
import base64
import io
import json
import os
import uuid
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Optional
try:
from dotenv import load_dotenv
load_dotenv(Path(__file__).resolve().parent.parent / ".env")
except ImportError:
pass
from jose import JWTError, jwt
from sqlalchemy import text as sa_text
from fastapi import FastAPI, Depends, File, Form, HTTPException, Query, Request, UploadFile
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse, Response
from fastapi.staticfiles import StaticFiles
from starlette.exceptions import HTTPException as StarletteHTTPException
from fastapi.exception_handlers import http_exception_handler as starlette_http_exception_handler
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel, EmailStr, field_validator
from sqlalchemy.orm import Session
from PIL import Image, ImageOps
from .auth import (
ALGORITHM,
COOKIE_NAME,
COOKIE_SAMESITE,
IS_SECURE_COOKIE,
LOGIN_OTP_EXPIRE_MINUTES,
LOGIN_OTP_RESEND_SECONDS,
SECRET_KEY,
check_account_lockout,
check_ip_throttle,
consume_password_reset_token,
create_access_token,
create_login_otp,
create_password_reset_token,
get_client_ip,
get_password_hash,
get_user_by_email,
get_user_by_phone,
get_current_user,
get_or_create_guest_user,
get_user_agent,
get_user_from_token,
latest_unused_otp,
mask_email,
normalize_phone,
record_login_event,
revoke_user_sessions,
verify_login_otp,
verify_password,
)
from .database import Base, engine, get_db, DATA_DIR
from .models import User, DetectionRun, LoginHistory, PasswordResetToken, LoginOtp # noqa: F401 — LoginHistory/PasswordResetToken/LoginOtp registered on Base.metadata for create_all()
from . import dda as _dda_pkg # noqa: F401 — register DDA tables
from .dda.models import DdaZone, DdaVillage, ImageAsset, DetectionJob, RegionReview, AutoPairSchedule, AutoDetectSettings # noqa: F401
from .dda.tree.models import TreeNode, ImageLibrary, AuditLog # noqa: F401
from .dda.rbac.models import Role, Module, RolePermission, MenuItem # noqa: F401
from .dda.rbac.permissions import get_user_role_row, resolve_user_menu, user_can
from .dda.config import IS_DDA_MODE
from .dda.bootstrap import init_dda_database, setup_dda
from .notifier import send_login_otp_email, send_notification, send_password_reset_email, send_test_email
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
try:
from .dda.applog import install_app_log_handler
install_app_log_handler()
except Exception:
pass
logger.info("Importing AI Change Detection app module")
_IST = timezone(timedelta(hours=5, minutes=30))
def _isoformat_ist(dt):
"""Convert a UTC datetime to IST (GMT+5:30) and return ISO-8601 string."""
if dt is None:
return None
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
return dt.astimezone(_IST).isoformat()
# Create tables and run migrations without crashing the app (HF Spaces can restart if startup fails)
try:
logger.info("Running database initialization")
Base.metadata.create_all(bind=engine, checkfirst=True)
with engine.connect() as conn:
for col, col_type in [
("zone", "VARCHAR(128) DEFAULT ''"),
("village", "VARCHAR(128) DEFAULT ''"),
("before_full_path", "VARCHAR(512) DEFAULT ''"),