MHamzaShahid commited on
Commit
669798f
·
verified ·
1 Parent(s): 2f62d0c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -10
app.py CHANGED
@@ -2,24 +2,20 @@ import os
2
  import warnings
3
  import joblib
4
  import pandas as pd
 
5
  from fastapi import FastAPI, HTTPException
6
  from pydantic import BaseModel
7
 
8
- # Suppress scikit-learn warnings globally (as backup; not needed with version match)
9
  warnings.filterwarnings("ignore", category=UserWarning, module="sklearn")
10
 
11
- app = FastAPI(
12
- title="Crop Yield Prediction API",
13
- description="API for predicting crop yields based on agricultural parameters",
14
- version="1.0.0"
15
- )
16
-
17
- # Load model at app startup to ensure single load
18
  model = None
19
  model_loaded = False
20
 
21
- @app.on_event("startup")
22
- async def load_model():
 
23
  global model, model_loaded
24
  script_dir = os.path.dirname(os.path.abspath(__file__))
25
  model_path = os.path.join(script_dir, "district_yield_pipeline.pkl")
@@ -34,6 +30,20 @@ async def load_model():
34
  else:
35
  print(f"Model file not found at: {model_path}")
36
  print(f"Available files: {os.listdir(script_dir)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
  class PredictionInput(BaseModel):
39
  crop: str
 
2
  import warnings
3
  import joblib
4
  import pandas as pd
5
+ from contextlib import asynccontextmanager # Added for lifespan
6
  from fastapi import FastAPI, HTTPException
7
  from pydantic import BaseModel
8
 
9
+ # Suppress any residual scikit-learn warnings (backup; not needed if versions match)
10
  warnings.filterwarnings("ignore", category=UserWarning, module="sklearn")
11
 
12
+ # Global variables for model (loaded in lifespan)
 
 
 
 
 
 
13
  model = None
14
  model_loaded = False
15
 
16
+ @asynccontextmanager
17
+ async def lifespan(app: FastAPI):
18
+ # Startup: Load model here
19
  global model, model_loaded
20
  script_dir = os.path.dirname(os.path.abspath(__file__))
21
  model_path = os.path.join(script_dir, "district_yield_pipeline.pkl")
 
30
  else:
31
  print(f"Model file not found at: {model_path}")
32
  print(f"Available files: {os.listdir(script_dir)}")
33
+
34
+ yield # App runs after this
35
+
36
+ # Optional shutdown/cleanup (e.g., free resources)
37
+ model = None
38
+ model_loaded = False
39
+ print("App shutdown: Model unloaded.")
40
+
41
+ app = FastAPI(
42
+ lifespan=lifespan, # Use the new lifespan handler
43
+ title="Crop Yield Prediction API",
44
+ description="API for predicting crop yields based on agricultural parameters",
45
+ version="1.0.0"
46
+ )
47
 
48
  class PredictionInput(BaseModel):
49
  crop: str