Spaces:
Running
Running
app.py
Browse files
app.py
CHANGED
@@ -1,122 +1,121 @@
|
|
1 |
-
import gradio as gr
|
2 |
-
|
3 |
-
import
|
4 |
-
|
5 |
-
from sklearn.
|
6 |
-
|
7 |
-
import
|
8 |
-
import
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
df =
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
index =
|
31 |
-
index.
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
openai.
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
sub_embs =
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
top_contexts
|
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 |
-
gr.Markdown("
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
demo.launch(share=True)
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import os
|
3 |
+
import pandas as pd
|
4 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
5 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
6 |
+
import numpy as np
|
7 |
+
import faiss
|
8 |
+
from sentence_transformers import SentenceTransformer, CrossEncoder
|
9 |
+
import openai
|
10 |
+
|
11 |
+
csv_path = 'train_data.csv'
|
12 |
+
if not os.path.isfile(csv_path):
|
13 |
+
raise FileNotFoundError(f"Could not find CSV at {csv_path}")
|
14 |
+
|
15 |
+
df = pd.read_csv(csv_path, on_bad_lines='skip').dropna()
|
16 |
+
df.columns = ['Question', 'Answer']
|
17 |
+
|
18 |
+
# STEP 3: Build TF-IDF structures (same)
|
19 |
+
questions = df['Question'].tolist()
|
20 |
+
answers = df['Answer'].tolist()
|
21 |
+
qa_pairs = [f"Q: {q}\nA: {a}" for q, a in zip(questions, answers)]
|
22 |
+
tfidf = TfidfVectorizer(max_features=5000).fit(questions)
|
23 |
+
tfidf_matrix = tfidf.transform(questions)
|
24 |
+
|
25 |
+
# STEP 4: Enhanced Embedding of Q+A pairs
|
26 |
+
embedder = SentenceTransformer("all-mpnet-base-v2")
|
27 |
+
qa_embeddings = embedder.encode(qa_pairs, convert_to_numpy=True)
|
28 |
+
dim = qa_embeddings.shape[1]
|
29 |
+
index = faiss.IndexHNSWFlat(dim, 32)
|
30 |
+
index.hnsw.efConstruction = 200
|
31 |
+
index.add(qa_embeddings)
|
32 |
+
|
33 |
+
# STEP 5: Together AI Setup (same)
|
34 |
+
openai.api_key = "cfbafb6a338787841b0295fa7fbe0e4acca77b70ccc3d92bafea2004783b93a3"
|
35 |
+
openai.api_base = "https://api.together.xyz/v1"
|
36 |
+
|
37 |
+
# STEP 6: Smarter Hybrid Context Retriever
|
38 |
+
cross_encoder = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-12-v2")
|
39 |
+
|
40 |
+
def get_top_k_matches(query, lex_n=50, sem_k=20, ce_k=5):
|
41 |
+
# Lexical filter
|
42 |
+
q_tfidf = tfidf.transform([query])
|
43 |
+
lex_scores = cosine_similarity(q_tfidf, tfidf_matrix).flatten()
|
44 |
+
lex_idxs = np.argsort(lex_scores)[-lex_n:][::-1]
|
45 |
+
|
46 |
+
# Embed query
|
47 |
+
q_emb = embedder.encode([query], convert_to_numpy=True)
|
48 |
+
sub_embs = qa_embeddings[lex_idxs]
|
49 |
+
dists = np.linalg.norm(sub_embs - q_emb, axis=1)
|
50 |
+
top_sem_idxs = np.argsort(dists)[:sem_k]
|
51 |
+
cand_idxs = [lex_idxs[i] for i in top_sem_idxs]
|
52 |
+
|
53 |
+
# Cross-encoder for precision rerank
|
54 |
+
candidates = [qa_pairs[i] for i in cand_idxs]
|
55 |
+
pairs = [[query, cand] for cand in candidates]
|
56 |
+
ce_scores = cross_encoder.predict(pairs)
|
57 |
+
scored = sorted(zip(ce_scores, candidates), reverse=True)
|
58 |
+
top_contexts = [ctx for _, ctx in scored[:ce_k]]
|
59 |
+
return top_contexts
|
60 |
+
|
61 |
+
# STEP 7: Smart Prompt Generator (unchanged)
|
62 |
+
def generate_prompt(user_query, context):
|
63 |
+
return f"""
|
64 |
+
You are a smart and friendly assistant helping students with academic-related queries.
|
65 |
+
|
66 |
+
Below is a question from a student. You have been given multiple pieces of relevant academic context pulled from the official college documentation. Carefully analyze all the given Q&A context and generate the most accurate, clear, and helpful answer for the student.
|
67 |
+
|
68 |
+
### Student's Question:
|
69 |
+
{user_query}
|
70 |
+
|
71 |
+
### Top Contexts:
|
72 |
+
{context}
|
73 |
+
|
74 |
+
### Instructions:
|
75 |
+
- Use all relevant context to form your answer.
|
76 |
+
- Avoid repeating the same sentences. Summarize smartly.
|
77 |
+
- Keep your answer polite and student-friendly.
|
78 |
+
- If not found, reply: "I'm sorry, I couldn't find this information in the provided academic context."
|
79 |
+
|
80 |
+
### Your Final Answer:
|
81 |
+
"""
|
82 |
+
|
83 |
+
# STEP 8: Ask a question and get response (unchanged)
|
84 |
+
def ask_bot(question):
|
85 |
+
context = get_top_k_matches(question)
|
86 |
+
prompt = generate_prompt(question, context)
|
87 |
+
response = openai.ChatCompletion.create(
|
88 |
+
model="meta-llama/Llama-3.3-70B-Instruct-Turbo-Free",
|
89 |
+
messages=[{"role":"user","content":prompt}],
|
90 |
+
temperature=0.5, max_tokens=1024
|
91 |
+
)
|
92 |
+
return response.choices[0].message.content
|
93 |
+
|
94 |
+
|
95 |
+
# Define query function
|
96 |
+
def qa_pipeline(query, history=[]):
|
97 |
+
try:
|
98 |
+
response = ask_bot(query)
|
99 |
+
history.append((query, response))
|
100 |
+
return "", history
|
101 |
+
except Exception as e:
|
102 |
+
history.append((query, f"⚠️ Error: {str(e)}"))
|
103 |
+
return "", history
|
104 |
+
|
105 |
+
# Launch UI with blocks
|
106 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
107 |
+
gr.Markdown("## 🤖 KCT Smart Chatbot")
|
108 |
+
gr.Markdown("Ask academic or college-related questions. Powered by your custom dataset.")
|
109 |
+
|
110 |
+
chatbot = gr.Chatbot(label="KCT Chatbot", height=400)
|
111 |
+
msg = gr.Textbox(label="Enter your question here")
|
112 |
+
clear = gr.Button("🧹 Clear Chat")
|
113 |
+
|
114 |
+
# On send
|
115 |
+
def user_submit(user_input, chat_history):
|
116 |
+
return qa_pipeline(user_input, chat_history)
|
117 |
+
|
118 |
+
msg.submit(user_submit, [msg, chatbot], [msg, chatbot])
|
119 |
+
clear.click(lambda: None, None, chatbot, queue=False)
|
120 |
+
|
|
|
121 |
demo.launch(share=True)
|