naveenseth commited on
Commit
a7d01d0
·
verified ·
1 Parent(s): 19cdbe9

api key edited

Browse files
Files changed (1) hide show
  1. app.py +186 -186
app.py CHANGED
@@ -1,186 +1,186 @@
1
- import streamlit as st
2
- import pandas as pd
3
- from pandasai import SmartDataframe
4
- from pandasai import SmartDatalake # Added for multiple datasets
5
- from pandasai.llm import OpenAI
6
- from pandasai.responses.streamlit_response import StreamlitResponse
7
- import os
8
- from pandasai.helpers.openai_info import get_openai_callback
9
- import openpyxl
10
- from openpyxl import Workbook
11
- import time
12
-
13
- # Initialize session state for storing prompts
14
- if "previous_prompts" not in st.session_state:
15
- st.session_state.previous_prompts = []
16
-
17
- # Define FAQs categorized by function
18
- frequently_asked_prompts_by_function = {
19
- 'Sales': [
20
- "What products have shown the highest performance by revenue?",
21
- "What products have shown the highest performance by volume?",
22
- "Which are the best performing categories?",
23
- "Which products generate the lowest revenue?"
24
- ],
25
- 'Marketing': [
26
- "Which eCommerce platform or channel has generated the highest revenue for product sales?",
27
- "Which style of product exhibits average order values?",
28
- "What are the average order values and profit margins with the top 10 selling products in each channel?",
29
- "Which specific product categories or types dominate the top-selling SKUs in terms of revenue?",
30
- ],
31
- 'Customer Support': [
32
- "What is the average resolution time for customer queries?",
33
- "Which issues are most frequently reported by customers?",
34
- "What is the customer satisfaction score for each support channel?",
35
- "Which product categories generate the most support tickets?"
36
- ]
37
- }
38
-
39
- # Page title
40
- st.title("Retail Co-Pilot")
41
- st.write("Ask questions about your dataset using conversational AI.")
42
-
43
- # Left sidebar with file uploader at the top
44
- with st.sidebar:
45
- st.subheader("Upload Your Datasets")
46
- uploaded_files = st.file_uploader("Choose CSV/Excel files", type=["xlsx", "csv"], accept_multiple_files=True)
47
-
48
- if uploaded_files:
49
- st.write(f"{len(uploaded_files)} file(s) uploaded.")
50
-
51
- st.write("---") # Separator line
52
-
53
- # Select function
54
- st.subheader("Select Function")
55
- selected_function = st.selectbox("Choose a function", list(frequently_asked_prompts_by_function.keys()))
56
-
57
- # Expandable FAQs Section
58
- with st.expander("Frequently Asked Prompts"):
59
- st.write(f"Here are some frequently asked questions for the {selected_function} function:")
60
- for i, prompt in enumerate(frequently_asked_prompts_by_function[selected_function], 1):
61
- st.write(f"{i}. {prompt}")
62
-
63
- # Expandable Previous Prompts Section
64
- with st.expander("Previous Prompts"):
65
- if st.session_state.previous_prompts:
66
- for i, prompt in enumerate(st.session_state.previous_prompts, 1):
67
- st.write(f"{i}. {prompt}")
68
- else:
69
- st.write("No questions asked yet.")
70
-
71
- # Main content area with Ask button
72
- st.write("---") # Separator line
73
- st.subheader("Ask a Question")
74
- temp_query = st.text_input("Enter your question:")
75
-
76
- # Create a container to place the ask button next to the file uploader on the right
77
- col1, col2 = st.columns([3, 1]) # Adjust the column width as needed
78
-
79
- # Center : Ask button
80
- with col1:
81
- if st.button("Ask", key="ask_btn"):
82
- if temp_query:
83
- st.session_state.previous_prompts.append(temp_query)
84
-
85
- # Display query dynamically below the columns
86
- st.subheader("Your Query")
87
- st.write(temp_query if temp_query else "No query entered yet.")
88
-
89
-
90
- # Initialize the LLM
91
- api_key = "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"
92
- # Add your OpenAI API key here
93
- llm = OpenAI(api_token=api_key, temperature=0, seed=42, model="gpt-3.5-turbo")
94
- os.environ["PANDASAI_API_KEY"] = api_key
95
-
96
- EXCEL_FILE_PATH = "callback_data.xlsx"
97
- user_defined_path = os.getcwd()
98
- udp = os.path.join(user_defined_path, "exports", "charts") # Define the current working directory
99
-
100
- # Function to parse callback output
101
- def parse_callback_output(cb) -> dict:
102
- output_lines = str(cb).split("\n")
103
- parsed_output = {
104
- "total_tokens": int(output_lines[0].split(":")[1].strip()),
105
- "prompt_tokens": int(output_lines[1].split(":")[1].strip()),
106
- "completion_tokens": int(output_lines[2].split(":")[1].strip()),
107
- "total_cost": float(output_lines[3].split(":")[1].strip().replace("$", "").strip()),
108
- }
109
- return parsed_output
110
-
111
- # Additional sections unchanged...
112
-
113
- # Function to append data to Excel
114
- def append_to_excel(file_path: str, data: dict):
115
- if not os.path.exists(file_path):
116
- wb = Workbook()
117
- ws = wb.active
118
- ws.append(["Total Tokens", "Prompt Tokens", "Completion Tokens", "Total Cost (USD)"])
119
- wb.save(file_path)
120
-
121
- wb = openpyxl.load_workbook(file_path)
122
- ws = wb.active
123
- ws.append([data["total_tokens"], data["prompt_tokens"], data["completion_tokens"], data["total_cost"]])
124
- wb.save(file_path)
125
-
126
- # Prepare datasets for SmartDatalake
127
- if uploaded_files:
128
- dataframes = []
129
- for uploaded_file in uploaded_files:
130
- try:
131
- if uploaded_file.name.endswith('.csv'):
132
- df = pd.read_csv(uploaded_file)
133
- elif uploaded_file.name.endswith('.xlsx'):
134
- df = pd.read_excel(uploaded_file)
135
- else:
136
- st.error(f"Unsupported file format: {uploaded_file.name}")
137
- continue
138
-
139
- dataframes.append(df) # Collect DataFrames
140
- success_message = st.success(f"File '{uploaded_file.name}' successfully loaded.")
141
- time.sleep(2) # Keep the message for 2 seconds
142
- success_message.empty() # Remove the message after 2 seconds
143
-
144
- except Exception as e:
145
- st.error(f"Error loading file '{uploaded_file.name}': {e}")
146
-
147
- # Use SmartDatalake for multiple datasets
148
- sales_data = SmartDatalake(dataframes, config={"llm": llm})
149
-
150
- else:
151
- sales_data = None # If no files uploaded, set to None
152
-
153
-
154
- ## Prompt Template
155
- prompt_template = '''You are a retail co-pilot, a master of sales with unparalleled expertise in providing the best solutions for any questions related to retail,
156
- both general and specific to uploaded Excel files. Your goal is to assist users in optimizing their sales strategies,
157
- understanding market trends, and making data-driven decisions. You should always be insightful, professional, and proactive in offering valuable recommendations and
158
- provide a clear and formatted response for the following query. Include spaces between sentences and highlight key points clearly{user_query}'''
159
-
160
-
161
-
162
- # Handle user queries
163
- if temp_query:
164
- with st.spinner("Thinking..."):
165
- try:
166
- # Get AI response
167
- with get_openai_callback() as cb:
168
- # using propmt template and temp query to chat with AI
169
- formatted_query = prompt_template.format(user_query=temp_query)
170
- response = sales_data.chat(formatted_query)
171
- track = parse_callback_output(cb)
172
- append_to_excel(EXCEL_FILE_PATH, track)
173
- if isinstance(response,str) and os.path.exists(response):
174
- # If response is an image path
175
- # Change here: Replaced use_column_width with use_container_width
176
- st.image(response, caption="Generated Chart",) #use_container_width=True)) # **This is the highlighted change**
177
-
178
- # Handle response
179
- if isinstance(response, str) and os.path.exists(response):
180
- st.image(response, caption="Generated Chart")
181
- with open(response, "rb") as file:
182
- st.download_button(label="Download Chart", data=file, file_name=os.path.basename(response), mime="image/png")
183
- else:
184
- st.write(response)
185
- except Exception as e:
186
- st.error(f"An error occurred: {e}")
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ from pandasai import SmartDataframe
4
+ from pandasai import SmartDatalake # Added for multiple datasets
5
+ from pandasai.llm import OpenAI
6
+ from pandasai.responses.streamlit_response import StreamlitResponse
7
+ import os
8
+ from pandasai.helpers.openai_info import get_openai_callback
9
+ import openpyxl
10
+ from openpyxl import Workbook
11
+ import time
12
+
13
+ # Initialize session state for storing prompts
14
+ if "previous_prompts" not in st.session_state:
15
+ st.session_state.previous_prompts = []
16
+
17
+ # Define FAQs categorized by function
18
+ frequently_asked_prompts_by_function = {
19
+ 'Sales': [
20
+ "What products have shown the highest performance by revenue?",
21
+ "What products have shown the highest performance by volume?",
22
+ "Which are the best performing categories?",
23
+ "Which products generate the lowest revenue?"
24
+ ],
25
+ 'Marketing': [
26
+ "Which eCommerce platform or channel has generated the highest revenue for product sales?",
27
+ "Which style of product exhibits average order values?",
28
+ "What are the average order values and profit margins with the top 10 selling products in each channel?",
29
+ "Which specific product categories or types dominate the top-selling SKUs in terms of revenue?",
30
+ ],
31
+ 'Customer Support': [
32
+ "What is the average resolution time for customer queries?",
33
+ "Which issues are most frequently reported by customers?",
34
+ "What is the customer satisfaction score for each support channel?",
35
+ "Which product categories generate the most support tickets?"
36
+ ]
37
+ }
38
+
39
+ # Page title
40
+ st.title("Retail Co-Pilot")
41
+ st.write("Ask questions about your dataset using conversational AI.")
42
+
43
+ # Left sidebar with file uploader at the top
44
+ with st.sidebar:
45
+ st.subheader("Upload Your Datasets")
46
+ uploaded_files = st.file_uploader("Choose CSV/Excel files", type=["xlsx", "csv"], accept_multiple_files=True)
47
+
48
+ if uploaded_files:
49
+ st.write(f"{len(uploaded_files)} file(s) uploaded.")
50
+
51
+ st.write("---") # Separator line
52
+
53
+ # Select function
54
+ st.subheader("Select Function")
55
+ selected_function = st.selectbox("Choose a function", list(frequently_asked_prompts_by_function.keys()))
56
+
57
+ # Expandable FAQs Section
58
+ with st.expander("Frequently Asked Prompts"):
59
+ st.write(f"Here are some frequently asked questions for the {selected_function} function:")
60
+ for i, prompt in enumerate(frequently_asked_prompts_by_function[selected_function], 1):
61
+ st.write(f"{i}. {prompt}")
62
+
63
+ # Expandable Previous Prompts Section
64
+ with st.expander("Previous Prompts"):
65
+ if st.session_state.previous_prompts:
66
+ for i, prompt in enumerate(st.session_state.previous_prompts, 1):
67
+ st.write(f"{i}. {prompt}")
68
+ else:
69
+ st.write("No questions asked yet.")
70
+
71
+ # Main content area with Ask button
72
+ st.write("---") # Separator line
73
+ st.subheader("Ask a Question")
74
+ temp_query = st.text_input("Enter your question:")
75
+
76
+ # Create a container to place the ask button next to the file uploader on the right
77
+ col1, col2 = st.columns([3, 1]) # Adjust the column width as needed
78
+
79
+ # Center : Ask button
80
+ with col1:
81
+ if st.button("Ask", key="ask_btn"):
82
+ if temp_query:
83
+ st.session_state.previous_prompts.append(temp_query)
84
+
85
+ # Display query dynamically below the columns
86
+ st.subheader("Your Query")
87
+ st.write(temp_query if temp_query else "No query entered yet.")
88
+
89
+
90
+ # Initialize the LLM
91
+ api_key = "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"
92
+ # Add your OpenAI API key here
93
+ llm = OpenAI(api_token=api_key, temperature=0, seed=42, model="gpt-3.5-turbo")
94
+ os.environ["PANDASAI_API_KEY"] = api_key
95
+
96
+ EXCEL_FILE_PATH = "callback_data.xlsx"
97
+ user_defined_path = os.getcwd()
98
+ udp = os.path.join(user_defined_path, "exports", "charts") # Define the current working directory
99
+
100
+ # Function to parse callback output
101
+ def parse_callback_output(cb) -> dict:
102
+ output_lines = str(cb).split("\n")
103
+ parsed_output = {
104
+ "total_tokens": int(output_lines[0].split(":")[1].strip()),
105
+ "prompt_tokens": int(output_lines[1].split(":")[1].strip()),
106
+ "completion_tokens": int(output_lines[2].split(":")[1].strip()),
107
+ "total_cost": float(output_lines[3].split(":")[1].strip().replace("$", "").strip()),
108
+ }
109
+ return parsed_output
110
+
111
+ # Additional sections unchanged...
112
+
113
+ # Function to append data to Excel
114
+ def append_to_excel(file_path: str, data: dict):
115
+ if not os.path.exists(file_path):
116
+ wb = Workbook()
117
+ ws = wb.active
118
+ ws.append(["Total Tokens", "Prompt Tokens", "Completion Tokens", "Total Cost (USD)"])
119
+ wb.save(file_path)
120
+
121
+ wb = openpyxl.load_workbook(file_path)
122
+ ws = wb.active
123
+ ws.append([data["total_tokens"], data["prompt_tokens"], data["completion_tokens"], data["total_cost"]])
124
+ wb.save(file_path)
125
+
126
+ # Prepare datasets for SmartDatalake
127
+ if uploaded_files:
128
+ dataframes = []
129
+ for uploaded_file in uploaded_files:
130
+ try:
131
+ if uploaded_file.name.endswith('.csv'):
132
+ df = pd.read_csv(uploaded_file)
133
+ elif uploaded_file.name.endswith('.xlsx'):
134
+ df = pd.read_excel(uploaded_file)
135
+ else:
136
+ st.error(f"Unsupported file format: {uploaded_file.name}")
137
+ continue
138
+
139
+ dataframes.append(df) # Collect DataFrames
140
+ success_message = st.success(f"File '{uploaded_file.name}' successfully loaded.")
141
+ time.sleep(2) # Keep the message for 2 seconds
142
+ success_message.empty() # Remove the message after 2 seconds
143
+
144
+ except Exception as e:
145
+ st.error(f"Error loading file '{uploaded_file.name}': {e}")
146
+
147
+ # Use SmartDatalake for multiple datasets
148
+ sales_data = SmartDatalake(dataframes, config={"llm": llm})
149
+
150
+ else:
151
+ sales_data = None # If no files uploaded, set to None
152
+
153
+
154
+ ## Prompt Template
155
+ prompt_template = '''You are a retail co-pilot, a master of sales with unparalleled expertise in providing the best solutions for any questions related to retail,
156
+ both general and specific to uploaded Excel files. Your goal is to assist users in optimizing their sales strategies,
157
+ understanding market trends, and making data-driven decisions. You should always be insightful, professional, and proactive in offering valuable recommendations and
158
+ provide a clear and formatted response for the following query. Include spaces between sentences and highlight key points clearly{user_query}'''
159
+
160
+
161
+
162
+ # Handle user queries
163
+ if temp_query:
164
+ with st.spinner("Thinking..."):
165
+ try:
166
+ # Get AI response
167
+ with get_openai_callback() as cb:
168
+ # using propmt template and temp query to chat with AI
169
+ formatted_query = prompt_template.format(user_query=temp_query)
170
+ response = sales_data.chat(formatted_query)
171
+ track = parse_callback_output(cb)
172
+ append_to_excel(EXCEL_FILE_PATH, track)
173
+ if isinstance(response,str) and os.path.exists(response):
174
+ # If response is an image path
175
+ # Change here: Replaced use_column_width with use_container_width
176
+ st.image(response, caption="Generated Chart",) #use_container_width=True)) # **This is the highlighted change**
177
+
178
+ # Handle response
179
+ if isinstance(response, str) and os.path.exists(response):
180
+ st.image(response, caption="Generated Chart")
181
+ with open(response, "rb") as file:
182
+ st.download_button(label="Download Chart", data=file, file_name=os.path.basename(response), mime="image/png")
183
+ else:
184
+ st.write(response)
185
+ except Exception as e:
186
+ st.error(f"An error occurred: {e}")