Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354from docx import Documentimport reimport tracebackimport gradio as grdef parse_docx_file(data_file_path):doc = Document(data_file_path)full_text = ' '.join(para.text.strip() for para in doc.paragraphs if para.text.strip())people = [p.strip() for p in full_text.split('\\') if p.strip()]person_list = []for person_text in people:fields = re.findall(r'([^:]+):\s*([^\n\\]+?)(?=(?:\s+\w+:|$))', person_text)person_dict = {label.strip(): value.strip() for label, value in fields}if person_dict:person_list.append(person_dict)return person_listdef fill_labels_template(payroll_path, template_path="ACE.docx", output_path="Labels_filled.docx"):try:person_list = parse_docx_file(payroll_path)if not person_list:return None, "❌ ERROR: No person data found in uploaded file!"template_doc = Document(template_path)table = template_doc.tables[0]idx = 0for row in table.rows:for cell in row.cells:if idx < len(person_list):person = person_list[idx]cell.text = ""for key, value in person.items():cell.add_paragraph(f"{key}: {value}")idx += 1else:cell.text = ""template_doc.save(output_path)return output_path, "✅ Success! Labels filled and ready."except Exception:return None, "⚠️ Exception:\n" + traceback.format_exc()with gr.Blocks() as demo:gr.Markdown("## Payroll Label Generator - Upload payroll .docx to fill ACE.docx labels")payroll_file = gr.File(label="Upload Payroll Data (.docx)", file_types=[".docx"], type="filepath")output_file = gr.File(label="Download Filled Labels", type="filepath")status = gr.Textbox(label="Status / Errors", interactive=False)generate_btn = gr.Button("Generate Labels")generate_btn.click(fill_labels_template, inputs=payroll_file, outputs=[output_file, status])if __name__ == "__main__":demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138import pandas as pdfrom docx import Documentfrom docx.shared import Ptfrom docx.enum.text import WD_PARAGRAPH_ALIGNMENTfrom docx.enum.table import WD_ALIGN_VERTICALfrom dateutil.parser import parsefrom datetime import datetimeimport difflibdef 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 format_hours(value):if pd.isna(value):return Nonetry:value = float(value)return f"{value}" if '.' in f"{value}" else f"{int(value)}"except:return Nonedef extract_pay_period_from_top_rows(df):dates_found = []for row_idx in range(3):for val in df.iloc[row_idx].values:if pd.isna(val):continuetry:dt = parse(str(val), fuzzy=False).date()if 1900 < dt.year < 2100:dates_found.append(dt)except Exception:continueif not dates_found:return "Pay Period Unknown"min_date = min(dates_found)max_date = max(dates_found)return f"{min_date.strftime('%d %b')} - {max_date.strftime('%d %b')}"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)pay_period = extract_pay_period_from_top_rows(pd.read_excel(file_path, sheet_name=sheet_name, header=None))cols = list(df.columns)name_col = find_best_match("DA'S NAME", cols)total_hours_col = find_best_match("Total Hours", cols) or find_best_match("JAXL", cols)stat_col = find_best_match("Stat", cols)training_col = find_best_match("Training", cols)bonus_col = find_best_match("Bonus", cols)deduction_col = find_best_match("Deduction", cols)total_pay_col = find_best_match("TOTAL PAY", cols)labels_per_page = 30doc = Document()table = doc.add_table(rows=10, cols=3)table.autofit = Falsefor idx, (_, row) in enumerate(df.iterrows()):r = idx // 3c = idx % 3cell = table.cell(r, c)cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTERlines = []name = str(row.get(name_col, "")).strip()if not name:continuelines.append(f"Name: {name}")# Total hours—must show decimals if presenthours_val = row.get(total_hours_col, None)hours_txt = format_hours(hours_val)if hours_txt:lines.append(f"Total Hours: {hours_txt}")# Stat (in hours, only if present)stat_val = row.get(stat_col, None)if pd.notna(stat_val) and stat_val != "":lines.append(f"Stat: {stat_val}")# Training (in money, only if present)training_val = row.get(training_col, None)tfmt = format_money(training_val)if tfmt:lines.append(f"Training: {tfmt}")# Bonus (in money format, only if present)bonus_val = row.get(bonus_col, None)bfmt = format_money(bonus_val)if bfmt:lines.append(f"Bonus: {bfmt}")# Deduction (in money format, only if present)deduction_val = row.get(deduction_col, None)dfmt = format_money(deduction_val)if dfmt:lines.append(f"Deduction: {dfmt}")# Total Paytotal_pay_val = row.get(total_pay_col, None)pfmt = format_money(total_pay_val)if pfmt:lines.append(f"Total Pay: {pfmt}")# Pay period (always append)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)# Add new page if neededif (idx + 1) % labels_per_page == 0 and idx + 1 < len(df):doc.add_page_break()output_file = "Generated_Labels.docx"doc.save(output_file)return output_file
app.py+135-51