-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
149 lines (124 loc) · 5.59 KB
/
app.py
File metadata and controls
149 lines (124 loc) · 5.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
from fastapi import FastAPI,Request
from fastapi.responses import Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from starlette.responses import HTMLResponse,RedirectResponse
from uvicorn import run as app_run
from typing import Optional
# importing constants and pipeline modules from the project
from src.constants import APP_HOST,APP_PORT
from src.pipeline.prediction_pipeline import VehicleData,VehicleDataClassifier
from src.entity.config_entity import VehiclePredictorConfig
from src.pipeline.training_pipeline import TrainingPipeline
# Initialise FastAPI application
app = FastAPI()
# Mount the 'static' directory serving static files(like CSS)
app.mount("/static",StaticFiles(directory="static"),name = "static")
# Set up Jinja2 template for rendering HTML templates
templates = Jinja2Templates(directory="templates")
# Allow all origins for cross-origin resource sharing(CORS)
origins = ["*"]
# Configure middleware to handle CORS,allowing requests from any origin
app.add_middleware(
CORSMiddleware,
allow_origins = origins,
allow_credentials = True,
allow_methods=["*"],
allow_headers=["*"]
)
class DataForm:
"""
DataForm class to handle and process incoming form data.
This class defines the vehicle-related attributes expected from the form.
"""
def __init__(self, request: Request):
self.request: Request = request
self.Gender: Optional[int] = None
self.Age: Optional[int] = None
self.Driving_License: Optional[int] = None
self.Region_Code: Optional[float] = None
self.Previously_Insured: Optional[int] = None
self.Annual_Premium: Optional[float] = None
self.Policy_Sales_Channel: Optional[float] = None
self.Vintage: Optional[int] = None
self.Vehicle_Age_lt_1_Year: Optional[int] = None
self.Vehicle_Age_gt_2_Years: Optional[int] = None
self.Vehicle_Damage_Yes: Optional[int] = None
async def get_vehicle_data(self):
"""
Method to retrieve and assign form data to class attributes.
This method is asynchronous to handle form data fetching without blocking.
"""
form = await self.request.form()
self.Gender = form.get("Gender")
self.Age = form.get("Age")
self.Driving_License = form.get("Driving_License")
self.Region_Code = form.get("Region_Code")
self.Previously_Insured = form.get("Previously_Insured")
self.Annual_Premium = form.get("Annual_Premium")
self.Policy_Sales_Channel = form.get("Policy_Sales_Channel")
self.Vintage = form.get("Vintage")
self.Vehicle_Age_lt_1_Year = form.get("Vehicle_Age_lt_1_Year")
self.Vehicle_Age_gt_2_Years = form.get("Vehicle_Age_gt_2_Years")
self.Vehicle_Damage_Yes = form.get("Vehicle_Damage_Yes")
# Route to render the main page with the form
@app.get("/", tags=["authentication"])
async def index(request: Request):
"""
Renders the main HTML form page for vehicle data input.
"""
return templates.TemplateResponse(
"vehicledata.html",{"request": request, "context": "Rendering"})
# Route to trigger the model training process
@app.get("/train")
async def trainRouteClient():
"""
Endpoint to initiate the model training pipeline.
"""
try:
train_pipeline = TrainingPipeline()
train_pipeline.run_pipeline()
return Response("Training successful!!!")
except Exception as e:
return Response(f"Error Occurred! {e}")
# Route to handle form submission and make predictions
@app.post("/")
async def predictRouteClient(request: Request):
"""
Endpoint to receive form data, process it, and make a prediction.
"""
try:
form = DataForm(request)
await form.get_vehicle_data()
vehicle_data = VehicleData(
Gender= form.Gender,
Age = form.Age,
Driving_License = form.Driving_License,
Region_Code = form.Region_Code,
Previously_Insured = form.Previously_Insured,
Annual_Premium = form.Annual_Premium,
Policy_Sales_Channel = form.Policy_Sales_Channel,
Vintage = form.Vintage,
Vehicle_Age_lt_1_Year = form.Vehicle_Age_lt_1_Year,
Vehicle_Age_gt_2_Years = form.Vehicle_Age_gt_2_Years,
Vehicle_Damage_Yes = form.Vehicle_Damage_Yes
)
# Convert form data into a DataFrame for the model
vehicle_df = vehicle_data.get_vehicle_input_data_frame()
# Initialize the prediction pipeline
model_predictor = VehicleDataClassifier(prediction_pipeline_config=VehiclePredictorConfig)
# Make a prediction and retrieve the result
value = model_predictor.predict(dataframe=vehicle_df)[0]
# Interpret the prediction result as 'Response-Yes' or 'Response-No'
status = "Response-Yes" if value == 1 else "Response-No"
# Render the same HTML page with the prediction result
return templates.TemplateResponse(
"vehicledata.html",
{"request": request, "context": status},
)
except Exception as e:
return {"status": False, "error": f"{e}"}
# Main entry point to start the FastAPI server
if __name__ == "__main__":
app_run(app, host=APP_HOST, port=APP_PORT)