
    h$                         d Z ddlZddlZddlmZ ddlmZ ddlmZ ddl	m
Z
mZmZmZmZmZ ddlmZ ddlmZ  ej(                  e      Z G d	 d
e      Zy)zDocument loader for EverNote ENEX export files.

This module provides functionality to securely load and parse EverNote notebook
export files (``.enex`` format) into LangChain Document objects.
    N)	b64decode)Path)strptime)AnyDictIteratorListOptionalUnion)Document)
BaseLoaderc                       e Zd ZdZddeeef   defdZde	e
   fdZde	e
   fdZededefd	       Zed
edefd       Zeddedee   defd       Zedede	eeef      fd       Zy)EverNoteLoadera  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``
    	file_pathload_single_documentc                 2    t        |      | _        || _        y)a  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.
        N)strr   r   )selfr   r   s      k/var/www/html/eduruby.in/venv/lib/python3.12/site-packages/langchain_community/document_loaders/evernote.py__init__zEverNoteLoader.__init__<   s     Y$8!    returnc              #     K   | j                  | j                        D ]\  }|j                  d      t        |d   i |j	                         D ci c]  \  }}|dvr|| c}}d| j                  i       ^ yc c}}w w)a-  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.
        contentN)r   content-rawresourcesourcepage_contentmetadata)_parse_note_xmlr   getr   items)r   notekeyvalues       r   
_lazy_loadzEverNoteLoader._lazy_loadI   s      ((8 	Dxx	".!%i /3jjl *U"*PP  J $T^^4
 
	
s   0BBA>!#Bc              #     K   | j                   s| j                         E d{    yt        dj                  | j                         D cg c]  }|j                   c}      d| j
                  i       y7 Vc c}w w)a9  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.
        N r   r   )r   r'   r   joinr   r   )r   documents     r   	lazy_loadzEverNoteLoader.lazy_loadc   sn      (((((WW;???;LMxX**M #DNN3	  ) Ns!    B A9'B 
A;B ;B r   c                     	 ddl }|j                  |       j                         S # t        $ r}t        d      |d}~ww xY w)a  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.
        r   NzCould 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.)	html2textstripImportError)r   r.   es      r   _parse_contentzEverNoteLoader._parse_contentv   sL     		&&w/5577 	X 		s   "% 	?:?r   c                 0   i }| D ]  }|j                   dk(  rd|j                  rt        |j                        nd||j                   <   t        j                  ||j                            j                         |d<   v|j                  ||j                   <    |S )ac  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.
        datar   hash)tagtextr   hashlibmd5	hexdigest)r   rsc_dictelems      r   _parse_resourcezEverNoteLoader._parse_resource   s     $& 	/Dxx6!=AYYYtyy%9C"#*;;x/A#B#L#L#N %)YY"	/ r   Nr$   prefixc                     i }g }dt         dt         ffd}| D ]  }|j                  dk(  r<t        j                  |j                        ||j                  <   |j                  |d<   O|j                  dk(  r%|j                  t        j                  |             |j                  dk(  s|j                  dk(  r$t        |j                  d	      ||j                  <   |j                  d
k(  r3t        j                  ||j                        }|j                  |       |j                  ||j                  <   " t        |      dkD  r||d<   |j                         D ci c]  \  }} ||      | c}}S c c}}w )a  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.
        element_tagr   c                     | S  d|  S )N. )r@   r>   s    r   
add_prefixz.EverNoteLoader._parse_note.<locals>.add_prefix   s    ~""XQ{m,,r   r   r   r   createdupdatedz%Y%m%dT%H%M%SZznote-attributesr   )r   r6   r   r2   r7   appendr=   r   _parse_noteupdatelenr#   )	r$   r>   	note_dict	resourcesrD   r<   additional_attributesr%   r&   s	    `       r   rH   zEverNoteLoader._parse_note   sJ    %'			-C 	-C 	-
  	0Dxx9$&4&C&CDII&N	$((#+/99	-(Z'  !?!?!EFY&$((i*?&.tyy:J&K	$((#..(6(B(B$(()%   !67&*ii	$((#	0" y>A$-Ij!9B9JK:3
3&KKKs   #E:xml_filec              #      K   	 ddl m} |j                  | ddddd      }|D ],  \  }}|j                  d	k(  st        j                  |       . y# t        $ r}t        j	                  d       |d}~ww xY ww)
a  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.
        r   )etreezCould 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.Nzutf-8FT)encodingresolve_entities
no_networkrecover	huge_treer$   )	lxmlrP   r0   loggererror	iterparser6   r   rH   )rN   rP   r1   contextactionr<   s         r   r!   zEverNoteLoader._parse_note_xml   s      	" //" " 
 $ 	7LFDxx6!$0066	7#  	LL?
 G	s,   A;A .A;A;	A8A33A88A;)T)N)__name__
__module____qualname____doc__r   r   r   boolr   r   r   r'   r,   staticmethodr2   listdictr=   r	   r
   rH   r   r   r!   rC   r   r   r   r      s    $L9%T	"2 9$ 9HX. 48H- &    4 $ 4  . )L$ )L )L )L )LV $7# $7(4S>*B $7 $7r   r   )r_   r8   loggingbase64r   pathlibr   timer   typingr   r   r   r	   r
   r   langchain_core.documentsr   )langchain_community.document_loaders.baser   	getLoggerr\   rW   r   rC   r   r   <module>rl      sG         = = - @			8	$e7Z e7r   