v2.8.0: Add project directory support, improve dependency resolution, and fix syntax injection

- Added direct project directory drag-and-drop support with automatic root workspace and requirements.txt detection
- Added smart entry script prioritization and interactive selection dialog for multi-script projects
- Expanded AST dependency analysis across the entire project workspace to capture sub-package imports
- Implemented local module and resource whitelisting to prevent unintended pip installations of local packages
- Expanded PyPI mappings and Auto-Hooks rules for C extensions and dynamic libraries (PyCryptodome, NaCl, pynput, etc.)
- Added automatic search path injection (`--paths` for PyInstaller and `PYTHONPATH` for Nuitka) for sub-directory entries
- Improved `requirements.txt` parser to safely handle inline comments and environment markers
- Added cross-hierarchy import detection and workspace configuration tips for standalone scripts
- Fixed SyntaxError caused by console pause code injection preceding `from __future__` statements
- Fixed TypeError crash caused by `os.walk` iteration variable shadowing the global translation function
Update QUICKSTART.md、README.MD...
This commit is contained in:
QwejayHuang committed 2026-08-31 19:57:05 +08:00
1 parent 1f24757a71
commit 448dbdbbf3
29 files changed
+2391 -369

No files matched your search

+149 -25
View File
@@ -14,70 +14,194 @@
</p>
<p align="center">
<strong>Ein plattformübergreifendes GUI-Tool zur Paketierung von Python-Anwendungen basierend auf PyInstaller & Nuitka</strong>
</p>
<p align="center">
<!-- PyPI Version -->
<a href="https://pypi.org/project/qpypack/">
<img src="https://img.shields.io/pypi/v/qpypack.svg?color=blue" alt="PyPI version" />
<img src="https://img.shields.io/pypi/v/qpypack.svg?color=blue&logo=pypi&logoColor=white" alt="PyPI version" />
</a>
<!-- Python Versions -->
<a href="https://pypi.org/project/qpypack/">
<img src="https://img.shields.io/pypi/pyversions/qpypack.svg" alt="Python versions" />
<img src="https://img.shields.io/pypi/pyversions/qpypack.svg?logo=python&logoColor=white" alt="Python versions" />
</a>
<!-- PyPI Downloads -->
<a href="https://pypistats.org/packages/qpypack">
<img src="https://img.shields.io/pypi/dm/qpypack?color=orange&logo=pypi&logoColor=white" alt="PyPI Downloads" />
</a>
<!-- Supported Platforms -->
<img src="https://img.shields.io/badge/platform-Windows%20%7C%20macOS%20%7C%20Linux-informational" alt="Platform Support" />
<br>
<!-- Release Date -->
<a href="https://github.com/Qwejay/QPyPack/releases">
<img src="https://img.shields.io/github/release-date/Qwejay/QPyPack?color=brightgreen&logo=github" alt="Release Date" />
</a>
<!-- Last Commit -->
<a href="https://github.com/Qwejay/QPyPack/commits/main">
<img src="https://img.shields.io/github/last-commit/Qwejay/QPyPack" alt="Last Commit" />
</a>
<!-- GitHub License -->
<a href="https://github.com/Qwejay/QPyPack/blob/main/LICENSE">
<img src="https://img.shields.io/github/license/Qwejay/QPyPack.svg" alt="License" />
</a>
<!-- GitHub Stars -->
<a href="https://github.com/Qwejay/QPyPack/stargazers">
<img src="https://img.shields.io/github/stars/Qwejay/QPyPack.svg" alt="GitHub stars" />
<img src="https://img.shields.io/github/stars/Qwejay/QPyPack.svg?logo=github&color=gold" alt="GitHub stars" />
</a>
</p>
QPyPack ist ein visuelles GUI-Tool zur Vereinfachung des Build-Prozesses von Python-Anwendungen. Es integriert PyInstaller und Nuitka nahtlos und wandelt komplexe Befehlszeilenparameter in eine intuitive grafische Benutzeroberfläche um.
---
<p align="center">
<strong>Modernes, einsatzbereites plattformübergreifendes GUI-Tool zur Paketierung von Python-Anwendungen</strong><br>
<sub>Angetrieben von PyInstaller und Nuitka, mit visueller Konfiguration, statischer Abhängigkeitsanalyse und automatisiertem Build-Workflow.</sub>
</p>
## 📌 Projektübersicht (Overview)
**QPyPack** ist ein plattformübergreifendes grafisches Paketierungstool für Python-Entwickler. Durch die nahtlose Integration der beiden Haupt-Engines **PyInstaller** (Bytecode-Bündelung) und **Nuitka** (native C/C++-Kompilierung) werden komplexe Compiler-Toolchains, implizite Abhängigkeitsanalysen, Sandbox-Isolation und Ressourcenextraktion in einer intuitiven Benutzeroberfläche abstrahiert.
Egal ob Sie einfache Automatisierungsskripte oder komplexe Desktop- und Serveranwendungen (mit PySide6/PyQt, Playwright, CustomTkinter, FastAPI etc.) verteilen möchten: QPyPack bietet einen stabilen, hochgradig reproduzierbaren Build-Prozess unter Windows, macOS und Linux.
---
## 📷 Screenshots
## 📸 Screenshots
<p align="center">
<img width="1143" height="1067" alt="image" src="https://github.com/user-attachments/assets/8658aaef-5867-470d-ba4d-07892309ab1a" />
<img width="1142" height="1067" alt="image" src="https://github.com/user-attachments/assets/b64d9b89-8bfd-4bf8-8fec-9c75f61305dd" />
<img width="32%" alt="Hauptfenster (Englisch)" src="https://github.com/user-attachments/assets/9d16c68e-d283-4020-86c1-9d4791756c29" />
<img width="32%" alt="Hauptfenster (Chinesisch)" src="https://github.com/user-attachments/assets/0147460d-1e9e-4612-9b52-9d347d81b7c5" />
<img width="32%" alt="Engine & Umgebung" src="https://github.com/user-attachments/assets/0ad4db6d-b008-4018-bd69-40a369a10b7d" />
<br />
<img width="32%" alt="Abhängigkeitsverwaltung" src="https://github.com/user-attachments/assets/c7fd1218-d079-4898-a97c-aa980c4d1375" />
<img width="32%" alt="Optimierung & Signierung" src="https://github.com/user-attachments/assets/e5b7500e-2a0d-4c6d-b20b-7d8d2d3bac8d" />
<img width="32%" alt="Über & Diagnose" src="https://github.com/user-attachments/assets/e652b222-49f5-44cd-ad3f-d93369ede26b" />
</p>
---
## 🚀 Hauptfunktionen
## 🛠️ Hauptfunktionen & Architektur
* 📥 **Drag & Drop** : Ziehen Sie `.py`- oder `.pyw`-Skripte direkt in das Anwendungsfenster.
* 🎨 **Automatische Icon-Erkennung** : Erkennt automatisch Bilddateien im Quellordner und wandelt diese um.
* 🛡️ **Virtuelle Umgebung (Sandbox)** : Erstellt automatisch eine isolierte Umgebung zur Minimierung der Ausgabegröße.
* 🔍 **Abhängigkeitsanalyse** : Erkennt `requirements.txt` und führt statische AST-Code-Analysen für verdeckte Importe durch.
* ⚙️ **Dual-Engine-Unterstützung** : Wechseln Sie nahtlos zwischen PyInstaller und Nuitka.
* 📝 **App-Metadaten-Injektion** : Fügen Sie Versionsnummern und Beschreibungen direkt in die Binärdatei ein.
### 1. Dual-Engine-Kompilierung & Binäroptimierung
* **Nahtloser Wechsel zwischen zwei Engines**:
* **PyInstaller**: Schnelle Build-Zeiten, keine C-Compiler-Abhängigkeit, hervorragende Kompatibilität.
* **Nuitka**: Übersetzt Python-Code direkt in native C/C++-Binärdateien für hohe Ausführungsgeschwindigkeit, starken Schutz gegen Reverse-Engineering und kompakte Ausgabegröße.
* **LTO-Linkzeitoptimierung & Modulbereinigung**: Unterstützt `--lto=yes` im Lite-Modus; ungenutzte schwere Qt-Submodule (z. B. `WebEngine`, `3D`, `Quick`) werden automatisch erkannt und entfernt, um Dateigrößen-Overhead zu vermeiden.
* **Flexible Ausgabeformate**: Unterstützt **Einzeldatei- (`--onefile`)** und **Verzeichnis-Modus (`--onedir`)** sowie benutzerdefinierte interne Ressourcenpfade (`--contents-directory`).
### 2. Statische Codeanalyse & Topologieschutz
* **Natives rekursives AST-Scanning**: Analysiert abstrakte Syntaxbäume (AST) direkt in Python, um explizite und implizite Importe (Hidden Imports) ohne Programmausführung zu erfassen.
* **Intelligentes Paket-Mapping**: Enthält Zuordnungstabellen für gängige Import- und PyPI-Paketnamen (z. B. `cv2` $\to$ `opencv-python`, `PIL` $\to$ `pillow`, `win32com` $\to$ `pywin32`), modular erweiterbar.
* **Automatische Backport-Isolation**: Erkennt und blockiert veraltete Backport-Bibliotheken, die mit modernen Standardbibliotheken kollidieren (z. B. `pathlib` oder `typing` unter Python 3.10+).
### 3. Automatisiertes Umgebungsmanagement & Selbstheilung
* **Automatische C/C++-Compiler-Verwaltung**: Erkennt lokale MSVC-, Clang- (LLVM) und GCC-Installationen. Falls kein nativer Compiler vorhanden ist, lädt Nuitka automatisch eine MinGW-w64-Toolchain herunter.
* **Lebenszyklus virtueller Umgebungen**: Unterstützt isolierte Sandkästen sowie wiederverwendbare geteilte virtuelle Umgebungen mit Bereinigungsfunktion.
* **Ressourcenüberwachung & Fehlerselbstheilung**:
* Bewertet vor dem Build RAM und Festplattenspeicher und passt die Thread-Parallelität (Adaptive Concurrency) an.
* Fängt Speicherengpässe (`ZstdError` / OOM) ab und wiederholt den Build im Single-Thread-Modus.
* Umgeht Dateisperren durch Antivirenprogramme oder Cloud-Synchronisationsdienste.
### 4. Codesignatur & Projekt-Voreinstellungen
* **Intelligente digitale Signatur**: Signiert Windows-Binärdateien automatisch via Authenticode (unterstützt Signtool und PowerShell mit RFC 3161 Zeitstempeln) sowie macOS `codesign`.
* **Zertifikat-Suite**: Integrierter Generator für selbstsignierte `.pfx`-Zertifikate und Unterstützung für kommerzielle Zertifikate.
* **Projekt-Presets (Import/Export)**: Speichert alle Build-Parameter, Ressourcenlisten und Mappings in portable `.qpypack`-Dateien.
### 5. Benutzererlebnis & Lokalisierung
* **Intuitive Drag & Drop-Bedienung**: Automatisches Auslesen von Modul-Metadaten (`__version__`, `__author__`, App-Titel) und Zuweisung von Programmsymbolen.
* **Google Material Vektor-UI**: Skaliert verlustfrei auf High-DPI/4K-Monitoren. Enthält Übersetzungen für 17 Sprachen (Deutsch, Englisch, Chinesisch, Japanisch, Koreanisch, Französisch, Spanisch etc.).
---
## ⚡ Schnellstart
## 📊 Engine-Vergleich (PyInstaller vs. Nuitka)
| Kriterium | PyInstaller | Nuitka |
| :--- | :--- | :--- |
| **Funktionsweise** | Bündelt Python-Interpreter + Bytecode (`.pyc`) | Kompiliert Python-Code zu nativen C/C++-Binärdateien |
| **Build-Geschwindigkeit** | Sehr schnell (typisch 10 – 60 s) | Moderat bis langsam (erfordert C++-Kompilierung) |
| **Compiler-Bedarf** | Keiner | Erforderlich (MSVC / GCC / Clang / MinGW-w64) |
| **Code-Schutz** | Basis (über Dekompilierer einsehbar) | Extrem hoch (Maschinencode, hoher Reverse-Engineering-Schutz) |
| **Ausführungsleistung** | Standard Python-Geschwindigkeit | Sehr schneller Start, optimierte Schleifen/Berechnungen |
| **Empfohlen für** | Schnelles Prototyping, interne Tools, dynamische Skripte | Kommerzielle Distribution, Schutz geistigen Eigentums, kompakte Größe |
---
## ⚡ Schnellstart (Quick Start)
> 💡 **Erste Schritte?** Konsultieren Sie unsere [**📖 Kurzanleitung (QUICKSTART.md)**](../../QUICKSTART.md) für Schritt-für-Schritt-Anweisungen und empfohlene Konfigurationen.
### Methode 1: Installation über pip / pipx (Empfohlen)
Voraussetzung: Python >= 3.8
```bash
# Über pip installieren
# Installation via pip
pip install qpypack
# Anwendung starten
qpypack
```
Alternativ können Sie vorkompilierte Dateien von der [GitHub Release-Seite](https://github.com/Qwejay/QPyPack/releases) herunterladen.
*Mit modernen Paketmanagern:*
```bash
# Isoliert über pipx
pipx run qpypack
# Ultraschnell über uv
uvx qpypack
```
### Methode 2: Vorkompilierte Binärdateien
Ohne lokale Python-Installation können Sie direkt kompilierte Binärdateien für Windows, macOS oder Linux herunterladen:
👉 [**Vorkompilierte Versionen herunterladen (GitHub Releases)**](https://github.com/Qwejay/QPyPack/releases)
---
## 📋 Pfadauflösung für Ressourcen (`sys._MEIPASS`)
Im Einzeldatei-Modus (`--onefile`) werden statische Dateien (Bilder, Konfigurationen, Modelle) zur Laufzeit temporär entpackt. Verwenden Sie folgendes Standardmuster zur Pfadauflösung:
```python
import sys
import os
from pathlib import Path
def get_asset_path(relative_path: str) -> Path:
"""Ermittelt den absoluten Pfad zu gepackten Ressourcen."""
if hasattr(sys, "_MEIPASS"):
# PyInstaller temporäres Extraktionsverzeichnis
base_path = Path(sys._MEIPASS)
elif "__compiled__" in globals():
# Nuitka natives Binärverzeichnis
base_path = Path(sys.argv[0]).resolve().parent
else:
# Lokale Entwicklungsumgebung
base_path = Path(__file__).resolve().parent
return base_path / relative_path
```
---
## 📅 Änderungsprotokoll (Changelog)
Die vollständige Versionshistorie finden Sie in [CHANGELOG.md](CHANGELOG.md) oder auf der [GitHub Releases-Seite](https://github.com/Qwejay/QPyPack/releases).
Ausführliche Versionshinweise und behobene Fehler finden Sie in [CHANGELOG.md](../../CHANGELOG.md).
---
## 📄 Lizenz
## 💖 Mitwirken & Sponsoring
Lizenziert unter der [GNU General Public License v3.0](LICENSE).
QPyPack ist ein Open-Source-Projekt. Wenn Ihnen das Tool bei Ihrer Arbeit geholfen hat, freuen wir uns über Ihre Unterstützung:
Copyright (C) 2026 QwejayHuang.
- 🌟 **Star vergeben**: Schenken Sie uns einen Stern auf [GitHub](https://github.com/Qwejay/QPyPack).
- 🐛 **Feedback & Fehlerberichte**: Erstellen Sie ein [Issue auf GitHub](https://github.com/Qwejay/QPyPack/issues).
- ⚡ **Sponsoring**: Unterstützen Sie das Projekt auf [Afdian (爱发电)](https://www.ifdian.net/a/qwejay) (WeChat / Alipay).
---
## 📄 Lizenz (License)
Lizenziert unter der [GNU General Public License v3.0 (GPL-3.0)](../../LICENSE).
> [!IMPORTANT]
> **Urheberrecht an kompilierten Binärdateien**:
> Die Rechte an Ihren mit QPyPack erstellten Anwendungen **verbleiben vollständig bei Ihnen**. Die GPL-3.0-Lizenz von QPyPack überträgt sich nicht auf Ihre kompilierten Programme.
<p align="right">Copyright (C) 2026 QwejayHuang.</p>
+149 -25
View File
@@ -14,70 +14,194 @@
</p>
<p align="center">
<strong>Herramienta GUI multiplataforma para empaquetar aplicaciones Python basada en PyInstaller y Nuitka</strong>
</p>
<p align="center">
<!-- PyPI Version -->
<a href="https://pypi.org/project/qpypack/">
<img src="https://img.shields.io/pypi/v/qpypack.svg?color=blue" alt="PyPI version" />
<img src="https://img.shields.io/pypi/v/qpypack.svg?color=blue&logo=pypi&logoColor=white" alt="PyPI version" />
</a>
<!-- Python Versions -->
<a href="https://pypi.org/project/qpypack/">
<img src="https://img.shields.io/pypi/pyversions/qpypack.svg" alt="Python versions" />
<img src="https://img.shields.io/pypi/pyversions/qpypack.svg?logo=python&logoColor=white" alt="Python versions" />
</a>
<!-- PyPI Downloads -->
<a href="https://pypistats.org/packages/qpypack">
<img src="https://img.shields.io/pypi/dm/qpypack?color=orange&logo=pypi&logoColor=white" alt="PyPI Downloads" />
</a>
<!-- Supported Platforms -->
<img src="https://img.shields.io/badge/platform-Windows%20%7C%20macOS%20%7C%20Linux-informational" alt="Platform Support" />
<br>
<!-- Release Date -->
<a href="https://github.com/Qwejay/QPyPack/releases">
<img src="https://img.shields.io/github/release-date/Qwejay/QPyPack?color=brightgreen&logo=github" alt="Release Date" />
</a>
<!-- Last Commit -->
<a href="https://github.com/Qwejay/QPyPack/commits/main">
<img src="https://img.shields.io/github/last-commit/Qwejay/QPyPack" alt="Last Commit" />
</a>
<!-- GitHub License -->
<a href="https://github.com/Qwejay/QPyPack/blob/main/LICENSE">
<img src="https://img.shields.io/github/license/Qwejay/QPyPack.svg" alt="License" />
</a>
<!-- GitHub Stars -->
<a href="https://github.com/Qwejay/QPyPack/stargazers">
<img src="https://img.shields.io/github/stars/Qwejay/QPyPack.svg" alt="GitHub stars" />
<img src="https://img.shields.io/github/stars/Qwejay/QPyPack.svg?logo=github&color=gold" alt="GitHub stars" />
</a>
</p>
QPyPack es una herramienta gráfica diseñada para simplificar el empaquetado de aplicaciones Python. Integra los motores PyInstaller y Nuitka, transformando comandos de consola en una interfaz intuitiva.
---
<p align="center">
<strong>Herramienta GUI moderna y lista para usar para empaquetar aplicaciones Python multiplataforma</strong><br>
<sub>Impulsada por los motores PyInstaller y Nuitka, con configuración visual, análisis estático de dependencias y flujo de compilación automatizado.</sub>
</p>
## 📌 Visión general del proyecto (Overview)
**QPyPack** es una herramienta gráfica multiplataforma diseñada para desarrolladores de Python. Al integrar de manera nativa los motores **PyInstaller** (empaquetado de bytecode) y **Nuitka** (compilación nativa C/C++), simplifica las cadenas de compilación complejas, el análisis de dependencias implícitas, el aislamiento de entornos y la recolección de recursos en una interfaz intuitiva.
Ya sea para distribuir scripts ligeros de automatización o aplicaciones de escritorio y servidor con dependencias complejas (como PySide6/PyQt, Playwright, CustomTkinter, FastAPI, etc.), QPyPack ofrece una experiencia de compilación estable, reproducible y con alta tasa de éxito en Windows, macOS y Linux.
---
## 📷 Capturas de pantalla (Screenshots)
## 📸 Capturas de pantalla (Screenshots)
<p align="center">
<img width="1143" height="1067" alt="image" src="https://github.com/user-attachments/assets/8658aaef-5867-470d-ba4d-07892309ab1a" />
<img width="1142" height="1067" alt="image" src="https://github.com/user-attachments/assets/b64d9b89-8bfd-4bf8-8fec-9c75f61305dd" />
<img width="32%" alt="Interfaz principal (Inglés)" src="https://github.com/user-attachments/assets/9d16c68e-d283-4020-86c1-9d4791756c29" />
<img width="32%" alt="Interfaz principal (Chino)" src="https://github.com/user-attachments/assets/0147460d-1e9e-4612-9b52-9d347d81b7c5" />
<img width="32%" alt="Motor y Entorno" src="https://github.com/user-attachments/assets/0ad4db6d-b008-4018-bd69-40a369a10b7d" />
<br />
<img width="32%" alt="Gestión de dependencias" src="https://github.com/user-attachments/assets/c7fd1218-d079-4898-a97c-aa980c4d1375" />
<img width="32%" alt="Optimización y Firma" src="https://github.com/user-attachments/assets/e5b7500e-2a0d-4c6d-b20b-7d8d2d3bac8d" />
<img width="32%" alt="Acerca de y Diagnósticos" src="https://github.com/user-attachments/assets/e652b222-49f5-44cd-ad3f-d93369ede26b" />
</p>
---
## 🚀 Características principales
## 🛠️ Arquitectura y características principales
* 📥 **Arrastrar y Soltar** : Arrastre archivos `.py` o `.pyw` directamente a la ventana.
* 🎨 **Detección de icono automática** : Convierte y previsualiza iconos del directorio fuente.
* 🛡️ **Aislamiento en entorno virtual** : Crea entornos virtuales automáticamente para reducir el tamaño final.
* 🔍 **Análisis de dependencias** : Lectura de `requirements.txt` y análisis estático de código AST para importaciones ocultas.
* ⚙️ **Conmutación de motor doble** : Cambie libremente entre PyInstaller y Nuitka.
* 📝 **Inyección de metadatos** : Configure la versión, autor y descripción directamente desde la interfaz.
### 1. Motor dual de compilación y optimización binaria
* **Conmutación fluida entre motores**:
* **PyInstaller**: Compilación rápida, sin dependencias de compilador C, excelente compatibilidad con el ecosistema.
* **Nuitka**: Traduce código Python a binarios C/C++ nativos para un rendimiento superior, máxima protección contra ingeniería inversa y tamaño reducido.
* **Optimización LTO y poda de submódulos**: Soporte para optimización en tiempo de enlace (`--lto=yes`) en modo Lite. Detección y exclusión automática de submódulos Qt pesados no utilizados (WebEngine, 3D, Quick, etc.) para evitar el sobrepeso binario.
* **Formatos de distribución flexibles**: Compatible con modo de **Archivo único (`--onefile`)** y modo **Directorio (`--onedir`)**, con personalización del directorio interno de dependencias (`--contents-directory`).
### 2. Análisis estático y protección de dependencias
* **Escaneo AST recursivo nativo**: Analizador estático de árbol de sintaxis abstracta (AST) en Python puro que descubre importaciones explícitas e implícitas sin ejecutar el código.
* **Mapeo inteligente de paquetes**: Tabla de correspondencia integrada entre nombres de importación y paquetes PyPI (ej. `cv2` $\to$ `opencv-python`, `PIL` $\to$ `pillow`, `win32com` $\to$ `pywin32`), modular y extensible.
* **Aislamiento dinámico de bibliotecas obsoletas (Backport Isolation)**: Detecta y bloquea paquetes de retrocompatibilidad que entren en conflicto con la biblioteca estándar moderna (ej. aislando `pathlib` o `typing` en Python 3.10+).
### 3. Gestión automatizada del entorno y autorreparación
* **Aprovisionamiento automático de compiladores C/C++**: Detecta entornos locales MSVC, Clang (LLVM) y GCC. Si no hay compilador nativo, Nuitka descarga y gestiona automáticamente una cadena MinGW-w64.
* **Gestión del ciclo de vida de entornos virtuales**: Admite sandboxes aislados y entornos virtuales compartidos, con utilidad de limpieza integrada.
* **Gestión adaptativa de recursos y autorrecuperación**:
* Evalúa RAM y espacio en disco antes de compilar, ajustando la concurrencia de hilos (Adaptive Concurrency).
* Captura errores de memoria saturada (`ZstdError` / OOM) y reintenta automáticamente en modo monohilo de bajo consumo.
* Evita bloqueos exclusivos de archivos temporales causados por antivirus o servicios de sincronización en la nube.
### 4. Firma de código y preajustes de proyecto
* **Firma digital inteligente**: Aplica firmas digitales Authenticode automáticamente a binarios de Windows (compatible con Signtool y PowerShell con sellado de tiempo RFC 3161) y firma en tiempo de ejecución `codesign` en macOS.
* **Suite de certificados**: Generador integrado de certificados autofirmados (`.pfx`) y soporte para certificados comerciales.
* **Importación/Exportación de preajustes**: Guarda todos los parámetros de compilación, recursos y reglas en archivos `.qpypack` compartibles.
### 5. Experiencia de usuario e internacionalización (i18n)
* **Arrastrar y soltar fluido**: Al soltar un script Python, extrae automáticamente los metadatos (`__version__`, `__author__`, nombre de la app), deduce el punto de entrada y mapea el icono de la aplicación.
* **Interfaz vectorial con soporte HiDPI**: Construida con iconos vectoriales Google Material SVG, con escalado perfecto en pantallas 4K. Traducida a 17 idiomas (español, inglés, chino, japonés, coreano, alemán, francés, etc.).
---
## ⚡ Inicio rápido
## 📊 Comparativa de motores (PyInstaller vs. Nuitka)
| Criterio | PyInstaller | Nuitka |
| :--- | :--- | :--- |
| **Principio** | Empaqueta intérprete de Python + bytecode (`.pyc`) | Compila código Python a binarios C/C++ nativos |
| **Velocidad de compilación** | Muy rápida (típicamente 10 – 60 s) | Más lenta (requiere generación de código C++ y optimización) |
| **Compilador C/C++** | No requerido | Requerido (gestión automática de MSVC / GCC / Clang / MinGW-w64) |
| **Nivel de protección** | Básico (código recuperable mediante descompiladores) | Extremadamente alto (código máquina, alta resistencia a ingeniería inversa) |
| **Rendimiento de ejecución**| Velocidad estándar de Python | Inicio más rápido, bucles y computación optimizados |
| **Recomendado para** | Prototipado rápido, herramientas internas, proyectos dinámicos | Software comercial, protección de algoritmos, optimización de tamaño |
---
## ⚡ Inicio rápido (Quick Start)
> 💡 **¿Primera vez usando QPyPack?** Consulte nuestra [**📖 Guía de inicio rápido (QUICKSTART.md)**](../../QUICKSTART.md) para un tutorial detallado y configuraciones recomendadas.
### Método 1: Instalación mediante pip / pipx (Recomendado)
Requiere Python >= 3.8:
```bash
# Instalar a través de pip
pip install qpypack
# Iniciar la aplicación
# Iniciar la interfaz gráfica
qpypack
```
Descargue ejecutables precompilados directamente en la página de [Releases de GitHub](https://github.com/Qwejay/QPyPack/releases).
*Con gestores de paquetes modernos:*
```bash
# Ejecutar aislado con pipx
pipx run qpypack
# Inicio ultrarrápido con uv
uvx qpypack
```
### Método 2: Versión binaria precompilada independiente
Sin necesidad de configurar Python localmente, descargue los ejecutables compilados directamente para su sistema operativo:
👉 [**Descargar versiones precompiladas (GitHub Releases)**](https://github.com/Qwejay/QPyPack/releases)
---
## 📋 Resolución de rutas de recursos (`sys._MEIPASS`)
En modo de archivo único (`--onefile`), los recursos estáticos (imágenes, configuraciones, modelos) se extraen temporalmente al ejecutarse. Utilice el siguiente patrón estándar para resolver rutas:
```python
import sys
import os
from pathlib import Path
def get_asset_path(relative_path: str) -> Path:
"""Obtiene la ruta absoluta a recursos empaquetados."""
if hasattr(sys, "_MEIPASS"):
# Directorio de extracción temporal de PyInstaller
base_path = Path(sys._MEIPASS)
elif "__compiled__" in globals():
# Directorio de ejecución binaria de Nuitka
base_path = Path(sys.argv[0]).resolve().parent
else:
# Entorno de desarrollo local
base_path = Path(__file__).resolve().parent
return base_path / relative_path
```
---
## 📅 Historial de cambios (Changelog)
Para ver las notas de versión completas, consulte [CHANGELOG.md](CHANGELOG.md) o la página de [Releases de GitHub](https://github.com/Qwejay/QPyPack/releases).
Consulte [CHANGELOG.md](../../CHANGELOG.md) para notas de versión detalladas y corrección de errores.
---
## 📄 Licencia
## 💖 Contribuciones y patrocinio
Licenciado bajo la [GNU General Public License v3.0](LICENSE).
QPyPack es un proyecto de código abierto mantenido en mi tiempo libre. Si le ha sido de utilidad, agradecemos su apoyo voluntario:
Copyright (C) 2026 QwejayHuang.
- 🌟 **Estrella en GitHub**: Dele una estrella al repositorio en [GitHub](https://github.com/Qwejay/QPyPack).
- 🐛 **Reportes y sugerencias**: Envíe incidencias a través de [GitHub Issues](https://github.com/Qwejay/QPyPack/issues).
- ⚡ **Patrocinar**: Apoye al autor a través de [Afdian (爱发电)](https://www.ifdian.net/a/qwejay) (WeChat Pay / Alipay).
---
## 📄 Licencia (License)
Este proyecto está licenciado bajo la [GNU General Public License v3.0 (GPL-3.0)](../../LICENSE).
> [!IMPORTANT]
> **Derechos de autor sobre los binarios generados**:
> La propiedad intelectual y los términos de licencia de las aplicaciones creadas con QPyPack **pertenecen en su totalidad al usuario**. La licencia GPL-3.0 de QPyPack no impone restricciones sobre su software compilado.
<p align="right">Copyright (C) 2026 QwejayHuang.</p>
+149 -25
View File
@@ -14,49 +14,121 @@
</p>
<p align="center">
<strong>Un outil GUI multiplateforme pour empaqueter des applications Python basé sur PyInstaller & Nuitka</strong>
</p>
<p align="center">
<!-- PyPI Version -->
<a href="https://pypi.org/project/qpypack/">
<img src="https://img.shields.io/pypi/v/qpypack.svg?color=blue" alt="PyPI version" />
<img src="https://img.shields.io/pypi/v/qpypack.svg?color=blue&logo=pypi&logoColor=white" alt="PyPI version" />
</a>
<!-- Python Versions -->
<a href="https://pypi.org/project/qpypack/">
<img src="https://img.shields.io/pypi/pyversions/qpypack.svg" alt="Python versions" />
<img src="https://img.shields.io/pypi/pyversions/qpypack.svg?logo=python&logoColor=white" alt="Python versions" />
</a>
<!-- PyPI Downloads -->
<a href="https://pypistats.org/packages/qpypack">
<img src="https://img.shields.io/pypi/dm/qpypack?color=orange&logo=pypi&logoColor=white" alt="PyPI Downloads" />
</a>
<!-- Supported Platforms -->
<img src="https://img.shields.io/badge/platform-Windows%20%7C%20macOS%20%7C%20Linux-informational" alt="Platform Support" />
<br>
<!-- Release Date -->
<a href="https://github.com/Qwejay/QPyPack/releases">
<img src="https://img.shields.io/github/release-date/Qwejay/QPyPack?color=brightgreen&logo=github" alt="Release Date" />
</a>
<!-- Last Commit -->
<a href="https://github.com/Qwejay/QPyPack/commits/main">
<img src="https://img.shields.io/github/last-commit/Qwejay/QPyPack" alt="Last Commit" />
</a>
<!-- GitHub License -->
<a href="https://github.com/Qwejay/QPyPack/blob/main/LICENSE">
<img src="https://img.shields.io/github/license/Qwejay/QPyPack.svg" alt="License" />
</a>
<!-- GitHub Stars -->
<a href="https://github.com/Qwejay/QPyPack/stargazers">
<img src="https://img.shields.io/github/stars/Qwejay/QPyPack.svg" alt="GitHub stars" />
<img src="https://img.shields.io/github/stars/Qwejay/QPyPack.svg?logo=github&color=gold" alt="GitHub stars" />
</a>
</p>
QPyPack est un outil graphique conçu pour simplifier le processus d'empaquetage des applications Python. Il intègre de manière transparente deux moteurs de compilation majeurs—PyInstaller et Nuitka—convertissant les arguments complexes en ligne de commande en une interface visuelle intuitive.
---
<p align="center">
<strong>Outil GUI moderne et prêt à l'emploi pour empaqueter des applications Python multiplateformes</strong><br>
<sub>Propulsé par PyInstaller et Nuitka, offrant configuration visuelle, analyse statique des dépendances et flux de compilation automatisé.</sub>
</p>
## 📌 Présentation du projet (Overview)
**QPyPack** est un outil graphique multiplateforme conçu pour les développeurs Python. En intégrant de manière transparente les deux moteurs majeurs **PyInstaller** (empaquetage de bytecode) et **Nuitka** (compilation C/C++ native), QPyPack abstrait les chaînes d'outils complexes, l'analyse des dépendances implicites, l'isolation d'environnements et la collecte de ressources dans une interface de bureau intuitive.
Qu'il s'agisse de distribuer de simples scripts d'automatisation ou des applications complexes (avec PySide6/PyQt, Playwright, CustomTkinter, FastAPI, etc.), QPyPack garantit une expérience de compilation fiable, reproductible et à haut taux de succès.
---
## 📷 Captures d'écran (Screenshots)
## 📸 Captures d'écran (Screenshots)
<p align="center">
<img width="1143" height="1067" alt="image" src="https://github.com/user-attachments/assets/8658aaef-5867-470d-ba4d-07892309ab1a" />
<img width="1142" height="1067" alt="image" src="https://github.com/user-attachments/assets/b64d9b89-8bfd-4bf8-8fec-9c75f61305dd" />
<img width="32%" alt="Interface principale (Anglais)" src="https://github.com/user-attachments/assets/9d16c68e-d283-4020-86c1-9d4791756c29" />
<img width="32%" alt="Interface principale (Chinois)" src="https://github.com/user-attachments/assets/0147460d-1e9e-4612-9b52-9d347d81b7c5" />
<img width="32%" alt="Moteur et Environnement" src="https://github.com/user-attachments/assets/0ad4db6d-b008-4018-bd69-40a369a10b7d" />
<br />
<img width="32%" alt="Gestion des dépendances" src="https://github.com/user-attachments/assets/c7fd1218-d079-4898-a97c-aa980c4d1375" />
<img width="32%" alt="Optimisation et Signature" src="https://github.com/user-attachments/assets/e5b7500e-2a0d-4c6d-b20b-7d8d2d3bac8d" />
<img width="32%" alt="À propos et Diagnostics" src="https://github.com/user-attachments/assets/e652b222-49f5-44cd-ad3f-d93369ede26b" />
</p>
---
## 🚀 Fonctionnalités principales
## 🛠️ Architecture & Fonctionnalités clés
* 📥 **Glisser-déposer intuitif** : Glissez simplement vos fichiers `.py` ou `.pyw` dans l'application.
* 🎨 **Détection d'icône automatique** : Conversion et aperçu automatique des icônes présentes dans le dossier source.
* 🛡️ **Bac à sable d'environnement virtuel** : Crée un environnement virtuel isolé pour réduire la taille de l'exécutable final.
* 🔍 **Analyse des dépendances** : Détection de `requirements.txt` et analyse statique du code (AST) pour inclure les dépendances implicites.
* ⚙️ **Commutation de moteur double** : Basculez facilement entre PyInstaller et Nuitka.
* 📝 **Injection de métadonnées** : Configurez la version, l'auteur et la description directement depuis l'interface (Windows PE & macOS Info.plist).
### 1. Double moteur de compilation & Optimisation binaire
* **Basculement transparent entre les moteurs** :
* **PyInstaller** : Compilation rapide, sans dépendance de compilateur C, excellente compatibilité.
* **Nuitka** : Traduit le code Python en binaires C/C++ natifs pour des performances accrues, une forte protection contre la rétro-ingénierie et une taille d'exécutable réduite.
* **Optimisation LTO & Élagage de sous-modules** : Support de l'optimisation à l'édition des liens (`--lto=yes`) en mode Lite. Détection et exclusion automatique des sous-modules Qt lourds non utilisés (WebEngine, 3D, Quick, etc.) pour éviter l'alourdissement du binaire.
* **Formats de distribution flexibles** : Prise en charge des modes **Fichier unique (`--onefile`)** et **Dossier (`--onedir`)**, avec personnalisation du dossier interne des ressources (`--contents-directory`).
### 2. Analyse statique & Protection des dépendances
* **Scan AST récursif natif** : Analyseur statique d'arbre syntaxique abstrait (AST) en pur Python, découvrant les dépendances explicites et implicites sans exécuter le code.
* **Système de mappage intelligent** : Table de correspondance intégrée entre noms d'import et paquets PyPI (ex. `cv2` $\to$ `opencv-python`, `PIL` $\to$ `pillow`, `win32com` $\to$ `pywin32`), entièrement personnalisable.
* **Isolation dynamique des bibliothèques obsolètes (Backport Isolation)** : Détecte et neutralise automatiquement les bibliothèques de rétrocompatibilité en conflit avec la bibliothèque standard moderne (ex. `pathlib` ou `typing` sous Python 3.10+).
### 3. Gestion automatisée des environnements & Auto-récupération
* **Provisionnement automatique des compilateurs C/C++** : Détecte automatiquement MSVC, Clang (LLVM) et GCC. En l'absence de compilateur local, Nuitka télécharge et gère automatiquement une chaîne d'outils MinGW-w64.
* **Gestion du cycle de vie des environnements virtuels** : Prise en charge des bacs à sable isolés et des environnements virtuels partagés, avec outil de nettoyage intégré.
* **Gestion adaptative des ressources & Résilience** :
* Évalue la mémoire vive et l'espace disque avant la compilation pour ajuster automatiquement le nombre de cœurs CPU (Adaptive Concurrency).
* Récupère automatiquement les erreurs de mémoire saturée (`ZstdError` / OOM) en relançant la compilation en mode basse mémoire mono-thread.
* Contourne les verrouillages temporaires de fichiers causés par les antivirus ou les services de synchronisation cloud.
### 4. Signature de code & Préréglages de projet
* **Signature numérique intelligente** : Applique automatiquement les signatures numériques Authenticode aux binaires Windows (compatible Signtool et PowerShell avec horodatage RFC 3161) et signature runtime `codesign` sous macOS.
* **Suite de certificats** : Outil intégré de génération de certificats auto-signés (`.pfx`) et prise en charge des certificats commerciaux.
* **Exportation / Importation de préréglages** : Sauvegarde tous les paramètres de compilation, listes de ressources et règles dans des fichiers portables `.qpypack`.
### 5. Expérience utilisateur moderne & i18n
* **Glisser-déposer intuitif** : Déposer un script Python analyse automatiquement les métadonnées (`__version__`, `__author__`, nom de l'application), déduit le point d'entrée et associe l'icône correspondante.
* **Interface vectorielle avec support HiDPI** : Entièrement conçue avec les icônes vectorielles Google Material SVG pour un rendu net sur écrans 4K/Haute résolution. Traduite en 17 langues (français, anglais, chinois, japonais, coréen, allemand, espagnol, etc.).
---
## ⚡ Démarrage rapide
## 📊 Comparatif des moteurs (PyInstaller vs. Nuitka)
| Critère | PyInstaller | Nuitka |
| :--- | :--- | :--- |
| **Principe** | Bündle l'interpréteur Python + bytecode (`.pyc`) | Compile le code Python en binaires C/C++ natifs |
| **Vitesse de compilation** | Très rapide (généralement 10 – 60 s) | Plus lente (génération de code C++ et optimisations) |
| **Compilateur C/C++** | Non requis | Requis (MSVC / GCC / Clang / MinGW-w64 géré) |
| **Protection du code** | Basique (décompilation possible) | Très élevée (code machine compilé, résistant à l'ingénierie inverse) |
| **Performances d'exécution** | Vitesse standard de Python | Démarrage plus rapide, boucles et calculs intensifs optimisés |
| **Recommandé pour** | Prototypage rapide, outils internes, projets à imports dynamiques | Logiciels commerciaux, protection d'algorithmes, optimisation de taille |
---
## ⚡ Démarrage rapide (Quick Start)
> 💡 **Première utilisation ?** Consultez notre [**📖 Guide de démarrage rapide (QUICKSTART.md)**](../../QUICKSTART.md) pour un pas-à-pas détaillé et les configurations recommandées.
### Méthode 1 : Installation via pip / pipx (Recommandée)
Nécessite Python >= 3.8 :
```bash
# Installer via pip
@@ -66,18 +138,70 @@ pip install qpypack
qpypack
```
Ou téléchargez les exécutables autonomes directement sur la page des [GitHub Releases](https://github.com/Qwejay/QPyPack/releases).
*Avec les gestionnaires de paquets modernes :*
```bash
# Exécuter de manière isolée avec pipx
pipx run qpypack
# Lancement ultra-rapide avec uv
uvx qpypack
```
### Méthode 2 : Version binaire autonome précompilée
Sans configuration préalable de Python, téléchargez directement les exécutables précompilés pour votre système :
👉 [**Télécharger la version précompilée (GitHub Releases)**](https://github.com/Qwejay/QPyPack/releases)
---
## 📅 Notes de version (Changelog)
## 📋 Résolution des chemins de ressources (`sys._MEIPASS`)
Pour consulter l'historique complet des mises à jour, veuillez vous référer à [CHANGELOG.md](CHANGELOG.md) ou à la page des [GitHub Releases](https://github.com/Qwejay/QPyPack/releases).
En mode fichier unique (`--onefile`), les fichiers statiques (images, configurations, modèles) sont extraits à l'exécution dans un dossier temporaire isolé. Utilisez le modèle standard suivant pour résoudre les chemins :
```python
import sys
import os
from pathlib import Path
def get_asset_path(relative_path: str) -> Path:
"""Résout le chemin absolu des ressources empaquetées."""
if hasattr(sys, "_MEIPASS"):
# Répertoire d'extraction temporaire PyInstaller
base_path = Path(sys._MEIPASS)
elif "__compiled__" in globals():
# Répertoire d'exécution binaire Nuitka
base_path = Path(sys.argv[0]).resolve().parent
else:
# Environnement de développement local
base_path = Path(__file__).resolve().parent
return base_path / relative_path
```
---
## 📄 Licence
## 📅 Historique des versions (Changelog)
Distribué sous la licence [GNU General Public License v3.0](LICENSE).
Pour consulter les notes de version détaillées et les corrections de bugs, référez-vous à [CHANGELOG.md](../../CHANGELOG.md).
Copyright (C) 2026 QwejayHuang.
---
## 💖 Contribution & Sponsoring
QPyPack est un projet open-source développé sur mon temps personnel. Si cet outil vous est utile, vous pouvez soutenir sa maintenance continue :
- 🌟 **Étoile GitHub** : Donnez une étoile au projet sur [GitHub](https://github.com/Qwejay/QPyPack).
- 🐛 **Retours & Suggestions** : Soumettez vos rapports de bugs sur [GitHub Issues](https://github.com/Qwejay/QPyPack/issues).
- ⚡ **Soutien financier** : Contribuez via [Afdian (爱发电)](https://www.ifdian.net/a/qwejay) (WeChat Pay / Alipay).
---
## 📄 Licence (License)
Ce projet est distribué sous licence [GNU General Public License v3.0 (GPL-3.0)](../../LICENSE).
> [!IMPORTANT]
> **Propriété des binaires générés** :
> Les droits de propriété intellectuelle et les licences des applications créées avec QPyPack **appartiennent intégralement à l'utilisateur**. La licence GPL-3.0 de QPyPack n'impose aucune contrainte sur vos binaires finaux.
<p align="right">Copyright (C) 2026 QwejayHuang.</p>
+149 -23
View File
@@ -14,70 +14,196 @@
</p>
<p align="center">
<strong>PyInstaller と Nuitka をベースにしたクロスプラットフォーム Python パッケージング GUI ツール</strong>
</p>
<p align="center">
<!-- PyPI Version -->
<a href="https://pypi.org/project/qpypack/">
<img src="https://img.shields.io/pypi/v/qpypack.svg?color=blue" alt="PyPI version" />
<img src="https://img.shields.io/pypi/v/qpypack.svg?color=blue&logo=pypi&logoColor=white" alt="PyPI version" />
</a>
<!-- Python Versions -->
<a href="https://pypi.org/project/qpypack/">
<img src="https://img.shields.io/pypi/pyversions/qpypack.svg" alt="Python versions" />
<img src="https://img.shields.io/pypi/pyversions/qpypack.svg?logo=python&logoColor=white" alt="Python versions" />
</a>
<!-- PyPI Downloads -->
<a href="https://pypistats.org/packages/qpypack">
<img src="https://img.shields.io/pypi/dm/qpypack?color=orange&logo=pypi&logoColor=white" alt="PyPI Downloads" />
</a>
<!-- Supported Platforms -->
<img src="https://img.shields.io/badge/platform-Windows%20%7C%20macOS%20%7C%20Linux-informational" alt="Platform Support" />
<br>
<!-- Release Date -->
<a href="https://github.com/Qwejay/QPyPack/releases">
<img src="https://img.shields.io/github/release-date/Qwejay/QPyPack?color=brightgreen&logo=github" alt="Release Date" />
</a>
<!-- Last Commit -->
<a href="https://github.com/Qwejay/QPyPack/commits/main">
<img src="https://img.shields.io/github/last-commit/Qwejay/QPyPack" alt="Last Commit" />
</a>
<!-- GitHub License -->
<a href="https://github.com/Qwejay/QPyPack/blob/main/LICENSE">
<img src="https://img.shields.io/github/license/Qwejay/QPyPack.svg" alt="License" />
</a>
<!-- GitHub Stars -->
<a href="https://github.com/Qwejay/QPyPack/stargazers">
<img src="https://img.shields.io/github/stars/Qwejay/QPyPack.svg" alt="GitHub stars" />
<img src="https://img.shields.io/github/stars/Qwejay/QPyPack.svg?logo=github&color=gold" alt="GitHub stars" />
</a>
</p>
QPyPack は、Python アプリケーションのパッケージング手順を簡素化するために設計された GUI ツールです。PyInstaller と Nuitka の 2 大コンパイルエンジンを高度に統合し、複雑な CLI コマンドライン引数を直感的な GUI 操作に変換します。
---
<p align="center">
<strong>モダンで使いやすいクロスプラットフォーム対応 Python アプリケーションパッケージング GUI ツール</strong><br>
<sub>PyInstaller と Nuitka のデュアルエンジンを搭載し、視覚的な設定、静的依存関係解析、自動ビルドパイプラインを提供</sub>
</p>
## 📌 プロジェクト概要 (Overview)
**QPyPack** は、Python 開発者のために設計されたクロスプラットフォームのグラフィカルパッケージングツールです。**PyInstaller**(インタープリタおよびバイトコード同梱)と **Nuitka**(C/C++ ネイティブコンパイル)の 2 大コアエンジンを高度に統合し、複雑な低レイヤコンパイル引数、暗黙の依存関係解析、環境分離、リソース収集プロセスを直感的な GUI に集約しました。
シンプルな自動化スクリプトの配布から、大規模な依存関係(PySide6 / PyQt、Playwright、CustomTkinter、FastAPI など)を持つデスクトップやサーバーサイドアプリまで、QPyPack は安定した高い成功率と再現性のあるビルド体験を提供します。
---
## 📷 スクリーンショット (Screenshots)
## 📸 スクリーンショット (Screenshots)
<p align="center">
<img width="1143" height="1067" alt="image" src="https://github.com/user-attachments/assets/8658aaef-5867-470d-ba4d-07892309ab1a" />
<img width="1142" height="1067" alt="image" src="https://github.com/user-attachments/assets/b64d9b89-8bfd-4bf8-8fec-9c75f61305dd" />
<img width="32%" alt="メイン画面(英語)" src="https://github.com/user-attachments/assets/9d16c68e-d283-4020-86c1-9d4791756c29" />
<img width="32%" alt="メイン画面(中国語)" src="https://github.com/user-attachments/assets/0147460d-1e9e-4612-9b52-9d347d81b7c5" />
<img width="32%" alt="エンジンと環境設定" src="https://github.com/user-attachments/assets/0ad4db6d-b008-4018-bd69-40a369a10b7d" />
<br />
<img width="32%" alt="依存関係管理とスキャン" src="https://github.com/user-attachments/assets/c7fd1218-d079-4898-a97c-aa980c4d1375" />
<img width="32%" alt="最適化・署名・セキュリティ" src="https://github.com/user-attachments/assets/e5b7500e-2a0d-4c6d-b20b-7d8d2d3bac8d" />
<img width="32%" alt="バージョン情報と診断" src="https://github.com/user-attachments/assets/e652b222-49f5-44cd-ad3f-d93369ede26b" />
</p>
---
## 🚀 主な機能 (Key Features)
## 🛠️ コアアーキテクチャと機能 (Key Features)
* 📥 **ドラッグ&ドロップ対応**: `.py` / `.pyw` ソースファイルをウィンドウに直接ドラッグして読み込み。
* 🎨 **アイコン自動検出**: ソースディレクトリ内の画像資産 (`icon.ico` / `logo.svg` 等) を自動検出しフォーマット変換。
* 🛡️ **仮想環境サンドボックス**: 独立した仮想環境を自動生成し、最小限の依存関係でバイナリサイズを削減。
* 🔍 **依存関係の自動解析**: `requirements.txt` 解析および AST 静的解析による暗黙のインポート (Hidden Imports) 補完。
* ⚙️ **デュアルエンジン切替**: PyInstaller と Nuitka をワンクリックで切り替え。
* 📝 **メタデータ注入**: バージョン情報や作者情報を実行ファイルプロパティに自動書き込み。
### 1. デュアルビルドエンジンとバイナリ最適化
* **シームレスなデュアルエンジン切替**:
* **PyInstaller**:高速なビルド速度、外部 C コンパイラ不要、優れた互換性とエコシステムサポート。
* **Nuitka**:Python ソースコードを直接ネイティブ C/C++ バイナリにトランスパイルし、実行パフォーマンス向上、高い難読化/耐リバースエンジニアリング性能、コンパクトなファイルサイズを実現。
* **LTO リンク時最適化とサブモジュール削除**:軽量モード(Lite Mode)で `--lto=yes` リンク時最適化をサポート。PySide/PyQt において参照されていない重いサブモジュール(WebEngine、3D、Quick など)を自動検出して除外し、バイナリ肥大化を防止。
* **柔軟な出力形式**:**単一ファイル形式 (`--onefile`)** と **ディレクトリ形式 (`--onedir`)** をサポートし、内部依存関係ディレクトリの指定 (`--contents-directory`) にも対応。
### 2. 静的解析と依存関係トポロジー保護
* **ネイティブ AST 再帰スキャン**:純粋な Python 実装の抽象構文木(AST)静的解析エンジンを内蔵。コードを実行せずにソースコードとプロジェクトディレクトリ内のインポート関係を再帰的に解析。
* **インテリジェントなパッケージ名マッピング**:一般的なサードパーティ製ライブラリのインポート名と PyPI パッケージ名のマッピングテーブルを内蔵(例: `cv2` $\to$ `opencv-python`、`PIL` $\to$ `pillow`、`win32com` $\to$ `pywin32`)。ユーザーによるカスタム拡張も可能。
* **古い互換パッケージの動的隔離 (Backport Isolation)**:ターゲット Python バージョンの標準ライブラリと競合する古い Backport パッケージを自動検知して除外(例: Python 3.10+ における `pathlib` や `typing` の自動隔離)。
### 3. 環境の自動管理と自己修復フォールバック
* **C/C++ コンパイラの自動プロビジョニング**:ローカルの MSVC、Clang (LLVM)、GCC 環境を自動検出。コンパイラが存在しない場合、Nuitka エンジンが互換性のある MinGW-w64 ツールチェーンを自動ダウンロードおよび管理。
* **仮想環境ライフサイクル管理**:完全隔離の仮想環境サンドボックスおよび共有仮想環境モードをサポート。過去の無効な仮想環境の一括スキャンとクリーンアップユーティリティを搭載。
* **適応型リソース管理とエラー自動復旧**:
* ビルド前にディスク容量と物理メモリを評価し、メモリ不足時には並行スレッド数(Adaptive Concurrency)を自動調整。
* メモリ割り当てオーバーフロー(OOM / ZstdError)を検知し、シングルスレッド低メモリモードで自動再試行。
* Windows アンチウイルスソフトウェアによる中間アイコンや一時ファイルの排他ロックを自動回避。
### 4. コード署名とデリバリー保証
* **スマートデジタル署名管理**:Windows ビルド生成後に Authenticode デジタル署名を自動適用(Signtool および PowerShell エンジンに対応、RFC 3161 タイムスタンプサービス統合)。macOS のワンクリック `codesign` ランタイム署名に対応。
* **自己署名証明書スイート**:Windows 自己署名コード署名証明書(`.pfx`)生成ツールを内蔵し、商用秘密鍵証明書とパスワード設定をサポート。
* **プロジェクト設定プリセットのインポート/エクスポート**:すべてのビルド引数、リソース一覧、マッピングルールを共有可能な `.qpypack` プリセットファイルとしてエクスポート可能。
### 5. クロスプラットフォーム UX
* **ドラッグ&ドロップ対応**:Python スクリプトをドロップするだけで、モジュールのメタデータ(バージョン、作者、アプリ名)の解析、エントリーポイントの推論、アプリアイコンのマッピングを自動完了。
* **ベクターレンダリングと多言語 i18n**:Google Material SVG ベクターアイコンを採用し、4K/高 DPI ディスプレイのスケーリングに完全対応。日本語、英語、簡体字/繁体字中国語、韓国語、ドイツ語、フランス語など 17 言語の即時切り替えをサポート。
---
## 📊 エンジン選定の比較 (PyInstaller vs. Nuitka)
| 比較項目 | PyInstaller | Nuitka |
| :--- | :--- | :--- |
| **パッケージング原理** | Python インタープリタとバイトコード (`.pyc`) を同梱 | Python コードをネイティブ C/C++ バイナリにコンパイル |
| **ビルド時間** | 非常に高速(通常 10 〜 60 秒) | 比較的低速(C++ コード生成とコンパイラ最適化を伴う) |
| **C/C++ コンパイラ依存** | 不要 | 必要(MSVC / GCC / Clang / MinGW-w64 自動ダウンロード対応) |
| **コード保護レベル** | 基本(デコンパイラでソース復元可能) | 極めて高い(機械語バイナリ化、強固な耐解析性) |
| **実行パフォーマンス** | 標準的な Python 実行速度 | 起動が高速、ループや計算負荷の高い処理で優位 |
| **推奨ユースケース** | 迅速なプロトタイプ検証、社内ツール、動的インポートが多いプロジェクト | 商用配布ソフトウェア、コアアルゴリズム保護、サイズ・起動速度重視 |
---
## ⚡ クイックスタート (Quick Start)
> 💡 **初めてのご利用ですか?** 詳細な手順と推奨設定については、[**📖 クイックスタートガイド (QUICKSTART.md)**](../../QUICKSTART.md) をご参照ください。
### 方法 1:pip / pipx によるインストール(推奨)
Python >= 3.8 の環境で以下を実行します:
```bash
# pip によるインストール
pip install qpypack
# アプリケーションの起動
# GUI アプリケーションの起動
qpypack
```
または [GitHub Releases ページ](https://github.com/Qwejay/QPyPack/releases) からビルド済みバイナリを直接ダウンロードできます。
*モダンなパッケージマネージャーを使用する場合(推奨):*
```bash
# pipx による隔離実行
pipx run qpypack
# uv による高速起動
uvx qpypack
```
### 方法 2:スタンドアロンビルド済みバイナリ版
Python 環境の事前構築を行わず、GitHub Releases ページから OS に適した実行ファイルを直接ダウンロードして利用できます:
👉 [**ビルド済みバイナリのダウンロード (GitHub Releases)**](https://github.com/Qwejay/QPyPack/releases)
---
## 📋 ベストプラクティス:リソース解決パス (`sys._MEIPASS`)
単一ファイルモード(`--onefile`)では、同梱された静的アセット(画像、設定ファイル、モデルデータなど)は実行時にサンドボックス一時ディレクトリへ展開されます。ソースコード内では以下の標準パターンを用いて安全にパスを解決してください:
```python
import sys
import os
from pathlib import Path
def get_asset_path(relative_path: str) -> Path:
"""パッケージング後のリソース絶対パスを取得"""
if hasattr(sys, "_MEIPASS"):
# PyInstaller 単一ファイルの展開ディレクトリ
base_path = Path(sys._MEIPASS)
elif "__compiled__" in globals():
# Nuitka ネイティブバイナリの実行ディレクトリ
base_path = Path(sys.argv[0]).resolve().parent
else:
# ローカル開発・デバッグ環境ディレクトリ
base_path = Path(__file__).resolve().parent
return base_path / relative_path
```
---
## 📅 更新履歴 (Changelog)
詳細なリリースノートおよび更新履歴については、[CHANGELOG.md](CHANGELOG.md) または [GitHub Releases ページ](https://github.com/Qwejay/QPyPack/releases) を参照してください。
詳細なバージョン履歴、新機能、バグ修正内容については [CHANGELOG.md](../../CHANGELOG.md) をご覧ください。
---
## 💖 貢献とスポンサーシップ (Contributing & Sponsorship)
QPyPack はオープンソースの理念に基づいて開発・メンテナンスされています。日々の開発や業務でお役に立ちましたら、継続的な改善のためご支援をいただけますと幸いです:
- 🌟 **Star を付ける**:[GitHub](https://github.com/Qwejay/QPyPack) リポジトリにスターをお願いします。
- 🐛 **フィードバックと提案**:[Issue](https://github.com/Qwejay/QPyPack/issues) からバグ報告や改善要望をお寄せください。
- ⚡ **スポンサー**:[Afdian (爱发电)](https://www.ifdian.net/a/qwejay) より無償の寄付を受け付けています(WeChat Pay / Alipay 対応)。
> *注:スポンサーシップはオープンソースコミュニティへの自発的な支援であり、商用サポートや特定機能開発の義務を伴うものではありません。*
---
## 📄 ライセンス (License)
[GNU General Public License v3.0](LICENSE) のもとでオープンソース化されています。
本プロジェクトは [GNU General Public License v3.0 (GPL-3.0)](../../LICENSE) に基づいてオープンソースとして公開されています。
Copyright (C) 2026 QwejayHuang.
> [!IMPORTANT]
> **ビルド成果物の著作権について**:
> QPyPack を使用して生成された最終バイナリおよびアプリケーションの**知的財産権とライセンス形態は、完全にユーザー自身に帰属します**。QPyPack の GPL-3.0 ライセンスがビルド成果物に対して伝播することはありません。
<p align="right">Copyright (C) 2026 QwejayHuang.</p>
+150 -24
View File
@@ -14,70 +14,196 @@
</p>
<p align="center">
<strong>PyInstaller 및 Nuitka 기반의 크로스 플랫폼 Python 애플리케이션 패키징 GUI 도구</strong>
</p>
<p align="center">
<!-- PyPI Version -->
<a href="https://pypi.org/project/qpypack/">
<img src="https://img.shields.io/pypi/v/qpypack.svg?color=blue" alt="PyPI version" />
<img src="https://img.shields.io/pypi/v/qpypack.svg?color=blue&logo=pypi&logoColor=white" alt="PyPI version" />
</a>
<!-- Python Versions -->
<a href="https://pypi.org/project/qpypack/">
<img src="https://img.shields.io/pypi/pyversions/qpypack.svg" alt="Python versions" />
<img src="https://img.shields.io/pypi/pyversions/qpypack.svg?logo=python&logoColor=white" alt="Python versions" />
</a>
<!-- PyPI Downloads -->
<a href="https://pypistats.org/packages/qpypack">
<img src="https://img.shields.io/pypi/dm/qpypack?color=orange&logo=pypi&logoColor=white" alt="PyPI Downloads" />
</a>
<!-- Supported Platforms -->
<img src="https://img.shields.io/badge/platform-Windows%20%7C%20macOS%20%7C%20Linux-informational" alt="Platform Support" />
<br>
<!-- Release Date -->
<a href="https://github.com/Qwejay/QPyPack/releases">
<img src="https://img.shields.io/github/release-date/Qwejay/QPyPack?color=brightgreen&logo=github" alt="Release Date" />
</a>
<!-- Last Commit -->
<a href="https://github.com/Qwejay/QPyPack/commits/main">
<img src="https://img.shields.io/github/last-commit/Qwejay/QPyPack" alt="Last Commit" />
</a>
<!-- GitHub License -->
<a href="https://github.com/Qwejay/QPyPack/blob/main/LICENSE">
<img src="https://img.shields.io/github/license/Qwejay/QPyPack.svg" alt="License" />
</a>
<!-- GitHub Stars -->
<a href="https://github.com/Qwejay/QPyPack/stargazers">
<img src="https://img.shields.io/github/stars/Qwejay/QPyPack.svg" alt="GitHub stars" />
<img src="https://img.shields.io/github/stars/Qwejay/QPyPack.svg?logo=github&color=gold" alt="GitHub stars" />
</a>
</p>
QPyPack은 Python 애플리케이션 패키징 프로세스를 단순화하도록 설계된 GUI 도구입니다. PyInstaller와 Nuitka를 깊이 통합하여 복잡한 CLI 명령을 직관적인 그래픽 인터페이스로 변환합니다.
---
<p align="center">
<strong>현대적이고 즉시 사용 가능한 크로스 플랫폼 Python 애플리케이션 패키징 GUI 도구</strong><br>
<sub>PyInstaller 및 Nuitka 듀얼 엔진을 탑재하여 시각적 구성, 정적 의존성 분석 및 자동화된 빌드 워크플로 제공</sub>
</p>
## 📌 프로젝트 개요 (Overview)
**QPyPack**은 Python 개발자를 위해 설계된 크로스 플랫폼 그래픽 패키징 도구입니다. **PyInstaller**(인터프리터 및 바이트코드 번들링)와 **Nuitka**(C/C++ 네이티브 컴파일) 듀얼 코어 엔진을 깊이 통합하여 복잡한 컴파일 파라미터, 암시적 의존성 분석, 가상 환경 격리, 리소스 수집 프로세스를 직관적인 GUI 인터페이스로 단순화했습니다.
경량 자동화 스크립트 배포부터 대규모 의존성(PySide6 / PyQt, Playwright, CustomTkinter, FastAPI 등)을 포함하는 데스크톱 및 서버 애플리케이션까지, QPyPack은 높은 성공률과 재현 가능한 빌드 경험을 제공합니다.
---
## 📷 스크린샷 (Screenshots)
## 📸 스크린샷 (Screenshots)
<p align="center">
<img width="1143" height="1067" alt="image" src="https://github.com/user-attachments/assets/8658aaef-5867-470d-ba4d-07892309ab1a" />
<img width="1142" height="1067" alt="image" src="https://github.com/user-attachments/assets/b64d9b89-8bfd-4bf8-8fec-9c75f61305dd" />
<img width="32%" alt="메인 화면 (영어)" src="https://github.com/user-attachments/assets/9d16c68e-d283-4020-86c1-9d4791756c29" />
<img width="32%" alt="메인 화면 (중국어)" src="https://github.com/user-attachments/assets/0147460d-1e9e-4612-9b52-9d347d81b7c5" />
<img width="32%" alt="빌드 엔진 및 환경" src="https://github.com/user-attachments/assets/0ad4db6d-b008-4018-bd69-40a369a10b7d" />
<br />
<img width="32%" alt="의존성 관리 및 스캔" src="https://github.com/user-attachments/assets/c7fd1218-d079-4898-a97c-aa980c4d1375" />
<img width="32%" alt="최적화, 서명 및 보안" src="https://github.com/user-attachments/assets/e5b7500e-2a0d-4c6d-b20b-7d8d2d3bac8d" />
<img width="32%" alt="정보 및 진단" src="https://github.com/user-attachments/assets/e652b222-49f5-44cd-ad3f-d93369ede26b" />
</p>
---
## 🚀 주요 기능 (Key Features)
## 🛠️ 핵심 아키텍처 및 주요 기능 (Key Features)
* 📥 **드래그 앤 드롭 지원**: 소스 파일(.py / .pyw)을 창으로 끌어다 놓아 빠르게 로드.
* 🎨 **아이콘 자동 추출**: 디렉터리 내 아이콘 자산(`icon.ico`, `logo.svg` 등) 자동 탐지 및 포맷 변환.
* 🛡️ **가상 환경 샌드박스**: 독립된 가상 환경을 생성하여 최소 의존성만 설치, 실행 파일 용량 최적화.
* 🔍 **의존성 자동 분석**: `requirements.txt` 파싱 및 AST 정적 스캔을 통한 암시적 임포트(Hidden Imports) 추출.
* ⚙️ **듀얼 엔진 스위칭**: PyInstaller와 Nuitka 간의 손쉬운 전환.
* 📝 **메타데이터 주입**: 버전 정보, 작성자, 설명을 UI에서 직접 실행 파일 속성에 주입.
### 1. 듀얼 빌드 엔진 및 바이너리 최적화
* **원활한 듀얼 엔진 전환**:
* **PyInstaller**: 빠른 빌드 속도, 외부 C 컴파일러 불필요, 광범위한 생태계 호환성 지원.
* **Nuitka**: Python 코드를 C/C++ 바이너리로 직접 변환하여 실행 속도 향상, 강력한 역공학 방지, 컴팩트한 용량 제공.
* **LTO 링크 최적화 및 모듈 가지치기**: 경량 모드(Lite Mode)에서 `--lto=yes` 링크 타임 최적화 지원. PySide/PyQt 사용 시 참조되지 않은 무거운 하위 모듈(WebEngine, 3D, Quick 등)을 자동 식별 및 제거하여 바이너리 용량 낭비 방지.
* **유연한 배포 형태**: **단일 파일 모드 (`--onefile`)** 및 **디렉터리 모드 (`--onedir`)** 지원, 내부 리소스 저장 디렉터리 경로 지정 (`--contents-directory`) 지원.
### 2. 정적 분석 및 의존성 토폴로지 보호
* **순수 AST 재귀 스캔**: 순수 Python 기반의 추상 구문 트리(AST) 정적 분석기를 내장하여 코드를 실행하지 않고도 소스 코드와 프로젝트 폴더의 명시적/암시적 임포트를 재귀적으로 분석.
* **스마트 패키지 이름 매핑 시스템**: 일반적인 서드파티 라이브러리 임포트 이름과 PyPI 패키지 이름 매핑 테이블 내장(예: `cv2` $\to$ `opencv-python`, `PIL` $\to$ `pillow`, `win32com` $\to$ `pywin32`), 사용자 정의 확장 지원.
* **레거시 호환 패키지 동적 격리 (Backport Isolation)**: 대상 Python 버전의 표준 라이브러리와 충돌하는 구형 Backport 패키지(예: Python 3.10+ 환경의 `pathlib`, `typing` 등)를 자동 감지 및 차단.
### 3. 환경 자동화 관리 및 자체 복구 메커니즘
* **C/C++ 컴파일러 자동 프로비저닝**: 로컬 MSVC, Clang (LLVM), GCC 환경 자동 감지. 네이티브 컴파일러가 없을 경우 Nuitka 엔진이 호환 가능한 MinGW-w64 툴체인을 자동 다운로드 및 관리.
* **가상 환경 라이프사이클 관리**: 독립 격리 가상 환경 및 공유 가상 환경 모드 지원. 이전 프로젝트의 비활성 가상 환경 원클릭 스캔 및 정리 유틸리티 제공.
* **리소스 인식형 동시성 및 오류 자가 치유**:
* 빌드 전 디스크 용량과 물리 메모리를 평가하여 저메모리 상태에서 CPU 동시 작업 스레드 수(Adaptive Concurrency) 자동 조절.
* 메모리 할당 오버플로(OOM / ZstdError)를 감지하고 단일 스레드 저메모리 모드로 자동 재시도.
* Windows 백신 프로그램의 중간 아이콘/임시 파일 잠금 충돌 자동 우회.
### 4. 코드 서명 및 릴리스 보증
* **스마트 디지털 서명 관리**: Windows 바이너리 빌드 완료 후 Authenticode 디지털 서명 자동 적용(Signtool 및 PowerShell 엔진 지원, RFC 3161 타임스탬프 서비스 통합). macOS의 원클릭 `codesign` 런타임 서명 지원.
* **자체 서명 인증서 도구**: Windows 자체 서명 코드 서명 인증서(`.pfx`) 생성 도구 내장 및 상용 개인 키 인증서/비밀번호 구성 지원.
* **프로젝트 설정 프리셋 가져오기/내보내기**: 모든 빌드 매개변수, 리소스 매핑 및 제외 규칙을 공유 가능한 `.qpypack` 프리셋 파일로 내보내어 팀 협업 및 CI/CD 워크플로 지원.
### 5. 크로스 플랫폼 사용자 경험
* **드래그 앤 드롭 지원**: Python 스크립트를 드롭하면 모듈 메타데이터(버전, 작성자, 앱 이름) 파싱, 진입점 유추, 소스 디렉터리의 앱 아이콘 매핑 자동 수행.
* **벡터 렌더링 및 글로벌 i18n**: Google Material SVG 벡터 아이콘을 적용하여 4K/고해상도 DPI 스케일링 완벽 지원. 한국어, 영어, 중국어(간체/번체), 일본어, 독일어, 프랑스어 등 17개 언어 실시간 다국어 지원.
---
## 📊 엔진 비교 (PyInstaller vs. Nuitka)
| 평가 지표 | PyInstaller | Nuitka |
| :--- | :--- | :--- |
| **패키징 방식** | Python 인터프리터 + 바이트코드 (`.pyc`) 번들링 | Python 코드를 네이티브 C/C++ 바이너리로 컴파일 |
| **빌드 속도** | 매우 빠름 (보통 10 ~ 60초) | 상대적으로 느림 (C++ 코드 생성 및 최적화 수반) |
| **C/C++ 컴파일러** | 불필요 | 필요 (MSVC / GCC / Clang / MinGW-w64 자동 관리) |
| **코드 보호 수준** | 기본 (디컴파일러를 통한 소스 복원 가능) | 매우 높음 (기계어 바이너리, 강력한 역공학 방지) |
| **실행 성능** | 표준 Python 실행 속도 | 빠른 시작 속도, 루프 및 연산 집약적 작업 최적화 |
| **권장 사용 시나리오** | 빠른 프로토타입 검증, 내부 도구, 동적 임포트 프로젝트 | 상용 배포 소프트웨어, 핵심 알고리즘 보호, 용량/속도 최적화 |
---
## ⚡ 빠른 시작 (Quick Start)
> 💡 **QPyPack을 처음 사용하시나요?** 자세한 사용 가이드와 모범 사례는 [**📖 빠른 시작 가이드 (QUICKSTART.md)**](../../QUICKSTART.md)를 참조하세요.
### 방법 1: pip / pipx를 통한 설치 (권장)
Python >= 3.8 환경에서 실행:
```bash
# pip를 통한 설치
pip install qpypack
# 실행
# GUI 애플리케이션 실행
qpypack
```
또는 [GitHub Releases 페이지](https://github.com/Qwejay/QPyPack/releases)에서 사전 빌드된 실행 파일을 다운로드하세요.
*최신 패키지 관리자 사용 시 (권장):*
```bash
# pipx를 통한 격리 실행
pipx run qpypack
# uv를 통한 초고속 실행
uvx qpypack
```
### 방법 2: 독립형 빌드 바이너리 버전
사전에 Python 환경을 구축할 필요 없이 GitHub Releases 페이지에서 해당 운영체제에 맞는 실행 파일을 직접 다운로드할 수 있습니다:
👉 [**사전 빌드 바이너리 다운로드 (GitHub Releases)**](https://github.com/Qwejay/QPyPack/releases)
---
## 📅 변경 사항 (Changelog)
## 📋 권장 설정: 리소스 해제 경로 (`sys._MEIPASS`)
자세한 릴리스 노트 및 업데이트 기록은 [CHANGELOG.md](CHANGELOG.md) 또는 [GitHub Releases 페이지](https://github.com/Qwejay/QPyPack/releases)를 참조하세요.
단일 파일 모드(`--onefile`)에서는 포함된 정적 리소스(이미지, 설정 파일, 모델 등)가 실행 시 임시 샌드박스 디렉터리에 압축 해제됩니다. 소스 코드 내에서 다음과 같은 표준 방식으로 경로를 참조하십시오:
```python
import sys
import os
from pathlib import Path
def get_asset_path(relative_path: str) -> Path:
"""패키징 후 리소스의 절대 경로를 안전하게 반환"""
if hasattr(sys, "_MEIPASS"):
# PyInstaller 단일 파일 압축 해제 임시 디렉터리
base_path = Path(sys._MEIPASS)
elif "__compiled__" in globals():
# Nuitka 네이티브 바이너리 실행 디렉터리
base_path = Path(sys.argv[0]).resolve().parent
else:
# 로컬 개발 및 디버깅 디렉터리
base_path = Path(__file__).resolve().parent
return base_path / relative_path
```
---
## 📅 변경 이력 (Changelog)
자세한 릴리스 정보, 신규 기능 및 버그 수정 내역은 [CHANGELOG.md](../../CHANGELOG.md)를 참조하세요.
---
## 💖 기여 및 후원 (Sponsorship & Contributing)
QPyPack은 오픈 소스 철학에 따라 유지 관리되는 프로젝트입니다. 본 프로젝트가 개발 효율 향상에 도움이 되었다면 지속적인 유지 관리를 위해 후원해 주실 수 있습니다:
- 🌟 **Star 지원**: [GitHub](https://github.com/Qwejay/QPyPack)에서 Star를 눌러주세요.
- 🐛 **피드백 및 제안**: [GitHub Issues](https://github.com/Qwejay/QPyPack/issues)를 통해 버그를 보고하거나 개선 사항을 제안해 주세요.
- ⚡ **프로젝트 후원**: [Afdian (爱发电)](https://www.ifdian.net/a/qwejay) 플랫폼을 통해 자발적 후원이 가능합니다 (WeChat Pay / Alipay 지원).
> *참고: 후원은 오픈 소스 프로젝트에 대한 자발적인 응원이며 상업적 서비스 약정을 포함하지 않습니다. 오픈 소스 생태계를 지원해 주시는 모든 분께 감사드립니다!*
---
## 📄 라이선스 (License)
[GNU General Public License v3.0](LICENSE)에 따라 오픈 소스로 제공됩니다.
본 프로젝트는 [GNU General Public License v3.0 (GPL-3.0)](../../LICENSE)에 따라 오픈 소스로 배포됩니다.
Copyright (C) 2026 QwejayHuang.
> [!IMPORTANT]
> **빌드 결과물의 저작권 안내**:
> QPyPack을 통해 빌드된 최종 애플리케이션 및 바이너리의 **지식재산권과 라이선스 형태는 전적으로 사용자에게 귀속됩니다**. QPyPack의 GPL-3.0 라이선스는 사용자가 패키징한 결과물에 전염되지 않습니다.
<p align="right">Copyright (C) 2026 QwejayHuang.</p>
+149 -25
View File
@@ -14,70 +14,194 @@
</p>
<p align="center">
<strong>Uma ferramenta GUI multiplataforma para empacotar aplicações Python baseada no PyInstaller & Nuitka</strong>
</p>
<p align="center">
<!-- PyPI Version -->
<a href="https://pypi.org/project/qpypack/">
<img src="https://img.shields.io/pypi/v/qpypack.svg?color=blue" alt="PyPI version" />
<img src="https://img.shields.io/pypi/v/qpypack.svg?color=blue&logo=pypi&logoColor=white" alt="PyPI version" />
</a>
<!-- Python Versions -->
<a href="https://pypi.org/project/qpypack/">
<img src="https://img.shields.io/pypi/pyversions/qpypack.svg" alt="Python versions" />
<img src="https://img.shields.io/pypi/pyversions/qpypack.svg?logo=python&logoColor=white" alt="Python versions" />
</a>
<!-- PyPI Downloads -->
<a href="https://pypistats.org/packages/qpypack">
<img src="https://img.shields.io/pypi/dm/qpypack?color=orange&logo=pypi&logoColor=white" alt="PyPI Downloads" />
</a>
<!-- Supported Platforms -->
<img src="https://img.shields.io/badge/platform-Windows%20%7C%20macOS%20%7C%20Linux-informational" alt="Platform Support" />
<br>
<!-- Release Date -->
<a href="https://github.com/Qwejay/QPyPack/releases">
<img src="https://img.shields.io/github/release-date/Qwejay/QPyPack?color=brightgreen&logo=github" alt="Release Date" />
</a>
<!-- Last Commit -->
<a href="https://github.com/Qwejay/QPyPack/commits/main">
<img src="https://img.shields.io/github/last-commit/Qwejay/QPyPack" alt="Last Commit" />
</a>
<!-- GitHub License -->
<a href="https://github.com/Qwejay/QPyPack/blob/main/LICENSE">
<img src="https://img.shields.io/github/license/Qwejay/QPyPack.svg" alt="License" />
</a>
<!-- GitHub Stars -->
<a href="https://github.com/Qwejay/QPyPack/stargazers">
<img src="https://img.shields.io/github/stars/Qwejay/QPyPack.svg" alt="GitHub stars" />
<img src="https://img.shields.io/github/stars/Qwejay/QPyPack.svg?logo=github&color=gold" alt="GitHub stars" />
</a>
</p>
O QPyPack é uma ferramenta gráfica projetada para simplificar o empacotamento de aplicações Python. Ele integra perfeitamente os motores PyInstaller e Nuitka, convertendo argumentos complexos de linha de comando em uma interface intuitiva.
---
<p align="center">
<strong>Ferramenta GUI moderna e pronta para uso para empacotar aplicações Python multiplataforma</strong><br>
<sub>Alimentada pelos motores PyInstaller e Nuitka, com configuração visual, análise estática de dependências e fluxo de compilação automatizado.</sub>
</p>
## 📌 Visão Geral do Projeto (Overview)
O **QPyPack** é uma ferramenta gráfica multiplataforma desenvolvida para simplificar o empacotamento de aplicações Python. Ao integrar perfeitamente os motores **PyInstaller** (agrupamento de bytecode) e **Nuitka** (compilação nativa C/C++), transforma cadeias de ferramentas complexas, análise de dependências implícitas, isolamento de ambientes e coleta de recursos em uma interface de usuário intuitiva.
Seja para distribuir scripts de automação simples ou aplicações complexas com dependências pesadas (como PySide6/PyQt, Playwright, CustomTkinter, FastAPI, etc.), o QPyPack oferece uma experiência de compilação estável, reproduzível e com alta taxa de sucesso no Windows, macOS e Linux.
---
## 📷 Capturas de Tela (Screenshots)
## 📸 Capturas de Tela (Screenshots)
<p align="center">
<img width="1143" height="1067" alt="image" src="https://github.com/user-attachments/assets/8658aaef-5867-470d-ba4d-07892309ab1a" />
<img width="1142" height="1067" alt="image" src="https://github.com/user-attachments/assets/b64d9b89-8bfd-4bf8-8fec-9c75f61305dd" />
<img width="32%" alt="Interface Principal (Inglês)" src="https://github.com/user-attachments/assets/9d16c68e-d283-4020-86c1-9d4791756c29" />
<img width="32%" alt="Interface Principal (Chinês)" src="https://github.com/user-attachments/assets/0147460d-1e9e-4612-9b52-9d347d81b7c5" />
<img width="32%" alt="Motor e Ambiente" src="https://github.com/user-attachments/assets/0ad4db6d-b008-4018-bd69-40a369a10b7d" />
<br />
<img width="32%" alt="Gerenciamento de Dependências" src="https://github.com/user-attachments/assets/c7fd1218-d079-4898-a97c-aa980c4d1375" />
<img width="32%" alt="Otimização e Assinatura" src="https://github.com/user-attachments/assets/e5b7500e-2a0d-4c6d-b20b-7d8d2d3bac8d" />
<img width="32%" alt="Sobre e Diagnósticos" src="https://github.com/user-attachments/assets/e652b222-49f5-44cd-ad3f-d93369ede26b" />
</p>
---
## 🚀 Principais Recursos
## 🛠️ Arquitetura e Principais Recursos
* 📥 **Arrastar e Soltar** : Arraste arquivos `.py` ou `.pyw` diretamente para a janela.
* 🎨 **Detecção Automática de Ícone** : Converte e pré-visualiza ícones da pasta fonte.
* 🛡️ **Ambiente Virtual Isolado** : Cria um ambiente virtual automaticamente para reduzir o tamanho do executável.
* 🔍 **Análise de Dependências** : Leitura de `requirements.txt` e análise estática de código AST para importações ocultas.
* ⚙️ **Troca de Motor Duplo** : Alterne facilmente entre PyInstaller e Nuitka.
* 📝 **Injeção de Metadados** : Configure versão, autor e descrição diretamente na interface gráfica.
### 1. Compilação por Motor Duplo e Otimização Binária
* **Alternância fluida entre motores**:
* **PyInstaller**: Compilação rápida, sem dependência de compiladores C externos, excelente compatibilidade.
* **Nuitka**: Traduz código Python diretamente para binários C/C++ nativos para alto desempenho, forte proteção contra engenharia reversa e tamanho compacto.
* **Otimização LTO e poda de submódulos**: Suporte a LTO (`--lto=yes`) no modo Lite. Identificação e exclusão automática de submódulos Qt pesados não utilizados (WebEngine, 3D, Quick, etc.) para evitar inchaço binário.
* **Formatos de distribuição flexíveis**: Compatível com modo de **Arquivo único (`--onefile`)** e modo **Diretório (`--onedir`)**, com personalização do diretório interno de dependências (`--contents-directory`).
### 2. Análise Estática e Proteção de Dependências
* **Varredura AST recursiva nativa**: Analisador estático de árvore de sintaxe abstrata (AST) em Python puro que descobre importações explícitas e implícitas sem executar o código.
* **Mapeamento inteligente de pacotes**: Tabela de correspondência integrada entre nomes de importação e pacotes PyPI (ex: `cv2` $\to$ `opencv-python`, `PIL` $\to$ `pillow`, `win32com` $\to$ `pywin32`), modular e extensível.
* **Isolamento dinâmico de bibliotecas obsoletas (Backport Isolation)**: Detecta e bloqueia pacotes de retrocompatibilidade obsoletos que entram em conflito com a biblioteca padrão moderna (ex: isolando `pathlib` ou `typing` no Python 3.10+).
### 3. Gerenciamento Automatizado de Ambiente e Autorrecuperação
* **Provisionamento automático de compiladores C/C++**: Detecta MSVC, Clang (LLVM) e GCC locais. Caso nenhum compilador seja encontrado, o Nuitka baixa e gerencia automaticamente a toolchain MinGW-w64.
* **Gerenciamento do ciclo de vida de ambientes virtuais**: Suporte para sandboxes isoladas e ambientes compartilhados com utilitário de limpeza integrado.
* **Gerenciamento adaptativo de recursos e autorrecuperação**:
* Avalia RAM e espaço em disco antes da compilação, ajustando a concorrência de threads (Adaptive Concurrency).
* Captura falhas de memória saturada (`ZstdError` / OOM) e reinicia a compilação no modo mono-thread de baixo consumo.
* Evita bloqueios exclusivos de arquivos causados por antivírus ou serviços de sincronização em nuvem.
### 4. Assinatura de Código e Predefinições de Projeto
* **Assinatura digital inteligente**: Aplica assinaturas digitais Authenticode em binários Windows (compatível com Signtool e PowerShell com carimbo de data/hora RFC 3161) e assinatura runtime `codesign` no macOS.
* **Suite de certificados**: Gerador integrado de certificados autoassinados (`.pfx`) e suporte para certificados comerciais.
* **Importação/Exportação de predefinições**: Salva todos os parâmetros de compilação, listas de recursos e regras em arquivos `.qpypack`.
### 5. Experiência de Usuário e Internacionalização (i18n)
* **Arrastar e soltar intuitivo**: Ao soltar um script Python, extrai metadados (`__version__`, `__author__`), deduz o ponto de entrada e mapeia o ícone da aplicação.
* **Interface vetorial com suporte HiDPI**: Construída com ícones vetoriais Google Material SVG, com dimensionamento perfeito em monitores 4K. Traduzida para 17 idiomas (português, inglês, chinês, japonês, coreano, alemão, francês, espanhol, etc.).
---
## ⚡ Início Rápido
## 📊 Comparativo de Motores (PyInstaller vs. Nuitka)
| Critério | PyInstaller | Nuitka |
| :--- | :--- | :--- |
| **Princípio** | Empacota interpretador Python + bytecode (`.pyc`) | Compila código Python para binários C/C++ nativos |
| **Velocidade de compilação** | Muito rápida (geralmente 10 – 60 s) | Mais lenta (requer geração de código C++ e otimizações) |
| **Compilador C/C++** | Não necessário | Necessário (gestão automática de MSVC / GCC / Clang / MinGW-w64) |
| **Nível de proteção** | Básico (código recuperável via descompiladores) | Extremamente alto (código de máquina nativo, alta proteção) |
| **Desempenho de execução**| Velocidade padrão do Python | Inicialização mais rápida, laços e computação otimizados |
| **Recomendado para** | Prototipagem rápida, ferramentas internas, projetos dinâmicos | Software comercial, proteção de algoritmos, otimização de tamanho |
---
## ⚡ Início Rápido (Quick Start)
> 💡 **Primeira vez usando o QPyPack?** Consulte nosso [**📖 Guia de Início Rápido (QUICKSTART.md)**](../../QUICKSTART.md) para um tutorial passo a passo e configurações recomendadas.
### Método 1: Instalação via pip / pipx (Recomendado)
Requer Python >= 3.8:
```bash
# Instalar via pip
pip install qpypack
# Iniciar aplicação
# Iniciar a aplicação gráfica
qpypack
```
Ou baixe executáveis pré-compilados diretamente na página de [Releases do GitHub](https://github.com/Qwejay/QPyPack/releases).
*Com gerenciadores de pacotes modernos:*
```bash
# Executar isolado via pipx
pipx run qpypack
# Inicialização ultrarrápida via uv
uvx qpypack
```
### Método 2: Versão binária pré-compilada independente
Sem necessidade de configurar o Python localmente, baixe os executáveis pré-compilados diretamente na página de lançamentos:
👉 [**Baixar versões pré-compiladas (GitHub Releases)**](https://github.com/Qwejay/QPyPack/releases)
---
## 📋 Resolução de Caminhos de Recursos (`sys._MEIPASS`)
No modo de arquivo único (`--onefile`), os recursos estáticos (imagens, arquivos de configuração, modelos) são extraídos temporariamente durante a execução. Utilize o seguinte padrão padrão para resolver caminhos:
```python
import sys
import os
from pathlib import Path
def get_asset_path(relative_path: str) -> Path:
"""Obtém o caminho absoluto para recursos empacotados."""
if hasattr(sys, "_MEIPASS"):
# Diretório de extração temporária do PyInstaller
base_path = Path(sys._MEIPASS)
elif "__compiled__" in globals():
# Diretório de execução do binário Nuitka
base_path = Path(sys.argv[0]).resolve().parent
else:
# Ambiente de desenvolvimento local
base_path = Path(__file__).resolve().parent
return base_path / relative_path
```
---
## 📅 Registro de Alterações (Changelog)
Para ver o histórico completo de atualizações, consulte [CHANGELOG.md](CHANGELOG.md) ou a página de [Releases do GitHub](https://github.com/Qwejay/QPyPack/releases).
Para notas de versão detalhadas e correções de bugs, consulte o arquivo [CHANGELOG.md](../../CHANGELOG.md).
---
## 📄 Licença
## 💖 Contribuição e Patrocínio
Distribuído sob a licença [GNU General Public License v3.0](LICENSE).
O QPyPack é um projeto de código aberto mantido no meu tempo livre. Se esta ferramenta foi útil para você, agradecemos seu apoio voluntário:
Copyright (C) 2026 QwejayHuang.
- 🌟 **Estrela no GitHub**: Deixe uma estrela no repositório no [GitHub](https://github.com/Qwejay/QPyPack).
- 🐛 **Feedback e Sugestões**: Envie relatórios de bugs e melhorias no [GitHub Issues](https://github.com/Qwejay/QPyPack/issues).
- ⚡ **Patrocínio**: Apoie o autor através do [Afdian (爱发电)](https://www.ifdian.net/a/qwejay) (compatível com WeChat Pay / Alipay).
---
## 📄 Licença (License)
Este projeto está licenciado sob a [GNU General Public License v3.0 (GPL-3.0)](../../LICENSE).
> [!IMPORTANT]
> **Direitos autorais sobre binários gerados**:
> Os direitos de propriedade intelectual e termos de licença das aplicações criadas com o QPyPack **pertencem integralmente ao usuário**. A licença GPL-3.0 do QPyPack não impõe restrições ao seu software compilado.
<p align="right">Copyright (C) 2026 QwejayHuang.</p>
+149 -25
View File
@@ -14,70 +14,194 @@
</p>
<p align="center">
<strong>Кроссплатформенный GUI-инструмент упаковки Python-приложений на базе PyInstaller и Nuitka</strong>
</p>
<p align="center">
<!-- PyPI Version -->
<a href="https://pypi.org/project/qpypack/">
<img src="https://img.shields.io/pypi/v/qpypack.svg?color=blue" alt="PyPI version" />
<img src="https://img.shields.io/pypi/v/qpypack.svg?color=blue&logo=pypi&logoColor=white" alt="PyPI version" />
</a>
<!-- Python Versions -->
<a href="https://pypi.org/project/qpypack/">
<img src="https://img.shields.io/pypi/pyversions/qpypack.svg" alt="Python versions" />
<img src="https://img.shields.io/pypi/pyversions/qpypack.svg?logo=python&logoColor=white" alt="Python versions" />
</a>
<!-- PyPI Downloads -->
<a href="https://pypistats.org/packages/qpypack">
<img src="https://img.shields.io/pypi/dm/qpypack?color=orange&logo=pypi&logoColor=white" alt="PyPI Downloads" />
</a>
<!-- Supported Platforms -->
<img src="https://img.shields.io/badge/platform-Windows%20%7C%20macOS%20%7C%20Linux-informational" alt="Platform Support" />
<br>
<!-- Release Date -->
<a href="https://github.com/Qwejay/QPyPack/releases">
<img src="https://img.shields.io/github/release-date/Qwejay/QPyPack?color=brightgreen&logo=github" alt="Release Date" />
</a>
<!-- Last Commit -->
<a href="https://github.com/Qwejay/QPyPack/commits/main">
<img src="https://img.shields.io/github/last-commit/Qwejay/QPyPack" alt="Last Commit" />
</a>
<!-- GitHub License -->
<a href="https://github.com/Qwejay/QPyPack/blob/main/LICENSE">
<img src="https://img.shields.io/github/license/Qwejay/QPyPack.svg" alt="License" />
</a>
<!-- GitHub Stars -->
<a href="https://github.com/Qwejay/QPyPack/stargazers">
<img src="https://img.shields.io/github/stars/Qwejay/QPyPack.svg" alt="GitHub stars" />
<img src="https://img.shields.io/github/stars/Qwejay/QPyPack.svg?logo=github&color=gold" alt="GitHub stars" />
</a>
</p>
QPyPack — это визуальный инструмент, предназначенный для упрощения процесса сборки приложений Python. Он объединяет два основных компилятора — PyInstaller и Nuitka, преобразуя сложные консольные команды в интуитивный графический интерфейс.
---
<p align="center">
<strong>Современный кроссплатформенный GUI-инструмент для упаковки Python-приложений</strong><br>
<sub>На базе PyInstaller и Nuitka, с визуальной конфигурацией, статическим анализом зависимостей и автоматизацией сборки.</sub>
</p>
## 📌 Обзор проекта (Overview)
**QPyPack** — это графический кроссплатформенный инструмент для упаковки Python-приложений. Благодаря глубокой интеграции двух компиляторов — **PyInstaller** (бандлинг байт-кода) и **Nuitka** (нативная компиляция в C/C++) — сложные параметры командной строки, отслеживание неявных зависимостей, изоляция сред и сбор ресурсов объединены в удобном интерфейсе.
От простых скриптов автоматизации до сложных приложений (с PySide6/PyQt, Playwright, CustomTkinter, FastAPI и др.) — QPyPack гарантирует стабильную сборку с высоким процентом успеха на Windows, macOS и Linux.
---
## 📷 Скриншоты (Screenshots)
## 📸 Скриншоты (Screenshots)
<p align="center">
<img width="1143" height="1067" alt="image" src="https://github.com/user-attachments/assets/8658aaef-5867-470d-ba4d-07892309ab1a" />
<img width="1142" height="1067" alt="image" src="https://github.com/user-attachments/assets/b64d9b89-8bfd-4bf8-8fec-9c75f61305dd" />
<img width="32%" alt="Главное окно (Английский)" src="https://github.com/user-attachments/assets/9d16c68e-d283-4020-86c1-9d4791756c29" />
<img width="32%" alt="Главное окно (Китайский)" src="https://github.com/user-attachments/assets/0147460d-1e9e-4612-9b52-9d347d81b7c5" />
<img width="32%" alt="Движок и окружение" src="https://github.com/user-attachments/assets/0ad4db6d-b008-4018-bd69-40a369a10b7d" />
<br />
<img width="32%" alt="Управление зависимостями" src="https://github.com/user-attachments/assets/c7fd1218-d079-4898-a97c-aa980c4d1375" />
<img width="32%" alt="Оптимизация и подпись" src="https://github.com/user-attachments/assets/e5b7500e-2a0d-4c6d-b20b-7d8d2d3bac8d" />
<img width="32%" alt="О программе и диагностика" src="https://github.com/user-attachments/assets/e652b222-49f5-44cd-ad3f-d93369ede26b" />
</p>
---
## 🚀 Основные возможности
## 🛠️ Архитектура и ключевые возможности
* 📥 **Drag & Drop** : Перетаскивайте файлы `.py` или `.pyw` прямо в окно программы.
* 🎨 **Автоопределение иконки** : Автоматически находит иконки в папке исходников и конвертирует их.
* 🛡️ **Виртуальное окружение (Sandbox)** : Создает изолированное окружение для минимизации размера итогового файла.
* 🔍 **Анализ зависимостей** : Считывание `requirements.txt` и статический AST-анализ кода для скрытых импортов.
* ⚙️ **Два движка сборки** : Быстрое переключение между PyInstaller и Nuitka.
* 📝 **Внедрение метаданных** : Указывайте версию, автора и описание приложения прямо в интерфейсе.
### 1. Двойной движок сборки и оптимизация бинарных файлов
* **Плавное переключение движков**:
* **PyInstaller**: Высокая скорость сборки, отсутствие потребности в C-компиляторе, отличная совместимость.
* **Nuitka**: Транслирует Python-код напрямую в C/C++ бинарники, обеспечивая высокую скорость выполнения, стойкость к декомпиляции и компактный размер.
* **LTO-оптимизация и обрезка модулей**: Поддержка оптимизации на этапе компоновки (`--lto=yes`) в режиме Lite. Автоматическое исключение неиспользуемых тяжелых субмодулей Qt (WebEngine, 3D, Quick и др.).
* **Гибкие форматы сборки**: Поддержка режимов **одного файла (`--onefile`)** и **директории (`--onedir`)**, а также настройка внутреннего каталога зависимостей (`--contents-directory`).
### 2. Статический анализ и защита зависимостей
* **Рекурсивный AST-анализ**: Встроенный анализатор абстрактного синтаксического дерева (AST) на чистом Python, определяющий явные и неявные импорты без запуска кода.
* **Интеллектуальное сопоставление пакетов**: Встроенная таблица соответствия имён импорта и пакетов PyPI (например, `cv2` $\to$ `opencv-python`, `PIL` $\to$ `pillow`, `win32com` $\to$ `pywin32`) с возможностью расширения.
* **Динамическая изоляция устаревших бэкпортов**: Автоматически блокирует устаревшие backport-модули, конфликтующие со стандартной библиотекой (например, изоляция `pathlib` или `typing` в Python 3.10+).
### 3. Автоматизация окружения и отказоустойчивость
* **Автоматическое управление компиляторами C/C++**: Определяет установленные MSVC, Clang (LLVM) и GCC. При отсутствии компилятора Nuitka автоматически загружает MinGW-w64.
* **Управление виртуальными окружениями**: Поддержка изолированных и общих виртуальных сред, а также встроенная утилита очистки старых сред.
* **Адаптивный контроль ресурсов и самовосстановление**:
* Оценивает ОЗУ и диск перед сборкой, автоматически снижая параллелизм потоков при нехватке памяти.
* Перехватывает ошибки нехватки памяти (`ZstdError` / OOM) и автоматически перезапускает сборку в однопоточном режиме.
* Обходит временные блокировки файлов антивирусами и облачными дисками.
### 4. Подпись кода и пресеты проектов
* **Умная цифровая подпись**: Автоматически подписывает исполняемые файлы Windows через Authenticode (Signtool/PowerShell с меткой времени RFC 3161) и выполняет `codesign` в macOS.
* **Генератор сертификатов**: Встроенный инструмент создания самоподписанных сертификатов (`.pfx`) и поддержка коммерческих ключей.
* **Импорт/экспорт пресетов**: Сохраняет все параметры сборки и списки ресурсов в файлы `.qpypack`.
### 5. Кроссплатформенный интерфейс и локализация
* **Удобный Drag & Drop**: При перетаскивании скрипта автоматически извлекаются метаданные (`__version__`, `__author__`), определяется точка входа и подбирается иконка.
* **Векторная графика и поддержка HiDPI**: Построен на векторных иконках Google Material SVG, отлично масштабируется на экранах 4K. Переведён на 17 языков (русский, английский, китайский, японский, корейский, немецкий, французский, испанский и др.).
---
## ⚡ Быстрый старт
## 📊 Сравнение движков (PyInstaller vs. Nuitka)
| Критерий | PyInstaller | Nuitka |
| :--- | :--- | :--- |
| **Принцип работы** | Упаковывает интерпретатор Python + байт-код (`.pyc`) | Компилирует Python в нативные C/C++ бинарники |
| **Скорость сборки** | Очень высокая (10 – 60 сек) | Более медленная (генерация C++ и компиляция) |
| **Компилятор C/C++** | Не требуется | Требуется (MSVC / GCC / Clang / MinGW-w64) |
| **Защита кода** | Базовая (исходники можно извлечь декомпилятором) | Максимальная (машинный код, защита от реверс-инжиниринга) |
| **Производительность** | Стандартная скорость Python | Быстрый запуск, ускорение циклов и вычислений |
| **Рекомендуется для** | Быстрого тестирования, внутренних утилит, динамических скриптов | Коммерческого ПО, защиты интеллектуальной собственности, оптимизации |
---
## ⚡ Быстрый старт (Quick Start)
> 💡 **Впервые используете QPyPack?** Ознакомьтесь с [**📖 Руководством по быстрому старту (QUICKSTART.md)**](../../QUICKSTART.md).
### Способ 1: Установка через pip / pipx (Рекомендуется)
Требуется Python >= 3.8:
```bash
# Установка через pip
pip install qpypack
# Запуск
# Запуск приложения
qpypack
```
Или скачайте готовые исполняемые файлы на странице [GitHub Releases](https://github.com/Qwejay/QPyPack/releases).
*С современными пакетными менеджерами:*
```bash
# Изолированный запуск через pipx
pipx run qpypack
# Быстрый запуск через uv
uvx qpypack
```
### Способ 2: Готовые скомпилированные версии
Без предварительной настройки Python скачайте готовые исполняемые файлы со страницы релизов:
👉 [**Скачать релизы (GitHub Releases)**](https://github.com/Qwejay/QPyPack/releases)
---
## 📋 Разрешение путей к ресурсам (`sys._MEIPASS`)
В режиме одного файла (`--onefile`) статические ресурсы (изображения, конфигурации, модели) распаковываются во временный каталог. Используйте следующий шаблон:
```python
import sys
import os
from pathlib import Path
def get_asset_path(relative_path: str) -> Path:
"""Получение абсолютного пути к упакованным ресурсам."""
if hasattr(sys, "_MEIPASS"):
# Временная папка распаковки PyInstaller
base_path = Path(sys._MEIPASS)
elif "__compiled__" in globals():
# Директория запуска бинарника Nuitka
base_path = Path(sys.argv[0]).resolve().parent
else:
# Локальное окружение разработки
base_path = Path(__file__).resolve().parent
return base_path / relative_path
```
---
## 📅 История изменений (Changelog)
Полную историю версий и примечания к релизу см. в [CHANGELOG.md](CHANGELOG.md) или на странице [GitHub Releases](https://github.com/Qwejay/QPyPack/releases).
Подробный список изменений версий доступен в [CHANGELOG.md](../../CHANGELOG.md).
---
## 📄 Лицензия
## 💖 Участие и поддержка проекта
Распространяется под лицензией [GNU General Public License v3.0](LICENSE).
QPyPack — это проект с открытым исходным кодом. Если инструмент помог вам в разработке, вы можете поддержать автора:
Copyright (C) 2026 QwejayHuang.
- 🌟 **Поставьте Star**: Отметьте репозиторий звездой на [GitHub](https://github.com/Qwejay/QPyPack).
- 🐛 **Обратная связь**: Создавайте тикеты на [GitHub Issues](https://github.com/Qwejay/QPyPack/issues).
- ⚡ **Спонсорство**: Поддержите автора через [Afdian (爱发电)](https://www.ifdian.net/a/qwejay) (WeChat Pay / Alipay).
---
## 📄 Лицензия (License)
Проект распространяется под лицензией [GNU General Public License v3.0 (GPL-3.0)](../../LICENSE).
> [!IMPORTANT]
> **Авторские права на собранные приложения**:
> Права интеллектуальной собственности и лицензия на созданные вами приложения **полностью принадлежат вам**. Лицензия GPL-3.0 проекта QPyPack не накладывает ограничений на созданные вами программы.
<p align="right">Copyright (C) 2026 QwejayHuang.</p>
+121 -59
View File
@@ -13,10 +13,6 @@
<a href="README_PT.md">Português</a>
</p>
<p align="center">
<strong>基於 PyInstaller 與 Nuitka 的跨平台 Python 應用程式視覺化打包建置工具</strong>
</p>
<p align="center">
<!-- PyPI Version -->
<a href="https://pypi.org/project/qpypack/">
@@ -47,102 +43,168 @@
</a>
<!-- GitHub Stars -->
<a href="https://github.com/Qwejay/QPyPack/stargazers">
<img src="https://img.shields.io/github/stars/Qwejay/QPyPack.svg?logo=github" alt="GitHub 星星數" />
<img src="https://img.shields.io/github/stars/Qwejay/QPyPack.svg?logo=github&color=gold" alt="GitHub 星星數" />
</a>
</p>
QPyPack 是一款致力於簡化 Python 應用程式打包流程的視覺化工具。它深度整合了 **PyInstaller** 與 **Nuitka** 兩大主流編譯引擎,將繁瑣的終端機命令列參數轉化為直觀、極簡的圖形介面互動,協助開發者高效、高成功率地產生跨平台原生可執行程式。
---
<p align="center">
<strong>現代化、開箱即用的跨平台 Python 應用程式打包 GUI 工具</strong><br>
<sub>基於 PyInstaller 與 Nuitka 雙引擎驅動,提供視覺化配置、靜態相依性分析與自動化建置工作流程</sub>
</p>
## 📌 專案概述
**QPyPack** 是一款專為 Python 開發者打造的跨平台圖形化打包工具。透過深度整合 **PyInstaller**(直譯器與位元組碼打包)與 **Nuitka**(C/C++ 原生編譯)雙核心引擎,將繁瑣的底層編譯參數、隱式相依性分析、環境隔離與資源收集等流程轉化為直觀的可視化介面。
無論是用於打包輕量命令列指令碼,還是包含大型複雜相依性(如 PySide6 / PyQt、Playwright、CustomTkinter、FastAPI 等)的桌面或伺服端應用,QPyPack 均可提供穩定、高成功率且可重現的建置體驗。
---
## 📷 介面預覽 (Screenshots)
## 📸 介面預覽 (Screenshots)
<p align="center">
<img width="1173" height="1067" alt="主介面預覽" src="https://github.com/user-attachments/assets/6cf1e937-d35f-4e71-b4e7-7fd86f771d20" />
<img width="1173" height="1067" alt="設定面板預覽" src="https://github.com/user-attachments/assets/b4f563fb-328b-4615-8522-e4f9e490f759" />
<img width="1173" height="1067" alt="相依性管理預覽" src="https://github.com/user-attachments/assets/522d7a3b-9a01-4387-8e81-def4cabcbfff" />
<img width="1173" height="1067" alt="進階優化預覽" src="https://github.com/user-attachments/assets/c8a89212-bf48-40d0-8125-98595f6052bd" />
<img width="1173" height="1067" alt="關於頁面預覽" src="https://github.com/user-attachments/assets/3f5b803a-3c96-493c-b56b-e11f50bd9139" />
<img width="32%" alt="主介面(英文)" src="https://github.com/user-attachments/assets/9d16c68e-d283-4020-86c1-9d4791756c29" />
<img width="32%" alt="主介面(中文)" src="https://github.com/user-attachments/assets/0147460d-1e9e-4612-9b52-9d347d81b7c5" />
<img width="32%" alt="建置引擎與環境" src="https://github.com/user-attachments/assets/0ad4db6d-b008-4018-bd69-40a369a10b7d" />
<br />
<img width="32%" alt="相依性管理與掃描" src="https://github.com/user-attachments/assets/c7fd1218-d079-4898-a97c-aa980c4d1375" />
<img width="32%" alt="最佳化、簽名與安全" src="https://github.com/user-attachments/assets/e5b7500e-2a0d-4c6d-b20b-7d8d2d3bac8d" />
<img width="32%" alt="關於與系統資訊" src="https://github.com/user-attachments/assets/e652b222-49f5-44cd-ad3f-d93369ede26b" />
</p>
---
## 🚀 核心特性 (Key Features)
## 🛠️ 核心架構與特性
QPyPack 旨在解決傳統命令列打包設定繁瑣、相依性遺漏、跨平台相容性差以及編譯失敗率高的問題:
### 1. 雙建置引擎與精簡最佳化
* **雙引擎無縫切換**:
* **PyInstaller**:建置速度快,零 C 編譯器相依,兼具優異的相容性與生態支援。
* **Nuitka**:將 Python 原始碼直接轉譯為 C/C++ 二進位檔,具備執行速度快、抗反編譯能力強、產物體積小等特點。
* **LTO 連結最佳化與模組修剪**:在精簡模式(Lite Mode)下支援開啟 `--lto=yes` 連結時間最佳化;針對 PySide/PyQt 自動識別並剔除未引用的重型子模組(如 WebEngine、3D、Quick 等),有效防止產物體積冗餘。
* **靈活產物形態**:支援 **單檔案 (`--onefile`)** 與 **目錄模式 (`--onedir`)**,支援自訂相依性內部存放目錄 (`--contents-directory`)。
### 1. 現代化 UI 與直觀互動體驗
* 📥 **拖放式載入 (Drag & Drop)**:只需將 `.py` 或 `.pyw` 原始程式碼檔案拖入視窗,系統全自動完成剖析與工作區初始化。
* 🎨 **純向量圖示棧 (Material Design SVG)**:全介面採用 Google Material 向量圖示,全面清理 Emoji 表情,徹底杜絕跨平台系統下字型遞補導致的排版亂碼與跳動。
* 🌐 **智慧多語言 (i18n)**:原生支援簡體中文、繁體中文、英文、德語、法語、日語、韓語等全球主流語言,自動辨識系統偏好語言並支援無縫切換。
* 📊 **雙模式即時日誌檢視器**:引入「精簡模式 (Concise)」與「詳細模式 (Detailed)」雙檢視日誌面板,支援即時擷取編譯引擎極細粒度的編譯進度、一鍵匯出與高亮提示。
### 2. 靜態分析與相依性拓撲防護
* **原生 AST 遞迴掃描**:內建純 Python 實現的抽象語法樹(AST)靜態分析器,無需執行程式碼即可遞迴分析原始碼及專案目錄中的相依性匯入。
* **智慧套件名稱對應系統**:內建主流第三方函式庫匯入名稱與 PyPI 套件名稱對應表(如 `cv2` $\to$ `opencv-python`、`PIL` $\to$ `pillow`、`win32com` $\to$ `pywin32`),支援使用者自訂擴充。
* **廢棄相容套件動態隔離 (Backport Isolation)**:自動識別並屏蔽與目標 Python 版本內建模組衝突的過時 Backport 函式庫(如在 Python 3.10+ 下自動隔離 `pathlib`、`typing` 等),防止執行期引發不可預測的命名空間覆蓋。
### 2. 雙編譯後端與智慧環境偵測
* ⚙️ **PyInstaller & Nuitka 架構**:圖形化介面一鍵切換引擎,根據所選引擎自適應提供針對性的優化選項與參數控制。
* 🔍 **C/C++ 編譯器智慧偵測**:Nuitka 引擎下自動偵測系統內已安裝的 **MSVC**、**Clang** (LLVM) 及 **Zig**(專為 Python 3.13+ C 後端優化)編譯器並優先呼叫,免除繁瑣的環境變數設定。
* 💻 **Python 平台相容性卡片**:動態顯示當前選中 Python 解譯器對 Windows 7/8/10/11、macOS 及 Linux 的支援狀態,並提供官方下載引導。
### 3. 環境自動化管理與容錯機制
* **C/C++ 編譯器自動託管**:自動偵測本機 MSVC、Clang (LLVM) 與 GCC 環境;在缺失本機編譯器時,Nuitka 引擎將自動下載並託管相容的 MinGW-w64 工具鏈。
* **環境生命週期管理**:支援獨立隔離虛擬環境與共享虛擬環境模式;支援對歷史失效虛擬環境的一鍵掃描與空間清理。
* **自適應資源與錯誤自癒**:
* 建置前自動評估磁碟與實體記憶體,低記憶體狀態下自適應下調並行數(Adaptive Concurrency)。
* 自動攔截記憶體配置溢位(OOM / ZstdError)並自動降級為單執行緒低記憶體模式重試。
* 自動規避 Windows 防毒軟體對中繼圖示/暫存檔案的獨占鎖定。
### 3. 三重安全相依性網與零設定預設
* 🛡️ **隔離虛擬沙盒 (Virtualenv Sandbox)**:一鍵在系統暫存目錄建立純淨建置沙盒,避免全域環境污染,極大精簡產物體積。
* 🔍 **多維相依性自動補全**:優先讀取 `requirements.txt`;搭配深度原生 **AST(靜態語法樹)** 掃描引擎與 `pipreqs`,精準補齊隱式匯入(Hidden Imports)。
* 📦 **免設定第三方套件打包預設**:內建對 `ttkbootstrap`、`customtkinter`、`playwright`、`moviepy` 等高頻缺失/報錯套件的自動化打包處理,實現零設定一鍵產生。
* ⚡ **多源 PIP 鏡像與備用切源**:內建主流鏡像加速源,支援主源逾時自動平滑切換至備用源。
### 4. 程式碼簽名與交付保障
* **智慧數位簽名託管**:支援在 Windows 產物輸出後自動套用 Authenticode 數位簽名(相容 Signtool 與 PowerShell 引擎,整合 RFC 3161 時間戳記服務);支援 macOS 下的一鍵 `codesign` 程式碼簽名。
* **自簽名憑證套件**:內建 Windows 自簽名程式碼簽名憑證(`.pfx`)產生工具,支援商業私密金鑰憑證與密碼配置。
* **專案配置預設匯入/匯出**:支援將所有建置參數、資源清單與對應規則匯出為獨立的 `.qpypack` 專案工程預設檔案,便於團隊共享與持續整合。
### 4. 強健的建置容錯與自癒降級
* 📏 **編譯前實體資源評估**:自動評估實體記憶體與磁碟可用空間,智慧調整併發 CPU 核心數。
* 🛡️ **OOM 記憶體溢出自癒**:建置過程中遭遇 `ZstdError`(記憶體溢出)時,自動觸發單執行緒 (`--jobs=1`) 降級重試。
* 🛡️ **圖示鎖定抗性**:遭遇防毒軟體或系統鎖定圖示檔案時,自動觸發剝離圖示參數自癒建置,保障二進位產物順利產生。
* ☁️ **雲端硬碟鎖定預警**:前置感知識別 OneDrive / Dropbox 等雲端硬碟對檔案的鎖定同步狀態並提供明確排查提示。
### 5. 資源管理與應用程式元資料
* 📝 **PE / Plist 元資料注入**:直接在介面設定版本號、公司名稱、產品描述,全自動寫入 Windows PE VersionInfo 或 macOS `Info.plist` 結構。
* 📂 **視覺化附加資源管理**:提供列表化介面管理附加檔案與資料夾,支援雙擊直接編輯打包後的相對釋放路徑(自適應路徑對映)。
### 5. 跨平台互動體驗
* **拖放即用**:直接拖入 Python 原始碼即可自動解析模組元資料(版本、作者、應用程式名稱)、推導進入點並匹配同層資源圖示。
* **向量渲染與全球化 i18n**:全介面基於 Google Material SVG 向量圖示繪製,完美適配 4K/高解析度螢幕 DPI 縮放;內建涵蓋簡繁中文、英語、日語、韓語、德語、法語等 17 種語言的即時國際化系統。
---
## ⚡ 快速上手 (Quick Start)
## 📊 引擎選型對比 (PyInstaller vs. Nuitka)
### 方法一:透過 pip 安裝並執行
| 評估維度 | PyInstaller | Nuitka |
| :--- | :--- | :--- |
| **打包原理** | 打包 Python 直譯器與位元組碼檔案 (`.pyc`) | 將 Python 程式碼編譯為原生 C/C++ 二進位檔案 |
| **建置速度** | 極快(通常 10 ~ 60 秒) | 較慢(涉及 C++ 程式碼產生與編譯器最佳化) |
| **C/C++ 編譯器相依** | 無需任何外部編譯器 | 相依 MSVC / GCC / Clang(支援自動託管下載) |
| **程式碼保護等級** | 基礎(可透過反編譯工具還原原始碼邏輯) | 極高(原生機器碼,深層抗逆向分析) |
| **產物執行效能** | 接近原生 Python 執行速度 | 啟動速度快,部分迴圈與計算密集型邏輯更優 |
| **推薦適用場景** | 快速反覆運算測試、內部工具、複雜動態匯入專案 | 商業交付軟體、核心演算法保護、追求體積與啟動速度 |
在 Python >= 3.8 的環境中,執行以下命令進行安裝與啟動:
---
## ⚡ 快速開始 (Quick Start)
> 💡 **首次使用?** 建議查閱 3 分鐘 [**📖 快速入門指南 (QUICKSTART.md)**](../../QUICKSTART.md) 了解詳細的使用教學與典型情境配置指南。
### 安裝方式 1:透過 pip / pipx 安裝(推薦)
在 Python >= 3.8 的環境中執行:
```bash
# 安裝 QPyPack
# 透過 pip 安裝
pip install qpypack
# 啟動程式
# 啟動圖形介面
qpypack
```
### 方法二:下載獨立二進位免安裝版
*若使用現代套件管理器(推薦):*
```bash
# 使用 pipx 隔離執行
pipx run qpypack
如果您不想設定本地 Python 環境,可直接在 GitHub Release 頁面下載對應系統的預編譯打包版本:
👉 [下載預編譯版本 (GitHub Releases)](https://github.com/Qwejay/QPyPack/releases)
# 或使用 uv 極速啟動
uvx qpypack
```
### 安裝方式 2:使用獨立預編譯免安裝版
無需預先安裝 Python 環境,可直接在 GitHub Release 頁面下載適用於您作業系統的可執行檔:
👉 [**下載預編譯版本 (GitHub Releases)**](https://github.com/Qwejay/QPyPack/releases)
---
## 📅 更新日誌 (Changelog)
## 📋 常用配置說明
完整的版本更新歷史與 Release 說明請參閱 [CHANGELOG.md](../../CHANGELOG.md) 或 [GitHub Releases 頁面](https://github.com/Qwejay/QPyPack/releases)。
### 相依性與資源釋放路徑 (`sys._MEIPASS`)
在單檔案打包模式下,附加的資料檔案(圖片、配置、模型等)會在執行期暫時解壓縮至特定沙盒目錄。請確保在原始碼中按如下標準方式解析路徑:
```python
import sys
import os
from pathlib import Path
def get_asset_path(relative_path: str) -> Path:
"""取得打包後資源的絕對路徑"""
if hasattr(sys, "_MEIPASS"):
# PyInstaller 單檔案解壓縮目錄
base_path = Path(sys._MEIPASS)
elif "__compiled__" in globals():
# Nuitka 二進位執行目錄
base_path = Path(sys.argv[0]).resolve().parent
else:
# 開發偵錯環境目錄
base_path = Path(__file__).resolve().parent
return base_path / relative_path
```
---
## 💖 贊助支援 (Sponsorship)
## 📅 版本更新歷史 (Changelog)
QPyPack 是一款完全開源且免費的專案,由作者利用業餘時間開發與維護。如果本專案協助您提高了開發效率或解決了打包難題,歡迎透過以下方式對專案進行**自願贊助**。您的支援將是本專案持續更新的重要動力:
- ⚡ **請作者喝咖啡**:[贊助支援 QPyPack](https://www.ifdian.net/a/qwejay)(支援微信 / 支付寶)
> **贊助說明**:贊助完全出於自願,屬於對開源專案的無償鼓勵,不包含任何商業服務繫結或特定功能開發承諾。非常感謝每一位支援開源創作的朋友!
詳細的版本演進路線、功能新增與缺陷修復說明請參閱 [CHANGELOG.md](../../CHANGELOG.md)。
---
## 📄 開源條款 (License)
## 💖 參與貢獻與贊助 (Sponsorship & Contributing)
本專案基於 [GNU General Public License v3.0](LICENSE) 開源,允許在遵循條款的前提下自由分發、修改和二次開發。
QPyPack 是一個遵循開源理念的專案。如果您在日常開發或工作中受益於本專案,歡迎透過以下方式支援本專案的長期維護與反覆運算:
> [!NOTE]
> **關於打包產物的版權**:
> 使用 QPyPack 建置產生的二進位檔案/應用程式,其版權和開源許可**完全由使用者自行決定**,QPyPack 的 GPL-3.0 協議不會約束或影響使用者打包後的程式。
- 🌟 **Star 支援**:在 [GitHub](https://github.com/Qwejay/QPyPack) 上為專案點亮 Star。
- 🐛 **反饋與建議**:提交 [Issue](https://github.com/Qwejay/QPyPack/issues) 反饋缺陷或提出改進需求。
- ⚡ **贊助專案**:透過 [愛發電平台](https://www.ifdian.net/a/qwejay) 進行無償資助(支援微信 / 支付寶)。
Copyright (C) 2026 QwejayHuang.
> *註:贊助屬於對開源社群專案的無償鼓勵,不涉及任何商業承諾或客製化開發服務。感謝所有支援開源社群建設的開發者!*
---
## 📄 開源許可 (License)
本專案基於 [GNU General Public License v3.0 (GPL-3.0)](../../LICENSE) 協議開源。
> [!IMPORTANT]
> **關於建置產物的版權說明**:
> 使用 QPyPack 建置產生的最終應用程式與二進位產物,其**智慧財產權與開源授權完全由使用者自行決定**,QPyPack 的 GPL-3.0 許可協議不會對您的編譯產物施加傳染性約束。
<p align="right">Copyright (C) 2026 QwejayHuang.</p>