Files
auto-ragas/rag_evaluation/testset/document_loader.py
T
2026-01-16 16:01:39 +08:00

101 lines
2.5 KiB
Python

"""
Document loader for various file formats
"""
from typing import List, Dict, Any
from pathlib import Path
import os
class Document:
"""Document class to represent loaded documents"""
def __init__(self, content: str, metadata: Dict[str, Any]):
self.page_content = content
self.metadata = metadata
class DocumentLoader:
"""Base document loader"""
def __init__(self, file_path: str):
self.file_path = Path(file_path)
if not self.file_path.exists():
raise FileNotFoundError(f"File not found: {file_path}")
def load(self) -> List[Document]:
"""Load document and return list of Document objects"""
raise NotImplementedError("Subclasses must implement load()")
def get_file_size(self) -> int:
"""Get file size in bytes"""
return os.path.getsize(self.file_path)
def get_file_extension(self) -> str:
"""Get file extension"""
return self.file_path.suffix.lower()
class TextLoader(DocumentLoader):
"""Text file loader"""
def load(self) -> List[Document]:
"""Load text file"""
with open(self.file_path, 'r', encoding='utf-8') as f:
content = f.read()
metadata = {
'source': str(self.file_path),
'file_type': 'text',
'file_size': self.get_file_size()
}
return [Document(content=content, metadata=metadata)]
class MarkdownLoader(DocumentLoader):
"""Markdown file loader"""
def load(self) -> List[Document]:
"""Load markdown file"""
with open(self.file_path, 'r', encoding='utf-8') as f:
content = f.read()
metadata = {
'source': str(self.file_path),
'file_type': 'markdown',
'file_size': self.get_file_size()
}
return [Document(content=content, metadata=metadata)]
def load_documents(file_paths: List[str]) -> List[Document]:
"""
Load multiple documents from file paths
Args:
file_paths: List of file paths to load
Returns:
List of Document objects
"""
documents = []
for file_path in file_paths:
path = Path(file_path)
extension = path.suffix.lower()
if extension in ['.txt']:
loader = TextLoader(file_path)
elif extension in ['.md', '.markdown']:
loader = MarkdownLoader(file_path)
else:
# For now, treat unknown types as text
loader = TextLoader(file_path)
docs = loader.load()
documents.extend(docs)
return documents