
    gE                        d Z ddlZddlZddlmZ ddlmZmZmZm	Z	 ddl
mZmZ  G d d      Z G d d	e      Z ej                  d
      ZddZ G d de      ZddZd Zd Zd Zd Zd Zd Zd Zedk(  r e        yy)zT
Module for reading, writing and manipulating
Toolbox databases and settings files.
    N)StringIO)ElementElementTree
SubElementTreeBuilder)PathPointerfindc                   B    e Zd ZdZd	dZd Zd Zd Z	 	 	 	 	 d
dZd Z	y)StandardFormatzT
    Class for reading and processing standard format marker files and strings.
    Nc                 :    || _         || j                  |       y y N)	_encodingopen)selffilenameencodings      A/var/www/openai/venv/lib/python3.12/site-packages/nltk/toolbox.py__init__zStandardFormat.__init__   s     !IIh      c                     t        |t              r!|j                  | j                        | _        yt        j                  |d| j                        | _        y)z
        Open a standard format marker file for sequential reading.

        :param sfm_file: name of the standard format marker input file
        :type sfm_file: str
        rN)
isinstancer   r   r   _filecodecs)r   sfm_files     r   r   zStandardFormat.open   s:     h,!t~~6DJXsDNNCDJr   c                 $    t        |      | _        y)z
        Open a standard format marker string for sequential reading.

        :param s: string to parse as a standard format marker input file
        :type s: str
        N)r   r   )r   ss     r   open_stringzStandardFormat.open_string+   s     a[
r   c              #   t  K   d}d}t        j                  |dz        }t        j                  |dz        }t        | j                        }	 t	        |      }t        j                  ||      }|j                         \  }}	|	g}
d| _        |D ]n  }| xj                  dz  c_        t        j                  ||      }|j                         \  }}	|r||j                  |
      f |}|	g}
^|
j                  |	       p | xj                  dz  c_        ||j                  |
      f y# t
        $ r Y yw xY ww)z
        Return an iterator that returns the next field in a (marker, value)
        tuple. Linebreaks and trailing white space are preserved except
        for the final newline in each field.

        :rtype: iter(tuple(str, str))
        
z^%s(?:\\(\S+)\s*)?(.*)$u   (?:ï»¿)? Nr      )recompileiterr   nextStopIterationmatchgroupsline_numjoinappend)r   join_stringline_regexpfirst_line_patline_pat	file_iterlinemobjmkr
line_valuevalue_linesline_mkrs               r   
raw_fieldszStandardFormat.raw_fields4   s*     0K2E$EF::kB./ $			?D xx-++-Z!lDMMQM88Hd+D#';;= HjK,,[9::)l"":.  	K$$[122%  		s+   A
D8D) CD8)	D52D84D55D8c              #      K   ||t        d      t        j                  d      }| j                         D ]1  \  }}|r|j	                  d|      }|r|j                         }||f 3 yw)a  
        Return an iterator that returns the next field in a ``(marker, value)``
        tuple, where ``marker`` and ``value`` are unicode strings if an ``encoding``
        was specified in the ``fields()`` method. Otherwise they are non-unicode strings.

        :param strip: strip trailing whitespace from the last line of each field
        :type strip: bool
        :param unwrap: Convert newlines in a field to spaces.
        :type unwrap: bool
        :param encoding: Name of an encoding to use. If it is specified then
            the ``fields()`` method returns unicode strings rather than non
            unicode strings.
        :type encoding: str or None
        :param errors: Error handling scheme for codec. Same as the ``decode()``
            builtin string method.
        :type errors: str
        :param unicode_fields: Set of marker names whose values are UTF-8 encoded.
            Ignored if encoding is None. If the whole file is UTF-8 encoded set
            ``encoding='utf8'`` and leave ``unicode_fields`` with its default
            value of None.
        :type unicode_fields: sequence
        :rtype: iter(tuple(str, str))
        Nz'unicode_fields is set but not encoding.z\n+ )
ValueErrorr#   r$   r8   subrstrip)	r   stripunwrapr   errorsunicode_fields
unwrap_patr4   vals	            r   fieldszStandardFormat.fields[   sm     >  :FGGZZ'
)HC nnS#.jjl* *s   A*A,c                 \    | j                   j                          	 | `y# t        $ r Y yw xY w)z@Close a previously opened standard format marker file or string.N)r   closer*   AttributeError)r   s    r   rF   zStandardFormat.close   s.    

	 		s    	++)NN)TTNstrictN)
__name__
__module____qualname____doc__r   r   r   r8   rD   rF    r   r   r   r      s9     

D!%3R 'Rr   r   c                   *    e Zd ZddZddZd ZddZy)ToolboxDataNc                 R    |r | j                   dd|i|S  | j                  di |S )NgrammarrM   )_chunk_parse_record_parse)r   rQ   kwargss      r   parsezToolboxData.parse   s6    $4$$?W???%4%%///r   c                 "   t               }|j                  di        |j                  di        d} | j                  di |D ]  \  }}||s
|d   dk7  r|}||k(  r9|r|j                  d       n|j                  d       d}|j                  di        |j                  |i        |j	                  |       |j                  |        |r|j                  d       n|j                  d       |j                  d       |j                         S )	a  
        Returns an element tree structure corresponding to a toolbox data file with
        all markers at the same level.

        Thus the following Toolbox database::
            \_sh v3.0  400  Rotokas Dictionary
            \_DateStampHasFourDigitYear

            \lx kaa
            \ps V.A
            \ge gag
            \gp nek i pas

            \lx kaa
            \ps V.B
            \ge strangle
            \gp pasim nek

        after parsing will end up with the same structure (ignoring the extra
        whitespace) as the following XML fragment after being parsed by
        ElementTree::
            <toolbox_data>
                <header>
                    <_sh>v3.0  400  Rotokas Dictionary</_sh>
                    <_DateStampHasFourDigitYear/>
                </header>

                <record>
                    <lx>kaa</lx>
                    <ps>V.A</ps>
                    <ge>gag</ge>
                    <gp>nek i pas</gp>
                </record>

                <record>
                    <lx>kaa</lx>
                    <ps>V.B</ps>
                    <ge>strangle</ge>
                    <gp>pasim nek</gp>
                </record>
            </toolbox_data>

        :param key: Name of key marker at the start of each record. If set to
            None (the default value) the first marker that doesn't begin with
            an underscore is assumed to be the key.
        :type key: str
        :param kwargs: Keyword arguments passed to ``StandardFormat.fields()``
        :type kwargs: dict
        :rtype: ElementTree._ElementInterface
        :return: contents of toolbox data divided into header and records
        toolbox_dataheaderFr   _recordTrM   )r   startrD   enddatarF   )r   keyrT   builder
in_recordsr4   values          r   rS   zToolboxData._record_parse   s    h -nb)h#
%$++//JC{:#a&C-czKK)KK)!%Jh+MM#r"LLKK 0 KK!KK!N#}}r   c                     ddl m} t        |j                               }|D ]G  }t	        ||      r!|j                  | j                  |             0|\  }}t        ||      }||_        I |S )Nr   Tree)		nltk.treerd   r   labelr   r,   _tree2etreer   text)r   parentrd   rootchildrh   tages           r   rg   zToolboxData._tree2etree   sc    "v||~&E%&D,,U34!	ctS)  r   c                    ddl m} ddlm} |j	                  |||      } | j
                  di |}t        d      }	|j                  d      }
|	j                  |
       |j                  d      D ]W  }|j                  |D cg c]  }|j                  |j                  f c}      }|	j                  | j                  |             Y |	S c c}w )	aw  
        Returns an element tree structure corresponding to a toolbox data file
        parsed according to the chunk grammar.

        :type grammar: str
        :param grammar: Contains the chunking rules used to parse the
            database.  See ``chunk.RegExp`` for documentation.
        :type root_label: str
        :param root_label: The node value that should be used for the
            top node of the chunk structure.
        :type trace: int
        :param trace: The level of tracing that should be used when
            parsing a text.  ``0`` will generate no tracing output;
            ``1`` will generate normal tracing output; and ``2`` or
            higher will generate verbose tracing output.
        :type kwargs: dict
        :param kwargs: Keyword arguments passed to ``toolbox.StandardFormat.fields()``
        :rtype: ElementTree._ElementInterface
        r   )chunkrc   )
root_labeltracerW   rX   rZ   rM   )nltkro   re   rd   RegexpParserrU   r   r	   r,   findallrh   rl   rg   )r   rQ   rp   rq   rT   ro   rd   cpdbtb_etreerX   rZ   elemparseds                 r   rR   zToolboxData._chunk_parse   s    ( 	"JeLTZZ!&!>*"jj*FXXH		4884HIFOOD,,V45 +  Is   C
r   )NrZ   r   )rI   rJ   rK   rU   rS   rg   rR   rM   r   r   rO   rO      s    0JXr   rO   z\Sc           	         | j                   dk(  rt        d      }|j                  |        |} | j                   dk7  rt        d      ||t        d      g }| D ]  }|j                  d       |D ]  }|j                   }|j                  }	|v|||v rd}
n|}
t        j                  t        |	      r)|j                  d| d	|	 dj                  |
|             k|j                  d| |	 dj                  |
|             t        j                  t        |	      r|j                  d| d	|	 d       |j                  d| |	 d         d
j                  |dd       S )a@  
    Return a string with a standard format representation of the toolbox
    data in tree (tree can be a toolbox database or a single record).

    :param tree: flat representation of toolbox data (whole database or single record)
    :type tree: ElementTree._ElementInterface
    :param encoding: Name of an encoding to use.
    :type encoding: str
    :param errors: Error handling scheme for codec. Same as the ``encode()``
        builtin string method.
    :type errors: str
    :param unicode_fields:
    :type unicode_fields: dict(str) or set(str)
    :rtype: str
    rZ   rW   z$not a toolbox_data element structureNz?if encoding is not specified then neither should unicode_fieldsr    utf8\r:   r!   r"   )
rl   r   r,   r;   rh   r#   search	_is_valueencoder+   )treer   r@   rA   rj   lrecfieldr4   ra   cur_encodings              r   to_sfm_stringr     sg     xx8~&Dxx>!?@@N6M
 	
 	A	E))CJJE#!-#2G#)L#+L99Y.HH3%qr2::<PQHH3%wb199,OP99Y.HHr#awb12HHr#ugR01!  & 771QR5>r   c                   *     e Zd ZdZ fdZddZ xZS )ToolboxSettingsz0This class is the base class for settings files.c                 "    t         |           y r   )superr   )r   	__class__s    r   r   zToolboxSettings.__init__G  s    r   c                 z   t               } | j                  d||d|D ]  \  }}|d   }|dv r|dd }nd}|dk(  r$|j                  |i        |j                  |       @|dk(  r|j	                  |       W|j                  |i        |j                  |       |j	                  |        |j                         S )	a  
        Return the contents of toolbox settings file with a nested structure.

        :param encoding: encoding used by settings file
        :type encoding: str
        :param errors: Error handling scheme for codec. Same as ``decode()`` builtin method.
        :type errors: str
        :param kwargs: Keyword arguments passed to ``StandardFormat.fields()``
        :type kwargs: dict
        :rtype: ElementTree._ElementInterface
        )r   r@   r   )+-r"   Nr   r   rM   )r   rD   r[   r]   r\   rF   )r   r   r@   rT   r_   r4   ra   blocks           r   rU   zToolboxSettings.parseJ  s     -%$++QxQ&QJC FE
"!"g|c2&U##C c2&U#C # R$ }}r   )NrH   )rI   rJ   rK   rL   r   rU   __classcell__)r   s   @r   r   r   D  s    :r   r   c                 t    t               }t        | j                         ||||       dj                  |      S )N)r   r@   rA   r!   )list_to_settings_stringgetrootr+   )r   r   r@   rA   r   s        r   to_settings_stringr   l  s6    A	% 771:r   c                 ^   | j                   }| j                  }t        |       dk(  r0|r|j                  d| d| d       y |j                  d|z         y |r|j                  d| d| d       n|j                  d|z         | D ]  }t	        ||fi |  |j                  d|z         y )	Nr   r|   r:   r    z\%s
z\+z\+%s
z\-%s
)rl   rh   lenr,   r   )noder   rT   rl   rh   ns         r   r   r   y  s    
((C99D
4yA~HHr#avR()  HHX^$  HHs3%qb)*HHY_%A1// 	S!
r   c                     t               }| D ]9  }t        |       |j                  st        |      dkD  s)|j	                  |       ; || dd y)z
    Remove all elements and subelements with no text and no child elements.

    :param elem: toolbox data in an elementtree structure
    :type elem: ElementTree._ElementInterface
    r   N)r   remove_blanksrh   r   r,   )rx   outrk   s      r   r   r     sE     &Ce::UaJJu  DGr   c                     |j                  | j                  g       D ]   }| j                  |      t        | |       " | D ]  }t	        ||        y)a(  
    Add blank elements and subelements specified in default_fields.

    :param elem: toolbox data in an elementtree structure
    :type elem: ElementTree._ElementInterface
    :param default_fields: fields to add to each type of element and subelement
    :type default_fields: dict(tuple)
    N)getrl   r	   r   add_default_fields)rx   default_fieldsr   rk   s       r   r   r     sN      ##DHHb199U#tU# 2 5.1 r   c                     t               }|j                         D ],  \  }}t               x||<   }t        |      D ]
  \  }}|||<    . t        | |       y)a-  
    Sort the elements and subelements in order specified in field_orders.

    :param elem: toolbox data in an elementtree structure
    :type elem: ElementTree._ElementInterface
    :param field_orders: order of fields for each type of element and subelement
    :type field_orders: dict(tuple)
    N)dictitems	enumerate_sort_fields)rx   field_ordersorder_dictsr   order	order_keyisubfields           r   sort_fieldsr     s\     &K$**,u)-/EY$U+KAx"#Ih , - {#r   c                     	 || j                      t        fdt        |       D              }|D cg c]  \  }}|	 c}}| dd | D ]  }t	        |      st        ||        yc c}}w # t        $ r Y 1w xY w)zsort the children of elemc              3   d   K   | ]'  \  }}j                  |j                  d       |f|f ) yw)g    eAN)r   rl   ).0r   rk   r   s      r   	<genexpr>z_sort_fields.<locals>.<genexpr>  s2      
DS5eii		3'+U3Os   -0N)rl   sortedr   KeyErrorr   r   )rx   orders_dictstmpr^   rk   r   s        @r   r   r     s    0TXX&  
DMdO
 
 ,//3ZS%53/Qu:-  0  s   A- A'-	A98A9c                    	 || j                      }|| j                      }d}| D ]  }|j                   }|A|j                   |k7  r2||v r]|[|j                         d   }|j                  xs ddz   |_        n/||v r+|j                         d   }|j                  xs ddz   |_        t        |      rt	        |||       |} y# t
        $ r# | D ]  }t        |      st	        |||        Y yw xY w)a1  
    Add blank lines before all elements and subelements specified in blank_before.

    :param elem: toolbox data in an elementtree structure
    :type elem: ElementTree._ElementInterface
    :param blank_before: elements and subelements to add blank lines before
    :type blank_before: dict(tuple)
    Nr!   r    )rl   getiteratorrh   r   add_blank_linesr   )	r   blanks_beforeblanks_betweenbeforebetween	last_elemrx   rl   rm   s	            r   r   r     s    txx( * 	D((C$#)=&=Y%:!--/3Affld2AF'>!--/3Affld2AF4ym^DI   ED4ym^D Es   C C.C.-C.c                     ddl m}  t        d      }t        |      j	                         }t        d       t        |d   d   j                         t        |d   d   j                         t        d        | |j                  d      d      D ]"  }t        |j                  |j                         $ t        d	        | |j                  d
      d      D ]  }t        |j                          t               }t        d      }|j                  |       |j	                  dd      }t        |j                  d      j                         t        |      }t        t        |      j                  d             y )Nr   )islicezcorpora/toolbox/rotokas.diczfirst field in fourth record:   z
fields in sequential order:rZ   
   z
lx fields:z	record/lxz corpora/toolbox/MDF/MDF_AltH.typFcp1252)r?   r   z$expset/expMDF/rtfPageSetup/paperSizer{   )	itertoolsr   r	   rO   rU   printrl   rh   rt   r   r   r   r   r   )r   	file_pathlexiconr   settingsr   settings_trees          r   demor     s-     23I)$**,G	
)*	'!*Q-

	'!*Q-

	
)*X.3eii$ 4 
.4b9ejj :  H78IMM)>>>:D	$)):
;
@
@A%M	
]
+
2
26
:;r   __main__)NrH   N)rL   r   r#   ior   xml.etree.ElementTreer   r   r   r   	nltk.datar   r	   r   rO   r$   r~   r   r   r   r   r   r   r   r   r   r   rI   rM   r   r   <module>r      s   
  	  O O 'u up. D BJJu	/d%n %P
(2 $". B<: zF r   