File size: 6,171 Bytes
4f33c76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193

import gradio as gr
import pandas as pd
import tempfile
import os

month_dict = {
    "January": 1, "February": 2, "March": 3, "April": 4,
    "May": 5, "June": 6, "July": 7, "August": 8,
    "September": 9, "October": 10, "November": 11, "December": 12
}

ATTENDANCE_MAP = {
    'P': 'Present',
    'WO': 'Weekend Off',
    'WFH': 'WFH',
    'A': 'Absent'
}

def format_date(date_val, col_index, start_month_num, switch_col, end_month_num):
    # Handles wrap-around of months in column headers
    if isinstance(date_val, (int, float)) or (isinstance(date_val, str) and date_val.isdigit()):
        day = int(date_val)
        if col_index < switch_col:
            month = start_month_num
        else:
            month = end_month_num
        return f'2025-{month:02d}-{day:02d}'
    return str(date_val)


def attendance_converter(
    uploaded_file,
    company_name,
    department,
    shift,
    start_month,
    end_month,
    output_format
):
    if uploaded_file is None:
        return None

    with tempfile.NamedTemporaryFile(delete=False, suffix='.xlsx') as tmp:
        tmp.write(uploaded_file)  # <-- fix is here!
        tmp_path = tmp.name

    df = pd.read_excel(tmp_path)
    os.unlink(tmp_path)
    date_cols = df.columns[4:]
    output_rows = []
    auto_id = 81
    switch_col = 11  # Adjust if your date columns change!
    start_month_num = month_dict[start_month]
    end_month_num = month_dict[end_month]

    for _, row in df.iterrows():
        emp_id = row['Emp.ID']
        emp_name = row["Employee's Name"]
        for date_idx, date_col in enumerate(date_cols):
            code = str(row[date_col]).strip()
            status = ATTENDANCE_MAP.get(code, '')
            if not status:
                continue
            attendance_date = format_date(date_col, date_idx, start_month_num, switch_col, end_month_num)

            # --- Skip Weekend Off ---
            if status == 'Weekend Off':
                continue

            working_hours = 0.0
            in_time = ''
            out_time = ''
            leave_type = ''

            if status == 'Present':
                working_hours = 8.01
                in_time = f"{attendance_date} 10:01:01"
                out_time = f"{attendance_date} 18:01:29"
            elif status == 'WFH':
                status = "On Leave"
                leave_type = "Work From Home"
                working_hours = 8.0

            output_rows.append({
                "ID": f'HR-ATT-2025-000{auto_id}',
                "Series": "HR-ATT-.YYYY.-",
                "Employee": emp_id,
                "Status": status,
                "Attendance Date": attendance_date,
                "Company": company_name,
                "Employee Name": emp_name,
                "Working Hours": working_hours,
                "Leave Type": leave_type,
                "Leave Application": "",
                "Department": department,
                "Shift": shift,
                "In Time": in_time,
                "Out Time": out_time
            })
            auto_id += 1

    out_df = pd.DataFrame(output_rows)

    if output_format == "Excel (.xlsx)":
        with tempfile.NamedTemporaryFile(delete=False, suffix='.xlsx') as out_buf:
            out_df.to_excel(out_buf.name, index=False)
            out_buf.seek(0)
            data = out_buf.read()
            filename = "attendance_converted.xlsx"
        os.unlink(out_buf.name)
        return (filename, data)
    else:
        with tempfile.NamedTemporaryFile(delete=False, suffix='.csv') as out_buf:
            out_df.to_csv(out_buf.name, index=False)
            out_buf.seek(0)
            data = out_buf.read()
            filename = "attendance_converted.csv"
        os.unlink(out_buf.name)
        return (filename, data)

# --------------- Gradio UI -----------------

def gradio_ui():
    with gr.Blocks() as demo:
        gr.Markdown(
            """
            # Attendance Converter

            1. Upload your attendance Excel file (in the original format).  
            2. Select start and end month.  
            3. Choose output format.  
            4. Click Convert and download your file.
            """
        )

        with gr.Row():
            company_name = gr.Textbox(label="Company Name", value="Omkara Infotech Pvt Ltd")
            department = gr.Textbox(label="Department (optional)", value="")
            shift = gr.Textbox(label="Shift", value="Day Shift")

        with gr.Row():
            start_month = gr.Dropdown(
                choices=list(month_dict.keys()), value="May", label="Start Month"
            )
            end_month = gr.Dropdown(
                choices=list(month_dict.keys()), value="June", label="End Month"
            )

        output_format = gr.Radio(
            ["Excel (.xlsx)", "CSV (.csv)"],
            label="Download Format",
            value="Excel (.xlsx)"
        )

        uploaded_file = gr.File(label="Upload Attendance Excel (.xlsx)", type="binary")

        convert_btn = gr.Button("Convert & Download")

        file_output = gr.File(label="Download Converted File")

        def wrap_attendance_converter(uploaded_file, company_name, department, shift, start_month, end_month, output_format):
            result = attendance_converter(
                uploaded_file,
                company_name,
                department,
                shift,
                start_month,
                end_month,
                output_format
            )
            if result is None:
                return None
            filename, data = result
            # Return file path for gr.File output
            with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(filename)[1]) as temp_f:
                temp_f.write(data)
                temp_f.flush()
                return temp_f.name

        convert_btn.click(
            wrap_attendance_converter,
            inputs=[uploaded_file, company_name, department, shift, start_month, end_month, output_format],
            outputs=file_output
        )

    return demo

# Run the app
if __name__ == "__main__":
    demo = gradio_ui()
    demo.launch(share=True)