daza | 54e072e | 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 | |
| 9 | |
| 10 | class WhitespaceTokenizer(object): |
| 11 | def __init__(self, vocab): |
| 12 | self.vocab = vocab |
| 13 | |
| 14 | def __call__(self, text): |
| 15 | words = text.split(' ') |
| 16 | # All tokens 'own' a subsequent space character in this tokenizer |
| 17 | spaces = [True] * len(words) |
| 18 | return Doc(self.vocab, words=words, spaces=spaces) |
| 19 | |
| 20 | |
| 21 | def get_conll_str(spacy_doc, use_germalemma): |
| 22 | conll_lines = [] # We want: [ID, FORM, LEMMA, UPOS, XPOS, FEATS, HEAD, DEPREL, DEPS, MISC] |
| 23 | for ix, token in enumerate(spacy_doc): |
| 24 | if use_germalemma == "True": |
| 25 | content = (str(ix), token.text, find_germalemma(token.text, token.tag_, token.lemma_), token.pos_, token.tag_, "_", "_", "_", "_", "_") |
| 26 | else: |
| 27 | content = (str(ix), token.text, token.lemma_, token.pos_, token.tag_, "_", "_", "_", "_", "_") # Pure SpaCy! |
| 28 | conll_lines.append("\t".join(content)) |
| 29 | return "\n".join(conll_lines) |
| 30 | |
| 31 | |
| 32 | # def freeling_lemma_lookup(): |
| 33 | # dicts_path = "/home/daza/Frameworks/FreeLing/data/de/dictionary/entries/" |
| 34 | |
| 35 | def find_germalemma(word, pos, spacy_lemma): |
| 36 | simplify_pos = {"ADJA":"ADJ", "ADJD":"ADJ", |
| 37 | "NA":"N", "NE":"N", "NN":"N", |
| 38 | "ADV":"ADV", "PAV":"ADV", "PROAV":"ADV", "PAVREL":"ADV", "PWAV":"ADV", "PWAVREL":"ADV", |
| 39 | "VAFIN":"V", "VAIMP":"V", "VAINF":"V", "VAPP":"V", "VMFIN":"V", "VMINF":"V", |
| 40 | "VMPP":"V", "VVFIN":"V", "VVIMP":"V", "VVINF":"V", "VVIZU":"V","VVPP":"V" |
| 41 | } |
| 42 | # simplify_pos = {"VERB": "V", "ADV": "ADV", "ADJ": "ADJ", "NOUN":"N", "PROPN": "N"} |
| 43 | try: |
| 44 | return lemmatizer.find_lemma(word, simplify_pos.get(pos, "UNK")) |
| 45 | except: |
| 46 | return spacy_lemma |
| 47 | |
| 48 | |
| 49 | if __name__ == "__main__": |
| 50 | """ |
| 51 | EXAMPLE: |
| 52 | python systems/parse_spacy.py --corpus_name Tiger \ |
| 53 | -i /home/daza/datasets/TIGER_conll/tiger_release_aug07.corrected.16012013.conll09 \ |
| 54 | -o /home/daza/datasets/TIGER_conll/tiger_spacy_parsed.conllu \ |
| 55 | -t /home/daza/datasets/TIGER_conll/tiger_all.txt |
| 56 | |
| 57 | python systems/parse_spacy.py --corpus_name DE_GSD --gld_token_type CoNLLUP_Token \ |
| 58 | -i /home/daza/datasets/ud-treebanks-v2.2/UD_German-GSD/de_gsd-ud-test.conllu \ |
| 59 | -o /home/daza/datasets/ud-treebanks-v2.2/UD_German-GSD/de_gsd-ud-test.parsed.germalemma.conllu \ |
| 60 | -t/home/daza/datasets/ud-treebanks-v2.2/UD_German-GSD/de_gsd-ud-test.txt |
| 61 | """ |
| 62 | |
| 63 | parser = argparse.ArgumentParser() |
| 64 | parser.add_argument("-i", "--input_file", help="Input Corpus", required=True) |
| 65 | parser.add_argument("-n", "--corpus_name", help="Corpus Name", default="Corpus") |
| 66 | parser.add_argument("-o", "--output_file", help="File where the Predictions will be saved", required=True) |
| 67 | parser.add_argument("-t", "--text_file", help="Output Plain Text File", default=None) |
| 68 | parser.add_argument("-gtt", "--gld_token_type", help="CoNLL Format of the Gold Data", default="CoNLL09_Token") |
| 69 | parser.add_argument("-ugl", "--use_germalemma", help="Use Germalemma lemmatizer on top of SpaCy", default="True") |
| 70 | parser.add_argument("-c", "--comment_str", help="CoNLL Format of comentaries inside the file", default="#") |
| 71 | args = parser.parse_args() |
| 72 | |
| 73 | file_has_next, chunk_ix = True, 0 |
| 74 | CHUNK_SIZE = 10000 |
| 75 | |
| 76 | # ===================================================================================== |
| 77 | # LOGGING INFO ... |
| 78 | # ===================================================================================== |
| 79 | logger = logging.getLogger(__name__) |
| 80 | console_hdlr = logging.StreamHandler(sys.stdout) |
| 81 | file_hdlr = logging.FileHandler(filename=f"logs/Parse_{args.corpus_name}.SpaCy.log") |
| 82 | logging.basicConfig(level=logging.INFO, handlers=[console_hdlr, file_hdlr]) |
| 83 | logger.info(f"Chunking {args.corpus_name} Corpus in chunks of {CHUNK_SIZE} Sentences") |
| 84 | |
| 85 | # ===================================================================================== |
| 86 | # POS TAG DOCUMENTS |
| 87 | # ===================================================================================== |
| 88 | spacy_de = spacy.load("de_core_news_lg", disable=["ner", "parser"]) |
| 89 | spacy_de.tokenizer = WhitespaceTokenizer(spacy_de.vocab) # We won't re-tokenize to respect how the source CoNLL are tokenized! |
| 90 | write_out = open(args.output_file, "w") |
| 91 | lemmatizer = GermaLemma() |
| 92 | if args.text_file: write_plain = open(args.text_file, "w") |
| 93 | |
| 94 | start = time.time() |
| 95 | total_processed_sents = 0 |
| 96 | line_generator = fu.file_generator(args.input_file) |
| 97 | while file_has_next: |
| 98 | sents, gld, file_has_next = fu.get_file_text_chunk(line_generator, chunk_size=CHUNK_SIZE, token_class=get_token_type(args.gld_token_type), comment_str=args.comment_str) |
| 99 | if len(sents) == 0: break |
| 100 | total_processed_sents += len(sents) |
| 101 | logger.info(f"Already processed {total_processed_sents} sentences...") |
| 102 | for doc in spacy_de.pipe(sents, batch_size=1000, n_process=10): |
| 103 | conll_str = get_conll_str(doc, use_germalemma=args.use_germalemma) |
| 104 | write_out.write(conll_str) |
| 105 | write_out.write("\n\n") |
| 106 | if args.text_file: |
| 107 | write_plain.write(" ".join([x.text for x in doc])+"\n") |
| 108 | |
| 109 | end = time.time() |
| 110 | logger.info(f"Processing {args.corpus_name} took {(end - start)} seconds!") |
| 111 | |