File size: 8,263 Bytes
4b62d23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
"""
Admin Analytics Dashboard (Streamlit)
Optional admin view for monitoring system metrics.
"""

import streamlit as st
import requests
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime, timedelta
import os


def check_admin_auth():
    """Check if admin is authenticated."""
    if "admin_token" not in st.session_state:
        st.session_state.admin_token = None
    
    if not st.session_state.admin_token:
        st.warning("⚠️ Please enter admin token to access analytics")
        token = st.text_input("Admin Token", type="password", key="token_input")
        if st.button("Login"):
            st.session_state.admin_token = token
            st.rerun()
        return False
    
    return True


def get_admin_headers():
    """Get authorization headers for admin endpoints."""
    return {
        "Authorization": f"Bearer {st.session_state.admin_token}"
    }


def fetch_metrics_summary(api_url: str):
    """Fetch metrics summary from admin endpoint."""
    try:
        response = requests.get(
            f"{api_url}/admin/metrics/summary",
            headers=get_admin_headers(),
            timeout=10
        )
        
        if response.status_code == 401:
            st.error("❌ Invalid admin token. Please check and try again.")
            st.session_state.admin_token = None
            return None
        
        response.raise_for_status()
        return response.json()["data"]
    
    except Exception as e:
        st.error(f"Failed to fetch summary: {str(e)}")
        return None


def fetch_events_timeline(api_url: str, days: int = 7):
    """Fetch events timeline."""
    try:
        response = requests.get(
            f"{api_url}/admin/metrics/events?days={days}",
            headers=get_admin_headers(),
            timeout=10
        )
        response.raise_for_status()
        return response.json()["data"]
    
    except Exception as e:
        st.error(f"Failed to fetch timeline: {str(e)}")
        return None


def fetch_funnel_analysis(api_url: str, days: int = 7):
    """Fetch funnel analysis."""
    try:
        response = requests.get(
            f"{api_url}/admin/metrics/funnel?days={days}",
            headers=get_admin_headers(),
            timeout=10
        )
        response.raise_for_status()
        return response.json()["data"]
    
    except Exception as e:
        st.error(f"Failed to fetch funnel: {str(e)}")
        return None


def fetch_rate_limit_stats(api_url: str, days: int = 7):
    """Fetch rate limit statistics."""
    try:
        response = requests.get(
            f"{api_url}/admin/metrics/rate-limits?days={days}",
            headers=get_admin_headers(),
            timeout=10
        )
        response.raise_for_status()
        return response.json()["data"]
    
    except Exception as e:
        st.error(f"Failed to fetch rate limit stats: {str(e)}")
        return None


def render_admin_dashboard():
    """Render admin analytics dashboard."""
    st.title("πŸ”’ Admin Analytics Dashboard")
    
    # Check authentication
    if not check_admin_auth():
        return
    
    # Logout button
    if st.button("Logout"):
        st.session_state.admin_token = None
        st.rerun()
    
    # API URL configuration
    api_url = st.sidebar.text_input(
        "API URL",
        value=os.getenv("API_URL", "http://localhost:7860"),
        help="FastAPI backend URL"
    )
    
    # Time range selector
    days = st.sidebar.slider(
        "Days to analyze",
        min_value=1,
        max_value=30,
        value=7,
        help="Number of days to include in analysis"
    )
    
    # Refresh button
    if st.sidebar.button("πŸ”„ Refresh Data"):
        st.rerun()
    
    st.divider()
    
    # === METRICS SUMMARY ===
    st.header("πŸ“Š Metrics Summary")
    
    summary = fetch_metrics_summary(api_url)
    
    if summary:
        col1, col2, col3 = st.columns(3)
        
        with col1:
            st.metric("Unique Devices", summary["unique_devices"])
        
        with col2:
            st.metric("Unique Users", summary["unique_users"])
        
        with col3:
            total_events = sum(summary["events_by_type"].values())
            st.metric("Total Events", total_events)
        
        # Events by type
        st.subheader("Events by Type")
        
        events_df = pd.DataFrame([
            {"Event Type": k, "Count": v}
            for k, v in summary["events_by_type"].items()
        ])
        
        if not events_df.empty:
            fig = px.bar(
                events_df,
                x="Event Type",
                y="Count",
                color="Event Type",
                title="Event Distribution"
            )
            st.plotly_chart(fig, use_container_width=True)
    
    st.divider()
    
    # === EVENTS TIMELINE ===
    st.header("πŸ“ˆ Events Timeline")
    
    timeline_data = fetch_events_timeline(api_url, days)
    
    if timeline_data and timeline_data["timeline"]:
        timeline_df = pd.DataFrame(timeline_data["timeline"])
        
        fig = px.line(
            timeline_df,
            x="date",
            y="count",
            color="event_type",
            title=f"Events Over Last {days} Days",
            labels={"count": "Event Count", "date": "Date", "event_type": "Event Type"}
        )
        st.plotly_chart(fig, use_container_width=True)
    else:
        st.info("No timeline data available")
    
    st.divider()
    
    # === FUNNEL ANALYSIS ===
    st.header("πŸ”€ Conversion Funnel")
    
    funnel_data = fetch_funnel_analysis(api_url, days)
    
    if funnel_data:
        stages = funnel_data["funnel_stages"]
        conversions = funnel_data["conversion_rates"]
        
        # Funnel chart
        funnel_stages = ["DASHBOARD_VIEW", "ANALYSIS_REQUEST", "TASK_QUEUED", "TASK_COMPLETED"]
        funnel_values = [stages.get(stage, 0) for stage in funnel_stages]
        
        fig = go.Figure(go.Funnel(
            y=funnel_stages,
            x=funnel_values,
            textinfo="value+percent initial"
        ))
        
        fig.update_layout(title=f"User Journey Funnel (Last {days} Days)")
        st.plotly_chart(fig, use_container_width=True)
        
        # Conversion metrics
        st.subheader("Conversion Rates")
        
        col1, col2 = st.columns(2)
        
        with col1:
            st.metric("View β†’ Request", f"{conversions['view_to_request']:.1f}%")
            st.metric("Request β†’ Queued", f"{conversions['request_to_queued']:.1f}%")
        
        with col2:
            st.metric("Queued β†’ Completed", f"{conversions['queued_to_completed']:.1f}%")
            st.metric("Overall Completion", f"{conversions['overall_completion']:.1f}%")
    
    st.divider()
    
    # === RATE LIMIT STATS ===
    st.header("🚦 Rate Limiting Statistics")
    
    rate_limit_data = fetch_rate_limit_stats(api_url, days)
    
    if rate_limit_data:
        col1, col2 = st.columns(2)
        
        with col1:
            st.metric("Total Rate Limit Hits", rate_limit_data["total_hits"])
        
        with col2:
            top_devices = len(rate_limit_data["top_devices"])
            st.metric("Unique Devices Hit", top_devices)
        
        # Top offenders
        if rate_limit_data["top_devices"]:
            st.subheader("Top Rate Limited Devices")
            
            devices_df = pd.DataFrame(rate_limit_data["top_devices"])
            st.dataframe(devices_df, use_container_width=True)
        
        # Timeline
        if rate_limit_data["timeline"]:
            st.subheader("Rate Limit Hits Over Time")
            
            timeline_df = pd.DataFrame(rate_limit_data["timeline"])
            
            fig = px.bar(
                timeline_df,
                x="date",
                y="count",
                title="Daily Rate Limit Hits",
                labels={"count": "Hits", "date": "Date"}
            )
            st.plotly_chart(fig, use_container_width=True)


if __name__ == "__main__":
    st.set_page_config(
        page_title="Admin Analytics",
        page_icon="πŸ”’",
        layout="wide"
    )
    
    render_admin_dashboard()