B
    >?["                 @   s   d Z ddlmZm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re  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.
    )print_functionunicode_literalsN)evaluatec             C   sr   ddl m} ddlm}m} t||r0||}n|||d}g }x,| D ]$}| }	t||	}
|	|
 qFW |S )ax  
    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``s
    r   )FeatureGrammar)FeatureChartParserload_parser)trace)
nltk.grammarr   Z
nltk.parser   r   
isinstancesplitlistparseappend)inputsgrammarr   r   r   r   ZcpZparsessenttokenssyntrees r   ,lib/python3.7/site-packages/nltk/sem/util.pyparse_sents   s    


r   SEMc             C   s^   ddl m} |  }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   Zlabelr
   AssertionErrorKeyErrorprint)syntreesemkeyr   Znoder   r   r   root_semrep5   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>W   s    z.interpret_sents.<locals>.<listcomp>.<listcomp>r   )r!   r   )r   r   r   r#   W   s   z#interpret_sents.<locals>.<listcomp>)r   )r   )r   r   r   r   r   )r   r   interpret_sentsJ   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#   j   s   z-evaluate_sents.<locals>.<listcomp>.<listcomp>r   )r!   Zinterpretations)r&   r'   r   r   r   r#   i   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t dd	gfd
t ddgfdt ddgfdt ddgfdt dd	dgfdt ddddgfdt dddddgfdt dddgfd t ddd!d"gfg} t| }|j}t||at|ad S )#N)Zjohnb1)Zmaryg1)Zsuzieg2)Zfidod1)Ztessd2)ZnoosanZgirlr*   r+   Zboyr)   b2Zdogr,   r-   ZbarkwalkZchase)r)   r*   )r/   r*   )r*   r,   )r+   r-   Zsee)r/   r-   )r*   r)   )r-   r)   )r+   r.   in)r)   r.   )r/   r.   )r-   r.   with)r,   r)   )r)   r,   )setr   Z	ValuationZdomainZModelm0Z
Assignmentg0)vvalZdomr   r   r   demo_model0q   s(    
r8   utf8c          	   C   sH   t | d|}dd |D }W d Q R X dd |D }dd |D }|S )Nrc             S   s   g | ]}|  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!   r<   r   r   r   r#      s    c             S   s   g | ]}|d  dks|qS )r   #r   )r!   r<   r   r   r   r#      s    )codecsopen)filenameencodingfpsentsr   r   r   
read_sents   s
    rE   c              C   sd   ddl m}  | 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: %sz********************Zhellor%   )r   zoutput: N)r	   r   Z
fromstringr   r$   )r   gZreadingr"   r%   r   r   r   demo_legacy_grammar   s    rG   c           	   C   s>  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# | \}}d1}t  d2d3d4d5d6d7g}d8}|jr|j}	|jr |j}|j	r6t
d9|j	  |d krHt|	}t}
t}|jrnt|||
||jd:}nt|||jd:}xt|D ]\}}d;}td<|  t| |jrx|| D ]D\}}}t|trt| }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--demorO   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--sentencesrP   z"read in a file of test sentences SSz-ez	--no-evalZstore_falser   zjust do a syntactic analysis)actionrR   rS   z-bz--no-beta-reductionrL   zdon't carry out beta-reductionz-tz
--syntracecountrM   z.set syntactic tracing on; requires '-e' optionz-Tz
--semtracerN   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 model)r      z
Sentence: %sz%d:  %s)sysZoptparserH   Zset_defaultsZ
add_option
parse_argsr8   rP   r   r'   execrE   r4   r5   r   r(   rN   r$   rM   	enumerater   r
   dictr3   keys)r[   rH   rI   ZoptsZoptionsargsZSPACERrD   ZgramfileZ	sentsfiler'   rF   ZevaluationsZsemrepsir   r.   r   Zsemrepvaluer   r   r   rO      s    

rO   __main__)r   )r   )r   r   )r   )r9   )__doc__Z
__future__r   r   r?   Znltk.semr   r   r    r$   r(   r8   rE   rG   rO   __name__r   r   r   r   <module>   s   



!

 