File size: 9,120 Bytes
0a76730
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import pandas as pd
import numpy as np
import re

from sklearn.feature_extraction.text import TfidfVectorizer
from sentence_transformers import SentenceTransformer
from rank_bm25 import BM25Okapi
from rapidfuzz import fuzz
import faiss
import nltk

# ==============================
# FIX NLTK (HUGGINGFACE SAFE)
# ==============================
nltk.download('wordnet', quiet=True)
from nltk.corpus import wordnet

# ==============================
# PAGE CONFIG
# ==============================
st.set_page_config(page_title="Multi Search Engine", layout="wide")
st.title("πŸ” Advanced Multi-Search Product Engine")

# ==============================
# LOAD MODEL (NO CACHE BUG)
# ==============================
if "model" not in st.session_state:
    with st.spinner("Loading AI model..."):
        st.session_state.model = SentenceTransformer(
            'all-MiniLM-L6-v2',
            device='cpu'
        )

model = st.session_state.model

# ==============================
# SEARCH INFO
# ==============================
search_info = {
    "Keyword": ("Find exact word match", "iphone β†’ iPhone"),
    "Regex": ("Pattern-based search", "^S β†’ Samsung"),
    "Boolean": ("Use AND / OR", "nike AND shoes"),
    "Fuzzy": ("Handles spelling mistakes", "iphon β†’ iPhone"),
    "N-Gram": ("Partial word match", "iph β†’ iPhone"),
    "Prefix": ("Starts with query", "app β†’ Apple"),
    "Suffix": ("Ends with query", "laptop β†’ Dell Laptop"),
    "TF-IDF": ("Ranks important words", "wireless headphones"),
    "BM25": ("Advanced keyword ranking", "gaming laptop"),
    "Semantic": ("Understands meaning", "sports footwear"),
    "FAISS": ("Fast semantic search", "music device"),
    "Hybrid": ("Keyword + meaning", "sports shoes"),
    "Query Expansion": ("Adds similar words", "speaker β†’ audio"),
    "Weighted Hybrid": ("Weighted ranking", "better accuracy"),
    "Ensemble": ("Combine all methods", "best results")
}

# ==============================
# CACHE PREPROCESSING (STABLE)
# ==============================
@st.cache(allow_output_mutation=True)
def preprocess_data(products):

    # TF-IDF
    tfidf = TfidfVectorizer()
    tfidf_matrix = tfidf.fit_transform(products)

    # Embeddings (NO progress bar β†’ HF fix)
    embeddings = model.encode(products, batch_size=64, show_progress_bar=False)

    # Normalize for FAISS
    faiss.normalize_L2(embeddings)

    # FAISS index
    dim = embeddings.shape[1]
    index = faiss.IndexFlatIP(dim)
    index.add(np.array(embeddings))

    # BM25
    tokenized = [p.split() for p in products]
    bm25 = BM25Okapi(tokenized)

    return tfidf, tfidf_matrix, embeddings, index, bm25


@st.cache(allow_output_mutation=True)
def get_synonyms(word):
    synonyms = set()
    for syn in wordnet.synsets(word):
        for lemma in syn.lemmas():
            synonyms.add(lemma.name())
    return synonyms

# ==============================
# FILE LOAD
# ==============================
uploaded_file = st.file_uploader("Upload CSV", type=["csv"])

if uploaded_file:
    df = pd.read_csv(uploaded_file)
else:
    st.info("Using sample dataset")
    df = pd.DataFrame({
        "product_name": [
            "iPhone 14 Pro",
            "Samsung Galaxy S23",
            "Nike Running Shoes",
            "Dell Gaming Laptop",
            "Bluetooth Speaker"
        ],
        "category": ["Mobile", "Mobile", "Footwear", "Laptop", "Electronics"],
        "brand": ["Apple", "Samsung", "Nike", "Dell", "JBL"],
        "description": [
            "Latest smartphone",
            "Android flagship phone",
            "Comfort sports shoes",
            "High performance laptop",
            "Portable music device"
        ]
    })

st.subheader("πŸ“„ Data Preview")
st.dataframe(df.head())

# ==============================
# COMBINE TEXT
# ==============================
df["combined"] = (
    df["product_name"].astype(str) + " " +
    df["category"].astype(str) + " " +
    df["brand"].astype(str) + " " +
    df["description"].astype(str)
)

products = df["combined"].tolist()

# ==============================
# PREPROCESS (ONLY ONCE)
# ==============================
with st.spinner("Processing data..."):
    tfidf, tfidf_matrix, embeddings, index, bm25 = preprocess_data(products)

# ==============================
# SEARCH FUNCTIONS
# ==============================
def keyword_search(q):
    return [(i, 1) for i, p in enumerate(products) if q.lower() in p.lower()]

def regex_search(q):
    return [(i, 1) for i, p in enumerate(products) if re.search(q, p, re.IGNORECASE)]

def boolean_search(q):
    if "AND" in q:
        terms = q.split("AND")
        return [(i, 1) for i, p in enumerate(products)
                if all(t.strip().lower() in p.lower() for t in terms)]
    elif "OR" in q:
        terms = q.split("OR")
        return [(i, 1) for i, p in enumerate(products)
                if any(t.strip().lower() in p.lower() for t in terms)]
    return []

def fuzzy_search(q):
    scores = [(i, fuzz.ratio(q, p)) for i, p in enumerate(products)]
    return sorted(scores, key=lambda x: x[1], reverse=True)[:10]

def ngram_search(q):
    return [(i, 1) for i, p in enumerate(products) if q[:3].lower() in p.lower()]

def prefix_search(q):
    return [(i, 1) for i, p in enumerate(products) if p.lower().startswith(q.lower())]

def suffix_search(q):
    return [(i, 1) for i, p in enumerate(products) if p.lower().endswith(q.lower())]

def tfidf_search(q):
    q_vec = tfidf.transform([q])
    scores = (tfidf_matrix @ q_vec.T).toarray().flatten()
    idx = np.argsort(scores)[::-1][:10]
    return [(i, float(scores[i])) for i in idx]

def bm25_search(q):
    scores = bm25.get_scores(q.split())
    idx = np.argsort(scores)[::-1][:10]
    return [(i, float(scores[i])) for i in idx]

def semantic_search(q):
    q_emb = model.encode([q], show_progress_bar=False)
    faiss.normalize_L2(q_emb)
    scores = np.dot(embeddings, q_emb.T).flatten()
    idx = np.argsort(scores)[::-1][:10]
    return [(i, float(scores[i])) for i in idx]

def faiss_search(q):
    q_emb = model.encode([q], show_progress_bar=False)
    faiss.normalize_L2(q_emb)
    D, I = index.search(np.array(q_emb), 10)
    return [(i, float(D[0][idx])) for idx, i in enumerate(I[0])]

def hybrid_search(q):
    tfidf_res = dict(tfidf_search(q))
    sem_res = dict(semantic_search(q))
    combined = {i: tfidf_res.get(i, 0) + sem_res.get(i, 0) for i in range(len(products))}
    return sorted(combined.items(), key=lambda x: x[1], reverse=True)[:10]

def query_expansion_search(q):
    synonyms = get_synonyms(q)
    expanded_query = q + " " + " ".join(synonyms)
    return tfidf_search(expanded_query)

def weighted_hybrid(q):
    tfidf_res = dict(tfidf_search(q))
    sem_res = dict(semantic_search(q))
    bm25_res = dict(bm25_search(q))

    combined = {}
    for i in range(len(products)):
        combined[i] = (
            0.4 * tfidf_res.get(i, 0) +
            0.4 * sem_res.get(i, 0) +
            0.2 * bm25_res.get(i, 0)
        )
    return sorted(combined.items(), key=lambda x: x[1], reverse=True)[:10]

def ensemble_search(q):
    results = {}
    for func in [tfidf_search, semantic_search, bm25_search]:
        for i, score in func(q):
            results[i] = results.get(i, 0) + score
    return sorted(results.items(), key=lambda x: x[1], reverse=True)[:10]

# ==============================
# UI
# ==============================
search_type = st.selectbox("Select Search Type", list(search_info.keys()))

explanation, example = search_info[search_type]

st.markdown(f"""

### πŸ” {search_type} Search

- **Explanation:** {explanation}

- **Example:** `{example}`

""")

query = st.text_input("Enter your search query")

if st.button("Try Example"):
    query = example.split("β†’")[0].strip()
    st.success(f"Example loaded: {query}")

top_k = st.slider("Top Results", 5, 20, 10)

if st.button("Search"):
    if not query:
        st.warning("Enter query")
    else:
        func_map = {
            "Keyword": keyword_search,
            "Regex": regex_search,
            "Boolean": boolean_search,
            "Fuzzy": fuzzy_search,
            "N-Gram": ngram_search,
            "Prefix": prefix_search,
            "Suffix": suffix_search,
            "TF-IDF": tfidf_search,
            "BM25": bm25_search,
            "Semantic": semantic_search,
            "FAISS": faiss_search,
            "Hybrid": hybrid_search,
            "Query Expansion": query_expansion_search,
            "Weighted Hybrid": weighted_hybrid,
            "Ensemble": ensemble_search
        }

        results = func_map[search_type](query)[:top_k]

        indices = [i for i, _ in results]
        result_df = df.iloc[indices].copy()
        result_df["Score"] = [score for _, score in results]

        st.subheader("πŸ”Ž Results")
        st.dataframe(result_df)