rawshal commited on
Commit
e29514a
Β·
verified Β·
1 Parent(s): 0a6f2a9

Update pages/1_Water_Tank.py

Browse files
Files changed (1) hide show
  1. pages/1_Water_Tank.py +19 -28
pages/1_Water_Tank.py CHANGED
@@ -10,7 +10,7 @@ from dateutil.relativedelta import relativedelta
10
  st.set_page_config(page_title="Wercore | Water Tank Engine", page_icon="πŸ’§", layout="wide")
11
 
12
  TPL_COVER = "Cover_Template.docx"
13
- TPL_INSPECTION = "Inspection_Template.docx" # This will now be used PER TANK
14
  TPL_WARRANTY = "Warranty_Template.docx"
15
  TPL_JOB = "Job_Completion_Template.docx"
16
  STATIC_DM_CERT = "DM_Certificate.pdf"
@@ -80,7 +80,6 @@ with st.sidebar:
80
  service_date = st.date_input("πŸ“… Date of Service*", value=date.today())
81
  date_str = service_date.strftime("%d-%m-%Y")
82
 
83
- # REQUIREMENT 4: Dynamic Expiry Date with Override
84
  default_expiry = service_date + relativedelta(months=+6)
85
  override_expiry = st.checkbox("Override Expiry Date?")
86
  if override_expiry:
@@ -115,10 +114,9 @@ for i, tank in enumerate(st.session_state.tanks):
115
  tank["sediments"] = cc2.checkbox("πŸͺ¨ Sediments", tank.get("sediments", False), key=f"sed_{i}")
116
  tank["algae"] = cc3.checkbox("🌿 Algae", tank.get("algae", False), key=f"alg_{i}")
117
 
118
- # REQUIREMENT 3: Instruct user to upload exactly 2 photos per state
119
  pc1, pc2 = st.columns(2)
120
- pc1.file_uploader(f"Before Photos (Require exactly 2)*", type=["jpg","jpeg","png"], accept_multiple_files=True, key=f"b_{i}")
121
- pc2.file_uploader(f"After Photos (Require exactly 2)*", type=["jpg","jpeg","png"], accept_multiple_files=True, key=f"a_{i}")
122
 
123
  if st.button("βž• Add Another Tank"):
124
  st.session_state.tanks.append({"name": f"Tank {len(st.session_state.tanks)+1}", "capacity": 1000, "ph": 7.0, "tds": 200, "biofilm": False, "sediments": False, "algae": False})
@@ -129,7 +127,6 @@ st.markdown("---")
129
  # ── 5. ENGINE: MASTER PDF ASSEMBLY ────────────────────────────────────────────
130
  if st.button("πŸš€ Generate Master Report", type="primary", use_container_width=True):
131
 
132
- # REQUIREMENT 5: Strict Mandatory Validation
133
  errors = []
134
  if not client_name: errors.append("Client Name is missing.")
135
  if not authorized_person: errors.append("Authorized Person is missing.")
@@ -139,23 +136,22 @@ if st.button("πŸš€ Generate Master Report", type="primary", use_container_width=
139
 
140
  for i, t in enumerate(st.session_state.tanks):
141
  if not t["name"].strip(): errors.append(f"Tank {i+1} is missing a name.")
142
- # Check photo counts
143
  before_count = len(st.session_state.get(f"b_{i}") or [])
144
  after_count = len(st.session_state.get(f"a_{i}") or [])
145
- if before_count != 2: errors.append(f"Tank '{t['name']}' requires exactly 2 'Before' photos (Currently has {before_count}).")
146
- if after_count != 2: errors.append(f"Tank '{t['name']}' requires exactly 2 'After' photos (Currently has {after_count}).")
 
 
147
 
148
  if errors:
149
  st.error("⚠️ **Cannot generate report. Please fix the following issues:**")
150
  for e in errors:
151
  st.error(f"❌ {e}")
152
- st.stop() # Halts the script completely until fixed
153
 
154
- # If validation passes, proceed:
155
  with st.spinner("Generating Complete Dossier..."):
156
  with tempfile.TemporaryDirectory() as tmp_dir:
157
 
158
- # Global context for cover, warranty, job completion
159
  global_context = {
160
  "client_name": client_name, "authorized_person": authorized_person,
161
  "client_email": client_email, "project_location": project_location,
@@ -163,7 +159,6 @@ if st.button("πŸš€ Generate Master Report", type="primary", use_container_width=
163
  "total_tanks": len(st.session_state.tanks)
164
  }
165
 
166
- # A1. Generate Global Documents
167
  for key, tpl in [("cover", TPL_COVER), ("warr", TPL_WARRANTY), ("job", TPL_JOB)]:
168
  if os.path.exists(tpl):
169
  path = os.path.join(tmp_dir, f"{key}.docx")
@@ -172,9 +167,8 @@ if st.button("πŸš€ Generate Master Report", type="primary", use_container_width=
172
  doc.save(path)
173
  convert_to_pdf(path, tmp_dir)
174
 
175
- # A2. REQUIREMENT 1: Generate Per-Tank Inspection Documents
176
  for i, t in enumerate(st.session_state.tanks):
177
- tank_context = global_context.copy() # Inherit global details
178
  tank_context.update({
179
  "tank_name": t["name"],
180
  "capacity_usg": t["capacity"],
@@ -191,20 +185,23 @@ if st.button("πŸš€ Generate Master Report", type="primary", use_container_width=
191
  doc.save(path)
192
  convert_to_pdf(path, tmp_dir)
193
 
194
- # B. Image Processing (Tank Grids)
195
- all_photos = []
196
  for i, t in enumerate(st.session_state.tanks):
 
197
  for lbl, state_key in [("Before Cleaning", f"b_{i}"), ("After Cleaning", f"a_{i}")]:
198
  uploaded_images = st.session_state.get(state_key)
199
  if uploaded_images:
200
  for f in uploaded_images:
201
  f.seek(0)
202
- all_photos.append({"tank_name": t["name"], "label": lbl, "image_bytes": f.read()})
203
-
204
- grid_pages = build_photo_grid_pages(all_photos, 4)
205
- grid_pdfs = [photo_grid_to_pdf_bytes(pg, i+1, len(grid_pages), client_name, date_str) for i, pg in enumerate(grid_pages)]
 
 
 
206
 
207
- # C. Stapling Sequence
208
  writer = PdfWriter()
209
  readers_cache = []
210
 
@@ -220,28 +217,22 @@ if st.button("πŸš€ Generate Master Report", type="primary", use_container_width=
220
  except Exception:
221
  pass
222
 
223
- # 1. Cover
224
  staple_pdf(os.path.join(tmp_dir, "cover.pdf"))
225
 
226
- # 2. Dynamic Inspection Reports (One per tank)
227
  for i in range(len(st.session_state.tanks)):
228
  staple_pdf(os.path.join(tmp_dir, f"insp_{i}.pdf"))
229
 
230
- # 3. & 4. Static Compliance Docs
231
  staple_pdf(STATIC_DM_CERT)
232
  staple_pdf(STATIC_MSDS)
233
 
234
- # 5. Tank Photo Grids (Will naturally be 1 page per tank due to validation)
235
  for pdf_bytes in grid_pdfs:
236
  staple_pdf(io.BytesIO(pdf_bytes))
237
 
238
- # 6. Uploaded Physical Reports
239
  if handwritten_files:
240
  for hw_pdf in handwritten_files:
241
  hw_pdf.seek(0)
242
  staple_pdf(hw_pdf)
243
 
244
- # 7. & 8. Warranty and Job Completion
245
  staple_pdf(os.path.join(tmp_dir, "warr.pdf"))
246
  staple_pdf(os.path.join(tmp_dir, "job.pdf"))
247
 
 
10
  st.set_page_config(page_title="Wercore | Water Tank Engine", page_icon="πŸ’§", layout="wide")
11
 
12
  TPL_COVER = "Cover_Template.docx"
13
+ TPL_INSPECTION = "Inspection_Template.docx"
14
  TPL_WARRANTY = "Warranty_Template.docx"
15
  TPL_JOB = "Job_Completion_Template.docx"
16
  STATIC_DM_CERT = "DM_Certificate.pdf"
 
80
  service_date = st.date_input("πŸ“… Date of Service*", value=date.today())
81
  date_str = service_date.strftime("%d-%m-%Y")
82
 
 
83
  default_expiry = service_date + relativedelta(months=+6)
84
  override_expiry = st.checkbox("Override Expiry Date?")
85
  if override_expiry:
 
114
  tank["sediments"] = cc2.checkbox("πŸͺ¨ Sediments", tank.get("sediments", False), key=f"sed_{i}")
115
  tank["algae"] = cc3.checkbox("🌿 Algae", tank.get("algae", False), key=f"alg_{i}")
116
 
 
117
  pc1, pc2 = st.columns(2)
118
+ pc1.file_uploader(f"Before Photos (1 or 2 max)*", type=["jpg","jpeg","png"], accept_multiple_files=True, key=f"b_{i}")
119
+ pc2.file_uploader(f"After Photos (1 or 2 max)*", type=["jpg","jpeg","png"], accept_multiple_files=True, key=f"a_{i}")
120
 
121
  if st.button("βž• Add Another Tank"):
122
  st.session_state.tanks.append({"name": f"Tank {len(st.session_state.tanks)+1}", "capacity": 1000, "ph": 7.0, "tds": 200, "biofilm": False, "sediments": False, "algae": False})
 
127
  # ── 5. ENGINE: MASTER PDF ASSEMBLY ────────────────────────────────────────────
128
  if st.button("πŸš€ Generate Master Report", type="primary", use_container_width=True):
129
 
 
130
  errors = []
131
  if not client_name: errors.append("Client Name is missing.")
132
  if not authorized_person: errors.append("Authorized Person is missing.")
 
136
 
137
  for i, t in enumerate(st.session_state.tanks):
138
  if not t["name"].strip(): errors.append(f"Tank {i+1} is missing a name.")
 
139
  before_count = len(st.session_state.get(f"b_{i}") or [])
140
  after_count = len(st.session_state.get(f"a_{i}") or [])
141
+
142
+ # Validation Updated: Must be 1 or 2 photos
143
+ if before_count not in [1, 2]: errors.append(f"Tank '{t['name']}' requires 1 or 2 'Before' photos (Currently has {before_count}).")
144
+ if after_count not in [1, 2]: errors.append(f"Tank '{t['name']}' requires 1 or 2 'After' photos (Currently has {after_count}).")
145
 
146
  if errors:
147
  st.error("⚠️ **Cannot generate report. Please fix the following issues:**")
148
  for e in errors:
149
  st.error(f"❌ {e}")
150
+ st.stop()
151
 
 
152
  with st.spinner("Generating Complete Dossier..."):
153
  with tempfile.TemporaryDirectory() as tmp_dir:
154
 
 
155
  global_context = {
156
  "client_name": client_name, "authorized_person": authorized_person,
157
  "client_email": client_email, "project_location": project_location,
 
159
  "total_tanks": len(st.session_state.tanks)
160
  }
161
 
 
162
  for key, tpl in [("cover", TPL_COVER), ("warr", TPL_WARRANTY), ("job", TPL_JOB)]:
163
  if os.path.exists(tpl):
164
  path = os.path.join(tmp_dir, f"{key}.docx")
 
167
  doc.save(path)
168
  convert_to_pdf(path, tmp_dir)
169
 
 
170
  for i, t in enumerate(st.session_state.tanks):
171
+ tank_context = global_context.copy()
172
  tank_context.update({
173
  "tank_name": t["name"],
174
  "capacity_usg": t["capacity"],
 
185
  doc.save(path)
186
  convert_to_pdf(path, tmp_dir)
187
 
188
+ # Isolated Per-Tank Photo Grids
189
+ grid_pdfs = []
190
  for i, t in enumerate(st.session_state.tanks):
191
+ tank_photos = []
192
  for lbl, state_key in [("Before Cleaning", f"b_{i}"), ("After Cleaning", f"a_{i}")]:
193
  uploaded_images = st.session_state.get(state_key)
194
  if uploaded_images:
195
  for f in uploaded_images:
196
  f.seek(0)
197
+ tank_photos.append({"tank_name": t["name"], "label": lbl, "image_bytes": f.read()})
198
+
199
+ # Render pages specifically for this tank to ensure no mixing
200
+ if tank_photos:
201
+ tank_pages = build_photo_grid_pages(tank_photos, 4)
202
+ for idx, pg in enumerate(tank_pages):
203
+ grid_pdfs.append(photo_grid_to_pdf_bytes(pg, idx+1, len(tank_pages), client_name, date_str))
204
 
 
205
  writer = PdfWriter()
206
  readers_cache = []
207
 
 
217
  except Exception:
218
  pass
219
 
 
220
  staple_pdf(os.path.join(tmp_dir, "cover.pdf"))
221
 
 
222
  for i in range(len(st.session_state.tanks)):
223
  staple_pdf(os.path.join(tmp_dir, f"insp_{i}.pdf"))
224
 
 
225
  staple_pdf(STATIC_DM_CERT)
226
  staple_pdf(STATIC_MSDS)
227
 
 
228
  for pdf_bytes in grid_pdfs:
229
  staple_pdf(io.BytesIO(pdf_bytes))
230
 
 
231
  if handwritten_files:
232
  for hw_pdf in handwritten_files:
233
  hw_pdf.seek(0)
234
  staple_pdf(hw_pdf)
235
 
 
236
  staple_pdf(os.path.join(tmp_dir, "warr.pdf"))
237
  staple_pdf(os.path.join(tmp_dir, "job.pdf"))
238