File size: 16,966 Bytes
007d878 934712d 007d878 934712d 007d878 934712d 007d878 934712d 007d878 934712d 007d878 934712d 007d878 934712d 007d878 934712d 007d878 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 | # exe_builder.py β Windows EXE Builder (Electron) kwa Space ya JAYNES MAX
# Inafungua tovuti (URL) kwenye dirisha la Windows. Inatoa: Installer (.exe) na/au Portable ZIP.
# Haihitaji Wine: signAndEditExecutable=false. Inahitaji intaneti kwenye Space (Node, npm, Electron, NSIS).
import os, re, json, time, shutil, tarfile, hashlib, threading, subprocess, glob, tempfile, urllib.request
NODE_VERSION = "v20.18.1"
NODE_URL = f"https://nodejs.org/dist/{NODE_VERSION}/node-{NODE_VERSION}-linux-x64.tar.gz"
NODE_HOME = "/opt/node" if os.access("/opt", os.W_OK) else "/tmp/node"
EXE_OUT_DIR = "/tmp/exe_builds"
DEFAULT_URL = "https://jaynestv-jaynestv.static.hf.space/"
os.makedirs(EXE_OUT_DIR, exist_ok=True)
_lock = threading.Lock()
MAIN_JS = r"""// Desktop (Windows) wrapper β inafungua tovuti ya app kwenye dirisha lake lenyewe.
const { app, BrowserWindow, shell, Menu } = require('electron');
const APP_URL = __APP_URL__;
const APP_NAME = __APP_NAME__;
const APP_ORIGIN = new URL(APP_URL).origin;
app.commandLine.appendSwitch('autoplay-policy', 'no-user-gesture-required');
if (!app.requestSingleInstanceLock()) { app.quit(); }
let win = null;
function offlinePage() {
const html = '<html><body style="margin:0;background:#0b0b10;color:#fff;font-family:Segoe UI,Arial,sans-serif;display:flex;align-items:center;justify-content:center;height:100vh;text-align:center">' +
'<div><h2>' + APP_NAME.replace(/[<>&]/g, '') + '</h2><p>Hakuna mtandao. Washa intaneti kisha bonyeza kitufe hapa chini.</p>' +
'<button onclick="location.href=\'' + APP_URL + '\'" style="padding:10px 22px;font-size:16px;border:0;border-radius:8px;background:#e50914;color:#fff;cursor:pointer">Jaribu tena</button></div></body></html>';
return 'data:text/html;charset=utf-8,' + encodeURIComponent(html);
}
function createWindow() {
win = new BrowserWindow({
width: 1280, height: 800, minWidth: 480, minHeight: 360,
backgroundColor: '#0b0b10', title: APP_NAME, autoHideMenuBar: true,
webPreferences: { contextIsolation: true, nodeIntegration: false, sandbox: true },
});
Menu.setApplicationMenu(null);
win.loadURL(APP_URL);
win.webContents.setWindowOpenHandler(({ url }) => { try { shell.openExternal(url); } catch (_) {} return { action: 'deny' }; });
win.webContents.on('will-navigate', (e, url) => {
if (!url.startsWith(APP_ORIGIN) && !url.startsWith('data:')) { e.preventDefault(); try { shell.openExternal(url); } catch (_) {} }
});
win.webContents.on('did-fail-load', (_e, code, _d, _u, isMain) => { if (isMain && code !== -3) win.loadURL(offlinePage()); });
win.webContents.on('before-input-event', (e, input) => {
if (input.type !== 'keyDown') return;
if (input.key === 'F11') { win.setFullScreen(!win.isFullScreen()); e.preventDefault(); }
if (input.key === 'F5') { win.webContents.reload(); e.preventDefault(); }
});
}
app.on('second-instance', () => { if (win) { if (win.isMinimized()) win.restore(); win.focus(); } });
app.whenReady().then(createWindow);
app.on('window-all-closed', () => app.quit());
"""
def human_size(n):
for u in ["B", "KB", "MB", "GB"]:
if n < 1024:
return f"{n:.1f} {u}"
n /= 1024
return f"{n:.1f} TB"
def sha256_file(path):
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(65536), b""):
h.update(chunk)
return h.hexdigest()
def clean_name(name):
n = re.sub(r"[^A-Za-z0-9 _-]", "", (name or "").strip())[:40].strip()
return n or "My App"
def slug(name):
return re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-") or "app"
def png_size(path):
"""Soma (upana, urefu) wa PNG kutoka header β bila maktaba."""
import struct
with open(path, "rb") as f:
head = f.read(24)
if len(head) < 24 or head[:8] != b"\x89PNG\r\n\x1a\n":
return None
return struct.unpack(">II", head[16:24])
def prepare_icon(src, dst):
"""Hakikisha icon ni PNG ya mraba, angalau 256x256 (electron-builder inadai hivyo).
Ndogo kuliko 256 -> inakuzwa hadi 512 (inahitaji Pillow). Returns (ok, ujumbe)."""
try:
if not (src and os.path.isfile(src) and src.lower().endswith(".png")):
return False, ""
if os.path.getsize(src) > 5 * 1024 * 1024:
return False, "icon kubwa kuliko 5MB β imerukwa"
size = png_size(src)
if not size:
return False, "faili la icon si PNG halali β imerukwa"
w, h = size
if w == h and w >= 256:
shutil.copy(src, dst)
return True, f"icon {w}x{h} imewekwa"
try:
from PIL import Image
except Exception:
return False, f"icon ni {w}x{h} (lazima iwe mraba, angalau 256x256) β imerukwa. Pakia PNG 512x512."
im = Image.open(src).convert("RGBA")
side = max(w, h, 256)
if side < 512 and max(w, h) < 256:
side = 512
canvas = Image.new("RGBA", (side, side), (0, 0, 0, 0))
scale = side / max(w, h)
nw, nh = max(1, int(w * scale)), max(1, int(h * scale))
im = im.resize((nw, nh), Image.LANCZOS)
canvas.paste(im, ((side - nw) // 2, (side - nh) // 2), im)
canvas.save(dst, "PNG")
return True, f"icon {w}x{h} imerekebishwa kuwa {side}x{side}"
except Exception as e:
return False, f"icon imeshindwa kusomwa ({e}) β imerukwa"
def write_project(dirpath, app_name, url, version, targets, icon_path=None):
"""Andika package.json + main.js (+ icon). targets: list ya 'nsis' / 'zip'."""
s = slug(app_name)
pkg = {
"name": s, "productName": app_name, "version": version,
"description": app_name, "author": app_name, "main": "main.js",
"scripts": {"start": "electron ."},
"devDependencies": {"electron": "^33.4.11", "electron-builder": "^25.1.8"},
"build": {
"appId": f"com.{s.replace('-', '')}.desktop",
"productName": app_name,
"files": ["main.js", "package.json"],
"directories": {"buildResources": "build", "output": "dist"},
"win": {"target": list(targets), "signAndEditExecutable": False},
"nsis": {"oneClick": True, "perMachine": False,
"createDesktopShortcut": True, "createStartMenuShortcut": True},
"artifactName": "${productName}-${version}-${os}.${ext}",
},
}
with open(os.path.join(dirpath, "package.json"), "w", encoding="utf-8") as f:
json.dump(pkg, f, indent=2, ensure_ascii=False)
main = MAIN_JS.replace("__APP_URL__", json.dumps(url)).replace("__APP_NAME__", json.dumps(app_name))
with open(os.path.join(dirpath, "main.js"), "w", encoding="utf-8") as f:
f.write(main)
os.makedirs(os.path.join(dirpath, "build"), exist_ok=True)
if icon_path:
return prepare_icon(icon_path, os.path.join(dirpath, "build", "icon.png"))
return False, ""
def node_ready():
return os.path.exists(f"{NODE_HOME}/bin/node") and os.path.exists(f"{NODE_HOME}/bin/npm")
def install_node():
tgz = "/tmp/node.tar.gz"
urllib.request.urlretrieve(NODE_URL, tgz)
os.makedirs(NODE_HOME, exist_ok=True)
with tarfile.open(tgz) as t:
for m in t.getmembers():
parts = m.name.split("/", 1)
if len(parts) < 2 or not parts[1]:
continue
m.name = parts[1]
try:
t.extract(m, NODE_HOME, filter="tar")
except TypeError:
t.extract(m, NODE_HOME)
try:
os.remove(tgz)
except Exception:
pass
def stream(cmd, cwd, env, timeout):
"""Endesha amri na toa mistari LIVE. Yield ('line', text) kisha ('exit', code)."""
proc = subprocess.Popen(cmd, shell=True, cwd=cwd, env=env, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, text=True, bufsize=1)
timer = threading.Timer(timeout, proc.kill)
timer.start()
try:
for line in proc.stdout:
yield ("line", line.rstrip())
proc.wait()
finally:
timer.cancel()
yield ("exit", proc.returncode)
def build_exe(app_name, url, version, target_choice, icon_file):
logs = []
summary = {"Node": "β³", "Project": "β³", "npm": "β³", "Build": "β³", "EXE": "β³"}
def render(tail=None):
head = " ".join(f"{v} {k}" for k, v in summary.items()) + "\n" + ("β" * 60) + "\n" + "\n".join(logs)
return head + (f"\n\n[Live β mistari ya mwisho]\n{tail}" if tail else "")
app_name = clean_name(app_name)
url = (url or "").strip()
version = (version or "1.0.0").strip()
if not re.match(r"^https?://[^\s]+$", url):
logs.append("β URL si sahihi. Lazima ianze na https:// (mf. https://jaynestv-jaynestv.static.hf.space/)")
yield render(), None
return
if not re.match(r"^\d+\.\d+\.\d+$", version):
logs.append("β Version lazima iwe kama 1.0.0")
yield render(), None
return
targets = {"Installer (.exe)": ["nsis"], "Portable ZIP": ["zip"]}.get(target_choice, ["nsis", "zip"])
if not _lock.acquire(blocking=False):
logs.append("β³ Build nyingine ya EXE inaendelea. Subiri imalize kisha ujaribu tena.")
yield render(), None
return
try:
logs.append(f"π₯οΈ EXE Builder β {app_name}")
logs.append(f" URL : {url}")
logs.append(f" Version : {version}")
logs.append(f" Targets : {', '.join(targets)}")
logs.append("β" * 60)
yield render(), None
# 1) Node.js
try:
if not node_ready():
logs.append(f"β¬οΈ Inapakua Node.js {NODE_VERSION} (mara ya kwanza tu)...")
yield render(), None
install_node()
if not node_ready():
raise RuntimeError("Node haikuinstall")
summary["Node"] = "β
"
logs.append("β
Node.js tayari.")
except Exception as e:
summary["Node"] = "β"
logs.append(f"β Node.js imeshindwa: {e}")
yield render(), None
return
yield render(), None
# 2) Project
build_id = hashlib.md5(f"{app_name}{url}{time.time()}".encode()).hexdigest()[:8]
work = os.path.join(tempfile.gettempdir(), f"exeproj_{build_id}")
os.makedirs(work, exist_ok=True)
icon_path = getattr(icon_file, "name", icon_file) if icon_file else None
try:
has_icon, icon_note = write_project(work, app_name, url, version, targets, icon_path)
summary["Project"] = "β
"
logs.append(f"π Project imeandikwa ({work})")
logs.append(" πΌοΈ " + (icon_note if icon_note else "icon ya kawaida (hukupakia icon)"))
except Exception as e:
summary["Project"] = "β"
logs.append(f"β Project imeshindwa: {e}")
yield render(), None
return
yield render(), None
env = dict(os.environ)
env["PATH"] = f"{NODE_HOME}/bin:" + env.get("PATH", "")
env["HOME"] = env.get("HOME") or "/tmp"
env["npm_config_cache"] = "/tmp/npm_cache"
env["ELECTRON_CACHE"] = "/tmp/electron_cache"
env["ELECTRON_BUILDER_CACHE"] = "/tmp/eb_cache"
env["ELECTRON_SKIP_BINARY_DOWNLOAD"] = "1" # Electron ya Linux haihitajiki; builder inapakua ya Windows
env["CSC_IDENTITY_AUTO_DISCOVERY"] = "false"
env["ADBLOCK"] = "1"
def run_step(label, cmd, timeout):
lines, code, last = [], None, time.time()
logs.append(f"\nβ‘ {label}: {cmd}")
yield ("ui", render())
for kind, val in stream(cmd, work, env, timeout):
if kind == "line":
lines.append(val)
if time.time() - last > 2:
yield ("ui", render("\n".join(lines[-12:])))
last = time.time()
else:
code = val
yield ("done", (code, lines))
# 3) npm install
res = None
for kind, val in run_step("npm install", "npm install --no-audit --no-fund --loglevel=error", 900):
if kind == "ui":
yield val, None
else:
res = val
code, lines = res
if code != 0:
summary["npm"] = "β"
logs.append("\n".join(lines[-25:]))
logs.append("β npm install imeshindwa. Angalia mtandao wa Space (npmjs.org).")
yield render(), None
return
summary["npm"] = "β
"
logs.append("β
Dependencies zimewekwa.")
yield render(), None
# 4) electron-builder
cli_targets = " ".join(targets)
cmd = f"npx electron-builder --win {cli_targets} --x64 --publish never"
for kind, val in run_step("electron-builder", cmd, 1500):
if kind == "ui":
yield val, None
else:
res = val
code, lines = res
out = "\n".join(lines)
logs.append(out[-3500:] if len(out) > 3500 else out)
logs.append("β" * 60)
files = []
for pat in ("*.exe", "*.zip"):
files += [p for p in glob.glob(os.path.join(work, "dist", pat))
if "unpacked" not in p and not p.endswith(".blockmap")]
if files:
dest_dir = os.path.join(EXE_OUT_DIR, build_id)
os.makedirs(dest_dir, exist_ok=True)
final = []
for p in files:
d = os.path.join(dest_dir, os.path.basename(p))
shutil.copy(p, d)
final.append(d)
summary["Build"] = "β
" if code == 0 else "β οΈ"
summary["EXE"] = "β
"
logs.append("\nπ IMEJENGWA!" if code == 0 else "\nβ οΈ Baadhi ya targets zimeshindwa, lakini faili hizi zimejengwa:")
for d in final:
logs.append(f" π¦ {os.path.basename(d)} ({human_size(os.path.getsize(d))})")
logs.append(f" SHA-256: {sha256_file(d)}")
logs.append("\nβ
Pakua faili hapo juu. Installer: bonyeza mara mbili. ZIP: toa (extract) kisha fungua faili la .exe ndani.")
logs.append("βΉοΈ Windows inaweza kuonyesha 'Unknown publisher' (faili halijasainiwa): More info β Run anyway.")
shutil.rmtree(work, ignore_errors=True)
yield render(), final
else:
summary["Build"] = "β"
summary["EXE"] = "β"
logs.append("\nβ EXE haikupatikana. Angalia makosa hapo juu.")
low = out.lower()
if "at least 256x256" in low:
logs.append(" π‘ Icon ni ndogo. Pakia PNG ya mraba 512x512, au usipakie icon kabisa.")
if "wine" in low:
logs.append(" π‘ Build inaomba Wine. Jaribu 'Portable ZIP' pekee (haihitaji Wine).")
if "enotfound" in low or "getaddrinfo" in low or "econnreset" in low or "timeout" in low:
logs.append(" π‘ Tatizo la mtandao (GitHub/npm). Jaribu tena baada ya muda.")
if "no space" in low or "enospc" in low:
logs.append(" π‘ Diski imejaa. Restart Space kisha ujaribu tena.")
yield render(), None
finally:
_lock.release()
def render():
"""Inaweka UI ya EXE Builder ndani ya gr.Blocks iliyopo."""
import gradio as gr
with gr.Accordion("π₯οΈ WINDOWS EXE BUILDER (kutoka URL ya app)", open=False):
gr.Markdown(
"Inatengeneza **.exe** inayofungua tovuti yako kwenye dirisha la Windows. "
"Ukibadilisha tovuti, .exe inabadilika yenyewe (haihitaji kujenga upya). "
"Build ya kwanza inachukua dakika 5-10 (inapakua Node, Electron, NSIS)."
)
with gr.Row():
with gr.Column(scale=1, min_width=340):
e_name = gr.Textbox(label="App Name", value="JAYNES MAX", lines=1)
e_url = gr.Textbox(label="URL ya app", value=DEFAULT_URL, lines=1)
e_ver = gr.Textbox(label="Version", value="1.0.0", lines=1)
e_target = gr.Radio(choices=["Installer (.exe)", "Portable ZIP", "Zote mbili"],
value="Zote mbili", label="Aina ya faili")
e_icon = gr.File(label="Icon (PNG 512x512, hiari)", file_types=[".png"])
e_btn = gr.Button("β‘ BUILD EXE", variant="primary")
e_files = gr.File(label="π₯ Download EXE / ZIP", interactive=False, file_count="multiple")
with gr.Column(scale=2):
e_log = gr.Textbox(label="Build Log (live)", lines=20, max_lines=300,
placeholder="Bonyeza BUILD EXE. Maendeleo yataonekana hapa papo hapo.")
e_btn.click(fn=build_exe, inputs=[e_name, e_url, e_ver, e_target, e_icon], outputs=[e_log, e_files])
|