Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,142 +1,82 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
-
import pandas as pd
|
| 3 |
import numpy as np
|
| 4 |
-
import
|
| 5 |
-
|
| 6 |
-
from sklearn.preprocessing import StandardScaler
|
| 7 |
-
|
| 8 |
-
from tensorflow.keras.layers import LSTM, Dense
|
| 9 |
-
import gym
|
| 10 |
-
from stable_baselines3 import PPO
|
| 11 |
-
|
| 12 |
-
# Simulated data and functions
|
| 13 |
-
def generate_sample_data(n_samples=1000):
|
| 14 |
-
dates = pd.date_range(start='2023-01-01', periods=n_samples)
|
| 15 |
-
df = pd.DataFrame({
|
| 16 |
-
'date': dates,
|
| 17 |
-
'base_price': np.random.uniform(4000000, 6000000, n_samples),
|
| 18 |
-
'competitor_price': np.random.uniform(4500000, 5500000, n_samples),
|
| 19 |
-
'demand': np.random.normal(100, 20, n_samples),
|
| 20 |
-
'social_media_sentiment': np.random.uniform(-1, 1, n_samples),
|
| 21 |
-
'economic_indicator': np.random.uniform(0.8, 1.2, n_samples),
|
| 22 |
-
})
|
| 23 |
-
df['price'] = df['base_price'] * (1 + 0.1 * df['social_media_sentiment']) * df['economic_indicator']
|
| 24 |
-
return df
|
| 25 |
-
|
| 26 |
-
# Step 1: Regression Model
|
| 27 |
-
def train_regression_model(data):
|
| 28 |
-
X = data[['competitor_price', 'demand', 'social_media_sentiment', 'economic_indicator']]
|
| 29 |
-
y = data['price']
|
| 30 |
-
model = GradientBoostingRegressor()
|
| 31 |
-
model.fit(X, y)
|
| 32 |
-
return model
|
| 33 |
-
|
| 34 |
-
# Step 2: LSTM Model
|
| 35 |
-
def create_lstm_model(input_shape):
|
| 36 |
-
model = Sequential([
|
| 37 |
-
LSTM(64, input_shape=input_shape, return_sequences=True),
|
| 38 |
-
LSTM(32),
|
| 39 |
-
Dense(1)
|
| 40 |
-
])
|
| 41 |
-
model.compile(optimizer='adam', loss='mse')
|
| 42 |
-
return model
|
| 43 |
-
|
| 44 |
-
def prepare_lstm_data(data, look_back=30):
|
| 45 |
-
X, y = [], []
|
| 46 |
-
for i in range(len(data) - look_back):
|
| 47 |
-
X.append(data[i:(i + look_back)])
|
| 48 |
-
y.append(data[i + look_back])
|
| 49 |
-
return np.array(X), np.array(y)
|
| 50 |
-
|
| 51 |
-
# Step 3: Reinforcement Learning Environment
|
| 52 |
-
class PricingEnv(gym.Env):
|
| 53 |
-
def __init__(self, data):
|
| 54 |
-
super(PricingEnv, self).__init__()
|
| 55 |
-
self.data = data
|
| 56 |
-
self.current_step = 0
|
| 57 |
-
self.action_space = gym.spaces.Box(low=0.9, high=1.1, shape=(1,))
|
| 58 |
-
self.observation_space = gym.spaces.Box(low=-np.inf, high=np.inf, shape=(5,))
|
| 59 |
-
|
| 60 |
-
def reset(self):
|
| 61 |
-
self.current_step = 0
|
| 62 |
-
return self._get_observation()
|
| 63 |
-
|
| 64 |
-
def step(self, action):
|
| 65 |
-
self.current_step += 1
|
| 66 |
-
if self.current_step >= len(self.data):
|
| 67 |
-
return self._get_observation(), 0, True, {}
|
| 68 |
-
|
| 69 |
-
current_price = self.data.iloc[self.current_step]['price']
|
| 70 |
-
new_price = current_price * action[0]
|
| 71 |
-
reward = self._calculate_reward(new_price)
|
| 72 |
-
|
| 73 |
-
return self._get_observation(), reward, False, {}
|
| 74 |
-
|
| 75 |
-
def _get_observation(self):
|
| 76 |
-
obs = self.data.iloc[self.current_step][['competitor_price', 'demand', 'social_media_sentiment', 'economic_indicator', 'price']].values
|
| 77 |
-
return obs
|
| 78 |
-
|
| 79 |
-
def _calculate_reward(self, new_price):
|
| 80 |
-
base_demand = self.data.iloc[self.current_step]['demand']
|
| 81 |
-
price_elasticity = -1.5
|
| 82 |
-
demand = base_demand * (new_price / self.data.iloc[self.current_step]['price']) ** price_elasticity
|
| 83 |
-
revenue = new_price * demand
|
| 84 |
-
cost = 3000000 # Assuming a fixed cost
|
| 85 |
-
profit = revenue - cost
|
| 86 |
-
return profit
|
| 87 |
-
|
| 88 |
-
# Streamlit App
|
| 89 |
-
def main():
|
| 90 |
-
st.title("Dynamic Pricing System for GTA V Source Code")
|
| 91 |
-
|
| 92 |
-
# Generate sample data
|
| 93 |
-
data = generate_sample_data()
|
| 94 |
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
regression_model = train_regression_model(data)
|
| 98 |
-
latest_data = data.iloc[-1]
|
| 99 |
-
initial_price = regression_model.predict(latest_data[['competitor_price', 'demand', 'social_media_sentiment', 'economic_indicator']].values.reshape(1, -1))[0]
|
| 100 |
-
st.write(f"Initial price estimation: ${initial_price:,.2f}")
|
| 101 |
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
X, y = prepare_lstm_data(scaled_data)
|
| 107 |
-
lstm_model = create_lstm_model((X.shape[1], 1))
|
| 108 |
-
lstm_model.fit(X, y, epochs=50, batch_size=32, verbose=0)
|
| 109 |
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
obs = env.reset()
|
| 122 |
-
rl_action, _ = model.predict(obs)
|
| 123 |
-
final_price = adjusted_price * rl_action[0]
|
| 124 |
-
st.write(f"Final dynamically optimized price: ${final_price:,.2f}")
|
| 125 |
-
|
| 126 |
-
# Interactive price adjustment
|
| 127 |
-
st.header("Interactive Price Adjustment")
|
| 128 |
-
user_adjustment = st.slider("Adjust the final price (%)", -20, 20, 0)
|
| 129 |
-
user_price = final_price * (1 + user_adjustment / 100)
|
| 130 |
-
st.write(f"User adjusted price: ${user_price:,.2f}")
|
| 131 |
-
|
| 132 |
-
# Visualize pricing history
|
| 133 |
-
st.header("Pricing History")
|
| 134 |
-
fig = go.Figure()
|
| 135 |
-
fig.add_trace(go.Scatter(x=data['date'], y=data['price'], mode='lines', name='Historical Price'))
|
| 136 |
-
fig.add_trace(go.Scatter(x=[data['date'].iloc[-1]], y=[final_price], mode='markers', name='AI Suggested Price', marker=dict(size=10, color='red')))
|
| 137 |
-
fig.add_trace(go.Scatter(x=[data['date'].iloc[-1]], y=[user_price], mode='markers', name='User Adjusted Price', marker=dict(size=10, color='green')))
|
| 138 |
-
fig.update_layout(title='GTA V Source Code Pricing History', xaxis_title='Date', yaxis_title='Price ($)')
|
| 139 |
-
st.plotly_chart(fig)
|
| 140 |
|
| 141 |
-
|
| 142 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
|
|
|
| 2 |
import numpy as np
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import tensorflow as tf
|
| 5 |
+
from sklearn.preprocessing import OneHotEncoder, StandardScaler
|
| 6 |
+
import joblib
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
+
# Load the trained model
|
| 9 |
+
model = tf.keras.models.load_model('trained_game_price_model.h5')
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
+
# Function to preprocess the input data
|
| 12 |
+
def preprocess_input(data, ohe, scaler):
|
| 13 |
+
# Convert input into DataFrame for processing
|
| 14 |
+
input_data = pd.DataFrame([data], columns=['genre', 'targetPlatform', 'gamePlays', 'competitorPricing', 'currencyFluctuations'])
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
+
# Apply OneHotEncoder for categorical features
|
| 17 |
+
input_data_transformed = ohe.transform(input_data[['genre', 'targetPlatform']])
|
| 18 |
+
|
| 19 |
+
# Merge with numerical features
|
| 20 |
+
input_data = np.hstack((input_data_transformed, input_data[['gamePlays', 'competitorPricing', 'currencyFluctuations']].values))
|
| 21 |
+
|
| 22 |
+
# Scale the numerical features
|
| 23 |
+
input_data_scaled = scaler.transform(input_data)
|
| 24 |
+
|
| 25 |
+
return input_data_scaled
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
+
# Function to make a prediction
|
| 28 |
+
def make_prediction(input_data):
|
| 29 |
+
# Preprocess the data for the model
|
| 30 |
+
input_data_scaled = preprocess_input(input_data, ohe, scaler)
|
| 31 |
+
|
| 32 |
+
# Make prediction
|
| 33 |
+
prediction = model.predict(input_data_scaled)
|
| 34 |
+
|
| 35 |
+
return prediction[0][0]
|
| 36 |
+
|
| 37 |
+
# Load pre-trained OneHotEncoder and StandardScaler (assuming you have these saved)
|
| 38 |
+
ohe = joblib.load('ohe.pkl') # Load the OneHotEncoder
|
| 39 |
+
scaler = joblib.load('scaler.pkl') # Load the StandardScaler
|
| 40 |
+
|
| 41 |
+
# Streamlit application
|
| 42 |
+
st.title("Game Price Prediction App")
|
| 43 |
+
|
| 44 |
+
st.write("""
|
| 45 |
+
### Enter the game details below to predict its price.
|
| 46 |
+
""")
|
| 47 |
+
|
| 48 |
+
# Game details form
|
| 49 |
+
with st.form("game_details_form"):
|
| 50 |
+
genre = st.selectbox('Genre', ['Action', 'RPG', 'Puzzle', 'Adventure', 'Simulation', 'Strategy', 'Horror', 'Fighting', 'Sports', 'Racing', 'Casual', 'MOBA', 'Sandbox'])
|
| 51 |
+
target_platform = st.selectbox('Platform', ['PC', 'PlayStation', 'Xbox', 'Mobile', 'Switch', 'Nintendo 3DS', 'VR', 'Web'])
|
| 52 |
+
game_plays = st.number_input('Number of Game Plays', min_value=0, value=50000)
|
| 53 |
+
competitor_pricing = st.number_input('Competitor Pricing', min_value=0.0, value=30.0, format="%.2f")
|
| 54 |
+
currency_fluctuations = st.number_input('Currency Fluctuations', min_value=0.5, max_value=1.5, value=1.0, format="%.2f")
|
| 55 |
+
|
| 56 |
+
# Submit button
|
| 57 |
+
submitted = st.form_submit_button("Predict Price")
|
| 58 |
+
|
| 59 |
+
# Prediction logic
|
| 60 |
+
if submitted:
|
| 61 |
+
# Prepare input data
|
| 62 |
+
input_data = {
|
| 63 |
+
'genre': genre,
|
| 64 |
+
'targetPlatform': target_platform,
|
| 65 |
+
'gamePlays': game_plays,
|
| 66 |
+
'competitorPricing': competitor_pricing,
|
| 67 |
+
'currencyFluctuations': currency_fluctuations
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
# Make prediction
|
| 71 |
+
predicted_price = make_prediction(input_data)
|
| 72 |
+
|
| 73 |
+
# Display results
|
| 74 |
+
st.write(f"### Predicted Game Price: ${predicted_price:.2f}")
|
| 75 |
+
|
| 76 |
+
# Show the input details for reference
|
| 77 |
+
st.write("#### Input Details:")
|
| 78 |
+
st.write(f"- **Genre**: {genre}")
|
| 79 |
+
st.write(f"- **Platform**: {target_platform}")
|
| 80 |
+
st.write(f"- **Game Plays**: {game_plays}")
|
| 81 |
+
st.write(f"- **Competitor Pricing**: ${competitor_pricing:.2f}")
|
| 82 |
+
st.write(f"- **Currency Fluctuations**: {currency_fluctuations}")
|