danupurnomo
Finalization background color
5a3cff5
import os
import time
import base64
import pickle
import numpy as np
import pandas as pd
import streamlit as st
import plotly.express as px
from PIL import Image
from collections import deque
from urllib.request import urlopen
# STEP 1 - DEFINE PATHS
base_path = os.path.abspath(os.path.dirname(__file__))
model_path = os.path.join(base_path, 'model')
img_path = os.path.join(base_path, 'img')
# STEP 2 - LOAD MODEL
model_filename = 'model_rating.pkl'
scaler_filename = 'model_feat_scaling.pkl'
encoder_filename = 'model_feat_enc.pkl'
model_filepath = os.path.join(model_path, model_filename)
scaler_filepath = os.path.join(model_path, scaler_filename)
encoder_filepath = os.path.join(model_path, encoder_filename)
with open(model_filepath, "rb") as filename:
model_rating = pickle.load(filename)
with open(scaler_filepath, "rb") as filename:
scaler = pickle.load(filename)
with open(encoder_filepath, "rb") as filename:
encoder = pickle.load(filename)
# STEP 3 - SET PAGE CONFIG
st.set_page_config(
page_title = 'FIFA 2022 Player Rating\'s Prediction',
layout = 'wide',
initial_sidebar_state = 'auto',
menu_items = {
'About': '''
## FIFA 2022 Player Rating\'s Prediction
---
_Made by Danu Purnomo_
Predict rating of a football player based on FIFA 2022 players.
'''
}
)
# STEP 4 - CREATE BACKGROUND
def convert_img_to_base64(img_path):
with open(img_path, 'rb') as image_file:
encoded_string = base64.b64encode(image_file.read())
return encoded_string
img_background_path = os.path.join(img_path, '01 - background.jpg')
# img_background_path = os.path.join(img_path, 'test-02.jpg')
encoded_string = convert_img_to_base64(img_background_path)
st.markdown(
f"""
<style>
.stApp {{
background-color: #dbe8ff;
}}
</style>
""",
unsafe_allow_html=True
)
# STEP 5 - SET TITLE AND OPENER
## STEP 5.1 - SET TITLE
text_title = '<h1 style="font-family:sans-serif; color:#051d69; text-align:center;">FIFA 2022 Player\'s Rating Predictions</h1>'
st.markdown(text_title, unsafe_allow_html=True)
## STEP 5.2 - SET OPENER
gif0 = '<div style="width:1080px"><iframe allow="fullscreen" align="center" frameBorder="0" height="720" src="https://giphy.com/embed/ICE7YmNTU9MatWIgxi/video" width=" 1380"></iframe></div>'
st.markdown(gif0, unsafe_allow_html=True)
# STEP 6 - SET PARAMETERS
st.markdown('---')
text_style = '<p style="font-family:sans-serif; color:#b41ff0; font-size: 30px;">Set Parameters</p>'
st.markdown(text_style, unsafe_allow_html=True)
# Attribute of a football player
# 0 Name 19260 non-null object
# 1 Age 19260 non-null int64
# 2 Height 19260 non-null int64
# 3 Weight 19260 non-null int64
# 4 Price 19260 non-null int64
# 5 AttackingWorkRate 19260 non-null object
# 6 DefensiveWorkRate 19260 non-null object
# 7 PaceTotal 19260 non-null int64
# 8 ShootingTotal 19260 non-null int64
# 9 PassingTotal 19260 non-null int64
# 10 DribblingTotal 19260 non-null int64
# 11 DefendingTotal 19260 non-null int64
# 12 PhysicalityTotal 19260 non-null int64
# 13 Rating 19260 non-null int64
with st.form(key='form_parameters'):
## STEP 6.1 : Section 1
header_section_1 = '<p style="font-family:sans-serif; color:#67b8f8; font-size: 20px;"> Personal Profile </p>'
st.markdown(header_section_1, unsafe_allow_html=True)
col1, col2, col3 = st.columns([1, 1, 1])
st.markdown(f'<p style="background-color:#0066cc;color:#33ff33;font-size:24px;border-radius:2%;"></p>', unsafe_allow_html=True)
with col1:
img_personal_profile_path = os.path.join(img_path, '02 - personal profile.png')
image = Image.open(img_personal_profile_path)
st.image(image, width=350)
with col2:
col_name = st.text_input('Name', value='', help='Player\'s name')
col_age = st.number_input('Age', min_value=14, max_value=60, value=22, step=1, help='Player\'s age. Default age is 22.')
col_price = st.number_input('Price (EUR)', min_value=0, value=1000000, step=1, format='%d', help='Player\'s price. Default price is EUR 1,000,000.')
with col3:
col_height = st.number_input('Height (cm)', min_value=140, max_value=220, value=180, step=1, help='Player\'s height. Default height is 180 cm.')
col_weight = st.number_input('Weight (kg)', min_value=40, max_value=120, value=70, step=1, help='Player\'s weight. Default weight is 70 kg.')
## STEP 6.2 : Section 2
header_section_2 = '<p style="font-family:sans-serif; color:#67b8f8; font-size: 20px;"> Work Rate </p>'
st.markdown('---')
st.markdown(header_section_2, unsafe_allow_html=True)
col1, col2, col3 = st.columns([1, 1, 1])
with col1:
img_work_rate_path = os.path.join(img_path, '03 - work rate.png')
image = Image.open(img_work_rate_path)
st.image(image, width=250)
with col2:
col_attacking_work_rate = st.selectbox('Attacking Work Rate', ['-', 'Low', 'Medium', 'High'], index=0, help='Player\'s desire to attack.')
col_defensive_work_rate = st.selectbox('Defensive Work Rate', ['-', 'Low', 'Medium', 'High'], index=0, help='Player\'s desire to defend.')
## STEP 6.3 : Section 3
header_section_3 = '<p style="font-family:sans-serif; color:#67b8f8; font-size: 20px;"> Ability </p>'
st.markdown('---')
st.markdown(header_section_3, unsafe_allow_html=True)
col1, col2, col3 = st.columns([1, 1, 1])
with col1:
img_work_rate_path = os.path.join(img_path, '04 - ability.png')
image = Image.open(img_work_rate_path)
st.image(image, width=350)
with col2:
col_pace_total = st.number_input('Pace Total', min_value=0, max_value=100, value=50, step=1, help='How fast is a player.')
col_shooting_total = st.number_input('Shooting Total', min_value=0, max_value=100, value=50, step=1, help='How good at kicking.')
col_passing_total = st.number_input('Passing Total', min_value=0, max_value=100, value=50, step=1, help='How good at passing.')
with col3:
col_dribbling_total = st.number_input('Dribbling Total', min_value=0, max_value=100, value=50, step=1, help='How good at dribbling.')
col_defending_total = st.number_input('Defending Total', min_value=0, max_value=100, value=50, step=1, help='How good at defending.')
col_physicality_total = st.number_input('Physicality Total', min_value=0, max_value=100, value=50, step=1, help='How good is a player\'s physique.')
## STEP 6.4 : Section 4
st.markdown('<br><br>', unsafe_allow_html=True)
col1, col2, col3 = st.columns([3, 1, 3])
with col2:
submitted = st.form_submit_button('Predict')
# STEP 7 - PREDICT NEW DATA
## STEP 7.1 - Create DataFrame for New Data
## `new_data` is for inference meanwhile `new_data_for_radar_plot` is for plot line_polar.
new_data = {
'Name': [col_name],
'Age': [col_age],
'Height': [col_height],
'Weight': [col_weight],
'Price': [col_price],
'AttackingWorkRate': [col_attacking_work_rate],
'DefensiveWorkRate': [col_defensive_work_rate],
'PaceTotal': [col_pace_total],
'ShootingTotal': [col_shooting_total],
'PassingTotal': [col_passing_total],
'DribblingTotal': [col_dribbling_total],
'DefendingTotal': [col_defending_total],
'PhysicalityTotal': [col_physicality_total]
}
new_data_for_radar_plot = {
'PaceTotal': [col_pace_total],
'ShootingTotal': [col_shooting_total],
'PassingTotal': [col_passing_total],
'DribblingTotal': [col_dribbling_total],
'DefendingTotal': [col_defending_total],
'PhysicalityTotal': [col_physicality_total]
}
new_data = pd.DataFrame.from_dict(new_data)
new_data_for_radar_plot = pd.DataFrame.from_dict(new_data_for_radar_plot)
# st.write(new_data)
print('New Data : ', new_data)
result_section = st.empty()
if submitted :
## STEP 7.2 - Split Numerical Columns and Categorical Columns
num_columns = ['Age', 'Height', 'Weight', 'Price', 'PaceTotal', 'ShootingTotal', 'PassingTotal', 'DribblingTotal', 'DefendingTotal', 'PhysicalityTotal']
cat_columns = ['AttackingWorkRate', 'DefensiveWorkRate']
new_data_num = new_data[num_columns]
new_data_cat = new_data[cat_columns]
## STEP 7.3 - Feature Scaling and Feature Encoding
new_data_num_scaled = scaler.transform(new_data_num)
new_data_cat_encoded = encoder.transform(new_data_cat)
## STEP 7.4 - Concatenate between Numerical Columns and Categorical Columns
new_data_final = np.concatenate([new_data_num_scaled, new_data_cat_encoded], axis=1)
## STEP 7.5 - Predict using Linear Regression
y_pred_inf = model_rating.predict(new_data_final)
print(type(y_pred_inf))
## STEP 7.6 - Display Prediction
result_section.empty()
bar = st.progress(0)
for i in range(100):
bar.progress(i + 1)
time.sleep(0.01)
bar.empty()
with result_section.container():
st.markdown('<br><br>', unsafe_allow_html=True)
col1, col2, col3, col4, col5 = st.columns([0.5, 2, 1, 2, 1])
with col2:
img_personal_profile_path = os.path.join(img_path, '05 - person rear.png')
image = Image.open(img_personal_profile_path)
st.image(image, width=350)
with col3:
st.markdown('<br><br><br><br>', unsafe_allow_html=True)
player_name = '<h1 style="font-family:helvetica; color:#fff9ac; text-align:center"> ' + col_name + ' </h1>'
st.markdown(player_name, unsafe_allow_html=True)
player_rating_pred = '<p style="font-family:helvetica; color:#494d55; font-size:100px; text-align:center"> <b>' + str(int(y_pred_inf)) + ' </p>'
st.markdown(player_rating_pred, unsafe_allow_html=True)
with col4:
st.markdown('<br><br>', unsafe_allow_html=True)
skill_total_fig = px.line_polar(
r = new_data_for_radar_plot.loc[0].values,
theta = new_data_for_radar_plot.columns,
line_close = True,
range_r = [0, 100],
color_discrete_sequence = ['#FFF9AC'],
# hover_name=['PaceTotal', '1', '2', '4', '5', '6'],
template='plotly_dark')
skill_total_fig.update_traces(fill='toself')
skill_total_fig.update_layout({
'plot_bgcolor': 'rgba(255, 0, 0, 0)',
'paper_bgcolor': 'rgba(0, 0, 0, 0)',
'font_size': 19
})
st.write(skill_total_fig)
st.write('''Source images :
[link](https://www.vecteezy.com/vector-art/5129950-football-player-figure-line-art-human-action-on-motion-lines-controlling-the-ball-with-chest),
[link](https://www.vecteezy.com/vector-art/5939693-football-player-figure-line-art-human-action-on-motion-lines-kicking-ball),
[link](https://www.vecteezy.com/vector-art/5129956-football-player-figure-line-art-human-action-on-motion-lines-kicking-ball),
[link](https://www.dreamstime.com/young-african-soccer-player-man-studio-isolated-white-background-silhouette-shadow-young-african-soccer-player-man-image199265151)
''')