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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
+
import io, math, os, tempfile, subprocess
|
| 3 |
+
from PIL import Image, ImageDraw, ImageFont, ImageOps
|
| 4 |
+
from docxtpl import DocxTemplate
|
| 5 |
+
from pypdf import PdfWriter, PdfReader
|
| 6 |
+
from datetime import date
|
| 7 |
+
|
| 8 |
+
# ββ 1. CONFIG & ASSETS ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 9 |
+
st.set_page_config(page_title="Wercore | Pest Control Engine", page_icon="πͺ³", layout="wide")
|
| 10 |
+
|
| 11 |
+
st.markdown("""
|
| 12 |
+
<style>
|
| 13 |
+
[data-testid="stLogo"] {
|
| 14 |
+
height: 6rem !important;
|
| 15 |
+
object-fit: contain !important;
|
| 16 |
+
}
|
| 17 |
+
</style>
|
| 18 |
+
""", unsafe_allow_html=True)
|
| 19 |
+
st.logo("WERCORE logo.png")
|
| 20 |
+
|
| 21 |
+
if not st.session_state.get("authenticated", False):
|
| 22 |
+
st.error("π **Access Denied.** Please log in through the main Wercore Portal.")
|
| 23 |
+
st.stop()
|
| 24 |
+
|
| 25 |
+
TPL_PEST = "Inspection_Template_Pest.docx"
|
| 26 |
+
|
| 27 |
+
def convert_to_pdf(docx_path, output_dir):
|
| 28 |
+
subprocess.run(["libreoffice", "--headless", "--convert-to", "pdf", docx_path, "--outdir", output_dir], check=True)
|
| 29 |
+
|
| 30 |
+
def load_font(size):
|
| 31 |
+
try: return ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", size)
|
| 32 |
+
except: return ImageFont.load_default()
|
| 33 |
+
|
| 34 |
+
def build_photo_grid_pages(all_photos, photos_per_page=4):
|
| 35 |
+
n = math.ceil(len(all_photos) / photos_per_page)
|
| 36 |
+
return [all_photos[i * photos_per_page:(i + 1) * photos_per_page] for i in range(n)]
|
| 37 |
+
|
| 38 |
+
def photo_grid_to_pdf_bytes(page_photos, page_num, total_pages, client_name, date_str):
|
| 39 |
+
PAGE_W, PAGE_H = 1240, 1754
|
| 40 |
+
PADDING, HEADER_H, FOOTER_H, CELL_GAP = 40, 70, 40, 20
|
| 41 |
+
canvas = Image.new("RGB", (PAGE_W, PAGE_H), (255, 255, 255))
|
| 42 |
+
draw = ImageDraw.Draw(canvas)
|
| 43 |
+
font_header, font_footer, font_wm = load_font(28), load_font(20), load_font(24)
|
| 44 |
+
|
| 45 |
+
draw.rectangle([(0, 0), (PAGE_W, HEADER_H)], fill=(0, 84, 166))
|
| 46 |
+
draw.text((PADDING, 18), f"Photo Documentation β {client_name} | {date_str}", font=font_header, fill=(255, 255, 255))
|
| 47 |
+
|
| 48 |
+
grid_top = HEADER_H + PADDING
|
| 49 |
+
grid_bot = PAGE_H - FOOTER_H - PADDING
|
| 50 |
+
cell_w = (PAGE_W - 2 * PADDING - CELL_GAP) // 2
|
| 51 |
+
cell_h = (grid_bot - grid_top - CELL_GAP) // 2
|
| 52 |
+
|
| 53 |
+
for idx, photo in enumerate(page_photos):
|
| 54 |
+
col, row = idx % 2, idx // 2
|
| 55 |
+
x0 = PADDING + col * (cell_w + CELL_GAP)
|
| 56 |
+
y0 = grid_top + row * (cell_h + CELL_GAP)
|
| 57 |
+
|
| 58 |
+
img = Image.open(io.BytesIO(photo)).convert("RGB")
|
| 59 |
+
img = ImageOps.exif_transpose(img)
|
| 60 |
+
img = ImageOps.fit(img, (cell_w, cell_h), Image.LANCZOS)
|
| 61 |
+
canvas.paste(img, (x0, y0))
|
| 62 |
+
|
| 63 |
+
wm_margin = 15
|
| 64 |
+
bbox = draw.textbbox((0, 0), date_str, font=font_wm)
|
| 65 |
+
wm_x = x0 + cell_w - (bbox[2] - bbox[0]) - wm_margin
|
| 66 |
+
wm_y = y0 + cell_h - (bbox[3] - bbox[1]) - wm_margin
|
| 67 |
+
draw.text((wm_x + 2, wm_y + 2), date_str, font=font_wm, fill=(0, 0, 0, 180))
|
| 68 |
+
draw.text((wm_x, wm_y), date_str, font=font_wm, fill=(255, 255, 255, 230))
|
| 69 |
+
|
| 70 |
+
draw.text((PADDING, PAGE_H - FOOTER_H + 8), "CONFIDENTIAL β Pest Control Compliance Report", font=font_footer, fill=(150, 150, 150))
|
| 71 |
+
draw.text((PAGE_W - 180, PAGE_H - FOOTER_H + 8), f"Page {page_num} of {total_pages}", font=font_footer, fill=(150, 150, 150))
|
| 72 |
+
buf = io.BytesIO()
|
| 73 |
+
canvas.save(buf, format="PDF")
|
| 74 |
+
return buf.getvalue()
|
| 75 |
+
|
| 76 |
+
# ββ 2. UI: SIDEBAR ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 77 |
+
with st.sidebar:
|
| 78 |
+
st.markdown("### Project Details")
|
| 79 |
+
client_name = st.text_input("π’ Client Name*", placeholder="e.g. Al Noor Properties")
|
| 80 |
+
building_name = st.text_input("π Building Name & Location*", placeholder="e.g. Factory - DIP, Dubai")
|
| 81 |
+
|
| 82 |
+
st.markdown("---")
|
| 83 |
+
service_date = st.date_input("π
Date of Service*", value=date.today(), format="DD/MM/YYYY")
|
| 84 |
+
date_str = service_date.strftime("%d-%m-%Y")
|
| 85 |
+
|
| 86 |
+
st.markdown("---")
|
| 87 |
+
handwritten_files = st.file_uploader("Upload physical reports (PDFs only - Max 5MB)*", type=["pdf", "PDF"], accept_multiple_files=True)
|
| 88 |
+
if handwritten_files:
|
| 89 |
+
for f in handwritten_files:
|
| 90 |
+
if f.size > 5 * 1024 * 1024:
|
| 91 |
+
st.error(f"β '{f.name}' exceeds the 5MB limit. Please compress it.")
|
| 92 |
+
|
| 93 |
+
# ββ 3. UI: DATA ENTRY βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 94 |
+
st.header("Pest Control Report Maker")
|
| 95 |
+
st.caption("Compliance & Inspection Documentation System")
|
| 96 |
+
|
| 97 |
+
service_type = st.text_input("Type of Service", value="General Pest Control Services")
|
| 98 |
+
|
| 99 |
+
col1, col2 = st.columns(2)
|
| 100 |
+
with col1:
|
| 101 |
+
service_done = st.text_area("Services Done By Wercore Team*", height=150,
|
| 102 |
+
placeholder="e.g. General Pest Control service done in Entire area of factory.\nRBS boxes cleaned and refilled with rodenticide.")
|
| 103 |
+
with col2:
|
| 104 |
+
remarks = st.text_area("Site Specific Remarks", height=150,
|
| 105 |
+
placeholder="e.g. Please remove the stagnant water to prevent mosquito breeding.")
|
| 106 |
+
|
| 107 |
+
st.markdown("### πΈ Site Photographs")
|
| 108 |
+
uploaded_photos = st.file_uploader("Upload up to 20+ images (Max 2MB each)", type=["jpg","jpeg","png"], accept_multiple_files=True)
|
| 109 |
+
|
| 110 |
+
if uploaded_photos:
|
| 111 |
+
for f in uploaded_photos:
|
| 112 |
+
if f.size > 2 * 1024 * 1024:
|
| 113 |
+
st.error(f"β Image '{f.name}' exceeds the 2MB limit.")
|
| 114 |
+
|
| 115 |
+
st.markdown("---")
|
| 116 |
+
|
| 117 |
+
# Hardcoded Option 2 Recommendations
|
| 118 |
+
recommendation_text = """To ensure complete and lasting pest eradication, Wercore strongly recommends that the clientβs team implements the following measures:
|
| 119 |
+
β’ Physical Proofing: Seal all exterior entry points, including structural cracks, crevices, drains, and manholes, to deny pests access.
|
| 120 |
+
β’ Sanitation: Maintain rigorous cleaning schedules and ensure the proper disposal of all waste.
|
| 121 |
+
β’ Moisture Control: Eliminate all sources of stagnant and pooling water.
|
| 122 |
+
|
| 123 |
+
Disclaimer: Wercoreβs service guarantee is contingent upon the execution of these recommendations. We cannot be held responsible for continuous infestations resulting from negligence in environmental and structural maintenance."""
|
| 124 |
+
|
| 125 |
+
# ββ 4. ENGINE: MASTER PDF ASSEMBLY ββββββββββββββββββββββββββββββββββββββββββββ
|
| 126 |
+
notification_zone = st.empty()
|
| 127 |
+
|
| 128 |
+
if st.button("π Generate Pest Control Report", type="primary", use_container_width=True):
|
| 129 |
+
errors = []
|
| 130 |
+
if not client_name: errors.append("Client Name is missing.")
|
| 131 |
+
if not building_name: errors.append("Building Name is missing.")
|
| 132 |
+
if not service_done: errors.append("Services Done details are missing.")
|
| 133 |
+
if not handwritten_files: errors.append("At least one Physical Report PDF must be uploaded.")
|
| 134 |
+
|
| 135 |
+
if handwritten_files:
|
| 136 |
+
for f in handwritten_files:
|
| 137 |
+
if f.size > 5 * 1024 * 1024: errors.append(f"Physical report '{f.name}' exceeds the 5MB limit.")
|
| 138 |
+
|
| 139 |
+
if uploaded_photos:
|
| 140 |
+
for f in uploaded_photos:
|
| 141 |
+
if f.size > 2 * 1024 * 1024: errors.append(f"Photo '{f.name}' exceeds 2MB.")
|
| 142 |
+
|
| 143 |
+
if errors:
|
| 144 |
+
with notification_zone.container():
|
| 145 |
+
st.error("β οΈ **Cannot generate report. Please fix the following issues:**")
|
| 146 |
+
for e in errors: st.error(f"β {e}")
|
| 147 |
+
st.stop()
|
| 148 |
+
|
| 149 |
+
with notification_zone.container():
|
| 150 |
+
with st.spinner("βοΈ Assembling Pest Control Dossier... Please wait."):
|
| 151 |
+
with tempfile.TemporaryDirectory() as tmp_dir:
|
| 152 |
+
|
| 153 |
+
# Render the Word Document
|
| 154 |
+
doc_context = {
|
| 155 |
+
"client_name": client_name,
|
| 156 |
+
"building_name": building_name,
|
| 157 |
+
"service_type": service_type,
|
| 158 |
+
"date_str": date_str,
|
| 159 |
+
"service_done": service_done,
|
| 160 |
+
"remarks": remarks if remarks else "No specific remarks.",
|
| 161 |
+
"recommendations": recommendation_text
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
if os.path.exists(TPL_PEST):
|
| 165 |
+
path = os.path.join(tmp_dir, "pest_report.docx")
|
| 166 |
+
doc = DocxTemplate(TPL_PEST)
|
| 167 |
+
doc.render(doc_context)
|
| 168 |
+
doc.save(path)
|
| 169 |
+
convert_to_pdf(path, tmp_dir)
|
| 170 |
+
else:
|
| 171 |
+
st.error(f"Template '{TPL_PEST}' not found in repository.")
|
| 172 |
+
st.stop()
|
| 173 |
+
|
| 174 |
+
# Process Photos into Grid
|
| 175 |
+
grid_pdfs = []
|
| 176 |
+
if uploaded_photos:
|
| 177 |
+
photo_bytes = [f.read() for f in uploaded_photos]
|
| 178 |
+
photo_pages = build_photo_grid_pages(photo_bytes, 4)
|
| 179 |
+
for idx, pg in enumerate(photo_pages):
|
| 180 |
+
grid_pdfs.append(photo_grid_to_pdf_bytes(pg, idx+1, len(photo_pages), client_name, date_str))
|
| 181 |
+
|
| 182 |
+
# Staple Everything Together
|
| 183 |
+
writer = PdfWriter()
|
| 184 |
+
|
| 185 |
+
def staple_pdf(file_source):
|
| 186 |
+
try:
|
| 187 |
+
reader = PdfReader(file_source)
|
| 188 |
+
for page in reader.pages: writer.add_page(page)
|
| 189 |
+
except Exception: pass
|
| 190 |
+
|
| 191 |
+
# 1. Add Text Report
|
| 192 |
+
staple_pdf(os.path.join(tmp_dir, "pest_report.pdf"))
|
| 193 |
+
|
| 194 |
+
# 2. Add Photo Grids
|
| 195 |
+
for pdf_bytes in grid_pdfs:
|
| 196 |
+
staple_pdf(io.BytesIO(pdf_bytes))
|
| 197 |
+
|
| 198 |
+
# 3. Add Physical Scans
|
| 199 |
+
for hw_pdf in handwritten_files:
|
| 200 |
+
hw_pdf.seek(0)
|
| 201 |
+
staple_pdf(hw_pdf)
|
| 202 |
+
|
| 203 |
+
output = io.BytesIO()
|
| 204 |
+
writer.write(output)
|
| 205 |
+
|
| 206 |
+
st.success("β
Pest Control Report generated successfully!")
|
| 207 |
+
st.download_button("β¬οΈ Download Master PDF", output.getvalue(), f"Pest_Control_{client_name.replace(' ', '_')}.pdf", "application/pdf", type="primary", use_container_width=True)
|