Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files- src/streamlit_app.py +255 -38
src/streamlit_app.py
CHANGED
|
@@ -1,40 +1,257 @@
|
|
| 1 |
-
import altair as alt
|
| 2 |
-
import numpy as np
|
| 3 |
-
import pandas as pd
|
| 4 |
import streamlit as st
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
|
| 7 |
-
#
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
In the meantime, below is an example of what you can do with just a few lines of code:
|
| 14 |
-
"""
|
| 15 |
-
|
| 16 |
-
num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
|
| 17 |
-
num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
|
| 18 |
-
|
| 19 |
-
indices = np.linspace(0, 1, num_points)
|
| 20 |
-
theta = 2 * np.pi * num_turns * indices
|
| 21 |
-
radius = indices
|
| 22 |
-
|
| 23 |
-
x = radius * np.cos(theta)
|
| 24 |
-
y = radius * np.sin(theta)
|
| 25 |
-
|
| 26 |
-
df = pd.DataFrame({
|
| 27 |
-
"x": x,
|
| 28 |
-
"y": y,
|
| 29 |
-
"idx": indices,
|
| 30 |
-
"rand": np.random.randn(num_points),
|
| 31 |
-
})
|
| 32 |
-
|
| 33 |
-
st.altair_chart(alt.Chart(df, height=700, width=700)
|
| 34 |
-
.mark_point(filled=True)
|
| 35 |
-
.encode(
|
| 36 |
-
x=alt.X("x", axis=None),
|
| 37 |
-
y=alt.Y("y", axis=None),
|
| 38 |
-
color=alt.Color("idx", legend=None, scale=alt.Scale()),
|
| 39 |
-
size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
|
| 40 |
-
))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import numpy as np
|
| 4 |
+
import altair as alt
|
| 5 |
+
import os
|
| 6 |
+
import time
|
| 7 |
+
import joblib
|
| 8 |
+
|
| 9 |
+
# =========================
|
| 10 |
+
# PATH SETUP
|
| 11 |
+
# =========================
|
| 12 |
+
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
|
| 13 |
+
|
| 14 |
+
DATA_PATH = os.path.join(BASE_DIR, "val.csv")
|
| 15 |
+
|
| 16 |
+
REG_PATH = os.path.join(BASE_DIR, "model_trainer/regression/model.pkl")
|
| 17 |
+
CLF_PATH = os.path.join(BASE_DIR, "model_trainer/classification/model.pkl")
|
| 18 |
+
CLUSTER_PATH = os.path.join(BASE_DIR, "model_trainer/clustering/model.pkl")
|
| 19 |
+
SCALER_PATH = os.path.join(BASE_DIR, "model_trainer/clustering/scaler.pkl")
|
| 20 |
+
|
| 21 |
+
# =========================
|
| 22 |
+
# LOAD MODELS
|
| 23 |
+
# =========================
|
| 24 |
+
@st.cache_resource
|
| 25 |
+
def load_models():
|
| 26 |
+
reg = joblib.load(REG_PATH)
|
| 27 |
+
clf = joblib.load(CLF_PATH)
|
| 28 |
+
cluster = joblib.load(CLUSTER_PATH)
|
| 29 |
+
scaler = joblib.load(SCALER_PATH)
|
| 30 |
+
return reg, clf, cluster, scaler
|
| 31 |
+
|
| 32 |
+
reg_model, clf_model, cluster_model, cluster_scaler = load_models()
|
| 33 |
+
|
| 34 |
+
# =========================
|
| 35 |
+
# LOAD DATA
|
| 36 |
+
# =========================
|
| 37 |
+
@st.cache_data
|
| 38 |
+
def load_data():
|
| 39 |
+
return pd.read_csv(DATA_PATH)
|
| 40 |
+
|
| 41 |
+
FULL_DATA = load_data()
|
| 42 |
+
|
| 43 |
+
# =========================
|
| 44 |
+
# STREAM STATE
|
| 45 |
+
# =========================
|
| 46 |
+
if "cursor" not in st.session_state:
|
| 47 |
+
st.session_state.cursor = 0
|
| 48 |
+
|
| 49 |
+
if "telemetry" not in st.session_state:
|
| 50 |
+
st.session_state.telemetry = pd.DataFrame()
|
| 51 |
+
|
| 52 |
+
# =========================
|
| 53 |
+
# UI CONFIG
|
| 54 |
+
# =========================
|
| 55 |
+
st.set_page_config(page_title="Race Telemetry", layout="wide")
|
| 56 |
+
|
| 57 |
+
st.markdown("""
|
| 58 |
+
<style>
|
| 59 |
+
.ml-label {
|
| 60 |
+
font-size: 20px;
|
| 61 |
+
color: #94a3b8;
|
| 62 |
+
margin-bottom: 0px;
|
| 63 |
+
}
|
| 64 |
+
.ml-value {
|
| 65 |
+
font-size: 38px;
|
| 66 |
+
font-weight: 500;
|
| 67 |
+
line-height: 2;
|
| 68 |
+
}
|
| 69 |
+
</style>
|
| 70 |
+
""", unsafe_allow_html=True)
|
| 71 |
+
|
| 72 |
+
# =========================
|
| 73 |
+
# SIDEBAR
|
| 74 |
+
# =========================
|
| 75 |
+
st.sidebar.title("Pit Wall Controls")
|
| 76 |
+
|
| 77 |
+
auto_refresh = st.sidebar.toggle("Auto Refresh", value=True)
|
| 78 |
+
refresh_interval = st.sidebar.slider("Refresh Interval (seconds)", 1, 5, 1)
|
| 79 |
+
batch_size = st.sidebar.selectbox("Rows per fetch", [1, 5, 10], index=0)
|
| 80 |
+
|
| 81 |
+
# =========================
|
| 82 |
+
# FETCH STREAM DATA
|
| 83 |
+
# =========================
|
| 84 |
+
def fetch_rows(batch_size):
|
| 85 |
+
start = st.session_state.cursor
|
| 86 |
+
end = start + batch_size
|
| 87 |
+
|
| 88 |
+
batch = FULL_DATA.iloc[start:end].copy()
|
| 89 |
+
st.session_state.cursor = end
|
| 90 |
+
|
| 91 |
+
return batch
|
| 92 |
+
|
| 93 |
+
# =========================
|
| 94 |
+
# REAL INFERENCE
|
| 95 |
+
# =========================
|
| 96 |
+
def run_inference(df_batch):
|
| 97 |
+
outputs = []
|
| 98 |
+
|
| 99 |
+
for _, row in df_batch.iterrows():
|
| 100 |
+
row_dict = row.to_dict()
|
| 101 |
+
|
| 102 |
+
# -------- REGRESSION --------
|
| 103 |
+
reg_features = ["speed", "current_engine_rpm", "boost", "torque"]
|
| 104 |
+
X_reg = np.array([row_dict[f] for f in reg_features]).reshape(1, -1)
|
| 105 |
+
pred_lap = float(reg_model.predict(X_reg)[0])
|
| 106 |
+
|
| 107 |
+
# -------- CLASSIFICATION --------
|
| 108 |
+
clf_features = ["speed", "current_engine_rpm", "gear"]
|
| 109 |
+
X_clf = np.array([row_dict[f] for f in clf_features]).reshape(1, -1)
|
| 110 |
+
pred_gear = int(clf_model.predict(X_clf)[0])
|
| 111 |
+
|
| 112 |
+
# -------- CLUSTERING --------
|
| 113 |
+
cluster_features = ["speed", "current_engine_rpm", "boost", "torque", "avg_tire_temp"]
|
| 114 |
+
X_cluster = np.array([row_dict[f] for f in cluster_features]).reshape(1, -1)
|
| 115 |
+
X_scaled = cluster_scaler.transform(X_cluster)
|
| 116 |
+
|
| 117 |
+
label = cluster_model.predict(X_scaled)[0]
|
| 118 |
+
behavior = "Aggressive" if label == 1 else "Smooth"
|
| 119 |
+
|
| 120 |
+
# attach predictions
|
| 121 |
+
row_dict["predicted_lap_time"] = pred_lap
|
| 122 |
+
row_dict["predicted_gear"] = pred_gear
|
| 123 |
+
row_dict["driving_behavior"] = behavior
|
| 124 |
+
|
| 125 |
+
outputs.append(row_dict)
|
| 126 |
+
|
| 127 |
+
return pd.DataFrame(outputs)
|
| 128 |
+
|
| 129 |
+
# =========================
|
| 130 |
+
# FETCH + PROCESS
|
| 131 |
+
# =========================
|
| 132 |
+
new_data = fetch_rows(batch_size)
|
| 133 |
+
|
| 134 |
+
if not new_data.empty:
|
| 135 |
+
processed = run_inference(new_data)
|
| 136 |
+
|
| 137 |
+
st.session_state.telemetry = pd.concat(
|
| 138 |
+
[st.session_state.telemetry, processed],
|
| 139 |
+
ignore_index=True
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
df = st.session_state.telemetry
|
| 143 |
+
|
| 144 |
+
if df.empty:
|
| 145 |
+
st.stop()
|
| 146 |
+
|
| 147 |
+
df["t"] = range(len(df))
|
| 148 |
+
latest = df.iloc[-1]
|
| 149 |
+
|
| 150 |
+
# =========================
|
| 151 |
+
# TITLE
|
| 152 |
+
# =========================
|
| 153 |
+
st.markdown(
|
| 154 |
+
"""
|
| 155 |
+
<div style="text-align:center; line-height:0;">
|
| 156 |
+
<h2>🏁 Race Telemetry</h2>
|
| 157 |
+
<h4>Pit Wall Dashboard</h4>
|
| 158 |
+
</div>
|
| 159 |
+
""",
|
| 160 |
+
unsafe_allow_html=True
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
# =========================
|
| 164 |
+
# MAIN GRID
|
| 165 |
+
# =========================
|
| 166 |
+
left, right = st.columns([3, 1])
|
| 167 |
+
|
| 168 |
+
with left:
|
| 169 |
+
|
| 170 |
+
with st.container(border=True):
|
| 171 |
+
c1, c2, c3 = st.columns(3)
|
| 172 |
+
|
| 173 |
+
with c1:
|
| 174 |
+
st.markdown('<div class="ml-label">Predicted Lap</div>', unsafe_allow_html=True)
|
| 175 |
+
st.markdown(
|
| 176 |
+
f'<div class="ml-value" style="color:#38bdf8;">{latest["predicted_lap_time"]:.2f} s</div>',
|
| 177 |
+
unsafe_allow_html=True
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
with c2:
|
| 181 |
+
st.markdown('<div class="ml-label">Recommended Gear</div>', unsafe_allow_html=True)
|
| 182 |
+
st.markdown(
|
| 183 |
+
f'<div class="ml-value" style="color:#22c55e;">{int(latest["predicted_gear"])}</div>',
|
| 184 |
+
unsafe_allow_html=True
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
with c3:
|
| 188 |
+
st.markdown('<div class="ml-label">Driving Style</div>', unsafe_allow_html=True)
|
| 189 |
+
st.markdown(
|
| 190 |
+
f'<div class="ml-value" style="color:#facc15;">{latest["driving_behavior"]}</div>',
|
| 191 |
+
unsafe_allow_html=True
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
st.markdown("<br>", unsafe_allow_html=True)
|
| 195 |
+
|
| 196 |
+
r2c1, r2c2 = st.columns(2)
|
| 197 |
+
|
| 198 |
+
r2c1.metric("Speed (km/h)", f"{latest['speed']:.1f}")
|
| 199 |
+
r2c1.altair_chart(
|
| 200 |
+
alt.Chart(df).mark_line().encode(x="t:Q", y="speed:Q"),
|
| 201 |
+
use_container_width=True
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
r2c2.metric("Engine RPM", int(latest["current_engine_rpm"]))
|
| 205 |
+
r2c2.altair_chart(
|
| 206 |
+
alt.Chart(df).mark_area(opacity=0.7).encode(x="t:Q", y="current_engine_rpm:Q"),
|
| 207 |
+
use_container_width=True
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
with right:
|
| 211 |
+
st.markdown("### Track")
|
| 212 |
+
st.image("assets/track.png", use_container_width=True)
|
| 213 |
+
|
| 214 |
+
# =========================
|
| 215 |
+
# LOWER METRICS
|
| 216 |
+
# =========================
|
| 217 |
+
p1, p2, p3, p4 = st.columns(4)
|
| 218 |
+
|
| 219 |
+
df["power_kw"] = df["power"] / 1000
|
| 220 |
+
|
| 221 |
+
p1.metric("Power (kW)", f"{df['power_kw'].iloc[-1]:.1f}")
|
| 222 |
+
p1.altair_chart(alt.Chart(df).mark_area().encode(x="t", y="power_kw"), use_container_width=True)
|
| 223 |
+
|
| 224 |
+
p2.metric("Torque (Nm)", f"{latest['torque']:.1f}")
|
| 225 |
+
p2.altair_chart(alt.Chart(df).mark_line().encode(x="t", y="torque"), use_container_width=True)
|
| 226 |
+
|
| 227 |
+
p3.metric("Boost (psi)", f"{latest['boost']:.2f}")
|
| 228 |
+
p3.altair_chart(alt.Chart(df).mark_line().encode(x="t", y="boost"), use_container_width=True)
|
| 229 |
+
|
| 230 |
+
p4.metric("Avg Tire Temp (°C)", f"{latest['avg_tire_temp']:.1f}")
|
| 231 |
+
p4.altair_chart(alt.Chart(df).mark_line().encode(x="t", y="avg_tire_temp"), use_container_width=True)
|
| 232 |
+
|
| 233 |
+
# =========================
|
| 234 |
+
# ATTITUDE
|
| 235 |
+
# =========================
|
| 236 |
+
attitude_chart = alt.Chart(df).transform_fold(
|
| 237 |
+
["yaw", "pitch", "roll"],
|
| 238 |
+
as_=["Axis", "Value"]
|
| 239 |
+
).mark_line().encode(
|
| 240 |
+
x="t:Q",
|
| 241 |
+
y="Value:Q",
|
| 242 |
+
color="Axis:N"
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
st.metric(
|
| 246 |
+
"Yaw / Pitch / Roll (rad)",
|
| 247 |
+
f"{latest['yaw']:.2f}, {latest['pitch']:.2f}, {latest['roll']:.2f}"
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
st.altair_chart(attitude_chart, use_container_width=True)
|
| 251 |
|
| 252 |
+
# =========================
|
| 253 |
+
# AUTO REFRESH
|
| 254 |
+
# =========================
|
| 255 |
+
if auto_refresh:
|
| 256 |
+
time.sleep(refresh_interval)
|
| 257 |
+
st.rerun()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|