File size: 2,016 Bytes
04b129a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Utility functions for the project
"""

import os
from pathlib import Path
from datetime import datetime
from typing import Union, Optional
import json


def get_project_root() -> Path:
    """Get the project root directory"""
    return Path(__file__).parent.parent


def ensure_dir_exists(directory: Union[str, Path]) -> Path:
    """Create directory if it doesn't exist"""
    path = Path(directory)
    path.mkdir(parents=True, exist_ok=True)
    return path


def get_timestamp() -> str:
    """Get current timestamp as string"""
    return datetime.now().strftime("%Y%m%d_%H%M%S")


def save_results(data: dict, filename: str, directory: Optional[Union[str, Path]] = None) -> Path:
    """
    Save results as JSON file
    
    Args:
        data: Dictionary to save
        filename: Output filename
        directory: Output directory (default: outputs/)
        
    Returns:
        Path to saved file
    """
    if directory is None:
        directory = get_project_root() / "data" / "outputs"
    
    ensure_dir_exists(directory)
    filepath = Path(directory) / filename
    
    with open(filepath, 'w') as f:
        json.dump(data, f, indent=4)
    
    return filepath


def format_number(value: float, decimals: int = 2) -> str:
    """Format number with specified decimals"""
    return f"{value:.{decimals}f}"


def generate_file_path(prefix: str = "", suffix: str = "", 
                       extension: str = "csv", directory: Optional[str] = None) -> Path:
    """Generate a timestamped file path"""
    if directory is None:
        directory = get_project_root() / "data" / "outputs"
    
    ensure_dir_exists(directory)
    
    timestamp = get_timestamp()
    filename = f"{prefix}_{timestamp}_{suffix}.{extension}".strip("_")
    
    return Path(directory) / filename


def log_message(message: str, level: str = "INFO") -> str:
    """Create a formatted log message"""
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    return f"[{timestamp}] [{level}] {message}"