File size: 8,558 Bytes
1c800e6
 
 
12c8491
 
1c800e6
 
12c8491
1c800e6
12c8491
 
bf67f88
 
3d41a3c
bf67f88
 
71d8250
12c8491
 
71d8250
12c8491
 
71d8250
 
12c8491
 
 
 
 
 
 
 
 
 
3d41a3c
12c8491
1c800e6
bf67f88
1c800e6
 
 
 
 
 
 
 
 
 
d56f189
1c800e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e2517e
 
 
 
 
 
 
 
 
1c800e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import pandas as pd
import string
# 1. FIRST, import the main nltk package
import nltk
import os
import logging
from dotenv import load_dotenv

# 2. Set up the NLTK data path BEFORE importing submodules
nltk_data_path = "/tmp/nltk_data"  # Use /tmp for Hugging Face Spaces
os.makedirs(nltk_data_path, exist_ok=True)

# Add it to NLTK paths
nltk.data.path.append(nltk_data_path)

# 3. Download required resources
# 3. Download required resources
nltk.download("punkt", download_dir=nltk_data_path, quiet=True)
nltk.download("punkt_tab", download_dir=nltk_data_path, quiet=True)  # <-- ADD THIS
nltk.download("stopwords", download_dir=nltk_data_path, quiet=True)
nltk.download("wordnet", download_dir=nltk_data_path, quiet=True)
nltk.download("omw-eng", download_dir=nltk_data_path, quiet=True)
 # Important for lemmatizer

# 4. NOW it's safe to import NLTK's submodules
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer

# 5. Continue with other imports
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import google.generativeai as genai

logger = logging.getLogger()

    

logger=logging.getLogger()


load_dotenv("secret_key.env")

my_api_key=os.getenv("YOUR_API_KEY")

# ------------------------ LOAD DATA ----------------------------
try:
    df = pd.read_csv("faq_dataset.csv")
except FileNotFoundError:
    logger.error("Faqs dataset not found")
    st.error("Faqs dataset is missing. Please upload Faqs dataset")
except pd.errors.EmptyDataError:
    logger.error("CSV file is empty")
    st.error("Faqs dataset is empty.")


#--------------------------History----------------------------------
def get_conversation_history(messages, max_history=30):
    """Extract conversation history from messages for AI context"""
    history = []
    # Take last N messages for context (avoid token limits)
    recent_messages = messages[-(max_history * 2):] if len(messages) > (max_history * 2) else messages
    
    for msg in recent_messages:
        if msg["role"] == "user":
            history.append({"role": "user", "content": msg["content"]})
        elif msg["role"] == "bot":
            history.append({"role": "assistant", "content": msg["content"]})
    
    return history

# ------------------------ PREPROCESSING ----------------------------
def preprocessing(text):
    text = text.translate(str.maketrans("", "", string.punctuation))
    tokenization = word_tokenize(text)
    stop_words = set(stopwords.words("english"))
    tokenization = [word for word in tokenization if word.lower() not in stop_words]
    lemmatizer = WordNetLemmatizer()
    tokenization = [lemmatizer.lemmatize(word, pos="v") for word in tokenization]
    return " ".join(tokenization)

df["question"] = df["question"].apply(preprocessing)

vectorizer = TfidfVectorizer()
try:
    x = vectorizer.fit_transform(df["question"])
except Exception as e:
    logger.error(f"Vectorizer error {e}")
    st.error("⚠️ Something went wrong while understanding your question.")


#------------------------ PRODUCT LIST ----------------------------
product_list = [
    "Electronics","Home Appliances","Accessories","Gadgets",
    "Mobile Phones","Smartphones",
    "LG Refrigerators","LG Washing Machines","LG Microwave Ovens","LG Air Conditioners","LG Televisions","LG Irons",
    "Laptops:HP,Dell,Asus ROG,Lenovo,MSI,Acer",
    "Gaming Laptops:Asus ROG,Lenovo,MSI,Acer",
    "Samsung Mobiles","Apple Mobiles","Xiaomi Mobiles",
]

# ------------------------ GEMINI MODEL ----------------------------
genai.configure(api_key=my_api_key)

model = genai.GenerativeModel(
    "gemini-2.5-flash-lite",
    generation_config={"max_output_tokens": 1080, "temperature": 0.2}
)

# ------------------------ PRODUCT SUGGESTION ----------------------------

def Product_suggestion(user_input,conversation_history):
    prompt = f"""
You are a professional product recommendation assistant.

You can only suggest products from this list:
{product_list}

When a user asks for a product suggestion, follow these rules:

1. Only suggest items that exist in the provided list. Never invent products.
2. If the user asks "Suggest me X under Y price":
    - Suggest the top 3 products that match the category/brand and are under the price limit.
    - Include for each product:
        - Product name
        - Brand
        - Category
        - Price in PKR
        - Key specifications
    - Highlight one product as the "best choice" with a short reason.
3. If nothing matches, respond with a friendly message like:
   "Sorry, no product is available under that price."
   {user_input}
Previous conversation history:
{conversation_history}
ALWAYS continue the context based on the full history above.
Maintain conversation flow and remember previous topics discussed.
"""

    try:
        response = model.generate_content(prompt)
        return response.text
    except Exception as e:
        logger.error(f"Gemini API Error: {e}")
        return "⚠️ Sorry, our AI recommendation service is temporarily unavailable."

# ------------------------ FAQ CHATBOT ----------------------------
def faq_chatbot(user_input):
    clean = preprocessing(user_input)
    vectorized = vectorizer.transform([clean])
    similarity = cosine_similarity(x, vectorized)
    index = similarity.argmax()
    if similarity.max() > 0.3:  # Confidence threshold
        return df["answer"].iloc[index]
    else:
        return "I'm not sure I understand. Could you please rephrase your question or contact our support team at support@example.com?"

# ------------------------ STREAMLIT UI (CHATGPT STYLE) ----------------------------
st.set_page_config(page_title="AI Support Chatbot", layout="wide")
st.markdown("""
    <style>
        
        .user-msg {
            background: #0a84ff;
            padding: 10px 15px;
            border-radius: 12px;
            margin: 10px 0;
            color: white;
            width: fit-content;
            max-width: 80%;
            margin-left: auto;
        }
        .bot-msg {
            background: #2e2e2e;
            padding: 10px 15px;
            border-radius: 12px;
            margin: 10px 0;
            color: white;
            width: fit-content;
            max-width: 80%;
        }
    </style>
""", unsafe_allow_html=True)

st.title("💬 AI Customer Support & Product Suggestion Chatbot")

if "chat" not in st.session_state:
    st.session_state.chat = []

# ------------------------ CHAT WINDOW ----------------------------
st.markdown("<div class='chat-container'>", unsafe_allow_html=True)
for sender, msg in st.session_state.chat:
    if sender == "user":
        st.markdown(f"<div class='user-msg'>{msg}</div>", unsafe_allow_html=True)
    else:
        st.markdown(f"<div class='bot-msg'>{msg}</div>", unsafe_allow_html=True)
st.markdown("</div>", unsafe_allow_html=True)

# ------------------------ USER INPUT ----------------------------
if "messages" not in st.session_state:
    st.session_state.messages = []

user_input = st.chat_input("Ask something...")
if user_input is not None:
    msg=user_input.strip()

    if not msg:
        st.warning("⚠️ Please type something.")
    elif len(msg) > 300:
        st.warning("⚠️ Your message is too long, please keep it shorter.")
    else:

        st.session_state.chat.append(("user", user_input))
        st.session_state.messages.append({"role": "user", "content": user_input})

        typing_placeholder = st.empty()
        typing_placeholder.markdown(
            "<div class='bot-msg'><span class='bot-icon'>🤖</span>Typing...</div>",
            unsafe_allow_html=True
        )

        conversation_history = get_conversation_history(st.session_state.messages)


        if msg.lower() in ['hello','hi','hey']:
            bot_reply=f"{user_input} sir i am your product assistance how can i help you"
        elif msg.lower() in ["okay","ok"]:
            bot_reply="If you want further detail contact us at -> support@example.com"
        # Product Suggestion
        elif any(k in user_input.lower() for k in ["suggest", "recommend", "phone", "mobile", "electronics", "under"]):
            bot_reply = Product_suggestion(user_input,conversation_history)

        # FAQ Search
        else:
            bot_reply = faq_chatbot(user_input)

        st.session_state.chat.append(("bot", bot_reply))
        st.session_state.messages.append({"role": "assistant", "content": bot_reply})

        st.rerun()