Spaces:
Sleeping
Sleeping
Download rag/loader.py from AI-ML-25/rag-chatbot: direct link, hf CLI and curl.
- Browser
- Download file 10.1 kB
-
https://huggingface.co/spaces/AI-ML-25/rag-chatbot/resolve/main/rag/loader.py
- Command line
-
hf download hf://spaces/AI-ML-25/rag-chatbot/rag/loader.py
-
curl -L -o loader.py https://huggingface.co/spaces/AI-ML-25/rag-chatbot/resolve/main/rag/loader.py
10.1 kB
| """ | |
| Document Loader Module | |
| Handles loading of documents from RAGBench datasets. | |
| Supports multiple domains with domain-specific document processing. | |
| """ | |
| import os | |
| from typing import List, Dict, Optional | |
| from langchain_core.documents import Document | |
| from datasets import load_dataset | |
| import logging | |
| logger = logging.getLogger(__name__) | |
| class RAGBenchLoader: | |
| """Loads documents from RAGBench datasets for specific domains.""" | |
| def __init__(self, config: Dict): | |
| """ | |
| Initialize the RAGBench document loader. | |
| Args: | |
| config: Configuration dictionary containing RAGBench settings | |
| """ | |
| self.config = config | |
| self.dataset_name = config.get('ragbench', {}).get('dataset_name', 'rungalileo/ragbench') | |
| self.domain_mapping = config.get('ragbench', {}).get('domain_mapping', {}) | |
| self.max_samples = config.get('ragbench', {}).get('max_samples_per_domain', 1000) | |
| def load_domain_documents(self, domain: str, split: str = "train") -> List[Document]: | |
| """ | |
| Load documents for a specific domain from RAGBench. | |
| Args: | |
| domain: Domain name (e.g., 'biomedical', 'legal', 'finance') | |
| split: Dataset split ('train' or 'test') | |
| Returns: | |
| List of LangChain Document objects | |
| """ | |
| if domain not in self.domain_mapping: | |
| logger.warning(f"Domain {domain} not found in mapping. Available: {list(self.domain_mapping.keys())}") | |
| return [] | |
| subset_name = self.domain_mapping[domain] | |
| logger.info(f"Loading {domain} domain from {self.dataset_name}/{subset_name} ({split} split)") | |
| try: | |
| # Try loading with specified split first | |
| try: | |
| dataset = load_dataset( | |
| self.dataset_name, | |
| subset_name, | |
| split=split | |
| ) | |
| except Exception as e: | |
| # If split fails, try without split specification | |
| logger.warning(f"Failed to load {split} split: {e}. Trying default split...") | |
| dataset = load_dataset( | |
| self.dataset_name, | |
| subset_name | |
| ) | |
| # Get the first available split | |
| if hasattr(dataset, 'keys'): | |
| available_splits = list(dataset.keys()) | |
| logger.info(f"Available splits: {available_splits}") | |
| if available_splits: | |
| dataset = dataset[available_splits[0]] | |
| logger.info(f"Using split: {available_splits[0]}") | |
| if not dataset or len(dataset) == 0: | |
| logger.warning(f"Empty dataset for {domain}") | |
| return [] | |
| documents = [] | |
| # Use full dataset if max_samples is -1, otherwise limit | |
| max_items = len(dataset) if self.max_samples == -1 else min(len(dataset), self.max_samples) | |
| logger.info(f"Processing {max_items} items from {domain} (total available: {len(dataset)})...") | |
| for idx, item in enumerate(dataset): | |
| if idx >= max_items: | |
| break | |
| # Extract document content and metadata based on domain | |
| doc = self._process_item(item, domain, idx) | |
| if doc: | |
| documents.append(doc) | |
| logger.info(f"Loaded {len(documents)} documents for {domain} domain") | |
| return documents | |
| except Exception as e: | |
| logger.error(f"Error loading domain {domain}: {str(e)}") | |
| logger.error(f"Try: pip install datasets --upgrade") | |
| return [] | |
| def _process_item(self, item: Dict, domain: str, idx: int) -> Optional[Document]: | |
| """ | |
| Process a dataset item into a Document object. | |
| RAGBench structure: All datasets have 'documents' (list), 'question', 'response', 'id' | |
| We index the DOCUMENTS (actual content), not questions. | |
| Args: | |
| item: Raw dataset item | |
| domain: Domain name | |
| idx: Item index | |
| Returns: | |
| Document object or None if processing fails | |
| """ | |
| try: | |
| # Debug: log available fields on first item | |
| if idx == 0: | |
| logger.info(f"Available fields in {domain}: {list(item.keys())}") | |
| # RAGBench datasets have standardized structure | |
| # Primary content is in 'documents' field (list of source documents) | |
| context = "" | |
| question = "" | |
| response = "" | |
| # Extract the actual documents (primary content to index) | |
| if 'documents' in item: | |
| docs = item['documents'] | |
| if isinstance(docs, list) and len(docs) > 0: | |
| # Join all documents with clear separators | |
| context = '\n\n=== DOCUMENT SEPARATOR ===\n\n'.join(str(d).strip() for d in docs if d) | |
| else: | |
| context = str(docs) | |
| # Fallback to other field names for non-RAGBench datasets | |
| elif 'document' in item: | |
| context = item['document'] | |
| elif 'context' in item: | |
| context = item['context'] | |
| elif 'contexts' in item: | |
| contexts = item['contexts'] | |
| if isinstance(contexts, list): | |
| context = '\n\n'.join(str(c) for c in contexts if c) | |
| else: | |
| context = str(contexts) | |
| elif 'passage' in item: | |
| context = item['passage'] | |
| elif 'text' in item: | |
| context = item['text'] | |
| # Extract question (stored in metadata, not primary content) | |
| if 'question' in item: | |
| question = item['question'] | |
| elif 'query' in item: | |
| question = item['query'] | |
| # Extract response (stored in metadata) | |
| if 'response' in item: | |
| response = item['response'] if isinstance(item['response'], str) else str(item['response']) | |
| elif 'answer' in item: | |
| response = item['answer'] if isinstance(item['answer'], str) else str(item['answer']) | |
| elif 'answers' in item: | |
| answers = item['answers'] | |
| if isinstance(answers, list) and len(answers) > 0: | |
| response = str(answers[0]) | |
| else: | |
| response = str(answers) | |
| # Validate we have actual content | |
| if not context or len(context.strip()) < 20: | |
| if idx == 0: | |
| logger.warning(f"No usable document content in {domain}. Item keys: {list(item.keys())}") | |
| return None | |
| # Primary content is the documents | |
| page_content = context | |
| # Create metadata | |
| metadata = { | |
| "source": f"{domain}_{idx}", | |
| "domain": domain, | |
| "index": idx, | |
| } | |
| # Add question and response to metadata (not primary content) | |
| if question: | |
| metadata["question"] = question | |
| if response: | |
| metadata["reference_response"] = response | |
| # Add other fields | |
| if 'id' in item: | |
| metadata["original_id"] = str(item['id']) | |
| return Document(page_content=page_content, metadata=metadata) | |
| except Exception as e: | |
| logger.warning(f"Failed to process item {idx} for {domain}: {str(e)}") | |
| return None | |
| def load_all_domains(self, domains: List[str], split: str = "train") -> Dict[str, List[Document]]: | |
| """ | |
| Load documents for multiple domains. | |
| Args: | |
| domains: List of domain names | |
| split: Dataset split | |
| Returns: | |
| Dictionary mapping domain names to document lists | |
| """ | |
| all_documents = {} | |
| for domain in domains: | |
| docs = self.load_domain_documents(domain, split) | |
| if docs: | |
| all_documents[domain] = docs | |
| return all_documents | |
| class DocumentLoader: | |
| """Legacy loader for backward compatibility - loads from local files.""" | |
| def __init__(self, data_dir: str = "data"): | |
| """ | |
| Initialize the document loader. | |
| Args: | |
| data_dir: Directory containing documents to load | |
| """ | |
| self.data_dir = data_dir | |
| self.supported_extensions = ['.txt', '.md'] | |
| def load_documents(self) -> List[Document]: | |
| """ | |
| Load all supported documents from the data directory. | |
| Returns: | |
| List of LangChain Document objects | |
| """ | |
| documents = [] | |
| if not os.path.exists(self.data_dir): | |
| raise ValueError(f"Data directory not found: {self.data_dir}") | |
| for filename in os.listdir(self.data_dir): | |
| file_path = os.path.join(self.data_dir, filename) | |
| if not os.path.isfile(file_path): | |
| continue | |
| ext = os.path.splitext(filename)[1].lower() | |
| if ext not in self.supported_extensions: | |
| continue | |
| with open(file_path, 'r', encoding='utf-8') as f: | |
| content = f.read() | |
| documents.append(Document( | |
| page_content=content, | |
| metadata={"source": filename, "domain": "general"} | |
| )) | |
| if not documents: | |
| raise ValueError(f"No documents found in {self.data_dir}") | |
| return documents | |