Py.Cafe

nilolom565/

rc-streamlit

DocsPricing
  • app.py
  • requirements.txt
app.py
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
import streamlit as st
import pandas as pd
from st_aggrid import AgGrid, GridOptionsBuilder, GridUpdateMode

# ✅ Must be first Streamlit command
st.set_page_config(page_title="Player History", layout="wide")

# Load and cache match data
@st.cache_data
def load_match_data():
    url = "https://www.ratingscentral.com/MatchList.php?CSV_Output=Text&PlayerID=142510"
    df = pd.read_csv(url)
    df = df.drop(df.columns[[0, 5, 7, 8, 11]], axis=1)
    df = df.sort_values(by=df.columns[0], ascending=False)

    history_wl = (
        df.groupby(df.columns[1])[df.columns[4]].value_counts().unstack(fill_value=0)
    )
    history_wl["W/L"] = history_wl.apply(
        lambda row: f"{row.get('W', 0)} / {row.get('L', 0)}", axis=1
    )

    df = df.merge(history_wl[["W/L"]], left_on=df.columns[1], right_index=True)

    df.columns = [
        "EventDate", "OpponentID", "OpponentName",
        "OpponentMean", "WonLost", "Score", "PlayerMean", "W/L"
    ]
    return df

@st.cache_data
def load_player_info():
    url = "https://www.ratingscentral.com/PlayerList.php?PlayerID=142510&PlayerSport=Any&SortOrder=Name&CSV_Output=Text"
    playerdf = pd.read_csv(url)
    info = playerdf.iloc[0]
    return {
        "rating": info["Rating"],
        "stdev": info["StDev"],
        "last_played": info["LastPlayed"],
        "last_event": info["LastEvent"],
    }

# Load data
player = load_player_info()
df = load_match_data()

# Show player info
st.markdown(
    f"Rating: {player['rating']} ± {player['stdev']} "
    f"[Last Played: {player['last_played']}]"
    f"(https://www.ratingscentral.com/EventDetail.php?EventID={player['last_event']}#P142510)"
)

# Columns to show in the grid
show_cols = ["EventDate", "OpponentID", "OpponentName", "OpponentMean", "WonLost", "Score", "W/L"]

# Initialize GridOptionsBuilder
gb = GridOptionsBuilder.from_dataframe(df[show_cols])

# Add configuration for hiding the 'OpponentID' column (keep it in the data)
gb.configure_column("OpponentID", hide=True)  # This hides the column

# Other configurations (pagination, grid settings)
gb.configure_selection("single", use_checkbox=False)
gb.configure_grid_options(domLayout="autoHeight")
gb.configure_pagination(paginationAutoPageSize=False, paginationPageSize=7)
gb.configure_default_column(resizable=True, width=120)

grid_options = gb.build()

grid_response = AgGrid(
    df[show_cols],
    gridOptions=grid_options,
    update_mode=GridUpdateMode.SELECTION_CHANGED,
    fit_columns_on_grid_load=True,
    theme="streamlit",
)

# Process selection logic
selected = grid_response["selected_rows"]

if isinstance(selected, pd.DataFrame) and not selected.empty:
    sel = selected.iloc[0].to_dict()
elif isinstance(selected, list) and len(selected) > 0:
    sel = selected[0]
else:
    st.info("Click a row above to see match details.")
    st.stop()

# Show match details for all previous records with the same Opponent ID
st.markdown("### Match Details")

row_df = df[df["OpponentID"] == sel["OpponentID"]]  # Show all matches against this Opponent

st.code(row_df.to_string(index=False))

if not row_df.empty:
    opp_id = sel["OpponentID"]
    opp_name = sel["OpponentName"]
    st.markdown(f"[View {opp_name}'s profile](https://www.ratingscentral.com/PlayerHistory.php?PlayerID={opp_id})")
else:
    st.warning("No matching opponent found.")