import streamlit as st import io, math, os, tempfile, subprocess from PIL import Image, ImageDraw, ImageFont, ImageOps from docxtpl import DocxTemplate from pypdf import PdfWriter, PdfReader from datetime import date # ── 1. CONFIG & ASSETS ──────────────────────────────────────────────────────── st.set_page_config(page_title="Wercore | Pest Control Engine", page_icon="🪳", layout="wide") st.markdown(""" """, unsafe_allow_html=True) st.logo("WERCORE logo.png") if not st.session_state.get("authenticated", False): st.error("🔒 **Access Denied.** Please log in through the main Wercore Portal.") st.stop() TPL_PEST = "Inspection_Template_Pest.docx" def convert_to_pdf(docx_path, output_dir): subprocess.run(["libreoffice", "--headless", "--convert-to", "pdf", docx_path, "--outdir", output_dir], check=True) def load_font(size): try: return ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", size) except: return ImageFont.load_default() def build_photo_grid_pages(all_photos, photos_per_page=9): n = math.ceil(len(all_photos) / photos_per_page) return [all_photos[i * photos_per_page:(i + 1) * photos_per_page] for i in range(n)] # UPDATED: Replaced client_name with building_name in the function parameters def photo_grid_to_pdf_bytes(page_photos, page_num, total_pages, building_name, date_str): PAGE_W, PAGE_H = 595, 842 PADDING, HEADER_H, FOOTER_H, CELL_GAP = 20, 50, 25, 10 canvas = Image.new("RGB", (PAGE_W, PAGE_H), (255, 255, 255)) draw = ImageDraw.Draw(canvas) font_header = load_font(14) font_footer = load_font(8) font_wm = load_font(8) draw.rectangle([(0, 0), (PAGE_W, HEADER_H)], fill=(0, 84, 166)) # UPDATED: Header string now uses the Project/Location variable draw.text((PADDING, 15), f"{building_name} | {date_str}", font=font_header, fill=(255, 255, 255)) grid_top = HEADER_H + PADDING cell_w = (PAGE_W - 2 * PADDING - 2 * CELL_GAP) // 3 cell_h = (PAGE_H - grid_top - FOOTER_H - 2 * CELL_GAP) // 3 for idx, photo_bytes in enumerate(page_photos): col = idx % 3 row = idx // 3 x0 = PADDING + col * (cell_w + CELL_GAP) y0 = grid_top + row * (cell_h + CELL_GAP) img = Image.open(io.BytesIO(photo_bytes)).convert("RGB") try: img = ImageOps.exif_transpose(img) except Exception: pass img = ImageOps.fit(img, (cell_w, cell_h), Image.LANCZOS) canvas.paste(img, (x0, y0)) wm_margin = 5 bbox = draw.textbbox((0, 0), date_str, font=font_wm) wm_w = bbox[2] - bbox[0] wm_h = bbox[3] - bbox[1] wm_x = x0 + cell_w - wm_w - wm_margin wm_y = y0 + cell_h - wm_h - wm_margin draw.text((wm_x + 1, wm_y + 1), date_str, font=font_wm, fill=(0, 0, 0, 180)) draw.text((wm_x, wm_y), date_str, font=font_wm, fill=(255, 255, 255, 230)) draw.text((PADDING, PAGE_H - FOOTER_H + 8), "CONFIDENTIAL — Pest Control Compliance Report", font=font_footer, fill=(150, 150, 150)) draw.text((PAGE_W - 80, PAGE_H - FOOTER_H + 8), f"Page {page_num} of {total_pages}", font=font_footer, fill=(150, 150, 150)) buf = io.BytesIO() canvas.save(buf, format="PDF", resolution=72.0) return buf.getvalue() # ── 2. UI: SIDEBAR ──────────────────────────────────────────────────────────── with st.sidebar: st.markdown("### Project Details") client_name = st.text_input("🏢 Client Name*", placeholder="e.g. Al Noor Properties") building_name = st.text_input("📍 Project / Location*", placeholder="e.g. Factory - DIP, Dubai") st.markdown("---") service_date = st.date_input("📅 Date of Service*", value=date.today(), format="DD/MM/YYYY") date_str = service_date.strftime("%d-%m-%Y") st.markdown("---") handwritten_files = st.file_uploader("Upload physical reports (PDFs only - Max 5MB)", type=["pdf", "PDF"], accept_multiple_files=True) if handwritten_files: for f in handwritten_files: if f.size > 5 * 1024 * 1024: st.error(f"❌ '{f.name}' exceeds the 5MB limit. Please compress it.") # ── 3. UI: DATA ENTRY ───────────────────────────────────────────────────────── st.header("Pest Control Report Maker") st.caption("Compliance & Inspection Documentation System") service_type = st.selectbox("Type of Service", [ "General Pest control", "Rodent Control service", "General Pest control & Rodent Control service" ]) st.markdown("### Services Performed") col_s1, col_s2 = st.columns(2) gen_text = "" rodent_text = "" with col_s1: if "General" in service_type: gen_text = st.text_area( "General Pest Control Details", value="Application of residual insecticidal spraying in designated areas", height=130 ) else: st.info("General Pest Control inactive.") with col_s2: if "Rodent" in service_type: default_rodent = "1. Rodent bait stations, we have inspected all RBS boxes and filled with new rodenticide.\n2. Glue traps, we have checked and changed glue traps." rodent_text = st.text_area("Rodent Control Details", value=default_rodent, height=130) else: st.info("Rodent Control inactive.") st.markdown("### Areas Covered") area_options = [ "Entrances and lobbies", "Corridors, Staircase", "Service Rooms", "Telephone Room", "Mechanical Room", "Electrical Room", "Water meter rooms", "Garbage Chutes", "Garbage Room", "Gym", "Swimming Pool areas", "Common Toilets", "Landscaped Areas", "Garden areas", "Basement", "Drainage lines, Manholes, Gullies", "Utility rooms", "Lift lobbies and elevator pits", "All other common areas" ] selected_areas = st.multiselect("Select all areas covered during service:", area_options) st.markdown("### Site Specific Recommendations") toggle_remarks = st.toggle("Include Site Specific Remarks?") remarks_text = "" if toggle_remarks: remarks_text = st.text_area("Enter specific observations/recommendations for this site:") st.markdown("### 📸 Site Photographs") st.info("Photos are formatted 9-per-page. No upload limit.") uploaded_photos = st.file_uploader("Upload images (Max 5MB each)", type=["jpg","jpeg","png"], accept_multiple_files=True) if uploaded_photos: for f in uploaded_photos: if f.size > 5 * 1024 * 1024: st.error(f"❌ Image '{f.name}' exceeds the 5MB limit.") st.markdown("---") # ── 4. ENGINE: MASTER PDF ASSEMBLY ──────────────────────────────────────────── notification_zone = st.empty() if st.button("🚀 Generate Pest Control Report", type="primary", use_container_width=True): errors = [] if not client_name: errors.append("Client Name is missing.") if not building_name: errors.append("Building Name is missing.") if not selected_areas: errors.append("Please select at least one Area Covered.") if uploaded_photos: for f in uploaded_photos: if f.size > 5 * 1024 * 1024: errors.append(f"Photo '{f.name}' exceeds 5MB.") if errors: with notification_zone.container(): st.error("⚠️ **Cannot generate report. Please fix the following issues:**") for e in errors: st.error(f"❌ {e}") st.stop() with notification_zone.container(): with st.spinner("⚙️ Assembling Pest Control Dossier... Please wait."): with tempfile.TemporaryDirectory() as tmp_dir: areas_str = ", ".join(selected_areas) doc_context = { "client_name": client_name, "building_name": building_name, "service_type": service_type, "date_str": date_str, "show_general": "General" in service_type and bool(gen_text), "gen_text": gen_text, "show_rodent": "Rodent" in service_type and bool(rodent_text), "rodent_text": rodent_text, "areas_covered": areas_str, "show_remarks": toggle_remarks and bool(remarks_text), "remarks_text": remarks_text } if os.path.exists(TPL_PEST): path = os.path.join(tmp_dir, "pest_report.docx") doc = DocxTemplate(TPL_PEST) doc.render(doc_context) doc.save(path) convert_to_pdf(path, tmp_dir) else: st.error(f"Template '{TPL_PEST}' not found in repository.") st.stop() grid_pdfs = [] if uploaded_photos: photo_bytes = [f.getvalue() for f in uploaded_photos] photo_pages = build_photo_grid_pages(photo_bytes, 9) for idx, pg in enumerate(photo_pages): # UPDATED: Passing building_name instead of client_name to the function grid_pdfs.append(photo_grid_to_pdf_bytes(pg, idx+1, len(photo_pages), building_name, date_str)) writer = PdfWriter() def staple_pdf(file_source): try: reader = PdfReader(file_source) for page in reader.pages: writer.add_page(page) except Exception: pass staple_pdf(os.path.join(tmp_dir, "pest_report.pdf")) for pdf_bytes in grid_pdfs: staple_pdf(io.BytesIO(pdf_bytes)) if handwritten_files: for hw_pdf in handwritten_files: hw_pdf.seek(0) staple_pdf(hw_pdf) output = io.BytesIO() writer.write(output) st.success("✅ Pest Control Report generated successfully!") st.download_button("⬇️ Download Master PDF", output.getvalue(), f"Pest_Control_{client_name.replace(' ', '_')}.pdf", "application/pdf", type="primary", use_container_width=True)