sheetpedia / filter.py
jcsama's picture
Upload 2 files
85d5c4d verified
#!/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()