Spaces:
Sleeping
Sleeping
Update rag.py
Browse files
rag.py
CHANGED
|
@@ -1,13 +1,11 @@
|
|
| 1 |
import json
|
| 2 |
from sentence_transformers import SentenceTransformer, util
|
| 3 |
from groq import Groq
|
| 4 |
-
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 |
|
| 12 |
# Load environment variables
|
| 13 |
load_dotenv()
|
|
@@ -15,18 +13,53 @@ load_dotenv()
|
|
| 15 |
# Initialize Groq client
|
| 16 |
groq_client = Groq(api_key=os.getenv("GROQ_API_KEY"))
|
| 17 |
|
| 18 |
-
# Load
|
| 19 |
similarity_model = SentenceTransformer('paraphrase-MiniLM-L6-v2')
|
| 20 |
|
| 21 |
-
#
|
| 22 |
-
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
# Precompute embeddings
|
| 26 |
-
dataset_questions = [item.get("
|
| 27 |
-
dataset_answers = [item.get("
|
| 28 |
dataset_embeddings = similarity_model.encode(dataset_questions, convert_to_tensor=True)
|
| 29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
def query_groq_llm(prompt, model_name="llama3-70b-8192"):
|
| 31 |
try:
|
| 32 |
chat_completion = groq_client.chat.completions.create(
|
|
@@ -43,23 +76,38 @@ def query_groq_llm(prompt, model_name="llama3-70b-8192"):
|
|
| 43 |
print(f"Error querying Groq API: {e}")
|
| 44 |
return ""
|
| 45 |
|
|
|
|
| 46 |
def get_best_answer(user_input):
|
|
|
|
|
|
|
|
|
|
| 47 |
user_input_lower = user_input.lower().strip()
|
| 48 |
|
| 49 |
-
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
return (
|
| 52 |
"π° For complete and up-to-date fee details for this program, we recommend visiting the official University of Education fee structure page.\n"
|
| 53 |
-
"You
|
| 54 |
"π https://ue.edu.pk/allfeestructure.php"
|
| 55 |
)
|
| 56 |
|
| 57 |
-
# π Continue with normal similarity-based logic
|
| 58 |
user_embedding = similarity_model.encode(user_input_lower, convert_to_tensor=True)
|
| 59 |
similarities = util.pytorch_cos_sim(user_embedding, dataset_embeddings)[0]
|
| 60 |
best_match_idx = similarities.argmax().item()
|
| 61 |
best_score = similarities[best_match_idx].item()
|
| 62 |
|
|
|
|
|
|
|
|
|
|
| 63 |
if best_score >= 0.65:
|
| 64 |
original_answer = dataset_answers[best_match_idx]
|
| 65 |
prompt = f"""As an official assistant for University of Education Lahore, provide a clear response:
|
|
@@ -76,16 +124,14 @@ def get_best_answer(user_input):
|
|
| 76 |
llm_response = query_groq_llm(prompt)
|
| 77 |
|
| 78 |
if llm_response:
|
| 79 |
-
for marker in ["Improved Answer:", "Official Answer:"]:
|
| 80 |
if marker in llm_response:
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
else:
|
| 84 |
-
response = llm_response
|
| 85 |
else:
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
|
|
|
| 1 |
import json
|
| 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", "aoa", "hi there",
|
| 27 |
+
"hey there", "greetings"
|
| 28 |
+
]
|
| 29 |
+
|
| 30 |
+
# Load local dataset
|
| 31 |
+
try:
|
| 32 |
+
with open('dataset.json', 'r') as f:
|
| 33 |
+
dataset = json.load(f)
|
| 34 |
+
if not all(isinstance(item, dict) and 'Question' in item and 'Answer' in item for item in dataset):
|
| 35 |
+
raise ValueError("Invalid dataset structure")
|
| 36 |
+
except Exception as e:
|
| 37 |
+
print(f"Error loading dataset: {e}")
|
| 38 |
+
dataset = []
|
| 39 |
|
| 40 |
# Precompute embeddings
|
| 41 |
+
dataset_questions = [item.get("Question", "").lower().strip() for item in dataset]
|
| 42 |
+
dataset_answers = [item.get("Answer", "") 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 |
+
|
| 111 |
if best_score >= 0.65:
|
| 112 |
original_answer = dataset_answers[best_match_idx]
|
| 113 |
prompt = f"""As an official assistant for University of Education Lahore, provide a clear response:
|
|
|
|
| 124 |
llm_response = query_groq_llm(prompt)
|
| 125 |
|
| 126 |
if llm_response:
|
| 127 |
+
for marker in ["Improved Answer:", "Official Answer:", "Rephrased 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 |
+
)
|