blob: d2bf1b1a205b5b88e8d49e6461093c338598993e [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
Marc Kupietz88eea722025-10-26 15:21:14 +01009def format_morphological_features(token):
10 """
11 Extract and format morphological features from a spaCy token for CoNLL-U output.
12
13 Args:
14 token: spaCy token object
15
16 Returns:
17 str: Formatted morphological features string for CoNLL-U 5th column
18 Returns "_" if no features are available
19 """
20 if not hasattr(token, 'morph') or not token.morph:
21 return "_"
22
23 morph_dict = token.morph.to_dict()
24 if not morph_dict:
25 return "_"
26
27 # Format as CoNLL-U format: Feature=Value|Feature2=Value2
28 features = []
29 for feature, value in sorted(morph_dict.items()):
30 features.append(f"{feature}={value}")
31
32 return "|".join(features)
33
dazae3bc92e2020-11-04 11:06:26 +010034
35class WhitespaceTokenizer(object):
36 def __init__(self, vocab):
37 self.vocab = vocab
38
39 def __call__(self, text):
40 words = text.split(' ')
41 # All tokens 'own' a subsequent space character in this tokenizer
42 spaces = [True] * len(words)
43 return Doc(self.vocab, words=words, spaces=spaces)
44
45
daza85347472020-11-23 18:43:33 +010046def get_conll_str(anno_obj, spacy_doc, use_germalemma):
47 # First lines are comments. (metadata)
48 conll_lines = anno_obj.metadata # Then we want: [ID, FORM, LEMMA, UPOS, XPOS, FEATS, HEAD, DEPREL, DEPS, MISC]
dazae3bc92e2020-11-04 11:06:26 +010049 for ix, token in enumerate(spacy_doc):
Marc Kupietz88eea722025-10-26 15:21:14 +010050 morph_features = format_morphological_features(token)
dazae3bc92e2020-11-04 11:06:26 +010051 if use_germalemma == "True":
Marc Kupietz88eea722025-10-26 15:21:14 +010052 content = (str(ix), token.text, find_germalemma(token.text, token.tag_, token.lemma_), token.pos_, token.tag_, morph_features, "_", "_", "_", "_")
dazae3bc92e2020-11-04 11:06:26 +010053 else:
Marc Kupietz88eea722025-10-26 15:21:14 +010054 content = (str(ix), token.text, token.lemma_, token.pos_, token.tag_, morph_features, "_", "_", "_", "_") # Pure SpaCy!
dazae3bc92e2020-11-04 11:06:26 +010055 conll_lines.append("\t".join(content))
56 return "\n".join(conll_lines)
57
dazae3bc92e2020-11-04 11:06:26 +010058
59def find_germalemma(word, pos, spacy_lemma):
60 simplify_pos = {"ADJA":"ADJ", "ADJD":"ADJ",
61 "NA":"N", "NE":"N", "NN":"N",
62 "ADV":"ADV", "PAV":"ADV", "PROAV":"ADV", "PAVREL":"ADV", "PWAV":"ADV", "PWAVREL":"ADV",
63 "VAFIN":"V", "VAIMP":"V", "VAINF":"V", "VAPP":"V", "VMFIN":"V", "VMINF":"V",
64 "VMPP":"V", "VVFIN":"V", "VVIMP":"V", "VVINF":"V", "VVIZU":"V","VVPP":"V"
65 }
66 # simplify_pos = {"VERB": "V", "ADV": "ADV", "ADJ": "ADJ", "NOUN":"N", "PROPN": "N"}
67 try:
68 return lemmatizer.find_lemma(word, simplify_pos.get(pos, "UNK"))
69 except:
70 return spacy_lemma
71
72
73if __name__ == "__main__":
74 """
75 EXAMPLE:
daza85347472020-11-23 18:43:33 +010076 --- TIGER Classic Orthography ---
dazad7d70752021-01-12 18:17:49 +010077 python systems/parse_spacy.py --corpus_name Tiger --gld_token_type CoNLL09_Token \
dazae3bc92e2020-11-04 11:06:26 +010078 -i /home/daza/datasets/TIGER_conll/tiger_release_aug07.corrected.16012013.conll09 \
79 -o /home/daza/datasets/TIGER_conll/tiger_spacy_parsed.conllu \
80 -t /home/daza/datasets/TIGER_conll/tiger_all.txt
dazad7d70752021-01-12 18:17:49 +010081
82 python systems/parse_spacy.py --corpus_name TigerOld_test \
83 -i /home/daza/datasets/TIGER_conll/data_splits/test/Tiger.OldOrth.test.conll \
84 -o /home/daza/datasets/TIGER_conll/tiger_spacy_parsed.test.conllu
daza85347472020-11-23 18:43:33 +010085
86 --- TIGER New Orthography ---
dazad7d70752021-01-12 18:17:49 +010087 python systems/parse_spacy.py --corpus_name TigerNew \
daza85347472020-11-23 18:43:33 +010088 -i /home/daza/datasets/TIGER_conll/Tiger.NewOrth.train.conll \
89 -o /home/daza/datasets/TIGER_conll/Tiger.NewOrth.train.spacy_parsed.conllu \
90 -t /home/daza/datasets/TIGER_conll/Tiger.NewOrth.train.txt
dazad7d70752021-01-12 18:17:49 +010091
92 python systems/parse_spacy.py --corpus_name TigerNew_test \
93 -i /home/daza/datasets/TIGER_conll/data_splits/test/Tiger.NewOrth.test.conll \
94 -o /home/daza/datasets/TIGER_conll/Tiger.NewOrth.test.spacy_parsed.conllu
daza85347472020-11-23 18:43:33 +010095
96 --- German GSD Universal Deps ---
dazad7d70752021-01-12 18:17:49 +010097 python systems/parse_spacy.py --corpus_name DE_GSD \
dazae3bc92e2020-11-04 11:06:26 +010098 -i /home/daza/datasets/ud-treebanks-v2.2/UD_German-GSD/de_gsd-ud-test.conllu \
99 -o /home/daza/datasets/ud-treebanks-v2.2/UD_German-GSD/de_gsd-ud-test.parsed.germalemma.conllu \
daza85347472020-11-23 18:43:33 +0100100 -t /home/daza/datasets/ud-treebanks-v2.2/UD_German-GSD/de_gsd-ud-test.txt
101
102
103 --- Real Data TEST ---
dazad7d70752021-01-12 18:17:49 +0100104 time python systems/parse_spacy.py --corpus_name DeReKo_a00 --comment_str "#" \
daza85347472020-11-23 18:43:33 +0100105 -i /export/netapp/kupietz/N-GRAMM-STUDIE/conllu/a00.conllu.gz \
106 -o /export/netapp/kupietz/N-GRAMM-STUDIE/conllu/0_SpaCyParsed/a00.spacy.gl.conllu
dazae3bc92e2020-11-04 11:06:26 +0100107 """
108
109 parser = argparse.ArgumentParser()
110 parser.add_argument("-i", "--input_file", help="Input Corpus", required=True)
111 parser.add_argument("-n", "--corpus_name", help="Corpus Name", default="Corpus")
112 parser.add_argument("-o", "--output_file", help="File where the Predictions will be saved", required=True)
113 parser.add_argument("-t", "--text_file", help="Output Plain Text File", default=None)
dazad7d70752021-01-12 18:17:49 +0100114 parser.add_argument("-sm", "--spacy_model", help="Spacy model containing the pipeline to tag", default="de_core_news_lg")
115 parser.add_argument("-gtt", "--gld_token_type", help="CoNLL Format of the Gold Data", default="CoNLLUP_Token")
dazae3bc92e2020-11-04 11:06:26 +0100116 parser.add_argument("-ugl", "--use_germalemma", help="Use Germalemma lemmatizer on top of SpaCy", default="True")
117 parser.add_argument("-c", "--comment_str", help="CoNLL Format of comentaries inside the file", default="#")
118 args = parser.parse_args()
119
120 file_has_next, chunk_ix = True, 0
dazad7d70752021-01-12 18:17:49 +0100121 CHUNK_SIZE = 20000
122 SPACY_BATCH = 2000
123 SPACY_PROC = 10
dazae3bc92e2020-11-04 11:06:26 +0100124
125 # =====================================================================================
126 # LOGGING INFO ...
127 # =====================================================================================
128 logger = logging.getLogger(__name__)
129 console_hdlr = logging.StreamHandler(sys.stdout)
130 file_hdlr = logging.FileHandler(filename=f"logs/Parse_{args.corpus_name}.SpaCy.log")
131 logging.basicConfig(level=logging.INFO, handlers=[console_hdlr, file_hdlr])
132 logger.info(f"Chunking {args.corpus_name} Corpus in chunks of {CHUNK_SIZE} Sentences")
133
134 # =====================================================================================
135 # POS TAG DOCUMENTS
136 # =====================================================================================
dazad7d70752021-01-12 18:17:49 +0100137 spacy_de = spacy.load(args.spacy_model, disable=["ner", "parser"])
dazae3bc92e2020-11-04 11:06:26 +0100138 spacy_de.tokenizer = WhitespaceTokenizer(spacy_de.vocab) # We won't re-tokenize to respect how the source CoNLL are tokenized!
139 write_out = open(args.output_file, "w")
140 lemmatizer = GermaLemma()
Marc Kupietzf629a402025-10-26 21:54:33 +0100141
142 # Log version information
143 logger.info(f"spaCy version: {spacy.__version__}")
144 logger.info(f"spaCy model: {args.spacy_model}")
145 logger.info(f"spaCy model version: {spacy_de.meta.get('version', 'unknown')}")
146 try:
147 import germalemma
148 logger.info(f"GermaLemma version: {germalemma.__version__}")
149 except AttributeError:
150 logger.info("GermaLemma version: unknown (no __version__ attribute)")
dazae3bc92e2020-11-04 11:06:26 +0100151 if args.text_file: write_plain = open(args.text_file, "w")
152
daza85347472020-11-23 18:43:33 +0100153 if ".gz" == args.input_file[-3:]:
154 in_file = fu.expand_file(args.input_file)
155 else:
156 in_file = args.input_file
157
dazae3bc92e2020-11-04 11:06:26 +0100158 start = time.time()
159 total_processed_sents = 0
daza85347472020-11-23 18:43:33 +0100160 line_generator = fu.file_generator(in_file)
dazae3bc92e2020-11-04 11:06:26 +0100161 while file_has_next:
daza85347472020-11-23 18:43:33 +0100162 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)
163 if len(annos) == 0: break
164 total_processed_sents += len(annos)
dazae3bc92e2020-11-04 11:06:26 +0100165 logger.info(f"Already processed {total_processed_sents} sentences...")
daza85347472020-11-23 18:43:33 +0100166 sents = [a.get_sentence() for a in annos]
167 for ix, doc in enumerate(spacy_de.pipe(sents, batch_size=SPACY_BATCH, n_process=SPACY_PROC)):
168 conll_str = get_conll_str(annos[ix], doc, use_germalemma=args.use_germalemma)
dazae3bc92e2020-11-04 11:06:26 +0100169 write_out.write(conll_str)
170 write_out.write("\n\n")
171 if args.text_file:
172 write_plain.write(" ".join([x.text for x in doc])+"\n")
173
174 end = time.time()
175 logger.info(f"Processing {args.corpus_name} took {(end - start)} seconds!")
176