"""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()