blob: 1a32b67a7713b1a1e8316382f57c2bfd16056166 [file] [log] [blame]
dazae3bc92e2020-11-04 11:06:26 +01001import argparse
2import spacy
3from spacy.tokens import Doc
4import logging, sys, time
5from lib.CoNLL_Annotation import get_token_type
6import my_utils.file_utils as fu
7from germalemma import GermaLemma
8
9
10class WhitespaceTokenizer(object):
11 def __init__(self, vocab):
12 self.vocab = vocab
13
14 def __call__(self, text):
15 words = text.split(' ')
16 # All tokens 'own' a subsequent space character in this tokenizer
17 spaces = [True] * len(words)
18 return Doc(self.vocab, words=words, spaces=spaces)
19
20
daza85347472020-11-23 18:43:33 +010021def get_conll_str(anno_obj, spacy_doc, use_germalemma):
22 # First lines are comments. (metadata)
23 conll_lines = anno_obj.metadata # Then we want: [ID, FORM, LEMMA, UPOS, XPOS, FEATS, HEAD, DEPREL, DEPS, MISC]
dazae3bc92e2020-11-04 11:06:26 +010024 for ix, token in enumerate(spacy_doc):
25 if use_germalemma == "True":
26 content = (str(ix), token.text, find_germalemma(token.text, token.tag_, token.lemma_), token.pos_, token.tag_, "_", "_", "_", "_", "_")
27 else:
28 content = (str(ix), token.text, token.lemma_, token.pos_, token.tag_, "_", "_", "_", "_", "_") # Pure SpaCy!
29 conll_lines.append("\t".join(content))
30 return "\n".join(conll_lines)
31
32
33# def freeling_lemma_lookup():
34# dicts_path = "/home/daza/Frameworks/FreeLing/data/de/dictionary/entries/"
35
36def find_germalemma(word, pos, spacy_lemma):
37 simplify_pos = {"ADJA":"ADJ", "ADJD":"ADJ",
38 "NA":"N", "NE":"N", "NN":"N",
39 "ADV":"ADV", "PAV":"ADV", "PROAV":"ADV", "PAVREL":"ADV", "PWAV":"ADV", "PWAVREL":"ADV",
40 "VAFIN":"V", "VAIMP":"V", "VAINF":"V", "VAPP":"V", "VMFIN":"V", "VMINF":"V",
41 "VMPP":"V", "VVFIN":"V", "VVIMP":"V", "VVINF":"V", "VVIZU":"V","VVPP":"V"
42 }
43 # simplify_pos = {"VERB": "V", "ADV": "ADV", "ADJ": "ADJ", "NOUN":"N", "PROPN": "N"}
44 try:
45 return lemmatizer.find_lemma(word, simplify_pos.get(pos, "UNK"))
46 except:
47 return spacy_lemma
48
49
50if __name__ == "__main__":
51 """
52 EXAMPLE:
daza85347472020-11-23 18:43:33 +010053 --- TIGER Classic Orthography ---
dazae3bc92e2020-11-04 11:06:26 +010054 python systems/parse_spacy.py --corpus_name Tiger \
55 -i /home/daza/datasets/TIGER_conll/tiger_release_aug07.corrected.16012013.conll09 \
56 -o /home/daza/datasets/TIGER_conll/tiger_spacy_parsed.conllu \
57 -t /home/daza/datasets/TIGER_conll/tiger_all.txt
daza85347472020-11-23 18:43:33 +010058
59 --- TIGER New Orthography ---
60 python systems/parse_spacy.py --corpus_name TigerNew --gld_token_type CoNLLUP_Token \
61 -i /home/daza/datasets/TIGER_conll/Tiger.NewOrth.train.conll \
62 -o /home/daza/datasets/TIGER_conll/Tiger.NewOrth.train.spacy_parsed.conllu \
63 -t /home/daza/datasets/TIGER_conll/Tiger.NewOrth.train.txt
64
65 --- German GSD Universal Deps ---
dazae3bc92e2020-11-04 11:06:26 +010066 python systems/parse_spacy.py --corpus_name DE_GSD --gld_token_type CoNLLUP_Token \
67 -i /home/daza/datasets/ud-treebanks-v2.2/UD_German-GSD/de_gsd-ud-test.conllu \
68 -o /home/daza/datasets/ud-treebanks-v2.2/UD_German-GSD/de_gsd-ud-test.parsed.germalemma.conllu \
daza85347472020-11-23 18:43:33 +010069 -t /home/daza/datasets/ud-treebanks-v2.2/UD_German-GSD/de_gsd-ud-test.txt
70
71
72 --- Real Data TEST ---
73 time python systems/parse_spacy.py --corpus_name DeReKo_a00 --gld_token_type CoNLLUP_Token --comment_str "#" \
74 -i /export/netapp/kupietz/N-GRAMM-STUDIE/conllu/a00.conllu.gz \
75 -o /export/netapp/kupietz/N-GRAMM-STUDIE/conllu/0_SpaCyParsed/a00.spacy.gl.conllu
76
dazae3bc92e2020-11-04 11:06:26 +010077 """
78
79 parser = argparse.ArgumentParser()
80 parser.add_argument("-i", "--input_file", help="Input Corpus", required=True)
81 parser.add_argument("-n", "--corpus_name", help="Corpus Name", default="Corpus")
82 parser.add_argument("-o", "--output_file", help="File where the Predictions will be saved", required=True)
83 parser.add_argument("-t", "--text_file", help="Output Plain Text File", default=None)
84 parser.add_argument("-gtt", "--gld_token_type", help="CoNLL Format of the Gold Data", default="CoNLL09_Token")
85 parser.add_argument("-ugl", "--use_germalemma", help="Use Germalemma lemmatizer on top of SpaCy", default="True")
86 parser.add_argument("-c", "--comment_str", help="CoNLL Format of comentaries inside the file", default="#")
87 args = parser.parse_args()
88
89 file_has_next, chunk_ix = True, 0
daza85347472020-11-23 18:43:33 +010090 CHUNK_SIZE = 100000
91 SPACY_BATCH = 10000
92 SPACY_PROC = 50
dazae3bc92e2020-11-04 11:06:26 +010093
94 # =====================================================================================
95 # LOGGING INFO ...
96 # =====================================================================================
97 logger = logging.getLogger(__name__)
98 console_hdlr = logging.StreamHandler(sys.stdout)
99 file_hdlr = logging.FileHandler(filename=f"logs/Parse_{args.corpus_name}.SpaCy.log")
100 logging.basicConfig(level=logging.INFO, handlers=[console_hdlr, file_hdlr])
101 logger.info(f"Chunking {args.corpus_name} Corpus in chunks of {CHUNK_SIZE} Sentences")
102
103 # =====================================================================================
104 # POS TAG DOCUMENTS
105 # =====================================================================================
106 spacy_de = spacy.load("de_core_news_lg", disable=["ner", "parser"])
107 spacy_de.tokenizer = WhitespaceTokenizer(spacy_de.vocab) # We won't re-tokenize to respect how the source CoNLL are tokenized!
108 write_out = open(args.output_file, "w")
109 lemmatizer = GermaLemma()
110 if args.text_file: write_plain = open(args.text_file, "w")
111
daza85347472020-11-23 18:43:33 +0100112 if ".gz" == args.input_file[-3:]:
113 in_file = fu.expand_file(args.input_file)
114 else:
115 in_file = args.input_file
116
dazae3bc92e2020-11-04 11:06:26 +0100117 start = time.time()
118 total_processed_sents = 0
daza85347472020-11-23 18:43:33 +0100119 line_generator = fu.file_generator(in_file)
dazae3bc92e2020-11-04 11:06:26 +0100120 while file_has_next:
daza85347472020-11-23 18:43:33 +0100121 annos, file_has_next = fu.get_file_annos_chunk(line_generator, chunk_size=CHUNK_SIZE, token_class=get_token_type(args.gld_token_type), comment_str=args.comment_str)
122 if len(annos) == 0: break
123 total_processed_sents += len(annos)
dazae3bc92e2020-11-04 11:06:26 +0100124 logger.info(f"Already processed {total_processed_sents} sentences...")
daza85347472020-11-23 18:43:33 +0100125 sents = [a.get_sentence() for a in annos]
126 for ix, doc in enumerate(spacy_de.pipe(sents, batch_size=SPACY_BATCH, n_process=SPACY_PROC)):
127 conll_str = get_conll_str(annos[ix], doc, use_germalemma=args.use_germalemma)
dazae3bc92e2020-11-04 11:06:26 +0100128 write_out.write(conll_str)
129 write_out.write("\n\n")
130 if args.text_file:
131 write_plain.write(" ".join([x.text for x in doc])+"\n")
132
133 end = time.time()
134 logger.info(f"Processing {args.corpus_name} took {(end - start)} seconds!")
135