
    gM                     t   d Z ddlZddlmZ ddlmZmZ ddlmZ ddl	m
Z
mZmZmZ ddlmZmZ  G d d	e      Z G d
 de      Z G d de
      Z G d de
      Z G d de
      Z G d de
      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Zd dZedk(  r e        yy)!a  
Classes and interfaces for associating probabilities with tree
structures that represent the internal organization of a text.  The
probabilistic parser module defines ``BottomUpProbabilisticChartParser``.

``BottomUpProbabilisticChartParser`` is an abstract class that implements
a bottom-up chart parser for ``PCFG`` grammars.  It maintains a queue of edges,
and adds them to the chart one at a time.  The ordering of this queue
is based on the probabilities associated with the edges, allowing the
parser to expand more likely edges before less likely ones.  Each
subclass implements a different queue ordering, producing different
search strategies.  Currently the following subclasses are defined:

  - ``InsideChartParser`` searches edges in decreasing order of
    their trees' inside probabilities.
  - ``RandomChartParser`` searches edges in random order.
  - ``LongestChartParser`` searches edges in decreasing order of their
    location's length.

The ``BottomUpProbabilisticChartParser`` constructor has an optional
argument beam_size.  If non-zero, this controls the size of the beam
(aka the edge queue).  This option is most useful with InsideChartParser.
    N)reduce)PCFGNonterminal)ParserI)AbstractChartRuleChartLeafEdgeTreeEdge)ProbabilisticTreeTreec                       e Zd Zd Zy)ProbabilisticLeafEdgec                      y)Ng      ? selfs    F/var/www/openai/venv/lib/python3.12/site-packages/nltk/parse/pchart.pyprobzProbabilisticLeafEdge.prob3   s        N)__name__
__module____qualname__r   r   r   r   r   r   2   s    r   r   c                   (    e Zd Zd Zd Zed        Zy)ProbabilisticTreeEdgec                 j    t        j                  | g|i | || _        | j                  |f| _        y N)r
   __init___prob_comparison_key)r   r   argskwargss       r   r   zProbabilisticTreeEdge.__init__8   s4    $000
 $ 4 4d;r   c                     | j                   S r   )r   r   s    r   r   zProbabilisticTreeEdge.prob>   s    zzr   c                 \    t        |||f| j                         | j                         d      S )Nr   )r   lhsrhs)
productionindexps      r   from_productionz%ProbabilisticTreeEdge.from_productionA   s,    $u~z~~/1A1
 	
r   N)r   r   r   r   r   staticmethodr)   r   r   r   r   r   7   s     < 
 
r   r   c                       e Zd ZdZd Zy)ProbabilisticBottomUpInitRuler   c              #      K   t        |j                               D ]4  }t        |j                  |      |      }|j	                  |d      s1| 6 y w)Nr   )range
num_leavesr   leafinsert)r   chartgrammarr'   new_edges        r   applyz#ProbabilisticBottomUpInitRule.applyL   sF     5++-.E,UZZ->FH||Hb) /s   A
AANr   r   r   	NUM_EDGESr5   r   r   r   r,   r,   I   s    Ir   r,   c                       e Zd ZdZd Zy) ProbabilisticBottomUpPredictRule   c              #   6  K   |j                         ry |j                         D ]q  }|j                         |j                         d   k(  s(t        j                  ||j                         |j                               }|j                  |d      sn| s y w)Nr   r   )	is_incompleteproductionsr$   r%   r   r)   startr   r1   )r   r2   r3   edgeprodr4   s         r   r5   z&ProbabilisticBottomUpPredictRule.applyV   sx     '')DxxzTXXZ]*0@@$**,		 <<"-"N *s   A	BABBNr6   r   r   r   r9   r9   S   s    I	#r   r9   c                       e Zd ZdZd Zy)ProbabilisticFundamentalRule   c              #   :  K   |j                         |j                         k(  rA|j                         |j                         k(  r |j	                         r|j                         sy |j                         |j                         z  }t        ||j                         |j                         f|j                         |j                         |j                         dz         }d}|j                  |      D ]  }|j                  |||fz         sd} |r| y y w)Nr:   )spanr$   r%   dotFT)endr>   nextsymr$   r<   is_completer   r   r%   rF   child_pointer_listsr1   )	r   r2   r3   	left_edge
right_edger(   r4   changed_chartcpl1s	            r   r5   z"ProbabilisticFundamentalRule.applye   s      MMOz//11!!#z~~'77'')&&( NNz00(//#Z^^%56!#
 --i8D||Hdj]&:; $ 9
 N s   DDDNr6   r   r   r   rB   rB   b   s    Ir   rB   c                   *    e Zd ZdZ e       Zd Zd Zy)&SingleEdgeProbabilisticFundamentalRuler:   c              #     K   | j                   }|j                         rR|j                  |j                         d|j	                               D ]  }|j                  ||||      E d {      y |j                  |j                         d|j                               D ]  }|j                  ||||      E d {      y 7 Y7 	w)NT)r>   rI   r$   F)rG   rI   rH   )_fundamental_ruler<   selectrG   rH   r5   r>   r$   )r   r2   r3   edge1fredge2s         r   r5   z,SingleEdgeProbabilisticFundamentalRule.apply   s     ## iikt &  88E7E5AAA KKMueiik &  88E7E5AAA B Bs%   A'C)C*AC;C<CCc                      y)NzFundamental Ruler   r   s    r   __str__z.SingleEdgeProbabilisticFundamentalRule.__str__   s    !r   N)r   r   r   r7   rB   rR   r5   rX   r   r   r   rP   rP      s    I46B"r   rP   c                   >    e Zd ZdZd
dZd ZddZd Zd Zd Z	d Z
y	) BottomUpProbabilisticChartParsera  
    An abstract bottom-up parser for ``PCFG`` grammars that uses a ``Chart`` to
    record partial results.  ``BottomUpProbabilisticChartParser`` maintains
    a queue of edges that can be added to the chart.  This queue is
    initialized with edges for each token in the text that is being
    parsed.  ``BottomUpProbabilisticChartParser`` inserts these edges into
    the chart one at a time, starting with the most likely edges, and
    proceeding to less likely edges.  For each edge that is added to
    the chart, it may become possible to insert additional edges into
    the chart; these are added to the queue.  This process continues
    until enough complete parses have been generated, or until the
    queue is empty.

    The sorting order for the queue is not specified by
    ``BottomUpProbabilisticChartParser``.  Different sorting orders will
    result in different search strategies.  The sorting order for the
    queue is defined by the method ``sort_queue``; subclasses are required
    to provide a definition for this method.

    :type _grammar: PCFG
    :ivar _grammar: The grammar used to parse sentences.
    :type _trace: int
    :ivar _trace: The level of tracing output that should be generated
        when parsing a text.
    c                 d    t        |t              st        d      || _        || _        || _        y)a%  
        Create a new ``BottomUpProbabilisticChartParser``, that uses
        ``grammar`` to parse texts.

        :type grammar: PCFG
        :param grammar: The grammar used to parse texts.
        :type beam_size: int
        :param beam_size: The maximum length for the parser's edge queue.
        :type trace: int
        :param trace: The level of tracing that should be used when
            parsing a text.  ``0`` will generate no tracing output;
            and higher numbers will produce more verbose tracing
            output.
        z&The grammar must be probabilistic PCFGN)
isinstancer   
ValueError_grammar	beam_size_trace)r   r3   r_   traces       r   r   z)BottomUpProbabilisticChartParser.__init__   s/     '4(EFF"r   c                     | j                   S r   )r^   r   s    r   r3   z(BottomUpProbabilisticChartParser.grammar   s    }}r   c                     || _         y)aP  
        Set the level of tracing output that should be generated when
        parsing a text.

        :type trace: int
        :param trace: The trace level.  A trace level of ``0`` will
            generate no tracing output; and higher trace levels will
            produce more verbose tracing output.
        :rtype: None
        N)r`   )r   ra   s     r   ra   z&BottomUpProbabilisticChartParser.trace   s     r   c                    | j                   j                  |       t        t        |            }| j                   }t	               }t               }t               }g }|j                  ||      D ]T  }| j                  dkD  r2t        d|j                  |d      dd|j                         d       |j                  |       V t        |      dkD  r| j                  ||       | j                  r| j!                  ||       |j#                         }| j                  dkD  r2t        d|j                  |d      dd|j                         d       |j%                  |j                  |||             |j%                  |j                  |||             t        |      dkD  rt        |j'                  |j)                         t*                    }	i }
|j-                         D ]3  }|j                         |
|j/                         |j1                         f<   5 |	D ]  }| j3                  ||
        |	j5                  d	d
        t7        |	      S )Nr:   z  rC   )width50z []r   Tc                 "    | j                         S r   r   )trees    r   <lambda>z8BottomUpProbabilisticChartParser.parse.<locals>.<lambda>  s
    499;r   )reversekey)r^   check_coverager   listr,   r9   rP   r5   r`   printpretty_format_edger   appendlen
sort_queuer_   _prunepopextendparsesr>   r   r=   r$   r%   _setprobsortiter)r   tokensr2   r3   bu_initburU   queuer?   rx   
prod_probsr@   parses                r   r   z&BottomUpProbabilisticChartParser.parse   s   $$V,d6l#-- 01-/35  MM%1D{{Q//A/>		M LL 2 %j1nOOE5) ~~E5) 99;D{{Q//A/>		M LL%$78LL%$78% %j1n* ell7==?4EFG 
'')D15Jtxxz488:-. *EMM%,  	D&>?F|r   c                    |j                         y t        |j                               }g }|D ]L  }t        |t              r)|j                  t        |j                                      <|j                  |       N ||t        |      f   }|D ]8  }t        |t              s| j                  ||       ||j                         z  }: |j                  |       y r   )	r   r   labelr\   r   rr   tuplery   set_prob)r   rj   r   r$   r%   childr   s          r   ry   z)BottomUpProbabilisticChartParser._setprob  s    99;" $**,'E%&

;u{{}56

5!	 
 #uSz/* E%&eZ0

$ 
 	dr   c                     t               )a  
        Sort the given queue of ``Edge`` objects, placing the edge that should
        be tried first at the beginning of the queue.  This method
        will be called after each ``Edge`` is added to the queue.

        :param queue: The queue of ``Edge`` objects to sort.  Each edge in
            this queue is an edge that could be added to the chart by
            the fundamental rule; but that has not yet been added.
        :type queue: list(Edge)
        :param chart: The chart being used to parse the text.  This
            chart can be used to provide extra information for sorting
            the queue.
        :type chart: Chart
        :rtype: None
        )NotImplementedErrorr   r   r2   s      r   rt   z+BottomUpProbabilisticChartParser.sort_queue,  s      "##r   c                     t        |      | j                  kD  rUt        |      | j                  z
  }| j                  dkD  r(|d| D ]   }t        d|j	                  |d      z         " |d|= yy)z@Discard items in the queue if the queue is longer than the beam.rC   Nz  %-50s [DISCARDED])rs   r_   r`   rp   rq   )r   r   r2   splitr?   s        r   ru   z'BottomUpProbabilisticChartParser._prune>  sk    u:&J/E{{Q!&5MD/%2J2J4QR2SST *fuf 'r   N)r   r   )rC   )r   r   r   __doc__r   r3   ra   r   ry   rt   ru   r   r   r   rZ   rZ      s+    4*7r,$$r   rZ   c                       e Zd ZdZd Zy)InsideChartParseraU  
    A bottom-up parser for ``PCFG`` grammars that tries edges in descending
    order of the inside probabilities of their trees.  The "inside
    probability" of a tree is simply the
    probability of the entire tree, ignoring its context.  In
    particular, the inside probability of a tree generated by
    production *p* with children *c[1], c[2], ..., c[n]* is
    *P(p)P(c[1])P(c[2])...P(c[n])*; and the inside
    probability of a token is 1 if it is present in the text, and 0 if
    it is absent.

    This sorting order results in a type of lowest-cost-first search
    strategy.
    c                 *    |j                  d        y)aD  
        Sort the given queue of edges, in descending order of the
        inside probabilities of the edges' trees.

        :param queue: The queue of ``Edge`` objects to sort.  Each edge in
            this queue is an edge that could be added to the chart by
            the fundamental rule; but that has not yet been added.
        :type queue: list(Edge)
        :param chart: The chart being used to parse the text.  This
            chart can be used to provide extra information for sorting
            the queue.
        :type chart: Chart
        :rtype: None
        c                 "    | j                         S r   ri   r?   s    r   rk   z.InsideChartParser.sort_queue.<locals>.<lambda>h  s
    DIIKr   rm   Nrz   r   s      r   rt   zInsideChartParser.sort_queueY  s     	

/
0r   Nr   r   r   r   rt   r   r   r   r   r   H  s     1r   r   c                       e Zd ZdZd Zy)RandomChartParserz
    A bottom-up parser for ``PCFG`` grammars that tries edges in random order.
    This sorting order results in a random search strategy.
    c                 j    t        j                  dt        |      dz
        }||   |d   c|d<   ||<   y )Nr   r:   )randomrandintrs   )r   r   r2   is       r   rt   zRandomChartParser.sort_queue  s6    NN1c%j1n-!&q59rE!Hr   Nr   r   r   r   r   r     s    6r   r   c                       e Zd ZdZd Zy)UnsortedChartParserzV
    A bottom-up parser for ``PCFG`` grammars that tries edges in whatever order.
    c                      y r   r   r   s      r   rt   zUnsortedChartParser.sort_queue  s    r   Nr   r   r   r   r   r     s    
r   r   c                       e Zd ZdZd Zy)LongestChartParserz
    A bottom-up parser for ``PCFG`` grammars that tries longer edges before
    shorter ones.  This sorting order results in a type of best-first
    search strategy.
    c                 *    |j                  d        y )Nc                 "    | j                         S r   )lengthr   s    r   rk   z/LongestChartParser.sort_queue.<locals>.<lambda>  s
    DKKMr   r   r   r   s      r   rt   zLongestChartParser.sort_queue  s    

1
2r   Nr   r   r   r   r   r     s    3r   r   c           
      2   ddl }ddl}ddlm} ddlm} t        j                  d      }t        j                  d      }d|fd|fg}	| t                t        t        |	            D ]:  }
t        |
d	z   d
d|	|
   d           t        d|	|
   d	   z         t                < t        dd	t        |	      fz  d       t        |j                  j                         j                               d	z
  } 	 |	|    \  }}|j                         }|j!                  |      |j#                  |      |j%                  |      |j'                  |      |j!                  |t        |      d	z         g}g }g }g }i }|D ]  }t        d| d| d|        |j)                  d       |j                         }t+        |j-                  |            }|j/                  |j                         |z
         |rt1        d |d      t        |      z  nd}|j/                  |       |j/                  t        |             |D ]  }d	||j3                         <     t                t        d       t        d       t        t        |            D ]B  }
t        d||
   j4                  j6                  ||
   j8                  ||
   ||
   ||
   fz         D |j;                         }|rt1        d |d      t        |      z  }nd}t        d       t        dddt        |      |fz         |\t                t        dd       |j                  j                         j                         j=                         j?                  d      }|rdd l m!} t        d!        ||  |\t                t        d"d       |j                  j                         j                         j=                         j?                  d      }|r|D ]  }t        |        yy#  t        d       Y yxY w)#z
    A demonstration of the probabilistic parsers.  The user is
    prompted to select which demo to run, and how many parses should
    be found; and then each parser is run on the same demo, and a
    summary of the results are displayed.
    r   N)tokenize)pcharta7  
    S -> NP VP [1.0]
    NP -> Det N [0.5] | NP PP [0.25] | 'John' [0.1] | 'I' [0.15]
    Det -> 'the' [0.8] | 'my' [0.2]
    N -> 'man' [0.5] | 'telescope' [0.5]
    VP -> VP PP [0.1] | V NP [0.7] | V [0.2]
    V -> 'ate' [0.35] | 'saw' [0.65]
    PP -> P NP [1.0]
    P -> 'with' [0.61] | 'under' [0.39]
    a  
    S    -> NP VP         [1.0]
    VP   -> V NP          [.59]
    VP   -> V             [.40]
    VP   -> VP PP         [.01]
    NP   -> Det N         [.41]
    NP   -> Name          [.28]
    NP   -> NP PP         [.31]
    PP   -> P NP          [1.0]
    V    -> 'saw'         [.21]
    V    -> 'ate'         [.51]
    V    -> 'ran'         [.28]
    N    -> 'boy'         [.11]
    N    -> 'cookie'      [.12]
    N    -> 'table'       [.13]
    N    -> 'telescope'   [.14]
    N    -> 'hill'        [.5]
    Name -> 'Jack'        [.52]
    Name -> 'Bob'         [.48]
    P    -> 'with'        [.61]
    P    -> 'under'       [.39]
    Det  -> 'the'         [.41]
    Det  -> 'a'           [.31]
    Det  -> 'my'          [.28]
    zI saw John with my telescopez:the boy saw Jack with Bob under the table with a telescoper:   z>3z: z     %rzWhich demo (%d-%d)?  )rG   zBad sentence number)r_   z
s: z	
parser: z

grammar:    c                 (    | |j                         z   S r   ri   abs     r   rk   zdemo.<locals>.<lambda>      AFFHr   zC       Parser      Beam | Time (secs)   # Parses   Average P(parse)zC------------------------+------------------------------------------z%18s %4d |%11.4f%11d%19.14fc                 (    | |j                         z   S r   ri   r   s     r   rk   zdemo.<locals>.<lambda>'  r   r   z%18s      |%11s%11d%19.14fz(All Parses)zn/azDraw parses (y/n)? y)
draw_treesz  please wait...zPrint parses (y/n)? )"systimenltkr   
nltk.parser   r   
fromstringrp   r.   rs   intstdinreadlinestripr   r   r   r   r   ra   ro   r   rr   r   freeze	__class__r   r_   keyslower
startswithnltk.draw.treer   )choicedraw_parsesprint_parsesr   r   r   r   	toy_pcfg1	toy_pcfg2demosr   sentr3   r|   parserstimes	average_p
num_parses
all_parsesparsertrx   r(   r   r   s                            r   demor     s    ! 		I 	I: 
(3	EyQE
 ~s5z"AQU2Jbq!./)eAhqk)*G # 	$3u:6C@SYY'')//12Q6fg ZZ\F 	  )  )""7+!!'*  CK!O DG EIJJdV:fX[	BCQIIKfll6*+TYY[1_%JPF,fa83v;FVW#f+&A%&Jqxxz"   
G	
OP	
OP3w< )
$$--
$$a1!		
 ! __F,fa83v;F	
OP	
&.%Va)P
PQ#-ii((*00288:EEcJ- !F$#.yy))+11399;FFsKE%L  Q#$s   4P P__main__)NNN)r   r   	functoolsr   nltk.grammarr   r   nltk.parse.apir   nltk.parse.chartr   r   r	   r
   	nltk.treer   r   r   r   r,   r9   rB   rP   rZ   r   r   r   r   r   r   r   r   r   <module>r      s   >   * " I I -H 

H 
$$5 #'8 ##4 D"-> "0iw iX 18  1~	68 	6: 	39 	3"Qh zF r   