File size: 5,138 Bytes
5e6746d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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,
    }