Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940import altair as altimport numpy as npimport pandas as pdimport streamlit as st"""# 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).In the meantime, below is an example of what you can do with just a few lines of code:"""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 = indicesx = 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])),))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173#!/usr/bin/env python3# -*- coding: utf-8 -*-"""Created on Thu Sep 11 14:24:06 2025@authors: lundyc, smalacar"""# --- Standard Libraries ------------------------------------------------------import jsonimport base64from datetime import datetimefrom pathlib import Path# --- 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 / filenameif 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 0col1, 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 leaderboardleaderboard = leaderboard.sort_values("Minutes", ascending=False).reset_index(drop=True)leaderboard.insert(0, "Rank", range(1, len(leaderboard)+1))# Display leaderboardst.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ösungwith 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)print(chart_path.resolve())html += img_htmlHTML(string=html).write_pdf(weekly_dir / "weekly_report.pdf")
src/streamlit_app.py+168-35