| 6 | |
| 7 | |
| 8 | class Model: |
| 9 | def __init__(self, path): |
| 10 | """Load given model.""" |
| 11 | self.model = ufal.udpipe.Model.load(path) |
| 12 | if not self.model: |
| 13 | raise Exception("Cannot load UDPipe model from file '%s'" % path) |
| 14 | |
| 15 | def tokenize(self, text, *args): |
| 16 | """Tokenize the text and return list of ufal.udpipe.Sentence-s.""" |
| 17 | tokenizer = self.model.newTokenizer(*args) |
| 18 | if not tokenizer: |
| 19 | raise Exception("The model does not have a tokenizer") |
| 20 | return self._read(text, tokenizer) |
| 21 | |
| 22 | def read(self, text, in_format): |
| 23 | """Load text in the given format (conllu|horizontal|vertical) and return list of ufal.udpipe.Sentence-s.""" |
| 24 | input_format = ufal.udpipe.InputFormat.newInputFormat(in_format) |
| 25 | if not input_format: |
| 26 | raise Exception("Cannot create input format '%s'" % in_format) |
| 27 | return self._read(text, input_format) |
| 28 | |
| 29 | def _read(self, text, input_format): |
| 30 | input_format.setText(text) |
| 31 | error = ufal.udpipe.ProcessingError() |
| 32 | sentences = [] |
| 33 | |
| 34 | sentence = ufal.udpipe.Sentence() |
| 35 | while input_format.nextSentence(sentence, error): |
| 36 | sentences.append(sentence) |
| 37 | sentence = ufal.udpipe.Sentence() |
| 38 | if error.occurred(): |
| 39 | raise Exception(error.message) |
| 40 | |
| 41 | return sentences |
| 42 | |
| 43 | def tag(self, sentence): |
| 44 | """Tag the given ufal.udpipe.Sentence (inplace).""" |
| 45 | self.model.tag(sentence, self.model.DEFAULT) |
| 46 | |
| 47 | def parse(self, sentence): |
| 48 | """Parse the given ufal.udpipe.Sentence (inplace).""" |
| 49 | self.model.parse(sentence, self.model.DEFAULT) |
| 50 | |
| 51 | def write(self, sentences, out_format): |
| 52 | """Write given ufal.udpipe.Sentence-s in the required format (conllu|horizontal|vertical).""" |
| 53 | |
| 54 | output_format = ufal.udpipe.OutputFormat.newOutputFormat(out_format) |
| 55 | output = '' |
| 56 | for sentence in sentences: |
| 57 | output += output_format.writeSentence(sentence) |
| 58 | output += output_format.finishDocument() |
| 59 | |
| 60 | return output |
no outgoing calls
no test coverage detected