File size: 9,967 Bytes
05d029a
 
 
 
 
 
 
 
 
3160149
05d029a
 
 
 
 
 
 
 
54cdcfe
 
 
 
 
 
 
 
 
 
 
 
05d029a
 
 
 
 
 
 
 
 
 
 
 
794a36c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05d029a
794a36c
 
 
05d029a
 
 
 
 
 
 
 
 
 
 
 
 
 
60104db
 
3160149
60104db
05d029a
286093e
 
38d5ce4
286093e
 
 
ede30af
 
286093e
 
ede30af
 
 
 
 
 
 
286093e
ede30af
 
93dfed1
ede30af
 
 
286093e
ede30af
 
 
 
 
 
 
 
 
38d5ce4
05d029a
 
 
 
 
 
 
 
 
 
 
 
 
286093e
 
 
 
 
ede30af
 
 
286093e
 
f42feaa
286093e
 
ede30af
 
 
f42feaa
05d029a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
import numpy as np
import pandas as pd
import streamlit as st
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import NearestNeighbors
import pickle

# Set page config
st.set_page_config(
    page_title="Project Futbiz (FIFA19)",
    page_icon="⚽",
    layout="wide"
)

# Load all pickle files
@st.cache_resource
def load_data():
    try:
        with open('newdf3.pkl', 'rb') as f:
            df3 = pickle.load(f)
        with open('predictorsscale.pkl', 'rb') as f:
            predictors_scaled = pickle.load(f)
        with open('newpredictors.pkl', 'rb') as f:
            predictors_df = pickle.load(f)
        with open('train_predictors_val.pkl', 'rb') as f:
            train_predictors_val = pickle.load(f)
        with open('newfifa.pkl', 'rb') as f:
            fifa = pickle.load(f)
        with open('df3scaled.pkl', 'rb') as f:
            df3scaled = pickle.load(f)
        with open('finalxbrmodel.pkl', 'rb') as f:
            xbr = pickle.load(f)
        return df3, predictors_scaled, predictors_df, train_predictors_val, fifa, df3scaled, xbr
    except Exception as e:
        st.error(f"Error loading data: {str(e)}")
        raise e

# Load data
df3, predictors_scaled, predictors_df, train_predictors_val, fifa, df3scaled, xbr = load_data()
predscale_target = predictors_scaled.columns.tolist()

def player_sim_team(team, position, NUM_RECOM, AGE_upper_bound):
    try:
        # part 1(recommendation)
        target_cols = predscale_target

        # team stats
        team_stats = df3scaled.query('position_group == @position and Club == @team').head(3)[target_cols].mean(axis=0)
        team_stats_np = team_stats.values

        # player stats by each position
        ply_stats = df3scaled.query('position_group == @position and Club != @team and Age1 <= @AGE_upper_bound')[
        ['ID'] + target_cols]
        ply_stats_np = ply_stats[target_cols].values
        X = np.vstack((team_stats_np, ply_stats_np))

        ## KNN
        nbrs = NearestNeighbors(n_neighbors=NUM_RECOM + 1, algorithm='auto').fit(X)
        dist, rank = nbrs.kneighbors(X)

        indice = ply_stats.iloc[rank[0, 1:]].index.tolist()
        predicted_players_name=df3['Name'].loc[indice,].tolist()
        predicted_players_value=fifa['Value'].loc[indice,].tolist()
        display_df1 = predictors_scaled.loc[indice,]
        playrpredictorss = predictors_df.loc[indice,]
        display_df2 = df3.loc[indice,]
        display_df = fifa.loc[indice,]

        try:
            #part 2(prediction)
            predictors_anomaly_processed=playrpredictorss[playrpredictorss.index.isin(list(display_df2['ID']))].copy()
            predictors_anomaly_processed['Forward_Skill'] = predictors_anomaly_processed.loc[:,['LS','ST','RS','LW','LF','CF','RF','RW']].mean(axis=1)
            predictors_anomaly_processed['Midfield_Skill'] = predictors_anomaly_processed.loc[:,['LAM','CAM','RAM','LM','LCM','CM','RCM','RM','LDM','CDM','RDM']].mean(axis=1)
            predictors_anomaly_processed['Defence_Skill'] = predictors_anomaly_processed.loc[:,['LWB','RWB','LB','LCB','CB','RCB','RB']].mean(axis=1)

            predictors_anomaly_processed = predictors_anomaly_processed.drop(['LS','ST','RS','LW','LF','CF','RF','RW',
                'LAM','CAM','RAM','LM','LCM','CM','RCM','RM','LDM','CDM','RDM',
                'LWB','RWB','LB','LCB','CB','RCB','RB'], axis=1)

            predictors_anomaly_processed=predictors_anomaly_processed.drop(predictors_anomaly_processed.iloc[:,predictors_anomaly_processed.columns.get_loc('Position_CAM'):predictors_anomaly_processed.columns.get_loc('Position_ST')+1], axis=1)

            predictors_anomaly_processed=predictors_anomaly_processed[train_predictors_val.columns]
            predictors_anomaly_processed[['International Reputation','Real Face']]=predictors_anomaly_processed[['International Reputation','Real Face']].astype('category')

            scaler = StandardScaler()
            predictors_anomaly_processed[predictors_anomaly_processed.select_dtypes(include=['float64','float32','int64','int32'], exclude=['category']).columns] = scaler.fit_transform(predictors_anomaly_processed.select_dtypes(include=['float64','float32','int64','int32'], exclude=['category']))
            predictors_anomaly_processed[predictors_anomaly_processed.select_dtypes(include='category').columns]=predictors_anomaly_processed[predictors_anomaly_processed.select_dtypes(include='category').columns].astype('int')

            try:
                predictions = abs(xbr.predict(predictors_anomaly_processed))
                predictions = predictions.astype('int64')
            except AttributeError:
                st.warning("Using fallback prediction method due to model version mismatch")
                # Fallback to using value directly if prediction fails
                predictions = predicted_players_value

        except Exception as e:
            st.error(f"Error in prediction part: {str(e)}")
            # Fallback to using original values if prediction fails
            predictions = predicted_players_value

        result = final_pred(NUM_RECOM, predictions, predicted_players_value, predicted_players_name)
        return result

    except Exception as e:
        st.error(f"Error in recommendation part: {str(e)}")
        return []

def final_pred(num_of_players,b=[],c=[],d=[]):

    z=[]
    for m in range(0,num_of_players):


        c[m]=((c[m]+b[m])/2)
        z.append({"starting_bid":c[m],"player_name":d[m]})


    return z

def main():
    # Replace st.title with custom markdown for smaller title
    st.markdown("""
    <h1 style='font-size: 24px; margin-bottom: 20px;'>Project Futbiz (FIFA19) 🎮⚽</h1>
    """, unsafe_allow_html=True)
    
    # Create two columns - one for instructions and one for results
    left_col, right_col = st.columns([1, 1])
    
    with left_col:
        # Add business context and description
        st.markdown("""
        <h4 style='font-size: 18px;'>About this App</h4>
        <p style='font-size: 14px;'>
        This FIFA 19 Player Recommender helps football clubs and managers identify similar players and predict their market value. 
        It's particularly useful for:
        </p>
        <ul style='font-size: 14px;'>
            <li>Scouting potential replacements for current players</li>
            <li>Finding undervalued talents in the market</li>
            <li>Discovering players that match your team's playing style</li>
            <li>Making informed decisions about player acquisitions</li>
        </ul>
        
        <h4 style='font-size: 18px;'>How it Works</h4>
        <ol style='font-size: 14px;'>
            <li>The app uses advanced machine learning(KNN and XGBoost) to analyze player attributes and find similar players</li>
            <li>It considers over 70 different player statistics and characteristics</li>
            <li>Provides market value predictions to help with transfer budget planning</li>
        </ol>
        
        <h4 style='font-size: 18px;'>How to Use</h4>
        <ol style='font-size: 14px;'>
            <li><b>Select Your Team</b> from the sidebar - this helps find players that would fit your team's style</li>
            <li><b>Choose Position</b> you're looking to fill</li>
            <li><b>Adjust Number of Recommendations</b> (1-10 players)</li>
            <li><b>Set Maximum Age</b> to focus on your preferred age range</li>
            <li>Click "Get Recommendations" to see your matches!</li>
        </ol>
        """, unsafe_allow_html=True)
    
    # Sidebar inputs
    st.sidebar.header("Search Parameters")
    
    # Get unique teams and positions
    teams = sorted(df3['Club'].unique())
    positions = sorted(df3['position_group'].unique())
    
    team_chosen = st.sidebar.selectbox("Select Team", teams)
    postion_chosen = st.sidebar.selectbox("Select Position", positions)
    num_of_players = st.sidebar.slider("Number of Players to Recommend", 1, 10, 5)
    age_up = st.sidebar.slider("Maximum Age", 16, 45, 30)
    
    if st.sidebar.button("Get Recommendations"):
        with right_col:
            with st.spinner("Finding similar players..."):
                recommendations = player_sim_team(team_chosen, postion_chosen, num_of_players, age_up)
                
                # Display results in a nice format
                st.markdown(f"""
                <h4 style='font-size: 18px;'>Recommended Players for {team_chosen} - {postion_chosen}</h4>
                """, unsafe_allow_html=True)
                
                # Create a container for recommendations
                for idx, player in enumerate(recommendations, 1):
                    with st.container():
                        st.markdown(f"""
                        <div style='font-size: 16px;'><b>Recommendation #{idx}: {player['player_name']}</b></div>
                        <div style='font-size: 13px; color: #888;'>Estimated Value: €{player['starting_bid']:,.0f}</div>
                        <hr style='margin: 3px 0px;'>
                        """, unsafe_allow_html=True)

if __name__ == '__main__':
    main()




    #print("postions=side_df,cent_df,cent_md,side_md,cent_fw,side_fw,goalkeep")
    #print("team=any club teams in any of the countries ")
    #print("*********************************************** \n")
    #team_chosen = str(input("Enter the team you are looking for:  \n"))
    #postion_chosen = str(input("Enter the position you are looking for:  \n"))
    #num_of_players = input("Enter the number of similar players you are looking for: \n")
    #age_up = input("Enter the age limit: ")
    #print("***please have some biscuits, it will take some time***")

    #player_sim_team(team_chosen,postion_chosen, int(num_of_players), int(age_up))
    #finalfunction = player_sim_team(team_chosen,postion_chosen, int(num_of_players), int(age_up))
    #pickle.dump(finalfunction, open('finalfunction.pkl', 'wb'))