Debian Codegraph @

bindings/python/linkgrammar.py

raw symbols SCIP
1 # -*- coding: utf8 -*-
2 """
3 High-level Python bindings build on top of the low-level C API (clinkgrammar)
4 See http://www.abisource.com/projects/link-grammar/api/index.html to get
5 more information about C API.
6 """
7
8 try:
9 #pylint: disable=no-name-in-module
10 import linkgrammar.clinkgrammar as clg
11 except ImportError:
12 #pylint: disable=import-error
13 import clinkgrammar as clg
14
15 Clinkgrammar = clg
16 __all__ = ['ParseOptions', 'Dictionary', 'Link', 'Linkage', 'Sentence',
17 'LG_Error', 'LG_DictionaryError', 'LG_TimerExhausted', 'Clinkgrammar']
18
19 # A decorator to ensure keyword-only arguments to __init__ (besides self).
20 # In Python3 it can be done by using "*" as the second __init__ argument,
21 # but here it is done with a decorator so it will work also in Python2.
22 def kwargs_only(init):
23 def new_init(self_, *args, **kwargs):
24 if args:
25 raise TypeError("{}: Positional arguments are "
26 "not allowed".format(self_.__class__.__name__))
27 return init(self_, **kwargs)
28 return new_init
29
30 class ParseOptions(object):
31 @kwargs_only
32 def __init__(self, verbosity=0,
33 linkage_limit=1000,
34 min_null_count=0,
35 max_null_count=0,
36 islands_ok=False,
37 short_length=16,
38 all_short_connectors=False,
39 display_morphology=True,
40 spell_guess=False,
41 use_sat=False,
42 max_parse_time=-1,
43 disjunct_cost=None,
44 repeatable_rand=True,
45 test='',
46 debug='',
47 dialect='',
48 ):
49
50 self._obj = clg.parse_options_create()
51 self.verbosity = verbosity
52 self.linkage_limit = linkage_limit
53 self.min_null_count = min_null_count
54 self.max_null_count = max_null_count
55 self.islands_ok = islands_ok
56 self.short_length = short_length
57 self.all_short_connectors = all_short_connectors
58 self.display_morphology = display_morphology
59 self.spell_guess = spell_guess
60 self.use_sat = use_sat
61 self.max_parse_time = max_parse_time
62 if disjunct_cost is not None:
63 self.disjunct_cost = disjunct_cost
64 self.repeatable_rand = repeatable_rand
65 self.test = test
66 self.debug = debug
67 self.dialect = dialect
68
69 # Allow only the attribute names listed below.
70 def __setattr__(self, name, value):
71 if not hasattr(self, name) and name != "_obj":
72 # TypeError for consistency. It maybe should have been NameError.
73 raise TypeError('Unknown parse option "{}".'.format(name))
74 super(ParseOptions, self).__setattr__(name, value)
75
76 @property
77 def test(self):
78 return clg.parse_options_get_test(self._obj)
79
80 @test.setter
81 def test(self, value):
82 if not isinstance(value, str):
83 raise TypeError("test must be set to a string")
84 return clg.parse_options_set_test(self._obj, value)
85
86 @property
87 def debug(self):
88 return clg.parse_options_get_debug(self._obj)
89
90 @debug.setter
91 def debug(self, value):
92 if not isinstance(value, str):
93 raise TypeError("debug must be set to a string")
94 return clg.parse_options_set_debug(self._obj, value)
95
96 @property
97 def dialect(self):
98 return clg.parse_options_get_dialect(self._obj)
99
100 @dialect.setter
101 def dialect(self, value):
102 if not isinstance(value, str):
103 raise TypeError("dialect must be set to a string")
104 return clg.parse_options_set_dialect(self._obj, value)
105
106 @property
107 def verbosity(self):
108 """
109 This is the level of description printed to stderr/stdout about the
110 parsing process.
111 """
112 return clg.parse_options_get_verbosity(self._obj)
113
114 @verbosity.setter
115 def verbosity(self, value):
116 if not isinstance(value, int):
117 raise TypeError("verbosity must be set to a nonnegative integer")
118 if value < 0:
119 raise ValueError("verbosity must be set to a nonnegative integer")
120 clg.parse_options_set_verbosity(self._obj, value)
121
122 @property
123 def linkage_limit(self):
124 """
125 This parameter determines the maximum number of linkages that are
126 considered in post-processing. If more than linkage_limit linkages
127 found, then a random sample of linkage_limit is chosen for
128 post-processing. When this happen a warning is displayed at verbosity
129 levels bigger than 1.
130 """
131 return clg.parse_options_get_linkage_limit(self._obj)
132
133 @linkage_limit.setter
134 def linkage_limit(self, value):
135 if not isinstance(value, int):
136 raise TypeError("linkage_limit must be set to an integer")
137 if value < 0:
138 raise ValueError("linkage_limit must be positive")
139 clg.parse_options_set_linkage_limit(self._obj, value)
140
141 @property
142 def disjunct_cost(self):
143 """
144 Determines the maximum disjunct cost used during parsing, where the
145 cost of a disjunct is equal to the maximum cost of all of its connectors.
146 The default is that only disjuncts of cost 2.7 or less are considered.
147 """
148 return clg.parse_options_get_disjunct_cost(self._obj)
149
150 @disjunct_cost.setter
151 def disjunct_cost(self, value):
152 if not isinstance(value, float):
153 raise TypeError("disjunct_cost must be set to a float")
154 clg.parse_options_set_disjunct_cost(self._obj, value)
155
156 @property
157 def min_null_count(self):
158 """
159 The minimum number of null links that a parse might have. A call to
160 sentence_parse will find all linkages having the minimum number of
161 null links within the range specified by this parameter.
162 """
163 return clg.parse_options_get_min_null_count(self._obj)
164
165 @min_null_count.setter
166 def min_null_count(self, value):
167 if not isinstance(value, int):
168 raise TypeError("min_null_count must be set to an integer")
169 if value < 0:
170 raise ValueError("min_null_count must be positive")
171 clg.parse_options_set_min_null_count(self._obj, value)
172
173 @property
174 def max_null_count(self):
175 """
176 The maximum number of null links that a parse might have. A call to
177 sentence_parse will find all linkages having the minimum number of
178 null links within the range specified by this parameter.
179 """
180 return clg.parse_options_get_max_null_count(self._obj)
181
182 @max_null_count.setter
183 def max_null_count(self, value):
184 if not isinstance(value, int):
185 raise TypeError("max_null_count must be set to an integer")
186 if value < 0:
187 raise ValueError("max_null_count must be positive")
188 clg.parse_options_set_max_null_count(self._obj, value)
189
190 @property
191 def short_length(self):
192 """
193 The short_length parameter determines how long the links are allowed
194 to be. The intended use of this is to speed up parsing by not
195 considering very long links for most connectors, since they are very
196 rarely used in a correct parse. An entry for UNLIMITED-CONNECTORS in
197 the dictionary will specify which connectors are exempt from the
198 length limit.
199 """
200 return clg.parse_options_get_short_length(self._obj)
201
202 @short_length.setter
203 def short_length(self, value):
204 if not isinstance(value, int):
205 raise TypeError("short_length must be set to an integer")
206 if value < 0:
207 raise ValueError("short_length must be positive")
208 clg.parse_options_set_short_length(self._obj, value)
209
210 @property
211 def islands_ok(self):
212 """
213 This option determines whether or not "islands" of links are allowed.
214 For example, the following linkage has an island:
215 +------Wd-----+
216 | +--Dsu--+---Ss--+-Paf-+ +--Dsu--+---Ss--+--Pa-+
217 | | | | | | | | |
218 ///// this sentence.n is.v false.a this sentence.n is.v true.a
219 """
220 return clg.parse_options_get_islands_ok(self._obj) == 1
221
222 @islands_ok.setter
223 def islands_ok(self, value):
224 if not isinstance(value, bool):
225 raise TypeError("islands_ok must be set to a bool")
226 clg.parse_options_set_islands_ok(self._obj, 1 if value else 0)
227
228 @property
229 def max_parse_time(self):
230 """
231 Determines the approximate maximum time (in seconds) that parsing is
232 allowed to take. After this time has expired, the parsing process is
233 artificially forced to complete quickly by pretending that no further
234 solutions can be constructed. The actual parsing time might be
235 slightly longer.
236 """
237 return clg.parse_options_get_max_parse_time(self._obj)
238
239 @max_parse_time.setter
240 def max_parse_time(self, value):
241 if not isinstance(value, int):
242 raise TypeError("max_parse_time must be set to an integer")
243 clg.parse_options_set_max_parse_time(self._obj, value)
244
245 @property
246 def display_morphology(self):
247 """
248 Whether or not to show word morphology when a linkage diagram is printed.
249 """
250 return clg.parse_options_get_display_morphology(self._obj) == 1
251
252 @display_morphology.setter
253 def display_morphology(self, value):
254 if not isinstance(value, bool):
255 raise TypeError("display_morphology must be set to a bool")
256 clg.parse_options_set_display_morphology(self._obj, 1 if value else 0)
257
258 @property
259 def spell_guess(self):
260 """
261 If greater then 0, the spelling guesser is used on unknown words.
262 In that case, it performs at most this number of spell corrections
263 per word, and performs run-on corrections which are not limited in
264 their number. If 0 - the spelling guesser would not be used.
265 """
266 return clg.parse_options_get_spell_guess(self._obj)
267
268 @spell_guess.setter
269 def spell_guess(self, value):
270 """
271 If the value is an int, it is the maximum number of spell corrections
272 per word. If it is True, an int value of 7 is assumed. A value of
273 0 or False disables the spelling guesser.
274 In case the spelling guesser is not disabled, run-on corrections will
275 be issued too, not limited in their number.
276 """
277 if not isinstance(value, bool) and (not isinstance(value, int) or value < 0):
278 raise TypeError("spell_guess must be set to bool or a non-negative integer")
279 if isinstance(value, bool):
280 value = 7 if value else 0
281 clg.parse_options_set_spell_guess(self._obj, value)
282
283 @property
284 def use_sat(self):
285 """
286 To be used after enabling the use of the SAT solver in order to
287 validate that it is supported by the LG library.
288 """
289 return clg.parse_options_get_use_sat_parser(self._obj)
290
291 @use_sat.setter
292 def use_sat(self, value):
293 if not isinstance(value, bool):
294 raise TypeError("use_sat must be set to a bool")
295 clg.parse_options_set_use_sat_parser(self._obj, value)
296
297 @property
298 def all_short_connectors(self):
299 """
300 If true, then all connectors have length restrictions imposed on
301 them -- they can be no farther than short_length apart. This is
302 used when parsing in \"panic\" mode, for example.
303 """
304 return clg.parse_options_get_all_short_connectors(self._obj) == 1
305
306 @all_short_connectors.setter
307 def all_short_connectors(self, value):
308 if not isinstance(value, bool):
309 raise TypeError("all_short_connectors must be set to a bool")
310 clg.parse_options_set_all_short_connectors(self._obj, 1 if value else 0)
311
312 @property
313 def repeatable_rand(self):
314 """
315 If set to True, then a repeatable random sequence will be used, whenever
316 a random number is required. The parser almost never uses random
317 numbers; currently they are only used in one place: to sample a subset
318 of linkages, if there are more parses than linkage_limit.
319 """
320 return clg.parse_options_get_repeatable_rand(self._obj) == 1
321
322 @repeatable_rand.setter
323 def repeatable_rand(self, value):
324 if not isinstance(value, bool):
325 raise TypeError("repeatable_rand must be set to a bool")
326 clg.parse_options_set_repeatable_rand(self._obj, 1 if value else 0)
327
328
329 class LG_Error(Exception):
330 @staticmethod
331 def set_handler(ehandler_function, ehandler_data=None):
332 old_handler = clg._py_error_set_handler((ehandler_function, ehandler_data))
333 if isinstance(old_handler, str):
334 return LG_Error._default_handler
335 return old_handler
336
337 # lg_error_formatmsg is implemented as method "formatmsg" on errinfo
338 #@staticmethod
339 #def format(lgerror):
340 # return clg.lg_error_formatmsg(lgerror)
341
342 @staticmethod
343 def flush():
344 return clg.lg_error_flush()
345
346 @staticmethod
347 def printall(ehandler_func, ehandler_data=None):
348 return clg._py_error_printall((ehandler_func, ehandler_data))
349
350 @staticmethod
351 def clearall():
352 return clg.lg_error_clearall()
353
354 @staticmethod
355 def message(msg):
356 """Print a message through the LG error facility"""
357 # Propagate a possible ending "\n" into the format, from which the LG
358 # error facility determine if this is a partial or a complete message.
359 if msg[-1:] == "\n": # a newline-ended complete message
360 _local_eol = "\n"
361 msg = msg[:-1]
362 elif msg[-2:] == "\n\\": # a newline-ended partial message
363 _local_eol = ""
364 msg = msg[:-1]
365 else:
366 _local_eol = "" # a partial message
367
368 return clg._prt_error('%s'+_local_eol, msg)
369
370 @staticmethod
371 def _default_handler(errinfo, data):
372 # Exceptions (on data): TypeError, ValueError
373 clg._py_error_default_handler(errinfo, data)
374
375 class LG_DictionaryError(LG_Error):
376 pass
377
378 class Dictionary(object):
379 def __init__(self, lang='en'):
380 self._obj = clg.dictionary_create_lang(lang)
381 if not self._obj:
382 # We should get the error message from the library.
383 raise LG_DictionaryError('Error: Failed to open dictionary {!r}'.format(lang))
384
385 def __str__(self):
386 return clg.dictionary_get_lang(self._obj)
387
388 def __del__(self):
389 if hasattr(self, '_obj'):
390 clg.dictionary_delete(self._obj)
391 del self._obj
392
393 def __nonzero__(self):
394 """Return False iff the dictionary could not be opened or has been closed"""
395 if not hasattr(self, '_obj'):
396 return False
397 return bool(self._obj)
398
399 __bool__ = __nonzero__ # Account python3
400
401 def linkgrammar_get_dict_version(self):
402 return clg.linkgrammar_get_dict_version(self._obj)
403
404 def linkgrammar_get_dict_locale(self):
405 return clg.linkgrammar_get_dict_locale(self._obj)
406
407
408 class Link(object):
409 def __init__(self, linkage, index, left_word, left_label, right_label, right_word):
410 self.linkage, self.index = linkage, index
411 self.left_word, self.right_word, self.left_label, self.right_label = \
412 left_word, right_word, left_label, right_label
413
414 def __eq__(self, other):
415 return self.left_word == other.left_word and self.left_label == other.left_label and \
416 self.right_word == other.right_word and self.right_label == other.right_label
417
418 def __str__(self):
419 if self.left_label == self.right_label:
420 return u"%s-%s-%s" % (self.left_word, self.left_label, self.right_word)
421 else:
422 return u"%s-%s-%s-%s" % (self.left_word, self.left_label, self.right_label, self.right_word)
423
424 def __unicode__(self):
425 return self.__str__()
426
427 def __repr__(self):
428 return u"Link: %s" % self.__str__()
429
430 def __len__(self):
431 return clg.linkage_get_link_length(self.linkage._obj, self.index)
432
433 def num_domains(self):
434 return clg.linkage_get_link_num_domains(self.linkage._obj, self.index)
435
436
437
438 class Linkage(object):
439
440 def __init__(self, idx, sentence, parse_options):
441 # Keep all args passed into clg.* functions.
442 self.sentence, self.parse_options = sentence, parse_options
443 self._obj = clg.linkage_create(idx, sentence._obj, parse_options)
444
445 def __del__(self):
446 if hasattr(self, '_obj'):
447 clg.linkage_delete(self._obj)
448 del self._obj
449
450 def __nonzero__(self):
451 """Return False for SAT sentinel value (NULL); else return True."""
452 return bool(self._obj)
453
454 __bool__ = __nonzero__ # Account python3
455
456 def num_of_words(self):
457 return clg.linkage_get_num_words(self._obj)
458
459 def num_of_links(self):
460 return clg.linkage_get_num_links(self._obj)
461
462 def words(self):
463 for i in range(self.num_of_words()):
464 yield self.word(i)
465
466 def word(self, i):
467 return clg.linkage_get_word(self._obj, i)
468
469 def unused_word_cost(self):
470 return clg.linkage_unused_word_cost(self._obj)
471
472 def link_cost(self):
473 return clg.linkage_link_cost(self._obj)
474
475 def disjunct_cost(self):
476 return clg.linkage_disjunct_cost(self._obj)
477
478 def link(self, i):
479 return Link(self, i, self.word(clg.linkage_get_link_lword(self._obj, i)),
480 clg.linkage_get_link_llabel(self._obj, i),
481 clg.linkage_get_link_rlabel(self._obj, i),
482 self.word(clg.linkage_get_link_rword(self._obj, i)))
483
484 def links(self):
485 for i in range(self.num_of_links()):
486 yield self.link(i)
487
488 def violation_name(self):
489 return clg.linkage_get_violation_name(self._obj)
490
491 def diagram(self, display_walls=False, screen_width=180):
492 return clg.linkage_print_diagram(self._obj, display_walls, screen_width)
493
494 def postscript(self, display_walls=True, print_ps_header=False):
495 return clg.linkage_print_postscript(self._obj, display_walls, print_ps_header)
496
497 def constituent_tree(self, mode=1):
498 return clg.linkage_print_constituent_tree(self._obj, mode)
499
500 def word_byte_start(self, w):
501 return clg.linkage_get_word_byte_start(self._obj, w)
502
503 def word_byte_end(self, w):
504 return clg.linkage_get_word_byte_end(self._obj, w)
505
506 def word_char_start(self, w):
507 return clg.linkage_get_word_char_start(self._obj, w)
508
509 def word_char_end(self, w):
510 return clg.linkage_get_word_char_end(self._obj, w)
511
512
513 class LG_TimerExhausted(LG_Error):
514 pass
515
516
517 class Sentence(object):
518 """
519 sent = Sentence("This is a test.", Dictionary(), ParseOptions())
520 # split() before parse() is optional.
521 # split() has ParseOptions as an optional argument
522 # (defaults to that of Sentence)
523 if sent.split(ParseOptions(verbosity=2)) < 0:
524 print "Cannot split sentence"
525 else
526 linkages = sent.parse()
527 print "English: found ", sent.num_valid_linkages(), "linkages"
528 for linkage in linkages:
529 print linkage.diagram()
530 """
531 def __init__(self, text, lgdict, parse_options):
532 # Keep all args passed into clg.* functions.
533 self.text, self.dict, self.parse_options = text, lgdict, parse_options
534 clg._py_incref(self.dict) # The Sentence struct refers to the Dictionary struct
535 self._obj = clg.sentence_create(self.text, self.dict._obj)
536
537 def __del__(self):
538 if hasattr(self, '_obj'):
539 clg.sentence_delete(self._obj)
540 clg._py_decref(self.dict)
541 del self._obj
542
543 def split(self, parse_options=None):
544 """Split a sentence. If an error occurs, return a negative number."""
545 if not parse_options:
546 parse_options = self.parse_options
547 return clg.sentence_split(self._obj, parse_options._obj)
548
549 def __len__(self):
550 """The number of tokens in the sentence."""
551 return clg.sentence_length(self._obj)
552
553 def null_count(self):
554 """Number of null links in the linkages of this sentence."""
555 return clg.sentence_null_count(self._obj)
556
557 class sentence_parse(object):
558 def __init__(self, sent, parse_options):
559 self.sent = sent
560 self.num = 0
561 self.parse_options = sent.parse_options if parse_options is None else parse_options
562 self.rc = clg.sentence_parse(sent._obj, self.parse_options._obj)
563 if clg.parse_options_timer_expired(self.parse_options._obj):
564 raise LG_TimerExhausted()
565
566 def __nonzero__(self):
567 """Return False if there was a split or parse error; else return True."""
568 return self.rc >= 0
569
570 __bool__ = __nonzero__ # Account python3
571
572 def __iter__(self):
573 if 0 == clg.sentence_num_valid_linkages(self.sent._obj):
574 return iter(())
575 return self
576
577 def __len__(self):
578 return clg.sentence_num_valid_linkages(self.sent._obj)
579
580 def next(self):
581 if self.num == clg.sentence_num_valid_linkages(self.sent._obj):
582 raise StopIteration()
583 linkage = Linkage(self.num, self.sent, self.parse_options._obj)
584 if not linkage: # SAT sentinel value
585 raise StopIteration()
586 self.num += 1
587 return linkage
588
589 __next__ = next # Account python3
590
591 def parse(self, parse_options=None):
592 return self.sentence_parse(self, parse_options)