PiyaJewpongpipat's picture
Update app.py
69bf9a5 verified
Raw History Blame Contribute Delete
8.97 kB
import os
import zipfile
import tempfile
from pathlib import Path
import pandas as pd
import gradio as gr
SUPPORTED_EXT = {".xlsx", ".xls", ".csv"}
# ========================
# CUSTOM LOGIN (Option 2)
# ========================
EXPECTED_USER = os.environ.get("USERNAME", "")
EXPECTED_PASS = os.environ.get("PASSWORD", "")
if not EXPECTED_USER or not EXPECTED_PASS:
raise RuntimeError(
"Missing USERNAME/PASSWORD secrets. "
"Set them in Hugging Face Space > Settings > Secrets."
)
def do_login(username: str, password: str):
"""Toggle visibility based on login success."""
if username == EXPECTED_USER and password == EXPECTED_PASS:
return (
True,
"✅ Logged in successfully.",
gr.update(visible=False), # hide login
gr.update(visible=True), # show app
)
return (
False,
"❌ Wrong username or password.",
gr.update(visible=True),
gr.update(visible=False),
)
# -----------------------------
# Header auto-detection
# -----------------------------
def _read_preview(path: Path, nrows: int = 25) -> pd.DataFrame:
if path.suffix.lower() in [".xlsx", ".xls"]:
return pd.read_excel(path, header=None, nrows=nrows, dtype=str)
return pd.read_csv(path, header=None, nrows=nrows, dtype=str, engine="python")
def _detect_header_row(preview: pd.DataFrame) -> int:
best_row, best_score = 0, float("-inf")
for r in range(len(preview)):
row = preview.iloc[r].fillna("").astype(str).map(lambda x: x.strip())
non_empty = row[row != ""]
if len(non_empty) < 2:
continue
numeric = 0
for v in non_empty:
try:
float(v.replace(",", ""))
numeric += 1
except:
pass
numeric_ratio = numeric / max(1, len(non_empty))
unique_ratio = len(set(non_empty)) / max(1, len(non_empty))
score = (len(non_empty) * 2.0) + (unique_ratio * 5.0) - (numeric_ratio * 8.0)
if score > best_score:
best_score, best_row = score, r
return best_row
def _read_with_auto_header(path: Path):
preview = _read_preview(path)
header_row = _detect_header_row(preview)
if path.suffix.lower() in [".xlsx", ".xls"]:
df = pd.read_excel(path, header=header_row, dtype=str)
else:
df = pd.read_csv(path, header=header_row, dtype=str, engine="python")
return df, header_row
# -----------------------------
# Rename unknown columns
# -----------------------------
def _rename_unknown_columns(df, start_idx):
idx = start_idx
new_cols = []
for c in df.columns:
name = "" if c is None else str(c).strip()
if name == "" or name.lower().startswith("unnamed"):
name = f"Unknown Column{idx}"
idx += 1
new_cols.append(name)
df.columns = new_cols
return df, idx
# -----------------------------
# Error detection
# -----------------------------
def _error_rows(df, file_label, header_row):
def is_empty(x):
if pd.isna(x):
return True
return str(x).strip() == ""
empty_counts = df.apply(lambda r: sum(is_empty(v) for v in r), axis=1)
total_cols = max(1, df.shape[1])
empty_ratio = empty_counts / total_cols
fully_blank = empty_counts == total_cols
mostly_blank = empty_ratio >= 0.8
mask = fully_blank | mostly_blank
err = df.loc[mask].copy()
if err.empty:
return err
reasons = []
for i in err.index:
if fully_blank.loc[i]:
reasons.append("Fully blank row")
else:
reasons.append("Mostly blank row (>=80% empty)")
err.insert(0, "ErrorReason", reasons)
err.insert(0, "DetectedHeaderRow", header_row)
err.insert(0, "File", file_label)
return err
# -----------------------------
# Collect files
# -----------------------------
def _collect_inputs(files, zip_batch):
tmpdir = Path(tempfile.mkdtemp(prefix="combine_"))
paths = []
if files:
for f in files:
src = Path(f)
if src.suffix.lower() in SUPPORTED_EXT:
dst = tmpdir / src.name
os.replace(src, dst)
paths.append(dst)
if zip_batch:
with zipfile.ZipFile(zip_batch, "r") as z:
for info in z.infolist():
if info.is_dir():
continue
ext = Path(info.filename).suffix.lower()
if ext in SUPPORTED_EXT:
out = tmpdir / Path(info.filename).name
with z.open(info) as src, open(out, "wb") as dst:
dst.write(src.read())
paths.append(out)
unique = {p.name: p for p in paths}
return tmpdir, sorted(unique.values(), key=lambda x: x.name)
# -----------------------------
# Main combine
# -----------------------------
def combine_excel(uploaded_files, uploaded_zip, progress=gr.Progress()):
if not uploaded_files and not uploaded_zip:
return "Please upload files or ZIP.", None, None, "No files uploaded."
tmpdir, input_paths = _collect_inputs(uploaded_files, uploaded_zip)
if not input_paths:
return "No supported files found.", None, None, "No valid files."
unknown_counter = 1
all_dfs = []
final_column_order = []
error_frames = []
total = len(input_paths)
progress(0, desc="Starting...")
for i, path in enumerate(input_paths, start=1):
progress((i - 1) / total, desc=f"Reading {path.name}")
df, header_row = _read_with_auto_header(path)
df, unknown_counter = _rename_unknown_columns(df, unknown_counter)
# detect errors
err = _error_rows(df, path.stem, header_row)
if not err.empty:
error_frames.append(err)
# Insert File column first
df.insert(0, "File", path.stem)
# Establish column order logic
if i == 1:
final_column_order = list(df.columns)
else:
for col in df.columns:
if col not in final_column_order:
final_column_order.append(col)
all_dfs.append(df)
progress(i / total, desc=f"Processed {path.name}")
progress(1, desc="Combining...")
combined = pd.concat(all_dfs, ignore_index=True, sort=False)
# Apply preserved column order
combined = combined.reindex(columns=final_column_order)
output_path = tmpdir / "combined_output.xlsx"
combined.to_excel(output_path, index=False)
error_path = None
error_count = 0
if error_frames:
errors = pd.concat(error_frames, ignore_index=True, sort=False)
error_count = len(errors)
error_path = tmpdir / "error_report.xlsx"
errors.to_excel(error_path, index=False)
summary = f"""
### Batch Summary
- Files processed: **{total}**
- Total rows: **{len(combined)}**
- Total columns: **{len(combined.columns)}**
- Error rows detected: **{error_count}**
"""
return "Done ✅", str(output_path), (str(error_path) if error_path else None), summary
# -----------------------------
# UI (with login gate)
# -----------------------------
with gr.Blocks(title="Excel Batch Combiner") as demo:
logged_in = gr.State(False)
# --- Login page ---
login_box = gr.Column(visible=True)
with login_box:
gr.Markdown("# Log in page Excel / ZIP Batch Combiner (Preserve Header Order)")
login_user = gr.Textbox(label="Username", placeholder="Enter username")
login_pass = gr.Textbox(label="Password", type="password", placeholder="Enter password")
login_btn = gr.Button("Log In", variant="primary")
login_msg = gr.Markdown("")
# --- App page (hidden until login) ---
app_box = gr.Column(visible=False)
with app_box:
gr.Markdown("# Excel / ZIP Batch Combiner (Preserve Header Order)")
with gr.Row():
uploaded_files = gr.File(
label="Upload Multiple Excel/CSV Files",
file_types=[".xlsx", ".xls", ".csv"],
file_count="multiple"
)
uploaded_zip = gr.File(
label="Or Upload ZIP Batch",
file_types=[".zip"]
)
run_btn = gr.Button("Combine")
status = gr.Textbox(label="Status", interactive=False)
output_file = gr.File(label="Download Combined File")
error_file = gr.File(label="Download Error Report")
summary = gr.Markdown()
run_btn.click(
combine_excel,
inputs=[uploaded_files, uploaded_zip],
outputs=[status, output_file, error_file, summary]
)
# Login action
login_btn.click(
fn=do_login,
inputs=[login_user, login_pass],
outputs=[logged_in, login_msg, login_box, app_box],
)
if __name__ == "__main__":
demo.queue().launch()