Skip to content

Instantly share code, notes, and snippets.

@alexeyev
Created February 5, 2020 15:11
Show Gist options
  • Save alexeyev/d6c402c374a7281f83336bca685e26d6 to your computer and use it in GitHub Desktop.
Save alexeyev/d6c402c374a7281f83336bca685e26d6 to your computer and use it in GitHub Desktop.
# coding: utf-8
"""
The MIT License (MIT)
Copyright (c) 2020 Anton Alekseev
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import sys
from conllu import parse
from graphviz import Digraph
from ufal.udpipe import Model, Pipeline, ProcessingError
INPUT_FORMAT = "tokenize"
OUTPUT_FORMAT = "conllu"
MODEL_FILE = "russian-taiga-ud-2.5-191206.udpipe"
print("Loading model:" + MODEL_FILE)
model = Model.load(MODEL_FILE)
print("Loading done")
if not model:
sys.stderr.write("Cannot load model from file '%s'\n" % sys.argv[3])
sys.exit(1)
pipeline = Pipeline(model, INPUT_FORMAT, Pipeline.DEFAULT, Pipeline.DEFAULT, OUTPUT_FORMAT)
error = ProcessingError()
def parse_syntax(raw_text):
"""
Applying UDPipe
:param sentences:
:return:
"""
text = raw_text.strip()
# Process data
processed = pipeline.process(text, error)
if error.occurred():
sys.stderr.write("An error occurred when running run_udpipe: ")
sys.stderr.write(error.message)
sys.stderr.write("\n")
return processed
def parse_output(conll):
"""
Preparing the dep tree for further processing
"""
sentences = parse(conll)
return sentences
def draw_tree(tree):
"""
Drawing a dependency tree for debugging stuff
"""
g = Digraph()
queue = [tree]
print(tree.token)
while len(queue) > 0:
head = queue.pop()
head_label = head.token["form"] + " [%s](%d)" % (head.token["upostag"], head.token["id"])
queue.extend(head.children)
for c in head.children:
c_label = c.token["form"] + " [%s](%d)" % (c.token["upostag"], c.token["id"])
g.edge(head_label, c_label)
g.view()
draw_tree(parse_output(parse_syntax("Однажды утром в Вавилоне пошёл густой снег."))[0].to_tree())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment