3
df#                 @   sz   d Z ddlZddlmZ dddZdddZdd	d
ZdddZdd ZdddZ	dd Z
dd Zedkrve  e
  dS )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             C   sr   ddl m} ddlm}m} t||r0||}n|||d}g }x,| D ]$}|j }	t|j|	}
|j	|
 qFW |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   Z
nltk.parser   r   
isinstancesplitlistparseappend)inputsgrammarr   r   r   r   cpZparsessenttokenssyntrees r   -/tmp/pip-build-v9q4h5k9/nltk/nltk/sem/util.pyparse_sents   s    


r   SEMc             C   s^   ddl m} | j }t||s"ty|| S  tk
rV   t|dd td|  Y nX  dS )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 %sN)r   r   labelr   AssertionErrorKeyErrorprint)syntreesemkeyr   noder   r   r   root_semrep4   s    	r!   c                s    fddt | ||dD S )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)))
    c                s   g | ]} fd d|D qS )c                s   g | ]}|t | fqS r   )r!   ).0syn)r   r   r   
<listcomp>V   s    z.interpret_sents.<locals>.<listcomp>.<listcomp>r   )r"   r   )r   r   r   r$   V   s   z#interpret_sents.<locals>.<listcomp>)r   )r   )r   r   r   r   r   )r   r   interpret_sentsI   s    
r%   c                s    fddt | |D S )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)))
    c                s"   g | ]} fd d|D qS )c          	      s*   g | ]"\}}||j d |  dfqS )z%s)r   )r   )r"   r#   sem)
assignmentmodelr   r   r   r$   i   s   z-evaluate_sents.<locals>.<listcomp>.<listcomp>r   )r"   Zinterpretations)r'   r(   r   r   r   r$   h   s   z"evaluate_sents.<locals>.<listcomp>)r%   )r   r   r(   r'   r   r   )r'   r(   r   r   evaluate_sents[   s    r)   c              C   s   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dddhfddddd hfdd!d"d#d$d%hfdd&d'd(hfdd)d*d+d,hfg} t j| }|j}t j||at j|ad S )-Njohnb1maryg1suzieg2fidod1tessd2noosanZgirlZboyb2ZdogZbarkwalkZchaseZseeinwith)r*   r+   )r,   r-   )r.   r/   )r0   r1   )r2   r3   )r4   r5   )r+   r-   )r6   r-   )r-   r1   )r/   r3   )r+   r-   )r6   r3   )r-   r+   )r3   r+   )r/   r5   )r+   r5   )r6   r5   )r3   r5   )r+   r-   )r-   r+   )r1   r+   )r+   r1   )r   Z	ValuationdomainZModelm0Z
Assignmentg0)vvaldomr   r   r   demo_model0p   s(    




r@   utf8c          	   C   sH   t j| d|}dd |D }W d Q R X dd |D }dd |D }|S )Nrc             S   s   g | ]}|j  qS r   )rstrip)r"   lr   r   r   r$      s    zread_sents.<locals>.<listcomp>c             S   s   g | ]}t |d kr|qS )r   )len)r"   rD   r   r   r   r$      s    c             S   s   g | ]}|d  dks|qS )r   #r   )r"   rD   r   r   r   r$      s    )codecsopen)filenameencodingfpsentsr   r   r   
read_sents   s
    rM   c              C   sd   ddl m}  | jd}td|  td x4tdg|dd	D ] }|d \}}t  td
| q<W dS )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: %s*   Zhellor&   )r   zoutput: Nz********************)r   r   
fromstringr   r%   )r   greadingr#   r&   r   r   r   demo_legacy_grammar   s    rS   c           	   C   sB  dd l } ddlm} d}||d}|jdddddddd |jd	d
dddd |jdddddd |jdddddd |jdddddd |jddd d!d"d# |jd$d%d d&d'd# |jd(d)d*d+d,d# |jd-d.d*d/d0d# |j \}}d1d2 }t  d3d4d5d6d7d8g}d9}|jr|j}	|jr$|j}|j	r:t
d:|j	  |d krLt|	}t}
t}|jrrt|||
||jd;}nt|||jd;}xt|D ]\}}d<}td=|  t| |jrx|| D ]D\}}}t|trt|j }td>||f  t| |d<7 }qW n0x.|| D ]"\}}td>||f  |d<7 }qW qW d S )?Nr   )OptionParserz,
    Parse and evaluate some sentences.
    )descriptionTdefault )r   betasyntracesemtracedemor   	sentencesz-dz--demor[   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--sentencesr\   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-reductionrX   zdon't carry out beta-reductionz-tz
--syntracecountrY   z.set syntactic tracing on; requires '-e' optionz-Tz
--semtracerZ   zset semantic tracing on-   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 model)r      z
Sentence: %sz%d:  %s)sysoptparserT   set_defaults
add_option
parse_argsr@   r\   r   r(   execrM   r;   r<   r   r)   rZ   r%   rY   	enumerater   r   dictsetkeys)rj   rT   rU   optsoptionsargsZSPACERrL   ZgramfileZ	sentsfiler(   rQ   ZevaluationsZsemrepsir   r5   r   Zsemrepvaluer   r   r   r[      s    

r[   __main__)r   )r   )r   r   )r   )rA   )__doc__rG   Znltk.semr   r   r!   r%   r)   r@   rM   rS   r[   __name__r   r   r   r   <module>   s   



!

 