Spaces:
Runtime error
Runtime error
File size: 12,862 Bytes
2bff293 7637125 2bff293 3ce52e9 2bff293 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 | import streamlit as st
import pandas as pd
from pandasai import SmartDataframe
from pandasai import SmartDatalake
from pandasai.llm import OpenAI
import os
from dotenv import load_dotenv
import openpyxl
from openpyxl import Workbook
from pandasai.helpers.openai_info import get_openai_callback
import time
# Initialize session state for storing prompts and feedback
if "previous_prompts" not in st.session_state:
st.session_state.previous_prompts = []
if 'chat_history' not in st.session_state:
st.session_state['chat_history'] = []
# Define FAQs categorized by function
frequently_asked_prompts_by_function = {
'Sales': [
"What products have shown the highest performance by revenue?",
"What products have shown the highest performance by volume?",
"Which are the best performing categories?",
"Which products generate the lowest revenue?"
],
'Marketing': [
"Which eCommerce platform or channel has generated the highest revenue for product sales?",
"Which style of product exhibits average order values?",
"What are the average order values and profit margins with the top 10 selling products in each channel?",
"Which specific product categories or types dominate the top-selling SKUs in terms of revenue?",
],
'Customer Support': [
"What is the average resolution time for customer queries?",
"Which issues are most frequently reported by customers?",
"What is the customer satisfaction score for each support channel?",
"Which product categories generate the most support tickets?"
]
}
# Page title
st.title("Retail Co-Pilot")
st.write('''Retail Co-Pilot, your AI-driven retail assistant, meticulously designed to optimize operations, ensure accuracy, and maintain robust security. ''')
# Left sidebar with file uploader at the top
with st.sidebar:
st.subheader("Upload Your Datasets")
uploaded_files = st.file_uploader("Choose CSV/Excel files", type=["xlsx", "csv"], accept_multiple_files=True)
if uploaded_files:
st.write(f"{len(uploaded_files)} file(s) uploaded.")
st.write("---") # Separator line
# Select function
st.subheader("Select Function")
selected_function = st.selectbox("Choose a function", list(frequently_asked_prompts_by_function.keys()))
# Expandable FAQs Section
with st.expander("Frequently Asked Prompts"):
st.write(f"Here are some frequently asked questions for the {selected_function} function:")
for i, prompt in enumerate(frequently_asked_prompts_by_function[selected_function], 1):
st.write(f"{i}. {prompt}")
# Expandable Previous Prompts Section
with st.expander("Previous Prompts"):
if st.session_state.previous_prompts:
for i, prompt in enumerate(st.session_state.previous_prompts, 1):
st.write(f"{i}. {prompt}")
else:
st.write("No questions asked yet.")
# Initialize the LLM
load_dotenv = ()
api_key = os.getenv("Open_AI_Key") # Add your OpenAI API key here
llm = OpenAI(api_token=api_key, temperature=0, seed=42, model="gpt-3.5-turbo")
os.environ["PANDASAI_API_KEY"] = api_key
# Function to handle thumbs-up and thumbs-down feedback
def handle_feedback(chat_idx, feedback):
st.session_state['chat_history'][chat_idx]['feedback'] = feedback
# Content area with Ask button
st.write("---") # Separator line
st.subheader("How can I help you ?")
temp_query = st.text_input("Enter your question:")
# Create a container to place the ask button next to the file uploader on the right
col1, col2 = st.columns([1, 0.2]) # Adjust the column width as needed,
# Center : Ask button
with col1:
if st.button("Ask", key="ask_btn"):
if temp_query:
# Save the query to chat history
st.session_state['chat_history'].append({"query": temp_query, "response": None})
# Display query dynamically below the columns with bold and larger font size
if temp_query:
st.markdown(
f"<p style='font-size:20px; font-weight:bold;'>{temp_query}</p>",
unsafe_allow_html=True
)
else:
st.write("No query entered yet.")
EXCEL_FILE_PATH = "callback_data.xlsx"
user_defined_path = os.getcwd()
udp = os.path.join(user_defined_path, "exports", "charts") # Define the current working directory
# Function to parse callback output
def parse_callback_output(cb) -> dict:
output_lines = str(cb).split("\n")
parsed_output = {
"total_tokens": int(output_lines[0].split(":")[1].strip()),
"prompt_tokens": int(output_lines[1].split(":")[1].strip()),
"completion_tokens": int(output_lines[2].split(":")[1].strip()),
"total_cost": float(output_lines[3].split(":")[1].strip().replace("$", "").strip()),
}
return parsed_output
# Function to append data to Excel
def append_to_excel(file_path: str, data: dict):
if not os.path.exists(file_path):
wb = Workbook()
ws = wb.active
ws.append(["Total Tokens", "Prompt Tokens", "Completion Tokens", "Total Cost (USD)"])
wb.save(file_path)
wb = openpyxl.load_workbook(file_path)
ws = wb.active
ws.append([data["total_tokens"], data["prompt_tokens"], data["completion_tokens"], data["total_cost"]])
wb.save(file_path)
# Prepare datasets for SmartDatalake
if uploaded_files:
dataframes = []
# Show success message only once during file upload process
if 'success_message_shown' not in st.session_state:
st.session_state.success_message_shown = False
for uploaded_file in uploaded_files:
try:
# Read the file based on its extension
if uploaded_file.name.endswith('.csv'):
df = pd.read_csv(uploaded_file)
elif uploaded_file.name.endswith('.xlsx'):
df = pd.read_excel(uploaded_file)
else:
st.error(f"Unsupported file format: {uploaded_file.name}")
continue
dataframes.append(df) # Collect DataFrames
# Show success message only once for each file
if not st.session_state.success_message_shown:
st.session_state.success_message_shown = True
st.success(f"File '{uploaded_file.name}' successfully loaded.")
except Exception as e:
st.error(f"Error loading file '{uploaded_file.name}': {e}")
# Use SmartDatalake for multiple datasets
sales_data = SmartDatalake(dataframes, config={"llm": llm})
else:
sales_data = None # If no files uploaded, set to None
# Prompt Template
# 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, both general and specific to uploaded Excel files. Your goal is to assist users in optimizing their sales strategies, understanding market trends, and making data-driven decisions. You should always be insightful, professional, and proactive in offering valuable recommendations and provide a clear and formatted response for the following query. Include spaces between sentences and highlight key points clearly: {user_query}'''
prompt_template_1 = '''
You are a retail and marketing campaign co-pilot, a master of sales strategies and campaign analysis, with unparalleled expertise in the following areas:
1. **Sales Strategy**: Provide actionable recommendations to optimize sales and maximize revenue.
2. **Campaign Performance Analysis**: Evaluate past marketing campaigns and provide actionable insights for improvement.
3. **Market Trends Analysis**: Offer professional insights into current market trends and their implications for retail and marketing.
4. **Data-Driven Decisions**: Analyze data (such as uploaded Excel files) to generate insights and recommendations for both retail operations and marketing campaigns.
5. **Audience Segmentation**: Recommend tailored strategies for specific audience segments to enhance campaign effectiveness.
6. **Channel Optimization**: Identify the most effective sales and marketing channels to maximize ROI.
7. **Inventory Management**: Suggest ways to efficiently manage stock levels, reduce waste, and prevent stockouts based on marketing and sales forecasts.
8. **Budget Allocation**: Suggest optimal budget distribution across campaigns and retail operations.
9. **Cross-Selling and Upselling**: Recommend techniques to encourage customers to purchase additional or premium products.
10. **Competitor Benchmarking**: Provide insights into how competitors are performing and strategies to outperform them.
11. **Customer Feedback Management**: Advise on handling customer reviews and improving customer satisfaction for both products and campaigns.
12. **Marketing Campaigns**: Develop innovative strategies to promote products and increase customer engagement.
13. **Conversion Rate Optimization**: Recommend steps to improve landing pages, campaign performance, and retail outcomes.
Your goal is to deliver structured, insightful, and actionable advice in response to the user’s query. Always include examples, clear next steps, and highlight key points. Align your recommendations with the context provided and ensure your response is professional, concise, and easy to follow.
**Additional Information:**
- If the user has uploaded a file, analyze the data and columns carefully and incorporate it into your response.
- Use clear, structured language to present your recommendations effectively.
User Query: {user_query}
'''
# Handle user queries
if temp_query:
with st.spinner("Thinking..."):
try:
# Get AI response
with get_openai_callback() as cb:
# Using prompt template and temp query to chat with AI
formatted_query = prompt_template_1.format(user_query=temp_query)
response = sales_data.chat(formatted_query)
track = parse_callback_output(cb)
append_to_excel(EXCEL_FILE_PATH, track)
# Update chat history with the AI response
for chat in st.session_state['chat_history']:
if chat["query"] == temp_query:
# If the response is a file path (i.e., a chart), just store "Generated chart"
if isinstance(response, str) and os.path.exists(response):
chat["response"] = "Generated chart" # Store only the message, not the file path
else:
chat["response"] = response # Store the normal text response
break
# Handle the response (image or text)
if isinstance(response, str) and os.path.exists(response):
st.image(response, caption="Generated Chart")
with open(response, "rb") as file:
st.download_button(label="Download Chart",
data=file,
file_name=os.path.basename(response),
mime="image/png")
else:
st.write(response)
# Thumbs-up and Thumbs-down buttons for feedback (below the model's response)
col1, col2 = st.columns(2)
with col1:
thumbs_up = st.button("👍", key="thumbs_up")
if thumbs_up:
handle_feedback(len(st.session_state['chat_history']) - 1, "👍")
with col2:
thumbs_down = st.button("👎", key="thumbs_down")
if thumbs_down:
handle_feedback(len(st.session_state['chat_history']) - 1, "👎")
except Exception as e:
st.error(f"An error occurred: {e}")
## Display chat history with styled response boxes
st.write("### Chat History")
for idx, chat in enumerate(st.session_state['chat_history']):
# User query display
st.write(f"**You:** {chat['query']}")
# Bot response display with styled box (Dark background, White text)
if chat['response']:
st.markdown(
f"""
<div style="
background-color: #333333; /* Dark background */
border: 1px solid #444444;
border-radius: 10px;
padding: 10px;
margin-top: 5px;
margin-bottom: 10px;
color: white; /* White text */
font-size: 14px;
">
<b>Bot:</b> {chat['response']}
</div>
""",
unsafe_allow_html=True,
)
# Feedback iedisplay (if available)
feedback = chat.get("feedback")
if feedback:
st.write(f"**Feedback:** {feedback}")
st.write("---") # Separator between chat entr
|