From d1dea2e22ec3c501f534aeba34bf2e11efc40631 Mon Sep 17 00:00:00 2001 From: voje Date: Mon, 11 Mar 2019 09:26:49 +0100 Subject: [PATCH 1/5] fixed the weird bug (defined a list instead of dict... should have gone to sleep yesterday) --- .gitignore | 2 +- data/kres_srl_ikt | 1 + src/pkg/corpusparser/corpusparser/Parser.py | 17 ++++++++--------- .../__pycache__/Parser.cpython-35.pyc | Bin 5389 -> 0 bytes .../__pycache__/Sentence.cpython-35.pyc | Bin 448 -> 0 bytes .../__pycache__/__init__.cpython-35.pyc | Bin 249 -> 0 bytes 6 files changed, 10 insertions(+), 10 deletions(-) create mode 120000 data/kres_srl_ikt delete mode 100644 src/pkg/corpusparser/corpusparser/__pycache__/Parser.cpython-35.pyc delete mode 100644 src/pkg/corpusparser/corpusparser/__pycache__/Sentence.cpython-35.pyc delete mode 100644 src/pkg/corpusparser/corpusparser/__pycache__/__init__.cpython-35.pyc diff --git a/.gitignore b/.gitignore index c57e05a..43fb148 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,3 @@ data/samples/ -*/__pycache__/ *egg-info/ +*.pyc diff --git a/data/kres_srl_ikt b/data/kres_srl_ikt new file mode 120000 index 0000000..465d987 --- /dev/null +++ b/data/kres_srl_ikt @@ -0,0 +1 @@ +/home/voje/work_data/final_json \ No newline at end of file diff --git a/src/pkg/corpusparser/corpusparser/Parser.py b/src/pkg/corpusparser/corpusparser/Parser.py index fb8b408..1c5dd6b 100644 --- a/src/pkg/corpusparser/corpusparser/Parser.py +++ b/src/pkg/corpusparser/corpusparser/Parser.py @@ -75,9 +75,9 @@ class Parser(): if len(sent_srl_links) == 0: print("HI") return [] - print(sent_srl_dict) + print(sent_srl_links) # find the correspointing json file with srl links - return [] + return sent_srl_links def parse(self): if self.corpus == "kres": @@ -112,7 +112,7 @@ class Parser(): else: divs = root.findall(".//div") - res_dict = [] # TODO: try making an iterator instead + res_dict = {} # parse divs for div in divs: @@ -150,7 +150,7 @@ class Parser(): sentence_text += el.text sentence_tokens += [{ "word": False, - "tid": el_id, + "tid": int(el_id), "text": el.text, }] elif el.tag in self.S_TAGS: @@ -166,16 +166,15 @@ class Parser(): raise KeyError("duplicated id: {}".format(sentence_id)) jos_links = self.parse_jos_links(s) srl_links = srl_dict.get(sentence_id) if self.corpus == "kres" else None - srl_links_fixed = self.parse_srl_links(s, srl_links) - print(srl_links) + srl_links_parsed = self.parse_srl_links(s, srl_links) res_dict[sentence_id] = { "sid": sentence_id, "text": sentence_text, "tokens": sentence_tokens, - "jos_links": "BBBB", - "srl_links": "AAAAA", + "jos_links": jos_links, + "srl_links": srl_links_parsed } - + print("------------------------------------------------- END") print(res_dict[sentence_id]) print("------------------------------------------------- END") return # TODO dev break diff --git a/src/pkg/corpusparser/corpusparser/__pycache__/Parser.cpython-35.pyc b/src/pkg/corpusparser/corpusparser/__pycache__/Parser.cpython-35.pyc deleted file mode 100644 index e438b679e512adfece77441901df5aaacf36d388..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 5389 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 T{_FJzIf4x@x)GP2ML+NhUEyBP diff --git a/src/pkg/corpusparser/corpusparser/__pycache__/__init__.cpython-35.pyc b/src/pkg/corpusparser/corpusparser/__pycache__/__init__.cpython-35.pyc deleted file mode 100644 index a365c8e295dbed9a0472980368c09666df7d3ef2..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 249 zcmWgR<>jikZ;c6LU|@I*#Bjg_WH|tFu?mn#0U}0*90rD5MusRx21XE{i6MuHA(xpU ziW$gfW(d|~c?nd>pvicPEg-R|IJF4K;s{R7D@n~uPW97di4soEFDfW4E&xmFLDUq1 ztcemuk%8$cVg|~sWGG?*QefhjnSMc0epYI7iGFcWvVK8!x<0Z-R8D++W?p7Ve7s&k X Date: Wed, 13 Mar 2019 08:59:27 +0100 Subject: [PATCH 2/5] corpusparser finished python dict representation; TODO .json and DB --- data/debugging/dbg.txt | 6 +++ data/kres_srl | 2 +- data/kres_srl_t420 | 1 + src/pkg/corpusparser/corpusparser/Parser.py | 33 +++++++++------- src/pkg/corpusparser/corpusparser/README.md | 38 +++++++++++++++++++ src/pkg/corpusparser/corpusparser/Sentence.py | 3 -- src/pkg/corpusparser/corpusparser/__init__.py | 3 +- 7 files changed, 67 insertions(+), 19 deletions(-) create mode 100644 data/debugging/dbg.txt create mode 120000 data/kres_srl_t420 create mode 100644 src/pkg/corpusparser/corpusparser/README.md delete mode 100644 src/pkg/corpusparser/corpusparser/Sentence.py diff --git a/data/debugging/dbg.txt b/data/debugging/dbg.txt new file mode 100644 index 0000000..2b6909d --- /dev/null +++ b/data/debugging/dbg.txt @@ -0,0 +1,6 @@ +F0034713.20.1": [{"dep": "7", "arg": "REC", "from": "9"}, {"dep": "10", "arg": "ACT", "from": "9"}, {"dep": "13", "arg": "MWPRED", "from": "12"}, {"dep": "18", "arg": "MANN", "from": "19"}, {"dep": "20", "arg": "LOC", "from": "19"}] + +Sentence: +F0034713.20.0 +1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 +Sodobni ali preprosto neosveščeni potrošnik vse prerad zavrže stvar, ki se je malenkostno pokvarila in bi se jo zlahka dalo popraviti. \ No newline at end of file diff --git a/data/kres_srl b/data/kres_srl index f1acfc4..465d987 120000 --- a/data/kres_srl +++ b/data/kres_srl @@ -1 +1 @@ -/home/kristjan/kres_srl/final_json/ \ No newline at end of file +/home/voje/work_data/final_json \ No newline at end of file diff --git a/data/kres_srl_t420 b/data/kres_srl_t420 new file mode 120000 index 0000000..f1acfc4 --- /dev/null +++ b/data/kres_srl_t420 @@ -0,0 +1 @@ +/home/kristjan/kres_srl/final_json/ \ No newline at end of file diff --git a/src/pkg/corpusparser/corpusparser/Parser.py b/src/pkg/corpusparser/corpusparser/Parser.py index 1c5dd6b..847fa69 100644 --- a/src/pkg/corpusparser/corpusparser/Parser.py +++ b/src/pkg/corpusparser/corpusparser/Parser.py @@ -1,14 +1,16 @@ -from corpusparser import Sentence from pathlib import Path import re import json from lxml import etree +import logging + +logging.basicConfig(level=logging.INFO) # Read input file(.xml, .json; kres or ssj500k). # Create an iterator that outputs resulting sentences (python dict format). class Parser(): - def __init__(self, corpus, infiles): + def __init__(self, corpus, infiles, logger=None): if corpus == "kres": self.kres_folder = Path(infiles[0]) @@ -22,6 +24,7 @@ class Parser(): self.W_TAGS = ['w'] self.C_TAGS = ['c'] self.S_TAGS = ['S', 'pc'] + self.logger = logger or logging.getLogger(__name__) def parse_jos_links(self, sent_el): if self.corpus == "kres": @@ -71,13 +74,15 @@ class Parser(): return self.parse_any_links_ssj(sent_el, "SRL") def parse_srl_links_kres(self, sent_el, sent_srl_links): - print("HA") - if len(sent_srl_links) == 0: - print("HI") - return [] - print(sent_srl_links) + res_links = [] + for link in sent_srl_links: + res_links += [{ + "from": int(link["from"]), + "afun": link["arg"], + "to": int(link["dep"]), + }] # find the correspointing json file with srl links - return sent_srl_links + return res_links def parse(self): if self.corpus == "kres": @@ -166,7 +171,10 @@ class Parser(): raise KeyError("duplicated id: {}".format(sentence_id)) jos_links = self.parse_jos_links(s) srl_links = srl_dict.get(sentence_id) if self.corpus == "kres" else None - srl_links_parsed = self.parse_srl_links(s, srl_links) + if srl_links is None: + srl_links_parsed = None + else: + srl_links_parsed = self.parse_srl_links(s, srl_links) res_dict[sentence_id] = { "sid": sentence_id, "text": sentence_text, @@ -174,8 +182,7 @@ class Parser(): "jos_links": jos_links, "srl_links": srl_links_parsed } - print("------------------------------------------------- END") - print(res_dict[sentence_id]) - print("------------------------------------------------- END") - return # TODO dev break + if srl_links is None: + self.logger.info("srl_links missing:{}:{}".format( + sentence_id, res_dict[sentence_id]["text"])) return res_dict diff --git a/src/pkg/corpusparser/corpusparser/README.md b/src/pkg/corpusparser/corpusparser/README.md new file mode 100644 index 0000000..0d41d60 --- /dev/null +++ b/src/pkg/corpusparser/corpusparser/README.md @@ -0,0 +1,38 @@ +# corpusparser +A tool for parsing ssj500k and Kres into a unified .json format. + +## Input: +### ssj500k +To parse ssj500k, point to the monolythic `ssj500k-sl.body.xml` file (tested on ssj500k 2.1). + +### Kres +To parse Kres, point to folders: +* Kres folder, containig several (around 20K) .xml files (`F00XXXXX.xml.parsed.xml`). +* Kres SRL folder, containing SRL links for the corresponding F00...xml files (`F00XXXXX.srl.json`). + +## Internal data format +This is the internal python dict data format. It can be stored to file as `.json` or stored into a database for application usage. +```python +{ + 'sid': 'F0034713.5.0', + 'text': 'Mednarodni denarni sklad je odobril 30 milijard evrov vredno posojilo Grčiji. ', + 'tokens': [ + {'text': 'Mednarodni', 'lemma': 'mednaroden', 'msd': 'Ppnmeid', 'word': True, 'tid': 1}, + {'text': 'denarni', 'lemma': 'denaren', 'msd': 'Ppnmeid', 'word': True, 'tid': 2}, + {'text': 'sklad', 'lemma': 'sklad', 'msd': 'Somei', 'word': True, 'tid': 3}, + {'text': 'je', 'lemma': 'biti', 'msd': 'Gp-ste-n', 'word': True, 'tid': 4}, + {'text': 'odobril', 'lemma': 'odobriti', 'msd': 'Ggdd-em', 'word': True, 'tid': 5}, + {'text': '30', 'lemma': '30', 'msd': 'Kag', 'word': True, 'tid': 6}, + {'text': 'milijard', 'lemma': 'milijarda', 'msd': 'Sozmr', 'word': True, 'tid': 7}, # ... + ] + 'jos_links': [ + {'to': 1, 'from': 3, 'afun': 'dol'}, + {'to': 2, 'from': 3, 'afun': 'dol'}, + {'to': 3, 'from': 5, 'afun': 'ena'}, # ... + ] + 'srl_links': [ + {'to': 3, 'from': 5, 'afun': 'ACT'}, + {'to': 7, 'from': 5, 'afun': 'PAT'} + ] +} +``` \ No newline at end of file diff --git a/src/pkg/corpusparser/corpusparser/Sentence.py b/src/pkg/corpusparser/corpusparser/Sentence.py deleted file mode 100644 index aba9a4a..0000000 --- a/src/pkg/corpusparser/corpusparser/Sentence.py +++ /dev/null @@ -1,3 +0,0 @@ -class Sentence(): - def __init__(): - print("Sentence __init__(): TODO") diff --git a/src/pkg/corpusparser/corpusparser/__init__.py b/src/pkg/corpusparser/corpusparser/__init__.py index 213c88a..d993b8c 100644 --- a/src/pkg/corpusparser/corpusparser/__init__.py +++ b/src/pkg/corpusparser/corpusparser/__init__.py @@ -1,2 +1 @@ -from corpusparser.Parser import Parser -from corpusparser.Sentence import Sentence \ No newline at end of file +from corpusparser.Parser import Parser \ No newline at end of file From dc20480e207c3b2a15697715a1388fffb8348a6b Mon Sep 17 00:00:00 2001 From: voje Date: Thu, 14 Mar 2019 08:30:33 +0100 Subject: [PATCH 3/5] todo: implement parser output separately --- Makefile | 7 ++- src/pkg/corpusparser/corpusparser/Parser.py | 57 ++++++++++++-------- src/pkg/corpusparser/corpusparser/main.py | 58 +++++++++++++++++++++ src/preflight/main_parse.py | 25 --------- 4 files changed, 99 insertions(+), 48 deletions(-) create mode 100644 src/pkg/corpusparser/corpusparser/main.py delete mode 100644 src/preflight/main_parse.py diff --git a/Makefile b/Makefile index 51a0afe..790cbf0 100644 --- a/Makefile +++ b/Makefile @@ -11,6 +11,9 @@ MAKE_ROOT = $(shell pwd) SSJ_FILE = "$(MAKE_ROOT)/data/samples/ssj_example/ssj500k-sl.body.sample.xml" KRES_FOLDER = "$(MAKE_ROOT)/data/samples/kres_example" KRES_SRL_FOLDER = "$(MAKE_ROOT)/data/kres_srl" +OUTPUT = "file" +OUTDIR = "$(HOME)/workdir/outputfolder" +DBADDR = "" export .PHONY: dev-env preflight @@ -30,5 +33,5 @@ data/samples: # when debugging, run this once, then run python3 ... by hand preflight: data/samples pip3 install -e src/pkg/corpusparser/. - python3 src/preflight/main_parse.py --kres-folder $(KRES_FOLDER) \ - --ssj-file $(SSJ_FILE) --kres-srl-folder $(KRES_SRL_FOLDER) + python3 src/pkg/corpusparser/corpusparser/main.py --kres-folder $(KRES_FOLDER) \ + --ssj-file $(SSJ_FILE) --kres-srl-folder $(KRES_SRL_FOLDER) --output $(OUTPUT) --outdir $(OUTDIR) --dbaddr $(DBADDR) diff --git a/src/pkg/corpusparser/corpusparser/Parser.py b/src/pkg/corpusparser/corpusparser/Parser.py index 847fa69..476a87c 100644 --- a/src/pkg/corpusparser/corpusparser/Parser.py +++ b/src/pkg/corpusparser/corpusparser/Parser.py @@ -10,7 +10,7 @@ logging.basicConfig(level=logging.INFO) # Create an iterator that outputs resulting sentences (python dict format). class Parser(): - def __init__(self, corpus, infiles, logger=None): + def __init__(self, corpus, infiles, output=None, outdir=None, dbaddr=None, logger=None): if corpus == "kres": self.kres_folder = Path(infiles[0]) @@ -20,11 +20,22 @@ class Parser(): else: raise ValueError("Argument corpus should be 'ssj' or 'kres'.") + self.output = output # None | file | db + if self.output == "file": + self.outdir = Path(outdir) + self.outdir.mkdir(parents=True, exist_ok=True) + elif self.output == "db": + self.dbaddr = "TODO" + self.corpus = corpus self.W_TAGS = ['w'] self.C_TAGS = ['c'] self.S_TAGS = ['S', 'pc'] self.logger = logger or logging.getLogger(__name__) + self.stats = { + "parsed_count": 0, + "missing_srl": [] + } def parse_jos_links(self, sent_el): if self.corpus == "kres": @@ -67,7 +78,7 @@ class Parser(): }] return res_links - def parse_srl_links(self, sent_el, sent_srl_links): + def parse_srl_links(self, sent_el, sent_srl_links=None): if self.corpus == "kres": return self.parse_srl_links_kres(sent_el, sent_srl_links) else: @@ -84,22 +95,23 @@ class Parser(): # find the correspointing json file with srl links return res_links - def parse(self): + def sentence_generator(self): + # Using generators so we don't copy a whole corpu around in memory. if self.corpus == "kres": for xml_file in self.kres_folder.iterdir(): - self.parse_xml_file(xml_file) - break # TODO dev break + # self.parse_xml_file(xml_file) + yield from self.parse_xml_file(xml_file) else: - self.parse_xml_file(self.ssj_file) + yield from self.parse_xml_file(self.ssj_file) def parse_xml_file(self, xml_file): - srl_dict = {} + srl_from_json = {} if self.corpus == "kres": # in case of kres, read the SRL links form a separate json file file_id = xml_file.name.split(".")[0] json_file = self.kres_srl_folder / Path(file_id).with_suffix(".srl.json") with json_file.open("r") as fp: - srl_dict = json.loads(fp.read()) + srl_from_json = json.loads(fp.read()) with xml_file.open("rb") as fp: # remove namespaces @@ -155,7 +167,7 @@ class Parser(): sentence_text += el.text sentence_tokens += [{ "word": False, - "tid": int(el_id), + "tid": (int(el_id) if self.corpus == "kres" else -1), "text": el.text, }] elif el.tag in self.S_TAGS: @@ -166,23 +178,26 @@ class Parser(): pass sentence_id = "{}.{}.{}".format(f_id, p_id, s_id) - # make a generator instead of holding the whole corpus in memory - if sentence_id in res_dict: - raise KeyError("duplicated id: {}".format(sentence_id)) jos_links = self.parse_jos_links(s) - srl_links = srl_dict.get(sentence_id) if self.corpus == "kres" else None - if srl_links is None: - srl_links_parsed = None + + if self.corpus == "kres": + srl_links_raw = srl_from_json.get(sentence_id) + if srl_links_raw is None: + srl_links_parsed = None + self.stats["missing_srl"] += [(sentence_id, sentence_text)] + else: + srl_links_parsed = self.parse_srl_links(s, srl_links_raw) else: - srl_links_parsed = self.parse_srl_links(s, srl_links) - res_dict[sentence_id] = { + srl_links_parsed = self.parse_srl_links(s) + if len(srl_links_parsed) == 0: + self.stats["missing_srl"] += [(sentence_id, sentence_text)] + + sentence_entry = { "sid": sentence_id, "text": sentence_text, "tokens": sentence_tokens, "jos_links": jos_links, "srl_links": srl_links_parsed } - if srl_links is None: - self.logger.info("srl_links missing:{}:{}".format( - sentence_id, res_dict[sentence_id]["text"])) - return res_dict + self.stats["parsed_count"] += 1 + yield (xml_file, sentence_entry) diff --git a/src/pkg/corpusparser/corpusparser/main.py b/src/pkg/corpusparser/corpusparser/main.py new file mode 100644 index 0000000..cb23c8c --- /dev/null +++ b/src/pkg/corpusparser/corpusparser/main.py @@ -0,0 +1,58 @@ +from corpusparser import Parser +import argparse +import logging +import json + +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +## Main handles command line arguments and writing to files / DB. + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Parsing corpora kres and ssj500k.") + parser.add_argument('--kres-folder', required=True) + parser.add_argument('--kres-srl-folder', required=True) + parser.add_argument('--ssj-file', required=True) + parser.add_argument('--output', required=False, default=None) + parser.add_argument('--outdir', required=False, default=None) + parser.add_argument('--dbaddr', required=False, default=None) + args = parser.parse_args() + + # parse ssj + logger.info("Parsing ssj500k: {}".format(args.ssj_file)) + ssj_parser = Parser( + corpus="ssj", + infiles=[args.ssj_file], + output=args.output, + outdir=args.outdir, + ) + res = [x[1]["sid"] for x in ssj_parser.sentence_generator()] + logger.info("Parsed {} sentences (ssj500k)".format(len(res))) + + # parse kres + logger.info("Parsing Kres: {}".format(args.ssj_file)) + kres_parser = Parser( + corpus="kres", + infiles=[args.kres_folder, args.kres_srl_folder], + output=args.output, + outdir=args.outdir, + ) + res = [x[1]["sid"] for x in kres_parser.sentence_generator()] + logger.info("Parsed {} sentences (kres)".format(len(res))) + + +## Handling output is situational --- implement it outside of Parser. +## Parser returns tuples (orig_file, element) +# 1. parse per-file and output to file (JSON) +# 2. parse and save to DB + +# TODO +def handle_output(self, sent_ent, xml_file): + if self.output is None: + pass + if self.output == "file": + outfile = Path(self.outdir) / Path(xml_file.name.split(".")[0]).with_suffix(".json") + with outfile.open("a") as fp: + print(sent_ent) + json.dumps(sent_ent, fp) + diff --git a/src/preflight/main_parse.py b/src/preflight/main_parse.py deleted file mode 100644 index 35bb2bb..0000000 --- a/src/preflight/main_parse.py +++ /dev/null @@ -1,25 +0,0 @@ -from corpusparser import Parser -import argparse - -if __name__ == "__main__": - parser = argparse.ArgumentParser(description="Parsing corpora kres and ssj500k.") - parser.add_argument('--kres-folder', required=True) - parser.add_argument('--kres-srl-folder', required=True) - parser.add_argument('--ssj-file', required=True) - args = parser.parse_args() - - # parse ssj - """ - ssj_parser = Parser( - corpus="ssj", - infiles=[args.ssj_file] - ) - ssj_parser.parse() - """ - - # parse kres - kres_parser = Parser( - corpus="kres", - infiles=[args.kres_folder, args.kres_srl_folder] - ) - kres_parser.parse() From 83c24609bfec2517770cb8faa2b8d3837470d47e Mon Sep 17 00:00:00 2001 From: voje Date: Thu, 14 Mar 2019 09:01:41 +0100 Subject: [PATCH 4/5] ssj dumps to json; todo: dump kres to multiple files; dump sentence_dict objects to DB --- src/pkg/corpusparser/corpusparser/Parser.py | 9 +-- src/pkg/corpusparser/corpusparser/main.py | 87 ++++++++++++--------- 2 files changed, 49 insertions(+), 47 deletions(-) diff --git a/src/pkg/corpusparser/corpusparser/Parser.py b/src/pkg/corpusparser/corpusparser/Parser.py index 476a87c..d908d04 100644 --- a/src/pkg/corpusparser/corpusparser/Parser.py +++ b/src/pkg/corpusparser/corpusparser/Parser.py @@ -10,7 +10,7 @@ logging.basicConfig(level=logging.INFO) # Create an iterator that outputs resulting sentences (python dict format). class Parser(): - def __init__(self, corpus, infiles, output=None, outdir=None, dbaddr=None, logger=None): + def __init__(self, corpus, infiles, logger=None): if corpus == "kres": self.kres_folder = Path(infiles[0]) @@ -20,13 +20,6 @@ class Parser(): else: raise ValueError("Argument corpus should be 'ssj' or 'kres'.") - self.output = output # None | file | db - if self.output == "file": - self.outdir = Path(outdir) - self.outdir.mkdir(parents=True, exist_ok=True) - elif self.output == "db": - self.dbaddr = "TODO" - self.corpus = corpus self.W_TAGS = ['w'] self.C_TAGS = ['c'] diff --git a/src/pkg/corpusparser/corpusparser/main.py b/src/pkg/corpusparser/corpusparser/main.py index cb23c8c..b6dd803 100644 --- a/src/pkg/corpusparser/corpusparser/main.py +++ b/src/pkg/corpusparser/corpusparser/main.py @@ -1,3 +1,4 @@ +from pathlib import Path from corpusparser import Parser import argparse import logging @@ -8,37 +9,54 @@ logger = logging.getLogger(__name__) ## Main handles command line arguments and writing to files / DB. +def ssj_to_json_file(sentence_generator, outfile): + # this funciton is based on the fact that files are parsed sequentially + data_buffer = [] + for s in sentence_generator: + sdata = s[1] + data_buffer += [sdata] + + # outfile = Path(outfile) + with open(outfile, "w") as fp: + logger.info("Writing to {}".format(outfile)) + json.dump(data_buffer, fp) + +def kres_to_json_files() + return "TODO" + +def to_db(): + return "TODO" + if __name__ == "__main__": - parser = argparse.ArgumentParser(description="Parsing corpora kres and ssj500k.") - parser.add_argument('--kres-folder', required=True) - parser.add_argument('--kres-srl-folder', required=True) - parser.add_argument('--ssj-file', required=True) - parser.add_argument('--output', required=False, default=None) - parser.add_argument('--outdir', required=False, default=None) - parser.add_argument('--dbaddr', required=False, default=None) - args = parser.parse_args() - - # parse ssj - logger.info("Parsing ssj500k: {}".format(args.ssj_file)) - ssj_parser = Parser( - corpus="ssj", - infiles=[args.ssj_file], - output=args.output, - outdir=args.outdir, - ) - res = [x[1]["sid"] for x in ssj_parser.sentence_generator()] - logger.info("Parsed {} sentences (ssj500k)".format(len(res))) - - # parse kres - logger.info("Parsing Kres: {}".format(args.ssj_file)) - kres_parser = Parser( - corpus="kres", - infiles=[args.kres_folder, args.kres_srl_folder], - output=args.output, - outdir=args.outdir, - ) - res = [x[1]["sid"] for x in kres_parser.sentence_generator()] - logger.info("Parsed {} sentences (kres)".format(len(res))) + parser = argparse.ArgumentParser(description="Parsing corpora kres and ssj500k.") + parser.add_argument('--kres-folder', required=True) + parser.add_argument('--kres-srl-folder', required=True) + parser.add_argument('--ssj-file', required=True) + parser.add_argument('--output', required=False, default=None) + parser.add_argument('--outdir', required=False, default=None) + parser.add_argument('--dbaddr', required=False, default=None) + args = parser.parse_args() + + # parse ssj + logger.info("Parsing ssj500k: {}".format(args.ssj_file)) + ssj_parser = Parser( + corpus="ssj", + infiles=[args.ssj_file], + ) + # res = [x[1]["sid"] for x in ssj_parser.sentence_generator()] + # logger.info("Parsed {} sentences (ssj500k)".format(len(res))) + + # ssj to json + ssj_to_json_file(ssj_parser.sentence_generator(), "/home/voje/workdir/ssj.json") + + # parse kres + logger.info("Parsing Kres: {}".format(args.ssj_file)) + kres_parser = Parser( + corpus="kres", + infiles=[args.kres_folder, args.kres_srl_folder], + ) + res = [x[1]["sid"] for x in kres_parser.sentence_generator()] + logger.info("Parsed {} sentences (kres)".format(len(res))) ## Handling output is situational --- implement it outside of Parser. @@ -47,12 +65,3 @@ if __name__ == "__main__": # 2. parse and save to DB # TODO -def handle_output(self, sent_ent, xml_file): - if self.output is None: - pass - if self.output == "file": - outfile = Path(self.outdir) / Path(xml_file.name.split(".")[0]).with_suffix(".json") - with outfile.open("a") as fp: - print(sent_ent) - json.dumps(sent_ent, fp) - From eb83519f51c315b49757e9bc8a634fe988d86c92 Mon Sep 17 00:00:00 2001 From: voje Date: Thu, 14 Mar 2019 14:13:01 +0100 Subject: [PATCH 5/5] done creating kres and ssj json files --- Makefile | 2 +- src/pkg/corpusparser/corpusparser/main.py | 49 +++++++++++++++++++---- 2 files changed, 43 insertions(+), 8 deletions(-) diff --git a/Makefile b/Makefile index 790cbf0..7734cb5 100644 --- a/Makefile +++ b/Makefile @@ -12,7 +12,7 @@ SSJ_FILE = "$(MAKE_ROOT)/data/samples/ssj_example/ssj500k-sl.body.sample.xml" KRES_FOLDER = "$(MAKE_ROOT)/data/samples/kres_example" KRES_SRL_FOLDER = "$(MAKE_ROOT)/data/kres_srl" OUTPUT = "file" -OUTDIR = "$(HOME)/workdir/outputfolder" +OUTDIR = "/home/voje/workdir/test_out" DBADDR = "" export diff --git a/src/pkg/corpusparser/corpusparser/main.py b/src/pkg/corpusparser/corpusparser/main.py index b6dd803..e0ba065 100644 --- a/src/pkg/corpusparser/corpusparser/main.py +++ b/src/pkg/corpusparser/corpusparser/main.py @@ -9,20 +9,52 @@ logger = logging.getLogger(__name__) ## Main handles command line arguments and writing to files / DB. -def ssj_to_json_file(sentence_generator, outfile): +def ssj_to_json_file(sentence_generator, outfolder): # this funciton is based on the fact that files are parsed sequentially + outfolder = Path(outfolder) + outfolder.mkdir(parents=True, exist_ok=True) + outfile = outfolder / "ssj500k.json" + data_buffer = [] for s in sentence_generator: sdata = s[1] data_buffer += [sdata] # outfile = Path(outfile) - with open(outfile, "w") as fp: + with outfile.open("w") as fp: logger.info("Writing to {}".format(outfile)) json.dump(data_buffer, fp) -def kres_to_json_files() - return "TODO" +def kres_to_json_files(sentence_generator, outfolder): + outfolder = Path(outfolder) / "kres_json" + outfolder.mkdir(parents=True, exist_ok=True) + + def write_buffer_to_file(outfile, outfile_buffer): + logger.info("Writing file: {}".format(outfile)) + with outfile.open("w") as fp: + json.dump(outfile_buffer, fp) + + outfile_buffer = None + current_outfile = None + for s in sentence_generator: + infile = s[0] + outfile = outfolder / Path(infile.name.split(".")[0]).with_suffix(".json") + + # parser sequentially parses files; when we're done with a file, write it out + if current_outfile is None: + current_outfile = outfile + outfile_buffer = [] + elif outfile != current_outfile: + write_buffer_to_file(current_outfile, outfile_buffer) + current_outfile = outfile + outfile_buffer = [] + + # update buffer + sdata = s[1] + outfile_buffer += [sdata] + write_buffer_to_file(current_outfile, outfile_buffer) + + def to_db(): return "TODO" @@ -47,7 +79,7 @@ if __name__ == "__main__": # logger.info("Parsed {} sentences (ssj500k)".format(len(res))) # ssj to json - ssj_to_json_file(ssj_parser.sentence_generator(), "/home/voje/workdir/ssj.json") + ssj_to_json_file(ssj_parser.sentence_generator(), args.outdir) # parse kres logger.info("Parsing Kres: {}".format(args.ssj_file)) @@ -55,8 +87,11 @@ if __name__ == "__main__": corpus="kres", infiles=[args.kres_folder, args.kres_srl_folder], ) - res = [x[1]["sid"] for x in kres_parser.sentence_generator()] - logger.info("Parsed {} sentences (kres)".format(len(res))) + # res = [x[1]["sid"] for x in kres_parser.sentence_generator()] + # logger.info("Parsed {} sentences (kres)".format(len(res))) + + # kres to json + kres_to_json_files(kres_parser.sentence_generator(), args.outdir) ## Handling output is situational --- implement it outside of Parser.