
    hO                       d dl mZ d dlZd dlZd dlZd dlmZ d dlmZm	Z	m
Z
mZmZmZmZmZ d dlZd dlmZ d dlmZmZ d dlmZ erd dlmZmZ d d	lmZ  G d
 de      Z G d d      Z G d d      Z e        G d de             Z y)    )annotationsN)StringIO)TYPE_CHECKINGAnyCallableLiteralOptional	TypedDictUnioncast)beta)BaseDocumentTransformerDocument)RecursiveCharacterTextSplitter)IterableSequence)PageElementc                  :    e Zd ZU dZded<   ded<   ded<   ded<   y)	ElementTypezElement type as typed dict.strurlxpathcontentdict[str, str]metadataN)__name__
__module____qualname____doc____annotations__     [/var/www/html/eduruby.in/venv/lib/python3.12/site-packages/langchain_text_splitters/html.pyr   r      s    %	HJLr"   r   c                  X    e Zd ZdZ	 d	 	 	 	 	 d	dZd
dZ	 d	 	 	 	 	 	 	 ddZddZddZy)HTMLHeaderTextSplittera~
  Split HTML content into structured Documents based on specified headers.

    Splits HTML content by detecting specified header tags (e.g., <h1>, <h2>) and
    creating hierarchical Document objects that reflect the semantic structure
    of the original content. For each identified section, the splitter associates
    the extracted text with metadata corresponding to the encountered headers.

    If no specified headers are found, the entire content is returned as a single
    Document. This allows for flexible handling of HTML input, ensuring that
    information is organized according to its semantic headers.

    The splitter provides the option to return each HTML element as a separate
    Document or aggregate them into semantically meaningful chunks. It also
    gracefully handles multiple levels of nested headers, creating a rich,
    hierarchical representation of the content.

    Example:

        .. code-block:: python

            from langchain_text_splitters.html_header_text_splitter import (
                HTMLHeaderTextSplitter,
            )

            # Define headers for splitting on h1 and h2 tags.
            headers_to_split_on = [("h1", "Main Topic"), ("h2", "Sub Topic")]

            splitter = HTMLHeaderTextSplitter(
                headers_to_split_on=headers_to_split_on,
                return_each_element=False
            )

            html_content = """
            <html>
              <body>
                <h1>Introduction</h1>
                <p>Welcome to the introduction section.</p>
                <h2>Background</h2>
                <p>Some background details here.</p>
                <h1>Conclusion</h1>
                <p>Final thoughts.</p>
              </body>
            </html>
            """

            documents = splitter.split_text(html_content)

            # 'documents' now contains Document objects reflecting the hierarchy:
            # - Document with metadata={"Main Topic": "Introduction"} and
            #   content="Introduction"
            # - Document with metadata={"Main Topic": "Introduction"} and
            #   content="Welcome to the introduction section."
            # - Document with metadata={"Main Topic": "Introduction",
            #   "Sub Topic": "Background"} and content="Background"
            # - Document with metadata={"Main Topic": "Introduction",
            #   "Sub Topic": "Background"} and content="Some background details here."
            # - Document with metadata={"Main Topic": "Conclusion"} and
            #   content="Conclusion"
            # - Document with metadata={"Main Topic": "Conclusion"} and
            #   content="Final thoughts."

    c                    t        |d       | _        t        | j                        | _        | j                  D cg c]  \  }}|	 c}}| _        || _        yc c}}w )a  Initialize with headers to split on.

        Args:
            headers_to_split_on: A list of (header_tag,
                header_name) pairs representing the headers that define splitting
                boundaries. For example, [("h1", "Header 1"), ("h2", "Header 2")]
                will split content by <h1> and <h2> tags, assigning their textual
                content to the Document metadata.
            return_each_element: If True, every HTML element encountered
                (including headers, paragraphs, etc.) is returned as a separate
                Document. If False, content under the same header hierarchy is
                aggregated into fewer Documents.
        c                $    t        | d   dd        S )Nr      )int)xs    r#   <lambda>z1HTMLHeaderTextSplitter.__init__.<locals>.<lambda>{   s    s1Q48} r"   )keyN)sortedheaders_to_split_ondictheader_mappingheader_tagsreturn_each_element)selfr.   r2   tag_s        r#   __init__zHTMLHeaderTextSplitter.__init__g   sW    & $*%<$
  #4#;#;<.2.F.FGFCCG#6  Hs   Ac                6    | j                  t        |            S )a]  Split the given text into a list of Document objects.

        Args:
            text: The HTML text to split.

        Returns:
            A list of split Document objects. Each Document contains
            `page_content` holding the extracted text and `metadata` that maps
            the header hierarchy to their corresponding titles.
        split_text_from_filer   r3   texts     r#   
split_textz!HTMLHeaderTextSplitter.split_text   s     (($88r"   c           
     (   |j                  d|       t        j                  |fd|j                  d|      i|j                         D ci c]  \  }}|dk7  s|| c}}}|j	                          | j                  |j                        S c c}}w )a=  Fetch text content from a URL and split it into documents.

        Args:
            url: The URL to fetch content from.
            timeout: Timeout for the request. Defaults to 10.
            **kwargs: Additional keyword arguments for the request.

        Returns:
            A list of split Document objects. Each Document contains
            `page_content` holding the extracted text and `metadata` that maps
            the header hierarchy to their corresponding titles.

        Raises:
            requests.RequestException: If the HTTP request fails.
        timeout)
setdefaultrequestsgetitemsraise_for_statusr<   r;   )r3   r   r>   kwargskvresponses          r#   split_text_from_urlz*HTMLHeaderTextSplitter.split_text_from_url   s    $ 	)W-<<
JJy'2
 !'A1!y.q!tA

 	!!#x}}-- Bs   
BBc                    t        |t              r't        |d      5 }|j                         }ddd       n|j                         }t	        | j                              S # 1 sw Y   #xY w)a  Split HTML content from a file into a list of Document objects.

        Args:
            file: A file path or a file-like object containing HTML content.

        Returns:
            A list of split Document objects. Each Document contains
            `page_content` holding the extracted text and `metadata` that maps
            the header hierarchy to their corresponding titles.
        zutf-8)encodingN)
isinstancer   openreadlist_generate_documents)r3   filefhtml_contents       r#   r9   z+HTMLHeaderTextSplitter.split_text_from_file   sb     dC dW- ( vvx( (  99;LD,,\:;;	( (s   A""A+c           	   #    K   	 ddl m}  ||d      }|j                  r|j                  n|}i g dfd}|g}|r|j	                         }	t        |	j                        }
ddlm |j                  fdt        |
      D               t        |	d	d      }|sa|	j                  d
d      D cg c]  }t        |      j                          }}dj                  d |D              }|st!        t        |	j"                              }|| j$                  v r| j&                  s |       }|r| 	 t)        |dd       }j-                         D cg c]  \  }\  }}}||k\  s| }}}}}|D ]  }|=  | j.                  |   }|||f|<   j-                         D ci c]  \  }}||d    }}}t1        ||       nj-                         D cg c]  \  }\  }}}||k  s| }}}}|D ]  }|=  | j&                  r6j-                         D ci c]  \  }}||d    }}}t1        ||       nj3                  |       |r| j&                  s |       }|r| yyy# t        $ r}d}t        |      |d}~ww xY wc c}w # t*        $ r d}Y dw xY wc c}}}}w c c}}w c c}}}w c c}}w w)a  Private method that performs a DFS traversal over the DOM and yields.

        Document objects on-the-fly. This approach maintains the same splitting
        logic (headers vs. non-headers, chunking, etc.) while walking the DOM
        explicitly in code.

        Args:
            html_content: The raw HTML content.

        Yields:
            Document objects as they are created.
        r   BeautifulSoupzEUnable to import BeautifulSoup. Please install via `pip install bs4`.Nhtml.parserc                     sydj                  d D              } j                          | j                         syj                         D ci c]  \  }}||d    }}}t	        | |      S c c}}w )z6Finalize the accumulated chunk into a single Document.Nz  
c              3  B   K   | ]  }|j                         s|  y wNstrip).0lines     r#   	<genexpr>zUHTMLHeaderTextSplitter._generate_documents.<locals>.finalize_chunk.<locals>.<genexpr>   s     $Tdtzz|T$Ts   r   page_contentr   )joinclearr[   rB   r   )
final_textrE   rF   
final_metaactive_headerscurrent_chunks       r#   finalize_chunkzBHTMLHeaderTextSplitter._generate_documents.<locals>.finalize_chunk   ss     $Tm$TTJ!##%.<.B.B.DEda!QqT'EJEjII Fs   A1)Tagc              3  <   K   | ]  }t        |      s|  y wrY   )rK   )r\   childrh   s     r#   r^   z=HTMLHeaderTextSplitter._generate_documents.<locals>.<genexpr>   s      E39Os   nameTFstring	recursive c              3  &   K   | ]	  }|s|  y wrY   r!   )r\   elems     r#   r^   z=HTMLHeaderTextSplitter._generate_documents.<locals>.<genexpr>   s      H$4 Hs   r(   i'  r_   )returnzOptional[Document])bs4rU   ImportErrorbodypoprN   childrenbs4.elementrh   extendreversedgetattrfind_allr   r[   ra   lenparentsr1   r2   r)   
ValueErrorrB   r0   r   append) r3   rR   rU   emsgsoupru   rg   stacknoderw   r4   rj   text_elements	node_text	dom_depthdoclevelrE   r5   lvldheaders_to_remover,   header_namerF   header_metaheaders_out_of_scopemetarh   re   rf   s                                 @@@r#   rO   z*HTMLHeaderTextSplitter._generate_documents   s    	*) \=9 IItyy4
 ;=#%	J 99;DDMM*H'LL #+H#5  $-C "]]$%]H E
  "M   H- HHID./I d&&&//(*C!	!ABLE -;,@,@,B% %(![aacUlA%! % - ,C&s+, #11#6/8%.K{+ 4B3G3G3IJ41aq!A$wJJILL +9*>*>*@( (&!YaAIPQMA($ ( 0 ,C&s+, ++0>0D0D0FG1AqtGGDG"	DII "((3C H '' "C	  (E  	*W  c")		*V* " ! E!% K( Hs   KI7 B'K4 JA"K7J KJ-
,J-
09K)J59'K J;2J;6-K#K3&KK7	J JJKJ*&K)J**KN)F)r.   list[tuple[str, str]]r2   boolrr   Noner;   r   rr   list[Document])
   )r   r   r>   r)   rD   r   rr   r   rP   r   rr   r   )rR   r   rr   r   )	r   r   r   r   r6   r<   rH   r9   rO   r!   r"   r#   r%   r%   '   sh    =D %*727 "7 
	749 (*..!$.58.	.6<$tr"   r%   c                  b    e Zd ZdZ	 	 	 	 	 	 d
dZddZddZ	 d	 	 	 	 	 ddZddZddZ	dd	Z
y)HTMLSectionSplitterz\Splitting HTML files based on specified tag and font sizes.

    Requires lxml package.
    c                    t        |      | _        t        j                  t              j
                  dz  j                         | _        || _        y)ay  Create a new HTMLSectionSplitter.

        Args:
            headers_to_split_on: list of tuples of headers we want to track mapped to
                (arbitrary) keys for metadata. Allowed header values: h1, h2, h3, h4,
                h5, h6 e.g. [("h1", "Header 1"), ("h2", "Header 2"].
            **kwargs (Any): Additional optional arguments for customizations.

        zxsl/converting_to_header.xsltN)	r/   r.   pathlibPath__file__parentabsolute	xslt_pathrD   )r3   r.   rD   s      r#   r6   zHTMLSectionSplitter.__init__8  sA     $((;#< LL")),KK
(* 	 r"   c                    g g }}|D ]8  }|j                  |j                         |j                  |j                         : | j                  ||      }t	        di | j
                  }|j                  |      S )zSplit documents.)	metadatasr!   )r   r`   r   create_documentsr   rD   split_documents)r3   	documentstextsr   r   resultstext_splitters          r#   r   z#HTMLSectionSplitter.split_documentsL  sw    ry 	+CLL))*S\\*	+ '''C6EE,,W55r"   c                6    | j                  t        |            S )zKSplit HTML text string.

        Args:
            text: HTML text
        r8   r:   s     r#   r<   zHTMLSectionSplitter.split_textX  s     (($88r"   Nc                   |xs i gt        |      z  }g }t        |      D ]  \  }}| j                  |      D ]  }t        j                  ||         }|j
                  D ]'  }	|j
                  |	   dk(  s|d   |j
                  |	<   ) i ||j
                  }t        |j                  |      }
|j                  |
         |S )z&Create documents from a list of texts.#TITLE#Titler_   )	r}   	enumerater<   copydeepcopyr   r   r`   r   )r3   r   r   
_metadatasr   ir;   chunkr   r,   new_docs              r#   r   z$HTMLSectionSplitter.create_documents`  s     32$U"3
	 ' 		*GAt. *==A7 >> @C~~c*i7.6w.?s+@ :h9%..9"0B0BXV  )*		* r"   c                   	 ddl m}  ||d      }t        | j                  j                               }g }|j                  dg|      }t        |      D ]  \  }}	t        d|	      }
|dk(  rd}d	}g }n(|
j                  j                         }|
j                  }g }|
j                  D ]B  }|d
z   t        |      k  r|||d
z      k(  r n$t        |t              s2|j!                  |       D dj#                  |      j                         }|dk7  s|j!                  |||d        |S # t        $ r}d}t        |      |d}~ww xY w)a  Split an HTML document into sections based on specified header tags.

        This method uses BeautifulSoup to parse the HTML content and divides it into
        sections based on headers defined in `headers_to_split_on`. Each section
        contains the header text, content under the header, and the tag name.

        Args:
            html_doc (str): The HTML document to be split into sections.

        Returns:
            List[Dict[str, Optional[str]]]: A list of dictionaries representing
            sections.
            Each dictionary contains:

            * 'header': The header text or a default title for the first section.
            * 'content': The content under the header.
            * 'tag_name': The name of the header tag (e.g., "h1", "h2").
        r   rT   zzUnable to import BeautifulSoup/PageElement,                     please install with `pip install                     bs4`.NrV   ru   r   r   h1r(   ro    )headerr   tag_name)rs   rU   rt   rN   r.   keysr|   r   r   r;   r[   rk   next_elementsr}   rK   r   r   ra   )r3   html_docrU   r   r   r   headerssectionsr   r   header_elementcurrent_headercurrent_header_tagsection_contentelementr   s                   r#   split_html_by_headersz)HTMLSectionSplitter.split_html_by_headersr  se   &	*) X}5t//446702-- 2' 23"7+ 	IAv!-8NAv!*%)"-/!/!4!4!:!:!<%3%8%8""$)77 4q53w<'Gwq1u~,Egs+#**73	4
 hh/557G"}"0#*$6%	4 M  	*C c")		*s   D* *	E3EEc                   	 ddl m} |j                  d      }|j	                  ddd      }|j
                  j                  }|j                  t        |      |      }|j                  | j                  |      }	|j                  |	|	      }
 |
|      }t        |      S # t        $ r}d}t        |      |d}~ww xY w)
a  Convert specific HTML tags to headers using an XSLT transformation.

        This method uses an XSLT file to transform the HTML content, converting
        certain tags into headers for easier parsing. If no XSLT path is provided,
        the HTML content is returned unchanged.

        Args:
            html_content (str): The HTML content to be transformed.

        Returns:
            str: The transformed HTML content as a string.
        r   )etreez>Unable to import lxml, please install with `pip install lxml`.NT)
no_networkF)resolve_entitiesr   load_dtd)access_control)lxmlr   rt   
HTMLParser	XMLParserXSLTAccessControlDENY_ALLparser   r   XSLTr   )r3   rR   r   r   r   html_parserxslt_parseractree	xslt_tree	transformresults               r#   convert_possible_tags_to_headerz3HTMLSectionSplitter.convert_possible_tags_to_header  s    	*" &&$&7oo"te & 
 $$--{{8L1;?KK<	JJyJ<	46{'  	*RCc")	*s   B! !	B=*B88B=c                    |j                         }| j                  |      }| j                  |      }|D cg c]:  }t        t	        d|d         | j
                  t        |d            |d   i      < c}S c c}w )zSplit HTML content from a file into a list of Document objects.

        Args:
            file: A file path or a file-like object containing HTML content.

        Returns:
            A list of split Document objects.
        r   r   r   r   )r   )getvaluer   r   r   r   r.   r   )r3   rP   file_contentr   sections        r#   r9   z(HTMLSectionSplitter.split_text_from_file  s     }};;LI--l; $

  UGI./,,S1D-EF I

 
	
 

s   ?A9)r.   r   rD   r   rr   r   )r   zIterable[Document]rr   r   r   rY   )r   	list[str]r   zOptional[list[dict[Any, Any]]]rr   r   )r   r   rr   zlist[dict[str, Optional[str]]])rR   r   rr   r   r   )r   r   r   r   r6   r   r<   r   r   r   r9   r!   r"   r#   r   r   2  sg    
2  
	(
69 MQ+I	$;z"H
r"   r   c                     e Zd ZdZdddddddddddddddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd	Zdd
Z	 	 	 	 	 	 ddZddZddZddZ	ddZ
ddZ	 	 	 	 	 	 	 	 ddZ	 	 	 	 	 	 	 	 ddZ	 	 	 	 	 	 ddZy)HTMLSemanticPreservingSplittera  Split HTML content preserving semantic structure.

    Splits HTML content by headers into generalized chunks, preserving semantic
    structure. If chunks exceed the maximum chunk size, it uses
    RecursiveCharacterTextSplitter for further splitting.

    The splitter preserves full HTML elements (e.g., <table>, <ul>) and converts
    links to Markdown-like links. It can also preserve images, videos, and audio
    elements by converting them into Markdown format. Note that some chunks may
    exceed the maximum size to maintain semantic integrity.

    .. versionadded: 0.3.5

    Example:
        .. code-block:: python

            from langchain_text_splitters.html import HTMLSemanticPreservingSplitter

            def custom_iframe_extractor(iframe_tag):
                ```
                Custom handler function to extract the 'src' attribute from an <iframe> tag.
                Converts the iframe to a Markdown-like link: [iframe:<src>](src).

                Args:
                    iframe_tag (bs4.element.Tag): The <iframe> tag to be processed.

                Returns:
                    str: A formatted string representing the iframe in Markdown-like format.
                ```
                iframe_src = iframe_tag.get('src', '')
                return f"[iframe:{iframe_src}]({iframe_src})"

            text_splitter = HTMLSemanticPreservingSplitter(
                headers_to_split_on=[("h1", "Header 1"), ("h2", "Header 2")],
                max_chunk_size=500,
                preserve_links=True,
                preserve_images=True,
                custom_handlers={"iframe": custom_iframe_extractor}
            )

    i  r   NFenglishT)max_chunk_sizechunk_overlap
separatorselements_to_preservepreserve_linkspreserve_imagespreserve_videospreserve_audiocustom_handlersstopword_removalstopword_langnormalize_textexternal_metadataallowlist_tagsdenylist_tagspreserve_parent_metadatakeep_separatorc          
        	 ddl m}m} || _        || _        t        |      | _        || _        |xs g | _	        || _
        || _        || _        |	| _        |
xs i | _        || _        || _        || _        |xs i | _        || _        || _        || _        |r-t-        t/        ||D cg c]  }|d   	 c}z               | _        || _        |r,|D cg c]  }||D cg c]  }|d   	 c}vr| c}}| _        |rt3        ||||      | _        nt3        |||      | _        | j                  rT	 ddl}|j9                  d       t/        |j:                  j<                  j?                  | j                               | _         yy# t
        $ r}d}t        |      |d}~ww xY wc c}w c c}w c c}}w # t
        $ r}d}t        |      |d}~ww xY w)	a  Initialize splitter.

        Args:
            headers_to_split_on: HTML headers (e.g., "h1", "h2")
                that define content sections.
            max_chunk_size: Maximum size for each chunk, with allowance for
                exceeding this limit to preserve semantics.
            chunk_overlap: Number of characters to overlap between chunks to ensure
                contextual continuity.
            separators: Delimiters used by RecursiveCharacterTextSplitter for
                further splitting.
            elements_to_preserve: HTML tags (e.g., <table>, <ul>) to remain
                intact during splitting.
            preserve_links: Converts <a> tags to Markdown links ([text](url)).
            preserve_images: Converts <img> tags to Markdown images (![alt](src)).
            preserve_videos: Converts <video> tags to Markdown
                video links (![video](src)).
            preserve_audio: Converts <audio> tags to Markdown
                audio links (![audio](src)).
            custom_handlers: Optional custom handlers for
                specific HTML tags, allowing tailored extraction or processing.
            stopword_removal: Optionally remove stopwords from the text.
            stopword_lang: The language of stopwords to remove.
            normalize_text: Optionally normalize text
                (e.g., lowercasing, removing punctuation).
            external_metadata: Additional metadata to attach to
                the Document objects.
            allowlist_tags: Only these tags will be retained in
                the HTML.
            denylist_tags: These tags will be removed from the HTML.
            preserve_parent_metadata: Whether to pass through parent document
                metadata to split documents when calling
                ``transform_documents/atransform_documents()``.
            keep_separator: Whether separators
                should be at the beginning of a chunk, at the end, or not at all.
        r   )rU   rh   zICould not import BeautifulSoup. Please install it with 'pip install bs4'.N)r   r   
chunk_sizer   )r   r   r   	stopwordszACould not import nltk. Please install it with 'pip install nltk'.)!rs   rU   rh   _BeautifulSoup_Tagrt   r-   _headers_to_split_on_max_chunk_size_elements_to_preserve_preserve_links_preserve_images_preserve_videos_preserve_audio_custom_handlers_stopword_removal_stopword_lang_normalize_text_external_metadata_allowlist_tags_preserve_parent_metadata_keep_separatorrN   set_denylist_tagsr   _recursive_splitternltkdownloadcorpusr   words
_stopwords)r3   r.   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rU   rh   errr   r   r4   r
  s                             r#   r6   z'HTMLSemanticPreservingSplitter.__init__  s   t
	,."/DDI %++>$?!-%9%?R"- / /- / 52!1+-"3"9r-)A&-#'N>Q%RFfQi%RRS$D  , )#7JKVvayKK #D
 'E%-)+	(D$ (F-)+(D$ !!	0k*"%dkk&;&;&A&A$BUBU&V"W "_  	,<  c"+	,0 &S L#2  0W  "#&C/	0sN   F 'F$
F.F))F.1AF4 	F!FF!)F.4	G=GGc                    | j                  |d      }| j                  |       | j                  r| j                  |       | j                  s| j
                  r| j                  |       | j                  |      S )a  Splits the provided HTML text into smaller chunks based on the configuration.

        Args:
            text (str): The HTML content to be split.

        Returns:
            List[Document]: A list of Document objects containing the split content.
        rV   )r   _process_mediar   _process_linksr  r  _filter_tags_process_html)r3   r;   r   s      r#   r<   z)HTMLSemanticPreservingSplitter.split_text  sk     ""47D!%4#6#6d#!!$''r"   c           	     
   g }|D ]v  }| j                  |j                        }| j                  r<|D cg c]1  }t        |j                  i |j                  |j                        3 }}|j                  |       x |S c c}w )z2Transform sequence of documents by splitting them.r_   )r<   r`   r  r   r   ry   )r3   r   rD   transformedr   splits	split_docs          r#   transform_documentsz2HTMLSemanticPreservingSplitter.transform_documents  s      
	'C__S%5%56F-- &,
 "	 %.%;%;!GCLL!GI4F4F!G  v&
	' s   6B c                j   | j                   rZ|j                  d      D ]F  }|j                  dd      }d| d| d}|j                  d      }||_        |j                  |       H | j                  rZ|j                  d      D ]F  }|j                  dd      }d	| d| d}|j                  d      }||_        |j                  |       H | j                  r[|j                  d
      D ]F  }	|	j                  dd      }
d|
 d|
 d}|j                  d      }||_        |	j                  |       H yy)zProcesses the media elements.

        Process elements in the HTML content by wrapping them in a <media-wrapper> tag
        and converting them to Markdown format.

        Args:
            soup (Any): Parsed HTML content using BeautifulSoup.
        imgsrcr   z![image:]()zmedia-wrappervideoz![video:audioz![audio:N)r   r|   rA   new_tagrm   replace_withr   r   )r3   r   img_tagimg_srcmarkdown_imgwrapper	video_tag	video_srcmarkdown_video	audio_tag	audio_srcmarkdown_audios               r#   r  z-HTMLSemanticPreservingSplitter._process_media  sE      ==/ .!++eR0!)'"WIQ?,,7!-$$W-.   !]]73 0	%MM%4	#+I;b1!E,,7!/&&w/0 !]]73 0	%MM%4	#+I;b1!E,,7!/&&w/0  r"   c                    |j                  d      D ]X  }|j                  dd      }|j                  d      }d| d| d}|j                  d	      }||_        |j                  |       Z y
)zProcesses the links in the HTML content.

        Args:
            soup (Any): Parsed HTML content using BeautifulSoup.
        ahrefr   TrZ   [r  r  zlink-wrapperN)r|   rA   get_textr!  rm   r"  )r3   r   a_taga_hrefa_textmarkdown_linkr&  s          r#   r  z-HTMLSemanticPreservingSplitter._process_links  ss     ]]3' 	.EYYvr*F^^$^/Fxr&3Mll>2G*GN}-	.r"   c                   | j                   r@|j                  d      D ]+  }|j                  | j                   vs|j                          - | j                  r1|j                  | j                        D ]  }|j                           yy)zFilters the HTML content based on the allowlist and denylist tags.

        Args:
            soup (Any): Parsed HTML content using BeautifulSoup.
        T)rk   N)r  r|   rk   	decomposer  )r3   r   r4   s      r#   r  z+HTMLSemanticPreservingSplitter._filter_tags  sy     }}$}/ $884#7#77MMO$ }}T%8%89    r"   c                P   | j                   rL|j                         }t        j                  dd|      }t        j                  dd|      j	                         }| j
                  r<dj                  |j                         D cg c]  }|| j                  vs| c}      }|S c c}w )zNormalizes the text by removing extra spaces and newlines.

        Args:
            text (str): The text to be normalized.

        Returns:
            str: The normalized text.
        z[^\w\s]r   \s+ro   )	r  lowerresubr[   r   ra   splitr  )r3   r;   words      r#   _normalize_and_clean_textz8HTMLSemanticPreservingSplitter._normalize_and_clean_text  s     ::<D66*b$/D66&#t,224D!!88"&**,N$$doo2MND  Os   B#B#c                
   	 g }i }g }i }d}d fd|j                  d      }	 	 	 	 	 	 	 	 	 	 	 	 	 	 d	 fd	 	||||||      \  }}}}}|r1|j                   j                  |dj                  |      |             |S )	a  Processes the HTML content using BeautifulSoup and splits it using headers.

        Args:
            soup (Any): Parsed HTML content using BeautifulSoup.

        Returns:
            List[Document]: A list of Document objects containing the split content.
        r   c                R   | j                   j                  v r j                  | j                      |       S d}| j                   6| j                  D ]&  } |      j                         }|r|r|dz  }||z  }( n| j                  r|| j                  z  }j                  |      S )a8  Recursively extracts and processes the text of an element.

            Applies custom handlers where applicable, and ensures correct spacing.

            Args:
                element (Any): The HTML element to process.

            Returns:
                str: The processed text of the element.
            r   ro   )rk   r   rw   r[   rm   r?  )r   r;   rj   
child_text_get_element_textr3   s       r#   rC  zGHTMLSemanticPreservingSplitter._process_html.<locals>._get_element_text  s     ||t444:t,,W\\:7CCD||'$-- 'E!25!9!?!?!AJ
J&D	'
 &11$77r"   Frn   c           	     `   | D ]  }|j                   j                         dv rl|j                  d      } ||||||      \  }}}}}dj                  |j                  dd            }|r"j	                  |      }|j                  |       |j                   j                  D 	cg c]  }	|	d   	 c}	v r|rQ|j                  j                  |dj                  |      |             |j                          |j                          |j                  d      }
t        j                        |j                      |
i}@|j                   j                  v r(d	| } |      ||<   |j                  |       |d
z  } |      }|s|j                  |        |||||fS c c}	w )N)htmlru   divmainFrD  ro   Trl   r   rZ   
PRESERVED_r(   )rk   r:  r|   ra   r?  r   r   ry   _create_documentsrb   r1  r/   r   )r   r   current_headerscurrent_contentpreserved_elementsplaceholder_countrq   rw   r   hr   placeholderrC  _process_elementr3   s               r#   rQ  zFHTMLSemanticPreservingSplitter._process_html.<locals>._process_element9  s      .899??$(GG#}}u}=H ) !''*)!''*) "hht}}DE}'RSG"&"@"@"I'..w799t/H/H I!1 II&!(( 22 / # 9 2 (--/*002"&--d-";KT667		BK'O YY$"<"<<$./@.A"BK6G6M&{3#**;7%*%/5G'..w7].8b "! 3 !Js   )F+ro   )r   r   rr   r   )r   z	list[Any]r   r   rK  r   rL  r   rM  r   rN  r)   rr   zEtuple[list[Document], dict[str, str], list[str], dict[str, str], int])r|   ry   rJ  ra   )
r3   r   r   rK  rL  rM  rN  elementsrC  rQ  s
   `       @@r#   r  z,HTMLSemanticPreservingSplitter._process_html  s     %'	*,%'-/!"	86 ==5=1>	>	%>	 ,>	 '	>	
 !/>	  #>	 S>	N 
	
 &&#HH_-& r"   c                   t        j                  dd|      j                         }i || j                  }t	        |      | j
                  k  r | j                  ||      }t        ||      gS | j                  |||      S )a  Creates Document objects from the provided headers, content, and elements.

        Args:
            headers (dict): The headers to attach as metadata to the Document.
            content (str): The content of the Document.
            preserved_elements (dict): Preserved elements to be reinserted
            into the content.

        Returns:
            List[Document]: A list of Document objects.
        r9  ro   r_   )	r;  r<  r[   r  r}   r   _reinsert_preserved_elementsr   _further_split_chunk)r3   r   r   rM  r   r`   s         r#   rJ  z0HTMLSemanticPreservingSplitter._create_documents  s     &&g.4469g9!8!89w<4///<<+L ,JKK(((<NOOr"   c                    | j                   j                  |      }g }|D ]O  }| j                  ||      }|j                         s&|j	                  t        |j                         |             Q |S )a  Further splits the content into smaller chunks.

        Args:
            content (str): The content to be split.
            metadata (dict): Metadata to attach to each chunk.
            preserved_elements (dict): Preserved elements
            to be reinserted into each chunk.

        Returns:
            List[Document]: A list of Document objects containing the split content.
        r_   )r	  r<   rT  r[   r   r   )r3   r   r   rM  r  r   r=  split_with_preserveds           r#   rU  z3HTMLSemanticPreservingSplitter._further_split_chunk  s}     ))44W= 
	E#'#D#D)$  $))+%9%?%?%A!)
	 r"   c                v    |j                         D ]%  \  }}|j                  ||j                               }' |S )a`  Reinserts preserved elements into the content into their original positions.

        Args:
            content (str): The content where placeholders need to be replaced.
            preserved_elements (dict): Preserved elements to be reinserted.

        Returns:
            str: The content with placeholders replaced by preserved elements.
        )rB   replacer[   )r3   r   rM  rP  preserved_contents        r#   rT  z;HTMLSemanticPreservingSplitter._reinsert_preserved_elements  sD     /A.F.F.H 	N*K*ook3D3J3J3LMG	Nr"   )&r.   r   r   r)   r   r)   r   Optional[list[str]]r   r[  r   r   r   r   r   r   r   r   r   z)Optional[dict[str, Callable[[Any], str]]]r   r   r   r   r   r   r   zOptional[dict[str, str]]r   r[  r   r[  r   r   r   z$Union[bool, Literal['start', 'end']]rr   r   r   )r   zSequence[Document]rD   r   rr   r   )r   r   rr   r   )r;   r   rr   r   )r   r   rr   r   )r   r   r   r   rM  r   rr   r   )r   r   r   zdict[Any, Any]rM  r   rr   r   )r   r   rM  r   rr   r   )r   r   r   r   r6   r<   r  r  r  r  r?  r  rJ  rU  rT  r!   r"   r#   r   r     s   (\ #*.48$ % %$EI!&&$6:.2-1).?C)x02x0 	x0
 x0 (x0 2x0 x0 x0 x0 x0 Cx0 x0 x0 x0  4!x0" ,#x0$ +%x0& #''x0( =)x0* 
+x0t(*+7:	$0B. *FPP%P03PIWP	P2&4JX	>0>	r"   r   )!
__future__r   r   r   r;  ior   typingr   r   r   r   r	   r
   r   r   r@   langchain_core._apir   langchain_core.documentsr   r   "langchain_text_splitters.characterr   collections.abcr   r   rx   r   r   r%   r   r   r!   r"   r#   <module>rc     s    "   	 	 	 	  $ F M2') H HVx
 x
v m%< m mr"   