Download exe_builder.py from JAYNESTV/apk: direct link, hf CLI and curl.
- Browser
- Download file 17 kB
-
https://huggingface.co/spaces/JAYNESTV/apk/resolve/main/exe_builder.py
- Command line
-
hf download hf://spaces/JAYNESTV/apk/exe_builder.py
-
curl -L -o exe_builder.py https://huggingface.co/spaces/JAYNESTV/apk/resolve/main/exe_builder.py
17 kB
| # 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]) | |