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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import os
|
| 3 |
+
from typing import List, Dict
|
| 4 |
+
import numpy as np
|
| 5 |
+
from datasets import load_dataset
|
| 6 |
+
from langchain.text_splitter import (
|
| 7 |
+
RecursiveCharacterTextSplitter,
|
| 8 |
+
CharacterTextSplitter,
|
| 9 |
+
TokenTextSplitter
|
| 10 |
+
)
|
| 11 |
+
from langchain_community.vectorstores import FAISS, Chroma
|
| 12 |
+
from langchain_community.document_loaders import PyPDFLoader
|
| 13 |
+
from langchain.chains import ConversationalRetrievalChain
|
| 14 |
+
from langchain_community.embeddings import HuggingFaceEmbeddings
|
| 15 |
+
from langchain_community.llms import HuggingFaceEndpoint
|
| 16 |
+
from langchain.memory import ConversationBufferMemory
|
| 17 |
+
from sentence_transformers import SentenceTransformer, util
|
| 18 |
+
import torch
|
| 19 |
+
from ragas import evaluate
|
| 20 |
+
from ragas.metrics import (
|
| 21 |
+
ContextRecall,
|
| 22 |
+
AnswerRelevancy,
|
| 23 |
+
Faithfulness,
|
| 24 |
+
ContextPrecision
|
| 25 |
+
)
|
| 26 |
+
import pandas as pd
|
| 27 |
+
|
| 28 |
+
# Constants and configurations
|
| 29 |
+
CHUNK_SIZES = {
|
| 30 |
+
"small": {"recursive": 512, "fixed": 512, "token": 256},
|
| 31 |
+
"medium": {"recursive": 1024, "fixed": 1024, "token": 512}
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
class RAGEvaluator:
|
| 35 |
+
def __init__(self):
|
| 36 |
+
self.datasets = {
|
| 37 |
+
"squad": "squad_v2",
|
| 38 |
+
"msmarco": "ms_marco"
|
| 39 |
+
}
|
| 40 |
+
self.current_dataset = None
|
| 41 |
+
self.test_samples = []
|
| 42 |
+
|
| 43 |
+
def load_dataset(self, dataset_name: str, num_samples: int = 50):
|
| 44 |
+
if dataset_name == "squad":
|
| 45 |
+
dataset = load_dataset("squad_v2", split="validation")
|
| 46 |
+
samples = dataset.select(range(num_samples))
|
| 47 |
+
self.test_samples = [
|
| 48 |
+
{
|
| 49 |
+
"question": sample["question"],
|
| 50 |
+
"ground_truth": sample["answers"]["text"][0] if sample["answers"]["text"] else "",
|
| 51 |
+
"context": sample["context"]
|
| 52 |
+
}
|
| 53 |
+
for sample in samples
|
| 54 |
+
if sample["answers"]["text"] # Filter out samples without answers
|
| 55 |
+
]
|
| 56 |
+
elif dataset_name == "msmarco":
|
| 57 |
+
dataset = load_dataset("ms_marco", "v2.1", split="train")
|
| 58 |
+
samples = dataset.select(range(num_samples))
|
| 59 |
+
self.test_samples = [
|
| 60 |
+
{
|
| 61 |
+
"question": sample["query"],
|
| 62 |
+
"ground_truth": sample["answers"][0] if sample["answers"] else "",
|
| 63 |
+
"context": sample["passages"]["passage_text"][0]
|
| 64 |
+
}
|
| 65 |
+
for sample in samples
|
| 66 |
+
if sample["answers"] # Filter out samples without answers
|
| 67 |
+
]
|
| 68 |
+
self.current_dataset = dataset_name
|
| 69 |
+
return self.test_samples
|
| 70 |
+
|
| 71 |
+
def evaluate_configuration(self,
|
| 72 |
+
vector_db,
|
| 73 |
+
qa_chain,
|
| 74 |
+
splitting_strategy: str,
|
| 75 |
+
chunk_size: str) -> Dict:
|
| 76 |
+
if not self.test_samples:
|
| 77 |
+
return {"error": "No dataset loaded"}
|
| 78 |
+
|
| 79 |
+
results = []
|
| 80 |
+
for sample in self.test_samples:
|
| 81 |
+
response = qa_chain.invoke({
|
| 82 |
+
"question": sample["question"],
|
| 83 |
+
"chat_history": []
|
| 84 |
+
})
|
| 85 |
+
|
| 86 |
+
results.append({
|
| 87 |
+
"question": sample["question"],
|
| 88 |
+
"answer": response["answer"],
|
| 89 |
+
"contexts": [doc.page_content for doc in response["source_documents"]],
|
| 90 |
+
"ground_truths": [sample["ground_truth"]]
|
| 91 |
+
})
|
| 92 |
+
|
| 93 |
+
# Convert to RAGAS dataset format
|
| 94 |
+
eval_dataset = Dataset.from_list(results)
|
| 95 |
+
|
| 96 |
+
# Calculate RAGAS metrics
|
| 97 |
+
metrics = [
|
| 98 |
+
ContextRecall(),
|
| 99 |
+
AnswerRelevancy(),
|
| 100 |
+
Faithfulness(),
|
| 101 |
+
ContextPrecision()
|
| 102 |
+
]
|
| 103 |
+
|
| 104 |
+
scores = evaluate(
|
| 105 |
+
eval_dataset,
|
| 106 |
+
metrics=metrics
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
return {
|
| 110 |
+
"configuration": f"{splitting_strategy}_{chunk_size}",
|
| 111 |
+
"context_recall": float(scores['context_recall']),
|
| 112 |
+
"answer_relevancy": float(scores['answer_relevancy']),
|
| 113 |
+
"faithfulness": float(scores['faithfulness']),
|
| 114 |
+
"context_precision": float(scores['context_precision']),
|
| 115 |
+
"average_score": float(np.mean([
|
| 116 |
+
scores['context_recall'],
|
| 117 |
+
scores['answer_relevancy'],
|
| 118 |
+
scores['faithfulness'],
|
| 119 |
+
scores['context_precision']
|
| 120 |
+
]))
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
def demo():
|
| 124 |
+
evaluator = RAGEvaluator()
|
| 125 |
+
|
| 126 |
+
with gr.Blocks(theme=gr.themes.Default(primary_hue="red", secondary_hue="pink", neutral_hue="sky")) as demo:
|
| 127 |
+
vector_db = gr.State()
|
| 128 |
+
qa_chain = gr.State()
|
| 129 |
+
|
| 130 |
+
gr.HTML("<center><h1>Enhanced RAG PDF Chatbot with Evaluation</h1></center>")
|
| 131 |
+
|
| 132 |
+
with gr.Tabs():
|
| 133 |
+
# Custom PDF Tab
|
| 134 |
+
with gr.Tab("Custom PDF Chat"):
|
| 135 |
+
# Your existing UI components here
|
| 136 |
+
with gr.Row():
|
| 137 |
+
with gr.Column(scale=86):
|
| 138 |
+
gr.Markdown("<b>Step 1 - Configure and Initialize RAG Pipeline</b>")
|
| 139 |
+
with gr.Row():
|
| 140 |
+
document = gr.Files(height=300, file_count="multiple", file_types=["pdf"], interactive=True, label="Upload PDF documents")
|
| 141 |
+
|
| 142 |
+
with gr.Row():
|
| 143 |
+
splitting_strategy = gr.Radio(
|
| 144 |
+
["recursive", "fixed", "token"],
|
| 145 |
+
label="Text Splitting Strategy",
|
| 146 |
+
value="recursive"
|
| 147 |
+
)
|
| 148 |
+
db_choice = gr.Dropdown(
|
| 149 |
+
["faiss", "chroma"],
|
| 150 |
+
label="Vector Database",
|
| 151 |
+
value="faiss"
|
| 152 |
+
)
|
| 153 |
+
chunk_size = gr.Radio(
|
| 154 |
+
["small", "medium"],
|
| 155 |
+
label="Chunk Size",
|
| 156 |
+
value="medium"
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
# Rest of your existing UI components...
|
| 160 |
+
|
| 161 |
+
# Evaluation Tab
|
| 162 |
+
with gr.Tab("RAG Evaluation"):
|
| 163 |
+
with gr.Row():
|
| 164 |
+
dataset_choice = gr.Dropdown(
|
| 165 |
+
choices=list(evaluator.datasets.keys()),
|
| 166 |
+
label="Select Evaluation Dataset",
|
| 167 |
+
value="squad"
|
| 168 |
+
)
|
| 169 |
+
load_dataset_btn = gr.Button("Load Dataset")
|
| 170 |
+
|
| 171 |
+
with gr.Row():
|
| 172 |
+
dataset_info = gr.JSON(label="Dataset Information")
|
| 173 |
+
|
| 174 |
+
with gr.Row():
|
| 175 |
+
eval_splitting_strategy = gr.Radio(
|
| 176 |
+
["recursive", "fixed", "token"],
|
| 177 |
+
label="Text Splitting Strategy",
|
| 178 |
+
value="recursive"
|
| 179 |
+
)
|
| 180 |
+
eval_chunk_size = gr.Radio(
|
| 181 |
+
["small", "medium"],
|
| 182 |
+
label="Chunk Size",
|
| 183 |
+
value="medium"
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
with gr.Row():
|
| 187 |
+
evaluate_btn = gr.Button("Run Evaluation")
|
| 188 |
+
evaluation_results = gr.DataFrame(label="Evaluation Results")
|
| 189 |
+
|
| 190 |
+
# Event handlers
|
| 191 |
+
def load_dataset_handler(dataset_name):
|
| 192 |
+
samples = evaluator.load_dataset(dataset_name)
|
| 193 |
+
return {
|
| 194 |
+
"dataset": dataset_name,
|
| 195 |
+
"num_samples": len(samples),
|
| 196 |
+
"sample_questions": [s["question"] for s in samples[:3]]
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
def run_evaluation(dataset_choice, splitting_strategy, chunk_size, vector_db, qa_chain):
|
| 200 |
+
if not evaluator.current_dataset:
|
| 201 |
+
return pd.DataFrame()
|
| 202 |
+
|
| 203 |
+
results = evaluator.evaluate_configuration(
|
| 204 |
+
vector_db=vector_db,
|
| 205 |
+
qa_chain=qa_chain,
|
| 206 |
+
splitting_strategy=splitting_strategy,
|
| 207 |
+
chunk_size=chunk_size
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
# Convert results to DataFrame
|
| 211 |
+
df = pd.DataFrame([results])
|
| 212 |
+
return df
|
| 213 |
+
|
| 214 |
+
# Connect event handlers
|
| 215 |
+
load_dataset_btn.click(
|
| 216 |
+
load_dataset_handler,
|
| 217 |
+
inputs=[dataset_choice],
|
| 218 |
+
outputs=[dataset_info]
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
evaluate_btn.click(
|
| 222 |
+
run_evaluation,
|
| 223 |
+
inputs=[
|
| 224 |
+
dataset_choice,
|
| 225 |
+
eval_splitting_strategy,
|
| 226 |
+
eval_chunk_size,
|
| 227 |
+
vector_db,
|
| 228 |
+
qa_chain
|
| 229 |
+
],
|
| 230 |
+
outputs=[evaluation_results]
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
qachain_btn.click(
|
| 234 |
+
initialize_llmchain, # Fixed function name here
|
| 235 |
+
inputs=[llm_btn, slider_temperature, slider_maxtokens, slider_topk, vector_db],
|
| 236 |
+
outputs=[qa_chain, llm_progress]
|
| 237 |
+
).then(
|
| 238 |
+
lambda: [None, "", 0, "", 0, "", 0],
|
| 239 |
+
inputs=None,
|
| 240 |
+
outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page],
|
| 241 |
+
queue=False
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
msg.submit(conversation,
|
| 245 |
+
inputs=[qa_chain, msg, chatbot],
|
| 246 |
+
outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page],
|
| 247 |
+
queue=False
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
submit_btn.click(conversation,
|
| 251 |
+
inputs=[qa_chain, msg, chatbot],
|
| 252 |
+
outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page],
|
| 253 |
+
queue=False
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
clear_btn.click(
|
| 257 |
+
lambda: [None, "", 0, "", 0, "", 0],
|
| 258 |
+
inputs=None,
|
| 259 |
+
outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page],
|
| 260 |
+
queue=False
|
| 261 |
+
)
|
| 262 |
+
demo.queue().launch(debug=True)
|
| 263 |
+
|
| 264 |
+
if __name__ == "__main__":
|
| 265 |
+
demo()
|