File size: 5,293 Bytes
4189555 | 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 | #!/usr/bin/env python3
"""Build a deterministic sampled course list for publishing.
Sources:
1. Blast columns that match *_exp from temporary/all_email_blasts_consolidated.csv.
2. Certification names from raw_data/expirations.csv (column: certification).
All discovered course names are deduplicated, ordered by salted hash, and written to:
temporary/sampled_courses.csv
"""
from __future__ import annotations
import argparse
import csv
import hashlib
from pathlib import Path
def parse_args() -> argparse.Namespace:
project_root = Path(__file__).resolve().parent.parent
parser = argparse.ArgumentParser(
description="Create deterministically ordered sampled course list."
)
parser.add_argument(
"--blast-file",
default=str(project_root / "temporary" / "all_email_blasts_consolidated.csv"),
help="Path to consolidated blast CSV.",
)
parser.add_argument(
"--expirations-file",
default=str(project_root / "raw_data" / "expirations.csv"),
help="Path to expirations CSV.",
)
parser.add_argument(
"--env-file",
default=str(project_root / ".env"),
help="Path to .env with SALT.",
)
parser.add_argument(
"--output",
default=str(project_root / "temporary" / "sampled_courses.csv"),
help="Output CSV path.",
)
return parser.parse_args()
def read_salt(env_path: Path) -> str:
if not env_path.exists():
raise FileNotFoundError(f"Required env file not found: {env_path}")
salt = ""
with env_path.open("r", encoding="utf-8") as f:
for line in f:
stripped = line.strip()
if not stripped or stripped.startswith("#"):
continue
if stripped.startswith("SALT="):
salt = stripped.split("=", 1)[1].strip().strip('"').strip("'")
break
if not salt:
raise RuntimeError(f"SALT was not found or empty in: {env_path}")
return salt
def derive_course_ordering_hash(salt: str) -> str:
return hashlib.sha256(f"{salt}course".encode("utf-8")).hexdigest()
def read_exp_columns_from_blast(blast_path: Path) -> set[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}")
course_names = {
col.strip().lower().removesuffix("_exp")
for col in reader.fieldnames
if col and col.strip().lower().endswith("_exp")
}
return {c for c in course_names if c}
def read_certifications(expirations_path: Path) -> set[str]:
if not expirations_path.exists():
raise FileNotFoundError(
f"Required expirations file not found: {expirations_path}"
)
certifications: set[str] = set()
with expirations_path.open("r", encoding="utf-8", newline="") as f:
reader = csv.DictReader(f)
if not reader.fieldnames:
raise RuntimeError(f"Expirations file has no header: {expirations_path}")
if "certification" not in reader.fieldnames:
raise RuntimeError(
"Expirations file missing required 'certification' column: "
f"{expirations_path}"
)
for row in reader:
cert = (row.get("certification") or "").strip().lower()
if cert:
certifications.add(cert)
return certifications
def course_order_hash(course_ordering_hash: str, course_name: str) -> str:
return hashlib.sha256(f"{course_ordering_hash}{course_name}".encode("utf-8")).hexdigest()
def write_courses(output_path: Path, courses: list[str]) -> None:
output_path.parent.mkdir(parents=True, exist_ok=True)
with output_path.open("w", encoding="utf-8", newline="") as f:
writer = csv.writer(f)
writer.writerow(["course"])
for course in courses:
writer.writerow([course])
def main() -> None:
args = parse_args()
blast_path = Path(args.blast_file)
expirations_path = Path(args.expirations_file)
env_path = Path(args.env_file)
output_path = Path(args.output)
salt = read_salt(env_path)
course_ordering_hash = derive_course_ordering_hash(salt)
blast_courses = read_exp_columns_from_blast(blast_path)
expiration_courses = read_certifications(expirations_path)
all_courses = blast_courses | expiration_courses
if not all_courses:
raise RuntimeError("No course values were found from either source.")
ordered_courses = [
value
for _, value in sorted(
(
(course_order_hash(course_ordering_hash, value), value)
for value in all_courses
),
key=lambda pair: (pair[0], pair[1]),
)
]
write_courses(output_path, ordered_courses)
print(f"Blast *_exp courses: {len(blast_courses)}")
print(f"Expiration certifications: {len(expiration_courses)}")
print(f"Total unique courses written: {len(ordered_courses)}")
print(f"Output: {output_path}")
if __name__ == "__main__":
main() |