blob: 14e5a9fca74a6d55840e4ac6e6418bc5f1ee8cfc [file] [log] [blame]
dazad7d70752021-01-12 18:17:49 +01001import argparse, os
2import spacy
3from spacy.language import Language
4from spacy.tokens import Doc
5import logging, sys, time
6from lib.CoNLL_Annotation import get_token_type
7import my_utils.file_utils as fu
8from germalemma import GermaLemma
9
10
11@Language.factory("my_component")
12class WhitespaceTokenizer(object):
13 def __init__(self, nlp, name):
14 self.vocab = nlp.vocab
15
16 def __call__(self, text):
17 words = text.split(' ')
18 # All tokens 'own' a subsequent space character in this tokenizer
19 spaces = [True] * len(words)
20 return Doc(self.vocab, words=words, spaces=spaces)
21
22
23def get_conll_str(anno_obj, spacy_doc, use_germalemma):
24 # First lines are comments. (metadata)
25 conll_lines = anno_obj.metadata # Then we want: [ID, FORM, LEMMA, UPOS, XPOS, FEATS, HEAD, DEPREL, DEPS, MISC]
26 for ix, token in enumerate(spacy_doc):
27 if use_germalemma == "True":
28 content = (str(ix), token.text, find_germalemma(token.text, token.tag_, token.lemma_), token.pos_, token.tag_, "_", "_", "_", "_", "_")
29 else:
30 content = (str(ix), token.text, token.lemma_, token.pos_, token.tag_, "_", "_", "_", "_", "_") # Pure SpaCy!
31 conll_lines.append("\t".join(content))
32 return "\n".join(conll_lines)
33
34
35# def freeling_lemma_lookup():
36# dicts_path = "/home/daza/Frameworks/FreeLing/data/de/dictionary/entries/"
37
38def find_germalemma(word, pos, spacy_lemma):
39 simplify_pos = {"ADJA":"ADJ", "ADJD":"ADJ",
40 "NA":"N", "NE":"N", "NN":"N",
41 "ADV":"ADV", "PAV":"ADV", "PROAV":"ADV", "PAVREL":"ADV", "PWAV":"ADV", "PWAVREL":"ADV",
42 "VAFIN":"V", "VAIMP":"V", "VAINF":"V", "VAPP":"V", "VMFIN":"V", "VMINF":"V",
43 "VMPP":"V", "VVFIN":"V", "VVIMP":"V", "VVINF":"V", "VVIZU":"V","VVPP":"V"
44 }
45 # simplify_pos = {"VERB": "V", "ADV": "ADV", "ADJ": "ADJ", "NOUN":"N", "PROPN": "N"}
46 try:
47 return lemmatizer.find_lemma(word, simplify_pos.get(pos, "UNK"))
48 except:
49 return spacy_lemma
50
51
52if __name__ == "__main__":
53 """
54 EXAMPLE:
55 --- TIGER Classic Orthography ---
56 python systems/parse_spacy3.py --corpus_name TigerTestNew \
57 -i /home/daza/datasets/TIGER_conll/data_splits/test/Tiger.NewOrth.test.conll \
58 -o /home/daza/datasets/TIGER_conll/tiger_spacy3_parsed.conllu
59 """
60
61 parser = argparse.ArgumentParser()
62 parser.add_argument("-i", "--input_file", help="Input Corpus", required=True)
63 parser.add_argument("-n", "--corpus_name", help="Corpus Name", default="Corpus")
64 parser.add_argument("-o", "--output_file", help="File where the Predictions will be saved", required=True)
65 parser.add_argument("-sm", "--spacy_model", help="Spacy model containing the pipeline to tag", default="de_core_news_sm")
66 parser.add_argument("-gtt", "--gld_token_type", help="CoNLL Format of the Gold Data", default="CoNLLUP_Token")
67 parser.add_argument("-ugl", "--use_germalemma", help="Use Germalemma lemmatizer on top of SpaCy", default="True")
68 parser.add_argument("-c", "--comment_str", help="CoNLL Format of comentaries inside the file", default="#")
69 args = parser.parse_args()
70
71 file_has_next, chunk_ix = True, 0
72 CHUNK_SIZE = 1000
73 SPACY_BATCH = 100
74 SPACY_PROC = 4
75
76 # =====================================================================================
77 # LOGGING INFO ...
78 # =====================================================================================
79 logger = logging.getLogger(__name__)
80 console_hdlr = logging.StreamHandler(sys.stdout)
81 file_hdlr = logging.FileHandler(filename=f"logs/Parse_{args.corpus_name}.SpaCy.log")
82 logging.basicConfig(level=logging.INFO, handlers=[console_hdlr, file_hdlr])
83 logger.info(f"Chunking {args.corpus_name} Corpus in chunks of {CHUNK_SIZE} Sentences")
84
85 # =====================================================================================
86 # POS TAG DOCUMENTS
87 # =====================================================================================
88
89 if os.path.exists(args.spacy_model):
90 pass # Load Custom Trained model
91 else:
92 # try:
93 spacy_de = spacy.load(args.spacy_model, disable=["ner", "parser"])
94 spacy_de.tokenizer = WhitespaceTokenizer(spacy_de, "keep_original_tokens") # We won't re-tokenize to respect how the source CoNLL are tokenized!
95 # except:
96 # print(f"Check if model {args.spacy_model} is a valid SpaCy Pipeline or if the Path containing the trained model exists!")
97 # exit()
98
99 write_out = open(args.output_file, "w")
100 lemmatizer = GermaLemma()
101
102 if ".gz" == args.input_file[-3:]:
103 in_file = fu.expand_file(args.input_file)
104 else:
105 in_file = args.input_file
106
107 start = time.time()
108 total_processed_sents = 0
109 line_generator = fu.file_generator(in_file)
110 while file_has_next:
111 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)
112 if len(annos) == 0: break
113 total_processed_sents += len(annos)
114 logger.info(f"Already processed {total_processed_sents} sentences...")
115 sents = [a.get_sentence() for a in annos]
116 for ix, doc in enumerate(spacy_de.pipe(sents, batch_size=SPACY_BATCH, n_process=SPACY_PROC)):
117 conll_str = get_conll_str(annos[ix], doc, use_germalemma=args.use_germalemma)
118 write_out.write(conll_str)
119 write_out.write("\n\n")
120
121 end = time.time()
122 logger.info(f"Processing {args.corpus_name} took {(end - start)} seconds!")
123