amv-device-sdk 0.2.1__py3-none-any.whl

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.
@@ -0,0 +1,60 @@
1
+ # Copyright (c) 2026 Uno Kim / AMEVA Foundation. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0 OR Commercial-License
3
+ """
4
+ AMEVA Device SDK (ameva-device-sdk)
5
+ ==================================
6
+ The Authoritative On-Device Systems Foundation for the AMEVA & uno-km Ecosystem.
7
+ Open-Source under Apache-2.0.
8
+ """
9
+
10
+ from .env import is_android, is_proot, is_termux
11
+ from .hardware import (
12
+ get_memory_info,
13
+ get_optimal_threads,
14
+ probe_vulkan_driver,
15
+ read_cpu_features,
16
+ )
17
+ from .storage import (
18
+ atomic_replace,
19
+ check_disk_space,
20
+ download_file_atomic,
21
+ get_unified_model_search_dirs,
22
+ verify_file_sha256,
23
+ )
24
+
25
+ from .runtime_guard import (
26
+ RUNTIME_REQUIRED_CODE,
27
+ RUNTIME_REQUIRED_EXIT_CODE,
28
+ AmevaRuntimeRequiredError,
29
+ exit_if_runtime_missing,
30
+ installed_runtime_version,
31
+ require_ameva_runtime,
32
+ )
33
+
34
+ __version__ = "0.2.0"
35
+
36
+ __all__ = [
37
+ "__version__",
38
+ # Environment
39
+ "is_termux",
40
+ "is_android",
41
+ "is_proot",
42
+ # Hardware Telemetry
43
+ "get_memory_info",
44
+ "read_cpu_features",
45
+ "get_optimal_threads",
46
+ "probe_vulkan_driver",
47
+ # Storage & Integrity
48
+ "get_unified_model_search_dirs",
49
+ "verify_file_sha256",
50
+ "check_disk_space",
51
+ "atomic_replace",
52
+ "download_file_atomic",
53
+ # GPU runtime guard
54
+ "RUNTIME_REQUIRED_CODE",
55
+ "RUNTIME_REQUIRED_EXIT_CODE",
56
+ "AmevaRuntimeRequiredError",
57
+ "require_ameva_runtime",
58
+ "exit_if_runtime_missing",
59
+ "installed_runtime_version",
60
+ ]
ameva_device/env.py ADDED
@@ -0,0 +1,44 @@
1
+ # Copyright (c) 2026 Uno Kim / AMEVA Foundation. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0 OR Commercial-License
3
+ """
4
+ ameva_device.env
5
+ ================
6
+ Authoritative on-device environment diagnostics for Android Termux & Linux environments.
7
+ Open-Source under Apache-2.0.
8
+ """
9
+ import os
10
+ from pathlib import Path
11
+
12
+
13
+ def is_termux() -> bool:
14
+ """Authoritative detection for Android Termux environment."""
15
+ if os.environ.get("TERMUX_VERSION") or os.environ.get("TERMUX_APP_PID"):
16
+ return True
17
+ prefix = os.environ.get("PREFIX", "")
18
+ if "com.termux" in prefix:
19
+ return True
20
+ return Path("/data/data/com.termux").is_dir()
21
+
22
+
23
+ def is_android() -> bool:
24
+ """Check whether running on Android.
25
+
26
+ Within the Termux on-device ecosystem, running in Termux mathematically
27
+ implies execution on the Android platform.
28
+ """
29
+ return is_termux()
30
+
31
+
32
+ def is_proot() -> bool:
33
+ """Check if execution is running inside a PRoot container."""
34
+ if os.environ.get("PROOT_TMP_DIR") or os.environ.get("PROOT"):
35
+ return True
36
+ try:
37
+ mountinfo = Path("/proc/1/mountinfo")
38
+ if mountinfo.exists():
39
+ content = mountinfo.read_text(encoding="utf-8", errors="ignore")
40
+ if "proot" in content.lower():
41
+ return True
42
+ except OSError:
43
+ pass
44
+ return False
@@ -0,0 +1,165 @@
1
+ # Copyright (c) 2026 Uno Kim / AMEVA Foundation. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0 OR Commercial-License
3
+ """
4
+ ameva_device.hardware
5
+ =====================
6
+ Authoritative hardware telemetry and capability detection for on-device accelerators.
7
+ Zero synthetic metrics, strict Linux/Android and cross-platform detection.
8
+ Open-Source under Apache-2.0.
9
+ """
10
+ import logging
11
+ import os
12
+ import platform
13
+ import shutil
14
+ import sys
15
+ from pathlib import Path
16
+ from typing import Dict, Optional, Tuple
17
+
18
+ logger = logging.getLogger("ameva_device.hardware")
19
+
20
+
21
+ def get_memory_info() -> Tuple[Optional[float], Optional[float]]:
22
+ """Get total and available RAM in megabytes without synthetic metric stubs.
23
+
24
+ Returns:
25
+ Tuple of (total_ram_mb, available_ram_mb), or (None, None) if undetectable.
26
+ """
27
+ total_mb: Optional[float] = None
28
+ avail_mb: Optional[float] = None
29
+
30
+ # 1. Linux / Android /proc/meminfo (SSOT for mobile Linux & Termux)
31
+ if os.path.exists("/proc/meminfo"):
32
+ try:
33
+ with open("/proc/meminfo", "r", encoding="utf-8", errors="ignore") as f:
34
+ for line in f:
35
+ parts = line.split()
36
+ if len(parts) >= 2:
37
+ if parts[0] == "MemTotal:":
38
+ total_mb = float(parts[1]) / 1024.0
39
+ elif parts[0] in ("MemAvailable:", "MemFree:"):
40
+ if avail_mb is None or parts[0] == "MemAvailable:":
41
+ avail_mb = float(parts[1]) / 1024.0
42
+ if total_mb is not None and avail_mb is not None:
43
+ return round(total_mb, 1), round(avail_mb, 1)
44
+ except Exception as e:
45
+ logger.debug("[ameva-device] /proc/meminfo read failed: %s", e)
46
+
47
+ # 2. Windows GlobalMemoryStatusEx via ctypes
48
+ if sys.platform == "win32":
49
+ try:
50
+ import ctypes
51
+
52
+ class MEMORYSTATUSEX(ctypes.Structure):
53
+ _fields_ = [
54
+ ("dwLength", ctypes.c_ulong),
55
+ ("dwMemoryLoad", ctypes.c_ulong),
56
+ ("ullTotalPhys", ctypes.c_ulonglong),
57
+ ("ullAvailPhys", ctypes.c_ulonglong),
58
+ ("ullTotalPageFile", ctypes.c_ulonglong),
59
+ ("ullAvailPageFile", ctypes.c_ulonglong),
60
+ ("ullTotalVirtual", ctypes.c_ulonglong),
61
+ ("ullAvailVirtual", ctypes.c_ulonglong),
62
+ ("sullAvailExtendedVirtual", ctypes.c_ulonglong),
63
+ ]
64
+
65
+ stat = MEMORYSTATUSEX()
66
+ stat.dwLength = ctypes.sizeof(MEMORYSTATUSEX)
67
+ if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat)):
68
+ return round(stat.ullTotalPhys / (1024.0 * 1024.0), 1), round(stat.ullAvailPhys / (1024.0 * 1024.0), 1)
69
+ except Exception as e:
70
+ logger.debug("[ameva-device] Windows memory detection failed: %s", e)
71
+
72
+ # 3. macOS / POSIX sysconf
73
+ if hasattr(os, "sysconf"):
74
+ try:
75
+ phys_pages = os.sysconf("SC_PHYS_PAGES")
76
+ page_size = os.sysconf("SC_PAGE_SIZE")
77
+ if phys_pages > 0 and page_size > 0:
78
+ tot = (phys_pages * page_size) / (1024.0 * 1024.0)
79
+ return round(tot, 1), round(tot * 0.5, 1)
80
+ except (ValueError, OSError) as e:
81
+ logger.debug("[ameva-device] POSIX sysconf memory detection failed: %s", e)
82
+
83
+ return total_mb, avail_mb
84
+
85
+
86
+ def read_cpu_features() -> Dict[str, bool]:
87
+ """Read CPU microarchitecture features from /proc/cpuinfo and architecture detection.
88
+
89
+ Returns:
90
+ Dict mapping feature names ('neon', 'fp16', 'dotprod') to boolean availability.
91
+ """
92
+ machine = platform.machine().lower()
93
+ is_arm = "arm64" in machine or "aarch64" in machine
94
+
95
+ features = {
96
+ "neon": is_arm,
97
+ "fp16": False,
98
+ "dotprod": False,
99
+ }
100
+
101
+ if os.path.exists("/proc/cpuinfo"):
102
+ try:
103
+ with open("/proc/cpuinfo", "r", encoding="utf-8", errors="ignore") as f:
104
+ content = f.read().lower()
105
+ features["neon"] = features["neon"] or ("neon" in content or "asimd" in content)
106
+ features["fp16"] = "fp16" in content or "fphp" in content or "asimdhp" in content
107
+ features["dotprod"] = "dotprod" in content or "asimddp" in content
108
+ except Exception as e:
109
+ logger.debug("[ameva-device] /proc/cpuinfo read failed: %s", e)
110
+
111
+ return features
112
+
113
+
114
+ def get_optimal_threads(cores: Optional[int] = None) -> int:
115
+ """Calculate recommended compute thread count balancing throughput and thermal/UI stability.
116
+
117
+ Heuristic:
118
+ - 8+ cores (typical big.LITTLE mobile SoC): 4 threads (allocates to performance cluster)
119
+ - 6 cores: 4 threads
120
+ - 4 cores: 3 threads
121
+ - <4 cores: max(1, cores)
122
+ """
123
+ if cores is None or cores <= 0:
124
+ cores = os.cpu_count() or 4
125
+
126
+ if cores >= 8:
127
+ return 4
128
+ if cores >= 6:
129
+ return 4
130
+ if cores >= 4:
131
+ return min(3, cores)
132
+ return max(1, cores)
133
+
134
+
135
+ def probe_vulkan_driver() -> Tuple[bool, Optional[str]]:
136
+ """Probe for usable Vulkan driver across Android system libraries and Termux prefix.
137
+
138
+ Returns:
139
+ Tuple of (is_available: bool, driver_description: Optional[str])
140
+ """
141
+ vulkan_candidates = [
142
+ ("/system/lib64/libvulkan.so", "Android System 64-bit Vulkan Driver"),
143
+ ("/vendor/lib64/hw/vulkan.adreno.so", "Qualcomm Adreno Vulkan Driver"),
144
+ ("/vendor/lib64/libvulkan.so", "Vendor 64-bit Vulkan Driver"),
145
+ ("/system/lib/libvulkan.so", "Android System 32-bit Vulkan Driver"),
146
+ ("/vendor/lib/hw/vulkan.adreno.so", "Qualcomm Adreno 32-bit Vulkan Driver"),
147
+ ("/data/data/com.termux/files/usr/lib/libvulkan.so", "Termux Userland Vulkan Driver"),
148
+ ]
149
+
150
+ for lib_path, desc in vulkan_candidates:
151
+ if Path(lib_path).exists():
152
+ return True, desc
153
+
154
+ if shutil.which("vulkaninfo") is not None:
155
+ return True, "Generic Vulkan Driver (vulkaninfo available)"
156
+
157
+ try:
158
+ from ameva_runtime import vulkan as avr
159
+ report = avr.Doctor().run_self_test(verbose=False)
160
+ if report.overall_success or report.recommended_backend in ("vulkan", "vulkan_driver_only"):
161
+ return True, f"AMEVA-Runtime Vulkan Driver ({report.device_name})"
162
+ except Exception:
163
+ pass
164
+
165
+ return False, None
@@ -0,0 +1,119 @@
1
+ # Copyright (c) 2026 Uno Kim / AMEVA Foundation. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0 OR Commercial-License
3
+ """
4
+ Runtime guard for GPU-requiring features.
5
+
6
+ Every termux-* package runs on the CPU by itself. GPU execution is provided by
7
+ ``amv-runtime`` (AMUDA). When a GPU run is requested and the runtime is missing
8
+ or too old, the process must stop with an explicit error that explains how to
9
+ install it. It must not continue on the CPU without telling the user.
10
+
11
+ Detection only checks that the runtime package is importable and at least the
12
+ requested version. It does not prove that a GPU device works; use
13
+ ``ameva-run doctor`` for that.
14
+ """
15
+
16
+ import importlib
17
+ import importlib.util
18
+ import re
19
+ import sys
20
+ from typing import Optional, Tuple
21
+
22
+ RUNTIME_REQUIRED_CODE = "AMU_ERR_RUNTIME_REQUIRED"
23
+ # Exit status used by command-line entry points (sysexits EX_UNAVAILABLE).
24
+ RUNTIME_REQUIRED_EXIT_CODE = 69
25
+ DEFAULT_MIN_VERSION = "2.0.0"
26
+ RUNTIME_PYPI_NAME = "amv-runtime"
27
+ RUNTIME_NPM_NAME = "amv-runtime"
28
+ RUNTIME_RELEASES_URL = "https://github.com/uno-km/amv-runtime-releases"
29
+
30
+
31
+ def parse_version(text: str) -> Tuple[int, ...]:
32
+ """Return the leading numeric components of a version string, e.g. '2.8.1rc1' -> (2, 8, 1)."""
33
+ parts = []
34
+ for piece in str(text).strip().split("."):
35
+ match = re.match(r"\d+", piece)
36
+ if not match:
37
+ break
38
+ parts.append(int(match.group(0)))
39
+ return tuple(parts)
40
+
41
+
42
+ def installed_runtime_version() -> Optional[str]:
43
+ """Return the installed amv-runtime version string, or None when it is not importable."""
44
+ try:
45
+ if importlib.util.find_spec("ameva_runtime") is None:
46
+ return None
47
+ module = importlib.import_module("ameva_runtime")
48
+ except (ImportError, ValueError, AttributeError):
49
+ return None
50
+ version = getattr(module, "__version__", None)
51
+ return str(version) if version else "unknown"
52
+
53
+
54
+ def runtime_required_message(component: str, feature: str, min_version: str,
55
+ found: Optional[str]) -> str:
56
+ """Build the user-facing explanation. Plain ASCII so that every terminal renders it."""
57
+ if found is None:
58
+ state = "amv-runtime is not installed."
59
+ elif found == "unknown":
60
+ state = "amv-runtime is installed but its version could not be read (need >= %s)." % min_version
61
+ else:
62
+ state = "amv-runtime %s is installed, but >= %s is required." % (found, min_version)
63
+ return (
64
+ "[{code}] {component}: '{feature}' needs the AMEVA GPU runtime.\n"
65
+ "{state}\n"
66
+ "Nothing was run, and no CPU fallback was used.\n"
67
+ "\n"
68
+ "What is AMUDA / amv-runtime:\n"
69
+ " AMUDA is AMEVA's GPU compute layer for Android phones (Vulkan and OpenCL on\n"
70
+ " Adreno and Mali GPUs). It ships inside amv-runtime and runs the model kernels\n"
71
+ " on the phone's GPU. Without it this tool can only run on the CPU.\n"
72
+ "\n"
73
+ "Install:\n"
74
+ " pip: pip install \"{pypi}>={minv}\"\n"
75
+ " npm: npm install -g {npm}\n"
76
+ " check: ameva-run doctor\n"
77
+ " Releases and documentation: {url}\n"
78
+ "\n"
79
+ "To run on the CPU instead, request it explicitly (for example --device cpu).\n"
80
+ ).format(code=RUNTIME_REQUIRED_CODE, component=component, feature=feature, state=state,
81
+ pypi=RUNTIME_PYPI_NAME, npm=RUNTIME_NPM_NAME, minv=min_version, url=RUNTIME_RELEASES_URL)
82
+
83
+
84
+ class AmevaRuntimeRequiredError(RuntimeError):
85
+ """Raised when a GPU feature is requested and amv-runtime is missing or too old."""
86
+
87
+ code = RUNTIME_REQUIRED_CODE
88
+
89
+ def __init__(self, component: str, feature: str, min_version: str, found: Optional[str]):
90
+ self.component = component
91
+ self.feature = feature
92
+ self.min_version = min_version
93
+ self.found = found
94
+ super().__init__(runtime_required_message(component, feature, min_version, found))
95
+
96
+
97
+ def require_ameva_runtime(component: str, feature: str = "GPU execution",
98
+ min_version: str = DEFAULT_MIN_VERSION) -> str:
99
+ """Return the installed runtime version, or raise AmevaRuntimeRequiredError.
100
+
101
+ Call this at the start of every code path that was asked to use the GPU.
102
+ """
103
+ found = installed_runtime_version()
104
+ if found is None:
105
+ raise AmevaRuntimeRequiredError(component, feature, min_version, None)
106
+ if found == "unknown" or parse_version(found) < parse_version(min_version):
107
+ raise AmevaRuntimeRequiredError(component, feature, min_version, found)
108
+ return found
109
+
110
+
111
+ def exit_if_runtime_missing(component: str, feature: str = "GPU execution",
112
+ min_version: str = DEFAULT_MIN_VERSION) -> str:
113
+ """Command-line variant: print the explanation to stderr and exit with status 69."""
114
+ try:
115
+ return require_ameva_runtime(component, feature, min_version)
116
+ except AmevaRuntimeRequiredError as err:
117
+ sys.stderr.write(str(err))
118
+ sys.stderr.flush()
119
+ raise SystemExit(RUNTIME_REQUIRED_EXIT_CODE)
@@ -0,0 +1,304 @@
1
+ # Copyright (c) 2026 Uno Kim / AMEVA Foundation. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0 OR Commercial-License
3
+ """
4
+ ameva_device.storage
5
+ ====================
6
+ Authoritative storage, path resolution, and cryptographic verification
7
+ conforming to the AMEVA Ecosystem Shared Storage Specification.
8
+ Open-Source under Apache-2.0.
9
+ """
10
+ import hashlib
11
+ import logging
12
+ import os
13
+ import shutil
14
+ from pathlib import Path
15
+ from typing import List, Optional, Union
16
+
17
+ logger = logging.getLogger("ameva_device.storage")
18
+
19
+
20
+ def get_unified_model_search_dirs(submodule: str = "models") -> List[Path]:
21
+ """Returns multi-tier model search paths adhering to the AMEVA Shared Storage Specification.
22
+
23
+ Enables zero-redundancy model sharing across STT, TTS, LLaMA, Vision, Diffusion, BitNet, etc.
24
+ Order of precedence:
25
+ 1. Custom environment variable override: AMEVA_MODELS_DIR or TERMUX_{SUBMODULE}_MODELS_DIR
26
+ 2. Primary user home paths and Termux prefix paths
27
+ 3. Multi-tier shared directories (models, ameva-models, .cache/ameva/models, .cache/termux-{submodule}/models)
28
+
29
+ Args:
30
+ submodule: Subsystem name, e.g. "stt", "tts", "llama", "vision", "diffusion", "bitnet".
31
+
32
+ Returns:
33
+ List of candidate Path objects deduplicated while preserving precedence.
34
+ """
35
+ dirs: List[Path] = []
36
+ clean_submodule = submodule.lower().strip()
37
+
38
+ # 1. Custom ENV override
39
+ env_sub_override = os.environ.get(f"TERMUX_{clean_submodule.upper()}_MODELS_DIR")
40
+ if env_sub_override:
41
+ dirs.append(Path(env_sub_override))
42
+
43
+ env_dir = os.environ.get("AMEVA_MODELS_DIR")
44
+ if env_dir:
45
+ p = Path(env_dir)
46
+ dirs.extend([p / clean_submodule, p])
47
+
48
+ # 2. Candidate prefixes (User Home + Termux $PREFIX/../home if different)
49
+ home = Path.home()
50
+ prefixes = [home]
51
+ prefix_env = os.environ.get("PREFIX")
52
+ if prefix_env:
53
+ termux_home = Path(prefix_env).parent / "home"
54
+ if termux_home != home:
55
+ prefixes.append(termux_home)
56
+
57
+ for base in prefixes:
58
+ dirs.extend([
59
+ base / "models" / clean_submodule,
60
+ base / "models",
61
+ base / "ameva-models" / clean_submodule,
62
+ base / "ameva-models",
63
+ base / ".cache" / "ameva" / "models" / clean_submodule,
64
+ base / ".cache" / "ameva" / "models",
65
+ base / ".cache" / f"termux-{clean_submodule}" / "models",
66
+ base / f".termux-{clean_submodule}" / "models",
67
+ ])
68
+
69
+ # Termux shared package data dir
70
+ if prefix_env:
71
+ dirs.append(Path(prefix_env) / "share" / f"termux-{clean_submodule}" / "models")
72
+
73
+ # Deduplicate while strictly preserving precedence order
74
+ seen = set()
75
+ unique_dirs = []
76
+ for d in dirs:
77
+ resolved = str(d.resolve()) if d.exists() else str(d)
78
+ if resolved not in seen:
79
+ seen.add(resolved)
80
+ unique_dirs.append(d)
81
+
82
+ return unique_dirs
83
+
84
+
85
+ def verify_file_sha256(
86
+ file_path: Union[str, Path],
87
+ expected_sha256: str,
88
+ block_size: int = 65536,
89
+ ) -> bool:
90
+ """Validate a file's SHA-256 checksum against an expected hash in constant memory.
91
+
92
+ Args:
93
+ file_path: Path to the target file.
94
+ expected_sha256: Expected hexadecimal SHA-256 hash.
95
+ block_size: Buffer block size in bytes (default: 64 KiB).
96
+
97
+ Returns:
98
+ True if the file exists and its hash matches; False otherwise.
99
+ """
100
+ target = Path(file_path)
101
+ if not target.is_file():
102
+ return False
103
+
104
+ clean_expected = expected_sha256.strip().lower()
105
+ hasher = hashlib.sha256()
106
+
107
+ try:
108
+ with open(target, "rb") as f:
109
+ while chunk := f.read(block_size):
110
+ hasher.update(chunk)
111
+ return hasher.hexdigest().lower() == clean_expected
112
+ except (OSError, ValueError) as e:
113
+ logger.debug("[ameva-device] Hash computation failed for %s: %s", target, e)
114
+ return False
115
+
116
+
117
+ def check_disk_space(target_path: Union[str, Path], required_bytes: int) -> bool:
118
+ """Verify whether the disk partition holding target_path has at least required_bytes available.
119
+
120
+ Args:
121
+ target_path: File or directory path to check partition for.
122
+ required_bytes: Minimum required free storage in bytes.
123
+
124
+ Returns:
125
+ True if free disk space >= required_bytes, False otherwise.
126
+ """
127
+ target = Path(target_path)
128
+ check_dir = target if target.is_dir() else target.parent
129
+ try:
130
+ check_dir.mkdir(parents=True, exist_ok=True)
131
+ usage = shutil.disk_usage(check_dir)
132
+ return usage.free >= required_bytes
133
+ except OSError:
134
+ return False
135
+
136
+
137
+ def atomic_replace(temp_path: Union[str, Path], target_path: Union[str, Path]) -> None:
138
+ """Safely and atomically replace target_path with temp_path.
139
+
140
+ Ensures parent directories exist before replacing.
141
+
142
+ Args:
143
+ temp_path: Path to temporary source file.
144
+ target_path: Path to final destination file.
145
+ """
146
+ src = Path(temp_path)
147
+ dst = Path(target_path)
148
+ dst.parent.mkdir(parents=True, exist_ok=True)
149
+ os.replace(src, dst)
150
+
151
+
152
+ def download_file_atomic(
153
+ url: str,
154
+ dest_path: Union[str, Path],
155
+ expected_sha256: Optional[str] = None,
156
+ expected_size: Optional[int] = None,
157
+ chunk_size: int = 1024 * 1024,
158
+ force: bool = False,
159
+ show_progress: bool = True,
160
+ user_agent: Optional[str] = None,
161
+ timeout: float = 30.0,
162
+ ) -> Path:
163
+ """Authoritative on-device atomic model/artifact downloader template.
164
+
165
+ Conforms to OpenSSF Zero-Corruption and BigTech atomic rename standards:
166
+ 1. Fast-Skip: If target exists and hash/size is valid, return immediately without network overhead.
167
+ 2. Isolation: Writes only to dest.part during streaming.
168
+ 3. Resume: Resumes partial downloads via HTTP Range headers.
169
+ 4. Verification: Streaming SHA-256 and byte-size checks before replacing destination.
170
+ 5. Atomic: Uses os.replace() so the destination file is never visible in an incomplete state.
171
+
172
+ Args:
173
+ url: Direct HTTP(S) remote download URL.
174
+ dest_path: Final destination path.
175
+ expected_sha256: Optional SHA-256 hexadecimal hash to verify.
176
+ expected_size: Optional expected byte length.
177
+ chunk_size: Streaming chunk size in bytes (default: 1 MiB).
178
+ force: If True, re-download even if already present.
179
+ show_progress: If True, display streaming progress.
180
+ user_agent: Custom User-Agent header string.
181
+ timeout: Socket timeout in seconds.
182
+
183
+ Returns:
184
+ Path: Resolved destination Path object.
185
+ """
186
+ import sys
187
+ dest = Path(dest_path).resolve()
188
+
189
+ # 1. Fast-Skip validation
190
+ if not force and dest.is_file():
191
+ if expected_sha256:
192
+ if verify_file_sha256(dest, expected_sha256):
193
+ return dest
194
+ elif expected_size is not None and expected_size > 0:
195
+ if dest.stat().st_size == expected_size:
196
+ return dest
197
+ elif dest.stat().st_size > 0:
198
+ return dest
199
+
200
+ dest.parent.mkdir(parents=True, exist_ok=True)
201
+ part_path = dest.with_suffix(dest.suffix + ".part")
202
+
203
+ # 2. Check disk space if size is known
204
+ if expected_size:
205
+ if not check_disk_space(dest.parent, expected_size):
206
+ raise OSError(f"Insufficient disk space in {dest.parent} for {expected_size} bytes.")
207
+
208
+ headers = {}
209
+ if user_agent:
210
+ headers["User-Agent"] = user_agent
211
+ else:
212
+ headers["User-Agent"] = "ameva-device-sdk/0.2.0 (Android; ARM64)"
213
+
214
+ downloaded = 0
215
+ mode = "wb"
216
+
217
+ if part_path.exists() and not force:
218
+ downloaded = part_path.stat().st_size
219
+ if expected_size and downloaded >= expected_size:
220
+ downloaded = 0
221
+ part_path.unlink(missing_ok=True)
222
+ else:
223
+ headers["Range"] = f"bytes={downloaded}-"
224
+ mode = "ab"
225
+
226
+ # Try requests first for robust chunking / connection pooling
227
+ use_requests = False
228
+ try:
229
+ import requests
230
+ use_requests = True
231
+ except ImportError:
232
+ pass
233
+
234
+ if use_requests:
235
+ resp = requests.get(url, headers=headers, stream=True, timeout=timeout)
236
+ if resp.status_code == 416: # Range Not Satisfiable -> file already complete or server changed
237
+ downloaded = 0
238
+ mode = "wb"
239
+ headers.pop("Range", None)
240
+ resp = requests.get(url, headers=headers, stream=True, timeout=timeout)
241
+
242
+ if resp.status_code not in (200, 206):
243
+ part_path.unlink(missing_ok=True)
244
+ raise RuntimeError(f"HTTP {resp.status_code} downloading {url}: {resp.text[:200]}")
245
+
246
+ total_bytes = None
247
+ cl = resp.headers.get("Content-Length")
248
+ if cl and cl.isdigit():
249
+ total_bytes = int(cl) + (downloaded if resp.status_code == 206 else 0)
250
+
251
+ with open(part_path, mode) as f:
252
+ for chunk in resp.iter_content(chunk_size=chunk_size):
253
+ if chunk:
254
+ f.write(chunk)
255
+ downloaded += len(chunk)
256
+ if show_progress and total_bytes:
257
+ pct = (downloaded / total_bytes) * 100
258
+ sys.stdout.write(f"\r[download] {pct:.1f}% ({downloaded // (1024*1024)}MB / {total_bytes // (1024*1024)}MB)")
259
+ sys.stdout.flush()
260
+ else:
261
+ import urllib.request
262
+ req = urllib.request.Request(url, headers=headers)
263
+ try:
264
+ with urllib.request.urlopen(req, timeout=timeout) as response:
265
+ total_bytes = None
266
+ cl = response.headers.get("Content-Length")
267
+ if cl and cl.isdigit():
268
+ total_bytes = int(cl) + downloaded
269
+
270
+ with open(part_path, mode) as f:
271
+ while True:
272
+ buf = response.read(chunk_size)
273
+ if not buf:
274
+ break
275
+ f.write(buf)
276
+ downloaded += len(buf)
277
+ if show_progress and total_bytes:
278
+ pct = (downloaded / total_bytes) * 100
279
+ sys.stdout.write(f"\r[download] {pct:.1f}% ({downloaded // (1024*1024)}MB / {total_bytes // (1024*1024)}MB)")
280
+ sys.stdout.flush()
281
+ except Exception as e:
282
+ part_path.unlink(missing_ok=True)
283
+ raise RuntimeError(f"Network error downloading {url}: {e}") from e
284
+
285
+ if show_progress:
286
+ sys.stdout.write("\n")
287
+ sys.stdout.flush()
288
+
289
+ # 3. Post-download validations
290
+ if expected_size is not None and expected_size > 0:
291
+ actual_sz = part_path.stat().st_size
292
+ if actual_sz != expected_size:
293
+ part_path.unlink(missing_ok=True)
294
+ raise ValueError(f"Size mismatch: expected {expected_size}, got {actual_sz}")
295
+
296
+ if expected_sha256:
297
+ if not verify_file_sha256(part_path, expected_sha256):
298
+ part_path.unlink(missing_ok=True)
299
+ raise ValueError(f"SHA-256 verification failed for downloaded artifact: {url}")
300
+
301
+ # 4. Atomic Replace
302
+ atomic_replace(part_path, dest)
303
+ return dest
304
+
@@ -0,0 +1,148 @@
1
+ Metadata-Version: 2.4
2
+ Name: amv-device-sdk
3
+ Version: 0.2.1
4
+ Summary: Lightweight on-device hardware, environment, unified cache and storage foundation for Android Termux & ARM64
5
+ Author-email: "uno-km (AMEVA Foundation)" <amv.foundation.kr@gmail.com>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/uno-km/amv-device-sdk
8
+ Project-URL: Repository, https://github.com/uno-km/amv-device-sdk
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Operating System :: POSIX :: Linux
13
+ Classifier: Operating System :: Android
14
+ Classifier: Programming Language :: Python :: 3
15
+ Requires-Python: >=3.8
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Dynamic: license-file
19
+
20
+ # amv-device-sdk
21
+
22
+ > Authoritative on-device telemetry, capability probing, and shared storage foundation for the AMEVA & Android Termux ecosystem.
23
+
24
+ [![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
25
+ [![Python](https://img.shields.io/badge/Python-3.9+-3776AB.svg?logo=python&logoColor=white)](https://www.python.org/)
26
+ [![Node.js](https://img.shields.io/badge/Node.js-16+-339933.svg?logo=node.js&logoColor=white)](https://nodejs.org/)
27
+
28
+ ---
29
+
30
+ ## Architecture & Purpose
31
+
32
+ `amv-device-sdk` serves as the Single Source of Truth (SSOT) foundation across all submodules in the `uno-km/termux` and `uno-km/ameva` ecosystems (including `termux-llamacpp`, `termux-vision`, `termux-diffusion`, `termux-tts`, `termux-stt`, `termux-bitnet`, and `termux-playwright`).
33
+
34
+ It eliminates cross-project fragmentation (AST drift) by unifying:
35
+ 1. **Environment Diagnostics**: Authoritative `is_termux()`, `is_android()`, `is_proot()`.
36
+ 2. **Hardware Telemetry**: Direct `/proc/meminfo` RAM detection, ARM64 feature flags (`neon`, `fp16`, `dotprod`), Vulkan ICD discovery, and thermal/compute thread heuristics.
37
+ 3. **Storage & Verification**: Multi-tier directory resolution according to the *AMEVA Shared Storage Specification*, streaming SHA-256 integrity checks, and atomic file replacements.
38
+ 4. **Dual-Engine ABI**: 100% functional parity between Python (`ameva_device`) and Node.js (`ameva-device-sdk`).
39
+
40
+ ---
41
+
42
+ ## Installation
43
+
44
+ ### Python
45
+ ```bash
46
+ pip install amv-device-sdk
47
+ # or within editable development mode:
48
+ pip install -e ./dev/ameva/ameva-device-sdk
49
+ ```
50
+
51
+ ### Node.js
52
+ ```bash
53
+ npm install amv-device-sdk
54
+ # or link locally:
55
+ npm link ./dev/ameva/ameva-device-sdk
56
+ ```
57
+
58
+ ---
59
+
60
+ ## API Specification
61
+
62
+ ### 1. Python API (`import ameva_device as dev`)
63
+
64
+ ```python
65
+ import ameva_device as dev
66
+
67
+ # Environment
68
+ is_termux: bool = dev.is_termux()
69
+ is_android: bool = dev.is_android()
70
+ is_proot: bool = dev.is_proot()
71
+
72
+ # Hardware Telemetry
73
+ total_mb, avail_mb = dev.get_memory_info()
74
+ features: dict[str, bool] = dev.read_cpu_features() # {'neon': bool, 'fp16': bool, 'dotprod': bool}
75
+ threads: int = dev.get_optimal_threads()
76
+ has_vulkan, desc = dev.probe_vulkan_driver()
77
+
78
+ # Storage & Cryptographic Verification
79
+ search_dirs = dev.get_unified_model_search_dirs(submodule="vision")
80
+ is_valid = dev.verify_file_sha256("model.bin", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
81
+ dev.atomic_replace("model.bin.tmp", "model.bin")
82
+ ```
83
+
84
+ ### 2. JavaScript / TypeScript API (`const dev = require('amv-device-sdk')`)
85
+
86
+ ```typescript
87
+ import {
88
+ isTermux,
89
+ isAndroid,
90
+ isProot,
91
+ getMemoryInfo,
92
+ readCpuFeatures,
93
+ getOptimalThreads,
94
+ probeVulkanDriver,
95
+ getUnifiedModelSearchDirs,
96
+ verifyFileSha256,
97
+ verifyFileSha256Sync,
98
+ atomicReplace,
99
+ } from 'amv-device-sdk';
100
+
101
+ // Hardware Telemetry
102
+ const { totalMb, availableMb } = getMemoryInfo();
103
+ const { neon, fp16, dotprod } = readCpuFeatures();
104
+ const optimalThreads = getOptimalThreads();
105
+
106
+ // Storage Resolution
107
+ const searchDirs: string[] = getUnifiedModelSearchDirs('llamacpp');
108
+
109
+ // Cryptographic Verification
110
+ const valid = await verifyFileSha256('model.gguf', '<sha256_hash>');
111
+ ```
112
+
113
+ ### GPU runtime guard (0.2.0)
114
+
115
+ The termux-* packages run on the CPU by themselves. GPU execution comes from `amv-runtime`
116
+ (AMUDA). Call the guard at the start of every code path that was asked to use the GPU. If the
117
+ runtime is missing or too old, it stops with `AMU_ERR_RUNTIME_REQUIRED`, explains what AMUDA is,
118
+ and prints how to install it. It never falls back to the CPU.
119
+
120
+ ```python
121
+ from ameva_device import require_ameva_runtime, exit_if_runtime_missing
122
+
123
+ version = require_ameva_runtime("termux-bitnet", "GPU inference", min_version="2.8.0") # raises
124
+ exit_if_runtime_missing("termux-bitnet", "GPU inference") # CLI: message on stderr, exit status 69
125
+ ```
126
+
127
+ ```javascript
128
+ const { requireAmevaRuntime, exitIfRuntimeMissing } = require('amv-device-sdk');
129
+ requireAmevaRuntime('termux-bitnet', 'GPU inference', { minVersion: '2.8.0' }); // throws AmevaRuntimeRequiredError
130
+ exitIfRuntimeMissing('termux-bitnet', 'GPU inference'); // CLI: message on stderr, exit status 69
131
+ ```
132
+
133
+ The check confirms that the package is installed at the requested version. It does not prove that
134
+ a GPU works; run `ameva-run doctor` for that.
135
+
136
+ ---
137
+
138
+ ## Verification & Compliance
139
+
140
+ All interfaces are strictly validated against:
141
+ - Automated regression test suites (`python tests/test_device.py`, `node tests/test_device.js`).
142
+ - OpenSSF best practices, zero synthetic stubs, and strict Linux ABI specifications.
143
+
144
+ ---
145
+
146
+ ## License
147
+
148
+ Apache License 2.0. Copyright (c) 2026 uno-km / AMEVA Systems Team.
@@ -0,0 +1,10 @@
1
+ ameva_device/__init__.py,sha256=boFBR4LnCJzSx_04AopFa6xGwQ1F66UknO6saI0_hwo,1540
2
+ ameva_device/env.py,sha256=mB-ErFN9tZvKpDo8rlvMyXwPzCoPedurQ6OKTNHPN_o,1394
3
+ ameva_device/hardware.py,sha256=EYqrnis2sHXp7RGEOPE9wN_14a6tOF5WVROYQIUO-UE,6587
4
+ ameva_device/runtime_guard.py,sha256=G4wDF7OVBDuTXOpGxyoZ-qME4rHjYkx1XEaIBHkVSaE,5057
5
+ ameva_device/storage.py,sha256=tQ2Kb5i6SYxXQx3p_WMthYVxS6TOMsGSC0ioPDtkr3o,11494
6
+ amv_device_sdk-0.2.1.dist-info/licenses/LICENSE,sha256=GSw08gS8vswNqc7yPNcD192N6f5-l66jMI3z8B6D44k,10352
7
+ amv_device_sdk-0.2.1.dist-info/METADATA,sha256=kT7YlobvSIx0CsqXXZbgEgRWsEdi3LqW31kHPSoYVOE,5575
8
+ amv_device_sdk-0.2.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
9
+ amv_device_sdk-0.2.1.dist-info/top_level.txt,sha256=yE10RnUiNJ21URxInOKEifIDAolG5uwh_4sYZTkskqs,13
10
+ amv_device_sdk-0.2.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,176 @@
1
+  Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1 @@
1
+ ameva_device