Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files1234123456778910119101112131413141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716171819202122232425262728293031323334353637383940168169170171172173import altair as altimport numpy as npimport pandas as pdimport streamlit as st#!/usr/bin/env python3# -*- coding: utf-8 -*-"""Created on Thu Sep 11 14:24:06 2025
@authors: lundyc, smalacar"""# Welcome to Streamlit!
Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [communityforums](https://discuss.streamlit.io).# --- Standard Libraries ------------------------------------------------------import jsonimport base64from datetime import datetimefrom pathlib import Path
In the meantime, below is an example of what you can do with just a few lines of code:"""# --- External Libraries ------------------------------------------------------import streamlit as stimport pandas as pdimport altair as altimport easyocrfrom weasyprint import HTML
# --- Local Modules -----------------------------------------------------------from parser.parsing import parse_log_filefrom 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_file = st.file_uploader("Upload your Counter-Strike log file", type=["log", "txt"])
# --- Globals -----------------------------------------------------------------ADMIN_FILE = Path("data") / "admins.txt"
# --- Start Analysis ----------------------------------------------------------if uploaded_file is not None and st.button("Analyze"):
# --- Check if data already available ------------------------------------- weekly_dir = Path("data") / "weekly" weekly_dir.mkdir(parents=True, exist_ok=True) filename = f"weekly_stats_{uploaded_file.name.strip('.log')}.json" outfile = weekly_dir / filename
if not outfile.exists(): # --- Parsing Logs ---------------------------------------------------- log_content = uploaded_file.read().decode("utf-8", errors="ignore") admin_actions = parse_log_file(log_content)
# --- OCR/GameTracker Section ----------------------------------------- st.subheader("🎮 GameTracker Playtime") gt_results = fetch_playtimes(Path("data")/ "admins.txt")
# --- 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), "renamed": actions.get("renamed", 0), "transfers": actions.get("transfers", 0), "whitechat": actions.get("whitechat", 0), "message" : actions.get("message", list()) }
# --- Save as JSON in data/weekly ------------------------------------- with outfile.open("w", encoding="utf-8") as f: json.dump(combined_stats, f, indent=2, ensure_ascii=False) st.success(f"✅ Stats saved to {outfile}")
else: with outfile.open("r", encoding="utf-8") as f: existing_data = json.load(f) # --- Separate dictionaries -------------------------------------------- gt_results = {admin: data.get("minutes", 0) for admin, data in existing_data.items()}
admin_actions = { admin: { "slapped": data.get("slapped", 0), "kicked": data.get("kicked", 0), "banned": data.get("banned", 0), "renamed": data.get("renamed", 0), "transfers": data.get("transfers", 0), "whitechat": data.get("whitechat", 0), "message" : data.get("message", list()) } for admin, data in existing_data.items() } print("GT Results:", gt_results) print("Admin Actions:", admin_actions) st.success(f"✅ Stats read from {outfile}")
# --- 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_chats = sum(a["whitechat"] for a in admin_actions.values()) total_renamed = sum(a["renamed"] 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 = st.columns(6) col1.metric("⏱ Total Playtime", f"{total_playtime} min") col2.metric("👊 Slaps", total_slaps) col3.metric("🚫 Bans", total_bans) col4.metric("✏️ Renamed", total_renamed) col5.metric("🔄 Transfers", total_transfers) col6.metric("💬 Admin Chats", total_chats)
st.subheader("🏆 Leaderboard (Minutes Played)")
if gt_results: leaderboard = pd.DataFrame({ "Admin": list(gt_results.keys()), "Minutes": list(gt_results.values()) })
# Sort leaderboard leaderboard = leaderboard.sort_values("Minutes", ascending=False).reset_index(drop=True) leaderboard.insert(0, "Rank", range(1, len(leaderboard)+1)) # Display leaderboard st.dataframe(leaderboard.set_index(leaderboard.columns[0]), height=400, width=600) else: st.info("No GameTracker results found.")
# --- Admin Actions Chart --------------------------------------------- st.subheader("🛠️ Admin Actions") color_scale = alt.Scale( domain=["slapped", "kicked", "banned", "renamed", "transfers", "whitechat"], range=["#1E88E5", "#ff7f0e", "#d62728", "#2ca02c", "#9467bd", "#C0C0C0"] ) 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"})
df_melt = df_actions.melt(id_vars="Admin", var_name="Action", value_name="Count") chart = alt.Chart(df_melt).mark_bar().encode( x="Admin", y="Count", color=alt.Color("Action", scale=color_scale) ).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) else: st.warning("No admin actions found in this log file.")
# --- Generate PDF report ------------------------------------------------- chart_path = weekly_dir / "admin_actions_chart.png" chart.save(chart_path, scale_factor=2) # scale_factor für bessere Auflösung 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;">'
num_points = st.slider("Number of points in spiral", 1, 10000, 1100)num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
indices = np.linspace(0, 1, num_points)theta = 2 * np.pi * num_turns * indicesradius = indices
x = radius * np.cos(theta)y = radius * np.sin(theta)
df = pd.DataFrame({ "x": x, "y": y, "idx": indices, "rand": np.random.randn(num_points),})
st.altair_chart(alt.Chart(df, height=700, width=700) .mark_point(filled=True) .encode( x=alt.X("x", axis=None), y=alt.Y("y", axis=None), color=alt.Color("idx", legend=None, scale=alt.Scale()), size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])), )) today_str = datetime.now().strftime("%Y-%m-%d") html = f"<h1>DSGC Admin Report {today_str}</h1>" html += leaderboard.to_html(index=False) print(chart_path.resolve()) html += img_html HTML(string=html).write_pdf(weekly_dir / "weekly_report.pdf")src/streamlit_app.py+168-35