rawshal commited on
Commit
f1d6092
Β·
verified Β·
1 Parent(s): 60c9272

Update pages/1_Water_Tank_Report.py

Browse files
Files changed (1) hide show
  1. pages/1_Water_Tank_Report.py +104 -115
pages/1_Water_Tank_Report.py CHANGED
@@ -9,15 +9,18 @@ from dateutil.relativedelta import relativedelta
9
  # ── 1. CONFIG & ASSETS ────────────────────────────────────────────────────────
10
  st.set_page_config(page_title="Wercore | Water Tank Engine", page_icon="πŸ’§", layout="wide")
11
 
 
 
 
12
  # ── SECURITY CHECK ──
13
  if not st.session_state.get("authenticated", False):
14
  st.error("πŸ”’ **Access Denied.** Please log in through the main Wercore Portal.")
15
  st.stop()
16
 
17
  TPL_COVER = "Cover_Template.docx"
18
- TPL_INSPECTION = "Inspction Report.docx" # Updated to match your new filename
19
  TPL_WARRANTY = "Warranty_Template.docx"
20
- TPL_JOB = "Job_Completion_Template.docx" # Ensure your recovered file is named exactly this
21
  STATIC_DM_CERT = "DM_Certificate.pdf"
22
  STATIC_MSDS = "MSDS.pdf"
23
 
@@ -39,7 +42,7 @@ def photo_grid_to_pdf_bytes(page_photos, page_num, total_pages, client_name, dat
39
  draw = ImageDraw.Draw(canvas)
40
  font_header, font_footer, font_caption, font_wm = load_font(28), load_font(20), load_font(22), load_font(24)
41
 
42
- draw.rectangle([(0, 0), (PAGE_W, HEADER_H)], fill=(0, 84, 166)) # Wercore Navy Header
43
  draw.text((PADDING, 18), f"Photo Documentation β€” {client_name} | {date_str}", font=font_header, fill=(255, 255, 255))
44
 
45
  caption_h = 35
@@ -74,8 +77,6 @@ def photo_grid_to_pdf_bytes(page_photos, page_num, total_pages, client_name, dat
74
 
75
  # ── 3. UI: SIDEBAR ────────────────────────────────────────────────────────────
76
  with st.sidebar:
77
- st.image("WERCORE logo.png", use_container_width=True)
78
- st.markdown("---")
79
  st.markdown("### Project Details")
80
  client_name = st.text_input("🏒 Client Name*", placeholder="e.g. Al Noor Properties")
81
  authorized_person = st.text_input("πŸ‘€ Authorized Person*", placeholder="e.g. Afzal Rahman")
@@ -100,10 +101,9 @@ with st.sidebar:
100
  handwritten_files = st.file_uploader("Upload physical reports (PDFs only)*", type=["pdf", "PDF"], accept_multiple_files=True)
101
 
102
  # ── 4. UI: TANK ENGINEERING DATA ──────────────────────────────────────────────
103
- st.header("Water Tank Cleaning Engine")
104
  st.caption("Compliance & Inspection Documentation System")
105
 
106
- # Dictionary of default states based on Workout.txt
107
  default_tank = {
108
  "name": "Roof Tank 1", "capacity": 10000, "ph": 6.7, "tds": 110, "chemical": "HygienX Water Tank Cleaner",
109
  "type": "GRP Panel", "pipe": "UPVC", "drain": True, "lid": True, "valves": True, "pumps": True,
@@ -118,12 +118,10 @@ if "tanks" not in st.session_state:
118
  for i, tank in enumerate(st.session_state.tanks):
119
  with st.expander(f"πŸ›’οΈ {tank['name']}", expanded=True):
120
 
121
- # 4.1 Basic Info
122
  c1, c2 = st.columns([2, 1])
123
  tank["name"] = c1.text_input("Tank Name / Location*", tank["name"], key=f"n_{i}")
124
  tank["capacity"] = c2.number_input("Capacity (USG)*", 0, 500000, tank["capacity"], step=100, key=f"cap_{i}")
125
 
126
- # 4.2 Hardware & Testing
127
  c_hw1, c_hw2, c_hw3, c_hw4 = st.columns(4)
128
  tank["type"] = c_hw1.selectbox("Tank Type", ["GRP Panel", "Concrete", "Molded Fiber", "Steel", "Other"], index=["GRP Panel", "Concrete", "Molded Fiber", "Steel", "Other"].index(tank["type"]), key=f"type_{i}")
129
  tank["pipe"] = c_hw2.selectbox("Pipe Type", ["UPVC", "Galvanized", "Stainless Steel", "Copper", "Other"], index=["UPVC", "Galvanized", "Stainless Steel", "Copper", "Other"].index(tank["pipe"]), key=f"pipe_{i}")
@@ -149,7 +147,6 @@ for i, tank in enumerate(st.session_state.tanks):
149
 
150
  st.markdown("---")
151
 
152
- # 4.3 Condition Matrix
153
  col_b, col_a = st.columns(2)
154
  with col_b:
155
  st.markdown("πŸ”΄ **BEFORE CLEANING**")
@@ -170,7 +167,7 @@ for i, tank in enumerate(st.session_state.tanks):
170
  st.markdown("🟒 **AFTER CLEANING**")
171
  tank["a_water"] = st.selectbox("Quantity of Water", ["Empty", "Quarter", "Half", "Full"], index=["Empty", "Quarter", "Half", "Full"].index(tank["a_water"]), key=f"aw_{i}")
172
  tank["a_cond"] = st.selectbox("Condition of Water", ["Clean", "Dirty", "Very Dirty"], index=["Clean", "Dirty", "Very Dirty"].index(tank["a_cond"]), key=f"ac_{i}")
173
- st.info("βœ… *All contaminants (Bio-Film, Sediments, Algae, Mould, Rust) are automatically set to 'No' for the final report.*")
174
  st.file_uploader(f"After Photos (1 or 2 max)*", type=["jpg","jpeg","png"], accept_multiple_files=True, key=f"a_img_{i}")
175
 
176
  if st.button("βž• Add Another Tank"):
@@ -182,6 +179,9 @@ if st.button("βž• Add Another Tank"):
182
  st.markdown("---")
183
 
184
  # ── 5. ENGINE: MASTER PDF ASSEMBLY ────────────────────────────────────────────
 
 
 
185
  if st.button("πŸš€ Generate Master Report", type="primary", use_container_width=True):
186
 
187
  errors = []
@@ -200,114 +200,103 @@ if st.button("πŸš€ Generate Master Report", type="primary", use_container_width=
200
  if after_count not in [1, 2]: errors.append(f"Tank '{t['name']}' requires 1 or 2 'After' photos (Currently has {after_count}).")
201
 
202
  if errors:
203
- st.error("⚠️ **Cannot generate report. Please fix the following issues:**")
204
- for e in errors:
205
- st.error(f"❌ {e}")
 
206
  st.stop()
207
 
208
- with st.spinner("Generating Complete Dossier..."):
209
- with tempfile.TemporaryDirectory() as tmp_dir:
210
-
211
- global_context = {
212
- "client_name": client_name, "authorized_person": authorized_person,
213
- "client_email": client_email, "project_location": project_location,
214
- "date_of_service": date_str, "expiry_date_str": expiry_date_str,
215
- "total_tanks": len(st.session_state.tanks),
216
- "dm_comments": "Cleaning has been done perfectly, according to rules & regulations of the DM Authority",
217
- "dm_recommendations": "All tanks should be cleaned bi-annually to ensure proper Hygiene and water safety. It is important to keep the storage tanks and supply lines clean to ensure free flow and to reduce possible damage to the supply line due to scaling and blockages. Neglected tanks are also the perfect breeding ground for harmful bacteria including Legionella, E-coli and TBC etc., which makes the water unfit for human use and consumption"
218
- }
219
-
220
- for key, tpl in [("cover", TPL_COVER), ("warr", TPL_WARRANTY), ("job", TPL_JOB)]:
221
- if os.path.exists(tpl):
222
- path = os.path.join(tmp_dir, f"{key}.docx")
223
- doc = DocxTemplate(tpl)
224
- doc.render(global_context)
225
- doc.save(path)
226
- convert_to_pdf(path, tmp_dir)
227
-
228
- for i, t in enumerate(st.session_state.tanks):
229
- tank_context = global_context.copy()
230
 
231
- # Format booleans into YES/NO for the Word Doc
232
- yes_no = lambda val: "YES" if val else "NO"
233
- yes_no_title = lambda val: "Yes" if val else "No"
234
-
235
- tank_context.update({
236
- "tank_name": t["name"], "capacity_usg": t["capacity"], "chemical": t["chemical"],
237
- "tank_type": t["type"], "pipe_type": t["pipe"],
238
- "ph": f"{float(t['ph']):.1f}", # Decimal Fix applied here
239
- "tds": t["tds"],
240
- "drain": yes_no(t["drain"]), "lid": yes_no(t["lid"]), "damage": yes_no(t["damage"]),
241
- "leaks": yes_no(t["leaks"]), "vent_present": yes_no_title(t["vent_present"]),
242
- "vent_installed": yes_no_title(t["vent_installed"]), "valves": yes_no(t["valves"]),
243
- "pumps": yes_no(t["pumps"]), "ladder_in": yes_no(t["ladder_in"]),
244
- "ladder_out": yes_no(t["ladder_out"]), "disinfected": t["disinfected"],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245
 
246
- # Before Cleaning
247
- "before_water": t["b_water"], "before_cond": t["b_cond"],
248
- "b_biofilm": yes_no_title(t["biofilm"]), "b_sediments": yes_no_title(t["sediments"]),
249
- "b_algae": yes_no_title(t["algae"]), "b_mould": yes_no_title(t["mould"]), "b_rust": yes_no_title(t["rust"]),
 
 
 
 
 
 
 
 
 
 
 
 
250
 
251
- # After Cleaning (Hardcoded NO)
252
- "after_water": t["a_water"], "after_cond": t["a_cond"],
253
- "a_biofilm": "No", "a_sediments": "No", "a_algae": "No", "a_mould": "No", "a_rust": "No"
254
- })
255
 
256
- if os.path.exists(TPL_INSPECTION):
257
- path = os.path.join(tmp_dir, f"insp_{i}.docx")
258
- doc = DocxTemplate(TPL_INSPECTION)
259
- doc.render(tank_context)
260
- doc.save(path)
261
- convert_to_pdf(path, tmp_dir)
262
-
263
- grid_pdfs = []
264
- for i, t in enumerate(st.session_state.tanks):
265
- tank_photos = []
266
- for lbl, state_key in [("Before Cleaning", f"b_img_{i}"), ("After Cleaning", f"a_img_{i}")]:
267
- uploaded_images = st.session_state.get(state_key)
268
- if uploaded_images:
269
- for f in uploaded_images:
270
- f.seek(0)
271
- tank_photos.append({"tank_name": t["name"], "label": lbl, "image_bytes": f.read()})
 
 
 
 
 
 
 
 
 
 
 
 
272
 
273
- if tank_photos:
274
- tank_pages = build_photo_grid_pages(tank_photos, 4)
275
- for idx, pg in enumerate(tank_pages):
276
- grid_pdfs.append(photo_grid_to_pdf_bytes(pg, idx+1, len(tank_pages), client_name, date_str))
277
-
278
- writer = PdfWriter()
279
- readers_cache = []
280
-
281
- def staple_pdf(file_source):
282
- try:
283
- if isinstance(file_source, str):
284
- if not os.path.exists(file_source): return
285
- reader = PdfReader(file_source)
286
- else:
287
- reader = PdfReader(file_source)
288
- readers_cache.append(reader)
289
- for page in reader.pages: writer.add_page(page)
290
- except Exception: pass
291
-
292
- staple_pdf(os.path.join(tmp_dir, "cover.pdf"))
293
-
294
- for i in range(len(st.session_state.tanks)):
295
- staple_pdf(os.path.join(tmp_dir, f"insp_{i}.pdf"))
296
-
297
- staple_pdf(STATIC_DM_CERT)
298
- staple_pdf(STATIC_MSDS)
299
-
300
- for pdf_bytes in grid_pdfs: staple_pdf(io.BytesIO(pdf_bytes))
301
-
302
- if handwritten_files:
303
- for hw_pdf in handwritten_files:
304
- hw_pdf.seek(0)
305
- staple_pdf(hw_pdf)
306
-
307
- staple_pdf(os.path.join(tmp_dir, "warr.pdf"))
308
- staple_pdf(os.path.join(tmp_dir, "job.pdf"))
309
-
310
- output = io.BytesIO()
311
- writer.write(output)
312
- st.success("βœ… Master Compliance Report generated successfully!")
313
- st.download_button("⬇️ Download Master PDF", output.getvalue(), f"Wercore_Report_{client_name.replace(' ', '_')}.pdf", "application/pdf", type="primary", use_container_width=True)
 
9
  # ── 1. CONFIG & ASSETS ────────────────────────────────────────────────────────
10
  st.set_page_config(page_title="Wercore | Water Tank Engine", page_icon="πŸ’§", layout="wide")
11
 
12
+ # Pins the logo to the absolute top of the sidebar above navigation!
13
+ st.logo("WERCORE logo.png")
14
+
15
  # ── SECURITY CHECK ──
16
  if not st.session_state.get("authenticated", False):
17
  st.error("πŸ”’ **Access Denied.** Please log in through the main Wercore Portal.")
18
  st.stop()
19
 
20
  TPL_COVER = "Cover_Template.docx"
21
+ TPL_INSPECTION = "Inspction Report.docx"
22
  TPL_WARRANTY = "Warranty_Template.docx"
23
+ TPL_JOB = "Job_Completion_Template.docx"
24
  STATIC_DM_CERT = "DM_Certificate.pdf"
25
  STATIC_MSDS = "MSDS.pdf"
26
 
 
42
  draw = ImageDraw.Draw(canvas)
43
  font_header, font_footer, font_caption, font_wm = load_font(28), load_font(20), load_font(22), 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
  caption_h = 35
 
77
 
78
  # ── 3. UI: SIDEBAR ────────────────────────────────────────────────────────────
79
  with st.sidebar:
 
 
80
  st.markdown("### Project Details")
81
  client_name = st.text_input("🏒 Client Name*", placeholder="e.g. Al Noor Properties")
82
  authorized_person = st.text_input("πŸ‘€ Authorized Person*", placeholder="e.g. Afzal Rahman")
 
101
  handwritten_files = st.file_uploader("Upload physical reports (PDFs only)*", type=["pdf", "PDF"], accept_multiple_files=True)
102
 
103
  # ── 4. UI: TANK ENGINEERING DATA ──────────────────────────────────────────────
104
+ st.header("Water Tank Cleaning Report Maker")
105
  st.caption("Compliance & Inspection Documentation System")
106
 
 
107
  default_tank = {
108
  "name": "Roof Tank 1", "capacity": 10000, "ph": 6.7, "tds": 110, "chemical": "HygienX Water Tank Cleaner",
109
  "type": "GRP Panel", "pipe": "UPVC", "drain": True, "lid": True, "valves": True, "pumps": True,
 
118
  for i, tank in enumerate(st.session_state.tanks):
119
  with st.expander(f"πŸ›’οΈ {tank['name']}", expanded=True):
120
 
 
121
  c1, c2 = st.columns([2, 1])
122
  tank["name"] = c1.text_input("Tank Name / Location*", tank["name"], key=f"n_{i}")
123
  tank["capacity"] = c2.number_input("Capacity (USG)*", 0, 500000, tank["capacity"], step=100, key=f"cap_{i}")
124
 
 
125
  c_hw1, c_hw2, c_hw3, c_hw4 = st.columns(4)
126
  tank["type"] = c_hw1.selectbox("Tank Type", ["GRP Panel", "Concrete", "Molded Fiber", "Steel", "Other"], index=["GRP Panel", "Concrete", "Molded Fiber", "Steel", "Other"].index(tank["type"]), key=f"type_{i}")
127
  tank["pipe"] = c_hw2.selectbox("Pipe Type", ["UPVC", "Galvanized", "Stainless Steel", "Copper", "Other"], index=["UPVC", "Galvanized", "Stainless Steel", "Copper", "Other"].index(tank["pipe"]), key=f"pipe_{i}")
 
147
 
148
  st.markdown("---")
149
 
 
150
  col_b, col_a = st.columns(2)
151
  with col_b:
152
  st.markdown("πŸ”΄ **BEFORE CLEANING**")
 
167
  st.markdown("🟒 **AFTER CLEANING**")
168
  tank["a_water"] = st.selectbox("Quantity of Water", ["Empty", "Quarter", "Half", "Full"], index=["Empty", "Quarter", "Half", "Full"].index(tank["a_water"]), key=f"aw_{i}")
169
  tank["a_cond"] = st.selectbox("Condition of Water", ["Clean", "Dirty", "Very Dirty"], index=["Clean", "Dirty", "Very Dirty"].index(tank["a_cond"]), key=f"ac_{i}")
170
+ st.info("βœ… *All contaminants are automatically set to 'No' for the final report.*")
171
  st.file_uploader(f"After Photos (1 or 2 max)*", type=["jpg","jpeg","png"], accept_multiple_files=True, key=f"a_img_{i}")
172
 
173
  if st.button("βž• Add Another Tank"):
 
179
  st.markdown("---")
180
 
181
  # ── 5. ENGINE: MASTER PDF ASSEMBLY ────────────────────────────────────────────
182
+ # We create a dedicated visual container ABOVE the button for alerts and loading spinners
183
+ notification_zone = st.empty()
184
+
185
  if st.button("πŸš€ Generate Master Report", type="primary", use_container_width=True):
186
 
187
  errors = []
 
200
  if after_count not in [1, 2]: errors.append(f"Tank '{t['name']}' requires 1 or 2 'After' photos (Currently has {after_count}).")
201
 
202
  if errors:
203
+ with notification_zone.container():
204
+ st.error("⚠️ **Cannot generate report. Please fix the following issues:**")
205
+ for e in errors:
206
+ st.error(f"❌ {e}")
207
  st.stop()
208
 
209
+ with notification_zone.container():
210
+ with st.spinner("βš™οΈ Assembling Complete Dossier... Please wait."):
211
+ with tempfile.TemporaryDirectory() as tmp_dir:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212
 
213
+ global_context = {
214
+ "client_name": client_name, "authorized_person": authorized_person,
215
+ "client_email": client_email, "project_location": project_location,
216
+ "date_of_service": date_str, "expiry_date_str": expiry_date_str,
217
+ "total_tanks": len(st.session_state.tanks),
218
+ "dm_comments": "Cleaning has been done perfectly, according to rules & regulations of the DM Authority",
219
+ "dm_recommendations": "All tanks should be cleaned bi-annually to ensure proper Hygiene and water safety. It is important to keep the storage tanks and supply lines clean to ensure free flow and to reduce possible damage to the supply line due to scaling and blockages. Neglected tanks are also the perfect breeding ground for harmful bacteria including Legionella, E-coli and TBC etc., which makes the water unfit for human use and consumption"
220
+ }
221
+
222
+ for key, tpl in [("cover", TPL_COVER), ("warr", TPL_WARRANTY), ("job", TPL_JOB)]:
223
+ if os.path.exists(tpl):
224
+ path = os.path.join(tmp_dir, f"{key}.docx")
225
+ doc = DocxTemplate(tpl)
226
+ doc.render(global_context)
227
+ doc.save(path)
228
+ convert_to_pdf(path, tmp_dir)
229
+
230
+ for i, t in enumerate(st.session_state.tanks):
231
+ tank_context = global_context.copy()
232
+ yes_no = lambda val: "YES" if val else "NO"
233
+ yes_no_title = lambda val: "Yes" if val else "No"
234
+
235
+ tank_context.update({
236
+ "tank_name": t["name"], "capacity_usg": t["capacity"], "chemical": t["chemical"],
237
+ "tank_type": t["type"], "pipe_type": t["pipe"], "ph": f"{float(t['ph']):.1f}", "tds": t["tds"],
238
+ "drain": yes_no(t["drain"]), "lid": yes_no(t["lid"]), "damage": yes_no(t["damage"]),
239
+ "leaks": yes_no(t["leaks"]), "vent_present": yes_no_title(t["vent_present"]),
240
+ "vent_installed": yes_no_title(t["vent_installed"]), "valves": yes_no(t["valves"]),
241
+ "pumps": yes_no(t["pumps"]), "ladder_in": yes_no(t["ladder_in"]),
242
+ "ladder_out": yes_no(t["ladder_out"]), "disinfected": t["disinfected"],
243
+ "before_water": t["b_water"], "before_cond": t["b_cond"],
244
+ "b_biofilm": yes_no_title(t["biofilm"]), "b_sediments": yes_no_title(t["sediments"]),
245
+ "b_algae": yes_no_title(t["algae"]), "b_mould": yes_no_title(t["mould"]), "b_rust": yes_no_title(t["rust"]),
246
+ "after_water": t["a_water"], "after_cond": t["a_cond"],
247
+ "a_biofilm": "No", "a_sediments": "No", "a_algae": "No", "a_mould": "No", "a_rust": "No"
248
+ })
249
 
250
+ if os.path.exists(TPL_INSPECTION):
251
+ path = os.path.join(tmp_dir, f"insp_{i}.docx")
252
+ doc = DocxTemplate(TPL_INSPECTION)
253
+ doc.render(tank_context)
254
+ doc.save(path)
255
+ convert_to_pdf(path, tmp_dir)
256
+
257
+ grid_pdfs = []
258
+ for i, t in enumerate(st.session_state.tanks):
259
+ tank_photos = []
260
+ for lbl, state_key in [("Before Cleaning", f"b_img_{i}"), ("After Cleaning", f"a_img_{i}")]:
261
+ uploaded_images = st.session_state.get(state_key)
262
+ if uploaded_images:
263
+ for f in uploaded_images:
264
+ f.seek(0)
265
+ tank_photos.append({"tank_name": t["name"], "label": lbl, "image_bytes": f.read()})
266
 
267
+ if tank_photos:
268
+ tank_pages = build_photo_grid_pages(tank_photos, 4)
269
+ for idx, pg in enumerate(tank_pages):
270
+ grid_pdfs.append(photo_grid_to_pdf_bytes(pg, idx+1, len(tank_pages), client_name, date_str))
271
 
272
+ writer = PdfWriter()
273
+ readers_cache = []
274
+
275
+ def staple_pdf(file_source):
276
+ try:
277
+ if isinstance(file_source, str):
278
+ if not os.path.exists(file_source): return
279
+ reader = PdfReader(file_source)
280
+ else:
281
+ reader = PdfReader(file_source)
282
+ readers_cache.append(reader)
283
+ for page in reader.pages: writer.add_page(page)
284
+ except Exception: pass
285
+
286
+ staple_pdf(os.path.join(tmp_dir, "cover.pdf"))
287
+ for i in range(len(st.session_state.tanks)): staple_pdf(os.path.join(tmp_dir, f"insp_{i}.pdf"))
288
+ staple_pdf(STATIC_DM_CERT)
289
+ staple_pdf(STATIC_MSDS)
290
+ for pdf_bytes in grid_pdfs: staple_pdf(io.BytesIO(pdf_bytes))
291
+ if handwritten_files:
292
+ for hw_pdf in handwritten_files:
293
+ hw_pdf.seek(0)
294
+ staple_pdf(hw_pdf)
295
+ staple_pdf(os.path.join(tmp_dir, "warr.pdf"))
296
+ staple_pdf(os.path.join(tmp_dir, "job.pdf"))
297
+
298
+ output = io.BytesIO()
299
+ writer.write(output)
300
 
301
+ st.success("βœ… Master Compliance Report generated successfully!")
302
+ st.download_button("⬇️ Download Master PDF", output.getvalue(), f"Wercore_Report_{client_name.replace(' ', '_')}.pdf", "application/pdf", type="primary", use_container_width=True)