import gradio as gr
import os
import subprocess
import sys
import shutil
import uuid
import platform
import time
from pathlib import Path
import tempfile
import glob
import traceback
import threading
import queue
def ensure_dir(dir_path):
"""Ensure directory exists"""
Path(dir_path).mkdir(parents=True, exist_ok=True)
def check_dependencies():
"""Check if required dependencies are available"""
missing_deps = []
# Check for nuitka first
try:
result = subprocess.run([sys.executable, "-m", "nuitka", "--version"], capture_output=True, text=True)
if result.returncode != 0:
missing_deps.append("nuitka")
except:
missing_deps.append("nuitka")
# Check for MinGW-w64 (needed for Windows cross-compilation)
result = subprocess.run(["which", "x86_64-w64-mingw32-gcc"], capture_output=True)
if result.returncode != 0:
missing_deps.append("mingw-w64")
# Check for patchelf (usually available in HF Spaces)
result = subprocess.run(["which", "patchelf"], capture_output=True)
if result.returncode != 0:
missing_deps.append("patchelf")
# Check for gcc (usually available in HF Spaces)
result = subprocess.run(["which", "gcc"], capture_output=True)
if result.returncode != 0:
missing_deps.append("gcc")
return missing_deps
def check_static_libpython():
"""Check if static libpython is available"""
try:
# Try to find static libpython
result = subprocess.run(
[sys.executable, "-c", "import sysconfig; print(sysconfig.get_config_var('LIBDIR'))"],
capture_output=True, text=True
)
if result.returncode == 0:
libdir = result.stdout.strip()
# Look for libpython.a files
static_libs = glob.glob(os.path.join(libdir, "libpython*.a"))
return len(static_libs) > 0
except:
pass
return False
def get_current_python_version():
"""Get the current Python version for compatibility notes"""
return f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"
def get_nuitka_version():
"""Get the current Nuitka version to handle different command line options"""
try:
result = subprocess.run([sys.executable, "-m", "nuitka", "--version"],
capture_output=True, text=True)
if result.returncode == 0:
version_line = result.stdout.strip().split('\n')[0]
# Extract version number from output like "Nuitka 2.5.0"
version = version_line.split()[-1]
return version
return "not installed"
except:
return "not installed"
def create_progress_bar(progress, status_text="", show_percentage=True):
"""Create an HTML progress bar"""
percentage = max(0, min(100, progress * 100))
color = "bg-green-500" if percentage == 100 else ("bg-yellow-500" if percentage > 50 else "bg-blue-500")
html = f"""
{f'{percentage:.1f}%' if show_percentage else ''}
{status_text}
"""
return html
def install_system_packages(packages_content, progress_callback=None):
"""Note about system packages in HF Spaces - they cannot be installed"""
if not packages_content.strip():
return "No system packages specified."
# In HF Spaces, we can't install system packages
packages_list = [line.strip() for line in packages_content.strip().split('\n')
if line.strip() and not line.strip().startswith('#')]
if packages_list:
return f"❌ System packages cannot be installed in Hugging Face Spaces:\n{', '.join(packages_list)}\n\nℹ️ HF Spaces runs in a containerized environment without sudo access.\nThese packages need to be pre-installed in the Docker image or available as Python packages."
return "No system packages specified."
def install_nuitka_if_missing():
"""Try to install Nuitka if it's missing"""
try:
# Check if nuitka is already installed
result = subprocess.run([sys.executable, "-m", "nuitka", "--version"], capture_output=True)
if result.returncode == 0:
return True, "Nuitka is already installed"
# Try to install nuitka
print("Installing Nuitka...")
result = subprocess.run([sys.executable, "-m", "pip", "install", "nuitka"],
capture_output=True, text=True)
if result.returncode == 0:
return True, "Nuitka installed successfully"
else:
return False, f"Failed to install Nuitka: {result.stderr}"
except Exception as e:
return False, f"Error installing Nuitka: {str(e)}"
def check_mingw_installation():
"""Check if MinGW-w64 is properly installed"""
mingw_compilers = [
"x86_64-w64-mingw32-gcc",
"x86_64-w64-mingw32-g++",
"x86_64-w64-mingw32-ld"
]
missing = []
for compiler in mingw_compilers:
result = subprocess.run(["which", compiler], capture_output=True)
if result.returncode != 0:
missing.append(compiler)
return missing
def find_compiled_binary(output_dir, output_filename):
"""Find the compiled binary, checking different possible paths"""
# Try direct path first
direct_path = os.path.join(output_dir, output_filename)
if os.path.exists(direct_path):
return direct_path
# Try in .dist folder (standalone builds)
dist_path = os.path.join(output_dir, "user_script.dist", output_filename)
if os.path.exists(dist_path):
return dist_path
# Try using glob to find any executable
patterns = [
os.path.join(output_dir, "**", output_filename),
os.path.join(output_dir, "**", "user_script"),
os.path.join(output_dir, "**", "user_script.exe"),
os.path.join(output_dir, "**", "*.bin"),
os.path.join(output_dir, "**", "*.exe"),
]
for pattern in patterns:
matches = glob.glob(pattern, recursive=True)
if matches:
return matches[0]
return None
def compile_with_nuitka(code, requirements, packages, compilation_mode, output_extension, log_queue, progress_callback=None):
"""Compile Python code with Nuitka"""
try:
# Initialize progress
if progress_callback:
progress_callback(0, "Starting compilation process...")
if log_queue:
log_queue.put("=== Starting Nuitka Compilation ===\n")
# Check if Nuitka is installed
nuitka_installed, nuitka_msg = install_nuitka_if_missing()
if not nuitka_installed:
error_summary = f"""# ❌ Nuitka Not Available
## Error:
{nuitka_msg}
## Solution:
Nuitka needs to be installed first. In Hugging Face Spaces, this should be done in the requirements.txt file:
```
nuitka
```
Add this to your requirements.txt and redeploy the space."""
return error_summary, None, nuitka_msg, False
if progress_callback:
progress_callback(0.05, "Checking environment...")
# Check for Windows cross-compilation requirements
if output_extension == ".exe":
missing_mingw = check_mingw_installation()
if missing_mingw:
if log_queue:
log_queue.put(f"⚠️ Warning: Missing MinGW components: {', '.join(missing_mingw)}\n")
log_queue.put("Windows cross-compilation may fail without proper MinGW-w64 installation\n")
# Check Nuitka version
nuitka_version = get_nuitka_version()
# Check if static libpython is available
has_static_libpython = check_static_libpython()
# Check dependencies first
missing_deps = check_dependencies()
if progress_callback:
progress_callback(0.1, "Setting up compilation directories...")
# Create unique ID for this compilation
job_id = str(uuid.uuid4())
base_dir = os.path.join(os.getcwd(), "user_code")
job_dir = os.path.join(base_dir, job_id)
output_dir = os.path.join(os.getcwd(), "compiled_output", job_id)
# Create directories
ensure_dir(job_dir)
ensure_dir(output_dir)
if progress_callback:
progress_callback(0.15, "Processing packages...")
# Handle system packages (just log them, can't install in HF Spaces)
packages_result = install_system_packages(packages)
# Write code to a Python file
script_path = os.path.join(job_dir, "user_script.py")
with open(script_path, "w") as f:
f.write(code)
if progress_callback:
progress_callback(0.2, "Installing Python requirements...")
# Handle requirements
install_result = "No Python requirements specified."
if requirements.strip():
req_path = os.path.join(job_dir, "requirements.txt")
with open(req_path, "w") as f:
f.write(requirements)
try:
if log_queue:
log_queue.put("Installing Python requirements...\n")
install_process = subprocess.run(
[sys.executable, "-m", "pip", "install", "--no-cache-dir", "-r", req_path],
capture_output=True,
text=True
)
if install_process.returncode == 0:
install_result = "✅ Python requirements installed successfully."
if log_queue:
log_queue.put("✅ Requirements installed successfully\n")
else:
install_result = f"⚠️ Installation completed with warnings. Return code: {install_process.returncode}\n{install_process.stderr}"
if log_queue:
log_queue.put(f"⚠️ Installation warnings:\n{install_process.stderr}\n")
except Exception as e:
install_result = f"❌ Error installing requirements: {str(e)}"
if log_queue:
log_queue.put(f"❌ Error installing requirements: {str(e)}\n")
return install_result, None, f"Error: {str(e)}", False
if progress_callback:
progress_callback(0.3, "Building compilation command...")
# Build compilation command based on mode
if compilation_mode == "Maximum Compatibility (Recommended)":
cmd = [
sys.executable, "-m", "nuitka",
"--standalone",
"--onefile", # Single portable file
"--show-progress",
"--remove-output",
"--follow-imports",
"--assume-yes-for-downloads", # Auto-download missing dependencies
"--python-flag=no_site", # Reduce dependencies
"--python-flag=no_warnings", # Reduce warnings
script_path,
f"--output-dir={output_dir}"
]
# Add static linking if available (not for Windows)
if has_static_libpython and output_extension != ".exe":
cmd.append("--static-libpython=yes")
mode_name = "Maximum Compatibility Binary"
elif compilation_mode == "Portable Binary":
cmd = [
sys.executable, "-m", "nuitka",
"--show-progress",
"--remove-output",
"--assume-yes-for-downloads",
"--python-flag=no_site",
"--python-flag=no_warnings",
script_path,
f"--output-dir={output_dir}"
]
mode_name = "Portable Non-Standalone"
else: # Standalone Binary
cmd = [
sys.executable, "-m", "nuitka",
"--standalone",
"--onefile",
"--show-progress",
"--remove-output",
"--assume-yes-for-downloads",
"--python-flag=no_site",
"--python-flag=no_warnings",
script_path,
f"--output-dir={output_dir}"
]
mode_name = "Standalone Binary"
# Add Windows-specific options using MinGW-w64
if output_extension == ".exe":
cmd.extend([
"--mingw64", # Use MinGW-w64 for cross-compilation
"--windows-disable-console", # Disable console window for GUI apps
"--target-arch=x64", # Explicitly target 64-bit architecture
"--msvc=14.3", # Use MSVC compatibility mode
])
# Note: --mingw64 flag tells Nuitka to use MinGW-w64 for Windows cross-compilation
if log_queue:
log_queue.put("Using MinGW-w64 for Windows 64-bit cross-compilation\n")
log_queue.put("Note: Cross-compiling from Linux to Windows x64 using proper MinGW-w64 toolchain\n")
log_queue.put("Target architecture: x64 (64-bit)\n")
# Run compilation
if progress_callback:
progress_callback(0.4, "Executing Nuitka compilation...")
if log_queue:
log_queue.put(f"Compilation command: {' '.join(cmd)}\n")
log_queue.put("Starting compilation...\n")
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1,
universal_newlines=True
)
# Progress tracking
compile_output = ""
line_count = 0
# Real-time progress display
for line in iter(process.stdout.readline, ''):
compile_output += line
line_count += 1
# Send line to log queue
if log_queue:
log_queue.put(line)
# Update progress
progress_val = 0.4 + (min(line_count / 200, 0.55) * 0.5)
status_text = "Compiling..."
if "INFO:" in line:
status_text = f"INFO: {line.strip()[:60]}..."
elif "PROCESSING" in line:
status_text = f"Processing: {line.strip()[:60]}..."
elif "Optimizing" in line:
status_text = f"Optimizing: {line.strip()[:60]}..."
elif "Creating" in line:
status_text = f"Creating: {line.strip()[:60]}..."
elif "MinGW" in line:
status_text = f"MinGW: {line.strip()[:60]}..."
if progress_callback:
progress_callback(progress_val, status_text)
process.wait()
if progress_callback:
progress_callback(0.9, "Finalizing compilation...")
# Find the compiled binary
output_filename = f"user_script{output_extension}"
binary_path = find_compiled_binary(output_dir, output_filename)
# If not found with expected extension, try finding any executable
if not binary_path:
# Try common executable patterns for onefile
patterns = [
os.path.join(output_dir, "user_script"),
os.path.join(output_dir, "user_script.bin"),
os.path.join(output_dir, "user_script.exe"),
os.path.join(output_dir, "**", "user_script"),
os.path.join(output_dir, "**", "*.bin"),
os.path.join(output_dir, "**", "*.exe"),
]
for pattern in patterns:
matches = glob.glob(pattern, recursive=True)
if matches:
binary_path = matches[0]
break
if log_queue:
log_queue.put(f"Compilation finished with exit code: {process.returncode}\n")
if process.returncode == 0 and binary_path:
# Check if it's really a binary file
try:
file_process = subprocess.run(["file", binary_path], capture_output=True, text=True)
binary_info = file_process.stdout
if log_queue:
log_queue.put(f"Binary info: {binary_info}\n")
except:
binary_info = "Binary file (unable to get detailed info)"
# Check linking type (only for non-Windows binaries on Linux)
if output_extension != ".exe":
try:
ldd_process = subprocess.run(["ldd", binary_path], capture_output=True, text=True)
if "not a dynamic executable" in ldd_process.stderr or "statically linked" in ldd_process.stdout:
linking_info = "✅ Statically linked - fully portable!"
else:
# Check what dynamic libraries are required
if ldd_process.returncode == 0:
libs = ldd_process.stdout.count("=>")
linking_info = f"🔗 Dynamically linked ({libs} libraries) - designed for maximum compatibility"
else:
linking_info = "ℹ️ Compiled binary - should work on compatible systems"
except:
linking_info = "ℹ️ Compiled binary created successfully"
else:
# For Windows, check architecture
linking_info = "📦 Windows x64 executable (cross-compiled with MinGW-w64)"
if log_queue:
log_queue.put("Binary architecture: 64-bit (x64)\n")
# Rename to desired extension
if output_extension in ['.bin', '.sh', '.exe'] and not binary_path.endswith(output_extension):
new_binary_path = binary_path + output_extension
shutil.move(binary_path, new_binary_path)
binary_path = new_binary_path
# Make executable (for non-Windows)
if output_extension != ".exe":
os.chmod(binary_path, 0o755)
# Current Python version info
current_python = get_current_python_version()
# Build the result summary string
static_status = "Yes" if has_static_libpython else "No"
file_size = os.path.getsize(binary_path) / 1024
binary_basename = os.path.basename(binary_path)
# Create result summary
result_summary = f"""# ✅ Compilation Successful!
## Compilation Details:
- **Mode**: {mode_name}
- **Nuitka Version**: {nuitka_version}
- **Exit Code**: {process.returncode}
- **Output Path**: {binary_path}
- **File Size**: {file_size:.2f} KB
- **Compiled with Python**: {current_python}
- **Static Libpython Available**: {static_status}
- **Linking**: {linking_info}
- **Target Platform**: {'Windows x64 (.exe) via MinGW-w64' if output_extension == '.exe' else 'Linux'}
## Environment Results:
**System Packages**: {packages_result}
**Python Requirements**: {install_result}
## Binary Information:
{binary_info}
## 🚀 Portability Notes:
- This binary was compiled with maximum compatibility settings
- Using --onefile for single-file distribution
- {'Cross-compiled specifically for Windows 64-bit (x64) using MinGW-w64 toolchain' if output_extension == '.exe' else 'Should work on most compatible Linux systems'}
{f'- Console window disabled for Windows GUI applications' if output_extension == '.exe' else ''}
- {'Explicitly targets x64 architecture for maximum Windows compatibility' if output_extension == '.exe' else ''}
## 📋 Usage Instructions:
```bash
{f'# For Windows (64-bit):' if output_extension == '.exe' else f'chmod +x {binary_basename}'}
{f'# Download to Windows machine and run:' if output_extension == '.exe' else ''}
{f'{binary_basename}' if output_extension == '.exe' else f'./{binary_basename}'}
```
## ⚠️ Cross-Compilation Notes:
{f'''- Compiled from Linux to Windows x64 using MinGW-w64
- Uses --target-arch=x64 for explicit 64-bit compilation
- Tested with wine if available: `wine {binary_basename}`
- Compatible with Windows 7 64-bit and later
- Some Windows-specific libraries may need additional setup
- GUI frameworks may require special handling''' if output_extension == '.exe' else 'Native Linux compilation with maximum compatibility'}
## 🧪 Testing:
{f'You can test the Windows executable on Linux using wine:' if output_extension == '.exe' else 'Run directly on compatible Linux systems:'}
```bash
{f'wine {binary_basename}' if output_extension == '.exe' else f'./{binary_basename}'}
```"""
if progress_callback:
progress_callback(1.0, "Compilation successful! 🎉")
if log_queue:
log_queue.put("✅ Compilation completed successfully!\n")
if output_extension == ".exe":
log_queue.put("🍷 You can test the Windows x64 executable with: wine " + binary_basename + "\n")
return result_summary, binary_path, compile_output, True
else:
# Add more detailed error information
error_summary = f"""# ❌ Compilation Failed
## Error Details:
- **Exit Code**: {process.returncode}
- **Mode Attempted**: {mode_name}
- **Target**: {'Windows x64 (.exe) via MinGW-w64' if output_extension == '.exe' else 'Linux'}
## Environment Results:
**System Packages**: {packages_result}
**Python Requirements**: {install_result}
## Compilation Output:
```
{compile_output}
```
## Possible Solutions:
1. Check your code for syntax errors
2. Ensure all imports are available in requirements.txt
3. Try a different compilation mode
4. Review the compilation logs above
{f"5. For Windows cross-compilation, ensure MinGW-w64 is properly installed" if output_extension == '.exe' else ''}
{f"6. Some packages may not support Windows cross-compilation" if output_extension == '.exe' else ''}
{f"7. For 64-bit Windows, ensure all dependencies support x64 architecture" if output_extension == '.exe' else ''}
## Missing Dependencies:
{', '.join(missing_deps) if missing_deps else 'None detected'}
## Environment Info:
- **Nuitka Version**: {nuitka_version}
- **Python Version**: {current_python}
- **Platform**: {platform.platform()}
{f"- **MinGW-w64**: {'Available' if not check_mingw_installation() else 'Missing components'}" if output_extension == '.exe' else ''}
{f"- **Target Architecture**: x64 (64-bit)" if output_extension == '.exe' else ''}"""
if progress_callback:
progress_callback(1.0, "Compilation failed ❌")
if log_queue:
log_queue.put("❌ Compilation failed!\n")
return error_summary, None, compile_output, False
except Exception as e:
# Provide detailed error information
error_trace = traceback.format_exc()
error_summary = f"""# ❌ Compilation Error
## Error:
{str(e)}
## Full Error Trace:
```
{error_trace}
```
## Environment Status:
- **Nuitka Version**: {get_nuitka_version()}
- **Python Version**: {get_current_python_version()}
- **Working Directory**: {os.getcwd()}
## Troubleshooting Steps:
1. Check if Nuitka is properly installed
2. Verify your code syntax
3. Check available disk space
4. Try with simpler code first
{f"5. Ensure MinGW-w64 is installed for Windows cross-compilation" if output_extension == '.exe' else ''}
{f"6. For Windows 64-bit, ensure proper x64 toolchain" if output_extension == '.exe' else ''}"""
if progress_callback:
progress_callback(1.0, "Error occurred ❌")
if log_queue:
log_queue.put(f"❌ Error: {str(e)}\n")
return error_summary, None, f"Error: {str(e)}\n\n{error_trace}", False
def run_compiled_binary(binary_path):
"""Run the compiled binary and return the output"""
if not binary_path or not os.path.exists(binary_path):
return "❌ No binary available to run."
try:
# Check if it's a Windows exe on Linux
if binary_path.endswith('.exe'):
# Try to run with wine first
wine_result = subprocess.run(["which", "wine"], capture_output=True)
if wine_result.returncode == 0:
return f"""🍷 **Running Windows x64 executable with Wine**
## Execution:
```bash
wine {os.path.basename(binary_path)}
```
## Output:
To run on Windows:
1. Download the .exe file
2. Transfer it to a Windows machine
3. Run it by double-clicking or from command prompt
```cmd
# On Windows command prompt:
{os.path.basename(binary_path)}
```
## Note:
- Wine is available on this system for basic testing
- This executable is compiled for Windows 64-bit (x64)
- Full compatibility requires running on actual Windows
- Some features may not work correctly in wine"""
else:
return f"""❌ Cannot run Windows .exe file on Linux system (wine not available).
## To run this binary:
1. Download the .exe file
2. Transfer it to a Windows machine (64-bit required)
3. Run it by double-clicking or from command prompt
```cmd
# On Windows command prompt:
cd /path/to/downloaded/file
{os.path.basename(binary_path)}
```
## Note:
- This executable is compiled for Windows 64-bit (x64)
- Compatible with Windows 7 64-bit and later
- Will not work on 32-bit Windows systems
## Alternative:
Install wine to test Windows executables on Linux:
```bash
sudo apt update
sudo apt install wine
wine {os.path.basename(binary_path)}
```"""
# Make the binary executable (for non-Windows)
if not binary_path.endswith('.exe'):
os.chmod(binary_path, 0o755)
# Run the binary with timeout
process = subprocess.run(
[binary_path],
capture_output=True,
text=True,
timeout=30, # Increased timeout for HF Spaces
cwd=os.path.dirname(binary_path) # Run in binary's directory
)
output = ""
if process.stdout:
output += f"## [STDOUT]\n```\n{process.stdout}\n```\n"
if process.stderr:
output += f"## [STDERR]\n```\n{process.stderr}\n```\n"
if process.returncode != 0:
output += f"## [EXIT CODE]\n{process.returncode}\n"
if not output:
output = "✅ Binary executed successfully with no output."
else:
output = "## 🧪 Execution Results\n" + output
return output
except subprocess.TimeoutExpired:
return "⏱️ **Execution timed out after 30 seconds.**\n\nThis might indicate:\n- The program is waiting for input\n- An infinite loop\n- Long-running computation"
except Exception as e:
return f"❌ **Error running the binary:**\n\n```\n{str(e)}\n```"
# Create Gradio interface
with gr.Blocks(title="Nuitka Python Compiler with MinGW-w64", theme=gr.themes.Soft()) as app:
gr.Markdown("# 🚀 Nuitka Python Compiler (MinGW-w64 Cross-Compilation)")
gr.Markdown("Convert your Python code into portable executables using Nuitka, with proper MinGW-w64 support for Windows 64-bit cross-compilation.")
# Check environment status
has_static = check_static_libpython()
missing_deps = check_dependencies()
mingw_missing = check_mingw_installation()
if "nuitka" in missing_deps:
gr.Markdown("⚠️ **Nuitka is not installed!** Add 'nuitka' to your requirements.txt file.")
if has_static:
gr.Markdown("🎯 **Static Libpython Available!** Maximum portability enabled.")
else:
gr.Markdown("🔧 **Using alternative portable options.** Static libpython not available.")
if mingw_missing:
gr.Markdown(f"⚠️ **MinGW-w64 Components Missing:** {', '.join(mingw_missing)}")
gr.Markdown("📝 **For Windows .exe generation**, MinGW-w64 should be pre-installed in the environment.")
else:
gr.Markdown("✅ **MinGW-w64 Available!** Windows 64-bit cross-compilation supported.")
if [dep for dep in missing_deps if dep != "nuitka" and dep != "mingw-w64"]:
gr.Markdown(f"⚠️ **Other missing dependencies:** {', '.join([dep for dep in missing_deps if dep != 'nuitka' and dep != 'mingw-w64'])}")
# MinGW-w64 information
gr.Markdown("""
> ℹ️ **MinGW-w64 Cross-Compilation**: Using proper MinGW-w64 toolchain for Windows 64-bit .exe generation.
> This follows the official Nuitka documentation and explicitly targets x64 architecture.
""")
with gr.Tabs():
with gr.TabItem("🔧 Compiler"):
with gr.Row():
with gr.Column(scale=2):
code_input = gr.Code(
value="""# Your Python code here
print('Hello from compiled Python!')
print('This cross-platform binary was created with Nuitka!')
# This will work with automatic compatibility detection
import os, sys
print(f'Running from: {os.getcwd()}')
print(f'Python executable: {sys.executable}')
print(f'Platform: {sys.platform}')
# Simple example with user input
name = input('What is your name? ')
print(f'Hello, {name}!')
# Wait for user before closing (helpful for Windows .exe)
input('Press Enter to exit...')""",
language="python",
label="Your Python Code",
lines=20
)
with gr.Column(scale=1):
with gr.Tabs():
with gr.TabItem("Python Requirements"):
requirements_input = gr.Textbox(
placeholder="""# Add your Python dependencies here
# Example:
# numpy==1.24.0
# pandas==2.0.0
# requests>=2.28.0
# matplotlib
# pillow
# Note: Some packages may not work with Windows cross-compilation""",
lines=8,
label="requirements.txt content"
)
with gr.TabItem("System Packages"):
gr.Markdown("⚠️ **System packages cannot be installed in HF Spaces**")
gr.Markdown("📝 **For MinGW-w64**, it should be pre-installed in the Docker image")
packages_input = gr.Textbox(
placeholder="""# System packages (for reference only)
# These should be pre-installed in HF Spaces
# mingw-w64
# gcc-mingw-w64
# g++-mingw-w64""",
lines=8,
label="System packages (Reference Only)",
interactive=True
)
# Fixed dropdown choices
compilation_mode = gr.Dropdown(
choices=[
"Maximum Compatibility (Recommended)",
"Portable Binary",
"Standalone Binary"
],
value="Maximum Compatibility (Recommended)",
label="Compilation Mode"
)
output_extension = gr.Dropdown(
choices=[".bin", ".sh", ".exe"],
value=".bin",
label="Output File Extension"
)
gr.Markdown("### 🔧 Environment Status")
gr.Markdown(f"📍 **Python Version**: {get_current_python_version()}")
gr.Markdown(f"🚀 **Nuitka Version**: {get_nuitka_version()}")
if mingw_missing:
gr.Markdown(f"⚠️ **MinGW-w64**: Missing ({', '.join(mingw_missing)})")
else:
gr.Markdown("✅ **MinGW-w64**: Available for Windows 64-bit cross-compilation")
if check_static_libpython():
gr.Markdown("🔗 **Static libpython will be used for Linux targets!**")
else:
gr.Markdown("🔧 **Using portable compilation flags**")
# Add architecture notice
gr.Markdown("🏗️ **Windows Target**: x64 (64-bit) architecture")
compile_btn = gr.Button("🚀 Compile with Nuitka", variant="primary")
# Progress Bar Section
with gr.Column(visible=False) as progress_section:
gr.Markdown("### 📊 Compilation Progress")
progress_bar = gr.HTML(create_progress_bar(0, "Ready to compile..."))
# Real-time Logs Section
with gr.Column(visible=False) as logs_section:
gr.Markdown("### 📜 Real-time Compilation Logs")
real_time_logs = gr.Textbox(
label="Compilation Logs",
lines=15,
max_lines=30,
value="Logs will appear here during compilation...",
interactive=False
)
# Results section
with gr.Column(visible=False) as results_section:
with gr.Accordion("📊 Compilation Results", open=True):
result_summary = gr.Markdown()
with gr.Accordion("📜 Complete Compilation Logs", open=False):
compile_logs = gr.Textbox(label="Complete Compilation Output", lines=15)
download_file = gr.File(label="📥 Download Compiled Binary")
# Test run section
with gr.Row():
run_btn = gr.Button("🧪 Test Run Binary", variant="secondary")
run_output = gr.Markdown(label="Execution Output")
# Variables to store state
current_binary_path = gr.State(None)
compilation_success = gr.State(False)
log_queue = gr.State(None)
def update_progress_display(progress, status):
"""Update the progress bar display"""
return gr.update(value=create_progress_bar(progress, status))
def handle_compilation(code, requirements, packages, mode, extension):
try:
# Initialize log queue here instead of in State
log_q = queue.Queue()
current_logs = ""
# Show progress and logs sections
yield (
gr.update(visible=True), # progress_section
gr.update(value=create_progress_bar(0, "Initializing compilation...")), # progress_bar
gr.update(visible=True), # logs_section
gr.update(value="=== Starting Compilation ===\n"), # real_time_logs
gr.update(visible=False), # results_section (hide initially)
gr.update(), # result_summary
gr.update(), # compile_logs
gr.update(visible=False), # download_file
None, # current_binary_path
False, # compilation_success
log_q # log_queue
)
# Define progress callback
def progress_callback(progress, status):
pass
# Start compilation in a separate thread
def compile_thread():
return compile_with_nuitka(
code, requirements, packages, mode, extension, log_q, progress_callback
)
# Run compilation
compilation_thread = threading.Thread(target=compile_thread)
compilation_result = [None]
def get_result():
compilation_result[0] = compile_with_nuitka(
code, requirements, packages, mode, extension, log_q, progress_callback
)
thread = threading.Thread(target=get_result)
thread.start()
# Progress simulation with log updates
progress_steps = [
(0.1, "Checking Nuitka installation..."),
(0.15, "Checking MinGW-w64 for Windows x64 targets..." if extension == ".exe" else "Checking environment..."),
(0.2, "Setting up environment..."),
(0.3, "Installing requirements..."),
(0.4, f"Starting {'Windows x64 cross-' if extension == '.exe' else ''}compilation..."),
(0.5, "Processing imports..."),
(0.6, "Optimizing code..."),
(0.7, f"Creating {extension} binary..."),
(0.8, "Finalizing..."),
]
for progress, status in progress_steps:
# Check for new logs
while not log_q.empty():
try:
new_line = log_q.get_nowait()
current_logs += new_line
except queue.Empty:
break
yield (
gr.update(visible=True), # progress_section
gr.update(value=create_progress_bar(progress, status)), # progress_bar
gr.update(visible=True), # logs_section
gr.update(value=current_logs), # real_time_logs
gr.update(visible=False), # results_section
gr.update(), # result_summary
gr.update(), # compile_logs
gr.update(visible=False), # download_file
None, # current_binary_path
False, # compilation_success
log_q # log_queue
)
time.sleep(0.5)
# Wait for compilation to complete
thread.join()
# Get any remaining logs
while not log_q.empty():
try:
new_line = log_q.get_nowait()
current_logs += new_line
except queue.Empty:
break
# Get compilation result
summary, binary_path, logs, success = compilation_result[0]
# Final progress update
final_status = "✅ Compilation successful!" if success else "❌ Compilation failed"
if success and extension == ".exe":
final_status += " (Windows x64 .exe created)"
yield (
gr.update(visible=True), # progress_section
gr.update(value=create_progress_bar(1.0, final_status)), # progress_bar
gr.update(visible=True), # logs_section
gr.update(value=current_logs), # real_time_logs
gr.update(visible=True), # results_section
gr.update(value=summary), # result_summary
gr.update(value=logs), # compile_logs
gr.update(visible=False), # download_file (initially hidden)
None, # current_binary_path
False, # compilation_success
log_q # log_queue
)
if success and binary_path:
# Create download file
download_filename = f"compiled_program{extension}"
download_path = os.path.join(os.path.dirname(binary_path), download_filename)
shutil.copy2(binary_path, download_path)
# Final update with download file
yield (
gr.update(visible=True), # progress_section
gr.update(value=create_progress_bar(1.0, f"✅ {extension} compilation successful! Ready to download.")), # progress_bar
gr.update(visible=True), # logs_section
gr.update(value=current_logs), # real_time_logs
gr.update(visible=True), # results_section
gr.update(value=summary), # result_summary
gr.update(value=logs), # compile_logs
gr.update(value=download_path, visible=True), # download_file
binary_path, # current_binary_path
True, # compilation_success
log_q # log_queue
)
else:
# Final update for failure
yield (
gr.update(visible=True), # progress_section
gr.update(value=create_progress_bar(1.0, "❌ Compilation failed. Check logs for details.")), # progress_bar
gr.update(visible=True), # logs_section
gr.update(value=current_logs), # real_time_logs
gr.update(visible=True), # results_section
gr.update(value=summary), # result_summary
gr.update(value=logs), # compile_logs
gr.update(visible=False), # download_file
None, # current_binary_path
False, # compilation_success
log_q # log_queue
)
except Exception as e:
error_trace = traceback.format_exc()
error_summary = f"""# ❌ Unexpected Error in Compilation Handler
## Error:
{str(e)}
## Full Trace:
```
{error_trace}
```"""
yield (
gr.update(visible=True), # progress_section
gr.update(value=create_progress_bar(1.0, "❌ Error occurred during compilation")), # progress_bar
gr.update(visible=True), # logs_section
gr.update(value=f"Error: {str(e)}\n{error_trace}"), # real_time_logs
gr.update(visible=True), # results_section
gr.update(value=error_summary), # result_summary
gr.update(value=f"Error: {str(e)}"), # compile_logs
gr.update(visible=False), # download_file
None, # current_binary_path
False, # compilation_success
log_q # log_queue
)
def handle_run(binary_path):
if binary_path:
output = run_compiled_binary(binary_path)
return gr.update(value=output)
else:
return gr.update(value="❌ No binary available to run.")
compile_btn.click(
handle_compilation,
inputs=[code_input, requirements_input, packages_input, compilation_mode, output_extension],
outputs=[progress_section, progress_bar, logs_section, real_time_logs, results_section, result_summary, compile_logs, download_file, current_binary_path, compilation_success, log_queue]
)
run_btn.click(
handle_run,
inputs=[current_binary_path],
outputs=[run_output]
)
with gr.TabItem("📖 How to Use"):
gr.Markdown("""
## 🎯 MinGW-w64 Cross-Compilation to Windows 64-bit
**Proper Windows x64 .exe Generation**
This app now uses the **correct method** for generating 64-bit Windows .exe files from Linux:
- **MinGW-w64 toolchain** for cross-compilation
- **`--mingw64` flag** in Nuitka
- **`--target-arch=x64`** for explicit 64-bit compilation
- **`--windows-disable-console`** for GUI applications
- **Proper cross-compilation setup** as per Nuitka documentation
**Features:**
- Real-time compilation logs
- Visual progress bar with cross-compilation status
- Automatic MinGW-w64 detection
- Wine testing support for .exe files
- **Explicit 64-bit architecture targeting**
## 📋 Usage Instructions
### 1. Write Your Code
- Enter your Python code in the code editor
- Add Python package requirements in the requirements tab
- For Windows .exe, consider adding `input('Press Enter to exit...')` to prevent console closing
### 2. Choose Target Platform
- **Linux (.bin)**: Native Linux executable (fastest compilation)
- **Linux (.sh)**: Shell script format
- **Windows (.exe)**: Cross-compiled using MinGW-w64 (64-bit, proper method)
### 3. Compile
- Click "Compile with Nuitka"
- Watch the real-time logs showing MinGW-w64 usage
- Monitor the progress bar for cross-compilation status
- Download the resulting 64-bit binary
### 4. Run Your Binary
#### For Linux binaries:
```bash
# On Linux (including WSL)
chmod +x compiled_program.bin
./compiled_program.bin
```
#### For Windows executables (64-bit):
```cmd
# Download the .exe file to Windows
compiled_program.exe
# Or from Windows command prompt:
cd Downloads
compiled_program.exe
```
#### Testing Windows .exe on Linux:
```bash
# If wine is available:
wine compiled_program.exe
```
## 🔧 MinGW-w64 Requirements
**For Windows 64-bit cross-compilation, the following should be pre-installed:**
```bash
# Ubuntu/Debian
apt install mingw-w64 gcc-mingw-w64 g++-mingw-w64
# Fedora/RHEL
dnf install mingw64-gcc mingw64-g++
```
## ⚠️ Cross-Compilation Notes
**Windows .exe from Linux (MinGW-w64 method):**
- ✅ Uses proper MinGW-w64 cross-compiler
- ✅ Follows official Nuitka documentation
- ✅ Produces native Windows 64-bit executables
- ✅ Explicitly targets x64 architecture
- ⚠️ Some Python packages may not cross-compile
- ⚠️ Windows-specific APIs may need special handling
- ✅ Can be tested with wine on Linux
- ✅ Compatible with Windows 7 64-bit and later
## 📊 Architecture Support
| Target | Architecture | Compatibility | Notes |
|--------|-------------|---------------|-------|
| Linux | x64 | Native | Best performance |
| Windows | x64 (64-bit) | Excellent | Proper MinGW-w64 cross-compilation |
| Windows | x86 (32-bit) | Not supported | Use x64 instead |
""")
with gr.TabItem("ℹ️ About"):
gr.Markdown(f"""
## 🧠 MinGW-w64 Cross-Compilation Technology
**Proper 64-bit Implementation:**
1. **MinGW-w64 Toolchain**: Uses the correct cross-compiler for Windows
2. **Nuitka Integration**: Proper `--mingw64` flag usage
3. **Architecture Targeting**: Explicit `--target-arch=x64` for 64-bit
4. **Real-time Monitoring**: Watch MinGW-w64 compilation in real-time
5. **Wine Testing**: Optional testing of Windows executables on Linux
6. **Automatic Detection**: Checks for required MinGW-w64 components
7. **Proper Flags**: Uses `--windows-disable-console` for GUI apps
## ✅ Improvements in This Version
**Enhanced cross-compilation:**
- ✅ Proper MinGW-w64 implementation
- ✅ Follows official Nuitka documentation
- ✅ **Explicit 64-bit architecture targeting**
- ✅ Real-time MinGW-w64 status in logs
- ✅ Automatic MinGW-w64 component detection
- ✅ Wine testing instructions
- ✅ Better error handling for cross-compilation
- ✅ **Architecture verification in output**
## ☁️ Environment Status
```
Platform: {platform.platform()}
Architecture: {platform.architecture()[0]}
Python Version: {get_current_python_version()}
Nuitka Version: {get_nuitka_version()}
MinGW-w64 Status: {'✅ Available' if not check_mingw_installation() else f'❌ Missing: {", ".join(check_mingw_installation())}'}
Static Libpython: {'✅ Available' if check_static_libpython() else '❌ Not Available'}
Environment: Hugging Face Spaces
Cross-Compilation: Proper MinGW-w64 support
Target Architecture: x64 (64-bit) for Windows
```
## 📋 Best Practices
**For cross-compilation:**
1. ✅ Use "Maximum Compatibility" mode
2. ✅ Test simple scripts first
3. ✅ Check MinGW-w64 status before compiling .exe
4. ✅ Use real-time logs to monitor progress
5. ✅ Test .exe files with wine if available
6. ✅ **Verify 64-bit architecture in compilation logs**
7. ✅ Test on actual Windows 64-bit systems
**Package compatibility:**
1. ✅ Pure Python packages work best
2. ⚠️ Avoid packages with C extensions when cross-compiling
3. ⚠️ GUI frameworks may need special handling
4. ⚠️ Windows-specific packages won't work in cross-compilation
5. ✅ **Ensure all dependencies support 64-bit architecture**
## 🔧 Troubleshooting
**MinGW-w64 issues:**
- **Missing MinGW-w64**: Install required packages in Docker image
- **Cross-compilation fails**: Check package compatibility
- **Large .exe files**: Normal for standalone Windows executables
- **32-bit/64-bit mismatch**: Script now explicitly targets x64
- **Runtime errors**: Test with different Nuitka flags
- **Wine issues**: Wine testing is optional, real Windows testing preferred
## 🚀 Technical Details
**MinGW-w64 process:**
1. Nuitka converts Python to C code
2. MinGW-w64 cross-compiles C to Windows PE format
3. **Explicitly targets x64 (64-bit) architecture**
4. Static linking reduces Windows dependencies
5. Result is a native Windows 64-bit executable
6. Optional Wine testing for basic validation
**Command structure:**
```bash
python -m nuitka \\
--mingw64 \\
--target-arch=x64 \\
--onefile \\
--windows-disable-console \\
--show-progress \\
your_script.py
```
**Key flags for 64-bit compilation:**
- `--mingw64`: Use MinGW-w64 toolchain
- `--target-arch=x64`: Explicitly target 64-bit architecture
- `--msvc=14.3`: MSVC compatibility mode
This ensures **proper 64-bit Windows compatibility**.
""")
gr.Markdown("---")
gr.Markdown("🤖 Created by Claude 3.7 Sonnet | 🚀 Powered by Nuitka + MinGW-w64 | ☁️ Proper x64 cross-compilation | 📊 Real-time logs")
if __name__ == "__main__":
# Create necessary directories on startup
ensure_dir("user_code")
ensure_dir("compiled_output")
# Check if Nuitka is available
if "nuitka" in check_dependencies():
print("WARNING: Nuitka is not installed. Please add 'nuitka' to your requirements.txt file.")
# Check MinGW-w64 status
mingw_missing = check_mingw_installation()
if mingw_missing:
print(f"WARNING: MinGW-w64 components missing: {', '.join(mingw_missing)}")
print("Windows cross-compilation may not work properly.")
app.launch()