| import os
|
| import sys
|
| import glob
|
| import joblib
|
| import numpy as np
|
| from tqdm import tqdm
|
|
|
| def merge_and_stack_folders(folder1_path, folder2_path, output_dir):
|
| """
|
| Merge same-name .pkl files from two folders and stack their contents by timestamp.
|
| """
|
|
|
| if not os.path.isdir(folder1_path):
|
| print(f"Error: Folder not found -> {folder1_path}")
|
| return
|
| if not os.path.isdir(folder2_path):
|
| print(f"Error: Folder not found -> {folder2_path}")
|
| return
|
|
|
|
|
| os.makedirs(output_dir, exist_ok=True)
|
| print(f"Input folder 1: {folder1_path}")
|
| print(f"Input folder 2: {folder2_path}")
|
| print(f"Output will be saved to: {output_dir}")
|
|
|
|
|
| folder1_files = glob.glob(os.path.join(folder1_path, "*.pkl"))
|
| if not folder1_files:
|
| print(f"Warning: No .pkl files found in {folder1_path}.")
|
| return
|
|
|
| print(f"\nFound {len(folder1_files)} files, starting pairwise merging...")
|
|
|
|
|
| for file1_path in tqdm(folder1_files, desc="Processing file pairs"):
|
| file_name = os.path.basename(file1_path)
|
| file2_path = os.path.join(folder2_path, file_name)
|
|
|
|
|
| if not os.path.exists(file2_path):
|
| print(f"\nSkipped: Paired file not found in {folder2_path} for {file_name}")
|
| continue
|
|
|
| try:
|
|
|
| with open(file1_path, 'rb') as f:
|
| data1 = joblib.load(f)
|
| with open(file2_path, 'rb') as f:
|
| data2 = joblib.load(f)
|
| except Exception as e:
|
| print(f"\nError: Failed to load file pair {file_name}: {e}")
|
| continue
|
|
|
|
|
| merged_data = {}
|
|
|
|
|
| common_keys = data1.keys() & data2.keys()
|
|
|
| for key in common_keys:
|
| vec1 = data1[key]
|
| vec2 = data2[key]
|
|
|
|
|
| if isinstance(vec1, np.ndarray) and isinstance(vec2, np.ndarray) and \
|
| vec1.ndim == 2 and vec2.ndim == 2 and \
|
| vec1.shape[1] == vec2.shape[1]:
|
|
|
|
|
|
|
| stacked_vec = np.vstack((vec1, vec2))
|
| merged_data[key] = stacked_vec
|
| else:
|
| print(f"\nWarning: Data format mismatch at timestamp {key} in file {file_name}, skipped.")
|
|
|
|
|
| if merged_data:
|
| output_path = os.path.join(output_dir, file_name)
|
| try:
|
| with open(output_path, 'wb') as f:
|
| joblib.dump(merged_data, f)
|
| except Exception as e:
|
| print(f"\nError: Failed to save merged file {output_path}: {e}")
|
|
|
| def main():
|
| """
|
| Main execution function.
|
| """
|
|
|
| folder1 = "./data/California_ISO/weather/san-francisco"
|
| folder2 = "./data/California_ISO/weather/san-diego"
|
| output_folder = "./data/California_ISO/weather/merged_report_embedding"
|
|
|
| merge_and_stack_folders(folder1, folder2, output_folder)
|
|
|
| print("\nAll matching files merged and stacked successfully!")
|
|
|
|
|
| if __name__ == "__main__":
|
| main()
|
|
|