|
| 1 | +import os |
| 2 | +import json |
| 3 | +from typing import List, Dict |
| 4 | +from src.config import settings |
| 5 | + |
| 6 | +def load_raw_data(file_path: str) -> List[Dict]: |
| 7 | + """Loads raw JSONL data.""" |
| 8 | + data = [] |
| 9 | + with open(file_path, 'r') as f: |
| 10 | + for line in f: |
| 11 | + data.append(json.loads(line)) |
| 12 | + return data |
| 13 | + |
| 14 | +def clean_data(data: List[Dict]) -> List[Dict]: |
| 15 | + """Basic data cleaning and duplicate removal.""" |
| 16 | + import pandas as pd |
| 17 | + df = pd.DataFrame(data) |
| 18 | + initial_len = len(df) |
| 19 | + df = df.drop_duplicates(subset=['instruction', 'response']) |
| 20 | + print(f"Removed {initial_len - len(df)} duplicates.") |
| 21 | + return df.to_dict('records') |
| 22 | + |
| 23 | +def format_prompt(sample: Dict) -> str: |
| 24 | + """Formats sample into a structured instruction format.""" |
| 25 | + # User requested format: <system> <instruction> <response> |
| 26 | + system_prompt = "You are a helpful domain-specific support assistant." |
| 27 | + instruction = sample['instruction'] |
| 28 | + response = sample['response'] |
| 29 | + |
| 30 | + prompt = f"<system> {system_prompt} </system> <instruction> {instruction} </instruction> <response> {response} </response>" |
| 31 | + return {"text": prompt} |
| 32 | + |
| 33 | +def preprocess_pipeline(input_path: str, output_dir: str): |
| 34 | + """Full preprocessing pipeline.""" |
| 35 | + import pandas as pd |
| 36 | + from sklearn.model_selection import train_test_split |
| 37 | + from datasets import Dataset, DatasetDict |
| 38 | + |
| 39 | + os.makedirs(output_dir, exist_ok=True) |
| 40 | + |
| 41 | + # 1. Load |
| 42 | + raw_data = load_raw_data(input_path) |
| 43 | + |
| 44 | + # 2. Clean |
| 45 | + cleaned_data = clean_data(raw_data) |
| 46 | + |
| 47 | + # 3. Format and Split |
| 48 | + df = pd.DataFrame(cleaned_data) |
| 49 | + train_df, val_df = train_test_split(df, test_size=settings.TRAIN_TEST_SPLIT, random_state=42) |
| 50 | + |
| 51 | + train_dataset = Dataset.from_pandas(train_df) |
| 52 | + val_dataset = Dataset.from_pandas(val_df) |
| 53 | + |
| 54 | + # Apply formatting |
| 55 | + train_dataset = train_dataset.map(format_prompt, remove_columns=train_dataset.column_names) |
| 56 | + val_dataset = val_dataset.map(format_prompt, remove_columns=val_dataset.column_names) |
| 57 | + |
| 58 | + # Save processed data |
| 59 | + train_dataset.to_json(os.path.join(output_dir, "train.jsonl")) |
| 60 | + val_dataset.to_json(os.path.join(output_dir, "validation.jsonl")) |
| 61 | + |
| 62 | + print(f"Preprocessed {len(train_dataset)} training samples and {len(val_dataset)} validation samples.") |
| 63 | + print(f"Data saved to {output_dir}") |
| 64 | + |
| 65 | +if __name__ == "__main__": |
| 66 | + preprocess_pipeline("data/raw/raw_support_data.jsonl", "data/processed") |
0 commit comments