shancx 1.8.92__py3-none-any.whl → 1.9.33.218__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.
- shancx/3D/__init__.py +25 -0
- shancx/Algo/Class.py +11 -0
- shancx/Algo/CudaPrefetcher1.py +112 -0
- shancx/Algo/Fake_image.py +24 -0
- shancx/Algo/Hsml.py +391 -0
- shancx/Algo/L2Loss.py +10 -0
- shancx/Algo/MetricTracker.py +132 -0
- shancx/Algo/Normalize.py +66 -0
- shancx/Algo/OptimizerWScheduler.py +38 -0
- shancx/Algo/Rmageresize.py +79 -0
- shancx/Algo/Savemodel.py +33 -0
- shancx/Algo/SmoothL1_losses.py +27 -0
- shancx/Algo/Tqdm.py +62 -0
- shancx/Algo/__init__.py +121 -0
- shancx/Algo/checknan.py +28 -0
- shancx/Algo/iouJU.py +83 -0
- shancx/Algo/mask.py +25 -0
- shancx/Algo/psnr.py +9 -0
- shancx/Algo/ssim.py +70 -0
- shancx/Algo/structural_similarity.py +308 -0
- shancx/Algo/tool.py +704 -0
- shancx/Calmetrics/__init__.py +97 -0
- shancx/Calmetrics/calmetrics.py +14 -0
- shancx/Calmetrics/calmetricsmatrixLib.py +147 -0
- shancx/Calmetrics/rmseR2score.py +35 -0
- shancx/Clip/__init__.py +50 -0
- shancx/Cmd.py +126 -0
- shancx/Config_.py +26 -0
- shancx/Df/DataFrame.py +11 -2
- shancx/Df/__init__.py +17 -0
- shancx/Df/tool.py +0 -0
- shancx/Diffm/Psamples.py +18 -0
- shancx/Diffm/__init__.py +0 -0
- shancx/Diffm/test.py +207 -0
- shancx/Doc/__init__.py +214 -0
- shancx/E/__init__.py +178 -152
- shancx/Fillmiss/__init__.py +0 -0
- shancx/Fillmiss/imgidwJU.py +46 -0
- shancx/Fillmiss/imgidwLatLonJU.py +82 -0
- shancx/Gpu/__init__.py +55 -0
- shancx/H9/__init__.py +126 -0
- shancx/H9/ahi_read_hsd.py +877 -0
- shancx/H9/ahisearchtable.py +298 -0
- shancx/H9/geometry.py +2439 -0
- shancx/Hug/__init__.py +81 -0
- shancx/Inst.py +22 -0
- shancx/Lib.py +31 -0
- shancx/Mos/__init__.py +37 -0
- shancx/NN/__init__.py +235 -106
- shancx/Path1.py +161 -0
- shancx/Plot/GlobMap.py +276 -116
- shancx/Plot/__init__.py +491 -1
- shancx/Plot/draw_day_CR_PNG.py +4 -21
- shancx/Plot/exam.py +116 -0
- shancx/Plot/plotGlobal.py +325 -0
- shancx/{radar_nmc.py → Plot/radarNmc.py} +4 -34
- shancx/{subplots_single_china_map.py → Plot/single_china_map.py} +1 -1
- shancx/Point.py +46 -0
- shancx/QC.py +223 -0
- shancx/RdPzl/__init__.py +32 -0
- shancx/Read.py +72 -0
- shancx/Resize.py +79 -0
- shancx/SN/__init__.py +62 -123
- shancx/Time/GetTime.py +9 -3
- shancx/Time/__init__.py +66 -1
- shancx/Time/timeCycle.py +302 -0
- shancx/Time/tool.py +0 -0
- shancx/Train/__init__.py +74 -0
- shancx/Train/makelist.py +187 -0
- shancx/Train/multiGpu.py +27 -0
- shancx/Train/prepare.py +161 -0
- shancx/Train/renet50.py +157 -0
- shancx/ZR.py +12 -0
- shancx/__init__.py +333 -262
- shancx/args.py +27 -0
- shancx/bak.py +768 -0
- shancx/df2database.py +62 -2
- shancx/geosProj.py +80 -0
- shancx/info.py +38 -0
- shancx/netdfJU.py +231 -0
- shancx/sendM.py +59 -0
- shancx/tensBoard/__init__.py +28 -0
- shancx/wait.py +246 -0
- {shancx-1.8.92.dist-info → shancx-1.9.33.218.dist-info}/METADATA +15 -5
- shancx-1.9.33.218.dist-info/RECORD +91 -0
- {shancx-1.8.92.dist-info → shancx-1.9.33.218.dist-info}/WHEEL +1 -1
- my_timer_decorator/__init__.py +0 -10
- shancx/Dsalgor/__init__.py +0 -19
- shancx/E/DFGRRIB.py +0 -30
- shancx/EN/DFGRRIB.py +0 -30
- shancx/EN/__init__.py +0 -148
- shancx/FileRead.py +0 -44
- shancx/Gray2RGB.py +0 -86
- shancx/M/__init__.py +0 -137
- shancx/MN/__init__.py +0 -133
- shancx/N/__init__.py +0 -131
- shancx/Plot/draw_day_CR_PNGUS.py +0 -206
- shancx/Plot/draw_day_CR_SVG.py +0 -275
- shancx/Plot/draw_day_pre_PNGUS.py +0 -205
- shancx/Plot/glob_nation_map.py +0 -116
- shancx/Plot/radar_nmc.py +0 -61
- shancx/Plot/radar_nmc_china_map_compare1.py +0 -50
- shancx/Plot/radar_nmc_china_map_f.py +0 -121
- shancx/Plot/radar_nmc_us_map_f.py +0 -128
- shancx/Plot/subplots_compare_devlop.py +0 -36
- shancx/Plot/subplots_single_china_map.py +0 -45
- shancx/S/__init__.py +0 -138
- shancx/W/__init__.py +0 -132
- shancx/WN/__init__.py +0 -132
- shancx/code.py +0 -331
- shancx/draw_day_CR_PNG.py +0 -200
- shancx/draw_day_CR_PNGUS.py +0 -206
- shancx/draw_day_CR_SVG.py +0 -275
- shancx/draw_day_pre_PNGUS.py +0 -205
- shancx/makenetCDFN.py +0 -42
- shancx/mkIMGSCX.py +0 -92
- shancx/netCDF.py +0 -130
- shancx/radar_nmc_china_map_compare1.py +0 -50
- shancx/radar_nmc_china_map_f.py +0 -125
- shancx/radar_nmc_us_map_f.py +0 -67
- shancx/subplots_compare_devlop.py +0 -36
- shancx/tool.py +0 -18
- shancx/user/H8mess.py +0 -317
- shancx/user/__init__.py +0 -137
- shancx/user/cinradHJN.py +0 -496
- shancx/user/examMeso.py +0 -293
- shancx/user/hjnDAAS.py +0 -26
- shancx/user/hjnFTP.py +0 -81
- shancx/user/hjnGIS.py +0 -320
- shancx/user/hjnGPU.py +0 -21
- shancx/user/hjnIDW.py +0 -68
- shancx/user/hjnKDTree.py +0 -75
- shancx/user/hjnLAPSTransform.py +0 -47
- shancx/user/hjnMiscellaneous.py +0 -182
- shancx/user/hjnProj.py +0 -162
- shancx/user/inotify.py +0 -41
- shancx/user/matplotlibMess.py +0 -87
- shancx/user/mkNCHJN.py +0 -623
- shancx/user/newTypeRadar.py +0 -492
- shancx/user/test.py +0 -6
- shancx/user/tlogP.py +0 -129
- shancx/util_log.py +0 -33
- shancx/wtx/H8mess.py +0 -315
- shancx/wtx/__init__.py +0 -151
- shancx/wtx/cinradHJN.py +0 -496
- shancx/wtx/colormap.py +0 -64
- shancx/wtx/examMeso.py +0 -298
- shancx/wtx/hjnDAAS.py +0 -26
- shancx/wtx/hjnFTP.py +0 -81
- shancx/wtx/hjnGIS.py +0 -330
- shancx/wtx/hjnGPU.py +0 -21
- shancx/wtx/hjnIDW.py +0 -68
- shancx/wtx/hjnKDTree.py +0 -75
- shancx/wtx/hjnLAPSTransform.py +0 -47
- shancx/wtx/hjnLog.py +0 -78
- shancx/wtx/hjnMiscellaneous.py +0 -201
- shancx/wtx/hjnProj.py +0 -161
- shancx/wtx/inotify.py +0 -41
- shancx/wtx/matplotlibMess.py +0 -87
- shancx/wtx/mkNCHJN.py +0 -613
- shancx/wtx/newTypeRadar.py +0 -492
- shancx/wtx/test.py +0 -6
- shancx/wtx/tlogP.py +0 -129
- shancx-1.8.92.dist-info/RECORD +0 -99
- /shancx/{Dsalgor → Algo}/dsalgor.py +0 -0
- {shancx-1.8.92.dist-info → shancx-1.9.33.218.dist-info}/top_level.txt +0 -0
shancx/Hug/__init__.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
#!/usr/bin/python
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
# gdown --folder https://drive.google.com/drive/folders/1D3bf2G2o4Hv-Ale26YW18r1Wrh7oIAwK 文件夹下所有内容太
|
|
4
|
+
from modelscope.hub.snapshot_download import snapshot_download
|
|
5
|
+
model_dir = snapshot_download('', cache_dir='autodl-tmp', revision='master', ignore_file_pattern='.bn')
|
|
6
|
+
from datasets import load_dataset
|
|
7
|
+
dataset = load_dataset("ayz2/ldm_pdes", download_mode="force_redownload")
|
|
8
|
+
print(dataset)
|
|
9
|
+
# dataset.save_to_disk('/path/to/save/dataset')
|
|
10
|
+
for split_name, split_dataset in dataset.items():
|
|
11
|
+
chunk_size = 5000 # 每片的样本数量,可根据内存大小调整
|
|
12
|
+
for i in range(0, len(split_dataset), chunk_size):
|
|
13
|
+
subset = split_dataset.select(range(i, min(i + chunk_size, len(split_dataset))))
|
|
14
|
+
subset.save_to_disk(f"./{split_name}_chunk_{i // chunk_size}")
|
|
15
|
+
|
|
16
|
+
from huggingface_hub import hf_hub_download
|
|
17
|
+
from shancx import crDir
|
|
18
|
+
# 下载权重文件
|
|
19
|
+
repo_id = "ayz2/ldm_pdes"
|
|
20
|
+
filename = "ae_cylinder.ckpt"
|
|
21
|
+
crDir("/mnt/wtx_weather_forecast/scx/ldm_pdes_checkpoint")
|
|
22
|
+
save_dir = "/mnt/wtx_weather_forecast/scx/ldm_pdes_checkpoint"
|
|
23
|
+
save_path = hf_hub_download(repo_id=repo_id, filename=filename, cache_dir=save_dir)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
print(f"权重文件已下载到: {save_path}")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
from modelscope.hub.snapshot_download import snapshot_download
|
|
30
|
+
crDir("/mnt/wtx_weather_forecast/scx/ldm_pdes_checkpoint")
|
|
31
|
+
save_dir = "/mnt/wtx_weather_forecast/scx/ldm_pdes_checkpoint"
|
|
32
|
+
model_dir = snapshot_download('ayz2/ldm_pdes', cache_dir=save_dir, revision='master', ignore_file_pattern='.bn') 下载 ae_cylinder.ckpt"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
from modelscope.hub.snapshot_download import snapshot_download
|
|
36
|
+
from shancx import crDir
|
|
37
|
+
save_dir = "/mnt/wtx_weather_forecast/scx/ldm_pdes_checkpoint"
|
|
38
|
+
crDir(save_dir)
|
|
39
|
+
model_dir = snapshot_download(
|
|
40
|
+
'ayz2/ldm_pdes',
|
|
41
|
+
cache_dir=save_dir,
|
|
42
|
+
revision='master',
|
|
43
|
+
ignore_file_pattern='.bn')
|
|
44
|
+
print(f"模型已下载到: {model_dir}")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
from google.colab import drive
|
|
51
|
+
import requests
|
|
52
|
+
import os
|
|
53
|
+
|
|
54
|
+
# 挂载 Google Drive
|
|
55
|
+
drive.mount('/content/drive')
|
|
56
|
+
ptname = "ae_cylinder.ckpt"
|
|
57
|
+
# 文件下载的URL
|
|
58
|
+
file_url = f"https://huggingface.co/datasets/ayz2/ldm_pdes/resolve/main/{ptname}"
|
|
59
|
+
|
|
60
|
+
# Google Drive中的保存路径(修改为你想保存的位置)
|
|
61
|
+
output_path = "/content/drive/My Drive/{ptname}"
|
|
62
|
+
|
|
63
|
+
# 下载文件并保存到指定路径
|
|
64
|
+
def download_file(url, output_path):
|
|
65
|
+
try:
|
|
66
|
+
with requests.get(url, stream=True) as response:
|
|
67
|
+
response.raise_for_status()
|
|
68
|
+
with open(output_path, "wb") as file:
|
|
69
|
+
for chunk in response.iter_content(chunk_size=8192):
|
|
70
|
+
if chunk: # 防止空块
|
|
71
|
+
file.write(chunk)
|
|
72
|
+
print(f"文件已成功下载并保存到 Google Drive: {output_path}")
|
|
73
|
+
except Exception as e:
|
|
74
|
+
print(f"下载文件时出错: {e}")
|
|
75
|
+
download_file(file_url, output_path)
|
|
76
|
+
|
|
77
|
+
import zipfile
|
|
78
|
+
def unzip_file(zip_path, extract_to):
|
|
79
|
+
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
|
|
80
|
+
zip_ref.extractall(extract_to)
|
|
81
|
+
unzip_file(output_path, os.getcwd())
|
shancx/Inst.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
import os
|
|
3
|
+
def current_dir_sys_path():
|
|
4
|
+
sys.path.append(os.getcwd()) #current_dir_sys_path()
|
|
5
|
+
|
|
6
|
+
import importlib
|
|
7
|
+
def instantiate_config(config):
|
|
8
|
+
if not "target" in config:
|
|
9
|
+
if config == '__is_first_stage__':
|
|
10
|
+
return None
|
|
11
|
+
elif config == "__is_unconditional__":
|
|
12
|
+
return None
|
|
13
|
+
raise KeyError("Expected key `target` to instantiate.")
|
|
14
|
+
return get_obj_from_str(config["target"])(**config.get("params", dict()))
|
|
15
|
+
def get_obj_from_str(string, reload=False):
|
|
16
|
+
module, cls = string.rsplit(".", 1)
|
|
17
|
+
if reload:
|
|
18
|
+
module_imp = importlib.import_module(module)
|
|
19
|
+
importlib.reload(module_imp)
|
|
20
|
+
return getattr(importlib.import_module(module, package=None), cls)
|
|
21
|
+
|
|
22
|
+
|
shancx/Lib.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import cv2
|
|
2
|
+
import copy
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
def QC(mat, dbzTH=10, areaTH=20): # 主QC函数
|
|
6
|
+
mat1 = copy.copy(mat)
|
|
7
|
+
varMask = np.where(mat1 > dbzTH, 1, 0)
|
|
8
|
+
varMask = varMask.astype(np.uint8)
|
|
9
|
+
|
|
10
|
+
ret, img_thre = cv2.threshold(varMask, 0, 255, cv2.THRESH_BINARY)
|
|
11
|
+
num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(img_thre, connectivity=8)
|
|
12
|
+
mask = np.zeros(varMask.shape, dtype=np.uint8)
|
|
13
|
+
|
|
14
|
+
for j in range(1, num_labels):
|
|
15
|
+
if stats[j, cv2.CC_STAT_AREA] >= areaTH:
|
|
16
|
+
mask[labels == j] = 255
|
|
17
|
+
mat1[mask != 255] = 0
|
|
18
|
+
return mat1
|
|
19
|
+
|
|
20
|
+
def QC_batch(mat, dbzTH=10, areaTH=20, phase="QC"): # 批量QC函数
|
|
21
|
+
from shancx.NN import _loggers
|
|
22
|
+
logger = _loggers(phase=phase)
|
|
23
|
+
for i in range(len(mat)):
|
|
24
|
+
logger.info(f"QC {i}")
|
|
25
|
+
mat[i] = QC(mat[i], dbzTH, areaTH)
|
|
26
|
+
return mat
|
|
27
|
+
|
|
28
|
+
"""
|
|
29
|
+
pre = QC_simple(pre,areaTH=30) 二维灰度
|
|
30
|
+
pre = QC_ref(pre,areaTH=30) 三维灰度
|
|
31
|
+
"""
|
shancx/Mos/__init__.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
def start_points(size, split_size, overlap=0.0):
|
|
6
|
+
stride = int(split_size * (1 - overlap)) # 计算步长
|
|
7
|
+
points = [i * stride for i in range((size - split_size) // stride + 1)]
|
|
8
|
+
if size > points[-1] + split_size:
|
|
9
|
+
points.append(size - split_size)
|
|
10
|
+
return points
|
|
11
|
+
|
|
12
|
+
def weigthOverlap(overlap,radarpre,x,y,b,weight_sum):
|
|
13
|
+
weight = np.ones((256, 256))
|
|
14
|
+
for i in range(overlap):
|
|
15
|
+
weight[:, i] = 0.5 * (1 - np.cos(np.pi * i / overlap))
|
|
16
|
+
weight[:, -i-1] = 0.5 * (1 - np.cos(np.pi * i / overlap))
|
|
17
|
+
weight[i, :] = np.minimum(weight[i, :], 0.5 * (1 - np.cos(np.pi * i / overlap)))
|
|
18
|
+
weight[-i-1, :] = np.minimum(weight[-i-1, :], 0.5 * (1 - np.cos(np.pi * i / overlap)))
|
|
19
|
+
patch = radarpre * weight
|
|
20
|
+
b[x:x+256, y:y+256] = np.where(np.isnan(b[x:x+256, y:y+256]),
|
|
21
|
+
patch,
|
|
22
|
+
b[x:x+256, y:y+256] + patch)
|
|
23
|
+
weight_sum[x:x+256, y:y+256] = np.where(np.isnan(weight_sum[x:x+256, y:y+256]),
|
|
24
|
+
weight,
|
|
25
|
+
weight_sum[x:x+256, y:y+256] + weight)
|
|
26
|
+
return b,weight_sum
|
|
27
|
+
|
|
28
|
+
"""
|
|
29
|
+
weight_sum = np.zeros_like(b)
|
|
30
|
+
b,weight_sum = weigthOverlap(overlap,radarpre,x,y,b,weight_sum)
|
|
31
|
+
b = np.divide(b, weight_sum, where=weight_sum!=0)
|
|
32
|
+
|
|
33
|
+
weight_sum = np.zeros_like(b)
|
|
34
|
+
overlap = 32
|
|
35
|
+
x_point = start_points(sat_data[0].shape[0], 256, overlap/256)
|
|
36
|
+
y_point = start_points(sat_data[0].shape[1], 256, overlap/256)
|
|
37
|
+
"""
|
shancx/NN/__init__.py
CHANGED
|
@@ -4,124 +4,253 @@ import os
|
|
|
4
4
|
def start():
|
|
5
5
|
print("import successful")
|
|
6
6
|
# constants
|
|
7
|
-
__author__ = 'shancx'
|
|
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
|
-
import tracback
|
|
38
|
-
try:
|
|
7
|
+
__author__ = 'shancx'
|
|
8
|
+
__author_email__ = 'shanhe12@163.com'
|
|
9
|
+
__time__ = '20251028 21:16'
|
|
10
|
+
import logging
|
|
11
|
+
from logging.handlers import RotatingFileHandler
|
|
12
|
+
import os
|
|
13
|
+
from shancx import crDir
|
|
14
|
+
def _loggers(logger_name="loggers", root="./logs", phase="project", level=logging.INFO, screen=True, max_bytes=10*1024*1024, backup_count=5, overwrite=False,handlersflag=False):
|
|
15
|
+
'''set up logger with rotating file handler'''
|
|
16
|
+
l = logging.getLogger(logger_name)
|
|
17
|
+
if handlersflag:
|
|
18
|
+
if l.handlers:
|
|
19
|
+
return l
|
|
20
|
+
formatter = logging.Formatter(
|
|
21
|
+
"%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s", datefmt='%Y-%m-%d %H:%M:%S')
|
|
22
|
+
log_file = os.path.join(root, '{}.log'.format(phase))
|
|
23
|
+
crDir(log_file)
|
|
24
|
+
# Use RotatingFileHandler with 'w' mode to overwrite log file if needed
|
|
25
|
+
mode = 'w' if overwrite else 'a'
|
|
26
|
+
fh = RotatingFileHandler(log_file, mode=mode, maxBytes=max_bytes, backupCount=backup_count)
|
|
27
|
+
fh.setFormatter(formatter)
|
|
28
|
+
l.setLevel(level)
|
|
29
|
+
l.addHandler(fh)
|
|
30
|
+
if screen:
|
|
31
|
+
sh = logging.StreamHandler()
|
|
32
|
+
sh.setFormatter(formatter)
|
|
33
|
+
l.addHandler(sh)
|
|
34
|
+
return l
|
|
39
35
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
36
|
+
"""
|
|
37
|
+
logger = _loggers(logger_name="test_logger", root=curpathplus, phase="test_log", overwrite=True, screen=True)
|
|
38
|
+
# 测试日志输出
|
|
39
|
+
for i in range(5):
|
|
40
|
+
logger.info(f"这是日志消息 {i+1}")
|
|
41
|
+
time.sleep(1)
|
|
43
42
|
"""
|
|
44
43
|
|
|
45
44
|
|
|
46
|
-
|
|
47
|
-
from
|
|
48
|
-
from multiprocessing import Pool
|
|
49
|
-
import datetime
|
|
50
|
-
from config import logger,output
|
|
51
|
-
import time
|
|
52
|
-
import pandas as pd
|
|
45
|
+
import logging
|
|
46
|
+
from logging.handlers import RotatingFileHandler
|
|
53
47
|
import os
|
|
54
|
-
from
|
|
55
|
-
import
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
48
|
+
from shancx import crDir
|
|
49
|
+
import multiprocessing
|
|
50
|
+
def _loggersPlus(logger_name="loggers", root="./logs", phase="project", level=logging.INFO,
|
|
51
|
+
screen=True, max_bytes=10 * 1024 * 1024, backup_count=5, overwrite=False,
|
|
52
|
+
handlersflag=False, enable_rotating=None):
|
|
53
|
+
l = logging.getLogger(logger_name)
|
|
54
|
+
if handlersflag:
|
|
55
|
+
if l.handlers:
|
|
56
|
+
return l
|
|
57
|
+
formatter = logging.Formatter(
|
|
58
|
+
"%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s",
|
|
59
|
+
datefmt='%Y-%m-%d %H:%M:%S'
|
|
60
|
+
)
|
|
61
|
+
log_file = os.path.join(root, '{}.log'.format(phase))
|
|
62
|
+
crDir(log_file)
|
|
63
|
+
mode = 'w' if overwrite else 'a'
|
|
64
|
+
if enable_rotating is None:
|
|
65
|
+
enable_rotating = (multiprocessing.current_process().name == 'MainProcess')
|
|
66
|
+
|
|
67
|
+
if enable_rotating:
|
|
68
|
+
fh = RotatingFileHandler(
|
|
69
|
+
log_file,
|
|
70
|
+
mode=mode,
|
|
71
|
+
maxBytes=max_bytes,
|
|
72
|
+
backupCount=backup_count
|
|
73
|
+
)
|
|
74
|
+
else:
|
|
75
|
+
fh = logging.FileHandler(log_file, mode=mode)
|
|
76
|
+
|
|
77
|
+
fh.setFormatter(formatter)
|
|
78
|
+
l.setLevel(level)
|
|
79
|
+
l.addHandler(fh)
|
|
80
|
+
|
|
81
|
+
if screen:
|
|
82
|
+
sh = logging.StreamHandler()
|
|
83
|
+
sh.setFormatter(formatter)
|
|
84
|
+
l.addHandler(sh)
|
|
85
|
+
return l
|
|
60
86
|
|
|
61
|
-
def gpuPro(makeListUTC, isPhase, isDebug, gpu, isOverwrite):
|
|
62
|
-
productList = product(makeListUTC, [isPhase], [isDebug], [gpu], [isOverwrite])
|
|
63
87
|
|
|
64
|
-
|
|
65
|
-
|
|
88
|
+
import logging
|
|
89
|
+
def setlogger(level=logging.INFO):
|
|
90
|
+
|
|
91
|
+
logging.basicConfig(
|
|
92
|
+
level=level, # 动态接受级别参数
|
|
93
|
+
format="%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s",
|
|
94
|
+
handlers=[logging.StreamHandler()],
|
|
95
|
+
force=True # 强制覆盖现有配置(Python 3.8+)
|
|
96
|
+
)
|
|
97
|
+
return logging.getLogger()
|
|
98
|
+
'''
|
|
99
|
+
# 使用示例
|
|
100
|
+
if __name__ == "__main__":
|
|
101
|
+
logger = setlogger(level=logging.DEBUG) # 设置为DEBUG级别
|
|
102
|
+
logger.debug("这条日志会显示") # 默认情况下DEBUG不显示,但因为我们设置了级别,现在会显示
|
|
103
|
+
logger.info("这是一条INFO日志")
|
|
104
|
+
'''
|
|
105
|
+
import os
|
|
106
|
+
import glob
|
|
107
|
+
import logging
|
|
108
|
+
from datetime import datetime
|
|
109
|
+
from shancx import loggers as logger
|
|
110
|
+
def cleanupLogs(log_dir='/mnt/wtx_weather_forecast/scx/SATH9SEAStest/logs', keep_count=10,
|
|
111
|
+
pattern='*.log', recursive=False, dry_run=False):
|
|
112
|
+
stats = {'total_dirs': 0, 'deleted_files': 0, 'errors': []}
|
|
113
|
+
def _cleanup_dir(directory):
|
|
114
|
+
stats['total_dirs'] += 1
|
|
115
|
+
if not os.path.exists(directory):
|
|
116
|
+
logging.warning(f"目录不存在: {directory}")
|
|
117
|
+
return
|
|
118
|
+
file_paths = glob.glob(os.path.join(directory, pattern))
|
|
119
|
+
log_files = [(path, os.path.getmtime(path)) for path in file_paths]
|
|
120
|
+
log_files.sort(key=lambda x: x[1], reverse=True)
|
|
121
|
+
if len(log_files) <= keep_count:
|
|
122
|
+
logging.info(f"目录 {directory} 中的文件数量 ({len(log_files)}) 不超过保留数量 ({keep_count}),无需清理")
|
|
123
|
+
return
|
|
124
|
+
files_to_delete = log_files[keep_count:]
|
|
125
|
+
for file_path, mtime in files_to_delete:
|
|
126
|
+
try:
|
|
127
|
+
if dry_run:
|
|
128
|
+
logging.info(f"[试运行] 将删除: {file_path} (修改时间: {datetime.fromtimestamp(mtime).strftime('%Y-%m-%d %H:%M:%S')})")
|
|
129
|
+
else:
|
|
130
|
+
os.remove(file_path)
|
|
131
|
+
logging.info(f"已删除: {file_path} (修改时间: {datetime.fromtimestamp(mtime).strftime('%Y-%m-%d %H:%M:%S')})")
|
|
132
|
+
stats['deleted_files'] += 1
|
|
133
|
+
except Exception as e:
|
|
134
|
+
error_msg = f"删除失败 {file_path}: {str(e)}"
|
|
135
|
+
logging.error(error_msg)
|
|
136
|
+
stats['errors'].append(error_msg)
|
|
137
|
+
if recursive:
|
|
138
|
+
for root, _, _ in os.walk(log_dir):
|
|
139
|
+
_cleanup_dir(root)
|
|
140
|
+
else:
|
|
141
|
+
_cleanup_dir(log_dir)
|
|
142
|
+
return stats
|
|
143
|
+
"""
|
|
144
|
+
if __name__ == "__main__":
|
|
145
|
+
dir = "/mnt/wtx_weather_forecast/scx/SATH9SEAStest/logs/H9SEAS/"
|
|
146
|
+
stats = cleanupLogs(dir,3, '*.log', False, False)
|
|
147
|
+
logging.info(f"清理完成: 处理目录数={stats['total_dirs']}, 删除文件数={stats['deleted_files']}, 错误数={len(stats['errors'])}")
|
|
148
|
+
if stats['errors']:
|
|
149
|
+
logging.error(f"错误详情: {stats['errors']}")
|
|
150
|
+
"""
|
|
66
151
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
152
|
+
from itertools import product
|
|
153
|
+
from concurrent.futures import ProcessPoolExecutor as PoolExecutor, as_completed
|
|
154
|
+
import sys
|
|
155
|
+
from tqdm import tqdm
|
|
156
|
+
def validate_param_list(param_list):
|
|
157
|
+
if len(param_list) == 0:
|
|
158
|
+
raise ValueError("param_list cannot be empty.")
|
|
159
|
+
for sublist in param_list:
|
|
160
|
+
if len(sublist) == 0:
|
|
161
|
+
raise ValueError("Sub-lists in param_list cannot be empty.")
|
|
162
|
+
def Mul_sub(task, param_list, num=6):
|
|
163
|
+
print(f"Pro num {num}")
|
|
164
|
+
validate_param_list(param_list)
|
|
165
|
+
if len(param_list) == 1:
|
|
166
|
+
product_list = [(x,) for x in param_list[0]]
|
|
167
|
+
else:
|
|
168
|
+
product_list = list(product(*param_list))
|
|
169
|
+
with PoolExecutor(max_workers=num) as executor:
|
|
170
|
+
try:
|
|
171
|
+
futures = [executor.submit(task, item) for item in product_list]
|
|
172
|
+
for future in tqdm(as_completed(futures), total=len(futures), desc="Processing tasks", unit="task"):
|
|
173
|
+
future.result()
|
|
174
|
+
except KeyboardInterrupt:
|
|
175
|
+
sys.exit(1)
|
|
176
|
+
print("All tasks completed")
|
|
79
177
|
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
178
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
179
|
+
from itertools import product
|
|
180
|
+
def Mul_TH(task, param_list, max_workers=6):
|
|
181
|
+
print(f"Thread num: {max_workers}")
|
|
182
|
+
validate_param_list(param_list)
|
|
183
|
+
task_args = [
|
|
184
|
+
(arg,) if len(param_list) == 1 else arg
|
|
185
|
+
for arg in (
|
|
186
|
+
param_list[0] if len(param_list) == 1
|
|
187
|
+
else product(*param_list)
|
|
188
|
+
)
|
|
189
|
+
]
|
|
190
|
+
with ThreadPoolExecutor(max_workers) as ex:
|
|
191
|
+
try:
|
|
192
|
+
list(ex.map(task, task_args))
|
|
193
|
+
except KeyboardInterrupt:
|
|
194
|
+
print("\n用户中断操作")
|
|
195
|
+
ex.shutdown(wait=False)
|
|
196
|
+
sys.exit(1)
|
|
87
197
|
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
198
|
+
import traceback
|
|
199
|
+
import shutil, os
|
|
200
|
+
def safe_del(path):
|
|
201
|
+
try:
|
|
202
|
+
shutil.rmtree(path) if os.path.isdir(path) else None
|
|
203
|
+
print(f"{path} deleted")
|
|
204
|
+
except Exception:
|
|
205
|
+
print(traceback.format_exc())
|
|
94
206
|
|
|
95
|
-
|
|
96
|
-
|
|
207
|
+
"""
|
|
208
|
+
safe_del("./data")
|
|
97
209
|
"""
|
|
98
210
|
|
|
211
|
+
import os, glob
|
|
212
|
+
def clean_files(folder, keep=0):
|
|
213
|
+
if os.path.isdir(folder):
|
|
214
|
+
try:
|
|
215
|
+
files = [os.path.join(folder, f) for f in os.listdir(folder)
|
|
216
|
+
if os.path.isfile(os.path.join(folder, f))]
|
|
217
|
+
if keep > 0 and len(files) > keep:
|
|
218
|
+
files.sort(key=os.path.getmtime)
|
|
219
|
+
[os.remove(f) for f in files[:-keep]]
|
|
220
|
+
elif keep == 0:
|
|
221
|
+
[os.remove(f) for f in files]
|
|
222
|
+
except Exception as e:
|
|
223
|
+
print(traceback.format_exc())
|
|
99
224
|
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
import time
|
|
105
|
-
import logging
|
|
106
|
-
from logging import handlers
|
|
107
|
-
|
|
108
|
-
logger = logging.getLogger()
|
|
109
|
-
logger.setLevel(logging.INFO)
|
|
110
|
-
log_name = 'project_tim_tor.log'
|
|
111
|
-
logfile = log_name
|
|
112
|
-
time_rotating_file_handler = handlers.TimedRotatingFileHandler(filename=logfile, when='D', encoding='utf-8')
|
|
113
|
-
time_rotating_file_handler.setLevel(logging.INFO)
|
|
114
|
-
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
|
|
115
|
-
time_rotating_file_handler.setFormatter(formatter)
|
|
116
|
-
logger.addHandler(time_rotating_file_handler)
|
|
117
|
-
print_handler = logging.StreamHandler()
|
|
118
|
-
print_handler.setFormatter(formatter)
|
|
119
|
-
logger.addHandler(print_handler)
|
|
120
|
-
|
|
121
|
-
'''
|
|
122
|
-
|
|
123
|
-
'''
|
|
124
|
-
###解决方法 pip install torch==2.4.0 torchvision torchaudio三个同时安装 python 3.12 解决cuda启动不了的问题
|
|
225
|
+
"""
|
|
226
|
+
clean_files("./logs", keep=10)
|
|
227
|
+
clean_files("./temp")
|
|
228
|
+
"""
|
|
125
229
|
|
|
126
|
-
|
|
127
|
-
|
|
230
|
+
# import os
|
|
231
|
+
# from datetime import datetime
|
|
232
|
+
# from shancx.NN import _loggers
|
|
233
|
+
# from shancx import lock_file
|
|
234
|
+
# from shancx.wait import check_lock
|
|
235
|
+
# from shancx import crDir
|
|
236
|
+
# logger =_loggers()
|
|
237
|
+
# def check_process_data(UTC, sat_cd,basepath ="/mnt/wtx_weather_forecast/scx/test/lock_files" ):
|
|
238
|
+
# try:
|
|
239
|
+
# UTCStr = UTC.strftime("%Y%m%d%H%M")
|
|
240
|
+
# file = f"/mnt/wtx_weather_forecast/scx/test/lock_files/{sat_cd}/{UTCStr[:4]}/{UTCStr[:8]}/File_{UTCStr}.lock"
|
|
241
|
+
# crDir(file)
|
|
242
|
+
# if not lock_file(file):
|
|
243
|
+
# if check_lock(file):
|
|
244
|
+
# logger.info("data is making or maked")
|
|
245
|
+
# return True ,file
|
|
246
|
+
# return False,file
|
|
247
|
+
# except Exception as e:
|
|
248
|
+
# logger.error(f"Error in check_and_process_data: {str(e)}")
|
|
249
|
+
# return False,file
|
|
250
|
+
# """
|
|
251
|
+
# flag1,file = check_process_data(UTC, "H9SEAS" )
|
|
252
|
+
# if flag1:
|
|
253
|
+
# sys.exit()
|
|
254
|
+
# if os.path.exists(output_path): #配合使用
|
|
255
|
+
# sys.exit()
|
|
256
|
+
# """
|