M5: camera expression cues via MediaPipe Face Landmarker

- CameraX ImageAnalysis + Face Landmarker (CPU, 10Hz, KEEP_ONLY_LATEST)
- Rule-based blendshape mapping: smiling/brow_furrowed/gaze/blink/face_presence
- Camera off by default, explicit user toggle, no image storage/upload
- Expression cues displayed as passive labels, never affect dialogue flow
- CameraX pinned 1.4.2 (compileSdk 34 compat), MediaPipe tasks-vision 1.1.0
- Face model bundled: face_landmarker.task (sha256 TOFU recorded)
- docs/EXPRESSION.md with rules table and privacy notes
- Version 0.2.0-m5
This commit is contained in:
zenord
2026-10-11 08:40:51 +08:00
parent 07d5f77808
commit f1da7abf93
18 changed files with 1612 additions and 21 deletions
+1
View File
@@ -4,6 +4,7 @@ set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
source /home/ubuntu/android-build/env.sh
cd "$ROOT"
./scripts/prepare-expression.sh
if [ $# -eq 0 ]; then set -- assembleDebug; fi
TS=$(date +%Y%m%d-%H%M%S)
./gradlew --console=plain "$@" 2>&1 | tee "logs/build-$TS.log"
+32
View File
@@ -0,0 +1,32 @@
#!/bin/bash
# Pure Kotlin synthetic-rule checks, no Gradle daemon, CAMERA, network or new dependencies.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
source /home/ubuntu/android-build/env.sh
cd "$ROOT"
python3 - <<'PY'
from pathlib import Path
import os
import subprocess
import tempfile
cache = Path(os.environ['GRADLE_USER_HOME']) / 'caches/modules-2/files-2.1'
def jar(group, name, version):
return str(next((cache / group / name / version).glob('*/*.jar')))
stdlib = jar('org.jetbrains.kotlin', 'kotlin-stdlib', '2.0.20')
compiler = ':'.join([
jar('org.jetbrains.kotlin', 'kotlin-compiler-embeddable', '2.0.20'), stdlib,
jar('org.jetbrains.kotlin', 'kotlin-reflect', '1.6.10'),
jar('org.jetbrains.kotlin', 'kotlin-script-runtime', '2.0.20'),
jar('org.jetbrains.intellij.deps', 'trove4j', '1.0.20200330'),
jar('org.jetbrains', 'annotations', '23.0.0'),
str(next((cache / 'org.jetbrains.kotlinx/kotlinx-coroutines-core-jvm').glob('*/*/*.jar'))),
])
java = str(Path(os.environ['JAVA_HOME']) / 'bin/java')
with tempfile.TemporaryDirectory(prefix='lan-voice-expression-check-') as output:
subprocess.run([java, '-cp', compiler, 'org.jetbrains.kotlin.cli.jvm.K2JVMCompiler',
'-no-stdlib', '-no-reflect', '-jvm-target', '17', '-classpath', stdlib, '-d', output,
'app/src/main/java/com/gorios/lanvoice/expression/ExpressionRules.kt',
'tests/expression/ExpressionRulesCheck.kt'], check=True)
subprocess.run([java, '-cp', output + ':' + stdlib, 'ExpressionRulesCheckKt'], check=True)
PY
+98
View File
@@ -0,0 +1,98 @@
"""Build inputs only. Never handles camera frames, blendshapes or user data."""
import hashlib
import re
import tempfile
import urllib.request
import xml.etree.ElementTree as ET
import zipfile
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
VERSIONS = ROOT / "gradle/expression-versions.properties"
MODEL = ROOT / "app/src/main/assets/face_landmarker.task"
MODEL_HASH = ROOT / "gradle/face-landmarker-model.sha256"
MODEL_URL = (
"https://storage.googleapis.com/mediapipe-models/face_landmarker/"
"face_landmarker/float16/1/face_landmarker.task"
)
GOOGLE_MAVEN = "https://dl.google.com/dl/android/maven2"
def fetch(url):
request = urllib.request.Request(url, headers={"User-Agent": "lan-voice-build/0.2"})
with urllib.request.urlopen(request, timeout=60) as response:
return response.read()
def stable_versions(path):
root = ET.fromstring(fetch(f"{GOOGLE_MAVEN}/{path}/maven-metadata.xml"))
return {node.text for node in root.findall("versioning/versions/version")
if node.text and re.fullmatch(r"\d+(?:\.\d+){2,}", node.text)}
def newest(versions):
if not versions:
raise RuntimeError("No common stable version found in official Maven metadata")
return max(versions, key=lambda value: tuple(map(int, value.split("."))))
def atomic_write(path, data):
path.parent.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as temporary:
temporary.write(data)
staging = Path(temporary.name)
try:
staging.replace(path)
finally:
staging.unlink(missing_ok=True)
def main():
if not VERSIONS.exists():
mediapipe = newest(stable_versions("com/google/mediapipe/tasks-vision"))
# All four CameraX modules use one common stable version; never use '+' at build time.
modules = ("camera-core", "camera-camera2", "camera-lifecycle", "camera-view")
camera_versions = [stable_versions(f"androidx/camera/{module}") for module in modules]
camera = newest(set.intersection(*camera_versions))
atomic_write(VERSIONS, (
"# Selected from official Google Maven stable versions; keep this file for reproducibility.\n"
f"mediapipe.version={mediapipe}\ncamerax.version={camera}\n"
).encode())
print(f"Pinned tasks-vision {mediapipe}, CameraX {camera}")
else:
values = dict(re.findall(r"^(mediapipe\.version|camerax\.version)=(.+)$",
VERSIONS.read_text(), re.MULTILINE))
if set(values) != {"mediapipe.version", "camerax.version"} or any(
not re.fullmatch(r"\d+(?:\.\d+){2,}", value) for value in values.values()
):
raise RuntimeError("Invalid pinned expression dependency versions")
if not MODEL.exists():
if MODEL_HASH.exists():
# Re-downloading must match the model already accepted for this repository.
expected = MODEL_HASH.read_text().split()[0]
else:
expected = None
data = fetch(MODEL_URL)
digest = hashlib.sha256(data).hexdigest()
if expected and digest != expected:
raise RuntimeError("Downloaded model does not match recorded SHA256")
atomic_write(MODEL, data)
if not zipfile.is_zipfile(MODEL):
raise RuntimeError("face_landmarker.task must be the official task bundle, not an HTML download")
with zipfile.ZipFile(MODEL) as bundle:
if not any("blendshape" in name and name.endswith(".tflite") for name in bundle.namelist()):
raise RuntimeError("Face model bundle is missing its blendshape model")
digest = hashlib.sha256(MODEL.read_bytes()).hexdigest()
if MODEL_HASH.exists():
if MODEL_HASH.read_text().split()[0] != digest:
raise RuntimeError("Packaged face model does not match recorded SHA256")
else:
# First download uses HTTPS TOFU, as with the Gradle dependency metadata.
atomic_write(MODEL_HASH, f"{digest} app/src/main/assets/face_landmarker.task\n".encode())
print(f"Face model ready: {digest}")
if __name__ == "__main__":
main()
+5
View File
@@ -0,0 +1,5 @@
#!/bin/bash
# External-shell bootstrap: pin stable dependencies once and package the official CPU model.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
python3 "$ROOT/scripts/prepare-expression.py"