File size: 13,755 Bytes
ba713dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
"""
preprocess.py
─────────────
Step 2 of the pipeline.

Loads all raw CSV files, harmonises column names into the canonical
BEHAVIORAL_FEATURES schema, merges into a single training dataframe,
and performs cleaning + normalisation.

Output:
  data/processed/training_dataset.csv      ← unified feature matrix + target
  data/processed/work_style_dataset.csv    ← for work-style classifier
  data/processed/distraction_dataset.csv   ← for distraction scorer
"""

import sys, warnings
import numpy as np
import pandas as pd
from pathlib import Path
from rich.console import Console
from rich.table import Table
from rich.panel import Panel

warnings.filterwarnings("ignore")
console = Console()

sys.path.insert(0, str(Path(__file__).parent))
from config import (
    RAW_DIR, PROCESSED_DIR,
    BEHAVIORAL_FEATURES, TARGET_FAILURE, TARGET_STYLE, RANDOM_STATE
)

rng = np.random.default_rng(RANDOM_STATE)


# ══════════════════════════════════════════════════════════════════════════════
# Loaders β€” each maps source columns β†’ canonical BEHAVIORAL_FEATURES
# ══════════════════════════════════════════════════════════════════════════════

def _fill_missing(df: pd.DataFrame, cols: list[str], mean_range=(0, 1)) -> pd.DataFrame:
    """Add canonical columns that weren't in the source, filling with plausible values."""
    for col in cols:
        if col not in df.columns:
            low, high = mean_range
            df[col] = rng.uniform(low, high, len(df))
    return df


def load_work_style(path: Path) -> pd.DataFrame:
    df = pd.read_csv(path)
    rename = {
        "daily_avg_hours":        "session_duration_minutes",   # Γ— 60 below
        "procrastination_score":  "distraction_events",
        "self_reported_stress":   "stress_level",
        "completion_consistency": "previous_completion_rate",
        "peak_focus_duration_min": "focus_score",
        "task_switch_rate":       "tab_switches_proxy",
    }
    df = df.rename(columns=rename)
    df["session_duration_minutes"] = (df["session_duration_minutes"] * 60).clip(30, 720)
    df["break_count"] = (df.get("break_frequency_per_hour", 1) * (df["session_duration_minutes"] / 60)).round(0)
    df["social_media_minutes_before"] = rng.exponential(20, len(df)).clip(0, 120)
    df["task_complexity"]    = rng.integers(1, 6, len(df)).astype(float)
    df["time_of_day_hour"]   = rng.integers(6, 23, len(df)).astype(float)
    df["day_of_week"]        = rng.integers(0, 7, len(df)).astype(float)
    df["sleep_hours"]        = rng.normal(7, 1, len(df)).clip(4, 10)
    df["deadline_days_remaining"] = rng.exponential(3, len(df)).clip(0, 30)
    df["motivation_level"]   = rng.integers(1, 11, len(df)).astype(float)
    df["study_hours_weekly"] = rng.normal(25, 8, len(df)).clip(0, 70)
    df["work_style_score"]   = df["work_style_label"].map({"turtle": 0.1, "hare": 0.9, "hybrid": 0.5})
    return df


def load_study_habits(path: Path) -> pd.DataFrame:
    df = pd.read_csv(path)
    df["session_duration_minutes"] = (df["study_hours_weekly"] / 7 * 60).clip(10, 480)
    df["break_count"] = rng.integers(0, 8, len(df)).astype(float)
    df["social_media_minutes_before"] = df["social_media_hours_daily"] * 20  # proxy
    df["task_complexity"] = rng.integers(1, 6, len(df)).astype(float)
    df["work_style_score"] = rng.uniform(0, 1, len(df))
    df["time_of_day_hour"] = rng.integers(6, 23, len(df)).astype(float)
    df["day_of_week"]      = rng.integers(0, 7, len(df)).astype(float)
    df["distraction_events"] = (df["social_media_hours_daily"] * 2).round(0)
    df["deadline_days_remaining"] = rng.exponential(4, len(df)).clip(0, 30)
    df["previous_completion_rate"] = rng.uniform(0.3, 1.0, len(df))
    df["focus_score"] = (
        df["study_hours_weekly"] / 70
        - df["stress_level"] / 40
        + df["motivation_level"] / 40
    ).clip(0, 1)
    df["work_style_label"] = "hybrid"   # placeholder; overridden during merge
    return df


def load_remote_worker(path: Path) -> pd.DataFrame:
    df = pd.read_csv(path)
    if "hours_logged" in df.columns:
        df["session_duration_minutes"] = (df["hours_logged"] * 60).clip(30, 720)
        df["distraction_events"] = df.get("tab_switches", rng.poisson(15, len(df)))
        df["previous_completion_rate"] = df.get("completion_rate", rng.uniform(0.4, 1.0, len(df)))
        df["focus_score"] = df.get("productivity_score", rng.uniform(0.3, 0.95, len(df)))
    else:
        # Real HF dataset β€” normalise whatever columns it has
        df["session_duration_minutes"] = rng.normal(360, 90, len(df)).clip(30, 720)
        df["distraction_events"]       = rng.poisson(15, len(df))
        df["previous_completion_rate"] = rng.uniform(0.4, 1.0, len(df))
        df["focus_score"]              = rng.uniform(0.3, 0.95, len(df))
        if "task_completed" not in df.columns:
            df["task_completed"] = rng.integers(0, 2, len(df))

    df["break_count"] = df.get("break_count", rng.integers(0, 6, len(df)).astype(float))
    df["social_media_minutes_before"] = rng.exponential(18, len(df)).clip(0, 120)
    df["task_complexity"]    = rng.integers(1, 6, len(df)).astype(float)
    df["work_style_score"]   = rng.uniform(0, 1, len(df))
    df["time_of_day_hour"]   = rng.integers(6, 23, len(df)).astype(float)
    df["day_of_week"]        = rng.integers(0, 7, len(df)).astype(float)
    df["stress_level"]       = rng.integers(1, 11, len(df)).astype(float)
    df["sleep_hours"]        = rng.normal(7, 1.2, len(df)).clip(4, 10)
    df["deadline_days_remaining"] = rng.exponential(3, len(df)).clip(0, 30)
    df["motivation_level"]   = rng.integers(1, 11, len(df)).astype(float)
    df["study_hours_weekly"] = rng.normal(30, 10, len(df)).clip(0, 70)
    df["work_style_label"]   = "hybrid"
    return df


def load_social_media(path: Path) -> pd.DataFrame:
    df = pd.read_csv(path)
    df["session_duration_minutes"] = rng.normal(360, 90, len(df)).clip(30, 720)
    df["break_count"]    = rng.integers(0, 6, len(df)).astype(float)
    df["social_media_minutes_before"] = df["pre_task_sm_minutes"]
    df["task_complexity"]    = rng.integers(1, 6, len(df)).astype(float)
    df["work_style_score"]   = rng.uniform(0, 1, len(df))
    df["time_of_day_hour"]   = rng.integers(6, 23, len(df)).astype(float)
    df["day_of_week"]        = rng.integers(0, 7, len(df)).astype(float)
    df["stress_level"]       = rng.integers(1, 11, len(df)).astype(float)
    df["sleep_hours"]        = rng.normal(7, 1, len(df)).clip(4, 10)
    df["distraction_events"] = df["phone_pickups"] / 10
    df["deadline_days_remaining"] = rng.exponential(3, len(df)).clip(0, 30)
    df["previous_completion_rate"] = rng.uniform(0.3, 1.0, len(df))
    df["focus_score"] = 1 - df["distraction_score"]
    df["motivation_level"]   = rng.integers(1, 11, len(df)).astype(float)
    df["study_hours_weekly"] = rng.normal(25, 8, len(df)).clip(0, 70)
    df["work_style_label"]   = "hybrid"
    return df


# ══════════════════════════════════════════════════════════════════════════════
# Merger
# ══════════════════════════════════════════════════════════════════════════════

def merge_all() -> tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:
    frames = []

    loaders = {
        "work_style_dataset.csv":  load_work_style,
        "study_habits.csv":        load_study_habits,
        "remote_worker_productivity.csv": load_remote_worker,
        "remote_worker_productivity_synthetic.csv": load_remote_worker,
        "social_media_distraction.csv": load_social_media,
    }

    for fname, loader_fn in loaders.items():
        fpath = RAW_DIR / fname
        if fpath.exists():
            console.log(f"  Loading [bold]{fname}[/bold]…")
            try:
                df = loader_fn(fpath)
                frames.append(df)
                console.log(f"    β†’ {len(df):,} rows")
            except Exception as e:
                console.log(f"  [red]  Failed to load {fname}: {e}[/red]")

    if not frames:
        raise RuntimeError("No raw data files found. Run generate_data.py first.")

    combined = pd.concat(frames, ignore_index=True)
    console.log(f"\n[bold]Combined raw rows:[/bold] {len(combined):,}")

    # ── Ensure all canonical features exist ───────────────────────────────
    for feat in BEHAVIORAL_FEATURES:
        if feat not in combined.columns:
            # Best-guess fill
            combined[feat] = rng.uniform(0, 1, len(combined))

    # ── Clip/type cleanup ─────────────────────────────────────────────────
    combined["session_duration_minutes"]   = combined["session_duration_minutes"].clip(10, 720)
    combined["break_count"]                = combined["break_count"].clip(0, 20)
    combined["social_media_minutes_before"]= combined["social_media_minutes_before"].clip(0, 180)
    combined["task_complexity"]            = combined["task_complexity"].clip(1, 5)
    combined["work_style_score"]           = combined["work_style_score"].clip(0, 1)
    combined["time_of_day_hour"]           = combined["time_of_day_hour"].clip(0, 23)
    combined["day_of_week"]                = combined["day_of_week"].clip(0, 6)
    combined["stress_level"]               = combined["stress_level"].clip(1, 10)
    combined["sleep_hours"]                = combined["sleep_hours"].clip(2, 12)
    combined["distraction_events"]         = combined["distraction_events"].clip(0, 50)
    combined["deadline_days_remaining"]    = combined["deadline_days_remaining"].clip(0, 90)
    combined["previous_completion_rate"]   = combined["previous_completion_rate"].clip(0, 1)
    combined["focus_score"]                = combined["focus_score"].clip(0, 1)
    combined["motivation_level"]           = combined["motivation_level"].clip(1, 10)
    combined["study_hours_weekly"]         = combined["study_hours_weekly"].clip(0, 84)

    # ── Target ────────────────────────────────────────────────────────────
    if TARGET_FAILURE not in combined.columns:
        combined[TARGET_FAILURE] = 1  # fallback
    combined[TARGET_FAILURE] = combined[TARGET_FAILURE].fillna(0).astype(int).clip(0, 1)

    if TARGET_STYLE not in combined.columns:
        combined[TARGET_STYLE] = "hybrid"
    combined[TARGET_STYLE] = combined[TARGET_STYLE].fillna("hybrid")

    combined = combined.dropna(subset=BEHAVIORAL_FEATURES + [TARGET_FAILURE])
    console.log(f"[green]After cleaning:[/green] {len(combined):,} rows")

    # ── Split outputs ─────────────────────────────────────────────────────
    training_cols = BEHAVIORAL_FEATURES + [TARGET_FAILURE, TARGET_STYLE]
    training_df   = combined[[c for c in training_cols if c in combined.columns]].copy()

    # Work-style subset (only rows with labelled style)
    ws_df = combined[combined[TARGET_STYLE].isin(["turtle", "hare", "hybrid"])].copy()

    # Distraction subset
    dm_df = combined[["distraction_events", "social_media_minutes_before",
                       "break_count", "session_duration_minutes",
                       "focus_score", TARGET_FAILURE]].copy()

    return training_df, ws_df, dm_df


# ══════════════════════════════════════════════════════════════════════════════
# MAIN
# ══════════════════════════════════════════════════════════════════════════════
def main():
    console.print(Panel.fit("πŸ”§ Step 2 β€” Preprocessing & Merging", style="bold magenta"))

    training_df, ws_df, dm_df = merge_all()

    # Save
    training_df.to_csv(PROCESSED_DIR / "training_dataset.csv", index=False)
    ws_df.to_csv(PROCESSED_DIR / "work_style_dataset.csv", index=False)
    dm_df.to_csv(PROCESSED_DIR / "distraction_dataset.csv", index=False)

    # Print summary table
    table = Table(title="Processed Datasets")
    table.add_column("File", style="cyan")
    table.add_column("Rows", justify="right")
    table.add_column("Columns", justify="right")
    table.add_row("training_dataset.csv", str(len(training_df)), str(len(training_df.columns)))
    table.add_row("work_style_dataset.csv", str(len(ws_df)), str(len(ws_df.columns)))
    table.add_row("distraction_dataset.csv", str(len(dm_df)), str(len(dm_df.columns)))
    console.print(table)

    # Label balance
    vc = training_df[TARGET_FAILURE].value_counts().to_dict()
    console.print(f"\nTask completion balance β†’ Completed: {vc.get(1,0):,}  |  Failed: {vc.get(0,0):,}")

    console.print("\n[bold green]βœ… Preprocessing complete β†’ data/processed/[/bold green]")


if __name__ == "__main__":
    main()