Spaces:
Runtime error
Runtime error
Download app.py from naveenseth/Retail-Copilo-Streamlit: direct link, hf CLI and curl.
- Browser
- Download file 12.9 kB
-
https://huggingface.co/spaces/naveenseth/Retail-Copilo-Streamlit/resolve/main/app.py
- Command line
-
hf download hf://spaces/naveenseth/Retail-Copilo-Streamlit/app.py
-
curl -L -o app.py https://huggingface.co/spaces/naveenseth/Retail-Copilo-Streamlit/resolve/main/app.py
12.9 kB
| 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 | |