Source code for langchain_community.document_loaders.evernote
"""Document loader for EverNote ENEX export files.This module provides functionality to securely load and parse EverNote notebookexport files (``.enex`` format) into LangChain Document objects."""importhashlibimportloggingfrombase64importb64decodefrompathlibimportPathfromtimeimportstrptimefromtypingimportAny,Dict,Iterator,List,Optional,Unionfromlangchain_core.documentsimportDocumentfromlangchain_community.document_loaders.baseimportBaseLoaderlogger=logging.getLogger(__name__)
[docs]classEverNoteLoader(BaseLoader):"""Document loader for EverNote ENEX export files. Loads EverNote notebook export files (``.enex`` format) into LangChain Documents. Extracts plain text content from HTML and preserves note metadata including titles, timestamps, and attachments. Uses secure XML parsing to prevent vulnerabilities. The loader supports two modes: - Single document: Concatenates all notes into one Document (default) - Multiple documents: Creates separate Documents for each note `Instructions for creating ENEX files <https://help.evernote.com/hc/en-us/articles/209005557-Export-notes-and-notebooks-as-ENEX-or-HTML>`__ Example: .. code-block:: python from langchain_community.document_loaders import EverNoteLoader # Load all notes as a single document loader = EverNoteLoader("my_notebook.enex") documents = loader.load() # Load each note as a separate document: # documents = [ document1, document2, ... ] loader = EverNoteLoader("my_notebook.enex", load_single_document=False) documents = loader.load() # Lazy loading for large files for doc in loader.lazy_load(): print(f"Title: {doc.metadata.get('title', 'Untitled')}") print(f"Content: {doc.page_content[:100]}...") Note: Requires the ``lxml`` and ``html2text`` packages to be installed. Install with: ``pip install lxml html2text`` """
[docs]def__init__(self,file_path:Union[str,Path],load_single_document:bool=True):"""Initialize the EverNote loader. Args: file_path: Path to the EverNote export file (``.enex`` extension). load_single_document: Whether to concatenate all notes into a single Document. If ``True``, only the ``source`` metadata is preserved. If ``False``, each note becomes a separate Document with its own metadata. """self.file_path=str(file_path)self.load_single_document=load_single_document
def_lazy_load(self)->Iterator[Document]:"""Lazily load documents from the EverNote export file. Lazy loading allows processing large EverNote files without loading everything into memory at once. This method yields Documents one by one by parsning the XML. Each document represents a note in the EverNote export, containing the note's content as ``page_content`` and metadata including ``title``, ``created/updated`` ``timestamps``, and other note attributes. Yields: Document: A Document object for each note in the export file. """fornoteinself._parse_note_xml(self.file_path):ifnote.get("content")isnotNone:yieldDocument(page_content=note["content"],metadata={**{key:valueforkey,valueinnote.items()ifkeynotin["content","content-raw","resource"]},**{"source":self.file_path},},)
[docs]deflazy_load(self)->Iterator[Document]:"""Load documents from EverNote export file. Depending on the ``load_single_document`` setting, either yields individual Documents for each note or a single Document containing all notes. Yields: Document: Either individual note Documents or a single combined Document. """ifnotself.load_single_document:yield fromself._lazy_load()else:yieldDocument(page_content="".join([document.page_contentfordocumentinself._lazy_load()]),metadata={"source":self.file_path},)
@staticmethoddef_parse_content(content:str)->str:"""Parse HTML content from EverNote into plain text. Converts HTML content to plain text using the ``html2text`` library. Strips whitespace from the result. Args: content: HTML content string from EverNote. Returns: Plain text version of the content. Raises: ImportError: If ``html2text`` is not installed. """try:importhtml2textreturnhtml2text.html2text(content).strip()exceptImportErrorase:raiseImportError("Could not import `html2text`. Although it is not a required package ""to use LangChain, using the EverNote loader requires `html2text`. ""Please install `html2text` via `pip install html2text` and try again.")frome@staticmethoddef_parse_resource(resource:list)->dict:"""Parse resource elements from EverNote XML. Extracts resource information like attachments, images, etc. Base64 decodes data elements and generates MD5 hashes. Args: resource: List of XML elements representing a resource. Returns: Dictionary containing resource metadata and decoded data. """rsc_dict:Dict[str,Any]={}foreleminresource:ifelem.tag=="data":# Sometimes elem.text is Nonersc_dict[elem.tag]=b64decode(elem.text)ifelem.textelseb""rsc_dict["hash"]=hashlib.md5(rsc_dict[elem.tag]).hexdigest()else:rsc_dict[elem.tag]=elem.textreturnrsc_dict@staticmethoddef_parse_note(note:List,prefix:Optional[str]=None)->dict:"""Parse a note element from EverNote XML. Extracts note content, metadata, resources, and attributes. Handles nested note-attributes recursively with prefixes. Args: note: List of XML elements representing a note. prefix: Optional prefix for nested attribute names. Returns: Dictionary containing note content and metadata. """note_dict:Dict[str,Any]={}resources=[]defadd_prefix(element_tag:str)->str:ifprefixisNone:returnelement_tagreturnf"{prefix}.{element_tag}"foreleminnote:ifelem.tag=="content":note_dict[elem.tag]=EverNoteLoader._parse_content(elem.text)# A copy of original contentnote_dict["content-raw"]=elem.textelifelem.tag=="resource":resources.append(EverNoteLoader._parse_resource(elem))elifelem.tag=="created"orelem.tag=="updated":note_dict[elem.tag]=strptime(elem.text,"%Y%m%dT%H%M%SZ")elifelem.tag=="note-attributes":additional_attributes=EverNoteLoader._parse_note(elem,elem.tag)# Recursively enter the note-attributes tagnote_dict.update(additional_attributes)else:note_dict[elem.tag]=elem.textiflen(resources)>0:note_dict["resource"]=resourcesreturn{add_prefix(key):valueforkey,valueinnote_dict.items()}@staticmethoddef_parse_note_xml(xml_file:str)->Iterator[Dict[str,Any]]:"""Parse EverNote XML file securely. Uses ``lxml`` with secure parsing configuration to prevent XML vulnerabilities including XXE attacks, XML bombs, and malformed XML exploitation. Args: xml_file: Path to the EverNote export XML file. Yields: Dictionary containing parsed note data for each note in the file. Raises: ImportError: If ``lxml`` is not installed. """try:fromlxmlimportetreeexceptImportErrorase:logger.error("Could not import `lxml`. Although it is not a required package to use ""LangChain, using the EverNote loader requires `lxml`. Please install ""`lxml` via `pip install lxml` and try again.")raiseecontext=etree.iterparse(xml_file,encoding="utf-8",resolve_entities=False,# Prevents XXE attacksno_network=True,# Blocks network-based external entitiesrecover=False,# Avoid parsing invalid/malformed XMLhuge_tree=False,# Protect against XML Bomb DoS attacks)foraction,elemincontext:ifelem.tag=="note":yieldEverNoteLoader._parse_note(elem)