-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
185 lines (148 loc) · 4.89 KB
/
utils.py
File metadata and controls
185 lines (148 loc) · 4.89 KB
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
"""
Utility functions for Google Drive video copier.
"""
import os
import sys
import logging
import traceback
from datetime import datetime
def setup_logging(log_level=logging.INFO, log_file=None, console=True):
"""
Set up logging configuration.
Args:
log_level (int): Logging level
log_file (str, optional): Path to log file
console (bool): Whether to log to console
Returns:
logging.Logger: Configured logger
"""
# Create logger
logger = logging.getLogger()
logger.setLevel(log_level)
# Create formatter
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
# Clear existing handlers
logger.handlers = []
# Add file handler if log file is specified
if log_file:
# Create directory if it doesn't exist
log_dir = os.path.dirname(log_file)
if log_dir and not os.path.exists(log_dir):
os.makedirs(log_dir)
file_handler = logging.FileHandler(log_file)
file_handler.setLevel(log_level)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
# Add console handler if console logging is enabled
if console:
console_handler = logging.StreamHandler()
console_handler.setLevel(log_level)
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)
return logger
def format_file_size(size_bytes):
"""
Format file size in human-readable format.
Args:
size_bytes (int): File size in bytes
Returns:
str: Formatted file size
"""
if size_bytes is None:
return "Unknown"
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if size_bytes < 1024.0:
return f"{size_bytes:.2f} {unit}"
size_bytes /= 1024.0
return f"{size_bytes:.2f} PB"
def format_duration(seconds):
"""
Format duration in human-readable format.
Args:
seconds (float): Duration in seconds
Returns:
str: Formatted duration
"""
minutes, seconds = divmod(int(seconds), 60)
hours, minutes = divmod(minutes, 60)
if hours > 0:
return f"{hours}h {minutes}m {seconds}s"
elif minutes > 0:
return f"{minutes}m {seconds}s"
else:
return f"{seconds}s"
def handle_error(error, exit_program=False):
"""
Handle an error by logging it and optionally exiting the program.
Args:
error (Exception): The error to handle
exit_program (bool): Whether to exit the program
"""
logger = logging.getLogger(__name__)
# Log the error
logger.error(f"Error: {str(error)}")
logger.debug(f"Error details: {traceback.format_exc()}")
# Exit the program if requested
if exit_program:
logger.critical("Exiting program due to error")
sys.exit(1)
def report_error_to_mcp(error, context=None):
"""
Report an error to MCP tools.
Args:
error (Exception): The error to report
context (dict, optional): Additional context information
"""
try:
# Import MCP tools if available
try:
from mcp_tools import report_error
# Prepare error report
error_report = {
'error': str(error),
'traceback': traceback.format_exc(),
'timestamp': datetime.now().isoformat(),
'context': context or {}
}
# Report error
report_error(error_report)
logger = logging.getLogger(__name__)
logger.info("Error reported to MCP tools")
except ImportError:
# MCP tools not available, log a warning
logger = logging.getLogger(__name__)
logger.warning("MCP tools not available, error not reported")
except Exception as e:
# Error reporting failed, log a warning
logger = logging.getLogger(__name__)
logger.warning(f"Error reporting failed: {str(e)}")
class MockMCPReporter:
"""
Mock MCP reporter for testing.
"""
def __init__(self):
self.reported_errors = []
def report_error(self, error_report):
"""
Report an error.
Args:
error_report (dict): Error report
"""
self.reported_errors.append(error_report)
logger = logging.getLogger(__name__)
logger.info(f"Mock MCP reporter: Error reported: {error_report['error']}")
def get_reported_errors(self):
"""
Get all reported errors.
Returns:
list: List of error reports
"""
return self.reported_errors
def clear_reported_errors(self):
"""
Clear all reported errors.
"""
self.reported_errors = []