| daza | e3bc92e | 2020-11-04 11:06:26 +0100 | [diff] [blame] | 1 | import argparse |
| 2 | import spacy |
| 3 | from spacy.tokens import Doc |
| 4 | import logging, sys, time |
| 5 | from lib.CoNLL_Annotation import get_token_type |
| 6 | import my_utils.file_utils as fu |
| 7 | from germalemma import GermaLemma |
| 8 | |
| Marc Kupietz | 88eea72 | 2025-10-26 15:21:14 +0100 | [diff] [blame] | 9 | def 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 | |
| daza | e3bc92e | 2020-11-04 11:06:26 +0100 | [diff] [blame] | 34 | |
| 35 | class 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 | |
| daza | 8534747 | 2020-11-23 18:43:33 +0100 | [diff] [blame] | 46 | def 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] |
| daza | e3bc92e | 2020-11-04 11:06:26 +0100 | [diff] [blame] | 49 | for ix, token in enumerate(spacy_doc): |
| Marc Kupietz | 88eea72 | 2025-10-26 15:21:14 +0100 | [diff] [blame] | 50 | morph_features = format_morphological_features(token) |
| daza | e3bc92e | 2020-11-04 11:06:26 +0100 | [diff] [blame] | 51 | if use_germalemma == "True": |
| Marc Kupietz | 88eea72 | 2025-10-26 15:21:14 +0100 | [diff] [blame] | 52 | content = (str(ix), token.text, find_germalemma(token.text, token.tag_, token.lemma_), token.pos_, token.tag_, morph_features, "_", "_", "_", "_") |
| daza | e3bc92e | 2020-11-04 11:06:26 +0100 | [diff] [blame] | 53 | else: |
| Marc Kupietz | 88eea72 | 2025-10-26 15:21:14 +0100 | [diff] [blame] | 54 | content = (str(ix), token.text, token.lemma_, token.pos_, token.tag_, morph_features, "_", "_", "_", "_") # Pure SpaCy! |
| daza | e3bc92e | 2020-11-04 11:06:26 +0100 | [diff] [blame] | 55 | conll_lines.append("\t".join(content)) |
| 56 | return "\n".join(conll_lines) |
| 57 | |
| daza | e3bc92e | 2020-11-04 11:06:26 +0100 | [diff] [blame] | 58 | |
| 59 | def 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 | |
| 73 | if __name__ == "__main__": |
| 74 | """ |
| 75 | EXAMPLE: |
| daza | 8534747 | 2020-11-23 18:43:33 +0100 | [diff] [blame] | 76 | --- TIGER Classic Orthography --- |
| daza | d7d7075 | 2021-01-12 18:17:49 +0100 | [diff] [blame] | 77 | python systems/parse_spacy.py --corpus_name Tiger --gld_token_type CoNLL09_Token \ |
| daza | e3bc92e | 2020-11-04 11:06:26 +0100 | [diff] [blame] | 78 | -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 |
| daza | d7d7075 | 2021-01-12 18:17:49 +0100 | [diff] [blame] | 81 | |
| 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 |
| daza | 8534747 | 2020-11-23 18:43:33 +0100 | [diff] [blame] | 85 | |
| 86 | --- TIGER New Orthography --- |
| daza | d7d7075 | 2021-01-12 18:17:49 +0100 | [diff] [blame] | 87 | python systems/parse_spacy.py --corpus_name TigerNew \ |
| daza | 8534747 | 2020-11-23 18:43:33 +0100 | [diff] [blame] | 88 | -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 |
| daza | d7d7075 | 2021-01-12 18:17:49 +0100 | [diff] [blame] | 91 | |
| 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 |
| daza | 8534747 | 2020-11-23 18:43:33 +0100 | [diff] [blame] | 95 | |
| 96 | --- German GSD Universal Deps --- |
| daza | d7d7075 | 2021-01-12 18:17:49 +0100 | [diff] [blame] | 97 | python systems/parse_spacy.py --corpus_name DE_GSD \ |
| daza | e3bc92e | 2020-11-04 11:06:26 +0100 | [diff] [blame] | 98 | -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 \ |
| daza | 8534747 | 2020-11-23 18:43:33 +0100 | [diff] [blame] | 100 | -t /home/daza/datasets/ud-treebanks-v2.2/UD_German-GSD/de_gsd-ud-test.txt |
| 101 | |
| 102 | |
| 103 | --- Real Data TEST --- |
| daza | d7d7075 | 2021-01-12 18:17:49 +0100 | [diff] [blame] | 104 | time python systems/parse_spacy.py --corpus_name DeReKo_a00 --comment_str "#" \ |
| daza | 8534747 | 2020-11-23 18:43:33 +0100 | [diff] [blame] | 105 | -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 |
| daza | e3bc92e | 2020-11-04 11:06:26 +0100 | [diff] [blame] | 107 | """ |
| 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) |
| daza | d7d7075 | 2021-01-12 18:17:49 +0100 | [diff] [blame] | 114 | 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") |
| daza | e3bc92e | 2020-11-04 11:06:26 +0100 | [diff] [blame] | 116 | 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 |
| daza | d7d7075 | 2021-01-12 18:17:49 +0100 | [diff] [blame] | 121 | CHUNK_SIZE = 20000 |
| 122 | SPACY_BATCH = 2000 |
| 123 | SPACY_PROC = 10 |
| daza | e3bc92e | 2020-11-04 11:06:26 +0100 | [diff] [blame] | 124 | |
| 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 | # ===================================================================================== |
| daza | d7d7075 | 2021-01-12 18:17:49 +0100 | [diff] [blame] | 137 | spacy_de = spacy.load(args.spacy_model, disable=["ner", "parser"]) |
| daza | e3bc92e | 2020-11-04 11:06:26 +0100 | [diff] [blame] | 138 | 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() |
| 141 | if args.text_file: write_plain = open(args.text_file, "w") |
| 142 | |
| daza | 8534747 | 2020-11-23 18:43:33 +0100 | [diff] [blame] | 143 | if ".gz" == args.input_file[-3:]: |
| 144 | in_file = fu.expand_file(args.input_file) |
| 145 | else: |
| 146 | in_file = args.input_file |
| 147 | |
| daza | e3bc92e | 2020-11-04 11:06:26 +0100 | [diff] [blame] | 148 | start = time.time() |
| 149 | total_processed_sents = 0 |
| daza | 8534747 | 2020-11-23 18:43:33 +0100 | [diff] [blame] | 150 | line_generator = fu.file_generator(in_file) |
| daza | e3bc92e | 2020-11-04 11:06:26 +0100 | [diff] [blame] | 151 | while file_has_next: |
| daza | 8534747 | 2020-11-23 18:43:33 +0100 | [diff] [blame] | 152 | 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) |
| 153 | if len(annos) == 0: break |
| 154 | total_processed_sents += len(annos) |
| daza | e3bc92e | 2020-11-04 11:06:26 +0100 | [diff] [blame] | 155 | logger.info(f"Already processed {total_processed_sents} sentences...") |
| daza | 8534747 | 2020-11-23 18:43:33 +0100 | [diff] [blame] | 156 | sents = [a.get_sentence() for a in annos] |
| 157 | for ix, doc in enumerate(spacy_de.pipe(sents, batch_size=SPACY_BATCH, n_process=SPACY_PROC)): |
| 158 | conll_str = get_conll_str(annos[ix], doc, use_germalemma=args.use_germalemma) |
| daza | e3bc92e | 2020-11-04 11:06:26 +0100 | [diff] [blame] | 159 | write_out.write(conll_str) |
| 160 | write_out.write("\n\n") |
| 161 | if args.text_file: |
| 162 | write_plain.write(" ".join([x.text for x in doc])+"\n") |
| 163 | |
| 164 | end = time.time() |
| 165 | logger.info(f"Processing {args.corpus_name} took {(end - start)} seconds!") |
| 166 | |