Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465# Instead of adding paragraphs, do this:from docx.enum.table import WD_ALIGN_VERTICALlabels_per_page = 30cols = 3rows = 10doc = Document()for i in range(0, len(df), labels_per_page):chunk = df.iloc[i:i+labels_per_page]table = doc.add_table(rows=rows, cols=cols)table.autofit = False# Optionally set cell widths for label sheetsfor col in table.columns:for cell in col.cells:cell.width = Pt(180) # adjust as needed for your label sheetsfor idx, (_, row) in enumerate(chunk.iterrows()):r = idx // colsc = idx % colscell = table.cell(r, c)cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER# Build label lines as beforename = str(row.get(name_col, "")).strip()hours = row.get(hours_col, 0)bonus = row.get(bonus_col, 0) if bonus_col else 0deduction = row.get(deduct_col, 0) if deduct_col else 0total_pay = row.get(total_col, 0)lines = []lines.append(f"Name: {name}")line2 = f"Total Hours: {int(hours) if pd.notna(hours) else 0}"if format_money(bonus):line2 += f" Bonus: {format_money(bonus)}"if format_money(deduction):line2 += f" Deduction: {format_money(deduction)}"lines.append(line2)lines.append(f"Total Pay: {format_money(total_pay) or '$0'}")lines.append(f"Pay Period: {sheet_name}")cell.text = "\n".join(lines)for paragraph in cell.paragraphs:paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTERfor run in paragraph.runs:run.font.name = "Arial"run.font.size = Pt(10)paragraph.space_before = Pt(0)paragraph.space_after = Pt(0)if i + labels_per_page < len(df):doc.add_page_break()# Save as beforedoc.save(output_file)# -------- Gradio App --------with gr.Blocks() as demo:gr.Markdown("## Smart Payroll Label Generator")gr.Markdown("Upload your **Excel file (.xlsx)** and download the Word labels file formatted for ULINE/Laser labels.")excel_input = gr.File(label="Upload Excel File", file_types=[".xlsx"])output_file = gr.File(label="Download Generated Labels")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123import pandas as pdfrom docx import Documentfrom docx.shared import Ptfrom docx.enum.text import WD_PARAGRAPH_ALIGNMENTfrom docx.enum.table import WD_ALIGN_VERTICALimport gradio as grimport difflib# -------- Helper functions --------def find_best_match(target, columns):"""Find the closest matching column name using fuzzy matching."""matches = difflib.get_close_matches(target.lower(), [c.lower() for c in columns], n=1, cutoff=0.4)if matches:# Return original column with same casefor col in columns:if col.lower() == matches[0]:return colreturn Nonedef format_money(value):"""Format numbers as $X (no decimals if integer)."""if pd.isna(value) or value == 0:return Nonetry:value = float(value)return f"${int(value)}" if value.is_integer() else f"${value:.2f}"except:return None# -------- Core function --------def generate_labels(excel_file):try:# Load Excelxls = pd.ExcelFile(excel_file.name)sheet_name = xls.sheet_names[0] # use first sheetdf = pd.read_excel(excel_file.name, sheet_name=sheet_name)# Normalize column namescolumns = list(df.columns)name_col = find_best_match("DA'S NAME", columns) or find_best_match("Name", columns)hours_col = find_best_match("Total Hours", columns)bonus_col = find_best_match("Bonus", columns)deduct_col = find_best_match("Deduction", columns)total_col = find_best_match("Total Pay", columns)if not all([name_col, hours_col, total_col]):raise ValueError(f"Required columns missing. Found: {columns}")# Setup label page parameterslabels_per_page = 30cols = 3rows = 10doc = Document()# Generate labels in table format: 3 x 10 per pagefor i in range(0, len(df), labels_per_page):chunk = df.iloc[i:i+labels_per_page]table = doc.add_table(rows=rows, cols=cols)table.autofit = False# Set cell width for each column (optional, adjust according to label sheet specs)for c_idx in range(cols):for r_idx in range(rows):cell = table.cell(r_idx, c_idx)cell.width = Pt(180) # You may adjust this depending on the label typefor idx, (_, row) in enumerate(chunk.iterrows()):r = idx // colsc = idx % colscell = table.cell(r, c)cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER# Build label linesname = str(row.get(name_col, "")).strip()hours = row.get(hours_col, 0)bonus = row.get(bonus_col, 0) if bonus_col else 0deduction = row.get(deduct_col, 0) if deduct_col else 0total_pay = row.get(total_col, 0)# Skip invalid namesif not name or name.lower() in ("nan", "none"):continuelines = []lines.append(f"Name: {name}")line2 = f"Total Hours: {int(hours) if pd.notna(hours) else 0}"if format_money(bonus):line2 += f" Bonus: {format_money(bonus)}"if format_money(deduction):line2 += f" Deduction: {format_money(deduction)}"lines.append(line2)lines.append(f"Total Pay: {format_money(total_pay) or '$0'}")lines.append(f"Pay Period: {sheet_name}")cell.text = "\n".join(lines)for paragraph in cell.paragraphs:paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTERfor run in paragraph.runs:run.font.name = "Arial"run.font.size = Pt(10)paragraph.space_before = Pt(0)paragraph.space_after = Pt(0)if i + labels_per_page < len(df):doc.add_page_break()output_file = "Generated_Labels.docx"doc.save(output_file)return output_fileexcept Exception as e:return f"❌ Error: {e}"# -------- Gradio App --------with gr.Blocks() as demo:gr.Markdown("## Smart Payroll Label Generator")gr.Markdown("Upload your **Excel file (.xlsx)** and download the Word labels file formatted for ULINE/Laser labels.")excel_input = gr.File(label="Upload Excel File", file_types=[".xlsx"])output_file = gr.File(label="Download Generated Labels")
app.py+113-55