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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
import subprocess
|
| 3 |
+
from itertools import combinations
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import pandas as pd
|
| 7 |
+
|
| 8 |
+
CSV_DIR = None
|
| 9 |
+
while CSV_DIR is None:
|
| 10 |
+
user_input = input("Enter the full path to the CSV directory: ").strip()
|
| 11 |
+
if not user_input:
|
| 12 |
+
continue
|
| 13 |
+
csv_path = Path(user_input)
|
| 14 |
+
if not csv_path.is_dir():
|
| 15 |
+
continue
|
| 16 |
+
CSV_DIR = csv_path
|
| 17 |
+
|
| 18 |
+
OUTPUT_FILE = Path("./schema_comparison_output.txt")
|
| 19 |
+
N_ROWS = 1000
|
| 20 |
+
SAMPLE_ROWS = 5
|
| 21 |
+
|
| 22 |
+
output_lines = []
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def output(*args, **kwargs):
|
| 26 |
+
line = " ".join(str(a) for a in args)
|
| 27 |
+
print(line, **kwargs)
|
| 28 |
+
output_lines.append(line)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def extract_date(filename: str) -> str:
|
| 32 |
+
match = re.match(r"^(.*?_\d{2}_\d{2}_\d{4})", filename)
|
| 33 |
+
return match.group(1) if match else None
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def get_row_count(filepath: Path) -> int:
|
| 37 |
+
result = subprocess.run(
|
| 38 |
+
["wc", "-l", str(filepath)],
|
| 39 |
+
capture_output=True,
|
| 40 |
+
text=True,
|
| 41 |
+
)
|
| 42 |
+
return int(result.stdout.strip().split()[0]) - 1
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def load_schema(filepath: Path, nrows: int = N_ROWS) -> tuple[dict, pd.DataFrame]:
|
| 46 |
+
try:
|
| 47 |
+
df = pd.read_csv(filepath, nrows=nrows)
|
| 48 |
+
except Exception as e:
|
| 49 |
+
output(f"Warning: Could not read {filepath.name}: {e}")
|
| 50 |
+
return {}, pd.DataFrame()
|
| 51 |
+
schema = dict(df.dtypes)
|
| 52 |
+
return schema, df
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def compare_schemas(
|
| 56 |
+
schema1: dict,
|
| 57 |
+
df1: pd.DataFrame,
|
| 58 |
+
name1: str,
|
| 59 |
+
schema2: dict,
|
| 60 |
+
df2: pd.DataFrame,
|
| 61 |
+
name2: str,
|
| 62 |
+
):
|
| 63 |
+
cols1 = set(schema1.keys())
|
| 64 |
+
cols2 = set(schema2.keys())
|
| 65 |
+
|
| 66 |
+
missing_in_1 = cols2 - cols1
|
| 67 |
+
missing_in_2 = cols1 - cols2
|
| 68 |
+
common_cols = cols1 & cols2
|
| 69 |
+
|
| 70 |
+
dtype_mismatches = {}
|
| 71 |
+
for col in common_cols:
|
| 72 |
+
if str(schema1[col]) != str(schema2[col]):
|
| 73 |
+
dtype_mismatches[col] = (schema1[col], schema2[col])
|
| 74 |
+
|
| 75 |
+
if missing_in_1 or missing_in_2 or dtype_mismatches:
|
| 76 |
+
return False, missing_in_1, missing_in_2, dtype_mismatches
|
| 77 |
+
return True, None, None, None
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def print_mismatch(
|
| 81 |
+
name1: str,
|
| 82 |
+
name2: str,
|
| 83 |
+
missing_in_1: set,
|
| 84 |
+
missing_in_2: set,
|
| 85 |
+
dtype_mismatches: dict,
|
| 86 |
+
df1: pd.DataFrame,
|
| 87 |
+
df2: pd.DataFrame,
|
| 88 |
+
):
|
| 89 |
+
output(f"\n{'=' * 60}")
|
| 90 |
+
output(f"MISMATCH: {name1} <-> {name2}")
|
| 91 |
+
output(f"{'=' * 60}")
|
| 92 |
+
|
| 93 |
+
if missing_in_1:
|
| 94 |
+
output(f"\nColumns in {name2} but not in {name1}: {missing_in_1}")
|
| 95 |
+
if missing_in_2:
|
| 96 |
+
output(f"\nColumns in {name1} but not in {name2}: {missing_in_2}")
|
| 97 |
+
|
| 98 |
+
if dtype_mismatches:
|
| 99 |
+
output("\n--- DTYPE MISMATCHES ---")
|
| 100 |
+
for col, (dt1, dt2) in dtype_mismatches.items():
|
| 101 |
+
output(f" {col}: {name1}={dt1}, {name2}={dt2}")
|
| 102 |
+
|
| 103 |
+
output("\n--- SAMPLE DATA FOR MISMATCHED COLUMNS ---")
|
| 104 |
+
for col in dtype_mismatches.keys():
|
| 105 |
+
output(f"\n--- {col} ---")
|
| 106 |
+
output(f"{name1} ({SAMPLE_ROWS} rows):")
|
| 107 |
+
output(df1[col].head(SAMPLE_ROWS).to_list())
|
| 108 |
+
output(f"{name2} ({SAMPLE_ROWS} rows):")
|
| 109 |
+
output(df2[col].head(SAMPLE_ROWS).to_list())
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def main():
|
| 113 |
+
global output_lines
|
| 114 |
+
|
| 115 |
+
csv_files = list(CSV_DIR.glob("*.csv"))
|
| 116 |
+
|
| 117 |
+
date_groups = {}
|
| 118 |
+
for f in csv_files:
|
| 119 |
+
date = extract_date(f.name)
|
| 120 |
+
if date:
|
| 121 |
+
date_groups.setdefault(date, []).append(f)
|
| 122 |
+
|
| 123 |
+
file_stats = {}
|
| 124 |
+
|
| 125 |
+
for date, files in sorted(date_groups.items()):
|
| 126 |
+
if len(files) < 2:
|
| 127 |
+
output(f"\nSkipping {date} (only 1 file: {files[0].name})")
|
| 128 |
+
for f in files:
|
| 129 |
+
schema, df = load_schema(f)
|
| 130 |
+
file_stats[f.name] = {
|
| 131 |
+
"row_count": get_row_count(f),
|
| 132 |
+
"col_count": len(df.columns),
|
| 133 |
+
}
|
| 134 |
+
continue
|
| 135 |
+
|
| 136 |
+
output(f"\n{'#' * 60}")
|
| 137 |
+
output(f"DATE GROUP: {date}")
|
| 138 |
+
|
| 139 |
+
row_counts = {}
|
| 140 |
+
schemas = {}
|
| 141 |
+
dataframes = {}
|
| 142 |
+
|
| 143 |
+
for f in files:
|
| 144 |
+
row_counts[f.name] = get_row_count(f)
|
| 145 |
+
file_stats[f.name] = {
|
| 146 |
+
"row_count": row_counts[f.name],
|
| 147 |
+
"col_count": 0,
|
| 148 |
+
}
|
| 149 |
+
schema, df = load_schema(f)
|
| 150 |
+
schemas[f.name] = schema
|
| 151 |
+
dataframes[f.name] = df
|
| 152 |
+
file_stats[f.name]["col_count"] = len(df.columns)
|
| 153 |
+
|
| 154 |
+
file_info = ", ".join(f"{f.name} ({row_counts[f.name]:,} rows)" for f in files)
|
| 155 |
+
output(f"Files: {file_info}")
|
| 156 |
+
output(f"{'#' * 60}")
|
| 157 |
+
|
| 158 |
+
has_mismatch = False
|
| 159 |
+
for f1, f2 in combinations(files, 2):
|
| 160 |
+
name1, name2 = f1.name, f2.name
|
| 161 |
+
is_match, missing_in_1, missing_in_2, dtype_mismatches = compare_schemas(
|
| 162 |
+
schemas[name1],
|
| 163 |
+
dataframes[name1],
|
| 164 |
+
name1,
|
| 165 |
+
schemas[name2],
|
| 166 |
+
dataframes[name2],
|
| 167 |
+
name2,
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
if not is_match:
|
| 171 |
+
has_mismatch = True
|
| 172 |
+
print_mismatch(
|
| 173 |
+
name1,
|
| 174 |
+
name2,
|
| 175 |
+
missing_in_1,
|
| 176 |
+
missing_in_2,
|
| 177 |
+
dtype_mismatches,
|
| 178 |
+
dataframes[name1],
|
| 179 |
+
dataframes[name2],
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
if not has_mismatch:
|
| 183 |
+
output("\nAll files in this group have matching schemas.")
|
| 184 |
+
|
| 185 |
+
output(f"\n{'#' * 60}")
|
| 186 |
+
output("FILE STATISTICS")
|
| 187 |
+
output(f"{'#' * 60}")
|
| 188 |
+
output(f"\n{'File':<60} {'Rows':>12} {'Columns':>10}")
|
| 189 |
+
output("-" * 82)
|
| 190 |
+
grand_total_rows = 0
|
| 191 |
+
for name, stats in sorted(file_stats.items()):
|
| 192 |
+
output(f"{name:<60} {stats['row_count']:>12,} {stats['col_count']:>10}")
|
| 193 |
+
grand_total_rows += stats["row_count"]
|
| 194 |
+
output("-" * 82)
|
| 195 |
+
output(f"{'TOTAL':<60} {grand_total_rows:>12,}")
|
| 196 |
+
|
| 197 |
+
OUTPUT_FILE.write_text("\n".join(output_lines))
|
| 198 |
+
print(f"\nOutput saved to {OUTPUT_FILE}")
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
if __name__ == "__main__":
|
| 202 |
+
main()
|