%%writefile app.py
import streamlit as st
import pandas as pd
import io
import joblib
import base64
import matplotlib.pyplot as plt
import seaborn as sns
Function to upload and generate predictions
def upload_and_generate_predictions():
# File upload and prediction code
def get_base64(bin_file):
with open(bin_file, 'rb') as f:
data = f.read()
return base64.b64encode(data).decode()
def set_background(png_file):
bin_str = get_base64(png_file)
page_bg_img = '''
.stApp {
background-image: url("data:image/png;base64,%s");
background-size: cover;
}
''' % bin_str
st.markdown(page_bg_img, unsafe_allow_html=True)
set_background('Screenshot (29).png')
red_title = '<h1 style="color: white;">Equipment Failure Prediction</h1>'
Display the red title using st.markdown
st.markdown(red_title, unsafe_allow_html=True)
# Display the custom CSS style
uploaded_file = st.file_uploader('Upload an Excel or CSV file', type=["xlsx", "csv"])
if uploaded_file is not None:
# Read the file into a DataFrame
if uploaded_file.type == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": # Excel file
df = pd.read_excel(uploaded_file, engine='openpyxl')
else: # CSV file
df = pd.read_csv(uploaded_file)
#st.session_state.predictions_df = df
#st.session_state.uploaded_file=uploaded_file
# Display the first screen
if st.button("Generate predictions"):
model = joblib.load('rfc_smote_1.joblib')
prediction = ''
if 'machine_status' in df.columns.to_list():
prediction = model.predict(df.drop(columns=['machine_status']))
else:
prediction = model.predict(df)
df['Predicted_Status'] = prediction
st.success("Predictions made successfully!")
st.session_state.predictions_df = df
st.session_state.uploaded_file=uploaded_file
# Display the modified DataFrame with predictions
# Save the DataFrame with predictions to st.session_state
# Move to the second screen (graph display)
def display_graph(predictions_df,uploaded_file):
def get_base64(bin_file):
with open(bin_file, 'rb') as f:
data = f.read()
return base64.b64encode(data).decode()
def set_background(png_file):
bin_str = get_base64(png_file)
page_bg_img = '''
.stApp {
background-image: url("data:image/png;base64,%s");
background-size: cover;
}
''' % bin_str
st.markdown(page_bg_img, unsafe_allow_html=True)
set_background('Screenshot (26).png')
st.markdown('<div style="margin-top: 50px;"></div>', unsafe_allow_html=True)
st.subheader("Early warning Signal:")
# Create a DataFrame with the first 10 records with prediction status 1
df_status_1 = predictions_df[predictions_df['Predicted_Status'] == 1]
# Create a DataFrame with all records with prediction status 0
df_status_0 = predictions_df[predictions_df['Predicted_Status'] == 0]
# Combine the DataFrames
df_combined = pd.concat([df_status_0, df_status_1])
df_combined['Synthetic_Timestamp'] = pd.date_range(start='2023-01-01 00:00', periods=len(df_combined), freq='T')
# Extract hours and minutes from the timestamp
df_combined['Hour_Minute'] = df_combined['Synthetic_Timestamp'].dt.strftime('%H:%M')
plt.figure(figsize=(10, 3))
sns.scatterplot(x='Synthetic_Timestamp', y='Predicted_Status', hue='Predicted_Status',marker='o', s=200, data=df_combined, palette={1: "red", 0: "green"})
plt.xticks(rotation=45, ha='right')
#plt.title("Machine Status Prediction - Combined")
plt.xlabel("Timestamp")
plt.ylabel("Value")
st.pyplot()
#Create a download link
st.subheader("Download the File with Predictions:")
st.write("Download the File with Predictions:")
#st.markdown(title1, unsafe_allow_html=True)
modified_file_name = f"file_with_predictions_{uploaded_file.name}" if uploaded_file.name else "file_with_predictions.xlsx"
# Convert DataFrame to binary stream
modified_file = io.BytesIO()
if uploaded_file.type == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": # Excel file
predictions_df.to_excel(modified_file, index=False, engine='xlsxwriter')
else: # CSV file
predictions_df.to_csv(modified_file, index=False)
modified_file.seek(0)
# Create a download link
st.download_button(label="Download File with Predictions", data=modified_file, file_name=modified_file_name, key="download_file_with_predictions")
Run the app
if name == "main":
st.set_option('deprecation.showPyplotGlobalUse', False)
st.set_page_config(page_title="Equipment Failure Prediction", page_icon="📈")
pages = ["Upload and Predict", "Graph and Download"]
page = st.sidebar.selectbox("Select a page", pages)
if page == "Upload and Predict":
upload_and_generate_predictions()
elif page=="Graph and Download":
if hasattr(st.session_state, 'predictions_df'):
display_graph(st.session_state.predictions_df,st.session_state.uploaded_file)
else:
st.warning("Please upload a file on the 'Upload and Predict' page first.")
this is my code in graph part for 10 records each it showimg nyc graph for all records it is nit showing correctly can you correct it