Upload app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145import pandas as pd
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.enum.table import WD_ALIGN_VERTICAL
import difflib
from datetime import datetime
from dateutil.parser import parse
import gradio as gr
import os
def 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 col
return None
def format_money(value):
if pd.isna(value) or value == 0:
return None
try:
value = float(value)
return f"${int(value)}" if value.is_integer() else f"${value:.2f}"
except:
return None
def is_reasonable_date(dt, current_year=None):
if not current_year:
current_year = datetime.now().year
if dt.year < current_year - 2 or dt.year > current_year + 2:
return False
if dt.year < 1900:
return False
return True
def 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):
continue
dt = None
try:
if isinstance(val, (pd.Timestamp, datetime)):
dt = val.date() if hasattr(val, 'date') else val
else:
dt = parse(str(val), fuzzy=False).date()
if is_reasonable_date(dt):
dates_found.append(dt)
except Exception:
continue
if 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 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.CENTER
run = 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.CENTER
def generate_labels(excel_file):
try:
file_path = excel_file.name
sheet_name = pd.ExcelFile(file_path).sheet_names[0]
df = pd.read_excel(file_path, sheet_name=sheet_name, header=1)
columns = list(df.columns)
name_col = find_best_match("DA'S NAME", columns) or find_best_match("Name", columns)
regular_hours_col = find_best_match("REGULAR HOURS", columns)
extra_shift_col = find_best_match("EXTRA SHIFT", columns)
bonus_col = find_best_match("BONUS", columns)
deduct_col = find_best_match("DEDUCTION", columns)
total_col = find_best_match("TOTAL PAY", columns)
pay_period = extract_pay_period_from_top_rows(file_path, sheet_name)
if not all([name_col, regular_hours_col, total_col]):
return f"Error: Required columns missing. Detected columns: {columns}"
labels_per_page = 30
cols = 3
rows = 10
doc = 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
for 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 // cols
c = idx % cols
cell = table.cell(r, c)
name = str(row.get(name_col, "")).strip()
regular_hours = row.get(regular_hours_col, 0)
extra_shift = row.get(extra_shift_col, 0) if extra_shift_col else 0
bonus = row.get(bonus_col, 0) if bonus_col else 0
deduction = row.get(deduct_col, 0) if deduct_col else 0
total_pay = row.get(total_col, 0)
if not name or name.lower() in ("nan", "none"):
continue
total_hours = 0
if pd.notna(regular_hours):
total_hours += float(regular_hours)
if 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_file = "Generated_Labels.docx"
doc.save(output_file)
return output_file
except Exception as e:
import traceback
return f"Error: {str(e)}\n{traceback.format_exc()}"
import gradio as gr
demo = gr.Interface(
fn=generate_labels,
inputs=gr.File(file_types=[".xlsx"], label="Upload Excel File"),
outputs=gr.File(label="Download Word Labels File"),
title="Payroll Label Generator",
description="Upload your payroll Excel file to generate label documents."
)
demo.launch()app.pyAdded+145