termux-diffusion 1.6.3__tar.gz → 1.6.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. {termux_diffusion-1.6.3/termux_diffusion.egg-info → termux_diffusion-1.6.4}/PKG-INFO +508 -508
  2. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/pyproject.toml +80 -80
  3. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/setup.cfg +4 -4
  4. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/setup.py +65 -65
  5. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/termux_diffusion/__init__.py +122 -93
  6. termux_diffusion-1.6.4/termux_diffusion/__main__.py +5 -0
  7. termux_diffusion-1.6.4/termux_diffusion/_version.py +1 -0
  8. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/termux_diffusion/adapter.py +39 -39
  9. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/termux_diffusion/cli.py +285 -285
  10. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/termux_diffusion/control/__init__.py +3 -3
  11. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/termux_diffusion/control/component.py +307 -304
  12. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/termux_diffusion/control/status.py +13 -13
  13. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/termux_diffusion/core.py +713 -713
  14. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/termux_diffusion/data/bootstrap-manifest.json +15 -15
  15. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/termux_diffusion/data/release-public-keys.json +9 -9
  16. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/termux_diffusion/data/validated-vulkan-profiles.json +297 -297
  17. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/termux_diffusion/downloader.py +109 -78
  18. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/termux_diffusion/exceptions.py +110 -89
  19. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/termux_diffusion/hardware.py +694 -642
  20. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/termux_diffusion/hub.py +502 -502
  21. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/termux_diffusion/installer.py +693 -615
  22. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/termux_diffusion/locking.py +132 -132
  23. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/termux_diffusion/manifest.py +126 -126
  24. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/termux_diffusion/npu.py +265 -265
  25. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/termux_diffusion/platform.py +371 -355
  26. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/termux_diffusion/selftest.py +149 -149
  27. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4/termux_diffusion.egg-info}/PKG-INFO +508 -508
  28. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/termux_diffusion.egg-info/SOURCES.txt +1 -0
  29. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/tests/test_core.py +552 -552
  30. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/tests/test_hardware.py +164 -164
  31. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/tests/test_installer.py +100 -100
  32. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/tests/test_presets.py +128 -128
  33. termux_diffusion-1.6.3/termux_diffusion/_version.py +0 -1
  34. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/LICENSE +0 -0
  35. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/README.md +0 -0
  36. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/termux_diffusion/py.typed +0 -0
  37. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/termux_diffusion.egg-info/dependency_links.txt +0 -0
  38. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/termux_diffusion.egg-info/entry_points.txt +0 -0
  39. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/termux_diffusion.egg-info/requires.txt +0 -0
  40. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/termux_diffusion.egg-info/top_level.txt +0 -0
  41. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/tests/test_hub.py +0 -0
  42. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/tests/test_npu.py +0 -0
  43. {termux_diffusion-1.6.3 → termux_diffusion-1.6.4}/tests/test_platform.py +0 -0
@@ -1,508 +1,508 @@
1
- Metadata-Version: 2.4
2
- Name: termux-diffusion
3
- Version: 1.6.3
4
- Summary: On-device Stable Diffusion runtime utilizing device resources for Android Termux & Samsung Galaxy (Dual-Engine Python & Node.js)
5
- Home-page: https://github.com/uno-km/termux-diffusion
6
- Author: uno-km (AMEVA Foundation)
7
- Author-email: "uno-km (AMEVA Foundation)" <hosequelbo@gmail.com>
8
- License: MIT
9
- Project-URL: Homepage, https://github.com/uno-km/termux-diffusion
10
- Project-URL: Documentation, https://uno-km.github.io/termux-diffusion/
11
- Project-URL: npm Package, https://www.npmjs.com/package/termux-diffusion
12
- Project-URL: Bug Tracker, https://github.com/uno-km/termux-diffusion/issues
13
- Project-URL: Source, https://github.com/uno-km/termux-diffusion
14
- Keywords: stable-diffusion,diffusion,termux,android,samsung-galaxy,edge-ai,on-device-ai,image-generation,text-to-image,txt2img,img2img,gguf,arm64,aarch64,vulkan,vulkan-compute,spirv,adreno,mali,snapdragon,exynos,bionic-libc,taesd,vae-tiling,lora,controlnet,sdxs,sd-turbo,dreamshaper,mobile-inference,camera-roll,galaxy-s25,galaxy-s20,private-ai
15
- Classifier: Development Status :: 5 - Production/Stable
16
- Classifier: Intended Audience :: Developers
17
- Classifier: License :: OSI Approved :: MIT License
18
- Classifier: Operating System :: POSIX :: Linux
19
- Classifier: Operating System :: Android
20
- Classifier: Programming Language :: Python :: 3
21
- Classifier: Programming Language :: Python :: 3.8
22
- Classifier: Programming Language :: Python :: 3.9
23
- Classifier: Programming Language :: Python :: 3.10
24
- Classifier: Programming Language :: Python :: 3.11
25
- Classifier: Programming Language :: Python :: 3.12
26
- Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
27
- Classifier: Topic :: Multimedia :: Graphics
28
- Requires-Python: >=3.8
29
- Description-Content-Type: text/markdown
30
- License-File: LICENSE
31
- Requires-Dist: ameva-runtime>=2.0.0
32
- Requires-Dist: ameva-component-sdk<2.0,>=0.1.0
33
- Dynamic: author
34
- Dynamic: classifier
35
- Dynamic: home-page
36
- Dynamic: license-file
37
- Dynamic: requires-python
38
-
39
- # Termux-Diffusion
40
-
41
- [![PyPI](https://img.shields.io/pypi/v/termux-diffusion.svg?style=flat-square&color=0369a1)](https://pypi.org/project/termux-diffusion/)
42
- [![Python](https://img.shields.io/pypi/pyversions/termux-diffusion.svg?style=flat-square)](https://pypi.org/project/termux-diffusion/)
43
- [![npm](https://img.shields.io/npm/v/termux-diffusion.svg?style=flat-square&color=b91c1c)](https://www.npmjs.com/package/termux-diffusion)
44
- [![npm downloads](https://img.shields.io/npm/dm/termux-diffusion.svg?style=flat-square&color=b91c1c)](https://www.npmjs.com/package/termux-diffusion)
45
- [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg?style=flat-square)](https://opensource.org/licenses/MIT)
46
-
47
- > **Native On-Device Stable Diffusion Runtime for Android Termux & Samsung Galaxy via Direct Bionic libc & Vulkan Compute Acceleration.**
48
- > *Zero PRoot. Zero Virtualization. 100% Native ARMv8.2-A NEON SIMD & Hardware GPU Acceleration.*
49
-
50
- ---
51
-
52
- ## 📑 Table of Contents
53
-
54
- 1. [Overview & Key Capabilities](#1-overview--key-capabilities)
55
- 2. [Installation Guide](#2-installation-guide)
56
- 3. [Enabling Hardware GPU Acceleration (with ameva-runtime)](#3-enabling-hardware-gpu-acceleration-with-ameva-runtime)
57
- 4. [Basic Usage (CLI, Python, Node.js)](#4-basic-usage-cli-python-nodejs)
58
- 5. [Advanced Workflows](#5-advanced-workflows)
59
- 6. [Feature & Parameter Matrix](#6-feature--parameter-matrix)
60
- 7. [Production Code Examples & Self-Diagnostics](#7-production-code-examples--self-diagnostics)
61
- 8. [Real-World Outputs & Hardware Benchmarks](#8-real-world-outputs--hardware-benchmarks)
62
- 9. [GPU Interconnect Architecture & Compatibility Matrix (Adreno vs. Mali)](#9-gpu-interconnect-architecture--compatibility-matrix)
63
- 10. [Hardware Requirements & Operational Limits](#10-hardware-requirements--operational-limits)
64
- 11. [24/7 Unattended Background Execution Guide (Termux -> Android -> ADB)](#11-247-unattended-background-execution-guide)
65
- 12. [License & Permissible Use](#12-license--permissible-use)
66
- 13. [Keywords & Discoverability Index](#13-keywords--discoverability-index)
67
-
68
- ---
69
-
70
- ## 1. Overview & Key Capabilities
71
-
72
- `termux-diffusion` is a production-grade, on-device diffusion inference engine engineered specifically for Android smartphones. Unlike legacy approaches relying on slow PRoot or chroot virtual machines, `termux-diffusion` compiles directly against Android's native Bionic libc and binds directly to host GPU drivers to execute high-quality 512x512 image synthesis natively on edge devices.
73
-
74
- * **Native Bionic libc ABI Direct Binding**: Runs directly inside Termux with zero virtual memory indirection, achieving bare-metal compute efficiency.
75
- * **Dual Compute Acceleration**: Integrates ARMv8.2-A DotProd/FP16 vector instructions with Qualcomm Adreno and ARM Mali Vulkan compute pipelines.
76
- * **Built-in VAE Tiling**: Eliminates the 1.2 GB memory spike during latent-to-pixel decoding, **reducing peak RAM consumption by ~70%** and preventing kernel Out-Of-Memory (OOM) aborts.
77
- * **Automated Android MediaStore Indexing**: Synchronizes generated images directly into `Pictures/TermuxDiffusion` and the native Samsung Gallery app in real time.
78
- * **Autonomous WakeLock Lifecycle Protection**: Automatically acquires an Android kernel CPU WakeLock during active inference to prevent thermal clock throttling when the display turns off.
79
-
80
- ---
81
-
82
- ## 2. Installation Guide
83
-
84
- ### 2.1 Termux System Prerequisites
85
- Launch the Termux terminal and install required native compilers, image processing libraries, and Vulkan tools:
86
- ```bash
87
- pkg update && pkg install -y python nodejs clang git libjpeg-turbo libpng termux-api vulkan-tools
88
- ```
89
-
90
- ### 2.2 Package Installation (Python & Node.js)
91
-
92
- * **Python SDK (PyPI)**:
93
- ```bash
94
- pip install termux-diffusion
95
- ```
96
-
97
- * **Node.js SDK & CLI (NPM)**:
98
- ```bash
99
- npm install -g termux-diffusion
100
- ```
101
-
102
- ### 2.3 One-Command Native Engine Provisioning (Fast-Track Stream Extractor)
103
- Run the automated installer to detect your device architecture and provision prebuilt native binaries or compile on-device:
104
- ```bash
105
- termux-diffusion install
106
- ```
107
-
108
- * **⚡ Fast-Track Stream Extractor (~3s)**: On Android ARM64 Termux, precompiled Bionic binaries (`sd-cli-vulkan`) and companion acceleration shims (`libegl_shim.so`, `libomp.so`) are automatically extracted from GitHub Releases in ~3 seconds, completely eliminating 20-minute on-device compilation and mobile OOM aborts.
109
- * **🛡️ Zero-Hardcoding SSOT Endpoints**: Binary downloads dynamically route through unified SSOT endpoints (`releases/latest/download` or `AMEVA_RELEASE_TAG`) with automated fallback to on-device C++ source compilation (`cmake` + `clang`) in air-gapped or offline environments.
110
-
111
-
112
- ---
113
-
114
- ## 3. Enabling Hardware GPU Acceleration (with ameva-runtime)
115
-
116
- To unlock mobile GPU acceleration via Vulkan compute shaders and achieve significant speedups over pure CPU execution, install **`termux-diffusion`** alongside **`ameva-runtime`** in a single command:
117
-
118
- ### 🌟 One-Line Installation
119
-
120
- ```bash
121
- # Python SDK
122
- pip install termux-diffusion ameva-runtime
123
-
124
- # Node.js SDK
125
- npm install -g termux-diffusion @ameva/runtime
126
- ```
127
-
128
- ### 🔮 Acceleration Mechanics with `ameva-runtime`
129
- 1. **Dynamic Driver Probing**: Automatically detects the underlying SoC (Snapdragon vs. Exynos/Dimensity) and dynamically locates the vendor Bionic Vulkan ICD (`/system/lib64/libvulkan.so`) in < 1ms.
130
- 2. **Vendor-Tailored Pipeline Dispatch**: Automatically binds optimized SPIR-V compute shaders tailored for Qualcomm Adreno or ARM Mali architectures without manual driver compilation.
131
- 3. **big.LITTLE Core Affinity Governor**: Binds worker compute threads exclusively to high-performance prime cores (Cortex-X / Cortex-A78) while streaming command buffers to the GPU queue.
132
-
133
- Verify GPU driver detection and hardware readiness:
134
- ```bash
135
- termux-diffusion doctor
136
- ```
137
-
138
- ---
139
-
140
- ## 4. Basic Usage (CLI, Python, Node.js)
141
-
142
- ### 4.1 Terminal CLI
143
- ```bash
144
- # Standard Photorealistic Generation (DreamShaper v8 Q4_0 preset)
145
- termux-diffusion generate "Cyberpunk Seoul street at night, neon lights, 8k, photorealistic"
146
-
147
- # Ultra-Fast Generation (SDXS-512-0.9 1~4 steps convergence) with GPU
148
- termux-diffusion generate "Cute fluffy white cat with sapphire eyes on the beach" -m speed --gpu
149
-
150
- # Explicit Output File Specification
151
- termux-diffusion generate "A majestic snow tiger in winter forest" -o /sdcard/tiger.png
152
- ```
153
-
154
- ### 4.2 Python SDK
155
- ```python
156
- import termux_diffusion as td
157
-
158
- # Generate high-fidelity image on mobile hardware
159
- result = td.generate(
160
- prompt="Cinematic portrait of an astronaut floating in colorful nebula, 8k, masterpiece",
161
- negative_prompt="lowres, bad anatomy, deformed, blurry, artifacts",
162
- model="realistic", # 'realistic' | 'speed' | 'turbo' | 'anime'
163
- device="gpu", # 'gpu' | 'cpu' | 'auto'
164
- steps=10, # Denoising iterations
165
- cfg_scale=4.5, # Classifier-Free Guidance scale
166
- width=512,
167
- height=512,
168
- seed=-1 # -1 for random seed
169
- )
170
-
171
- print(f"Generated Image: {result.path}")
172
- print(f"Samsung Gallery Path: {result.gallery_path}")
173
- print(f"Inference Time: {result.elapsed_sec:.1f}s")
174
- ```
175
-
176
- ### 4.3 Node.js / TypeScript SDK
177
- ```typescript
178
- import { generate } from "termux-diffusion";
179
-
180
- async function main() {
181
- const result = await generate({
182
- prompt: "An ancient temple hidden in a lush rainforest with golden sunlight beams, 8k",
183
- negativePrompt: "blurry, low quality, dark, distorted",
184
- model: "realistic",
185
- device: "gpu",
186
- steps: 10,
187
- cfgScale: 4.5,
188
- width: 512,
189
- height: 512
190
- });
191
-
192
- console.log(`Success: ${result.path} (${result.elapsedSec}s elapsed)`);
193
- }
194
-
195
- main();
196
- ```
197
-
198
- ---
199
-
200
- ## 5. Advanced Workflows
201
-
202
- ### 5.1 Image-to-Image (Img2Img Transformation)
203
- Transform an existing photograph or sketch into stylized AI artwork:
204
- ```python
205
- result = td.generate(
206
- prompt="Futuristic robotic mecha warrior with glowing blue armor, 8k",
207
- init_img="source_sketch.png",
208
- strength=0.65, # Denoising strength (0.0 keeps source, 1.0 full reimagining)
209
- model="realistic"
210
- )
211
- ```
212
- ```bash
213
- # Terminal CLI
214
- termux-diffusion generate "Robotic mecha warrior" -i source_sketch.png --strength 0.65
215
- ```
216
-
217
- ### 5.2 VAE Tiling (Mobile OOM Prevention)
218
- Standard VAE decoding creates an instantaneous **1.2 GB RAM spike** when converting latents to RGB pixels at 768x768 or higher resolutions. Enabling `vae_tiling` processes the latent tensor in spatial chunks, **lowering peak memory consumption by 70%**:
219
- ```python
220
- result = td.generate(
221
- prompt="Breathtaking wide landscape of Alpine mountains during sunset",
222
- width=768,
223
- height=768,
224
- vae_tiling=True # Enforces low-memory tiled VAE decode
225
- )
226
- ```
227
-
228
- ### 5.3 TAESD (Tiny AutoEncoder) Ultra-Fast Decoding
229
- Replaces heavy multi-layer autoencoders with Tiny AutoEncoder for Stable Diffusion, slashing the final decode step from **12 seconds down to < 0.1 seconds**:
230
- ```python
231
- result = td.generate(
232
- prompt="A cute golden retriever puppy sitting in a flower basket",
233
- model="speed",
234
- taesd="taesd.gguf", # Path to TAESD weights
235
- steps=4
236
- )
237
- ```
238
-
239
- ### 5.4 LoRA Style Adaptation & ControlNet Guidance
240
- ```python
241
- result = td.generate(
242
- prompt="A cyberpunk warrior swinging an energy katana, <lora:cyber_armor:0.8>",
243
- lora_dir="/data/data/com.termux/files/home/loras",
244
- control_net="controlnet-canny.gguf",
245
- control_image="edge_guide.png",
246
- control_strength=0.9
247
- )
248
- ```
249
-
250
- ### 5.5 High-Fidelity Sampler & Scheduler Pairings
251
- ```python
252
- # Optimal pairing for hyperrealistic skin textures and micro-details: DPM++ 2M + Karras
253
- result = td.generate(
254
- prompt="Studio portrait of an elderly watchmaker working with intricate gears",
255
- sampling_method="dpm++2m",
256
- schedule="karras",
257
- steps=14,
258
- cfg_scale=5.0
259
- )
260
- ```
261
-
262
- ---
263
-
264
- ## 6. Feature & Parameter Matrix
265
-
266
- | Parameter (Python / JS) | CLI Flag | Type | Default | Recommended Range | Description |
267
- | :--- | :--- | :---: | :---: | :---: | :--- |
268
- | `prompt` | `prompt` | String | (Required) | - | Text description of the desired image. |
269
- | `negative_prompt` | `-n`, `--negative` | String | `None` | - | Guidance describing elements to avoid (blur, artifacts, etc.). |
270
- | `model` | `-m`, `--model` | String | `realistic` | Preset / Path | `realistic`, `speed`, `turbo`, `anime`, or custom `.gguf` filepath. |
271
- | `device` | `-d`, `--device` | String | `auto` | `auto`,`gpu`,`cpu` | Hardware compute backend (`gpu` triggers Vulkan compute). |
272
- | `steps` | `-s`, `--steps` | Integer | Per-preset | 1 ~ 30 | Denoising steps (`speed`: 1~4, `realistic`: 8~15). |
273
- | `cfg_scale` | `-c`, `--cfg` | Float | Per-preset | 1.0 ~ 8.0 | Classifier-Free Guidance scale (`speed`: 1.0, `realistic`: 4.0~6.0). |
274
- | `width` / `height` | `-W`, `-H` | Integer | `512` | 256 ~ 768 | Spatial resolution in pixels (multiples of 64 recommended). |
275
- | `seed` | `--seed` | Integer | `-1` | -1 ~ 4294967295 | RNG seed (-1 selects an unseeded random state). |
276
- | `sampling_method` | `--sampler` | String | `euler_a` | `euler_a`,`dpm++2m` | Numerical solver algorithm (`dpm++2m`, `euler`, `lcm`, etc.). |
277
- | `schedule` | `--schedule` | String | `default` | `karras`,`ays` | Noise variance schedule (`karras`, `exponential`, `ays`). |
278
- | `vae_tiling` | `--vae-tiling` | Boolean | `False` | `True` / `False` | Enables spatial tiled decoding to prevent memory spikes. |
279
- | `init_img` | `-i`, `--init-img` | Path | `None` | Image Path | Source image file for Image-to-Image synthesis. |
280
- | `strength` | `--strength` | Float | `0.75` | 0.0 ~ 1.0 | Img2Img transformation strength relative to source. |
281
- | `lora_dir` | `--lora-dir` | Path | `None` | Directory | Path to folder containing LoRA adapter weights. |
282
- | `taesd` | `--taesd` | Path | `None` | `.gguf` Path | Tiny AutoEncoder model path for sub-second decoding. |
283
- | `clip_skip` | `--clip-skip` | Integer | `None` | 1 or 2 | Number of final CLIP text encoder layers to bypass. |
284
- | `export_gallery` | - | Boolean | `True` | `True` / `False` | Automatically registers output in Android MediaStore / Gallery. |
285
- | `wake_lock` | - | Boolean | `True` | `True` / `False` | Automatically manages CPU WakeLock during active inference. |
286
-
287
- ---
288
-
289
- ## 7. Production Code Examples & Self-Diagnostics
290
-
291
- ### 7.1 Automated Continuous Batch Loop
292
- ```python
293
- import termux_diffusion as td
294
-
295
- prompts = [
296
- "A cozy rainy cafe street in Kyoto, watercolor style",
297
- "A futuristic cyberpunk police car chasing a neon drone",
298
- "A serene zen garden with blooming cherry blossoms, golden hour"
299
- ]
300
-
301
- for idx, p in enumerate(prompts):
302
- print(f"[{idx+1}/{len(prompts)}] Generating: {p}")
303
- res = td.generate(prompt=p, model="speed", steps=4, width=512, height=512)
304
- print(f" -> Saved to: {res.path} ({res.elapsed_sec:.1f}s)")
305
- ```
306
-
307
- ### 7.2 Asynchronous Non-Blocking Execution (FastAPI / Bot Integration)
308
- ```python
309
- import asyncio
310
- from termux_diffusion import generate_async
311
-
312
- async def main():
313
- print("Dispatching asynchronous diffusion task...")
314
- task = asyncio.create_task(
315
- generate_async(
316
- prompt="A majestic eagle soaring above snow-capped Rocky Mountains",
317
- model="realistic",
318
- steps=10
319
- )
320
- )
321
- # Concurrent I/O operations continue unblocked
322
- await asyncio.sleep(1)
323
- print("Event loop running freely without thread lock...")
324
-
325
- result = await task
326
- print(f"Task completed: {result.path}")
327
-
328
- asyncio.run(main())
329
- ```
330
-
331
- ### 7.3 Hardware Diagnostic Inspection
332
- ```python
333
- import termux_diffusion as td
334
-
335
- profile = td.get_hardware_profile()
336
- print(f"CPU Architecture: {profile.cpu_arch}")
337
- print(f"GPU Device: {profile.gpu_name}")
338
- print(f"Vulkan Hardware Available: {profile.vulkan_available}")
339
- print(f"Optimal Backend: {profile.recommended_backend}")
340
- ```
341
-
342
- ---
343
-
344
- ## 8. Real-World Outputs & Hardware Benchmarks
345
-
346
- All benchmark metrics and rendered outputs represent physical executions on commercial Samsung Galaxy smartphones.
347
-
348
- ### 🖼️ Real-Device Rendered Samples
349
-
350
- | DreamShaper v8 (10 Steps) | SDXS-512 (1 Step Fast) | SD 1.5 Native (4 Steps) |
351
- | :---: | :---: | :---: |
352
- | ![Galaxy S25 Golden Cat](docs/assets/samples/s25_perfect_golden_cat.png) | ![SDXS Cat Beach](docs/assets/samples/sdxs_cat_beach.png) | ![SD15 Native](docs/assets/samples/sd15_512_native_s4.png) |
353
- | *Galaxy S25 + Vulkan (32s)* | *Galaxy S21 + SDXS (7.2s)* | *Galaxy S20 + Turbo (18s)* |
354
-
355
- ### 📊 Physical Benchmark Matrix (512x512 Resolution)
356
-
357
- | Device Model | SoC / Processor | GPU Architecture | SDXS-512 (1 Step) | Turbo (4 Steps) | Realistic (10 Steps) |
358
- | :--- | :--- | :--- | :---: | :---: | :---: |
359
- | **Galaxy S25** | Snapdragon 8 Elite | Adreno 830 (Vulkan) | **3.8s** | **12.4s** | **32.1s** |
360
- | **Galaxy S21** | Exynos 2100 | Mali-G78 (Vulkan) | **7.2s** | **22.8s** | **58.4s** |
361
- | **Galaxy S20 5G** | Snapdragon 865 | Adreno 650 (Vulkan) | **8.5s** | **26.1s** | **68.2s** |
362
- | **Galaxy A35** | Exynos 1380 | Mali-G68 (Vulkan) | **14.1s** | **38.5s** | **92.0s** |
363
-
364
- ---
365
-
366
- ## 9. GPU Interconnect Architecture & Compatibility Matrix
367
-
368
- ### 9.1 Native Bionic libc Binding Mechanism
369
- Virtual machine abstractions (e.g. PRoot) incur severe context switching and memory copy penalties when communicating with Linux kernel GPU drivers. `termux-diffusion` bypasses user-space shims and loads the host Android Bionic ICD directly:
370
-
371
- ```
372
- [termux-diffusion Native Core]
373
- │
374
- ▼
375
- (Direct dlopen)
376
- │
377
- ├──> /system/lib64/libvulkan.so (Host Android System ICD - Primary)
378
- └──> /vendor/lib64/libvulkan.so (Vendor Hardware Driver)
379
- ```
380
-
381
- > **Critical Safety Rule**: Dynamically linking Termux's desktop Mesa wrapper (`$PREFIX/lib/libvulkan.so`) forces compute operations into software CPU emulation or causes dispatch table collisions (`SIGSEGV`). `termux-diffusion` enforces **primary binding to the host system ICD**.
382
-
383
- ### 9.2 GPU Vendor Compatibility Matrix
384
-
385
- * **Qualcomm Adreno Series (Snapdragon)**:
386
- - **Compatibility**: 100% Native Production Support (Adreno 6xx, 7xx, 8xx).
387
- - **Details**: Full SPIR-V compute shader dispatch with native FP16 mixed-precision and hardware texture sampling.
388
- * **ARM Mali Series (Exynos / MediaTek Dimensity)**:
389
- - **Compatibility**: 100% Validated (Mali-G68, G77, G78, Immortalis).
390
- - **Mali-Specific Mitigations**: To resolve the documented Mali Bifrost/Valhall driver defect (**FP16 denormal float underflow causing green image corruption or NaN divergence**), `termux-diffusion` applies a Flush-to-Zero (FTZ) compilation pass via its verified runtime bundle (`mali-compat-v2`).
391
- * **Samsung Xclipse Series (AMD RDNA on Exynos 2200/2400)**:
392
- - **Compatibility**: Supported via Vulkan 1.3 standard compute interfaces.
393
-
394
- ---
395
-
396
- ## 10. Hardware Requirements & Operational Limits
397
-
398
- ### 10.1 Minimum vs. Recommended Specifications
399
-
400
- | Specification | Minimum Required | Recommended Production |
401
- | :--- | :--- | :--- |
402
- | **CPU Architecture** | ARM64-v8a (64-bit strictly required) | ARMv8.2-A+ with DotProd / FP16 SIMD |
403
- | **Physical RAM** | **6 GB RAM** (or 4 GB RAM + 4 GB zRAM/SWAP) | **8 GB ~ 12 GB LPDDR5** |
404
- | **GPU Capability** | Vulkan 1.1 Compute compliant | Adreno 650+ / Mali-G78+ |
405
- | **Operating System**| Android 10 (API Level 29) or higher | Android 13 ~ 15 (One UI 5 ~ 7) |
406
- | **Available Storage**| 4 GB free flash storage (model cache) | 10 GB+ free high-speed UFS 3.0+ flash |
407
-
408
- ### 10.2 Operational Boundaries
409
- 1. **No 32-bit Support**: 32-bit ARM (armv7l) environments are strictly unsupported due to address space limitations.
410
- 2. **4 GB RAM Preflight Guard**: Devices equipped with only 4 GB of physical RAM must enable the `--vae-tiling` flag to prevent kernel OOM killer termination during VAE image reconstruction.
411
-
412
- ---
413
-
414
- ## 11. 24/7 Unattended Background Execution Guide
415
-
416
- Follow this 3-tier hardening procedure to transform an idle Android phone into a continuous, non-throttling on-device AI generation node:
417
-
418
- ### Tier 1: Termux Environment Hardening
419
- Acquire an Android kernel CPU WakeLock to prevent the scheduler from dropping core frequencies when the display sleeps:
420
- ```bash
421
- # Acquire permanent CPU WakeLock
422
- termux-wake-lock
423
-
424
- # Grant Termux read/write access to shared internal storage
425
- termux-setup-storage
426
- ```
427
-
428
- ### Tier 2: Android OS GUI Settings
429
- 1. **Disable Battery Optimization**:
430
- - `Settings` $
431
- ightarrow$ `Apps` $
432
- ightarrow$ `Termux` $
433
- ightarrow$ `Battery` $
434
- ightarrow$ Select **'Unrestricted'**.
435
- 2. **Samsung One UI Background Exemption**:
436
- - `Settings` $
437
- ightarrow$ `Battery` $
438
- ightarrow$ `Background usage limits` $
439
- ightarrow$ Add `Termux` to **'Never sleeping apps'**.
440
- 3. **Maximize Virtual Memory (RAM Plus)**:
441
- - `Settings` $
442
- ightarrow$ `Device Care` $
443
- ightarrow$ `Memory` $
444
- ightarrow$ `RAM Plus` $
445
- ightarrow$ Select **8 GB** and reboot.
446
-
447
- ### Tier 3: ADB Protocol Configuration (via USB or Wireless LADB)
448
- Android 12 through 16 incorporate the **Phantom Process Killer**, which terminates background processes if total child process counts exceed 32 or sustained CPU load is detected. Completely neutralize this limitation:
449
-
450
- ```bash
451
- # 1. Permanently disable the Android Phantom Process Killer
452
- adb shell "/system/bin/device_config put activity_manager max_phantom_processes 2147483647"
453
- adb shell "/system/bin/device_config set_sync_disabled_for_tests persistent"
454
-
455
- # 2. Whitelist Termux against Android Doze deep-sleep standby
456
- adb shell "dumpsys deviceidle whitelist +com.termux"
457
-
458
- # 3. Lock Linux Low Memory Killer (LMK) priority (-1000 guarantees critical daemon status)
459
- adb shell "echo -1000 > /proc/$(adb shell pidof com.termux)/oom_score_adj"
460
- ```
461
-
462
- ---
463
-
464
- ## 12. License & Permissible Use
465
-
466
- `termux-diffusion` is released under the **MIT License**.
467
-
468
- ```text
469
- MIT License
470
-
471
- Copyright (c) 2026 Eunho Kim (uno-km / AMEVA Foundation)
472
-
473
- Permission is hereby granted, free of charge, to any person obtaining a copy
474
- of this software and associated documentation files (the "Software"), to deal
475
- in the Software without restriction, including without limitation the rights
476
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
477
- copies of the Software, and to permit persons to whom the Software is
478
- furnished to do so, subject to the following conditions:
479
-
480
- The above copyright notice and this permission notice shall be included in all
481
- copies or substantial portions of the Software.
482
-
483
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
484
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
485
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
486
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
487
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
488
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
489
- SOFTWARE.
490
- ```
491
-
492
- ### Summary of Rights:
493
- * **Commercial Use**: Permitted freely in proprietary and commercial services.
494
- * **Modification & Distribution**: Permitted with copyright notice retention.
495
- * **Private Use & Sublicensing**: Permitted without royalty or attribution fees.
496
-
497
- ---
498
-
499
- ## 13. Keywords & Discoverability Index
500
-
501
- `stable-diffusion`, `diffusion`, `termux`, `android`, `samsung-galaxy`, `edge-ai`, `on-device-ai`, `image-generation`, `text-to-image`, `txt2img`, `img2img`, `gguf`, `arm64`, `aarch64`, `vulkan`, `vulkan-compute`, `spirv`, `adreno`, `mali`, `snapdragon`, `exynos`, `bionic-libc`, `taesd`, `vae-tiling`, `lora`, `controlnet`, `sdxs`, `sd-turbo`, `dreamshaper`, `offline-ai`, `mobile-inference`, `camera-roll`, `galaxy-s25`, `galaxy-s20`
502
-
503
- ---
504
-
505
- ## 📖 Official Ecosystem Links
506
- * **AMEVA Foundation Portal**: [https://uno-km.vercel.app/foundation/index.html](https://uno-km.vercel.app/foundation/index.html)
507
- * **Interactive Web Documentation**: [https://uno-km.vercel.app/lib/diffusion/](https://uno-km.vercel.app/lib/diffusion/)
508
- * **Issue Tracker**: [https://github.com/uno-km/termux-diffusion/issues](https://github.com/uno-km/termux-diffusion/issues)
1
+ Metadata-Version: 2.4
2
+ Name: termux-diffusion
3
+ Version: 1.6.4
4
+ Summary: On-device Stable Diffusion runtime utilizing device resources for Android Termux & Samsung Galaxy (Dual-Engine Python & Node.js)
5
+ Home-page: https://github.com/uno-km/termux-diffusion
6
+ Author: uno-km (AMEVA Foundation)
7
+ Author-email: "uno-km (AMEVA Foundation)" <hosequelbo@gmail.com>
8
+ License: MIT
9
+ Project-URL: Homepage, https://github.com/uno-km/termux-diffusion
10
+ Project-URL: Documentation, https://uno-km.github.io/termux-diffusion/
11
+ Project-URL: npm Package, https://www.npmjs.com/package/termux-diffusion
12
+ Project-URL: Bug Tracker, https://github.com/uno-km/termux-diffusion/issues
13
+ Project-URL: Source, https://github.com/uno-km/termux-diffusion
14
+ Keywords: stable-diffusion,diffusion,termux,android,samsung-galaxy,edge-ai,on-device-ai,image-generation,text-to-image,txt2img,img2img,gguf,arm64,aarch64,vulkan,vulkan-compute,spirv,adreno,mali,snapdragon,exynos,bionic-libc,taesd,vae-tiling,lora,controlnet,sdxs,sd-turbo,dreamshaper,mobile-inference,camera-roll,galaxy-s25,galaxy-s20,private-ai
15
+ Classifier: Development Status :: 5 - Production/Stable
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: License :: OSI Approved :: MIT License
18
+ Classifier: Operating System :: POSIX :: Linux
19
+ Classifier: Operating System :: Android
20
+ Classifier: Programming Language :: Python :: 3
21
+ Classifier: Programming Language :: Python :: 3.8
22
+ Classifier: Programming Language :: Python :: 3.9
23
+ Classifier: Programming Language :: Python :: 3.10
24
+ Classifier: Programming Language :: Python :: 3.11
25
+ Classifier: Programming Language :: Python :: 3.12
26
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
27
+ Classifier: Topic :: Multimedia :: Graphics
28
+ Requires-Python: >=3.8
29
+ Description-Content-Type: text/markdown
30
+ License-File: LICENSE
31
+ Requires-Dist: ameva-runtime>=2.0.0
32
+ Requires-Dist: ameva-component-sdk<2.0,>=0.1.0
33
+ Dynamic: author
34
+ Dynamic: classifier
35
+ Dynamic: home-page
36
+ Dynamic: license-file
37
+ Dynamic: requires-python
38
+
39
+ # Termux-Diffusion
40
+
41
+ [![PyPI](https://img.shields.io/pypi/v/termux-diffusion.svg?style=flat-square&color=0369a1)](https://pypi.org/project/termux-diffusion/)
42
+ [![Python](https://img.shields.io/pypi/pyversions/termux-diffusion.svg?style=flat-square)](https://pypi.org/project/termux-diffusion/)
43
+ [![npm](https://img.shields.io/npm/v/termux-diffusion.svg?style=flat-square&color=b91c1c)](https://www.npmjs.com/package/termux-diffusion)
44
+ [![npm downloads](https://img.shields.io/npm/dm/termux-diffusion.svg?style=flat-square&color=b91c1c)](https://www.npmjs.com/package/termux-diffusion)
45
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg?style=flat-square)](https://opensource.org/licenses/MIT)
46
+
47
+ > **Native On-Device Stable Diffusion Runtime for Android Termux & Samsung Galaxy via Direct Bionic libc & Vulkan Compute Acceleration.**
48
+ > *Zero PRoot. Zero Virtualization. 100% Native ARMv8.2-A NEON SIMD & Hardware GPU Acceleration.*
49
+
50
+ ---
51
+
52
+ ## 📑 Table of Contents
53
+
54
+ 1. [Overview & Key Capabilities](#1-overview--key-capabilities)
55
+ 2. [Installation Guide](#2-installation-guide)
56
+ 3. [Enabling Hardware GPU Acceleration (with ameva-runtime)](#3-enabling-hardware-gpu-acceleration-with-ameva-runtime)
57
+ 4. [Basic Usage (CLI, Python, Node.js)](#4-basic-usage-cli-python-nodejs)
58
+ 5. [Advanced Workflows](#5-advanced-workflows)
59
+ 6. [Feature & Parameter Matrix](#6-feature--parameter-matrix)
60
+ 7. [Production Code Examples & Self-Diagnostics](#7-production-code-examples--self-diagnostics)
61
+ 8. [Real-World Outputs & Hardware Benchmarks](#8-real-world-outputs--hardware-benchmarks)
62
+ 9. [GPU Interconnect Architecture & Compatibility Matrix (Adreno vs. Mali)](#9-gpu-interconnect-architecture--compatibility-matrix)
63
+ 10. [Hardware Requirements & Operational Limits](#10-hardware-requirements--operational-limits)
64
+ 11. [24/7 Unattended Background Execution Guide (Termux -> Android -> ADB)](#11-247-unattended-background-execution-guide)
65
+ 12. [License & Permissible Use](#12-license--permissible-use)
66
+ 13. [Keywords & Discoverability Index](#13-keywords--discoverability-index)
67
+
68
+ ---
69
+
70
+ ## 1. Overview & Key Capabilities
71
+
72
+ `termux-diffusion` is a production-grade, on-device diffusion inference engine engineered specifically for Android smartphones. Unlike legacy approaches relying on slow PRoot or chroot virtual machines, `termux-diffusion` compiles directly against Android's native Bionic libc and binds directly to host GPU drivers to execute high-quality 512x512 image synthesis natively on edge devices.
73
+
74
+ * **Native Bionic libc ABI Direct Binding**: Runs directly inside Termux with zero virtual memory indirection, achieving bare-metal compute efficiency.
75
+ * **Dual Compute Acceleration**: Integrates ARMv8.2-A DotProd/FP16 vector instructions with Qualcomm Adreno and ARM Mali Vulkan compute pipelines.
76
+ * **Built-in VAE Tiling**: Eliminates the 1.2 GB memory spike during latent-to-pixel decoding, **reducing peak RAM consumption by ~70%** and preventing kernel Out-Of-Memory (OOM) aborts.
77
+ * **Automated Android MediaStore Indexing**: Synchronizes generated images directly into `Pictures/TermuxDiffusion` and the native Samsung Gallery app in real time.
78
+ * **Autonomous WakeLock Lifecycle Protection**: Automatically acquires an Android kernel CPU WakeLock during active inference to prevent thermal clock throttling when the display turns off.
79
+
80
+ ---
81
+
82
+ ## 2. Installation Guide
83
+
84
+ ### 2.1 Termux System Prerequisites
85
+ Launch the Termux terminal and install required native compilers, image processing libraries, and Vulkan tools:
86
+ ```bash
87
+ pkg update && pkg install -y python nodejs clang git libjpeg-turbo libpng termux-api vulkan-tools
88
+ ```
89
+
90
+ ### 2.2 Package Installation (Python & Node.js)
91
+
92
+ * **Python SDK (PyPI)**:
93
+ ```bash
94
+ pip install termux-diffusion
95
+ ```
96
+
97
+ * **Node.js SDK & CLI (NPM)**:
98
+ ```bash
99
+ npm install -g termux-diffusion
100
+ ```
101
+
102
+ ### 2.3 One-Command Native Engine Provisioning (Fast-Track Stream Extractor)
103
+ Run the automated installer to detect your device architecture and provision prebuilt native binaries or compile on-device:
104
+ ```bash
105
+ termux-diffusion install
106
+ ```
107
+
108
+ * **⚡ Fast-Track Stream Extractor (~3s)**: On Android ARM64 Termux, precompiled Bionic binaries (`sd-cli-vulkan`) and companion acceleration shims (`libegl_shim.so`, `libomp.so`) are automatically extracted from GitHub Releases in ~3 seconds, completely eliminating 20-minute on-device compilation and mobile OOM aborts.
109
+ * **🛡️ Zero-Hardcoding SSOT Endpoints**: Binary downloads dynamically route through unified SSOT endpoints (`releases/latest/download` or `AMEVA_RELEASE_TAG`) with automated fallback to on-device C++ source compilation (`cmake` + `clang`) in air-gapped or offline environments.
110
+
111
+
112
+ ---
113
+
114
+ ## 3. Enabling Hardware GPU Acceleration (with ameva-runtime)
115
+
116
+ To unlock mobile GPU acceleration via Vulkan compute shaders and achieve significant speedups over pure CPU execution, install **`termux-diffusion`** alongside **`ameva-runtime`** in a single command:
117
+
118
+ ### 🌟 One-Line Installation
119
+
120
+ ```bash
121
+ # Python SDK
122
+ pip install termux-diffusion ameva-runtime
123
+
124
+ # Node.js SDK
125
+ npm install -g termux-diffusion @ameva/runtime
126
+ ```
127
+
128
+ ### 🔮 Acceleration Mechanics with `ameva-runtime`
129
+ 1. **Dynamic Driver Probing**: Automatically detects the underlying SoC (Snapdragon vs. Exynos/Dimensity) and dynamically locates the vendor Bionic Vulkan ICD (`/system/lib64/libvulkan.so`) in < 1ms.
130
+ 2. **Vendor-Tailored Pipeline Dispatch**: Automatically binds optimized SPIR-V compute shaders tailored for Qualcomm Adreno or ARM Mali architectures without manual driver compilation.
131
+ 3. **big.LITTLE Core Affinity Governor**: Binds worker compute threads exclusively to high-performance prime cores (Cortex-X / Cortex-A78) while streaming command buffers to the GPU queue.
132
+
133
+ Verify GPU driver detection and hardware readiness:
134
+ ```bash
135
+ termux-diffusion doctor
136
+ ```
137
+
138
+ ---
139
+
140
+ ## 4. Basic Usage (CLI, Python, Node.js)
141
+
142
+ ### 4.1 Terminal CLI
143
+ ```bash
144
+ # Standard Photorealistic Generation (DreamShaper v8 Q4_0 preset)
145
+ termux-diffusion generate "Cyberpunk Seoul street at night, neon lights, 8k, photorealistic"
146
+
147
+ # Ultra-Fast Generation (SDXS-512-0.9 1~4 steps convergence) with GPU
148
+ termux-diffusion generate "Cute fluffy white cat with sapphire eyes on the beach" -m speed --gpu
149
+
150
+ # Explicit Output File Specification
151
+ termux-diffusion generate "A majestic snow tiger in winter forest" -o /sdcard/tiger.png
152
+ ```
153
+
154
+ ### 4.2 Python SDK
155
+ ```python
156
+ import termux_diffusion as td
157
+
158
+ # Generate high-fidelity image on mobile hardware
159
+ result = td.generate(
160
+ prompt="Cinematic portrait of an astronaut floating in colorful nebula, 8k, masterpiece",
161
+ negative_prompt="lowres, bad anatomy, deformed, blurry, artifacts",
162
+ model="realistic", # 'realistic' | 'speed' | 'turbo' | 'anime'
163
+ device="gpu", # 'gpu' | 'cpu' | 'auto'
164
+ steps=10, # Denoising iterations
165
+ cfg_scale=4.5, # Classifier-Free Guidance scale
166
+ width=512,
167
+ height=512,
168
+ seed=-1 # -1 for random seed
169
+ )
170
+
171
+ print(f"Generated Image: {result.path}")
172
+ print(f"Samsung Gallery Path: {result.gallery_path}")
173
+ print(f"Inference Time: {result.elapsed_sec:.1f}s")
174
+ ```
175
+
176
+ ### 4.3 Node.js / TypeScript SDK
177
+ ```typescript
178
+ import { generate } from "termux-diffusion";
179
+
180
+ async function main() {
181
+ const result = await generate({
182
+ prompt: "An ancient temple hidden in a lush rainforest with golden sunlight beams, 8k",
183
+ negativePrompt: "blurry, low quality, dark, distorted",
184
+ model: "realistic",
185
+ device: "gpu",
186
+ steps: 10,
187
+ cfgScale: 4.5,
188
+ width: 512,
189
+ height: 512
190
+ });
191
+
192
+ console.log(`Success: ${result.path} (${result.elapsedSec}s elapsed)`);
193
+ }
194
+
195
+ main();
196
+ ```
197
+
198
+ ---
199
+
200
+ ## 5. Advanced Workflows
201
+
202
+ ### 5.1 Image-to-Image (Img2Img Transformation)
203
+ Transform an existing photograph or sketch into stylized AI artwork:
204
+ ```python
205
+ result = td.generate(
206
+ prompt="Futuristic robotic mecha warrior with glowing blue armor, 8k",
207
+ init_img="source_sketch.png",
208
+ strength=0.65, # Denoising strength (0.0 keeps source, 1.0 full reimagining)
209
+ model="realistic"
210
+ )
211
+ ```
212
+ ```bash
213
+ # Terminal CLI
214
+ termux-diffusion generate "Robotic mecha warrior" -i source_sketch.png --strength 0.65
215
+ ```
216
+
217
+ ### 5.2 VAE Tiling (Mobile OOM Prevention)
218
+ Standard VAE decoding creates an instantaneous **1.2 GB RAM spike** when converting latents to RGB pixels at 768x768 or higher resolutions. Enabling `vae_tiling` processes the latent tensor in spatial chunks, **lowering peak memory consumption by 70%**:
219
+ ```python
220
+ result = td.generate(
221
+ prompt="Breathtaking wide landscape of Alpine mountains during sunset",
222
+ width=768,
223
+ height=768,
224
+ vae_tiling=True # Enforces low-memory tiled VAE decode
225
+ )
226
+ ```
227
+
228
+ ### 5.3 TAESD (Tiny AutoEncoder) Ultra-Fast Decoding
229
+ Replaces heavy multi-layer autoencoders with Tiny AutoEncoder for Stable Diffusion, slashing the final decode step from **12 seconds down to < 0.1 seconds**:
230
+ ```python
231
+ result = td.generate(
232
+ prompt="A cute golden retriever puppy sitting in a flower basket",
233
+ model="speed",
234
+ taesd="taesd.gguf", # Path to TAESD weights
235
+ steps=4
236
+ )
237
+ ```
238
+
239
+ ### 5.4 LoRA Style Adaptation & ControlNet Guidance
240
+ ```python
241
+ result = td.generate(
242
+ prompt="A cyberpunk warrior swinging an energy katana, <lora:cyber_armor:0.8>",
243
+ lora_dir="/data/data/com.termux/files/home/loras",
244
+ control_net="controlnet-canny.gguf",
245
+ control_image="edge_guide.png",
246
+ control_strength=0.9
247
+ )
248
+ ```
249
+
250
+ ### 5.5 High-Fidelity Sampler & Scheduler Pairings
251
+ ```python
252
+ # Optimal pairing for hyperrealistic skin textures and micro-details: DPM++ 2M + Karras
253
+ result = td.generate(
254
+ prompt="Studio portrait of an elderly watchmaker working with intricate gears",
255
+ sampling_method="dpm++2m",
256
+ schedule="karras",
257
+ steps=14,
258
+ cfg_scale=5.0
259
+ )
260
+ ```
261
+
262
+ ---
263
+
264
+ ## 6. Feature & Parameter Matrix
265
+
266
+ | Parameter (Python / JS) | CLI Flag | Type | Default | Recommended Range | Description |
267
+ | :--- | :--- | :---: | :---: | :---: | :--- |
268
+ | `prompt` | `prompt` | String | (Required) | - | Text description of the desired image. |
269
+ | `negative_prompt` | `-n`, `--negative` | String | `None` | - | Guidance describing elements to avoid (blur, artifacts, etc.). |
270
+ | `model` | `-m`, `--model` | String | `realistic` | Preset / Path | `realistic`, `speed`, `turbo`, `anime`, or custom `.gguf` filepath. |
271
+ | `device` | `-d`, `--device` | String | `auto` | `auto`,`gpu`,`cpu` | Hardware compute backend (`gpu` triggers Vulkan compute). |
272
+ | `steps` | `-s`, `--steps` | Integer | Per-preset | 1 ~ 30 | Denoising steps (`speed`: 1~4, `realistic`: 8~15). |
273
+ | `cfg_scale` | `-c`, `--cfg` | Float | Per-preset | 1.0 ~ 8.0 | Classifier-Free Guidance scale (`speed`: 1.0, `realistic`: 4.0~6.0). |
274
+ | `width` / `height` | `-W`, `-H` | Integer | `512` | 256 ~ 768 | Spatial resolution in pixels (multiples of 64 recommended). |
275
+ | `seed` | `--seed` | Integer | `-1` | -1 ~ 4294967295 | RNG seed (-1 selects an unseeded random state). |
276
+ | `sampling_method` | `--sampler` | String | `euler_a` | `euler_a`,`dpm++2m` | Numerical solver algorithm (`dpm++2m`, `euler`, `lcm`, etc.). |
277
+ | `schedule` | `--schedule` | String | `default` | `karras`,`ays` | Noise variance schedule (`karras`, `exponential`, `ays`). |
278
+ | `vae_tiling` | `--vae-tiling` | Boolean | `False` | `True` / `False` | Enables spatial tiled decoding to prevent memory spikes. |
279
+ | `init_img` | `-i`, `--init-img` | Path | `None` | Image Path | Source image file for Image-to-Image synthesis. |
280
+ | `strength` | `--strength` | Float | `0.75` | 0.0 ~ 1.0 | Img2Img transformation strength relative to source. |
281
+ | `lora_dir` | `--lora-dir` | Path | `None` | Directory | Path to folder containing LoRA adapter weights. |
282
+ | `taesd` | `--taesd` | Path | `None` | `.gguf` Path | Tiny AutoEncoder model path for sub-second decoding. |
283
+ | `clip_skip` | `--clip-skip` | Integer | `None` | 1 or 2 | Number of final CLIP text encoder layers to bypass. |
284
+ | `export_gallery` | - | Boolean | `True` | `True` / `False` | Automatically registers output in Android MediaStore / Gallery. |
285
+ | `wake_lock` | - | Boolean | `True` | `True` / `False` | Automatically manages CPU WakeLock during active inference. |
286
+
287
+ ---
288
+
289
+ ## 7. Production Code Examples & Self-Diagnostics
290
+
291
+ ### 7.1 Automated Continuous Batch Loop
292
+ ```python
293
+ import termux_diffusion as td
294
+
295
+ prompts = [
296
+ "A cozy rainy cafe street in Kyoto, watercolor style",
297
+ "A futuristic cyberpunk police car chasing a neon drone",
298
+ "A serene zen garden with blooming cherry blossoms, golden hour"
299
+ ]
300
+
301
+ for idx, p in enumerate(prompts):
302
+ print(f"[{idx+1}/{len(prompts)}] Generating: {p}")
303
+ res = td.generate(prompt=p, model="speed", steps=4, width=512, height=512)
304
+ print(f" -> Saved to: {res.path} ({res.elapsed_sec:.1f}s)")
305
+ ```
306
+
307
+ ### 7.2 Asynchronous Non-Blocking Execution (FastAPI / Bot Integration)
308
+ ```python
309
+ import asyncio
310
+ from termux_diffusion import generate_async
311
+
312
+ async def main():
313
+ print("Dispatching asynchronous diffusion task...")
314
+ task = asyncio.create_task(
315
+ generate_async(
316
+ prompt="A majestic eagle soaring above snow-capped Rocky Mountains",
317
+ model="realistic",
318
+ steps=10
319
+ )
320
+ )
321
+ # Concurrent I/O operations continue unblocked
322
+ await asyncio.sleep(1)
323
+ print("Event loop running freely without thread lock...")
324
+
325
+ result = await task
326
+ print(f"Task completed: {result.path}")
327
+
328
+ asyncio.run(main())
329
+ ```
330
+
331
+ ### 7.3 Hardware Diagnostic Inspection
332
+ ```python
333
+ import termux_diffusion as td
334
+
335
+ profile = td.get_hardware_profile()
336
+ print(f"CPU Architecture: {profile.cpu_arch}")
337
+ print(f"GPU Device: {profile.gpu_name}")
338
+ print(f"Vulkan Hardware Available: {profile.vulkan_available}")
339
+ print(f"Optimal Backend: {profile.recommended_backend}")
340
+ ```
341
+
342
+ ---
343
+
344
+ ## 8. Real-World Outputs & Hardware Benchmarks
345
+
346
+ All benchmark metrics and rendered outputs represent physical executions on commercial Samsung Galaxy smartphones.
347
+
348
+ ### 🖼️ Real-Device Rendered Samples
349
+
350
+ | DreamShaper v8 (10 Steps) | SDXS-512 (1 Step Fast) | SD 1.5 Native (4 Steps) |
351
+ | :---: | :---: | :---: |
352
+ | ![Galaxy S25 Golden Cat](docs/assets/samples/s25_perfect_golden_cat.png) | ![SDXS Cat Beach](docs/assets/samples/sdxs_cat_beach.png) | ![SD15 Native](docs/assets/samples/sd15_512_native_s4.png) |
353
+ | *Galaxy S25 + Vulkan (32s)* | *Galaxy S21 + SDXS (7.2s)* | *Galaxy S20 + Turbo (18s)* |
354
+
355
+ ### 📊 Physical Benchmark Matrix (512x512 Resolution)
356
+
357
+ | Device Model | SoC / Processor | GPU Architecture | SDXS-512 (1 Step) | Turbo (4 Steps) | Realistic (10 Steps) |
358
+ | :--- | :--- | :--- | :---: | :---: | :---: |
359
+ | **Galaxy S25** | Snapdragon 8 Elite | Adreno 830 (Vulkan) | **3.8s** | **12.4s** | **32.1s** |
360
+ | **Galaxy S21** | Exynos 2100 | Mali-G78 (Vulkan) | **7.2s** | **22.8s** | **58.4s** |
361
+ | **Galaxy S20 5G** | Snapdragon 865 | Adreno 650 (Vulkan) | **8.5s** | **26.1s** | **68.2s** |
362
+ | **Galaxy A35** | Exynos 1380 | Mali-G68 (Vulkan) | **14.1s** | **38.5s** | **92.0s** |
363
+
364
+ ---
365
+
366
+ ## 9. GPU Interconnect Architecture & Compatibility Matrix
367
+
368
+ ### 9.1 Native Bionic libc Binding Mechanism
369
+ Virtual machine abstractions (e.g. PRoot) incur severe context switching and memory copy penalties when communicating with Linux kernel GPU drivers. `termux-diffusion` bypasses user-space shims and loads the host Android Bionic ICD directly:
370
+
371
+ ```
372
+ [termux-diffusion Native Core]
373
+ │
374
+ ▼
375
+ (Direct dlopen)
376
+ │
377
+ ├──> /system/lib64/libvulkan.so (Host Android System ICD - Primary)
378
+ └──> /vendor/lib64/libvulkan.so (Vendor Hardware Driver)
379
+ ```
380
+
381
+ > **Critical Safety Rule**: Dynamically linking Termux's desktop Mesa wrapper (`$PREFIX/lib/libvulkan.so`) forces compute operations into software CPU emulation or causes dispatch table collisions (`SIGSEGV`). `termux-diffusion` enforces **primary binding to the host system ICD**.
382
+
383
+ ### 9.2 GPU Vendor Compatibility Matrix
384
+
385
+ * **Qualcomm Adreno Series (Snapdragon)**:
386
+ - **Compatibility**: 100% Native Production Support (Adreno 6xx, 7xx, 8xx).
387
+ - **Details**: Full SPIR-V compute shader dispatch with native FP16 mixed-precision and hardware texture sampling.
388
+ * **ARM Mali Series (Exynos / MediaTek Dimensity)**:
389
+ - **Compatibility**: 100% Validated (Mali-G68, G77, G78, Immortalis).
390
+ - **Mali-Specific Mitigations**: To resolve the documented Mali Bifrost/Valhall driver defect (**FP16 denormal float underflow causing green image corruption or NaN divergence**), `termux-diffusion` applies a Flush-to-Zero (FTZ) compilation pass via its verified runtime bundle (`mali-compat-v2`).
391
+ * **Samsung Xclipse Series (AMD RDNA on Exynos 2200/2400)**:
392
+ - **Compatibility**: Supported via Vulkan 1.3 standard compute interfaces.
393
+
394
+ ---
395
+
396
+ ## 10. Hardware Requirements & Operational Limits
397
+
398
+ ### 10.1 Minimum vs. Recommended Specifications
399
+
400
+ | Specification | Minimum Required | Recommended Production |
401
+ | :--- | :--- | :--- |
402
+ | **CPU Architecture** | ARM64-v8a (64-bit strictly required) | ARMv8.2-A+ with DotProd / FP16 SIMD |
403
+ | **Physical RAM** | **6 GB RAM** (or 4 GB RAM + 4 GB zRAM/SWAP) | **8 GB ~ 12 GB LPDDR5** |
404
+ | **GPU Capability** | Vulkan 1.1 Compute compliant | Adreno 650+ / Mali-G78+ |
405
+ | **Operating System**| Android 10 (API Level 29) or higher | Android 13 ~ 15 (One UI 5 ~ 7) |
406
+ | **Available Storage**| 4 GB free flash storage (model cache) | 10 GB+ free high-speed UFS 3.0+ flash |
407
+
408
+ ### 10.2 Operational Boundaries
409
+ 1. **No 32-bit Support**: 32-bit ARM (armv7l) environments are strictly unsupported due to address space limitations.
410
+ 2. **4 GB RAM Preflight Guard**: Devices equipped with only 4 GB of physical RAM must enable the `--vae-tiling` flag to prevent kernel OOM killer termination during VAE image reconstruction.
411
+
412
+ ---
413
+
414
+ ## 11. 24/7 Unattended Background Execution Guide
415
+
416
+ Follow this 3-tier hardening procedure to transform an idle Android phone into a continuous, non-throttling on-device AI generation node:
417
+
418
+ ### Tier 1: Termux Environment Hardening
419
+ Acquire an Android kernel CPU WakeLock to prevent the scheduler from dropping core frequencies when the display sleeps:
420
+ ```bash
421
+ # Acquire permanent CPU WakeLock
422
+ termux-wake-lock
423
+
424
+ # Grant Termux read/write access to shared internal storage
425
+ termux-setup-storage
426
+ ```
427
+
428
+ ### Tier 2: Android OS GUI Settings
429
+ 1. **Disable Battery Optimization**:
430
+ - `Settings` $
431
+ ightarrow$ `Apps` $
432
+ ightarrow$ `Termux` $
433
+ ightarrow$ `Battery` $
434
+ ightarrow$ Select **'Unrestricted'**.
435
+ 2. **Samsung One UI Background Exemption**:
436
+ - `Settings` $
437
+ ightarrow$ `Battery` $
438
+ ightarrow$ `Background usage limits` $
439
+ ightarrow$ Add `Termux` to **'Never sleeping apps'**.
440
+ 3. **Maximize Virtual Memory (RAM Plus)**:
441
+ - `Settings` $
442
+ ightarrow$ `Device Care` $
443
+ ightarrow$ `Memory` $
444
+ ightarrow$ `RAM Plus` $
445
+ ightarrow$ Select **8 GB** and reboot.
446
+
447
+ ### Tier 3: ADB Protocol Configuration (via USB or Wireless LADB)
448
+ Android 12 through 16 incorporate the **Phantom Process Killer**, which terminates background processes if total child process counts exceed 32 or sustained CPU load is detected. Completely neutralize this limitation:
449
+
450
+ ```bash
451
+ # 1. Permanently disable the Android Phantom Process Killer
452
+ adb shell "/system/bin/device_config put activity_manager max_phantom_processes 2147483647"
453
+ adb shell "/system/bin/device_config set_sync_disabled_for_tests persistent"
454
+
455
+ # 2. Whitelist Termux against Android Doze deep-sleep standby
456
+ adb shell "dumpsys deviceidle whitelist +com.termux"
457
+
458
+ # 3. Lock Linux Low Memory Killer (LMK) priority (-1000 guarantees critical daemon status)
459
+ adb shell "echo -1000 > /proc/$(adb shell pidof com.termux)/oom_score_adj"
460
+ ```
461
+
462
+ ---
463
+
464
+ ## 12. License & Permissible Use
465
+
466
+ `termux-diffusion` is released under the **MIT License**.
467
+
468
+ ```text
469
+ MIT License
470
+
471
+ Copyright (c) 2026 Eunho Kim (uno-km / AMEVA Foundation)
472
+
473
+ Permission is hereby granted, free of charge, to any person obtaining a copy
474
+ of this software and associated documentation files (the "Software"), to deal
475
+ in the Software without restriction, including without limitation the rights
476
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
477
+ copies of the Software, and to permit persons to whom the Software is
478
+ furnished to do so, subject to the following conditions:
479
+
480
+ The above copyright notice and this permission notice shall be included in all
481
+ copies or substantial portions of the Software.
482
+
483
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
484
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
485
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
486
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
487
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
488
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
489
+ SOFTWARE.
490
+ ```
491
+
492
+ ### Summary of Rights:
493
+ * **Commercial Use**: Permitted freely in proprietary and commercial services.
494
+ * **Modification & Distribution**: Permitted with copyright notice retention.
495
+ * **Private Use & Sublicensing**: Permitted without royalty or attribution fees.
496
+
497
+ ---
498
+
499
+ ## 13. Keywords & Discoverability Index
500
+
501
+ `stable-diffusion`, `diffusion`, `termux`, `android`, `samsung-galaxy`, `edge-ai`, `on-device-ai`, `image-generation`, `text-to-image`, `txt2img`, `img2img`, `gguf`, `arm64`, `aarch64`, `vulkan`, `vulkan-compute`, `spirv`, `adreno`, `mali`, `snapdragon`, `exynos`, `bionic-libc`, `taesd`, `vae-tiling`, `lora`, `controlnet`, `sdxs`, `sd-turbo`, `dreamshaper`, `offline-ai`, `mobile-inference`, `camera-roll`, `galaxy-s25`, `galaxy-s20`
502
+
503
+ ---
504
+
505
+ ## 📖 Official Ecosystem Links
506
+ * **AMEVA Foundation Portal**: [https://uno-km.vercel.app/foundation/index.html](https://uno-km.vercel.app/foundation/index.html)
507
+ * **Interactive Web Documentation**: [https://uno-km.vercel.app/lib/diffusion/](https://uno-km.vercel.app/lib/diffusion/)
508
+ * **Issue Tracker**: [https://github.com/uno-km/termux-diffusion/issues](https://github.com/uno-km/termux-diffusion/issues)