File size: 5,238 Bytes
a6326c7 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 |
"""
Base preprocessor class.
Author: md
"""
from config import BaseConfig
import os
from logger import build_logger
import logging
import json
from const import TRAIN_SPLIT, DEV_SPLIT, TEST_SPLIT, DIALOGUE_STATE_TRACKING
from typing import Dict
import shutil
class BasePreprocessorConfig(BaseConfig):
def __init__(
self,
input_dir: str,
output_dir: str,
task: str,
formatter="%(asctime)s | [%(name)s] | %(levelname)s | %(message)s",
*args,
**kwargs,
) -> None:
super().__init__(*args, **kwargs)
self.input_dir = input_dir
self.output_dir = output_dir
self.task = task
self.formatter = formatter
class BasePreprocessor(object):
def __init__(self, config: BasePreprocessorConfig) -> None:
self.config = config
self.logger = build_logger(
config.logger_name,
logging.INFO,
config.log_file,
config.log_mode,
config.formatter,
)
if self.config.task == DIALOGUE_STATE_TRACKING:
self.ontologies = {
split: self.load_ontology(split)
for split in [TRAIN_SPLIT, DEV_SPLIT, TEST_SPLIT]
}
def load_ontology(self, split: str) -> Dict:
"""
Load the ontology file.
"""
ontology_file = os.path.join(self.config.input_dir, f"{split}_ontology.json")
if not os.path.exists(ontology_file):
return None
return json.load(open(ontology_file, "r", encoding="utf8"))
def preprocess_line(self, split: str, example: Dict) -> Dict:
"""
Every preprocessor should customize this function for all `train`, `dev` and `test` split.
"""
raise NotImplementedError("The preprocess line procedure is required!")
def _preprocess_file(
self, start, infile, src_writer, tgt_writer, split, encoding="UTF-8"
):
with open(infile, "r", encoding=encoding) as reader:
for line in reader:
if line.strip():
example = json.loads(line)
if start:
start = False
elif split != "train":
tgt_writer.write("\n")
for processed_example in self.preprocess_line(split, example):
src_writer.write(f"{processed_example['src']}\n")
tgt_writer.write(f"{processed_example['tgt']}")
if "db_id" in processed_example and split != "train":
tgt_writer.write(f"\t{processed_example['db_id']}")
tgt_writer.write("\n")
return start
def preprocess(self, split: str) -> bool:
if not os.path.exists(self.config.output_dir):
os.makedirs(self.config.output_dir)
src_file = os.path.join(self.config.output_dir, f"{split}.src")
tgt_file = os.path.join(
self.config.output_dir,
f"{split}.tgt" if split == "train" else f"{split}.gold",
)
exist = False
with open(src_file, "w") as src_writer, open(tgt_file, "w") as tgt_writer:
start = True
for filename in os.listdir(self.config.input_dir):
if split not in filename or not filename.endswith(".jsonl"):
continue
exist = True
infile = os.path.join(self.config.input_dir, filename)
self.logger.info(f"preprocessing {infile}")
try:
start = self._preprocess_file(
start, infile, src_writer, tgt_writer, split
)
except UnicodeDecodeError:
start = self._preprocess_file(
start, infile, src_writer, tgt_writer, split, "ISO-8859-1"
)
return exist
def launch(self) -> None:
self.logger.info(f"Start to preprocess: {TRAIN_SPLIT}")
train = self.preprocess(TRAIN_SPLIT)
assert train
self.logger.info(f"Start to preprocess: {DEV_SPLIT}")
dev = self.preprocess(DEV_SPLIT)
self.logger.info(f"Start to preprocess: {TEST_SPLIT}")
test = self.preprocess(TEST_SPLIT)
if dev and not test:
self.logger.info("Copy dev to test")
shutil.copyfile(
os.path.join(self.config.output_dir, "dev.src"),
os.path.join(self.config.output_dir, "test.src"),
)
shutil.copyfile(
os.path.join(self.config.output_dir, "dev.gold"),
os.path.join(self.config.output_dir, "test.gold"),
)
if test and not dev:
self.logger.info("Copy test to dev")
shutil.copyfile(
os.path.join(self.config.output_dir, "test.src"),
os.path.join(self.config.output_dir, "dev.src"),
)
shutil.copyfile(
os.path.join(self.config.output_dir, "test.gold"),
os.path.join(self.config.output_dir, "dev.gold"),
)
self.logger.info("Preprocess successfully!")
|