ESMATUGBA commited on
Commit
1074cbb
·
verified ·
1 Parent(s): 266f379

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +151 -37
src/streamlit_app.py CHANGED
@@ -1,40 +1,154 @@
1
- import altair as alt
2
  import numpy as np
3
  import pandas as pd
4
- import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
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 numpy as np
3
  import pandas as pd
4
+ import plotly.graph_objects as go
5
+ import pickle
6
+ from keras.models import load_model
7
+
8
+ # ============================================================
9
+ # SETTINGS & MODEL LOAD
10
+ # ============================================================
11
+ st.set_page_config(page_title="Workforce AI Optimizer", layout="wide")
12
+
13
+ # Sidebar genişliğini sabitleyen CSS
14
+ st.markdown(
15
+ """
16
+ <style>
17
+ [data-testid="stSidebar"][aria-expanded="true"]{
18
+ min-width: 360px;
19
+ max-width: 360px;
20
+ }
21
+ </style>
22
+ """,
23
+ unsafe_allow_html=True,
24
+ )
25
+
26
+ @st.cache_resource
27
+ def load_assets():
28
+ model = load_model("lstm_traffic_model.keras")
29
+ sc = pickle.load(open("scaler.pkl", "rb"))
30
+ return model, sc
31
+
32
+ try:
33
+ model, sc = load_assets()
34
+ except Exception as e:
35
+ st.error(f"Error: Model files not found! -> {e}")
36
+ st.stop()
37
+
38
+ # ============================================================
39
+ # SIDEBAR / 🛠️ SETUP & GUIDE
40
+ # ============================================================
41
+ st.sidebar.title("🛠️ Setup & Guide / Rehber")
42
+
43
+ st.sidebar.markdown("""
44
+ **Data Format / Veri Formatı:**
45
+ The CSV should contain historical call data. / CSV geçmiş çağrı verilerini içermelidir.
46
+ """)
47
+
48
+ # SLOT MANTIĞI - 6 Örnekli ve Noktalı Versiyon
49
+ st.sidebar.info("""
50
+ **Slot Logic / Slot Mantığı:**
51
+ - **Slot 0:** 08:00-09:00 (100 cals)
52
+ - **Slot 1:** 09:00-10:00 (150 cals)
53
+ - **Slot 2:** 10:00-11:00 (120 cals)
54
+ - **Slot 3:** 11:00-12:00 (180 cals)
55
+ - **Slot 4:** 12:00-13:00 (200 cals)
56
+ - **Slot 5:** 13:00-14:00 (160 cals)
57
+ - **...**
58
+ - **Slot 81:** Midnight (5 cals)
59
+ """)
60
+
61
+ st.sidebar.subheader("Sample CSV / Örnek Yapı")
62
+ example_df = pd.DataFrame({"calls": [105, 140, 88, 120, 200, 160]})
63
+ st.sidebar.dataframe(example_df, use_container_width=True)
64
+
65
+ st.sidebar.warning("⚠️ **Column Name:** 'calls' or 'Incoming Calls'")
66
+
67
+ st.sidebar.markdown("---")
68
+ st.sidebar.subheader("💰 Cost Settings / Maliyet")
69
+ wage = st.sidebar.number_input("Hourly Wage / Saatlik Ücret ($)", value=20)
70
+ capacity = st.sidebar.number_input("Calls per Staff / Kapasite", value=15)
71
+
72
+ # ============================================================
73
+ # MAIN UI
74
+ # ============================================================
75
+ st.title("📞 Workforce Optimization AI / İş Gücü Optimizasyonu")
76
+ st.write("Ensuring the right number of people at the right time.")
77
+ st.markdown("---")
78
+
79
+ file = st.file_uploader("Upload CSV / CSV Yükle", type=["csv"])
80
+
81
+ if file is not None:
82
+ df = pd.read_csv(file)
83
+ target_col = "calls" if "calls" in df.columns else ("Incoming Calls" if "Incoming Calls" in df.columns else None)
84
+
85
+ if target_col is None:
86
+ st.error("❌ Column not found!")
87
+ st.stop()
88
+
89
+ raw_data = df[[target_col]].values
90
+
91
+ # PREDICTION
92
+ scaled_data = sc.transform(raw_data)
93
+ pred_scaled = model.predict(scaled_data)
94
+ predictions = sc.inverse_transform(pred_scaled)
95
+ needed_staff = np.ceil(predictions / capacity).flatten().astype(int)
96
+
97
+ # 🎯 DECISION LOGIC
98
+ st.header("🎯 Decision Logic / Karar Mantığı")
99
+ logic_col1, logic_col2 = st.columns(2)
100
+
101
+ with logic_col1:
102
+ st.error("### 🔥 High Intensity (Yüksek Yoğunluk)")
103
+ st.write("**Advice:** INCREASE STAFF to protect quality.")
104
+ st.write("**Öneri:** Kalite için PERSONEL ARTIRIN.")
105
+
106
+ with logic_col2:
107
+ st.success("### 💰 Saving Area (Tasarruf Alanı)")
108
+ st.write("**Advice:** REDUCE STAFF to maximize profit.")
109
+ st.write("**Öneri:** Kâr için PERSONELİ AZALTIN.")
110
+
111
+ # 📈 GRAPH
112
+ st.markdown("---")
113
+ st.subheader("📈 Capacity Analysis / Kapasite Analizi")
114
+ fig = go.Figure()
115
+ fig.add_trace(go.Scatter(y=raw_data.flatten(), name="Past", line=dict(color="gray")))
116
+ fig.add_trace(go.Scatter(y=predictions.flatten(), name="AI Forecast", line=dict(color="#1C83E1", width=3)))
117
+ fig.add_trace(go.Bar(y=needed_staff * capacity, name="Capacity", opacity=0.2, marker_color="green"))
118
+ fig.update_layout(hovermode="x unified", template="plotly_white", height=400)
119
+ st.plotly_chart(fig, use_container_width=True)
120
+
121
+ # 🧠 RECOMMENDATIONS
122
+ st.header("🧠 AI Strategic Recommendations")
123
+ mean_val = np.mean(needed_staff)
124
+ peak_indices = np.where(needed_staff > mean_val * 1.25)[0].tolist()
125
+ low_indices = np.where(needed_staff < mean_val * 0.75)[0].tolist()
126
+
127
+ c1, c2 = st.columns(2)
128
+ with c1:
129
+ st.error(f"### 🚨 High Intensity")
130
+ if peak_indices:
131
+ st.write(f"**At:** {', '.join([f'Slot {i}' for i in peak_indices[:5]])}...")
132
+ st.write("Increase staff. / Personel artırın.")
133
+ else:
134
+ st.write("No major peaks.")
135
+
136
+ with c2:
137
+ st.success(f"### 📉 Saving Area")
138
+ if low_indices:
139
+ st.write(f"**At:** {', '.join([f'Slot {i}' for i in low_indices[:5]])}...")
140
+ st.write("Reduce staff. / Personeli azaltın.")
141
+ else:
142
+ st.write("No saving opportunity.")
143
+
144
+ # 📊 TABLE
145
+ with st.expander("📊 Detailed Schedule Table"):
146
+ res_df = pd.DataFrame({
147
+ "Time Slot": [f"Slot {i}" for i in range(len(predictions))],
148
+ "Predicted Demand": predictions.flatten().astype(int),
149
+ "Suggested Staff": needed_staff
150
+ })
151
+ st.dataframe(res_df, use_container_width=True)
152
 
153
+ else:
154
+ st.info("👋 Please upload your CSV file to begin. / Başlamak için CSV yükleyin.")