saad1BM commited on
Commit
a0b5bd3
·
verified ·
1 Parent(s): 9697672

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +63 -83
main.py CHANGED
@@ -1,83 +1,63 @@
1
- import os
2
- import joblib
3
- import pandas as pd
4
- import logging
5
- from fastapi import FastAPI
6
- from pydantic import BaseModel
7
- from datetime import datetime
8
-
9
- # LOGGING: Console par log karein taake Docker ya cloud environments mein logs asani se milain
10
- logging.basicConfig(
11
- level=logging.INFO,
12
- format='%(asctime)s - %(levelname)s - %(message)s'
13
- )
14
-
15
- app = FastAPI(title="Flight Delay Prediction API")
16
-
17
- # --- PATH SETUP (DOCKER FRIENDLY) ---
18
- # BASE_DIR ko aik level up le kar jana hai (api folder se bahar)
19
- # Example: /app/api/main.py -> /app/
20
- BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
21
- MODEL_PATH = os.path.join(BASE_DIR, 'models', 'flight_model.joblib')
22
-
23
- logging.info(f"Looking for model at: {MODEL_PATH}")
24
-
25
- try:
26
- # Model load logic
27
- model = joblib.load(MODEL_PATH)
28
- logging.info("Model successfully loaded.")
29
- except Exception as e:
30
- logging.error(f"Model load karne mein masla: {e}")
31
- model = None
32
-
33
- # --- DATA SCHEMA ---
34
- class FlightData(BaseModel):
35
- MONTH: int
36
- DAY_OF_WEEK: int
37
- DISTANCE: float
38
- CRS_DEP_TIME: int
39
- OP_UNIQUE_CARRIER: str
40
- ORIGIN: str
41
- DEST: str
42
-
43
- # --- ENDPOINTS ---
44
- @app.get("/")
45
- def home():
46
- return {"message": "Flight Delay Prediction API is Running!"}
47
-
48
- @app.post("/predict")
49
- def predict(data: FlightData):
50
- if model is None:
51
- logging.error("Prediction failed: Model is not loaded.")
52
- return {"error": "Model not loaded on server. Check path and logs."}
53
-
54
- logging.info(f"Prediction requested for: {data.dict()}")
55
-
56
- try:
57
- # Convert incoming Pydantic model to DataFrame
58
- input_df = pd.DataFrame([data.dict()])
59
-
60
- # Categorical columns ko numeric mein badalne ke liye hash use ho raha hai
61
- for col in ['OP_UNIQUE_CARRIER', 'ORIGIN', 'DEST']:
62
- input_df[col] = input_df[col].apply(lambda x: abs(hash(str(x))) % 1000)
63
-
64
- # Make Prediction
65
- prediction = model.predict(input_df)[0]
66
- probability = model.predict_proba(input_df)[0][1]
67
-
68
- result = {
69
- "delay_probability": round(float(probability), 2),
70
- "prediction": "Delayed" if prediction == 1 else "On Time"
71
- }
72
-
73
- logging.info(f"Prediction successful: {result}")
74
- return result
75
-
76
- except Exception as e:
77
- logging.error(f"Prediction error: {str(e)}")
78
- return {"error": "There is an issue with the prediction process", "details": str(e)}
79
-
80
- if __name__ == "__main__":
81
- import uvicorn
82
- # Docker/External access ke liye 0.0.0.0 zaroori hai
83
- uvicorn.run(app, host="0.0.0.0", port=8000)
 
1
+ import os
2
+ import joblib
3
+ import pandas as pd
4
+ import logging
5
+ from fastapi import FastAPI
6
+ from pydantic import BaseModel
7
+
8
+ # LOGGING setup
9
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
10
+
11
+ app = FastAPI(title="Flight Delay Prediction API")
12
+
13
+ # --- PATH SETUP (DOCKER FIXED) ---
14
+ # Docker mein hum /app folder mein hotay hain
15
+ MODEL_PATH = '/app/models/flight_model.joblib'
16
+
17
+ logging.info(f"Looking for model at: {MODEL_PATH}")
18
+
19
+ try:
20
+ if os.path.exists(MODEL_PATH):
21
+ model = joblib.load(MODEL_PATH)
22
+ logging.info("Model successfully loaded.")
23
+ else:
24
+ logging.error(f"Model file not found at {MODEL_PATH}")
25
+ model = None
26
+ except Exception as e:
27
+ logging.error(f"Model load karne mein masla: {e}")
28
+ model = None
29
+
30
+ class FlightData(BaseModel):
31
+ MONTH: int
32
+ DAY_OF_WEEK: int
33
+ DISTANCE: float
34
+ CRS_DEP_TIME: int
35
+ OP_UNIQUE_CARRIER: str
36
+ ORIGIN: str
37
+ DEST: str
38
+
39
+ @app.get("/")
40
+ def home():
41
+ return {"message": "Flight Delay Prediction API is Running!", "status": "online"}
42
+
43
+ @app.post("/predict")
44
+ def predict(data: FlightData):
45
+ if model is None:
46
+ return {"error": "Model not loaded on server."}
47
+
48
+ try:
49
+ input_df = pd.DataFrame([data.dict()])
50
+
51
+ # Hashing for categorical columns
52
+ for col in ['OP_UNIQUE_CARRIER', 'ORIGIN', 'DEST']:
53
+ input_df[col] = input_df[col].apply(lambda x: abs(hash(str(x))) % 1000)
54
+
55
+ prediction = model.predict(input_df)[0]
56
+ probability = model.predict_proba(input_df)[0][1]
57
+
58
+ return {
59
+ "delay_probability": round(float(probability), 2),
60
+ "prediction": "Delayed" if prediction == 1 else "On Time"
61
+ }
62
+ except Exception as e:
63
+ return {"error": str(e)}