Spaces:
Sleeping
Sleeping
Update src/streamlit_app.py
Browse files6 unmodified lines78910111213141516171819202122232425263 unmodified lines303132333435363738392 unmodified lines42434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596976 unmodified lines1041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721736 unmodified lines"""import os# import json# import base64# from datetime import datetimefrom 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)import streamlit as stimport pandas as pdimport altair as alt# import easyocrfrom parser.parsing import parse_log_filefrom gametracker.grab_gt_stats import fetch_playtimes3 unmodified linesst.title("๐ DS Gaming - CS 1.6 Admin Dashboard")# Optional: Streamlit config path to avoid permission issuesos.environ["STREAMLIT_CONFIG_DIR"] = "/tmp/.streamlit"uploaded_file = st.file_uploader("Upload your Counter-Strike log file", type=["log", "txt"])# --- Globals -----------------------------------------------------------------DATA_DIR = Path(__file__).resolve().parent / "data"2 unmodified lines# --- Start Analysis ----------------------------------------------------------if uploaded_file is not None and st.button("Analyze"):filename = f"weekly_stats_{uploaded_file.name.replace('.log','')}.json"# --- Parsing Logs ----------------------------------------------------log_content = uploaded_file.read().decode("utf-8", errors="ignore")admin_actions = parse_log_file(log_content)# --- GameTracker Section ---------------------------------------------st.subheader("๐ฎ GameTracker Playtime")with st.spinner("โณ Fetching GameTracker Data..."):gt_results = fetch_playtimes(ADMIN_FILE)# gt_results = fetch_playtimes(ADMIN_FILE)# --- 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 0col1, 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)# --- Leaderboard ------------------------------------------------------st.subheader("๐ Leaderboard (Minutes Played)")if gt_results:leaderboard = pd.DataFrame({6 unmodified lineselse:st.info("No GameTracker results found.")# --- Admin Actions Table ---------------------------------------------# Build admin actions tabledf_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 columnsdf_actions["Total"] = df_actions.drop(columns="Admin").sum(axis=1, numeric_only=True)# Display tablest.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 actionsunique_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 Chartchart = 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.")6 unmodified lines7891011121314151617181920212223243 unmodified lines282930313233342 unmodified lines373839404142434445464748495051525354556 unmodified lines62636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921936 unmodified lines"""import osfrom 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 issuesos.environ["STREAMLIT_CONFIG_DIR"] = "/tmp/.streamlit"import streamlit as stimport pandas as pdimport altair as altfrom parser.parsing import parse_log_filefrom gametracker.grab_gt_stats import fetch_playtimes3 unmodified linesst.title("๐ DS Gaming - CS 1.6 Admin Dashboard")uploaded_file = st.file_uploader("Upload a server log file (*.log) or an **admins.txt** file containing the admin names, with one name per line.", type=["log", "txt"])# --- Globals -----------------------------------------------------------------DATA_DIR = Path(__file__).resolve().parent / "data"2 unmodified lines# --- Start Analysis ----------------------------------------------------------if uploaded_file is not None and st.button("Analyze"):# --- CASE 1: Admin list (.txt) uploaded ---if uploaded_file.name.endswith(".txt"):# --- Grab Admin Names from File ------------------------------------------content = uploaded_file.getvalue().decode("utf-8")admins = [line.strip() for line in content.splitlines() if line.strip()]# --- GameTracker Section -------------------------------------------------st.subheader("๐ฎ GameTracker Playtime")with st.spinner("โณ Fetching GameTracker Data..."):gt_results = fetch_playtimes(admins)# gt_results = fetch_playtimes(ADMIN_FILE)# --- Leaderboard ---------------------------------------------------------st.subheader("๐ Leaderboard (Minutes Played)")if gt_results:leaderboard = pd.DataFrame({6 unmodified lineselse:st.info("No GameTracker results found.")# --- CASE 2: Log file (.log) uploaded ---elif uploaded_file.name.endswith(".log"):# --- Parsing Logs ----------------------------------------------------log_content = uploaded_file.read().decode("utf-8", errors="ignore")admin_actions = parse_log_file(log_content)# --- GameTracker Section ---------------------------------------------st.subheader("๐ฎ GameTracker Playtime")with st.spinner("โณ Fetching GameTracker Data..."):gt_results = fetch_playtimes(ADMIN_FILE)# gt_results = fetch_playtimes(ADMIN_FILE)# --- 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 0col1, 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)# --- 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.")# --- Admin Actions Table ---------------------------------------------# Build admin actions tabledf_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 columnsdf_actions["Total"] = df_actions.drop(columns="Admin").sum(axis=1, numeric_only=True)# Display tablest.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 actionsunique_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 Chartchart = 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.")
src/streamlit_app.py+145-125