File size: 19,606 Bytes
85d5c4d | 1 2 3 4 5 6 7 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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Filter Sheetpedia-style XLSX files by worksheet-level quality rules.
Main logic:
1. Iterate over all .xlsx files under input_dir
2. For each worksheet, compute metadata on the effective table region
3. Decide keep/drop for each worksheet
4. Keep the workbook if at least one worksheet is kept
5. Export worksheet-level metadata and file-level summary
Recommended usage:
python filter_xlsx_dataset.py \
--input_dir /path/to/xlsx_folder \
--output_dir /path/to/output_metadata
Dependencies:
pip install openpyxl pandas
"""
import os
import re
import csv
import math
import argparse
import unicodedata
from collections import Counter
from pathlib import Path
import pandas as pd
from openpyxl import load_workbook
# =========================
# Configuration
# =========================
DEFAULT_MAX_ROWS = 100
DEFAULT_MAX_COLS = 80
DEFAULT_MIN_ROWS = 3
DEFAULT_MIN_COLS = 3
DEFAULT_MIN_FILL_RATIO = 0.15
DEFAULT_MAX_MISSING_NOISE_RATIO = 0.30
DEFAULT_MAX_PLACEHOLDER_RATIO = 0.50
DEFAULT_MIN_HEADER_UNIQUE_RATIO = 0.50
DEFAULT_MAX_NUMERIC_HEADER_RATIO = 0.80
# Missing / noisy markers after normalization
MISSING_MARKERS = {
"", "na", "n/a", "null", "none", "nan", "#n/a", "-", "--", "?", "unk", "unknown"
}
# Generic low-information placeholder tokens
PLACEHOLDER_TOKENS = {
"name", "field", "value", "item", "data", "text", "label",
"column", "row", "header", "col", "attr"
}
# =========================
# Utility functions
# =========================
def normalize_text(value):
"""
Normalize a cell value into a comparable string.
"""
if value is None:
return ""
# Keep numbers/bools readable
if isinstance(value, bool):
s = str(value).lower()
elif isinstance(value, (int, float)):
if isinstance(value, float):
if math.isnan(value):
return "nan"
if math.isinf(value):
return "inf"
s = str(value)
else:
s = str(value)
# Unicode normalization
s = unicodedata.normalize("NFKC", s)
# Remove surrounding whitespace and collapse internal whitespace
s = s.strip()
s = re.sub(r"\s+", " ", s)
return s
def is_empty_cell(value):
"""
Define whether a cell is empty for effective region detection.
"""
s = normalize_text(value)
return s == ""
def is_missing_marker(value):
"""
Detect common missing-value markers after normalization.
"""
s = normalize_text(value).lower()
return s in MISSING_MARKERS
def contains_replacement_char(s):
return "�" in s
def contains_control_chars(s):
"""
Keep common whitespace chars; detect suspicious non-printable chars.
"""
for ch in s:
cat = unicodedata.category(ch)
if cat.startswith("C") and ch not in ("\t", "\n", "\r"):
return True
return False
def informative_char_ratio(s):
"""
Ratio of letters/digits/CJK characters among non-space characters.
"""
s_no_space = re.sub(r"\s+", "", s)
if not s_no_space:
return 0.0
valid_count = 0
for ch in s_no_space:
# Latin letters / digits
if ch.isalnum():
valid_count += 1
continue
# CJK Unified Ideographs
code = ord(ch)
if (
0x4E00 <= code <= 0x9FFF or
0x3400 <= code <= 0x4DBF or
0x20000 <= code <= 0x2A6DF
):
valid_count += 1
return valid_count / len(s_no_space)
def is_symbol_noise(s):
"""
Detect strings dominated by repeated punctuation/symbols.
Examples: #####, ****, ..., @@@@
"""
s = s.strip()
if len(s) < 3:
return False
# all chars same non-alnum symbol
if len(set(s)) == 1 and not s[0].isalnum():
return True
# mostly punctuation/symbols
non_space = re.sub(r"\s+", "", s)
if not non_space:
return False
punct_or_symbol = sum(
1 for ch in non_space
if unicodedata.category(ch)[0] in {"P", "S"}
)
return punct_or_symbol / len(non_space) >= 0.8
def is_garbled(value):
"""
Detect garbled/noisy cell values.
"""
s = normalize_text(value)
if s == "":
return False
if contains_replacement_char(s):
return True
if contains_control_chars(s):
return True
if is_symbol_noise(s):
return True
# low informative ratio for non-trivial strings
if len(s) >= 4 and informative_char_ratio(s) < 0.30:
return True
return False
def is_numeric_like(s):
"""
Determine whether a normalized string is numeric-like.
"""
s = s.strip()
if s == "":
return False
try:
float(s.replace(",", ""))
return True
except Exception:
return False
def is_placeholder_like(value):
"""
Detect placeholder-like header content.
"""
s = normalize_text(value).lower()
if s == "":
return False
# [name], [date], [field], [column1], etc.
if re.fullmatch(r"\[[^\[\]]+\]", s):
return True
# generic tokens
if s in PLACEHOLDER_TOKENS:
return True
# auto-generated field names: column1, column_1, col1, field1, item1, attr1
if re.fullmatch(r"(column|col|field|item|attr|header|row|name|value|data|label|text)[ _-]?\d+", s):
return True
# repeated symbol strings
if re.fullmatch(r"[-*#.@]{3,}", s):
return True
return False
def unique_ratio(values):
"""
Unique ratio over non-empty normalized strings.
"""
vals = [normalize_text(v) for v in values if normalize_text(v) != ""]
if not vals:
return None
return len(set(vals)) / len(vals)
def numeric_ratio(values):
"""
Numeric-like ratio over non-empty normalized strings.
"""
vals = [normalize_text(v) for v in values if normalize_text(v) != ""]
if not vals:
return None
return sum(is_numeric_like(v) for v in vals) / len(vals)
def placeholder_ratio(values):
"""
Placeholder-like ratio over non-empty values.
"""
vals = [v for v in values if normalize_text(v) != ""]
if not vals:
return None
return sum(is_placeholder_like(v) for v in vals) / len(vals)
def mean_string_length(values):
vals = [normalize_text(v) for v in values if normalize_text(v) != ""]
if not vals:
return None
return sum(len(v) for v in vals) / len(vals)
def find_effective_region(ws):
"""
Find the minimal bounding rectangle covering all non-empty cells.
Returns (min_row, max_row, min_col, max_col), 1-based indexing,
or None if no non-empty cells exist.
"""
min_row = None
max_row = None
min_col = None
max_col = None
for row in ws.iter_rows():
for cell in row:
if not is_empty_cell(cell.value):
r, c = cell.row, cell.column
if min_row is None or r < min_row:
min_row = r
if max_row is None or r > max_row:
max_row = r
if min_col is None or c < min_col:
min_col = c
if max_col is None or c > max_col:
max_col = c
if min_row is None:
return None
return min_row, max_row, min_col, max_col
def extract_region_values(ws, region):
"""
Extract all values from the effective region into a 2D Python list.
"""
min_row, max_row, min_col, max_col = region
data = []
for row in ws.iter_rows(
min_row=min_row,
max_row=max_row,
min_col=min_col,
max_col=max_col,
values_only=True
):
data.append(list(row))
return data
def evaluate_worksheet(
ws,
max_rows=DEFAULT_MAX_ROWS,
max_cols=DEFAULT_MAX_COLS,
min_rows=DEFAULT_MIN_ROWS,
min_cols=DEFAULT_MIN_COLS,
min_fill_ratio=DEFAULT_MIN_FILL_RATIO,
max_missing_noise_ratio=DEFAULT_MAX_MISSING_NOISE_RATIO,
max_placeholder_ratio=DEFAULT_MAX_PLACEHOLDER_RATIO,
min_header_unique_ratio=DEFAULT_MIN_HEADER_UNIQUE_RATIO,
max_numeric_header_ratio=DEFAULT_MAX_NUMERIC_HEADER_RATIO,
):
"""
Compute worksheet metadata and keep/drop decision.
"""
metadata = {
"sheet_name": ws.title,
"has_effective_region": False,
"effective_min_row": None,
"effective_max_row": None,
"effective_min_col": None,
"effective_max_col": None,
"n_rows": 0,
"n_cols": 0,
"area": 0,
"non_empty_cells": 0,
"fill_ratio": None,
"missing_noise_cells": 0,
"missing_noise_ratio": None,
"header_row_nonempty": 0,
"header_col_nonempty": 0,
"header_row_placeholder_ratio": None,
"header_col_placeholder_ratio": None,
"header_row_unique_ratio": None,
"header_col_unique_ratio": None,
"header_row_numeric_ratio": None,
"header_col_numeric_ratio": None,
"header_row_mean_len": None,
"header_col_mean_len": None,
"keep_sheet": False,
"drop_reasons": "",
}
reasons = []
region = find_effective_region(ws)
if region is None:
reasons.append("no_effective_region")
metadata["drop_reasons"] = ";".join(reasons)
return metadata
metadata["has_effective_region"] = True
metadata["effective_min_row"], metadata["effective_max_row"], metadata["effective_min_col"], metadata["effective_max_col"] = region
values_2d = extract_region_values(ws, region)
R = len(values_2d)
C = len(values_2d[0]) if R > 0 else 0
area = R * C
metadata["n_rows"] = R
metadata["n_cols"] = C
metadata["area"] = area
# Size rules
if R < min_rows:
reasons.append("too_few_rows")
if C < min_cols:
reasons.append("too_few_cols")
if R > max_rows:
reasons.append("too_many_rows")
if C > max_cols:
reasons.append("too_many_cols")
if area < 9:
reasons.append("area_lt_9")
# Cell statistics
flat_values = [v for row in values_2d for v in row]
non_empty_cells = sum(not is_empty_cell(v) for v in flat_values)
metadata["non_empty_cells"] = non_empty_cells
fill_ratio = non_empty_cells / area if area > 0 else 0.0
metadata["fill_ratio"] = fill_ratio
if fill_ratio < min_fill_ratio:
reasons.append("low_fill_ratio")
missing_noise_cells = sum(
is_missing_marker(v) or is_garbled(v)
for v in flat_values
)
metadata["missing_noise_cells"] = missing_noise_cells
missing_noise_ratio = missing_noise_cells / area if area > 0 else 0.0
metadata["missing_noise_ratio"] = missing_noise_ratio
if missing_noise_ratio > max_missing_noise_ratio:
reasons.append("high_missing_noise_ratio")
# Header candidates
header_row = values_2d[0] if R >= 1 else []
header_col = [row[0] for row in values_2d] if C >= 1 else []
# Exclude top-left cell from both header stats to avoid double counting
if header_row:
header_row_eval = header_row[1:] if len(header_row) > 1 else []
else:
header_row_eval = []
if header_col:
header_col_eval = header_col[1:] if len(header_col) > 1 else []
else:
header_col_eval = []
header_row_nonempty = sum(normalize_text(v) != "" for v in header_row_eval)
header_col_nonempty = sum(normalize_text(v) != "" for v in header_col_eval)
metadata["header_row_nonempty"] = header_row_nonempty
metadata["header_col_nonempty"] = header_col_nonempty
metadata["header_row_placeholder_ratio"] = placeholder_ratio(header_row_eval)
metadata["header_col_placeholder_ratio"] = placeholder_ratio(header_col_eval)
metadata["header_row_unique_ratio"] = unique_ratio(header_row_eval)
metadata["header_col_unique_ratio"] = unique_ratio(header_col_eval)
metadata["header_row_numeric_ratio"] = numeric_ratio(header_row_eval)
metadata["header_col_numeric_ratio"] = numeric_ratio(header_col_eval)
metadata["header_row_mean_len"] = mean_string_length(header_row_eval)
metadata["header_col_mean_len"] = mean_string_length(header_col_eval)
# Apply header rules only if there are at least 3 non-empty candidate headers
if header_row_nonempty >= 3:
pr = metadata["header_row_placeholder_ratio"]
ur = metadata["header_row_unique_ratio"]
nr = metadata["header_row_numeric_ratio"]
if pr is not None and pr > max_placeholder_ratio:
reasons.append("bad_column_headers_placeholder")
if ur is not None and ur < min_header_unique_ratio:
reasons.append("bad_column_headers_low_unique")
if nr is not None and nr > max_numeric_header_ratio:
reasons.append("bad_column_headers_too_numeric")
if header_col_nonempty >= 3:
pr = metadata["header_col_placeholder_ratio"]
ur = metadata["header_col_unique_ratio"]
nr = metadata["header_col_numeric_ratio"]
if pr is not None and pr > max_placeholder_ratio:
reasons.append("bad_row_headers_placeholder")
if ur is not None and ur < min_header_unique_ratio:
reasons.append("bad_row_headers_low_unique")
if nr is not None and nr > max_numeric_header_ratio:
reasons.append("bad_row_headers_too_numeric")
metadata["keep_sheet"] = len(reasons) == 0
metadata["drop_reasons"] = ";".join(reasons)
return metadata
def process_workbook(
xlsx_path,
**kwargs
):
"""
Evaluate all worksheets in one workbook.
Returns:
sheet_records: list of worksheet metadata dict
file_summary: dict
"""
sheet_records = []
try:
wb = load_workbook(
filename=xlsx_path,
read_only=True,
data_only=True
)
except Exception as e:
return [], {
"file_path": str(xlsx_path),
"file_name": Path(xlsx_path).name,
"num_sheets_total": 0,
"num_sheets_kept": 0,
"keep_file": False,
"drop_reason": f"workbook_read_error:{type(e).__name__}"
}
for ws in wb.worksheets:
meta = evaluate_worksheet(ws, **kwargs)
meta["file_path"] = str(xlsx_path)
meta["file_name"] = Path(xlsx_path).name
sheet_records.append(meta)
num_sheets_total = len(sheet_records)
num_sheets_kept = sum(r["keep_sheet"] for r in sheet_records)
# File-level rule:
# Keep workbook if at least one worksheet is valid
keep_file = num_sheets_kept > 0
if keep_file:
drop_reason = ""
else:
if num_sheets_total == 0:
drop_reason = "no_worksheets"
else:
drop_reason = "all_worksheets_filtered"
file_summary = {
"file_path": str(xlsx_path),
"file_name": Path(xlsx_path).name,
"num_sheets_total": num_sheets_total,
"num_sheets_kept": num_sheets_kept,
"keep_file": keep_file,
"drop_reason": drop_reason,
}
try:
wb.close()
except Exception:
pass
return sheet_records, file_summary
def find_xlsx_files(input_dir):
"""
Recursively find all .xlsx files, excluding temporary Excel lock files.
"""
input_dir = Path(input_dir)
files = []
for p in input_dir.rglob("*.xlsx"):
if p.name.startswith("~$"):
continue
files.append(p)
return sorted(files)
def write_txt_lines(path, lines):
with open(path, "w", encoding="utf-8") as f:
for line in lines:
f.write(str(line) + "\n")
def main():
parser = argparse.ArgumentParser(description="Filter XLSX dataset by worksheet quality rules.")
parser.add_argument("--input_dir", type=str, required=True, help="Input folder containing .xlsx files")
parser.add_argument("--output_dir", type=str, required=True, help="Output folder for metadata and lists")
parser.add_argument("--max_rows", type=int, default=DEFAULT_MAX_ROWS)
parser.add_argument("--max_cols", type=int, default=DEFAULT_MAX_COLS)
parser.add_argument("--min_rows", type=int, default=DEFAULT_MIN_ROWS)
parser.add_argument("--min_cols", type=int, default=DEFAULT_MIN_COLS)
parser.add_argument("--min_fill_ratio", type=float, default=DEFAULT_MIN_FILL_RATIO)
parser.add_argument("--max_missing_noise_ratio", type=float, default=DEFAULT_MAX_MISSING_NOISE_RATIO)
parser.add_argument("--max_placeholder_ratio", type=float, default=DEFAULT_MAX_PLACEHOLDER_RATIO)
parser.add_argument("--min_header_unique_ratio", type=float, default=DEFAULT_MIN_HEADER_UNIQUE_RATIO)
parser.add_argument("--max_numeric_header_ratio", type=float, default=DEFAULT_MAX_NUMERIC_HEADER_RATIO)
args = parser.parse_args()
output_dir = Path(args.output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
xlsx_files = find_xlsx_files(args.input_dir)
print(f"Found {len(xlsx_files)} xlsx files.")
worksheet_records = []
file_records = []
for i, xlsx_path in enumerate(xlsx_files, 1):
if i % 100 == 0 or i == 1:
print(f"[{i}/{len(xlsx_files)}] Processing: {xlsx_path}")
sheet_records, file_summary = process_workbook(
xlsx_path,
max_rows=args.max_rows,
max_cols=args.max_cols,
min_rows=args.min_rows,
min_cols=args.min_cols,
min_fill_ratio=args.min_fill_ratio,
max_missing_noise_ratio=args.max_missing_noise_ratio,
max_placeholder_ratio=args.max_placeholder_ratio,
min_header_unique_ratio=args.min_header_unique_ratio,
max_numeric_header_ratio=args.max_numeric_header_ratio,
)
worksheet_records.extend(sheet_records)
file_records.append(file_summary)
# Save worksheet metadata
worksheet_df = pd.DataFrame(worksheet_records)
worksheet_csv = output_dir / "worksheet_metadata.csv"
worksheet_df.to_csv(worksheet_csv, index=False, encoding="utf-8-sig")
# Save file summary
file_df = pd.DataFrame(file_records)
file_csv = output_dir / "file_summary.csv"
file_df.to_csv(file_csv, index=False, encoding="utf-8-sig")
kept_files = file_df.loc[file_df["keep_file"] == True, "file_path"].tolist()
dropped_files = file_df.loc[file_df["keep_file"] == False, "file_path"].tolist()
write_txt_lines(output_dir / "kept_files.txt", kept_files)
write_txt_lines(output_dir / "dropped_files.txt", dropped_files)
# Save simple statistics
stats = {
"num_xlsx_total": len(file_df),
"num_xlsx_kept": int(file_df["keep_file"].sum()) if len(file_df) > 0 else 0,
"num_xlsx_dropped": int((~file_df["keep_file"]).sum()) if len(file_df) > 0 else 0,
"num_worksheets_total": len(worksheet_df),
"num_worksheets_kept": int(worksheet_df["keep_sheet"].sum()) if len(worksheet_df) > 0 else 0,
"num_worksheets_dropped": int((~worksheet_df["keep_sheet"]).sum()) if len(worksheet_df) > 0 else 0,
}
stats_path = output_dir / "stats_summary.csv"
pd.DataFrame([stats]).to_csv(stats_path, index=False, encoding="utf-8-sig")
print("\nDone.")
print(f"Worksheet metadata saved to: {worksheet_csv}")
print(f"File summary saved to: {file_csv}")
print(f"Stats summary saved to: {stats_path}")
print(f"Kept files list saved to: {output_dir / 'kept_files.txt'}")
print(f"Dropped files list saved to:{output_dir / 'dropped_files.txt'}")
if __name__ == "__main__":
main() |