jacksung-dev 0.0.4.15__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. jacksung/__init__.py +1 -0
  2. jacksung/ai/GeoAttX.py +356 -0
  3. jacksung/ai/GeoNet/__init__.py +0 -0
  4. jacksung/ai/GeoNet/m_block.py +393 -0
  5. jacksung/ai/GeoNet/m_blockV2.py +442 -0
  6. jacksung/ai/GeoNet/m_network.py +107 -0
  7. jacksung/ai/GeoNet/m_networkV2.py +91 -0
  8. jacksung/ai/__init__.py +0 -0
  9. jacksung/ai/latex_tool.py +199 -0
  10. jacksung/ai/metrics.py +181 -0
  11. jacksung/ai/utils/__init__.py +0 -0
  12. jacksung/ai/utils/cmorph.py +42 -0
  13. jacksung/ai/utils/data_parallelV2.py +90 -0
  14. jacksung/ai/utils/fy.py +333 -0
  15. jacksung/ai/utils/goes.py +161 -0
  16. jacksung/ai/utils/gsmap.py +24 -0
  17. jacksung/ai/utils/imerg.py +159 -0
  18. jacksung/ai/utils/metsat.py +164 -0
  19. jacksung/ai/utils/norm_util.py +109 -0
  20. jacksung/ai/utils/util.py +300 -0
  21. jacksung/libs/times.ttf +0 -0
  22. jacksung/utils/__init__.py +1 -0
  23. jacksung/utils/base_db.py +72 -0
  24. jacksung/utils/cache.py +71 -0
  25. jacksung/utils/data_convert.py +273 -0
  26. jacksung/utils/exception.py +27 -0
  27. jacksung/utils/fastnumpy.py +115 -0
  28. jacksung/utils/figure.py +251 -0
  29. jacksung/utils/hash.py +26 -0
  30. jacksung/utils/image.py +221 -0
  31. jacksung/utils/log.py +86 -0
  32. jacksung/utils/login.py +149 -0
  33. jacksung/utils/mean_std.py +66 -0
  34. jacksung/utils/multi_task.py +129 -0
  35. jacksung/utils/number.py +6 -0
  36. jacksung/utils/nvidia.py +140 -0
  37. jacksung/utils/time.py +87 -0
  38. jacksung/utils/web.py +63 -0
  39. jacksung_dev-0.0.4.15.dist-info/LICENSE +201 -0
  40. jacksung_dev-0.0.4.15.dist-info/METADATA +228 -0
  41. jacksung_dev-0.0.4.15.dist-info/RECORD +44 -0
  42. jacksung_dev-0.0.4.15.dist-info/WHEEL +5 -0
  43. jacksung_dev-0.0.4.15.dist-info/entry_points.txt +3 -0
  44. jacksung_dev-0.0.4.15.dist-info/top_level.txt +1 -0
@@ -0,0 +1,149 @@
1
+ import time
2
+ import os
3
+ import requests
4
+ import subprocess
5
+ # 从selenium导入webdriver
6
+ from selenium import webdriver
7
+ from selenium.webdriver.chrome.service import Service
8
+ from selenium.webdriver.common.by import By
9
+ import platform
10
+ from selenium.common.exceptions import NoSuchElementException
11
+ import traceback, sys
12
+ import argparse
13
+ import yaml
14
+
15
+
16
+ class ecnu_login:
17
+ def __init__(self, driver_path=None, tmp_path=None):
18
+ options = webdriver.ChromeOptions()
19
+
20
+ options.add_argument("--no-sandbox")
21
+ options.add_argument('--disable-dev-shm-usage')
22
+ options.add_argument('--user-agent=Mozilla/5.0 HAHA')
23
+ options.add_experimental_option("detach", True)
24
+ options.add_argument('--headless') # 浏览器隐式启动
25
+ options.add_argument("--window-size=1920,1080")
26
+ self.url = "https://login.ecnu.edu.cn/"
27
+ self.driver = None
28
+ if tmp_path:
29
+ options.add_argument("crash-dumps-dir=" + tmp_path)
30
+ self.options = options
31
+ self.driver_path = driver_path
32
+
33
+ def get_drive(self):
34
+ print('driver is going to init!')
35
+ self.driver = webdriver.Chrome(service=Service(self.driver_path) if self.driver_path else None,
36
+ options=self.options)
37
+ print('driver is inited!')
38
+ self.driver.get(self.url)
39
+ time.sleep(0.5)
40
+ self.driver.refresh()
41
+ time.sleep(2)
42
+
43
+ # todo:准备打包
44
+ def refresh_drive(self):
45
+ self.driver.get(self.url)
46
+ self.driver.refresh()
47
+ time.sleep(3)
48
+
49
+ def close_driver(self):
50
+ self.driver.close()
51
+ self.driver.quit()
52
+
53
+ def login_check(self, username, password):
54
+ print('checking net......')
55
+ if self.print_ip():
56
+ return True
57
+ else:
58
+ return self.login(username, password)
59
+
60
+ def print_ip(self):
61
+ try:
62
+ time.sleep(4)
63
+ ipv4 = self.driver.find_element(By.ID, 'ipv4')
64
+ if ipv4:
65
+ print('当前IP:', ipv4.text)
66
+ return True
67
+ except Exception as e:
68
+ return False
69
+
70
+ def login(self, username, password):
71
+ if self.print_ip():
72
+ print('目前已登录!')
73
+ return True
74
+ driver = self.driver
75
+ try:
76
+ driver.refresh()
77
+ time.sleep(2)
78
+ username_ele = driver.find_element(By.ID, "username")
79
+ password_ele = driver.find_element(By.ID, "password")
80
+ username_ele.send_keys(username)
81
+ password_ele.send_keys(password)
82
+ print(rf'当前登录账户:{username}')
83
+ # driver.find_element(By.ID, 'login-account').click()
84
+ button = driver.find_element(By.ID, 'login-account')
85
+ driver.execute_script("arguments[0].click();", button)
86
+ time.sleep(2)
87
+ try:
88
+ ipv4 = driver.find_element(By.ID, 'ipv4')
89
+ print('登录成功')
90
+ print('当前IP:', ipv4.text)
91
+ return True
92
+ except NoSuchElementException as e:
93
+ print(driver.find_element(By.XPATH,
94
+ "/html/body/div[2]/div[@class='component dialog confirm active']/div[@class='content']/div[@class='section']")
95
+ .text)
96
+ return False
97
+ except Exception as e:
98
+ print('登录失败!')
99
+ traceback.print_exc()
100
+ driver.save_screenshot('err.png')
101
+ return False
102
+
103
+ def logout(self):
104
+ driver = self.driver
105
+ try:
106
+ driver.find_element(By.ID, 'logout').click()
107
+ time.sleep(3)
108
+ driver.find_element(By.CLASS_NAME, 'btn-confirm').click()
109
+ print('登出成功')
110
+ return True
111
+ except Exception as e:
112
+ print('登出失败!')
113
+ traceback.print_exc()
114
+ return False
115
+
116
+
117
+ def main():
118
+ if platform.system().lower() == 'windows':
119
+ driver_path = os.path.expanduser("~/chrome/chromedriver.exe")
120
+ else:
121
+ driver_path = os.path.expanduser("~/chrome/chromedriver")
122
+
123
+ login = ecnu_login(driver_path=driver_path, tmp_path=os.path.expanduser("~/chrome/tmp"))
124
+ login.get_drive()
125
+ parser = argparse.ArgumentParser(
126
+ prog='login', # 程序名
127
+ description='login or logout', # 描述
128
+ epilog='Copyright(r), 2023' # 说明信息
129
+ )
130
+
131
+ parser.add_argument('-t', default='login_check')
132
+ parser.add_argument('-u', default='')
133
+ parser.add_argument('-p', default='')
134
+ args = parser.parse_args()
135
+ config_file = os.path.expanduser("~/.ecnu_login")
136
+ if os.path.exists(config_file):
137
+ opt = vars(args)
138
+ yaml_args = yaml.load(open(config_file), Loader=yaml.FullLoader)
139
+ if args.u != '' and 'u' in yaml_args:
140
+ yaml_args.pop('u')
141
+ if args.p != '' and 'p' in yaml_args:
142
+ yaml_args.pop('p')
143
+ opt.update(yaml_args)
144
+ if args.t == 'login_check':
145
+ login.login_check(args.u, args.p)
146
+ elif args.t == 'login':
147
+ login.login(args.u, args.p)
148
+ elif args.t == 'logout':
149
+ login.logout()
@@ -0,0 +1,66 @@
1
+ import numpy as np
2
+
3
+
4
+ def mean_std_part2all(num_list, mean_list, std_list):
5
+ # [(n,mean,std)]
6
+ group_num = len(num_list)
7
+ dim = mean_list[0].shape
8
+ data_num = sum(num_list)
9
+
10
+ global_mean = np.zeros(dim, dtype=np.float64)
11
+ global_var = np.zeros(dim, dtype=np.float64)
12
+ for i in range(group_num):
13
+ global_mean += (num_list[i] / data_num * mean_list[i])
14
+ for i in range(group_num):
15
+ global_var += (num_list[i] / data_num * (std_list[i] ** 2 + (global_mean - mean_list[i]) ** 2))
16
+ return global_mean, np.sqrt(global_var)
17
+
18
+
19
+ def cal_mean_std_one_loop(s, ss, count):
20
+ mean_pixel = s / count
21
+ mean_level = mean_pixel.mean((-2, -1))
22
+
23
+ var_pixel = ss / count - np.square(mean_pixel)
24
+ ss_level = ss.mean((-2, -1))
25
+ var_level = ss_level / count - np.square(mean_level)
26
+
27
+ std_level = np.sqrt(var_level)
28
+ std_pixel = np.sqrt(var_pixel)
29
+
30
+ return mean_pixel, std_pixel, mean_level, std_level
31
+
32
+
33
+ if __name__ == '__main__':
34
+ d1 = np.random.rand(2, 3, 2, 2)
35
+ d2 = np.random.rand(3, 3, 2, 2)
36
+ d = np.concatenate([d1, d2])
37
+ s1 = d1.sum((0,))
38
+ ss1 = np.array([i ** 2 for i in d1]).sum((0,))
39
+
40
+ s2 = d2.sum((0,))
41
+ ss2 = np.array([i ** 2 for i in d2]).sum((0,))
42
+
43
+ mean_pixel1, std_pixel1, mean_level1, std_level1 = cal_mean_std_one_loop(s1, ss1, 2)
44
+ mean_pixel2, std_pixel2, mean_level2, std_level2 = cal_mean_std_one_loop(s2, ss2, 3)
45
+ # print('*' * 40)
46
+ # print(mean_pixel1, end='\n\n')
47
+ # print(std_pixel1, end='\n\n')
48
+ # print(mean_level1, end='\n\n')
49
+ print(std_level1)
50
+ # print('*' * 40)
51
+ # print(mean_pixel2, end='\n\n')
52
+ # print(std_pixel2, end='\n\n')
53
+ # print(mean_level2, end='\n\n')
54
+ print(std_level2)
55
+
56
+ mean_pixel, std_pixel = mean_std_part2all([2, 3], [mean_pixel1, mean_pixel2], [std_pixel1, std_pixel2])
57
+ mean_level, std_level = mean_std_part2all([2, 3], [mean_level1, mean_level2], [std_level1, std_level2])
58
+ # print('*' * 40)
59
+ # print(mean_pixel, end='\n\n')
60
+ # print(std_pixel, end='\n\n')
61
+ # print(mean_level, end='\n\n')
62
+ print(std_level)
63
+ print('*' * 40)
64
+ print(d1.std((0, -2, -1)))
65
+ print(d2.std((0, -2, -1)))
66
+ print(d.std((0, -2, -1)))
@@ -0,0 +1,129 @@
1
+ import concurrent.futures
2
+ import threading
3
+ import multiprocessing
4
+ import time
5
+ from tqdm import tqdm
6
+
7
+ type_thread = 'type_thread'
8
+ type_process = 'type_process'
9
+
10
+
11
+ class ThreadingLock:
12
+ def __init__(self):
13
+ self.lock = threading.Lock()
14
+ self.owner = None
15
+
16
+ def acquire(self, blocking=True):
17
+ acquired = self.lock.acquire(blocking)
18
+ if acquired:
19
+ self.owner = threading.current_thread().name
20
+ return acquired
21
+
22
+ def release(self):
23
+ self.lock.release()
24
+ self.owner = None
25
+
26
+ def get_owner(self):
27
+ return self.owner
28
+
29
+
30
+ def init_process(pl):
31
+ """进程池初始化函数,只设置进程锁"""
32
+ global p_lock
33
+ p_lock = pl
34
+
35
+
36
+ def init_thread(tl):
37
+ """线程池初始化函数,只设置线程锁"""
38
+ global t_lock
39
+ t_lock = tl
40
+
41
+
42
+ class MultiTasks:
43
+ def __init__(self, threads=10, pool=type_thread, desc="Mult. Pro."):
44
+ self.threads = threads
45
+ self.task_list = {}
46
+ self.features = {}
47
+ self.results = {}
48
+ self.submitted = []
49
+ self.pool_type = pool
50
+
51
+ if pool == type_thread:
52
+ # 线程池不需要在初始化时传递锁
53
+ self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=self.threads)
54
+ elif pool == type_process:
55
+ # 进程池需要特殊处理锁
56
+ self.process_mutex = multiprocessing.Manager().Lock()
57
+ self.executor = concurrent.futures.ProcessPoolExecutor(
58
+ max_workers=self.threads,
59
+ initializer=init_process,
60
+ initargs=(self.process_mutex,)
61
+ )
62
+ self.desc = desc
63
+ self.progress_bar = None
64
+
65
+ def add_task(self, k, function, args):
66
+ self.task_list[k] = (function, args)
67
+
68
+ def execute_task_nowait(self, save=False, print_log=False):
69
+ if print_log:
70
+ print('Now running tasks:', rf'{len(self.submitted)}/{len(self.task_list)}')
71
+ for k, f_and_a in self.task_list.items():
72
+ if k not in self.submitted:
73
+ r = self.executor.submit(f_and_a[0], *f_and_a[1])
74
+ if save:
75
+ self.features[k] = r
76
+ self.submitted.append(k)
77
+
78
+ def wrap_fun(self, fun, args):
79
+ """包装函数,处理进度条更新"""
80
+ result = fun(*args)
81
+ if self.progress_bar:
82
+ # 使用适当的方式更新进度条
83
+ if self.pool_type == type_thread:
84
+ # 线程环境下直接更新
85
+ self.progress_bar.update(1)
86
+ else:
87
+ # 进程环境下需要特殊处理,这里简化处理
88
+ raise Exception('进程环境下需要特殊处理,这里简化处理.')
89
+ return result
90
+
91
+ def execute_task(self, print_percent=True, desc=None):
92
+ if print_percent:
93
+ self.progress_bar = tqdm(total=len(self.task_list), desc=desc if desc else self.desc)
94
+
95
+ # 根据池类型选择不同的执行策略
96
+ if self.pool_type == type_thread:
97
+ # 线程池直接执行
98
+ for k, f_and_a in self.task_list.items():
99
+ self.features[k] = self.executor.submit(self.wrap_fun, f_and_a[0], f_and_a[1])
100
+ else:
101
+ # 进程池需要避免传递不可序列化对象
102
+ for k, f_and_a in self.task_list.items():
103
+ # 直接提交函数,不包装进度条更新
104
+ self.features[k] = self.executor.submit(f_and_a[0], *f_and_a[1])
105
+
106
+ # 收集结果并更新进度条
107
+ for i, (k, feature) in enumerate(self.features.items()):
108
+ self.results[k] = feature.result()
109
+ if self.progress_bar and self.pool_type == type_process:
110
+ # 进程环境下在主线程更新进度条
111
+ self.progress_bar.update(1)
112
+
113
+ if self.progress_bar:
114
+ self.progress_bar.close()
115
+
116
+ return self.results
117
+
118
+
119
+ def worker(i):
120
+ # print(i)
121
+ time.sleep(0.1)
122
+ return i * 2
123
+
124
+
125
+ if __name__ == '__main__':
126
+ mt = MultiTasks(10, pool=type_thread)
127
+ for i in range(100):
128
+ mt.add_task(i, worker, [i])
129
+ mt.execute_task()
@@ -0,0 +1,6 @@
1
+ def round2str(number, digits=2):
2
+ number = round(number, digits)
3
+ if digits == 0:
4
+ return str(int(number))
5
+ else:
6
+ return f"{number:.{digits}f}"
@@ -0,0 +1,140 @@
1
+ import sys
2
+ import os
3
+ import re
4
+ import subprocess
5
+ import select
6
+ import argparse
7
+ from termcolor import colored
8
+
9
+ MEMORY_FREE_RATIO = 0.05
10
+ MEMORY_MODERATE_RATIO = 0.9
11
+ GPU_FREE_RATIO = 0.05
12
+ GPU_MODERATE_RATIO = 0.75
13
+
14
+
15
+ def colorize(_lines):
16
+ for i in range(len(_lines)):
17
+ line = _lines[i]
18
+ m = re.match(r"\| (?:N/A|..%)\s+[0-9]{2,3}C.*\s([0-9]+)MiB\s+\/\s+([0-9]+)MiB.*\s([0-9]+)%", line)
19
+ if m is not None:
20
+ used_mem = int(m.group(1))
21
+ total_mem = int(m.group(2))
22
+ gpu_util = int(m.group(3)) / 100.0
23
+ mem_util = used_mem / float(total_mem)
24
+
25
+ is_low = is_moderate = is_high = False
26
+ is_high = gpu_util >= GPU_MODERATE_RATIO or mem_util >= MEMORY_MODERATE_RATIO
27
+ if not is_high:
28
+ is_moderate = gpu_util >= GPU_FREE_RATIO or mem_util >= MEMORY_FREE_RATIO
29
+
30
+ if not is_high and not is_moderate:
31
+ is_free = True
32
+
33
+ c = 'red' if is_high else ('yellow' if is_moderate else 'green')
34
+ _lines[i] = colored(_lines[i], c)
35
+ _lines[i - 1] = colored(_lines[i - 1], c)
36
+
37
+ return _lines
38
+
39
+
40
+ def main():
41
+ parser = argparse.ArgumentParser(
42
+ prog='nvidia-watch', # 程序名
43
+ description='watch gpu', # 描述
44
+ epilog='Copyright(r), 2023' # 说明信息
45
+ )
46
+ parser.add_argument('-l', '--command-length', default=20, const=100, type=int, nargs='?')
47
+ parser.add_argument('-c', '--color', action='store_true')
48
+ args = parser.parse_args()
49
+
50
+ # parse the command length argument
51
+ command_length = args.command_length
52
+ color = args.color
53
+ processes = subprocess.run('nvidia-smi', stdout=subprocess.PIPE)
54
+ lines = processes.stdout.decode().split("\n")[:-1]
55
+ lines_to_print = []
56
+ # Copy the utilization upper part verbatim
57
+ pid_idx = 0
58
+ for i in range(len(lines)):
59
+ if not lines[i].startswith("| Processes:"):
60
+ # if lines[i].count('MIG M.') > 0 or lines[i].count('N/A') > 0:
61
+ # continue
62
+ lines_to_print.append(lines[i].rstrip())
63
+ else:
64
+ pid_idx = i + 3
65
+ break
66
+
67
+ if color:
68
+ lines_to_print = colorize(lines_to_print)
69
+
70
+ for line in lines_to_print:
71
+ print(line)
72
+
73
+ # Parse the PIDs from the lower part
74
+ gpu_num = []
75
+ pid = []
76
+ gpu_mem = []
77
+ user = []
78
+ cpu = []
79
+ mem = []
80
+ time = []
81
+ command = []
82
+ for i in range(pid_idx, len(lines)):
83
+ if lines[i].startswith("+--") or lines[i].startswith('|==') or "Not Supported" in lines[i]:
84
+ continue
85
+ no_running_process = "No running processes found"
86
+ if no_running_process in lines[i]:
87
+ print("| " + no_running_process + " " * (83 - len(no_running_process)) + " |")
88
+ print(lines[-1])
89
+ sys.exit()
90
+ line = lines[i]
91
+ line = re.split(r'\s+', line)
92
+ gpu_num.append(line[1])
93
+ pid.append(line[4])
94
+ gpu_mem.append(line[7])
95
+ user.append("")
96
+ cpu.append("")
97
+ mem.append("")
98
+ time.append("")
99
+ command.append("")
100
+
101
+ # Query the PIDs using ps
102
+ ps_format = "pid,user,%cpu,%mem,etime,command"
103
+ processes = subprocess.run(["ps", "-o", ps_format, "-p", ",".join(pid)], stdout=subprocess.PIPE)
104
+
105
+ # Parse ps output
106
+ for line in processes.stdout.decode().split("\n"):
107
+ if line.strip().startswith('PID') or len(line) == 0:
108
+ continue
109
+ parts = re.split(r'\s+', line.strip(), 5)
110
+ idx = pid.index(parts[0])
111
+ user[idx] = parts[1]
112
+ cpu[idx] = parts[2]
113
+ mem[idx] = parts[3]
114
+ time[idx] = parts[4] if not "-" in parts[4] else parts[4].split("-")[0] + " days"
115
+ command[idx] = parts[5][0:100]
116
+
117
+ format = ("| %5s %10s %8s %10s %8s %8s %8s %-" + str(command_length) + "." + str(command_length) + "s |")
118
+
119
+ print(format % (
120
+ "GPU", "PID", "USER", "GPU MEM", "%CPU", "%MEM", "TIME", "COMMAND"
121
+ ))
122
+
123
+ for i in range(len(pid)):
124
+ # continue
125
+ print(format % (
126
+ gpu_num[i],
127
+ pid[i],
128
+ user[i],
129
+ gpu_mem[i],
130
+ cpu[i],
131
+ mem[i],
132
+ time[i],
133
+ command[i]
134
+ ))
135
+
136
+ print(lines[-1])
137
+
138
+
139
+ if __name__ == '__main__':
140
+ main()
jacksung/utils/time.py ADDED
@@ -0,0 +1,87 @@
1
+ import time
2
+ from datetime import datetime
3
+ import pytz
4
+ from jacksung.utils.log import oprint
5
+ import calendar
6
+
7
+
8
+ def get_days_in_month(year, month):
9
+ return calendar.monthrange(year, month)[1]
10
+
11
+
12
+ def cal_time(fun_str):
13
+ # 记录第一个时间戳
14
+ start_time = time.time()
15
+ eval(fun_str)
16
+ # 记录第二个时间戳
17
+ end_time = time.time()
18
+ # 计算耗时
19
+ elapsed_time = end_time - start_time
20
+ print("Elapsed Time:", elapsed_time, "seconds")
21
+
22
+ def get_time_str():
23
+ return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
24
+ def cur_timestamp_str():
25
+ now = datetime.now()
26
+ year = str(now.year)
27
+ month = str(now.month).zfill(2)
28
+ day = str(now.day).zfill(2)
29
+ hour = str(now.hour).zfill(2)
30
+ minute = str(now.minute).zfill(2)
31
+ second = str(now.second).zfill(2)
32
+ microsecond = str(now.microsecond // 10000).zfill(2)
33
+ content = "{}-{}{}-{}{}-{}{}".format(year, month, day, hour, minute, second, microsecond)
34
+ return content
35
+
36
+
37
+ class RemainTime:
38
+ def __init__(self, epoch):
39
+ self.start_time = time.time()
40
+ self.epoch = epoch
41
+ self.now_epoch = 0
42
+
43
+ def update(self, log_temp='Spe {:.0f}s, Rem Epoch:{}, Fin in {}', print_log=True, update_step=1):
44
+ self.now_epoch += update_step
45
+ epoch_time = time.time() - self.start_time
46
+ epoch_remaining = self.epoch - self.now_epoch
47
+ time_remaining = epoch_time * epoch_remaining
48
+ pytz.timezone('Asia/Shanghai') # 东八区
49
+ t = datetime.fromtimestamp(int(time.time()) + time_remaining,
50
+ pytz.timezone('Asia/Shanghai')).strftime('%Y-%m-%d %H:%M:%S')
51
+ log = log_temp.format(epoch_time, epoch_remaining, t)
52
+ if print_log:
53
+ oprint(log)
54
+ self.start_time = time.time()
55
+ return epoch_remaining, t
56
+
57
+
58
+ class Stopwatch:
59
+ def __init__(self):
60
+ self.start_time = time.time()
61
+
62
+ def reset(self, format_type='{:>5.1f}s'):
63
+ timer_end = time.time()
64
+ duration = timer_end - self.start_time
65
+ self.start_time = timer_end
66
+ return format_type.format(duration)
67
+
68
+ def pinch(self, format_type='{:>5.1f}s'):
69
+ return format_type.format(time.time() - self.start_time)
70
+
71
+
72
+ def getHumanSize(in_size):
73
+ unit = 'B'
74
+ if in_size >= 1024:
75
+ in_size /= 1024
76
+ unit = 'K'
77
+ if in_size >= 1024:
78
+ in_size /= 1024
79
+ unit = 'M'
80
+ if in_size >= 1024:
81
+ in_size /= 1024
82
+ unit = 'G'
83
+ return f'{round(in_size, 2)} {unit}'
84
+
85
+
86
+ if __name__ == '__main__':
87
+ print(getHumanSize(1023))
jacksung/utils/web.py ADDED
@@ -0,0 +1,63 @@
1
+ import os
2
+ import platform
3
+ # 从selenium导入webdriver
4
+ from selenium import webdriver
5
+ from selenium.common.exceptions import NoSuchElementException
6
+ from selenium.webdriver.chrome.service import Service
7
+ from jacksung.utils.log import oprint as print
8
+ from selenium.webdriver.common.by import By
9
+
10
+
11
+ def make_driver(url=None, is_headless=False, tmp_path=None, download_dir=None, options=webdriver.ChromeOptions()):
12
+ options.add_argument("--disable-blink-features=AutomationControlled")
13
+ if tmp_path:
14
+ options.add_argument("crash-dumps-dir=" + tmp_path)
15
+ options.add_argument("--no-sandbox")
16
+ # options.add_argument("--auto-open-devtools-for-tabs")
17
+ options.add_argument('--disable-dev-shm-usage')
18
+ options.add_argument("--disable-web-security") # 禁用Web安全
19
+ options.add_argument("--allow-running-insecure-content") # 允许不安全的内容
20
+ options.add_argument('--user-agent=Mozilla/5.0')
21
+ options.add_argument('--ignore-ssl-errors=yes')
22
+ options.add_argument('--allow-insecure-localhost')
23
+ options.add_argument('--ignore-certificate-errors')
24
+ options.add_argument(
25
+ '--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36') # 设置User-Agent
26
+ options.add_argument("--lang=zh-CN") # 将语言设置为简体中文,英文为en-US
27
+ options.add_experimental_option("detach", True)
28
+ if download_dir:
29
+ options.add_experimental_option("prefs", {
30
+ "download.default_directory": download_dir,
31
+ "download.prompt_for_download": False,
32
+ "safebrowsing.enabled": True, # 允许“不安全”文件自动下载
33
+ "safebrowsing.disable_download_protection": True, # 禁用“可能有害文件”的拦截
34
+ "intl.accept_languages": "zh-CN,zh"
35
+ # "download.directory_upgrade": True,
36
+ })
37
+ options.set_capability('pageLoadStrategy', 'none')
38
+ options.set_capability("unhandledPromptBehavior", "accept")
39
+ if is_headless:
40
+ options.add_argument('--headless') # 浏览器隐式启动
41
+ # driver_path = os.path.expanduser("~/chrome/chromedriver.exe")
42
+ print('driver is going to init!')
43
+ if platform.system().lower() == 'windows':
44
+ driver_path = None
45
+ # driver_path = os.path.expanduser("~/chrome/chromedriver.exe")
46
+ else:
47
+ driver_path = os.path.expanduser("~/chrome/chromedriver")
48
+ # driver = uc.Chrome(service=Service(driver_path) if driver_path else None, options=options)
49
+ driver = webdriver.Chrome(service=Service(driver_path) if driver_path else None, options=options)
50
+ # driver.maximize_window()
51
+ driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
52
+ "source": """
53
+ Object.defineProperty(navigator, 'webdriver', {
54
+ get: () => undefined
55
+ })
56
+ """
57
+ })
58
+ driver.implicitly_wait(10)
59
+ driver.set_page_load_timeout(10)
60
+ if url is not None:
61
+ print(f'请求地址:{url}')
62
+ driver.get(url)
63
+ return driver