File size: 8,965 Bytes
7de25d4
 
 
 
 
 
 
 
 
 
 
6e1f487
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2d1973
 
 
 
7de25d4
d2d1973
 
 
7de25d4
d2d1973
 
7de25d4
d2d1973
 
 
7de25d4
 
 
d2d1973
 
 
 
 
 
 
 
 
7de25d4
d2d1973
7de25d4
d2d1973
7de25d4
 
 
 
9c6c096
d2d1973
 
7de25d4
 
 
 
 
 
 
 
 
d2d1973
9c6c096
d2d1973
9c6c096
d2d1973
7de25d4
 
 
 
 
d2d1973
 
7de25d4
 
 
9c6c096
7de25d4
 
d2d1973
9c6c096
d2d1973
9c6c096
7de25d4
7463a69
7de25d4
9c6c096
7de25d4
9c6c096
d2d1973
 
7de25d4
d2d1973
9c6c096
 
 
 
7de25d4
d2d1973
 
7de25d4
7463a69
d2d1973
 
7463a69
 
 
9c6c096
d2d1973
 
 
9c6c096
d2d1973
7de25d4
7463a69
d2d1973
9c6c096
d2d1973
 
9c6c096
7de25d4
 
7463a69
 
7de25d4
 
 
 
 
 
d2d1973
9c6c096
7de25d4
 
 
 
 
 
 
 
 
 
d2d1973
 
7de25d4
 
d2d1973
9c6c096
d2d1973
 
 
9c6c096
7de25d4
d2d1973
9c6c096
d2d1973
9c6c096
d2d1973
 
 
9c6c096
d2d1973
7de25d4
d2d1973
 
7de25d4
d2d1973
9c6c096
7de25d4
9c6c096
 
 
 
 
d2d1973
 
7463a69
9c6c096
7de25d4
 
9c6c096
 
 
 
 
 
 
 
7de25d4
9c6c096
 
 
7de25d4
 
 
9c6c096
 
d2d1973
9c6c096
 
7de25d4
9c6c096
 
d2d1973
 
9c6c096
 
 
7de25d4
9c6c096
 
 
 
 
 
 
 
7de25d4
 
d2d1973
6e1f487
d2d1973
7de25d4
6e1f487
 
 
 
 
69bf9a5
6e1f487
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2d1973
 
6e1f487
 
 
 
 
7de25d4
 
6e1f487
 
 
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
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()