Spaces:
Sleeping

File size: 5,117 Bytes
f3ed5c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef24acd
f3ed5c9
 
 
ef24acd
 
f3ed5c9
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
import 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

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
            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 generate_labels(file_path):
    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)

    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 idx, (_, row) in enumerate(chunk.iterrows()):
            r = idx // cols
            c = idx % cols
            cell = table.cell(r, c)
            cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER

            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 = []
            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.CENTER
                for run in paragraph.runs:
                    run.font.name = "Arial"
                    run.font.size = Pt(10)

        if i + labels_per_page < len(df):
            doc.add_page_break()

    output_file = "Generated_Labels.docx"
    doc.save(output_file)
    return output_file

def process_excel(file):
    return generate_labels(file)

with gr.Blocks() as demo:
    gr.Markdown("## Payroll Label Generator 📑")
    file_input = gr.File(label="Upload Excel File", file_types=[".xls", ".xlsx"], type="filepath")
    output_file = gr.File(label="Download Labels", type="filepath")

    file_input.change(process_excel, inputs=file_input, outputs=output_file)

if __name__ == "__main__":
    demo.launch()