-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPyToExe.py
More file actions
2907 lines (2509 loc) · 139 KB
/
PyToExe.py
File metadata and controls
2907 lines (2509 loc) · 139 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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2025
# Developer : Mohammed Al-Baqer
import os
from pyclbr import Class
import sys
import time
import json
import shlex
import traceback
import webbrowser
import shutil
import ctypes
import subprocess
import importlib
import importlib.util
import GPUtil
import psutil
import ctypes
import struct
import shlex
import winsound
import tempfile
from collections import deque
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import numpy as np
from matplotlib.figure import Figure
from plyer import notification
from dataclasses import dataclass
from typing import List, Dict, Optional, Any
from PyQt5.QtCore import Qt, QThread, pyqtSignal, QObject, QTimer
from PyQt5.QtCore import QSize
from PyQt5.QtGui import QIcon, QPalette, QColor, QFont
from PyQt5.QtWidgets import QColorDialog
from PyQt5.QtWidgets import QDialog
from PyQt5.QtCore import QCoreApplication, QProcess
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QWidget, QFileDialog, QListWidget, QListWidgetItem,
QLineEdit, QPushButton, QCheckBox, QPlainTextEdit, QMessageBox, QLabel,
QHBoxLayout, QVBoxLayout, QGroupBox, QComboBox, QProgressBar, QMenu, QAction,
QTabWidget, QSpinBox, QDoubleSpinBox, QTextEdit, QSplitter, QInputDialog
)
SETTINGS_FILE = "settings.json"
LOG_FILE = "log.txt"
BACKUP_DIR = "backups"
PLUGINS_DIR = "plugins"
PRESETS_DIR = "presets"
DEFAULT_SETTINGS = {
"onefile": True,
"noconsole": False,
"clean": True,
"last_output": os.path.abspath("output"),
"last_icon": "",
"last_manifest": "",
"last_entries": [],
"last_files": [],
"last_folders": [],
"python_interpreter": "",
"advanced": {
"hidden_imports": [],
"exclude_modules": [],
"uac_admin": False,
"key": "",
"optimize": False,
"strip": False,
"no_prefer_redirect": False,
"obfuscate": False,
"anti_debug": False,
"packer": False
},
"version_info": {
"version": "1.0.0",
"company": "",
"copyright": "",
"description": "",
"website": ""
},
"security": {
"sign_certificate": "",
"cert_password": "",
"timestamp_server": "http://timestamp.digicert.com"
},
"build_system": "PyInstaller",
"platform": "win32",
"theme": "light",
"language": "ar",
"virtual_env": "",
"template": "مخصص (Custom)",
"resource_compression": "normal",
"resource_encryption": False,
"ide_integration": {
"vscode": False,
"pycharm": False
}
}
PATHSEP = ";" if os.name == "nt" else ":"
class LanguageManager:
def __init__(self, settings_path="settings.json", languages_dir="languages"):
self.languages_dir = languages_dir
self.settings_path = settings_path
self.current_language = "ar"
self.translations = {}
os.makedirs(self.languages_dir, exist_ok=True)
self.SaveLoadLanguages()
def SaveLoadLanguages(self):
try:
if not os.path.exists(self.settings_path):
print("[Language] settings.json Not Found so using default language (ar)")
return self.LoadLanguages("ar")
with open(self.settings_path, "r", encoding="utf-8") as f:
settings = json.load(f)
lang_code = settings.get("language", "ar")
if isinstance(lang_code, list):
lang_code = lang_code[0] if lang_code else "ar"
if not isinstance(lang_code, str):
lang_code = "ar"
return self.LoadLanguages(lang_code)
except Exception as e:
print(f"[Language] Error loading language from settings: {e}")
return self.LoadLanguages("ar")
def LoadLanguages(self, lang_code: str):
lang_file = os.path.join(self.languages_dir, f"{lang_code}.json")
try:
if not os.path.exists(lang_file):
print(f"[Language] Language file {lang_code}.json not found, using default language (ar)")
lang_file = os.path.join(self.languages_dir, "ar.json")
with open(lang_file, "r", encoding="utf-8") as f:
self.translations = json.load(f)
self.current_language = lang_code
S = "\033[0m" # Reset
R = "\033[91;1m" # Red
G = "\033[92;1m" # Green
B = "\033[94;1m" # Blue
Y = "\033[93;1m" # Yellow
C = "\033[96;1m" # Cyan
M = "\033[95;1m" # Magenta
W = "\033[97;1m" # White
D = "\033[90;1m" # Grey
P = "\033[38;5;198m" # Pink
O = "\033[38;5;202m" # Orange
print(f"[Language] Language loaded -> {lang_code}\n")
os.system('cls' if os.name == 'nt' else 'clear')
print(f"{C}From Python To Executable\n{Y}Developer {W}: {O}Mohammed Al-Baqer\n{B}Instagram {W}: {P}@wsl.iq{W}")
if not self.translations.get("ui"):
self.translations["ui"] = {
"title": "عنوان",
"message": "رسالة",
"button": "زر",
"entry": "مدخل",
"checkbox": "خانة اختيار",
"combobox": "قائمة منسدلة",
"radiobutton": "زر اختيار",
"error": "خطأ",
"success": "نجاح",
"info": "معلومات"
}
return True
except Exception as e:
print(f"[Language] Error loading language {lang_code}: {e}")
return False
def get(self, key: str, default: str = None) -> str:
return self.translations.get(key, default or key)
def tr(self, key: str, *args) -> str:
keys = key.split('.')
value = self.translations
try:
for k in keys:
value = value[k]
text = value
except (KeyError, TypeError):
text = key
if args:
try:
text = text.format(*args)
except Exception:
pass
return text
def AvailableLanguges(self) -> List[str]:
languages = []
for file in os.listdir(self.languages_dir):
if file.endswith(".json"):
languages.append(file[:-5])
return sorted(languages)
class PluginManager:
def __init__(self, plugins_dir="plugins"):
self.plugins_dir = plugins_dir
self.plugins = {}
os.makedirs(plugins_dir, exist_ok=True)
def LoadPlugins(self):
for file in os.listdir(self.plugins_dir):
if file.endswith(".py") and not file.startswith("_"):
try:
plugin_name = file[:-3]
spec = importlib.util.spec_from_file_location(plugin_name, os.path.join(self.plugins_dir, file))
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
self.plugins[plugin_name] = module
print(f"[Plugin] Loaded: {plugin_name}")
except Exception as e:
print(f"[Plugin] Failed to load plugin {file}: {e}")
def ExecuteHook(self, hook_name, *args, **kwargs):
results = {}
for name, plugin in self.plugins.items():
if hasattr(plugin, hook_name):
try:
result = getattr(plugin, hook_name)(*args, **kwargs)
results[name] = result
except Exception as e:
print(f"[Plugin] Failed to execute hook {hook_name} in {name}: {e}")
return results
def quote(p: str) -> str:
if not p:
return p
if os.name != "nt":
return shlex.quote(p)
if " " in p or "(" in p or ")" in p:
return f'"{p}"'
return p
def Administrator() -> bool:
try:
if os.name == "nt":
return ctypes.windll.shell32.IsUserAnAdmin() != 0
else:
return os.geteuid() == 0
except Exception:
return False
def FindPythonInterpreters() -> List[str]:
candidates = []
for name in ("python", "python3", "py"):
path = shutil.which(name)
if path and path not in candidates:
candidates.append(path)
if os.name == "nt":
program_files = os.environ.get("ProgramFiles", r"C:\Program Files")
pf_x86 = os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)")
for base in (program_files, pf_x86):
for root, dirs, files in os.walk(base):
for f in files:
if f.lower().startswith("python") and f.lower().endswith(".exe"):
p = os.path.join(root, f)
if p not in candidates:
candidates.append(p)
break
virtual_envs = FindVirtualEnvironments()
candidates.extend(virtual_envs)
return candidates
def FindVirtualEnvironments() -> List[str]:
envs = []
common_locations = [
os.path.expanduser("~"),
os.path.expanduser("~/.virtualenvs"),
os.path.expanduser("~/Envs"),
os.path.curdir
]
for location in common_locations:
if os.path.exists(location):
for item in os.listdir(location):
env_path = os.path.join(location, item)
if os.path.isdir(env_path):
python_exe = None
if os.name == "nt":
python_exe = os.path.join(env_path, "Scripts", "python.exe")
else:
python_exe = os.path.join(env_path, "bin", "python")
if python_exe and os.path.isfile(python_exe):
envs.append(python_exe)
return envs
@dataclass
class BuildItem:
entry_script: str
class BuildWorker(QObject):
line = pyqtSignal(str)
done = pyqtSignal(bool)
progress = pyqtSignal(int)
cpu_mem = pyqtSignal(float, float)
def __init__(self, commands: List[List[str]], cwd: str, python_exec: Optional[str] = None, run_after=False):
super().__init__()
self.commands = commands
self.cwd = cwd
self._stopped = False
self.python_exec = python_exec
self.run_after = run_after
def stop(self):
self._stopped = True
def EmitSysUsage(self):
if psutil:
try:
cpu = psutil.cpu_percent(interval=None)
mem = psutil.virtual_memory().percent
self.cpu_mem.emit(cpu, mem)
except Exception:
pass
def run(self):
ok = True
for cmd in self.commands:
if self._stopped:
ok = False
break
display_cmd = " ".join(map(str, cmd))
self.line.emit(f"\n=== تشغيل: {display_cmd}\n")
try:
with subprocess.Popen(
cmd,
cwd=self.cwd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1,
universal_newlines=True
) as p:
for out_line in p.stdout:
if self._stopped:
p.kill()
ok = False
break
text = out_line.rstrip("\n")
self.line.emit(text)
self.EmitSysUsage()
rc = p.wait()
if rc != 0:
ok = False
self.line.emit(f"[ERROR] The Process Ended with a code ! -> {rc}")
break
except FileNotFoundError:
ok = False
self.line.emit("[ERROR] The command was not found")
break
except Exception as e:
ok = False
self.line.emit(f"[ERROR] {e}")
break
if ok and self.run_after and self.commands:
try:
output_dir = self.commands[0][self.commands[0].index("--distpath") + 1] if "--distpath" in self.commands[0] else "dist"
entry_script = self.commands[0][-1]
exe_name = os.path.splitext(os.path.basename(entry_script))[0] + (".exe" if os.name == "nt" else "")
exe_path = os.path.join(output_dir, exe_name)
if os.path.exists(exe_path):
self.line.emit(f"[INFO] Turning {exe_path}")
if os.name == "nt":
os.startfile(exe_path)
else:
subprocess.Popen([exe_path])
else:
self.line.emit("[WARN] Not Found file run!")
except Exception as e:
self.line.emit(f"[ERROR] Failed to run the output file: {e}")
self.done.emit(ok)
class PyInstallerExtras:
def __init__(self, presets_dir="presets"):
self.presets_dir = presets_dir
os.makedirs(presets_dir, exist_ok=True)
def AnalyzeMissingImports(self, script_path: str) -> List[str]:
if not os.path.isfile(script_path):
return []
missing = set()
cmd = ["pyinstaller", "--debug=imports", "--noconfirm", "--onefile", script_path]
try:
with subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
universal_newlines=True
) as proc:
for line in proc.stdout:
if "ModuleNotFoundError" in line:
mod_name = line.split("'")[-2]
missing.add(mod_name)
elif "WARNING" in line and "hidden import" in line.lower():
parts = line.split("'")
if len(parts) >= 2:
missing.add(parts[1])
except Exception as e:
print(f"[Analyzer] Failed to analyze: {e}")
finally:
for d in ("build", "__pycache__"):
if os.path.isdir(d):
shutil.rmtree(d, ignore_errors=True)
spec_file = os.path.splitext(os.path.basename(script_path))[0] + ".spec"
if os.path.isfile(spec_file):
os.remove(spec_file)
return list(missing)
def AdvancedDependencyAnalysis(self, script_path: str) -> Dict[str, Any]:
analysis_result = {
"missing_imports": [],
"large_files": [],
"suspicious_imports": [],
"performance_issues": [],
"recommendations": []
}
missing = self.AnalyzeMissingImports(script_path)
analysis_result["missing_imports"] = missing
script_dir = os.path.dirname(script_path)
for root, dirs, files in os.walk(script_dir):
for file in files:
file_path = os.path.join(root, file)
if os.path.getsize(file_path) > 10 * 1024 * 1024:
analysis_result["large_files"].append(file_path)
suspicious_keywords = ["os.system", "subprocess", "eval", "exec", "pickle", "marshal"]
with open(script_path, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read()
for keyword in suspicious_keywords:
if keyword in content:
analysis_result["suspicious_imports"].append(keyword)
performance_issues = ["time.sleep", "while True", "recursive"]
for issue in performance_issues:
if issue in content:
analysis_result["performance_issues"].append(issue)
if "tkinter" in content:
analysis_result["recommendations"].append("نوصي باستخدام --noconsole لتطبيقات GUI")
if "requests" in content or "urllib" in content:
analysis_result["recommendations"].append("تأكد من إضافة شهادات SSL إذا كان التطبيق يتصل بالإنترنت")
return analysis_result
def BuildWithUPX(self, cmd: List[str], upx_dir: str) -> List[str]:
if upx_dir and os.path.isdir(upx_dir):
cmd.extend(["--upx-dir", upx_dir])
return cmd
def SavePreset(self, name: str, data: Dict) -> str:
path = os.path.join(self.presets_dir, f"{name}.json")
try:
with open(path, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
except Exception as e:
print(f"[Preset] Failed to save preset: {e}")
return path
def LoadPreset(self, name: str) -> Dict:
path = os.path.join(self.presets_dir, f"{name}.json")
if not os.path.isfile(path):
return {}
try:
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
return data
except Exception as e:
print(f"[Preset] Failed to load preset: {e}")
return {}
def ListPresets(self) -> List[str]:
files = [f[:-5] for f in os.listdir(self.presets_dir) if f.endswith(".json")]
return files
def DeletePreset(self, name: str):
path = os.path.join(self.presets_dir, f"{name}.json")
try:
os.remove(path)
except FileNotFoundError:
pass
except Exception as e:
print(f"[Preset] Failed to delete preset: {e}")
def CopyToClipboard(self, text: str):
try:
CF_UNICODETEXT = 13
ctypes.windll.user32.OpenClipboard(0)
ctypes.windll.user32.EmptyClipboard()
hCd = ctypes.windll.kernel32.GlobalAlloc(0x2000, (len(text) + 1) * 2)
lpCd = ctypes.windll.kernel32.GlobalLock(hCd)
ctypes.cdll.msvcrt.wcscpy(lpCd, text)
ctypes.windll.kernel32.GlobalUnlock(hCd)
ctypes.windll.user32.SetClipboardData(CF_UNICODETEXT, hCd)
ctypes.windll.user32.CloseClipboard()
except Exception as e:
print(f"[Clipboard] Failed to copy: {e}")
def GetScriptPaths(ui) -> list:
if ui.modeCombo.currentIndex() == 0:
path = ui.entryLine.text().strip()
return [path] if path else []
else:
return [ui.entryList.item(i).text() for i in range(ui.entryList.count())]
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.settings = {}
self.LoadSettings()
self.lang_manager = LanguageManager()
self.lang_manager.LoadLanguages("ar")
self.setWindowTitle(self.lang_manager.tr("app_title", "From Python To Executable v3.1.0"))
self.resize(1200, 800)
self.icon_path = r"icon\icon.png" if os.path.isfile(r"icon\icon.png") else None
self.shield_icon = r"icon\run.ico" if os.path.isfile(r"icon\run.ico") else self.icon_path
if self.icon_path:
self.setWindowIcon(QIcon(self.icon_path))
self.info_label = QLabel()
self.info_label.setWordWrap(True)
self.info_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
self.info_label.setStyleSheet("background-color: rgba(255, 255, 255, 0.8); border: 1px solid #ccc; padding: 5px;")
self.info_label.setMinimumHeight(100)
self.interval_ms = 1000
self.settings = {}
self.thread = None
self.worker = None
self._indeterminate = False
self.LoadSettings()
self.CreateBackup()
self.lang_manager = LanguageManager()
self.LoadLanguagesFromSettings()
self.__CreateMenus__()
self.CreateMenusGUI()
self.setAcceptDrops(True)
self.__ApplySettingsGUI__()
self.ui_timer = QTimer()
self.ui_timer.setInterval(1000)
self.ui_timer.timeout.connect(self.__UpdateSysLabelUsing__)
self.ui_timer.start()
self.apply_theme()
try:
self.plugin_manager = PluginManager(PLUGINS_DIR)
self.plugin_manager.LoadPlugins()
except Exception as e:
print(f"[Plugin] Failed to load plugins: {e}")
def RestartApplication(self):
exe_path = os.path.abspath(sys.argv[0])
bat_path = os.path.join(tempfile.gettempdir(), "restart_pytoexe.bat")
with open(bat_path, "w", encoding="utf-8") as bat:
bat.write(f"""@echo off
timeout /t 1 >nul
start "" "{exe_path}"
exit
""")
os.startfile(bat_path)
QCoreApplication.quit()
def ChangeLanguage(self, lang_code: str):
if self.lang_manager.LoadLanguages(lang_code):
self.settings["language"] = lang_code
self.SaveSettings()
self.RefreshGUI()
msg = {
"ar": "تم تغيير اللغة إلى (العربية)",
"en": "Language changed to (English)",
"fr": "La langue a été changée en (Français)",
"ru": "Язык изменён на (Русский)",
"zh": "语言已更改为 (中文)"
}.get(lang_code, "Language changed.")
restart_q = {
"ar": "هل تريد إعادة تشغيل البرنامج الآن لتطبيق التغييرات؟",
"en": "Do you want to restart now to apply changes?",
"fr": "Voulez-vous redémarrer maintenant pour appliquer les modifications ?",
"ru": "Хотите перезапустить сейчас?",
"zh": "是否现在重新启动?"
}.get(lang_code, "Restart now?")
QMessageBox.information(self,
self.lang_manager.tr("language", "اللغة"),
msg)
reply = QMessageBox.question(self,
self.lang_manager.tr("language", "اللغة"),
restart_q,
QMessageBox.Yes | QMessageBox.No)
if reply == QMessageBox.Yes:
self.RestartApplication()
def LoadLanguagesFromSettings(self):
try:
if not hasattr(self, 'settings') or not self.settings:
self.LoadSettings()
lang = self.settings.get("language", "ar")
if isinstance(lang, list):
lang = lang[0] if lang else "ar"
if not isinstance(lang, str):
lang = "ar"
if not self.lang_manager.LoadLanguages(lang):
print(f"[Language] Failed to load {lang}, using Arabic")
self.lang_manager.LoadLanguages("ar")
except Exception as e:
print(f"[Language] Failed to load language from settings: {e}")
self.lang_manager.LoadLanguages("ar")
def RefreshGUI(self):
self.ApplyLanguage()
self.apply_theme()
def ApplyLanguage(self):
tr = self.lang_manager.tr
self.setWindowTitle(self.lang_manager.tr("app_title", "from Python To Executable v3.1.0"))
self.UpdateMenusText()
self.UpdateTextGUI()
def UpdateMenusText(self):
tr = self.lang_manager.tr
self.menuBar().actions()[0].setText(tr("file_menu", "قائمة الملف"))
def UpdateTextGUI(self):
tr = self.lang_manager.tr
if not hasattr(self, "tab_basic"):
return
self.tab_basic.setText(tr("tab_basic", "أساسي"))
self.tab_advanced.setText(tr("tab_advanced", "متقدم"))
self.tab_version.setText(tr("tab_version", "معلومات الإصدار"))
self.tab_security.setText(tr("tab_security", "الأمان"))
self.entryLabel.setText(tr("options_os_system", "خيارات نظام التشغيل"))
self.modeCombo.setItemText(0, tr("single_file"))
self.modeCombo.setItemText(1, tr("batch_files"))
self.entryBtn.setText(tr("choose_file"))
self.addEntryBtn.setText(tr("add_script"))
self.remEntryBtn.setText(tr("remove_selected"))
self.oneFileChk.setText(tr("one_file"))
self.consoleChk.setText(tr("show_console"))
self.cleanChk.setText(tr("clean_before"))
self.buildSystemCombo.setItemText(0, tr("PyInstaller", "PyInstaller تجميع شامل"))
self.buildSystemCombo.setItemText(1, tr("cx_Freeze", "cx_Freeze تجميع تقليدي"))
self.buildSystemCombo.setItemText(2, tr("Nuitka", "Nuitka C مترجم لغة"))
self.buildSystemCombo.setItemText(3, tr("PyOxidizer", "PyOxidizer Rustمدمج بـ"))
self.platformCombo.setItemText(0, tr("Windows 32-bit (win32)", "Windows 32-bit (win32)"))
self.platformCombo.setItemText(1, tr("Windows 64-bit (win64)", "Windows 64-bit (win64)"))
self.platformCombo.setItemText(2, tr("Linux", "Linux"))
self.platformCombo.setItemText(3, tr("macOS", "macOS"))
self.templateCombo.setItemText(0, tr("Application (GUI)", "تطبيق واجهة رسومية (GUI)"))
self.templateCombo.setItemText(1, tr("Application (CLI)", "تطبيق وحدة التحكم (CLI)"))
self.templateCombo.setItemText(2, tr("Application (Service)", "تطبيق خدمة (Service)"))
self.templateCombo.setItemText(3, tr("Application (Web)", "تطبيق ويب (Web)"))
self.templateCombo.setItemText(4, tr("Custom (Custom)", "مخصص (Custom)"))
self.optimizeChk.setText(tr("enable_optimizations"))
self.stripChk.setText(tr("strip_info"))
self.noPreferRedirectChk.setText(tr("disable_redirect"))
self.obfuscateChk.setText(tr("obfuscation"))
self.antiDebugChk.setText(tr("anti_debug"))
self.packerChk.setText(tr("packer"))
self.certFileBtn.setText(tr("choose_certificate"))
self.certPassEdit.setPlaceholderText(tr("cert_password"))
self.timestampCombo.setItemText(0, tr("http://timestamp.digicert.com", "http://timestamp.digicert.com"))
self.timestampCombo.setItemText(1, tr("http://timestamp.comodoca.com", "http://timestamp.comodoca.com"))
self.timestampCombo.setItemText(2, tr("http://timestamp.globalsign.com", "http://timestamp.globalsign.com"))
self.addFileBtn.setText(tr("add_file"))
self.remFileBtn.setText(tr("remove_file"))
self.addFolderBtn.setText(tr("add_folder"))
self.remFolderBtn.setText(tr("remove_folder"))
self.compressionCombo.setItemText(0, tr("compression_levels.0", "بدون ضغط"))
self.compressionCombo.setItemText(1, tr("compression_levels.1", "ضغط عادي"))
self.compressionCombo.setItemText(2, tr("compression_levels.2", "ضغط عالي"))
self.encryptionChk.setText(tr("encrypt_resources"))
self.outBtn.setText(tr("choose_output"))
self.iconBtn.setText(tr("choose_icon"))
self.manifestBtn.setText(tr("choose_manifest"))
self.buildBtn.setText(tr("start_build_button"))
self.cancelBtn.setText(tr("cancel"))
self.runAfterChk.setText(tr("run_after"))
self.sysUsageLabel.setText(tr("sys_usage", "CPU: -% RAM: -%"))
self.cmdPreview.setPlaceholderText(tr("command_placeholder"))
self.log.setPlaceholderText(tr("log_placeholder"))
self.reportText.setPlaceholderText(tr("report_placeholder"))
self.saveLogBtn.setText(tr("save_log"))
self.openDistBtn.setText(tr("open_output"))
self.openBuildBtn.setText(tr("open_build"))
self.testOutputBtn.setText(tr("test_output"))
self.setWindowTitle(tr("app_title"))
try:
QApplication.processEvents()
self.repaint()
mb = self.menuBar()
if mb:
mb.update()
except Exception:
pass
try:
menubar = self.menuBar()
for action in menubar.actions():
text = action.text().lower()
if "language" in text or "اللغة" in text:
action.setText(tr("language_menu", "اللغة"))
if "file" in text or "الملف" in text:
action.setText(tr("file_menu", "الملف"))
if "build" in text or "البناء" in text:
action.setText(tr("build_menu", "البناء"))
if "tools" in text or "أدوات" in text:
action.setText(tr("tools_menu", "أدوات"))
if "view" in text or "المظهر" in text:
action.setText(tr("view_menu", "المظهر"))
if "settings" in text or "الإعدادات" in text:
action.setText(tr("settings_menu", "الإعدادات"))
if "help" in text or "مساعدة" in text:
action.setText(tr("help_menu", "مساعدة"))
if "about" in text or "حول" in text:
action.setText(tr("about_menu", "حول"))
if "exit" in text or "خروج" in text:
action.setText(tr("exit_menu", "خروج"))
action.triggered.connect(self.close)
except Exception:
pass
try:
addtab = addtab = self.tabWidget.widget(0)
addtab.setTitle(tr("tab_basic", "أساسي", "Basic", "Basique", "Базовый", "基础"))
except Exception:
pass
try:
addtab = self.tabWidget.widget(1)
addtab.setTitle(tr("tab_advanced", "متقدم", "Advanced", "Avancé", "Продвинутый", "高级"))
except Exception:
pass
try:
addtab = self.tabWidget.widget(2)
addtab.setTitle(tr("tab_version", "معلومات الإصدار", "Version Info", "Infos de version", "Информация о версии", "版本信息"))
except Exception:
pass
try:
addtab = self.tabWidget.widget(3)
addtab.setTitle(tr("tab_security", "الأمان", "Security", "Sécurité", "Безопасность", "安全"))
except Exception:
pass
try:
addtab = self.tabWidget.widget(4)
addtab.setTitle(tr("tab_resources", "الموارد", "Resources", "Ressources", "Ресурсы", "资源"))
except Exception:
pass
try:
addtab = self.tabWidget.widget(5)
addtab.setTitle(tr("tab_log", "السجل", "Log", "Journal", "Журнал", "日志"))
except Exception:
pass
try: # entryLabel خيارات نظام التشغيل
addtab = self.entryLabel
addtab.setText(tr("options_os_system", "خيارات نظام التشغيل", "OS System Options", "Options du système d'exploitation", "Параметры ОС", "操作系统选项"))
except Exception:
pass
def LoadSettings(self):
if os.path.isfile(SETTINGS_FILE):
try:
with open(SETTINGS_FILE, "r", encoding="utf-8") as f:
self.settings = json.load(f)
except Exception as e:
print(f"[Settings] Failed to load settings: {e}")
self.settings = DEFAULT_SETTINGS.copy()
else:
self.settings = DEFAULT_SETTINGS.copy()
def CreateBackup(self):
os.makedirs(BACKUP_DIR, exist_ok=True)
timestamp = time.strftime("%Y%m%d_%H%M%S")
backup_file = os.path.join(BACKUP_DIR, f"settings_backup_{timestamp}.json")
try:
shutil.copy2(SETTINGS_FILE, backup_file)
except Exception:
pass
def SaveSettings(self):
self.settings["onefile"] = self.oneFileChk.isChecked()
self.settings["noconsole"] = not self.consoleChk.isChecked()
self.settings["clean"] = self.cleanChk.isChecked()
self.settings["last_output"] = self.outLine.text().strip()
self.settings["last_icon"] = self.iconLine.text().strip()
self.settings["last_manifest"] = self.manifestLine.text().strip()
self.settings["last_entries"] = [self.entryList.item(i).text() for i in range(self.entryList.count())]
self.settings["last_files"] = [self.filesList.item(i).text() for i in range(self.filesList.count())]
self.settings["last_folders"] = [self.foldersList.item(i).text() for i in range(self.foldersList.count())]
self.settings["python_interpreter"] = self.interpCombo.currentText()
self.settings["language"] = self.lang_manager.current_language
self.settings["advanced"] = {
"hidden_imports": [s.strip() for s in self.hiddenImportsLine.text().split(",") if s.strip()],
"exclude_modules": [s.strip() for s in self.excludeModulesLine.text().split(",") if s.strip()],
"uac_admin": self.uacChk.isChecked(),
"key": self.keyLine.text().strip(),
"optimize": self.optimizeChk.isChecked(),
"strip": self.stripChk.isChecked(),
"no_prefer_redirect": self.noPreferRedirectChk.isChecked(),
"obfuscate": self.obfuscateChk.isChecked(),
"anti_debug": self.antiDebugChk.isChecked(),
"packer": self.packerChk.isChecked()
}
self.settings["version_info"] = {
"version": self.versionEdit.text().strip(),
"company": self.companyEdit.text().strip(),
"copyright": self.copyrightEdit.text().strip(),
"description": self.descriptionEdit.text().strip()
}
self.settings["security"] = {
"sign_certificate": self.certFileEdit.text().strip(),
"cert_password": self.certPassEdit.text().strip(),
"timestamp_server": self.timestampCombo.currentText()
}
self.settings["build_system"] = self.buildSystemCombo.currentText()
self.settings["platform"] = self.platformCombo.currentText()
self.settings["virtual_env"] = self.virtualEnvCombo.currentText()
self.settings["template"] = self.templateCombo.currentText()
self.settings["resource_compression"] = self.compressionCombo.currentText()
self.settings["resource_encryption"] = self.encryptionChk.isChecked()
try:
with open(SETTINGS_FILE, "w", encoding="utf-8") as f:
json.dump(self.settings, f, ensure_ascii=False, indent=2)
except Exception as e:
QMessageBox.warning(self, "حفظ الإعدادات", f"فشل حفظ الإعدادات: {e}")
def __ApplySettingsGUI__(self):
self.entryList.clear()
for p in self.settings.get("last_entries", []):
self.entryList.addItem(p)
self.filesList.clear()
for p in self.settings.get("last_files", []):
self.filesList.addItem(p)
self.foldersList.clear()
for p in self.settings.get("last_folders", []):
self.foldersList.addItem(p)
self.outLine.setText(self.settings.get("last_output", os.path.abspath("output")))
self.iconLine.setText(self.settings.get("last_icon", ""))
self.manifestLine.setText(self.settings.get("last_manifest", ""))
self.oneFileChk.setChecked(self.settings.get("onefile", True))
self.consoleChk.setChecked(not self.settings.get("noconsole", False))
self.cleanChk.setChecked(self.settings.get("clean", True))
adv = self.settings.get("advanced", {})
self.hiddenImportsLine.setText(", ".join(adv.get("hidden_imports", [])))
self.excludeModulesLine.setText(", ".join(adv.get("exclude_modules", [])))
self.uacChk.setChecked(adv.get("uac_admin", False))
self.keyLine.setText(adv.get("key", ""))
self.optimizeChk.setChecked(adv.get("optimize", False))
self.stripChk.setChecked(adv.get("strip", False))
self.noPreferRedirectChk.setChecked(adv.get("no_prefer_redirect", False))
self.obfuscateChk.setChecked(adv.get("obfuscate", False))
self.antiDebugChk.setChecked(adv.get("anti_debug", False))
self.packerChk.setChecked(adv.get("packer", False))
version_info = self.settings.get("version_info", {})
self.versionEdit.setText(version_info.get("version", "1.0.0"))
self.companyEdit.setText(version_info.get("company", ""))
self.WebSiteEdit.setText(version_info.get("WebSite", ""))
self.copyrightEdit.setText(version_info.get("copyright", ""))
self.descriptionEdit.setText(version_info.get("description", ""))
security = self.settings.get("security", {})
self.certFileEdit.setText(security.get("sign_certificate", ""))
self.certPassEdit.setText(security.get("cert_password", ""))
timestamp_server = security.get("timestamp_server", "http://timestamp.digicert.com")
index = self.timestampCombo.findText(timestamp_server)
if index >= 0:
self.timestampCombo.setCurrentIndex(index)
build_system = self.settings.get("build_system", "PyInstaller")
index = self.buildSystemCombo.findText(build_system)
if index >= 0:
self.buildSystemCombo.setCurrentIndex(index)
platform = self.settings.get("platform", "win32")
index = self.platformCombo.findText(platform)
if index >= 0:
self.platformCombo.setCurrentIndex(index)
virtual_env = self.settings.get("virtual_env", "")
if virtual_env:
index = self.virtualEnvCombo.findText(virtual_env)
if index >= 0:
self.virtualEnvCombo.setCurrentIndex(index)
else:
self.virtualEnvCombo.setEditText(virtual_env)
template = self.settings.get("template", "مخصص (Custom)")
index = self.templateCombo.findText(template)
if index >= 0:
self.templateCombo.setCurrentIndex(index)
compression = self.settings.get("resource_compression", "normal")
index = self.compressionCombo.findText(compression)
if index >= 0:
self.compressionCombo.setCurrentIndex(index)
self.encryptionChk.setChecked(self.settings.get("resource_encryption", False))
python_interpreter = self.settings.get("python_interpreter", "")
if python_interpreter:
index = self.interpCombo.findText(python_interpreter)
if index >= 0:
self.interpCombo.setCurrentIndex(index)
else:
self.interpCombo.setEditText(python_interpreter)
def ResetSettings(self):
reply = QMessageBox.question(self, self.lang_manager.tr("reset_settings", "إعادة التعيين"), self.lang_manager.tr("reset_confirm", "هل تريد إعادة الإعدادات إلى الوضع الافتراضي؟"), QMessageBox.Yes | QMessageBox.No)
if reply == QMessageBox.Yes:
self.settings = DEFAULT_SETTINGS.copy()
try:
if os.path.isfile(SETTINGS_FILE):
os.remove(SETTINGS_FILE)
except Exception:
pass
self.__ApplySettingsGUI__()
QMessageBox.information(self, self.lang_manager.tr("reset_complete", "تم"), self.lang_manager.tr("reset_complete", "تمت إعادة التعيين للإعدادات الافتراضية."))
def __AnalyzeMissingModules__(self):
self.extra = PyInstallerExtras()
script_paths = GetScriptPaths(self)
if not script_paths:
QMessageBox.warning(self, self.lang_manager.tr("analyze", "تحليل"), self.lang_manager.tr("no_inputs", "رجاءً اختر ملف أو سكربتات أولاً."))
return
all_missing = []
for script in script_paths:
missing = self.extra.AnalyzeMissingImports(script)
if missing:
all_missing.extend(missing)
if all_missing:
QMessageBox.information(
self,
"نتائج التحليل",
f"الموديولات المفقودة:\n{', '.join(set(all_missing))}"