File size: 4,652 Bytes
c798357
a5a0539
c798357
a5a0539
 
c798357
 
8987fa8
d75eaf5
8987fa8
c798357
109c402
 
d75eaf5
109c402
 
19c5fbf
109c402
fdcf881
dc65e52
c798357
 
d75eaf5
c798357
 
d75eaf5
c798357
 
 
d75eaf5
 
c798357
 
 
 
 
 
d75eaf5
 
c798357
 
d75eaf5
c798357
 
 
 
 
d75eaf5
 
c798357
 
 
 
 
d75eaf5
 
c798357
 
 
 
d75eaf5
c798357
 
 
 
d75eaf5
c798357
 
d75eaf5
c798357
 
d75eaf5
 
 
 
c798357
 
d75eaf5
109c402
c798357
d75eaf5
 
c798357
d75eaf5
c798357
 
d75eaf5
c798357
 
 
 
 
 
 
d75eaf5
 
c798357
 
d75eaf5
c798357
a5a0539
109c402
d75eaf5
 
109c402
 
 
d75eaf5
 
 
a5a0539
d75eaf5
 
 
109c402
c798357
d75eaf5
a5a0539
c798357
109c402
c798357
a5a0539
 
 
d75eaf5
109c402
d75eaf5
 
a5a0539
 
c798357
d75eaf5
 
109c402
 
a5a0539
 
c798357
d75eaf5
c798357
 
 
109c402
d75eaf5
109c402
 
d75eaf5
 
 
109c402
 
d75eaf5
 
 
c798357
 
d75eaf5
 
 
 
c798357
 
d75eaf5
 
109c402
a5a0539
109c402
 
c798357
d75eaf5
c798357
 
109c402
 
d75eaf5
 
 
 
109c402
c798357
d75eaf5
 
 
 
 
 
 
 
 
c798357
d75eaf5
 
 
 
c798357
d75eaf5
 
 
 
c798357
d75eaf5
c798357
d75eaf5
 
c798357
d75eaf5
 
c798357
d75eaf5
c798357
d75eaf5
 
 
c798357
 
d75eaf5
 
 
 
 
 
 
 
 
 
c798357
d75eaf5
c798357
a5a0539
d75eaf5
 
 
a5a0539
 
c798357
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
import os
import gradio as gr

from huggingface_hub import InferenceClient

from scraper import scrape

from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_community.vectorstores import FAISS


# =====================================================
# 0. Config
# =====================================================

HF_TOKEN = os.environ.get("HF_API_KEY")

MODEL_NAME = "HuggingFaceH4/zephyr-7b-beta"  # Much better for RAG


# =====================================================
# 1. Load + Build Knowledge Base
# =====================================================

print("🔄 Scraping website...")

raw_docs = scrape()

texts = []
metas = []

for d in raw_docs:
    texts.append(d["text"])
    metas.append({"source": d["source"]})


print("✂️ Splitting documents...")

splitter = RecursiveCharacterTextSplitter(
    chunk_size=800,
    chunk_overlap=150,
)

documents = splitter.create_documents(texts, metas)


print("🧠 Building embeddings...")

embeddings = HuggingFaceEmbeddings(
    model_name="sentence-transformers/all-mpnet-base-v2"
)


print("📦 Building vector store...")

db = FAISS.from_documents(documents, embeddings)

retriever = db.as_retriever(search_kwargs={"k": 4})


print("✅ Knowledge base ready!")


# =====================================================
# 2. Prompt Builder
# =====================================================

def build_prompt(question, docs):

    context = "\n\n".join(
        [
            f"[Source: {d.metadata['source']}]\n{d.page_content}"
            for d in docs
        ]
    )

    prompt = f"""
You are an academic assistant for SPJIMR.

Answer ONLY using the context below.
If information is missing, say "I don't know."

---------------------
CONTEXT:
{context}
---------------------

QUESTION:
{question}

ANSWER:
"""

    return prompt.strip()


# =====================================================
# 3. LLM Client
# =====================================================

client = InferenceClient(
    model=MODEL_NAME,
    token=HF_TOKEN
)


# =====================================================
# 4. Chat Function (Fixed Retriever API)
# =====================================================

def chat(message, history):

    # New LangChain API
    docs = retriever.invoke(message)

    prompt = build_prompt(message, docs)

    messages = [
        {"role": "user", "content": prompt}
    ]

    response = ""

    for chunk in client.chat_completion(
        messages=messages,
        max_tokens=700,
        temperature=0.3,
        stream=True,
    ):

        if chunk.choices[0].delta.content:
            token = chunk.choices[0].delta.content
            response += token
            yield response


# =====================================================
# 5. Minimal Dark UI
# =====================================================

custom_css = """
body {
    background: #0f172a !important;
}

.gradio-container {
    max-width: 900px !important;
    margin: auto !important;
}

h1 {
    color: #e5e7eb;
    text-align: center;
}

.subtitle {
    text-align: center;
    color: #9ca3af;
    margin-bottom: 20px;
}

footer {
    display: none !important;
}
"""


# =====================================================
# 6. App
# =====================================================

with gr.Blocks(
    css=custom_css,
    theme=gr.themes.Base(
        primary_hue="indigo",
        neutral_hue="slate",
    ),
) as demo:

    gr.Markdown(
        """
        # 🎓 SPJIMR AI Assistant
        <div class="subtitle">
        Ask questions based on official SPJIMR website
        </div>
        """,
        elem_id="title"
    )

    chatbot = gr.Chatbot(
        height=520,
        bubble_full_width=False,
    )

    msg = gr.Textbox(
        placeholder="Ask about programs, admissions, faculty...",
        show_label=False,
    )

    clear = gr.Button("Clear Chat")

    def user(user_message, history):
        return "", history + [[user_message, None]]

    def bot(history):
        user_message = history[-1][0]

        history[-1][1] = ""

        for chunk in chat(user_message, history):
            history[-1][1] = chunk
            yield history


    msg.submit(
        user,
        [msg, chatbot],
        [msg, chatbot],
        queue=False,
    ).then(
        bot,
        chatbot,
        chatbot,
    )

    clear.click(lambda: [], None, chatbot)


# =====================================================
# 7. Launch
# =====================================================

if __name__ == "__main__":
    demo.launch()