-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpdf_certificate.py
More file actions
306 lines (273 loc) · 12.2 KB
/
pdf_certificate.py
File metadata and controls
306 lines (273 loc) · 12.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
"""
pdf_certificate.py — SiteWarden Compliance Certificate Generator
=================================================================
Generates a professional PDF compliance report with:
- Header with logo, title, timestamp, document ID
- Executive summary
- Detected violations
- Applied corrections
- Verification status
- Before/After visual evidence
- Footer with page numbers
"""
from __future__ import annotations
import io
import uuid
from datetime import datetime
from typing import List, Optional
from PIL import Image
from reportlab.lib import colors
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_JUSTIFY
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
from reportlab.lib.units import mm, cm
from reportlab.platypus import (
BaseDocTemplate,
Frame,
Image as RLImage,
NextPageTemplate,
PageBreak,
PageTemplate,
Paragraph,
SimpleDocTemplate,
Spacer,
Table,
TableStyle,
)
# ═══════════════════════════════════════════════════════════════
# Color palette
# ═══════════════════════════════════════════════════════════════
BLUE = colors.HexColor("#0066cc")
DARK_BLUE = colors.HexColor("#003d7a")
LIGHT_BLUE = colors.HexColor("#e8f0fe")
GREEN = colors.HexColor("#28a745")
RED = colors.HexColor("#dc3545")
GRAY = colors.HexColor("#6c757d")
LIGHT_GRAY = colors.HexColor("#f8f9fa")
DARK = colors.HexColor("#1a1a1a")
# ═══════════════════════════════════════════════════════════════
# PIL Image → ReportLab Image helper
# ═══════════════════════════════════════════════════════════════
def _pil_to_rl_image(pil_img: Image.Image, max_width: float, max_height: float) -> RLImage:
"""Convert a PIL Image to a ReportLab Image that fits within bounds."""
buf = io.BytesIO()
pil_img.save(buf, format="PNG")
buf.seek(0)
img_w, img_h = pil_img.size
ratio = min(max_width / img_w, max_height / img_h)
return RLImage(buf, width=img_w * ratio, height=img_h * ratio)
# ═══════════════════════════════════════════════════════════════
# Main generator
# ═══════════════════════════════════════════════════════════════
def generate_compliance_pdf(
violations_list: List[str],
corrections_list: List[str],
before_image: Optional[Image.Image] = None,
after_image: Optional[Image.Image] = None,
regulation_name: str = "Building Accessibility Regulation",
iteration_count: int = 1,
context_info: str = "",
is_generated_schematic: bool = False,
) -> bytes:
"""
Generate a professional compliance certificate PDF.
Returns the PDF as bytes (ready for st.download_button).
"""
buf = io.BytesIO()
doc = SimpleDocTemplate(
buf,
pagesize=A4,
leftMargin=20 * mm,
rightMargin=20 * mm,
topMargin=25 * mm,
bottomMargin=20 * mm,
)
page_w = A4[0] - 40 * mm # usable width
# ── Styles ───────────────────────────────────────────────────
styles = getSampleStyleSheet()
s_title = ParagraphStyle(
"CertTitle", parent=styles["Title"],
fontName="Helvetica-Bold", fontSize=24, leading=30,
textColor=DARK_BLUE, alignment=TA_CENTER, spaceAfter=4 * mm,
)
s_subtitle = ParagraphStyle(
"CertSubtitle", parent=styles["Normal"],
fontName="Helvetica", fontSize=12, leading=16,
textColor=GRAY, alignment=TA_CENTER, spaceAfter=8 * mm,
)
s_section = ParagraphStyle(
"SectionHead", parent=styles["Heading2"],
fontName="Helvetica-Bold", fontSize=14, leading=18,
textColor=DARK_BLUE, spaceBefore=8 * mm, spaceAfter=4 * mm,
borderWidth=0, borderPadding=0,
)
s_body = ParagraphStyle(
"BodyText2", parent=styles["Normal"],
fontName="Helvetica", fontSize=10.5, leading=15,
textColor=DARK, alignment=TA_JUSTIFY, spaceAfter=3 * mm,
)
s_bullet = ParagraphStyle(
"Bullet", parent=s_body,
leftIndent=12 * mm, bulletIndent=4 * mm,
spaceAfter=2 * mm,
)
s_meta = ParagraphStyle(
"Meta", parent=styles["Normal"],
fontName="Helvetica", fontSize=9, leading=12,
textColor=GRAY, alignment=TA_CENTER,
)
s_img_caption = ParagraphStyle(
"ImgCaption", parent=styles["Normal"],
fontName="Helvetica-Bold", fontSize=10, leading=14,
textColor=DARK_BLUE, alignment=TA_CENTER, spaceAfter=2 * mm,
)
# ── Build story ──────────────────────────────────────────────
story: list = []
now = datetime.now()
doc_id = f"SW-{now.strftime('%Y%m%d%H%M%S')}-{uuid.uuid4().hex[:6].upper()}"
# ── Header ───────────────────────────────────────────────────
story.append(Paragraph("SiteWarden Compliance Certificate", s_title))
story.append(Paragraph("Autonomous Architectural Analysis Report", s_subtitle))
# Meta row
meta_data = [
[
Paragraph(f"<b>Date:</b> {now.strftime('%d %B %Y, %H:%M')}", s_meta),
Paragraph(f"<b>Document ID:</b> {doc_id}", s_meta),
]
]
meta_table = Table(meta_data, colWidths=[page_w / 2] * 2)
meta_table.setStyle(TableStyle([
("BACKGROUND", (0, 0), (-1, -1), LIGHT_BLUE),
("BOX", (0, 0), (-1, -1), 0.5, BLUE),
("TOPPADDING", (0, 0), (-1, -1), 6),
("BOTTOMPADDING", (0, 0), (-1, -1), 6),
]))
story.append(meta_table)
story.append(Spacer(1, 6 * mm))
# ── Divider ──────────────────────────────────────────────────
def _divider():
d = Table([[""]], colWidths=[page_w])
d.setStyle(TableStyle([
("LINEBELOW", (0, 0), (-1, -1), 1, BLUE),
("TOPPADDING", (0, 0), (-1, -1), 0),
("BOTTOMPADDING", (0, 0), (-1, -1), 0),
]))
story.append(d)
story.append(Spacer(1, 4 * mm))
# ── Section 1: Executive Summary ─────────────────────────────
story.append(Paragraph("1. Executive Summary", s_section))
_divider()
story.append(Paragraph(
"This document certifies that the submitted floor plan has been "
"autonomously analyzed and corrected to meet the specified building "
"regulations by the SiteWarden AI Agent, powered by Google Gemini.",
s_body,
))
story.append(Paragraph(f"<b>Regulation Applied:</b> {regulation_name}", s_body))
if context_info:
story.append(Paragraph(f"<b>Building Context:</b> {context_info}", s_body))
story.append(Spacer(1, 2 * mm))
# ── Section 2: Detected Violations ───────────────────────────
story.append(Paragraph("2. Detected Violations", s_section))
_divider()
if violations_list:
for i, v in enumerate(violations_list, 1):
story.append(Paragraph(
f'<font color="{RED.hexval()}">✗</font> <b>Violation #{i}:</b> {v}',
s_bullet,
))
else:
story.append(Paragraph(
'<font color="green">No violations detected — plan was already compliant.</font>',
s_body,
))
story.append(Spacer(1, 2 * mm))
# ── Section 3: Applied Corrections / Recommendations ────────
story.append(Paragraph("3. Recommendations & Corrections", s_section))
_divider()
if corrections_list:
for i, c in enumerate(corrections_list, 1):
story.append(Paragraph(
f'<font color="{GREEN.hexval()}">✓</font> <b>#{i}:</b> {c}',
s_bullet,
))
else:
story.append(Paragraph("No corrections were necessary.", s_body))
story.append(Spacer(1, 2 * mm))
# ── Section 4: Verification ──────────────────────────────────
story.append(Paragraph("4. Verification", s_section))
_divider()
if not violations_list:
story.append(Paragraph(
"The submitted blueprint has been analyzed and confirmed "
"<b>fully compliant</b> with all specified regulations.",
s_body,
))
else:
story.append(Paragraph(
"The submitted blueprint has been analyzed. "
f"<b>{len(violations_list)} violation(s)</b> were identified. "
"The recommendations above should be applied by the architect "
"to achieve full compliance.",
s_body,
))
story.append(Paragraph(
f"<b>Iterations required:</b> Fixed in {iteration_count} iteration{'s' if iteration_count != 1 else ''}.",
s_body,
))
story.append(Spacer(1, 4 * mm))
# ── Section 5: Visual Evidence ───────────────────────────────
if before_image or after_image:
story.append(Paragraph("5. Visual Evidence", s_section))
_divider()
img_cells = []
captions = []
img_max_w = (page_w - 10 * mm) / 2
img_max_h = 80 * mm
if before_image:
img_cells.append(_pil_to_rl_image(before_image, img_max_w, img_max_h))
captions.append(Paragraph(
"BEFORE — Original Blueprint" if not is_generated_schematic
else "BEFORE — Initial Schematic",
s_img_caption))
else:
img_cells.append(Paragraph("N/A", s_meta))
captions.append(Paragraph("", s_meta))
after_label = (
"AFTER — Compliant Schematic (Demo)"
if is_generated_schematic
else "AFTER — Compliance Analysis"
)
if after_image:
img_cells.append(_pil_to_rl_image(after_image, img_max_w, img_max_h))
captions.append(Paragraph(after_label, s_img_caption))
else:
img_cells.append(Paragraph("N/A", s_meta))
captions.append(Paragraph("", s_meta))
img_table = Table(
[captions, img_cells],
colWidths=[page_w / 2] * 2,
)
img_table.setStyle(TableStyle([
("ALIGN", (0, 0), (-1, -1), "CENTER"),
("VALIGN", (0, 0), (-1, -1), "MIDDLE"),
("BOX", (0, 0), (0, -1), 0.5, BLUE),
("BOX", (1, 0), (1, -1), 0.5, GREEN),
("BACKGROUND", (0, 0), (0, 0), colors.HexColor("#fff0f0")),
("BACKGROUND", (1, 0), (1, 0), colors.HexColor("#f0fff0")),
("TOPPADDING", (0, 0), (-1, -1), 4),
("BOTTOMPADDING", (0, 0), (-1, -1), 4),
]))
story.append(img_table)
# ── Build PDF ────────────────────────────────────────────────
def _footer(canvas, doc):
canvas.saveState()
canvas.setFont("Helvetica", 8)
canvas.setFillColor(GRAY)
canvas.drawString(20 * mm, 12 * mm,
"Generated by SiteWarden AI Agent | Powered by Google Gemini 3 Pro")
canvas.drawRightString(A4[0] - 20 * mm, 12 * mm,
f"Page {doc.page}")
canvas.restoreState()
doc.build(story, onFirstPage=_footer, onLaterPages=_footer)
return buf.getvalue()