
    g                     ,   d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlm	Z	m
Z
 d dlmZmZmZmZ d dlmZ d dlmZmZmZmZmZmZmZ d dl d dlmZmZmZ  ed      d	        Zd
 Zd3dZ d4dZ!d5dZ"d4dZ# G d de	      Z$d6dZ%d Z&e'dfdZ(e'ddfdZ)d7dZ*e'ddfdZ+e'ddfdZ,e'ddddfdZ-e'ddddfdZ.d Z/e'fdZ0e'fdZ1d Z2d  Z3d! Z4d8d"Z5d# Z6d$ Z7d% Z8d& Z9	 	 	 	 d9d'Z:d( Z;d) Z<d* Z=	 d:d+Z>d, Z?d;d-Z@d<d.ZAd=d/ZBd0 ZCd1 ZDd8d2ZEy)>    N)defaultdictdeque)chaincombinationsislicetee)pprint)HTTPPasswordMgrWithDefaultRealmProxyBasicAuthHandlerProxyDigestAuthHandlerProxyHandlerbuild_opener
getproxiesinstall_opener)*)
deprecatedraise_unorderable_typesslice_boundszUse help(obj) instead.c                 B   t        |        t        | t              s| j                  } t	        | j
                   d       t        t        j                  |       j                               D ]  \  }}|j                  d      rt        |dd      r'	 t        t        j                  |            }|j                  d      j!                  d      j#                  d      }t        j$                  | |      }t        |t&        t(        f      rd	| }n |r|d
   dk(  rd| }|j+                  d
       t	        t-        j.                  | ddj1                  |       dddt3        |      dz   z                y # t        $ r}dt        |      v rY d }~, d }~ww xY w)Nz# supports the following operations:___deprecated__Fbuiltin(), zcls.r   selfzself.z  -     )initial_indentsubsequent_indent)str
isinstancetype	__class__print__name__sortedpydoc
allmethodsitems
startswithgetattrinspect	signature
ValueErrorlstriprstripsplitgetattr_staticclassmethodstaticmethodpoptextwrapfilljoinlen)objnamemethodsigeargsmeths          >/var/www/openai/venv/lib/python3.12/site-packages/nltk/util.pyusagerC   %   si   Hc4 mm	S\\N=
>?u//4::<=f??36+U3	g''/0C zz#%%c*006%%c40d[,78$=Dd1g'4&>DHHQKMM&$))D/*!,%"%TQ"7	
- >  	CF"	s   E<<	FFFFc                  N    ddl } | j                  j                  j                  dv S )a  
    Return True if this function is run within idle.  Tkinter
    programs that are run in idle should never call ``Tk.mainloop``; so
    this function should be used to gate all calls to ``Tk.mainloop``.

    :warning: This function works by checking ``sys.stdin``.  If the
        user has modified ``sys.stdin``, then it may return incorrect
        results.
    :rtype: bool
    r   N)PyShellRPCProxy)sysstdinr$   r&   )rG   s    rB   in_idlerI   Q   s#     99''+BBB    c           	      B    t        t        t        | ||                   y)z
    Pretty print a sequence of data items

    :param data: the data stream to print
    :type data: sequence or iter
    :param start: the start position
    :type start: int
    :param end: the end position
    :type end: int
    N)r	   listr   )datastartends      rB   prrP   f   s     4tUC()*rJ   c                 b    t        dj                  t        j                  | |                   y)z
    Pretty print a string, breaking lines on whitespace

    :param s: the string to print, consisting of words and spaces
    :type s: str
    :param width: the display width
    :type width: int
    
widthN)r%   r9   r7   wrap)srT   s     rB   print_stringrW   t   s      
$))HMM!51
23rJ   c                 l    dj                  t        j                  |j                  |       |            S )a#  
    Pretty print a list of text tokens, breaking lines on whitespace

    :param tokens: the tokens to print
    :type tokens: list
    :param separator: the string to use to separate tokens
    :type separator: str
    :param width: the display width (default=70)
    :type width: int
    rR   rS   )r9   r7   rU   )tokens	separatorrT   s      rB   	tokenwrapr[      s'     99X]]9>>&#9GHHrJ   c                     d}d}d}t        |      }t        |       }||k  rM||k  rH|dk  r| |dz       }||z   }n
| |   }||z   }|dz  }t        j                  |      s|dz  }||k  r||k  rH|S )a  
    Cut off and return a given width of a string

    Return the same as s[:width] if width >= 0 or s[-width:] if
    width < 0, as long as s has no unicode combining characters.
    If it has combining characters make sure the returned string's
    visible width matches the called-for width.

    :param s: the string to cut
    :type s: str
    :param width: the display_width
    :type width: int
    r       )absr:   unicodedata	combining)rV   rT   chars_sofarwidth_sofarresult	abs_width	max_charschars           rB   
cut_stringrh      s     KKFE
IAI
	
!kI&=19{Q'(DF]F[>Dd]Fq$$T*1K 	
!kI&= MrJ   c                       e Zd Zd Zy)Indexc                 t    t        j                  | t               |D ]  \  }}| |   j                  |        y N)r   __init__rL   append)r   pairskeyvalues       rB   rm   zIndex.__init__   s2    T4(JCIU#  rJ   N)r&   
__module____qualname__rm    rJ   rB   rj   rj      s    $rJ   rj   c                     t        t        j                  | t        j                        j	                  |dz   |z   |j                                      y)a3  
    Return a string with markers surrounding the matched substrings.
    Search str for substrings matching ``regexp`` and wrap the matches
    with braces.  This is convenient for learning about regular expressions.

    :param regexp: The regular expression.
    :type regexp: str
    :param string: The string being matched.
    :type string: str
    :param left: The left delimiter (printed before the matched substring)
    :type left: str
    :param right: The right delimiter (printed after the matched substring)
    :type right: str
    :rtype: str
    z\g<0>N)r%   recompileMsubr1   )regexpstringleftrights       rB   re_showr~      s7      
"**VRTT
"
&
&th'>
PQrJ   c                     t        | d      r| j                         S t        | t              r%t	        |       5 }|j                         cd d d        S t        d      # 1 sw Y   y xY w)Nreadz2Must be called with a filename or file-like object)hasattrr   r"   r!   openr/   )finfiles     rB   
filestringr      sP    q&vvx	As	!W;;= W MNN Ws   AA&c              #      K   t        | dfg      }|rA|j                         \  }| |k7  r!	 |j                  fd ||      D               |r@yy# t        $ r Y w xY ww)zTraverse the nodes of a tree in breadth-first order.
    (No check for cycles.)
    The first argument should be the tree root;
    children should be a function taking as argument a tree node
    and returning an iterator of the node's children.
    r   c              3   ,   K   | ]  }|d z   f  yw)r^   Nrt   ).0cdepths     rB   	<genexpr>z breadth_first.<locals>.<genexpr>   s     D^a^^s   N)r   popleftextend	TypeError)treechildrenmaxdepthqueuenoder   s        @rB   breadth_firstr      sk      D!9+E
mmoe
HDXd^DD   s.   -A% A A%A%	A"A%!A""A%Fc              #     K   t               }t               }t        | dfg      }|r|j                         \  }}|j                  |       ||k7  rj	  ||      D ]]  }	|	|vr|j	                  |	|dz   f       n"|r t        j                  d|	 d|dz    d       ||	f}
|
|vsI|
 |j                  |
       _ 	 |ryy# t        $ r Y w xY ww)a  
    :param tree: the tree root
    :param children: a function taking as argument a tree node
    :param maxdepth: to limit the search depth
    :param verbose: to print warnings when cycles are discarded

    Yield the edges of a graph in breadth-first order,
    discarding eventual cycles.
    The first argument should be the start node;
    children should be a function taking as argument a graph node
    and returning an iterator of the node's children.

    >>> from nltk.util import edge_closure
    >>> print(list(edge_closure('A', lambda node:{'A':['B','C'], 'B':'C', 'C':'B'}[node])))
    [('A', 'B'), ('A', 'C'), ('B', 'C'), ('C', 'B')]
    r   r^   zDiscarded redundant search for z
 at depth    
stacklevelN)setr   r   addrn   warningswarnr   )r   r   r   verbose	traversededgesr   r   r   childedges              rB   edge_closurer     s     " IEED!9+E
mmoedH%d^EI-eUQY%78"$MM"A%
SX[\S\R] ^+, !%=D5("
		$ , $  s7   ACAB? "B? 9C=C?	CC
CCc           	      X   |s
t               }|s
t               }d}|j                         D ]  }||d    d|d    dz  } | D ]_  }|j                         D ]8  }t        d      D ](  }|d   t        ||         v s|d||    d|d    d	z  }* : |d|d    d
|d    dz  }a |dz  }|S )a  
    :param edges: the set (or list) of edges of a directed graph.
    :param shapes: dictionary of strings that trigger a specified shape.
    :param attr: dictionary with global graph attributes
    :return: a representation of 'edges' as a string in the DOT graph language.

    Returns dot_string: a representation of 'edges' as a string in the DOT
    graph language, which can be converted to an image by the 'dot' program
    from the Graphviz package, or nltk.parse.dependencygraph.dot2img(dot_string).

    >>> import nltk
    >>> from nltk.util import edges2dot
    >>> print(edges2dot([('A', 'B'), ('A', 'C'), ('B', 'C'), ('C', 'B')]))
    digraph G {
    "A" -> "B";
    "A" -> "C";
    "B" -> "C";
    "C" -> "B";
    }
    <BLANKLINE>
    zdigraph G {
r   z = r^   z;
r   "z" [shape = z];
z" -> "z";
z}
)dictr*   rangerepr)r   shapesattr
dot_stringpairr   shaper   s           rB   	edges2dotr   -  s    , v J

a	T!WIS11
  \\^Ea8tDJ//Ad4j\U1XJd"KKJ ! $ 	$q'&a	66
  %JrJ   c                 <     t        t          fd      ||      S )a'  
    :param tree: the tree root
    :param children: a function taking as argument a tree node
    :param shapes: dictionary of strings that trigger a specified shape.
    :param attr: dictionary with global graph attributes

        Build a Minimum Spanning Tree (MST) of an unweighted graph,
    by traversing the nodes of a tree in breadth-first order,
    discarding eventual cycles.

    Return a representation of this MST as a string in the DOT graph language,
    which can be converted to an image by the 'dot' program from the Graphviz
    package, or nltk.parse.dependencygraph.dot2img(dot_string).

    The first argument should be the tree root;
    children should be a function taking as argument a tree node
    and returning an iterator of the node's children.

    >>> import nltk
    >>> wn=nltk.corpus.wordnet
    >>> from nltk.util import unweighted_minimum_spanning_digraph as umsd
    >>> print(umsd(wn.synset('bound.a.01'), lambda s:sorted(s.also_sees())))
    digraph G {
    "Synset('bound.a.01')" -> "Synset('unfree.a.02')";
    "Synset('unfree.a.02')" -> "Synset('confined.a.02')";
    "Synset('unfree.a.02')" -> "Synset('dependent.a.01')";
    "Synset('unfree.a.02')" -> "Synset('restricted.a.01')";
    "Synset('restricted.a.01')" -> "Synset('classified.a.02')";
    }
    <BLANKLINE>
    c                 "    t              |    S rl   ) unweighted_minimum_spanning_dict)r   r   r   s    rB   <lambda>z5unweighted_minimum_spanning_digraph.<locals>.<lambda>z  s    ?hOPTUrJ   )r   r   )r   r   r   r   s   ``  rB   #unweighted_minimum_spanning_digraphr   X  s)    @ U	
 	 rJ   c              #   x  K   t               }t        | dfg      }|r|j                         \  }}||v r| |j                  |       ||k7  rW	  ||      D ]J  }||vr|j	                  ||dz   f       |s!t        j                  dj                  ||dz         d       L 	 |ryy# t        $ r Y w xY ww)a@  
    :param tree: the tree root
    :param children: a function taking as argument a tree node
    :param maxdepth: to limit the search depth
    :param verbose: to print warnings when cycles are discarded
    :return: the tree in breadth-first order

        Adapted from breadth_first() above, to discard cycles.
    Traverse the nodes of a tree in breadth-first order,
    discarding eventual cycles.

    The first argument should be the tree root;
    children should be a function taking as argument a tree node
    and returning an iterator of the node's children.
    r   r^   -Discarded redundant search for {} at depth {}r   r   N)	r   r   r   r   rn   r   r   formatr   )	r   r   r   r   r   r   r   r   r   s	            rB   acyclic_breadth_firstr     s       ID!9+E
mmoe9
dH%d^EI-eUQY%78  KRR %uqy ()		 , $  s6   AB:(B+ 9,B+ %B:)B:+	B74B:6B77B:c           	      N   || h}| g}|dk7  r	  ||       D ]p  }||vr(|j                  |       |t        |||dz
  ||      gz  }/|r*t        j                  dj	                  ||dz
        d       |s^|d| d|dz
   d| dgz  }r 	 |S |r||gz  }|S # t
        $ r Y |S w xY w)	a+  
    :param tree: the tree root
    :param children: a function taking as argument a tree node
    :param depth: the maximum depth of the search
    :param cut_mark: the mark to add when cycles are truncated
    :param traversed: the set of traversed nodes
    :param verbose: to print warnings when cycles are discarded
    :return: the tree in depth-first order

    Traverse the nodes of a tree in depth-first order,
    discarding eventual cycles within any branch,
    adding cut_mark (when specified) if cycles were truncated.
    The first argument should be the tree root;
    children should be a function taking as argument a tree node
    and returning an iterator of the node's children.

    Catches all cycles:

    >>> import nltk
    >>> from nltk.util import acyclic_depth_first as acyclic_tree
    >>> wn=nltk.corpus.wordnet
    >>> from pprint import pprint
    >>> pprint(acyclic_tree(wn.synset('dog.n.01'), lambda s:sorted(s.hypernyms()),cut_mark='...'))
    [Synset('dog.n.01'),
     [Synset('canine.n.02'),
      [Synset('carnivore.n.01'),
       [Synset('placental.n.01'),
        [Synset('mammal.n.01'),
         [Synset('vertebrate.n.01'),
          [Synset('chordate.n.01'),
           [Synset('animal.n.01'),
            [Synset('organism.n.01'),
             [Synset('living_thing.n.01'),
              [Synset('whole.n.02'),
               [Synset('object.n.01'),
                [Synset('physical_entity.n.01'),
                 [Synset('entity.n.01')]]]]]]]]]]]]],
     [Synset('domestic_animal.n.01'), "Cycle(Synset('animal.n.01'),-3,...)"]]
    r   r^   r      r   Cycle(,r   )r   acyclic_depth_firstr   r   r   r   r   r   r   cut_markr   r   out_treer   s           rB   r   r     s    T F	vHz	!$	)MM%(+!8UQY)! H  KRR %uqy ()	   veWAeai[(1%M$NN% (. O 
XJO	  	 O		s   A%B 5B 	B$#B$c                 L   || h}| g}|dk7  r~	  ||       D ]o  }||vr'|t        |||dz
  ||j                  |h            gz  }.|r*t        j                  dj	                  ||dz
        d       |s]|d| d|dz
   d| dgz  }q 	 |S |r||gz  }|S # t
        $ r Y |S w xY w)	a  
    :param tree: the tree root
    :param children: a function taking as argument a tree node
    :param depth: the maximum depth of the search
    :param cut_mark: the mark to add when cycles are truncated
    :param traversed: the set of traversed nodes
    :param verbose: to print warnings when cycles are discarded
    :return: the tree in depth-first order

        Adapted from acyclic_depth_first() above, to
    traverse the nodes of a tree in depth-first order,
    discarding eventual cycles within the same branch,
    but keep duplicate paths in different branches.
    Add cut_mark (when defined) if cycles were truncated.

    The first argument should be the tree root;
    children should be a function taking as argument a tree node
    and returning an iterator of the node's children.

    Catches only only cycles within the same branch,
    but keeping cycles from different branches:

    >>> import nltk
    >>> from nltk.util import acyclic_branches_depth_first as tree
    >>> wn=nltk.corpus.wordnet
    >>> from pprint import pprint
    >>> pprint(tree(wn.synset('certified.a.01'), lambda s:sorted(s.also_sees()), cut_mark='...', depth=4))
    [Synset('certified.a.01'),
     [Synset('authorized.a.01'),
      [Synset('lawful.a.01'),
       [Synset('legal.a.01'),
        "Cycle(Synset('lawful.a.01'),0,...)",
        [Synset('legitimate.a.01'), '...']],
       [Synset('straight.a.06'),
        [Synset('honest.a.01'), '...'],
        "Cycle(Synset('lawful.a.01'),0,...)"]],
      [Synset('legitimate.a.01'),
       "Cycle(Synset('authorized.a.01'),1,...)",
       [Synset('legal.a.01'),
        [Synset('lawful.a.01'), '...'],
        "Cycle(Synset('legitimate.a.01'),0,...)"],
       [Synset('valid.a.01'),
        "Cycle(Synset('legitimate.a.01'),0,...)",
        [Synset('reasonable.a.01'), '...']]],
      [Synset('official.a.01'), "Cycle(Synset('authorized.a.01'),1,...)"]],
     [Synset('documented.a.01')]]
    r   r^   r   r   r   r   r   r   )acyclic_branches_depth_firstunionr   r   r   r   r   s           rB   r   r     s    d F	vHz	!$	)4!$!AI$%OOUG4! H  KRR %uqy ()	   veWAeai[(1%M$NN+ (4 O 
XJO	  	 O		s   A$B 4B 	B#"B#c                 N    | g||    D cg c]  }t        ||       c}z   S c c}w )a  
    :param node: the root node
    :param dic: the dictionary of children

    Convert acyclic dictionary 'dic', where the keys are nodes, and the
    values are lists of children, to output tree suitable for pprint(),
    starting at root 'node', with subtrees as nested lists.)acyclic_dic2tree)r   dicr   s      rB   r   r   K  s/     6s4yIye%eS1yIIIIs   "c                 *   t               }t        | g      }| h}i }|ru|j                         }g ||<   ||vrY|j                  |        ||      D ]=  }||vs||   j	                  |       |j	                  |       |j                  |       ? |ru|S )aH  
    :param tree: the tree root
    :param children: a function taking as argument a tree node

            Output a dictionary representing a Minimum Spanning Tree (MST)
    of an unweighted graph, by traversing the nodes of a tree in
    breadth-first order, discarding eventual cycles.

    The first argument should be the tree root;
    children should be a function taking as argument a tree node
    and returning an iterator of the node's children.

    >>> import nltk
    >>> from nltk.corpus import wordnet as wn
    >>> from nltk.util import unweighted_minimum_spanning_dict as umsd
    >>> from pprint import pprint
    >>> pprint(umsd(wn.synset('bound.a.01'), lambda s:sorted(s.also_sees())))
    {Synset('bound.a.01'): [Synset('unfree.a.02')],
     Synset('classified.a.02'): [],
     Synset('confined.a.02'): [],
     Synset('dependent.a.01'): [],
     Synset('restricted.a.01'): [Synset('classified.a.02')],
     Synset('unfree.a.02'): [Synset('confined.a.02'),
                             Synset('dependent.a.01'),
                             Synset('restricted.a.01')]}

    )r   r   r   r   rn   )r   r   r   r   agendamstdicr   r   s           rB   r   r   V  s    8 I4&MEVFF
}}ty MM$!$&4L''.LL'JJu%	 (  MrJ   c                 .    t        | t        | |            S )aS  
    :param tree: the tree root
    :param children: a function taking as argument a tree node

       Output a Minimum Spanning Tree (MST) of an unweighted graph,
    by traversing the nodes of a tree in breadth-first order,
    discarding eventual cycles.

    The first argument should be the tree root;
    children should be a function taking as argument a tree node
    and returning an iterator of the node's children.

    >>> import nltk
    >>> from nltk.util import unweighted_minimum_spanning_tree as mst
    >>> wn=nltk.corpus.wordnet
    >>> from pprint import pprint
    >>> pprint(mst(wn.synset('bound.a.01'), lambda s:sorted(s.also_sees())))
    [Synset('bound.a.01'),
     [Synset('unfree.a.02'),
      [Synset('confined.a.02')],
      [Synset('dependent.a.01')],
      [Synset('restricted.a.01'), [Synset('classified.a.02')]]]]
    )r   r   )r   r   s     rB    unweighted_minimum_spanning_treer     s    0 D"B4"RSSrJ   c                    d}dg}	 |j                  t        j                  t        j                               	 |j                  t        j
                         d          	 |j                  t        j                         d          |j                  d       |D ]  }|s	 t        | |      }|} n |s7t        ddj                  |D cg c]  }|st        |       c}      z        |fS # t        $ r Y w xY w# t        t        f$ r Y w xY w# t        t        f$ r Y w xY w# t        t        f$ r Y w xY wc c}w )at  
    Given a byte string, attempt to decode it.
    Tries the standard 'UTF8' and 'latin-1' encodings,
    Plus several gathered from locale information.

    The calling program *must* first call::

        locale.setlocale(locale.LC_ALL, '')

    If successful it returns ``(decoded_unicode, successful_encoding)``.
    If unsuccessful it raises a ``UnicodeError``.
    Nzutf-8r^   zlatin-1z?Unable to decode input data. Tried the following encodings: %s.r   )rn   localenl_langinfoCODESETAttributeError	getlocale
IndexErrorgetdefaultlocaler!   UnicodeErrorLookupErrorr9   r   )rM   successful_encoding	encodingsencdecodeds        rB   guess_encodingr     s`    	I++FNN;<))+A./002156
 Y 	$nG"%
   1iii?is3ci?@A
 	
 ,--C   J'  J'  k* 		 @sR   2C/ &C> !&D !D(	D=D=/	C;:C;>DDD%$D%(D:9D:c                 n    t               }| D cg c]  }||vs|j                  |      r| c}S c c}w rl   )r   r   )xsseenxs      rB   unique_listr     s1    5D?r!Qd]488A;Ar???s   	222c                     t        t              }| D ]8  }t        | |   d      r| |   D ]  }||   j                  |        1||| |   <   : |S )N__iter__)r   rL   r   rn   )dinverted_dictrp   terms       rB   invert_dictr     s]    %M1S6:&#d#**3/  %(M!C&!  rJ   c                    |rd }nd }| D ci c]  }|| |   j                          }}| D ci c]  }| ||       }}| D ]n  }||   }||   }|s|j                         }	|j                  |	       ||j                  |	 ||	            z  }||j	                  |	 ||	            z  }||z  }|r_p |S c c}w c c}w )a  
    Calculate the transitive closure of a directed graph,
    optionally the reflexive transitive closure.

    The algorithm is a slight modification of the "Marking Algorithm" of
    Ioannidis & Ramakrishnan (1998) "Efficient Transitive Closure Algorithms".

    :param graph: the initial graph, represented as a dictionary of sets
    :type graph: dict(set)
    :param reflexive: if set, also make the closure reflexive
    :type reflexive: bool
    :rtype: dict(set)
    c                     | hS rl   rt   ks    rB   r   z$transitive_closure.<locals>.<lambda>  s    aSrJ   c                     t               S rl   )r   r   s    rB   r   z$transitive_closure.<locals>.<lambda>  s    SUrJ   )copyr6   r   
setdefaultget)
graph	reflexivebase_setr   agenda_graphclosure_graphir   closurejs
             rB   transitive_closurer     s      "0561AuQx}}&L6-23UQ^UM3a"

AKKN}//8A;??Gl&&q(1+66FgF    73s
   B6B;c                 ~    i }| D ]5  }| |   D ]+  }|j                  |t                     j                  |       - 7 |S )z
    Inverts a directed graph.

    :param graph: the graph, represented as a dictionary of sets
    :type graph: dict(set)
    :return: the inverted graph
    :rtype: dict(set)
    )r   r   r   )r   invertedrp   rq   s       rB   invert_graphr   !  sE     H3ZEsu-11#6    OrJ   c                     t        d      Nz>To remove HTML markup, use BeautifulSoup's get_text() functionNotImplementedError)htmls    rB   
clean_htmlr   6      
H rJ   c                     t        d      r   r   )urls    rB   	clean_urlr  <  r   rJ   c                      g }| D ]d  }t        |t        t        f      s|g}|D ]D  }t        |t        t        f      r|j                  t	        |             4|j                  |       F f |S )z
    Flatten a list.

        >>> from nltk.util import flatten
        >>> flatten(1, 2, ['b', 'a' , ['c', 'd']], 3)
        [1, 2, 'b', 'a', 'c', 'd', 3]

    :param args: items and lists to be combined into a single list
    :rtype: list
    )r"   rL   tupler   flattenrn   )r@   r   litems       rB   r  r  G  sb     	A!dE]+AD$u.'	   HrJ   c                 p    t        |       } |rt        |f|dz
  z  |       } |rt        | |f|dz
  z        } | S )a  
    Returns a padded sequence of items before ngram extraction.

        >>> list(pad_sequence([1,2,3,4,5], 2, pad_left=True, pad_right=True, left_pad_symbol='<s>', right_pad_symbol='</s>'))
        ['<s>', 1, 2, 3, 4, 5, '</s>']
        >>> list(pad_sequence([1,2,3,4,5], 2, pad_left=True, left_pad_symbol='<s>'))
        ['<s>', 1, 2, 3, 4, 5]
        >>> list(pad_sequence([1,2,3,4,5], 2, pad_right=True, right_pad_symbol='</s>'))
        [1, 2, 3, 4, 5, '</s>']

    :param sequence: the source data to be padded
    :type sequence: sequence or iter
    :param n: the degree of the ngrams
    :type n: int
    :param pad_left: whether the ngrams should be left-padded
    :type pad_left: bool
    :param pad_right: whether the ngrams should be right-padded
    :type pad_right: bool
    :param left_pad_symbol: the symbol to use for left padding (default is None)
    :type left_pad_symbol: any
    :param right_pad_symbol: the symbol to use for right padding (default is None)
    :type right_pad_symbol: any
    :rtype: sequence or iter
    r^   )iterr   )sequencenpad_left	pad_rightleft_pad_symbolright_pad_symbols         rB   pad_sequencer  d  sJ    @ H~H/+q1u5x@$4#6!a%#@AOrJ   c              +      K   t        | |fi |} t        |       }t        t        ||      |      }t	        |      |k(  rt        |       |D ]   }|j                  |       t        |       " yw)a  
    Return the ngrams generated from a sequence of items, as an iterator.
    For example:

        >>> from nltk.util import ngrams
        >>> list(ngrams([1,2,3,4,5], 3))
        [(1, 2, 3), (2, 3, 4), (3, 4, 5)]

    Wrap with list for a list version of this function.  Set pad_left
    or pad_right to true in order to get additional ngrams:

        >>> list(ngrams([1,2,3,4,5], 2, pad_right=True))
        [(1, 2), (2, 3), (3, 4), (4, 5), (5, None)]
        >>> list(ngrams([1,2,3,4,5], 2, pad_right=True, right_pad_symbol='</s>'))
        [(1, 2), (2, 3), (3, 4), (4, 5), (5, '</s>')]
        >>> list(ngrams([1,2,3,4,5], 2, pad_left=True, left_pad_symbol='<s>'))
        [('<s>', 1), (1, 2), (2, 3), (3, 4), (4, 5)]
        >>> list(ngrams([1,2,3,4,5], 2, pad_left=True, pad_right=True, left_pad_symbol='<s>', right_pad_symbol='</s>'))
        [('<s>', 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, '</s>')]


    :param sequence: the source data to be converted into ngrams
    :type sequence: sequence or iter
    :param n: the degree of the ngrams
    :type n: int
    :param pad_left: whether the ngrams should be left-padded
    :type pad_left: bool
    :param pad_right: whether the ngrams should be right-padded
    :type pad_right: bool
    :param left_pad_symbol: the symbol to use for left padding (default is None)
    :type left_pad_symbol: any
    :param right_pad_symbol: the symbol to use for right padding (default is None)
    :type right_pad_symbol: any
    :rtype: sequence or iter
    )maxlenN)r  r	  r   r   r:   r  rn   )r
  r  kwargsitwindowr   s         rB   ngramsr    sm     H Ha262H 
hB6"a=+F
6{aFmaFm s   A1A3c              +   :   K   t        | dfi |E d{    y7 w)a  
    Return the bigrams generated from a sequence of items, as an iterator.
    For example:

        >>> from nltk.util import bigrams
        >>> list(bigrams([1,2,3,4,5]))
        [(1, 2), (2, 3), (3, 4), (4, 5)]

    Use bigrams for a list version of this function.

    :param sequence: the source data to be converted into bigrams
    :type sequence: sequence or iter
    :rtype: iter(tuple)
    r   Nr  r
  r  s     rB   bigramsr           h,V,,,   c              +   :   K   t        | dfi |E d{    y7 w)a  
    Return the trigrams generated from a sequence of items, as an iterator.
    For example:

        >>> from nltk.util import trigrams
        >>> list(trigrams([1,2,3,4,5]))
        [(1, 2, 3), (2, 3, 4), (3, 4, 5)]

    Use trigrams for a list version of this function.

    :param sequence: the source data to be converted into trigrams
    :type sequence: sequence or iter
    :rtype: iter(tuple)
    r   Nr  r  s     rB   trigramsr    r  r  c              +     K   |dk(  r	 t        |       }t        | |||fi |} t        t	        | |            }|rOt        |t        |      dz         D ]  }t        |d|         	 |j                  t        |              |d= |rNyy# t        $ r t        |       } t        |       }Y w xY w# t        $ r Y 8w xY ww)av  
    Returns all possible ngrams generated from a sequence of items, as an iterator.

        >>> sent = 'a b c'.split()

    New version outputs for everygrams.
        >>> list(everygrams(sent))
        [('a',), ('a', 'b'), ('a', 'b', 'c'), ('b',), ('b', 'c'), ('c',)]

    Old version outputs for everygrams.
        >>> sorted(everygrams(sent), key=len)
        [('a',), ('b',), ('c',), ('a', 'b'), ('b', 'c'), ('a', 'b', 'c')]

        >>> list(everygrams(sent, max_len=2))
        [('a',), ('a', 'b'), ('b',), ('b', 'c'), ('c',)]

    :param sequence: the source data to be converted into ngrams. If max_len is
        not provided, this sequence will be loaded into memory
    :type sequence: sequence or iter
    :param min_len: minimum length of the ngrams, aka. n-gram order/degree of ngram
    :type  min_len: int
    :param max_len: maximum length of the ngrams (set to length of sequence by default)
    :type  max_len: int
    :param pad_left: whether the ngrams should be left-padded
    :type pad_left: bool
    :param pad_right: whether the ngrams should be right-padded
    :type pad_right: bool
    :rtype: iter(tuple)
    r   r^   Nr   )
r:   r   rL   r  r   r   r  rn   nextStopIteration)r
  min_lenmax_lenr  r  r  history	ngram_lens           rB   
everygramsr&    s     D "}	$(mG HgxMfMH 6(G,-G wGq(89I
+,, :	NN4>* AJ   	$H~H(mG	$$  		sR   B>B
 AB>(B/ B>B>
B,)B>+B,,B>/	B;8B>:B;;B>c              +      K   d|v sd|v rt        | |fi |} t               }t        | ||z   d|      D ]/  }|dd }|dd }t        ||dz
        D ]  }|d   |u r||z     1 yw)a  
    Returns all possible skipgrams generated from a sequence of items, as an iterator.
    Skipgrams are ngrams that allows tokens to be skipped.
    Refer to http://homepages.inf.ed.ac.uk/ballison/pdf/lrec_skipgrams.pdf

        >>> sent = "Insurgents killed in ongoing fighting".split()
        >>> list(skipgrams(sent, 2, 2))
        [('Insurgents', 'killed'), ('Insurgents', 'in'), ('Insurgents', 'ongoing'), ('killed', 'in'), ('killed', 'ongoing'), ('killed', 'fighting'), ('in', 'ongoing'), ('in', 'fighting'), ('ongoing', 'fighting')]
        >>> list(skipgrams(sent, 3, 2))
        [('Insurgents', 'killed', 'in'), ('Insurgents', 'killed', 'ongoing'), ('Insurgents', 'killed', 'fighting'), ('Insurgents', 'in', 'ongoing'), ('Insurgents', 'in', 'fighting'), ('Insurgents', 'ongoing', 'fighting'), ('killed', 'in', 'ongoing'), ('killed', 'in', 'fighting'), ('killed', 'ongoing', 'fighting'), ('in', 'ongoing', 'fighting')]

    :param sequence: the source data to be converted into trigrams
    :type sequence: sequence or iter
    :param n: the degree of the ngrams
    :type n: int
    :param k: the skip distance
    :type  k: int
    :rtype: iter(tuple)
    r  r  T)r  r  Nr^   r   )r  objectr  r   )	r
  r  r   r  SENTINELngramheadtail	skip_tails	            rB   	skipgramsr.  #  s     , V{f4!6v6
 xH!a%4(SRayQRy%dAE2I}("" 3 Ts   A%A'c                 2   |dz   }t        |      }d}d}t        | d      r-t        j                  | j                        j
                  dz
  }n6| j                  dd       | j                         dz
  }| j                  d       |i }||k  r
||f}||z   dz  }	|j                  |	      r	||	   \  }
}nzd}	 | j                  t        d|	dz
               |	dkD  r| j                          | j                         }
| j                         }|dk7  rn||	z   dz  }	|	|dz
  k(  ryk||k  r|
|f||	<   |
|kD  r||	dz
  k7  sJ d       |	dz
  }n:|d| |k(  r|S ||kD  r||	dz
  k7  sJ d       |	dz
  }n||k  r|
t        |      z   dz
  }|dz  }||f}||k(  ry||k  r
y)	a  
    Return the line from the file with first word key.
    Searches through a sorted file using the binary search algorithm.

    :type file: file
    :param file: the file to be searched through.
    :type key: str
    :param key: the identifier we are searching for.
    r   r   r<   r^   r   Nr]   zinfinite loop)r:   r   osstatr<   st_sizeseektellr   maxdiscard_linereadline)filerp   cache
cacheDepthkeylenrN   currentDepthrO   	lastStatemiddleoffsetline	thisStates                rB   binary_search_filerB  O  s    )CXFELtVggdii ((1,		!QiikAo		!}
#+3J	#+!#99V =LFD D		#a!,-A:%%'}}2:&.Q.S1W$  j(!'fC<&1*$5o5$1*C'6]c!KCZ&1*$5o5$1*CCZSY&*E3J		! S #+V rJ   c                 P   | 	 t               d   } t        | | d      }t	        |      }|St               }|j                  d| ||       |j                  t        |             |j                  t        |             t        |       y# t        $ r}t        d      |d}~ww xY w)a  
    Set the HTTP proxy for Python to download through.

    If ``proxy`` is None then tries to set proxy from environment or system
    settings.

    :param proxy: The HTTP proxy server to use. For example:
        'http://proxy.example.com:3128/'
    :param user: The username to authenticate with. Use None to disable
        authentication.
    :param password: The password to authenticate with.
    Nhttpz'Could not detect default proxy settings)httpsrD  )realmuriuserpasswd)r   KeyErrorr/   r   r   r
   add_passwordadd_handlerr   r   r   )proxyrH  passwordr?   proxy_handleropenerpassword_managers          rB   	set_proxyrR    s     }	OL(E
 !5%!@AM-(F:<%%De$x%X01ABC12BCD 6  	OFGQN	Os   B 	B%B  B%c                 v   d|dz  z   }t        |       ru| j                  r| j                  j                         s
|dz   | _        | D ]  } t        | |dz           | j                  r| j                  j                         s|| _        yy|r/| j                  r| j                  j                         s|| _        yyy)a  
    Recursive function to indent an ElementTree._ElementInterface
    used for pretty printing. Run indent on elem and then output
    in the normal way.

    :param elem: element to be indented. will be modified.
    :type elem: ElementTree._ElementInterface
    :param level: level of indentation for this element
    :type level: nonnegative integer
    :rtype:   ElementTree._ElementInterface
    :return:  Contents of elem indented to reflect its structure
    rR   z  r^   N)r:   textstripelementtree_indentr,  )elemlevelr   s      rB   rV  rV    s     	ut|A
4yyy		 1DDIDtUQY/ yy		 1DI !2 $))499??+<DI ,=5rJ   c                     d|cxk  r| k  r=n yd\  }}t        dt        || |z
        dz         D ]  }|| z  }||z  }| dz  }  ||z  S y)a9  
    This function is a fast way to calculate binomial coefficients, commonly
    known as nCk, i.e. the number of combinations of n things taken k at a time.
    (https://en.wikipedia.org/wiki/Binomial_coefficient).

    This is the *scipy.special.comb()* with long integer computation but this
    approximation is faster, see https://github.com/nltk/nltk/issues/1181

        >>> choose(4, 2)
        6
        >>> choose(6, 2)
        15

    :param n: The number of things.
    :type n: int
    :param r: The number of times a thing is taken.
    :type r: int
    r   )r^   r^   r^   )r   min)r  r   ntokktokts        rB   chooser^    si    & 	A{{  
dq#aQ-!+,AAIDAIDFA - t|rJ   c                 N    t        |       \  }}t        |d       t        ||      S )z$s -> (s0,s1), (s1,s2), (s2, s3), ...N)r   r   zip)iterableabs      rB   pairwiserd    s$    x=DAqDMq!9rJ   c                      ddl m}m ddlm} |r ||      n|}|dk  rt	         |      S   ||       fd|D              S )Nr   )Paralleldelayed)tqdmr^   )n_jobsc              3   :   K   | ]  }        |        y wrl   rt   )r   r@  rg  funcs     rB   r   z)parallelize_preprocess.<locals>.<genexpr>  s     %OhdmgdmD&9hs   )joblibrf  rg  rh  map)rk  iterator	processesprogress_barrf  rh  rg  s   `     @rB   parallelize_preprocessrq    sB    (!-tH~8HA~4""%89%%Oh%OOOrJ   )r   N)F   )r   rr  ){})NN)F)FFNN)r^   r   FF)Nr   )Nr]   )r   )Fr-   r   r0  r(   rv   r7   r`   r   collectionsr   r   	itertoolsr   r   r   r   r	   urllib.requestr
   r   r   r   r   r   r   nltk.collectionsnltk.internalsr   r   r   rC   rI   rP   rW   r[   rh   rj   r~   r   r	  r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r  r  r&  r.  rB  rR  rV  r^  rd  rq  rt   rJ   rB   <module>rz     s     	  	    * 6 6     L L $%#
 &#
VC*+	4I P$K $R2O "& 2 !%r5 'T(V 8<Dt &\ *.E %R rDD%FT rDD%QhJ 59 *Z 59 TF5.z@"D*@ %V.b-&-( @E:z##XEZ P@FPrJ   