Spaces:
Running
Running
Update rag.py
Browse files
rag.py
CHANGED
@@ -2,14 +2,10 @@ import json
|
|
2 |
from sentence_transformers import SentenceTransformer, util
|
3 |
from groq import Groq
|
4 |
from datetime import datetime
|
5 |
-
import requests
|
6 |
-
from io import BytesIO
|
7 |
-
from PIL import Image, ImageDraw, ImageFont
|
8 |
-
import numpy as np
|
9 |
-
from dotenv import load_dotenv
|
10 |
import os
|
11 |
-
from datasets import load_dataset, Dataset, DatasetDict
|
12 |
import pandas as pd
|
|
|
|
|
13 |
|
14 |
# Load environment variables
|
15 |
load_dotenv()
|
@@ -17,21 +13,21 @@ load_dotenv()
|
|
17 |
# Initialize Groq client
|
18 |
groq_client = Groq(api_key=os.getenv("GROQ_API_KEY"))
|
19 |
|
20 |
-
# Load
|
21 |
similarity_model = SentenceTransformer('paraphrase-MiniLM-L6-v2')
|
22 |
|
23 |
-
#
|
24 |
-
HF_DATASET_REPO = "midrees2806/unmatched_queries"
|
25 |
-
HF_TOKEN = os.getenv("HF_TOKEN")
|
26 |
|
27 |
-
# Greeting
|
28 |
GREETINGS = [
|
29 |
"hi", "hello", "hey", "good morning", "good afternoon", "good evening",
|
30 |
"assalam o alaikum", "salam", "namaste", "hola", "bonjour", "hi there",
|
31 |
"hey there", "greetings", "howdy"
|
32 |
]
|
33 |
|
34 |
-
#
|
35 |
try:
|
36 |
with open('dataset.json', 'r') as f:
|
37 |
dataset = json.load(f)
|
@@ -46,31 +42,24 @@ dataset_questions = [item.get("input", "").lower().strip() for item in dataset]
|
|
46 |
dataset_answers = [item.get("response", "") for item in dataset]
|
47 |
dataset_embeddings = similarity_model.encode(dataset_questions, convert_to_tensor=True)
|
48 |
|
49 |
-
#
|
50 |
def manage_unmatched_queries(query: str):
|
51 |
-
"""Save unmatched queries to HF Dataset with error handling"""
|
52 |
try:
|
53 |
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
54 |
-
|
55 |
-
# Load existing dataset or create new
|
56 |
try:
|
57 |
ds = load_dataset(HF_DATASET_REPO, token=HF_TOKEN)
|
58 |
df = ds["train"].to_pandas()
|
59 |
except:
|
60 |
df = pd.DataFrame(columns=["Query", "Timestamp", "Processed"])
|
61 |
-
|
62 |
-
# Append new query (avoid duplicates)
|
63 |
if query not in df["Query"].values:
|
64 |
new_entry = {"Query": query, "Timestamp": timestamp, "Processed": False}
|
65 |
df = pd.concat([df, pd.DataFrame([new_entry])], ignore_index=True)
|
66 |
-
|
67 |
-
# Push to Hub
|
68 |
updated_ds = Dataset.from_pandas(df)
|
69 |
updated_ds.push_to_hub(HF_DATASET_REPO, token=HF_TOKEN)
|
70 |
except Exception as e:
|
71 |
print(f"Failed to save query: {e}")
|
72 |
|
73 |
-
#
|
74 |
def query_groq_llm(prompt, model_name="llama3-70b-8192"):
|
75 |
try:
|
76 |
chat_completion = groq_client.chat.completions.create(
|
@@ -87,63 +76,35 @@ def query_groq_llm(prompt, model_name="llama3-70b-8192"):
|
|
87 |
print(f"Error querying Groq API: {e}")
|
88 |
return ""
|
89 |
|
90 |
-
|
91 |
-
user_input = input_field.value.strip()
|
92 |
-
|
93 |
-
if not user_input:
|
94 |
-
show_message("Please enter a question")
|
95 |
-
return
|
96 |
-
|
97 |
-
response = get_best_answer(user_input)
|
98 |
-
|
99 |
-
if response.get('should_scroll', False):
|
100 |
-
scroll_to_answer()
|
101 |
-
|
102 |
-
display_response(response.get('response', ''))
|
103 |
-
|
104 |
def get_best_answer(user_input):
|
105 |
-
# 1. Check for empty input
|
106 |
if not user_input.strip():
|
107 |
-
return
|
108 |
-
|
109 |
user_input_lower = user_input.lower().strip()
|
110 |
-
|
111 |
-
# 2. Check for minimum word count (3 words)
|
112 |
if len(user_input_lower.split()) < 3 and not any(greet in user_input_lower for greet in GREETINGS):
|
113 |
-
return
|
114 |
-
|
115 |
-
"should_scroll": True
|
116 |
-
}
|
117 |
-
|
118 |
-
# 3. Handle greetings (regardless of word count)
|
119 |
if any(greet in user_input_lower for greet in GREETINGS):
|
120 |
greeting_response = query_groq_llm(
|
121 |
f"You are an official assistant for University of Education Lahore. "
|
122 |
f"Respond to this greeting in a friendly and professional manner: {user_input}"
|
123 |
)
|
124 |
-
return
|
125 |
-
|
126 |
-
"should_scroll": True
|
127 |
-
}
|
128 |
-
|
129 |
-
# 4. Check if question is about fee
|
130 |
if any(keyword in user_input_lower for keyword in ["fee structure", "fees structure", "semester fees", "semester fee"]):
|
131 |
-
return
|
132 |
-
"
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
"should_scroll": True
|
138 |
-
}
|
139 |
-
|
140 |
-
# π Continue with normal similarity-based logic
|
141 |
user_embedding = similarity_model.encode(user_input_lower, convert_to_tensor=True)
|
142 |
similarities = util.pytorch_cos_sim(user_embedding, dataset_embeddings)[0]
|
143 |
best_match_idx = similarities.argmax().item()
|
144 |
best_score = similarities[best_match_idx].item()
|
145 |
|
146 |
-
# Save unmatched queries (threshold = 0.65)
|
147 |
if best_score < 0.65:
|
148 |
manage_unmatched_queries(user_input)
|
149 |
|
@@ -165,17 +126,12 @@ def get_best_answer(user_input):
|
|
165 |
if llm_response:
|
166 |
for marker in ["Improved Answer:", "Official Answer:"]:
|
167 |
if marker in llm_response:
|
168 |
-
|
169 |
-
|
170 |
-
else:
|
171 |
-
response = llm_response
|
172 |
else:
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
"response": response,
|
180 |
-
"should_scroll": True
|
181 |
-
}
|
|
|
2 |
from sentence_transformers import SentenceTransformer, util
|
3 |
from groq import Groq
|
4 |
from datetime import datetime
|
|
|
|
|
|
|
|
|
|
|
5 |
import os
|
|
|
6 |
import pandas as pd
|
7 |
+
from datasets import load_dataset, Dataset
|
8 |
+
from dotenv import load_dotenv
|
9 |
|
10 |
# Load environment variables
|
11 |
load_dotenv()
|
|
|
13 |
# Initialize Groq client
|
14 |
groq_client = Groq(api_key=os.getenv("GROQ_API_KEY"))
|
15 |
|
16 |
+
# Load similarity model
|
17 |
similarity_model = SentenceTransformer('paraphrase-MiniLM-L6-v2')
|
18 |
|
19 |
+
# Config
|
20 |
+
HF_DATASET_REPO = "midrees2806/unmatched_queries"
|
21 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
22 |
|
23 |
+
# Greeting list
|
24 |
GREETINGS = [
|
25 |
"hi", "hello", "hey", "good morning", "good afternoon", "good evening",
|
26 |
"assalam o alaikum", "salam", "namaste", "hola", "bonjour", "hi there",
|
27 |
"hey there", "greetings", "howdy"
|
28 |
]
|
29 |
|
30 |
+
# Load local dataset
|
31 |
try:
|
32 |
with open('dataset.json', 'r') as f:
|
33 |
dataset = json.load(f)
|
|
|
42 |
dataset_answers = [item.get("response", "") for item in dataset]
|
43 |
dataset_embeddings = similarity_model.encode(dataset_questions, convert_to_tensor=True)
|
44 |
|
45 |
+
# Save unmatched queries to Hugging Face
|
46 |
def manage_unmatched_queries(query: str):
|
|
|
47 |
try:
|
48 |
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
|
|
|
49 |
try:
|
50 |
ds = load_dataset(HF_DATASET_REPO, token=HF_TOKEN)
|
51 |
df = ds["train"].to_pandas()
|
52 |
except:
|
53 |
df = pd.DataFrame(columns=["Query", "Timestamp", "Processed"])
|
|
|
|
|
54 |
if query not in df["Query"].values:
|
55 |
new_entry = {"Query": query, "Timestamp": timestamp, "Processed": False}
|
56 |
df = pd.concat([df, pd.DataFrame([new_entry])], ignore_index=True)
|
|
|
|
|
57 |
updated_ds = Dataset.from_pandas(df)
|
58 |
updated_ds.push_to_hub(HF_DATASET_REPO, token=HF_TOKEN)
|
59 |
except Exception as e:
|
60 |
print(f"Failed to save query: {e}")
|
61 |
|
62 |
+
# Query Groq LLM
|
63 |
def query_groq_llm(prompt, model_name="llama3-70b-8192"):
|
64 |
try:
|
65 |
chat_completion = groq_client.chat.completions.create(
|
|
|
76 |
print(f"Error querying Groq API: {e}")
|
77 |
return ""
|
78 |
|
79 |
+
# Main logic function to be called from Gradio
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
80 |
def get_best_answer(user_input):
|
|
|
81 |
if not user_input.strip():
|
82 |
+
return "Please enter a valid question."
|
83 |
+
|
84 |
user_input_lower = user_input.lower().strip()
|
85 |
+
|
|
|
86 |
if len(user_input_lower.split()) < 3 and not any(greet in user_input_lower for greet in GREETINGS):
|
87 |
+
return "Please ask your question properly with at least 3 words."
|
88 |
+
|
|
|
|
|
|
|
|
|
89 |
if any(greet in user_input_lower for greet in GREETINGS):
|
90 |
greeting_response = query_groq_llm(
|
91 |
f"You are an official assistant for University of Education Lahore. "
|
92 |
f"Respond to this greeting in a friendly and professional manner: {user_input}"
|
93 |
)
|
94 |
+
return greeting_response if greeting_response else "Hello! How can I assist you today?"
|
95 |
+
|
|
|
|
|
|
|
|
|
96 |
if any(keyword in user_input_lower for keyword in ["fee structure", "fees structure", "semester fees", "semester fee"]):
|
97 |
+
return (
|
98 |
+
"π° For complete and up-to-date fee details for this program, we recommend visiting the official University of Education fee structure page.\n"
|
99 |
+
"You'll find comprehensive information regarding tuition, admission charges, and other applicable fees there.\n"
|
100 |
+
"π https://ue.edu.pk/allfeestructure.php"
|
101 |
+
)
|
102 |
+
|
|
|
|
|
|
|
|
|
103 |
user_embedding = similarity_model.encode(user_input_lower, convert_to_tensor=True)
|
104 |
similarities = util.pytorch_cos_sim(user_embedding, dataset_embeddings)[0]
|
105 |
best_match_idx = similarities.argmax().item()
|
106 |
best_score = similarities[best_match_idx].item()
|
107 |
|
|
|
108 |
if best_score < 0.65:
|
109 |
manage_unmatched_queries(user_input)
|
110 |
|
|
|
126 |
if llm_response:
|
127 |
for marker in ["Improved Answer:", "Official Answer:"]:
|
128 |
if marker in llm_response:
|
129 |
+
return llm_response.split(marker)[-1].strip()
|
130 |
+
return llm_response
|
|
|
|
|
131 |
else:
|
132 |
+
return dataset_answers[best_match_idx] if best_score >= 0.65 else (
|
133 |
+
"For official information:\n"
|
134 |
+
"π +92-42-99262231-33\n"
|
135 |
+
"βοΈ info@ue.edu.pk\n"
|
136 |
+
"π https://ue.edu.pk"
|
137 |
+
)
|
|
|
|
|
|