Spaces:
Sleeping
Sleeping
Update rag.py
Browse files
rag.py
CHANGED
|
@@ -2,14 +2,12 @@ import json
|
|
| 2 |
from sentence_transformers import SentenceTransformer, util
|
| 3 |
from groq import Groq
|
| 4 |
from datetime import datetime
|
| 5 |
-
import requests
|
| 6 |
-
from datasets import load_dataset, Dataset
|
| 7 |
-
from io import BytesIO
|
| 8 |
-
from PIL import Image, ImageDraw, ImageFont
|
| 9 |
-
import numpy as np
|
| 10 |
-
from dotenv import load_dotenv
|
| 11 |
import os
|
| 12 |
import pandas as pd
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
# Load environment variables
|
| 15 |
load_dotenv()
|
|
@@ -17,13 +15,28 @@ 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 |
# Config
|
| 24 |
HF_DATASET_REPO = "midrees2806/unmatched_queries"
|
| 25 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
# Load multiple JSON datasets
|
| 28 |
dataset = []
|
| 29 |
try:
|
|
@@ -64,6 +77,7 @@ def manage_unmatched_queries(query: str):
|
|
| 64 |
except Exception as e:
|
| 65 |
print(f"Failed to save query: {e}")
|
| 66 |
|
|
|
|
| 67 |
def query_groq_llm(prompt, model_name="llama3-70b-8192"):
|
| 68 |
try:
|
| 69 |
chat_completion = groq_client.chat.completions.create(
|
|
@@ -80,24 +94,23 @@ def query_groq_llm(prompt, model_name="llama3-70b-8192"):
|
|
| 80 |
print(f"Error querying Groq API: {e}")
|
| 81 |
return ""
|
| 82 |
|
|
|
|
| 83 |
def get_best_answer(user_input):
|
| 84 |
-
|
| 85 |
if not user_input.strip():
|
| 86 |
return "Please enter a valid question."
|
|
|
|
| 87 |
user_input_lower = user_input.lower().strip()
|
| 88 |
|
| 89 |
-
if len(user_input_lower.split()) < 3:
|
| 90 |
return "Please ask your question properly with at least 3 words."
|
| 91 |
|
| 92 |
-
|
| 93 |
-
if any(keyword in user_input_lower for keyword in ["fee structure", "fees structure"]):
|
| 94 |
return (
|
| 95 |
-
"๐ฐ For complete and up-to-date fee details for
|
| 96 |
-
"
|
| 97 |
-
"๐ https://
|
| 98 |
)
|
| 99 |
|
| 100 |
-
# ๐ Continue with normal similarity-based logic
|
| 101 |
user_embedding = similarity_model.encode(user_input_lower, convert_to_tensor=True)
|
| 102 |
similarities = util.pytorch_cos_sim(user_embedding, dataset_embeddings)[0]
|
| 103 |
best_match_idx = similarities.argmax().item()
|
|
@@ -105,33 +118,26 @@ def get_best_answer(user_input):
|
|
| 105 |
|
| 106 |
if best_score < 0.65:
|
| 107 |
manage_unmatched_queries(user_input)
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
|
| 122 |
llm_response = query_groq_llm(prompt)
|
| 123 |
|
| 124 |
if llm_response:
|
| 125 |
-
for marker in ["Improved Answer:", "Official Answer:"]:
|
| 126 |
if marker in llm_response:
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
else:
|
| 130 |
-
response = llm_response
|
| 131 |
else:
|
| 132 |
-
|
| 133 |
-
๐ +92-42-99262231-33
|
| 134 |
-
โ๏ธ info@ue.edu.pk
|
| 135 |
-
๐ ue.edu.pk"""
|
| 136 |
-
|
| 137 |
-
return response
|
|
|
|
| 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 |
+
import random
|
| 10 |
+
import glob
|
| 11 |
|
| 12 |
# Load environment variables
|
| 13 |
load_dotenv()
|
|
|
|
| 15 |
# Initialize Groq client
|
| 16 |
groq_client = Groq(api_key=os.getenv("GROQ_API_KEY"))
|
| 17 |
|
| 18 |
+
# Load similarity model
|
| 19 |
similarity_model = SentenceTransformer('paraphrase-MiniLM-L6-v2')
|
| 20 |
|
| 21 |
# Config
|
| 22 |
HF_DATASET_REPO = "midrees2806/unmatched_queries"
|
| 23 |
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 24 |
|
| 25 |
+
# Greeting list
|
| 26 |
+
GREETINGS = [
|
| 27 |
+
"hi", "hello", "hey", "good morning", "good afternoon", "good evening",
|
| 28 |
+
"assalam o alaikum", "salam", "aoa", "hi there",
|
| 29 |
+
"hey there", "greetings"
|
| 30 |
+
]
|
| 31 |
+
|
| 32 |
+
# Fixed rephrased unmatched query responses
|
| 33 |
+
UNMATCHED_RESPONSES = [
|
| 34 |
+
"Thank you for your query. Weโve forwarded it to our support team and it will be added soon. In the meantime, you can visit the University of Education official website or reach out via the contact details below.\n\n๐ +92-42-99262231-33\nโ๏ธ info@ue.edu.pk\n๐ https://ue.edu.pk",
|
| 35 |
+
"Weโve noted your question and itโs in queue for inclusion. For now, please check the University of Education website or contact the administration directly.\n\n๐ +92-42-99262231-33\nโ๏ธ info@ue.edu.pk\n๐ https://ue.edu.pk",
|
| 36 |
+
"Your query has been recorded. Weโll update the system with relevant information shortly. Meanwhile, you can visit UE's official site or reach out using the details below:\n\n๐ +92-42-99262231-33\nโ๏ธ info@ue.edu.pk\n๐ https://ue.edu.pk",
|
| 37 |
+
"We appreciate your question. It has been forwarded for further processing. Until itโs available here, feel free to visit the official UE website or use the contact options:\n\n๐ +92-42-99262231-33\nโ๏ธ info@ue.edu.pk\n๐ https://ue.edu.pk"
|
| 38 |
+
]
|
| 39 |
+
|
| 40 |
# Load multiple JSON datasets
|
| 41 |
dataset = []
|
| 42 |
try:
|
|
|
|
| 77 |
except Exception as e:
|
| 78 |
print(f"Failed to save query: {e}")
|
| 79 |
|
| 80 |
+
# Query Groq LLM
|
| 81 |
def query_groq_llm(prompt, model_name="llama3-70b-8192"):
|
| 82 |
try:
|
| 83 |
chat_completion = groq_client.chat.completions.create(
|
|
|
|
| 94 |
print(f"Error querying Groq API: {e}")
|
| 95 |
return ""
|
| 96 |
|
| 97 |
+
# Main logic function to be called from Gradio
|
| 98 |
def get_best_answer(user_input):
|
|
|
|
| 99 |
if not user_input.strip():
|
| 100 |
return "Please enter a valid question."
|
| 101 |
+
|
| 102 |
user_input_lower = user_input.lower().strip()
|
| 103 |
|
| 104 |
+
if len(user_input_lower.split()) < 3 and not any(greet in user_input_lower for greet in GREETINGS):
|
| 105 |
return "Please ask your question properly with at least 3 words."
|
| 106 |
|
| 107 |
+
if any(keyword in user_input_lower for keyword in ["fee structure", "fees structure", "semester fees", "semester fee"]):
|
|
|
|
| 108 |
return (
|
| 109 |
+
"๐ฐ For the most complete and up-to-date fee details for your program at the University of Education Lahore, please visit the official fee structure page.\n"
|
| 110 |
+
"This webpage offers a detailed overview of the fee structure, providing you with essential information to support your academic journey at our institution.\n"
|
| 111 |
+
"๐ https://drive.google.com/file/d/1B30FKoP6GrkS9pQk10PWKCwcjco5E9Cc/view"
|
| 112 |
)
|
| 113 |
|
|
|
|
| 114 |
user_embedding = similarity_model.encode(user_input_lower, convert_to_tensor=True)
|
| 115 |
similarities = util.pytorch_cos_sim(user_embedding, dataset_embeddings)[0]
|
| 116 |
best_match_idx = similarities.argmax().item()
|
|
|
|
| 118 |
|
| 119 |
if best_score < 0.65:
|
| 120 |
manage_unmatched_queries(user_input)
|
| 121 |
+
return random.choice(UNMATCHED_RESPONSES)
|
| 122 |
+
|
| 123 |
+
original_answer = dataset_answers[best_match_idx]
|
| 124 |
+
prompt = f"""Name is UOE AI Assistant! You are an official assistant for the University of Education Lahore.
|
| 125 |
+
Rephrase the following official answer clearly and professionally.
|
| 126 |
+
Use structured formatting (like headings, bullet points, or numbered lists) where appropriate.
|
| 127 |
+
DO NOT add any new or extra information. ONLY rephrase and improve the clarity and formatting of the original answer.
|
| 128 |
+
### Question:
|
| 129 |
+
{user_input}
|
| 130 |
+
### Original Answer:
|
| 131 |
+
{original_answer}
|
| 132 |
+
### Rephrased Answer:
|
| 133 |
+
"""
|
| 134 |
|
| 135 |
llm_response = query_groq_llm(prompt)
|
| 136 |
|
| 137 |
if llm_response:
|
| 138 |
+
for marker in ["Improved Answer:", "Official Answer:", "Rephrased Answer:"]:
|
| 139 |
if marker in llm_response:
|
| 140 |
+
return llm_response.split(marker)[-1].strip()
|
| 141 |
+
return llm_response
|
|
|
|
|
|
|
| 142 |
else:
|
| 143 |
+
return dataset_answers[best_match_idx]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|