WaysAhead Global commited on
Commit
f27be35
Β·
verified Β·
1 Parent(s): eff4325

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -56
app.py CHANGED
@@ -4,14 +4,15 @@ import numpy as np
4
  import os
5
  import matplotlib.pyplot as plt
6
  import seaborn as sns
7
- from dotenv import load_dotenv
 
8
  from langchain_openai import ChatOpenAI
9
  from langchain.chains import LLMChain
10
  from langchain.prompts import PromptTemplate
 
11
  from pycaret.regression import setup as setup_reg, compare_models, predict_model
12
  from pandasai import SmartDatalake
13
  from pandasai.llm import OpenAI
14
- from crewai import Crew, Agent, Task
15
 
16
  # βœ… Load Environment Variables
17
  load_dotenv()
@@ -25,6 +26,21 @@ folder_path = os.getcwd()
25
  data_file = os.path.join(folder_path, "kpi.xlsx")
26
  df = pd.read_excel(data_file, engine="openpyxl")
27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  # βœ… Store Categorization Dictionary
29
  store_categories = {
30
  "E-commerce": ["6th Street.com"],
@@ -49,64 +65,69 @@ store_categories = {
49
  "REN by Sushi Library", "Sushi Library", "Tim Hortons", "LM Exchange"]
50
  }
51
 
52
- # βœ… CrewAI Agents & Tasks with Backstories
53
- cleaning_agent = Agent(
54
- role="Data Cleaning Expert",
55
- goal="Ensure data quality by handling missing values and duplicates.",
56
- backstory="A seasoned data scientist who specializes in cleaning and structuring large datasets.",
57
- llm=ChatOpenAI(model="gpt-4"),
58
- allow_delegation=True
59
- )
60
-
61
- competitor_agent = Agent(
62
- role="Competitor Analyst",
63
- goal="Fetch competitors for the selected mall or generate AI-based fallback.",
64
- backstory="A retail market expert who analyzes competitors and provides key insights for store replacements.",
65
- llm=ChatOpenAI(model="gpt-4"),
66
- allow_delegation=True
67
- )
68
-
69
- replacement_agent = Agent(
70
- role="Store Replacement Specialist",
71
- goal="Find the best replacement stores matching the selected store’s category.",
72
- backstory="An AI-powered retail strategist with expertise in category-based store recommendations.",
73
- llm=ChatOpenAI(model="gpt-4"),
74
- allow_delegation=True
75
- )
76
-
77
- prediction_agent = Agent(
78
- role="AI KPI Forecaster",
79
- goal="Use AutoML to predict sales, footfall, conversion rate, and margins.",
80
- backstory="A machine learning expert trained in forecasting business metrics using the best models.",
81
- llm=ChatOpenAI(model="gpt-4"),
82
- allow_delegation=True
83
- )
84
-
85
- chatbot_agent = Agent(
86
- role="Conversational Data Assistant",
87
- goal="Answer business-related queries about the dataset.",
88
- backstory="An AI-powered assistant trained to answer complex retail analytics questions based on data.",
89
- llm=ChatOpenAI(model="gpt-4"),
90
- allow_delegation=True
91
- )
92
-
93
- crew = Crew(agents=[cleaning_agent, competitor_agent, replacement_agent, prediction_agent, chatbot_agent])
94
-
95
  # βœ… Streamlit Page Configuration
96
  st.set_page_config(page_title="AI Store Replacement & Chatbot", layout="wide")
97
 
98
  # βœ… Title
99
- st.title("πŸ”„ AI-Powered Store Replacement, AutoML Demand Prediction & CrewAI")
100
 
101
- # βœ… Data Preview (First 10 Rows)
102
  st.subheader("πŸ“Š Sample Data Preview - KPI Sheet")
103
  st.dataframe(df.head(10))
104
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  # βœ… AI-Powered Conversational Smart Data Lake
106
  st.subheader("πŸ’¬ AI-Powered Data Chatbot")
107
-
108
- llm_sdl = OpenAI(api_token=openai_api_key)
109
- sdl = SmartDatalake([df], config={"llm": llm_sdl, "enable_cache": False})
110
 
111
  user_query = st.text_input("πŸ” Ask AI About Your Data:")
112
  if user_query:
@@ -116,9 +137,3 @@ if user_query:
116
  st.markdown(f"πŸ€– **AI:** {response}")
117
  except Exception as e:
118
  st.error(f"❌ AI Error: {str(e)}")
119
-
120
- # βœ… CrewAI Execution
121
- st.subheader("πŸš€ AI Task Execution with CrewAI")
122
- st.write("Executing all AI agents...")
123
- crew.kickoff()
124
- st.success("βœ… CrewAI execution completed!")
 
4
  import os
5
  import matplotlib.pyplot as plt
6
  import seaborn as sns
7
+ from fuzzywuzzy import process
8
+ from sklearn.cluster import KMeans
9
  from langchain_openai import ChatOpenAI
10
  from langchain.chains import LLMChain
11
  from langchain.prompts import PromptTemplate
12
+ from dotenv import load_dotenv
13
  from pycaret.regression import setup as setup_reg, compare_models, predict_model
14
  from pandasai import SmartDatalake
15
  from pandasai.llm import OpenAI
 
16
 
17
  # βœ… Load Environment Variables
18
  load_dotenv()
 
26
  data_file = os.path.join(folder_path, "kpi.xlsx")
27
  df = pd.read_excel(data_file, engine="openpyxl")
28
 
29
+ # βœ… Load Competitor Mapping Files
30
+ competitor_files = {
31
+ "Deira City Centre": os.path.join(folder_path, "Competitor Mapping Doc Final1(DEIRA CITY CENTRE).csv"),
32
+ "Arabian Centre": os.path.join(folder_path, "Competitor Mapping Doc Final1(ARABIAN CENTRE).csv"),
33
+ "Al Ghurair Centre": os.path.join(folder_path, "Competitor Mapping Doc Final1(AL GHURAIR CENTRE).csv"),
34
+ "Ibn Battuta Mall": os.path.join(folder_path, "Competitor Mapping Doc Final1(IBN BATTUTA MALL).csv"),
35
+ "Dubai Hills": os.path.join(folder_path, "Competitor Mapping Doc Final1(DUBAI HILLS).csv"),
36
+ }
37
+
38
+ # βœ… Load competitors data
39
+ competitor_data = {}
40
+ for mall, file in competitor_files.items():
41
+ if os.path.exists(file):
42
+ competitor_data[mall] = pd.read_csv(file, encoding="ISO-8859-1")
43
+
44
  # βœ… Store Categorization Dictionary
45
  store_categories = {
46
  "E-commerce": ["6th Street.com"],
 
65
  "REN by Sushi Library", "Sushi Library", "Tim Hortons", "LM Exchange"]
66
  }
67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  # βœ… Streamlit Page Configuration
69
  st.set_page_config(page_title="AI Store Replacement & Chatbot", layout="wide")
70
 
71
  # βœ… Title
72
+ st.title("πŸ”„ AI-Powered Store Replacement, AutoML Demand Prediction & Smart Data Lake AI")
73
 
74
+ # βœ… Data Preview (Only First 10 Rows)
75
  st.subheader("πŸ“Š Sample Data Preview - KPI Sheet")
76
  st.dataframe(df.head(10))
77
 
78
+ # βœ… Store Replacement System
79
+ st.subheader("🏬 AI-Based Store Replacement")
80
+
81
+ # Select Mall
82
+ selected_mall = st.selectbox("🏬 Select a Mall:", df["Mall"].unique())
83
+
84
+ if selected_mall:
85
+ # Get all stores in the selected mall
86
+ mall_data = df[df["Mall"] == selected_mall]
87
+
88
+ # Select the store that will be replaced
89
+ store_to_replace = st.selectbox("πŸšͺ Select the store that is closing:", mall_data["Store_Brand"].unique())
90
+
91
+ if store_to_replace:
92
+ llm = ChatOpenAI(model="gpt-4", api_key=openai_api_key)
93
+
94
+ # βœ… Fuzzy Matching to Find the Correct Category
95
+ all_store_names = [store for category in store_categories.values() for store in category]
96
+ best_match, score = process.extractOne(store_to_replace, all_store_names)
97
+
98
+ store_category = None
99
+ if score > 80: # Ensure strong match confidence
100
+ for category, stores in store_categories.items():
101
+ if best_match in stores:
102
+ store_category = category
103
+ break
104
+ else:
105
+ store_category = "Others"
106
+
107
+ st.write(f"πŸ” **Identified Category:** {store_category} (Matched: {best_match}, Score: {score})")
108
+
109
+ # βœ… Find Replacement Stores Based on Performance
110
+ replacement_candidates = df[(df["Category"] == store_category) & (df["Annual_Sales"] > df["Annual_Sales"].median())]
111
+ top_replacements = replacement_candidates["Store_Brand"].unique()[:3]
112
+
113
+ if top_replacements.any():
114
+ st.success("βœ… **Recommended Replacement Stores:**")
115
+ for replacement_store in top_replacements:
116
+ store_data = df[df["Store_Brand"] == replacement_store]
117
+
118
+ # βœ… AutoML Model Selection
119
+ setup_reg(df, target="Annual_Sales", silent=True, verbose=False)
120
+ best_model = compare_models()
121
+ projected_sales = predict_model(best_model, data=store_data)["Label"].mean()
122
+
123
+ # βœ… Display KPIs in the Green Section
124
+ st.subheader(f"πŸ“Š Projected KPIs for {replacement_store}")
125
+ st.write(f"πŸ† **Best Model Used:** {best_model}")
126
+ st.write(f"πŸ“Š **Projected Sales:** AED {projected_sales:,.2f}")
127
+
128
  # βœ… AI-Powered Conversational Smart Data Lake
129
  st.subheader("πŸ’¬ AI-Powered Data Chatbot")
130
+ sdl = SmartDatalake([df], config={"llm": OpenAI(api_token=openai_api_key), "enable_cache": False})
 
 
131
 
132
  user_query = st.text_input("πŸ” Ask AI About Your Data:")
133
  if user_query:
 
137
  st.markdown(f"πŸ€– **AI:** {response}")
138
  except Exception as e:
139
  st.error(f"❌ AI Error: {str(e)}")