soroushsrd commited on
Commit
18fb305
·
verified ·
1 Parent(s): ecdf3a7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +160 -97
app.py CHANGED
@@ -1,99 +1,162 @@
1
  import streamlit as st
2
  import pandas as pd
3
- import matplotlib.pyplot as plt
4
-
5
- # Load data
6
- data = pd.read_csv('customers.csv')
7
-
8
-
9
- # Function to display basic data information
10
- def display_data_info(data):
11
- st.write("### Data Information")
12
- st.write(data.info())
13
- st.write("### Data Description")
14
- st.write(data.describe())
15
-
16
-
17
- # Function to plot data
18
- def plot_data(data, column, chart_type):
19
- if column == 'Net Sale':
20
- data[column] = data[column].replace('[\$,]', '', regex=True).str.strip()
21
- data[column] = pd.to_numeric(data[column], errors='coerce')
22
- elif column == 'Cost':
23
- data[column] = data[column].replace('[\$,]', '', regex=True).str.strip()
24
- data[column] = pd.to_numeric(data[column], errors='coerce')
25
- elif column == 'Gross Profit':
26
- data[column] = data[column].replace('[\$,]', '', regex=True).str.strip()
27
- data[column] = pd.to_numeric(data[column], errors='coerce')
28
- elif column == ' AVG Inv. ':
29
- data[column] = data[column].replace('[\$,]', '', regex=True).str.strip()
30
- data[column] = pd.to_numeric(data[column], errors='coerce')
31
-
32
- grouped_data = data.groupby('Mail ZIP')[column].sum()
33
-
34
- plt.figure(figsize=(10, 6))
35
- if chart_type == 'Bar Chart':
36
- grouped_data.plot(kind='bar', color='skyblue')
37
- elif chart_type == 'Scatter Plot':
38
- plt.scatter(grouped_data.index, grouped_data.values, color='skyblue')
39
- elif chart_type == 'Line Chart':
40
- grouped_data.plot(kind='line', color='skyblue')
41
- plt.title(f'{column} by ZIP Code')
42
- plt.xlabel('ZIP Code')
43
- plt.ylabel(column)
44
- plt.xticks(rotation=45)
45
- st.pyplot(plt)
46
-
47
-
48
- # Function to plot gross margin by ZIP Code
49
- def gross_margin_by_zip_code(data, chart_type):
50
- margin_by_zip = data.groupby('Mail ZIP')['Gross Margin'].mean()
51
- plt.figure(figsize=(10, 6))
52
- if chart_type == 'Bar Chart':
53
- margin_by_zip.plot(kind='bar', color='orange')
54
- elif chart_type == 'Scatter Plot':
55
- plt.scatter(margin_by_zip.index, margin_by_zip.values, color='orange')
56
- elif chart_type == 'Line Chart':
57
- margin_by_zip.plot(kind='line', color='orange')
58
- plt.title('Gross Margin by ZIP Code')
59
- plt.xlabel('ZIP Code')
60
- plt.ylabel('Gross Margin (%)')
61
- plt.xticks(rotation=45)
62
- st.pyplot(plt)
63
-
64
-
65
- # Streamlit App
66
- def main():
67
- st.title("Sales and Cost Dashboard")
68
-
69
- # Sidebar options
70
- st.sidebar.title("Options")
71
- options = st.sidebar.radio(
72
- "Select a Report", [
73
- 'Data Information',
74
- 'Net Sales by ZIP Code',
75
- 'Cost by ZIP Code',
76
- 'Gross Profit by ZIP Code',
77
- 'Gross Margin by ZIP Code',
78
- 'Average Invoice by ZIP Code'
79
- ]
80
- )
81
-
82
- chart_type = st.sidebar.selectbox("Select Chart Type", ['Bar Chart', 'Scatter Plot', 'Line Chart'])
83
-
84
- if options == 'Data Information':
85
- display_data_info(data)
86
- elif options == 'Net Sales by ZIP Code':
87
- plot_data(data, 'Net Sale', chart_type)
88
- elif options == 'Cost by ZIP Code':
89
- plot_data(data, 'Cost', chart_type)
90
- elif options == 'Gross Profit by ZIP Code':
91
- plot_data(data, 'Gross Profit', chart_type)
92
- elif options == 'Gross Margin by ZIP Code':
93
- gross_margin_by_zip_code(data, chart_type)
94
- elif options == 'Average Invoice by ZIP Code':
95
- plot_data(data, ' AVG Inv. ', chart_type)
96
-
97
-
98
- if __name__ == '__main__':
99
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.")