219 lines
8.5 KiB
Python
219 lines
8.5 KiB
Python
# check_pkl_files_and_delete.py
|
|
import os
|
|
import pickle
|
|
import numpy as np
|
|
from tqdm import tqdm
|
|
|
|
|
|
def check_pkl_file_integrity(filepath):
|
|
"""
|
|
Checks a single .pkl file for format and data integrity.
|
|
|
|
Args:
|
|
filepath (str): Path to the .pkl file.
|
|
|
|
Returns:
|
|
tuple: (list of errors, list of warnings, boolean indicating if 'data' has Inf)
|
|
"""
|
|
errors = []
|
|
warnings = []
|
|
data_has_inf = False # Flag to indicate if 'data' contains Inf values
|
|
|
|
try:
|
|
with open(filepath, 'rb') as f:
|
|
data_dict = pickle.load(f)
|
|
except Exception as e:
|
|
errors.append(f"Failed to load pickle file: {e}")
|
|
# Return False for data_has_inf on load failure
|
|
return errors, warnings, data_has_inf
|
|
|
|
# 1. Check top-level keys
|
|
expected_keys = {"uid", "data", "sampling_rate", "label"}
|
|
actual_keys = set(data_dict.keys())
|
|
if not expected_keys.issubset(actual_keys):
|
|
missing = expected_keys - actual_keys
|
|
extra = actual_keys - expected_keys
|
|
if missing:
|
|
errors.append(f"Missing top-level keys: {missing}")
|
|
if extra:
|
|
warnings.append(f"Unexpected top-level keys: {extra}")
|
|
|
|
# 2. Check 'uid'
|
|
if "uid" in data_dict:
|
|
if not isinstance(data_dict["uid"], str):
|
|
errors.append(
|
|
f"'uid' is not a string (type: {type(data_dict['uid'])}). Value: {data_dict['uid']}")
|
|
# No 'else' needed here as missing key is caught above
|
|
|
|
# 3. Check 'data'
|
|
if "data" in data_dict:
|
|
sensor_data = data_dict["data"]
|
|
if not isinstance(sensor_data, np.ndarray):
|
|
errors.append(
|
|
f"'data' is not a numpy.ndarray (type: {type(sensor_data)}).")
|
|
else:
|
|
if sensor_data.dtype != np.float16:
|
|
warnings.append(
|
|
f"'data' dtype is {sensor_data.dtype}, expected np.float16.")
|
|
|
|
if sensor_data.ndim != 2:
|
|
errors.append(
|
|
f"'data' has {sensor_data.ndim} dimensions, expected 2. Shape: {sensor_data.shape}")
|
|
else:
|
|
num_channels, sequence_length = sensor_data.shape
|
|
if num_channels == 0:
|
|
errors.append("'data' has 0 channels.")
|
|
if sequence_length == 0:
|
|
errors.append("'data' has 0 sequence length.")
|
|
|
|
if np.isnan(sensor_data).any():
|
|
nan_count = np.isnan(sensor_data).sum()
|
|
errors.append(f"'data' contains {nan_count} NaN values.")
|
|
if np.isinf(sensor_data).any():
|
|
inf_count = np.isinf(sensor_data).sum()
|
|
errors.append(f"'data' contains {inf_count} Inf values.")
|
|
data_has_inf = True # Set the flag
|
|
# No 'else' needed here
|
|
|
|
# 4. Check 'sampling_rate'
|
|
if "sampling_rate" in data_dict:
|
|
sr = data_dict["sampling_rate"]
|
|
if not isinstance(sr, (int, float)):
|
|
errors.append(
|
|
f"'sampling_rate' is not a number (type: {type(sr)}). Value: {sr}")
|
|
elif sr <= 0:
|
|
errors.append(f"'sampling_rate' is not positive. Value: {sr}")
|
|
# No 'else' needed here
|
|
|
|
# 5. Check 'label'
|
|
if "label" in data_dict:
|
|
labels = data_dict["label"]
|
|
if not isinstance(labels, list):
|
|
errors.append(f"'label' is not a list (type: {type(labels)}).")
|
|
else:
|
|
if not labels:
|
|
warnings.append("'label' list is empty.")
|
|
for i, label_item in enumerate(labels):
|
|
if not isinstance(label_item, dict):
|
|
errors.append(
|
|
f"Item {i} in 'label' list is not a dict (type: {type(label_item)}).")
|
|
continue
|
|
if len(label_item) != 1:
|
|
errors.append(
|
|
f"Item {i} in 'label' dict does not have exactly one key. Keys: {list(label_item.keys())}")
|
|
continue
|
|
|
|
task_type, label_value = list(label_item.items())[0]
|
|
if task_type not in ["class", "reg"]:
|
|
errors.append(
|
|
f"Item {i} in 'label' dict has invalid task type '{task_type}'.")
|
|
|
|
if task_type == "class" and not isinstance(label_value, (int, np.integer)):
|
|
warnings.append(
|
|
f"Label for 'class' task (item {i}) is not an integer. Value: {label_value}")
|
|
elif task_type == "reg" and not isinstance(label_value, (int, float, np.number)):
|
|
warnings.append(
|
|
f"Label for 'reg' task (item {i}) is not a number. Value: {label_value}")
|
|
|
|
if label_value is None:
|
|
errors.append(
|
|
f"Label value for task '{task_type}' (item {i}) is None.")
|
|
# No 'else' needed here
|
|
|
|
return errors, warnings, data_has_inf
|
|
|
|
|
|
def main():
|
|
target_directory = input("Enter the directory containing .pkl files: ")
|
|
|
|
if not os.path.isdir(target_directory):
|
|
print(f"Error: Directory '{target_directory}' not found.")
|
|
return
|
|
|
|
# --- 新增:确认是否删除文件 ---
|
|
confirm_delete = input(
|
|
"Do you want to DELETE files where 'data' contains Inf values? (yes/no): ").strip().lower()
|
|
if confirm_delete == 'yes':
|
|
print("\n!!! WARNING: Files with Inf values in 'data' will be PERMANENTLY DELETED. !!!")
|
|
final_confirm = input(
|
|
"Are you absolutely sure? This cannot be undone. (yes/no): ").strip().lower()
|
|
if final_confirm != 'yes':
|
|
print("Deletion cancelled by user.")
|
|
confirm_delete = 'no'
|
|
else:
|
|
print("Files will NOT be deleted.")
|
|
# --- 结束新增 ---
|
|
|
|
print(f"\nScanning directory: {target_directory}")
|
|
|
|
pkl_files = [os.path.join(target_directory, f) for f in os.listdir(
|
|
target_directory) if f.endswith(".pkl")]
|
|
|
|
if not pkl_files:
|
|
print("No .pkl files found in the directory.")
|
|
return
|
|
|
|
# Tracks if any file had issues before potential deletion
|
|
all_files_ok_initially = True
|
|
total_errors = 0
|
|
total_warnings = 0
|
|
files_deleted_count = 0
|
|
deleted_files_log = []
|
|
|
|
for pkl_file_path in tqdm(pkl_files, desc="Checking files"):
|
|
errors, warnings, data_has_inf = check_pkl_file_integrity(
|
|
pkl_file_path)
|
|
|
|
if errors or warnings:
|
|
all_files_ok_initially = False
|
|
print(
|
|
f"\n--- Issues found in: {os.path.basename(pkl_file_path)} ---")
|
|
if errors:
|
|
total_errors += len(errors)
|
|
print(" Errors:")
|
|
for err in errors:
|
|
print(f" - {err}")
|
|
if warnings:
|
|
total_warnings += len(warnings)
|
|
print(" Warnings:")
|
|
for warn in warnings:
|
|
print(f" - {warn}")
|
|
|
|
# --- 新增:删除逻辑 ---
|
|
if data_has_inf and confirm_delete == 'yes':
|
|
try:
|
|
os.remove(pkl_file_path)
|
|
print(
|
|
f" DELETED file: {os.path.basename(pkl_file_path)} due to Inf values in 'data'.")
|
|
files_deleted_count += 1
|
|
deleted_files_log.append(os.path.basename(pkl_file_path))
|
|
except OSError as e:
|
|
print(
|
|
f" ERROR: Could not delete file {os.path.basename(pkl_file_path)}: {e}")
|
|
# --- 结束新增 ---
|
|
|
|
print("\n--- Scan Complete ---")
|
|
if all_files_ok_initially and files_deleted_count == 0:
|
|
print(
|
|
"All .pkl files seem to be in the correct format and have no NaN/Inf in 'data'.")
|
|
else:
|
|
print(
|
|
f"Initial scan found {total_errors} error(s) and {total_warnings} warning(s).")
|
|
|
|
if files_deleted_count > 0:
|
|
print(
|
|
f"\nSuccessfully deleted {files_deleted_count} file(s) containing Inf values in 'data':")
|
|
for fname in deleted_files_log:
|
|
print(f" - {fname}")
|
|
elif confirm_delete == 'yes':
|
|
print("\nNo files were deleted (either no Inf values found or deletion was cancelled).")
|
|
|
|
if not all_files_ok_initially and files_deleted_count < total_errors and confirm_delete == 'yes': # Check if other errors remain
|
|
print("\nNote: Some files with other errors (not Inf in data) might still exist.")
|
|
elif not all_files_ok_initially and confirm_delete != 'yes':
|
|
print("\nPlease review the messages above for files with issues.")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|