File size: 15,820 Bytes
f257da4
 
 
2158d39
a01d977
253cc8c
a01d977
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b7c0bd
a01d977
454cdd7
 
 
aa531e0
454cdd7
2158d39
04cba9b
819ec9b
04cba9b
 
91e4b30
2ad7bbc
e4fa134
 
 
2158d39
 
 
 
 
 
 
 
 
 
 
b983f79
 
 
 
 
ea26be4
f257da4
659f242
 
 
8e7f876
5aa7b5b
8e7f876
5aa7b5b
 
ea26be4
 
5aa7b5b
 
ea26be4
f257da4
b983f79
f257da4
ea26be4
f257da4
ea26be4
f257da4
 
 
ea26be4
 
 
04cba9b
185c971
f257da4
ea26be4
f257da4
 
ea26be4
f257da4
 
 
 
 
 
ea26be4
f257da4
 
 
 
 
de05309
 
 
 
f257da4
 
 
ea26be4
f257da4
 
 
 
 
 
 
023441b
 
f257da4
 
 
 
 
 
 
 
 
 
 
 
 
ea26be4
f257da4
 
 
 
 
 
 
 
 
 
 
 
 
023441b
 
f257da4
 
 
 
 
 
 
 
 
 
 
 
e8bb07c
 
 
 
 
 
 
 
95fc507
920bfb0
 
e8bb07c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa531e0
e8bb07c
 
 
920bfb0
 
e8bb07c
920bfb0
06ebac5
015728f
920bfb0
 
61a1dfa
d705a83
1fc5b91
5da8b5d
306eb28
 
61a1dfa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44211ab
61a1dfa
 
 
35cdb85
61a1dfa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f009cfa
 
 
 
 
 
 
61a1dfa
 
f009cfa
 
61a1dfa
 
 
 
 
 
 
 
 
 
b0becdb
 
61a1dfa
 
 
 
 
 
356c6bf
847b6c6
356c6bf
eb18a9c
847b6c6
f009cfa
61a1dfa
 
b0becdb
356c6bf
2a897f6
7efb924
61a1dfa
 
 
f257da4
5f73574
 
 
 
 
f257da4
 
 
 
 
 
 
 
 
 
 
04cba9b
f257da4
 
 
7b0667e
306eb28
 
 
 
 
 
 
 
 
 
f257da4
996f416
f257da4
 
 
 
 
 
cbeccdb
f257da4
 
 
 
 
 
 
c27e646
f257da4
 
819ec9b
 
ae98e19
8ab6174
819ec9b
 
 
b0becdb
0100613
819ec9b
 
 
de05309
 
356c6bf
 
 
 
 
2a897f6
f257da4
 
 
 
 
f040c98
 
 
 
 
cbeccdb
f040c98
 
f257da4
 
 
 
 
306eb28
f257da4
 
f040c98
f257da4
 
f040c98
 
 
 
 
 
 
 
 
 
 
 
 
015728f
5da8b5d
454cdd7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
import gradio as gr
import matplotlib.pyplot as plt
import json
import logging

from datetime import datetime


# ==== Metrics Calculation
from sklearn.metrics import roc_auc_score
from sklearn.metrics import mean_squared_error

# === HuggingFace & Transformers ===
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline


# === Misc ===
import json
import gradio as gr
from json_repair import repair_json

import datetime

from utils import (
    form_document_sentences_from_chunks,
    form_response_sentences,
    convert_to_serializable
)

from constants import (
    CHUNKING_STRATEGIES,
)

from ragbench import RAGSystem, RAGEvaluator

import nltk
nltk.download('punkt_tab')

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler()  # Log to console
    ]
)

logger = logging.getLogger(__name__)

SUMMARY = 'summary'
DATASET_TYPE = 'dataset_type'
ENTRIES = 'entries'
QUESTIONS = 'questions'

ragbench_details = {}

import os
print(os.listdir("data"))  # Check if the file is there


# 1. FIXED DATA LOADING - use absolute path
DATA_PATH = 'data/ragbench_summary_questions_chunking.json'
try:
    with open(DATA_PATH) as f:
        ragbench_details = json.load(f)
    logger.info(f"Loaded data with {len(ragbench_details)} subsets")
except Exception as e:
    logger.error(f"Failed to load data: {e}")
    ragbench_details = {}  # Fallback empty dict

# Placeholder for generated values (integrate your pipeline here)
available_questions = {}
for item in ragbench_details.keys():
    available_questions[item] = []
    for sq in ragbench_details[item][QUESTIONS]:
        available_questions[item].append(sq['question'])

# Sample Configs and Options

available_subsets = list(ragbench_details.keys())

# chunking_strategies = ["SentenceBasedLangchain", "Hybrid"]
embedding_models = ["BAAI/bge-large-en-v1.5", "intfloat/e5-large-v2"]
generator_models = ["mistralai/Mistral-7B-Instruct-v0.2"]
evaluators = ["llama"]

def update_question_list_and_info(subset):
    subset_questions = ragbench_details.get(subset, [])
    questions = [q["question"] for q in subset_questions[QUESTIONS]]
    selected = questions[0] if questions else None
    orig_ans, y_metrics = get_info_from_sample_questions(subset, selected) if selected else ("", "")
    return gr.update(choices=questions, value=selected), orig_ans, y_metrics

def get_info_from_sample_questions(subset, question):
    subset_questions = ragbench_details.get(subset, [])

    for entry in subset_questions[QUESTIONS]:
        if entry.get("question") == question:
            orig_ans = entry.get("original_response", "N/A")
            y_metrics = entry.get("y_metrics", {})
            # y_metrics_text = "\n".join(
            #     f"{k.replace('_', ' ').title()}: {v}" for k, v in y_metrics.items()
            # ) if y_metrics else "No metrics available."
            return orig_ans, y_metrics
    return "No answer found.", "No metrics found."

def plot_subset_metrics(subset_name):
    summary = ragbench_details[subset_name]["summary"]

    # Create a DataFrame for plotting
    keys = ['Entries', 'TotalDocs', 'TotalUniqueIds', 'TotalUniqueDocs', 'UniqueDocsPercent']
    values = [summary.get(k, 0) for k in keys]

    fig, ax = plt.subplots(figsize=(10, 6))
    bars = ax.bar(keys, values, color='skyblue')
    plt.tight_layout()  # Apply tight layout after plotting


    # βœ… Add count on top of bars
    ax.bar_label(bars, fmt='%.0f', padding=3)
    
    # ax.bar(keys, values, color="mediumseagreen")
    ax.set_title(f"Metrics for Subset: {subset_name}, Domain: {summary.get('Domain')}", fontsize=14)
    ax.set_ylabel("Value")
    ax.grid(axis='y')
    ax.set_xticks(range(len(keys)))
    ax.set_xticklabels(keys, rotation=21, ha='right')
    return fig

def plot_chunking_strategies(subset_name):
    chunking_data = ragbench_details[subset_name]["chunking"]

    plt.figure(figsize=(10, 6))
    strategies = list(chunking_data.keys())
    counts = list(chunking_data.values())

    bars = plt.bar(strategies, counts, color="skyblue")

    # Add value labels on top of bars
    for bar in bars:
        yval = bar.get_height()
        plt.text(bar.get_x() + bar.get_width()/2, yval + 20, int(yval), ha='center', va='bottom', fontsize=10)

    # plt.xlabel("Chunking Strategies")
    plt.tight_layout()  # Apply tight layout after plotting

    plt.ylabel("Number of Chunks")
    plt.title(f"Chunking Strategy Distribution - {subset_name}")
    plt.xticks(rotation=30)
    plt.tight_layout()

    # Return plot as figure (Gradio accepts it)
    return plt.gcf()

# Initialize with first subset's summary
initial_subset = available_subsets[0] if available_subsets else None
initial_plot = plot_subset_metrics(initial_subset) if initial_subset else "No data available"

def generate_file(subset_dropdown, dataset_type_dropdown, 
                        chunking_dropdown, embed_dropdown, retriever_dropdown,
                        chunk_count, retriever_type,
                        reranking_checkbox, evaluator_dropdown,
                        orig_ans_display, y_metrics_display,
                        gen_ans_display, y_pred_metrics_display,
                        chunks_retrieved_display, 
                        evaluator_json_output):
    
    """Generate a file with the given text and return the file path."""

    export_data = {
            "metadata": {
                "timestamp": datetime.datetime.now().isoformat(),
                "format_version": "1.0"
            },
            "subset": {
                "subset": subset_dropdown,
                "dataset_type": dataset_type_dropdown,
            },
            "model_details": {
                "strategy": chunking_dropdown,
                "embed_model": embed_dropdown,
                "generator_model": retriever_dropdown,
                "chunk_count": chunk_count,
                "retriever_type": retriever_type,
                "reranking": reranking_checkbox,
                "evaluator_model": evaluator_dropdown
            },
            "results": {
                "original_answer": orig_ans_display,
                "y_metrics": y_metrics_display,
                "generated_answer": gen_ans_display,
                "y_pred_metrics": y_pred_metrics_display,
                "retrieved_chunks": convert_to_serializable(chunks_retrieved_display),
                "evaluator_json_output": evaluator_json_output
            }
        }

    # Step 2: Convert to JSON string for display
    json_str = json.dumps(export_data, indent=2)

    fileName = f"{subset_dropdown}_output_{datetime.datetime.now().strftime('%d-%B-%Y-%H-%M-%S')}.json"
    # Save to file inside Space
    with open(fileName, "w") as f:
        f.write(json_str)

    return json_str, fileName


def run_rag_pipeline(subset, question, custom_question, chunking, embed_model, retriever, chunk_count, retriever_type,
                     reranking, evaluator):
    final_question = custom_question if custom_question.strip() else question
    print(f"The query is {final_question}")

    # 1. Load pre-chunked data (you should load from memory or cache as needed)
    # chunks = load_chunked_data(subset=subset, strategy=chunking)

    print("Starting RAG pipeline using print")
    logging.info("Starting RAG Pipeline using logging")
    gr.Info("Starting RAG Pipeline using gradio")  # Shows as a toast notification in UI

    rag = RAGSystem(
            subset=subset,
            dataset_type="test",
            strategy=chunking,
            chunks=[],  # Not needed for loading
            generator_model_name=retriever,
            retriever_model_name=embed_model
        )

    # 3. Load or use stored vector DB
    # rag.store_embeddings_database()  # or 
    rag.load_embeddings_database(retriever_type=retriever_type)
    print("Loaded the embeddings database - Complete")

    # 4. Retrieve and Generate Answer
    retrieved_chunks = rag.retrieve(final_question, top_k=chunk_count)
    print("Retrieved the chunks - Complete")

    context_docs = [chunk.text for chunk in retrieved_chunks]
    print(f"Retrieved Chunks: {context_docs}")
    # context_docs = rag.trim_context(context_docs)
    # context = "\n\n".join(context_docs)
    document_sentences = form_document_sentences_from_chunks(context_docs)

    generated_answer = rag.generate(final_question, context_docs)
    print("Generated the answer - Complete, generated_answer: ", generated_answer)

    response_sentences = form_response_sentences(generated_answer)

    # print(f"\nResponse Sentences: {response_sentences}")

    print(f"Length of Response Sentences: {len(response_sentences)}")
    print(f"Length of Document Sentences : {len(document_sentences)}")

    y_pred_metrics = {
        "relevance_score": "NA",
        "utilization_score": "NA",
        "completeness_score": "NA",
        "adherence_score": "NA"
    }

    # Call evaluator with the right variables
    try:
        grok_api_key = os.environ.get("GROQ_API_KEY")  # Safely loaded from HF Secrets

        evaluator = RAGEvaluator(
            use_groq=True,
            groq_api_key=grok_api_key,
            groq_model="llama3-70b-8192"
        )
        
        result = evaluator.evaluate(document_sentences, question, response_sentences)
        print(f"\nResult----\n: {result}")
        if result is not None:
            y_pred_metrics = evaluator.extract_trace_metrics_from_json(result, len(document_sentences))
            evaluator_json_output = json.dumps(result, indent=4)
            print(f"Result: {evaluator_json_output}")
            print(f"Metrics: {y_pred_metrics}")
        else:
            print("No result obtained for this question")
    except Exception as e:
        print(f"Exception Raised in evaluation / extract_trace_metrics_from_json. Details: {e}")
    
    # Format as list of lists
    formatted_chunks = [
        [f"Source {i+1}", chunk.text]
        for i, chunk in enumerate(retrieved_chunks)
    ]

    return (
        generated_answer,
        json.dumps(y_pred_metrics, indent=2),
        formatted_chunks,
        json.loads(evaluator_json_output) if evaluator_json_output else {"error": "No evaluation result available."},
        None
    )


# UI Layout
# with gr.Blocks(title="RAGBench Explorer") as demo:
with gr.Blocks(
    head="<!DOCTYPE html>",
    css=":root { -webkit-print-color-adjust: exact; }") as demo: 
    demo.title = "RAGBench Interactive Explorer"
    gr.Markdown("## πŸ” RAGBench Interactive Explorer")

    with gr.Row():
        with gr.Column(scale=2):
            gr.Markdown("### βš™οΈ Subset and Dataset Selection")
            subset_dropdown = gr.Dropdown(choices=available_subsets, label="πŸ“‚ Subset", value=initial_subset, interactive=True)
            dataset_type_dropdown = gr.Dropdown(choices=["test"], label="πŸ“‚ Dataset Type", value="test", interactive=False)

        
        with gr.Column(scale=3):
            gr.Markdown("### βš™οΈ Chunking and Model Selection")
            chunking_dropdown = gr.Dropdown(choices=CHUNKING_STRATEGIES, label="πŸ“¦ Chunking Strategy", value="SentenceBasedLangchain")
            embed_dropdown = gr.Dropdown(choices=embedding_models, label="πŸ”— Embedding Model", value="BAAI/bge-large-en-v1.5")
            retriever_dropdown = gr.Dropdown(choices=generator_models, label="🧭 Generator Model", value="mistralai/Mistral-7B-Instruct-v0.2")

        with gr.Column(scale=4):
            gr.Markdown("### βš™οΈ Retrieval Settings and Evaluation Option")
            chunk_count = gr.Slider(minimum=1, maximum=15,
                    value=5,  # Default value
                    step=1, label="Number of Chunks to Retrieve")
                
            retriever_type = gr.Dropdown(
                    choices=["BM25", "Vector"],  # Add other options as needed
                    value="BM25",  # Default selection
                    label="Retriever Type")
            
            reranking_checkbox = gr.Checkbox(label="Use Reranking", value=False)
            evaluator_dropdown = gr.Dropdown(choices=evaluators, label="🧠 Evaluator Model", value="llama")

    with gr.Row():
        metrics_plot = gr.Plot()
        chunking_strategies_plot = gr.Plot()
    
    with gr.Row():
        question_dropdown = gr.Dropdown(choices=available_questions[initial_subset], filterable=True, label="πŸ“‹ Predefined Questions", interactive=True)
        custom_question_input = gr.Textbox(label="✍️ Custom Question (optional)")


    # Link dropdown to plot
    subset_dropdown.change(fn=plot_subset_metrics, inputs=[subset_dropdown], outputs=[metrics_plot])
    subset_dropdown.change(fn=plot_chunking_strategies, inputs=[subset_dropdown], outputs=[chunking_strategies_plot])

    submit_btn = gr.Button("πŸš€ Run RAG Evaluation", variant="primary")

    with gr.Row():
        with gr.Column(scale=2):
            gr.Markdown("### πŸ“„ Original Answer and Metrics")
            orig_ans_display = gr.Textbox(label="πŸ“ Original Answer", lines=5, interactive=False)
            y_metrics_display = gr.JSON(label="y-metrics", value={})

        with gr.Column(scale=2):
            gr.Markdown("### πŸ€– Generated Answer and Evaluation Metrics")
            gen_ans_display = gr.Textbox(label="πŸ€– Generated Answer", lines=5)
            y_pred_metrics_display = gr.JSON(label="πŸ“Š Evaluation (y-pred) Metrics", value={})
        
        with gr.Column(scale=2):
            gr.Markdown("### πŸ“Š Analysis Results")
            # chunks_retrieved_display = gr.Textbox(label="Chunks Retrieved", lines=5, interactive=False)
            with gr.Accordion(label="πŸ” Retrieved Chunks (Expand to View)", open=False):
                chunks_retrieved_display = gr.Dataframe(
                    headers=["Source", "Chunk Text"],
                    datatype=["str", "str"],
                    interactive=False,
                    wrap=True)
            evaluator_json_output = gr.JSON(label="Analysis Results", value={})


    subset_dropdown.change(fn=update_question_list_and_info, inputs=[subset_dropdown], outputs=[question_dropdown, orig_ans_display, y_metrics_display])
    question_dropdown.change(fn=get_info_from_sample_questions, inputs=[subset_dropdown, question_dropdown], outputs=[orig_ans_display, y_metrics_display])

    with gr.Row():
        # Add export button
        # gr.Interface(fn=generate_file, inputs=orig_ans_display, outputs="file")
        generate_btn = gr.Button("Generate JSON & Download")
        with gr.Column(scale=2):
            json_output = gr.Code(label="JSON Output", max_lines=50, language="json")
            download_file = gr.File(label="Download Link")

    submit_btn.click(
        fn=run_rag_pipeline,
        inputs=[
            subset_dropdown, question_dropdown, custom_question_input,
            chunking_dropdown, embed_dropdown, retriever_dropdown,
            chunk_count, retriever_type,
            reranking_checkbox, evaluator_dropdown
        ],
        outputs=[gen_ans_display, y_pred_metrics_display, chunks_retrieved_display, evaluator_json_output, download_file]
    )

    generate_btn.click(
        fn=generate_file,
        inputs=[subset_dropdown, dataset_type_dropdown, 
                chunking_dropdown, embed_dropdown, retriever_dropdown,
                chunk_count, retriever_type,
                reranking_checkbox, evaluator_dropdown,
                orig_ans_display, y_metrics_display,
                gen_ans_display, y_pred_metrics_display,
                chunks_retrieved_display, 
                evaluator_json_output
                ],
            outputs=[json_output, download_file]
        )


demo.launch(debug=True, prevent_thread_lock=True, share=True)