| |
| """Create blinded publishable datasets from raw and temporary inputs. |
| |
| Inputs: |
| - temporary/all_email_blasts_consolidated.csv |
| - temporary/sampled_email_addresses.csv |
| - temporary/sampled_courses.csv |
| - raw_data/expirations.csv |
| - raw_data/orders.csv |
| - .env with LARGE_BLAST_SIZE |
| |
| Outputs: |
| - published_data/email_blasts.parquet |
| - published_data/expirations.parquet |
| - published_data/orders.parquet |
| |
| Blinded indexes are the 0-based row positions from the sampled CSV files, |
| excluding the header row. |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import csv |
| from decimal import Decimal, InvalidOperation |
| from pathlib import Path |
|
|
| import pyarrow as pa |
| import pyarrow.parquet as pq |
|
|
|
|
| def parse_args() -> argparse.Namespace: |
| project_root = Path(__file__).resolve().parent.parent |
| parser = argparse.ArgumentParser( |
| description="Create publishable blinded datasets from sampled inputs." |
| ) |
| parser.add_argument( |
| "--blast-file", |
| default=str(project_root / "temporary" / "all_email_blasts_consolidated.csv"), |
| ) |
| parser.add_argument( |
| "--sampled-emails-file", |
| default=str(project_root / "temporary" / "sampled_email_addresses.csv"), |
| ) |
| parser.add_argument( |
| "--sampled-courses-file", |
| default=str(project_root / "temporary" / "sampled_courses.csv"), |
| ) |
| parser.add_argument( |
| "--expirations-file", |
| default=str(project_root / "raw_data" / "expirations.csv"), |
| ) |
| parser.add_argument( |
| "--orders-file", |
| default=str(project_root / "raw_data" / "orders.csv"), |
| ) |
| parser.add_argument( |
| "--env-file", |
| default=str(project_root / ".env"), |
| ) |
| parser.add_argument( |
| "--output-folder", |
| default=str(project_root / "published_data"), |
| ) |
| return parser.parse_args() |
|
|
|
|
| def read_env_values(env_path: Path) -> dict[str, str]: |
| if not env_path.exists(): |
| raise FileNotFoundError(f"Required env file not found: {env_path}") |
|
|
| values: dict[str, str] = {} |
| with env_path.open("r", encoding="utf-8") as f: |
| for line in f: |
| stripped = line.strip() |
| if not stripped or stripped.startswith("#") or "=" not in stripped: |
| continue |
| key, value = stripped.split("=", 1) |
| values[key.strip()] = value.strip().strip('"').strip("'") |
| return values |
|
|
|
|
| def read_required_large_blast_size(env_path: Path) -> int: |
| values = read_env_values(env_path) |
| raw = values.get("LARGE_BLAST_SIZE", "") |
| if not raw: |
| raise RuntimeError(f"LARGE_BLAST_SIZE was not found or empty in: {env_path}") |
| try: |
| return int(raw) |
| except ValueError as exc: |
| raise RuntimeError( |
| f"LARGE_BLAST_SIZE must be an integer in: {env_path}" |
| ) from exc |
|
|
|
|
| def read_index_map(path: Path, required_header: str) -> dict[str, int]: |
| if not path.exists(): |
| raise FileNotFoundError(f"Required sampled file not found: {path}") |
|
|
| mapping: dict[str, int] = {} |
| with path.open("r", encoding="utf-8", newline="") as f: |
| reader = csv.DictReader(f) |
| if not reader.fieldnames: |
| raise RuntimeError(f"Sampled file has no header: {path}") |
| if required_header not in reader.fieldnames: |
| raise RuntimeError( |
| f"Sampled file missing required '{required_header}' column: {path}" |
| ) |
|
|
| for index, row in enumerate(reader): |
| key = (row.get(required_header) or "").strip().lower() |
| if not key: |
| raise RuntimeError( |
| f"Blank {required_header} value found at sampled index {index} in: {path}" |
| ) |
| if key in mapping: |
| raise RuntimeError( |
| f"Duplicate {required_header} value found in sampled file: {key}" |
| ) |
| mapping[key] = index |
|
|
| if not mapping: |
| raise RuntimeError(f"No sampled values found in: {path}") |
|
|
| return mapping |
|
|
|
|
| def read_blast_exp_columns(blast_path: Path) -> list[str]: |
| if not blast_path.exists(): |
| raise FileNotFoundError(f"Required blast file not found: {blast_path}") |
|
|
| with blast_path.open("r", encoding="utf-8", newline="") as f: |
| reader = csv.DictReader(f) |
| if not reader.fieldnames: |
| raise RuntimeError(f"Blast file has no header: {blast_path}") |
| return [ |
| col for col in reader.fieldnames if col and col.strip().lower().endswith("_exp") |
| ] |
|
|
|
|
| def get_blast_course_columns( |
| exp_columns: list[str], course_index_map: dict[str, int] |
| ) -> list[tuple[int, str, str]]: |
| blinded_columns: list[tuple[int, str, str]] = [] |
| for exp_col in exp_columns: |
| course_name = exp_col.strip().lower().removesuffix("_exp") |
| if course_name not in course_index_map: |
| raise RuntimeError( |
| f"Course from blast column not found in sampled courses: {course_name}" |
| ) |
| course_index = course_index_map[course_name] |
| blinded_columns.append( |
| (course_index, exp_col, f"blinded_course_{course_index}_exp") |
| ) |
| blinded_columns.sort(key=lambda item: (item[0], item[2])) |
| return blinded_columns |
|
|
|
|
| def parse_decimal(value: str) -> Decimal: |
| try: |
| return Decimal(value) |
| except InvalidOperation as exc: |
| raise RuntimeError(f"Invalid decimal value: {value}") from exc |
|
|
|
|
| def write_parquet_rows(rows: list[dict[str, object]], fieldnames: list[str], output_path: Path) -> None: |
| columns = {name: [row.get(name) for row in rows] for name in fieldnames} |
| table = pa.table(columns) |
| pq.write_table(table, output_path) |
|
|
|
|
| def create_published_blasts( |
| blast_path: Path, |
| output_path: Path, |
| email_index_map: dict[str, int], |
| large_blast_size: int, |
| blast_course_columns: list[tuple[int, str, str]], |
| ) -> int: |
| blinded_exp_columns = [target_col for _, _, target_col in blast_course_columns] |
| fieldnames = [ |
| "sent_at", |
| "is_large_blast", |
| "email_blinded_index", |
| *blinded_exp_columns, |
| ] |
|
|
| rows: list[dict[str, object]] = [] |
| with blast_path.open("r", encoding="utf-8", newline="") as src: |
| reader = csv.DictReader(src) |
|
|
| for row in reader: |
| email = (row.get("email") or "").strip().lower() |
| if email not in email_index_map: |
| continue |
|
|
| sent_at = (row.get("sent_at") or "").strip() |
| if not sent_at: |
| raise RuntimeError("Blast row missing required sent_at value") |
|
|
| total_recipients_raw = (row.get("total_recipients_of_batch") or "").strip() |
| try: |
| total_recipients = int(total_recipients_raw) |
| except ValueError as exc: |
| raise RuntimeError( |
| f"Invalid total_recipients_of_batch value: {total_recipients_raw}" |
| ) from exc |
|
|
| out_row = { |
| "sent_at": sent_at, |
| "is_large_blast": 1 if total_recipients >= large_blast_size else 0, |
| "email_blinded_index": email_index_map[email], |
| } |
| for _, source_col, target_col in blast_course_columns: |
| out_row[target_col] = (row.get(source_col) or "").strip() |
| rows.append(out_row) |
|
|
| rows.sort( |
| key=lambda row: ( |
| str(row["sent_at"]), |
| int(row["is_large_blast"]), |
| int(row["email_blinded_index"]), |
| *[str(row[col]) for col in blinded_exp_columns], |
| ) |
| ) |
|
|
| write_parquet_rows(rows, fieldnames, output_path) |
|
|
| return len(rows) |
|
|
|
|
| def create_published_expirations( |
| expirations_path: Path, |
| output_path: Path, |
| email_index_map: dict[str, int], |
| course_index_map: dict[str, int], |
| ) -> int: |
| fieldnames = [ |
| "email_blinded_index", |
| "expired_date", |
| "course_blinded_index", |
| "our_course", |
| ] |
|
|
| rows: list[dict[str, object]] = [] |
| with expirations_path.open("r", encoding="utf-8", newline="") as src: |
| reader = csv.DictReader(src) |
|
|
| for row in reader: |
| email = (row.get("email") or "").strip().lower() |
| if email not in email_index_map: |
| continue |
|
|
| certification = (row.get("certification") or "").strip().lower() |
| if certification not in course_index_map: |
| raise RuntimeError( |
| f"Certification not found in sampled courses: {certification}" |
| ) |
|
|
| rows.append( |
| { |
| "email_blinded_index": email_index_map[email], |
| "expired_date": (row.get("expired_date") or "").strip(), |
| "course_blinded_index": course_index_map[certification], |
| "our_course": (row.get("our_course") or "").strip(), |
| } |
| ) |
|
|
| rows.sort( |
| key=lambda row: ( |
| int(row["email_blinded_index"]), |
| str(row["expired_date"]), |
| int(row["course_blinded_index"]), |
| str(row["our_course"]), |
| ) |
| ) |
|
|
| write_parquet_rows(rows, fieldnames, output_path) |
|
|
| return len(rows) |
|
|
|
|
| def create_published_orders( |
| orders_path: Path, |
| output_path: Path, |
| email_index_map: dict[str, int], |
| ) -> int: |
| fieldnames = ["created_at", "email_blinded_index", "price"] |
| rows: list[dict[str, object]] = [] |
|
|
| with orders_path.open("r", encoding="utf-8", newline="") as src: |
| reader = csv.DictReader(src) |
|
|
| for row in reader: |
| email = (row.get("email") or "").strip().lower() |
| if email not in email_index_map: |
| continue |
|
|
| rows.append( |
| { |
| "created_at": (row.get("created_at") or "").strip(), |
| "email_blinded_index": email_index_map[email], |
| "price": (row.get("price") or "").strip(), |
| } |
| ) |
|
|
| rows.sort( |
| key=lambda row: ( |
| str(row["created_at"]), |
| int(row["email_blinded_index"]), |
| parse_decimal(str(row["price"])), |
| ) |
| ) |
|
|
| write_parquet_rows(rows, fieldnames, output_path) |
|
|
| return len(rows) |
|
|
|
|
| def main() -> None: |
| args = parse_args() |
| blast_path = Path(args.blast_file) |
| sampled_emails_path = Path(args.sampled_emails_file) |
| sampled_courses_path = Path(args.sampled_courses_file) |
| expirations_path = Path(args.expirations_file) |
| orders_path = Path(args.orders_file) |
| env_path = Path(args.env_file) |
| output_folder = Path(args.output_folder) |
|
|
| output_folder.mkdir(parents=True, exist_ok=True) |
|
|
| large_blast_size = read_required_large_blast_size(env_path) |
| email_index_map = read_index_map(sampled_emails_path, "email") |
| course_index_map = read_index_map(sampled_courses_path, "course") |
| exp_columns = read_blast_exp_columns(blast_path) |
| blast_course_columns = get_blast_course_columns(exp_columns, course_index_map) |
|
|
| blast_rows = create_published_blasts( |
| blast_path, |
| output_folder / "email_blasts.parquet", |
| email_index_map, |
| large_blast_size, |
| blast_course_columns, |
| ) |
| expiration_rows = create_published_expirations( |
| expirations_path, |
| output_folder / "expirations.parquet", |
| email_index_map, |
| course_index_map, |
| ) |
| order_rows = create_published_orders( |
| orders_path, |
| output_folder / "orders.parquet", |
| email_index_map, |
| ) |
|
|
| print(f"Published blast rows: {blast_rows:,}") |
| print(f"Published expiration rows: {expiration_rows:,}") |
| print(f"Published order rows: {order_rows:,}") |
| print(f"Output folder: {output_folder}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |