SuhasGholkar commited on
Commit
d8d9973
Β·
verified Β·
1 Parent(s): 272732e

Update src/mis.py

Browse files
Files changed (1) hide show
  1. src/mis.py +71 -46
src/mis.py CHANGED
@@ -59,37 +59,42 @@ def _apply_filters_base_query(start_dt, end_dt, intents_selected, user_id_select
59
  return where_sql, params
60
 
61
  def render_mis_admin(conn):
62
- st.title("πŸ“Š MIS (Admin)")
 
63
 
64
- # --- Filters
65
- st.subheader("Filters")
 
66
  intents = _load_distinct_intents(conn)
67
  users_df = _load_users_for_picker(conn)
68
 
69
- c1, c2, c3 = st.columns([1,1,1])
70
- with c1:
71
- start_date = st.date_input("Start date", value=None, format="YYYY-MM-DD")
72
- with c2:
73
- end_date = st.date_input("End date", value=None, format="YYYY-MM-DD")
74
- with c3:
75
- chosen_intents = st.multiselect("Intent(s)", intents, default=[])
76
 
77
  user_picker = None
78
  if not users_df.empty:
79
  user_label_to_id = {row.label: int(row.id) for _, row in users_df.iterrows()}
80
  selected_label = st.selectbox(
81
- "Filter by user", options=["(All)"] + users_df["label"].tolist(), index=0
 
 
 
82
  )
83
  user_picker = user_label_to_id.get(selected_label, None)
84
  else:
85
  st.info("No users yet; user filter not available.")
86
 
87
- # Build WHERE
88
  start_str = start_date.strftime("%Y-%m-%d") if start_date else None
89
  end_str = end_date.strftime("%Y-%m-%d") if end_date else None
90
  where_sql, params = _apply_filters_base_query(start_str, end_str, chosen_intents, user_picker)
91
 
92
- # Query filtered data
93
  base_sql = (
94
  "SELECT id, user_id, timestamp, intent, sentiment, resolution, ftr_ms "
95
  "FROM chat_history "
@@ -100,49 +105,69 @@ def render_mis_admin(conn):
100
  st.info("No chats found for the selected filters.")
101
  return
102
 
103
- # KPIs
104
  total = len(df)
105
  avg_ftr = df["ftr_ms"].dropna().mean() if "ftr_ms" in df else None
106
  p95_ftr = df["ftr_ms"].dropna().quantile(0.95) if "ftr_ms" in df and not df["ftr_ms"].dropna().empty else None
107
  resolved_pct = (df["resolution"] == "Resolved").mean() if "resolution" in df else None
108
 
109
- c1,c2,c3,c4 = st.columns(4)
110
- _metric_card("Total chats", f"{total}")
111
- _metric_card("Resolved %", f"{resolved_pct*100:.1f}%" if resolved_pct is not None else None)
112
- _metric_card("Avg FTR (ms)", f"{avg_ftr:.0f}" if avg_ftr is not None else None)
113
- _metric_card("P95 FTR (ms)", f"{p95_ftr:.0f}" if p95_ftr is not None else None)
114
-
115
- st.markdown("---")
116
-
117
- # By intent
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  if "intent" in df:
119
- st.subheader("Top intents")
120
- counts = df["intent"].fillna("UNMAPPED").value_counts().head(15)
121
- fig, ax = plt.subplots()
122
- ax.bar(counts.index.astype(str), counts.values)
123
- ax.set_ylabel("Count"); ax.set_title("Top intents")
124
- plt.setp(ax.get_xticklabels(), rotation=30, ha="right")
125
- st.pyplot(fig)
126
-
127
- # Sentiment distribution
 
128
  if "sentiment" in df:
129
- st.subheader("Sentiment distribution")
130
- sent = df["sentiment"].fillna("Unknown").value_counts()
131
- fig2, ax2 = plt.subplots()
132
- ax2.bar(sent.index.astype(str), sent.values)
133
- ax2.set_ylabel("Count")
134
- st.pyplot(fig2)
135
-
136
- # Volume by user
137
- st.subheader("Top users by chat volume")
 
 
138
  by_user = df.groupby("user_id").size().sort_values(ascending=False).head(10)
139
- fig3, ax3 = plt.subplots()
140
  ax3.bar(by_user.index.astype(str), by_user.values)
141
- ax3.set_xlabel("user_id"); ax3.set_ylabel("Chats")
142
- st.pyplot(fig3)
 
143
 
144
- st.subheader("Filtered chats (first 300)")
145
- st.dataframe(df.head(300), use_container_width=True)
 
146
 
147
  def render_mis_user(conn, user_id: int):
148
  st.title("πŸ“Š My MIS")
 
59
  return where_sql, params
60
 
61
  def render_mis_admin(conn):
62
+ import pandas as pd
63
+ import matplotlib.pyplot as plt
64
 
65
+ st.markdown("### πŸ“Š MIS (Admin) β€” Compact")
66
+
67
+ # --- Filters (unchanged sources)
68
  intents = _load_distinct_intents(conn)
69
  users_df = _load_users_for_picker(conn)
70
 
71
+ f1, f2, f3 = st.columns([1, 1, 1])
72
+ with f1:
73
+ start_date = st.date_input("From", value=None, format="YYYY-MM-DD", key="mis_admin_from")
74
+ with f2:
75
+ end_date = st.date_input("To", value=None, format="YYYY-MM-DD", key="mis_admin_to")
76
+ with f3:
77
+ chosen_intents = st.multiselect("Intent(s)", intents, default=[], key="mis_admin_intents")
78
 
79
  user_picker = None
80
  if not users_df.empty:
81
  user_label_to_id = {row.label: int(row.id) for _, row in users_df.iterrows()}
82
  selected_label = st.selectbox(
83
+ "User",
84
+ options=["(All)"] + users_df["label"].tolist(),
85
+ index=0,
86
+ key="mis_admin_user"
87
  )
88
  user_picker = user_label_to_id.get(selected_label, None)
89
  else:
90
  st.info("No users yet; user filter not available.")
91
 
92
+ # Build WHERE (same logic as your original)
93
  start_str = start_date.strftime("%Y-%m-%d") if start_date else None
94
  end_str = end_date.strftime("%Y-%m-%d") if end_date else None
95
  where_sql, params = _apply_filters_base_query(start_str, end_str, chosen_intents, user_picker)
96
 
97
+ # Query filtered data (same base)
98
  base_sql = (
99
  "SELECT id, user_id, timestamp, intent, sentiment, resolution, ftr_ms "
100
  "FROM chat_history "
 
105
  st.info("No chats found for the selected filters.")
106
  return
107
 
108
+ # ---- KPIs (retain your 4 KPIs, render as compact cards)
109
  total = len(df)
110
  avg_ftr = df["ftr_ms"].dropna().mean() if "ftr_ms" in df else None
111
  p95_ftr = df["ftr_ms"].dropna().quantile(0.95) if "ftr_ms" in df and not df["ftr_ms"].dropna().empty else None
112
  resolved_pct = (df["resolution"] == "Resolved").mean() if "resolution" in df else None
113
 
114
+ k1, k2, k3, k4 = st.columns(4)
115
+ with k1:
116
+ st.markdown('<div class="kpi-card">', unsafe_allow_html=True)
117
+ _metric_card("Total chats", f"{total}")
118
+ st.markdown("</div>", unsafe_allow_html=True)
119
+ with k2:
120
+ st.markdown('<div class="kpi-card">', unsafe_allow_html=True)
121
+ _metric_card("Resolved %", f"{resolved_pct*100:.1f}%" if resolved_pct is not None else None)
122
+ st.markdown("</div>", unsafe_allow_html=True)
123
+ with k3:
124
+ st.markdown('<div class="kpi-card">', unsafe_allow_html=True)
125
+ _metric_card("Avg FTR (ms)", f"{avg_ftr:.0f}" if avg_ftr is not None else None)
126
+ st.markdown("</div>", unsafe_allow_html=True)
127
+ with k4:
128
+ st.markdown('<div class="kpi-card">', unsafe_allow_html=True)
129
+ _metric_card("P95 FTR (ms)", f"{p95_ftr:.0f}" if p95_ftr is not None else None)
130
+ st.markdown("</div>", unsafe_allow_html=True)
131
+
132
+ st.markdown("")
133
+
134
+ # ---- Mini charts (short height)
135
+ cA, cB = st.columns(2)
136
+
137
+ # Top intents (same data; small bar)
138
  if "intent" in df:
139
+ with cA:
140
+ st.markdown('<div class="mini-chart"><b>Top intents</b></div>', unsafe_allow_html=True)
141
+ counts = df["intent"].fillna("UNMAPPED").value_counts().head(15)
142
+ fig, ax = plt.subplots(figsize=(5.4, 2.0)) # ~200px tall
143
+ ax.bar(counts.index.astype(str), counts.values)
144
+ ax.set_ylabel("Count"); ax.set_title("")
145
+ plt.setp(ax.get_xticklabels(), rotation=30, ha="right", fontsize=8)
146
+ st.pyplot(fig, use_container_width=True)
147
+
148
+ # Sentiment distribution (same data; small bar)
149
  if "sentiment" in df:
150
+ with cB:
151
+ st.markdown('<div class="mini-chart"><b>Sentiment distribution</b></div>', unsafe_allow_html=True)
152
+ sent = df["sentiment"].fillna("Unknown").value_counts()
153
+ fig2, ax2 = plt.subplots(figsize=(5.4, 2.0))
154
+ ax2.bar(sent.index.astype(str), sent.values)
155
+ ax2.set_ylabel("Count"); ax2.set_title("")
156
+ plt.setp(ax2.get_xticklabels(), rotation=0, ha="center", fontsize=9)
157
+ st.pyplot(fig2, use_container_width=True)
158
+
159
+ # Volume by user (same query; short)
160
+ st.markdown('<div class="mini-chart"><b>Top users by chat volume</b></div>', unsafe_allow_html=True)
161
  by_user = df.groupby("user_id").size().sort_values(ascending=False).head(10)
162
+ fig3, ax3 = plt.subplots(figsize=(6.0, 2.0))
163
  ax3.bar(by_user.index.astype(str), by_user.values)
164
+ ax3.set_xlabel("user_id"); ax3.set_ylabel("Chats"); ax3.set_title("")
165
+ plt.setp(ax3.get_xticklabels(), rotation=0, ha="center", fontsize=9)
166
+ st.pyplot(fig3, use_container_width=True)
167
 
168
+ # Tables behind expanders to keep page short
169
+ with st.expander("Filtered chats (first 100)", expanded=False):
170
+ st.dataframe(df.head(100), use_container_width=True, height=320)
171
 
172
  def render_mis_user(conn, user_id: int):
173
  st.title("πŸ“Š My MIS")