Spaces:
Sleeping
Sleeping
File size: 9,716 Bytes
d40b9df |
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 |
from datasets import load_dataset
from typing import List, Dict, Optional
import json
class DatasetHandler:
"""Handles loading and searching the CGIAR agricultural dataset."""
def __init__(self, use_streaming: bool = True, max_samples: Optional[int] = None):
"""
Initialize dataset handler.
Args:
use_streaming: If True, use streaming mode (faster, doesn't download all files)
max_samples: Maximum number of samples to load (None = all, for testing use smaller number)
"""
self.dataset = None
self.loaded = False
self.use_streaming = use_streaming
self.max_samples = max_samples
def load_dataset(self):
"""Load the CGIAR dataset from HuggingFace."""
if not self.loaded:
try:
print("Loading CGIAR dataset from HuggingFace (this may take a moment)...")
if self.use_streaming:
self.dataset = load_dataset(
"CGIAR/gardian-ai-ready-docs",
split="train",
streaming=True
)
print("Dataset loaded in streaming mode (lazy loading - files downloaded on-demand only)")
else:
if self.max_samples:
self.dataset = load_dataset(
"CGIAR/gardian-ai-ready-docs",
split=f"train[:{self.max_samples}]"
)
print(f"Dataset loaded successfully! Loaded {len(self.dataset)} documents (sample)")
else:
self.dataset = load_dataset("CGIAR/gardian-ai-ready-docs", split="train")
print(f"Dataset loaded successfully! Total documents: {len(self.dataset)}")
self.loaded = True
except Exception as e:
print(f"Error loading dataset: {e}")
raise
return self.dataset
def search_by_keyword(self, keyword: str, limit: int = 5) -> List[Dict]:
"""
Search documents by keyword in title, abstract, or keywords.
Args:
keyword: Search keyword
limit: Maximum number of results to return
Returns:
List of matching documents
"""
if not self.loaded:
self.load_dataset()
keyword_lower = keyword.lower()
results = []
checked = 0
max_to_check = 300 if self.use_streaming else None
consecutive_errors = 0
max_consecutive_errors = 3
try:
for doc in self.dataset:
try:
checked += 1
# Show progress every 100 documents
if checked % 100 == 0:
print(f"[DATASET] Checked {checked} documents, found {len(results)} matches so far...")
if max_to_check and checked > max_to_check:
print(f"[DATASET] Reached search limit of {max_to_check} documents")
break
# Search in title
title = doc.get('title', '').lower()
# Search in abstract
abstract = doc.get('abstract', '').lower()
# Search in keywords
keywords = ' '.join(doc.get('keywords', [])).lower()
if keyword_lower in title or keyword_lower in abstract or keyword_lower in keywords:
results.append({
'title': doc.get('title', ''),
'abstract': doc.get('abstract', ''),
'keywords': doc.get('keywords', []),
'url': doc.get('metadata', {}).get('url', ''),
'source': doc.get('metadata', {}).get('source', ''),
'pageCount': doc.get('pageCount', 0)
})
consecutive_errors = 0 # Reset on success
if len(results) >= limit:
break
except Exception as e:
consecutive_errors += 1
if consecutive_errors >= max_consecutive_errors:
print(f"[DATASET] Too many consecutive errors ({consecutive_errors}), stopping search")
break
# Continue to next document
continue
except Exception as e:
print(f"[DATASET] Error during search: {e}")
# Return partial results if available
if results:
print(f"[DATASET] Found {len(results)} results after checking {checked} documents")
else:
print(f"[DATASET] No results found after checking {checked} documents")
return results
def search_by_topic(self, topic: str, limit: int = 5) -> List[Dict]:
"""
Search documents by agricultural topic.
Args:
topic: Agricultural topic (e.g., "crop management", "pest control")
limit: Maximum number of results to return
Returns:
List of matching documents
"""
return self.search_by_keyword(topic, limit)
def get_document_by_title(self, title: str) -> Optional[Dict]:
"""
Retrieve a specific document by its title.
Args:
title: Document title
Returns:
Document data or None if not found
"""
if not self.loaded:
self.load_dataset()
title_lower = title.lower()
checked = 0
max_to_check = 300 if self.use_streaming else None # Very aggressive limit
consecutive_errors = 0
max_consecutive_errors = 3
try:
for doc in self.dataset:
try:
checked += 1
if max_to_check and checked > max_to_check:
break
if doc.get('title', '').lower() == title_lower:
return {
'title': doc.get('title', ''),
'abstract': doc.get('abstract', ''),
'keywords': doc.get('keywords', []),
'chapters': doc.get('chapters', []),
'figures': doc.get('figures', []),
'url': doc.get('metadata', {}).get('url', ''),
'source': doc.get('metadata', {}).get('source', ''),
'pageCount': doc.get('pageCount', 0)
}
except Exception as e:
consecutive_errors += 1
if consecutive_errors >= max_consecutive_errors:
break
continue
except Exception as e:
print(f"[DATASET] Error searching for document: {e}")
return None
def get_random_documents(self, limit: int = 3) -> List[Dict]:
"""
Get random documents from the dataset.
Args:
limit: Number of documents to return
Returns:
List of random documents
"""
if not self.loaded:
self.load_dataset()
import random
results = []
if self.use_streaming:
count = 0
for doc in self.dataset:
if count >= limit:
break
results.append({
'title': doc.get('title', ''),
'abstract': doc.get('abstract', ''),
'keywords': doc.get('keywords', []),
'url': doc.get('metadata', {}).get('url', ''),
'source': doc.get('metadata', {}).get('source', ''),
'pageCount': doc.get('pageCount', 0)
})
count += 1
else:
indices = random.sample(range(len(self.dataset)), min(limit, len(self.dataset)))
for idx in indices:
doc = self.dataset[idx]
results.append({
'title': doc.get('title', ''),
'abstract': doc.get('abstract', ''),
'keywords': doc.get('keywords', []),
'url': doc.get('metadata', {}).get('url', ''),
'source': doc.get('metadata', {}).get('source', ''),
'pageCount': doc.get('pageCount', 0)
})
return results
def format_document_summary(self, doc: Dict) -> str:
"""
Format a document for display in the chat.
Args:
doc: Document dictionary
Returns:
Formatted string representation
"""
summary = f"**Title:** {doc.get('title', 'N/A')}\n"
summary += f"**Abstract:** {doc.get('abstract', 'N/A')[:500]}...\n"
if doc.get('keywords'):
summary += f"**Keywords:** {', '.join(doc.get('keywords', []))}\n"
summary += f"**Source:** {doc.get('source', 'N/A')}\n"
if doc.get('url'):
summary += f"**URL:** {doc.get('url')}\n"
return summary
|