Spaces:
Sleeping

File size: 9,843 Bytes
290338a
 
 
 
834420c
290338a
834420c
 
525e0ce
 
 
 
 
 
 
592b743
 
6faec03
290338a
 
 
 
 
525e0ce
290338a
 
 
 
525e0ce
591aece
 
 
 
 
525e0ce
591aece
 
 
 
 
 
 
 
 
 
 
 
290338a
 
ae9ea98
591aece
290338a
 
591aece
290338a
591aece
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
290338a
592b743
591aece
592b743
591aece
592b743
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 11 14:24:06 2025

@authors: lundyc, smalacar
"""

import os
from pathlib import Path

# --- Fix Fontconfig Error ---------------------------------------------------
os.environ["FONTCONFIG_PATH"] = "/tmp/fonts"
os.environ["FC_CACHE_HOME"] = "/tmp/fonts"
os.makedirs("/tmp/fonts", exist_ok=True)
# Optional: Streamlit config path to avoid permission issues
os.environ["STREAMLIT_CONFIG_DIR"] = "/tmp/.streamlit"

import streamlit as st
import pandas as pd
import altair as alt

from parser.parsing import parse_log_file
from gametracker.grab_gt_stats import fetch_playtimes

# --- Setup Dashboard ---------------------------------------------------------
st.set_page_config(page_title="DS Gaming Dashboard", layout="wide")
st.title("๐Ÿ“Š DS Gaming - CS 1.6 Admin Dashboard")

# uploaded_files = st.file_uploader(
#     "Upload one or more server log files (*.log) or admin files (*.txt)",
#     type=["log", "txt"],
#     accept_multiple_files=True
# )

st.markdown(
    """
**Upload either a single admin file (`*.txt`) or a pair of files: a `*.log` and a `*.txt`.**

- If the text file is named **`admins.txt`**, data will be taken from the **DS GAMING PUBLIC SERVER**.
- If it is named **`admins_afk.txt`**, data will be taken from the **DS GAMING AFK SERVER**.
"""
)

uploaded_files = st.file_uploader("Upload your files", type=["log", "txt"],accept_multiple_files=True)

# uploaded_file = st.file_uploader("Upload a server log file (*.log) or an **admins_type.txt** file containing the admin names, with one name per line. The type can be either **public** or **afk**.", type=["log", "txt"])

# --- Globals -----------------------------------------------------------------
DATA_DIR = Path(__file__).resolve().parent / "data"
# ADMIN_FILE = DATA_DIR / "admins.txt"

# --- Start Analysis ----------------------------------------------------------
if uploaded_files is not None and st.button("Analyze"):

    # Filter files by type
    txt_files = [f for f in uploaded_files if f.name.lower().endswith(".txt")]
    log_files = [f for f in uploaded_files if f.name.lower().endswith(".log")]

    CASE = None
    # Check allowed combinations
    if len(uploaded_files) == 1 and len(txt_files) == 1:
        admin_file = txt_files[0]
        st.success(f"Admin file uploaded: {admin_file.name}")

    elif len(uploaded_files) == 2 and len(txt_files) == 1 and len(log_files) == 1:
        admin_file = txt_files[0]
        log_file = log_files[0]
        st.success(f"Files uploaded: Admin = {admin_file.name}, Log = {log_file.name}")
        CASE = "with log"

    else:
        st.error("โŒ Invalid upload. Please upload either a single *.txt or exactly one *.log and one *.txt file.")    

    # --- Grab Admin Names from File -------------------------------------- 
    content = admin_file.getvalue().decode("utf-8")
    admins = [line.strip() for line in content.splitlines() if line.strip()]

    # --- Check if AFK or PUBLIC ------------------------------------------
    if "afk" in admin_file.name: 
        server = "afk"
    else:
        server = "public"

    st.info(f"Grabbing data from DS GAMING {server.upper()} SERVER.")

    # --- GameTracker Section ---------------------------------------------
    st.subheader("๐ŸŽฎ GameTracker Playtime")
    with st.spinner("โณ Fetching GameTracker Data..."):
        gt_results = fetch_playtimes(admins, server)
    # gt_results = fetch_playtimes(ADMIN_FILE)

    # --- Leaderboard -----------------------------------------------------
    st.subheader("๐Ÿ† Leaderboard (Minutes Played)")
    if gt_results:
        leaderboard = pd.DataFrame({
            "Admin": list(gt_results.keys()),
            "Minutes": list(gt_results.values())
        })
        leaderboard = leaderboard.sort_values("Minutes", ascending=False).reset_index(drop=True)
        leaderboard.insert(0, "Rank", range(1, len(leaderboard)+1))
        st.dataframe(leaderboard.set_index("Rank"), height=400, width=600)
    else:
        st.info("No GameTracker results found.")

    # --- CASE 2: Log file (.log) uploaded ---
    if CASE == "with log":
        # --- Parsing Logs ----------------------------------------------------
        log_content = log_file.read().decode("utf-8", errors="ignore")
        admin_actions = parse_log_file(log_content)
    
    
        # --- Combine stats ---------------------------------------------------
        combined_stats = {}
        for admin, minutes in gt_results.items():
            actions = admin_actions.get(admin, {})
            combined_stats[admin] = {
                "minutes": minutes,
                "slapped": actions.get("slapped", 0),
                "kicked": actions.get("kicked", 0),
                "banned": actions.get("banned", 0),
                "slayed": actions.get("slayed", 0),
                "renamed": actions.get("renamed", 0),
                "transfers": actions.get("transfers", 0),
                "whitechat": actions.get("whitechat", 0),
                "message" : actions.get("message", list())
            }
    
        # --- Dashboard Cards -----------------------------------------------------
        if admin_actions:
            total_slaps = sum(a["slapped"] for a in admin_actions.values())
            total_bans = sum(a["banned"] for a in admin_actions.values())
            total_kicks = sum(a["kicked"] for a in admin_actions.values())
            total_chats = sum(a["whitechat"] for a in admin_actions.values())
            total_renamed = sum(a["renamed"] for a in admin_actions.values())
            total_slayed = sum(a["slayed"] for a in admin_actions.values())
            total_transfers = sum(a["transfers"] for a in admin_actions.values())
            total_playtime = sum(gt_results.values()) if gt_results else 0
    
            col1, col2, col3, col4, col5, col6, col7, col8 = st.columns(8)
            col1.metric("โฑ Total Playtime", f"{total_playtime} min")
            col2.metric("๐Ÿ‘Š Slaps", total_slaps)
            col3.metric("๐Ÿฅพ Kicks", total_kicks)
            col4.metric("๐Ÿšซ Bans", total_bans)
            col5.metric("๐Ÿ’€ Slays", total_slayed)
            col6.metric("โœ๏ธ Renamed", total_renamed)
            col7.metric("๐Ÿ”„ Transfers", total_transfers)
            col8.metric("๐Ÿ’ฌ Admin Chats", total_chats)
    
            # --- Admin Actions Table ---------------------------------------------
            # Build admin actions table
            df_actions = pd.DataFrame({
                admin: {k: v for k, v in actions.items() if k != "message"}
                for admin, actions in admin_actions.items()
            }).T.reset_index().rename(columns={"index": "Admin"})
            
            # Sort columns alphabetically (except Admin)
            cols = ["Admin"] + sorted([c for c in df_actions.columns if c != "Admin"])
            df_actions = df_actions[cols]
            
            # Add a "Total" column that sums all numeric action columns
            df_actions["Total"] = df_actions.drop(columns="Admin").sum(axis=1, numeric_only=True)
            
            # Display table
            st.subheader("๐Ÿ“‹ Admin Actions Table")
            st.dataframe(df_actions.set_index("Admin"), height=400, width=900)
    
            # --- Admin Actions Chart ---------------------------------------------
            st.subheader("๐Ÿ› ๏ธ Admin Actions")
            
            # Prepare data for Altair (exclude Total column)
            df_melt = df_actions.drop(columns="Total").melt(
                id_vars="Admin", var_name="Action", value_name="Count"
            )
            
            # Define colors with sorted actions 
            unique_actions = sorted(df_melt["Action"].unique())    
            color_scale = alt.Scale(
                domain=["slapped", "kicked", "banned", "renamed", "transfers", "whitechat", "slayed"],
                range=["#1E88E5", "#ff7f0e", "#d62728", "#2ca02c", "#9467bd", "#C0C0C0", "#660000"]
            )
    
            # Draw Chart
            chart = alt.Chart(df_melt).mark_bar().encode(
                x="Admin",
                y="Count",
                color=alt.Color("Action", scale=color_scale, sort="ascending")
            ).properties(height=600)
            st.altair_chart(chart, use_container_width=True)
    
            # --- Whitechat Messages ----------------------------------------------
            st.subheader("๐Ÿ’ฌ Whitechat Messages")
            with st.expander("Show Whitechat Messages", expanded=False):
                for admin, actions in admin_actions.items():
                    if "message" in actions:
                        messages_html = "<div style='font-size:12px; line-height:1.2em; margin-bottom:5px;'>"
                        for message in actions["message"]:
                            messages_html += f"<p><b>{admin}:</b> {message}</p>"
                        messages_html += "</div>"
                        st.markdown(messages_html, unsafe_allow_html=True)
    
            # --- Generate PDF report -------------------------------------------------
            # chart_path = WEEKLY_DIR / "admin_actions_chart.png"
            # chart.save(chart_path, scale_factor=2)
            # with chart_path.open("rb") as f:
            #     encoded = base64.b64encode(f.read()).decode("utf-8")
            # img_html = f'<img src="data:image/png;base64,{encoded}" style="width:600px;">'
    
            # today_str = datetime.now().strftime("%Y-%m-%d")
            # html = f"<h1>DSGC Admin Report {today_str}</h1>"
            # html += leaderboard.to_html(index=False)
            # html += img_html
            # HTML(string=html).write_pdf(WEEKLY_DIR / "weekly_report.pdf")
    
        else:
            st.warning("No admin actions found in this log file.")