
    QdX                     f   d Z ddlZddlmZmZ ddlmZ ddlmZm	Z	 ddl
mZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZmZ ddlmZ ddlmZ ddlmZ  G d de          Z G d de          Z G d de          Z G d d          Z d Z!ddZ"ddZ#d dZ$d Z%e&dk    r e%             dS dS )!a  
Module for incrementally developing simple discourses, and checking for semantic ambiguity,
consistency and informativeness.

Many of the ideas are based on the CURT family of programs of Blackburn and Bos
(see http://homepages.inf.ed.ac.uk/jbos/comsem/book1.html).

Consistency checking is carried out  by using the ``mace`` module to call the Mace4 model builder.
Informativeness checking is carried out with a call to ``Prover.prove()`` from
the ``inference``  module.

``DiscourseTester`` is a constructor for discourses.
The basic data structure is a list of sentences, stored as ``self._sentences``. Each sentence in the list
is assigned a "sentence ID" (``sid``) of the form ``s``\ *i*. For example::

    s0: A boxer walks
    s1: Every boxer chases a girl

Each sentence can be ambiguous between a number of readings, each of which receives a
"reading ID" (``rid``) of the form ``s``\ *i* -``r``\ *j*. For example::

    s0 readings:

    s0-r1: some x.(boxer(x) & walk(x))
    s0-r0: some x.(boxerdog(x) & walk(x))

A "thread" is a list of readings, represented as a list of ``rid``\ s.
Each thread receives a "thread ID" (``tid``) of the form ``d``\ *i*.
For example::

    d0: ['s0-r0', 's1-r0']

The set of all threads for a discourse is the Cartesian product of all the readings of the sequences of sentences.
(This is not intended to scale beyond very short discourses!) The method ``readings(filter=True)`` will only show
those threads which are consistent (taking into account any background assumptions).
    N)ABCMetaabstractmethod)reduce)addand_)show_cfg)MaceCommand)Prover9Command)load_parser)
MaltParser)AnaphoraResolutionExceptionresolve_anaphora)DrtGlue
Expression)RegexpTaggerc                   V    e Zd Zed             Zd Zed             Zed             ZdS )ReadingCommandc                     dS )zS
        :param sentence: the sentence to read
        :type sentence: str
        N selfsentences     8lib/python3.11/site-packages/nltk/inference/discourse.pyparse_to_readingsz ReadingCommand.parse_to_readings?             c                     |S )a9  
        This method should be used to handle dependencies between readings such
        as resolving anaphora.

        :param sentence_readings: readings to process
        :type sentence_readings: list(Expression)
        :return: the list of readings after processing
        :rtype: list(Expression)
        r   r   sentence_readingss     r   process_threadzReadingCommand.process_threadF   s
     ! r   c                     dS )z
        :param readings: readings to combine
        :type readings: list(Expression)
        :return: one combined reading
        :rtype: Expression
        Nr   r   readingss     r   combine_readingszReadingCommand.combine_readingsR   r   r   c                     dS )z
        Convert this expression into a First-Order Logic expression.

        :param expression: an expression
        :type expression: Expression
        :return: a FOL version of the input expression
        :rtype: Expression
        Nr   r   
expressions     r   to_folzReadingCommand.to_fol[   r   r   N)__name__
__module____qualname__r   r   r!   r%   r)   r   r   r   r   r   >   sr          ^
! 
! 
!   ^   ^  r   r   )	metaclassc                   (    e Zd ZddZd Zd Zd ZdS )CfgReadingCommandNc                 N    |r|nd| _         t          | j                   | _        dS )zg
        :param gramfile: name of file where grammar can be loaded
        :type gramfile: str
        z%grammars/book_grammars/discourse.fcfgN)	_gramfiler   _parser)r   gramfiles     r   __init__zCfgReadingCommand.__init__h   s/     !MHH&M 	 #4>22r   c                     ddl m |                                }| j                            |          }fd|D             S )(:see: ReadingCommand.parse_to_readings()r   )root_semrepc                 &    g | ]} |          S r   r   ).0treer7   s     r   
<listcomp>z7CfgReadingCommand.parse_to_readings.<locals>.<listcomp>x   s#    444dD!!444r   )nltk.semr7   splitr2   parse)r   r   tokenstreesr7   s       @r   r   z#CfgReadingCommand.parse_to_readingsr   sS    ((((((!!""6**4444e4444r   c                 ,    t          t          |          S z':see: ReadingCommand.combine_readings())r   r   r#   s     r   r%   z"CfgReadingCommand.combine_readingsz   s    dH%%%r   c                     |S z:see: ReadingCommand.to_fol()r   r'   s     r   r)   zCfgReadingCommand.to_fol~   s    r   N)r*   r+   r,   r4   r   r%   r)   r   r   r   r/   r/   g   sU        3 3 3 35 5 5& & &    r   r/   c                   .    e Zd ZddZd Zd Zd Zd ZdS )	DrtGlueReadingCommandNFc                 z    |!t           j                            ddd          }t          |||          | _        dS )z
        :param semtype_file: name of file where grammar can be loaded
        :param remove_duplicates: should duplicates be removed?
        :param depparser: the dependency parser
        Ngrammarssample_grammarszdrt_glue.semtype)semtype_fileremove_duplicates	depparser)ospathjoinr   _glue)r   rK   rL   rM   s       r   r4   zDrtGlueReadingCommand.__init__   sM     7<<-/A L %/
 
 



r   c                 6    | j                             |          S )r6   )rQ   parse_to_meaningr   s     r   r   z'DrtGlueReadingCommand.parse_to_readings   s    z**8444r   c                 T    	 |                      |          gS # t          $ r g cY S w xY w)z%:see: ReadingCommand.process_thread())r%   r   r   s     r   r!   z$DrtGlueReadingCommand.process_thread   sC    	))*;<<==* 	 	 	III	s    ''c                 n    t          t          |          }t          |                                          S rB   )r   r   r   simplify)r   r$   thread_readings      r   r%   z&DrtGlueReadingCommand.combine_readings   s+    X.. 7 7 9 9:::r   c                 *    |                                 S rD   )folr'   s     r   r)   zDrtGlueReadingCommand.to_fol   s    ~~r   )NFN)r*   r+   r,   r4   r   r!   r%   r)   r   r   r   rG   rG      sd        
 
 
 
 5 5 5  ; ; ;
         r   rG   c                       e Zd ZdZddZd ZddZddZd	 Zd
 Z	d Z
d ZddZddZ	 	 	 	 	 ddZddZddZddZddZd Zed             ZdS )DiscourseTesterz3
    Check properties of an ongoing discourse.
    Nc                    || _         d t          |          D             | _        d| _        i | _        |r|nt                      | _        i | _        i | _        |&ddl	m
} |D ]}t          ||          sJ || _        dS g | _        dS )z
        Initialize a ``DiscourseTester``.

        :param input: the discourse sentences
        :type input: list of str
        :param background: Formulas which express background assumptions
        :type background: list(Expression)
        c                      i | ]\  }}d |z  |S zs%sr   r9   isents      r   
<dictcomp>z,DiscourseTester.__init__.<locals>.<dictcomp>   s"    KKKwq$519dKKKr   Nr   r   )_input	enumerate
_sentences_models	_readingsr/   _reading_command_threads_filtered_threadsnltk.sem.logicr   
isinstance_background)r   inputreading_command
backgroundr   es         r   r4   zDiscourseTester.__init__   s     KK)E:J:JKKK.GOO4E4G4G 	 !#!111111 1 1!!Z000000)D!Dr   c                 r    t          | j                  D ]!}t          | d| j        |                     "dS )zI
        Display the list of sentences in the current discourse.
        : N)sortedre   print)r   ids     r   	sentenceszDiscourseTester.sentences   sM     )) 	2 	2BR004?2.001111	2 	2r   Fc           
      t   |r|                      d           t          | j                  D ]}d |                     |          D             }|| j        z  }|                     |          D ]\}t          ||          }|                                r5t          d|dt          |          d           t          d|z             ]| j
                            |           d	 t          | j
                  D             | _        |r.|                      d           |                     d
           dS dS )a  
        Add a sentence to the current discourse.

        Updates ``self._input`` and ``self._sentences``.
        :param sentence: An input sentence
        :type sentence: str
        :param informchk: if ``True``, check that the result of adding the sentence is thread-informative. Updates ``self._readings``.
        :param consistchk: if ``True``, check that the result of adding the sentence is thread-consistent. Updates ``self._readings``.

        Fverbosec                     g | ]\  }}|S r   r   r9   ridreadings      r   r;   z0DiscourseTester.add_sentence.<locals>.<listcomp>   s    VVV>CwVVVr   )goalassumptionsz
Sentence 'z' under reading 'z':z'Not informative relative to thread '%s'c                      i | ]\  }}d |z  |S r^   r   r_   s      r   rb   z0DiscourseTester.add_sentence.<locals>.<dictcomp>   "    QQQwq$519dQQQr   )showN)r$   rt   ri   expand_threadsrm   _get_readingsr
   proveru   strrc   appendrd   re   models)r   r   	informchk
consistchktidr   sent_readingtps           r   add_sentencezDiscourseTester.add_sentence   ss     	OMM%M(((dm,, 
O 
OVVT=P=PQT=U=UVVVt//$($6$6x$@$@ O OL'\{SSSBxxzz O'xx\):):):):<   G#MNNNO 	8$$$QQ)DK:P:PQQQ  	$MM%M(((KKUK#####	$ 	$r   Tc                 l   	 | j                             |           n7# t          $ r* t          d|z             |                                  Y dS w xY wd t          | j                   D             | _        |                     d           |r%t          d           |                                  dS dS )a#  
        Remove a sentence from the current discourse.

        Updates ``self._input``, ``self._sentences`` and ``self._readings``.
        :param sentence: An input sentence
        :type sentence: str
        :param verbose: If ``True``,  report on the updated list of sentences.
        zJRetraction failed. The sentence '%s' is not part of the current discourse:Nc                      i | ]\  }}d |z  |S r^   r   r_   s      r   rb   z4DiscourseTester.retract_sentence.<locals>.<dictcomp>  r   r   Fry   zCurrent sentences are )rc   remove
ValueErrorru   rw   rd   re   r$   )r   r   rz   s      r   retract_sentencez DiscourseTester.retract_sentence   s    	Kx(((( 	 	 	\   NN44	 RQ)DK:P:PQQQe$$$ 	*+++NN	 	s    0AAc                 8    t          | j        j                   dS )zJ
        Print out the grammar in use for parsing input sentences
        N)r   rh   r1   )r   s    r   grammarzDiscourseTester.grammar  s     	&011111r   c                 6    | j                             |          S )ze
        Build a list of semantic readings for a sentence.

        :rtype: list(Expression)
        )rh   r   r   s     r   r   zDiscourseTester._get_readings  s     $66x@@@r   c                     i | _         t          | j                  D ][| j                 }|                     |          }fdt	          t          |t
                              D             | j         <   \dS )zV
        Use ``self._sentences`` to construct a value for ``self._readings``.
        c                 J    i | ]\  }} d | |                                  S )z-r)rV   )r9   r}   r~   sids      r   rb   z7DiscourseTester._construct_readings.<locals>.<dictcomp>)  sE     # # # C #!1!1!3!3# # #r   )keyN)rg   rt   re   r   rd   r   )r   r   r$   r   s      @r   _construct_readingsz#DiscourseTester._construct_readings   s    
 $/** 	 	Cs+H))(33H# # # #$-fX3.G.G.G$H$H# # #DN3	 	r   c                 r   g g}t          | j                  D ]0}|                     |t          | j        |                             }1d t          |          D             | _        i | _        |                     | j                  }| j                                        D ]\  }}|df|v r
|| j        |<   dS )z
        Use ``self._readings`` to construct a value for ``self._threads``
        and use the model builder to construct a value for ``self._filtered_threads``
        c                      i | ]\  }}d |z  |S )zd%sr   )r9   r   threads      r   rb   z6DiscourseTester._construct_threads.<locals>.<dictcomp>6  s"    WWWffWWWr   TN)rt   rg   multiplyrd   ri   rj   _check_consistencyitems)r   thread_listr   consistency_checkedr   r   s         r   _construct_threadsz"DiscourseTester._construct_threads.  s    
 d$.)) 	R 	RC--VDN3<O5P5PQQKKWW	+@V@VWWW!#"55dmDD!]0022 	5 	5MS&T{111.4&s+	5 	5r   c                    |Ht          d|z             d |                     |          D             D ]}t          d|z             dS t          | j                  D ]}t                       t          d|z             t                       t          | j        |                   D ];}| j        |         |         }t          | d|                                            <dS )zS
        Print out the readings for  the discourse (or a single sentence).
        Nz%The sentence '%s' has these readings:c                 ,    g | ]}t          |          S r   )r   )r9   r~   s     r   r;   z2DiscourseTester._show_readings.<locals>.<listcomp>E  s    QQQwc'llQQQr   z    %sz%s readings:rs   )ru   r   rt   rg   	normalize)r   r   rr   r}   lfs         r   _show_readingszDiscourseTester._show_readings?  s    9HDEEEQQ43E3Eh3O3OQQQ $ $hl####$ $ dn-- 6 6ns*+++!$."566 6 6C,S1BS44BLLNN4455556	6 6r   c                 r    |r j         n j        }t          |          D ]}|rp fd j        |         D             }	 d j                            |                                          z  }n(# t          $ r}d|j        j        z  }Y d}~n
d}~ww xY wd}t          d|z   j        |         |           dS )zW
        Print out the value of ``self._threads`` or ``self._filtered_hreads``
        c                 h    g | ].}j         |                    d           d                  |         /S )-r   )rg   r=   )r9   r}   r   s     r   r;   z1DiscourseTester._show_threads.<locals>.<listcomp>W  sA       ?BDN399S>>!#45c:  r   z: %sz: INVALID: %sN z%s:)
rj   ri   rt   rh   r%   r   	Exception	__class__r*   ru   )r   filtershow_thread_readingsthreadsr   r$   rW   rq   s   `       r   _show_threadszDiscourseTester._show_threadsP  s    -3E$(('?? 	C 	CC# $   FJmTWFX  L/@@JJTTVVW #N ! L L L%4q{7K%KNNNNNNL "$%#+t}S1>BBBB	C 	Cs   /A//
B9BBc                     |                                   |                                  |s|rd}|r3|s|                     |           dS |                     ||           dS dS )a^  
        Construct and show the readings of the discourse (or of a single sentence).

        :param sentence: test just this sentence
        :type sentence: str
        :param threaded: if ``True``, print out each thread ID and the corresponding thread.
        :param filter: if ``True``, only print out consistent thread IDs and threads.
        T)r   r   r   N)r   r   r   r   )r   r   threadedrz   r   r   s         r   r$   zDiscourseTester.readingsf  s      	  """!!!  	) 	H 	 ##X#66666""!8L #     		 	r   c                 >     | j         } fd||         D             S )a  
        Given a thread ID, find the list of ``logic.Expression`` objects corresponding to the reading IDs in that thread.

        :param thread_id: thread ID
        :type thread_id: str
        :param threads: a mapping from thread IDs to lists of reading IDs
        :type threads: dict
        :return: A list of pairs ``(rid, reading)`` where reading is the ``logic.Expression`` associated with a reading ID
        :rtype: list of tuple
        Nc                 z    g | ]7}|                     d           dd         D ]}|j        |         |         f8S )r   N   )r=   rg   )r9   r}   r   r   s      r   r;   z2DiscourseTester.expand_threads.<locals>.<listcomp>  sd     
 
 
yy~~bqb)
 
  $.%c*+
 
 
 
r   )ri   )r   	thread_idr   s   `  r   r   zDiscourseTester.expand_threads  sA     ?mG
 
 
 
y)
 
 
 	
r   c           	         g }t          |          D ]<}d |                     ||          D             }t          t          | j        j        | j                            |                              }|r1|| j        z  }t          d |d          }|	                                }nd}|
                    ||f           |rt          d           t          d|z             t          d           |r#|D ]}	t          |	           t          d           |r%t          |                    d	                     -t          d
           >|S )Nc                     g | ]\  }}|S r   r   r|   s      r   r;   z6DiscourseTester._check_consistency.<locals>.<listcomp>  s)       *S'  r   )r      )
max_modelsFP   zModel for Discourse Thread %scooked)formatzNo model found!
)rt   r   listmaprh   r)   r!   rm   r	   build_modelr   spacerru   model)
r   r   r   rz   resultsr   r   mb
modelfoundas
             r   r   z"DiscourseTester._check_consistency  s}   '?? 	/ 	/C .2.A.A#w.A.W.W  K )0)88EE  K  #t// {rBBB^^--

"
NNC,--- /r


5;<<<r


 ( ! !a2JJJ /"((((334444-...r   c           	         |                                   |                                  |r|| j        |         in| j        }|                     |||          D ]\  }}d ||         D             }|sgt	          d| d| d           |                     |          D ],\  }}	t	          d| d|	                                            -t	                       t	          d| d| d           |                     |          D ],\  }}	t	          d| d|	                                            -t	                       d	S )
z
        Call Mace4 to build a model for each current discourse thread.

        :param thread_id: thread ID
        :type thread_id: str
        :param show: If ``True``, display the model that has been found.
        )r   rz   c                     g | ]}|S r   r   )r9   r}   s     r   r;   z*DiscourseTester.models.<locals>.<listcomp>  s    222cc222r   zInconsistent discourse:  :z    rs   zConsistent discourse: N)r   r   ri   r   ru   r   r   )
r   r   r   rz   r   r   r   idlistr}   r~   s
             r   r   zDiscourseTester.models  s    	  """!!!;DW9dmI677$-!%!8!8$ "9 "
 "
 	 	S* 32WS\222F 	@@@v@@@AAA$($7$7$<$< ? ?LC===(9(9(;(;==>>>>>s>>V>>>???$($7$7$<$< ? ?LC===(9(9(;(;==>>>>	 	r   c                    ddl m} t          |          D ]E\  }}t          ||          sJ |rt	          d|z             | j                            |           F|                                  |                                  dS )a0  
        Add a list of background assumptions for reasoning about the discourse.

        When called,  this method also updates the discourse model's set of readings and threads.
        :param background: Formulas which contain background information
        :type background: list(Expression)
        r   r   z"Adding assumption %s to backgroundN)	rk   r   rd   rl   ru   rm   r   r   r   )r   rp   rz   r   countrq   s         r   add_backgroundzDiscourseTester.add_background  s     	.-----#J// 	' 	'JUAa,,,,, D:UBCCC##A&&&& 	  """!!!!!r   c                 R    | j         D ]}t          t          |                     dS )z:
        Show the current background assumptions.
        N)rm   ru   r   )r   rq   s     r   rp   zDiscourseTester.background  s3     ! 	 	A#a&&MMMM	 	r   c                     g }| D ]8}|D ]3}g }||z  }|                     |           |                     |           49|S )a  
        Multiply every thread in ``discourse`` by every reading in ``readings``.

        Given discourse = [['A'], ['B']], readings = ['a', 'b', 'c'] , returns
        [['A', 'a'], ['A', 'b'], ['A', 'c'], ['B', 'a'], ['B', 'b'], ['B', 'c']]

        :param discourse: the current list of readings
        :type discourse: list of lists
        :param readings: an additional list of readings
        :type readings: list(Expression)
        :rtype: A list of lists
        )r   )	discourser$   resultsublistr   news         r   r   zDiscourseTester.multiply  se       	# 	#G # #w

1c""""	#
 r   )NN)FF)TrE   )NFTFF)NTF)F)r*   r+   r,   __doc__r4   rw   r   r   r   r   r   r   r   r   r$   r   r   r   r   rp   staticmethodr   r   r   r   r[   r[      su        " " " ">2 2 2 $  $  $  $D   02 2 2A A A  5 5 5"6 6 6 6"C C C C0 "   >
 
 
 
.       D   8" " " "(     \  r   r[   c                 X   g }t          |                                           D ]\  }}|                                }|                    d          s|dk    r5	 |                    t          j        |                     ^# t          $ r}t          d| d|           |d}~ww xY w|S )a	  
    Temporarily duplicated from ``nltk.sem.util``.
    Convert a  file of first order formulas into a list of ``Expression`` objects.

    :param s: the contents of the file
    :type s: str
    :return: a list of parsed formulas.
    :rtype: list(Expression)
    #r   zUnable to parse line rs   N)	rd   
splitlinesstrip
startswithr   r   
fromstringr   r   )s
statementslinenumlinerq   s        r   load_folr     s     J"1<<>>22 O Ozz||??3 	42::	Oj3D99:::: 	O 	O 	OFWFFFFGGQN	Os   'B
B'B""B'c                    t          ddg|           }|                                 t                       t                       |                                 t                       |                                 t                       |                    d           t                       |                    d           |                    d           t                       |                                 t                       |                    d           t                       t          ddg|           }t                       |                    d	d
           t                       |                                 t                       |                    d	d           t                       |                                 t                       |                    d           t                       |                    dd           t          g d|           }|                    d           ddl}t          j	        
                    ddd          }|j                            |          }t                       |                    |d           |                                 t                       |                    d           t                       |                                 dS )?
    Illustrate the various methods of ``DiscourseTester``
    zA boxer walkszEvery boxer chases a girlT)r   d1zJohn is a boxerzA student danceszEvery student is a personzNo person dances)r   ry   zA person dances)r   )zVincent is a boxerzFido is a boxerzVincent is marriedz
Fido barks)r   r   NrI   book_grammarszbackground.folF)r[   r   ru   rw   r$   r   r   	nltk.datarN   rO   rP   dataloadr   rp   )ro   dtnltkbackground_filerp   s        r   discourse_demor   *  s{    
	56
 
B IIKKK	GGG	GGGLLNNN	GGGKKMMM	GGGKKK	GGGIIdOOOOO%&&&	GGGLLNNN	GGGKKK	GGG		89?
 
B 
GGGOO&4O888	GGGKKMMM	GGG*D999	GGGIIKKK	GGGKK!"""	GGGOO%O666	UUU
 
B KKtKgll:@PQQO00J	GGGj%000MMOOO	GGGKKtK	GGGIIKKKKKr   c                 l   t          ddg|           }|                                 t                       |                                 t                       |                                 t                       |                    d           t                       |                    dd           dS )r   zevery dog chases a boyzhe runsT)r   r   N)r[   r   ru   rw   r$   )ro   r   s     r   drt_discourse_demor   d  s     
2I>	P	PBIIKKK	GGGLLNNN	GGGKKMMM	GGGKKTK***	GGGKKt$K77777r      c                 *    t          d| z             d S )Nr   )ru   )nums    r   r   r   t  s    	#)r   c                      t                       t          g d          } t          |           }t          t	          d|                     d S )N))z^(chases|runs)$VB)z^(a)$ex_quant)z	^(every)$
univ_quant)z^(dog|boy)$NN)z^(he)$PRP)taggerF)rL   rM   )r   r   r   r   rG   )r   rM   s     r   demor   x  sj    	
 	
 	
 F &)))IKKK    r   __main__rE   )r   )'r   rN   abcr   r   	functoolsr   operatorr   r   r   r   nltk.inference.macer	   nltk.inference.prover9r
   
nltk.parser   nltk.parse.maltr   nltk.sem.drtr   r   nltk.sem.gluer   rk   r   nltk.tagr   r   r/   rG   r[   r   r   r   r   r   r*   r   r   r   <module>r     s:  # #J 
			 ' ' ' ' ' ' ' '                     + + + + + + 1 1 1 1 1 1 " " " " " " & & & & & & F F F F F F F F ! ! ! ! ! ! % % % % % % ! ! ! ! ! !& & & & &w & & & &R       8#  #  #  #  # N #  #  # Le e e e e e e eP  27 7 7 7t8 8 8 8      $ zDFFFFF r   