PiyaJewpongpipat commited on
Commit
d2d1973
·
verified ·
1 Parent(s): 7463a69

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +152 -121
app.py CHANGED
@@ -9,38 +9,47 @@ import gradio as gr
9
  SUPPORTED_EXT = {".xlsx", ".xls", ".csv"}
10
 
11
 
12
- # -------------------------------------------------
13
- # HEADER AUTO-DETECTION
14
- # -------------------------------------------------
15
- def detect_header_row(path: Path, preview_rows: int = 25):
16
  if path.suffix.lower() in [".xlsx", ".xls"]:
17
- preview = pd.read_excel(path, header=None, nrows=preview_rows, dtype=str)
18
- else:
19
- preview = pd.read_csv(path, header=None, nrows=preview_rows, dtype=str, engine="python")
20
 
21
- best_row = 0
22
- best_score = -999
23
 
24
- for i in range(len(preview)):
25
- row = preview.iloc[i].fillna("").astype(str)
26
- non_empty = row[row.str.strip() != ""]
27
  if len(non_empty) < 2:
28
  continue
29
 
30
- numeric_ratio = sum(non_empty.str.replace(",", "").str.isnumeric()) / len(non_empty)
31
- unique_ratio = len(set(non_empty)) / len(non_empty)
 
 
 
 
 
 
 
32
 
33
- score = (len(non_empty) * 2) + (unique_ratio * 5) - (numeric_ratio * 8)
 
34
 
 
35
  if score > best_score:
36
- best_score = score
37
- best_row = i
38
 
39
  return best_row
40
 
41
 
42
- def read_with_auto_header(path: Path):
43
- header_row = detect_header_row(path)
 
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
- # RENAME UNKNOWN COLUMNS
55
- # -------------------------------------------------
56
- def rename_unknown_columns(df, counter_start):
57
- counter = counter_start
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{counter}"
66
  created.append(name)
67
- counter += 1
68
-
69
  new_cols.append(name)
70
 
71
  df.columns = new_cols
72
- return df, counter, created
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
- return str(x).strip() == ""
 
85
 
86
- empty_count = temp.apply(lambda r: sum(is_empty(v) for v in r), axis=1)
87
- total_cols = max(1, temp.shape[1])
88
- empty_ratio = empty_count / total_cols
89
 
90
- fully_blank = empty_count == total_cols
91
- mostly_blank = empty_ratio >= 0.8
92
 
93
  problem_mask = fully_blank | mostly_blank
94
- problems = temp.loc[problem_mask].copy()
95
-
96
- if problems.empty:
97
- return problems
98
 
99
  reasons = []
100
- for idx in problems.index:
101
- if fully_blank.loc[idx]:
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
- tmpdir = Path(tempfile.mkdtemp(prefix="combine_"))
 
 
 
 
122
  paths = []
123
 
124
- # Collect multiple files
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
- # Collect ZIP files
134
- if zip_file:
135
- with zipfile.ZipFile(zip_file, "r") as z:
 
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
- if not paths:
147
- return "No supported files found.", None, None, "No valid files."
 
148
 
149
- all_dfs = []
150
- all_columns = set()
151
- unknown_counter = 1
152
- error_list = []
153
 
154
- total = len(paths)
155
- progress(0, desc="Starting...")
 
 
 
 
156
 
157
- for i, path in enumerate(paths, start=1):
 
 
 
 
 
 
 
158
 
159
- progress((i - 1) / total, desc=f"Processing {path.name}")
 
160
 
161
- df, header_row = read_with_auto_header(path)
 
 
162
 
163
- df, unknown_counter, _ = rename_unknown_columns(df, unknown_counter)
 
164
 
165
- # Detect problem rows
166
- problems = detect_problem_rows(df, path.stem, header_row)
167
- if not problems.empty:
168
- error_list.append(problems)
169
 
170
- # Add dynamic File column FIRST
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"Finished {path.name}")
177
 
178
- # Combine
179
- progress(1, desc="Combining...")
180
  combined = pd.concat(all_dfs, ignore_index=True, sort=False)
181
 
182
- # Ensure File column always first
183
- ordered_columns = ["File"] + sorted([c for c in combined.columns if c != "File"])
184
- combined = combined.reindex(columns=ordered_columns)
 
 
 
185
 
186
- output_path = tmpdir / "combined_output.xlsx"
187
- combined.to_excel(output_path, index=False)
 
 
 
 
 
188
 
189
- error_path = None
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
- summary = f"""
196
- ### Batch Summary
197
- - Files processed: **{total}**
198
- - Total rows combined: **{len(combined)}**
199
- - Total columns: **{len(combined.columns)}**
200
- - Error rows detected: **{sum(len(e) for e in error_list) if error_list else 0}**
201
- """
 
 
202
 
203
- return "Done ✅", str(output_path), (str(error_path) if error_path else None), summary
204
 
205
 
206
- # -------------------------------------------------
207
- # UI
208
- # -------------------------------------------------
209
  with gr.Blocks(title="Excel Batch Combiner") as demo:
210
- gr.Markdown("# Excel / ZIP Batch Combiner")
 
 
 
 
 
 
211
 
212
  with gr.Row():
213
- files = gr.Files(label="Upload Multiple Excel/CSV Files")
214
- zip_file = gr.File(label="Or Upload ZIP Batch")
215
-
216
- run = gr.Button("Combine")
 
 
 
 
 
 
 
 
217
 
218
  status = gr.Textbox(label="Status", interactive=False)
219
- output_file = gr.File(label="Download Combined File")
220
- error_file = gr.File(label="Download Error Report")
221
- summary = gr.Markdown()
222
-
223
- run.click(
224
- combine_excel,
225
- inputs=[files, zip_file],
226
- outputs=[status, output_file, error_file, summary],
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()