LLM-DPS / app.py
ositamiles's picture
Update app.py
d39f76e verified
import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.model_selection import train_test_split
import tensorflow as tf
from tensorflow.keras.models import Sequential, load_model
from tensorflow.keras.layers import Dense
import joblib
import os
import openai
# Set page config
st.set_page_config(page_title="Dynamic Game Pricing App", layout="wide")
# OpenAI API key
openai.api_key = "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"
# Function to load or create data
@st.cache_data
def load_data():
if os.path.exists('game_data.csv'):
return pd.read_csv('game_data.csv')
else:
# Sample dataset
data = {
'game_id': range(1, 101),
'genre': np.random.choice(['RPG', 'FPS', 'Strategy', 'Puzzle', 'Sports'], 100),
'region': np.random.choice(['Africa', 'NA', 'EU', 'Asia', 'SA'], 100),
'release_year': np.random.randint(2018, 2024, 100),
'demand_index': np.random.uniform(0.1, 1.0, 100),
'competitor_price': np.random.uniform(20, 60, 100),
'past_sales': np.random.randint(100, 1000, 100),
'suggested_price': np.random.uniform(25, 65, 100)
}
df = pd.DataFrame(data)
df.to_csv('game_data.csv', index=False)
return df
# Load data
df = load_data()
# Function to get LLM analysis with GPT-4 function calling
def get_llm_analysis(game_info, market_info):
prompt = f"""
Analyze the following game and market information for pricing strategy:
Game Information:
{game_info}
Market Information:
{market_info}
Based on this information, suggest a pricing strategy and any factors that might influence the game's price.
Provide your analysis in a structured format with clear recommendations.
"""
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are an expert in game pricing and market trends."},
{"role": "user", "content": prompt}
],
max_tokens=300,
n=1,
stop=None,
temperature=0.7,
)
return response['choices'][0]['message']['content']
# Function to call GPT-4 for extracting market trends
def extract_market_trends():
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are a market analyst."},
{"role": "user", "content": "Pull the latest market trends for video games."}
],
max_tokens=200,
n=1,
stop=None,
temperature=0.7,
)
return response['choices'][0]['message']['content']
# Function to call GPT-4 for extracting customer review summary
def extract_customer_reviews(game_name):
prompt = f"Summarize the customer reviews for the game {game_name} in the last 6 months."
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are a customer sentiment analyst."},
{"role": "user", "content": prompt}
],
max_tokens=200,
n=1,
stop=None,
temperature=0.7,
)
return response['choices'][0]['message']['content']
# Sidebar for navigation
page = st.sidebar.selectbox("Choose a page", ["Data Explorer", "Model Training", "Price Prediction"])
if page == "Data Explorer":
st.title("Data Explorer")
st.write(df)
st.subheader("Data Statistics")
st.write(df.describe())
st.subheader("Data Visualization")
fig, ax = plt.subplots(1, 2, figsize=(15, 5))
ax[0].scatter(df['competitor_price'], df['suggested_price'])
ax[0].set_xlabel('Competitor Price')
ax[0].set_ylabel('Suggested Price')
ax[0].set_title('Competitor Price vs Suggested Price')
ax[1].scatter(df['demand_index'], df['suggested_price'])
ax[1].set_xlabel('Demand Index')
ax[1].set_ylabel('Suggested Price')
ax[1].set_title('Demand Index vs Suggested Price')
st.pyplot(fig)
elif page == "Model Training":
st.title("Model Training")
# Data preprocessing
le_genre = LabelEncoder()
df['genre_encoded'] = le_genre.fit_transform(df['genre'])
le_region = LabelEncoder()
df['region_encoded'] = le_region.fit_transform(df['region'])
features = ['genre_encoded', 'region_encoded', 'release_year', 'demand_index', 'competitor_price', 'past_sales']
X = df[features]
y = df['suggested_price']
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# Split the data
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)
# Model architecture
model = Sequential([
Dense(64, activation='relu', input_shape=(X_train.shape[1],)),
Dense(32, activation='relu'),
Dense(16, activation='relu'),
Dense(1)
])
model.compile(optimizer='adam', loss='mean_squared_error', metrics=['mae'])
# Training
if st.button("Train Model"):
with st.spinner("Training in progress..."):
history = model.fit(X_train, y_train, validation_split=0.2, epochs=100, batch_size=32, verbose=0)
st.success("Model trained successfully!")
# Plot training history
fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(history.history['loss'], label='Training Loss')
ax.plot(history.history['val_loss'], label='Validation Loss')
ax.set_xlabel('Epoch')
ax.set_ylabel('Loss')
ax.legend()
st.pyplot(fig)
# Save model and scaler
model.save('dynamic_pricing_model.h5')
joblib.dump(scaler, 'scaler.pkl')
joblib.dump(le_genre, 'le_genre.pkl')
joblib.dump(le_region, 'le_region.pkl')
st.info("Model and preprocessing objects saved.")
elif page == "Price Prediction":
st.title("Price Prediction")
# Load saved model and objects
if os.path.exists('dynamic_pricing_model.h5'):
model = load_model('dynamic_pricing_model.h5')
scaler = joblib.load('scaler.pkl')
le_genre = joblib.load('le_genre.pkl')
le_region = joblib.load('le_region.pkl')
# User input
genre = st.selectbox("Select Genre", le_genre.classes_)
region = st.selectbox("Select Region", le_region.classes_)
release_year = st.slider("Release Year", 2018, 2024, 2022)
demand_index = st.slider("Demand Index", 0.1, 1.0, 0.5)
competitor_price = st.slider("Competitor Price", 20.0, 60.0, 40.0)
past_sales = st.slider("Past Sales", 100, 1000, 500)
# Get market trends and customer reviews
with st.spinner("Fetching market trends..."):
market_trends = extract_market_trends()
with st.spinner("Analyzing customer reviews..."):
customer_reviews = extract_customer_reviews(genre)
# Display market trends and customer reviews
st.subheader("Market Trends")
st.write(market_trends)
st.subheader("Customer Reviews Summary")
st.write(customer_reviews)
# Prepare input for prediction
input_data = np.array([[
le_genre.transform([genre])[0],
le_region.transform([region])[0],
release_year,
demand_index,
competitor_price,
past_sales
]])
input_scaled = scaler.transform(input_data)
# Make prediction
if st.button("Predict Price"):
ann_predicted_price = model.predict(input_scaled)[0][0]
# Prepare game and market info for LLM
game_info = f"Genre: {genre}, Region: {region}, Release Year: {release_year}, Past Sales: {past_sales}"
market_info = f"Demand Index: {demand_index}, Competitor Price: {competitor_price}, Customer Reviews: {customer_reviews}, Market Trends: {market_trends}"
# Get LLM analysis
with st.spinner("Analyzing pricing strategy..."):
llm_analysis = get_llm_analysis(game_info, market_info)
# Display results
st.success(f"ANN Predicted Price: ${ann_predicted_price:.2f}")
st.subheader("LLM Pricing Analysis:")
st.write(llm_analysis)
# Visualize the prediction
fig, ax = plt.subplots(figsize=(10, 5))
ax.bar(['ANN Prediction', 'Competitor Price'], [ann_predicted_price, competitor_price])
ax.set_ylabel('Price ($)')
ax.set_title('Price Comparison')
st.pyplot(fig)
st.info("Consider both the ANN prediction and the LLM analysis to make a final pricing decision.")
else:
st.warning("Please train the model first!")
st.sidebar.info("This app demonstrates dynamic pricing for game codes using a combination of Feedforward ANN and LLM.")