Update app.py
Browse files
app.py
CHANGED
|
@@ -1,75 +1,77 @@
|
|
| 1 |
-
import pickle
|
| 2 |
-
import pandas as pd
|
| 3 |
-
from sklearn.linear_model import LogisticRegression
|
| 4 |
-
from sklearn.metrics import classification_report, accuracy_score
|
| 5 |
-
from sklearn.model_selection import train_test_split
|
| 6 |
-
from fastapi import FastAPI, UploadFile, File, HTTPException
|
| 7 |
-
from pydantic import BaseModel
|
| 8 |
-
import io
|
| 9 |
-
|
| 10 |
-
app = FastAPI()
|
| 11 |
-
data = None
|
| 12 |
-
|
| 13 |
-
# Function to train the model
|
| 14 |
-
def train_aut(data):
|
| 15 |
-
data['Downtime_Flag'] = data['Downtime_Flag'].map({'Yes': 1, 'No': 0})
|
| 16 |
-
X = data[['Temperature', 'Run_Time']]
|
| 17 |
-
y = data['Downtime_Flag']
|
| 18 |
-
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
|
| 19 |
-
model = LogisticRegression()
|
| 20 |
-
model.fit(X_train, y_train)
|
| 21 |
-
with open('model.pkl', 'wb') as file:
|
| 22 |
-
pickle.dump(model, file)
|
| 23 |
-
y_pred = model.predict(X_test)
|
| 24 |
-
accuracy = accuracy_score(y_test, y_pred)
|
| 25 |
-
f1 = classification_report(y_test, y_pred, output_dict=True)['1']['f1-score']
|
| 26 |
-
return accuracy, f1
|
| 27 |
-
|
| 28 |
-
# Function to make predictions
|
| 29 |
-
def predict_aut(temp, run_time):
|
| 30 |
-
try:
|
| 31 |
-
with open('model.pkl', 'rb') as file:
|
| 32 |
-
model = pickle.load(file)
|
| 33 |
-
input_data = [[temp, run_time]]
|
| 34 |
-
y_pred = model.predict(input_data)
|
| 35 |
-
return 'Yes' if y_pred[0] == 1 else 'No'
|
| 36 |
-
except FileNotFoundError:
|
| 37 |
-
raise HTTPException(status_code=400, detail="Model not trained. Please upload data and train the model first.")
|
| 38 |
-
|
| 39 |
-
# Pydantic model for prediction input
|
| 40 |
-
class PredictionInput(BaseModel):
|
| 41 |
-
Temperature: float
|
| 42 |
-
Run_Time: float
|
| 43 |
-
|
| 44 |
-
@app.post("/upload")
|
| 45 |
-
async def upload(file: UploadFile = File(...)):
|
| 46 |
-
try:
|
| 47 |
-
global data
|
| 48 |
-
contents = await file.read()
|
| 49 |
-
data = pd.read_csv(io.StringIO(contents.decode("utf-8")))
|
| 50 |
-
return {"message": "File uploaded successfully."}
|
| 51 |
-
except Exception as e:
|
| 52 |
-
raise HTTPException(status_code=400, detail=f"Error reading file: {str(e)}")
|
| 53 |
-
|
| 54 |
-
@app.post("/train")
|
| 55 |
-
def train():
|
| 56 |
-
global data
|
| 57 |
-
if data is None:
|
| 58 |
-
raise HTTPException(status_code=400, detail="No data uploaded. Please upload a dataset first.")
|
| 59 |
-
try:
|
| 60 |
-
accuracy, f1 = train_aut(data)
|
| 61 |
-
return {"message": "Model trained successfully.", "accuracy": accuracy, "f1_score": f1}
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
|
|
|
|
|
|
|
|
| 1 |
+
import pickle
|
| 2 |
+
import pandas as pd
|
| 3 |
+
from sklearn.linear_model import LogisticRegression
|
| 4 |
+
from sklearn.metrics import classification_report, accuracy_score
|
| 5 |
+
from sklearn.model_selection import train_test_split
|
| 6 |
+
from fastapi import FastAPI, UploadFile, File, HTTPException
|
| 7 |
+
from pydantic import BaseModel
|
| 8 |
+
import io
|
| 9 |
+
|
| 10 |
+
app = FastAPI()
|
| 11 |
+
data = None
|
| 12 |
+
|
| 13 |
+
# Function to train the model
|
| 14 |
+
def train_aut(data):
|
| 15 |
+
data['Downtime_Flag'] = data['Downtime_Flag'].map({'Yes': 1, 'No': 0})
|
| 16 |
+
X = data[['Temperature', 'Run_Time']]
|
| 17 |
+
y = data['Downtime_Flag']
|
| 18 |
+
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
|
| 19 |
+
model = LogisticRegression()
|
| 20 |
+
model.fit(X_train, y_train)
|
| 21 |
+
with open('model.pkl', 'wb') as file:
|
| 22 |
+
pickle.dump(model, file)
|
| 23 |
+
y_pred = model.predict(X_test)
|
| 24 |
+
accuracy = accuracy_score(y_test, y_pred)
|
| 25 |
+
f1 = classification_report(y_test, y_pred, output_dict=True)['1']['f1-score']
|
| 26 |
+
return accuracy, f1
|
| 27 |
+
|
| 28 |
+
# Function to make predictions
|
| 29 |
+
def predict_aut(temp, run_time):
|
| 30 |
+
try:
|
| 31 |
+
with open('model.pkl', 'rb') as file:
|
| 32 |
+
model = pickle.load(file)
|
| 33 |
+
input_data = [[temp, run_time]]
|
| 34 |
+
y_pred = model.predict(input_data)
|
| 35 |
+
return 'Yes' if y_pred[0] == 1 else 'No'
|
| 36 |
+
except FileNotFoundError:
|
| 37 |
+
raise HTTPException(status_code=400, detail="Model not trained. Please upload data and train the model first.")
|
| 38 |
+
|
| 39 |
+
# Pydantic model for prediction input
|
| 40 |
+
class PredictionInput(BaseModel):
|
| 41 |
+
Temperature: float
|
| 42 |
+
Run_Time: float
|
| 43 |
+
|
| 44 |
+
@app.post("/upload")
|
| 45 |
+
async def upload(file: UploadFile = File(...)):
|
| 46 |
+
try:
|
| 47 |
+
global data
|
| 48 |
+
contents = await file.read()
|
| 49 |
+
data = pd.read_csv(io.StringIO(contents.decode("utf-8")))
|
| 50 |
+
return {"message": "File uploaded successfully."}
|
| 51 |
+
except Exception as e:
|
| 52 |
+
raise HTTPException(status_code=400, detail=f"Error reading file: {str(e)}")
|
| 53 |
+
|
| 54 |
+
@app.post("/train")
|
| 55 |
+
def train():
|
| 56 |
+
global data
|
| 57 |
+
if data is None:
|
| 58 |
+
raise HTTPException(status_code=400, detail="No data uploaded. Please upload a dataset first.")
|
| 59 |
+
try:
|
| 60 |
+
accuracy, f1 = train_aut(data)
|
| 61 |
+
# return {"message": "Model trained successfully.", "accuracy": accuracy, "f1_score": f1}
|
| 62 |
+
return {"message": "Please Contact the owner to switch this space on."}
|
| 63 |
+
except Exception as e:
|
| 64 |
+
raise HTTPException(status_code=500, detail=f"Error during training: {str(e)}")
|
| 65 |
+
|
| 66 |
+
@app.post("/predict")
|
| 67 |
+
def predict(input_data: PredictionInput):
|
| 68 |
+
try:
|
| 69 |
+
result = predict_aut(input_data.Temperature, input_data.Run_Time)
|
| 70 |
+
# return {"Downtime": result}
|
| 71 |
+
return {"message": "Please Contact the owner to switch this space on."}
|
| 72 |
+
except Exception as e:
|
| 73 |
+
raise HTTPException(status_code=500, detail=f"Error during prediction: {str(e)}")
|
| 74 |
+
|
| 75 |
+
if __name__ == "__main__":
|
| 76 |
+
import uvicorn
|
| 77 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|