
    g+"                     ~    d Z ddlZddlmZ ddZddZddZddZd Zdd	Z	d
 Z
d Zedk(  r e         e
        yy)z
Utility functions for batch-processing sentences: parsing and
extraction of the semantic representation of the root node of the the
syntax tree, followed by evaluation of the semantic representation in
a first-order model.
    N)evaluatec                     ddl m} ddlm}m} t        ||      r	 ||      }n
 |||      }g }| D ]=  }|j                         }	t        |j                  |	            }
|j                  |
       ? |S )a  
    Convert input sentences into syntactic trees.

    :param inputs: sentences to be parsed
    :type inputs: list(str)
    :param grammar: ``FeatureGrammar`` or name of feature-based grammar
    :type grammar: nltk.grammar.FeatureGrammar
    :rtype: list(nltk.tree.Tree) or dict(list(str)): list(Tree)
    :return: a mapping from input sentences to a list of ``Tree`` instances.
    r   FeatureGrammar)FeatureChartParserload_parsertrace)
nltk.grammarr   
nltk.parser   r   
isinstancesplitlistparseappend)inputsgrammarr
   r   r   r   cpparsessenttokenssyntreess              B/var/www/openai/venv/lib/python3.12/site-packages/nltk/sem/util.pyparse_sentsr      sj     ,:'>*(.F()h  M    c                     ddl m} | j                         }t        ||      sJ 	 ||   S # t        $ r t        |d       t        d|z         Y  w xY w)a  
    Find the semantic representation at the root of a tree.

    :param syntree: a parse ``Tree``
    :param semkey: the feature label to use for the root semantics in the tree
    :return: the semantic representation at the root of a ``Tree``
    :rtype: sem.Expression
    r   )FeatStructNonterminal )endz'has no specification for the feature %s)r   r   labelr   KeyErrorprint)syntreesemkeyr   nodes       r   root_semrepr&   4   s_     3==?Dd1222BF| Bd7&@A	Bs   + $AAc                     t        | ||      D cg c]  }|D cg c]  }|t        ||      f c}  c}}S c c}w c c}}w )a  
    Add the semantic representation to each syntactic parse tree
    of each input sentence.

    :param inputs: a list of sentences
    :type inputs: list(str)
    :param grammar: ``FeatureGrammar`` or name of feature-based grammar
    :type grammar: nltk.grammar.FeatureGrammar
    :return: a mapping from sentences to lists of pairs (parse-tree, semantic-representations)
    :rtype: list(list(tuple(nltk.tree.Tree, nltk.sem.logic.ConstantExpression)))
    r	   )r   r&   )r   r   r$   r
   r   syns         r   interpret_sentsr)   I   sP     $FG5AAH 5==HS#{3'	(H=A =s   	>9>>c                     t        | |      D cg c]/  }|D cg c]  \  }}|||j                  d|z  ||      f! c}}1 c}}}S c c}}w c c}}}w )a  
    Add the truth-in-a-model value to each semantic representation
    for each syntactic parse of each input sentences.

    :param inputs: a list of sentences
    :type inputs: list(str)
    :param grammar: ``FeatureGrammar`` or name of feature-based grammar
    :type grammar: nltk.grammar.FeatureGrammar
    :return: a mapping from sentences to lists of triples (parse-tree, semantic-representations, evaluation-in-model)
    :rtype: list(list(tuple(nltk.tree.Tree, nltk.sem.logic.ConstantExpression, bool or dict(str): bool)))
    z%sr	   )r)   r   )r   r   model
assignmentr
   interpretationsr(   sems           r   evaluate_sentsr/   [   sq    "  /vw?
  @O .	
-
c #u~~dSj*E~JK-	
  @ 	
s   
A$A
A
Ac                     ddddddddd	hfd
ddhfdddhfdddhfdh dfdh dfdh dfdh dfdh dfg} t        j                  |       }|j                  }t        j                  ||      at        j
                  |      ay )N)johnb1)maryg1)suzieg2)fidod1)tessd2)noosangirlr4   r6   boyr2   b2dogr8   r:   barkwalk>   r2   r8   r6   chase>   r?   r4   r4   r8   r6   r:   r2   r4   see>   r?   r:   r:   r2   r6   r<   rG   r4   r2   in>   r2   r<   r?   r<   r:   r<   with>   r2   r8   r8   r2   rG   rL   )r   	ValuationdomainModelm0
Assignmentg0)vvaldoms      r   demo_model0r]   p   s     		$	t	t	$	#$	JKQ	
 
67	IJ%	A* 

Q
C
**C	S	!B			S	!Br   c                 "   t        j                  | d|      5 }|D cg c]  }|j                          }}d d d        D cg c]  }t        |      dkD  s| }}|D cg c]  }|d   dk(  r| }}|S c c}w # 1 sw Y   FxY wc c}w c c}w )Nrr   #)codecsopenrstriplen)filenameencodingfplsentss        r   
read_sentsrj      s    	XsH	-%'(RR( 
. ,1Q!QE,11QqTS[QE1L ) 
.	- -1s3   A;A6A;BB B.B6A;;Bc                      ddl m}  | j                  d      }t        d|z         t        d       t	        dg|d      D ]   }|d   \  }}t                t        d	|       " y
)z
    Check that interpret_sents() is compatible with legacy grammars that use
    a lowercase 'sem' feature.

    Define 'test.fcfg' to be the following

    r   r   z1
    % start S
    S[sem=<hello>] -> 'hello'
    zReading grammar: %sz********************hellor.   )r$   zoutput: N)r   r   
fromstringr"   r)   )r   greadingr(   r.   s        r   demo_legacy_grammarrp      sd     ,!!		A 

!
#$	(O"G9a>1:Sj# ?r   c            	         dd l } ddlm} d} ||      }|j                  ddddddd       |j	                  d	d
ddd       |j	                  ddddd       |j	                  ddddd       |j	                  ddddd       |j	                  ddd d!d"#       |j	                  d$d%d d&d'#       |j	                  d(d)d*d+d,#       |j	                  d-d.d*d/d0#       |j                         \  }}d1}t                g d2}d3}|j                  r|j                  }	|j                  r|j                  }|j                  rt        d4|j                  z         |t        	      }t        }
t        }|j                  rt        |||
||j                   5      }nt#        |||j$                  5      }t'        |      D ]  \  }}d6}t)        d7|z         t)        |       |j                  rX|   D ]O  \  }}}t+        |t,              rt/        |j1                               }t)        d8||fz         t)        |       |d6z  }Q |   D ]  \  }}t)        d8||fz         |d6z  }  y )9Nr   )OptionParserz,
    Parse and evaluate some sentences.
    )descriptionTdefault )r   betasyntracesemtracedemor   	sentencesz-dz--demory   zBchoose demo D; omit this for the default demo, or specify 'chat80'D)desthelpmetavarz-gz--gramr   zread in grammar GGz-mz--modelr+   z"import model M (omit '.py' suffix)Mz-sz--sentencesrz   z"read in a file of test sentences SSz-ez	--no-evalstore_falser   zjust do a syntactic analysis)actionr|   r}   z-bz--no-beta-reductionrv   zdon't carry out beta-reductionz-tz
--syntracecountrw   z.set syntactic tracing on; requires '-e' optionz-Tz
--semtracerx   zset semantic tracing onz------------------------------)zFido sees a boy with MaryzJohn sees Maryzevery girl chases a dogzevery boy chases a girlzJohn walks with a girl in Noosaz	who walksz"grammars/sample_grammars/sem2.fcfgzimport %s as modelr	      z
Sentence: %sz%d:  %s)sysoptparserr   set_defaults
add_option
parse_argsr]   rz   r   r+   execrj   rW   rY   r   r/   rx   r)   rw   	enumerater"   r   dictsetkeys)r   rr   rs   optsoptionsargsSPACERri   gramfile	sentsfiler+   rn   evaluationssemrepsir   r<   r#   semrepvalues                       r   ry   ry      s   %K K0D   	OOQ   	OOhY-@#   	OO1   	OO1   	OO+   	OO-   	OO=   	OO&   oo'OWdFME 4H%%	??}}!GMM12}9% E
A$UHeQgFVFVW!%9I9IJU#4%&f*5a.&eT*

-Ei1f+-.eQ +9 $+1:i1f+-.Q $. $r   __main__)r   )SEM)r   r   )utf8)__doc__ra   nltk.semr   r   r&   r)   r/   r]   rj   rp   ry   __name__ r   r   <module>r      sW     6
*$*"B0{| zF r   