22.10.2025

This commit is contained in:
2025-10-22 12:34:34 +03:00
parent ac4bab26a0
commit aa62821e5f
101 changed files with 689103 additions and 281486 deletions

322
visual.py
View File

@@ -181,7 +181,31 @@ def process_player_data(team_json, player_index):
"time": str(player_data["CareerTPlayedTime"]),
}
return [season_total, season_avg, career_total], player_data
career_avg = {
"name": "Career Average",
"game_count": "",
"start_count": "",
"pts": str(player_data["AvgCarPoints"]),
"pt-2": str(player_data["CareerTShot2Percent"]),
"pt-3": str(player_data["CareerTShot3Percent"]),
"pt-1": str(player_data["CareerTShot1Percent"]),
"fg": str(player_data["CareerTShot23Percent"]),
"ast": str(player_data["AvgCarAssist"]),
"stl": str(player_data["AvgCarSteal"]),
"blk": str(player_data["AvgCarBlocks"]),
"dreb": str(player_data["AvgCarDefRebound"]),
"oreb": str(player_data["AvgCarOffRebound"]),
"reb": str(player_data["AvgCarRebound"]),
# "to": str(player_data["AvgTurnover"]),
# "foul": str(player_data["AvgFoul"]),
"fouled": str(player_data["AvgCarOpponentFoul"]),
"dunk": str(player_data["AvgCarDunk"]),
"time": str(player_data["AvgCarPlayedTime"]),
}
return [season_total, season_avg, career_total, career_avg], player_data
config = {
@@ -190,24 +214,24 @@ config = {
"num": st.column_config.TextColumn("#", width=27),
"NameGFX": st.column_config.TextColumn(width=170),
"isOn": st.column_config.TextColumn("🏀", width=27),
"pts": st.column_config.NumberColumn("PTS", width=27),
"pt-2": st.column_config.TextColumn("2-PT", width=45),
"pt-3": st.column_config.TextColumn("3-PT", width=45),
"pt-1": st.column_config.TextColumn("FT", width=45),
"fg": st.column_config.TextColumn("FG", width=45),
"ast": st.column_config.NumberColumn("AS", width=27),
"stl": st.column_config.NumberColumn("ST", width=27),
"blk": st.column_config.NumberColumn("BL", width=27),
"blkVic": st.column_config.NumberColumn("BV", width=27),
"dreb": st.column_config.NumberColumn("DR", width=27),
"oreb": st.column_config.NumberColumn("OR", width=27),
"reb": st.column_config.NumberColumn("R", width=27),
"to": st.column_config.NumberColumn("TO", width=27),
"foul": st.column_config.NumberColumn("F", width=27),
"fouled": st.column_config.NumberColumn("Fed", width=27),
"plusMinus": st.column_config.NumberColumn("+/-", width=27),
"dunk": st.column_config.NumberColumn("DUNK", width=27),
"kpi": st.column_config.NumberColumn("KPI", width=27),
"pts": st.column_config.TextColumn("PTS", width="content", help="⭐ = Career High"),
"pt-2": st.column_config.TextColumn("2-PT", width="content"),
"pt-3": st.column_config.TextColumn("3-PT", width="content"),
"pt-1": st.column_config.TextColumn("FT", width="content"),
"fg": st.column_config.TextColumn("FG", width="content"),
"ast": st.column_config.TextColumn("AS", width="content"),
"stl": st.column_config.TextColumn("ST", width="content"),
"blk": st.column_config.TextColumn("BL", width="content"),
"blkVic": st.column_config.TextColumn("BV", width="content"),
"dreb": st.column_config.TextColumn("DR", width="content"),
"oreb": st.column_config.TextColumn("OR", width="content"),
"reb": st.column_config.TextColumn("R", width="content"),
"to": st.column_config.TextColumn("TO", width="content"),
"foul": st.column_config.TextColumn("F", width="content"),
"fouled": st.column_config.TextColumn("Fed", width="content"),
"plusMinus": st.column_config.TextColumn("+/-", width="content"),
"dunk": st.column_config.TextColumn("DUNK", width="content"),
"kpi": st.column_config.TextColumn("KPI", width="content"),
"time": st.column_config.TextColumn("TIME"),
"game_count": st.column_config.TextColumn("G", width=27),
"start_count": st.column_config.TextColumn("S", width=27),
@@ -813,19 +837,127 @@ columns_game = [
if cached_team1 and cached_team2:
team1_data = process_team_data(cached_team1, columns_game)
team2_data = process_team_data(cached_team2, columns_game)
# Добавляем звездочку, если pts > PTS_Career_High
def _get_first_number(x):
"""Безопасно вытащить число из строки/значения (например '12 (60%)' -> 12)."""
try:
if x is None:
return None
s = str(x)
# заберём ведущие число/знак (поддержим +/-)
import re
m = re.search(r"[-+]?\d+(\.\d+)?", s)
return float(m.group(0)) if m else None
except Exception:
return None
CAREER_HIGH_KEYS = {
"pts": ["PTS_Career_High", "CareerHighPoints", "career_high_pts"],
"ast": ["AST_Career_High", "CareerHighAssist", "career_high_ast"],
"stl": ["STL_Career_High", "CareerHighSteal", "career_high_stl"],
"blk": ["BLK_Career_High", "CareerHighBlocks", "career_high_blk"],
"reb": ["REB_Career_High", "CareerHighRebound", "career_high_reb"],
# если нужно — добавь ещё пары "df_column": ["possible_key1","possible_key2"...]
}
def _build_career_high_map(cached_team_list):
"""Вернёт словарь: player_id -> {stat_key: value} для всех доступных максимумов."""
out = {}
if not isinstance(cached_team_list, list):
return out
for p in cached_team_list:
if not isinstance(p, dict):
continue
pid = p.get("id")
if pid is None:
continue
out[pid] = {}
for stat_col, aliases in CAREER_HIGH_KEYS.items():
for k in aliases:
if k in p and p[k] not in (None, ""):
out[pid][stat_col] = _get_first_number(p[k])
break
return out
def _ensure_id_column(df, cached_team_list):
"""Присвоить игрокам id в том же порядке, что и в списке cached_team."""
try:
ids = [p.get("id") if isinstance(p, dict) else None for p in cached_team_list][:len(df)]
if "id" not in df.columns:
df["id"] = ids
else:
# не затираем, только заполняем пустые
df["id"] = df["id"].fillna(pd.Series(ids, index=df.index))
except Exception:
pass
def _mark_star_for_columns(df, cached_team_list, columns):
"""
Для каждого col в columns: если текущее значение > career high — добавляем ' ⭐️'.
Преобразуем колонки в текст (для отображения эмодзи).
"""
_ensure_id_column(df, cached_team_list)
ch_map = _build_career_high_map(cached_team_list)
def format_with_star(val, career_max):
v = _get_first_number(val)
cm = _get_first_number(career_max)
if v is not None and cm is not None and v >= cm and val > 0:
# сохраняем исходное текстовое представление + ⭐️
return f"{val} ⭐️"
return f"{val}" if val is not None else ""
for col in columns:
if col not in df.columns:
continue
new_vals = []
for idx, row in df.iterrows():
pid = row.get("id")
career_max = (ch_map.get(pid, {}) or {}).get(col)
new_vals.append(format_with_star(row[col], career_max))
df[col] = new_vals # теперь это текст для отображения
STAR_COLUMNS = [
"pts", "ast", "stl", "blk", "reb",
]
team1_data["_pts_num"] = pd.to_numeric(team1_data["pts"], errors="coerce")
team1_data["_kpi_num"] = pd.to_numeric(team1_data["kpi"], errors="coerce")
team2_data["_pts_num"] = pd.to_numeric(team2_data["pts"], errors="coerce")
team2_data["_kpi_num"] = pd.to_numeric(team2_data["kpi"], errors="coerce")
def highlight_max_by_refcol(df, view_col, ref_col):
ref = pd.to_numeric(df[ref_col], errors="coerce")
mx = ref.max()
return [("background-color: green" if (pd.notna(v) and v == mx and v > 0) else "")
for v in ref]
_mark_star_for_columns(team1_data, cached_team1, STAR_COLUMNS)
_mark_star_for_columns(team2_data, cached_team2, STAR_COLUMNS)
# Стилизация данных
# team1_styled = (
# team1_data.style.apply(highlight_grey, axis=1)
# .apply(highlight_foul, subset="foul")
# .apply(highlight_max, subset="pts")
# .apply(highlight_max, subset="kpi")
# )
# team2_styled = (
# team2_data.style.apply(highlight_grey, axis=1)
# .apply(highlight_foul, subset="foul")
# .apply(highlight_max, subset="pts")
# .apply(highlight_max, subset="kpi")
# )
team1_styled = (
team1_data.style.apply(highlight_grey, axis=1)
.apply(highlight_foul, subset="foul")
.apply(highlight_max, subset="pts")
.apply(highlight_max, subset="kpi")
team1_data[columns_game].style
.apply(highlight_grey, axis=1)
.apply(highlight_foul, subset="foul")
.apply(lambda _: highlight_max_by_refcol(team1_data, "pts", "_pts_num"), axis=0, subset=["pts"])
.apply(lambda _: highlight_max_by_refcol(team1_data, "kpi", "_kpi_num"), axis=0, subset=["kpi"])
)
team2_styled = (
team2_data.style.apply(highlight_grey, axis=1)
team2_data[columns_game].style
.apply(highlight_grey, axis=1)
.apply(highlight_foul, subset="foul")
.apply(highlight_max, subset="pts")
.apply(highlight_max, subset="kpi")
.apply(lambda _: highlight_max_by_refcol(team2_data, "pts", "_pts_num"), axis=0, subset=["pts"])
.apply(lambda _: highlight_max_by_refcol(team2_data, "kpi", "_kpi_num"), axis=0, subset=["kpi"])
)
def get_player_all_game(player_data_1):
@@ -863,29 +995,28 @@ if cached_team1 and cached_team2:
# Сортировка от последнего матча к первому
df_filtered = df_filtered.sort_values(by="game.gameDate", ascending=False)
# Указать нужные колонки для вывода
columns_to_show = [
"season",
"game.gameDate",
"game.team1Name",
"game.team2Name",
"game.score",
"stats.points",
"stats.shot2Percent",
"stats.shot3Percent",
"stats.shot23Percent",
"stats.shot1Percent",
"stats.assist",
"stats.steal",
"stats.blockShot",
"stats.defRebound",
"stats.offRebound",
"stats.rebound",
"stats.turnover",
"stats.foul",
"stats.playedTime",
"stats.plusMinus",
"Сезон",
"Дата",
"Команда 1",
"Команда 2",
"Счёт",
"PTS",
"2-PTS%",
"3-PTS%",
"FG%",
"FT%",
"AST",
"STL",
"BLK",
"DR",
"OR",
"REB",
"TO",
"F",
"TIME",
"+/-",
]
numeric_cols = [
"stats.points",
@@ -897,24 +1028,63 @@ if cached_team1 and cached_team2:
# df_filtered[numeric_cols] = df_filtered[numeric_cols].apply(
# pd.to_numeric, errors="coerce"
# )
df_filtered[numeric_cols] = df_filtered[numeric_cols].apply(pd.to_numeric, errors="coerce")
# 🟢 Переименовываем колонки для отображения в Streamlit
rename_map = {
"season": "Сезон",
"game.gameDate": "Дата",
"game.team1Name": "Команда 1",
"game.team2Name": "Команда 2",
"game.score": "Счёт",
"stats.points": "PTS",
"stats.shot2Percent": "2-PTS%",
"stats.shot3Percent": "3-PTS%",
"stats.shot23Percent": "FG%",
"stats.shot1Percent": "FT%",
"stats.assist": "AST",
"stats.steal": "STL",
"stats.blockShot": "BLK",
"stats.defRebound": "DR",
"stats.offRebound": "OR",
"stats.rebound": "REB",
"stats.turnover": "TO",
"stats.foul": "F",
"stats.playedTime": "TIME",
"stats.plusMinus": "+/-",
}
df_filtered[numeric_cols] = df_filtered[numeric_cols].apply(
pd.to_numeric, errors="coerce"
)
df_filtered[numeric_cols] = df_filtered[numeric_cols].round(0).astype("Int64")
df_filtered = df_filtered.rename(columns=rename_map)
df_filtered["Дата"] = df_filtered["Дата"].dt.strftime("%d.%m.%Y")
styled = (
df_filtered[columns_to_show]
.style
.apply(highlight_max, subset=["stats.points"])
.apply(highlight_max, subset=["stats.assist"])
.apply(highlight_max, subset=["stats.steal"])
.apply(highlight_max, subset=["stats.blockShot"])
.apply(highlight_max, subset=["stats.rebound"])
.style.apply(highlight_max, subset=["PTS"])
.apply(highlight_max, subset=["AST"])
.apply(highlight_max, subset=["STL"])
.apply(highlight_max, subset=["BLK"])
.apply(highlight_max, subset=["REB"])
.format(
{
"Дата": lambda x: x, # уже строка, просто оставляем как есть
"PTS": "{:,.0f}".format,
"AST": "{:,.0f}".format,
"STL": "{:,.0f}".format,
"BLK": "{:,.0f}".format,
"REB": "{:,.0f}".format,
}
)
)
return styled
# Вывод данных
col_player1, col_player2 = tab_temp_1.columns((5, 5))
config_copy = config.copy()
event1 = col_player1.dataframe(
team1_styled,
column_config=config,
column_config=config_copy,
hide_index=True,
height=460,
on_select="rerun",
@@ -960,7 +1130,8 @@ if cached_team1 and cached_team2:
hide_index=True,
)
col_player1.dataframe(get_player_all_game(player_data_1))
col_player1.title("Статистика каждой игры")
col_player1.dataframe(get_player_all_game(player_data_1), hide_index=True)
if event2.selection and event2.selection.get("rows"):
selected_index2 = event2.selection["rows"][0]
@@ -988,7 +1159,8 @@ if cached_team1 and cached_team2:
column_config=config_season,
hide_index=True,
)
col_player2.dataframe(get_player_all_game(player_data_2))
col_player2.title("Статистика каждой игры")
col_player2.dataframe(get_player_all_game(player_data_2), hide_index=True)
team_col1, team_col2 = tab_temp_2.columns((5, 5))
if isinstance(cached_team_stats, list) and len(cached_team_stats) >= 34:
@@ -1085,12 +1257,31 @@ if cached_standings:
pass
return [""] * len(s)
styled = df_st.style.apply(highlight_teams, axis=1)
styled = df_st[
[
"teamId",
"start",
"place",
"name",
"regionName",
"totalGames",
"totalWin",
"totalDefeat",
"totalPoints",
"totalGoalPlus",
"totalGoalMinus",
"logo",
"w_l",
"procent",
"plus_minus",
]
].style.apply(highlight_teams, axis=1)
tab_temp_4.dataframe(
styled,
column_config={"logo": st.column_config.ImageColumn("logo")},
hide_index=True,
height=610,
width="content"
)
@@ -1534,23 +1725,22 @@ with tab_online:
live_data_map = {}
# Собираем live-данные по каждому game.id
for _, row in df_filtered.iterrows():
game_id = row["game.id"]
try:
json_data = requests.get(
f"https://pro.russiabasket.org/api/abc/games/live-status?Id={game_id}&Lang=en",
f"https://vtb-league.org/api/abc/games/live-status?Id={game_id}&Lang=en",
).json()
except Exception as ex:
# json_data = {
# "period": None,
# "timeToGo": 0.0,
# }
print(ex)
# Берём содержимое result (словарь с gameId и данными)
result = json_data.get("result", {})
if result and "gameId" in result:
live_data_map[result["gameId"]] = result
if json_data:
result = json_data.get("result", {})
if result and "gameId" in result:
live_data_map[result["gameId"]] = result
# Создаём колонки для live-данных
df_filtered["live_period"] = None