-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_certs.py
More file actions
253 lines (208 loc) · 7.92 KB
/
generate_certs.py
File metadata and controls
253 lines (208 loc) · 7.92 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
#!/usr/bin/env python3
"""
Generate PDF certificates from a template and CSV data.
Usage:
python generate_certs.py --template template.pdf \
--csv "Certyfikaty mapping - attendance.csv" \
--output-dir output \
--only-attended
"""
import argparse
import csv
import os
from concurrent.futures import ProcessPoolExecutor, as_completed
import fitz # PyMuPDF
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
DEFAULT_FONT_REGULAR = os.path.join(SCRIPT_DIR, "fonts", "Montserrat-Regular.ttf")
DEFAULT_FONT_BOLD = os.path.join(SCRIPT_DIR, "fonts", "Montserrat-Bold.ttf")
# Top 5 placements (team name lowercase -> place number)
TOP_PLACEMENTS = {
"sztucznie inteligentni": 1,
"random overfitters": 2,
"dns drużyna nieobecnego szymona": 3,
"kaskaderzy": 4,
"maind_controllers": 5,
}
def get_za_co(team_name):
"""Return the [ZA_CO] text based on team placement."""
place = TOP_PLACEMENTS.get(team_name.lower())
if place is not None:
return f"zajęcie {place}. miejsca"
return "udział"
def collect_spans(page):
"""Return all text spans from the page as a flat list."""
spans = []
for block in page.get_text("dict")["blocks"]:
if "lines" not in block:
continue
for line in block["lines"]:
for span in line["spans"]:
spans.append(span)
return spans
def generate_certificate(template_path, font_regular, font_bold, name, team, za_co, output_path):
doc = fitz.open(template_path)
page = doc[0]
pw = page.rect.width
spans = collect_spans(page)
name_span = None
team_span = None
za_co_span = None
druzyna_span = None
for span in spans:
text = span["text"]
if "[IMIE_NAZWISKO]" in text:
name_span = span
elif "[NAZWA_DRUZYNY]" in text:
team_span = span
elif "[ZA_CO]" in text:
za_co_span = span
elif "drużyna" in text.lower() and "[" not in text:
druzyna_span = span
rects = []
if name_span:
rects.append(fitz.Rect(name_span["bbox"]))
if team_span:
rects.append(fitz.Rect(team_span["bbox"]))
if za_co_span:
rects.append(fitz.Rect(za_co_span["bbox"]))
if druzyna_span:
rects.append(fitz.Rect(druzyna_span["bbox"]))
for r in rects:
page.add_redact_annot(r, fill=(1, 1, 1))
page.apply_redactions()
font_r = fitz.Font(fontfile=font_regular)
font_b = fitz.Font(fontfile=font_bold)
# --- [IMIE_NAZWISKO] ---
if name_span:
bbox = fitz.Rect(name_span["bbox"])
fs = name_span["size"]
tw = font_r.text_length(name, fontsize=fs)
max_w = pw - 40
while tw > max_w and fs > 12:
fs -= 0.5
tw = font_r.text_length(name, fontsize=fs)
x = (pw - tw) / 2
ascender = font_r.ascender
descender = font_r.descender
font_height = (ascender - descender) * fs
baseline_y = bbox.y0 + (bbox.height + font_height) / 2 - (-descender * fs)
page.insert_text(
(x, baseline_y),
name,
fontsize=fs,
fontname="montr",
fontfile=font_regular,
)
# --- drużyna [NAZWA_DRUZYNY] ---
if team_span:
bbox = fitz.Rect(team_span["bbox"])
fs = team_span["size"]
prefix = "drużyna "
prefix_fs = druzyna_span["size"] if druzyna_span else fs
pw_prefix = font_r.text_length(prefix, fontsize=prefix_fs)
pw_team = font_b.text_length(team, fontsize=fs)
total_w = pw_prefix + pw_team
max_w = pw - 40
scale = 1.0
if total_w > max_w:
scale = max_w / total_w
adj_prefix_fs = prefix_fs * scale
adj_team_fs = fs * scale
pw_prefix = font_r.text_length(prefix, fontsize=adj_prefix_fs)
pw_team = font_b.text_length(team, fontsize=adj_team_fs)
total_w = pw_prefix + pw_team
start_x = (pw - total_w) / 2
ascender = font_r.ascender
descender = font_r.descender
ref_fs = fs * scale
font_height = (ascender - descender) * ref_fs
baseline_y = bbox.y0 + (bbox.height + font_height) / 2 - (-descender * ref_fs)
page.insert_text(
(start_x, baseline_y),
prefix,
fontsize=adj_prefix_fs,
fontname="montr",
fontfile=font_regular,
)
page.insert_text(
(start_x + pw_prefix, baseline_y),
team,
fontsize=adj_team_fs,
fontname="montb",
fontfile=font_bold,
)
# --- za [ZA_CO] ---
if za_co_span:
bbox = fitz.Rect(za_co_span["bbox"])
fs = za_co_span["size"]
new_text = f"za {za_co} "
tw = font_r.text_length(new_text, fontsize=fs)
x = (pw - tw) / 2
ascender = font_r.ascender
descender = font_r.descender
font_height = (ascender - descender) * fs
baseline_y = bbox.y0 + (bbox.height + font_height) / 2 - (-descender * fs)
page.insert_text(
(x, baseline_y),
new_text,
fontsize=fs,
fontname="montr",
fontfile=font_regular,
)
doc.save(output_path, garbage=4, deflate=True)
doc.close()
def main():
parser = argparse.ArgumentParser(
description="Generate PDF certificates from a template and CSV."
)
parser.add_argument("--template", required=True, help="Path to PDF template with placeholders")
parser.add_argument("--csv", required=True, help="Path to CSV with participant data")
parser.add_argument("--output-dir", default="output", help="Output directory (default: output)")
parser.add_argument("--za-co", default="udział", help="Text for [ZA_CO] placeholder (default: udział)")
parser.add_argument("--only-attended", action="store_true", help="Only generate for rows with attendance=TRUE")
parser.add_argument("--font-regular", default=DEFAULT_FONT_REGULAR, help="Path to regular TTF font")
parser.add_argument("--font-bold", default=DEFAULT_FONT_BOLD, help="Path to bold TTF font")
parser.add_argument("--limit", type=int, default=0, help="Limit number of certificates (0=all)")
args = parser.parse_args()
os.makedirs(args.output_dir, exist_ok=True)
print(f"Template: {args.template}")
print(f"Fonts: {args.font_regular}, {args.font_bold}")
jobs = []
with open(args.csv, newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
name = row["first_last_name"].strip()
team = row["team_name"].strip()
attended = row.get("Czy przyszedł", "TRUE").strip().upper()
if not name:
continue
if args.only_attended and attended != "TRUE":
continue
safe_name = "".join(
c if c.isalnum() or c in " _-" else "_" for c in name
).replace(" ", "_")
output_path = os.path.join(args.output_dir, f"{safe_name}.pdf")
za_co = get_za_co(team)
jobs.append((name, team, za_co, output_path))
if args.limit and len(jobs) >= args.limit:
break
print(f"Generating {len(jobs)} certificates using parallel workers...")
workers = min(os.cpu_count() or 4, len(jobs))
done = 0
with ProcessPoolExecutor(max_workers=workers) as pool:
futures = {
pool.submit(
generate_certificate,
args.template, args.font_regular, args.font_bold,
name, team, za_co, out,
): (name, team, out)
for name, team, za_co, out in jobs
}
for future in as_completed(futures):
name, team, out = futures[future]
future.result()
done += 1
print(f" [{done}/{len(jobs)}] {name} ({team})")
print(f"\nDone! Generated {done} certificates in '{args.output_dir}/'")
if __name__ == "__main__":
main()