coderuday21 commited on
Commit
454d6d6
·
1 Parent(s): b31590e

Fix HF restart loop: /health endpoint, resilient migration, lazy-load detection_engine

Browse files
Files changed (1) hide show
  1. app/main.py +27 -17
app/main.py CHANGED
@@ -26,28 +26,37 @@ from .auth import (
26
  )
27
  from .database import Base, engine, get_db, DATA_DIR
28
  from .models import User, DetectionRun
29
- from .detection_engine import run_detection
30
  from .notifier import send_notification
31
 
32
- Base.metadata.create_all(bind=engine, checkfirst=True)
33
-
34
- # Lightweight migration: add columns introduced after initial schema
35
- with engine.connect() as conn:
36
- for col, col_type in [
37
- ("zone", "VARCHAR(128) DEFAULT ''"),
38
- ("village", "VARCHAR(128) DEFAULT ''"),
39
- ("before_thumb_path", "VARCHAR(512) DEFAULT ''"),
40
- ("after_thumb_path", "VARCHAR(512) DEFAULT ''"),
41
- ]:
42
- try:
43
- conn.execute(sa_text(
44
- f"ALTER TABLE detection_runs ADD COLUMN {col} {col_type}"))
45
- conn.commit()
46
- except Exception:
47
- conn.rollback()
 
 
 
48
 
49
  app = FastAPI(title="AI Change Detection", version="2.0.0")
50
 
 
 
 
 
 
 
51
  # Mount static files
52
  STATIC_DIR = Path(__file__).resolve().parent.parent / "static"
53
  TEMPLATES_DIR = Path(__file__).resolve().parent.parent / "templates"
@@ -210,6 +219,7 @@ async def detect(
210
  raise
211
  except Exception as e:
212
  raise HTTPException(status_code=400, detail=f"Invalid image: {e}")
 
213
  change_mask, result_image, stats, change_regions = run_detection(
214
  before_pil, after_pil, method=method, enable_registration=enable_registration, enable_normalization=enable_normalization
215
  )
 
26
  )
27
  from .database import Base, engine, get_db, DATA_DIR
28
  from .models import User, DetectionRun
29
+ # detection_engine (cv2, sklearn) imported lazily in /api/detect to speed up startup on HF Spaces
30
  from .notifier import send_notification
31
 
32
+ # Create tables and run migrations without crashing the app (HF Spaces can restart if startup fails)
33
+ try:
34
+ Base.metadata.create_all(bind=engine, checkfirst=True)
35
+ with engine.connect() as conn:
36
+ for col, col_type in [
37
+ ("zone", "VARCHAR(128) DEFAULT ''"),
38
+ ("village", "VARCHAR(128) DEFAULT ''"),
39
+ ("before_thumb_path", "VARCHAR(512) DEFAULT ''"),
40
+ ("after_thumb_path", "VARCHAR(512) DEFAULT ''"),
41
+ ]:
42
+ try:
43
+ conn.execute(sa_text(
44
+ f"ALTER TABLE detection_runs ADD COLUMN {col} {col_type}"))
45
+ conn.commit()
46
+ except Exception:
47
+ conn.rollback()
48
+ except Exception as e:
49
+ import logging
50
+ logging.getLogger("uvicorn.error").warning("Startup migration skipped: %s", e)
51
 
52
  app = FastAPI(title="AI Change Detection", version="2.0.0")
53
 
54
+
55
+ @app.get("/health")
56
+ def health():
57
+ """Lightweight health check so Hugging Face can mark the Space as running quickly."""
58
+ return {"status": "ok"}
59
+
60
  # Mount static files
61
  STATIC_DIR = Path(__file__).resolve().parent.parent / "static"
62
  TEMPLATES_DIR = Path(__file__).resolve().parent.parent / "templates"
 
219
  raise
220
  except Exception as e:
221
  raise HTTPException(status_code=400, detail=f"Invalid image: {e}")
222
+ from .detection_engine import run_detection
223
  change_mask, result_image, stats, change_regions = run_detection(
224
  before_pil, after_pil, method=method, enable_registration=enable_registration, enable_normalization=enable_normalization
225
  )