naveenseth commited on
Commit
feb8ff6
·
verified ·
1 Parent(s): 41bce61

Delete app.py

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