File size: 5,446 Bytes
1074cbb 6ad1647 1074cbb 6ad1647 1074cbb | 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 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 | import streamlit as st
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import pickle
from keras.models import load_model
# ============================================================
# SETTINGS & MODEL LOAD
# ============================================================
st.set_page_config(page_title="Workforce AI Optimizer", layout="wide")
# Sidebar genişliğini sabitleyen CSS
st.markdown(
"""
<style>
[data-testid="stSidebar"][aria-expanded="true"]{
min-width: 360px;
max-width: 360px;
}
</style>
""",
unsafe_allow_html=True,
)
@st.cache_resource
def load_assets():
model = load_model("lstm_traffic_model.keras")
sc = pickle.load(open("scaler.pkl", "rb"))
return model, sc
try:
model, sc = load_assets()
except Exception as e:
st.error(f"Error: Model files not found! -> {e}")
st.stop()
# ============================================================
# SIDEBAR / 🛠️ SETUP & GUIDE
# ============================================================
st.sidebar.title("🛠️ Setup & Guide / Rehber")
st.sidebar.markdown("""
**Data Format / Veri Formatı:**
The CSV should contain historical call data. / CSV geçmiş çağrı verilerini içermelidir.
""")
# SLOT MANTIĞI - 6 Örnekli ve Noktalı Versiyon
st.sidebar.info("""
**Slot Logic / Slot Mantığı:**
- **Slot 0:** 08:00-09:00 (100 cals)
- **Slot 1:** 09:00-10:00 (150 cals)
- **Slot 2:** 10:00-11:00 (120 cals)
- **Slot 3:** 11:00-12:00 (180 cals)
- **Slot 4:** 12:00-13:00 (200 cals)
- **Slot 5:** 13:00-14:00 (160 cals)
- **...**
- **Slot 81:** Midnight (5 cals)
""")
st.sidebar.subheader("Sample CSV / Örnek Yapı")
example_df = pd.DataFrame({"calls": [105, 140, 88, 120, 200, 160]})
st.sidebar.dataframe(example_df, use_container_width=True)
st.sidebar.warning("⚠️ **Column Name:** 'calls' or 'Incoming Calls'")
st.sidebar.markdown("---")
st.sidebar.subheader("💰 Cost Settings / Maliyet")
wage = st.sidebar.number_input("Hourly Wage / Saatlik Ücret ($)", value=20)
capacity = st.sidebar.number_input("Calls per Staff / Kapasite", value=15)
# ============================================================
# MAIN UI
# ============================================================
st.title("📞 Workforce Optimization AI / İş Gücü Optimizasyonu")
st.write("Ensuring the right number of people at the right time.")
st.markdown("---")
file = st.file_uploader("Upload CSV / CSV Yükle", type=["csv"])
if file is not None:
df = pd.read_csv(file)
target_col = "calls" if "calls" in df.columns else ("Incoming Calls" if "Incoming Calls" in df.columns else None)
if target_col is None:
st.error("❌ Column not found!")
st.stop()
raw_data = df[[target_col]].values
# PREDICTION
scaled_data = sc.transform(raw_data)
pred_scaled = model.predict(scaled_data)
predictions = sc.inverse_transform(pred_scaled)
needed_staff = np.ceil(predictions / capacity).flatten().astype(int)
# 🎯 DECISION LOGIC
st.header("🎯 Decision Logic / Karar Mantığı")
logic_col1, logic_col2 = st.columns(2)
with logic_col1:
st.error("### 🔥 High Intensity (Yüksek Yoğunluk)")
st.write("**Advice:** INCREASE STAFF to protect quality.")
st.write("**Öneri:** Kalite için PERSONEL ARTIRIN.")
with logic_col2:
st.success("### 💰 Saving Area (Tasarruf Alanı)")
st.write("**Advice:** REDUCE STAFF to maximize profit.")
st.write("**Öneri:** Kâr için PERSONELİ AZALTIN.")
# 📈 GRAPH
st.markdown("---")
st.subheader("📈 Capacity Analysis / Kapasite Analizi")
fig = go.Figure()
fig.add_trace(go.Scatter(y=raw_data.flatten(), name="Past", line=dict(color="gray")))
fig.add_trace(go.Scatter(y=predictions.flatten(), name="AI Forecast", line=dict(color="#1C83E1", width=3)))
fig.add_trace(go.Bar(y=needed_staff * capacity, name="Capacity", opacity=0.2, marker_color="green"))
fig.update_layout(hovermode="x unified", template="plotly_white", height=400)
st.plotly_chart(fig, use_container_width=True)
# 🧠 RECOMMENDATIONS
st.header("🧠 AI Strategic Recommendations")
mean_val = np.mean(needed_staff)
peak_indices = np.where(needed_staff > mean_val * 1.25)[0].tolist()
low_indices = np.where(needed_staff < mean_val * 0.75)[0].tolist()
c1, c2 = st.columns(2)
with c1:
st.error(f"### 🚨 High Intensity")
if peak_indices:
st.write(f"**At:** {', '.join([f'Slot {i}' for i in peak_indices[:5]])}...")
st.write("Increase staff. / Personel artırın.")
else:
st.write("No major peaks.")
with c2:
st.success(f"### 📉 Saving Area")
if low_indices:
st.write(f"**At:** {', '.join([f'Slot {i}' for i in low_indices[:5]])}...")
st.write("Reduce staff. / Personeli azaltın.")
else:
st.write("No saving opportunity.")
# 📊 TABLE
with st.expander("📊 Detailed Schedule Table"):
res_df = pd.DataFrame({
"Time Slot": [f"Slot {i}" for i in range(len(predictions))],
"Predicted Demand": predictions.flatten().astype(int),
"Suggested Staff": needed_staff
})
st.dataframe(res_df, use_container_width=True)
else:
st.info("👋 Please upload your CSV file to begin. / Başlamak için CSV yükleyin.") |