Spaces:
Build error
Build error
Download exe_builder.py from jumannendange/iphone-stream1: direct link, hf CLI and curl.
- Browser
- Download file 26.4 kB
-
https://huggingface.co/spaces/jumannendange/iphone-stream1/resolve/main/exe_builder.py
- Command line
-
hf download hf://spaces/jumannendange/iphone-stream1/exe_builder.py
-
curl -L -o exe_builder.py https://huggingface.co/spaces/jumannendange/iphone-stream1/resolve/main/exe_builder.py
26.4 kB
| # exe_builder.py β Windows EXE Builder (Electron) kwa Space ya JAYNES MAX | |
| # Inafungua tovuti (URL) AU source code uliyopakia (ZIP/HTML) 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, zipfile | |
| # ZeroGPU: faili hili linatumia CPU tu (Node/npm/electron-builder). Function hii ya kimya | |
| # inahakikisha "@spaces.GPU" ipo hata kama exe_builder inapakiwa peke yake; haiitwi kamwe. | |
| try: | |
| import spaces | |
| def _gpu_placeholder_exe(): | |
| return None | |
| except Exception: | |
| pass | |
| 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 os.path.join(tempfile.gettempdir(), "node") # ZeroGPU: si root | |
| 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 (URL) AU source code iliyopakiwa (folda app/). | |
| const { app, BrowserWindow, shell, Menu, protocol, net } = require('electron'); | |
| const path = require('path'); | |
| const { pathToFileURL } = require('url'); | |
| const LOCAL_ENTRY = __LOCAL_ENTRY__; // null = tumia URL; vinginevyo njia ya index ndani ya app/ | |
| const APP_URL = LOCAL_ENTRY ? 'app://local/' + encodeURI(LOCAL_ENTRY) : __APP_URL__; | |
| const APP_NAME = __APP_NAME__; | |
| const APP_ORIGIN = LOCAL_ENTRY ? 'app://local' : new URL(APP_URL).origin; | |
| if (LOCAL_ENTRY) { | |
| protocol.registerSchemesAsPrivileged([{ scheme: 'app', privileges: { standard: true, secure: true, supportFetchAPI: true, corsEnabled: true, stream: true } }]); | |
| } | |
| 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 (!LOCAL_ENTRY && 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(); } }); | |
| function registerLocal() { | |
| const root = path.join(__dirname, 'app'); | |
| protocol.handle('app', (req) => { | |
| try { | |
| let rel = decodeURIComponent(new URL(req.url).pathname); | |
| if (rel === '/' || rel === '') rel = '/' + LOCAL_ENTRY; | |
| const full = path.normalize(path.join(root, rel)); | |
| if (full !== root && !full.startsWith(root + path.sep)) return new Response('Forbidden', { status: 403 }); | |
| return net.fetch(pathToFileURL(full).toString()).catch(() => new Response('Not found', { status: 404 })); | |
| } catch (_) { return new Response('Bad request', { status: 400 }); } | |
| }); | |
| } | |
| app.whenReady().then(() => { if (LOCAL_ENTRY) registerLocal(); 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" | |
| MAX_SRC_BYTES = 300 * 1024 * 1024 | |
| MAX_SRC_FILES = 20000 | |
| def prepare_source(src, app_dir): | |
| """Weka source code (ZIP ya tovuti au faili la .html) ndani ya app_dir. | |
| Returns (entry, ujumbe) β entry ni njia ya faili la kuanzia (mf. 'index.html'). Inatupa ValueError kwa kosa.""" | |
| if not (src and os.path.isfile(src)): | |
| raise ValueError("faili la source halikupatikana") | |
| ext = os.path.splitext(src)[1].lower() | |
| os.makedirs(app_dir, exist_ok=True) | |
| if ext in (".html", ".htm"): | |
| shutil.copy(src, os.path.join(app_dir, "index.html")) | |
| return "index.html", "faili la HTML limewekwa kama index.html" | |
| if ext != ".zip": | |
| raise ValueError("source lazima iwe .zip (folda la tovuti) au faili la .html") | |
| if not zipfile.is_zipfile(src): | |
| raise ValueError("faili la ZIP si halali au limeharibika") | |
| root = os.path.realpath(app_dir) | |
| total = count = 0 | |
| with zipfile.ZipFile(src) as z: | |
| for info in z.infolist(): | |
| name = info.filename.replace("\\", "/") | |
| parts = [p for p in name.split("/") if p not in ("", ".")] | |
| if not parts or parts[0] == "__MACOSX" or parts[-1] == ".DS_Store": | |
| continue | |
| if ".." in parts or name.startswith("/") or re.match(r"^[A-Za-z]:", parts[0]): | |
| continue # njia hatari (zip-slip) β imerukwa | |
| target = os.path.realpath(os.path.join(root, *parts)) | |
| if not target.startswith(root + os.sep): | |
| continue | |
| if info.is_dir(): | |
| os.makedirs(target, exist_ok=True) | |
| continue | |
| count += 1 | |
| total += info.file_size | |
| if count > MAX_SRC_FILES: | |
| raise ValueError(f"ZIP lina mafaili mengi mno (zaidi ya {MAX_SRC_FILES})") | |
| if total > MAX_SRC_BYTES: | |
| raise ValueError(f"ZIP ni kubwa mno (zaidi ya {human_size(MAX_SRC_BYTES)} baada ya kufunguliwa)") | |
| os.makedirs(os.path.dirname(target), exist_ok=True) | |
| with z.open(info) as s_, open(target, "wb") as d_: | |
| shutil.copyfileobj(s_, d_) | |
| if count == 0: | |
| raise ValueError("ZIP ni tupu") | |
| # Kama kila kitu kiko ndani ya folda moja (mf. mysite/index.html) β leta juu | |
| for _ in range(3): | |
| items = os.listdir(app_dir) | |
| if len(items) == 1 and os.path.isdir(os.path.join(app_dir, items[0])): | |
| inner = os.path.join(app_dir, items[0]) | |
| tmp = inner + "__flat" | |
| os.rename(inner, tmp) | |
| for n in os.listdir(tmp): | |
| shutil.move(os.path.join(tmp, n), os.path.join(app_dir, n)) | |
| os.rmdir(tmp) | |
| else: | |
| break | |
| # Project ya Electron iliyokamilika (package.json + main.js) β itajengwa moja kwa moja | |
| pj = os.path.join(app_dir, "package.json") | |
| if os.path.isfile(pj): | |
| try: | |
| with open(pj, "r", encoding="utf-8") as f: | |
| pkg = json.load(f) | |
| except Exception: | |
| pkg = None | |
| if isinstance(pkg, dict): | |
| deps = {**(pkg.get("dependencies") or {}), **(pkg.get("devDependencies") or {})} | |
| if "electron" in deps: | |
| main_rel = pkg.get("main") or "index.js" | |
| if not os.path.isfile(os.path.join(app_dir, main_rel)): | |
| raise ValueError(f"project ya Electron inadai '{main_rel}' (main) lakini haipo ndani ya ZIP") | |
| return None, f"project ya Electron ({count} mafaili, {human_size(total)}) β itajengwa kama ilivyo" | |
| htmls = [] | |
| for dp, _dn, fn in os.walk(app_dir): | |
| for f in fn: | |
| if f.lower().endswith((".html", ".htm")): | |
| htmls.append(os.path.relpath(os.path.join(dp, f), app_dir).replace(os.sep, "/")) | |
| if not htmls: | |
| hint = "" | |
| if os.path.isfile(os.path.join(app_dir, "package.json")): | |
| hint = " Inaonekana ni source ghafi (package.json) β jenga kwanza (npm run build) kisha pakia ZIP ya folda la dist/build." | |
| raise ValueError("hakuna faili la .html ndani ya ZIP." + hint) | |
| pool = [h for h in htmls if os.path.basename(h).lower() == "index.html"] or htmls | |
| entry = min(pool, key=lambda h: (h.count("/"), h)) | |
| note = f"{count} mafaili ({human_size(total)}), faili la kuanzia: {entry}" | |
| try: | |
| with open(os.path.join(app_dir, entry), "r", encoding="utf-8", errors="ignore") as f: | |
| head = f.read(200000) | |
| if os.path.isfile(os.path.join(app_dir, "package.json")) and re.search(r"""src=["']/?src/[^"']+\.(jsx?|tsx?)""", head): | |
| note += " β οΈ Inaonekana ni source ambayo haijajengwa (build) β inaweza isifanye kazi." | |
| except Exception: | |
| pass | |
| return entry, note | |
| def patch_electron_project(dirpath, targets): | |
| """Rekebisha package.json ya project ya Electron iliyopakiwa ili ijengwe hapa (bila Wine, targets zilizochaguliwa).""" | |
| pj = os.path.join(dirpath, "package.json") | |
| with open(pj, "r", encoding="utf-8") as f: | |
| pkg = json.load(f) | |
| dev = pkg.setdefault("devDependencies", {}) | |
| deps = pkg.get("dependencies") or {} | |
| if "electron" in deps: # electron-builder inakataa electron kwenye dependencies | |
| dev["electron"] = deps.pop("electron") | |
| dev.setdefault("electron", "^33.4.11") | |
| dev.setdefault("electron-builder", "^25.1.8") | |
| b = pkg.setdefault("build", {}) | |
| b.setdefault("directories", {})["output"] = "dist" | |
| win = b.setdefault("win", {}) | |
| win["target"] = list(targets) | |
| win["signAndEditExecutable"] = False | |
| with open(pj, "w", encoding="utf-8") as f: | |
| json.dump(pkg, f, indent=2, ensure_ascii=False) | |
| return pkg.get("productName") or pkg.get("name") or "App" | |
| def write_project(dirpath, app_name, url, version, targets, icon_path=None, local_entry=None): | |
| """Andika package.json + main.js (+ icon). targets: list ya 'nsis' / 'zip'. | |
| local_entry: kama ipo, app inapakia source ya ndani (folda app/) badala ya URL.""" | |
| 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"] + (["app/**/*"] if local_entry else []), | |
| "asar": False if local_entry else True, | |
| "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("__LOCAL_ENTRY__", json.dumps(local_entry)) | |
| .replace("__APP_URL__", json.dumps(url or "")) | |
| .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, src_file=None): | |
| 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() | |
| src_path = getattr(src_file, "name", src_file) if src_file else None | |
| use_src = bool(src_path) | |
| if not use_src and not re.match(r"^https?://[^\s]+$", url): | |
| logs.append("β URL si sahihi. Lazima ianze na https:// (mf. https://jaynestv-jaynestv.static.hf.space/) AU pakia source code (ZIP/HTML).") | |
| 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}") | |
| if use_src: | |
| logs.append(f" Chanzo : source code ({os.path.basename(src_path)}) β inafanya kazi bila mtandao") | |
| else: | |
| 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: | |
| local_entry = None | |
| is_electron = False | |
| if use_src: | |
| app_dir = os.path.join(work, "app") | |
| local_entry, src_note = prepare_source(src_path, app_dir) | |
| logs.append(f"π Source code imewekwa: {src_note}") | |
| if local_entry is None: # project ya Electron β hamisha mafaili hadi root ya work | |
| is_electron = True | |
| tmp = os.path.join(work, "_src_tmp") | |
| os.rename(app_dir, tmp) | |
| for n in os.listdir(tmp): | |
| shutil.move(os.path.join(tmp, n), os.path.join(work, n)) | |
| os.rmdir(tmp) | |
| patch_electron_project(work, targets) | |
| if is_electron: | |
| has_icon = False | |
| icon_note = "icon ya project yenyewe" + (" (icon uliyopakia imepuuzwa)" if icon_path else "") | |
| else: | |
| has_icon, icon_note = write_project(work, app_name, "" if use_src else url, version, targets, icon_path, local_entry) | |
| 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}") | |
| shutil.rmtree(work, ignore_errors=True) | |
| 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. " | |
| "Chagua: **URL** (ukibadilisha tovuti, .exe inabadilika yenyewe) AU **pakia source code** " | |
| "(ZIP ya folda la tovuti lenye index.html, faili moja la .html, AU ZIP ya project nzima ya Electron lenye package.json + main.js) β " | |
| "tovuti za ndani zinafanya kazi bila server. Ukipakia source, URL, App Name na Version zinapuuzwa kwa project ya Electron (inatumia vyake). " | |
| "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 (haihitajiki ukipakia source code)", value=DEFAULT_URL, lines=1) | |
| e_src = gr.File(label="π Source code (ZIP ya tovuti / ZIP ya Electron project / .html, hiari)", file_types=[".zip", ".html", ".htm"]) | |
| 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, e_src], outputs=[e_log, e_files]) | |