2Btainment commited on
Commit
3da9c98
·
verified ·
1 Parent(s): 739497f

feat(android): Capacitor Hosted Wrapper project converter (no APK on HF)

Browse files
ANDROID.md ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SpaceForge — Android (Capacitor) MVP
2
+
3
+ ## Artifact shipped
4
+
5
+ | | |
6
+ |--|--|
7
+ | **Type** | Capacitor 6 **Android project ZIP** |
8
+ | **Mode** | **Hosted Wrapper** (Hybrid runtime — WebView loads live Space URL) |
9
+ | **APK on HF?** | **No** — never claimed. Build locally. |
10
+ | **Converter** | `backend/app/converters/mobile/android.py` |
11
+
12
+ ## Compatibility badges (UI)
13
+
14
+ - ✓ **project** — complete Capacitor + Gradle scaffold in the zip
15
+ - ⚠ **APK not built in HF** — `cpu-basic` has no Android SDK / realistic Gradle CI
16
+ - ✗ **GPU local impossible** — when Space needs GPU; inference stays on Hugging Face
17
+
18
+ ## What the user installs
19
+
20
+ 1. In SpaceForge UI: Analyze Space → select **Android (Capacitor)** → Build → Download zip.
21
+ 2. Unzip → `npm install` → `npx cap sync android`.
22
+ 3. **Android Studio**: open `android/` → Run ▶ / Build APK
23
+ **or** `./scripts/build-android.sh` (needs `ANDROID_HOME`, JDK 17, Node 18+).
24
+ 4. Install the **locally built** debug APK on a device/emulator.
25
+
26
+ ## Labeling rules
27
+
28
+ - Never call the HF download a “Local APK”.
29
+ - Correct: “Hosted Wrapper project zip” / “Hybrid WebView shell”.
30
+ - APK only after the user (or a real CI with Android SDK) produces `.apk`.
31
+
32
+ ## Layout inside zip
33
+
34
+ ```
35
+ {name}-android/
36
+ package.json
37
+ capacitor.config.json # server.url → embed Space
38
+ www/ # iframe fallback shell + bridge
39
+ android/ # Gradle app + MainActivity (BridgeActivity)
40
+ scripts/build-android.sh
41
+ README.md
42
+ ANDROID.md
43
+ spaceforge.json # binary_included/apk_included: false
44
+ ```
README.md CHANGED
@@ -29,8 +29,11 @@ Paste a Hugging Face Space URL → analyze runtime → choose packaging targets
29
  - Firefox Extension (.xpi) — Hybrid
30
  - Chromium Extension MV3 (zip) — Hybrid
31
  - Tauri project generator (zip) — Local **project** (no binary claimed on HF)
 
32
 
33
- Stubs (clear message): Linux AppImage, Windows portable, Android — not buildable inside HF CPU.
 
 
34
 
35
  ## Privacy
36
 
 
29
  - Firefox Extension (.xpi) — Hybrid
30
  - Chromium Extension MV3 (zip) — Hybrid
31
  - Tauri project generator (zip) — Local **project** (no binary claimed on HF)
32
+ - **Android Capacitor** (zip) — **Hosted Wrapper** project (APK **not** built on HF; build via Android Studio / `./scripts/build-android.sh`)
33
 
34
+ Stubs (clear message): Linux AppImage, Windows portable — binaries not buildable inside HF CPU.
35
+
36
+ See `ANDROID.md` for Android install steps and labeling.
37
 
38
  ## Privacy
39
 
README.space.md CHANGED
@@ -29,8 +29,11 @@ Paste a Hugging Face Space URL → analyze runtime → choose packaging targets
29
  - Firefox Extension (.xpi) — Hybrid
30
  - Chromium Extension MV3 (zip) — Hybrid
31
  - Tauri project generator (zip) — Local **project** (no binary claimed on HF)
 
32
 
33
- Stubs (clear message): Linux AppImage, Windows portable, Android — not buildable inside HF CPU.
 
 
34
 
35
  ## Privacy
36
 
 
29
  - Firefox Extension (.xpi) — Hybrid
30
  - Chromium Extension MV3 (zip) — Hybrid
31
  - Tauri project generator (zip) — Local **project** (no binary claimed on HF)
32
+ - **Android Capacitor** (zip) — **Hosted Wrapper** project (APK **not** built on HF; build via Android Studio / `./scripts/build-android.sh`)
33
 
34
+ Stubs (clear message): Linux AppImage, Windows portable — binaries not buildable inside HF CPU.
35
+
36
+ See `ANDROID.md` for Android install steps and labeling.
37
 
38
  ## Privacy
39
 
README_HF.md CHANGED
@@ -29,8 +29,11 @@ Paste a Hugging Face Space URL → analyze runtime → choose packaging targets
29
  - Firefox Extension (.xpi) — Hybrid
30
  - Chromium Extension MV3 (zip) — Hybrid
31
  - Tauri project generator (zip) — Local **project** (no binary claimed on HF)
 
32
 
33
- Stubs (clear message): Linux AppImage, Windows portable, Android — not buildable inside HF CPU.
 
 
34
 
35
  ## Privacy
36
 
 
29
  - Firefox Extension (.xpi) — Hybrid
30
  - Chromium Extension MV3 (zip) — Hybrid
31
  - Tauri project generator (zip) — Local **project** (no binary claimed on HF)
32
+ - **Android Capacitor** (zip) — **Hosted Wrapper** project (APK **not** built on HF; build via Android Studio / `./scripts/build-android.sh`)
33
 
34
+ Stubs (clear message): Linux AppImage, Windows portable — binaries not buildable inside HF CPU.
35
+
36
+ See `ANDROID.md` for Android install steps and labeling.
37
 
38
  ## Privacy
39
 
RESULT.md CHANGED
@@ -7,13 +7,13 @@
7
  | **App domain** | https://2btainment-spaceforge.hf.space |
8
  | **Visibility** | **private** (owner: 2Btainment / Pro) |
9
  | **SDK / HW** | Docker · `cpu-basic` |
10
- | **Commit** | `48a7b171cebe7200c52a8d891dade4f0762b408b` |
11
- | **Runtime** | **RUNNING** (verified 2026-10-01 ~13:18 CEST / Europe/Berlin; UI crash fixed) |
12
 
13
  Auth note: private Space — call API/UI with a logged-in HF session or `Authorization: Bearer …` (never log tokens; docs use `[ERSATZ_KEY]`).
14
 
15
  ## What works (MVP)
16
- Live E2E against `gradio/hello_world`:
17
 
18
  | Target | Mode | Artifact | Status |
19
  |--------|------|----------|--------|
@@ -22,33 +22,40 @@ Live E2E against `gradio/hello_world`:
22
  | Firefox Extension | **Hybrid** | `.xpi` (+ zip twin in build dir) | ✅ downloadable |
23
  | Chromium Extension MV3 | **Hybrid** | `.zip` | ✅ downloadable |
24
  | Tauri | **Local** (project) | `*-tauri-project.zip` | ✅ project + build scripts; **no binary claimed** |
 
25
  | Linux AppImage | Local stub | — | ✅ clear “project-only / not in HF env” |
26
  | Windows Portable | Local stub | — | ✅ same |
27
- | Android | Local stub | — | ✅ same |
28
 
29
  Also:
30
- - `POST /api/analyze` — public Spaces without token; private with user token
31
- - Runtime/SDK/hardware surfaced; GPU / unknown SDK warnings
32
- - Modes never mislabel Hosted Wrapper / Hybrid as Local
33
  - Zip-slip protection, path checks, download size limit, TTL build dirs
34
- - Frontend (EN UI, i18n-ready via `frontend/src/i18n`) served by FastAPI static
35
- - **25/25** pytest passed locally
 
 
 
 
 
 
 
 
36
 
37
  ## Known limits
38
- - AppImage / Windows / Android **binaries** are not produced inside HF CPU — stubs + Tauri project path only.
 
39
  - Tauri zip is a **generator output**; user builds binaries locally (Rust + Node).
40
- - Hybrid/PWA/extensions embed the **live** Space URL (network required for Space content).
41
  - Firefox `.xpi` is **unsigned** (temporary install / self-sign for AMO).
42
  - Private Space: visitors need access; subdomain returns Hub 404 HTML without auth.
43
  - Build artifacts TTL ~1h under `/tmp` (or `/data/builds` if volume present).
44
  - No privileged Docker / no untrusted code exec in main process.
45
 
46
  ## Layout
47
- See `SPEC.md`. Key paths: `backend/app/`, `frontend/`, `templates/`, `Dockerfile`, `README.md` (Space card frontmatter).
48
 
49
  ## Tests covered
50
- invalid URL, missing space, public gradio, static SDK, external APIs flag, GPU warning, unknown SDK, firefox/widget/pwa/tauri generators, path traversal / zip-slip, large download → 413, stub messages, API health/build/download/delete.
51
-
52
 
53
  ## UI fix (2026-10-01)
54
  See `UI-FIX.md` — React crashed rendering `hardware` object; normalized to string.
 
7
  | **App domain** | https://2btainment-spaceforge.hf.space |
8
  | **Visibility** | **private** (owner: 2Btainment / Pro) |
9
  | **SDK / HW** | Docker · `cpu-basic` |
10
+ | **Commit** | _(set after HF push)_ |
11
+ | **Runtime** | verify after deploy |
12
 
13
  Auth note: private Space — call API/UI with a logged-in HF session or `Authorization: Bearer …` (never log tokens; docs use `[ERSATZ_KEY]`).
14
 
15
  ## What works (MVP)
16
+ Live E2E against `gradio/hello_world` (prior) + Android converter:
17
 
18
  | Target | Mode | Artifact | Status |
19
  |--------|------|----------|--------|
 
22
  | Firefox Extension | **Hybrid** | `.xpi` (+ zip twin in build dir) | ✅ downloadable |
23
  | Chromium Extension MV3 | **Hybrid** | `.zip` | ✅ downloadable |
24
  | Tauri | **Local** (project) | `*-tauri-project.zip` | ✅ project + build scripts; **no binary claimed** |
25
+ | **Android (Capacitor)** | **Hosted Wrapper** | `*-android-capacitor-project.zip` | ✅ **full project** + `scripts/build-android.sh` + README; **APK not built on HF** |
26
  | Linux AppImage | Local stub | — | ✅ clear “project-only / not in HF env” |
27
  | Windows Portable | Local stub | — | ✅ same |
 
28
 
29
  Also:
30
+ - `POST /api/analyze` — Android selectable with compat chips: ✓ project / ⚠ APK not built in HF / ✗ GPU local impossible
31
+ - Modes never mislabel Hosted Wrapper as Local APK
 
32
  - Zip-slip protection, path checks, download size limit, TTL build dirs
33
+ - Frontend (EN UI, i18n-ready) served by FastAPI static
34
+ - **29/29** pytest passed locally
35
+
36
+ ## Android install (user)
37
+ 1. Download Capacitor project zip from SpaceForge.
38
+ 2. `npm install && npx cap sync android`
39
+ 3. Open `android/` in **Android Studio** (or `./scripts/build-android.sh` with SDK + JDK 17).
40
+ 4. Install the **locally built** debug APK.
41
+
42
+ See `ANDROID.md`.
43
 
44
  ## Known limits
45
+ - AppImage / Windows **binaries** are not produced inside HF CPU — stubs + Tauri project path only.
46
+ - Android **APK** is not produced on HF — project zip only (documented).
47
  - Tauri zip is a **generator output**; user builds binaries locally (Rust + Node).
48
+ - Hybrid/PWA/extensions/Android embed the **live** Space URL (network required).
49
  - Firefox `.xpi` is **unsigned** (temporary install / self-sign for AMO).
50
  - Private Space: visitors need access; subdomain returns Hub 404 HTML without auth.
51
  - Build artifacts TTL ~1h under `/tmp` (or `/data/builds` if volume present).
52
  - No privileged Docker / no untrusted code exec in main process.
53
 
54
  ## Layout
55
+ See `SPEC.md`. Android converter: `backend/app/converters/mobile/android.py`.
56
 
57
  ## Tests covered
58
+ invalid URL, missing space, public gradio, static SDK, external APIs flag, GPU warning, unknown SDK, firefox/widget/pwa/tauri/**android** generators, path traversal / zip-slip, large download → 413, stub messages, Android compat badges, API health/build/download/delete.
 
59
 
60
  ## UI fix (2026-10-01)
61
  See `UI-FIX.md` — React crashed rendering `hardware` object; normalized to string.
SPEC.md CHANGED
@@ -15,7 +15,7 @@ build downloadable artifacts. Clear distinction: **Local** / **Hybrid** / **Host
15
  |------|---------|---------|
16
  | **Local** | Runs offline / as installed app (or generated project you build locally) | Tauri project zip, AppImage/Windows stubs (project-only in HF) |
17
  | **Hybrid** | Local shell + embedded remote Space (iframe / API proxy) | PWA, browser extensions, HTML widget |
18
- | **Hosted Wrapper** | Thin client that always needs the live Space URL | Same hybrid targets when marked wrapper-only |
19
 
20
  Extensions / PWA / HTML widget are **Hybrid** (or Hosted Wrapper if they only iframe).
21
  Tauri generator is **Local project** — we ship source + scripts, **not** a claimed binary unless built.
@@ -29,8 +29,9 @@ Tauri generator is **Local project** — we ship source + scripts, **not** a cla
29
  - `DELETE /api/build/{id}` → cleanup
30
 
31
  ## Converters (`Converter` interface)
32
- `html_widget`, `pwa`, `firefox_ext`, `chromium_ext`, `tauri` — full MVP.
33
- Stubs: `linux_appimage`, `windows_portable`, `android` → clear "project-only / not in HF env".
 
34
 
35
  ## Security
36
  - Builds under `/tmp/spaceforge/{id}` or `/data/builds/{id}` with TTL cleanup
@@ -62,6 +63,7 @@ spaceforge/
62
  │ │ │ ├── firefox_ext.py
63
  │ │ │ ├── chromium_ext.py
64
  │ │ │ ├── tauri.py
 
65
  │ │ │ └── stubs.py
66
  │ │ ├── security/zipsafe.py
67
  │ │ └── services/builds.py
 
15
  |------|---------|---------|
16
  | **Local** | Runs offline / as installed app (or generated project you build locally) | Tauri project zip, AppImage/Windows stubs (project-only in HF) |
17
  | **Hybrid** | Local shell + embedded remote Space (iframe / API proxy) | PWA, browser extensions, HTML widget |
18
+ | **Hosted Wrapper** | Thin client that always needs the live Space URL | **Android Capacitor** project zip, wrapper-only shells |
19
 
20
  Extensions / PWA / HTML widget are **Hybrid** (or Hosted Wrapper if they only iframe).
21
  Tauri generator is **Local project** — we ship source + scripts, **not** a claimed binary unless built.
 
29
  - `DELETE /api/build/{id}` → cleanup
30
 
31
  ## Converters (`Converter` interface)
32
+ `html_widget`, `pwa`, `firefox_ext`, `chromium_ext`, `tauri`, **`android` (Capacitor project)** — full MVP.
33
+ Stubs: `linux_appimage`, `windows_portable` → clear "project-only / not in HF env".
34
+ Android ships **project zip + build script** (Hosted Wrapper) — **never** claims Local APK on HF.
35
 
36
  ## Security
37
  - Builds under `/tmp/spaceforge/{id}` or `/data/builds/{id}` with TTL cleanup
 
63
  │ │ │ ├── firefox_ext.py
64
  │ │ │ ├── chromium_ext.py
65
  │ │ │ ├── tauri.py
66
+ │ │ │ ├── mobile/android.py
67
  │ │ │ └── stubs.py
68
  │ │ ├── security/zipsafe.py
69
  │ │ └── services/builds.py
backend/app/converters/mobile/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ """Mobile packaging converters (Android Capacitor, etc.)."""
2
+ from backend.app.converters.mobile.android import AndroidConverter
3
+
4
+ __all__ = ["AndroidConverter"]
backend/app/converters/mobile/android.py ADDED
@@ -0,0 +1,865 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Android Capacitor converter — Hosted Wrapper / Hybrid project zip (no APK on HF).
2
+
3
+ Generates a complete, buildable Capacitor Android project that wraps the live
4
+ Hugging Face Space URL in a WebView. APK is NOT produced inside HF Spaces CPU;
5
+ users build locally with Android Studio or ./scripts/build-android.sh.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import re
11
+ import zipfile
12
+ from pathlib import Path
13
+
14
+ from backend.app.converters.base import Artifact, BuildContext, Converter, ConverterResult
15
+ from backend.app.security.zipsafe import safe_add_tree
16
+
17
+
18
+ def _slug(s: str) -> str:
19
+ out = "".join(c if c.isalnum() or c in "-_" else "-" for c in s)[:48].strip("-")
20
+ return out or "spaceforge-app"
21
+
22
+
23
+ def _java_package(slug: str) -> str:
24
+ """Safe Java package segment from slug."""
25
+ parts = re.sub(r"[^a-zA-Z0-9]+", ".", slug.lower()).strip(".").split(".")
26
+ cleaned = []
27
+ for p in parts:
28
+ if not p:
29
+ continue
30
+ if p[0].isdigit():
31
+ p = "a" + p
32
+ cleaned.append(p)
33
+ return cleaned[0] if cleaned else "app"
34
+
35
+
36
+ def _e(s: str) -> str:
37
+ return (
38
+ str(s)
39
+ .replace("&", "&")
40
+ .replace("<", "&lt;")
41
+ .replace(">", "&gt;")
42
+ .replace('"', "&quot;")
43
+ )
44
+
45
+
46
+ def _app_id(slug: str) -> str:
47
+ seg = _java_package(slug.replace("-", ""))
48
+ return f"com.spaceforge.{seg}"
49
+
50
+
51
+ class AndroidConverter(Converter):
52
+ """Capacitor Android project generator.
53
+
54
+ Mode is **hosted_wrapper** (WebView always needs the live Space URL).
55
+ Artifact is a **project zip** — never claim Local APK unless an APK file
56
+ is actually produced (HF CPU does not ship Android SDK / Gradle builds).
57
+ """
58
+
59
+ id = "android"
60
+ label = "Android (Capacitor)"
61
+ mode = "hosted_wrapper"
62
+ available = True
63
+ stub = False
64
+
65
+ async def convert(self, ctx: BuildContext) -> ConverterResult:
66
+ info = ctx.space_info
67
+ name = _slug(info["name"])
68
+ app_id = _app_id(name)
69
+ pkg_path = app_id.replace(".", "/")
70
+ title = info.get("title") or info["repo_id"]
71
+ embed = info.get("embed_url") or ""
72
+ space_url = info.get("space_url") or ""
73
+ needs_gpu = bool(info.get("needs_gpu"))
74
+ hybrid_notes = []
75
+ if needs_gpu:
76
+ hybrid_notes.append(
77
+ "Space uses GPU on Hugging Face — local device cannot replicate GPU; "
78
+ "inference stays on the hosted Space (Hosted Wrapper)."
79
+ )
80
+ if info.get("has_external_apis"):
81
+ hybrid_notes.append("Space may call external APIs — network required at runtime.")
82
+ if info.get("private"):
83
+ hybrid_notes.append(
84
+ "Private Space: WebView may need cookies / user login inside the app."
85
+ )
86
+ hybrid_notes.append(
87
+ f"SDK={info.get('sdk', 'unknown')} — Capacitor WebView loads {embed}."
88
+ )
89
+
90
+ out_dir = ctx.work_dir / "android_project" / f"{name}-android"
91
+ out_dir.mkdir(parents=True, exist_ok=True)
92
+ ctx.info(
93
+ f"Generating Capacitor Android project for {info['repo_id']} "
94
+ "(mode=hosted_wrapper PROJECT ZIP — APK not built on HF)"
95
+ )
96
+
97
+ www = out_dir / "www"
98
+ www.mkdir(parents=True, exist_ok=True)
99
+ scripts = out_dir / "scripts"
100
+ scripts.mkdir(parents=True, exist_ok=True)
101
+ android_root = out_dir / "android"
102
+ app_src = android_root / "app" / "src" / "main"
103
+ java_dir = app_src / "java" / Path(pkg_path)
104
+ res = app_src / "res"
105
+ for d in (
106
+ java_dir,
107
+ res / "layout",
108
+ res / "values",
109
+ res / "xml",
110
+ res / "mipmap-hdpi",
111
+ res / "drawable",
112
+ android_root / "gradle" / "wrapper",
113
+ ):
114
+ d.mkdir(parents=True, exist_ok=True)
115
+
116
+ # --- package.json (Capacitor 6) ---
117
+ (out_dir / "package.json").write_text(
118
+ json.dumps(
119
+ {
120
+ "name": f"{name}-android",
121
+ "private": True,
122
+ "version": "0.1.0",
123
+ "description": f"SpaceForge Capacitor wrapper for {info['repo_id']}",
124
+ "scripts": {
125
+ "build:web": "node -e \"console.log('www/ already prepared')\"",
126
+ "cap:sync": "npx cap sync android",
127
+ "cap:open": "npx cap open android",
128
+ "android:sync": "npx cap sync android",
129
+ },
130
+ "dependencies": {
131
+ "@capacitor/android": "^6.1.2",
132
+ "@capacitor/core": "^6.1.2",
133
+ "@capacitor/app": "^6.0.1",
134
+ "@capacitor/status-bar": "^6.0.1",
135
+ },
136
+ "devDependencies": {
137
+ "@capacitor/cli": "^6.1.2",
138
+ },
139
+ },
140
+ indent=2,
141
+ )
142
+ + "\n",
143
+ encoding="utf-8",
144
+ )
145
+
146
+ # Hosted Wrapper: Capacitor can load remote URL via server.url.
147
+ # We also ship a local www shell (Hybrid fallback / offline banner).
148
+ cap_cfg = {
149
+ "appId": app_id,
150
+ "appName": title[:40],
151
+ "webDir": "www",
152
+ "server": {
153
+ "url": embed,
154
+ "cleartext": False,
155
+ "allowNavigation": [
156
+ "*.hf.space",
157
+ "huggingface.co",
158
+ "*.huggingface.co",
159
+ "hf.co",
160
+ "*.hf.co",
161
+ ],
162
+ },
163
+ "android": {
164
+ "allowMixedContent": False,
165
+ "backgroundColor": "#0b1020",
166
+ "webContentsDebuggingEnabled": True,
167
+ },
168
+ "plugins": {
169
+ "SplashScreen": {
170
+ "launchShowDuration": 0,
171
+ }
172
+ },
173
+ }
174
+ (out_dir / "capacitor.config.json").write_text(
175
+ json.dumps(cap_cfg, indent=2) + "\n", encoding="utf-8"
176
+ )
177
+
178
+ notes_html = "".join(f"<li>{_e(n)}</li>" for n in hybrid_notes)
179
+ (www / "index.html").write_text(
180
+ f"""<!DOCTYPE html>
181
+ <html lang="en">
182
+ <head>
183
+ <meta charset="UTF-8"/>
184
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover"/>
185
+ <meta name="color-scheme" content="dark"/>
186
+ <title>{_e(title)}</title>
187
+ <style>
188
+ html,body{{margin:0;height:100%;background:#0b1020;color:#e8eefc;font:14px system-ui,sans-serif}}
189
+ .banner{{position:fixed;top:0;left:0;right:0;z-index:3;padding:8px 12px;
190
+ background:#121a33;display:flex;flex-wrap:wrap;gap:8px;align-items:center;
191
+ border-bottom:1px solid #2a3a63}}
192
+ .badge{{background:#5b21b6;border-radius:999px;padding:2px 10px;font-size:11px;font-weight:700;
193
+ letter-spacing:.04em;text-transform:uppercase}}
194
+ .warn{{background:#854d0e;color:#fef3c7}}
195
+ iframe,.frame{{position:fixed;top:48px;left:0;right:0;bottom:0;width:100%;height:calc(100% - 48px);
196
+ border:0;background:#0b1020}}
197
+ .fallback{{padding:1.25rem;max-width:520px;margin:4rem auto}}
198
+ a{{color:#6ea8ff}}
199
+ ul{{color:#9bb0d4}}
200
+ </style>
201
+ </head>
202
+ <body>
203
+ <div class="banner">
204
+ <strong>{_e(info.get("emoji") or "🚀")} {_e(title)}</strong>
205
+ <span class="badge">Hosted Wrapper</span>
206
+ <span class="badge warn">Hybrid runtime</span>
207
+ <span style="opacity:.7;font-size:12px">SpaceForge · not a Local APK offline build</span>
208
+ </div>
209
+ <iframe class="frame" title="HF Space"
210
+ src="{_e(embed)}"
211
+ allow="camera; microphone; clipboard-write; fullscreen; autoplay; geolocation"
212
+ referrerpolicy="no-referrer-when-downgrade"></iframe>
213
+ <noscript class="fallback">
214
+ <p>JavaScript required. Open the Space directly:</p>
215
+ <p><a href="{_e(embed)}">{_e(embed)}</a></p>
216
+ </noscript>
217
+ <!-- Hybrid notes (analysis) -->
218
+ <template id="spaceforge-notes"><ul>{notes_html}</ul></template>
219
+ <script src="js/spaceforge-bridge.js"></script>
220
+ </body>
221
+ </html>
222
+ """,
223
+ encoding="utf-8",
224
+ )
225
+
226
+ js_dir = www / "js"
227
+ js_dir.mkdir(exist_ok=True)
228
+ (js_dir / "spaceforge-bridge.js").write_text(
229
+ f"""/* SpaceForge Capacitor bridge — Hosted Wrapper / Hybrid */
230
+ (function () {{
231
+ window.SPACEFORGE = {{
232
+ mode: "hosted_wrapper",
233
+ artifactKind: "project-zip",
234
+ binaryIncluded: false,
235
+ space: {json.dumps(info.get("repo_id"))},
236
+ embedUrl: {json.dumps(embed)},
237
+ spaceUrl: {json.dumps(space_url)},
238
+ notes: {json.dumps(hybrid_notes)},
239
+ }};
240
+ document.documentElement.dataset.spaceforgeMode = "hosted_wrapper";
241
+ // If Capacitor injected server.url fails to load, iframe above still works.
242
+ console.info("[SpaceForge] Android Hosted Wrapper ready", window.SPACEFORGE);
243
+ }})();
244
+ """,
245
+ encoding="utf-8",
246
+ )
247
+
248
+ # --- Android Gradle project (Capacitor-compatible scaffold) ---
249
+ (android_root / "settings.gradle").write_text(
250
+ f"""include ':app'
251
+ include ':capacitor-cordova-android-plugins'
252
+ project(':capacitor-cordova-android-plugins').projectDir = new File('./capacitor-cordova-android-plugins/')
253
+
254
+ apply from: 'capacitor.settings.gradle'
255
+ """,
256
+ encoding="utf-8",
257
+ )
258
+ (android_root / "capacitor.settings.gradle").write_text(
259
+ """// Populated/refreshed by `npx cap sync android`.
260
+ // Placeholder so the project opens before the first sync.
261
+ include ':capacitor-android'
262
+ project(':capacitor-android').projectDir = new File('../node_modules/@capacitor/android/capacitor')
263
+ """,
264
+ encoding="utf-8",
265
+ )
266
+ (android_root / "build.gradle").write_text(
267
+ """buildscript {
268
+ repositories {
269
+ google()
270
+ mavenCentral()
271
+ }
272
+ dependencies {
273
+ classpath 'com.android.tools.build:gradle:8.2.1'
274
+ }
275
+ }
276
+
277
+ apply from: 'variables.gradle'
278
+
279
+ allprojects {
280
+ repositories {
281
+ google()
282
+ mavenCentral()
283
+ }
284
+ }
285
+
286
+ task clean(type: Delete) {
287
+ delete rootProject.buildDir
288
+ }
289
+ """,
290
+ encoding="utf-8",
291
+ )
292
+ (android_root / "variables.gradle").write_text(
293
+ """ext {
294
+ minSdkVersion = 22
295
+ compileSdkVersion = 34
296
+ targetSdkVersion = 34
297
+ androidxActivityVersion = '1.8.0'
298
+ androidxAppCompatVersion = '1.6.1'
299
+ androidxCoordinatorLayoutVersion = '1.2.0'
300
+ androidxCoreVersion = '1.12.0'
301
+ androidxFragmentVersion = '1.6.2'
302
+ coreSplashScreenVersion = '1.0.1'
303
+ androidxWebkitVersion = '1.9.0'
304
+ junitVersion = '4.13.2'
305
+ androidxJunitVersion = '1.1.5'
306
+ androidxEspressoCoreVersion = '3.5.1'
307
+ cordovaAndroidVersion = '10.1.1'
308
+ }
309
+ """,
310
+ encoding="utf-8",
311
+ )
312
+ (android_root / "gradle.properties").write_text(
313
+ """org.gradle.jvmargs=-Xmx1536m
314
+ android.useAndroidX=true
315
+ android.enableJetifier=true
316
+ """,
317
+ encoding="utf-8",
318
+ )
319
+ (android_root / "gradle" / "wrapper" / "gradle-wrapper.properties").write_text(
320
+ """distributionBase=GRADLE_USER_HOME
321
+ distributionPath=wrapper/dists
322
+ distributionUrl=https\\://services.gradle.org/distributions/gradle-8.2.1-all.zip
323
+ networkTimeout=10000
324
+ validateDistributionUrl=true
325
+ zipStoreBase=GRADLE_USER_HOME
326
+ zipStorePath=wrapper/dists
327
+ """,
328
+ encoding="utf-8",
329
+ )
330
+
331
+ # Minimal cordova plugins stub so settings.gradle include does not break before sync
332
+ cordova_stub = android_root / "capacitor-cordova-android-plugins"
333
+ cordova_stub.mkdir(exist_ok=True)
334
+ (cordova_stub / "build.gradle").write_text(
335
+ """ext {
336
+ androidxAppCompatVersion = project.hasProperty('androidxAppCompatVersion') ? rootProject.ext.androidxAppCompatVersion : '1.6.1'
337
+ }
338
+ buildscript {
339
+ repositories {
340
+ google()
341
+ mavenCentral()
342
+ }
343
+ dependencies {
344
+ classpath 'com.android.tools.build:gradle:8.2.1'
345
+ }
346
+ }
347
+ apply plugin: 'com.android.library'
348
+ android {
349
+ namespace "capacitor.cordova.android.plugins"
350
+ compileSdk project.hasProperty('compileSdkVersion') ? rootProject.ext.compileSdkVersion : 34
351
+ defaultConfig {
352
+ minSdkVersion project.hasProperty('minSdkVersion') ? rootProject.ext.minSdkVersion : 22
353
+ targetSdkVersion project.hasProperty('targetSdkVersion') ? rootProject.ext.targetSdkVersion : 34
354
+ versionCode 1
355
+ versionName "1.0"
356
+ }
357
+ lintOptions {
358
+ abortOnError false
359
+ }
360
+ compileOptions {
361
+ sourceCompatibility JavaVersion.VERSION_17
362
+ targetCompatibility JavaVersion.VERSION_17
363
+ }
364
+ }
365
+ repositories {
366
+ google()
367
+ mavenCentral()
368
+ }
369
+ dependencies {
370
+ implementation fileTree(dir: 'src/main/libs', include: ['*.jar'])
371
+ implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
372
+ }
373
+ """,
374
+ encoding="utf-8",
375
+ )
376
+ (cordova_stub / "src" / "main" / "AndroidManifest.xml").parent.mkdir(parents=True, exist_ok=True)
377
+ (cordova_stub / "src" / "main" / "AndroidManifest.xml").write_text(
378
+ '<manifest xmlns:android="http://schemas.android.com/apk/res/android"></manifest>\n',
379
+ encoding="utf-8",
380
+ )
381
+
382
+ (android_root / "app" / "build.gradle").write_text(
383
+ f"""apply plugin: 'com.android.application'
384
+
385
+ android {{
386
+ namespace "{app_id}"
387
+ compileSdk rootProject.ext.compileSdkVersion
388
+ defaultConfig {{
389
+ applicationId "{app_id}"
390
+ minSdkVersion rootProject.ext.minSdkVersion
391
+ targetSdkVersion rootProject.ext.targetSdkVersion
392
+ versionCode 1
393
+ versionName "0.1.0"
394
+ testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
395
+ aaptOptions {{
396
+ ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~'
397
+ }}
398
+ }}
399
+ buildTypes {{
400
+ release {{
401
+ minifyEnabled false
402
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
403
+ }}
404
+ debug {{
405
+ debuggable true
406
+ }}
407
+ }}
408
+ compileOptions {{
409
+ sourceCompatibility JavaVersion.VERSION_17
410
+ targetCompatibility JavaVersion.VERSION_17
411
+ }}
412
+ }}
413
+
414
+ repositories {{
415
+ flatDir {{
416
+ dirs '../capacitor-cordova-android-plugins/src/main/libs', 'libs'
417
+ }}
418
+ }}
419
+
420
+ dependencies {{
421
+ implementation fileTree(include: ['*.jar'], dir: 'libs')
422
+ implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
423
+ implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"
424
+ implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion"
425
+ implementation project(':capacitor-android')
426
+ implementation project(':capacitor-cordova-android-plugins')
427
+ testImplementation "junit:junit:$junitVersion"
428
+ androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
429
+ androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
430
+ }}
431
+
432
+ apply from: 'capacitor.build.gradle'
433
+
434
+ try {{
435
+ def servicesJSON = file('google-services.json')
436
+ if (servicesJSON.text) {{
437
+ apply plugin: 'com.google.gms.google-services'
438
+ }}
439
+ }} catch(Exception e) {{
440
+ logger.info("google-services.json not found, google-services plugin not applied.")
441
+ }}
442
+ """,
443
+ encoding="utf-8",
444
+ )
445
+ (android_root / "app" / "capacitor.build.gradle").write_text(
446
+ """// Generated / refreshed by `npx cap sync android`
447
+ android {
448
+ compileOptions {
449
+ sourceCompatibility JavaVersion.VERSION_17
450
+ targetCompatibility JavaVersion.VERSION_17
451
+ }
452
+ }
453
+
454
+ apply from: '../capacitor-cordova-android-plugins/cordova.variables.gradle'
455
+
456
+ dependencies {
457
+ }
458
+
459
+ if (hasProperty('postBuildExtras')) {
460
+ postBuildExtras()
461
+ }
462
+ """,
463
+ encoding="utf-8",
464
+ )
465
+ (android_root / "app" / "proguard-rules.pro").write_text(
466
+ "# SpaceForge Capacitor — add keep rules as needed.\n",
467
+ encoding="utf-8",
468
+ )
469
+ (cordova_stub / "cordova.variables.gradle").write_text(
470
+ "// Cordova variables placeholder (cap sync may overwrite)\n",
471
+ encoding="utf-8",
472
+ )
473
+
474
+ (app_src / "AndroidManifest.xml").write_text(
475
+ f"""<?xml version="1.0" encoding="utf-8"?>
476
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
477
+
478
+ <application
479
+ android:allowBackup="true"
480
+ android:icon="@mipmap/ic_launcher"
481
+ android:label="@string/app_name"
482
+ android:supportsRtl="true"
483
+ android:theme="@style/AppTheme"
484
+ android:usesCleartextTraffic="false">
485
+
486
+ <activity
487
+ android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode"
488
+ android:name=".MainActivity"
489
+ android:label="@string/title_activity_main"
490
+ android:theme="@style/AppTheme.NoActionBarLaunch"
491
+ android:launchMode="singleTask"
492
+ android:exported="true">
493
+
494
+ <intent-filter>
495
+ <action android:name="android.intent.action.MAIN" />
496
+ <category android:name="android.intent.category.LAUNCHER" />
497
+ </intent-filter>
498
+
499
+ </activity>
500
+
501
+ <provider
502
+ android:name="androidx.core.content.FileProvider"
503
+ android:authorities="${{applicationId}}.fileprovider"
504
+ android:exported="false"
505
+ android:grantUriPermissions="true">
506
+ <meta-data
507
+ android:name="android.support.FILE_PROVIDER_PATHS"
508
+ android:resource="@xml/file_paths" />
509
+ </provider>
510
+ </application>
511
+
512
+ <!-- Permissions -->
513
+ <uses-permission android:name="android.permission.INTERNET" />
514
+ </manifest>
515
+ """,
516
+ encoding="utf-8",
517
+ )
518
+
519
+ (java_dir / "MainActivity.java").write_text(
520
+ f"""package {app_id};
521
+
522
+ import com.getcapacitor.BridgeActivity;
523
+
524
+ /**
525
+ * SpaceForge Capacitor Hosted Wrapper.
526
+ * Loads the live Hugging Face Space (see capacitor.config.json server.url / www iframe).
527
+ * This is NOT an offline Local APK of the Space model runtime.
528
+ */
529
+ public class MainActivity extends BridgeActivity {{}}
530
+ """,
531
+ encoding="utf-8",
532
+ )
533
+
534
+ (res / "values" / "strings.xml").write_text(
535
+ f"""<?xml version="1.0" encoding="utf-8"?>
536
+ <resources>
537
+ <string name="app_name">{_e(title)[:40]}</string>
538
+ <string name="title_activity_main">{_e(title)[:40]}</string>
539
+ <string name="package_name">{app_id}</string>
540
+ <string name="custom_url_scheme">{app_id}</string>
541
+ </resources>
542
+ """,
543
+ encoding="utf-8",
544
+ )
545
+ (res / "values" / "styles.xml").write_text(
546
+ """<?xml version="1.0" encoding="utf-8"?>
547
+ <resources>
548
+ <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
549
+ <item name="colorPrimary">#6ea8ff</item>
550
+ <item name="colorPrimaryDark">#0b1020</item>
551
+ <item name="colorAccent">#8b5cf6</item>
552
+ <item name="android:background">@null</item>
553
+ </style>
554
+ <style name="AppTheme.NoActionBar" parent="Theme.AppCompat.DayNight.NoActionBar">
555
+ <item name="windowActionBar">false</item>
556
+ <item name="windowNoTitle">true</item>
557
+ <item name="android:background">@null</item>
558
+ </style>
559
+ <style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen">
560
+ <item name="android:background">@drawable/splash</item>
561
+ </style>
562
+ </resources>
563
+ """,
564
+ encoding="utf-8",
565
+ )
566
+ (res / "layout" / "activity_main.xml").write_text(
567
+ """<?xml version="1.0" encoding="utf-8"?>
568
+ <androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
569
+ xmlns:app="http://schemas.android.com/apk/res-auto"
570
+ xmlns:tools="http://schemas.android.com/tools"
571
+ android:layout_width="match_parent"
572
+ android:layout_height="match_parent"
573
+ tools:context=".MainActivity">
574
+ <WebView
575
+ android:layout_width="match_parent"
576
+ android:layout_height="match_parent" />
577
+ </androidx.coordinatorlayout.widget.CoordinatorLayout>
578
+ """,
579
+ encoding="utf-8",
580
+ )
581
+ (res / "xml" / "file_paths.xml").write_text(
582
+ """<?xml version="1.0" encoding="utf-8"?>
583
+ <paths xmlns:android="http://schemas.android.com/apk/res/android">
584
+ <external-path name="my_images" path="." />
585
+ <cache-path name="my_cache_images" path="." />
586
+ </paths>
587
+ """,
588
+ encoding="utf-8",
589
+ )
590
+ # Simple vector-as-XML splash / launcher placeholders (no binary PNG required for compile with color drawable)
591
+ (res / "drawable" / "splash.xml").write_text(
592
+ """<?xml version="1.0" encoding="utf-8"?>
593
+ <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
594
+ <solid android:color="#0b1020"/>
595
+ </shape>
596
+ """,
597
+ encoding="utf-8",
598
+ )
599
+ (res / "mipmap-hdpi" / "ic_launcher.xml").write_text(
600
+ """<?xml version="1.0" encoding="utf-8"?>
601
+ <adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
602
+ <background android:drawable="@color/ic_launcher_background"/>
603
+ <foreground android:drawable="@drawable/splash"/>
604
+ </adaptive-icon>
605
+ """,
606
+ encoding="utf-8",
607
+ )
608
+ # ic_launcher as drawable reference — also provide color + use @drawable for icon fallback
609
+ (res / "values" / "ic_launcher_background.xml").write_text(
610
+ """<?xml version="1.0" encoding="utf-8"?>
611
+ <resources>
612
+ <color name="ic_launcher_background">#0b1020</color>
613
+ </resources>
614
+ """,
615
+ encoding="utf-8",
616
+ )
617
+ # Prefer PNG-less: point icon to drawable
618
+ (app_src / "AndroidManifest.xml").write_text(
619
+ (app_src / "AndroidManifest.xml")
620
+ .read_text(encoding="utf-8")
621
+ .replace("@mipmap/ic_launcher", "@drawable/ic_launcher_fg"),
622
+ encoding="utf-8",
623
+ )
624
+ (res / "drawable" / "ic_launcher_fg.xml").write_text(
625
+ """<?xml version="1.0" encoding="utf-8"?>
626
+ <vector xmlns:android="http://schemas.android.com/apk/res/android"
627
+ android:width="108dp" android:height="108dp" android:viewportWidth="108" android:viewportHeight="108">
628
+ <path android:fillColor="#0b1020" android:pathData="M0,0h108v108h-108z"/>
629
+ <path android:fillColor="#6ea8ff" android:pathData="M30,54 L54,30 L78,54 L54,78 Z"/>
630
+ </vector>
631
+ """,
632
+ encoding="utf-8",
633
+ )
634
+
635
+ # Capacitor assets config copy (cap sync will refresh)
636
+ assets = app_src / "assets"
637
+ assets.mkdir(parents=True, exist_ok=True)
638
+ (assets / "capacitor.config.json").write_text(
639
+ json.dumps(cap_cfg, indent=2) + "\n", encoding="utf-8"
640
+ )
641
+ (assets / "capacitor.plugins.json").write_text("[]\n", encoding="utf-8")
642
+ pub = assets / "public"
643
+ pub.mkdir(exist_ok=True)
644
+ # Mirror www into assets/public for first open before sync
645
+ (pub / "index.html").write_text((www / "index.html").read_text(encoding="utf-8"), encoding="utf-8")
646
+ (pub / "js").mkdir(exist_ok=True)
647
+ (pub / "js" / "spaceforge-bridge.js").write_text(
648
+ (js_dir / "spaceforge-bridge.js").read_text(encoding="utf-8"), encoding="utf-8"
649
+ )
650
+
651
+ # --- build script ---
652
+ build_sh = scripts / "build-android.sh"
653
+ build_sh.write_text(
654
+ r'''#!/usr/bin/env bash
655
+ # SpaceForge — build debug APK locally (NOT on Hugging Face Spaces).
656
+ # Requires: Node 18+, JDK 17+, Android SDK (ANDROID_HOME), network for deps.
657
+ set -euo pipefail
658
+ ROOT="$(cd "$(dirname "$0")/.." && pwd)"
659
+ cd "$ROOT"
660
+
661
+ echo "==> SpaceForge Android build"
662
+ echo " Mode: Hosted Wrapper / Hybrid (WebView → live Space URL)"
663
+ echo " Artifact from SpaceForge HF: project zip only — APK built HERE."
664
+ echo
665
+
666
+ if ! command -v npm >/dev/null; then
667
+ echo "ERROR: npm not found. Install Node 18+."
668
+ exit 1
669
+ fi
670
+ if ! command -v java >/dev/null; then
671
+ echo "ERROR: java not found. Install JDK 17+."
672
+ exit 1
673
+ fi
674
+
675
+ npm install --no-audit --no-fund
676
+ npx cap sync android
677
+
678
+ # Bootstrap Gradle wrapper jar if missing (Android Studio also does this)
679
+ WRAPPER_JAR="android/gradle/wrapper/gradle-wrapper.jar"
680
+ if [[ ! -f "$WRAPPER_JAR" ]]; then
681
+ echo "==> gradle-wrapper.jar missing — downloading Gradle 8.2.1 distribution to generate wrapper"
682
+ if command -v gradle >/dev/null; then
683
+ (cd android && gradle wrapper --gradle-version 8.2.1)
684
+ else
685
+ echo "TIP: Open android/ in Android Studio (File → Open) and use Build → Build Bundle(s) / APK(s)."
686
+ echo " Or install Gradle and re-run this script."
687
+ echo " Project is complete; APK was NOT produced by this script yet."
688
+ exit 0
689
+ fi
690
+ fi
691
+
692
+ if [[ -z "${ANDROID_HOME:-}${ANDROID_SDK_ROOT:-}" ]]; then
693
+ echo "WARN: ANDROID_HOME / ANDROID_SDK_ROOT not set."
694
+ echo " Open android/ in Android Studio to build, or export ANDROID_HOME and re-run."
695
+ exit 0
696
+ fi
697
+
698
+ chmod +x android/gradlew 2>/dev/null || true
699
+ if [[ ! -x android/gradlew ]]; then
700
+ echo "gradlew missing — open project in Android Studio once, or install gradle wrapper."
701
+ exit 0
702
+ fi
703
+
704
+ (cd android && ./gradlew assembleDebug)
705
+
706
+ APK=$(find android/app/build/outputs/apk/debug -name '*.apk' 2>/dev/null | head -1 || true)
707
+ if [[ -n "${APK:-}" ]]; then
708
+ echo
709
+ echo "OK: Debug APK built locally at:"
710
+ echo " $APK"
711
+ echo "This APK was built on YOUR machine — SpaceForge on HF never claimed a Local APK."
712
+ else
713
+ echo "Build finished but no APK found — check Gradle output above."
714
+ exit 1
715
+ fi
716
+ ''',
717
+ encoding="utf-8",
718
+ )
719
+ try:
720
+ build_sh.chmod(0o755)
721
+ except OSError:
722
+ pass
723
+
724
+ # gradlew script (without jar — Studio / build script bootstraps)
725
+ (android_root / "gradlew").write_text(
726
+ r'''#!/bin/sh
727
+ # Gradle start-up — requires gradle-wrapper.jar (see scripts/build-android.sh)
728
+ DIR="$(cd "$(dirname "$0")" && pwd)"
729
+ exec java -jar "$DIR/gradle/wrapper/gradle-wrapper.jar" "$@"
730
+ ''',
731
+ encoding="utf-8",
732
+ )
733
+ try:
734
+ (android_root / "gradlew").chmod(0o755)
735
+ except OSError:
736
+ pass
737
+
738
+ readme = f"""# {title} — Android Capacitor (Hosted Wrapper)
739
+
740
+ Generated by **SpaceForge**.
741
+
742
+ ## What you got
743
+
744
+ | Item | Status |
745
+ |------|--------|
746
+ | Capacitor Android **project** | ✅ Complete, buildable sources in this zip |
747
+ | **APK / AAB** | ⚠️ **Not** built on Hugging Face Spaces CPU — build locally |
748
+ | Offline GPU / model Local APK | ❌ Impossible for GPU Spaces — inference stays hosted |
749
+
750
+ **Mode: Hosted Wrapper** (Hybrid runtime): the app WebView loads the live Space
751
+ (`{embed}`). This is **never** a Local offline APK of the Space backend.
752
+
753
+ ## Hybrid / analysis notes
754
+
755
+ {chr(10).join(f'- {n}' for n in hybrid_notes)}
756
+
757
+ ## Install & build (Android Studio — recommended)
758
+
759
+ 1. Install [Android Studio](https://developer.android.com/studio) (SDK 34, JDK 17).
760
+ 2. Unzip this archive.
761
+ 3. In a terminal:
762
+ ```bash
763
+ cd {name}-android
764
+ npm install
765
+ npx cap sync android
766
+ npx cap open android
767
+ ```
768
+ 4. In Android Studio: **Build → Build Bundle(s) / APK(s) → Build APK(s)**.
769
+ 5. Install the debug APK on a device/emulator (Run ▶).
770
+
771
+ ## CLI build script
772
+
773
+ ```bash
774
+ ./scripts/build-android.sh
775
+ ```
776
+
777
+ Requires `ANDROID_HOME`, JDK 17, Node 18+. If `gradle-wrapper.jar` is missing,
778
+ the script guides you to Android Studio or system Gradle.
779
+
780
+ ## Important labeling
781
+
782
+ - SpaceForge on HF ships a **project zip**, not an APK.
783
+ - Do not describe this artifact as a “Local APK” unless you built an `.apk` yourself.
784
+ - Network access to Hugging Face is required while using the app.
785
+
786
+ ## Space
787
+
788
+ - Repo: `{info['repo_id']}`
789
+ - Embed: `{embed}`
790
+ - Hub: `{space_url}`
791
+ - Application id: `{app_id}`
792
+ """
793
+ (out_dir / "README.md").write_text(readme, encoding="utf-8")
794
+ (out_dir / "ANDROID.md").write_text(
795
+ f"""# Android packaging brief
796
+
797
+ ## Artifact type
798
+ **Capacitor Android project zip** (Hosted Wrapper / Hybrid).
799
+
800
+ ## Not included
801
+ - Prebuilt `.apk` / `.aab` (HF Space `cpu-basic` has no Android SDK / Gradle CI for this MVP).
802
+
803
+ ## How the user installs
804
+ 1. Download zip from SpaceForge.
805
+ 2. `npm install && npx cap sync android`.
806
+ 3. Open `android/` in Android Studio **or** run `./scripts/build-android.sh`.
807
+ 4. Install debug APK on device.
808
+
809
+ ## Compatibility
810
+ - ✓ Project generated
811
+ - ⚠ APK not built in HF
812
+ - {'✗ GPU local impossible' if needs_gpu else '⚠ Full offline Local not claimed (hosted WebView)'}
813
+ """,
814
+ encoding="utf-8",
815
+ )
816
+
817
+ meta = {
818
+ "product": "SpaceForge",
819
+ "target": self.id,
820
+ "mode": self.mode,
821
+ "artifact_kind": "project-zip",
822
+ "binary_included": False,
823
+ "apk_included": False,
824
+ "framework": "capacitor",
825
+ "capacitor_major": 6,
826
+ "app_id": app_id,
827
+ "space": info["repo_id"],
828
+ "embed_url": embed,
829
+ "space_url": space_url,
830
+ "hybrid_notes": hybrid_notes,
831
+ "compat": {
832
+ "project": "ok",
833
+ "apk": "warn",
834
+ "gpu_local": "no" if needs_gpu else "warn",
835
+ },
836
+ "labeling": {
837
+ "never_claim": "Local APK",
838
+ "shipped_as": "Hosted Wrapper project zip",
839
+ },
840
+ }
841
+ (out_dir / "spaceforge.json").write_text(
842
+ json.dumps(meta, indent=2) + "\n", encoding="utf-8"
843
+ )
844
+
845
+ zip_path = ctx.work_dir / f"{name}-android-capacitor-project.zip"
846
+ with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
847
+ safe_add_tree(zf, out_dir.parent)
848
+ ctx.info(
849
+ f"Wrote {zip_path.name} (Capacitor Android project only — "
850
+ "APK not included; mode=hosted_wrapper)"
851
+ )
852
+ return ConverterResult(
853
+ ok=True,
854
+ project_only=True,
855
+ artifact=Artifact(
856
+ target_id=self.id,
857
+ path=zip_path,
858
+ filename=zip_path.name,
859
+ mode=self.mode,
860
+ notes=(
861
+ "Capacitor Android project zip (Hosted Wrapper). "
862
+ "APK not built on HF — use Android Studio or ./scripts/build-android.sh."
863
+ ),
864
+ ),
865
+ )
backend/app/converters/registry.py CHANGED
@@ -9,10 +9,10 @@ from backend.app.converters.pwa import PwaConverter
9
  from backend.app.converters.firefox_ext import FirefoxExtConverter
10
  from backend.app.converters.chromium_ext import ChromiumExtConverter
11
  from backend.app.converters.tauri import TauriConverter
 
12
  from backend.app.converters.stubs import (
13
  LinuxAppImageStub,
14
  WindowsPortableStub,
15
- AndroidStub,
16
  )
17
 
18
 
@@ -23,8 +23,8 @@ def get_registry() -> Dict[str, Converter]:
23
  FirefoxExtConverter(),
24
  ChromiumExtConverter(),
25
  TauriConverter(),
 
26
  LinuxAppImageStub(),
27
  WindowsPortableStub(),
28
- AndroidStub(),
29
  ]
30
  return {c.id: c for c in converters}
 
9
  from backend.app.converters.firefox_ext import FirefoxExtConverter
10
  from backend.app.converters.chromium_ext import ChromiumExtConverter
11
  from backend.app.converters.tauri import TauriConverter
12
+ from backend.app.converters.mobile.android import AndroidConverter
13
  from backend.app.converters.stubs import (
14
  LinuxAppImageStub,
15
  WindowsPortableStub,
 
16
  )
17
 
18
 
 
23
  FirefoxExtConverter(),
24
  ChromiumExtConverter(),
25
  TauriConverter(),
26
+ AndroidConverter(),
27
  LinuxAppImageStub(),
28
  WindowsPortableStub(),
 
29
  ]
30
  return {c.id: c for c in converters}
backend/app/converters/stubs.py CHANGED
@@ -27,8 +27,3 @@ class LinuxAppImageStub(_Stub):
27
  class WindowsPortableStub(_Stub):
28
  id = "windows_portable"
29
  label = "Windows Portable"
30
-
31
-
32
- class AndroidStub(_Stub):
33
- id = "android"
34
- label = "Android"
 
27
  class WindowsPortableStub(_Stub):
28
  id = "windows_portable"
29
  label = "Windows Portable"
 
 
 
 
 
backend/app/providers/huggingface.py CHANGED
@@ -235,12 +235,25 @@ def classify_compatibility(info: dict[str, Any]) -> dict[str, Any]:
235
  },
236
  {
237
  "id": "android",
238
- "label": "Android",
239
- "mode": "local",
240
- "available": False,
241
- "stub": True,
242
- "artifact": "project-only",
243
- "reason": "Android APK build requires Android SDK — not in HF env. Stub reserved for later.",
 
 
 
 
 
 
 
 
 
 
 
 
 
244
  },
245
  ]
246
 
 
235
  },
236
  {
237
  "id": "android",
238
+ "label": "Android (Capacitor)",
239
+ "mode": "hosted_wrapper",
240
+ "available": True,
241
+ "stub": False,
242
+ "artifact": "project-zip",
243
+ "reason": (
244
+ "✓ Capacitor Android project zip · "
245
+ "⚠ APK not built in HF · "
246
+ + (
247
+ "✗ GPU local impossible (Hosted Wrapper keeps inference on HF)"
248
+ if info.get("needs_gpu")
249
+ else "⚠ Hosted Wrapper WebView — not a Local offline APK"
250
+ )
251
+ ),
252
+ "compat": {
253
+ "project": "ok",
254
+ "apk": "warn",
255
+ "gpu_local": "no" if info.get("needs_gpu") else "warn",
256
+ },
257
  },
258
  ]
259
 
backend/tests/test_converters.py CHANGED
@@ -80,3 +80,47 @@ async def test_stub_appimage(tmp_path: Path):
80
  assert not r.ok
81
  assert r.project_only
82
  assert "not available" in (r.error or "").lower() or "HF" in (r.error or "")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  assert not r.ok
81
  assert r.project_only
82
  assert "not available" in (r.error or "").lower() or "HF" in (r.error or "")
83
+
84
+
85
+ @pytest.mark.asyncio
86
+ async def test_android_capacitor_project(tmp_path: Path):
87
+ from backend.app.converters.mobile.android import AndroidConverter
88
+
89
+ r = await AndroidConverter().convert(_ctx(tmp_path))
90
+ assert r.ok and r.artifact
91
+ assert r.project_only
92
+ assert r.artifact.mode == "hosted_wrapper"
93
+ assert "project" in r.artifact.filename
94
+ assert "apk" not in r.artifact.filename.lower() or "project" in r.artifact.filename
95
+ assert "APK not" in (r.artifact.notes or "") or "not built" in (r.artifact.notes or "").lower()
96
+ with zipfile.ZipFile(r.artifact.path) as zf:
97
+ names = zf.namelist()
98
+ assert any("capacitor.config.json" in n for n in names)
99
+ assert any(n.endswith("MainActivity.java") for n in names)
100
+ assert any("build-android.sh" in n for n in names)
101
+ assert any(n.endswith("ANDROID.md") for n in names)
102
+ assert any(n.endswith("AndroidManifest.xml") for n in names)
103
+ meta_name = [n for n in names if n.endswith("spaceforge.json")][0]
104
+ meta = zf.read(meta_name)
105
+ assert b'"binary_included": false' in meta or b'"binary_included":false' in meta.replace(b" ", b"")
106
+ assert b'"apk_included": false' in meta or b'"apk_included":false' in meta.replace(b" ", b"")
107
+ assert b"hosted_wrapper" in meta
108
+ assert b'"artifact_kind": "project-zip"' in meta or b"project-zip" in meta
109
+ # Never claim Local APK in labeling
110
+ assert b"Local APK" in meta # listed under never_claim
111
+ cfg = zf.read([n for n in names if n.endswith("capacitor.config.json") and "/android/" not in n and "assets" not in n][0])
112
+ assert b"hf.space" in cfg or b"server" in cfg
113
+
114
+
115
+ @pytest.mark.asyncio
116
+ async def test_android_gpu_notes(tmp_path: Path):
117
+ from backend.app.converters.mobile.android import AndroidConverter
118
+
119
+ info = dict(SAMPLE)
120
+ info["needs_gpu"] = True
121
+ ctx = BuildContext(build_id="test", work_dir=tmp_path, space_info=info)
122
+ r = await AndroidConverter().convert(ctx)
123
+ assert r.ok and r.artifact
124
+ with zipfile.ZipFile(r.artifact.path) as zf:
125
+ meta = zf.read([n for n in zf.namelist() if n.endswith("spaceforge.json")][0])
126
+ assert b'"gpu_local": "no"' in meta or b'"gpu_local":"no"' in meta.replace(b" ", b"")
backend/tests/test_provider.py CHANGED
@@ -40,8 +40,15 @@ def test_classify_gpu_and_unknown():
40
  assert any("GPU" in w for w in c["warnings"])
41
  assert c["targets"][0]["id"] == "html_widget"
42
  stubs = [t for t in c["targets"] if t.get("stub")]
43
- assert len(stubs) >= 3
44
  assert all(not t["available"] for t in stubs)
 
 
 
 
 
 
 
45
 
46
 
47
  def test_classify_static_local_full():
@@ -78,3 +85,12 @@ def test_normalize_hardware_dict():
78
  }
79
  c = classify_compatibility(info)
80
  assert c["hybrid_ok"] is True
 
 
 
 
 
 
 
 
 
 
40
  assert any("GPU" in w for w in c["warnings"])
41
  assert c["targets"][0]["id"] == "html_widget"
42
  stubs = [t for t in c["targets"] if t.get("stub")]
43
+ assert len(stubs) >= 2 # linux_appimage, windows_portable (android is real converter)
44
  assert all(not t["available"] for t in stubs)
45
+ android = next(t for t in c["targets"] if t["id"] == "android")
46
+ assert android["available"] is True
47
+ assert android["stub"] is False
48
+ assert android["mode"] == "hosted_wrapper"
49
+ assert android["compat"]["project"] == "ok"
50
+ assert android["compat"]["apk"] == "warn"
51
+ assert android["compat"]["gpu_local"] == "no" # needs_gpu True in this test
52
 
53
 
54
  def test_classify_static_local_full():
 
85
  }
86
  c = classify_compatibility(info)
87
  assert c["hybrid_ok"] is True
88
+
89
+
90
+ def test_android_compat_no_gpu():
91
+ c = classify_compatibility({"sdk": "gradio", "needs_gpu": False, "private": False})
92
+ android = next(t for t in c["targets"] if t["id"] == "android")
93
+ assert android["available"] is True
94
+ assert android["mode"] == "hosted_wrapper"
95
+ assert android["compat"]["gpu_local"] == "warn"
96
+ assert "APK not built" in android["reason"] or "project" in android["reason"].lower()
frontend/src/components/TargetPicker.tsx CHANGED
@@ -1,7 +1,16 @@
1
- import type { TargetInfo } from "../types";
2
  import { ModeBadge } from "./ModeBadge";
3
  import { t } from "../i18n";
4
 
 
 
 
 
 
 
 
 
 
5
  export function TargetPicker({
6
  targets,
7
  selected,
@@ -17,6 +26,7 @@ export function TargetPicker({
17
  {targets.map((tg) => {
18
  const disabled = !tg.available;
19
  const checked = selected.has(tg.id);
 
20
  return (
21
  <div key={tg.id} className={`target ${disabled ? "disabled" : ""}`}>
22
  <input
@@ -35,6 +45,30 @@ export function TargetPicker({
35
  {tg.label} <ModeBadge mode={tg.mode} />
36
  </label>
37
  <div className="reason">{tg.reason}</div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  {tg.stub ? <div className="reason">{m.stubNote}</div> : null}
39
  </div>
40
  <div>{disabled ? <span className="hint">{m.unavailable}</span> : null}</div>
 
1
+ import type { CompatLevel, TargetInfo } from "../types";
2
  import { ModeBadge } from "./ModeBadge";
3
  import { t } from "../i18n";
4
 
5
+ function CompatChip({ level, label }: { level: CompatLevel; label: string }) {
6
+ const icon = level === "ok" ? "✓" : level === "warn" ? "⚠" : "✗";
7
+ return (
8
+ <span className={`compat ${level}`} title={label}>
9
+ {icon} {label}
10
+ </span>
11
+ );
12
+ }
13
+
14
  export function TargetPicker({
15
  targets,
16
  selected,
 
26
  {targets.map((tg) => {
27
  const disabled = !tg.available;
28
  const checked = selected.has(tg.id);
29
+ const c = tg.compat;
30
  return (
31
  <div key={tg.id} className={`target ${disabled ? "disabled" : ""}`}>
32
  <input
 
45
  {tg.label} <ModeBadge mode={tg.mode} />
46
  </label>
47
  <div className="reason">{tg.reason}</div>
48
+ {c ? (
49
+ <div className="compat-row">
50
+ {c.project ? (
51
+ <CompatChip
52
+ level={c.project}
53
+ label={c.project === "ok" ? m.compatProjectOk : m.compatProjectNo}
54
+ />
55
+ ) : null}
56
+ {c.apk ? (
57
+ <CompatChip
58
+ level={c.apk}
59
+ label={c.apk === "ok" ? m.compatApkOk : m.compatApkWarn}
60
+ />
61
+ ) : null}
62
+ {c.gpu_local ? (
63
+ <CompatChip
64
+ level={c.gpu_local}
65
+ label={
66
+ c.gpu_local === "no" ? m.compatGpuNo : m.compatGpuWarn
67
+ }
68
+ />
69
+ ) : null}
70
+ </div>
71
+ ) : null}
72
  {tg.stub ? <div className="reason">{m.stubNote}</div> : null}
73
  </div>
74
  <div>{disabled ? <span className="hint">{m.unavailable}</span> : null}</div>
frontend/src/i18n/en.ts CHANGED
@@ -26,6 +26,12 @@ export const en = {
26
  selectTargets: "Choose packaging targets",
27
  noSecrets: "Tokens are sent only for this request and never logged.",
28
  footer: "SpaceForge MVP · 2Btainment · Artifacts expire after ~1h",
 
 
 
 
 
 
29
  } as const;
30
 
31
  export type Messages = typeof en;
 
26
  selectTargets: "Choose packaging targets",
27
  noSecrets: "Tokens are sent only for this request and never logged.",
28
  footer: "SpaceForge MVP · 2Btainment · Artifacts expire after ~1h",
29
+ compatProjectOk: "project",
30
+ compatProjectNo: "no project",
31
+ compatApkOk: "APK included",
32
+ compatApkWarn: "APK not built in HF",
33
+ compatGpuNo: "GPU local impossible",
34
+ compatGpuWarn: "not Local offline APK",
35
  } as const;
36
 
37
  export type Messages = typeof en;
frontend/src/styles.css CHANGED
@@ -132,3 +132,15 @@ pre.logs {
132
  color: #b7c7e8;
133
  }
134
  .footer { margin-top: 1.5rem; color: var(--muted); font-size: .8rem; text-align: center; }
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  color: #b7c7e8;
133
  }
134
  .footer { margin-top: 1.5rem; color: var(--muted); font-size: .8rem; text-align: center; }
135
+
136
+ .compat-row { display: flex; flex-wrap: wrap; gap: .35rem; margin-top: .4rem; }
137
+ .compat {
138
+ font-size: .7rem;
139
+ font-weight: 600;
140
+ padding: .15rem .45rem;
141
+ border-radius: 999px;
142
+ border: 1px solid var(--border);
143
+ }
144
+ .compat.ok { color: var(--ok); background: rgba(52,211,153,.12); }
145
+ .compat.warn { color: var(--warn); background: rgba(251,191,36,.12); }
146
+ .compat.no { color: var(--err); background: rgba(248,113,113,.12); }
frontend/src/types/index.ts CHANGED
@@ -1,5 +1,13 @@
1
  export type DeliveryMode = "local" | "hybrid" | "hosted_wrapper";
2
 
 
 
 
 
 
 
 
 
3
  export interface TargetInfo {
4
  id: string;
5
  label: string;
@@ -8,6 +16,7 @@ export interface TargetInfo {
8
  stub?: boolean;
9
  artifact?: string;
10
  reason?: string;
 
11
  }
12
 
13
  export interface SpaceInfo {
 
1
  export type DeliveryMode = "local" | "hybrid" | "hosted_wrapper";
2
 
3
+ export type CompatLevel = "ok" | "warn" | "no";
4
+
5
+ export interface TargetCompat {
6
+ project?: CompatLevel;
7
+ apk?: CompatLevel;
8
+ gpu_local?: CompatLevel;
9
+ }
10
+
11
  export interface TargetInfo {
12
  id: string;
13
  label: string;
 
16
  stub?: boolean;
17
  artifact?: string;
18
  reason?: string;
19
+ compat?: TargetCompat;
20
  }
21
 
22
  export interface SpaceInfo {
pytest.ini ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ [pytest]
2
+ asyncio_mode = auto
3
+ asyncio_default_fixture_loop_scope = function
4
+ testpaths = backend/tests