
    g                        d Z ddlZddlZddlZddlZddlZddl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mZ ddlmZmZmZ d	Zd3d
Zd4dZd Zd Zd Zd Zd Zd Zd Zd Zd Z d Z!d5dZ"d Z#d Z$d Z%d Z&d Z'd Z( G d de)      Z* G d d e+      Z, G d! d"e-      Z. G d# d$      Z/ G d% d&e,      Z0 G d' d(e-      Z1 G d) d*e      Z2 G d+ d,e      Z3 G d- d.e      Z4 G d/ d0e      Z5d1 Z6e7d2k(  r e6        yy)6z8
Corpus reader for the FrameNet 1.7 lexicon and corpus.
    N)OrderedDictdefaultdict)zip_longest)
itemgetter)pprint)XMLCorpusReaderXMLCorpusView)LazyConcatenationLazyIteratorListLazyMapz
epytext enc              +      K   t        j                  | d   d      j                  d       fd}| dd D ]  }t         ||              yw)zy
    Wrap the first of 'lines' with textwrap and the remaining lines at exactly the same
    positions as the first.
    r   Fdrop_whitespace
c              3     K   d}| rN|t              dz
  k  r=| d t        |           | t        |         d  } |dz  }| r|t              dz
  k  r=| r0t        j                  | d      j                  d      E d {    y y 7 w)Nr      Fr   r   )lentextwrapfillsplit)lineil0l0wrap_ats     P/var/www/openai/venv/lib/python3.12/site-packages/nltk/corpus/reader/framenet.py_zmimic_wrap.<locals>._'   s     sSWq[(~RW&&BsG'D1HC sSWq[( }}T7EJPPQUVVV Vs   AB,BB	Br   N)r   r   r   list)linesr   kwargsr   lr   s    `   @r   
mimic_wrapr!      sU     
 
uQx%	@	F	Ft	LB
HW 12Y1Q4j s   AAc                     dj                  t        j                  | |      j                  d      D cg c]  }||z   	 c}      S c c}w )z
    Helper function for pretty-printing a long string.

    :param defstr: The string to be printed.
    :type defstr: str
    :return: A nicely formatted string representation of the long string.
    :rtype: str
    r   )joinr   r   r   )defstrprefixr   r   s       r   _pretty_longstringr&   5   sF     99#+==#A#G#G#MN#M4$#MN Ns   Ac                     d}| D ]f  }t        | |   t              rBt        | |         dkD  r1|d| dz  }|dj                  t	        | |   d            z  }|dz  }X|d| d	| |    dz  }h |S )
z
    Helper function for pretty-printing any AttrDict object.

    :param obj: The obj to be printed.
    :type obj: AttrDict
    :return: A nicely formatted string representation of the AttrDict object.
    :rtype: str
     A   [z]
z{}  r%   r   ] )
isinstancestrr   formatr&   )objoutstrks      r   _pretty_anyr4   C   s     Fc!fc"s3q6{R'7!Cj Fdkk"4SVD"IJJFdNF!Bs1vhb))F  M    c                    | j                         }t        |      dk(  ryd}|dj                  |       z  }d|v r|d| j                   dz  }d|v r|d	z  }|t	        | j
                  d
      z  }|d| j                  j                   d| j                  j                   dz  }| j                  |dz  }n4|d| j                  j                   d| j                  j                   dz  }|dt        | j                         dz  }|d
dj                  d | j                  D              z   dt        | j                        dkD  z  z   z  }|S )z
    Helper function for pretty-printing a semantic type.

    :param st: The semantic type to be printed.
    :type st: AttrDict
    :return: A nicely formatted string representation of the semantic type.
    :rtype: str
    r   z<None>r(   z!semantic type ({0.ID}): {0.name}
abbrev	[abbrev] r   
definition[definition]
r+   z[rootType] ()
z[superType] <None>
z[superType] z[subTypes] z
 subtypes
, c              3   T   K   | ]   }|j                    d |j                   d " ywr;   )NnameID.0xs     r   	<genexpr>z"_pretty_semtype.<locals>.<genexpr>v   s&     =AqvvhavQ'   &(r   )keysr   r0   r7   r&   r9   rootTyperB   rC   	superTypesubTypesr#   )stsemkeysr2   s      r   _pretty_semtyperO   Y   sW    ggiG
7|qF
299"==F7Ibii[++w""$R]]D99
BKK,,-Qr{{~~.>cBBF	||((L!2!2 31R\\__4ESII
C,-[99F

))==
=	>
#bkk"Q&
'	(F
 Mr5   c                 (    dj                  |       }|S )z
    Helper function for pretty-printing a frame relation type.

    :param freltyp: The frame relation type to be printed.
    :type freltyp: AttrDict
    :return: A nicely formatted string representation of the frame relation type.
    :rtype: str
    zR<frame relation type ({0.ID}): {0.superFrameName} -- {0.name} -> {0.subFrameName}>r0   )freltypr2   s     r   _pretty_frame_relation_typerS   |   s     bhhF Mr5   c                 (    dj                  |       }|S )z
    Helper function for pretty-printing a frame relation.

    :param frel: The frame relation to be printed.
    :type frel: AttrDict
    :return: A nicely formatted string representation of the frame relation.
    :rtype: str
    zg<{0.type.superFrameName}={0.superFrameName} -- {0.type.name} -> {0.type.subFrameName}={0.subFrameName}>rQ   )frelr2   s     r   _pretty_frame_relationrV      s     w}}F Mr5   c                 (    dj                  |       }|S )z
    Helper function for pretty-printing an FE relation.

    :param ferel: The FE relation to be printed.
    :type ferel: AttrDict
    :return: A nicely formatted string representation of the FE relation.
    :rtype: str
    z<{0.type.superFrameName}={0.frameRelation.superFrameName}.{0.superFEName} -- {0.type.name} -> {0.type.subFrameName}={0.frameRelation.subFrameName}.{0.subFEName}>rQ   )ferelr2   s     r   _pretty_fe_relationrY      s%     q  x  xF Mr5   c                    | j                         }d}|dj                  |       z  }d|v r|dz  }|t        | j                  d      z  }d|v r4|d| j                  j
                   d| j                  j                   d	z  }d
|v r|d| j                   dz  }d|v r|d| j                   dz  }d|v r|d| j                   dz  }d|v r|d| j                   dz  }d|v r4|dj                  dj                  d | j                  D                    z  }d|v ry|dt        | j                         dz  }|dt        | j                        dkD  z  dj                  d | j                  D              z   dt        | j                        dkD  z  z   z  }d|v r|d| j                   dz  }d |v r| j                   D cg c]  }|j
                   }}|d!t        | j                          d"z  }t#        j$                  dj                  t'        |            d#      j)                  d      D ]  }|d| dz  } d$|v r'|d%j                  t        | j*                              z  }|S c c}w )&z
    Helper function for pretty-printing a lexical unit.

    :param lu: The lu to be printed.
    :type lu: AttrDict
    :return: A nicely formatted string representation of the lexical unit.
    :rtype: str
    r(   z!lexical unit ({0.ID}): {0.name}

r9   r:   r+   framez	
[frame] r;   r<   incorporatedFEz
[incorporatedFE] r   POS
[POS] status

[status] totalAnnotatedz
[totalAnnotated] z annotated examples
lexemesz
[lexemes] {}
 c              3   R   K   | ]  }|j                    d |j                    ! yw)/N)rB   r]   )rE   lexs     r   rG   z_pretty_lu.<locals>.<genexpr>   s$     C
z377),
s   %'semTypesz
[semTypes]  semantic types
r   r=   c              3   T   K   | ]   }|j                    d |j                   d " ywr?   rA   rD   s     r   rG   z_pretty_lu.<locals>.<genexpr>   s&     A[166(!ADD6+[rH   URLz
[URL] 	subCorpusz
[subCorpus] z subcorpora
<   	exemplarsz0
[exemplars] {} sentences across all subcorpora
)rI   r0   r&   r9   r[   rB   rC   r\   r]   r_   ra   r#   rb   r   rg   rj   rk   r   r   sortedr   rm   )lulukeysr2   rF   subcr   s         r   
_pretty_lurr      s    WWYFF
3::2>>Fv""$R]]D99&Jrxx}}oQrxx{{m3??6!'(9(9':"==HRVVHB''6K		{"--6!'(9(9'::OPPF$++HHC

CC
 	
 VM#bkk"2!33DEEC$q()iiAR[[AABc"++&*+,	

 HRVVHB''f "-1-N3r||#4"5]CCMM$))F4L"92>DDTJD4&m#F KfFMM
 	
 M .s   ;I$c                     d}|dj                  |      z  }t        |       D ]  \  }}|d| d|j                   dz  } |dz  }|S )a
  
    Helper function for pretty-printing a list of exemplar sentences for a lexical unit.

    :param sent: The list of exemplar sentences to be printed.
    :type sent: list(AttrDict)
    :return: An index of the text of the exemplar sentences.
    :rtype: str
    r(   z4exemplar sentences for {0.name} in {0.frame.name}:

r*   r-   r   )r0   	enumeratetext)rm   ro   r2   isents        r   _pretty_exemplarsrx      s]     F
FMMbQQFY'4AaS499+R(( (
dNFMr5   c                     d}|dj                  |       z  }|dj                  |       z  }|dz  }t        | j                        D ]  \  }}|d| d|j                   dz  } |dz  }|S )z
    Helper function for pretty-printing a list of annotated sentences for a full-text document.

    :param sent: The list of sentences to be printed.
    :type sent: list(AttrDict)
    :return: An index of the text of the sentences.
    :rtype: str
    r(   z'full-text document ({0.ID}) {0.name}:

zY[corpid] {0.corpid}
[corpname] {0.corpname}
[description] {0.description}
[URL] {0.URL}

z[sentence]
r*   r-   r   )r0   rt   sentenceru   )sentsr2   rv   rw   s       r   _pretty_fulltext_sentencesr|      s     F
9@@GGF
nuu F FU^^,4AaS499+R(( -
dNFMr5   c                 (   d}|dj                  | | j                  j                  d| j                  j                              z  }|dt	        | j
                         dz  }|d| j                   dz  }|dz  }|| j                         z  }|d	z  }|S )
a  
    Helper function for pretty-printing an annotated sentence from a full-text document.

    :param sent: The sentence to be printed.
    :type sent: list(AttrDict)
    :return: The text of the sentence with annotation set indices on frame targets.
    :rtype: str
    r(   z%full-text sentence ({0.ID}) in {1}:

rB   r^    tags

[POS_tagset] 

z[text] + [annotationSet]

r   )r0   docgetdescriptionr   r]   
POS_tagset_ascii)rw   r2   s     r   _pretty_fulltext_sentencer     s     F
7>>dhhll6488#7#78 F TXXw//F
055F
,,F
dkkmF
dNFMr5   c                    d}|dj                  |       z  }t        | j                        }| j                  }|j                  }d}d}d}d}|D ]  \  }	}
}|	|k\  sJ d|	|
|ff       |d|	|z
  z  d|
|	z
  z  z   z  }t        |      |
|	z
  kD  rDt        |      |
|	z
  z
  }|d|
|z    d|z  z   ||
|z   d z   }|d|
|z    d|z  z   ||
|z   d z   }||z  }|d|	|z
  z  |j                  |
|	z
        z   z  }|
} |||g}|d	j                  t        d
j                  t        t        |      ddi            j                  dd      z  }|d
z  }|S )z
    Helper function for pretty-printing a sentence with its POS tags.

    :param aset: The POS annotation set of the sentence to be printed.
    :type sent: list(AttrDict)
    :return: The text of the sentence and its POS tags.
    :rtype: str
    r(   zEPOS annotation set ({0.ID}) {0.POS_tagset} in sentence {0.sent.ID}:

r   Overlapping targets?rc   -N~r   r   	fillvalue)r0   rn   r]   rw   ru   r   ljustr#   mapr   r!   replace)asetr2   overtrw   s0s1s2rv   adjustjr3   lblamt
long_liness                 r   _pretty_posr     s    F
W^^ F
 488E99D	B	B	B	AF	1cAv<.As<<v
cQUmcQUm++s8q1uc(a!e$C<QZ 39,r!f*,/??  La&j!C#I-1v:<0@@BcMF
cQUmciiA...  b"J
fkkDII{Jz$:JcJKgc3F dNFMr5   c           
      2   | j                         }|rdnd}|d| j                   dz  }|r|d| j                   dz  }dD ]  }||v s|d| d	| |    dz  } || j                  rd
j	                  | j                        ndz  }|dj	                  | j
                        z  }|sV|dj	                  t        | j                              z  }|dt        | j                         dz  }|d| j                   dz  }|dj	                  t        | j                        t        | j                        dk7  rdnd      z  }|dj	                  t        | j                        t        | j                        dk7  rdnd      z  }	 dD ]B  }|| v s| |   s|dj	                  |t        | |         t        | |         dk7  rdnd      z  }D |dz  }dD ]  }|| v s| |   s|d| dz  } d|v r|dz  }d |v r|d!z  }|d"z  }|| j                         z  }|dz  }|S )#a  
    Helper function for pretty-printing an exemplar sentence for a lexical unit.

    :param sent: An annotation set or exemplar sentence to be printed.
    :param aset_level: If True, 'sent' is actually an annotation set within a sentence.
    :type sent: AttrDict
    :return: A nicely formatted string representation of the exemplar sentence
    with its target, frame, and FE annotations.
    :rtype: str
    zannotation setzexemplar sentence (z):
r`   r   )corpIDdocIDparagNosentNoaPosr*   r-   z*
[LU] ({0.ID}) {0.name} in {0.frame.name}
z
[LU] Not found!z
[frame] ({0.ID}) {0.name}
z$
[annotationSet] {} annotation sets
r^   r~   r   z
[GF] {} relation{}
r   sr(   z
[PT] {} phrase{}
)NERWSLOtherSentz
[{}] {} entr{}
iesyz
[text] + [Target] + [FE]VerbNounAdjAdvPrepSconArtz + []FE2z + [FE2]FE3z + [FE3]r   )rI   rC   r_   LUr0   r[   r   annotationSetr]   r   GFPTr   )rw   
aset_levelsentkeysr2   r3   lyrs         r   _pretty_annotationr   J  sq    yy{H!+1DF
477)4  FK}B//==!BtAwir**F > 77 	7==dggF F
 -44

 F :AA""#
 	
 	HS]O733ODOO#4B77
&--DGGS\Q.cB F $++DGGS\Q.cB F&N /$;49*11Sc^c$s)n.AUs F /
 **F E$;49SEm#F E *Hj F
fF
dkkmF
dNFMr5   c                     | j                   dk(  sd| v r#t        | j                        dkD  rt        |       S t	        |       S )ar  
    Given a sentence or FE annotation set, construct the width-limited string showing
    an ASCII visualization of the sentence's annotations, calling either
    _annotation_ascii_frames() or _annotation_ascii_FEs() as appropriate.
    This will be attached as a method to appropriate AttrDict instances
    and called in the full pretty-printing of the instance.
    fulltext_sentencer      )_typer   r   _annotation_ascii_frames_annotation_ascii_FEs)rw   s    r   _annotation_asciir     sC     zz((4C(:(:$;a$? (--$T**r5   c           
         g }t        | j                  dd       D ]  \  }}|j                  D ]  \  }}d|dz    d}|j                  dk(  s|j                  j                  dk(  r7|dz  }|j                  dk(  r|dz  }|j                  j                  dk(  r|d	z  }|j                  |||j                  j                  j                  |f         t        |      }t               }t        |      D ]  \  }\  }}}	}
|d
kD  s|||dz
     d   k  s ||dz
     dd ||fk(  re||dz
     d   |	k(  rW||dz
     d   |
z   }|j                  dd      j                  dd      }||dz
     dd |fz   ||dz
  <   |j                  |       | j                  }|D ](  \  }}}	}
|d|
z   dz   | j                  || z   dz   |	z   z  }* |dz  }|c S  t        t        |            D ]  }||=  | j                  }d}d}d}d
}d
}t               }|D ]R  \  }}}	}
||k\  s5||k\  s0J dt        d | j                  dd D              rdndz   |||
ff       |d||z
  z  d||z
  z  z   z  }|	d||z
   }||z
  t!        |	      k  r5d
}||v r*||   |	k(  rn&|dz  }|	d||z
  dz
   t#        |      z   }||v r*|	||<   |d||z
  z  |j%                  ||z
        z   z  }t!        |
      ||z
  kD  r[t!        |
      ||z
  z
  }|d||z    d|z  z   |||z   d z   }|d||z    d|z  z   |||z   d z   }|d||z    d|z  z   |||z   d z   }||z  }|d||z
  z  |
j%                  ||z
        z   z  }|}U ||||g}dj'                  t)        dj&                  t+        t-        |      ddi            j                  dd      }|dz  }|rV|ddj'                  d |j/                         D              z   dz   z  }t!        |      t!        t1        |            k(  sJ d        |S )!a!  
    ASCII string rendering of the sentence along with its targets and frame names.
    Called for all full-text sentences, as well as the few LU sentences with multiple
    targets (e.g., fn.lu(6412).exemplars[82] has two want.v targets).
    Line-wrapped to limit the display width.
    r   Nr*   r   UNANNProblemrc   !?r   r      z !z! z ?z? r   z :: zG
(Unable to display sentence with targets marked inline due to overlap)r(   r   c              3   :   K   | ]  }|j                   d k(    yw)r   N)r_   )rE   r   s     r   rG   z+_annotation_ascii_frames.<locals>.<genexpr>  s     U>Td4;;'1>Ts   z UNANN*r   r   r   r   r=   c              3   >   K   | ]  }d j                  |        yw=Nr#   rE   pairs     r   rG   z+_annotation_ascii_frames.<locals>.<genexpr>  s     "O>Nd388D>>N   r@   Abbreviation clash)rt   r   Targetr_   r   appendr[   rB   rn   setr   addru   reversedr   anyr   r/   r   r#   r   r   r!   itemsdict)rw   r   ar   r   r3   indexS
duplicatesofname	asetIndexcombinedIndexr   r   r   s11r   rv   r   fAbbrevsshortrr   r   r2   s                            r   r   r     s    ET//344KKDAqQq\F{{g%9)D#;;')cMF77>>Y.cMFLL!Q 2 2F;<   5 5MEJ'0'7##Aq%q5Q%A,q/) a!eRa QF*uQU|A%/G !a%LOi/  !. 5 5dD A I I$PT U$QU|BQ/=2BBa!eq!II.3*Aq%	)C/$))Aa.@6IEQQA /4__' (8( fZ()!H * 
B	B
C	B	AF}H"'1eYAv6 & Ud>P>PQRQS>TUU 	 Ay! 6 	cQUmcQUm++gAESZA8#E?e+QkA	*SV3	 8# #(sa!e}u{{1q5111y>QU#i.AE*C<QZ 39,r!f*,/??  La&j!C#I-1v:<0@@BlF
#cCi/#a&jl2CCCcMF
cQUmiooa!e444C #(F b#r"J[[DII{Jz$:JcJKgc3  dNF$"Ohnn>N"OOORUUU8}DN 33I5II3Mr5   c           	         d}d}d}| D ]  \  }}}|d||z
  z  |j                         rdnd||z
  z  z   z  }|d||z
   }	t        |      t        |	      kD  r5d}
|	|v r*||	   |k(  rn&|
dz  }
|d||z
  dz
   t        |
      z   }	|	|v r*|||	<   |d||z
  z  |	j                  ||z
        z   z  }|} d}|r8|dd	j	                  d
 t        |j                               D              z   dz   z  }|||gS )z#Helper for _annotation_ascii_FEs().r(   r   rc   ^r   Nr   z [r=   c              3   >   K   | ]  }d j                  |        yw):Nr   rD   s     r   rG   z-_annotation_ascii_FE_layer.<locals>.<genexpr>;  s     H5G5Gr   r   )islowerr   r/   r   r#   rn   r   )r   ni	feAbbrevsr   r   rv   r   r3   fenamer   r   sNIs               r   _annotation_ascii_FE_layerr   %  s1   	B	B	A1f
cQUmfnn&6sCAEJJJwQv;U#A9$U#v-Q{Q+c!f4	 9$ $*	% 
cQUmekk!a%000  C	tdiiHVBHHJ5GHHH3NNC=r5   c           
         t               }g }d}dD ]w  }|| v s| |   s| |   D ]b  \  }|dk(  rt        fd| j                  d   D              rd}|j                  |j	                         j                  dd      f       d y |rt        |i |      }t        t        | j                  d   |s|ng z         | j                  d	   |      }d
x}}	d| v rRt        | j                  d   | j                  d	   |      }d| v r't        | j                  d   | j                  d	   |      }	| j                  D ]  \  }
}|\  }}}t        |      |k  r|d|t        |      z
  z  z  }t        |      |k  r|d|t        |      z
  z  z  }||d	<   |d
|
 ||
| j                  dd      j                  dd      z   ||d
 z   |d<    | j                  g}|r|j                  d
d        |j                  |d   |d	   |d   z   g       |r@|j                  |d   |d	   |d   z   g       |	r|j                  |	d   |	d	   |	d   z   g       |j                  d       dj                  t        dj                  t!        t#        |      ddi            }|rV|ddj                  d |j%                         D              z   dz   z  }t        |      t        t'        |            k(  sJ d       |dz  }|S )a  
    ASCII string rendering of the sentence along with a single target and its FEs.
    Secondary and tertiary FE layers are included if present.
    'sent' can be an FE annotation set or an LU sentence with a single target.
    Line-wrapped to limit the display width.
    Fr   Xc              3   b   K   | ]&  \  }}}|cxk  r|k  sn |cxk  rk  s n nd  ( yw)r   N )rE   rF   r   felblr   bs       r   rG   z(_annotation_ascii_FEs.<locals>.<genexpr>Q  s-     SJ[Q5!q*1*Q
QR
qJs   !/
/r   Tr   r(   r   Nr   r   rc   r   r   r   r   r   r;   r=   c              3   >   K   | ]  }d j                  |        ywr   r   r   s     r   rG   z(_annotation_ascii_FEs.<locals>.<genexpr>}  s     !O=NT#((4.=Nr   r@   r   )r   r   FEr   lowerr   r   rn   r   r   r   r   ru   extendr#   r   r   r!   r   r   )rw   r   posspecposspec_separater   r   POSSPECFE1r   r   rv   r   FE1spanFE1nameFE1expr   r2   r   r   s                    @@r   r   r   ?  s    IGD$;49!#Y	1c3J SDGGAJSS  % 399;..sB78 ' E  ,Wb)D
$twwqz,<W"EF
C
 C#}(!dhhqk9MD=,TXXa[$((1+yQC1#& &w<!sa#g,.//Gw<!sa#g,.//GCFBQK'!A,..sC8@@cJJWUVUW[X 	A  ))J'"1+&s1vs1vA/0
3q63q6CF?34s1vs1vA78bYYDII{Jz$:JcJKF #		!OY__=N!OOORUUU9~T)_!55K7KK5
dNFMr5   c                    | j                         }d}|dj                  | | j                        z  }d|v r|dz  }|t        | j                  d      z  }d|v r|d| j
                   dz  }d	|v r|d
| j                   dz  }d|v rJ|dz  }| j                  |dz  }n3|| j                  j                   d| j                  j                   dz  }d|v rJ|dz  }| j                  |dz  }n3|| j                  j                   d| j                  j                   dz  }d|v rQ|dz  }| j                  |dz  }|S |d| j                  j                   d| j                  j                   dz   dz   z  }|S )z
    Helper function for pretty-printing a frame element.

    :param fe: The frame element to be printed.
    :type fe: AttrDict
    :return: A nicely formatted string representation of the frame element.
    :rtype: str
    r(   z9frame element ({0.ID}): {0.name}
    of {1.name}({1.ID})
r9   r:   r+   r7   r8   r   coreTypez[coreType] 
requiresFEz[requiresFE] z<None>
r;   r<   
excludesFEz[excludesFE] semTypez
[semType] 
  r@   )rI   r0   r[   r&   r9   r7   r  r  rB   rC   r  r  )fefekeysr2   s      r   
_pretty_fer    s    WWYFF
KRR
BHH F v""$R]]D996Ibii[++VK}B//v/!== j F++,Abmm.>.>-?sCCFv/!== j F++,Abmm.>.>-?sCCFF,::j F M f"**//!2!BJJMM?!DDtKKFMr5   c                 4   d}|dj                  |       z  }|d| j                   dz  }|dz  }|t        | j                  d      dz   z  }|dt	        | j
                         d	z  }|dt	        | j
                        d
kD  z  dj                  d | j
                  D              z   dt	        | j
                        d
kD  z  z   z  }|dj                  t	        | j                              z  }|ddj                  d | j                  D              z   dz   z  }|dt	        | j                         dz  }g }t        | j                  j                               D ](  \  }}| d|j                   d}|j                  |       * |dj                  t        dj                  |      d            z  }|dt	        | j                         dz  }i }t        | j                  j                               D ]4  \  }}	 ||j                     j                  | d|j                   d       6 t        |j!                         d       D ]2  }	|dj                  |	dj                  t        ||	                     z  }4 |dj                  t	        | j"                              z  }|ddj                  d | j"                  D              z   dz   z  }|S # t        $ rA g ||j                  <   ||j                     j                  | d|j                   d       Y %w xY w)z
    Helper function for pretty-printing a frame.

    :param frame: The frame to be printed.
    :type frame: AttrDict
    :return: A nicely formatted string representation of the frame.
    :rtype: str
    r(   zframe ({0.ID}): {0.name}

z[URL] r   r:   r+   r   z[semTypes] rh   r   r=   c              3   T   K   | ]   }|j                    d |j                   d " ywr?   rA   rD   s     r   rG   z _pretty_frame.<locals>.<genexpr>  s&     @AqvvhavQ'rH   z%
[frameRelations] {} frame relations
r  c              3   2   K   | ]  }t        |        y wN)repr)rE   rU   s     r   rG   z _pretty_frame.<locals>.<genexpr>  s      M8Ld8Ls   z
[lexUnit] z lexical units
r   r@   z{}
r,   z
[FE] z frame elements
c                 (    g dj                  |       S )N)CorezCore-Unexpressed
PeripheralzExtra-Thematic)index)ct2s    r   <lambda>z_pretty_frame.<locals>.<lambda>  s     

 %*r5   keyz{:>16}: {}
z)
[FEcoreSets] {} frame element core sets
c              3   x   K   | ]-  }d j                  |D cg c]  }|j                   c}       / yc c}w w)r=   N)r#   rB   )rE   coreSetrF   s      r   rG   z _pretty_frame.<locals>.<genexpr>  s4      
@PWDIIw/w!qvvw/0@P/s   :5
:)r0   rj   r&   r9   r   rg   r#   frameRelationslexUnitrn   r   rC   r   r   r  KeyErrorrI   
FEcoreSets)
r[   r2   lustrsluNamero   tmpstrfesfeNamer  cts
             r   _pretty_framer"    s    F
,33E::F
uyyk&&F
F
 !1!1484??F
C/00ABBF
ENN#a'(
))@@
@	A
#enn%)
*	+F 7>>E  ! F dV[[ M8L8L MMMPTTTF
S/00@AAFFU]]0023
82beeWA&f 4 fmm.tyy/@NOOF
EHH&788F
CUXX^^-.
	;##vhbq$9: / 
 	.''DIIfSWo,FGG ;BBE F 
++ 
@E@P@P
 
	
 		F M3  	;!C##vhbq$9:	;s   8.KALLc                       e Zd ZdZy)FramenetErrorz/An exception class for framenet-related errors.N)__name__
__module____qualname____doc__r   r5   r   r$  r$    s    9r5   r$  c                   P     e Zd ZdZ fdZd Zd Z fdZd Zd Z	d Z
d	 Z xZS )
AttrDicta  A class that wraps a dict and allows accessing the keys of the
    dict as if they were attributes. Taken from here:
    https://stackoverflow.com/a/14620633/8879

    >>> foo = {'a':1, 'b':2, 'c':3}
    >>> bar = AttrDict(foo)
    >>> pprint(dict(bar))
    {'a': 1, 'b': 2, 'c': 3}
    >>> bar.b
    2
    >>> bar.d = 4
    >>> pprint(dict(bar))
    {'a': 1, 'b': 2, 'c': 3, 'd': 4}
    c                 $    t        |   |i | y r  )super__init__selfargsr   	__class__s      r   r-  zAttrDict.__init__  s    $)&)r5   c                     || |<   y r  r   )r/  rB   values      r   __setattr__zAttrDict.__setattr__  s    T
r5   c                 .    |dk(  r| j                   S | |   S )N_short_repr)r6  r/  rB   s     r   __getattr__zAttrDict.__getattr__  s     = ###Dzr5   c                 f    t         |   |      }t        |t              r|j	                         S |S r  )r,  __getitem__r.   Future_data)r/  rB   vr1  s      r   r:  zAttrDict.__getitem__  s-    G%a 779r5   c                 N   d| v rA| d   j                  d      r| j                         S 	 dj                  | d   | d   | d         S | j                         S # t        $ rE 	 dj                  | d   | d         cY S # t        $ r dj                  | d   | d         cY cY S w xY ww xY w)Nr   relationz<{} ID={} name={}>rC   rB   z<{} name={}>z
<{} ID={}>)endswith__repr__r0   r  r/  s    r   r6  zAttrDict._short_repr  s    d?G}%%j1}}&J+22M4:tF|  ==?"  JJ)00gVMM J'..tG}d4jIIJJs/   A 	B$ A:7B$:!B B$B  B$c                    d}d| vrt        |       }|S | d   dk(  rt        |       }|S | d   dk(  rt        |       }|S | d   dk(  rt        |       }|S | d   dk(  rt	        | | d   j
                        }|S | d   dk(  rt        |       }|S | d   d	k(  rt        |       }|S | d   d
k(  rt        |       }|S | d   dv rt        | d      }|S | d   dk(  rt        |       }|S | d   dk(  rt        |       }|S | d   dk(  rt        |       }|S | d   dk(  rt        |       }|S | d   dk(  rt        |       }|S t        |       }|S )Nr(   r   r[   r  ro   luexemplarsr   fulltext_annotation
lusentencer   )luannotationsetfulltext_annotationsetT)r   posannotationsetsemtypeframerelationtypeframerelation
ferelation)r4   r"  r  rr   rx   r   r|   r   r   r   rO   rS   rV   rY   r/  r2   s     r   _strzAttrDict._str)  s   $ &FJ I ']g%"4(FF E ']d"%FB A ']d"%F> = ']m+&tT!WZZ8F: 7 M22/5F2 1 ']l*'-F. - ']11.t4F* ) ']KK'>F& % ']00 &F" ! ']i'$T*F  ']1106F  ']o-+D1F  ']l*(.F  !&F r5   c                 "    | j                         S r  rO  rB  s    r   __str__zAttrDict.__str__T      yy{r5   c                 "    | j                         S r  rR  rB  s    r   rA  zAttrDict.__repr__W      ||~r5   )r%  r&  r'  r(  r-  r4  r8  r:  r6  rO  rR  rA  __classcell__r1  s   @r   r*  r*    s1    *
# )Vr5   r*  c                   4     e Zd ZdZ fdZd Zd Zd Z xZS )SpecialListz
    A list subclass which adds a '_type' attribute for special printing
    (similar to an AttrDict, though this is NOT an AttrDict subclass).
    c                 2    t        |   |i | || _        y r  )r,  r-  r   )r/  typr0  r   r1  s       r   r-  zSpecialList.__init__a  s    $)&)
r5   c                     d}| j                   sJ t        |       dk(  rd}|S | j                   dk(  rt        | | d   j                        }|S J | j                          )Nr(   r   z[]rD  )r   r   rx   r   rN  s     r   rO  zSpecialList._stre  sc    zzzt9>F
 	 ZZ=(&tT!WZZ8F  %$**$5r5   c                 "    | j                         S r  rQ  rB  s    r   rR  zSpecialList.__str__q  rS  r5   c                 "    | j                         S r  rU  rB  s    r   rA  zSpecialList.__repr__t  rV  r5   )	r%  r&  r'  r(  r-  rO  rR  rA  rW  rX  s   @r   rZ  rZ  [  s    

r5   rZ  c                   R     e Zd ZdZ fdZd Zd Zd Zd Zd Z	d Z
d	 Zd
 Z xZS )r;  z
    Wraps and acts as a proxy for a value to be loaded lazily (on demand).
    Adapted from https://gist.github.com/sergey-miryanov/2935416
    c                 @    t        |   |i | || _        d| _        y)z}
        :param loader: when called with no arguments, returns the value to be stored
        :type loader: callable
        N)r,  r-  _loader_d)r/  loaderr0  r   r1  s       r   r-  zFuture.__init__~  s%    
 	$)&)r5   c                 |    t        | j                        r| j                         | _        d | _        | j                  S r  )callablerb  rc  rB  s    r   r<  zFuture._data  s+    DLL!llnDGDLwwr5   c                 4    t        | j                               S r  )boolr<  rB  s    r   __nonzero__zFuture.__nonzero__  s    DJJL!!r5   c                 4    t        | j                               S r  )r   r<  rB  s    r   __len__zFuture.__len__  s    4::<  r5   c                 B    | j                         j                  ||      S r  )r<  __setitem__)r/  r  r3  s      r   rm  zFuture.__setitem__  s    zz|''U33r5   c                 @    | j                         j                  |      S r  )r<  r:  r/  r  s     r   r:  zFuture.__getitem__      zz|'',,r5   c                 @    | j                         j                  |      S r  )r<  r8  ro  s     r   r8  zFuture.__getattr__  rp  r5   c                 >    | j                         j                         S r  )r<  rR  rB  s    r   rR  zFuture.__str__  s    zz|##%%r5   c                 >    | j                         j                         S r  )r<  rA  rB  s    r   rA  zFuture.__repr__  s    zz|$$&&r5   )r%  r&  r'  r(  r-  r<  ri  rk  rm  r:  r8  rR  rA  rW  rX  s   @r   r;  r;  x  s5    
"!4--&'r5   r;  c                   (     e Zd ZdZ fdZd Z xZS )
PrettyDictz
    Displays an abbreviated repr of values where possible.
    Inherits from AttrDict, so a callable value will
    be lazily converted to an actual value.
    c                 v    |j                  dd      }t        |   |i | t        j	                  | d|       y )N
breakLinesF_BREAK_LINES)popr,  r-  r   r4  )r/  r0  r   rx  r1  s       r   r-  zPrettyDict.__init__  s7    zz,6$)&)~|<r5   c                 2   g }t        | j                               D ]8  \  }}t        |      dz   }	 ||j                         z  }|j                  |       : d| j                  rdndj                  |      z   dz   S # t        $ r |t        |      z  }Y Qw xY w)Nz: {,
 r=   })rn   r   r  r6  AttributeErrorr   rx  r#   )r/  partsr3   r=  kvs        r   rA  zPrettyDict.__repr__  s    4::<(DAqa4Bammo% LL )  1 1ftAA%HH3NN " d1gs   A<<BBr%  r&  r'  r(  r-  rA  rW  rX  s   @r   ru  ru    s    =
	Or5   ru  c                   (     e Zd ZdZ fdZd Z xZS )
PrettyList^
    Displays an abbreviated repr of only the first several elements, not the whole list.
    c                     |j                  dd      | _        |j                  dd      | _        t        |   |i | y )NmaxReprSizerl   rw  F)ry  _MAX_REPR_SIZErx  r,  r-  r.  s      r   r-  zPrettyList.__init__  s;    $jj;"JJ|U;$)&)r5   c                    g }d}| D ]  }|j                  |j                                |t        |d         dz   z  }| j                  sC|| j                  kD  sSt        |      dkD  sbdt	        | j
                  rdnd      j                  |dd       z  c S  dt	        | j
                  rdnd      j                  |      z  S )	
        Return a string representation for this corpus view that is
        similar to a list's representation; but if it would be more
        than 60 characters long, it is truncated.
           r   	[%s, ...]r|  r=   N[%s])r   r6  r   r  r/   rx  r#   r/  pieceslengthelts       r   rA  zPrettyList.__repr__  s     CMM! c&*o))F""v0C0C'CFVW"S43D3D$%O%T%T3BK&    d&7&7FTBGGOOOr5   r  rX  s   @r   r  r    s    
*
Pr5   r  c                       e Zd ZdZdZd Zy)PrettyLazyMapr  rl   c                    g }d}| D ]l  }|j                  |j                                |t        |d         dz   z  }|| j                  kD  sFt        |      dkD  sUddj	                  |dd       z  c S  ddj	                  |      z  S r  r  r  r   r  r=   Nr  r   r6  r   r  r#   r  s       r   rA  zPrettyLazyMap.__repr__       CMM! c&*o))F+++Fa"TYYvcr{%;;;  		&)))r5   Nr%  r&  r'  r(  r  rA  r   r5   r   r  r        
 N*r5   r  c                       e Zd ZdZdZd Zy)PrettyLazyIteratorListr  rl   c                    g }d}| D ]l  }|j                  |j                                |t        |d         dz   z  }|| j                  kD  sFt        |      dkD  sUddj	                  |dd       z  c S  ddj	                  |      z  S r  r  r  s       r   rA  zPrettyLazyIteratorList.__repr__  r  r5   Nr  r   r5   r   r  r    r  r5   r  c                   &    e Zd ZdZdZd Zd Zd Zy)PrettyLazyConcatenationr  rl   c                    g }d}| D ]l  }|j                  |j                                |t        |d         dz   z  }|| j                  kD  sFt        |      dkD  sUddj	                  |dd       z  c S  ddj	                  |      z  S r  r  r  s       r   rA  z PrettyLazyConcatenation.__repr__  r  r5   c                 @    t        t        j                  | |            S )z,Return a list concatenating self with other.r  	itertoolschainr/  others     r   __add__zPrettyLazyConcatenation.__add__(  s    %ioodE&BCCr5   c                 @    t        t        j                  ||             S )z,Return a list concatenating other with self.r  r  s     r   __radd__z PrettyLazyConcatenation.__radd__,  s    %iooeT&BCCr5   N)r%  r&  r'  r(  r  rA  r  r  r   r5   r   r  r    s    
 N*"DDr5   r  c                      e Zd ZdZdgZ	 dZd Zd Zd?dZd Z	d	 Z
d
 Zd Zd Zd Zd Zg fdZg dfdZg fdZd Zd Zg dddfdZg f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!dAd"Z"dBd#Z#dCd$Z$d?d%Z%d?d&Z&d' Z'dDd(Z(d) Z)d* Z*d+ Z+d, Z,d?d-Z-d?d.Z.g fd/Z/d0 Z0d1 Z1d2 Z2d3 Z3d4 Z4dEd5Z5d6 Z6d7 Z7d8 Z8d9 Z9d: Z:dEd;Z;d< Z<d= Z=d?d>Z>y)FFramenetCorpusReaderaT  A corpus reader for the Framenet Corpus.

    >>> from nltk.corpus import framenet as fn
    >>> fn.lu(3238).frame.lexUnit['glint.v'] is fn.lu(3238)
    True
    >>> fn.frame_by_name('Replacing') is fn.lus('replace.v')[0].frame
    True
    >>> fn.lus('prejudice.n')[0].frame.frameRelations == fn.frame_relations('Partiality')
    True
    r   Fc                     || _         y)a<  Enable or disable warnings of data integrity issues as they are encountered.
        If v is truthy, warnings will be enabled.

        (This is a function rather than just an attribute/property to ensure that if
        enabling warnings is the first action taken, the corpus reader is instantiated first.)
        N)	_warnings)r/  r=  s     r   warningszFramenetCorpusReader.warningsG  s     r5   c                     t        j                  | ||       d| _        d| _        d| _        d| _        d | _        i | _        d | _        d | _	        d | _
        d | _        d | _        d | _        d | _        d| _        y )Nr[   ro   fulltextz2https://framenet2.icsi.berkeley.edu/fnReports/dataz
README.txt)r   r-  
_frame_dir_lu_dir_fulltext_dir
_fnweb_url
_frame_idx_cached_frames_lu_idx_fulltext_idx	_semtypes_freltyp_idx	_frel_idx
_ferel_idx_frel_f_idx_readme)r/  rootfileidss      r   r-  zFramenetCorpusReader.__init__P  s      tW5 "' O  ! #r5   Nc                 V    |t        | j                  |            S d}t        |       y)z6Display help information summarizing the main methods.NaK  
Citation: Nathan Schneider and Chuck Wooters (2017),
"The NLTK FrameNet API: Designing for Discoverability with a Rich Linguistic Resource".
Proceedings of EMNLP: System Demonstrations. https://arxiv.org/abs/1703.07438

Use the following methods to access data in FrameNet.
Provide a method name to `help()` for more information.

FRAMES
======

frame() to look up a frame by its exact name or ID
frames() to get frames matching a name pattern
frames_by_lemma() to get frames containing an LU matching a name pattern
frame_ids_and_names() to get a mapping from frame IDs to names

FRAME ELEMENTS
==============

fes() to get frame elements (a.k.a. roles) matching a name pattern, optionally constrained
  by a frame name pattern

LEXICAL UNITS
=============

lu() to look up an LU by its ID
lus() to get lexical units matching a name pattern, optionally constrained by frame
lu_ids_and_names() to get a mapping from LU IDs to names

RELATIONS
=========

frame_relation_types() to get the different kinds of frame-to-frame relations
  (Inheritance, Subframe, Using, etc.).
frame_relations() to get the relation instances, optionally constrained by
  frame(s) or relation type
fe_relations() to get the frame element pairs belonging to a frame-to-frame relation

SEMANTIC TYPES
==============

semtypes() to get the different kinds of semantic types that can be applied to
  FEs, LUs, and entire frames
semtype() to look up a particular semtype by name, ID, or abbreviation
semtype_inherits() to check whether two semantic types have a subtype-supertype
  relationship in the semtype hierarchy
propagate_semtypes() to apply inference rules that distribute semtypes over relations
  between FEs

ANNOTATIONS
===========

annotations() to get annotation sets, in which a token in a sentence is annotated
  with a lexical unit in a frame, along with its frame elements and their syntactic properties;
  can be constrained by LU name pattern and limited to lexicographic exemplars or full-text.
  Sentences of full-text annotation can have multiple annotation sets.
sents() to get annotated sentences illustrating one or more lexical units
exemplars() to get sentences of lexicographic annotation, most of which have
  just 1 annotation set; can be constrained by LU name pattern, frame, and overt FE(s)
doc() to look up a document of full-text annotation by its ID
docs() to get documents of full-text annotation that match a name pattern
docs_metadata() to get metadata about all full-text documents without loading them
ft_sents() to iterate over sentences of full-text annotation

UTILITIES
=========

buildindexes() loads metadata about all frames, LUs, etc. into memory to avoid
  delay when one is accessed for the first time. It does not load annotations.
readme() gives the text of the FrameNet README file
warnings(True) to display corpus consistency warnings when loading data
        )help__getattribute__print)r/  attrnamemsgs      r   r  zFramenetCorpusReader.helpk  s2     --h788GP 	c
r5   c                     | j                   s| j                          i | _        t        | j	                  d      d| j
                        5 }|D ]  }|| j                  |d   <    	 d d d        y # 1 sw Y   y xY w)NzframeIndex.xmlzframeIndex/framerC   )r  _buildrelationindexr  r	   abspath_handle_elt)r/  viewfs      r   _buildframeindexz%FramenetCorpusReader._buildframeindex  sm     ~~$$&LL)*,>@P@P
+,$( 
 
 
s   
A..A7c                     i | _         t        | j                  d      d| j                        5 }|D ]"  }|D ]  }|| j                   |j                  <    $ 	 d d d        y # 1 sw Y   y xY w)NzfulltextIndex.xmlzfulltextIndex/corpus)r  r	   r  _handle_fulltextindex_eltrC   )r/  r  doclistr   s       r   _buildcorpusindexz&FramenetCorpusReader._buildcorpusindex  sj      LL,-"**
 "C14D&&svv. #  
 
 
s   (A  A)c                     i | _         t        | j                  d      d| j                        5 }|D ]  }|| j                   |d   <    	 d d d        y # 1 sw Y   y xY w)NzluIndex.xmlz
luIndex/lurC   )r  r	   r  r  )r/  r  ro   s      r   _buildluindexz"FramenetCorpusReader._buildluindex  s[     LL't7G7G
 RX& 
 
 
s   AAc           	          i  _         i  _        t        t               _        i  _        t         j                  d      d j                        5 }|D ]z  }| j                   |j                  <   |j                  D ]N  }t          fd|j                              x}x|_        ||j                  <   t          fd|j                              x}x|_        ||j"                  <   | j                  |j                  <    j                  |j                     j%                  |j                          j                  |j                     j%                  |j                         |j&                  D ]W  }||_        ||_        t         d |            |_        t         d |            |_        | j
                  |j                  <   Y Q } 	 d d d        y # 1 sw Y   y xY w)NzfrRelation.xmlz frameRelations/frameRelationTypec                       fdS )Nc                  &    j                         S r  frame_by_idfIDr/  s   r   r  zLFramenetCorpusReader._buildrelationindex.<locals>.<lambda>.<locals>.<lambda>      T-=-=c-Br5   r   r  s   `r   r  z:FramenetCorpusReader._buildrelationindex.<locals>.<lambda>      %Br5   c                       fdS )Nc                  &    j                         S r  r  r  s   r   r  zLFramenetCorpusReader._buildrelationindex.<locals>.<lambda>.<locals>.<lambda>  r  r5   r   r  s   `r   r  z:FramenetCorpusReader._buildrelationindex.<locals>.<lambda>  r  r5   c                       fdS )Nc                  J     j                   j                   j                     S r  )
superFramer   superFENamefers   r   r  zLFramenetCorpusReader._buildrelationindex.<locals>.<lambda>.<locals>.<lambda>  s    1B1B3??1Sr5   r   r  s   `r   r  z:FramenetCorpusReader._buildrelationindex.<locals>.<lambda>  s    )Sr5   c                       fdS )Nc                  J     j                   j                   j                     S r  )subFramer   	subFENamer  s   r   r  zLFramenetCorpusReader._buildrelationindex.<locals>.<lambda>.<locals>.<lambda>  s    1Or5   r   r  s   `r   r  z:FramenetCorpusReader._buildrelationindex.<locals>.<lambda>  s    )Or5   )r  r  r   r   r  r  r	   r  _handle_framerelationtype_eltrC   r  r;  supIDr  superFrameNamesubIDr  subFrameNamer   feRelationssuperFEsubFE)r/  r  rR   rU   supFsubFrX   s   `      r   r  z(FramenetCorpusReader._buildrelationindex  s   &s+LL)*...
 07!!'**-#22DLRBDJJOM D 4?T'2H2H-I IOBDJJOI D 4=40D0D+E /3DNN477+$$TZZ044TWW=$$TZZ044TWW=!%!1!1+/()-(.S %)
 '-OQVW' 5:1 "2 3  
 
 
s   FGG%c                 t    | j                   r,|j                  dt        j                         t	        |i | y y )Nfile)r  
setdefaultsysstderrr  )r/  messager   s      r   _warnzFramenetCorpusReader._warn  s/    >>fcjj17%f% r5   c                     | j                          | j                          | j                          | j                          y)zE
        Build the internal indexes to make look-ups faster.
        N)r  r  r  r  rB  s    r   buildindexesz!FramenetCorpusReader.buildindexes  s4    
 	   "r5   c                    	 | j                   |   j                  }t        j                  j                  | j                   | j                  |      }t        |d      5 }|d   }ddd       | j                        }| j                   |   j                         D ]
  \  }}	|	||<    |S # t        $ r, | j                          | j                   |   j                  }Y t        $ r}t        d|       |d}~ww xY w# 1 sw Y   xY w)a  
        Returns the annotated document whose id number is
        ``fn_docid``. This id number can be obtained by calling the
        Documents() function.

        The dict that is returned from this function will contain the
        following keys:

        - '_type'      : 'fulltextannotation'
        - 'sentence'   : a list of sentences in the document
           - Each item in the list is a dict containing the following keys:
              - 'ID'    : the ID number of the sentence
              - '_type' : 'sentence'
              - 'text'  : the text of the sentence
              - 'paragNo' : the paragraph number
              - 'sentNo'  : the sentence number
              - 'docID'   : the document ID number
              - 'corpID'  : the corpus ID number
              - 'aPos'    : the annotation position
              - 'annotationSet' : a list of annotation layers for the sentence
                 - Each item in the list is a dict containing the following keys:
                    - 'ID'       : the ID number of the annotation set
                    - '_type'    : 'annotationset'
                    - 'status'   : either 'MANUAL' or 'UNANN'
                    - 'luName'   : (only if status is 'MANUAL')
                    - 'luID'     : (only if status is 'MANUAL')
                    - 'frameID'  : (only if status is 'MANUAL')
                    - 'frameName': (only if status is 'MANUAL')
                    - 'layer' : a list of labels for the layer
                       - Each item in the layer is a dict containing the following keys:
                          - '_type': 'layer'
                          - 'rank'
                          - 'name'
                          - 'label' : a list of labels in the layer
                             - Each item is a dict containing the following keys:
                                - 'start'
                                - 'end'
                                - 'name'
                                - 'feID' (optional)

        :param fn_docid: The Framenet id number of the document
        :type fn_docid: int
        :return: Information about the annotated document
        :rtype: dict
        zUnknown document id: NfullTextAnnotationr   )r  filename	TypeErrorr  r  r$  ospathr#   _rootr  r	   _handle_fulltextannotation_eltr   )
r/  fn_docidxmlfnameelocpathr  r  infor3   r=  s
             r   r   zFramenetCorpusReader.doc  s    \	K))(3<<H '',,$**0B0BHM 7$89Tq'C :2237&&x0668DAqDG 9#  	=""$))(3<<H 	K"7z BCJ	K :9s)   B( C;(2C8C8$C33C8;Dc                     	 | j                   |   }d|v r|S |d   }| j                  ||d      S # t        $ r% | j                          | j                   |   d   }Y At        $ r}t	        d|       |d}~ww xY w)a  
        Get the details for the specified Frame using the frame's id
        number.

        Usage examples:

        >>> from nltk.corpus import framenet as fn
        >>> f = fn.frame_by_id(256)
        >>> f.ID
        256
        >>> f.name
        'Medical_specialties'
        >>> f.definition # doctest: +NORMALIZE_WHITESPACE
        "This frame includes words that name medical specialties and is closely related to the
        Medical_professionals frame.  The FE Type characterizing a sub-are in a Specialty may also be
        expressed. 'Ralph practices paediatric oncology.'"

        :param fn_fid: The Framenet id number of the frame
        :type fn_fid: int
        :param ignorekeys: The keys to ignore. These keys will not be
            included in the output. (optional)
        :type ignorekeys: list(str)
        :return: Information about a frame
        :rtype: dict

        Also see the ``frame()`` function for details about what is
        contained in the dict that is returned.
        r   rB   zUnknown frame id: NF)check_cache)r  r  r  r  r$  frame_by_name)r/  fn_fid
ignorekeysfentryrB   r  s         r   r  z FramenetCorpusReader.frame_by_ida  s    >		F__V,F& &>D !!$
!FF  	3!!#??6*62D 	F"4VH =>AE	Fs   0 0 +A9A9%A44A9Tc                   
 |r*|| j                   v r| j                  | j                   |      S | j                  s| j                          t        j                  j                  | j                   | j                  |dz         }	 t        |d      5 }|d   }ddd       | j                  |      }|sJ | j                  dz   | j                  z   dz   |z   dz   |_        |j                  D ]u  

j                  j                   dk(  s|j"                  j%                         D ]<  }	t'        
fd|	j                  D              r"|	j                  j)                  
       > w || j                  |j*                  <   |j*                  | j                   |j                   <   	 |S # 1 sw Y   xY w# t        $ r}t        d|       |d}~ww xY w)	a  
        Get the details for the specified Frame using the frame's name.

        Usage examples:

        >>> from nltk.corpus import framenet as fn
        >>> f = fn.frame_by_name('Medical_specialties')
        >>> f.ID
        256
        >>> f.name
        'Medical_specialties'
        >>> f.definition # doctest: +NORMALIZE_WHITESPACE
         "This frame includes words that name medical specialties and is closely related to the
          Medical_professionals frame.  The FE Type characterizing a sub-are in a Specialty may also be
          expressed. 'Ralph practices paediatric oncology.'"

        :param fn_fname: The name of the frame
        :type fn_fname: str
        :param ignorekeys: The keys to ignore. These keys will not be
            included in the output. (optional)
        :type ignorekeys: list(str)
        :return: Information about a frame
        :rtype: dict

        Also see the ``frame()`` function for details about what is
        contained in the dict that is returned.
        .xmlr[   r   NzUnknown frame: re   Lexical_typec              3   &   K   | ]  }|u  
 y wr  r   )rE   rF   rM   s     r   rG   z5FramenetCorpusReader.frame_by_name.<locals>.<genexpr>  s      )4ARs   )r  r  r  r  r   r#   r  r  r	   OSErrorr$  _handle_frame_eltr  rj   rg   rJ   rB   r  valuesr   r   rC   )r/  fn_fnamer  r	  r  r  r  r  r  ro   rM   s             @r   r
  z"FramenetCorpusReader.frame_by_name  s   : 8t':'::??4#6#6x#@AA!!# '',,$**FARS	Ew0D1g 1
 ''Z8v__s*T__<sBXMPVV
 //B{{>1 ..//1B )+  **2.	 2 " &,		"+199FKK(	 7 10 	E/( <=1D	Es0   F. F!F. !F+&F. .	G7GGc                 r    t        |t              r| j                  ||      }|S | j                  ||      }|S )a  
        Get the details for the specified Frame using the frame's name
        or id number.

        Usage examples:

        >>> from nltk.corpus import framenet as fn
        >>> f = fn.frame(256)
        >>> f.name
        'Medical_specialties'
        >>> f = fn.frame('Medical_specialties')
        >>> f.ID
        256
        >>> # ensure non-ASCII character in definition doesn't trigger an encoding error:
        >>> fn.frame('Imposing_obligation') # doctest: +ELLIPSIS
        frame (1494): Imposing_obligation...


        The dict that is returned from this function will contain the
        following information about the Frame:

        - 'name'       : the name of the Frame (e.g. 'Birth', 'Apply_heat', etc.)
        - 'definition' : textual definition of the Frame
        - 'ID'         : the internal ID number of the Frame
        - 'semTypes'   : a list of semantic types for this frame
           - Each item in the list is a dict containing the following keys:
              - 'name' : can be used with the semtype() function
              - 'ID'   : can be used with the semtype() function

        - 'lexUnit'    : a dict containing all of the LUs for this frame.
                         The keys in this dict are the names of the LUs and
                         the value for each key is itself a dict containing
                         info about the LU (see the lu() function for more info.)

        - 'FE' : a dict containing the Frame Elements that are part of this frame
                 The keys in this dict are the names of the FEs (e.g. 'Body_system')
                 and the values are dicts containing the following keys

              - 'definition' : The definition of the FE
              - 'name'       : The name of the FE e.g. 'Body_system'
              - 'ID'         : The id number
              - '_type'      : 'fe'
              - 'abbrev'     : Abbreviation e.g. 'bod'
              - 'coreType'   : one of "Core", "Peripheral", or "Extra-Thematic"
              - 'semType'    : if not None, a dict with the following two keys:
                 - 'name' : name of the semantic type. can be used with
                            the semtype() function
                 - 'ID'   : id number of the semantic type. can be used with
                            the semtype() function
              - 'requiresFE' : if not None, a dict with the following two keys:
                 - 'name' : the name of another FE in this frame
                 - 'ID'   : the id of the other FE in this frame
              - 'excludesFE' : if not None, a dict with the following two keys:
                 - 'name' : the name of another FE in this frame
                 - 'ID'   : the id of the other FE in this frame

        - 'frameRelation'      : a list of objects describing frame relations
        - 'FEcoreSets'  : a list of Frame Element core sets for this frame
           - Each item in the list is a list of FE objects

        :param fn_fid_or_fname: The Framenet name or id number of the frame
        :type fn_fid_or_fname: int or str
        :param ignorekeys: The keys to ignore. These keys will not be
            included in the output. (optional)
        :type ignorekeys: list(str)
        :return: Information about a frame
        :rtype: dict
        )r.   r/   r
  r  )r/  fn_fid_or_fnamer  r  s       r   r[   zFramenetCorpusReader.frame  sA    N os+""?J?A    *=Ar5   c                 H    t        fd| j                         D              S )a  
        Returns a list of all frames that contain LUs in which the
        ``name`` attribute of the LU matches the given regular expression
        ``pat``. Note that LU names are composed of "lemma.POS", where
        the "lemma" part can be made up of either a single lexeme
        (e.g. 'run') or multiple lexemes (e.g. 'a little').

        Note: if you are going to be doing a lot of this type of
        searching, you'd want to build an index that maps from lemmas to
        frames because each time frames_by_lemma() is called, it has to
        search through ALL of the frame XML files in the db.

        >>> from nltk.corpus import framenet as fn
        >>> from nltk.corpus.reader.framenet import PrettyList
        >>> PrettyList(sorted(fn.frames_by_lemma(r'(?i)a little'), key=itemgetter('ID'))) # doctest: +ELLIPSIS
        [<frame ID=189 name=Quanti...>, <frame ID=2001 name=Degree>]

        :return: A list of frame objects.
        :rtype: list(AttrDict)
        c              3   ^   K   | ]$  }t        fd |j                  D              r| & yw)c              3   J   K   | ]  }t        j                  |        y wr  research)rE   r  pats     r   rG   zAFramenetCorpusReader.frames_by_lemma.<locals>.<genexpr>.<genexpr>7  s     B	f299S&)	s    #N)r   r  )rE   r  r  s     r   rG   z7FramenetCorpusReader.frames_by_lemma.<locals>.<genexpr>4  s+      
"B		BB "s   *-)r  frames)r/  r  s    `r   frames_by_lemmaz$FramenetCorpusReader.frames_by_lemma  s%    *  
[[]
 
 	
r5   c                 ,    | j                  |ddg      S )a  
        Returns basic information about the LU whose id is
        ``fn_luid``. This is basically just a wrapper around the
        ``lu()`` function with "subCorpus" info excluded.

        >>> from nltk.corpus import framenet as fn
        >>> lu = PrettyDict(fn.lu_basic(256), breakLines=True)
        >>> # ellipses account for differences between FN 1.5 and 1.7
        >>> lu # doctest: +ELLIPSIS
        {'ID': 256,
         'POS': 'V',
         'URL': 'https://framenet2.icsi.berkeley.edu/fnReports/data/lu/lu256.xml',
         '_type': 'lu',
         'cBy': ...,
         'cDate': '02/08/2001 01:27:50 PST Thu',
         'definition': 'COD: be aware of beforehand; predict.',
         'definitionMarkup': 'COD: be aware of beforehand; predict.',
         'frame': <frame ID=26 name=Expectation>,
         'lemmaID': 15082,
         'lexemes': [{'POS': 'V', 'breakBefore': 'false', 'headword': 'false', 'name': 'foresee', 'order': 1}],
         'name': 'foresee.v',
         'semTypes': [],
         'sentenceCount': {'annotated': ..., 'total': ...},
         'status': 'FN1_Sent'}

        :param fn_luid: The id number of the desired LU
        :type fn_luid: int
        :return: Basic information about the lexical unit
        :rtype: dict
        rk   rm   )r  ro   )r/  fn_luids     r   lu_basiczFramenetCorpusReader.lu_basic:  s    > wwwK+EwFFr5   c                 n   | j                   s| j                          t               }| j                   j                  ||      }||u r| j	                  dj                  ||||             t        d|||dd      }| j                  |j                        }|j                  |k(  sJ |j                  |f       ||d<   || j                   |<   n.d|vr*| j                  |j                        }| j                   |   }|r2t        |j                         D 	
ci c]  \  }	}
|	|vs|	|
 c}
}	      S |S c c}
}	w )aq  
        Access a lexical unit by its ID. luName, frameID, and frameName are used
        only in the event that the LU does not have a file in the database
        (which is the case for LUs with "Problem" status); in this case,
        a placeholder LU is created which just contains its name, ID, and frame.


        Usage examples:

        >>> from nltk.corpus import framenet as fn
        >>> fn.lu(256).name
        'foresee.v'
        >>> fn.lu(256).definition
        'COD: be aware of beforehand; predict.'
        >>> fn.lu(256).frame.name
        'Expectation'
        >>> list(map(PrettyDict, fn.lu(256).lexemes))
        [{'POS': 'V', 'breakBefore': 'false', 'headword': 'false', 'name': 'foresee', 'order': 1}]

        >>> fn.lu(227).exemplars[23] # doctest: +NORMALIZE_WHITESPACE
        exemplar sentence (352962):
        [sentNo] 0
        [aPos] 59699508
        <BLANKLINE>
        [LU] (227) guess.v in Coming_to_believe
        <BLANKLINE>
        [frame] (23) Coming_to_believe
        <BLANKLINE>
        [annotationSet] 2 annotation sets
        <BLANKLINE>
        [POS] 18 tags
        <BLANKLINE>
        [POS_tagset] BNC
        <BLANKLINE>
        [GF] 3 relations
        <BLANKLINE>
        [PT] 3 phrases
        <BLANKLINE>
        [Other] 1 entry
        <BLANKLINE>
        [text] + [Target] + [FE]
        <BLANKLINE>
        When he was inside the house , Culley noticed the characteristic
                                                      ------------------
                                                      Content
        <BLANKLINE>
        he would n't have guessed at .
        --                ******* --
        Co                        C1 [Evidence:INI]
         (Co=Cognizer, C1=Content)
        <BLANKLINE>
        <BLANKLINE>

        The dict that is returned from this function will contain most of the
        following information about the LU. Note that some LUs do not contain
        all of these pieces of information - particularly 'totalAnnotated' and
        'incorporatedFE' may be missing in some LUs:

        - 'name'       : the name of the LU (e.g. 'merger.n')
        - 'definition' : textual definition of the LU
        - 'ID'         : the internal ID number of the LU
        - '_type'      : 'lu'
        - 'status'     : e.g. 'Created'
        - 'frame'      : Frame that this LU belongs to
        - 'POS'        : the part of speech of this LU (e.g. 'N')
        - 'totalAnnotated' : total number of examples annotated with this LU
        - 'incorporatedFE' : FE that incorporates this LU (e.g. 'Ailment')
        - 'sentenceCount'  : a dict with the following two keys:
                 - 'annotated': number of sentences annotated with this LU
                 - 'total'    : total number of sentences with this LU

        - 'lexemes'  : a list of dicts describing the lemma of this LU.
           Each dict in the list contains these keys:

           - 'POS'     : part of speech e.g. 'N'
           - 'name'    : either single-lexeme e.g. 'merger' or
                         multi-lexeme e.g. 'a little'
           - 'order': the order of the lexeme in the lemma (starting from 1)
           - 'headword': a boolean ('true' or 'false')
           - 'breakBefore': Can this lexeme be separated from the previous lexeme?
                Consider: "take over.v" as in::

                         Germany took over the Netherlands in 2 days.
                         Germany took the Netherlands over in 2 days.

                In this case, 'breakBefore' would be "true" for the lexeme
                "over". Contrast this with "take after.v" as in::

                         Mary takes after her grandmother.
                        *Mary takes her grandmother after.

                In this case, 'breakBefore' would be "false" for the lexeme "after"

        - 'lemmaID'    : Can be used to connect lemmas in different LUs
        - 'semTypes'   : a list of semantic type objects for this LU
        - 'subCorpus'  : a list of subcorpora
           - Each item in the list is a dict containing the following keys:
              - 'name' :
              - 'sentence' : a list of sentences in the subcorpus
                 - each item in the list is a dict with the following keys:
                    - 'ID':
                    - 'sentNo':
                    - 'text': the text of the sentence
                    - 'aPos':
                    - 'annotationSet': a list of annotation sets
                       - each item in the list is a dict with the following keys:
                          - 'ID':
                          - 'status':
                          - 'layer': a list of layers
                             - each layer is a dict containing the following keys:
                                - 'name': layer name (e.g. 'BNC')
                                - 'rank':
                                - 'label': a list of labels for the layer
                                   - each label is a dict containing the following keys:
                                      - 'start': start pos of label in sentence 'text' (0-based)
                                      - 'end': end pos of label in sentence 'text' (0-based)
                                      - 'name': name of label (e.g. 'NN1')

        Under the hood, this implementation looks up the lexical unit information
        in the *frame* definition file. That file does not contain
        corpus annotations, so the LU files will be accessed on demand if those are
        needed. In principle, valence patterns could be loaded here too,
        though these are not currently supported.

        :param fn_luid: The id number of the lexical unit
        :type fn_luid: int
        :param ignorekeys: The keys to ignore. These keys will not be
            included in the output. (optional)
        :type ignorekeys: list(str)
        :return: All information about the lexical unit
        :rtype: dict
        z#LU ID not found: {} ({}) in {} ({})ro   r   )r   rC   rB   frameIDr_   r[   r   )r  r  objectr   r  r0   r*  r  r&  rB   r   )r/  r#  r  r  r&  	frameNameOOVluinfor  r3   r=  s              r   ro   zFramenetCorpusReader.lu[  s5   L || h!!'3/S= JJ5<<GY
 !!"&'F   0A66Y&;(;;&F7O$*DLL!F"  0A\\'*FfllnTnda@SQTnTUU Us   D1
"D1
c           	         |j                   }d| d}t        j                  j                  | j                   | j
                  |      }| j                  s| j                          	 t        |d      5 }|d   }ddd       | j                  |      }	| j                  dz   | j
                  z   dz   |z   |_        |	j                  |_        t        d|j                  D 
cg c]  }
|
j                   D ]  }|  c}}
      |_        |j"                  D ];  }||d	<   |j$                  |d
<   |j&                  D ]  }||d	<   |j$                  |d
<    = |S # 1 sw Y   xY w# t        $ r}t        d|       |d}~ww xY wc c}}
w )z
        Augment the LU information that was loaded from the frame file
        with additional information from the LU file.
        ro   r  r  r   NzUnknown LU id: re   rD  r   r[   )rC   r  r   r#   r  r  r  r  r	   r  r$  _handle_lexunit_eltr  rj   rk   rZ  rz   rm   r[   r   )r/  ro   r  r#  r   r  r  r  r  lu2rq   rw   r   s                r   _lu_filezFramenetCorpusReader._lu_file  sf   
 %%WIT"'',,$**eD|| 	Dw	2d1g 3
 &&sJ73&5;eC}}"R\\T\TdmmdDmD\T
 LLDDJHHDM**T
 "W + ! 	% 32 	D/' ;<!C	D Us6   &E 2E8E E>EE 	E;'E66E;c                    t               | _        t        | j                  d      d| j                        5 }|D ]>  }|d   }|d   }|d   }|| j                  |<   || j                  |<   || j                  |<   @ 	 ddd       g }| j                         D ]z  }|j                  rP| j                  |j                  j                        |_        |j                  j                  j                  |       _||vr|j                  |       ||_        | t        |      }|sJ |rH|j                  d      }|j                  D ]$  }|j                  |_        |j                  |       & |rGyy# 1 sw Y   xY w)z Create the semantic types index.zsemTypes.xmlzsemTypes/semTyperB   r7   rC   Nr   )r*  r  r	   r  _handle_semtype_eltsemtypesrK   rJ  r  rL   r   rJ   r   ry  )	r/  r  rM   nr   rv   rootsqueuechilds	            r   _loadsemtypesz"FramenetCorpusReader._loadsemtypes&  sG   !LL($$
 vJxLtH %&q!$%q!$&q! 
 --/B||#||BLL,>,>?%%,,R0U?LL$  " Uu1B!#U# % 5
 
s   AE,,E5c                    | j                   s| j                          | j                  s| j                          d}d}d}|r|dz  }d}| j	                         D ]  }|j
                  j                  }|j                  j                  }	 |rR||urN|0| j                  ||      sJ |j                  ||j                  f       ||x|j                  _        }d}|dz  }|j                  j                  dv r@|r>||ur:|J |j                  ||j                  f       |x|j
                  _        }d}|dz  } |ryy# t        $ r
}Y d}~d}~ww xY w)a  
        Apply inference rules to distribute semtypes over relations between FEs.
        For FrameNet 1.5, this results in 1011 semtypes being propagated.
        (Not done by default because it requires loading all frame files,
        which takes several seconds. If this needed to be fast, it could be rewritten
        to traverse the neighboring relations on demand for each FE semtype.)

        >>> from nltk.corpus import framenet as fn
        >>> x = sum(1 for f in fn.frames() for fe in f.FE.values() if fe.semType)
        >>> fn.propagate_semtypes()
        >>> y = sum(1 for f in fn.frames() for fe in f.FE.values() if fe.semType)
        >>> y-x > 1000
        True
        Tr   r   FN)Perspective_onSubframePrecedes)r  r6  r  r  fe_relationsr  r  r  semtype_inheritsrB   typeAssertionError)r/  changedrv   nPropagationsrX   superSTsubSTexs           r   propagate_semtypesz'FramenetCorpusReader.propagate_semtypesJ  sb    ~~ $$&FAG**,--//++7%#7$}0E0EeW0U #LL!!JJX U
 !=:AAEKK/%&*G)Q.M

+UU!!0  'Quejj0QQ:??-"&%*1 -	 : &  s   B,D;;	E	Ec                 &   t        |t              r|}n	 | j                  |   }	 | j                  |   }|S # t        $ r" | j	                          | j                  |   }Y <w xY w# t        $ r# | j	                          | j                  |   }Y |S w xY w)a  
        >>> from nltk.corpus import framenet as fn
        >>> fn.semtype(233).name
        'Temperature'
        >>> fn.semtype(233).abbrev
        'Temp'
        >>> fn.semtype('Temperature').ID
        233

        :param key: The name, abbreviation, or id number of the semantic type
        :type key: string or int
        :return: Information about a semantic type
        :rtype: dict
        )r.   intr  r  r6  )r/  r  stidrM   s       r   rJ  zFramenetCorpusReader.semtype  s     c3D+~~c*
	&%B
 	  +""$~~c*+  	& %B			&s    6 A$ (A! A!$(BBc                     t        |t              s| j                  |      }t        |t              s| j                  |      }|j                  }|r||u ry|j                  }|ry)NTF)r.   r   rJ  rK   )r/  rM   rA  pars       r   r<  z%FramenetCorpusReader.semtype_inherits  s[    "d#b!B'4(ll7+Gllg~--C  r5   c                 b    	 t         j                  j                               }|1t         fd j                  |      j                         D              S t         j                  |      S # t        $ r6  j	                          t         j                  j                               }Y w xY w)a
  
        Obtain details for a specific frame.

        >>> from nltk.corpus import framenet as fn
        >>> len(fn.frames()) in (1019, 1221)    # FN 1.5 and 1.7, resp.
        True
        >>> x = PrettyList(fn.frames(r'(?i)crim'), maxReprSize=0, breakLines=True)
        >>> x.sort(key=itemgetter('ID'))
        >>> x
        [<frame ID=200 name=Criminal_process>,
         <frame ID=500 name=Criminal_investigation>,
         <frame ID=692 name=Crime_scenario>,
         <frame ID=700 name=Committing_crime>]

        A brief intro to Frames (excerpted from "FrameNet II: Extended
        Theory and Practice" by Ruppenhofer et. al., 2010):

        A Frame is a script-like conceptual structure that describes a
        particular type of situation, object, or event along with the
        participants and props that are needed for that Frame. For
        example, the "Apply_heat" frame describes a common situation
        involving a Cook, some Food, and a Heating_Instrument, and is
        evoked by words such as bake, blanch, boil, broil, brown,
        simmer, steam, etc.

        We call the roles of a Frame "frame elements" (FEs) and the
        frame-evoking words are called "lexical units" (LUs).

        FrameNet includes relations between Frames. Several types of
        relations are defined, of which the most important are:

           - Inheritance: An IS-A relation. The child frame is a subtype
             of the parent frame, and each FE in the parent is bound to
             a corresponding FE in the child. An example is the
             "Revenge" frame which inherits from the
             "Rewards_and_punishments" frame.

           - Using: The child frame presupposes the parent frame as
             background, e.g the "Speed" frame "uses" (or presupposes)
             the "Motion" frame; however, not all parent FEs need to be
             bound to child FEs.

           - Subframe: The child frame is a subevent of a complex event
             represented by the parent, e.g. the "Criminal_process" frame
             has subframes of "Arrest", "Arraignment", "Trial", and
             "Sentencing".

           - Perspective_on: The child frame provides a particular
             perspective on an un-perspectivized parent frame. A pair of
             examples consists of the "Hiring" and "Get_a_job" frames,
             which perspectivize the "Employment_start" frame from the
             Employer's and the Employee's point of view, respectively.

        :param name: A regular expression pattern used to match against
            Frame names. If 'name' is None, then a list of all
            Framenet Frames will be returned.
        :type name: str
        :return: A list of matching Frames (or all Frames).
        :rtype: list(AttrDict)
        c              3   F   K   | ]  \  }}j                  |        y wr  r[   )rE   r  finfor/  s      r   rG   z.FramenetCorpusReader.frames.<locals>.<genexpr>  s"      2XJC

32X   !)
r   r  rI   r~  r  r  frame_ids_and_namesr   r  r[   )r/  rB   fIDss   `  r   r  zFramenetCorpusReader.frames  s    z	0,,./D
  262J2J42P2V2V2X   !T22  	0!!#,,./D	0s   #A/ /<B.-B.c                     | j                   s| j                          | j                   j                         D ci c]4  \  }}| t        j                  ||j
                        ||j
                  6 c}}S c c}}w )z
        Uses the frame index, which is much faster than looking up each frame definition
        if only the names and IDs are needed.
        )r  r  r   r  r  rB   )r/  rB   r  rM  s       r   rO  z(FramenetCorpusReader.frame_ids_and_names  sp    
 !!# #oo335
5
U|ryyuzz:F O5
 	
 
s   9A7c                     |It        |t              r| j                  |      g}n6t        |t              r| j	                  |      }n|g}n| j	                         }t        fd|D              S )a  
        Lists frame element objects. If 'name' is provided, this is treated as
        a case-insensitive regular expression to filter by frame name.
        (Case-insensitivity is because casing of frame element names is not always
        consistent across frames.) Specify 'frame' to filter by a frame name pattern,
        ID, or object.

        >>> from nltk.corpus import framenet as fn
        >>> fn.fes('Noise_maker')
        [<fe ID=6043 name=Noise_maker>]
        >>> sorted([(fe.frame.name,fe.name) for fe in fn.fes('sound')]) # doctest: +NORMALIZE_WHITESPACE
        [('Cause_to_make_noise', 'Sound_maker'), ('Make_noise', 'Sound'),
         ('Make_noise', 'Sound_source'), ('Sound_movement', 'Location_of_sound_source'),
         ('Sound_movement', 'Sound'), ('Sound_movement', 'Sound_source'),
         ('Sounds', 'Component_sound'), ('Sounds', 'Location_of_sound_source'),
         ('Sounds', 'Sound_source'), ('Vocalizations', 'Location_of_sound_source'),
         ('Vocalizations', 'Sound_source')]
        >>> sorted([(fe.frame.name,fe.name) for fe in fn.fes('sound',r'(?i)make_noise')]) # doctest: +NORMALIZE_WHITESPACE
        [('Cause_to_make_noise', 'Sound_maker'),
         ('Make_noise', 'Sound'),
         ('Make_noise', 'Sound_source')]
        >>> sorted(set(fe.name for fe in fn.fes('^sound')))
        ['Sound', 'Sound_maker', 'Sound_source']
        >>> len(fn.fes('^sound$'))
        2

        :param name: A regular expression pattern used to match against
            frame element names. If 'name' is None, then a list of all
            frame elements will be returned.
        :type name: str
        :return: A list of matching frame elements
        :rtype: list(AttrDict)
        c              3      K   | ]O  }|j                   j                         D ]0  \  }}%t        j                  |t        j                        r| 2 Q y wr  )r   r   r  r  I)rE   r  r   r  rB   s       r   rG   z+FramenetCorpusReader.fes.<locals>.<genexpr>3  sL      
ddjjl
|ryyvrtt< * s   AA)r.   rF  r[   r/   r  r  )r/  rB   r[   r  s    `  r   r  zFramenetCorpusReader.fes  sk    F %%**U+,E3'U+[[]F 

 
 	
r5   c                 8   	  j                   s j                          |t         fd j                  |      j	                         D              }|ot        |t              r|h	nGt        |t              r* j                  |      D ch c]  }|j                   c}	n|j                  h	t        	fd|D              }|S |nt        |t              r j                  |      g}n%t        |t              r j                  |      }n|g}t        t        t        d |D                          }|S  j                   j	                         D cg c]  \  }}|j                   j                  vr|! }}}t!         j"                  |      }|S c c}w c c}}w )a  
        Obtain details for lexical units.
        Optionally restrict by lexical unit name pattern, and/or to a certain frame
        or frames whose name matches a pattern.

        >>> from nltk.corpus import framenet as fn
        >>> len(fn.lus()) in (11829, 13572) # FN 1.5 and 1.7, resp.
        True
        >>> PrettyList(sorted(fn.lus(r'(?i)a little'), key=itemgetter('ID')), maxReprSize=0, breakLines=True)
        [<lu ID=14733 name=a little.n>,
         <lu ID=14743 name=a little.adv>,
         <lu ID=14744 name=a little bit.adv>]
        >>> PrettyList(sorted(fn.lus(r'interest', r'(?i)stimulus'), key=itemgetter('ID')))
        [<lu ID=14894 name=interested.a>, <lu ID=14920 name=interesting.a>]

        A brief intro to Lexical Units (excerpted from "FrameNet II:
        Extended Theory and Practice" by Ruppenhofer et. al., 2010):

        A lexical unit (LU) is a pairing of a word with a meaning. For
        example, the "Apply_heat" Frame describes a common situation
        involving a Cook, some Food, and a Heating Instrument, and is
        _evoked_ by words such as bake, blanch, boil, broil, brown,
        simmer, steam, etc. These frame-evoking words are the LUs in the
        Apply_heat frame. Each sense of a polysemous word is a different
        LU.

        We have used the word "word" in talking about LUs. The reality
        is actually rather complex. When we say that the word "bake" is
        polysemous, we mean that the lemma "bake.v" (which has the
        word-forms "bake", "bakes", "baked", and "baking") is linked to
        three different frames:

           - Apply_heat: "Michelle baked the potatoes for 45 minutes."

           - Cooking_creation: "Michelle baked her mother a cake for her birthday."

           - Absorb_heat: "The potatoes have to bake for more than 30 minutes."

        These constitute three different LUs, with different
        definitions.

        Multiword expressions such as "given name" and hyphenated words
        like "shut-eye" can also be LUs. Idiomatic phrases such as
        "middle of nowhere" and "give the slip (to)" are also defined as
        LUs in the appropriate frames ("Isolated_places" and "Evading",
        respectively), and their internal structure is not analyzed.

        Framenet provides multiple annotated examples of each sense of a
        word (i.e. each LU).  Moreover, the set of examples
        (approximately 20 per LU) illustrates all of the combinatorial
        possibilities of the lexical unit.

        Each LU is linked to a Frame, and hence to the other words which
        evoke that Frame. This makes the FrameNet database similar to a
        thesaurus, grouping together semantically similar words.

        In the simplest case, frame-evoking words are verbs such as
        "fried" in:

           "Matilde fried the catfish in a heavy iron skillet."

        Sometimes event nouns may evoke a Frame. For example,
        "reduction" evokes "Cause_change_of_scalar_position" in:

           "...the reduction of debt levels to $665 million from $2.6 billion."

        Adjectives may also evoke a Frame. For example, "asleep" may
        evoke the "Sleep" frame as in:

           "They were asleep for hours."

        Many common nouns, such as artifacts like "hat" or "tower",
        typically serve as dependents rather than clearly evoking their
        own frames.

        :param name: A regular expression pattern used to search the LU
            names. Note that LU names take the form of a dotted
            string (e.g. "run.v" or "a little.adv") in which a
            lemma precedes the "." and a POS follows the
            dot. The lemma may be composed of a single lexeme
            (e.g. "run") or of multiple lexemes (e.g. "a
            little"). If 'name' is not given, then all LUs will
            be returned.

            The valid POSes are:

                   v    - verb
                   n    - noun
                   a    - adjective
                   adv  - adverb
                   prep - preposition
                   num  - numbers
                   intj - interjection
                   art  - article
                   c    - conjunction
                   scon - subordinating conjunction

        :type name: str
        :type frame: str or int or frame
        :return: A list of selected (or all) lexical units
        :rtype: list of LU objects (dicts). See the lu() function for info
          about the specifics of LU objects.

        c              3   F   K   | ]  \  }}j                  |        y wr  r"  )rE   luIDr  r/  s      r   rG   z+FramenetCorpusReader.lus.<locals>.<genexpr>  s"       2U,$2UrN  c              3   T   K   | ]  }|j                   j                  v s| ! y wr  )r[   rC   )rE   ro   frameIDss     r   rG   z+FramenetCorpusReader.lus.<locals>.<genexpr>  s!     #S2288;;(;RBs   ((c              3   b   K   | ]'  }t        |j                  j                                ) y wr  )r   r  r  )rE   r  s     r   rG   z+FramenetCorpusReader.lus.<locals>.<genexpr>  s#     &PAtAII,<,<,>'?s   -/)r  r  r  lu_ids_and_namesr   r.   rF  r/   r  rC   r[   r  iterr
   r_   _bad_statusesr  ro   )
r/  rB   r[   resultr  r  rW  ro   luIDsrY  s
   `        @r   luszFramenetCorpusReader.lus:  s   R ||   262G2G2M2S2S2U  F  eS) %wHs+.2kk%.@A.@.@AH %zH##S#SS$ # %%**U+,E3'U++&&P&PPQF 	 !% 2 2 4 4HD"99D$6$66  4  
 #477E2F+  Bs   F$Fc                 *   | j                   s| j                          | j                   j                         D ci c]L  \  }}|j                  | j                  vr/| t        j                  ||j                        ||j                  N c}}S c c}}w )z
        Uses the LU index, which is much faster than looking up each LU definition
        if only the names and IDs are needed.
        )r  r  r   r_   r]  r  r  rB   )r/  rB   rW  r*  s       r   r[  z%FramenetCorpusReader.lu_ids_and_names  s    
 ||  !% 2 2 4
 4f}}D$6$664!=!I &++ 4
 	
 
s   ABc                     	 t        | j                  j                               }|S t        fd|D              S # t        $ r6 | j	                          t        | j                  j                               }Y Vw xY w)a]  
        Return an index of the annotated documents in Framenet.

        Details for a specific annotated document can be obtained using this
        class's doc() function and pass it the value of the 'ID' field.

        >>> from nltk.corpus import framenet as fn
        >>> len(fn.docs()) in (78, 107) # FN 1.5 and 1.7, resp.
        True
        >>> set([x.corpname for x in fn.docs_metadata()])>=set(['ANC', 'KBEval',                     'LUCorpus-v0.3', 'Miscellaneous', 'NTI', 'PropBank'])
        True

        :param name: A regular expression pattern used to search the
            file name of each annotated document. The document's
            file name contains the name of the corpus that the
            document is from, followed by two underscores "__"
            followed by the document name. So, for example, the
            file name "LUCorpus-v0.3__20000410_nyt-NEW.xml" is
            from the corpus named "LUCorpus-v0.3" and the
            document name is "20000410_nyt-NEW.xml".
        :type name: str
        :return: A list of selected (or all) annotated documents
        :rtype: list of dicts, where each dict object contains the following
                keys:

                - 'name'
                - 'ID'
                - 'corpid'
                - 'corpname'
                - 'description'
                - 'filename'
        c              3   V   K   | ]   }t        j                  |d          | " yw)r  Nr  )rE   rF   rB   s     r   rG   z5FramenetCorpusReader.docs_metadata.<locals>.<genexpr>  s)      !aRYYtQz]%C%O6s   )))r  r  r  r~  r  )r/  rB   ftlists    ` r   docs_metadataz"FramenetCorpusReader.docs_metadata  s~    D	= 2 2 9 9 ;<F
 <M !    	=""$ 2 2 9 9 ;<F	=s   #> <A=<A=c                 @     t         fd j                  |            S )z
        Return a list of the annotated full-text documents in FrameNet,
        optionally filtered by a regex to be matched against the document name.
        c                 :    j                  | j                        S r  )r   rC   )rF   r/  s    r   r  z+FramenetCorpusReader.docs.<locals>.<lambda>	  s    r5   )r  re  r7  s   ` r   docszFramenetCorpusReader.docs	  s    
 69K9KD9QRRr5   c                     |r3|r!| j                         | j                         z   S | j                         S |r| j                         S y)zF
        Annotated sentences matching the specified criteria.
        N)rm   ft_sents)r/  rm   	full_texts      r   r{   zFramenetCorpusReader.sents		  sC     ~~'$--/99~~''==?" r5   c                    |r"t        d | j                        D              }ng }|rN(t        | j                        j	                               t        fd| j                         D              }ng }|r	|r||z   S |S |r|S y)zH
        Frame annotation sets matching the specified criteria.
        c              3   4   K   | ]  }|j                     y wr  )frameAnnotation)rE   rw   s     r   rG   z3FramenetCorpusReader.annotations.<locals>.<genexpr>	  s      +1N$$1Ns   Nc              3   v   K   | ]0  }|j                   d d D ]  }|j                  dd      v r|  2 yw)r   NrW  CXN_ASET)r   r   )rE   rw   r   luNamePatternmatchedLUIDss      r   rG   z3FramenetCorpusReader.annotations.<locals>.<genexpr>$	  sK      ,+D ..qr2D (DHHVZ,HL,X 2 +s   69)r  rm   r   r[  rI   rj  )r/  rq  rm   rk  epartftpartrr  s    `    @r   annotationsz FramenetCorpusReader.annotations	  s    
 * +151N+ E E("4#8#8#G#L#L#NO+ , MMO, F Fv~%M r5   c                    	
 t        d      KIt        t              s9t        t              rcn#j                  j                  urt        d      |t        t              sj                  }t	        t
              
|q|t        |t              rt               	 j                  |      D ]O  }	j                  |j                  j                         
|j                  j                     j                  |       Q t         j                  t        	            	nY j                  |      	nGt        |t              r j                  |      g	n|g	|j                   j                  |      i
t        t              rt        fd	D              	n&j                  	vrt        d      j                  g	t        t              rt        fd	D              	n j!                        D ch c]  }|j                  j                   c}	7 j!                        D ch c]  }|j                  j                   }}	|z  	t         j                  t        	            	n j                         		
 fd}t         |             S c c}w c c}w )ab  
        Lexicographic exemplar sentences, optionally filtered by LU name and/or 1-2 FEs that
        are realized overtly. 'frame' may be a name pattern, frame ID, or frame instance.
        'fe' may be a name pattern or FE instance; if specified, 'fe2' may also
        be specified to retrieve sentences with both overt FEs (in either order).
        z3exemplars(..., fe=None, fe2=<value>) is not allowedzSexemplars() call with inconsistent `fe` and `fe2` specification (frames must match)rL  c              3      K   | ]@  }|j                   v s,t        fd |j                   j                         D              r| B yw)c              3   h   K   | ])  }t        j                  |t         j                         + y wr  r  r  rT  )rE   ffer  s     r   rG   z;FramenetCorpusReader.exemplars.<locals>.<genexpr>.<genexpr>h	  s#     O;CryyS"$$7;   /2Nr   r   rI   )rE   r  r  s     r   rG   z1FramenetCorpusReader.exemplars.<locals>.<genexpr>d	  s<      4!'A:O14499;OO !'   AA	zAexemplars() call with inconsistent `frame` and `fe` specificationc              3      K   | ]@  }|j                   v s,t        fd |j                   j                         D              r| B yw)c              3   h   K   | ])  }t        j                  |t         j                         + y wr  ry  )rE   rz  fe2s     r   rG   z;FramenetCorpusReader.exemplars.<locals>.<genexpr>.<genexpr>w	  s#     "T299S#rtt#<r{  Nr|  )rE   r  r  s     r   rG   z1FramenetCorpusReader.exemplars.<locals>.<genexpr>s	  s<      8%+"add{""T		"TT %+r}  c            	   3     K   D ]P  } d x}}t        t              rN| j                  j                         D ch c]*  }t	        j
                  |t        j                        s)|, c}nj                  h}kt        t              rN| j                  j                         D ch c]*  }t	        j
                  |t        j                        s)|, c}nj                  h}	
| j                     n| j                  j                         D ]A  }|j                  D ]0  }|j                  ||      s|j                  ||      s-| 2 C S y c c}w c c}w wr  )r.   r/   r   rI   r  r  rT  rB   r  r  rm   _exemplar_of_fes)r  r  fes2rz  ro   rC  r  r  r  rq  
lusByFramer/  s         r   _matching_exsz5FramenetCorpusReader.exemplars.<locals>._matching_exs	  s;    !!d> &b#. )*		PryyS"$$7OP ggY 
   *#s3 -.DDIIKUKS299S#rtt;TSKU"%((  %0 qvv&))+, 
 !llK4+@+@S+I LD,A,A"d,K"$H	 +	,!  Q Vs5   9E%*E'E+>E%)*E E A!E%:E%E%)r$  r.   r/   r[   r   r   r   r`  r   rC   rB   r   r   r  rF  r  r  )r/  rq  r[   r  r  ro   rz  frames2r  r  r  s   `` ``    @@r   rm   zFramenetCorpusReader.exemplars5	  s{    :#/ UVV^c3'b#&!2GBXXSYY.'m  =R^Jr34GHHE !

  9}
5# 6 , UF"hh}EhB

288;;/"288==188< C %TZZf>F![[/FeS)"jj/0F#WF ,"'**dhh}Eh.R!SJ~b#&3 4!'4 F xxv-+_  !hhZF?!#s+!7 8%+8 " ~26((2,?,3#)),,,??7;xx}E}syy||}GE#g-F T&\:
	% 	%6 &mo66M @Es   K Kc           	         |j                   d   r*t        t        t        |j                   d          d         n	t               }d|v r||j                  d   r*t        t        t        |j                  d          d         n	t               z  }d|v rF||j
                  d   r*t        t        t        |j
                  d          d         n	t               z  }|||z  S |S )z
        Given an exemplar sentence and a set of FE names, return the subset of FE names
        that are realized overtly in the sentence on the FE, FE2, or FE3 layer.

        If 'fes' is None, returns all overt FE names.
        r   r   r   r   )r   r   r   zipr   r   )r/  rC  r  
overtNamess       r   r  z%FramenetCorpusReader._exemplar_of_fes	  s     68UU1XSc2558n-a0135
B;266!9#d3q	?3A67#%OJ{rvvayc$sBFF1I"7":;ceS
#&?zCB
Br5   c                 D    t        d | j                  |      D              S )zW
        Full-text annotation sentences, optionally filtered by document name.
        c              3   B   K   | ]  }|j                   D ]  }|   y wr  )rz   )rE   drw   s      r   rG   z0FramenetCorpusReader.ft_sents.<locals>.<genexpr>	  s!      &
3Q

D
D3s   )r  rh  )r/  docNamePatterns     r   rj  zFramenetCorpusReader.ft_sents	  s'     & &
))N3&
 
 	
r5   c                 n    | j                   s| j                          | j                   j                         S )a  
        Obtain a list of frame relation types.

        >>> from nltk.corpus import framenet as fn
        >>> frts = sorted(fn.frame_relation_types(), key=itemgetter('ID'))
        >>> isinstance(frts, list)
        True
        >>> len(frts) in (9, 10)    # FN 1.5 and 1.7, resp.
        True
        >>> PrettyDict(frts[0], breakLines=True)
        {'ID': 1,
         '_type': 'framerelationtype',
         'frameRelations': [<Parent=Event -- Inheritance -> Child=Change_of_consistency>, <Parent=Event -- Inheritance -> Child=Rotting>, ...],
         'name': 'Inheritance',
         'subFrameName': 'Child',
         'superFrameName': 'Parent'}

        :return: A list of all of the frame relation types in framenet
        :rtype: list(dict)
        )r  r  r  rB  s    r   frame_relation_typesz)FramenetCorpusReader.frame_relation_types	  s.    *   $$&  ''))r5   c                 `   |}| j                   s| j                          d}|St        |t              sC| j	                         D cg c]  }|j
                  |k(  s| c}d   }t        |t              sJ |t        |t              rd|v rt        |j                        }nqt        |t              s8t        |t              r|j                  }n| j                  |      j                  }| j                  |   D cg c]  }| j                   |    }}|H|D cg c]  }|j                  |u s| }}n)||j                  }n| j                   j                         }||t        d      t        |t              s8t        |t              r|j                  }n| j                  |      j                  }||k(  rt        d      |D cg c]6  }|j                  j                  |k(  s|j                   j                  |k(  r|8 }}t        t#        |d             S c c}w c c}w c c}w c c}w )a  
        :param frame: (optional) frame object, name, or ID; only relations involving
            this frame will be returned
        :param frame2: (optional; 'frame' must be a different frame) only show relations
            between the two specified frames, in either direction
        :param type: (optional) frame relation type (name or object); show only relations
            of this type
        :type frame: int or str or AttrDict
        :return: A list of all of the frame relations in framenet
        :rtype: list(dict)

        >>> from nltk.corpus import framenet as fn
        >>> frels = fn.frame_relations()
        >>> isinstance(frels, list)
        True
        >>> len(frels) in (1676, 2070)  # FN 1.5 and 1.7, resp.
        True
        >>> PrettyList(fn.frame_relations('Cooking_creation'), maxReprSize=0, breakLines=True)
        [<Parent=Intentionally_create -- Inheritance -> Child=Cooking_creation>,
         <Parent=Apply_heat -- Using -> Child=Cooking_creation>,
         <MainEntry=Apply_heat -- See_also -> ReferringEntry=Cooking_creation>]
        >>> PrettyList(fn.frame_relations(274), breakLines=True)
        [<Parent=Avoiding -- Inheritance -> Child=Dodging>,
         <Parent=Avoiding -- Inheritance -> Child=Evading>, ...]
        >>> PrettyList(fn.frame_relations(fn.frame('Cooking_creation')), breakLines=True)
        [<Parent=Intentionally_create -- Inheritance -> Child=Cooking_creation>,
         <Parent=Apply_heat -- Using -> Child=Cooking_creation>, ...]
        >>> PrettyList(fn.frame_relations('Cooking_creation', type='Inheritance'))
        [<Parent=Intentionally_create -- Inheritance -> Child=Cooking_creation>]
        >>> PrettyList(fn.frame_relations('Cooking_creation', 'Apply_heat'), breakLines=True) # doctest: +NORMALIZE_WHITESPACE
        [<Parent=Apply_heat -- Using -> Child=Cooking_creation>,
        <MainEntry=Apply_heat -- See_also -> ReferringEntry=Cooking_creation>]
        Nr   r  z:frame_relations(frame=None, frame2=<value>) is not allowedzEThe two frame arguments to frame_relations() must be different framesc                 \    | j                   j                  | j                  | j                  fS r  )r=  rC   r  r  )rU   s    r   r  z6FramenetCorpusReader.frame_relations.<locals>.<lambda>.
  s    $)),,0C0CTEVEV!Wr5   r  )r  r  r.   r   r  rB   r  r  rF  rC   r
  r  r=  r  r$  r  r  rn   )	r/  r[   frame2r=  relation_typerelsrtfrelIDrels	            r   frame_relationsz$FramenetCorpusReader.frame_relations	  s#   D ~~$$&$mT2%)%>%>%@T%@rBGGtO%@TUVW!$--- %&+;u+D!%"6"67!%-!%. % $ 2 25 9 < <=A=M=Me=TU=T6v.=TU '+@tsxx4/?t@&&D>>((*D }#P  fc*fd+#YYF!//7::F#[ 
  C>>$$.#,,//V2K    W
 	
[ U V A,s$   HH;H!H&-H&;H+c                     | j                   s| j                          t        t        | j                   j	                         d             S )a  
        Obtain a list of frame element relations.

        >>> from nltk.corpus import framenet as fn
        >>> ferels = fn.fe_relations()
        >>> isinstance(ferels, list)
        True
        >>> len(ferels) in (10020, 12393)   # FN 1.5 and 1.7, resp.
        True
        >>> PrettyDict(ferels[0], breakLines=True) # doctest: +NORMALIZE_WHITESPACE
        {'ID': 14642,
        '_type': 'ferelation',
        'frameRelation': <Parent=Abounding_with -- Inheritance -> Child=Lively_place>,
        'subFE': <fe ID=11370 name=Degree>,
        'subFEName': 'Degree',
        'subFrame': <frame ID=1904 name=Lively_place>,
        'subID': 11370,
        'supID': 2271,
        'superFE': <fe ID=2271 name=Degree>,
        'superFEName': 'Degree',
        'superFrame': <frame ID=262 name=Abounding_with>,
        'type': <framerelationtype ID=1 name=Inheritance>}

        :return: A list of all of the frame element relations in framenet
        :rtype: list(dict)
        c                     | j                   j                  | j                  j                  | j                  | j                  j
                  | j                  fS r  )r=  rC   frameRelationr  r  r  r  )rX   s    r   r  z3FramenetCorpusReader.fe_relations.<locals>.<lambda>R
  s@    JJMM''66%%''44OO#r5   r  )r  r  r  rn   r  rB  s    r   r;  z!FramenetCorpusReader.fe_relations2
  sA    6 $$&&&(	
 	
r5   c                 x      j                   s j                          t         fd j                   D              S )a  
        Obtain a list of semantic types.

        >>> from nltk.corpus import framenet as fn
        >>> stypes = fn.semtypes()
        >>> len(stypes) in (73, 109) # FN 1.5 and 1.7, resp.
        True
        >>> sorted(stypes[0].keys())
        ['ID', '_type', 'abbrev', 'definition', 'definitionMarkup', 'name', 'rootType', 'subTypes', 'superType']

        :return: A list of all of the semantic types in framenet
        :rtype: list(dict)
        c              3   ^   K   | ]$  }t        |t              sj                  |    & y wr  )r.   rF  r  )rE   rv   r/  s     r   rG   z0FramenetCorpusReader.semtypes.<locals>.<genexpr>l
  s'      
'5!As9KDNN1~s   --)r  r6  r  rB  s   `r   r1  zFramenetCorpusReader.semtypes\
  s6     ~~  
'+~~
 
 	
r5   c                      t        |      |      }	 |j                  }||S g d}|D ]@  t        fd|D              r|   }|j	                         rt        |      |<   <||<   B |S # t        $ r |cY S w xY w)a  
        Extracts a subset of the attributes from the given element and
        returns them in a dictionary.

        :param d: A dictionary in which to store the attributes.
        :type d: dict
        :param elt: An ElementTree Element
        :type elt: Element
        :return: Returns the input dict ``d`` possibly including attributes from ``elt``
        :rtype: dict
        )xsischemaLocationxmlnsbgColorfgColorc              3   @   K   | ]  }j                  |        y wr  )r@  )rE   rF   attrs     r   rG   z<FramenetCorpusReader._load_xml_attributes.<locals>.<genexpr>
  s     :\4==#\s   )r=  attribr~  r   isdigitrF  )r/  r  r  	attr_dictignore_attrsvalr  s         @r   _load_xml_attributesz)FramenetCorpusReader._load_xml_attributesp
  s     DGAJ	

I H
 D:\::D/C{{}c($$  3  	H	s   A/ /A=<A=c                    	 	 |j                  dd      }|j                  dd      }t        j                  dd|      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  d	d      }|j                  d
d      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|S # t        $ r Y |S w xY w)z
        Gets rid of all tags and newline characters from the given input

        :return: A cleaned-up version of the input string
        :rtype: str
        z<t>r(   z</t>z<fex name="[^"]+">z</fex>z<fen>z</fen>z<m>z</m>z<ment>z</ment>z<ex>'z</ex>z<gov>z</gov>z<x>z</x>z
<def-root>z</def-root>r   rc   )r   r  subr~  )r/  datas     r   _strip_tagsz FramenetCorpusReader._strip_tags
  sc   	 <<r*D<<+D66.D9D<<"-D<<,D<<"-D<<r*D<<+D<<"-D<<	2.D<<,D<<-D<<,D<<"-D<<r*D<<+D <<b1D<<r2D<<c*D   		s   EE   	E-,E-c                 6    | j                  t               |      S )z8Extracts and returns the attributes of the given element)r  r*  )r/  r  tagspecs      r   r  z FramenetCorpusReader._handle_elt
  s    ((S99r5   c                    | j                  t               |      }|j                  }|j                  }g }|D ]  }|j                  j                  d      s| j                  t               |      }d|v r|j                  }	n|j                  }	| d|	 d|_        | j                  dz   | j                  z   dz   |j                  z   |_
        ||_        ||_        |j                  |        |S )a  
        Extracts corpus/document info from the fulltextIndex.xml file.

        Note that this function "flattens" the information contained
        in each of the "corpus" elements, so that each "document"
        element will contain attributes for the corpus and
        corpusid. Also, each of the "document" items will contain a
        new attribute called "filename" that is the base file name of
        the xml file for the document in the "fulltext" subdir of the
        Framenet corpus.
        documentrB   __r  re   )r  r*  rB   rC   tagr@  r   r  r  r  rj   corpnamecorpidr   )
r/  r  r  ftinfor  r  retlistr  r   docnames
             r   r  z.FramenetCorpusReader._handle_fulltextindex_elt
  s     **8:s;;;Cww
+//
C@S=!hhG!ooG"*2gYd;OOc)D,>,>>Ds||S   (#
s#  r5   c                 r     j                  t               |      dd<   dd<   dd<   t               d<   g d<   t               d<   g d	<   |D ]
  }|v s|=  |D ]O  }|j                  j	                  d      r2d|vr.|j
                  d<    j                  |j
                        d<   Q|j                  j	                  d      r-d|vr) j                  |      }|d   |j                  <   |d<   |j                  j	                  d
      r<d
|vr8 j                  |      }d   j                  t        fd|D                     |j                  j	                  d      rd|vr׉ j                  |      }|d    j                  v r3|d<    j                  dz    j                  z   dz   dj!                  |d         z   |d<   t#          fd|            |d<   t#          fd|            |d<   |d   |j                  <    j$                  s j'                          | j$                  |j(                  <   |j                  j	                  d      sd	|vs	 j                  t               |      }d	   j                   j+                  |j(                               R  j-                        d<   j.                  j1                         D ]  }	|	j2                  r[|	j2                  j                  |	j2                  j(                  }}
j.                  |
   |	_        |	j2                  j(                  |k(  sJ |	j4                  sw|	j4                  j                  |	j4                  j(                  }}
j.                  |
   |	_        |	j4                  j(                  |k(  rJ  S )z/Load the info for a Frame from a frame xml filer[   r   r(   r9   definitionMarkupr   r  r  rg   	FEcoreSetc              3   B   K   | ]  }d    |j                        yw)r   N)rB   )rE   r  frinfos     r   rG   z9FramenetCorpusReader._handle_frame_elt.<locals>.<genexpr>  s     Gwvd|BGG4ws   r_   re   zlu{}.xmlrC   rj   c                       fdS )Nc                  :    j                         j                  S r  )r.  rk   ro   r/  s   r   r  zJFramenetCorpusReader._handle_frame_elt.<locals>.<lambda>.<locals>.<lambda>      b(9(C(Cr5   r   r  s   `r   r  z8FramenetCorpusReader._handle_frame_elt.<locals>.<lambda>       Cr5   rk   c                       fdS )Nc                  :    j                         j                  S r  )r.  rm   r  s   r   r  zJFramenetCorpusReader._handle_frame_elt.<locals>.<lambda>.<locals>.<lambda>  r  r5   r   r  s   `r   r  z8FramenetCorpusReader._handle_frame_elt.<locals>.<lambda>  r  r5   rm   r  rL  r  )r  r*  ru  r  r@  ru   r  _handle_fe_eltrB   _handle_fecoreset_eltr   r  _handle_framelexunit_eltr]  r  r  r0   r;  r  r  rC   rJ  r  r   r  r  r  )r/  r  r  r3   r  feinfocoresetluentrysemtypeinfor  rB   rC   r  s   `           @r   r  z&FramenetCorpusReader._handle_frame_elt
  sq   **8:s;!w!|%'!"!|t!|&LyzAF{1I  Cww-,j2P-0XX)*'+'7'7'A|$!!$'D
,B,,S1,2tV[[)"(w!!+.;j3P44S9|$++GwGG !!),*1L77<8$(:(::#) OOll#  !''6	7  (.CWM($ (.CWM($ 3:y!',,/||&&(+2WZZ(!!),:1M"77
CHz"))$,,{~~*FGO R $(#7#7f#7#E  ))""$B}}==--r}}/?/?b &		$}}''2---}}==--r}}/?/?b &		$}}''2--- % r5   c                     | j                  t               |      }g }|D ]+  }|j                  | j                  t               |             - |S )zLoad fe coreset info from xml.)r  r*  r   )r/  r  r  tmpr  s        r   r  z*FramenetCorpusReader._handle_fecoreset_elt3  sG    ((S9CJJt00SAB  
r5   c                 $   | j                  t               |      }d|d<   t               |d<   |D ]^  }|j                  j	                  d      s| j                  |      }||d<   |j                  D ]  }||d<   	 |d   j                  |       ` |S )SLoad frame-relation element and its child fe-relation elements from frRelation.xml.rK  r   r  r  r=  )r  r*  r  r  r@  _handle_framerelation_eltr  r   )r/  r  r0  r  r  rU   rX   s          r   r  z2FramenetCorpusReader._handle_framerelationtype_elt<  s    ((S9+W!+Cww055c:#V!--E$(E&M .%&--d3  r5   c                 *   | j                  t               |      }|d   |d   k7  s	J ||f       d|d<   t               |d<   |D ]M  }|j                  j	                  d      s| j                  |      }d|d<   ||d<   |d   j                  |       O |S )	r  r  r  rL  r   r  
FERelationrM  r  )r  r*  r  r  r@  r  r   )r/  r  r  r  rX   s        r   r  z.FramenetCorpusReader._handle_framerelation_eltL  s    ((S9$%n)==JT{J='W(l]Cww-((-!-g)-o&]#**51  r5   c                    t               }d|d<   g |d<   |D ]f  }|j                  j                  d      r|j                  j                  d      s;| j                  |      }||_        |d   j                  |       h |S )zLoad full annotation info for a document from its xml
        file. The main element (fullTextAnnotation) contains a 'header'
        element (which we ignore here) and a bunch of 'sentence'
        elements.rE  r   rz   header)r*  r  r@  _handle_fulltext_sentence_eltr   r   )r/  r  r  r  r   s        r   r  z3FramenetCorpusReader._handle_fulltextannotation_elt\  s    
 z-WZCww)!!*-66s;Z ''*  r5   c           
         | j                  t               |      }d|d<   g |d<   g |d<   t               }t        j                  t
        |      |d<   d|d<   |D ]Q  }|j                  j                  d      r| j                  |j                        |d<   >|j                  j                  d      sZ| j                  |t        |d         dk(  	      }d
|v r||_        |j                  |_	        |d   j                  |       d|v s|j                  D ]\  }||v rE| j                  dj!                  |j                  t#        |          |d|d   |j                         L|j%                  |       ^ |d   j                  |j                  |j&                  |j(                  f       T |d   d   j*                  dk(  sJ |d   d   j,                  |d<   |d   d   j.                  |d<   |S )zLoad information from the given 'sentence' element. Each
        'sentence' element contains a "text" and "annotationSet" sub
        elements.r   r   r   targetsr   r(   ru   r   is_poscxnIDr   zDuplicate target span "{}"zin sentencerC   r   r]   r   )r  r*  r   types
MethodTyper   r  r@  r  ru   !_handle_fulltextannotationset_eltr   rw   r   r   r  r0   slicer   r  r(  r_   r]   r   )r/  r  r  target_spansr  r   tspans          r   r  z2FramenetCorpusReader._handle_fulltext_sentence_elto  s    ((S9+W "_Yu))t
X VCww'#//9V!!/2::T/%:!;q!@ ;  a<_%,,Q/q=!" L0 JJ < C C$(IIeUm$<!" !& - $T
 $		 ),,U3 "* O**AHHahh+LM9 < O$Q'..'999?+A.22U!/215@@\r5   c                     | j                  ||      }|sbd|d<   d|vrY| j                  |j                  |j                  |j                  |j
                        |d<   |j                  j                  |d<   |S )zxLoad information from the given 'annotationSet' element. Each
        'annotationSet' contains several "layer" elements.r  rH  r   r  )r  r&  r(  r   r[   )_handle_luannotationset_eltro   rW  r  r&  r(  r   r[   )r/  r  r  r  s       r   r  z6FramenetCorpusReader._handle_fulltextannotationset_elt  sx     //F/C4DMd"!WWII;; LL"nn	 % T
 !%Wr5   c                     | j                  t               |      }d|d<   g |d<   |D ]L  }|j                  j                  d      s| j                  t               |      }|d   j	                  |       N |S )zhLoad information from the given 'layer' element. Each
        'layer' contains several "label" elements.layerr   labelr  r*  r  r@  r   )r/  r  r  r  r    s        r   _handle_fulltextlayer_eltz.FramenetCorpusReader._handle_fulltextlayer_elt  ss     ((S9WWCww(--hj#>W$$Q' 
 r5   c                    t               }d|d<   | j                  ||      }d|d<   d|d<   t               |d<   t               |d<   t               |d<   |D ]h  }|j                  j                  d      r.|j                  |d<   | j                  |j                        |d<   M|j                  j                  d      r| j                  t               |      |d<   |j                  j                  d	      rd| j                  t               |      }t        |j                  t              st        |j                        |_	        |d   j                  |       |j                  j                  d
      s"| j                  t               |      }|d   j                  | j                  |j                               k |d   j                  d        |S )zELoad the lexical unit info from an xml element in a frame's xml file.ro   r   r(   r9   r  sentenceCountrb   rg   lexemer  c                     | j                   S r  )order)rF   s    r   r  z?FramenetCorpusReader._handle_framelexunit_elt.<locals>.<lambda>  s    QWWr5   r  )r*  r  ru  r  r  r@  ru   r  r.   rB   r/   r   rJ  rC   sort)r/  r  r*  r  
lexemeinfor  s         r   r  z-FramenetCorpusReader._handle_framelexunit_elt  s   w**637!|%'!"",,&Ly'\zCww--0XX)*'+'7'7'A|$!!/2*.*C*CJLRU*V'!!(+!66z|SI
!*//37 '**//&:JOy!((4!!),"77
cJz"))$,,{~~*FG & 	y#45r5   c                    | j                  t               |      }d|d<   d|d<   d|d<   t               |d<   t               |d<   t               |d<   |D ]
  }||v s||=  |D ]  }|j                  j	                  d	      r |j                  j	                  d
      r<|j                  j	                  d      r2d|vr.|j
                  |d<   | j                  |j
                        |d<   |j                  j	                  d      r-d|vr)| j                  |      }||d   j                  |       |j                  j	                  d      r2d|vr.|d   j                  | j                  t               |             |j                  j	                  d      s;d|vsA| j                  t               |      }|d   j                  | j                  |j                                |S )z
        Load full info for a lexical unit from its xml file.
        This should only be called when accessing corpus annotations
        (which are not included in frame files).
        ro   r   r(   r9   r  rk   rb   rg   r  valencesr  r  )r  r*  r  r  r@  ru   r  _handle_lusubcorpus_eltr   ru  rJ  rC   )r/  r  r  r*  r3   r  scr  s           r   r,  z(FramenetCorpusReader._handle_lexunit_elt  s    **8:s;w!|%'!"(l{&Ly'\zAF{1I  Cww)!!*-!!,/L
4R-0XX)*'+'7'7'A|$!!+.;j3P11#6>;'..r2!!(+
0Jy!(()B)B:<QT)UV!!),*1L"77
CHz"))$,,{~~*FG! $ r5   c                    t               }	 |j                  d      |d<   d|d<   g |d<   |D ]F  }|j                  j	                  d      s| j                  |      }|3|d   j                  |       H |S # t        $ r Y yw xY w)z6Load a subcorpus of a lexical unit from the given xml.rB   Nlusubcorpusr   rz   )r*  r   r~  r  r@  _handle_lusentence_eltr   )r/  r  r  r  r   s        r   r  z,FramenetCorpusReader._handle_lusubcorpus_elt  s    Z	BvJ $7:Cww
+//4=zN))!,	  	  		s   A7 7	BBc                 `   | j                  t               |      }d|d<   g |d<   t        j                  t        |      |d<   |D ]  }|j
                  j                  d      r| j                  |j                        |d<   =|j
                  j                  d      sY| j                  |t        |d         dk(        }|~|j                  dk(  sd	|v sJ |       |j                  dk7  r||d
<   dD ]  }||v s||   ||<    |d   j                  |       ||d<   |j                  |d<    |S )z3Load a sentence from a subcorpus of an LU from xml.rF  r   r   r   ru   r   r  r   r   rn  )r   r   r   r   r   r   r]   r   r   r   r   r   r   r   r   r   r   rw   )r  r*  r  r  r   r  r@  r  ru   r  r   r_   r   )r/  r  r  r  annsetr3   s         r   r  z+FramenetCorpusReader._handle_lusentence_elt  sE   ((S9$W "_))t
X Cww'#//9V!!/299T/%:!;q!@ :  %!==G3tv~MvME}}/28./& ;&,QiDG)* )008%)F6N%)YYF6NG H r5   c           	      T   | j                  t               |      }|rdnd|d<   g |d<   t        j                  t        |      |d<   d|v r|S |D ]  }|j
                  j                  d      s | j                  |      }|4g }i }|d   j                  |       |j                  D ]  }d|v rh|j                  |j                  dz   |j                  f}	|j                  d	vr"|	|vsJ |j                  |j                  |	f       |j                  |	       o|j                  |v r6| j                  d
|j                  ||j                     |j                         |j                  ||j                  <    t!        |      }|j                  dk(  r|s,| j                  dj#                  |j                               nt%        d |D              sJ d|v r,| j                  dj#                  |j                               |D 
cg c]
  \  }
}}|
|f c}}}
|d<   |j                  dk(  rm|j&                  dk(  rd|vsJ ||f|d<   d|j&                  cxk  rdk  sn J |j&                         dt)        |j&                        z   }||vsJ ||f||<   M|j                  dv r"|j&                  dk(  sJ |||j                  <   }|j                  dv r'|j&                  dk(  sJ ||d<   |j                  |d<   |r+|j                  dvrG| j                  d|j                         n*|j                  dvr| j                  d|j                         |||j                  <    |s6d|vr2d|vr| j                  d|j                          d|v sJ d|v rd|v sJ |S c c}}}
w )z?Load an annotation set from a sentence in an subcorpus of an LUrI  rG  r   r  r   r  startr   )r   r   zFE with multiple NI entries:r   z3Skipping empty Target layer in annotation set ID={}c              3   .   K   | ]  \  }}}|d k(    yw)r   Nr   )rE   rv   r   lblnames       r   rG   zCFramenetCorpusReader._handle_luannotationset_elt.<locals>.<genexpr>w  s     "RE=1a7h#6Es   z,Annotation set {} has multiple Target layersr   r   r   )r   r   )BNCPENNr]   r   )r   r   z+Unexpected layer in sentence annotationset:)	r   r   r   r   r   r   r   r   r   z(Unexpected layer in frame annotationset:z$Missing target in annotation set ID=r   r   )r  r*  r  r  r   r  r@  _handle_lulayer_eltr   r  r  endrB   rC   r  itypern   r0   allrankr/   )r/  r  r  r  r  r    r   r   r   thespanrv   r   r   r3   s                 r   r  z0FramenetCorpusReader._handle_luannotationset_eltF  s   ((S9.4*:KWW))t
X d?KCww(,,S1=EBM((+ ww"c>'*yy#''A+sxx&HG vv .   (/e'; Wdggqvvw=W W';!LL1"xx2~ $

$B$'HH$&sxxL$'II	!" 03yy388%  '& #5MEvv)$ JJ U \ \$(GG!"
 %""RE"RRRR#t+ JJ N U U$(GG!" GL-Le!Qq!fe-LDN466Q;#'t#33#3*/DJ $%#3!#3;QVV;#3 $s166{ 2A#$D=0=',bkDG</ vv{*{',QVV?2 vv{*{&+U-.VV\*! vv^; $

$Q$%FF!"
  !vv 
. 
  !%

$NPQPVPV!" (-QVVm n '-t#

A$''KL4<<}}$}c .Ms   N#
c                     | j                  t               |      }d|d<   g |d<   |D ]O  }|j                  j                  d      s| j                  t               |      }|<|d   j	                  |       Q |S )z#Load a layer from an annotation setlulayerr   r  r  )r/  r  r  r  r    s        r   r  z(FramenetCorpusReader._handle_lulayer_elt  sv    ))(*c:"ggCww(--hj#>='N))!,	 
 r5   c                    | j                  t               |      }d|d<   d|d<   d|d<   d |d<   d |d<   d |d<   |D ]  }|j                  j                  d      r.|j                  |d<   | j                  |j                        |d<   M|j                  j                  d      r9| j                  t               |      }| j                  |j                        |d<   |j                  j                  d      r| j                  t               |      |d<   |j                  j                  d      s| j                  t               |      |d<    |S )	Nr  r   r(   r9   r  r  r  r  )r  r*  r  r@  ru   r  rJ  rC   )r/  r  r  r  stinfos        r   r  z#FramenetCorpusReader._handle_fe_elt  s0   **8:s;w!|%'!" y#|#|Cww--0XX)*'+'7'7'A|$!!),228:sC$(LL$;y!!!,/'+'@'@S'Q|$!!,/'+'@'@S'Q|$  r5   c                 (   | j                  t               |      }d|d<   d |d<   t               |d<   |D ][  }|j                  .|j                  |d<   | j	                  |j                        |d<   =| j                  t               |      }||d<   ] |S )NrJ  r   rK   rL   r  r9   )r  r*  r  ru   r  )r/  r  r  semtr  supertypeinfos         r   r0  z(FramenetCorpusReader._handle_semtype_elt  s    ((S9!W [%<ZCxx#+.88'(%)%5%5chh%?\" $ 9 9(*c J$1[!  r5   r  )NN)TT)NTT)NNNN)NNNF)?r%  r&  r'  r(  r]  r  r  r-  r  r  r  r  r  r  r  r   r  r
  r[   r   r$  ro   r.  r6  rD  rJ  r<  r  rO  r  r`  r[  re  rh  r{   ru  rm   r  rj  r  r  r;  r1  r  r  r  r  r  r  r  r  r  r  r  r  r  r,  r  r  r  r  r  r0  r   r5   r   r  r  1  s   	 KM I$6Rh-5
#:L&
#AF .0 *GX 24 BH 13 L\
6GB &(dd gR ')  D!$H6r@
H3T
2
hIV
-^S
#@m7^C
*2]
~(
T
(*X)V:B 13 EN  &/b" D#J$,\jX,r5   r  c                     ddl m}  t        d       | j                          t        dt	        | j                                      t        dt	        | j                                      t        dt	        | j                                      t                t        d       | j                  d      }t        d	t	        |       d
       t        |D cg c]  }|j                  |j                  f c}       |d   j                  }| j                  |      }t        dj                  |j                  |j                        t	        |j                               |j                  D ]  }t        d|        t        d|j                   dt	        |j                               t        d|j                  D cg c]  }| c}       t        d|j                   d       t        d|j                  j                         D cg c]  }|j                  dk(  s|j                    c}       t        d       | j                  d      }|j                   j                         D cg c]  }d|v r|j"                  dk(  r| }}t        d|D cg c]  }|j                   c}       t        d|j                   dt	        |j                                t        d|j                   j                         D cg c]  }|j                   c}d d d       |j                   d   j                  }| j%                  |      }t        d|j                          t'        |       t        d       | j)                         D ch c]  }|j*                   }	}t'        t-        |	             t-        |	      d   }
| j                  |
      }t        d|
 d       t'        |D cg c]  }|j.                   c}       t        d       t'        | j1                  d             y c c}w c c}w c c}w c c}w c c}w c c}w c c}w c c}w ) Nr   )framenetzBuilding the indexes...zNumber of Frames:zNumber of Lexical Units:zNumber of annotated documents:zMgetting frames whose name matches the (case insensitive) regex: "(?i)medical"z(?i)medicalzFound z) Frames whose name matches "(?i)medical":z3
Number of frame relations for the "{}" ({}) frame:z   z"
Number of Frame Elements in the "z" frame:z#
The "core" Frame Elements in the "r  z=
All Lexical Units that are incorporated in the "Ailment" FE:   r\   Ailmentz!
Number of Lexical Units in the "r+   r  z...z	ailment.nz
Information on the LU: z:
Names of all of the corpora used for fulltext annotation:z*
Names of the annotated documents in the "z	" corpus:zO
Searching for all Frames that have a lemma that matches the regexp: "^run.v$":z^run.v$)nltk.corpusr  r  r  r   r  r`  rh  rB   rC   r[   r0   r  r   r  r  r  r\   r$  r   re  r  r   r  r   )fn	medframesr  tmp_idm_framefrrF   ailment_lusr*  
allcorpora	firstcorpfirstcorp_docss               r   demor    s   * 

#$OO
 

s299;/0	
$c"&&(m4	
*C	N;	G
 
W 		.)I	F3y>""K
LM	9
-9aAFFADD>9
-.
 q\__FhhvG
 
>EELL'**	
 	G""#	 $$eR % 

-gll^8DGJJ 
%WZZ(Z!Z()
 
0h
GH	%'**"3"3"5N"5Qv9M!&&"5NO 

JKhhsmG ''))Aq Q%5%5%B 	
)  
 
%+.+Q!&&+./
 

,W\\N(CGOO 
$!7!7!9:!9A!9:2A>F
 __[),,F[[ F	%fkk]
34
6N
 

GH&(&6&6&89&8!**&8J9
4

 Z #IWWY'N	7	{)
LM
/1AJJ/0 
Z 2j)*y .6 ) O
 / ; : 0s6   P9	P$
P)
P)
&P.P3
7P8
?P=Q__main__)r)   )r(   r)   r  )8r(  r  r  r  r  r   r  collectionsr   r   r   operatorr   r   nltk.corpus.readerr   r	   	nltk.utilr
   r   r   __docformat__r!   r&   r4   rO   rS   rV   rY   rr   rx   r|   r   r   r   r   r   r   r   r  r"  	Exceptionr$  r   r*  r   rZ  r;  ru  r  r  r  r  r  r  r%  r   r5   r   <module>r%     sF    	 	 
   0 !   = B B,, F1h$,,,^bJ+$aH4BJ(VAH:I :at aH$ :(' ('VO O0P P@*G *4*- *4D/ DDr"? r"pEw+t zF r5   