Spaces:
Sleeping

admin_dashboard / src /streamlit_app.py
smalacar's picture
Update src/streamlit_app.py
8276f3a verified
Raw History Blame Contribute Delete
9.84 kB
#!/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.")