PiyaJewpongpipat commited on
Commit
9c6c096
·
verified ·
1 Parent(s): aa11d3f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -76
app.py CHANGED
@@ -27,7 +27,6 @@ def _detect_header_row(preview: pd.DataFrame) -> int:
27
  if len(non_empty) < 2:
28
  continue
29
 
30
- # numeric-ish ratio
31
  numeric = 0
32
  for v in non_empty:
33
  try:
@@ -36,8 +35,6 @@ def _detect_header_row(preview: pd.DataFrame) -> int:
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)
@@ -47,7 +44,7 @@ def _detect_header_row(preview: pd.DataFrame) -> int:
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
 
@@ -60,44 +57,42 @@ def _read_with_auto_header(path: Path) -> tuple[pd.DataFrame, int]:
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
 
@@ -107,20 +102,21 @@ def _error_rows(df: pd.DataFrame, file_label: str, header_row: int) -> pd.DataFr
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,10 +125,8 @@ def _collect_inputs(files, zip_batch):
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,118 +137,116 @@ def _collect_inputs(files, zip_batch):
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()
 
27
  if len(non_empty) < 2:
28
  continue
29
 
 
30
  numeric = 0
31
  for v in non_empty:
32
  try:
 
35
  except:
36
  pass
37
  numeric_ratio = numeric / max(1, len(non_empty))
 
 
38
  unique_ratio = len(set(non_empty)) / max(1, len(non_empty))
39
 
40
  score = (len(non_empty) * 2.0) + (unique_ratio * 5.0) - (numeric_ratio * 8.0)
 
44
  return best_row
45
 
46
 
47
+ def _read_with_auto_header(path: Path):
48
  preview = _read_preview(path)
49
  header_row = _detect_header_row(preview)
50
 
 
57
 
58
 
59
  # -----------------------------
60
+ # Rename unknown columns
61
  # -----------------------------
62
+ def _rename_unknown_columns(df, start_idx):
63
  idx = start_idx
64
  new_cols = []
 
65
 
66
  for c in df.columns:
67
  name = "" if c is None else str(c).strip()
68
  if name == "" or name.lower().startswith("unnamed"):
69
  name = f"Unknown Column{idx}"
 
70
  idx += 1
71
  new_cols.append(name)
72
 
73
  df.columns = new_cols
74
+ return df, idx
75
 
76
 
77
  # -----------------------------
78
+ # Error detection
79
  # -----------------------------
80
+ def _error_rows(df, file_label, header_row):
81
  def is_empty(x):
82
  if pd.isna(x):
83
  return True
84
+ return str(x).strip() == ""
 
85
 
86
+ empty_counts = df.apply(lambda r: sum(is_empty(v) for v in r), axis=1)
87
  total_cols = max(1, df.shape[1])
88
  empty_ratio = empty_counts / total_cols
89
 
90
  fully_blank = empty_counts == total_cols
91
+ mostly_blank = empty_ratio >= 0.8
92
+
93
+ mask = fully_blank | mostly_blank
94
+ err = df.loc[mask].copy()
95
 
 
 
96
  if err.empty:
97
  return err
98
 
 
102
  reasons.append("Fully blank row")
103
  else:
104
  reasons.append("Mostly blank row (>=80% empty)")
105
+
106
  err.insert(0, "ErrorReason", reasons)
107
  err.insert(0, "DetectedHeaderRow", header_row)
108
  err.insert(0, "File", file_label)
109
+
110
  return err
111
 
112
 
113
  # -----------------------------
114
+ # Collect files
115
  # -----------------------------
116
  def _collect_inputs(files, zip_batch):
117
+ tmpdir = Path(tempfile.mkdtemp(prefix="combine_"))
118
  paths = []
119
 
 
120
  if files:
121
  for f in files:
122
  src = Path(f)
 
125
  os.replace(src, dst)
126
  paths.append(dst)
127
 
 
128
  if zip_batch:
129
+ with zipfile.ZipFile(zip_batch, "r") as z:
 
130
  for info in z.infolist():
131
  if info.is_dir():
132
  continue
 
137
  dst.write(src.read())
138
  paths.append(out)
139
 
 
140
  unique = {p.name: p for p in paths}
141
  return tmpdir, sorted(unique.values(), key=lambda x: x.name)
142
 
143
 
144
  # -----------------------------
145
+ # Main combine
146
  # -----------------------------
147
  def combine_excel(uploaded_files, uploaded_zip, progress=gr.Progress()):
148
+
149
  if not uploaded_files and not uploaded_zip:
150
+ return "Please upload files or ZIP.", None, None, "No files uploaded."
151
 
152
  tmpdir, input_paths = _collect_inputs(uploaded_files, uploaded_zip)
153
+
154
  if not input_paths:
155
+ return "No supported files found.", None, None, "No valid files."
156
 
157
  unknown_counter = 1
158
  all_dfs = []
159
+ final_column_order = []
160
  error_frames = []
161
 
162
  total = len(input_paths)
163
  progress(0, desc="Starting...")
164
 
165
  for i, path in enumerate(input_paths, start=1):
 
 
166
 
167
+ progress((i - 1) / total, desc=f"Reading {path.name}")
 
168
 
169
+ df, header_row = _read_with_auto_header(path)
170
+ df, unknown_counter = _rename_unknown_columns(df, unknown_counter)
171
+
172
+ # detect errors
173
+ err = _error_rows(df, path.stem, header_row)
174
  if not err.empty:
175
  error_frames.append(err)
176
 
177
+ # Insert File column first
178
  df.insert(0, "File", path.stem)
179
 
180
+ # Establish column order logic
181
+ if i == 1:
182
+ final_column_order = list(df.columns)
183
+ else:
184
+ for col in df.columns:
185
+ if col not in final_column_order:
186
+ final_column_order.append(col)
187
+
188
  all_dfs.append(df)
189
 
190
+ progress(i / total, desc=f"Processed {path.name}")
191
+
192
+ progress(1, desc="Combining...")
193
 
 
194
  combined = pd.concat(all_dfs, ignore_index=True, sort=False)
195
 
196
+ # Apply preserved column order
197
+ combined = combined.reindex(columns=final_column_order)
 
198
 
199
+ output_path = tmpdir / "combined_output.xlsx"
200
+ combined.to_excel(output_path, index=False)
201
 
202
+ error_path = None
203
+ error_count = 0
204
  if error_frames:
205
  errors = pd.concat(error_frames, ignore_index=True, sort=False)
206
+ error_count = len(errors)
207
+ error_path = tmpdir / "error_report.xlsx"
208
+ errors.to_excel(error_path, index=False)
209
 
210
+ summary = f"""
211
+ ### Batch Summary
212
+ - Files processed: **{total}**
213
+ - Total rows: **{len(combined)}**
214
+ - Total columns: **{len(combined.columns)}**
215
+ - Error rows detected: **{error_count}**
216
+ """
217
 
218
+ return "Done ✅", str(output_path), (str(error_path) if error_path else None), summary
 
 
 
 
 
 
 
 
 
 
219
 
220
 
221
  # -----------------------------
222
+ # UI
223
  # -----------------------------
224
  with gr.Blocks(title="Excel Batch Combiner") as demo:
225
+ gr.Markdown("# Excel / ZIP Batch Combiner (Preserve Header Order)")
 
 
 
 
 
 
226
 
227
  with gr.Row():
228
  uploaded_files = gr.File(
229
  label="Upload Multiple Excel/CSV Files",
230
  file_types=[".xlsx", ".xls", ".csv"],
231
+ file_count="multiple"
232
  )
233
+
234
  uploaded_zip = gr.File(
235
  label="Or Upload ZIP Batch",
236
+ file_types=[".zip"]
 
237
  )
238
 
239
  run_btn = gr.Button("Combine")
240
 
241
  status = gr.Textbox(label="Status", interactive=False)
242
+ output_file = gr.File(label="Download Combined File")
243
+ error_file = gr.File(label="Download Error Report")
244
+ summary = gr.Markdown()
245
 
246
  run_btn.click(
247
+ combine_excel,
248
  inputs=[uploaded_files, uploaded_zip],
249
+ outputs=[status, output_file, error_file, summary]
250
  )
251
 
252
  demo.launch()