| daza | d7d7075 | 2021-01-12 18:17:49 +0100 | [diff] [blame] | 1 | import argparse, os |
| 2 | import spacy |
| 3 | from spacy.language import Language |
| 4 | from spacy.tokens import Doc |
| 5 | import logging, sys, time |
| 6 | from lib.CoNLL_Annotation import get_token_type |
| 7 | import my_utils.file_utils as fu |
| 8 | from germalemma import GermaLemma |
| 9 | |
| Marc Kupietz | 88eea72 | 2025-10-26 15:21:14 +0100 | [diff] [blame^] | 10 | def 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 | |
| daza | d7d7075 | 2021-01-12 18:17:49 +0100 | [diff] [blame] | 35 | |
| 36 | @Language.factory("my_component") |
| 37 | class 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 | |
| 48 | def 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 Kupietz | 88eea72 | 2025-10-26 15:21:14 +0100 | [diff] [blame^] | 52 | morph_features = format_morphological_features(token) |
| daza | d7d7075 | 2021-01-12 18:17:49 +0100 | [diff] [blame] | 53 | if use_germalemma == "True": |
| Marc Kupietz | 88eea72 | 2025-10-26 15:21:14 +0100 | [diff] [blame^] | 54 | content = (str(ix), token.text, find_germalemma(token.text, token.tag_, token.lemma_), token.pos_, token.tag_, morph_features, "_", "_", "_", "_") |
| daza | d7d7075 | 2021-01-12 18:17:49 +0100 | [diff] [blame] | 55 | else: |
| Marc Kupietz | 88eea72 | 2025-10-26 15:21:14 +0100 | [diff] [blame^] | 56 | content = (str(ix), token.text, token.lemma_, token.pos_, token.tag_, morph_features, "_", "_", "_", "_") # Pure SpaCy! |
| daza | d7d7075 | 2021-01-12 18:17:49 +0100 | [diff] [blame] | 57 | 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 | |
| 64 | def 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 | |
| 78 | if __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 | |
| 128 | if ".gz" == args.input_file[-3:]: |
| 129 | in_file = fu.expand_file(args.input_file) |
| 130 | else: |
| 131 | in_file = args.input_file |
| 132 | |
| 133 | start = time.time() |
| 134 | total_processed_sents = 0 |
| 135 | line_generator = fu.file_generator(in_file) |
| 136 | while file_has_next: |
| 137 | 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) |
| 138 | if len(annos) == 0: break |
| 139 | total_processed_sents += len(annos) |
| 140 | logger.info(f"Already processed {total_processed_sents} sentences...") |
| 141 | sents = [a.get_sentence() for a in annos] |
| 142 | for ix, doc in enumerate(spacy_de.pipe(sents, batch_size=SPACY_BATCH, n_process=SPACY_PROC)): |
| 143 | conll_str = get_conll_str(annos[ix], doc, use_germalemma=args.use_germalemma) |
| 144 | write_out.write(conll_str) |
| 145 | write_out.write("\n\n") |
| 146 | |
| 147 | end = time.time() |
| 148 | logger.info(f"Processing {args.corpus_name} took {(end - start)} seconds!") |
| 149 | |