masturakinan commited on
Commit
1f21904
Β·
verified Β·
1 Parent(s): ee29449

feat: add intro video

Browse files
Files changed (3) hide show
  1. .gitattributes +1 -0
  2. app.py +219 -216
  3. intro.mp4 +3 -0
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ intro.mp4 filter=lfs diff=lfs merge=lfs -text
app.py CHANGED
@@ -1,216 +1,219 @@
1
- import os
2
- import uuid
3
- import streamlit as st
4
- import matplotlib.pyplot as plt
5
- import pandas as pd
6
- import requests
7
-
8
- st.set_page_config(page_title="Miragic Sales Pilot", page_icon="πŸ“Š")
9
-
10
- # Display logo and title in a horizontal layout
11
- col1, col2 = st.columns([1, 4])
12
- with col1:
13
- st.image("logo.png", width=100) # Adjust width as needed
14
- with col2:
15
- st.title("Miragic Sales Pilot")
16
-
17
-
18
- sales_file = None
19
- # st.write("Enter comma-separated numbers (e.g. `10, 20, 30`) to generate a bar chart.")
20
-
21
- def upload_sales_data(data: pd.DataFrame):
22
- upload_url = os.environ['upload_url']
23
- file_name = 'sample.csv'
24
- files = {'file': (file_name, data.to_csv(index=False))}
25
- response = requests.post(upload_url, files=files)
26
- return response.json()
27
-
28
- def analyze_sales_data(sales_file: str, prompt: str):
29
- analyze_url = os.environ['analyze_url']
30
-
31
- data = {'filename': sales_file, 'question': prompt}
32
- response = requests.post(analyze_url, json=data)
33
- return response.json()
34
-
35
- # Sidebar Menu
36
- with st.sidebar:
37
- # TODO Name for product
38
- # st.title("πŸ“Š Miragic Sales Pilot")
39
- # st.subheader("Intelligent sales assistant")
40
- st.markdown("""
41
- ### πŸ“ Instructions
42
- 1. **Upload your data**: Use the file uploader below to upload your sales data
43
- 2. **File format**: Your file should be a CSV containing:
44
- - A 'Date' column
45
- - A 'Sales' column
46
- 3. **Sample file**: Download our sample CSV below to see the expected format
47
-
48
- ### πŸ” What this app does
49
- - Analyzes your sales data
50
- - Generates visualizations
51
- - Provides intelligent insights
52
-
53
- ### ⚠️ Note
54
- Make sure your data is clean and follows the required format to get the best results.
55
- """)
56
- uploaded_file = st.file_uploader("", type=["csv", "excel"])
57
- if uploaded_file is not None:
58
- date_found = False
59
- sales_found = False
60
- df = pd.read_csv(uploaded_file, parse_dates=True)
61
- for column in df.columns:
62
- if 'Date' in column:
63
- date_found = True
64
- if 'Sales' in column:
65
- sales_found = True
66
- if(date_found == False or sales_found == False):
67
- st.error('Please upload a csv containing both Date and Sales...')
68
- st.stop()
69
-
70
- response = upload_sales_data(df)
71
- sales_file = response['csv_file']
72
-
73
- st.success("File uploaded successfully!")
74
- st.write("Your uploaded data:")
75
- st.write(df)
76
-
77
- # df = drop(df)
78
- # df = date_format(df)
79
- # merge_sort(df)
80
- # series = group_to_three(df)
81
-
82
- st.session_state.uploaded = True
83
-
84
- with open(os.path.join(os.path.dirname(__file__), 'sample.csv'), 'rb') as f:
85
- st.download_button("Download our sample CSV", f, file_name='sample.csv')
86
-
87
- st.markdown("""![Visitors](https://api.visitorbadge.io/api/combined?path=https%3A%2F%2Fhuggingface.co%2Fspaces%2FMiragic-AI%2FMiragic-Sales-Pilot&labelColor=%2337d67a&countColor=%23ff8a65&style=plastic&labelStyle=upper)""")
88
-
89
-
90
- # Initialize chat history in session state
91
- if "messages" not in st.session_state:
92
- st.session_state.messages = []
93
- if "greetings" not in st.session_state:
94
- st.session_state.greetings = False
95
-
96
- # Display chat history
97
- for msg in st.session_state.messages:
98
- with st.chat_message(msg["role"]):
99
- if isinstance(msg["content"], str):
100
- st.markdown(msg["content"])
101
- else:
102
- st.pyplot(msg["content"])
103
-
104
- # Greet user
105
- if not st.session_state.greetings:
106
- with st.chat_message("assistant"):
107
- intro = "Hey! As a sales analyst, I can analyze and forecast sales using your historical excel or csv data."
108
- st.markdown(intro)
109
- # Add assistant response to chat history
110
- st.session_state.messages.append({"role": "assistant", "content": intro})
111
- st.session_state.greetings = True
112
-
113
- # Example prompts
114
- example_prompts = [
115
- "Top 10 best selling products",
116
- "Top 10 worst selling products",
117
- "Sales forecast for next month",
118
- "How many items were sold in total each month?",
119
- "What are the projected sales for next month?",
120
- "How many unique product categories are there?",
121
- ]
122
-
123
- example_prompts_help = [
124
- "Search for the best selling products",
125
- "Search for the worst selling products",
126
- "Search for the projected sales for next month",
127
- "Search for the number of items sold in total each month",
128
- "Search for the sales forecast for next month",
129
- "Search for the number of unique product categories",
130
- ]
131
-
132
- button_cols = st.columns(3)
133
- button_cols_2 = st.columns(3)
134
-
135
- button_pressed = ""
136
-
137
- if button_cols[0].button(example_prompts[0], help=example_prompts_help[0]):
138
- button_pressed = example_prompts[0]
139
- elif button_cols[1].button(example_prompts[1], help=example_prompts_help[1]):
140
- button_pressed = example_prompts[1]
141
- elif button_cols[2].button(example_prompts[2], help=example_prompts_help[2]):
142
- button_pressed = example_prompts[2]
143
-
144
- elif button_cols_2[0].button(example_prompts[3], help=example_prompts_help[3]):
145
- button_pressed = example_prompts[3]
146
- elif button_cols_2[1].button(example_prompts[4], help=example_prompts_help[4]):
147
- button_pressed = example_prompts[4]
148
- elif button_cols_2[2].button(example_prompts[5], help=example_prompts_help[5]):
149
- button_pressed = example_prompts[5]
150
-
151
- # Chat input
152
- if prompt := (st.chat_input("Ask me anything about your sales data") or button_pressed):
153
- # Add user message
154
- st.session_state.messages.append({"role": "user", "content": prompt})
155
- with st.chat_message("user"):
156
- st.markdown(prompt)
157
-
158
- if sales_file is None:
159
- st.error("Please upload a file first")
160
- st.stop()
161
-
162
- response = analyze_sales_data(sales_file, prompt)
163
- print("==========>: ", response)
164
-
165
- if response['status'] == 'success':
166
- dummy_response = response['result'][0]
167
-
168
- try:
169
- # Process input
170
- # values = list(map(int, prompt.strip().split(',')))
171
- # labels = [f"Item {i+1}" for i in range(len(values))]
172
- values = [item['y_axis'] for item in dummy_response['visualization']['data']]
173
- labels = [item['x_axis'] for item in dummy_response['visualization']['data']]
174
-
175
- # Create chart
176
- fig, ax = plt.subplots()
177
- if dummy_response['visualization']['type'] == 'line_chart':
178
- ax.plot(labels, values, marker='o', color="lightcoral")
179
- else:
180
- ax.bar(labels, values, color="lightcoral")
181
- plt.xticks(rotation=45, ha='right')
182
- ax.set_title(dummy_response['visualization']['config']['title'])
183
- ax.set_ylabel(dummy_response['visualization']['config']['y_axis'])
184
- ax.set_xlabel(dummy_response['visualization']['config']['x_axis'])
185
-
186
- # Add value labels on top of each bar
187
- for i, v in enumerate(values):
188
- ax.text(i, v, f'{v:,.2f}', ha='center', va='bottom')
189
-
190
- # Generate analysis message
191
- analysis = "πŸ“Š Insights:\n"
192
- for insight in dummy_response['insights']:
193
- analysis += f"- {insight}\n"
194
-
195
- # Add bot replies
196
- st.session_state.messages.append({"role": "assistant", "content": fig})
197
- st.session_state.messages.append({"role": "assistant", "content": analysis})
198
- with st.chat_message("assistant"):
199
- st.pyplot(fig)
200
- st.markdown(analysis)
201
-
202
- except Exception as e:
203
- err_msg = f"❌ Error: {str(e)} β€” please enter only comma-separated numbers."
204
- st.session_state.messages.append({"role": "assistant", "content": err_msg})
205
- with st.chat_message("assistant"):
206
- st.markdown(err_msg)
207
- else:
208
- err_msg = "❌ Error: Unable to process the request. Here are some example queries you can try:\n\n"
209
- for candidate in response['candidate_questions']:
210
- err_msg += f"- {candidate}\n"
211
-
212
- st.session_state.messages.append({"role": "assistant", "content": err_msg})
213
- with st.chat_message("assistant"):
214
- st.markdown(err_msg)
215
-
216
- st.rerun()
 
 
 
 
1
+ import os
2
+ import uuid
3
+ import streamlit as st
4
+ import matplotlib.pyplot as plt
5
+ import pandas as pd
6
+ import requests
7
+
8
+ st.set_page_config(page_title="Miragic Sales Pilot", page_icon="πŸ“Š")
9
+
10
+ # Display logo and title in a horizontal layout
11
+ col1, col2 = st.columns([1, 4])
12
+ with col1:
13
+ st.image("logo.png", width=100) # Adjust width as needed
14
+ with col2:
15
+ st.title("Miragic Sales Pilot")
16
+
17
+
18
+ sales_file = None
19
+ # st.write("Enter comma-separated numbers (e.g. `10, 20, 30`) to generate a bar chart.")
20
+
21
+ def upload_sales_data(data: pd.DataFrame):
22
+ upload_url = os.environ['upload_url']
23
+ file_name = 'sample.csv'
24
+ files = {'file': (file_name, data.to_csv(index=False))}
25
+ response = requests.post(upload_url, files=files)
26
+ return response.json()
27
+
28
+ def analyze_sales_data(sales_file: str, prompt: str):
29
+ analyze_url = os.environ['analyze_url']
30
+
31
+ data = {'filename': sales_file, 'question': prompt}
32
+ response = requests.post(analyze_url, json=data)
33
+ return response.json()
34
+
35
+ # Sidebar Menu
36
+ with st.sidebar:
37
+ # TODO Name for product
38
+ # st.title("πŸ“Š Miragic Sales Pilot")
39
+ # st.subheader("Intelligent sales assistant")
40
+ st.markdown("""
41
+ ### πŸ“ Instructions
42
+ 1. **Upload your data**: Use the file uploader below to upload your sales data
43
+ 2. **File format**: Your file should be a CSV containing:
44
+ - A 'Date' column
45
+ - A 'Sales' column
46
+ 3. **Sample file**: Download our sample CSV below to see the expected format
47
+
48
+ ### πŸ” What this app does
49
+ - Analyzes your sales data
50
+ - Generates visualizations
51
+ - Provides intelligent insights
52
+
53
+ ### ⚠️ Note
54
+ Make sure your data is clean and follows the required format to get the best results.
55
+ """)
56
+ uploaded_file = st.file_uploader("", type=["csv", "excel"])
57
+ if uploaded_file is not None:
58
+ date_found = False
59
+ sales_found = False
60
+ df = pd.read_csv(uploaded_file, parse_dates=True)
61
+ for column in df.columns:
62
+ if 'Date' in column:
63
+ date_found = True
64
+ if 'Sales' in column:
65
+ sales_found = True
66
+ if(date_found == False or sales_found == False):
67
+ st.error('Please upload a csv containing both Date and Sales...')
68
+ st.stop()
69
+
70
+ response = upload_sales_data(df)
71
+ sales_file = response['csv_file']
72
+
73
+ st.success("File uploaded successfully!")
74
+ st.write("Your uploaded data:")
75
+ st.write(df)
76
+
77
+ # df = drop(df)
78
+ # df = date_format(df)
79
+ # merge_sort(df)
80
+ # series = group_to_three(df)
81
+
82
+ st.session_state.uploaded = True
83
+
84
+ with open(os.path.join(os.path.dirname(__file__), 'sample.csv'), 'rb') as f:
85
+ st.download_button("Download our sample CSV", f, file_name='sample.csv')
86
+
87
+ st.markdown("""![Visitors](https://api.visitorbadge.io/api/combined?path=https%3A%2F%2Fhuggingface.co%2Fspaces%2FMiragic-AI%2FMiragic-Sales-Pilot&labelColor=%2337d67a&countColor=%23ff8a65&style=plastic&labelStyle=upper)""")
88
+
89
+ col1, col2, col3 = st.columns([0.01, 0.98, 0.01])
90
+
91
+ col2.video("intro.mp4")
92
+
93
+ # Initialize chat history in session state
94
+ if "messages" not in st.session_state:
95
+ st.session_state.messages = []
96
+ if "greetings" not in st.session_state:
97
+ st.session_state.greetings = False
98
+
99
+ # Display chat history
100
+ for msg in st.session_state.messages:
101
+ with st.chat_message(msg["role"]):
102
+ if isinstance(msg["content"], str):
103
+ st.markdown(msg["content"])
104
+ else:
105
+ st.pyplot(msg["content"])
106
+
107
+ # Greet user
108
+ if not st.session_state.greetings:
109
+ with st.chat_message("assistant"):
110
+ intro = "Hey! As a sales analyst, I can analyze and forecast sales using your historical excel or csv data."
111
+ st.markdown(intro)
112
+ # Add assistant response to chat history
113
+ st.session_state.messages.append({"role": "assistant", "content": intro})
114
+ st.session_state.greetings = True
115
+
116
+ # Example prompts
117
+ example_prompts = [
118
+ "Top 10 best selling products",
119
+ "Top 10 worst selling products",
120
+ "Sales forecast for next month",
121
+ "How many items were sold in total each month?",
122
+ "What are the projected sales for next month?",
123
+ "How many unique product categories are there?",
124
+ ]
125
+
126
+ example_prompts_help = [
127
+ "Search for the best selling products",
128
+ "Search for the worst selling products",
129
+ "Search for the projected sales for next month",
130
+ "Search for the number of items sold in total each month",
131
+ "Search for the sales forecast for next month",
132
+ "Search for the number of unique product categories",
133
+ ]
134
+
135
+ button_cols = st.columns(3)
136
+ button_cols_2 = st.columns(3)
137
+
138
+ button_pressed = ""
139
+
140
+ if button_cols[0].button(example_prompts[0], help=example_prompts_help[0]):
141
+ button_pressed = example_prompts[0]
142
+ elif button_cols[1].button(example_prompts[1], help=example_prompts_help[1]):
143
+ button_pressed = example_prompts[1]
144
+ elif button_cols[2].button(example_prompts[2], help=example_prompts_help[2]):
145
+ button_pressed = example_prompts[2]
146
+
147
+ elif button_cols_2[0].button(example_prompts[3], help=example_prompts_help[3]):
148
+ button_pressed = example_prompts[3]
149
+ elif button_cols_2[1].button(example_prompts[4], help=example_prompts_help[4]):
150
+ button_pressed = example_prompts[4]
151
+ elif button_cols_2[2].button(example_prompts[5], help=example_prompts_help[5]):
152
+ button_pressed = example_prompts[5]
153
+
154
+ # Chat input
155
+ if prompt := (st.chat_input("Ask me anything about your sales data") or button_pressed):
156
+ # Add user message
157
+ st.session_state.messages.append({"role": "user", "content": prompt})
158
+ with st.chat_message("user"):
159
+ st.markdown(prompt)
160
+
161
+ if sales_file is None:
162
+ st.error("Please upload a file first")
163
+ st.stop()
164
+
165
+ response = analyze_sales_data(sales_file, prompt)
166
+ print("==========>: ", response)
167
+
168
+ if response['status'] == 'success':
169
+ dummy_response = response['result'][0]
170
+
171
+ try:
172
+ # Process input
173
+ # values = list(map(int, prompt.strip().split(',')))
174
+ # labels = [f"Item {i+1}" for i in range(len(values))]
175
+ values = [item['y_axis'] for item in dummy_response['visualization']['data']]
176
+ labels = [item['x_axis'] for item in dummy_response['visualization']['data']]
177
+
178
+ # Create chart
179
+ fig, ax = plt.subplots()
180
+ if dummy_response['visualization']['type'] == 'line_chart':
181
+ ax.plot(labels, values, marker='o', color="lightcoral")
182
+ else:
183
+ ax.bar(labels, values, color="lightcoral")
184
+ plt.xticks(rotation=45, ha='right')
185
+ ax.set_title(dummy_response['visualization']['config']['title'])
186
+ ax.set_ylabel(dummy_response['visualization']['config']['y_axis'])
187
+ ax.set_xlabel(dummy_response['visualization']['config']['x_axis'])
188
+
189
+ # Add value labels on top of each bar
190
+ for i, v in enumerate(values):
191
+ ax.text(i, v, f'{v:,.2f}', ha='center', va='bottom')
192
+
193
+ # Generate analysis message
194
+ analysis = "πŸ“Š Insights:\n"
195
+ for insight in dummy_response['insights']:
196
+ analysis += f"- {insight}\n"
197
+
198
+ # Add bot replies
199
+ st.session_state.messages.append({"role": "assistant", "content": fig})
200
+ st.session_state.messages.append({"role": "assistant", "content": analysis})
201
+ with st.chat_message("assistant"):
202
+ st.pyplot(fig)
203
+ st.markdown(analysis)
204
+
205
+ except Exception as e:
206
+ err_msg = f"❌ Error: {str(e)} β€” please enter only comma-separated numbers."
207
+ st.session_state.messages.append({"role": "assistant", "content": err_msg})
208
+ with st.chat_message("assistant"):
209
+ st.markdown(err_msg)
210
+ else:
211
+ err_msg = "❌ Error: Unable to process the request. Here are some example queries you can try:\n\n"
212
+ for candidate in response['candidate_questions']:
213
+ err_msg += f"- {candidate}\n"
214
+
215
+ st.session_state.messages.append({"role": "assistant", "content": err_msg})
216
+ with st.chat_message("assistant"):
217
+ st.markdown(err_msg)
218
+
219
+ st.rerun()
intro.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b0ecfb205220f88f8b21c3c3d4fb4f7e6578153178088a07040b4c9a4aa7c07c
3
+ size 27648329