blob: 90ca23764d97409bc24ad621062047d907e87bf0 [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
dazae3bc92e2020-11-04 11:06:26 +010032
33def find_germalemma(word, pos, spacy_lemma):
34 simplify_pos = {"ADJA":"ADJ", "ADJD":"ADJ",
35 "NA":"N", "NE":"N", "NN":"N",
36 "ADV":"ADV", "PAV":"ADV", "PROAV":"ADV", "PAVREL":"ADV", "PWAV":"ADV", "PWAVREL":"ADV",
37 "VAFIN":"V", "VAIMP":"V", "VAINF":"V", "VAPP":"V", "VMFIN":"V", "VMINF":"V",
38 "VMPP":"V", "VVFIN":"V", "VVIMP":"V", "VVINF":"V", "VVIZU":"V","VVPP":"V"
39 }
40 # simplify_pos = {"VERB": "V", "ADV": "ADV", "ADJ": "ADJ", "NOUN":"N", "PROPN": "N"}
41 try:
42 return lemmatizer.find_lemma(word, simplify_pos.get(pos, "UNK"))
43 except:
44 return spacy_lemma
45
46
47if __name__ == "__main__":
48 """
49 EXAMPLE:
daza85347472020-11-23 18:43:33 +010050 --- TIGER Classic Orthography ---
dazad7d70752021-01-12 18:17:49 +010051 python systems/parse_spacy.py --corpus_name Tiger --gld_token_type CoNLL09_Token \
dazae3bc92e2020-11-04 11:06:26 +010052 -i /home/daza/datasets/TIGER_conll/tiger_release_aug07.corrected.16012013.conll09 \
53 -o /home/daza/datasets/TIGER_conll/tiger_spacy_parsed.conllu \
54 -t /home/daza/datasets/TIGER_conll/tiger_all.txt
dazad7d70752021-01-12 18:17:49 +010055
56 python systems/parse_spacy.py --corpus_name TigerOld_test \
57 -i /home/daza/datasets/TIGER_conll/data_splits/test/Tiger.OldOrth.test.conll \
58 -o /home/daza/datasets/TIGER_conll/tiger_spacy_parsed.test.conllu
daza85347472020-11-23 18:43:33 +010059
60 --- TIGER New Orthography ---
dazad7d70752021-01-12 18:17:49 +010061 python systems/parse_spacy.py --corpus_name TigerNew \
daza85347472020-11-23 18:43:33 +010062 -i /home/daza/datasets/TIGER_conll/Tiger.NewOrth.train.conll \
63 -o /home/daza/datasets/TIGER_conll/Tiger.NewOrth.train.spacy_parsed.conllu \
64 -t /home/daza/datasets/TIGER_conll/Tiger.NewOrth.train.txt
dazad7d70752021-01-12 18:17:49 +010065
66 python systems/parse_spacy.py --corpus_name TigerNew_test \
67 -i /home/daza/datasets/TIGER_conll/data_splits/test/Tiger.NewOrth.test.conll \
68 -o /home/daza/datasets/TIGER_conll/Tiger.NewOrth.test.spacy_parsed.conllu
daza85347472020-11-23 18:43:33 +010069
70 --- German GSD Universal Deps ---
dazad7d70752021-01-12 18:17:49 +010071 python systems/parse_spacy.py --corpus_name DE_GSD \
dazae3bc92e2020-11-04 11:06:26 +010072 -i /home/daza/datasets/ud-treebanks-v2.2/UD_German-GSD/de_gsd-ud-test.conllu \
73 -o /home/daza/datasets/ud-treebanks-v2.2/UD_German-GSD/de_gsd-ud-test.parsed.germalemma.conllu \
daza85347472020-11-23 18:43:33 +010074 -t /home/daza/datasets/ud-treebanks-v2.2/UD_German-GSD/de_gsd-ud-test.txt
75
76
77 --- Real Data TEST ---
dazad7d70752021-01-12 18:17:49 +010078 time python systems/parse_spacy.py --corpus_name DeReKo_a00 --comment_str "#" \
daza85347472020-11-23 18:43:33 +010079 -i /export/netapp/kupietz/N-GRAMM-STUDIE/conllu/a00.conllu.gz \
80 -o /export/netapp/kupietz/N-GRAMM-STUDIE/conllu/0_SpaCyParsed/a00.spacy.gl.conllu
dazae3bc92e2020-11-04 11:06:26 +010081 """
82
83 parser = argparse.ArgumentParser()
84 parser.add_argument("-i", "--input_file", help="Input Corpus", required=True)
85 parser.add_argument("-n", "--corpus_name", help="Corpus Name", default="Corpus")
86 parser.add_argument("-o", "--output_file", help="File where the Predictions will be saved", required=True)
87 parser.add_argument("-t", "--text_file", help="Output Plain Text File", default=None)
dazad7d70752021-01-12 18:17:49 +010088 parser.add_argument("-sm", "--spacy_model", help="Spacy model containing the pipeline to tag", default="de_core_news_lg")
89 parser.add_argument("-gtt", "--gld_token_type", help="CoNLL Format of the Gold Data", default="CoNLLUP_Token")
dazae3bc92e2020-11-04 11:06:26 +010090 parser.add_argument("-ugl", "--use_germalemma", help="Use Germalemma lemmatizer on top of SpaCy", default="True")
91 parser.add_argument("-c", "--comment_str", help="CoNLL Format of comentaries inside the file", default="#")
92 args = parser.parse_args()
93
94 file_has_next, chunk_ix = True, 0
dazad7d70752021-01-12 18:17:49 +010095 CHUNK_SIZE = 20000
96 SPACY_BATCH = 2000
97 SPACY_PROC = 10
dazae3bc92e2020-11-04 11:06:26 +010098
99 # =====================================================================================
100 # LOGGING INFO ...
101 # =====================================================================================
102 logger = logging.getLogger(__name__)
103 console_hdlr = logging.StreamHandler(sys.stdout)
104 file_hdlr = logging.FileHandler(filename=f"logs/Parse_{args.corpus_name}.SpaCy.log")
105 logging.basicConfig(level=logging.INFO, handlers=[console_hdlr, file_hdlr])
106 logger.info(f"Chunking {args.corpus_name} Corpus in chunks of {CHUNK_SIZE} Sentences")
107
108 # =====================================================================================
109 # POS TAG DOCUMENTS
110 # =====================================================================================
dazad7d70752021-01-12 18:17:49 +0100111 spacy_de = spacy.load(args.spacy_model, disable=["ner", "parser"])
dazae3bc92e2020-11-04 11:06:26 +0100112 spacy_de.tokenizer = WhitespaceTokenizer(spacy_de.vocab) # We won't re-tokenize to respect how the source CoNLL are tokenized!
113 write_out = open(args.output_file, "w")
114 lemmatizer = GermaLemma()
115 if args.text_file: write_plain = open(args.text_file, "w")
116
daza85347472020-11-23 18:43:33 +0100117 if ".gz" == args.input_file[-3:]:
118 in_file = fu.expand_file(args.input_file)
119 else:
120 in_file = args.input_file
121
dazae3bc92e2020-11-04 11:06:26 +0100122 start = time.time()
123 total_processed_sents = 0
daza85347472020-11-23 18:43:33 +0100124 line_generator = fu.file_generator(in_file)
dazae3bc92e2020-11-04 11:06:26 +0100125 while file_has_next:
daza85347472020-11-23 18:43:33 +0100126 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)
127 if len(annos) == 0: break
128 total_processed_sents += len(annos)
dazae3bc92e2020-11-04 11:06:26 +0100129 logger.info(f"Already processed {total_processed_sents} sentences...")
daza85347472020-11-23 18:43:33 +0100130 sents = [a.get_sentence() for a in annos]
131 for ix, doc in enumerate(spacy_de.pipe(sents, batch_size=SPACY_BATCH, n_process=SPACY_PROC)):
132 conll_str = get_conll_str(annos[ix], doc, use_germalemma=args.use_germalemma)
dazae3bc92e2020-11-04 11:06:26 +0100133 write_out.write(conll_str)
134 write_out.write("\n\n")
135 if args.text_file:
136 write_plain.write(" ".join([x.text for x in doc])+"\n")
137
138 end = time.time()
139 logger.info(f"Processing {args.corpus_name} took {(end - start)} seconds!")
140