-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
96 lines (68 loc) · 2.63 KB
/
app.py
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
import sys
import os
import certifi
from dotenv import load_dotenv
import pymongo
from fastapi.middleware.cors import CORSMiddleware
from fastapi import FastAPI, File, UploadFile, Request
from fastapi.templating import Jinja2Templates
from uvicorn import run as app_run
from fastapi.responses import Response
from starlette.responses import RedirectResponse
import pandas as pd
ca = certifi.where()
load_dotenv()
mongo_db_url = os.getenv("MONGODB_URL_KEY")
print(mongo_db_url)
from networksecurity.exception.exception import NetworkSecurityException
from networksecurity.logging.logger import logging
from networksecurity.pipeline.training_pipeline import TrainingPipeline
from networksecurity.utils.main_utils.utils import load_numpy_object
from networksecurity.utils.ml_utils.model.estimator import NetworkModel
from networksecurity.constant.training_pipeline import (
DATA_INGESTION_COLLECTION_NAME,
DATA_INGESTION_DATABASE_NAME,
)
client = pymongo.MongoClient(mongo_db_url, tlsCAFile=ca)
database = client[DATA_INGESTION_DATABASE_NAME]
collection = database[DATA_INGESTION_COLLECTION_NAME]
app = FastAPI()
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins= origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
templates = Jinja2Templates(directory= "./templates")
@app.get("/", tags = ["authentication"])
async def index():
return RedirectResponse(url="/docs")
@app.get("/train")
async def train_route():
try:
train_pipeline = TrainingPipeline()
train_pipeline.run_pipeline()
return Response("Training is successful")
except Exception as e:
raise NetworkSecurityException(e,sys)
@app.post("/predict")
async def predict_route(request: Request, file: UploadFile = File(...)):
try:
df = pd.read_csv(file.file)
print(df)
preprocessor = load_numpy_object("final_model/preprocessor.pkl")
final_model = load_numpy_object("final_model/model.pkl")
network_model = NetworkModel(preprocessor=preprocessor, model=final_model)
y_pred = network_model.predict(df)
print(y_pred)
df['predicted_column'] = y_pred
df.to_csv('prediction_output/output.csv', index=False)
table_html = df.to_html(classes="table table-striped")
return templates.TemplateResponse("table.html", {"request" : request, "table":table_html})
except Exception as e:
logging.error(f"Error in prediction route: {str(e)}")
raise NetworkSecurityException(e, sys)
if __name__ == "__main__":
app_run(app, host="localhost", port=8000)