""" 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!")