File size: 5,376 Bytes
7ce6975
 
 
 
 
eba760d
 
 
7ce6975
 
 
 
 
 
 
eba760d
 
 
7ce6975
 
 
 
 
 
 
 
eba760d
 
 
 
 
7ce6975
 
eba760d
7ce6975
 
 
 
 
 
eba760d
 
 
7ce6975
 
eba760d
 
 
7ce6975
eba760d
 
 
7ce6975
 
 
 
 
 
 
 
 
eba760d
 
 
7ce6975
 
 
 
 
 
 
 
 
eba760d
 
 
7ce6975
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eba760d
7ce6975
 
eba760d
 
 
7ce6975
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eba760d
 
 
7ce6975
 
 
 
 
eba760d
 
7ce6975
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eba760d
7ce6975
 
 
 
eba760d
 
 
7ce6975
 
eba760d
7ce6975
 
eba760d
7ce6975
 
 
 
 
 
 
 
 
 
 
eba760d
7ce6975
 
 
 
 
 
 
 
 
 
 
eba760d
7ce6975
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eba760d
 
7ce6975
 
 
 
 
 
eba760d
 
 
 
 
 
 
7ce6975
 
eba760d
7ce6975
 
 
eba760d
 
 
 
 
 
 
7ce6975
 
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
import streamlit as st
import chromadb
from sentence_transformers import SentenceTransformer
import uuid

# ==========================================
# PAGE CONFIG
# ==========================================

st.set_page_config(
    page_title="Semantic Search Engine",
    page_icon="πŸ”",
    layout="wide"
)

# ==========================================
# CUSTOM CSS
# ==========================================

st.markdown("""

<style>



.main {

    padding-top: 1rem;

}



.block-container {

    padding-top: 2rem;

}



.result-box {

    padding: 1rem;

    border-radius: 12px;

    border: 1px solid #333;

    margin-bottom: 10px;

}



</style>

""", unsafe_allow_html=True)

# ==========================================
# TITLE
# ==========================================

st.title("πŸ” Semantic Search Engine")
st.caption(
    "Search documents using semantic similarity powered by Hugging Face embeddings."
)

# ==========================================
# LOAD MODEL
# ==========================================

@st.cache_resource
def load_model():
    return SentenceTransformer(
        "sentence-transformers/all-MiniLM-L6-v2"
    )

model = load_model()

# ==========================================
# CHROMADB
# ==========================================

client = chromadb.PersistentClient(
    path="./chroma_db"
)

collection = client.get_or_create_collection(
    name="documents"
)

# ==========================================
# SIDEBAR
# ==========================================

with st.sidebar:

    st.header("βš™οΈ Settings")

    top_k = st.slider(
        "Number of Results",
        min_value=1,
        max_value=10,
        value=5
    )

    st.markdown("---")

    st.info(
        "Semantic Search compares meanings instead of matching exact keywords."
    )

# ==========================================
# DATABASE STATS
# ==========================================

st.markdown("## πŸ“Š Database Statistics")

col1, col2 = st.columns(2)

with col1:
    st.metric(
        "Documents Stored",
        collection.count()
    )

with col2:
    st.metric(
        "Embedding Model",
        "MiniLM-L6-v2"
    )

# ==========================================
# DOCUMENT INPUT
# ==========================================

st.markdown("---")
st.markdown("## πŸ“₯ Add Documents")

documents = st.text_area(
    "Enter documents (one document per line)",
    height=220,
    placeholder="""

Python is a programming language.

FastAPI is used to build APIs.

Machine learning learns patterns from data.

ChromaDB stores embeddings.

"""
)

if st.button("πŸ’Ύ Store Documents"):

    docs = [
        doc.strip()
        for doc in documents.split("\n")
        if doc.strip()
    ]

    if len(docs) == 0:
        st.warning("Please enter at least one document.")

    else:

        with st.spinner("Generating embeddings..."):

            embeddings = model.encode(
                docs
            ).tolist()

            collection.add(
                ids=[
                    str(uuid.uuid4())
                    for _ in docs
                ],
                documents=docs,
                embeddings=embeddings
            )

        st.success(
            f"{len(docs)} document(s) stored successfully."
        )

        st.rerun()

# ==========================================
# SEARCH SECTION
# ==========================================

st.markdown("---")
st.markdown("## πŸ”Ž Search")

query = st.text_input(
    "Enter your search query",
    placeholder="How can I build an API?"
)

if st.button(
    "πŸš€ Search",
    use_container_width=True
):

    if collection.count() == 0:

        st.error(
            "No documents available. Add documents first."
        )

    elif not query.strip():

        st.warning(
            "Please enter a search query."
        )

    else:

        with st.spinner(
            "Searching similar documents..."
        ):

            query_embedding = model.encode(
                query
            ).tolist()

            results = collection.query(
                query_embeddings=[
                    query_embedding
                ],
                n_results=min(
                    top_k,
                    collection.count()
                )
            )

        docs = results["documents"][0]
        distances = results["distances"][0]

        st.markdown("---")
        st.markdown("## πŸ“„ Search Results")

        for rank, (doc, distance) in enumerate(
            zip(docs, distances),
            start=1
        ):

            # Relevance Label
            if distance < 0.7:
                relevance = "🟒 Highly Relevant"
            elif distance < 1.2:
                relevance = "🟑 Relevant"
            else:
                relevance = "πŸ”΄ Weak Match"

            with st.expander(
                f"#{rank} | {relevance}"
            ):
                st.write(doc)

                st.caption(
                    f"Distance Score: {distance:.4f}"
                )

# ==========================================
# FOOTER
# ==========================================

st.markdown("---")