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