-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathmisc_utils.py
More file actions
235 lines (203 loc) · 7.64 KB
/
misc_utils.py
File metadata and controls
235 lines (203 loc) · 7.64 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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
#################################################################################
# Copyright (c) 2023-2026, Texas Instruments
# All Rights Reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#################################################################################
import errno
import importlib
import json
import os
import platform
import re
import shutil
import subprocess
import sys
from logging import getLogger
import tqdm
import yaml
from . import config_dict
def _absolute_path(relpath):
if relpath is None:
return relpath
elif relpath.startswith('http://') or relpath.startswith('https://'):
return relpath
else:
return os.path.abspath(os.path.expanduser(os.path.normpath(relpath)))
def absolute_path(relpath):
if isinstance(relpath, (list,tuple)):
return [_absolute_path(f) for f in relpath]
else:
return _absolute_path(relpath)
def is_junction(path: str) -> bool:
try:
return bool(os.readlink(path))
except OSError:
return False
def remove_if_exists(path):
try:
if os.path.islink(path):
os.unlink(path)
elif is_junction(path):
os.unlink(path)
else:
shutil.rmtree(path)
#
except OSError as e:
if e.errno != errno.ENOENT:
raise
#
def make_symlink(source, dest):
if source is None or (not os.path.exists(source)):
print(f'make_symlink failed - source: {source} is invalid')
return
#
remove_if_exists(dest)
if os.path.dirname(source) == os.path.dirname(dest):
base_dir = os.path.dirname(source)
cur_dir = os.getcwd()
os.chdir(base_dir)
create_link_or_shortcut(os.path.basename(source), os.path.basename(dest))
os.chdir(cur_dir)
else:
create_link_or_shortcut(source, dest)
def create_link_or_shortcut(src, dst):
logger = getLogger("root.utils.misc.CLS")
try:
if os.path.isdir(src):
# Required to support Windows OS with developer mode enabled, target_is_directory is ignored on Linux
os.symlink(src, dst, target_is_directory=True)
else:
os.symlink(src, dst)
except OSError as e:
if platform.system() in ['Windows']:
logger.warning("Failed to create symbolic link. Creating a junction instead")
try:
subprocess.check_call(['cmd', '/c', 'mklink', '/J', dst, src])
logger.info("Junction created: {dst} -> {src}")
except subprocess.CalledProcessError as e:
logger.error(f"Failed to create junction: {e}")
else:
logger.error(f"Failed to create symbolic link due to {e}. Creating a junction instead")
def import_file_or_folder(folder_or_file_name, package_name=None, force_import=False):
if folder_or_file_name.endswith(os.sep):
folder_or_file_name = folder_or_file_name[:-1]
#
if folder_or_file_name.endswith('.py'):
folder_or_file_name = folder_or_file_name[:-3]
#
parent_folder = os.path.dirname(folder_or_file_name)
basename = os.path.basename(folder_or_file_name)
if force_import:
sys.modules.pop(basename, None)
#
sys.path.insert(0, parent_folder)
imported_module = importlib.import_module(basename, package_name or __name__)
sys.path.pop(0)
return imported_module
def simplify_dict(in_dict):
'''
simplify dict so that it can be written using yaml(pyyaml) package
'''
assert isinstance(in_dict, (dict, config_dict.ConfigDict)), 'input must of type dict or ConfigDict'
d = dict()
for k, v in in_dict.items():
if isinstance(v, (dict,config_dict.ConfigDict)):
d[k] = simplify_dict(v)
elif isinstance(v, tuple):
d[k] = list(v)
else:
d[k] = v
#
#
return d
def write_dict(dict_obj, filename, write_json=True, write_yaml=True):
if write_json:
filename_json = os.path.splitext(filename)[0] + '.json'
with open(filename_json, 'w') as fp:
json.dump(dict_obj, fp, indent=2, separators=[',',':'])
#
#
if write_yaml:
dict_obj = simplify_dict(dict_obj)
filename_yaml = os.path.splitext(filename)[0] + '.yaml'
with open(filename_yaml, 'w') as fp:
yaml.safe_dump(dict_obj, fp)
#
#
def cleanup_special_chars(file_name):
if os.path.exists(file_name):
with open(file_name, encoding="utf-8") as rfp:
new_lines = []
log_lines = rfp.readlines()
for log_line in log_lines:
log_line = re.sub(r'(\x9B|\x1B[\[\(\=])[0-?]*[ -\/]*([@-~]|$)', '', log_line)
new_lines.append(log_line)
#
#
# Write after closing the read handle to avoid data loss if write fails mid-way
with open(file_name, 'w', encoding="utf-8") as wfp:
wfp.writelines(new_lines)
#
#
def is_url(download_entry):
return isinstance(download_entry, str) and \
(download_entry.startswith('http://') or download_entry.startswith('https://'))
class ProgressBar():
def __init__(self, total_size, unit=None):
self.total_size = total_size
self.pbar = None
self.unit = unit
def __call__(self, cur_size):
if self.pbar is None:
# creation of pbar is delayed so that if the call happens in a different process, it will still work
self.pbar = tqdm.tqdm(total=self.total_size, unit=self.unit)
#
self.pbar.update(cur_size)
if cur_size >= self.total_size:
self.pbar.close()
#
def update(self, cur_size):
self.__call__(cur_size)
def str2bool(v):
'''a utility function used for argument parsing'''
if v is None:
return False
elif isinstance(v, str):
if v.lower() in ('', 'none', 'false', 'no', '0'):
return False
elif v.lower() in ('true', 'yes', '1'):
return True
#
#
return bool(v)
def deep_update_dict(dict1, dict2):
for key, value in dict2.items():
if isinstance(value, dict) and key in dict1 and isinstance(dict1[key], dict):
deep_update_dict(dict1[key], value)
else:
dict1[key] = value
return dict1