
    Ng"              	           d dl Z d dlZd dlmZmZmZmZmZmZm	Z	m
Z
mZ d dlmZ d dlmZ d dlmZ dedefdZd	ed
edefdZdededee	e         ddf         fdZdedeeef         fdZ G d de          ZdS )    N)	AnyCallableDict	GeneratorIterableIteratorListOptionalTuple)urlparse)Document)WebBaseLoadercontentreturnc                 D    t          |                                           S N)strget_text)r   s    h/var/www/html/ai-engine/env/lib/python3.11/site-packages/langchain_community/document_loaders/sitemap.py_default_parsing_functionr      s    w!!"""    meta_contentc                     d| d         i| S )Nsourceloc )r   r   s     r   _default_meta_functionr      s    d5k*T**r   iterablesizec              #      K   t          |           }t          t          j        ||                    x}r*|V  t          t          j        ||                    x}(d S d S r   )iterlist	itertoolsislice)r   r    ititems       r   _batch_blockr(      st      	hBy'D1122
2$ 


 y'D1122
2$     r   urlc                 <    t          |           }|j        |j        fS )zExtract the scheme + domain from a given URL.

    Args:
        url (str): The input URL.

    Returns:
        return a 2-tuple of scheme and domain
    )r   schemenetloc)r)   
parsed_uris     r   _extract_scheme_and_domainr.   #   s      #Jj///r   c                        e Zd ZdZ	 	 	 	 	 	 	 	 	 ddedeee                  d	ee         d
ee         dedee         de	de	de	dede
f fdZddde
dedee         fdZdee         fdZ xZS )SitemapLoaderaH  Load a sitemap and its URLs.

    **Security Note**: This loader can be used to load all URLs specified in a sitemap.
        If a malicious actor gets access to the sitemap, they could force
        the server to load URLs from other domains by modifying the sitemap.
        This could lead to server-side request forgery (SSRF) attacks; e.g.,
        with the attacker forcing the server to load URLs from internal
        service endpoints that are not publicly accessible. While the attacker
        may not immediately gain access to this data, this data could leak
        into downstream systems (e.g., data loader is used to load data for indexing).

        This loader is a crawler and web crawlers should generally NOT be deployed
        with network access to any internal servers.

        Control access to who can submit crawling requests and what network access
        the crawler has.

        By default, the loader will only load URLs from the same domain as the sitemap
        if the site map is not a local file. This can be disabled by setting
        restrict_to_same_domain to False (not recommended).

        If the site map is a local file, no such risk mitigation is applied by default.

        Use the filter URLs argument to limit which URLs can be loaded.

        See https://python.langchain.com/docs/security
    Nr   FT
   web_pathfilter_urlsparsing_function	blocksizeblocknummeta_functionis_localcontinue_on_failurerestrict_to_same_domain	max_depthkwargsc                 x   ||dk     rt          d          |dk     rt          d          	 ddl}n# t          $ r t          d          w xY w t                      j        dd|gi| || _        |	| _        |pt          | _        |pt          | _
        || _        || _        || _        || _        |
| _        dS )	a  Initialize with webpage path and optional filter URLs.

        Args:
            web_path: url of the sitemap. can also be a local path
            filter_urls: a list of regexes. If specified, only
                URLS that match one of the filter URLs will be loaded.
                *WARNING* The filter URLs are interpreted as regular expressions.
                Remember to escape special characters if you do not want them to be
                interpreted as regular expression syntax. For example, `.` appears
                frequently in URLs and should be escaped if you want to match a literal
                `.` rather than any character.
                restrict_to_same_domain takes precedence over filter_urls when
                restrict_to_same_domain is True and the sitemap is not a local file.
            parsing_function: Function to parse bs4.Soup output
            blocksize: number of sitemap locations per block
            blocknum: the number of the block that should be loaded - zero indexed.
                Default: 0
            meta_function: Function to parse bs4.Soup output for metadata
                remember when setting this method to also copy metadata["loc"]
                to metadata["source"] if you are using this field
            is_local: whether the sitemap is a local file. Default: False
            continue_on_failure: whether to continue loading the sitemap if an error
                occurs loading a url, emitting a warning instead of raising an
                exception. Setting this to True makes the loader more robust, but also
                may result in missing data. Default: False
            restrict_to_same_domain: whether to restrict loading to URLs to the same
                domain as the sitemap. Attention: This is only applied if the sitemap
                is not a local file!
            max_depth: maximum depth to follow sitemap links. Default: 10
        N   z&Sitemap blocksize should be at least 1r   z(Sitemap blocknum can not be lower then 0zAlxml package not found, please install it with `pip install lxml`	web_pathsr   )
ValueErrorlxmlImportErrorsuper__init__allow_url_patternsr:   r   r4   r   r7   r5   r6   r8   r9   r;   )selfr2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   rA   	__class__s                r   rD   zSitemapLoader.__init__M   s    Z  Y]]EFFFa<<GHHH	KKKK 	 	 	S  	
 	88H:8888 #.'>$ 0 M4M*D.D"  #6 "s	   4 AdepthsouprI   r   c                  	 || j         k    rg S g }|                    d          D ]		                    d          }|s|j                                        | j        r-| j        s&t                    t          | j                  k    rg| j	        r!t          fd| j	        D                       s|                    	fddD                        |                    d          D ]i}|                    d          }|s|                     |j        gd          d         }|                    |                     ||d	z   
                     j|S )zParse sitemap xml and load into a list of dicts.

        Args:
            soup: BeautifulSoup object.
            depth: current depth of the sitemap. Default: 0

        Returns:
            List of dicts.
        r)   r   c              3   B   K   | ]}t          j        |          V  d S r   )rematch).0regexp_patternloc_texts     r   	<genexpr>z.SitemapLoader.parse_sitemap.<locals>.<genexpr>   sC       3 3" 223 3 3 3 3 3r   c                 N    i | ]!}                     |          x|j        "S r   )findtext)rO   tagpropr)   s     r   
<dictcomp>z/SitemapLoader.parse_sitemap.<locals>.<dictcomp>   sB        #-  r   )r   lastmod
changefreqprioritysitemapxmlr   r>   rH   )r;   find_allrT   rU   stripr:   r8   r.   r2   rE   anyappend
scrape_allextendparse_sitemap)
rF   rJ   rI   elsr   r\   
soup_childrQ   rW   r)   s
          @@@r   rd   zSitemapLoader.parse_sitemap   s    DN""I=='' 	 	C((5//C  x~~''H+ DM -h77;UM< <   & s 3 3 3 3&*&=3 3 3 0 0  JJ    K      }}Y// 	H 	HG,,u%%C #(U;;A>JJJt))*EAI)FFGGGG
r   c              #     K   | j         rN	 ddl}n# t          $ r t          d          w xY wt          | j                  }|                    |d          }n|                     | j        d          }|                     |          }| j        [t          t          || j                            }t          |          }|dz
  | j        k     rt          d          || j                 }|                     d |D                       }t          |          D ]E\  }}	t!          |                     |	          |                     ||         |	          	          V  FdS )
zLoad sitemap.r   NzUbeautifulsoup4 package not found, please install it with `pip install beautifulsoup4`r]   )parserr>   zBSelected sitemap does not contain enough blocks for given blocknumc                 J    g | ] }d |v |d                                           !S )r   )r_   )rO   els     r   
<listcomp>z+SitemapLoader.lazy_load.<locals>.<listcomp>   s+    "R"R"Rerkk2e9??#4#4kkkr   )page_contentmetadata)r8   bs4rB   openr2   BeautifulSoup_scraperd   r5   r#   r(   lenr6   r@   rb   	enumerater   r4   r7   )
rF   rn   fprJ   re   elblocks
blockcountresultsiresults
             r   	lazy_loadzSitemapLoader.lazy_load   s     = 	=



   !9  
 dm$$B$$R//DD<<e<<<D  &&>%Ldn==>>HXJA~-- X   t}-//"R"Rs"R"R"RSS"7++ 	 	IAv!226::++CFF;;      	 	s    *)	NNNr   NFFTr1   )__name__
__module____qualname____doc__r   r
   r	   r   intboolr   rD   dictrd   r   r   rz   __classcell__)rG   s   @r   r0   r0   0   s\        > ,0/3#',0$)(,H# H#H# d3i(H# #8,	H#
 C=H# H#  )H# H# "H# "&H# H# H# H# H# H# H# H#T 89 2 2 2# 2 2T$Z 2 2 2 2h!8H- ! ! ! ! ! ! ! !r   r0   )r$   rM   typingr   r   r   r   r   r   r	   r
   r   urllib.parser   langchain_core.documentsr   -langchain_community.document_loaders.web_baser   r   r   r   r   r   r(   r.   r0   r   r   r   <module>r      s       				
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 " ! ! ! ! ! - - - - - - G G G G G G#s #s # # # #+ + + + + + +8 3 9T$Zt=S3T    
0C 
0E#s(O 
0 
0 
0 
0| | | | |M | | | | |r   