Spaces:
Sleeping
Sleeping
Update rag.py
Browse files
rag.py
CHANGED
|
@@ -1,11 +1,15 @@
|
|
| 1 |
import json
|
| 2 |
from sentence_transformers import SentenceTransformer, util
|
| 3 |
from groq import Groq
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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,12 +17,17 @@ load_dotenv()
|
|
| 13 |
# Initialize Groq client
|
| 14 |
groq_client = Groq(api_key=os.getenv("GROQ_API_KEY"))
|
| 15 |
|
| 16 |
-
# Load
|
| 17 |
similarity_model = SentenceTransformer('paraphrase-MiniLM-L6-v2')
|
| 18 |
|
| 19 |
-
#
|
| 20 |
-
|
| 21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
# Greeting list
|
| 24 |
GREETINGS = [
|
|
@@ -27,25 +36,14 @@ GREETINGS = [
|
|
| 27 |
"hey there", "greetings"
|
| 28 |
]
|
| 29 |
|
| 30 |
-
#
|
| 31 |
-
|
| 32 |
-
|
| 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()
|
|
@@ -59,7 +57,6 @@ def manage_unmatched_queries(query: str):
|
|
| 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,16 +73,10 @@ def query_groq_llm(prompt, model_name="llama3-70b-8192"):
|
|
| 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 |
-
|
| 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. "
|
|
@@ -93,18 +84,21 @@ def get_best_answer(user_input):
|
|
| 93 |
)
|
| 94 |
return greeting_response if greeting_response else "Hello! How can I assist you today?"
|
| 95 |
|
| 96 |
-
|
|
|
|
| 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
|
| 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 |
|
|
@@ -124,14 +118,16 @@ def get_best_answer(user_input):
|
|
| 124 |
llm_response = query_groq_llm(prompt)
|
| 125 |
|
| 126 |
if llm_response:
|
| 127 |
-
for marker in ["Improved Answer:", "Official Answer:"
|
| 128 |
if marker in llm_response:
|
| 129 |
-
|
| 130 |
-
|
|
|
|
|
|
|
| 131 |
else:
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
|
|
|
| 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 |
import pandas as pd
|
| 12 |
from datasets import load_dataset, Dataset
|
|
|
|
| 13 |
|
| 14 |
# Load environment variables
|
| 15 |
load_dotenv()
|
|
|
|
| 17 |
# Initialize Groq client
|
| 18 |
groq_client = Groq(api_key=os.getenv("GROQ_API_KEY"))
|
| 19 |
|
| 20 |
+
# Load models and dataset
|
| 21 |
similarity_model = SentenceTransformer('paraphrase-MiniLM-L6-v2')
|
| 22 |
|
| 23 |
+
# Load dataset (automatically using the path)
|
| 24 |
+
with open('dataset.json', 'r') as f:
|
| 25 |
+
dataset = json.load(f)
|
| 26 |
+
|
| 27 |
+
# Precompute embeddings
|
| 28 |
+
dataset_questions = [item.get("input", "").lower().strip() for item in dataset]
|
| 29 |
+
dataset_answers = [item.get("response", "") for item in dataset]
|
| 30 |
+
dataset_embeddings = similarity_model.encode(dataset_questions, convert_to_tensor=True)
|
| 31 |
|
| 32 |
# Greeting list
|
| 33 |
GREETINGS = [
|
|
|
|
| 36 |
"hey there", "greetings"
|
| 37 |
]
|
| 38 |
|
| 39 |
+
# Hugging Face config
|
| 40 |
+
HF_DATASET_REPO = "midrees2806/unmatched_queries"
|
| 41 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
# Save unmatched queries to Hugging Face
|
| 44 |
def manage_unmatched_queries(query: str):
|
| 45 |
try:
|
| 46 |
+
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 47 |
try:
|
| 48 |
ds = load_dataset(HF_DATASET_REPO, token=HF_TOKEN)
|
| 49 |
df = ds["train"].to_pandas()
|
|
|
|
| 57 |
except Exception as e:
|
| 58 |
print(f"Failed to save query: {e}")
|
| 59 |
|
|
|
|
| 60 |
def query_groq_llm(prompt, model_name="llama3-70b-8192"):
|
| 61 |
try:
|
| 62 |
chat_completion = groq_client.chat.completions.create(
|
|
|
|
| 73 |
print(f"Error querying Groq API: {e}")
|
| 74 |
return ""
|
| 75 |
|
|
|
|
| 76 |
def get_best_answer(user_input):
|
|
|
|
|
|
|
|
|
|
| 77 |
user_input_lower = user_input.lower().strip()
|
| 78 |
|
| 79 |
+
# π Greeting functionality
|
|
|
|
|
|
|
| 80 |
if any(greet in user_input_lower for greet in GREETINGS):
|
| 81 |
greeting_response = query_groq_llm(
|
| 82 |
f"You are an official assistant for University of Education Lahore. "
|
|
|
|
| 84 |
)
|
| 85 |
return greeting_response if greeting_response else "Hello! How can I assist you today?"
|
| 86 |
|
| 87 |
+
# π Check if question is about fee
|
| 88 |
+
if any(keyword in user_input_lower for keyword in ["semester fee", "semester fees"]):
|
| 89 |
return (
|
| 90 |
"π° For complete and up-to-date fee details for this program, we recommend visiting the official University of Education fee structure page.\n"
|
| 91 |
+
"Youβll find comprehensive information regarding tuition, admission charges, and other applicable fees there.\n"
|
| 92 |
"π https://ue.edu.pk/allfeestructure.php"
|
| 93 |
)
|
| 94 |
|
| 95 |
+
# π Continue with normal similarity-based logic
|
| 96 |
user_embedding = similarity_model.encode(user_input_lower, convert_to_tensor=True)
|
| 97 |
similarities = util.pytorch_cos_sim(user_embedding, dataset_embeddings)[0]
|
| 98 |
best_match_idx = similarities.argmax().item()
|
| 99 |
best_score = similarities[best_match_idx].item()
|
| 100 |
|
| 101 |
+
# π Save unmatched query if no close match
|
| 102 |
if best_score < 0.65:
|
| 103 |
manage_unmatched_queries(user_input)
|
| 104 |
|
|
|
|
| 118 |
llm_response = query_groq_llm(prompt)
|
| 119 |
|
| 120 |
if llm_response:
|
| 121 |
+
for marker in ["Improved Answer:", "Official Answer:"]:
|
| 122 |
if marker in llm_response:
|
| 123 |
+
response = llm_response.split(marker)[-1].strip()
|
| 124 |
+
break
|
| 125 |
+
else:
|
| 126 |
+
response = llm_response
|
| 127 |
else:
|
| 128 |
+
response = dataset_answers[best_match_idx] if best_score >= 0.65 else """For official information:
|
| 129 |
+
π +92-42-99262231-33
|
| 130 |
+
βοΈ info@ue.edu.pk
|
| 131 |
+
π ue.edu.pk"""
|
| 132 |
+
|
| 133 |
+
return response
|