-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild_local.py
More file actions
283 lines (240 loc) · 9.97 KB
/
Copy pathbuild_local.py
File metadata and controls
283 lines (240 loc) · 9.97 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
import os
import sys
import shutil
import subprocess
import platform
import re
from typing import Optional
def get_version() -> str:
"""Extract version from NullifyPDF.py with fallback.
Returns:
str: Version string from __version__ or 'unknown' fallback.
"""
try:
if not os.path.exists("NullifyPDF.py"):
return "unknown"
with open("NullifyPDF.py", "r", encoding="utf-8") as f:
content = f.read()
match = re.search(r'__version__\s*=\s*[\'"]([^\'"]+)[\'"]', content)
if match:
return match.group(1)
except (IOError, OSError) as e:
print(f"[WARNING] Could not read version: {e}")
return "unknown"
def ensure_icon(sys_os: str) -> Optional[str]:
"""Find icon file for the current OS.
Args:
sys_os: Operating system name (Windows, Darwin, Linux).
Returns:
Optional[str]: Path to icon file, or None if not found (Windows).
"""
base_dir = "images"
if sys_os == "Windows":
ico_path = os.path.join(base_dir, "NullifyPDF_icon.ico")
return ico_path.replace("\\", "/") if os.path.exists(ico_path) else None
elif sys_os == "Darwin":
icns_path = os.path.join(base_dir, "NullifyPDF_icon.icns")
return icns_path.replace("\\", "/") if os.path.exists(icns_path) else None
return os.path.join(base_dir, "NullifyPDF_icon.png").replace("\\", "/")
def build_rpm(version: str, executable_name: str) -> None:
"""Build RPM package for Fedora/RHEL.
Args:
version: Application version.
executable_name: Name of compiled executable.
"""
print("\n[INFO] Creazione pacchetto RPM per Fedora/RHEL...")
rpm_dir = os.path.abspath("rpm_build_tmp")
for d in ["BUILD", "BUILDROOT", "RPMS", "SOURCES", "SPECS", "SRPMS"]:
os.makedirs(os.path.join(rpm_dir, d), exist_ok=True)
icon_source = os.path.abspath("images/NullifyPDF_icon.png")
spec_path = os.path.join(rpm_dir, "SPECS", "nullify.spec")
with open(spec_path, "w", encoding="utf-8") as f:
f.write(
f"""
Name: nullify-pdf
Version: {version}
Release: 1
Summary: AI-Powered PDF Anonymization Tool
License: MIT
BuildArch: x86_64
%description
Professional forensic tool for PDF anonymization using AI.
%install
mkdir -p %{{buildroot}}/usr/bin
mkdir -p %{{buildroot}}/usr/share/applications
mkdir -p %{{buildroot}}/usr/share/icons/hicolor/256x256/apps
cp {os.path.abspath(f'dist/{executable_name}')} %{{buildroot}}/usr/bin/nullify-pdf
cp {icon_source} %{{buildroot}}/usr/share/icons/hicolor/256x256/apps/nullify-pdf.png
cat <<EOF > %{{buildroot}}/usr/share/applications/nullify-pdf.desktop
[Desktop Entry]
Name=NullifyPDF
Exec=/usr/bin/nullify-pdf
Icon=nullify-pdf
Type=Application
Categories=Utility;Security;
Terminal=false
StartupWMClass=nullify-pdf
EOF
%post
/usr/bin/update-desktop-database &> /dev/null || :
/usr/bin/gtk-update-icon-cache %{{_datadir}}/icons/hicolor &> /dev/null || :
%postun
/usr/bin/update-desktop-database &> /dev/null || :
/usr/bin/gtk-update-icon-cache %{{_datadir}}/icons/hicolor &> /dev/null || :
%files
/usr/bin/nullify-pdf
/usr/share/applications/nullify-pdf.desktop
/usr/share/icons/hicolor/256x256/apps/nullify-pdf.png
"""
)
try:
subprocess.run(
["rpmbuild", "--define", f"_topdir {rpm_dir}", "-bb", spec_path],
check=True,
stdout=subprocess.DEVNULL,
)
for root, _, files in os.walk(os.path.join(rpm_dir, "RPMS")):
for file in files:
if file.endswith(".rpm"):
shutil.move(
os.path.join(root, file),
f"dist/NullifyPDF_v{version}_Fedora.rpm",
)
print("[OK] RPM creato con successo.")
except Exception as e:
print(f"[ERROR] Errore RPM: {e}")
finally:
shutil.rmtree(rpm_dir, ignore_errors=True)
def build_deb(version: str, executable_name: str) -> None:
"""Build DEB package for Ubuntu/Debian.
Args:
version: Application version.
executable_name: Name of compiled executable.
"""
print("\n[INFO] Creazione pacchetto DEB per Ubuntu/Debian...")
pkg_dir = "deb_build_tmp"
for d in [
"DEBIAN",
"usr/bin",
"usr/share/applications",
"usr/share/icons/hicolor/256x256/apps",
]:
os.makedirs(os.path.join(pkg_dir, d), exist_ok=True)
shutil.copy(f"dist/{executable_name}", f"{pkg_dir}/usr/bin/nullify-pdf")
os.chmod(f"{pkg_dir}/usr/bin/nullify-pdf", 0o755)
if os.path.exists("images/NullifyPDF_icon.png"):
shutil.copy(
"images/NullifyPDF_icon.png",
f"{pkg_dir}/usr/share/icons/hicolor/256x256/apps/nullify-pdf.png",
)
with open(
f"{pkg_dir}/usr/share/applications/nullify-pdf.desktop", "w", encoding="utf-8"
) as f:
f.write(
"[Desktop Entry]\nName=NullifyPDF\nExec=/usr/bin/nullify-pdf\nIcon=nullify-pdf\nType=Application\nCategories=Utility;Security;\nTerminal=false\nStartupWMClass=nullify-pdf\n"
)
with open(f"{pkg_dir}/DEBIAN/control", "w", encoding="utf-8") as f:
f.write(
f"Package: nullify-pdf\nVersion: {version}\nSection: utils\nPriority: optional\nArchitecture: amd64\nMaintainer: Graziano\nDescription: AI PDF Redaction Tool\n"
)
postinst_content = "#!/bin/sh\nset -e\nupdate-desktop-database -q || true\ngtk-update-icon-cache -f -t /usr/share/icons/hicolor || true\n"
with open(f"{pkg_dir}/DEBIAN/postinst", "w", newline="\n") as f:
f.write(postinst_content)
with open(f"{pkg_dir}/DEBIAN/postrm", "w", newline="\n") as f:
f.write(postinst_content)
os.chmod(f"{pkg_dir}/DEBIAN/postinst", 0o755)
os.chmod(f"{pkg_dir}/DEBIAN/postrm", 0o755)
try:
subprocess.run(
["dpkg-deb", "--build", pkg_dir, f"dist/NullifyPDF_v{version}_Ubuntu.deb"],
check=True,
stdout=subprocess.DEVNULL,
)
print("[OK] DEB creato con successo.")
except Exception as e:
print(f"[ERROR] Errore DEB: {e}")
finally:
shutil.rmtree(pkg_dir, ignore_errors=True)
def build_app() -> None:
"""Build NullifyPDF application for current OS using PyInstaller.
Automatically generates platform-specific executables:
- Windows: .exe standalone
- macOS: .app bundle (zipped)
- Linux: portable binary + .deb + .rpm packages
"""
print("--- Avvio Compilazione NullifyPDF (PySide6) ---")
version = get_version()
sys_os = platform.system()
for item in ["build", "dist", "NullifyPDF.spec"]:
if os.path.exists(item):
shutil.rmtree(item) if os.path.isdir(item) else os.remove(item)
os_name, ext = (
("Windows", ".exe")
if sys_os == "Windows"
else ("macOS", "") if sys_os == "Darwin" else ("Linux_Portable", "")
)
final_name = f"NullifyPDF_v{version}_{os_name}{ext}"
icon_path = ensure_icon(sys_os)
# Use repr() to safely embed the path as a Python literal in the spec file.
# Manual single-quote wrapping is unsafe for paths containing quotes/backslashes.
icon_str = repr(icon_path) if icon_path else "None"
if sys_os == "Darwin":
spec_content = f"""# -*- mode: python ; coding: utf-8 -*-
from PyInstaller.utils.hooks import collect_all
datas = [('images', 'images')] if __import__('os').path.exists('images') else []
binaries = []
hiddenimports = ['spacy', 'presidio_analyzer']
for pkg in ['presidio_analyzer', 'spacy', 'en_core_web_md', 'it_core_news_md']:
t = collect_all(pkg)
datas += t[0]; binaries += t[1]; hiddenimports += t[2]
a = Analysis(['NullifyPDF.py'], datas=datas, hiddenimports=hiddenimports)
pyz = PYZ(a.pure)
exe = EXE(pyz, a.scripts, [], exclude_binaries=True, name='NullifyPDF', debug=False, console=False, icon={icon_str})
coll = COLLECT(exe, a.binaries, a.datas, strip=False, upx=True, upx_exclude=[], name='NullifyPDF')
app = BUNDLE(coll, name='NullifyPDF.app', icon={icon_str}, bundle_identifier='com.nullifypdf.forensic')
"""
else:
spec_content = f"""# -*- mode: python ; coding: utf-8 -*-
from PyInstaller.utils.hooks import collect_all
datas = [('images', 'images')] if __import__('os').path.exists('images') else []
binaries = []
hiddenimports = ['spacy', 'presidio_analyzer']
for pkg in ['presidio_analyzer', 'spacy', 'en_core_web_md', 'it_core_news_md']:
t = collect_all(pkg)
datas += t[0]; binaries += t[1]; hiddenimports += t[2]
a = Analysis(['NullifyPDF.py'], datas=datas, hiddenimports=hiddenimports)
pyz = PYZ(a.pure)
exe = EXE(pyz, a.scripts, a.binaries, a.datas, name='NullifyPDF', debug=False, console=False, icon={icon_str})
"""
with open("NullifyPDF.spec", "w", encoding="utf-8") as f:
f.write(spec_content)
try:
subprocess.run(
[sys.executable, "-m", "PyInstaller", "NullifyPDF.spec"], check=True
)
if sys_os == "Windows":
os.rename("dist/NullifyPDF.exe", f"dist/{final_name}")
print(f"[OK] Compilazione completata: dist/{final_name}")
elif sys_os == "Darwin":
print("[INFO] Compressione App Bundle per macOS in formato ZIP...")
zip_filename = f"NullifyPDF_v{version}_macOS.zip"
subprocess.run(
["zip", "-r", "-y", zip_filename, "NullifyPDF.app"],
cwd="dist",
check=True,
stdout=subprocess.DEVNULL,
)
shutil.rmtree("dist/NullifyPDF.app")
print(f"[OK] Compilazione completata: dist/{zip_filename}")
else: # Linux
os.rename("dist/NullifyPDF", f"dist/{final_name}")
print(f"[OK] Eseguibile portatile pronto: dist/{final_name}")
if shutil.which("rpmbuild"):
build_rpm(version, final_name)
if shutil.which("dpkg-deb"):
build_deb(version, final_name)
except subprocess.CalledProcessError as e:
print(f"\n[ERROR] ERRORE CRITICO: Compilazione fallita (exit {e.returncode}).")
sys.exit(1)
if __name__ == "__main__":
build_app()