-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate.py
More file actions
157 lines (118 loc) Β· 4.62 KB
/
Copy pathgenerate.py
File metadata and controls
157 lines (118 loc) Β· 4.62 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
import os
import re
import io
import time
import yaml
import pandas as pd
from pptx import Presentation
import comtypes.client
def load_config(path="config.yaml"):
with open(path, "r") as f:
return yaml.safe_load(f)
def load_data(file_path):
if file_path.endswith(".csv"):
return pd.read_csv(file_path, dtype=str).fillna("")
return pd.read_excel(file_path, dtype=str).fillna("")
def sanitize_filename(text):
return re.sub(r'[\\/*?:"<>|]', "", str(text)).replace(" ", "_")
def replace_text(shape, replacements):
if not shape.has_text_frame:
return
for paragraph in shape.text_frame.paragraphs:
full_text = "".join(run.text for run in paragraph.runs)
new_text = full_text
for key, value in replacements.items():
new_text = new_text.replace(key, str(value))
if new_text == full_text:
continue
current_index = 0
for run in paragraph.runs:
run_length = len(run.text)
run.text = new_text[current_index:current_index + run_length]
current_index += run_length
if current_index < len(new_text):
paragraph.runs[-1].text += new_text[current_index:]
def convert_to_pdf(powerpoint, ppt_path, pdf_path):
# ppt_path = os.path.abspath(ppt_path)
# pdf_path = os.path.abspath(pdf_path)
presentation = powerpoint.Presentations.Open(ppt_path, WithWindow=False)
presentation.SaveAs(pdf_path, 32)
presentation.Close()
os.remove(ppt_path)
def generate_certificates(config, df):
start_time = time.time()
cert_type = config["certificate"]["type"]
template_path = config["certificate"]["templates"][cert_type]
output_folder = config["output"]["folder"]
name_column = config["input"]["name_column"]
uid_column = config["input"]["uid_column"]
ref_column = config["input"]["ref_column"]
dept_column = config["input"]["dept_column"]
role_column = config["input"].get("role_column")
event_name = config["event"]["name"]
event_date = config["event"]["date"]
os.makedirs(output_folder, exist_ok=True)
with open(template_path, "rb") as f:
template_bytes = f.read()
ppt_files = []
success, fail = 0, 0
print("π Generating PPT files...")
for row in df.itertuples(index=False):
try:
uid = str(getattr(row, uid_column, "")).strip()
if not uid:
# print("β οΈ Skipping row with empty UID")
continue
name = getattr(row, name_column, "")
ref = getattr(row, ref_column, "")
dept = getattr(row, dept_column, "")
role = getattr(row, role_column, "") if role_column else ""
prs = Presentation(io.BytesIO(template_bytes))
replacements = {
"{{name}}": name,
"{{uid}}": uid,
"{{ref}}": ref,
"{{dept}}": dept,
"{{event_name}}": event_name,
"{{event_date}}": event_date
}
if role_column:
replacements["{{role}}"] = role
for slide in prs.slides:
for shape in slide.shapes:
replace_text(shape, replacements)
safe_event = sanitize_filename(event_name)
safe_ref = sanitize_filename(ref)
safe_uid = sanitize_filename(uid)
filename = f"{safe_event}_{safe_ref}_{safe_uid}"
ppt_path = os.path.abspath(os.path.join(output_folder, filename + ".pptx"))
prs.save(ppt_path)
ppt_files.append(ppt_path)
success+=1
except Exception as e:
print(f"β {uid} - {e}")
fail += 1
print(f"PPT Generated β {success}")
print("π Converting to PDF...")
powerpoint = comtypes.client.CreateObject("Powerpoint.Application")
powerpoint.Visible = 1
powerpoint.WindowState = 2
try:
for ppt_path in ppt_files:
try:
pdf_path = ppt_path.replace(".pptx", ".pdf")
convert_to_pdf(powerpoint, ppt_path, pdf_path)
print(f"β
{os.path.basename(pdf_path)}")
except Exception as e:
print(f"β Conversion failed: {ppt_path} - {e}")
fail += 1
finally:
powerpoint.Quit()
end_time = time.time()
print(f"β
Success: {success} | β Failure: {fail} | Time: {round(end_time - start_time, 2)} sec")
def main():
config = load_config()
df = load_data(config["input"]["file"])
generate_certificates(config, df)
if __name__=="__main__":
main()