yuvis commited on
Commit
a3c924f
·
verified ·
1 Parent(s): f4c70c8

Upload folder using huggingface_hub

Browse files
Files changed (3) hide show
  1. tools/generate-dataset.py +71 -0
  2. tools/run_eval.py +105 -0
  3. tools/test_query.py +29 -0
tools/generate-dataset.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import random
3
+ from datasets import load_dataset
4
+
5
+ RAW_DIR = "data/raw"
6
+
7
+ def save_docs(dataset_name, docs, prefix, field="text"):
8
+ print(f"Saving {len(docs)} docs from {dataset_name}...")
9
+ for i, doc_content in enumerate(docs):
10
+ # Handle cases where content might be dict or list
11
+ if isinstance(doc_content, dict):
12
+ content = doc_content.get(field, "")
13
+ else:
14
+ content = doc_content
15
+
16
+ if not content:
17
+ continue
18
+
19
+ filename = f"{RAW_DIR}/{prefix}_{i:03d}.txt"
20
+ with open(filename, "w", encoding="utf-8") as f:
21
+ f.write(f"Source: {dataset_name}\n\n")
22
+ f.write(str(content))
23
+
24
+ def main():
25
+ os.makedirs(RAW_DIR, exist_ok=True)
26
+
27
+ # Clear existing files to avoid mixing fake data with real data
28
+ print("Clearing old data...")
29
+ import glob
30
+ files = glob.glob(f"{RAW_DIR}/*")
31
+ for f in files:
32
+ os.remove(f)
33
+
34
+ # 1. Multi-News (Long news articles)
35
+ print("Downloading Multi-News...")
36
+ try:
37
+ ds = load_dataset("alexfabbri/multi_news", split="train[:50]", trust_remote_code=True) # Take 50
38
+ save_docs("Multi-News", ds["document"], "multinews", field="document")
39
+ except Exception as e:
40
+ print(f"Error loading Multi-News: {e}")
41
+
42
+ # 2. GovReport (Gov reports)
43
+ print("Downloading GovReport...")
44
+ try:
45
+ ds = load_dataset("launch/gov_report", split="train[:20]", trust_remote_code=True) # Take 20 (they are long)
46
+ save_docs("GovReport", ds["document"], "govreport", field="document")
47
+ except Exception as e:
48
+ print(f"Error loading GovReport: {e}")
49
+
50
+ # 3. WikiQA (QA pairs - we'll index the candidate sentences as knowledge)
51
+ print("Downloading WikiQA...")
52
+ try:
53
+ ds = load_dataset("microsoft/wiki_qa", split="train[:100]", trust_remote_code=True) # Take 100
54
+ # WikiQA has 'question', 'answer', 'document_title', 'label'
55
+ save_docs("WikiQA", ds["answer"], "wikiqa", field="answer")
56
+ except Exception as e:
57
+ print(f"Error loading WikiQA: {e}")
58
+
59
+ # 4. Financial Phrasebank (Sentences)
60
+ print("Downloading Financial Phrasebank...")
61
+ try:
62
+ # Use official dataset for reliability
63
+ ds = load_dataset("financial_phrasebank", "sentences_allagree", split="train[:100]", trust_remote_code=True)
64
+ save_docs("FinancialPhrasebank", ds["sentence"], "finphrase", field="sentence")
65
+ except Exception as e:
66
+ print(f"Error loading Financial Phrasebank: {e}")
67
+
68
+ print("Done generating real data.")
69
+
70
+ if __name__ == "__main__":
71
+ main()
tools/run_eval.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ from datasets import load_dataset
4
+ from tqdm import tqdm
5
+ import numpy as np
6
+ from src.pipeline.query_pipeline import QueryPipeline
7
+ from src.eval.retrieval_metrics import recall_at_k, mrr_score, precision_at_k
8
+ from src.eval.hallucination import HallucinationGrader
9
+ from src.eval.relevancy import RelevancyGrader
10
+
11
+ def main():
12
+ print("Initializing Pipeline...")
13
+ pipeline = QueryPipeline()
14
+ grader = HallucinationGrader(pipeline.llm)
15
+ relevancy_grader = RelevancyGrader(pipeline.llm)
16
+
17
+ print("Loading Evaluation Data (WikiQA Test Split)...")
18
+ # For meaningful evaluation, we need questions that actually have answers in our indexed subset.
19
+ # Since we indexed the 'train' split of WikiQA (first 100), we should evaluate on that same subset
20
+ # to test "retrieval ability" (can it find what we vaguely know is there).
21
+ # In a real scenario, you'd test on a hold-out set, but only if you indexed the whole knowledge base.
22
+ try:
23
+ ds = load_dataset("microsoft/wiki_qa", split="train[:20]", trust_remote_code=True)
24
+ except Exception as e:
25
+ print(f"Error loading dataset: {e}")
26
+ return
27
+
28
+ # Metrics
29
+ recalls = []
30
+ precisions = []
31
+ mrrs = []
32
+ hallucination_scores = []
33
+ relevancy_scores = []
34
+
35
+ print("Running Evaluation...")
36
+ for i, row in tqdm(enumerate(ds), total=len(ds)):
37
+ query = row['question']
38
+ relevant_doc_content = row['answer'] # The correct sentence
39
+ is_correct = row['label'] == 1
40
+
41
+
42
+
43
+
44
+ if not is_correct:
45
+ # If this row isn't a correct answer pair, skip for retrieval accuracy measurement
46
+ # (or treat as a negative, but for RAG recall we usually care about positive queries)
47
+ continue
48
+
49
+ result = pipeline.run(query, top_k_retrieval=10, top_k_rerank=3)
50
+
51
+ # Retrieval Metrics
52
+ retrieved_contents = [doc if isinstance(doc, str) else doc['content'] for doc, score in result['context']]
53
+
54
+
55
+
56
+
57
+ # Check if relevant content is in retrieved
58
+ # The ingestion pipeline might add metadata like "Source: ...".
59
+ # So we check if the relevant content SUBSTRING is in the retrieved chunks.
60
+ is_hit = False
61
+ for content in retrieved_contents:
62
+ if relevant_doc_content in content:
63
+ is_hit = True
64
+ break
65
+
66
+ recalls.append(1.0 if is_hit else 0.0)
67
+ # Precision (strict: is the retrieved doc the specific sentence?)
68
+ # Since we only retrieve 10 and usually there is only 1 relevant sentence in WikiQA:
69
+ # Precision will be at best 0.1 if is_hit is true.
70
+ precisions.append(1.0/10.0 if is_hit else 0.0)
71
+
72
+ # MRR
73
+ # Find rank
74
+ rank = -1
75
+ for idx, content in enumerate(retrieved_contents):
76
+ if relevant_doc_content in content:
77
+ rank = idx + 1
78
+ break
79
+
80
+ if rank > 0:
81
+ mrrs.append(1.0 / rank)
82
+ else:
83
+ mrrs.append(0.0)
84
+
85
+ # Generation / Hallucination Metric
86
+ # We ask the LLM to grade if the answer supported by context
87
+ grade = grader.grade(
88
+ context="\n".join(retrieved_contents),
89
+ answer=result['answer']
90
+ )
91
+ hallucination_scores.append(grade.get('score', 0.0))
92
+
93
+ # New: Answer Relevancy
94
+ rel_grade = relevancy_grader.grade(query=query, answer=result['answer'])
95
+ relevancy_scores.append(rel_grade.get('score', 0.0))
96
+
97
+ print("\nXXX Evaluation Results XXX")
98
+ print(f"Average Recall@10: {np.mean(recalls):.4f}")
99
+ print(f"Average Precision@10: {np.mean(precisions):.4f}")
100
+ print(f"Average MRR: {np.mean(mrrs):.4f}")
101
+ print(f"Average Factuality Score: {np.mean(hallucination_scores):.4f}")
102
+ print(f"Average Answer Relevancy: {np.mean(relevancy_scores):.4f}")
103
+
104
+ if __name__ == "__main__":
105
+ main()
tools/test_query.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os
3
+ from src.pipeline.query_pipeline import QueryPipeline
4
+
5
+ def test_manual_query():
6
+ print("Initializing Pipeline...")
7
+ pipeline = QueryPipeline()
8
+
9
+ query = 'what is emerging contaminants according to DOD?'
10
+ print(f"\nProcessing Query: {query}")
11
+
12
+ # Run pipeline
13
+ result = pipeline.run(query, top_k_retrieval=5, top_k_rerank=3)
14
+
15
+ print("\n--- Retrieved Context (Top 3) ---")
16
+ for doc, score in result['context']:
17
+ content = doc if isinstance(doc, str) else doc['content']
18
+ print(f"[Score: {score:.4f}] {content[:150]}...")
19
+
20
+ print("\n--- Generated Answer ---")
21
+ print(result['answer'])
22
+
23
+ print("\n--- Scores ---")
24
+ print(f"Retrieval Score: {result.get('retrieval_score', 'N/A')}")
25
+ print(f"Hallucination Score: {result.get('hallucination_score', 'N/A')}")
26
+ print(f"Groundedness: {result.get('groundedness', 'N/A')}")
27
+
28
+ if __name__ == "__main__":
29
+ test_manual_query()