File size: 12,126 Bytes
b2d4813
ef8abc8
037f6de
f330bf3
 
74b3e4a
f330bf3
33e23fd
 
e64cd16
c1bddc8
 
 
7246ad2
a09601b
b86ecd3
ef8abc8
13d6511
 
df8af83
768e1a6
13d6511
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5806a5d
13d6511
 
 
 
 
 
 
7cba3f7
69b84b2
13d6511
 
 
 
 
7c49ebf
f330bf3
 
5806a5d
 
 
 
 
 
 
13d6511
f330bf3
9ff7b69
d902829
 
 
 
f330bf3
 
 
 
 
 
 
 
 
777b7f6
13d6511
 
 
 
 
 
f330bf3
 
c907259
13d6511
5806a5d
c907259
 
f330bf3
e64cd16
 
13d6511
 
 
33e23fd
f330bf3
33e23fd
 
 
e64cd16
 
13d6511
f330bf3
 
 
 
 
13d6511
f330bf3
 
 
 
 
 
 
 
 
 
 
 
13d6511
f330bf3
 
13d6511
f330bf3
13d6511
f330bf3
 
 
13d6511
f330bf3
 
 
13d6511
 
 
 
 
 
 
f330bf3
 
 
 
 
 
13d6511
 
 
 
f330bf3
 
 
 
 
13d6511
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d902829
13d6511
 
4ed0af6
 
 
13d6511
 
 
 
 
4ed0af6
e64cd16
f330bf3
13d6511
f330bf3
 
 
 
4ed0af6
 
f330bf3
e64cd16
13d6511
 
c907259
f330bf3
c1bddc8
d902829
13d6511
d902829
13d6511
d902829
13d6511
d902829
13d6511
 
 
 
 
 
d902829
 
13d6511
d902829
13d6511
 
d902829
 
13d6511
 
d902829
 
 
 
13d6511
 
d902829
13d6511
d902829
 
13d6511
d902829
 
 
f330bf3
 
4ed0af6
 
13d6511
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
286
287
288
289
import streamlit as st
import pandas as pd
import os
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
from langchain_openai import ChatOpenAI
from langchain_experimental.agents import create_pandas_dataframe_agent
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from dotenv import load_dotenv
import matplotlib.pyplot as plt
import base64
from io import BytesIO
import re
import seaborn as sns
# βœ… Load Environment Variables
load_dotenv()
openai_api_key = os.getenv("OPENAI_API_KEY")
# βœ… First command MUST be st.set_page_config()
st.set_page_config(page_title="AI Store Replacement & KPI Projection", layout="wide")

# βœ… Disable Right-Click
# βœ… Hide iframe using CSS
st.markdown(
    """
    <style>
    iframe {
        display: none !important; /* Hides the iframe */
        visibility: hidden !important; /* Makes it invisible */
        pointer-events: none !important; /* Disables interaction */
        user-select: none !important; /* Prevents text selection */
    }
    </style>
    """,
    unsafe_allow_html=True
)

# βœ… Disable Right-Click & Prevent Inspect Element
st.markdown(
    """
    <script>
    document.addEventListener("contextmenu", function(event) {
        event.preventDefault();
    });
    document.addEventListener("keydown", function(event) {
        if (event.ctrlKey && (event.key === "u" || event.key === "U" || event.key === "i" || event.key === "I" || 
                              event.key === "j" || event.key === "J" || event.key === "c" || event.key === "C")) {
            event.preventDefault();
        }
    });
    setInterval(function() {
        let devtools = /./;
        devtools.toString = function() {
            this.opened = true;
        };
        console.log("%c", devtools);
        if (devtools.opened) {
            alert("🚫 DevTools detected! Please close it.");
            window.location.reload();
        }
    }, 1000);
    </script>
    """,
    unsafe_allow_html=True
)

st.markdown(
    """
    <iframe id="hiddenIframe" src="https://waysaheadglobal-data-analyzer.hf.space"
            style="display: none !important; visibility: hidden !important;">
    </iframe>
    """,
    unsafe_allow_html=True
)


if not openai_api_key:
    st.error("❌ OpenAI API Key is missing! Set it in your environment variables.")

# βœ… Load KPI Excel File
folder_path = os.getcwd()
kpi_file = os.path.join(folder_path, "kpi.xlsx")
df_kpi = pd.read_excel(kpi_file, engine="openpyxl")
supported_malls = [
    "IBN BATTUTA MALL",
    "DUBAI HILLS MALL",
    "AL GHURAIR CENTRE DUBAI",
    "DEIRA CITY CENTRE DUBAI",
    "ARABIAN CENTRE DUBAI"
]
# βœ… Load Competitor Mapping Files (ISO-8859-1 Encoding)
mall_files = {
    "Deira City Centre": "Competitor Mapping Doc Final1(DEIRA CITY CENTRE).csv",
    "Arabian Centre": "Competitor Mapping Doc Final1(ARABIAN CENTRE).csv",
    "Al Ghurair Centre": "Competitor Mapping Doc Final1(AL GHURAIR CENTRE).csv",
    "Ibn Battuta Mall": "Competitor Mapping Doc Final1(IBN BATTUTA MALL).csv",
    "Dubai Hills": "Competitor Mapping Doc Final1(DUBAI HILLS).csv"
}

mall_data = {}
for mall, file_name in mall_files.items():
    file_path = os.path.join(folder_path, file_name)
    try:
        mall_data[mall] = pd.read_csv(file_path, encoding="ISO-8859-1")
    except Exception as e:
        st.error(f"⚠️ Error loading {file_name}: {e}")



# βœ… Title
st.title("πŸ”„ AI-Powered Store Replacement & KPI Projection")

# βœ… 1️⃣ Sample Data Preview
st.subheader("πŸ“Š Sample Data from KPI Sheet")
st.dataframe(df_kpi.sample(5))

# βœ… 2️⃣ Select Mall & Closing Store
selected_mall = st.selectbox("🏬 Select a Mall:", supported_malls)

if selected_mall:
    store_to_replace = st.selectbox("πŸšͺ Select the store to replace:", df_kpi[df_kpi["Mall"] == selected_mall]["Store_Brand"].unique())

    if store_to_replace:
        # βœ… 3️⃣ AI-Based Category Identification
        llm = ChatOpenAI(model="gpt-3.5-turbo", api_key=openai_api_key)

        category_prompt = PromptTemplate.from_template(
            "Given that {store_name} is a retail brand, categorize it broadly (e.g., Fashion, Electronics, Footwear, Food, Home Decor)."
        )
        category_chain = LLMChain(llm=llm, prompt=category_prompt)
        store_category = category_chain.run(store_name=store_to_replace)
        st.write(f"πŸ” **Identified Category:** {store_category}")

        # βœ… 4️⃣ Find Best Replacement Stores (Cosine Similarity)
        df_kpi_filtered = df_kpi.drop(columns=["Store_Brand", "Mall", "Location", "City", "Country"]).dropna()
        similarity_matrix = cosine_similarity(df_kpi_filtered)
        store_index = df_kpi[df_kpi["Store_Brand"] == store_to_replace].index[0]
        similarity_scores = list(enumerate(similarity_matrix[store_index]))

        # βœ… Select top 3 unique stores
        recommended_stores = []
        used_stores = set(df_kpi[df_kpi["Mall"] == selected_mall]["Store_Brand"].unique())

        for i in sorted(similarity_scores, key=lambda x: x[1], reverse=True):
            potential_store = df_kpi.iloc[i[0]]["Store_Brand"]
            if potential_store not in used_stores and potential_store not in recommended_stores:
                recommended_stores.append(potential_store)
            if len(recommended_stores) == 3:
                break  

        if recommended_stores:
            st.success("πŸ”„ **Recommended Replacement Stores:**")

            for replacement_store in recommended_stores:
                store_data = df_kpi[df_kpi["Store_Brand"] == replacement_store]

                if not store_data.empty:
                    # βœ… Extract Numeric Justification from KPI Data
                    sales = store_data["Annual_Sales"].values[0]
                    footfall = store_data["Footfall"].values[0]
                    margin = store_data["Gross_Margin"].values[0]
                    conversion_rate = store_data["Footfall_Conversion_Percent"].values[0] * 100  # βœ… Multiply by 100

                    # βœ… AI-Based Justification
                    justification_prompt = PromptTemplate.from_template(
                        "Analyze the historical data trends and customer demographics of {mall_name} from your knowledge"
                        "Explain why {replacement_store} is the best replacement for {store_to_replace}, considering these factors: "
                        "- Customer spending habits at {mall_name}. "
                        "- Historical footfall patterns. "
                        "- Expected revenue growth for {replacement_store}. "
                        "- How it aligns with customer demographics and preferences. "
                        "Use these KPIs for prediction: Sales: {sales}, Footfall: {footfall}, Margin: {margin}, Conversion Rate: {conversion_rate}%."
                    )
                    justification_chain = LLMChain(llm=llm, prompt=justification_prompt)
                    justification = justification_chain.run(
                        replacement_store=replacement_store,
                        store_to_replace=store_to_replace,
                        mall_name=selected_mall,
                        sales=f"{sales:,.2f} AED",
                        footfall=f"{footfall:,.0f} visitors",
                        margin=f"{margin:,.2f} AED",
                        conversion_rate=f"{conversion_rate:.2f}%"
                    )

                    st.write(f"πŸ“Œ **{replacement_store}**")
                    st.write(f"πŸ€– **AI Justification:** {justification}")

                    # βœ… Display Projected KPIs
                    st.write(f"πŸ“Š **Projected KPIs for {replacement_store}:**")
                    st.write(f"πŸ’° **Projected Sales:** AED {sales:,.2f}")
                    st.write(f"πŸ‘£ **Projected Footfall:** {footfall:,.0f} visitors")
                    st.write(f"πŸ“ˆ **Projected Margin:** AED {margin:,.2f}")
                    st.write(f"πŸ”„ **Projected Conversion Rate:** {conversion_rate:.2f}%")

                    # βœ… Fetch Competitors (Prefer Sheet Over AI)
                    competitor_list = []
                    if selected_mall in mall_data:
                        mall_df = mall_data[selected_mall]
                        if "Brand Name" in mall_df.columns:
                            competitors = mall_df[mall_df["Brand Name"].str.strip().str.lower() == replacement_store.lower()]
                            competitor_list = competitors.iloc[:, 2:].dropna(axis=1).values.flatten().tolist()
                            competitor_list = [c.strip() for c in competitor_list if isinstance(c, str)]

                    if competitor_list:
                        st.subheader(f"πŸ”Ž Competitors of {replacement_store} (from Sheet)")
                        for competitor in competitor_list:
                            st.write(f"- {competitor}")
                    else:
                        competitor_ai_prompt = PromptTemplate.from_template(
                            "Generate a list of 5 competing brands for {store_name} in the retail industry."
                        )
                        competitor_ai_chain = LLMChain(llm=llm, prompt=competitor_ai_prompt)
                        competitor_list = competitor_ai_chain.run(store_name=replacement_store).split("\n")

                        st.subheader(f"πŸ€– AI-Suggested Competitors for {replacement_store}")
                        for competitor in competitor_list:
                            st.write(f"- {competitor}")


# βœ… AI Chatbot with System Prompt


st.subheader("πŸ’¬ Chat with WaysAhead AI Engine")

system_prompt = """
You are an advanced AI specializing in retail analytics. You help users:
1. Find similar stores based on category and sales performance.
2. Generate insights from sales data.
3. Create visualizations like bar charts, line charts, and heatmaps.
4. If a visualization request is made, generate clean Python code without markdown formatting or any text just give code.
"""

agent = create_pandas_dataframe_agent(
    ChatOpenAI(model="gpt-3.5-turbo", api_key=openai_api_key),
    df_kpi,
    verbose=True,
    agent_type="openai-tools",
    allow_dangerous_code=True,
    handle_parsing_errors=True,
    system_prompt=system_prompt
)

# βœ… User Input
user_query = st.text_input("πŸ” Ask AI for similar stores or analytics:")
if user_query:
    try:
        response = agent.run(user_query)

        # βœ… Detect if AI Generated Python Code for a Chart
        if "import matplotlib.pyplot" in response or "sns.heatmap" in response:
            st.write("πŸ›  AI is generating a chart based on your request...")

            # βœ… Extract Python Code Using Regex
            code_match = re.search(r"```python\n(.*?)```", response, re.DOTALL)
            if code_match:
                ai_generated_code = code_match.group(1)  # Extracted Python code
            else:
                ai_generated_code = response  # Use full response if no markdown formatting

            # βœ… Remove Any Remaining Triple Quotes or Formatting Issues
            ai_generated_code = ai_generated_code.replace("```", "").strip()

            # βœ… Create a dictionary for exec() and ensure df_kpi is accessible
            exec_globals = {"df": df_kpi, "plt": plt, "sns": sns}

            # βœ… Execute the AI-generated Python Code
            try:
                exec(ai_generated_code, exec_globals)

                # βœ… Capture Matplotlib Figure
                fig = plt.gcf()
                buf = BytesIO()
                fig.savefig(buf, format="png")
                buf.seek(0)

                # βœ… Display Image in Streamlit
                st.image(buf, caption="πŸ“Š AI-Generated Chart", use_column_width=True)

            except Exception as e:
                st.error(f"⚠️ Error generating chart: {e}")

        else:
            st.markdown(f"πŸ€– **AI Response:** {response}")

    except Exception as e:
        st.error(f"⚠️ Error: {e}")

st.markdown("---")
st.markdown("πŸš€ **Powered by WaysAhead Global AI Engine**")