rmpro / app.py
soroushsrd's picture
Update app.py
1add288 verified
import streamlit as st
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import openai
# Add your OpenAI API key here
openai.api_key = st.secrets["OPEN_AI_KEY"]
st.title("Transaction Analysis")
# Load the data
df_converted = pd.read_csv('payments_optimized.csv')
# Convert CreatedDate to datetime
df_converted['CreatedDate'] = pd.to_datetime(df_converted['CreatedDate'])
# Function to analyze transaction data
def analyze_transaction_data(df):
summary = {
"total_transactions": len(df),
"total_amount": df['Amount'].sum(),
"average_amount": df['Amount'].mean(),
"max_amount": df['Amount'].max(),
"min_amount": df['Amount'].min(),
"median_amount": df['Amount'].median(),
"transaction_trend": df.groupby(df['CreatedDate'].dt.to_period("M"))['Amount'].sum().tolist()
}
return summary
# Function to get response from ChatGPT
def get_chatgpt_response(prompt):
response = openai.ChatCompletion.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": prompt}
],
max_tokens=500
)
return response.choices[0].message['content'].strip()
# Function to send report to ChatGPT
def send_report(plot_title, data):
summary = analyze_transaction_data(data)
prompt = f"""
Transaction Data Insights:
1. Total Transactions: {summary['total_transactions']}
2. Total Amount Transacted: ${summary['total_amount']:.2f}
3. Average Transaction Amount: ${summary['average_amount']:.2f}
4. Maximum Transaction Amount: ${summary['max_amount']:.2f}
5. Minimum Transaction Amount: ${summary['min_amount']:.2f}
6. Median Transaction Amount: ${summary['median_amount']:.2f}
Provide strategic ideas based on this data.
"""
response = get_chatgpt_response(prompt)
st.session_state['chat_with_gpt'] = f"Report for {plot_title} sent to ChatGPT. Data Summary: {summary}\n\nChatGPT Response: {response}"
st.experimental_rerun()
# Plotting Transaction Amounts over Time with clickable dots
st.subheader('Transaction Amounts Over Time')
fig = px.scatter(
df_converted,
x='CreatedDate',
y='Amount',
custom_data=['CustomerName', 'PaymentMethod', 'Store', 'InvoiceType', 'TransactionType'],
title='Transaction Amounts Over Time'
)
fig.update_traces(
marker=dict(size=10),
selector=dict(mode='markers'),
hovertemplate=(
'Date: %{x}<br>'
'Amount: $%{y}<br>'
'Customer: %{customdata[0]}<br>'
'Payment Method: %{customdata[1]}<br>'
'Store: %{customdata[2]}<br>'
'Invoice Type: %{customdata[3]}<br>'
'Transaction Type: %{customdata[4]}<br>'
)
)
# Convert Plotly figure to a FigureWidget
fig_widget = go.FigureWidget(fig)
# Function to display click data
def display_click_data(trace, points, state):
if points.point_inds:
point = points.point_inds[0]
selected_data = df_converted.iloc[point]
st.session_state['selected_point'] = selected_data.to_dict()
st.experimental_rerun()
# Add click event handler
fig_widget.data[0].on_click(display_click_data)
# Display the plot
st.plotly_chart(fig_widget)
# Display details when a point is clicked
if 'selected_point' in st.session_state:
st.write('Details for selected transaction:')
st.write(st.session_state['selected_point'])
# Button to send report to ChatGPT
if st.button("Executive Report - Transaction Amounts Over Time"):
send_report("Transaction Amounts Over Time", df_converted[
['CreatedDate', 'Amount', 'CustomerName', 'PaymentMethod', 'Store', 'InvoiceType', 'TransactionType']]
)
# Plotting Payment Method Preferences
st.subheader('Payment Method Preferences')
payment_method_counts_converted = df_converted['PaymentMethod'].value_counts().reset_index()
payment_method_counts_converted.columns = ['PaymentMethod', 'Count']
fig = px.bar(payment_method_counts_converted, x='PaymentMethod', y='Count', title='Payment Method Preferences')
fig.update_layout(xaxis_title='Payment Method', yaxis_title='Number of Transactions')
st.plotly_chart(fig)
# Button to send report to ChatGPT
if st.button("Executive Report - Payment Method Preferences"):
send_report("Payment Method Preferences", payment_method_counts_converted)
# Calculate the total amount of payments for the most frequent customers
top_customers = df_converted['CustomerName'].value_counts().index[:10]
total_amounts = df_converted[df_converted['CustomerName'].isin(top_customers)].groupby('CustomerName', observed=True)[
'Amount'].sum().reset_index()
# Plot the total payment amounts for the most frequent customers
st.subheader('Total Payment Amounts for Most Frequent Customers')
fig = px.bar(total_amounts, x='CustomerName', y='Amount', title='Total Payment Amounts for Most Frequent Customers')
fig.update_layout(xaxis_title='Customer Name', yaxis_title='Total Transaction Amount ($)', yaxis_tickprefix='$')
st.plotly_chart(fig)
# Button to send report to ChatGPT
if st.button("Executive Report - Total Payment Amounts for Most Frequent Customers"):
send_report("Total Payment Amounts for Most Frequent Customers", total_amounts)
# Simulated chat with ChatGPT
if 'chat_with_gpt' in st.session_state:
st.subheader("Chat with ChatGPT")
st.write(st.session_state['chat_with_gpt'])
user_input = st.text_input("Your question for ChatGPT:", key="chat_input")
if st.button("Send"):
if user_input:
summary = analyze_transaction_data(df_converted)
prompt = f"""
Transaction Data Insights:
1. Total Transactions: {summary['total_transactions']}
2. Total Amount Transacted: ${summary['total_amount']:.2f}
3. Average Transaction Amount: ${summary['average_amount']:.2f}
4. Maximum Transaction Amount: ${summary['max_amount']:.2f}
5. Minimum Transaction Amount: ${summary['min_amount']:.2f}
6. Median Transaction Amount: ${summary['median_amount']:.2f}
User Question: {user_input}
"""
response = get_chatgpt_response(prompt)
st.write(f"ChatGPT Response: {response}")
else:
st.write("Please enter a question for ChatGPT.")