
    gk                         d dl mZ d dlmZ d dlmZ d dlmZmZm	Z	 d dl
mZ d dlmZ e G d d             Z G d	 d
      Z G d d      Z G d d      Zd Zd Zd Zd Zedk(  r e        yy)    )defaultdict)total_ordering)chain)DependencyGrammarDependencyProductionProbabilisticDependencyGrammar)raise_unorderable_types)DependencyGraphc                   @    e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
d	 Zy
)DependencySpanaT  
    A contiguous span over some part of the input string representing
    dependency (head -> modifier) relationships amongst words.  An atomic
    span corresponds to only one word so it isn't a 'span' in the conventional
    sense, as its _start_index = _end_index = _head_index for concatenation
    purposes.  All other spans are assumed to have arcs between all nodes
    within the start and end indexes of the span, and one head index corresponding
    to the head word for the entire span.  This is the same as the root node if
    the dependency structure were depicted as a graph.
    c                     || _         || _        || _        || _        || _        |||t        |      f| _        t        | j                        | _        y N)	_start_index
_end_index_head_index_arcs_tagstuple_comparison_keyhash_hash)selfstart_index	end_index
head_indexarcstagss         Z/var/www/openai/venv/lib/python3.12/site-packages/nltk/parse/projectivedependencyparser.py__init__zDependencySpan.__init__(   sN    '#%

 +Y
E$KP$../
    c                     | j                   S )zk
        :return: An value indexing the head of the entire ``DependencySpan``.
        :rtype: int
        )r   r   s    r   r   zDependencySpan.head_index1   s    
 r    c                 N    d| j                   | j                  | j                  fz  S )zj
        :return: A concise string representatino of the ``DependencySpan``.
        :rtype: str.
        Span %d-%d; Head Index: %d)r   r   r   r"   s    r   __repr__zDependencySpan.__repr__8   s/    
 ,OO/
 
 	
r    c                     d| j                   | j                  | j                  fz  }t        t	        | j
                              D ]'  }|d|| j
                  |   | j                  |   fz  z  }) |S )zi
        :return: A verbose string representation of the ``DependencySpan``.
        :rtype: str
        r$   z
%d <- %d, %s)r   r   r   rangelenr   r   )r   stris      r   __str__zDependencySpan.__str__C   sq    
 +OO.
 

 s4::'A#q$**Q-A&GGGC (
r    c                 f    t        |       t        |      k(  xr | j                  |j                  k(  S r   )typer   r   others     r   __eq__zDependencySpan.__eq__Q   s-    J$u+%W$*>*>%BWBW*W	
r    c                     | |k(   S r    r.   s     r   __ne__zDependencySpan.__ne__V   s    5=  r    c                 n    t        |t              st        d| |       | j                  |j                  k  S )N<)
isinstancer   r	   r   r.   s     r   __lt__zDependencySpan.__lt__Y   s/    %0#Cu5##e&;&;;;r    c                     | j                   S )zE
        :return: The hash value of this ``DependencySpan``.
        )r   r"   s    r   __hash__zDependencySpan.__hash__^   s     zzr    N)__name__
__module____qualname____doc__r   r   r%   r+   r0   r3   r7   r9   r2   r    r   r   r      s/    	0 	


!<
r    r   c                   (    e Zd ZdZd Zd Zd Zd Zy)	ChartCellz
    A cell from the parse chart formed when performing the CYK algorithm.
    Each cell keeps track of its x and y coordinates (though this will probably
    be discarded), and a list of spans serving as the cell's entries.
    c                 >    || _         || _        t               | _        y)z
        :param x: This cell's x coordinate.
        :type x: int.
        :param y: This cell's y coordinate.
        :type y: int.
        N)_x_yset_entries)r   xys      r   r   zChartCell.__init__q   s     r    c                 :    | j                   j                  |       y)z
        Appends the given span to the list of spans
        representing the chart cell's entries.

        :param span: The span to add.
        :type span: DependencySpan
        N)rD   add)r   spans     r   rH   zChartCell.add|   s     	$r    c                 N    d| j                   | j                  | j                  fz  S )zf
        :return: A verbose string representation of this ``ChartCell``.
        :rtype: str.
        zCC[%d,%d]: %s)rA   rB   rD   r"   s    r   r+   zChartCell.__str__   s"    
 $''477DMM!BBBr    c                     d| z  S )zf
        :return: A concise string representation of this ``ChartCell``.
        :rtype: str.
        z%sr2   r"   s    r   r%   zChartCell.__repr__   s    
 d{r    N)r:   r;   r<   r=   r   rH   r+   r%   r2   r    r   r?   r?   j   s    	 Cr    r?   c                   "    e Zd ZdZd Zd Zd Zy)ProjectiveDependencyParsera  
    A projective, rule-based, dependency parser.  A ProjectiveDependencyParser
    is created with a DependencyGrammar, a set of productions specifying
    word-to-word dependency relations.  The parse() method will then
    return the set of all parses, in tree representation, for a given input
    sequence of tokens.  Each parse must meet the requirements of the both
    the grammar and the projectivity constraint which specifies that the
    branches of the dependency tree are not allowed to cross.  Alternatively,
    this can be understood as stating that each parent node and its children
    in the parse tree form a continuous substring of the input sequence.
    c                     || _         y)a  
        Create a new ProjectiveDependencyParser, from a word-to-word
        dependency grammar ``DependencyGrammar``.

        :param dependency_grammar: A word-to-word relation dependencygrammar.
        :type dependency_grammar: DependencyGrammar
        N)_grammar)r   dependency_grammars     r   r   z#ProjectiveDependencyParser.__init__   s     +r    c              #     K   t        |      | _        g }t        dt        | j                        dz         D ]  }|j	                  g        t        dt        | j                        dz         D ]U  }||   j	                  t        ||             ||dz   k(  s*||   |   j                  t        |dz
  ||dz
  dgdg             W  t        dt        | j                        dz         D ]  }t        |dz
  dd      D ]s  }t        |dz
  |d      D ]^  }||   |   j                  D ]G  }||   |   j                  D ]0  }| j                  ||      D ]  }||   |   j                  |        2 I ` u  |t        | j                           d   j                  D ]e  }	d}
t        t        |            D ]-  }|
d|dz   ||   ||   ddd|	j                  |   dz   dd	d	f
z  z  }
/ t        |
      }|j                          g y
w)a>  
        Performs a projective dependency parse on the list of tokens using
        a chart-based, span-concatenation algorithm similar to Eisner (1996).

        :param tokens: The list of input tokens.
        :type tokens: list(str)
        :return: An iterator over parse trees.
        :rtype: iter(Tree)
        r      null    	%d	%s	%s	%s	%s	%s	%d	%s	%s	%s
ROOT-N)list_tokensr'   r(   appendr?   rH   r   rD   concatenater   r
   tree)r   tokenschartr*   jkspan1span2newspanparseconll_formatdgs               r   rf   z ProjectiveDependencyParser.parse   s      F|q#dll+a/0ALL1c$,,/!34a	!Q0A:!HQKOON1q5!QURD6($ST 5 1 q#dll+a/0A1q5"b)q1ua,A!&q!!5!5%*1Xa[%9%9E+/+;+;E5+I %a 8 ,J &: "6 - * 1 3t||,-a099EL3v;'  LE1I1IKKNQ&P ! 	 (  !.B'')O+ :s   BHE+Hc           	         g }|j                   |j                   k(  rt        d       |j                   |j                   kD  r|}|}|}|j                  |j                  z   }|j                  |j                  z   }| j                  j                  | j                  |j                     | j                  |j                           rb|j                  ||j                  |j                   z
  <   |j                  t        |j                   |j                  |j                  ||             |j                  |j                  z   }| j                  j                  | j                  |j                     | j                  |j                           rb|j                  ||j                  |j                   z
  <   |j                  t        |j                   |j                  |j                  ||             |S a  
        Concatenates the two spans in whichever way possible.  This
        includes rightward concatenation (from the leftmost word of the
        leftmost span to the rightmost word of the rightmost span) and
        leftward concatenation (vice-versa) between adjacent spans.  Unlike
        Eisner's presentation of span concatenation, these spans do not
        share or pivot on a particular word/word-index.

        :return: A list of new spans formed through concatenation.
        :rtype: list(DependencySpan)
        z8Error: Mismatched spans - replace this with thrown errorr   printr   r   rO   containsr[   r   r\   r   r   r   rc   rd   spans	temp_spannew_arcsnew_tagss          r   r]   z&ProjectiveDependencyParser.concatenate   s    !3!33LM 2 22IEE;;,;;,==!!LL**+T\\%:K:K-L
 @E?P?PHU&&););;<LL&&$$%% ;;,==!!LL**+T\\%:K:K-L
 @E?P?PHU&&););;<LL&&$$%% r    N)r:   r;   r<   r=   r   rf   r]   r2   r    r   rM   rM      s    
+0d4r    rM   c                   .    e Zd ZdZd Zd Zd Zd Zd Zy)'ProbabilisticProjectiveDependencyParsera  A probabilistic, projective dependency parser.

    This parser returns the most probable projective parse derived from the
    probabilistic dependency grammar derived from the train() method.  The
    probabilistic model is an implementation of Eisner's (1996) Model C, which
    conditions on head-word, head-tag, child-word, and child-tag.  The decoding
    uses a bottom-up chart-based span concatenation algorithm that's identical
    to the one utilized by the rule-based projective parser.

    Usage example

    >>> from nltk.parse.dependencygraph import conll_data2

    >>> graphs = [
    ... DependencyGraph(entry) for entry in conll_data2.split('\n\n') if entry
    ... ]

    >>> ppdp = ProbabilisticProjectiveDependencyParser()
    >>> ppdp.train(graphs)

    >>> sent = ['Cathy', 'zag', 'hen', 'wild', 'zwaaien', '.']
    >>> list(ppdp.parse(sent))
    [Tree('zag', ['Cathy', 'hen', Tree('zwaaien', ['wild', '.'])])]

    c                      y)zp
        Create a new probabilistic dependency parser.  No additional
        operations are necessary.
        Nr2   r"   s    r   r   z0ProbabilisticProjectiveDependencyParser.__init__:  s    r    c                    t        |      | _        g }t        dt        | j                        dz         D ]  }|j	                  g        t        dt        | j                        dz         D ]  }||   j	                  t        ||             ||dz   k(  s*||dz
     | j                  j                  v rQ| j                  j                  ||dz
        D ].  }||   |   j                  t        |dz
  ||dz
  dg|g             0 t        d||dz
     z         g c c S   t        dt        | j                        dz         D ]  }t        |dz
  dd      D ]s  }t        |dz
  |d      D ]^  }||   |   j                  D ]G  }||   |   j                  D ]0  }| j                  ||      D ]  }	||   |   j                  |	        2 I ` u  g }
d}d}|t        | j                           d   j                  D ]  }d}d}t        t        |            D ]f  }|d||   d	|j                  |   dz   d	fz  z  }|d
|dz   ||   ||   |j                  |   |j                  |   d	|j                  |   dz   dddf
z  z  }h t        |      }| j                  |      }|
j	                  ||j!                         f        |
j#                          d |
D        S )aX  
        Parses the list of tokens subject to the projectivity constraint
        and the productions in the parser's grammar.  This uses a method
        similar to the span-concatenation algorithm defined in Eisner (1996).
        It returns the most probable parse derived from the parser's
        probabilistic dependency grammar.
        r   rR   rS   z7No tag found for input token '%s', parse is impossible.rU   NrV   z%s	%s	%d	%s
rT   rW   rX   rY   c              3   &   K   | ]	  \  }}|  y wr   r2   ).0scorer^   s      r   	<genexpr>z@ProbabilisticProjectiveDependencyParser.parse.<locals>.<genexpr>  s     0%%%s   )rZ   r[   r'   r(   r\   r?   rO   r   rH   r   rl   rD   r]   r   r
   compute_probr^   sort)r   r_   r`   r*   ra   tagrb   rc   rd   re   trees	max_parse	max_scorerf   rg   malt_formatrh   ry   s                     r   rf   z-ProbabilisticProjectiveDependencyParser.parse@  s    F|q#dll+a/0ALL1c$,,/!34a	!Q0A:a!e}(;(;;#'==#6#6va!e}#EC!!HQKOO .q1uaQse L $F
 U$QUm,  "	 5 1  q#dll+a/0A1q5"b)q1ua,A!&q!!5!5%*1Xa[%9%9E+/+;+;E5+I %a 8 ,J &: "6 - * 1 		3t||,-a099ELK3v;'11IKKNQ&	5     LE1I1IKKNKKNKKNQ&P !  (* !.B%%b)ELL%+,5 :6 	

0%00r    c           	         g }|j                   |j                   k(  rt        d       |j                   |j                   kD  r|}|}|}|j                  |j                  z   }|j                  |j                  z   }| j                  j                  | j                  |j                     | j                  |j                           rb|j                  ||j                  |j                   z
  <   |j                  t        |j                   |j                  |j                  ||             |j                  |j                  z   }|j                  |j                  z   }| j                  j                  | j                  |j                     | j                  |j                           rb|j                  ||j                  |j                   z
  <   |j                  t        |j                   |j                  |j                  ||             |S rj   rk   rn   s          r   r]   z3ProbabilisticProjectiveDependencyParser.concatenate  s    !3!33LM 2 22IEE;;,;;,==!!LL**+T\\%:K:K-L
 @E?P?PHU&&););;<LL&&$$%% ;;,;;,==!!LL**+T\\%:K:K-L
 @E?P?PHU&&););;<LL&&$$%% r    c           
         g }t        t              }i }|D ]  }t        dt        |j                              D ]v  }t        t        j                  |j                  |   d   j                                     }|j                  |      }|j                  |      }	||	z   }
t        d|dz   z
  |	dz         D ]  }|j                  |   d   }|j                  |   d   }||v r||   j                  |       n|h||<   d}d}d}d}|dk  r||z   }|dk\  r*|j                  ||      d   }|j                  ||      d   }|d	k7  r0|j                  ||dz         d   }|j                  ||dz         d   }|dk7  r|j                  t        ||g             d
j                  |||||      }dj                  |||      }||xx   dz  cc<   ||xx   dz  cc<   "|dkD  s)||z   dz
  }||
k  r*|j                  ||      d   }|j                  ||      d   }|dk7  r0|j                  ||dz
        d   }|j                  ||dz
        d   }|dk7  r|j                  t        ||g             dj                  |||||      }dj                  |||      }||xx   dz  cc<   ||xx   dz  cc<    y  t        |||      | _        y)a  
        Trains a ProbabilisticDependencyGrammar based on the list of input
        DependencyGraphs.  This model is an implementation of Eisner's (1996)
        Model C, which derives its statistics from head-word, head-tag,
        child-word, and child-tag relationships.

        :param graphs: A list of dependency graphs to train from.
        :type: list(DependencyGraph)
        rR   depsr   rU   wordr}   STOPSTARTrS   '(head ({} {}) (mods ({}, {}, {}) left))(mods ({}, {}, {}) left))((head ({} {}) (mods ({}, {}, {}) right))(mods ({}, {}, {}) right))N)r   intr'   r(   nodesrZ   r   from_iterablevaluesleft_childrenright_childrenrH   r\   r   formatr   rO   )r   graphsproductionseventsr   rh   
node_indexchildrennr_left_childrennr_right_childrennr_childrenchild_index	head_wordhead_tagchild	child_tag	prev_wordprev_tagarray_index
head_event	mod_events                        r   trainz-ProbabilisticProjectiveDependencyParser.train  sF    S!B#As288}5
''(<V(D(K(K(MN $&#3#3J#? $&$5$5j$A!.1BB#()A-.0AA0E$K !# 4V <I!xx
3E:H D(Y++H5+3*Y"E &I 'I&H"Q&14D&D&!+$&HHXk-B$CF$KE(*+1F(G(NI&",(*+/1J(KF(SI')xxq0I'J5'QH F?'../CIPUw/WX%N%U%U!%$%$&
 %@$F$F$%$%	
 z*a/*y)Q.)$q&14D&Dq&H&4$&HHXk-B$CF$KE(*+1F(G(NI&!+(*+/1J(KF(SI')xxq0I'J5'QH F?'../CIPUw/WX%O%V%V!%$%$&
 %A$G$G$%$%	
 z*a/*y)Q.)y$ 6 N 7{FDQr    c           	         d}t        dt        |j                              D ]g  }t        t	        j
                  |j                  |   d   j                                     }|j                  |      }|j                  |      }||z   }t        d|dz   z
  |dz         D ]  }|j                  |   d   }	|j                  |   d   }
d}d}d	}d	}|dk  r||z   }|dk\  r*|j                  ||      d   }|j                  ||      d   }|d
k7  r0|j                  ||dz         d   }|j                  ||dz         d   }dj                  ||||	|
      }dj                  ||	|
      }| j                  j                  |   }| j                  j                  |   }|dk7  r
|||z  z  }d}|dkD  s||z   dz
  }||k  r*|j                  ||      d   }|j                  ||      d   }|dk7  r0|j                  ||dz
        d   }|j                  ||dz
        d   }dj                  ||||	|
      }dj                  ||	|
      }| j                  j                  |   }| j                  j                  |   }|dk7  r
|||z  z  }d} j |S )aS  
        Computes the probability of a dependency graph based
        on the parser's probability model (defined by the parser's
        statistical dependency grammar).

        :param dg: A dependency graph to score.
        :type dg: DependencyGraph
        :return: The probability of the dependency graph.
        :rtype: int
        g      ?rR   r   r   rU   r   r}   r   r   rS   r   r   g:0yE>r   r   )r'   r(   r   rZ   r   r   r   r   r   r   rO   _events)r   rh   probr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   h_countm_counts                       r   r{   z4ProbabilisticProjectiveDependencyParser.compute_prob  s    3rxx=1JE//0DV0L0S0S0UVWH!//
; " 1 1* =*->>K$Q*:Q*>%?ARUVAVWHHZ08	88J/6"	#	"?"-0@"@K"a' "+)> ? G$&HHXk-B$CE$J	"b($&HHXkAo-F$G$O	#%88H[1_,E#Fu#M!J!Q!Q! ! "J !< B B ! !I
 #mm33J?G"mm33I>G !|' 11) 1_"-0@"@1"DK"[0 "+)> ? G$&HHXk-B$CE$J	"a'$&HHXkAo-F$G$O	#%88H[1_,E#Fu#M!K!R!R! ! "J != C C ! !I
 #mm33J?G"mm33I>G!|' 11)}  X 2N r    N)	r:   r;   r<   r=   r   rf   r]   r   r{   r2   r    r   rt   rt     s'    4@1D3jTRlSr    rt   c                  ,    t                t                y r   )projective_rule_parse_demoprojective_prob_parse_demor2   r    r   demor   h  s      r    c                      t        j                  d      } t        |        t        |       }|j	                  g d      }|D ]  }t        |        y)z
    A demonstration showing the creation and use of a
    ``DependencyGrammar`` to perform a projective dependency
    parse.
    zP
    'scratch' -> 'cats' | 'walls'
    'walls' -> 'the'
    'cats' -> 'the'
    )thecatsscratchr   wallsN)r   
fromstringrl   rM   rf   grammarpdpr~   r^   s       r   r   r   n  sL      **	G 
'N
$W
-CII@AEd r    c                  p   t                t        d       t        d       t        d       t        j                  d      } t        |        t                t        d       t        d       t        |       }|j	                  g d      }|D ]  }t        |        t                t        d       t        d	       t        d
       t        d       t        j                  d      } t        |        t                t        d       t        |       }|j	                  g d      }|D ]  }t        |        y)a   
    A demonstration showing the creation of a ``DependencyGrammar``
    in which a specific number of modifiers is listed for a given
    head.  This can further constrain the number of possible parses
    created by a ``ProjectiveDependencyParser``.
    z>A grammar with no arity constraints. Each DependencyProductionz;specifies a relationship between one head word and only onezmodifier word.zj
    'fell' -> 'price' | 'stock'
    'price' -> 'of' | 'the'
    'of' -> 'stock'
    'stock' -> 'the'
    z<For the sentence 'The price of the stock fell', this grammarz(will produce the following three parses:)r   priceofr   stockfellz.By contrast, the following grammar contains a z2DependencyProduction that specifies a relationshipz5between a single head word, 'price', and two modifierzwords, 'of' and 'the'.zh
    'fell' -> 'price' | 'stock'
    'price' -> 'of' 'the'
    'of' -> 'stock'
    'stock' -> 'the'
    z:This constrains the number of possible parses to just one:N)rl   r   r   rM   rf   r   s       r   arity_parse_demor     s    
G	
JK	
GH	
**	G 
'N	G	
HI	
45
$W
-CIIDEEd  
G	
:;	
>?	
AB	
"#**	G 
'N	G	D %W
-CIIDEEd r    c                  R   ddl m}  | j                  d      D cg c]  }|st        |       }}t	               }t        d       |j                  |       g d}t        ddj                  |      d       t        d	       |j                  |      D ]  }t        |        y
c c}w )zT
    A demo showing the training and use of a projective
    dependency parser.
    r   )conll_data2z

z6Training Probabilistic Projective Dependency Parser...)Cathyzaghenwildzwaaien.z	Parsing ' z'...zParse:N)	nltk.parse.dependencygraphr   splitr
   rt   rl   r   joinrf   )r   entryr   ppdpsentr^   s         r   r   r     s    
 72=2C2CF2KU2Kuoe$2KFU24D	
BCJJv:D	+sxx~v.	(O

4 d ! Vs
   B$B$__main__N)collectionsr   	functoolsr   	itertoolsr   nltk.grammarr   r   r   nltk.internalsr	   r   r
   r   r?   rM   rt   r   r   r   r   r:   r2   r    r   <module>r      s    $ $  
 3 6 F F F\( (`} }JA AR
!(3l& zF r    