File size: 7,687 Bytes
948d437
 
 
 
 
a850cfa
948d437
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a850cfa
948d437
 
a850cfa
948d437
 
a850cfa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
948d437
 
 
 
 
 
 
 
 
 
 
 
e347e10
948d437
 
 
 
 
a850cfa
948d437
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a850cfa
 
 
 
 
948d437
 
a850cfa
948d437
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a850cfa
948d437
 
 
 
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
import streamlit as st
import os
import numpy as np
import faiss
from sentence_transformers import SentenceTransformer
from transformers import pipeline

# =========================================================
# PAGE CONFIG
# =========================================================
st.set_page_config(
    page_title="Harry Potter RAG Chatbot",
    page_icon="⚑",
    layout="wide"
)

# =========================================================
# CUSTOM CSS
# =========================================================
st.markdown("""

<style>



.main {

    background-color: #0E1117;

    color: white;

}



.chat-user {

    background-color: #1E293B;

    padding: 15px;

    border-radius: 12px;

    margin-bottom: 10px;

}



.chat-bot {

    background-color: #111827;

    padding: 15px;

    border-radius: 12px;

    margin-bottom: 10px;

}



</style>

""", unsafe_allow_html=True)

# =========================================================
# TITLE
# =========================================================
st.title("⚑ Harry Potter RAG Chatbot")
st.markdown("### Ask anything from the Harry Potter universe")

# =========================================================
# SIDEBAR
# =========================================================
with st.sidebar:

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

    top_k = st.slider(
        "Retrieved Context Chunks",
        min_value=1,
        max_value=10,
        value=3
    )

    st.markdown("---")

    st.markdown("## πŸ“š About")

    st.write("""

This chatbot uses:



βœ… Sentence Transformers  

βœ… FAISS Vector Search  

βœ… Hugging Face Transformers  

βœ… Retrieval-Augmented Generation (RAG)



Runs on Hugging Face Spaces.

""")

# =========================================================
# LOAD LLM
# =========================================================
@st.cache_resource
def load_llm():

    pipe = pipeline(
        "text-generation",
        model="google/gemma-2b"
    )

    return pipe

pipe = load_llm()

# =========================================================
# LOAD EVERYTHING ONLY ONCE
# =========================================================
@st.cache_resource
def load_rag_system():

    # Load embedding model
    embedding_model = SentenceTransformer(
        "all-MiniLM-L6-v2"
    )

    # Dataset path
    data_path = "./src/dataset"

    # Check dataset folder
    if not os.path.exists(data_path):

        st.error("❌ dataset folder not found!")
        st.write("Current files:", os.listdir("./src"))
        st.stop()

    # Read txt files
    all_texts = []

    txt_files = [
        file for file in os.listdir(data_path)
        if file.endswith(".txt")
    ]

    if len(txt_files) == 0:

        st.error("❌ No TXT files found in dataset folder!")
        st.stop()

    # Load file contents
    for file_name in txt_files:

        file_path = os.path.join(data_path, file_name)

        with open(
            file_path,
            "r",
            encoding="utf-8"
        ) as f:

            content = f.read().strip()

            if content:
                all_texts.append(content)

    # Combine all text
    full_text = " ".join(all_texts)

    # Chunking
    chunks = [
        chunk.strip()
        for chunk in full_text.split(". ")
        if chunk.strip()
    ]

    # Speed optimization
    chunks = chunks[:2000]

    # Create embeddings
    embeddings = embedding_model.encode(
        chunks,
        show_progress_bar=True
    )

    # Create FAISS index
    dimension = embeddings.shape[1]

    index = faiss.IndexFlatL2(dimension)

    index.add(np.array(embeddings))

    return (
        embedding_model,
        chunks,
        index,
        len(txt_files)
    )

# =========================================================
# LOAD DATA
# =========================================================
with st.spinner("⚑ Loading AI model and dataset..."):

    embedding_model, chunks, index, total_files = load_rag_system()

st.success(
    f"βœ… Loaded {total_files} dataset files successfully!"
)

# =========================================================
# SESSION STATE
# =========================================================
if "messages" not in st.session_state:

    st.session_state.messages = []

# =========================================================
# DISPLAY CHAT HISTORY
# =========================================================
for message in st.session_state.messages:

    if message["role"] == "user":

        st.markdown(
            f"""

<div class="chat-user">

<b>πŸ§‘ You:</b><br><br>

{message["content"]}

</div>

""",
            unsafe_allow_html=True
        )

    else:

        st.markdown(
            f"""

<div class="chat-bot">

<b>⚑ AI:</b><br><br>

{message["content"]}

</div>

""",
            unsafe_allow_html=True
        )

# =========================================================
# CHAT INPUT
# =========================================================
query = st.chat_input(
    "Ask a Harry Potter question..."
)

# =========================================================
# PROCESS QUERY
# =========================================================
if query:

    # Save user message
    st.session_state.messages.append(
        {
            "role": "user",
            "content": query
        }
    )

    # Display user message
    st.markdown(
        f"""

<div class="chat-user">

<b>πŸ§‘ You:</b><br><br>

{query}

</div>

""",
        unsafe_allow_html=True
    )

    # AI Processing
    with st.spinner("πŸ” Searching Hogwarts Library..."):

        try:

            # Encode query
            query_embedding = embedding_model.encode([query])

            # Search FAISS
            distances, indices = index.search(
                np.array(query_embedding),
                k=top_k
            )

            # Retrieve chunks
            retrieved_chunks = [
                chunks[i]
                for i in indices[0]
            ]

            retrieved_text = "\n".join(retrieved_chunks)

            # Prompt
            prompt = f"""

You are a Harry Potter expert assistant.



Use ONLY the provided context.



================ CONTEXT ================

{retrieved_text}



================ QUESTION ================

{query}



Instructions:

- Give a clear answer

- Keep it beginner-friendly

- Keep it short and accurate

"""

            # Generate response
            response = pipe(
                prompt,
                max_new_tokens=200,
                do_sample=True
            )

            answer = response[0]["generated_text"]

        except Exception as e:

            answer = f"❌ Error: {str(e)}"

    # Save assistant response
    st.session_state.messages.append(
        {
            "role": "assistant",
            "content": answer
        }
    )

    # Display assistant response
    st.markdown(
        f"""

<div class="chat-bot">

<b>⚑ AI:</b><br><br>

{answer}

</div>

""",
        unsafe_allow_html=True
    )

    # Show retrieved context
    with st.expander("πŸ“š Retrieved Context"):

        st.write(retrieved_text)

# =========================================================
# FOOTER
# =========================================================
st.markdown("---")

st.markdown(
    """

<center>

⚑ Built with Streamlit + Transformers + FAISS + SentenceTransformers

</center>

""",
    unsafe_allow_html=True
)