Update app.py
Browse files2 unmodified lines34567891011121314151617181920212223242526272829308 unmodified lines394041424344456 unmodified lines52535455565758596061626364656611 unmodified lines787980818283848586878889909192939495969798991001011021031041051062 unmodified linesfrom docx.shared import Ptfrom docx.enum.text import WD_PARAGRAPH_ALIGNMENTfrom docx.enum.table import WD_ALIGN_VERTICALimport difflibfrom datetime import datetimefrom dateutil.parser import parseimport osimport gradio as gr# (Include all your helper functions here - find_best_match, format_money, is_reasonable_date, extract_pay_period_from_top_rows)def write_label_to_cell(cell, lines):cell._element.clear_content()for i, line in enumerate(lines):para = cell.add_paragraph()para.alignment = WD_PARAGRAPH_ALIGNMENT.CENTERrun = para.add_run(line)run.font.name = "Arial"run.font.size = Pt(10)para.space_before = Pt(0)para.space_after = Pt(2 if i < len(lines) - 1 else 0)cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTERdef generate_labels_gradio(excel_file):file_path = excel_file.namesheet_name = pd.ExcelFile(file_path).sheet_names[0]df = pd.read_excel(file_path, sheet_name=sheet_name, header=1)columns = list(df.columns)8 unmodified linespay_period = extract_pay_period_from_top_rows(file_path, sheet_name)if not all([name_col, regular_hours_col, total_col]):return "Error: Required columns missing. Detected columns: " + str(columns)labels_per_page = 30cols = 36 unmodified linestable = doc.add_table(rows=rows, cols=cols)table.autofit = Falsefor c_idx in range(cols):for r_idx in range(rows):cell = table.cell(r_idx, c_idx)cell.width = Pt(180)for idx, (_, row) in enumerate(chunk.iterrows()):r = idx // colsc = idx % colscell = table.cell(r, c)name = str(row.get(name_col, "")).strip()regular_hours = row.get(regular_hours_col, 0)11 unmodified linesif pd.notna(extra_shift):total_hours += float(extra_shift)lines = [f"Name: {name}",f"Total Hours: {int(total_hours)}" + (f" Bonus: {format_money(bonus)}" if format_money(bonus) else "") + (f" Deduction: {format_money(deduction)}" if format_money(deduction) else ""),f"Total Pay: {format_money(total_pay) or '$0'}",f"Pay Period: {pay_period}"]write_label_to_cell(cell, lines)if i + labels_per_page < len(df):doc.add_page_break()output_filename = "Generated_Labels.docx"doc.save(output_filename)return output_filename# Gradio interfacewith gr.Blocks() as demo:gr.Markdown("### Upload your Excel payroll file to generate label Word document")excel_input = gr.File(file_types=[".xlsx"], label="Upload Excel File")output_file = gr.File(label="Download Generated Labels")btn = gr.Button("Generate Labels")btn.click(fn=generate_labels_gradio, inputs=excel_input, outputs=output_file)demo.launch()2 unmodified lines3456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172738 unmodified lines828384858687886 unmodified lines959697989910010110210310410510610711 unmodified lines1191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581592 unmodified linesfrom docx.shared import Ptfrom docx.enum.text import WD_PARAGRAPH_ALIGNMENTfrom docx.enum.table import WD_ALIGN_VERTICALfrom datetime import datetimefrom dateutil.parser import parseimport difflibimport osimport tempfileimport gradio as grdef find_best_match(target, columns):str_columns = [str(c) for c in columns]matches = difflib.get_close_matches(target.lower(), [c.lower() for c in str_columns], n=1, cutoff=0.4)if matches:for col in str_columns:if col.lower() == matches[0]:return colreturn Nonedef format_money(value):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 Nonedef is_reasonable_date(dt, current_year=None):if not current_year:current_year = datetime.now().yearif dt.year < current_year - 2 or dt.year > current_year + 2:return Falseif dt.year < 1900:return Falsereturn Truedef extract_pay_period_from_top_rows(file_path, sheet_name, rows_to_check=3):df_raw = pd.read_excel(file_path, sheet_name=sheet_name, header=None)dates_found = []for row_idx in range(rows_to_check):for val in df_raw.iloc[row_idx].values:if pd.isna(val):continuedt = Nonetry:if isinstance(val, (pd.Timestamp, datetime)):dt = val.date() if hasattr(val, 'date') else valelse:dt = parse(str(val), fuzzy=False).date()if is_reasonable_date(dt):dates_found.append(dt)except Exception:continueif not dates_found:return "Pay Period Unknown"min_date = min(dates_found)max_date = max(dates_found)fmt = "%d %b"return f"{min_date.strftime(fmt)} - {max_date.strftime(fmt)}"def generate_labels(file_obj):file_path = file_obj.namesheet_name = pd.ExcelFile(file_path).sheet_names[0]df = pd.read_excel(file_path, sheet_name=sheet_name, header=1)columns = list(df.columns)8 unmodified linespay_period = extract_pay_period_from_top_rows(file_path, sheet_name)if not all([name_col, regular_hours_col, total_col]):raise ValueError(f"Error: Required columns missing. Detected columns: {columns}")labels_per_page = 30cols = 36 unmodified linestable = doc.add_table(rows=rows, cols=cols)table.autofit = Falsefor idx, (_, row) in enumerate(chunk.iterrows()):r = idx // colsc = idx % colsif r >= rows:continuecell = table.cell(r, c)cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTERname = str(row.get(name_col, "")).strip()regular_hours = row.get(regular_hours_col, 0)11 unmodified linesif pd.notna(extra_shift):total_hours += float(extra_shift)lines = []lines.append(f"Name: {name}")line2 = f"Total Hours: {int(total_hours)}"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: {pay_period}")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)if i + labels_per_page < len(df):doc.add_page_break()tmpdir = tempfile.mkdtemp()output_path = os.path.join(tmpdir, "Generated_Labels.docx")doc.save(output_path)return output_path# Gradio Interfacedemo = gr.Interface(fn=generate_labels,inputs=gr.File(label="Upload Excel File", file_types=[".xlsx"]),outputs=gr.File(label="Download Labels DOCX"),title="Payroll Labels Generator",description="Upload your payroll Excel sheet and generate printable Word labels.")if __name__ == "__main__":demo.launch()
app.py+95-42