WaysAhead Global commited on
Commit
e31ce50
Β·
verified Β·
1 Parent(s): f525de7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -81
app.py CHANGED
@@ -5,9 +5,9 @@ import os
5
  import matplotlib.pyplot as plt
6
  import seaborn as sns
7
  from sklearn.cluster import KMeans
8
- from statsmodels.tsa.holtwinters import ExponentialSmoothing
9
  from langchain_openai import ChatOpenAI
10
- from pandasai import SmartDatalake
 
11
  from dotenv import load_dotenv
12
 
13
  # βœ… Load Environment Variables
@@ -17,34 +17,18 @@ openai_api_key = os.getenv("OPENAI_API_KEY")
17
  if not openai_api_key:
18
  st.error("❌ OpenAI API Key is missing! Set it in your environment variables.")
19
 
20
- # βœ… Auto-Load All Files from the Folder
21
- folder_path = os.getcwd() # Uses current folder
22
-
23
- # Load KPI Excel File (Main store dataset)
24
  data_file = os.path.join(folder_path, "kpi.xlsx")
25
  df = pd.read_excel(data_file, engine="openpyxl")
26
 
27
- # Load Competitor Mapping Files
28
- competitor_files = {
29
- "Deira City Centre": os.path.join(folder_path, "Competitor Mapping Doc Final1(DEIRA CITY CENTRE).csv"),
30
- "Arabian Centre": os.path.join(folder_path, "Competitor Mapping Doc Final1(ARABIAN CENTRE).csv"),
31
- "Al Ghurair Centre": os.path.join(folder_path, "Competitor Mapping Doc Final1(AL GHURAIR CENTRE).csv"),
32
- "Ibn Battuta Mall": os.path.join(folder_path, "Competitor Mapping Doc Final1(IBN BATTUTA MALL).csv"),
33
- "Dubai Hills": os.path.join(folder_path, "Competitor Mapping Doc Final1(DUBAI HILLS).csv"),
34
- }
35
-
36
- # Store all competitor data in a dictionary
37
- competitor_data = {}
38
- for mall, file in competitor_files.items():
39
- competitor_data[mall] = pd.read_csv(file, encoding="ISO-8859-1")
40
-
41
  # βœ… Streamlit Page Configuration
42
- st.set_page_config(page_title="AI Store Replacement, Demand Prediction & Chatbot", layout="wide")
43
 
44
  # βœ… Title
45
- st.title("πŸ”„ AI-Powered Store Replacement, Demand Prediction & Chatbot")
46
 
47
- # βœ… Data Preview Section
48
  st.subheader("πŸ“Š Full Data Preview - KPI Sheet")
49
  st.dataframe(df)
50
 
@@ -65,81 +49,74 @@ if selected_mall:
65
  llm = ChatOpenAI(model="gpt-4", api_key=openai_api_key)
66
 
67
  # βœ… Identify Store Category
68
- category_prompt = f"Given that {store_to_replace} is a retail brand, what type of store is it? Categorize it broadly (e.g., Fashion, Electronics, Footwear, Food, Home Decor, etc.)."
69
- store_category = llm.invoke(category_prompt).content
 
 
 
70
  st.write(f"πŸ” **Identified Category:** {store_category}")
71
 
72
- # βœ… Find 5 Competitors in the Same Mall
73
- if selected_mall in competitor_data:
74
- mall_competitor_data = competitor_data[selected_mall]
75
- competitor_list = mall_competitor_data["Competitors in mall"].dropna().unique()
76
-
77
- if len(competitor_list) > 5:
78
- competitor_list = np.random.choice(competitor_list, 5, replace=False)
79
-
80
- st.subheader("πŸ”Ž Competitors in This Mall")
81
- for competitor in competitor_list:
82
- st.write(f"- {competitor}")
83
-
84
- # βœ… AI-Based Store Clustering (Finding Best Replacements)
85
- store_features = df[["Annual_Sales", "Footfall", "Gross_Margin"]].dropna()
86
- kmeans = KMeans(n_clusters=5, random_state=42) # 5 Clusters
87
- df["Cluster"] = kmeans.fit_predict(store_features)
88
-
89
- # βœ… Find a replacement store in the same category (From kpi.xlsx, Not in this mall)
90
  all_stores = set(df["Store_Brand"].unique())
91
  existing_stores = set(mall_data["Store_Brand"].unique())
92
  potential_replacements = list(all_stores - existing_stores)
93
 
 
 
 
94
  if potential_replacements:
95
- replacement_prompt = f"Based on the category {store_category}, suggest 3 stores from the list below that are not already in {selected_mall}. The stores should match the mall’s customer base. Store List: {potential_replacements}"
96
- replacement_response = llm.invoke(replacement_prompt).content
97
- replacement_stores = replacement_response.split(", ")
98
-
99
- st.success(f"πŸ”„ **Recommended Replacement Stores:**")
100
- for replacement_store in replacement_stores:
101
- store_data = df[df["Store_Brand"] == replacement_store]
102
-
103
- if not store_data.empty:
104
- sales_history = store_data["Annual_Sales"]
105
- if len(sales_history) > 3:
106
- # βœ… Time-Series Forecasting for Demand Prediction
107
- model = ExponentialSmoothing(sales_history, trend="add", seasonal="add", seasonal_periods=3)
108
- fit = model.fit()
109
- forecast_sales = fit.forecast(1).values[0] # Predict next year's sales
110
-
111
- expected_footfall = store_data["Footfall"].mean()
112
- expected_conversion = store_data["Conversion_Rate"].mean()
113
- expected_margin = store_data["Gross_Margin"].mean()
 
 
 
 
114
 
115
  st.write(f"**{replacement_store}**")
116
- st.write(f"πŸ“Š **Projected Sales:** AED {forecast_sales:,.2f}")
117
- st.write(f"πŸ‘£ **Projected Footfall:** {expected_footfall:,.0f} visitors")
118
- st.write(f"πŸ’° **Projected Margin:** AED {expected_margin:,.2f}")
119
- st.write(f"πŸ”„ **Projected Conversion Rate:** {expected_conversion:.2f}%")
120
 
121
  # βœ… Justification
122
- justification_prompt = f"Explain why {replacement_store} is a good replacement for {store_to_replace} in {selected_mall}. Include numeric KPIs: expected sales, footfall, conversion rate, and profit margins."
123
- justification = llm.invoke(justification_prompt).content
 
 
 
 
 
 
 
124
  st.write(f"πŸ€– **AI Justification:** {justification}")
125
 
126
- # βœ… AI Chatbot for Dynamic Insights
127
  st.subheader("πŸ’¬ AI-Powered Chatbot")
128
 
129
- # AI Chatbot using PandasAI
130
- llm_pandas = ChatOpenAI(model="gpt-3.5-turbo", api_key=openai_api_key)
131
- sdl = SmartDatalake([df], config={"llm": llm_pandas, "enable_cache": False})
132
-
133
  user_query = st.text_input("πŸ” Ask AI About Your Data:")
134
  if user_query:
135
- with st.spinner("πŸ€– AI is thinking..."):
136
- try:
137
- response = sdl.chat(user_query)
138
- st.markdown(f"πŸ€– **AI:** {response}")
139
-
140
- except Exception as e:
141
- st.error(f"❌ AI Error: {str(e)}")
142
 
143
  # βœ… Footer
144
  st.markdown("---")
145
- st.markdown("πŸ’‘ Built with ❀️ using **AI-Powered Store Replacement & Demand Prediction**")
 
5
  import matplotlib.pyplot as plt
6
  import seaborn as sns
7
  from sklearn.cluster import KMeans
 
8
  from langchain_openai import ChatOpenAI
9
+ from langchain.chains import LLMChain
10
+ from langchain.prompts import PromptTemplate
11
  from dotenv import load_dotenv
12
 
13
  # βœ… Load Environment Variables
 
17
  if not openai_api_key:
18
  st.error("❌ OpenAI API Key is missing! Set it in your environment variables.")
19
 
20
+ # βœ… Load KPI Excel File
21
+ folder_path = os.getcwd()
 
 
22
  data_file = os.path.join(folder_path, "kpi.xlsx")
23
  df = pd.read_excel(data_file, engine="openpyxl")
24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  # βœ… Streamlit Page Configuration
26
+ st.set_page_config(page_title="AI Store Replacement & Chatbot", layout="wide")
27
 
28
  # βœ… Title
29
+ st.title("πŸ”„ AI-Powered Store Replacement & LangChain Chatbot")
30
 
31
+ # βœ… Data Preview
32
  st.subheader("πŸ“Š Full Data Preview - KPI Sheet")
33
  st.dataframe(df)
34
 
 
49
  llm = ChatOpenAI(model="gpt-4", api_key=openai_api_key)
50
 
51
  # βœ… Identify Store Category
52
+ category_prompt = PromptTemplate.from_template(
53
+ "Given that {store_name} is a retail brand, what type of store is it? Categorize it broadly (e.g., Fashion, Electronics, Footwear, Food, Home Decor, etc.)."
54
+ )
55
+ category_chain = LLMChain(llm=llm, prompt=category_prompt)
56
+ store_category = category_chain.run(store_name=store_to_replace)
57
  st.write(f"πŸ” **Identified Category:** {store_category}")
58
 
59
+ # βœ… Find Replacement Stores from kpi.xlsx
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  all_stores = set(df["Store_Brand"].unique())
61
  existing_stores = set(mall_data["Store_Brand"].unique())
62
  potential_replacements = list(all_stores - existing_stores)
63
 
64
+ # βœ… Debugging: Print available replacements
65
+ st.write(f"πŸ” **Available Replacement Stores:** {potential_replacements}")
66
+
67
  if potential_replacements:
68
+ replacement_prompt = PromptTemplate.from_template(
69
+ "Based on the category {store_category}, suggest 3 stores from the list below that are not already in {mall_name}. The stores should match the mall’s customer base. Store List: {store_list}"
70
+ )
71
+ replacement_chain = LLMChain(llm=llm, prompt=replacement_prompt)
72
+ replacement_response = replacement_chain.run(
73
+ store_category=store_category, mall_name=selected_mall, store_list=potential_replacements
74
+ )
75
+
76
+ # βœ… Debugging: Print AI Response
77
+ st.write(f"🧠 **AI Raw Response:** {replacement_response}")
78
+
79
+ # Ensure AI response is formatted correctly
80
+ replacement_stores = [store.strip() for store in replacement_response.split("\n") if store.strip()]
81
+
82
+ if replacement_stores:
83
+ st.success(f"πŸ”„ **Recommended Replacement Stores:**")
84
+ for replacement_store in replacement_stores[:3]:
85
+ store_data = df[df["Store_Brand"] == replacement_store]
86
+
87
+ if not store_data.empty:
88
+ projected_sales = store_data["Annual_Sales"].mean()
89
+ projected_footfall = store_data["Footfall"].mean()
90
+ projected_margin = store_data["Gross_Margin"].mean()
91
 
92
  st.write(f"**{replacement_store}**")
93
+ st.write(f"πŸ“Š **Projected Sales:** AED {projected_sales:,.2f}")
94
+ st.write(f"πŸ‘£ **Projected Footfall:** {projected_footfall:,.0f} visitors")
95
+ st.write(f"πŸ’° **Projected Margin:** AED {projected_margin:,.2f}")
 
96
 
97
  # βœ… Justification
98
+ justification_prompt = PromptTemplate.from_template(
99
+ "Explain why {replacement_store} is a good replacement for {store_to_replace} in {mall_name}. "
100
+ "Include numeric KPIs: expected sales, footfall, conversion rate, and profit margins."
101
+ )
102
+ justification_chain = LLMChain(llm=llm, prompt=justification_prompt)
103
+ justification = justification_chain.run(
104
+ replacement_store=replacement_store, store_to_replace=store_to_replace, mall_name=selected_mall
105
+ )
106
+
107
  st.write(f"πŸ€– **AI Justification:** {justification}")
108
 
109
+ # βœ… AI Chatbot using LangChain
110
  st.subheader("πŸ’¬ AI-Powered Chatbot")
111
 
 
 
 
 
112
  user_query = st.text_input("πŸ” Ask AI About Your Data:")
113
  if user_query:
114
+ chat_prompt = PromptTemplate.from_template("Answer this retail business question based on the dataset: {question}")
115
+ chat_chain = LLMChain(llm=llm, prompt=chat_prompt)
116
+ chat_response = chat_chain.run(question=user_query)
117
+
118
+ st.markdown(f"πŸ€– **AI Response:** {chat_response}")
 
 
119
 
120
  # βœ… Footer
121
  st.markdown("---")
122
+ st.markdown("πŸ’‘ Built with ❀️ using **LangChain AI for Store Replacement & Demand Prediction**")