Ilayr222 commited on
Commit
2de5071
·
verified ·
1 Parent(s): db9d69e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -183
app.py CHANGED
@@ -1,197 +1,67 @@
1
- import os, io, re, math
2
- import pandas as pd
3
- import numpy as np
4
- import gradio as gr
5
- import pycountry
6
-
7
- # === CONFIG ===
8
- DATA_FILE = "players.dataset.xlsx"
9
- BASE_POSITIONS = ["CB","RB","LB","CDM","CM","CAM","RW","ST","LW"]
10
-
11
- EXCLUDED_NATIONS = {
12
- "PALESTINE","STATE OF PALESTINE","PALESTINIAN TERRITORY","PALESTINIAN TERRITORIES","PSE","PS"
13
- }
14
-
15
- CANON = {
16
- "name": ["name","player","player_name"],
17
- "age": ["age"],
18
- "position": ["position","pos"],
19
- "nation": ["nation","nationality","country","citizenship"],
20
- "club": ["club","team","current_club"],
21
- "overall": ["overall","rating","ovr"],
22
- "potential": ["potential","pot"],
23
- "value": ["value","value_eur","market_value","market_value_eur"],
24
- "wage": ["wage","wage_eur","salary","salary_eur"],
25
- "height_cm": ["height","height_cm","cm_height"],
26
- "weight_kg": ["weight","weight_kg","kg_weight"],
27
- }
28
-
29
- def _canon_map(columns):
30
- cols = [str(c).strip() for c in columns]
31
- lower = [c.lower().strip() for c in cols]
32
- out = {}
33
- for std, variants in CANON.items():
34
- for v in variants:
35
- if v in lower:
36
- out[std] = cols[lower.index(v)]
37
- break
38
- return out
39
-
40
- def _to_number(x):
41
- if pd.isna(x): return np.nan
42
- s = re.sub(r"[^\d.\-]", "", str(x))
43
- try: return float(s)
44
- except: return np.nan
45
-
46
- def _to_full_country(n):
47
- if pd.isna(n): return None
48
- s = str(n).strip()
49
- candidate = None
50
- if len(s) <= 3:
51
- c = pycountry.countries.get(alpha_3=s.upper())
52
- if c: candidate = c.name
53
- if candidate is None:
54
- c = pycountry.countries.get(alpha_2=s.upper())
55
- if c: candidate = c.name
56
- if candidate is None:
57
- candidate = s
58
- norm = re.sub(r"\s+"," ", candidate).strip().upper()
59
- if norm in EXCLUDED_NATIONS:
60
- return None
61
- return candidate
62
-
63
- def load_df():
64
- if not os.path.exists(DATA_FILE):
65
- return pd.DataFrame(columns=[
66
- "Name","Age","Position","Nation","Club","Overall","Potential",
67
- "Height_cm","Weight_kg","Value","Wage"
68
- ])
69
- df = pd.read_excel(DATA_FILE, engine="openpyxl")
70
- df.columns = [str(c).strip() for c in df.columns]
71
- cmap = _canon_map(df.columns)
72
-
73
- out = pd.DataFrame()
74
- out["Name"] = df.get(cmap.get("name"), pd.Series(dtype=str)).astype(str).str.strip()
75
- out["Age"] = df.get(cmap.get("age"), pd.Series(dtype=object)).apply(_to_number)
76
- out["Position"] = df.get(cmap.get("position"), pd.Series(dtype=str)).astype(str).str.upper().str.strip()
77
- nat_raw = df.get(cmap.get("nation"), pd.Series(dtype=str))
78
- out["Nation"] = nat_raw.apply(_to_full_country) if nat_raw is not None else pd.Series(dtype=str)
79
-
80
- club = df.get(cmap.get("club"), pd.Series(dtype=str)).astype(str).str.strip()
81
- club = club.replace({"": pd.NA, "nan": pd.NA, "None": pd.NA})
82
- out["Club"] = club
83
-
84
- out["Overall"] = df.get(cmap.get("overall"), pd.Series(dtype=object)).apply(_to_number)
85
- out["Potential"] = df.get(cmap.get("potential"), pd.Series(dtype=object)).apply(_to_number)
86
- out["Value"] = df.get(cmap.get("value"), pd.Series(dtype=object)).apply(_to_number)
87
- out["Wage"] = df.get(cmap.get("wage"), pd.Series(dtype=object)).apply(_to_number)
88
- out["Height_cm"] = df.get(cmap.get("height_cm"), pd.Series(dtype=object)).apply(_to_number)
89
- out["Weight_kg"] = df.get(cmap.get("weight_kg"), pd.Series(dtype=object)).apply(_to_number)
90
-
91
- out = out[~out["Nation"].isna()].reset_index(drop=True)
92
- return out
93
-
94
- DF = load_df()
95
-
96
- def positions_list():
97
- vals = set(BASE_POSITIONS)
98
- if "Position" in DF.columns:
99
- vals |= set(str(x).upper().strip() for x in DF["Position"].dropna().unique())
100
- return sorted(vals)
101
-
102
- def nations_list():
103
- # Always list all countries (minus exclusions), not just those in the dataset
104
- all_names = []
105
- for c in pycountry.countries:
106
- nm = c.name
107
- if re.sub(r"\s+"," ", nm).upper() not in EXCLUDED_NATIONS:
108
- all_names.append(nm)
109
- return sorted(set(all_names))
110
-
111
- def clubs_list():
112
- if "Club" not in DF.columns: return []
113
- vals = [c for c in DF["Club"].dropna().unique().tolist() if str(c).strip()]
114
- return sorted(set(vals))
115
-
116
- def filter_players(positions, nations, clubs, min_overall, min_potential,
117
- max_age, min_h, max_h, min_w, max_w, max_val, max_wage, query):
118
- df = DF.copy()
119
- if positions: df = df[df["Position"].isin(positions)]
120
- if nations: df = df[df["Nation"].isin(nations)]
121
- if clubs: df = df[df["Club"].isin(clubs)]
122
- if not math.isnan(min_overall): df = df[df["Overall"] >= min_overall]
123
- if not math.isnan(min_potential): df = df[df["Potential"] >= min_potential]
124
- if not math.isnan(max_age): df = df[df["Age"] <= max_age]
125
- if not math.isnan(min_h): df = df[df["Height_cm"] >= min_h]
126
- if not math.isnan(max_h): df = df[df["Height_cm"] <= max_h]
127
- if not math.isnan(min_w): df = df[df["Weight_kg"] >= min_w]
128
- if not math.isnan(max_w): df = df[df["Weight_kg"] <= max_w]
129
- if not math.isnan(max_val): df = df[df["Value"] <= max_val]
130
- if not math.isnan(max_wage): df = df[df["Wage"] <= max_wage]
131
- if query:
132
- q = query.strip().lower()
133
- df = df[df.apply(lambda r: any(
134
- q in str(r.get(c, "")).lower()
135
- for c in ["Name","Club","Position","Nation"]
136
- ), axis=1)]
137
- cols = [c for c in ["Name","Age","Position","Nation","Club","Overall","Potential",
138
- "Height_cm","Weight_kg","Value","Wage"] if c in df.columns]
139
- return df[cols].reset_index(drop=True)
140
-
141
- def to_csv_bytes(df):
142
- buf = io.StringIO()
143
- df.to_csv(buf, index=False, encoding="utf-8")
144
- return buf.getvalue().encode("utf-8")
145
-
146
  # === UI ===
147
  THEME = gr.themes.Soft(primary_hue="blue")
148
  CSS = """
149
  #title { text-align:center; }
150
- .card { border-radius:16px; padding:14px; background:#fff; }
 
151
  .stat { font-weight:600; font-size:14px; }
152
  """
153
 
154
  with gr.Blocks(theme=THEME, css=CSS) as demo:
155
  gr.Markdown("<h1 id='title'>ProScout — Player Finder</h1>")
156
 
157
- # Filters in three columns, results wide on the right
158
  with gr.Row():
159
- # Column 1: positions + nations/clubs + free-text search at the end
160
- with gr.Column(scale=1, elem_classes="card"):
161
- pos = gr.CheckboxGroup(positions_list(), label="Positions", value=[], info="Pick one or more")
162
- nat = gr.Dropdown(nations_list(), multiselect=True, label="Nations", value=[], filterable=True)
163
- clu = gr.Dropdown(clubs_list(), multiselect=True, label="Clubs", value=[], filterable=True)
164
- query = gr.Textbox(label="Search", placeholder="e.g., Maccabi, Brazil, CAM")
165
-
166
- # Column 2: ratings & age
167
- with gr.Column(scale=1, elem_classes="card"):
168
- min_ovr = gr.Slider(0, 99, value=0, step=1, label="Min Overall")
169
- min_pot = gr.Slider(0, 99, value=0, step=1, label="Min Potential")
170
- max_age = gr.Slider(15, 45, value=45, step=1, label="Max Age")
171
-
172
- # Column 3: physical & financial
173
- with gr.Column(scale=1, elem_classes="card"):
174
- min_h = gr.Slider(140, 210, value=140, step=1, label="Min Height (cm)")
175
- max_h = gr.Slider(140, 210, value=210, step=1, label="Max Height (cm)")
176
- min_w = gr.Slider(45, 120, value=45, step=1, label="Min Weight (kg)")
177
- max_w = gr.Slider(45, 120, value=120, step=1, label="Max Weight (kg)")
178
- max_val = gr.Number(value=np.nan, label="Max Value (EUR)")
179
- max_wage = gr.Number(value=np.nan, label="Max Wage (EUR)")
180
-
181
- # Results panel (wide)
182
- with gr.Column(scale=2, elem_classes="card"):
183
- results = gr.Dataframe(row_count=(12,"dynamic"), wrap=True, interactive=False, label="Results")
184
- with gr.Row():
185
- count_box = gr.Markdown("", elem_classes="stat")
186
- avg_ovr_box = gr.Markdown("", elem_classes="stat")
187
- avg_age_box = gr.Markdown("", elem_classes="stat")
188
- dl = gr.DownloadButton("Download CSV")
189
-
190
- # Button full-width under filters/results
 
 
 
 
 
 
 
 
 
 
 
 
 
 
191
  with gr.Row():
192
- gr.Markdown("") # left spacer
193
- btn = gr.Button("Search", variant="primary")
194
- gr.Markdown("") # right spacer
195
 
196
  def _run(positions, nations, clubs, min_overall, min_potential,
197
  max_age, min_h, max_h, min_w, max_w, max_val, max_wage, query):
@@ -203,7 +73,6 @@ with gr.Blocks(theme=THEME, css=CSS) as demo:
203
  csv_bytes = to_csv_bytes(df)
204
  return df, f"**Players:** {count}", f"**Avg OVR:** {avg_ovr}", f"**Avg Age:** {avg_age}", csv_bytes
205
 
206
- # Load initial data automatically
207
  demo.load(
208
  _run,
209
  inputs=[pos,nat,clu,min_ovr,min_pot,max_age,min_h,max_h,min_w,max_w,max_val,max_wage,query],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # === UI ===
2
  THEME = gr.themes.Soft(primary_hue="blue")
3
  CSS = """
4
  #title { text-align:center; }
5
+ .bubble { background:#fff; border-radius:16px; padding:12px; box-shadow:0 2px 10px rgba(0,0,0,.06); }
6
+ .grid { gap:12px; }
7
  .stat { font-weight:600; font-size:14px; }
8
  """
9
 
10
  with gr.Blocks(theme=THEME, css=CSS) as demo:
11
  gr.Markdown("<h1 id='title'>ProScout — Player Finder</h1>")
12
 
13
+ # Filters area: 3 columns, EACH control in its own "bubble"
14
  with gr.Row():
15
+ # Column 1
16
+ with gr.Column(scale=1, elem_classes="grid"):
17
+ with gr.Group(elem_classes="bubble"):
18
+ pos = gr.CheckboxGroup(positions_list(), label="Positions", value=[], info="Pick one or more")
19
+ with gr.Group(elem_classes="bubble"):
20
+ nat = gr.Dropdown(nations_list(), multiselect=True, label="Nations", value=[], filterable=True)
21
+ with gr.Group(elem_classes="bubble"):
22
+ clu = gr.Dropdown(clubs_list(), multiselect=True, label="Clubs", value=[], filterable=True)
23
+ with gr.Group(elem_classes="bubble"):
24
+ query = gr.Textbox(label="Search", placeholder="e.g., Maccabi, Brazil, CAM")
25
+
26
+ # Column 2
27
+ with gr.Column(scale=1, elem_classes="grid"):
28
+ with gr.Group(elem_classes="bubble"):
29
+ min_ovr = gr.Slider(0, 99, value=0, step=1, label="Min Overall")
30
+ with gr.Group(elem_classes="bubble"):
31
+ min_pot = gr.Slider(0, 99, value=0, step=1, label="Min Potential")
32
+ with gr.Group(elem_classes="bubble"):
33
+ max_age = gr.Slider(15, 45, value=45, step=1, label="Max Age")
34
+
35
+ # Column 3
36
+ with gr.Column(scale=1, elem_classes="grid"):
37
+ with gr.Group(elem_classes="bubble"):
38
+ min_h = gr.Slider(140, 210, value=140, step=1, label="Min Height (cm)")
39
+ with gr.Group(elem_classes="bubble"):
40
+ max_h = gr.Slider(140, 210, value=210, step=1, label="Max Height (cm)")
41
+ with gr.Group(elem_classes="bubble"):
42
+ min_w = gr.Slider(45, 120, value=45, step=1, label="Min Weight (kg)")
43
+ with gr.Group(elem_classes="bubble"):
44
+ max_w = gr.Slider(45, 120, value=120, step=1, label="Max Weight (kg)")
45
+ with gr.Group(elem_classes="bubble"):
46
+ max_val = gr.Number(value=np.nan, label="Max Value (EUR)")
47
+ with gr.Group(elem_classes="bubble"):
48
+ max_wage = gr.Number(value=np.nan, label="Max Wage (EUR)")
49
+
50
+ # Results panel (wide, also a bubble)
51
+ with gr.Column(scale=2):
52
+ with gr.Group(elem_classes="bubble"):
53
+ results = gr.Dataframe(row_count=(12,"dynamic"), wrap=True, interactive=False, label="Results")
54
+ with gr.Row():
55
+ count_box = gr.Markdown("", elem_classes="stat")
56
+ avg_ovr_box = gr.Markdown("", elem_classes="stat")
57
+ avg_age_box = gr.Markdown("", elem_classes="stat")
58
+ dl = gr.DownloadButton("Download CSV")
59
+
60
+ # Full-width Search button in its own bubble below filters
61
  with gr.Row():
62
+ with gr.Column(scale=3):
63
+ with gr.Group(elem_classes="bubble"):
64
+ btn = gr.Button("Search")
65
 
66
  def _run(positions, nations, clubs, min_overall, min_potential,
67
  max_age, min_h, max_h, min_w, max_w, max_val, max_wage, query):
 
73
  csv_bytes = to_csv_bytes(df)
74
  return df, f"**Players:** {count}", f"**Avg OVR:** {avg_ovr}", f"**Avg Age:** {avg_age}", csv_bytes
75
 
 
76
  demo.load(
77
  _run,
78
  inputs=[pos,nat,clu,min_ovr,min_pot,max_age,min_h,max_h,min_w,max_w,max_val,max_wage,query],