| import os |
| import random |
| import json |
| from pathlib import Path |
|
|
| import numpy as np |
| import pandas as pd |
| import yaml |
|
|
|
|
|
|
| def set_seed(seed: int = 17) -> None: |
| """Set global seeds for Python, NumPy, and PyTorch.""" |
| os.environ["PYTHONHASHSEED"] = str(seed) |
| random.seed(seed) |
| np.random.seed(seed) |
| try: |
| import torch |
| torch.manual_seed(seed) |
| torch.cuda.manual_seed_all(seed) |
| torch.backends.cudnn.deterministic = True |
| torch.backends.cudnn.benchmark = False |
| except ImportError: |
| pass |
|
|
|
|
|
|
| def load_cfg(path: str = "env/config.yaml") -> dict: |
| """Load a YAML config file and return as a dict.""" |
| with open(path, "r") as f: |
| return yaml.safe_load(f) |
|
|
|
|
|
|
| def must_read_csv(p) -> pd.DataFrame: |
| """Read a CSV, raising FileNotFoundError if missing.""" |
| p = Path(p) |
| if not p.exists(): |
| raise FileNotFoundError(f"Required file not found: {p}") |
| return pd.read_csv(p) |
|
|
|
|
| def save_df(df: pd.DataFrame, p) -> None: |
| """Save a DataFrame to CSV, creating parent directories as needed.""" |
| p = Path(p) |
| p.parent.mkdir(parents=True, exist_ok=True) |
| df.to_csv(p, index=False) |
|
|
|
|
| def save_json(obj: dict, p) -> None: |
| """Save a dict to JSON.""" |
| p = Path(p) |
| p.parent.mkdir(parents=True, exist_ok=True) |
| with open(p, "w") as f: |
| json.dump(obj, f, indent=2) |
|
|