toolbox.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. # coding: utf-8
  2. # Natural Language Toolkit: Toolbox Reader
  3. #
  4. # Copyright (C) 2001-2019 NLTK Project
  5. # Author: Greg Aumann <greg_aumann@sil.org>
  6. # URL: <http://nltk.org>
  7. # For license information, see LICENSE.TXT
  8. """
  9. Module for reading, writing and manipulating
  10. Toolbox databases and settings files.
  11. """
  12. from __future__ import print_function
  13. import re, codecs
  14. from xml.etree.ElementTree import ElementTree, TreeBuilder, Element, SubElement
  15. from six import u
  16. from nltk.compat import StringIO, PY3
  17. from nltk.data import PathPointer, find
  18. class StandardFormat(object):
  19. """
  20. Class for reading and processing standard format marker files and strings.
  21. """
  22. def __init__(self, filename=None, encoding=None):
  23. self._encoding = encoding
  24. if filename is not None:
  25. self.open(filename)
  26. def open(self, sfm_file):
  27. """
  28. Open a standard format marker file for sequential reading.
  29. :param sfm_file: name of the standard format marker input file
  30. :type sfm_file: str
  31. """
  32. if isinstance(sfm_file, PathPointer):
  33. # [xx] We don't use 'rU' mode here -- do we need to?
  34. # (PathPointer.open doesn't take a mode option)
  35. self._file = sfm_file.open(self._encoding)
  36. else:
  37. self._file = codecs.open(sfm_file, 'rU', self._encoding)
  38. def open_string(self, s):
  39. """
  40. Open a standard format marker string for sequential reading.
  41. :param s: string to parse as a standard format marker input file
  42. :type s: str
  43. """
  44. self._file = StringIO(s)
  45. def raw_fields(self):
  46. """
  47. Return an iterator that returns the next field in a (marker, value)
  48. tuple. Linebreaks and trailing white space are preserved except
  49. for the final newline in each field.
  50. :rtype: iter(tuple(str, str))
  51. """
  52. join_string = '\n'
  53. line_regexp = r'^%s(?:\\(\S+)\s*)?(.*)$'
  54. # discard a BOM in the first line
  55. first_line_pat = re.compile(line_regexp % '(?:\xef\xbb\xbf)?')
  56. line_pat = re.compile(line_regexp % '')
  57. # need to get first line outside the loop for correct handling
  58. # of the first marker if it spans multiple lines
  59. file_iter = iter(self._file)
  60. # PEP 479, prevent RuntimeError when StopIteration is raised inside generator
  61. try:
  62. line = next(file_iter)
  63. except StopIteration:
  64. # no more data is available, terminate the generator
  65. return
  66. mobj = re.match(first_line_pat, line)
  67. mkr, line_value = mobj.groups()
  68. value_lines = [line_value]
  69. self.line_num = 0
  70. for line in file_iter:
  71. self.line_num += 1
  72. mobj = re.match(line_pat, line)
  73. line_mkr, line_value = mobj.groups()
  74. if line_mkr:
  75. yield (mkr, join_string.join(value_lines))
  76. mkr = line_mkr
  77. value_lines = [line_value]
  78. else:
  79. value_lines.append(line_value)
  80. self.line_num += 1
  81. yield (mkr, join_string.join(value_lines))
  82. def fields(
  83. self,
  84. strip=True,
  85. unwrap=True,
  86. encoding=None,
  87. errors='strict',
  88. unicode_fields=None,
  89. ):
  90. """
  91. Return an iterator that returns the next field in a ``(marker, value)``
  92. tuple, where ``marker`` and ``value`` are unicode strings if an ``encoding``
  93. was specified in the ``fields()`` method. Otherwise they are non-unicode strings.
  94. :param strip: strip trailing whitespace from the last line of each field
  95. :type strip: bool
  96. :param unwrap: Convert newlines in a field to spaces.
  97. :type unwrap: bool
  98. :param encoding: Name of an encoding to use. If it is specified then
  99. the ``fields()`` method returns unicode strings rather than non
  100. unicode strings.
  101. :type encoding: str or None
  102. :param errors: Error handling scheme for codec. Same as the ``decode()``
  103. builtin string method.
  104. :type errors: str
  105. :param unicode_fields: Set of marker names whose values are UTF-8 encoded.
  106. Ignored if encoding is None. If the whole file is UTF-8 encoded set
  107. ``encoding='utf8'`` and leave ``unicode_fields`` with its default
  108. value of None.
  109. :type unicode_fields: sequence
  110. :rtype: iter(tuple(str, str))
  111. """
  112. if encoding is None and unicode_fields is not None:
  113. raise ValueError('unicode_fields is set but not encoding.')
  114. unwrap_pat = re.compile(r'\n+')
  115. for mkr, val in self.raw_fields():
  116. if encoding and not PY3: # kludge - already decoded in PY3?
  117. if unicode_fields is not None and mkr in unicode_fields:
  118. val = val.decode('utf8', errors)
  119. else:
  120. val = val.decode(encoding, errors)
  121. mkr = mkr.decode(encoding, errors)
  122. if unwrap:
  123. val = unwrap_pat.sub(' ', val)
  124. if strip:
  125. val = val.rstrip()
  126. yield (mkr, val)
  127. def close(self):
  128. """Close a previously opened standard format marker file or string."""
  129. self._file.close()
  130. try:
  131. del self.line_num
  132. except AttributeError:
  133. pass
  134. class ToolboxData(StandardFormat):
  135. def parse(self, grammar=None, **kwargs):
  136. if grammar:
  137. return self._chunk_parse(grammar=grammar, **kwargs)
  138. else:
  139. return self._record_parse(**kwargs)
  140. def _record_parse(self, key=None, **kwargs):
  141. """
  142. Returns an element tree structure corresponding to a toolbox data file with
  143. all markers at the same level.
  144. Thus the following Toolbox database::
  145. \_sh v3.0 400 Rotokas Dictionary
  146. \_DateStampHasFourDigitYear
  147. \lx kaa
  148. \ps V.A
  149. \ge gag
  150. \gp nek i pas
  151. \lx kaa
  152. \ps V.B
  153. \ge strangle
  154. \gp pasim nek
  155. after parsing will end up with the same structure (ignoring the extra
  156. whitespace) as the following XML fragment after being parsed by
  157. ElementTree::
  158. <toolbox_data>
  159. <header>
  160. <_sh>v3.0 400 Rotokas Dictionary</_sh>
  161. <_DateStampHasFourDigitYear/>
  162. </header>
  163. <record>
  164. <lx>kaa</lx>
  165. <ps>V.A</ps>
  166. <ge>gag</ge>
  167. <gp>nek i pas</gp>
  168. </record>
  169. <record>
  170. <lx>kaa</lx>
  171. <ps>V.B</ps>
  172. <ge>strangle</ge>
  173. <gp>pasim nek</gp>
  174. </record>
  175. </toolbox_data>
  176. :param key: Name of key marker at the start of each record. If set to
  177. None (the default value) the first marker that doesn't begin with
  178. an underscore is assumed to be the key.
  179. :type key: str
  180. :param kwargs: Keyword arguments passed to ``StandardFormat.fields()``
  181. :type kwargs: dict
  182. :rtype: ElementTree._ElementInterface
  183. :return: contents of toolbox data divided into header and records
  184. """
  185. builder = TreeBuilder()
  186. builder.start('toolbox_data', {})
  187. builder.start('header', {})
  188. in_records = False
  189. for mkr, value in self.fields(**kwargs):
  190. if key is None and not in_records and mkr[0] != '_':
  191. key = mkr
  192. if mkr == key:
  193. if in_records:
  194. builder.end('record')
  195. else:
  196. builder.end('header')
  197. in_records = True
  198. builder.start('record', {})
  199. builder.start(mkr, {})
  200. builder.data(value)
  201. builder.end(mkr)
  202. if in_records:
  203. builder.end('record')
  204. else:
  205. builder.end('header')
  206. builder.end('toolbox_data')
  207. return builder.close()
  208. def _tree2etree(self, parent):
  209. from nltk.tree import Tree
  210. root = Element(parent.label())
  211. for child in parent:
  212. if isinstance(child, Tree):
  213. root.append(self._tree2etree(child))
  214. else:
  215. text, tag = child
  216. e = SubElement(root, tag)
  217. e.text = text
  218. return root
  219. def _chunk_parse(self, grammar=None, root_label='record', trace=0, **kwargs):
  220. """
  221. Returns an element tree structure corresponding to a toolbox data file
  222. parsed according to the chunk grammar.
  223. :type grammar: str
  224. :param grammar: Contains the chunking rules used to parse the
  225. database. See ``chunk.RegExp`` for documentation.
  226. :type root_label: str
  227. :param root_label: The node value that should be used for the
  228. top node of the chunk structure.
  229. :type trace: int
  230. :param trace: The level of tracing that should be used when
  231. parsing a text. ``0`` will generate no tracing output;
  232. ``1`` will generate normal tracing output; and ``2`` or
  233. higher will generate verbose tracing output.
  234. :type kwargs: dict
  235. :param kwargs: Keyword arguments passed to ``toolbox.StandardFormat.fields()``
  236. :rtype: ElementTree._ElementInterface
  237. """
  238. from nltk import chunk
  239. from nltk.tree import Tree
  240. cp = chunk.RegexpParser(grammar, root_label=root_label, trace=trace)
  241. db = self.parse(**kwargs)
  242. tb_etree = Element('toolbox_data')
  243. header = db.find('header')
  244. tb_etree.append(header)
  245. for record in db.findall('record'):
  246. parsed = cp.parse([(elem.text, elem.tag) for elem in record])
  247. tb_etree.append(self._tree2etree(parsed))
  248. return tb_etree
  249. _is_value = re.compile(r"\S")
  250. def to_sfm_string(tree, encoding=None, errors='strict', unicode_fields=None):
  251. """
  252. Return a string with a standard format representation of the toolbox
  253. data in tree (tree can be a toolbox database or a single record).
  254. :param tree: flat representation of toolbox data (whole database or single record)
  255. :type tree: ElementTree._ElementInterface
  256. :param encoding: Name of an encoding to use.
  257. :type encoding: str
  258. :param errors: Error handling scheme for codec. Same as the ``encode()``
  259. builtin string method.
  260. :type errors: str
  261. :param unicode_fields:
  262. :type unicode_fields: dict(str) or set(str)
  263. :rtype: str
  264. """
  265. if tree.tag == 'record':
  266. root = Element('toolbox_data')
  267. root.append(tree)
  268. tree = root
  269. if tree.tag != 'toolbox_data':
  270. raise ValueError("not a toolbox_data element structure")
  271. if encoding is None and unicode_fields is not None:
  272. raise ValueError(
  273. "if encoding is not specified then neither should unicode_fields"
  274. )
  275. l = []
  276. for rec in tree:
  277. l.append('\n')
  278. for field in rec:
  279. mkr = field.tag
  280. value = field.text
  281. if encoding is not None:
  282. if unicode_fields is not None and mkr in unicode_fields:
  283. cur_encoding = 'utf8'
  284. else:
  285. cur_encoding = encoding
  286. if re.search(_is_value, value):
  287. l.append(
  288. (u("\\%s %s\n") % (mkr, value)).encode(cur_encoding, errors)
  289. )
  290. else:
  291. l.append(
  292. (u("\\%s%s\n") % (mkr, value)).encode(cur_encoding, errors)
  293. )
  294. else:
  295. if re.search(_is_value, value):
  296. l.append("\\%s %s\n" % (mkr, value))
  297. else:
  298. l.append("\\%s%s\n" % (mkr, value))
  299. return ''.join(l[1:])
  300. class ToolboxSettings(StandardFormat):
  301. """This class is the base class for settings files."""
  302. def __init__(self):
  303. super(ToolboxSettings, self).__init__()
  304. def parse(self, encoding=None, errors='strict', **kwargs):
  305. """
  306. Return the contents of toolbox settings file with a nested structure.
  307. :param encoding: encoding used by settings file
  308. :type encoding: str
  309. :param errors: Error handling scheme for codec. Same as ``decode()`` builtin method.
  310. :type errors: str
  311. :param kwargs: Keyword arguments passed to ``StandardFormat.fields()``
  312. :type kwargs: dict
  313. :rtype: ElementTree._ElementInterface
  314. """
  315. builder = TreeBuilder()
  316. for mkr, value in self.fields(encoding=encoding, errors=errors, **kwargs):
  317. # Check whether the first char of the field marker
  318. # indicates a block start (+) or end (-)
  319. block = mkr[0]
  320. if block in ("+", "-"):
  321. mkr = mkr[1:]
  322. else:
  323. block = None
  324. # Build tree on the basis of block char
  325. if block == "+":
  326. builder.start(mkr, {})
  327. builder.data(value)
  328. elif block == '-':
  329. builder.end(mkr)
  330. else:
  331. builder.start(mkr, {})
  332. builder.data(value)
  333. builder.end(mkr)
  334. return builder.close()
  335. def to_settings_string(tree, encoding=None, errors='strict', unicode_fields=None):
  336. # write XML to file
  337. l = list()
  338. _to_settings_string(
  339. tree.getroot(),
  340. l,
  341. encoding=encoding,
  342. errors=errors,
  343. unicode_fields=unicode_fields,
  344. )
  345. return ''.join(l)
  346. def _to_settings_string(node, l, **kwargs):
  347. # write XML to file
  348. tag = node.tag
  349. text = node.text
  350. if len(node) == 0:
  351. if text:
  352. l.append('\\%s %s\n' % (tag, text))
  353. else:
  354. l.append('\\%s\n' % tag)
  355. else:
  356. if text:
  357. l.append('\\+%s %s\n' % (tag, text))
  358. else:
  359. l.append('\\+%s\n' % tag)
  360. for n in node:
  361. _to_settings_string(n, l, **kwargs)
  362. l.append('\\-%s\n' % tag)
  363. return
  364. def remove_blanks(elem):
  365. """
  366. Remove all elements and subelements with no text and no child elements.
  367. :param elem: toolbox data in an elementtree structure
  368. :type elem: ElementTree._ElementInterface
  369. """
  370. out = list()
  371. for child in elem:
  372. remove_blanks(child)
  373. if child.text or len(child) > 0:
  374. out.append(child)
  375. elem[:] = out
  376. def add_default_fields(elem, default_fields):
  377. """
  378. Add blank elements and subelements specified in default_fields.
  379. :param elem: toolbox data in an elementtree structure
  380. :type elem: ElementTree._ElementInterface
  381. :param default_fields: fields to add to each type of element and subelement
  382. :type default_fields: dict(tuple)
  383. """
  384. for field in default_fields.get(elem.tag, []):
  385. if elem.find(field) is None:
  386. SubElement(elem, field)
  387. for child in elem:
  388. add_default_fields(child, default_fields)
  389. def sort_fields(elem, field_orders):
  390. """
  391. Sort the elements and subelements in order specified in field_orders.
  392. :param elem: toolbox data in an elementtree structure
  393. :type elem: ElementTree._ElementInterface
  394. :param field_orders: order of fields for each type of element and subelement
  395. :type field_orders: dict(tuple)
  396. """
  397. order_dicts = dict()
  398. for field, order in field_orders.items():
  399. order_dicts[field] = order_key = dict()
  400. for i, subfield in enumerate(order):
  401. order_key[subfield] = i
  402. _sort_fields(elem, order_dicts)
  403. def _sort_fields(elem, orders_dicts):
  404. """sort the children of elem"""
  405. try:
  406. order = orders_dicts[elem.tag]
  407. except KeyError:
  408. pass
  409. else:
  410. tmp = sorted(
  411. [((order.get(child.tag, 1e9), i), child) for i, child in enumerate(elem)]
  412. )
  413. elem[:] = [child for key, child in tmp]
  414. for child in elem:
  415. if len(child):
  416. _sort_fields(child, orders_dicts)
  417. def add_blank_lines(tree, blanks_before, blanks_between):
  418. """
  419. Add blank lines before all elements and subelements specified in blank_before.
  420. :param elem: toolbox data in an elementtree structure
  421. :type elem: ElementTree._ElementInterface
  422. :param blank_before: elements and subelements to add blank lines before
  423. :type blank_before: dict(tuple)
  424. """
  425. try:
  426. before = blanks_before[tree.tag]
  427. between = blanks_between[tree.tag]
  428. except KeyError:
  429. for elem in tree:
  430. if len(elem):
  431. add_blank_lines(elem, blanks_before, blanks_between)
  432. else:
  433. last_elem = None
  434. for elem in tree:
  435. tag = elem.tag
  436. if last_elem is not None and last_elem.tag != tag:
  437. if tag in before and last_elem is not None:
  438. e = last_elem.getiterator()[-1]
  439. e.text = (e.text or "") + "\n"
  440. else:
  441. if tag in between:
  442. e = last_elem.getiterator()[-1]
  443. e.text = (e.text or "") + "\n"
  444. if len(elem):
  445. add_blank_lines(elem, blanks_before, blanks_between)
  446. last_elem = elem
  447. def demo():
  448. from itertools import islice
  449. # zip_path = find('corpora/toolbox.zip')
  450. # lexicon = ToolboxData(ZipFilePathPointer(zip_path, 'toolbox/rotokas.dic')).parse()
  451. file_path = find('corpora/toolbox/rotokas.dic')
  452. lexicon = ToolboxData(file_path).parse()
  453. print('first field in fourth record:')
  454. print(lexicon[3][0].tag)
  455. print(lexicon[3][0].text)
  456. print('\nfields in sequential order:')
  457. for field in islice(lexicon.find('record'), 10):
  458. print(field.tag, field.text)
  459. print('\nlx fields:')
  460. for field in islice(lexicon.findall('record/lx'), 10):
  461. print(field.text)
  462. settings = ToolboxSettings()
  463. file_path = find('corpora/toolbox/MDF/MDF_AltH.typ')
  464. settings.open(file_path)
  465. # settings.open(ZipFilePathPointer(zip_path, entry='toolbox/MDF/MDF_AltH.typ'))
  466. tree = settings.parse(unwrap=False, encoding='cp1252')
  467. print(tree.find('expset/expMDF/rtfPageSetup/paperSize').text)
  468. settings_tree = ElementTree(tree)
  469. print(to_settings_string(settings_tree).encode('utf8'))
  470. if __name__ == '__main__':
  471. demo()