|
| 1 | +# Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import argparse |
| 16 | +import json |
| 17 | +import os |
| 18 | +from functools import partial |
| 19 | +from typing import Any |
| 20 | + |
| 21 | +from docbuilder import EmailsDownloader, EmailsIterator |
| 22 | +from filters import FilterEmailsWithLongBody, FilterEmptyEmails |
| 23 | +from modifiers import AddPeriod, AddSystemPrompt |
| 24 | + |
| 25 | +from nemo_curator import ScoreFilter, Sequential |
| 26 | +from nemo_curator.datasets import DocumentDataset |
| 27 | +from nemo_curator.modifiers.pii_modifier import PiiModifier |
| 28 | +from nemo_curator.modifiers.unicode_reformatter import UnicodeReformatter |
| 29 | +from nemo_curator.modules.modify import Modify |
| 30 | +from nemo_curator.utils.distributed_utils import get_client |
| 31 | +from nemo_curator.utils.script_utils import add_distributed_args |
| 32 | + |
| 33 | +SCRIPT_DIR_PATH = os.path.dirname(os.path.abspath(__file__)) |
| 34 | +DATA_DIR = os.path.join(SCRIPT_DIR_PATH, "data") |
| 35 | +DATASET_URL = "https://huggingface.co/datasets/neelblabla/enron_labeled_emails_with_subjects-llama2-7b_finetuning/raw/main/prompts_train.csv" |
| 36 | + |
| 37 | + |
| 38 | +def download_and_convert_to_jsonl() -> str: |
| 39 | + """ |
| 40 | + Downloads the emails dataset and converts it to JSONL format. |
| 41 | +
|
| 42 | + Returns: |
| 43 | + str: The path to the JSONL file. |
| 44 | + """ |
| 45 | + |
| 46 | + # Download the dataset in raw format and convert it to JSONL. |
| 47 | + downloader = EmailsDownloader(DATA_DIR) |
| 48 | + output_path = os.path.join(DATA_DIR, "emails.jsonl") |
| 49 | + raw_fp = downloader.download(DATASET_URL) |
| 50 | + |
| 51 | + iterator = EmailsIterator() |
| 52 | + |
| 53 | + # Parse the raw data and write it to a JSONL file. |
| 54 | + with open(output_path, "w") as f: |
| 55 | + for record in iterator.iterate(raw_fp): |
| 56 | + json_record = json.dumps(record, ensure_ascii=False) |
| 57 | + f.write(json_record + "\n") |
| 58 | + |
| 59 | + return output_path |
| 60 | + |
| 61 | + |
| 62 | +def redact_pii(dataset: DocumentDataset, text_field) -> DocumentDataset: |
| 63 | + """ |
| 64 | + Redacts personally identifiable information (PII) from a given dataset. |
| 65 | +
|
| 66 | + Args: |
| 67 | + dataset (DocumentDataset): The dataset containing documents with PII. |
| 68 | +
|
| 69 | + Returns: |
| 70 | + DocumentDataset: The redacted dataset with PII replaced by a generic value. |
| 71 | + """ |
| 72 | + redactor = Modify( |
| 73 | + PiiModifier( |
| 74 | + supported_entities=[ |
| 75 | + "ADDRESS", |
| 76 | + "EMAIL_ADDRESS", |
| 77 | + "LOCATION", |
| 78 | + "PERSON", |
| 79 | + "URL", |
| 80 | + "PHONE_NUMBER", |
| 81 | + ], |
| 82 | + anonymize_action="replace", |
| 83 | + device="cpu", |
| 84 | + ), |
| 85 | + text_field=text_field, |
| 86 | + ) |
| 87 | + return redactor(dataset) |
| 88 | + |
| 89 | + |
| 90 | +def run_curation_pipeline(args: Any, jsonl_fp: str) -> str: |
| 91 | + """ |
| 92 | + Run the curation pipeline on the dataset. |
| 93 | +
|
| 94 | + Args: |
| 95 | + args (Any): Command-line arguments. |
| 96 | + jsonl_fp (str): The path to the uncurated JSONL file. |
| 97 | +
|
| 98 | + Returns: |
| 99 | + str: The path to the curated JSONL file. |
| 100 | + """ |
| 101 | + client = get_client(args, args.device) |
| 102 | + print(f" Running the curation pipeline on '{jsonl_fp}'...") |
| 103 | + orig_dataset = DocumentDataset.read_json(jsonl_fp, add_filename=True) |
| 104 | + dataset = orig_dataset |
| 105 | + |
| 106 | + redact_pii_subject = partial(redact_pii, text_field="subject") |
| 107 | + redact_pii_body = partial(redact_pii, text_field="body") |
| 108 | + |
| 109 | + curation_steps = Sequential( |
| 110 | + [ |
| 111 | + # |
| 112 | + # Unify the text encoding to Unicode. |
| 113 | + # |
| 114 | + Modify(UnicodeReformatter(), text_field="subject"), |
| 115 | + Modify(UnicodeReformatter(), text_field="body"), |
| 116 | + Modify(UnicodeReformatter(), text_field="category"), |
| 117 | + # |
| 118 | + # Filtering |
| 119 | + # |
| 120 | + # Filter out empty emails. |
| 121 | + ScoreFilter( |
| 122 | + FilterEmptyEmails(), text_field="subject", score_type=bool, invert=True |
| 123 | + ), |
| 124 | + ScoreFilter( |
| 125 | + FilterEmptyEmails(), text_field="body", score_type=bool, invert=True |
| 126 | + ), |
| 127 | + ScoreFilter( |
| 128 | + FilterEmptyEmails(), text_field="category", score_type=bool, invert=True |
| 129 | + ), |
| 130 | + # Filter out emails that are too long. |
| 131 | + ScoreFilter(FilterEmailsWithLongBody(), text_field="body", score_type=bool), |
| 132 | + # |
| 133 | + # Redact personally identifiable information (PII). |
| 134 | + # |
| 135 | + redact_pii_subject, |
| 136 | + redact_pii_body, |
| 137 | + # |
| 138 | + # Final modifications. |
| 139 | + # |
| 140 | + # Add system prompts to every email, which helps the model focus on the task. |
| 141 | + Modify(AddSystemPrompt(), text_field="body"), |
| 142 | + # Add a period to the end of each email category, which makes PEFT easier. |
| 143 | + Modify(AddPeriod(), text_field="category"), |
| 144 | + ] |
| 145 | + ) |
| 146 | + |
| 147 | + dataset = curation_steps(dataset) |
| 148 | + dataset = dataset.persist() |
| 149 | + |
| 150 | + print(f" Original dataset length: {len(orig_dataset.df)}") |
| 151 | + print(f" After running the curation pipeline: {len(dataset.df)}") |
| 152 | + print(f" Writing to '{jsonl_fp}'...") |
| 153 | + out_path = os.path.join( |
| 154 | + os.path.dirname(jsonl_fp), |
| 155 | + "curated", |
| 156 | + ) |
| 157 | + os.makedirs(out_path, exist_ok=True) |
| 158 | + dataset.to_json(out_path, write_to_filename=True) |
| 159 | + client.close() |
| 160 | + return os.path.join(out_path, os.path.basename(jsonl_fp)) |
| 161 | + |
| 162 | + |
| 163 | +def main(): |
| 164 | + parser = argparse.ArgumentParser() |
| 165 | + parser = add_distributed_args(parser) |
| 166 | + args = parser.parse_args() |
| 167 | + # Limit the total number of workers to ensure we don't run out of memory. |
| 168 | + args.n_workers = min(args.n_workers, 8) |
| 169 | + |
| 170 | + # Prepare the download and JSONL directories. |
| 171 | + if not os.path.isdir(DATA_DIR): |
| 172 | + os.makedirs(DATA_DIR) |
| 173 | + |
| 174 | + jsonl_fp = download_and_convert_to_jsonl() |
| 175 | + run_curation_pipeline(args, jsonl_fp) |
| 176 | + |
| 177 | + |
| 178 | +if __name__ == "__main__": |
| 179 | + main() |
0 commit comments