Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -9,38 +9,47 @@ import gradio as gr
|
|
| 9 |
SUPPORTED_EXT = {".xlsx", ".xls", ".csv"}
|
| 10 |
|
| 11 |
|
| 12 |
-
# -----------------------------
|
| 13 |
-
#
|
| 14 |
-
# -----------------------------
|
| 15 |
-
def
|
| 16 |
if path.suffix.lower() in [".xlsx", ".xls"]:
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
|
| 21 |
-
|
| 22 |
-
best_score = -
|
| 23 |
|
| 24 |
-
for
|
| 25 |
-
row = preview.iloc[
|
| 26 |
-
non_empty = row[row
|
| 27 |
if len(non_empty) < 2:
|
| 28 |
continue
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
-
|
|
|
|
| 34 |
|
|
|
|
| 35 |
if score > best_score:
|
| 36 |
-
best_score = score
|
| 37 |
-
best_row = i
|
| 38 |
|
| 39 |
return best_row
|
| 40 |
|
| 41 |
|
| 42 |
-
def
|
| 43 |
-
|
|
|
|
| 44 |
|
| 45 |
if path.suffix.lower() in [".xlsx", ".xls"]:
|
| 46 |
df = pd.read_excel(path, header=header_row, dtype=str)
|
|
@@ -50,78 +59,68 @@ def read_with_auto_header(path: Path):
|
|
| 50 |
return df, header_row
|
| 51 |
|
| 52 |
|
| 53 |
-
# -----------------------------
|
| 54 |
-
#
|
| 55 |
-
# -----------------------------
|
| 56 |
-
def
|
| 57 |
-
|
| 58 |
new_cols = []
|
| 59 |
created = []
|
| 60 |
|
| 61 |
for c in df.columns:
|
| 62 |
name = "" if c is None else str(c).strip()
|
| 63 |
-
|
| 64 |
if name == "" or name.lower().startswith("unnamed"):
|
| 65 |
-
name = f"Unknown Column{
|
| 66 |
created.append(name)
|
| 67 |
-
|
| 68 |
-
|
| 69 |
new_cols.append(name)
|
| 70 |
|
| 71 |
df.columns = new_cols
|
| 72 |
-
return df,
|
| 73 |
-
|
| 74 |
|
| 75 |
-
# -------------------------------------------------
|
| 76 |
-
# ERROR DETECTION (GENERIC)
|
| 77 |
-
# -------------------------------------------------
|
| 78 |
-
def detect_problem_rows(df, file_name, header_row):
|
| 79 |
-
temp = df.copy()
|
| 80 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
def is_empty(x):
|
| 82 |
if pd.isna(x):
|
| 83 |
return True
|
| 84 |
-
|
|
|
|
| 85 |
|
| 86 |
-
|
| 87 |
-
total_cols = max(1,
|
| 88 |
-
empty_ratio =
|
| 89 |
|
| 90 |
-
fully_blank =
|
| 91 |
-
mostly_blank = empty_ratio >= 0.
|
| 92 |
|
| 93 |
problem_mask = fully_blank | mostly_blank
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
return problems
|
| 98 |
|
| 99 |
reasons = []
|
| 100 |
-
for
|
| 101 |
-
if fully_blank.loc[
|
| 102 |
reasons.append("Fully blank row")
|
| 103 |
else:
|
| 104 |
reasons.append("Mostly blank row (>=80% empty)")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
|
| 106 |
-
problems.insert(0, "ErrorReason", reasons)
|
| 107 |
-
problems.insert(0, "DetectedHeaderRow", header_row)
|
| 108 |
-
problems.insert(0, "File", file_name)
|
| 109 |
-
|
| 110 |
-
return problems
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
# -------------------------------------------------
|
| 114 |
-
# MAIN FUNCTION
|
| 115 |
-
# -------------------------------------------------
|
| 116 |
-
def combine_excel(files, zip_file, progress=gr.Progress()):
|
| 117 |
-
|
| 118 |
-
if not files and not zip_file:
|
| 119 |
-
return "Please upload files or ZIP.", None, None, "No files uploaded."
|
| 120 |
|
| 121 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
paths = []
|
| 123 |
|
| 124 |
-
#
|
| 125 |
if files:
|
| 126 |
for f in files:
|
| 127 |
src = Path(f)
|
|
@@ -130,9 +129,10 @@ def combine_excel(files, zip_file, progress=gr.Progress()):
|
|
| 130 |
os.replace(src, dst)
|
| 131 |
paths.append(dst)
|
| 132 |
|
| 133 |
-
#
|
| 134 |
-
if
|
| 135 |
-
|
|
|
|
| 136 |
for info in z.infolist():
|
| 137 |
if info.is_dir():
|
| 138 |
continue
|
|
@@ -143,87 +143,118 @@ def combine_excel(files, zip_file, progress=gr.Progress()):
|
|
| 143 |
dst.write(src.read())
|
| 144 |
paths.append(out)
|
| 145 |
|
| 146 |
-
|
| 147 |
-
|
|
|
|
| 148 |
|
| 149 |
-
all_dfs = []
|
| 150 |
-
all_columns = set()
|
| 151 |
-
unknown_counter = 1
|
| 152 |
-
error_list = []
|
| 153 |
|
| 154 |
-
|
| 155 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
|
| 157 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
|
| 159 |
-
|
|
|
|
| 160 |
|
| 161 |
-
|
|
|
|
|
|
|
| 162 |
|
| 163 |
-
|
|
|
|
| 164 |
|
| 165 |
-
#
|
| 166 |
-
|
| 167 |
-
if not
|
| 168 |
-
|
| 169 |
|
| 170 |
-
#
|
| 171 |
df.insert(0, "File", path.stem)
|
| 172 |
|
| 173 |
all_columns.update(df.columns)
|
| 174 |
all_dfs.append(df)
|
| 175 |
|
| 176 |
-
progress(i / total, desc=f"
|
| 177 |
|
| 178 |
-
|
| 179 |
-
progress(1, desc="Combining...")
|
| 180 |
combined = pd.concat(all_dfs, ignore_index=True, sort=False)
|
| 181 |
|
| 182 |
-
# Ensure File
|
| 183 |
-
|
| 184 |
-
combined = combined.reindex(columns=
|
|
|
|
|
|
|
|
|
|
| 185 |
|
| 186 |
-
|
| 187 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
|
| 189 |
-
|
| 190 |
-
if error_list:
|
| 191 |
-
error_df = pd.concat(error_list, ignore_index=True, sort=False)
|
| 192 |
-
error_path = tmpdir / "error_report.xlsx"
|
| 193 |
-
error_df.to_excel(error_path, index=False)
|
| 194 |
|
| 195 |
-
|
| 196 |
-
### Batch Summary
|
| 197 |
-
- Files processed: **{total}**
|
| 198 |
-
- Total rows combined: **{len(combined)}**
|
| 199 |
-
- Total columns: **{len(combined.columns)}**
|
| 200 |
-
-
|
| 201 |
-
""
|
|
|
|
|
|
|
| 202 |
|
| 203 |
-
return "Done ✅", str(
|
| 204 |
|
| 205 |
|
| 206 |
-
# -----------------------------
|
| 207 |
-
# UI
|
| 208 |
-
# -----------------------------
|
| 209 |
with gr.Blocks(title="Excel Batch Combiner") as demo:
|
| 210 |
-
gr.Markdown(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 211 |
|
| 212 |
with gr.Row():
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
|
| 218 |
status = gr.Textbox(label="Status", interactive=False)
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
summary = gr.Markdown()
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
combine_excel,
|
| 225 |
-
inputs=[
|
| 226 |
-
outputs=[status,
|
| 227 |
)
|
| 228 |
|
| 229 |
-
demo.launch()
|
|
|
|
| 9 |
SUPPORTED_EXT = {".xlsx", ".xls", ".csv"}
|
| 10 |
|
| 11 |
|
| 12 |
+
# -----------------------------
|
| 13 |
+
# Header auto-detection
|
| 14 |
+
# -----------------------------
|
| 15 |
+
def _read_preview(path: Path, nrows: int = 25) -> pd.DataFrame:
|
| 16 |
if path.suffix.lower() in [".xlsx", ".xls"]:
|
| 17 |
+
return pd.read_excel(path, header=None, nrows=nrows, dtype=str)
|
| 18 |
+
return pd.read_csv(path, header=None, nrows=nrows, dtype=str, engine="python")
|
| 19 |
+
|
| 20 |
|
| 21 |
+
def _detect_header_row(preview: pd.DataFrame) -> int:
|
| 22 |
+
best_row, best_score = 0, float("-inf")
|
| 23 |
|
| 24 |
+
for r in range(len(preview)):
|
| 25 |
+
row = preview.iloc[r].fillna("").astype(str).map(lambda x: x.strip())
|
| 26 |
+
non_empty = row[row != ""]
|
| 27 |
if len(non_empty) < 2:
|
| 28 |
continue
|
| 29 |
|
| 30 |
+
# numeric-ish ratio
|
| 31 |
+
numeric = 0
|
| 32 |
+
for v in non_empty:
|
| 33 |
+
try:
|
| 34 |
+
float(v.replace(",", ""))
|
| 35 |
+
numeric += 1
|
| 36 |
+
except:
|
| 37 |
+
pass
|
| 38 |
+
numeric_ratio = numeric / max(1, len(non_empty))
|
| 39 |
|
| 40 |
+
# uniqueness ratio
|
| 41 |
+
unique_ratio = len(set(non_empty)) / max(1, len(non_empty))
|
| 42 |
|
| 43 |
+
score = (len(non_empty) * 2.0) + (unique_ratio * 5.0) - (numeric_ratio * 8.0)
|
| 44 |
if score > best_score:
|
| 45 |
+
best_score, best_row = score, r
|
|
|
|
| 46 |
|
| 47 |
return best_row
|
| 48 |
|
| 49 |
|
| 50 |
+
def _read_with_auto_header(path: Path) -> tuple[pd.DataFrame, int]:
|
| 51 |
+
preview = _read_preview(path)
|
| 52 |
+
header_row = _detect_header_row(preview)
|
| 53 |
|
| 54 |
if path.suffix.lower() in [".xlsx", ".xls"]:
|
| 55 |
df = pd.read_excel(path, header=header_row, dtype=str)
|
|
|
|
| 59 |
return df, header_row
|
| 60 |
|
| 61 |
|
| 62 |
+
# -----------------------------
|
| 63 |
+
# Unknown columns renaming
|
| 64 |
+
# -----------------------------
|
| 65 |
+
def _rename_unknown_columns(df: pd.DataFrame, start_idx: int):
|
| 66 |
+
idx = start_idx
|
| 67 |
new_cols = []
|
| 68 |
created = []
|
| 69 |
|
| 70 |
for c in df.columns:
|
| 71 |
name = "" if c is None else str(c).strip()
|
|
|
|
| 72 |
if name == "" or name.lower().startswith("unnamed"):
|
| 73 |
+
name = f"Unknown Column{idx}"
|
| 74 |
created.append(name)
|
| 75 |
+
idx += 1
|
|
|
|
| 76 |
new_cols.append(name)
|
| 77 |
|
| 78 |
df.columns = new_cols
|
| 79 |
+
return df, idx, created
|
|
|
|
| 80 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
+
# -----------------------------
|
| 83 |
+
# Error report (generic)
|
| 84 |
+
# -----------------------------
|
| 85 |
+
def _error_rows(df: pd.DataFrame, file_label: str, header_row: int) -> pd.DataFrame:
|
| 86 |
def is_empty(x):
|
| 87 |
if pd.isna(x):
|
| 88 |
return True
|
| 89 |
+
s = str(x).strip()
|
| 90 |
+
return s == "" or s.lower() == "nan"
|
| 91 |
|
| 92 |
+
empty_counts = df.apply(lambda row: sum(is_empty(v) for v in row), axis=1)
|
| 93 |
+
total_cols = max(1, df.shape[1])
|
| 94 |
+
empty_ratio = empty_counts / total_cols
|
| 95 |
|
| 96 |
+
fully_blank = empty_counts == total_cols
|
| 97 |
+
mostly_blank = empty_ratio >= 0.80
|
| 98 |
|
| 99 |
problem_mask = fully_blank | mostly_blank
|
| 100 |
+
err = df.loc[problem_mask].copy()
|
| 101 |
+
if err.empty:
|
| 102 |
+
return err
|
|
|
|
| 103 |
|
| 104 |
reasons = []
|
| 105 |
+
for i in err.index:
|
| 106 |
+
if fully_blank.loc[i]:
|
| 107 |
reasons.append("Fully blank row")
|
| 108 |
else:
|
| 109 |
reasons.append("Mostly blank row (>=80% empty)")
|
| 110 |
+
err.insert(0, "ErrorReason", reasons)
|
| 111 |
+
err.insert(0, "DetectedHeaderRow", header_row)
|
| 112 |
+
err.insert(0, "File", file_label)
|
| 113 |
+
return err
|
| 114 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
|
| 116 |
+
# -----------------------------
|
| 117 |
+
# Collect inputs (multi files + zip)
|
| 118 |
+
# -----------------------------
|
| 119 |
+
def _collect_inputs(files, zip_batch):
|
| 120 |
+
tmpdir = Path(tempfile.mkdtemp(prefix="hf_combine_"))
|
| 121 |
paths = []
|
| 122 |
|
| 123 |
+
# Multiple uploaded files
|
| 124 |
if files:
|
| 125 |
for f in files:
|
| 126 |
src = Path(f)
|
|
|
|
| 129 |
os.replace(src, dst)
|
| 130 |
paths.append(dst)
|
| 131 |
|
| 132 |
+
# ZIP batch
|
| 133 |
+
if zip_batch:
|
| 134 |
+
zpath = Path(zip_batch)
|
| 135 |
+
with zipfile.ZipFile(zpath, "r") as z:
|
| 136 |
for info in z.infolist():
|
| 137 |
if info.is_dir():
|
| 138 |
continue
|
|
|
|
| 143 |
dst.write(src.read())
|
| 144 |
paths.append(out)
|
| 145 |
|
| 146 |
+
# de-dupe by filename
|
| 147 |
+
unique = {p.name: p for p in paths}
|
| 148 |
+
return tmpdir, sorted(unique.values(), key=lambda x: x.name)
|
| 149 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
|
| 151 |
+
# -----------------------------
|
| 152 |
+
# Main combine function
|
| 153 |
+
# -----------------------------
|
| 154 |
+
def combine_excel(uploaded_files, uploaded_zip, progress=gr.Progress()):
|
| 155 |
+
if not uploaded_files and not uploaded_zip:
|
| 156 |
+
return "Please upload files or a ZIP batch.", None, None, "No files uploaded."
|
| 157 |
|
| 158 |
+
tmpdir, input_paths = _collect_inputs(uploaded_files, uploaded_zip)
|
| 159 |
+
if not input_paths:
|
| 160 |
+
return "No supported files found (.xlsx/.xls/.csv).", None, None, "No valid files."
|
| 161 |
+
|
| 162 |
+
unknown_counter = 1
|
| 163 |
+
all_dfs = []
|
| 164 |
+
all_columns = set(["File"])
|
| 165 |
+
error_frames = []
|
| 166 |
|
| 167 |
+
total = len(input_paths)
|
| 168 |
+
progress(0, desc="Starting...")
|
| 169 |
|
| 170 |
+
for i, path in enumerate(input_paths, start=1):
|
| 171 |
+
progress((i - 1) / total, desc=f"Auto-detect header: {path.name}")
|
| 172 |
+
df, header_row = _read_with_auto_header(path)
|
| 173 |
|
| 174 |
+
progress((i - 1) / total, desc=f"Clean columns: {path.name}")
|
| 175 |
+
df, unknown_counter, _ = _rename_unknown_columns(df, unknown_counter)
|
| 176 |
|
| 177 |
+
# Error rows (generic)
|
| 178 |
+
err = _error_rows(df, file_label=path.stem, header_row=header_row)
|
| 179 |
+
if not err.empty:
|
| 180 |
+
error_frames.append(err)
|
| 181 |
|
| 182 |
+
# Always add File column first
|
| 183 |
df.insert(0, "File", path.stem)
|
| 184 |
|
| 185 |
all_columns.update(df.columns)
|
| 186 |
all_dfs.append(df)
|
| 187 |
|
| 188 |
+
progress(i / total, desc=f"Processed: {path.name}")
|
| 189 |
|
| 190 |
+
progress(1.0, desc="Combining...")
|
|
|
|
| 191 |
combined = pd.concat(all_dfs, ignore_index=True, sort=False)
|
| 192 |
|
| 193 |
+
# Ensure File first, others dynamic
|
| 194 |
+
ordered_cols = ["File"] + sorted([c for c in combined.columns if c != "File"])
|
| 195 |
+
combined = combined.reindex(columns=ordered_cols)
|
| 196 |
+
|
| 197 |
+
out_combined = tmpdir / "combined_output.xlsx"
|
| 198 |
+
combined.to_excel(out_combined, index=False)
|
| 199 |
|
| 200 |
+
out_error = None
|
| 201 |
+
error_rows_count = 0
|
| 202 |
+
if error_frames:
|
| 203 |
+
errors = pd.concat(error_frames, ignore_index=True, sort=False)
|
| 204 |
+
error_rows_count = len(errors)
|
| 205 |
+
out_error = tmpdir / "error_report.xlsx"
|
| 206 |
+
errors.to_excel(out_error, index=False)
|
| 207 |
|
| 208 |
+
unknown_cols = [c for c in combined.columns if c.startswith("Unknown Column")]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
|
| 210 |
+
summary_md = []
|
| 211 |
+
summary_md.append("### Batch Summary")
|
| 212 |
+
summary_md.append(f"- Files processed: **{total}**")
|
| 213 |
+
summary_md.append(f"- Total rows (combined): **{len(combined)}**")
|
| 214 |
+
summary_md.append(f"- Total columns (combined): **{len(combined.columns)}**")
|
| 215 |
+
summary_md.append(f"- Unknown columns created: **{len(unknown_cols)}**")
|
| 216 |
+
summary_md.append(f"- Error rows detected: **{error_rows_count}**")
|
| 217 |
+
if unknown_cols:
|
| 218 |
+
summary_md.append(f"- Unknown column names: `{', '.join(unknown_cols)}`")
|
| 219 |
|
| 220 |
+
return "Done ✅", str(out_combined), (str(out_error) if out_error else None), "\n".join(summary_md)
|
| 221 |
|
| 222 |
|
| 223 |
+
# -----------------------------
|
| 224 |
+
# UI (Hugging Face Space)
|
| 225 |
+
# -----------------------------
|
| 226 |
with gr.Blocks(title="Excel Batch Combiner") as demo:
|
| 227 |
+
gr.Markdown(
|
| 228 |
+
"# Excel / ZIP Batch Combiner\n"
|
| 229 |
+
"- Upload **multiple Excel/CSV files** OR a **ZIP batch**\n"
|
| 230 |
+
"- Auto-detect header row\n"
|
| 231 |
+
"- Combine with **File** column (filename) as column A\n"
|
| 232 |
+
"- Create **error_report.xlsx** for problematic rows\n"
|
| 233 |
+
)
|
| 234 |
|
| 235 |
with gr.Row():
|
| 236 |
+
uploaded_files = gr.File(
|
| 237 |
+
label="Upload Multiple Excel/CSV Files",
|
| 238 |
+
file_types=[".xlsx", ".xls", ".csv"],
|
| 239 |
+
file_count="multiple",
|
| 240 |
+
)
|
| 241 |
+
uploaded_zip = gr.File(
|
| 242 |
+
label="Or Upload ZIP Batch",
|
| 243 |
+
file_types=[".zip"],
|
| 244 |
+
file_count="single",
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
run_btn = gr.Button("Combine")
|
| 248 |
|
| 249 |
status = gr.Textbox(label="Status", interactive=False)
|
| 250 |
+
out_combined = gr.File(label="Output File (Download)")
|
| 251 |
+
out_error = gr.File(label="Error Report (Download)")
|
| 252 |
+
summary = gr.Markdown(label="Batch Summary")
|
| 253 |
+
|
| 254 |
+
run_btn.click(
|
| 255 |
+
fn=combine_excel,
|
| 256 |
+
inputs=[uploaded_files, uploaded_zip],
|
| 257 |
+
outputs=[status, out_combined, out_error, summary],
|
| 258 |
)
|
| 259 |
|
| 260 |
+
demo.launch()
|