import numpy as np
import pandas as pd
import plotly.graph_objects as go
import streamlit as st
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
st.set_page_config(page_title="AIMPACT | Equipment Health",page_icon="⚙️",layout="wide")
st.title("⚙️ AI Equipment Health Monitor")
st.caption("Teaching demo • Synthetic training data • NOT a real equipment health diagnosis")
@st.cache_data
def make_data():
    rng=np.random.default_rng(12); n=1400
    temp=rng.normal(67,12,n).clip(30,120); vib=rng.gamma(2,1.15,n); load=rng.uniform(25,100,n)
    risk=0.065*(temp-75)+0.8*(vib-3)+0.02*(load-75)
    p=1/(1+np.exp(-risk)); y=rng.binomial(1,p)
    return pd.DataFrame({'temperature_c':temp,'vibration_mm_s':vib,'load_pct':load,'anomaly':y})
df=make_data(); X=df.drop(columns='anomaly');y=df.anomaly
Xtr,Xte,ytr,yte=train_test_split(X,y,test_size=.25,stratify=y,random_state=42)
model=RandomForestClassifier(n_estimators=120,min_samples_leaf=4,random_state=42).fit(Xtr,ytr)
with st.sidebar:
    st.header('Test equipment conditions')
    temp=st.slider('Temperature (°C)',30,120,78)
    vib=st.slider('Vibration (mm/s)',0.0,12.0,3.2,.1)
    load=st.slider('Load (%)',25,100,78)
prob=float(model.predict_proba(pd.DataFrame([{'temperature_c':temp,'vibration_mm_s':vib,'load_pct':load}]))[0,1])
a,b,c=st.columns(3)
a.metric('Model anomaly probability',f'{prob:.0%}')
b.metric('Teaching status','Investigate' if prob>=.5 else 'Lower score')
c.metric('Held-out accuracy',f'{model.score(Xte,yte):.0%}')
fig=go.Figure(go.Indicator(mode='gauge+number',value=round(prob*100,1),title={'text':'Illustrative anomaly score (%)'},gauge={'axis':{'range':[0,100]},'bar':{'color':'#20bfa9'}}))
st.plotly_chart(fig,use_container_width=True)
st.subheader('Synthetic training examples')
st.scatter_chart(df,x='temperature_c',y='vibration_mm_s',color='anomaly')
with st.expander('Model evaluation and limitations'):
    st.text(classification_report(yte,model.predict(Xte),zero_division=0))
    st.write('Labels were generated from an invented mathematical relationship. Accuracy does not demonstrate performance on any real pump or motor.')
    st.dataframe(df.head(20))
st.download_button('Download synthetic training CSV',df.to_csv(index=False).encode(),'synthetic_equipment_health.csv','text/csv')
