U
    e=                     @   sZ  d Z ddlZddlZddlmZ dddddd	d
ddg	dddgdddddd	d
ddddgdZeddddZeddddZdd Z	dd Z
d?ddZejjfddZdd  Zd!d" Zd@d$d%ZdAd(d)ZdBd*d+Zd,d- ZdCd/d0ZdDd1d2Zd3d4 ZdEd6d7Zd8d9 Zd:d; Zed<krVddlZdd=lmZ edd> edd> e  e  e  e  dS )Fa  
Code for extracting relational triples from the ieer and conll2002 corpora.

Relations are stored internally as dictionaries ('reldicts').

The two serialization outputs are "rtuple" and "clause".

- An rtuple is a tuple of the form ``(subj, filler, obj)``,
  where ``subj`` and ``obj`` are pairs of Named Entity mentions, and ``filler`` is the string of words
  occurring between ``sub`` and ``obj`` (with no intervening NEs). Strings are printed via ``repr()`` to
  circumvent locale variations in rendering utf-8 encoded strings.
- A clause is an atom of the form ``relsym(subjsym, objsym)``,
  where the relation, subject and object have been canonicalized to single strings.
    N)defaultdictLOCATIONORGANIZATIONPERSONZDURATIONZDATEZCARDINALPERCENTZMONEYZMEASURELOCPERORGZFACILITYZGPE)ieer	conll2002ace)r   r	   r   )r   r   r   c                 C   s(   z
t |  W S  tk
r"   |  Y S X dS )zF
    Expand an NE class name.
    :type type: str
    :rtype: str
    N)
short2longKeyErrortype r   T/var/www/html/assets/scripts/venv/lib/python3.8/site-packages/nltk/sem/relextract.py_expand?   s    
r   c                 C   s(   z
t |  W S  tk
r"   |  Y S X dS )zJ
    Abbreviate an NE class name.
    :type type: str
    :rtype: str
    N)
long2shortr   r   r   r   r   class_abbrevK   s    
r    Fc                    sf   z| | W S  tk
r`   |r8| dd | D  Y S ddlm  |  fdd| D  Y S X dS )z
    Join a list into a string, turning tags tuples into tag strings or just words.
    :param untag: if ``True``, omit the tag from tagged input strings.
    :type lst: list
    :rtype: str
    c                 s   s   | ]}|d  V  qdS )r   Nr   .0tupr   r   r   	<genexpr>b   s     z_join.<locals>.<genexpr>r   	tuple2strc                 3   s   | ]} |V  qd S )Nr   r   r   r   r   r   e   s     N)join	TypeErrorZnltk.tagr   )lstsepuntagr   r   r   _joinW   s    r"   c                 C   s4   z||  d W S  tk
r.   |  d Y S X dS )z`
    Translate one entity to its ISO Latin value.
    Inspired by example from effbot.org


       r   N)groupr   )mZdefsr   r   r   descape_entityh   s    r&   c                 C   s<   t | ddd}| }td}|t|}|dd}|S )z
    Convert a list of strings into a canonical symbol.
    :type lst: list
    :return: a Unicode string without whitespace
    :rtype: unicode
    _Tr!   z&(\w+?);. )r"   lowerrecompilesubr&   replace)r   symZENTr   r   r   list2symv   s    
r1   c                 C   sZ   ddl m} g }g dg}| D ]8}t||s:|d | q||d< || g dg}q|S )a  
    Group a chunk structure into a list of 'semi-relations' of the form (list(str), ``Tree``).

    In order to facilitate the construction of (``Tree``, string, ``Tree``) triples, this
    identifies pairs whose first member is a list (possibly empty) of terminal
    strings, and whose second member is a ``Tree`` of the form (NE_label, terminals).

    :param tree: a chunk tree
    :return: a list of pairs (list(str), ``Tree``)
    :rtype: list of tuple
    r   TreeNr#   )	nltk.treer3   
isinstanceappend)treer3   Z	semi_relsZsemi_relZdtrr   r   r   tree2semi_rel   s    


r8      c                 C   sH  g }t | dkrDtt}t| d d | d |d< | d d  |d< t| d d  |d< t| d d  |d< t| d d |d	< t| d d d
d|d< | d d  |d< t| d d  |d< t| d d  |d< t| d d d| |d< |r,td|d |d |d f  || | dd } q|S )a  
    Converts the pairs generated by ``tree2semi_rel`` into a 'reldict': a dictionary which
    stores information about the subject and object NEs plus the filler between them.
    Additionally, a left and right context of length =< window are captured (within
    a given input sentence).

    :param pairs: a pair of list(str) and ``Tree``, as generated by
    :param window: a threshold for the number of items to include in the left and right context
    :type window: int
    :return: 'relation' dictionaries whose keys are 'lcon', 'subjclass', 'subjtext', 'subjsym', 'filler', objclass', objtext', 'objsym' and 'rcon'
    :rtype: list(defaultdict)
       r   Nlconr#   	subjclasssubjtextsubjsymfillerTr(   Zuntagged_fillerobjclassobjtextobjsymrconz(%s(%s, %s))	lenr   strr"   labelleavesr1   printr6   )pairswindowtraceresultreldictr   r   r   semi_rel2reldict   s2    
rN   r   
   c           	         s   r6t | kr6tt | kr*tntd  rl t | krlt t | kr`t  ntd  |dks||dkrt|}n&|dkrt|jt|j }ntdt|} fdd}tt||S )	a  
    Filter the output of ``semi_rel2reldict`` according to specified NE classes and a filler pattern.

    The parameters ``subjclass`` and ``objclass`` can be used to restrict the
    Named Entities to particular types (any of 'LOCATION', 'ORGANIZATION',
    'PERSON', 'DURATION', 'DATE', 'CARDINAL', 'PERCENT', 'MONEY', 'MEASURE').

    :param subjclass: the class of the subject Named Entity.
    :type subjclass: str
    :param objclass: the class of the object Named Entity.
    :type objclass: str
    :param doc: input document
    :type doc: ieer document or a list of chunk trees
    :param corpus: name of the corpus to take as input; possible values are
        'ieer' and 'conll2002'
    :type corpus: str
    :param pattern: a regular expression for filtering the fillers of
        retrieved triples.
    :type pattern: SRE_Pattern
    :param window: filters out fillers which exceed this threshold
    :type window: int
    :return: see ``mk_reldicts``
    :rtype: list(defaultdict)
    z;your value for the subject type has not been recognized: %sz:your value for the object type has not been recognized: %sr   r   r
   zcorpus type not recognizedc                    s:   | d ko8t | d  ko8| d o8| d  kS )Nr<   r?   r@   )rD   splitmatch)xr@   patternr<   rJ   r   r   <lambda>   s    zextract_rels.<locals>.<lambda>)	
NE_CLASSESr   
ValueErrorr8   textheadlinerN   listfilter)	r<   r@   doccorpusrT   rJ   rI   ZreldictsZ	relfilterr   rS   r   extract_rels   s,    


r^   c                 C   sr   t | d | d | d t | d | d g}d}|rH| d g| }d| }|rb|| d	  |d
 }t|}|| S )zy
    Pretty print the reldict as an rtuple.
    :param reldict: a relation dictionary
    :type reldict: defaultdict
    r<   r=   r?   r@   rA   z[%s: %r] %r [%s: %r]r;   z...%r)rC   z(%r...)r   r6   tuple)rM   r;   rC   itemsformatZ	printargsr   r   r   rtuple  s    

rb   c                 C   s   || d | d f}d| S )z
    Print the relation in clausal form.
    :param reldict: a relation dictionary
    :type reldict: defaultdict
    :param relsym: a label for the relation
    :type relsym: str
    r>   rB   z
%s(%r, %r)r   )rM   relsymr`   r   r   r   clause  s    rd   Tc                 C   s~  ddl m} |r`z(ddl}|d}| }|d W n& tk
r^   ddl}|d Y nX t	
d}t  td td	 | D ]}||D ]}	| rt|	j td
 tdd|	d|dD ]\}
tt|
dd |rz,|
d |
d |	jf}|d| |  W q tk
r   Y qX qqq|rzz8|d t  td td |D ]}t| qPW n tk
rx   Y nX dS )a.  
    Select pairs of organizations and locations whose mentions occur with an
    intervening occurrence of the preposition "in".

    If the sql parameter is set to True, then the entity pairs are loaded into
    an in-memory database, and subsequently pulled out using an SQL "SELECT"
    query.
    r   r
   Nz:memory:zPcreate table Locations
            (OrgName text, LocationName text, DocID text)z/Cannot import sqlite; sql flag will be ignored.z.*\bin\b(?!\b.+ing)z'IEER: in(ORG, LOC) -- just the clauses:-============================================================r	   r   r
   r]   rT   INrc   r=   rA   zJinsert into Locations
                                    values (?, ?, ?)zTselect OrgName from Locations
                        where LocationName = 'Atlanta'z,Extract data from SQL table: ORGs in Atlantaz---------------)nltk.corpusr
   sqlite3connectcursorexecuteImportErrorwarningswarnr,   r-   rH   fileidsparsed_docsdocnor^   rd   commit	NameError)rK   sqlr
   rl   
connectioncurrq   ri   filer\   relrb   rowr   r   r   in_demo2  sZ    	


r~   c           	   	   C   s   ddl m} d}t|tj}t  td td | D ]d}||D ]T}d }}| rtt|j td d }}t	d	d
|d|dD ]}tt
|||d qqJq<d S )Nr   re   a  
    (.*(                   # assorted roles
    analyst|
    chair(wo)?man|
    commissioner|
    counsel|
    director|
    economist|
    editor|
    executive|
    foreman|
    governor|
    head|
    lawyer|
    leader|
    librarian).*)|
    manager|
    partner|
    president|
    producer|
    professor|
    researcher|
    spokes(wo)?man|
    writer|
    ,\sof\sthe?\s*  # "X, of (the) Y"
    z(IEER: has_role(PER, ORG) -- raw rtuples:rf   Frg   Tr   r	   r
   rh   r;   rC   )rk   r
   r,   r-   VERBOSErH   rs   rt   ru   r^   rb   )	rK   r
   ZrolesZROLESr{   r\   r;   rC   r|   r   r   r   
roles_demoy  s    
r   c                     sf   ddl m  ddlm}  td td  fdd  D }|d d D ]}t  td	|  qJd S )
Nr   re   r2   zIEER: First 20 Headlinesrf   c                    s(   g | ] }  |D ]}|j|jfqqS r   )rt   ru   rY   )r   r{   r\   re   r   r   
<listcomp>  s    z"ieer_headlines.<locals>.<listcomp>   z%s:
%s)rk   r
   r4   r3   rH   rs   )r3   Ztreesr7   r   re   r   ieer_headlines  s    
r   r#   c              	   C   s   ddl m} d}t|tj}t  td td |dD ]D}d }}| rVd }}td	d
|d|ddD ]}tt|||d qjq>dS )zh
    Find the copula+'van' relation ('of') in the Dutch tagged training corpus
    from CoNLL 2002.
    r   r   z
    (
    is/V|    # 3rd sing present and
    was/V|   # past forms of the verb zijn ('be')
    werd/V|  # and also present
    wordt/V  # past of worden ('become)
    )
    .*       # followed by anything
    van/Prep # followed by van ('of')
    z;Dutch CoNLL2002: van(PER, ORG) -- raw rtuples with context:rf   z	ned.trainFTr   r	   r   rO   r]   rT   rJ   r   N)	rk   r   r,   r-   r   rH   chunked_sentsr^   rb   )rK   r   ZvnvZVANr\   r;   rC   r|   r   r   r   conllned  s&    
     
r   c                     sx   ddl m}  d}t|tj t  td td  fdd| dD }|d d	 D ]}tt|d
d qXt  d S )Nr   r   z.
    .*
    (
    de/SP|
    del/SP
    )
    z=Spanish CoNLL2002: de(ORG, LOC) -- just the first 10 clauses:rf   c              	      s(   g | ] }t d d|d dD ]}|qqS )r	   r   r   rh   )r^   )r   r\   r|   DEr   r   r     s    zconllesp.<locals>.<listcomp>z	esp.trainrO   r   rj   )rk   r   r,   r-   r   rH   r   rd   )r   derelsrr   r   r   conllesp  s    
r   c               	   C   s   t   t d t d td} g }ttjj d d D ]F\}}t|}t	dd|d| dd	}|D ]}t |d
t
|  qfq<d S )NzB1500 Sentences from Penn Treebank, as processed by NLTK NE Chunkerrf   zC.*(chairman|president|trader|scientist|economist|analyst|partner).*i  r   r	   r      r   z<5)rH   r,   r-   	enumeratenltkr]   ZtreebankZtagged_sentsZne_chunkr^   rb   )ZROLEr   isentr|   r   r   r   
ne_chunked  s     
r   __main__)
relextract)rK   )r   F)r9   F)r   NrO   )FF)r   T)r   )r#   )__doc__htmlr,   collectionsr   rV   dictr   r   r   r   r"   entities
entitydefsr&   r1   r8   rN   r^   rb   rd   r~   r   r   r   r   r   __name__r   Znltk.semr   r   r   r   r   <module>   sl   

(
=

G
3
'


