Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,99 +1,162 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
import pandas as pd
|
| 3 |
-
import
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
import pandas as pd
|
| 3 |
+
import plotly.express as px
|
| 4 |
+
import plotly.graph_objects as go
|
| 5 |
+
import openai
|
| 6 |
+
|
| 7 |
+
# Add your OpenAI API key here
|
| 8 |
+
openai.api_key = st.secret["OPEN_AI_KEY"]
|
| 9 |
+
|
| 10 |
+
st.title("Transaction Analysis")
|
| 11 |
+
|
| 12 |
+
# Load the data
|
| 13 |
+
df_converted = pd.read_csv('payments_optimized.csv')
|
| 14 |
+
|
| 15 |
+
# Convert CreatedDate to datetime
|
| 16 |
+
df_converted['CreatedDate'] = pd.to_datetime(df_converted['CreatedDate'])
|
| 17 |
+
|
| 18 |
+
# Function to analyze transaction data
|
| 19 |
+
def analyze_transaction_data(df):
|
| 20 |
+
summary = {
|
| 21 |
+
"total_transactions": len(df),
|
| 22 |
+
"total_amount": df['Amount'].sum(),
|
| 23 |
+
"average_amount": df['Amount'].mean(),
|
| 24 |
+
"max_amount": df['Amount'].max(),
|
| 25 |
+
"min_amount": df['Amount'].min(),
|
| 26 |
+
"median_amount": df['Amount'].median(),
|
| 27 |
+
"transaction_trend": df.groupby(df['CreatedDate'].dt.to_period("M"))['Amount'].sum().tolist()
|
| 28 |
+
}
|
| 29 |
+
return summary
|
| 30 |
+
|
| 31 |
+
# Function to get response from ChatGPT
|
| 32 |
+
def get_chatgpt_response(prompt):
|
| 33 |
+
response = openai.ChatCompletion.create(
|
| 34 |
+
model="gpt-4o",
|
| 35 |
+
messages=[
|
| 36 |
+
{"role": "system", "content": "You are a helpful assistant."},
|
| 37 |
+
{"role": "user", "content": prompt}
|
| 38 |
+
],
|
| 39 |
+
max_tokens=500
|
| 40 |
+
)
|
| 41 |
+
return response.choices[0].message['content'].strip()
|
| 42 |
+
|
| 43 |
+
# Function to send report to ChatGPT
|
| 44 |
+
def send_report(plot_title, data):
|
| 45 |
+
summary = analyze_transaction_data(data)
|
| 46 |
+
prompt = f"""
|
| 47 |
+
Transaction Data Insights:
|
| 48 |
+
1. Total Transactions: {summary['total_transactions']}
|
| 49 |
+
2. Total Amount Transacted: ${summary['total_amount']:.2f}
|
| 50 |
+
3. Average Transaction Amount: ${summary['average_amount']:.2f}
|
| 51 |
+
4. Maximum Transaction Amount: ${summary['max_amount']:.2f}
|
| 52 |
+
5. Minimum Transaction Amount: ${summary['min_amount']:.2f}
|
| 53 |
+
6. Median Transaction Amount: ${summary['median_amount']:.2f}
|
| 54 |
+
|
| 55 |
+
Provide strategic ideas based on this data.
|
| 56 |
+
"""
|
| 57 |
+
response = get_chatgpt_response(prompt)
|
| 58 |
+
st.session_state['chat_with_gpt'] = f"Report for {plot_title} sent to ChatGPT. Data Summary: {summary}\n\nChatGPT Response: {response}"
|
| 59 |
+
st.experimental_rerun()
|
| 60 |
+
|
| 61 |
+
# Plotting Transaction Amounts over Time with clickable dots
|
| 62 |
+
st.subheader('Transaction Amounts Over Time')
|
| 63 |
+
fig = px.scatter(
|
| 64 |
+
df_converted,
|
| 65 |
+
x='CreatedDate',
|
| 66 |
+
y='Amount',
|
| 67 |
+
custom_data=['CustomerName', 'PaymentMethod', 'Store', 'InvoiceType', 'TransactionType'],
|
| 68 |
+
title='Transaction Amounts Over Time'
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
fig.update_traces(
|
| 72 |
+
marker=dict(size=10),
|
| 73 |
+
selector=dict(mode='markers'),
|
| 74 |
+
hovertemplate=(
|
| 75 |
+
'Date: %{x}<br>'
|
| 76 |
+
'Amount: $%{y}<br>'
|
| 77 |
+
'Customer: %{customdata[0]}<br>'
|
| 78 |
+
'Payment Method: %{customdata[1]}<br>'
|
| 79 |
+
'Store: %{customdata[2]}<br>'
|
| 80 |
+
'Invoice Type: %{customdata[3]}<br>'
|
| 81 |
+
'Transaction Type: %{customdata[4]}<br>'
|
| 82 |
+
)
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
# Convert Plotly figure to a FigureWidget
|
| 86 |
+
fig_widget = go.FigureWidget(fig)
|
| 87 |
+
|
| 88 |
+
# Function to display click data
|
| 89 |
+
def display_click_data(trace, points, state):
|
| 90 |
+
if points.point_inds:
|
| 91 |
+
point = points.point_inds[0]
|
| 92 |
+
selected_data = df_converted.iloc[point]
|
| 93 |
+
st.session_state['selected_point'] = selected_data.to_dict()
|
| 94 |
+
st.experimental_rerun()
|
| 95 |
+
|
| 96 |
+
# Add click event handler
|
| 97 |
+
fig_widget.data[0].on_click(display_click_data)
|
| 98 |
+
|
| 99 |
+
# Display the plot
|
| 100 |
+
st.plotly_chart(fig_widget)
|
| 101 |
+
|
| 102 |
+
# Display details when a point is clicked
|
| 103 |
+
if 'selected_point' in st.session_state:
|
| 104 |
+
st.write('Details for selected transaction:')
|
| 105 |
+
st.write(st.session_state['selected_point'])
|
| 106 |
+
|
| 107 |
+
# Button to send report to ChatGPT
|
| 108 |
+
if st.button("Executive Report - Transaction Amounts Over Time"):
|
| 109 |
+
send_report("Transaction Amounts Over Time", df_converted[
|
| 110 |
+
['CreatedDate', 'Amount', 'CustomerName', 'PaymentMethod', 'Store', 'InvoiceType', 'TransactionType']]
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
# Plotting Payment Method Preferences
|
| 114 |
+
st.subheader('Payment Method Preferences')
|
| 115 |
+
payment_method_counts_converted = df_converted['PaymentMethod'].value_counts().reset_index()
|
| 116 |
+
payment_method_counts_converted.columns = ['PaymentMethod', 'Count']
|
| 117 |
+
fig = px.bar(payment_method_counts_converted, x='PaymentMethod', y='Count', title='Payment Method Preferences')
|
| 118 |
+
fig.update_layout(xaxis_title='Payment Method', yaxis_title='Number of Transactions')
|
| 119 |
+
st.plotly_chart(fig)
|
| 120 |
+
|
| 121 |
+
# Button to send report to ChatGPT
|
| 122 |
+
if st.button("Executive Report - Payment Method Preferences"):
|
| 123 |
+
send_report("Payment Method Preferences", payment_method_counts_converted)
|
| 124 |
+
|
| 125 |
+
# Calculate the total amount of payments for the most frequent customers
|
| 126 |
+
top_customers = df_converted['CustomerName'].value_counts().index[:10]
|
| 127 |
+
total_amounts = df_converted[df_converted['CustomerName'].isin(top_customers)].groupby('CustomerName', observed=True)[
|
| 128 |
+
'Amount'].sum().reset_index()
|
| 129 |
+
|
| 130 |
+
# Plot the total payment amounts for the most frequent customers
|
| 131 |
+
st.subheader('Total Payment Amounts for Most Frequent Customers')
|
| 132 |
+
fig = px.bar(total_amounts, x='CustomerName', y='Amount', title='Total Payment Amounts for Most Frequent Customers')
|
| 133 |
+
fig.update_layout(xaxis_title='Customer Name', yaxis_title='Total Transaction Amount ($)', yaxis_tickprefix='$')
|
| 134 |
+
st.plotly_chart(fig)
|
| 135 |
+
|
| 136 |
+
# Button to send report to ChatGPT
|
| 137 |
+
if st.button("Executive Report - Total Payment Amounts for Most Frequent Customers"):
|
| 138 |
+
send_report("Total Payment Amounts for Most Frequent Customers", total_amounts)
|
| 139 |
+
|
| 140 |
+
# Simulated chat with ChatGPT
|
| 141 |
+
if 'chat_with_gpt' in st.session_state:
|
| 142 |
+
st.subheader("Chat with ChatGPT")
|
| 143 |
+
st.write(st.session_state['chat_with_gpt'])
|
| 144 |
+
user_input = st.text_input("Your question for ChatGPT:", key="chat_input")
|
| 145 |
+
if st.button("Send"):
|
| 146 |
+
if user_input:
|
| 147 |
+
summary = analyze_transaction_data(df_converted)
|
| 148 |
+
prompt = f"""
|
| 149 |
+
Transaction Data Insights:
|
| 150 |
+
1. Total Transactions: {summary['total_transactions']}
|
| 151 |
+
2. Total Amount Transacted: ${summary['total_amount']:.2f}
|
| 152 |
+
3. Average Transaction Amount: ${summary['average_amount']:.2f}
|
| 153 |
+
4. Maximum Transaction Amount: ${summary['max_amount']:.2f}
|
| 154 |
+
5. Minimum Transaction Amount: ${summary['min_amount']:.2f}
|
| 155 |
+
6. Median Transaction Amount: ${summary['median_amount']:.2f}
|
| 156 |
+
|
| 157 |
+
User Question: {user_input}
|
| 158 |
+
"""
|
| 159 |
+
response = get_chatgpt_response(prompt)
|
| 160 |
+
st.write(f"ChatGPT Response: {response}")
|
| 161 |
+
else:
|
| 162 |
+
st.write("Please enter a question for ChatGPT.")
|