blob: eeb1efa537118fe919df293b74d80386d6be3e30 [file] [log] [blame]
daza48606ba2021-02-10 14:16:41 +01001from sys import stdin
2import argparse
3import spacy
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
Marc Kupietz88eea722025-10-26 15:21:14 +010010def format_morphological_features(token):
11 """
12 Extract and format morphological features from a spaCy token for CoNLL-U output.
13
14 Args:
15 token: spaCy token object
16
17 Returns:
18 str: Formatted morphological features string for CoNLL-U 5th column
19 Returns "_" if no features are available
20 """
21 if not hasattr(token, 'morph') or not token.morph:
22 return "_"
23
24 morph_dict = token.morph.to_dict()
25 if not morph_dict:
26 return "_"
27
28 # Format as CoNLL-U format: Feature=Value|Feature2=Value2
29 features = []
30 for feature, value in sorted(morph_dict.items()):
31 features.append(f"{feature}={value}")
32
33 return "|".join(features)
34
daza48606ba2021-02-10 14:16:41 +010035
36class WhitespaceTokenizer(object):
37 def __init__(self, vocab):
38 self.vocab = vocab
39
40 def __call__(self, text):
41 words = text.split(' ')
42 # All tokens 'own' a subsequent space character in this tokenizer
43 spaces = [True] * len(words)
44 return Doc(self.vocab, words=words, spaces=spaces)
45
46
47def get_conll_str(anno_obj, spacy_doc, use_germalemma):
48 # First lines are comments. (metadata)
49 conll_lines = anno_obj.metadata # Then we want: [ID, FORM, LEMMA, UPOS, XPOS, FEATS, HEAD, DEPREL, DEPS, MISC]
50 for ix, token in enumerate(spacy_doc):
Marc Kupietz88eea722025-10-26 15:21:14 +010051 morph_features = format_morphological_features(token)
daza48606ba2021-02-10 14:16:41 +010052 if use_germalemma == "True":
Marc Kupietz88eea722025-10-26 15:21:14 +010053 content = (str(ix+1), token.text, find_germalemma(token.text, token.tag_, token.lemma_), token.pos_, token.tag_, morph_features, "_", "_", "_", "_")
daza48606ba2021-02-10 14:16:41 +010054 else:
Marc Kupietz88eea722025-10-26 15:21:14 +010055 content = (str(ix+1), token.text, token.lemma_, token.pos_, token.tag_, morph_features, "_", "_", "_", "_") # Pure SpaCy!
daza48606ba2021-02-10 14:16:41 +010056 conll_lines.append("\t".join(content))
57 return "\n".join(conll_lines)
58
59
60def find_germalemma(word, pos, spacy_lemma):
61 simplify_pos = {"ADJA":"ADJ", "ADJD":"ADJ",
62 "NA":"N", "NE":"N", "NN":"N",
63 "ADV":"ADV", "PAV":"ADV", "PROAV":"ADV", "PAVREL":"ADV", "PWAV":"ADV", "PWAVREL":"ADV",
64 "VAFIN":"V", "VAIMP":"V", "VAINF":"V", "VAPP":"V", "VMFIN":"V", "VMINF":"V",
65 "VMPP":"V", "VVFIN":"V", "VVIMP":"V", "VVINF":"V", "VVIZU":"V","VVPP":"V"
66 }
67 # simplify_pos = {"VERB": "V", "ADV": "ADV", "ADJ": "ADJ", "NOUN":"N", "PROPN": "N"}
68 try:
69 return lemmatizer.find_lemma(word, simplify_pos.get(pos, "UNK"))
70 except:
71 return spacy_lemma
72
73
74if __name__ == "__main__":
75 """
76 --- Example Real Data TEST ---
77
78 cat /export/netapp/kupietz/N-GRAMM-STUDIE/conllu/zca18.conllu | python systems/parse_spacy_pipe.py \
79 --corpus_name DeReKo_zca18 --comment_str "#" > output_zca18.conll
80 """
81
82 parser = argparse.ArgumentParser()
83 parser.add_argument("-n", "--corpus_name", help="Corpus Name", default="Corpus")
84 parser.add_argument("-sm", "--spacy_model", help="Spacy model containing the pipeline to tag", default="de_core_news_lg")
85 parser.add_argument("-gtt", "--gld_token_type", help="CoNLL Format of the Gold Data", default="CoNLLUP_Token")
86 parser.add_argument("-ugl", "--use_germalemma", help="Use Germalemma lemmatizer on top of SpaCy", default="True")
87 parser.add_argument("-c", "--comment_str", help="CoNLL Format of comentaries inside the file", default="#")
88 args = parser.parse_args()
89
90 file_has_next, chunk_ix = True, 0
91 CHUNK_SIZE = 20000
92 SPACY_BATCH = 2000
93 SPACY_PROC = 10
94
95 # =====================================================================================
96 # LOGGING INFO ...
97 # =====================================================================================
98 logger = logging.getLogger(__name__)
99 console_hdlr = logging.StreamHandler(sys.stderr)
100 file_hdlr = logging.FileHandler(filename=f"logs/Parse_{args.corpus_name}.SpaCy.log")
101 logging.basicConfig(level=logging.INFO, handlers=[console_hdlr, file_hdlr])
102 logger.info(f"Chunking {args.corpus_name} Corpus in chunks of {CHUNK_SIZE} Sentences")
103
104 # =====================================================================================
105 # POS TAG DOCUMENTS
106 # =====================================================================================
107 spacy_de = spacy.load(args.spacy_model, disable=["ner", "parser"])
108 spacy_de.tokenizer = WhitespaceTokenizer(spacy_de.vocab) # We won't re-tokenize to respect how the source CoNLL are tokenized!
109 lemmatizer = GermaLemma()
110
111 start = time.time()
112 total_processed_sents = 0
113
114 while file_has_next:
Marc Kupietza01314f2021-02-11 17:02:08 +0100115 annos, file_has_next = fu.get_file_annos_chunk(stdin, chunk_size=CHUNK_SIZE, token_class=get_token_type(args.gld_token_type), comment_str=args.comment_str, our_foundry="spacy")
daza48606ba2021-02-10 14:16:41 +0100116 if len(annos) == 0: break
117 total_processed_sents += len(annos)
118 logger.info(f"Already processed {total_processed_sents} sentences...")
119 sents = [a.get_sentence() for a in annos]
120 for ix, doc in enumerate(spacy_de.pipe(sents, batch_size=SPACY_BATCH, n_process=SPACY_PROC)):
121 conll_str = get_conll_str(annos[ix], doc, use_germalemma=args.use_germalemma)
122 print(conll_str+ "\n")
123
124 end = time.time()
125 logger.info(f"Processing {args.corpus_name} took {(end - start)} seconds!")
126