"""Common utility functions for the MLOps platform.""" import hashlib import json import os import time from functools import wraps from pathlib import Path from typing import Any, Callable, Dict, List, Optional, TypeVar, Union import joblib import numpy as np import pandas as pd import yaml from src.logger import get_logger logger = get_logger(__name__) T = TypeVar("T") def timer(func: Callable) -> Callable: """Decorator to measure function execution time.""" @wraps(func) def wrapper(*args, **kwargs): start = time.perf_counter() result = func(*args, **kwargs) elapsed = time.perf_counter() - start logger.info(f"{func.__name__} completed in {elapsed:.3f}s") return result return wrapper def ensure_dir(path: Union[str, Path]) -> Path: """Ensure directory exists, create if not.""" path = Path(path) path.mkdir(parents=True, exist_ok=True) return path def save_json(data: Dict[str, Any], path: Union[str, Path]) -> None: """Save data as JSON file.""" path = Path(path) ensure_dir(path.parent) with open(path, "w", encoding="utf-8") as f: json.dump(data, f, indent=2, default=str) logger.debug(f"Saved JSON to {path}") def load_json(path: Union[str, Path]) -> Dict[str, Any]: """Load JSON file.""" with open(path, "r", encoding="utf-8") as f: return json.load(f) def save_yaml(data: Dict[str, Any], path: Union[str, Path]) -> None: """Save data as YAML file.""" path = Path(path) ensure_dir(path.parent) with open(path, "w", encoding="utf-8") as f: yaml.dump(data, f, default_flow_style=False, indent=2) def load_yaml(path: Union[str, Path]) -> Dict[str, Any]: """Load YAML file.""" with open(path, "r", encoding="utf-8") as f: return yaml.safe_load(f) or {} def save_object(obj: Any, path: Union[str, Path], compress: int = 3) -> None: """Save Python object using joblib with compression. Args: obj: Object to serialize. path: Destination file path. compress: joblib compression level 0-9 (3 = good speed/size tradeoff). """ path = Path(path) ensure_dir(path.parent) joblib.dump(obj, path, compress=compress, protocol=4) logger.debug("Saved object to %s (compress=%d)", path, compress) def load_object(path: Union[str, Path]) -> Any: """Load Python object using joblib.""" return joblib.load(path) def get_file_hash(path: Union[str, Path]) -> str: """Calculate SHA256 hash of a file.""" sha256 = hashlib.sha256() with open(path, "rb") as f: for chunk in iter(lambda: f.read(8192), b""): sha256.update(chunk) return sha256.hexdigest() def get_dataframe_info(df: pd.DataFrame) -> Dict[str, Any]: """Get comprehensive info about a DataFrame.""" numeric_cols = df.select_dtypes(include=[np.number]).columns.tolist() categorical_cols = df.select_dtypes(include=["object", "category"]).columns.tolist() return { "rows": len(df), "columns": len(df.columns), "missing_total": int(df.isnull().sum().sum()), "missing_per_column": df.isnull().sum().to_dict(), "duplicates": int(df.duplicated().sum()), "numeric_columns": numeric_cols, "categorical_columns": categorical_cols, "dtypes": {col: str(dtype) for col, dtype in df.dtypes.items()}, "memory_mb": round(df.memory_usage(deep=True).sum() / 1024**2, 2), } def detect_task_type(series: pd.Series, threshold: int = 10) -> str: """Auto-detect if target column is for regression or classification.""" if series.dtype in [np.float64, np.float32]: return "regression" n_unique = series.nunique() if n_unique <= threshold: return "classification" return "regression" def format_metric(value: float, decimals: int = 4) -> str: """Format a metric value for display.""" return f"{value:.{decimals}f}" def flatten_dict(d: Dict, parent_key: str = "", sep: str = ".") -> Dict[str, Any]: """Flatten a nested dictionary.""" items: List = [] for k, v in d.items(): new_key = f"{parent_key}{sep}{k}" if parent_key else k if isinstance(v, dict): items.extend(flatten_dict(v, new_key, sep).items()) else: items.append((new_key, v)) return dict(items) def sanitize_metric_name(name: str) -> str: """Sanitize metric name for MLflow logging.""" return name.replace(" ", "_").replace("-", "_").lower() def get_system_info() -> Dict[str, Any]: """Get system resource information.""" import platform import psutil return { "platform": platform.system(), "python_version": platform.python_version(), "cpu_count": os.cpu_count(), "cpu_percent": psutil.cpu_percent(interval=1), "memory_total_gb": round(psutil.virtual_memory().total / 1024**3, 2), "memory_available_gb": round(psutil.virtual_memory().available / 1024**3, 2), "memory_percent": psutil.virtual_memory().percent, "disk_usage_percent": psutil.disk_usage("/").percent, }