From 81ec554857199b03a9ab6886e399bf5a648dbcb1 Mon Sep 17 00:00:00 2001 From: b3b Date: Thu, 20 Aug 2026 14:23:51 +0200 Subject: [PATCH 01/13] Expand coding agent setup documentation --- examples/coding-agents.md | 73 ++++++++++++++++++++++++++++++--------- 1 file changed, 56 insertions(+), 17 deletions(-) diff --git a/examples/coding-agents.md b/examples/coding-agents.md index 982ead4..e770eed 100644 --- a/examples/coding-agents.md +++ b/examples/coding-agents.md @@ -1,32 +1,71 @@ # Coding agent skills -PythonHere includes a `pythonhere` agent skill with instructions for working -inside the running Kivy and Android application. Its Herethere dependency also -includes a `there-cli` skill for the transport, command syntax, structured -results, and file transfers. +PythonHere gives Python coding agents a live Android runtime to work with. It +includes a `pythonhere` skill for working with the running Kivy application and +Android environment, while its `herethere` dependency provides the `there-cli` +skill for connecting, executing code, and transferring files. + +## Prerequisites + +Install and start PythonHere on the Android device as described in +[Installation](../install.md#remote-side). + +The setup below uses Python 3.10 or newer and +[uv](https://docs.astral.sh/uv/). + +## Create a local workspace + +Create a minimal project and install PythonHere: + +```console +uv init --bare my-pythonhere-project +cd my-pythonhere-project +uv add pythonhere +``` ## Install the skills -After installing PythonHere in your project environment, run -[Library Skills](https://library-skills.io/) from that project: +Run [Library Skills](https://library-skills.io/) from the workspace: ```console uvx library-skills --skill pythonhere --skill there-cli ``` Library Skills links the selected skills into the project's `.agents/skills` -directory. The explicit selectors include `there-cli` even though Herethere is -a transitive dependency, without selecting skills from every transitive -package. Add `--claude` to also install and manage the skills in -`.claude/skills`. +directory. The explicit selectors include `there-cli` from the `herethere` +dependency without selecting skills from other transitive packages. Add +`--claude` to also install and manage the skills in `.claude/skills`. -Run the command again after upgrading PythonHere or Herethere so Library Skills +Run the command again after upgrading PythonHere or `herethere` so Library Skills can check and repair the managed links. -## What the skill uses +## Connect to PythonHere + +Create a `there.env` file in the workspace and fill it with the host, port, +username, and password shown in the PythonHere app's Settings screen. See the +[`there.env` example](commands.md#there-env-example) +for the file format. + +With PythonHere running on the Android device, check the connection: + +```console +uv run there --json ping +``` + +The CLI finds `there.env` in the current directory or a parent directory. See +[The `there` command-line interface](there-cli.md) +for execution, inspection, file-transfer, and troubleshooting commands. + +## What the skills cover + +The [`there-cli` skill](https://github.com/b3b/herethere/blob/master/herethere/.agents/skills/there-cli/SKILL.md) +documents the generic `herethere` connection, CLI syntax, remote execution, +structured results, and file transfers. + +The [`pythonhere` skill](https://github.com/b3b/pythonhere/blob/master/pythonhere/.agents/skills/pythonhere/SKILL.md) +adds PythonHere-specific knowledge about the running Kivy application, Android +environment, and `tools_here` helpers for UI snapshots, runtime information, +and screenshots. -The `pythonhere` skill uses the `there` CLI to execute code and inspect the -running application. It also uses PythonHere's `tools_here` runtime helpers for -UI snapshots, runtime information, and screenshots. See -[The `there` command-line interface](https://herethere.me/pythonhere/examples/there-cli.html) -for the commands and helper examples. +Once `uv run there --json ping` succeeds, the workspace is ready for the coding +agent to use the installed skills with the running PythonHere application. From 251246e3e5520348b88dda270ea82981ac8817db Mon Sep 17 00:00:00 2001 From: b3b Date: Thu, 20 Aug 2026 15:19:08 +0200 Subject: [PATCH 02/13] Update worker execution documentation --- CHANGELOG.rst | 6 +++++ buildozer.spec | 2 +- examples/commands.md | 22 +++++++++++++++++++ examples/there-cli.md | 18 ++++++++------- pyproject.toml | 2 +- pythonhere/.agents/skills/pythonhere/SKILL.md | 19 ++++++++++++---- tests/test_main.py | 16 +++----------- uv.lock | 8 +++---- 8 files changed, 62 insertions(+), 31 deletions(-) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 0354ed3..5de080d 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,6 +1,12 @@ Changelog ========= +0.3.1 +----- + +* Updated ``herethere`` to 0.3.2 and documented the new ``--worker`` option + for blocking or long-running operations in Jupyter and the CLI. + 0.3.0 ----- diff --git a/buildozer.spec b/buildozer.spec index 1396480..9570d1e 100644 --- a/buildozer.spec +++ b/buildozer.spec @@ -37,7 +37,7 @@ requirements = # herethere dependencies asyncssh==2.23.1, python-dotenv==1.2.2, - herethere==0.3.1, + herethere==0.3.2, # asyncssh dependencies cryptography, typing_extensions, diff --git a/examples/commands.md b/examples/commands.md index 294e294..181c3d8 100644 --- a/examples/commands.md +++ b/examples/commands.md @@ -72,6 +72,28 @@ Default action for *%there*, if command is not specified - execute python code. import this ``` +Python code normally runs on the PythonHere application's main thread. For a +slow or blocking operation, use `--worker` so the UI stays responsive. The cell +waits for completion and then displays the buffered output: + +```{code-cell} python +:tags: ["skip-execution"] +%%there --worker +import time + + +def perform_expensive_work(): + """Simulate a blocking operation.""" + time.sleep(1) + print("Work complete") + + +perform_expensive_work() +``` + +Use `--background` instead when the notebook cell should return immediately +while the code continues on a remote worker thread. + ### get Evaluate a Python expression on the remote PythonHere side and return the value to the local notebook. diff --git a/examples/there-cli.md b/examples/there-cli.md index 3b9dba6..ee954d6 100644 --- a/examples/there-cli.md +++ b/examples/there-cli.md @@ -29,20 +29,22 @@ there --json --config /path/to/there.env ping Options for the whole invocation, including `--json`, `--config`, `--timeout`, and `--max-output`, go before the command name. -## Background execution +## Worker execution By default, `run` and `get` execute on the application's main thread. Blocking -or long-running work there can freeze the Kivy UI. Use `--background` to run -such work in a worker thread: +or long-running work there can freeze the Kivy UI. Use `--worker` to run such +work in a worker thread: ```console -there --json run --background long_task.py -there --json get --background "task_done.wait(30)" +there --json run --worker long_task.py +there --json get --worker "task_done.wait(30)" ``` -The CLI remains attached and waits for the background operation to finish. -Direct Kivy UI access must still run on Kivy's main thread. The `tools_here` -helpers described below marshal their own Kivy operations to that thread. +The CLI remains attached and waits for the worker operation to finish. +`run --worker` replays captured output after the code finishes, and +`get --worker` returns the resulting value. Direct Kivy UI access must still +run on Kivy's main thread. The `tools_here` helpers described below marshal +their own Kivy operations to that thread. ## Runtime helpers diff --git a/pyproject.toml b/pyproject.toml index 6f3dd26..e4ed9ad 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -22,7 +22,7 @@ classifiers = [ "Programming Language :: Python :: 3.14", ] dependencies = [ - "herethere[magic]>=0.3.1", + "herethere[magic]>=0.3.2", "ipython", "ipywidgets", "Pillow", diff --git a/pythonhere/.agents/skills/pythonhere/SKILL.md b/pythonhere/.agents/skills/pythonhere/SKILL.md index c7b5c39..43cd1f1 100644 --- a/pythonhere/.agents/skills/pythonhere/SKILL.md +++ b/pythonhere/.agents/skills/pythonhere/SKILL.md @@ -66,9 +66,11 @@ They complement rather than restrict normal Python: These helpers may be called on Kivy's main thread or from a worker. Worker calls are transparently marshaled to Kivy's thread and block that worker until Kivy finishes the operation, normally on its next frame. Continue to prefer normal -foreground `there get` and `there run` for quick UI operations. Background -execution is useful when surrounding work would otherwise block the UI; it does -not make other Kivy access thread-safe. +foreground `there get` and `there run` for quick UI operations. Add `--worker` +to `get` or `run` when surrounding slow or blocking work would otherwise block +the UI. The CLI remains attached, waits for completion, and then returns the +value or captured output. Worker execution does not make other Kivy access +thread-safe. Do not call a worker-marshaled helper while Kivy's main thread is synchronously waiting for that same worker. Neither side can progress in that cross-thread @@ -179,7 +181,9 @@ there --json run --code "from tools_here import pin_shortcut; pin_shortcut('demo - Keep callbacks non-blocking and marshal UI changes to the Kivy thread. 4. For more than a short expression, create a local UTF-8 Python file and run it with `there --json run FILE`. Prefer a file over fragile shell quoting or a - long `--code` value. Keep within the installed CLI's input limit. + long `--code` value. Keep within the installed CLI's input limit. Add + `--worker` for slow or blocking code that should not occupy Kivy's main + thread. 5. Make only the requested live-app mutation. Reuse existing state when practical and provide cleanup helpers for scheduled events, sensors, Bluetooth, MIDI, files, or other held resources. @@ -223,6 +227,13 @@ Run a prepared UI change: there --json run /tmp/pythonhere-ui.py ``` +Run slow or blocking non-UI work without freezing Kivy, while waiting for its +buffered output: + +```console +there --json run --worker /tmp/pythonhere-long-task.py +``` + Verify a named status left by that code: ```console diff --git a/tests/test_main.py b/tests/test_main.py index 3c88b9e..72ce4b7 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -111,7 +111,7 @@ async def test_root_object_is_in_context(capfd, app_instance, there): @pytest.mark.asyncio -async def test_background_snapshot_traverses_widgets_on_main_thread( +async def test_worker_snapshot_traverses_widgets_on_main_thread( app_instance, there, ): @@ -129,18 +129,8 @@ async def test_background_snapshot_traverses_widgets_on_main_thread( ) ) try: - if hasattr(there, "get_background"): - snapshot = await there.get_background("tools_here.snapshot_ui(root)") - runtime = await there.get_background("tools_here.runtime_info(app, root)") - else: - # Herethere 0.3.0 has background execution but predates its - # background value command. Exercise the same worker bridge while - # keeping this integration test compatible with that release. - await there.runcode_background( - "tools_here._test_background_results = " - "(tools_here.snapshot_ui(root), tools_here.runtime_info(app, root))" - ) - snapshot, runtime = await there.get("tools_here._test_background_results") + snapshot = await there.get_worker("tools_here.snapshot_ui(root)") + runtime = await there.get_worker("tools_here.runtime_info(app, root)") ran_on_main_thread = await there.get( "tools_here._test_snapshot_thread == " "__import__('threading').main_thread().ident" diff --git a/uv.lock b/uv.lock index 2c740f7..7715d85 100644 --- a/uv.lock +++ b/uv.lock @@ -613,16 +613,16 @@ wheels = [ [[package]] name = "herethere" -version = "0.3.1" +version = "0.3.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "asyncssh", marker = "sys_platform == 'linux'" }, { name = "click", marker = "sys_platform == 'linux'" }, { name = "python-dotenv", marker = "sys_platform == 'linux'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/65/39/7649caa906504bc73931d4e9d08f992c411f30ecc2c2f90ffe0546177b34/herethere-0.3.1.tar.gz", hash = "sha256:8ea7a682a52cc5b99fdefa70a0f712c16691a633f72f43530c10e979d6c37ceb", size = 60710, upload-time = "2026-08-03T07:06:24.987Z" } +sdist = { url = "https://files.pythonhosted.org/packages/2d/ef/241312c499ea63089cd8133f102322f8d4824d87d70431cfe52b3009c338/herethere-0.3.2.tar.gz", hash = "sha256:24c5e8d319103d0a8dc4fac9b3b267051c1395065d2990a449fa48a7bd2c0844", size = 63022, upload-time = "2026-08-24T16:33:11.802Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/14/dd/bd60a211ceedad92f39a3f0edd3cf29de51afaf0032c33ad7a7cbc4d9146/herethere-0.3.1-py3-none-any.whl", hash = "sha256:26c6638f38d0c03a785efcd607645ffaec4bca0de584d19d3ed55b64d1319c0f", size = 63230, upload-time = "2026-08-03T07:06:24.041Z" }, + { url = "https://files.pythonhosted.org/packages/41/b9/94950a1cb3fd7160d5684f86fb241f160a7e5004b1d02d83efe72ccace00/herethere-0.3.2-py3-none-any.whl", hash = "sha256:aeb24092eaa612d5f1f1ebabd6fa627509ce8d4f02fd6d13e32b218643e457ca", size = 65178, upload-time = "2026-08-24T16:33:10.712Z" }, ] [package.optional-dependencies] @@ -1661,7 +1661,7 @@ docker = [ [package.metadata] requires-dist = [ - { name = "herethere", extras = ["magic"], specifier = ">=0.3.1" }, + { name = "herethere", extras = ["magic"], specifier = ">=0.3.2" }, { name = "ipython" }, { name = "ipywidgets" }, { name = "pillow" }, From 4f944a9d838476f730d04cf865e826b50bb1ae2d Mon Sep 17 00:00:00 2001 From: b3b Date: Wed, 26 Aug 2026 18:36:01 +0200 Subject: [PATCH 03/13] Add LiteRT LM to Android APK build Add a python-for-android recipe for the LiteRT LM API, declare the optional OpenCL native libraries through a p4a build hook, and raise the minimum Android and NDK API levels to 24 for LiteRT compatibility. --- buildozer.spec | 5 ++- p4a_hook.py | 55 +++++++++++++++++++++++++++++++ recipes/litert_lm_api/__init__.py | 32 ++++++++++++++++++ 3 files changed, 91 insertions(+), 1 deletion(-) create mode 100644 p4a_hook.py create mode 100644 recipes/litert_lm_api/__init__.py diff --git a/buildozer.spec b/buildozer.spec index 9570d1e..877a0b3 100644 --- a/buildozer.spec +++ b/buildozer.spec @@ -13,6 +13,7 @@ package.domain = me.herethere source.dir = pythonhere source.include_exts = py,png,kv,rst,rsa,ttf,atlas p4a.local_recipes = ./recipes +p4a.hook = p4a_hook.py # search the version information into the source code version.regex = __version__ = "(.*)" @@ -57,13 +58,15 @@ requirements = idna==3.18, # https://github.com/kivy/python-for-android/issues/3098 filetype==1.2.0, + litert_lm_api==0.16.0, # android specific p4a.branch = v2026.05.09 android.api = 36 -android.minapi = 22 +android.minapi = 24 android.ndk = 28c +android.ndk_api = 24 android.accept_sdk_license = True android.release_artifact = apk diff --git a/p4a_hook.py b/p4a_hook.py new file mode 100644 index 0000000..24f76da --- /dev/null +++ b/p4a_hook.py @@ -0,0 +1,55 @@ +from pathlib import Path + +from pythonforandroid.toolchain import ToolchainCL + + +# LiteRT-LM GPU acceleration uses OpenCL. On Android, the required +# non-NDK native libraries must be declared in the application manifest. +# +# See: +# https://github.com/google-ai-edge/LiteRT-LM/blob/main/docs/api/kotlin/getting_started.md +# +# The libraries are optional so the APK can still be installed on devices +# that do not provide them; GPU availability is handled at runtime. +LITERT_NATIVE_LIBRARIES = """ + + + +""" + + +def after_apk_build(toolchain: ToolchainCL) -> None: + """Add native-library declarations required for LiteRT-LM GPU support.""" + + manifest = Path(toolchain._dist.dist_dir) / "src" / "main" / "AndroidManifest.xml" + + print(f"Patching manifest for LiteRT-LM GPU support: {manifest}") + + if not manifest.exists(): + raise RuntimeError(f"Generated manifest does not exist: {manifest}") + + text = manifest.read_text(encoding="utf-8") + + # libOpenCL.so is used as the marker because this hook always adds + # both LiteRT-LM declarations together. + if 'android:name="libOpenCL.so"' in text: + print("LiteRT-LM native-library declarations already present") + return + + marker = "" + + if marker not in text: + raise RuntimeError(f"Cannot find {marker!r} in {manifest}") + + updated = text.replace( + marker, + LITERT_NATIVE_LIBRARIES + "\n " + marker, + 1, + ) + + manifest.write_text(updated, encoding="utf-8") + print("Added LiteRT-LM GPU native-library declarations") diff --git a/recipes/litert_lm_api/__init__.py b/recipes/litert_lm_api/__init__.py new file mode 100644 index 0000000..4702318 --- /dev/null +++ b/recipes/litert_lm_api/__init__.py @@ -0,0 +1,32 @@ +from pythonforandroid.recipe import PyProjectRecipe + + +class LiteRTLMAPIRecipe(PyProjectRecipe): + """python-for-android recipe for Google's LiteRT-LM Python API.""" + + version = "0.16.0" + + # Distribution name is "litert-lm-api", but the installed Python package + # is imported as "litert_lm". + site_packages_name = "litert_lm" + + # LiteRT-LM Android wheels are built for Android API 23+. + min_ndk_api_support = 23 + + @staticmethod + def get_wheel_platform_tags(arch, ctx): + """Return the wheel platform tag published by LiteRT-LM for this ABI.""" + + # LiteRT-LM currently publishes Android wheels for these two ABIs. + if arch == "arm64-v8a": + return ["android_23_arm64_v8a"] + + if arch == "x86_64": + return ["android_23_x86_64"] + + raise RuntimeError( + f"litert-lm-api does not provide an Android wheel for {arch}" + ) + + +recipe = LiteRTLMAPIRecipe() From 9fea1ec1ca971993941fc0e3abc3eb12b75a98fc Mon Sep 17 00:00:00 2001 From: b3b Date: Sun, 6 Sep 2026 12:36:06 +0200 Subject: [PATCH 04/13] Add ML model helpers and LiteRT usage guidance --- pyproject.toml | 7 + pythonhere/.agents/skills/pythonhere/SKILL.md | 4 +- .../skills/pythonhere/references/litert.md | 121 +++ pythonhere/ml_here/__init__.py | 17 + pythonhere/ml_here/huggingface.py | 998 ++++++++++++++++++ pythonhere/ml_here/storage.py | 145 +++ tests/test_ml_here.py | 416 ++++++++ tests/test_pythonhere_skill.py | 4 +- uv.lock | 19 + 9 files changed, 1729 insertions(+), 2 deletions(-) create mode 100644 pythonhere/.agents/skills/pythonhere/references/litert.md create mode 100644 pythonhere/ml_here/__init__.py create mode 100644 pythonhere/ml_here/huggingface.py create mode 100644 pythonhere/ml_here/storage.py create mode 100644 tests/test_ml_here.py diff --git a/pyproject.toml b/pyproject.toml index e4ed9ad..14fdd16 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -28,6 +28,12 @@ dependencies = [ "Pillow", ] +[project.optional-dependencies] +litert = [ + "litert-lm-api==0.16.0", + "requests", +] + [dependency-groups] dev = [ { include-group = "docker" }, @@ -66,6 +72,7 @@ pythonpath = ["pythonhere"] [tool.setuptools] packages = [ "pythonhere", + "pythonhere.ml_here", "pythonhere.magic_here", "pythonhere.ui_here", ] diff --git a/pythonhere/.agents/skills/pythonhere/SKILL.md b/pythonhere/.agents/skills/pythonhere/SKILL.md index 43cd1f1..0a9c6fd 100644 --- a/pythonhere/.agents/skills/pythonhere/SKILL.md +++ b/pythonhere/.agents/skills/pythonhere/SKILL.md @@ -1,6 +1,6 @@ --- name: pythonhere -description: "Build, inspect, and debug PythonHere applications by executing Python through the `there` CLI in an already-running Kivy/Python-for-Android process. Use when a task targets a PythonHere device or `there.env` connection and involves live Kivy UI, KV language, Android APIs, Pyjnius, permissions, installed Android packages, media/files, Plyer device features, BLE with able, or MIDI with midistream." +description: "Build, inspect, and debug PythonHere applications by executing Python through the `there` CLI in an already-running Kivy/Python-for-Android process. Use when a task targets a PythonHere device or `there.env` connection and involves live Kivy UI, KV language, Android APIs, Pyjnius, permissions, installed Android packages, media/files, Plyer device features, BLE with able, MIDI with midistream, or on-device AI with LiteRT-LM and `.litertlm` models." --- # Operate PythonHere with `there` @@ -40,6 +40,8 @@ when the task depends on it broadly or requires its exact current contents. recording, camera, file selection, GPS, battery, or sensors. - Consult [able.md](references/able.md) for Bluetooth Low Energy work. - Consult [midi.md](references/midi.md) for MIDI or synthesizer work. +- Consult [litert.md](references/litert.md) for PythonHere's ML model helpers + and LiteRT-LM usage. Combine references when a feature genuinely needs details from several concerns; for example, an Android gallery may need permission, MediaStore, and diff --git a/pythonhere/.agents/skills/pythonhere/references/litert.md b/pythonhere/.agents/skills/pythonhere/references/litert.md new file mode 100644 index 0000000..e543826 --- /dev/null +++ b/pythonhere/.agents/skills/pythonhere/references/litert.md @@ -0,0 +1,121 @@ +# ML model helpers for LiteRT + +PythonHere provides `ml_here` for acquiring and locating ML model files. It +does not wrap LiteRT-LM inference. + +All public model helpers return paths as strings (a list of strings for +`discover_models()`), ready to pass to `litert_lm.Engine()`. + +```python +from ml_here import ( + discover_models, + download_hf_model, + model_path, + models_directory, + require_model, +) +``` + +- `models_directory(create=False)` returns PythonHere's model directory. On + Android this is the app-specific external files directory under `models`; on + Linux it is `~/.local/share/pythonhere/models`. +- `model_path(repo_id, filename)` returns the namespaced path for a model. It + does not create directories and rejects unsafe path components. +- `require_model(repo_id, filename)` returns that path when the model is + installed and raises `FileNotFoundError` otherwise. +- `discover_models(extra_directories=(), extensions=".litertlm")` recursively + returns sorted, unique LiteRT-LM model paths from managed storage and any + additional directories. Pass another extension or iterable to select other + formats, or `extensions=None` to include every completed stored artifact. +- `download_hf_model(repo_id, filename, *, revision="main", token=None, + destination=None, progress=None, cancelled=None, overwrite=False, + expected_sha256=None)` downloads a Hugging Face model file of any format. By + default, it stores the file at `model_path(repo_id, filename)`. + +Choose by intent: use `require_model()` to load a known installed model, the +path returned by `download_hf_model()` after a download, and +`discover_models()` only to inventory models whose identities are not already +known. Use `model_path()` when only the expected location is needed. + +Downloads are resumable across restarts and make the final file visible only +after the download completes. Cancellation preserves the partial download for +resuming. Pass a token for private or gated models. The `progress` callback +receives the following interface; use it directly rather than redefining it: + +```python +class DownloadProgress: + repo_id: str + filename: str + destination: str + downloaded: int + total: int | None + elapsed: float + speed_bps: float + fraction: float | None + percent: float | None + speed_mbps: float + remaining: int | None + eta: float | None +``` + +Use `litert_lm` directly to load and run the returned model path. + +## Run an installed model + +Run model loading and inference on a worker (`--worker`) to keep Kivy +responsive. In the app runtime, import model helpers from `ml_here`. + +```python +import litert_lm +from ml_here import require_model + +model_file = require_model( + "litert-community/SmolLM2-135M-Instruct", + "SmolLM2_135M_Instruct.litertlm", +) +engine = litert_lm.Engine(model_file) +try: + with engine.create_conversation(max_output_tokens=128) as conversation: + response = conversation.send_message( + "What is the Kivy framework? Answer in one short paragraph." + ) + text = "".join( + part["text"] + for part in response["content"] + if part.get("type") == "text" + ) + print(text) +finally: + engine.close() +``` + +The conversation closes before the engine, including when inference raises. +For an interactive chat, keep the engine loaded and reuse the conversation +for follow-up messages; close both when the chat is finished. + +`litert_lm.Engine(model_file)` uses CPU by default. For a model and device +that support GPU inference, replace the engine construction above with: + +```python +engine = litert_lm.Engine(model_file, backend=litert_lm.Backend.GPU()) +``` + +## Download first when needed + +If the model is not installed, download it on a worker before inference: + +```python +from ml_here import download_hf_model + +model_file = download_hf_model( + "litert-community/SmolLM2-135M-Instruct", + "SmolLM2_135M_Instruct.litertlm", +) +print(model_file) +``` + +When downloading and loading in the same script, pass the returned +`model_file` directly to `litert_lm.Engine()`. + +See the [upstream Python API](https://github.com/google-ai-edge/LiteRT-LM/tree/main/python) +for streaming, sampling, and multimodal inference. diff --git a/pythonhere/ml_here/__init__.py b/pythonhere/ml_here/__init__.py new file mode 100644 index 0000000..a2b75df --- /dev/null +++ b/pythonhere/ml_here/__init__.py @@ -0,0 +1,17 @@ +"""Acquire, store, index, and discover ML model files for PythonHere.""" + +from .huggingface import download_hf_model +from .storage import ( + discover_models, + model_path, + models_directory, + require_model, +) + +__all__ = ( + "discover_models", + "download_hf_model", + "model_path", + "models_directory", + "require_model", +) diff --git a/pythonhere/ml_here/huggingface.py b/pythonhere/ml_here/huggingface.py new file mode 100644 index 0000000..01ace6e --- /dev/null +++ b/pythonhere/ml_here/huggingface.py @@ -0,0 +1,998 @@ +""" +A small cross-platform Hugging Face Hub downloader designed for PythonHere. + +Uses requests to download public, private, or gated files with persistent resume, +progress callbacks, retries, integrity checks, and atomic completion. This module +implements only the Hub features needed for model downloads; it is not a general +replacement for huggingface_hub. + +Typical use: + + from pythonhere.ml_here import download_hf_model + + path = download_hf_model( + "litert-community/some-model", + "model.tflite", + token=oauth_access_token, + progress=lambda p: print(p.percent, p.speed_mbps), + ) + +For a public model, omit `token`. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import random +import re +import time +from collections.abc import Callable +from dataclasses import asdict, dataclass, field +from http import HTTPStatus +from pathlib import Path +from typing import Any +from urllib.parse import quote + +import requests + +from .storage import model_path + +__all__ = [ + "HFClient", + "DownloadProgress", + "RemoteFile", + "HFError", + "HFAuthError", + "HFGatedError", + "HFNotFoundError", + "HFRateLimitError", + "HFIntegrityError", + "HFCancelled", + "download_hf_model", +] + + +class HFError(RuntimeError): + """Base error for Hugging Face Hub operations.""" + + +class HFAuthError(HFError): + """Authentication is missing, invalid, or insufficient.""" + + +class HFGatedError(HFAuthError): + """The model is gated and this user does not currently have access.""" + + +class HFNotFoundError(HFError): + """Repository, revision, or file was not found.""" + + +class HFRateLimitError(HFError): + """Hugging Face rejected the request because of rate limiting.""" + + +class HFIntegrityError(HFError): + """Downloaded data did not match expected size/hash.""" + + +class HFCancelled(HFError): + """Download was cancelled by the caller.""" + + +@dataclass(frozen=True) +class RemoteFile: + """Remote identity and metadata used to validate a download.""" + + repo_id: str + filename: str + revision: str + size: int | None + etag: str | None + commit: str | None + url: str + + +@dataclass(frozen=True) +class DownloadProgress: + """Byte counts and timing for a download progress notification.""" + + repo_id: str + filename: str + destination: str + downloaded: int + total: int | None + elapsed: float + speed_bps: float + + @property + def fraction(self) -> float | None: + if not self.total: + return None + return min(1.0, self.downloaded / self.total) + + @property + def percent(self) -> float | None: + value = self.fraction + return None if value is None else value * 100.0 + + @property + def speed_mbps(self) -> float: + return self.speed_bps / (1024 * 1024) + + @property + def remaining(self) -> int | None: + if self.total is None: + return None + return max(0, self.total - self.downloaded) + + @property + def eta(self) -> float | None: + remaining = self.remaining + if remaining is None or self.speed_bps <= 0: + return None + return remaining / self.speed_bps + + +@dataclass +class _PartialMeta: + repo_id: str + filename: str + revision: str + etag: str | None + commit: str | None + expected_size: int | None + + +@dataclass +class _ProgressReporter: + remote: RemoteFile + destination: Path + callback: Callable[[DownloadProgress], None] | None + interval: float + started: float = field(init=False, default=0.0) + initial_size: int = field(init=False, default=0) + last_time: float = field(init=False, default=0.0) + last_size: int = field(init=False, default=0) + + def start(self, size: int) -> None: + self.started = self.last_time = time.monotonic() + self.initial_size = self.last_size = size + + def report(self, current: int) -> None: + now = time.monotonic() + if self.callback and ( + now - self.last_time >= self.interval + or (self.remote.size is not None and current >= self.remote.size) + ): + self.callback( + DownloadProgress( + repo_id=self.remote.repo_id, + filename=self.remote.filename, + destination=str(self.destination), + downloaded=current, + total=self.remote.size, + elapsed=now - self.started, + speed_bps=(current - self.last_size) + / max(now - self.last_time, 1e-9), + ) + ) + self.last_time = now + self.last_size = current + + def finish(self) -> None: + if self.callback: + end = time.monotonic() + size = self.destination.stat().st_size + self.callback( + DownloadProgress( + repo_id=self.remote.repo_id, + filename=self.remote.filename, + destination=str(self.destination), + downloaded=size, + total=self.remote.size or size, + elapsed=end - self.started, + speed_bps=(size - self.initial_size) + / max(end - self.started, 1e-9), + ) + ) + + +def _raise_download_error(response: requests.Response, filename: str) -> None: + if response.status_code == HTTPStatus.TOO_MANY_REQUESTS: + raise HFRateLimitError( + f"Hugging Face rate limit exceeded while downloading {filename!r}." + ) + raise HFError(f"HTTP {response.status_code} while downloading {filename!r}.") + + +_BYTES_PER_KIB = 1024 +_SECONDS_PER_MINUTE = 60 +_MINUTES_PER_HOUR = 60 + +_RETRYABLE_STATUS = {408, 425, 429, 500, 502, 503, 504} +_SAFE_ETAG = re.compile(r'^(?:W/)?"?(.*?)"?$') + + +def _clean_etag(value: str | None) -> str | None: + if not value: + return None + value = value.strip() + m = _SAFE_ETAG.match(value) + return m.group(1) if m else value.strip('"') + + +def _int_header( + headers: requests.structures.CaseInsensitiveDict, name: str +) -> int | None: + value = headers.get(name) + if value is None: + return None + try: + return int(value) + except (TypeError, ValueError): + return None + + +def _remote_size(response: requests.Response) -> int | None: + # HF exposes the actual object size through X-Linked-Size for LFS-backed + # files. On a final ranged/CDN response, Content-Range is the strongest + # source. Fall back to ordinary Content-Length. + linked = _int_header(response.headers, "X-Linked-Size") + if linked is not None: + return linked + + content_range = response.headers.get("Content-Range") + if content_range and "/" in content_range: + tail = content_range.rsplit("/", 1)[-1] + if tail != "*": + try: + return int(tail) + except ValueError: + pass + + # Only trust Content-Length when the body is not content-encoded. + encoding = response.headers.get("Content-Encoding", "identity").lower() + if encoding == "identity": + return _int_header(response.headers, "Content-Length") + return None + + +def _retry_after(response: requests.Response) -> float | None: + value = response.headers.get("Retry-After") + if not value: + return None + try: + return max(0.0, float(value)) + except ValueError: + return None + + +def _atomic_json_write(path: Path, data: dict[str, Any]) -> None: + tmp = path.with_name(path.name + ".tmp") + tmp.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8") + os.replace(tmp, path) + + +class HFClient: + """ + Lightweight Hugging Face Hub download client. + + Parameters + ---------- + token: + Hugging Face user token or OAuth access token. Use None for public files. + endpoint: + Hub base URL. Mainly useful for testing or custom Hub-compatible hosts. + user_agent: + Sent on all requests. + timeout: + `(connect_timeout, read_timeout)` passed to requests. + The read timeout is per socket read, not a total download timeout. + chunk_size: + Streaming chunk size. + max_retries: + Retries after transient network/server failures. + backoff: + Base exponential retry delay. + """ + + # Public connection options remain individually configurable. + def __init__( # noqa: PLR0913 + self, + token: str | None = None, + *, + endpoint: str = "https://huggingface.co", + user_agent: str = "pythonhere-hf-downloader/1.0", + timeout: tuple[float, float] = (15.0, 60.0), + chunk_size: int = 1024 * 1024, + max_retries: int = 5, + backoff: float = 1.0, + session: requests.Session | None = None, + ): + # pylint: disable=too-many-arguments + self.token = token + self.endpoint = endpoint.rstrip("/") + self.user_agent = user_agent + self.timeout = timeout + self.chunk_size = chunk_size + self.max_retries = max_retries + self.backoff = backoff + self.session = session or requests.Session() + + def resolve_url(self, repo_id: str, filename: str, revision: str = "main") -> str: + repo = "/".join(quote(part, safe="") for part in repo_id.split("/")) + rev = quote(revision, safe="") + file_path = "/".join(quote(part, safe="") for part in filename.split("/")) + return f"{self.endpoint}/{repo}/resolve/{rev}/{file_path}" + + def raw_url(self, repo_id: str, filename: str, revision: str = "main") -> str: + repo = "/".join(quote(part, safe="") for part in repo_id.split("/")) + rev = quote(revision, safe="") + file_path = "/".join(quote(part, safe="") for part in filename.split("/")) + return f"{self.endpoint}/{repo}/raw/{rev}/{file_path}" + + def model_url(self, repo_id: str) -> str: + return f"{self.endpoint}/{repo_id}" + + def _headers(self, extra: dict[str, str] | None = None) -> dict[str, str]: + # identity matters for reliable byte ranges / sizes. + headers = { + "User-Agent": self.user_agent, + "Accept-Encoding": "identity", + } + if self.token: + headers["Authorization"] = f"Bearer {self.token}" + if extra: + headers.update(extra) + return headers + + def model_info( + self, repo_id: str, *, revision: str | None = None + ) -> dict[str, Any]: + """ + Return raw model metadata from the Hub REST API. + + The response includes useful fields such as `sha`, `gated`, and `siblings`. + """ + repo = "/".join(quote(part, safe="") for part in repo_id.split("/")) + if revision: + rev = quote(revision, safe="") + url = f"{self.endpoint}/api/models/{repo}/revision/{rev}" + else: + url = f"{self.endpoint}/api/models/{repo}" + + response = self._request_with_retry("GET", url, headers=self._headers()) + self._raise_hf_error(response, repo_id=repo_id) + return response.json() + + def list_files(self, repo_id: str, *, revision: str | None = None) -> list[str]: + info = self.model_info(repo_id, revision=revision) + return [ + item["rfilename"] + for item in info.get("siblings", []) + if isinstance(item, dict) and item.get("rfilename") + ] + + def file_info( + self, + repo_id: str, + filename: str, + *, + revision: str = "main", + ) -> RemoteFile: + """ + Resolve a Hub file and return size/ETag/commit metadata without + downloading the body. + """ + url = self.resolve_url(repo_id, filename, revision) + + response = self._request_with_retry( + "HEAD", + url, + headers=self._headers(), + allow_redirects=True, + ) + self._raise_hf_error( + response, + repo_id=repo_id, + filename=filename, + ) + + etag = _clean_etag( + response.headers.get("X-Linked-Etag") or response.headers.get("ETag") + ) + commit = response.headers.get("X-Repo-Commit") + size = _remote_size(response) + + return RemoteFile( + repo_id=repo_id, + filename=filename, + revision=revision, + size=size, + etag=etag, + commit=commit, + # Intentionally expose the stable HF resolve URL, not an expiring + # signed CDN/Xet redirect target. + url=url, + ) + + def git_lfs_info( + self, + repo_id: str, + filename: str, + *, + revision: str = "main", + ) -> dict[str, Any] | None: + """Return SHA-256 and size when the repository stores a Git LFS pointer.""" + + response = self._request_with_retry( + "GET", + self.raw_url(repo_id, filename, revision), + headers=self._headers({"Range": "bytes=0-1024"}), + stream=True, + ) + try: + self._raise_hf_error(response, repo_id=repo_id, filename=filename) + data = response.raw.read(1025) + finally: + response.close() + + try: + text = data.decode("utf-8") + except UnicodeDecodeError: + return None + match = re.fullmatch( + r"version https://git-lfs\.github\.com/spec/v1\r?\n" + r"oid sha256:([0-9a-fA-F]{64})\r?\n" + r"size ([0-9]+)\r?\n?", + text, + ) + if match: + return {"sha256": match.group(1).lower(), "size": int(match.group(2))} + if text.startswith("version https://git-lfs.github.com/spec/v1"): + raise HFIntegrityError(f"Malformed Git LFS pointer for {filename}") + return None + + # Preserve the public download keyword options. + def download( # noqa: PLR0913 + self, + repo_id: str, + filename: str, + destination: str | os.PathLike[str], + *, + revision: str = "main", + resume: bool = True, + overwrite: bool = False, + progress: Callable[[DownloadProgress], None] | None = None, + cancelled: Callable[[], bool] | None = None, + expected_sha256: str | None = None, + progress_interval: float = 0.15, + ) -> Path: + """ + Download one file from a Hugging Face model repository. + + The final destination is written atomically: + destination.part + destination.part.json + -> destination + + Existing partial downloads are resumed when their remote metadata still + matches. If the revision/file changed, the stale partial is discarded. + + Parameters + ---------- + progress: + Callback receiving DownloadProgress. It runs on the thread calling + `download`; for Kivy, marshal UI changes onto the UI thread. + cancelled: + Callback returning True when cancellation is requested. The .part + file is preserved, so calling download() later resumes it. + expected_sha256: + Optional explicit SHA-256 integrity check. Usually unnecessary for + ordinary HF use, but useful when your app ships a trusted catalog. + """ + # Public options account for eleven of the seventeen local names. + # pylint: disable=too-many-arguments,too-many-locals + dest = Path(destination) + dest.parent.mkdir(parents=True, exist_ok=True) + part = dest.with_name(dest.name + ".part") + meta_path = dest.with_name(dest.name + ".part.json") + + remote = self.file_info(repo_id, filename, revision=revision) + + if dest.exists() and not overwrite: + self._check_existing(dest, remote, expected_sha256) + return dest + + # Files above regular HF HTTP's supported range require Xet. + if remote.size is not None and remote.size > 50 * 1024**3: + raise HFError( + f"{filename!r} is larger than 50 GiB. Hugging Face does not " + "serve files of this size through its regular HTTP download " + "path; an Xet-capable client is required." + ) + + expected_meta = self._prepare_partial(part, meta_path, remote, resume) + + # If a previous invocation finished the bytes but died before rename, + # finish locally without a network GET. + if remote.size is not None and part.stat().st_size == remote.size: + self._verify_and_commit( + part, + dest, + meta_path, + expected_size=remote.size, + expected_sha256=expected_sha256, + ) + return dest + + reporter = _ProgressReporter(remote, dest, progress, progress_interval) + reporter.start(part.stat().st_size) + self._download_with_retry( + part, meta_path, expected_meta, reporter, cancelled=cancelled, resume=resume + ) + + self._verify_and_commit( + part, + dest, + meta_path, + expected_size=remote.size, + expected_sha256=expected_sha256, + ) + + reporter.finish() + + return dest + + @staticmethod + def _check_existing(dest: Path, remote: RemoteFile, expected_sha256: str | None): + actual_size = dest.stat().st_size + if remote.size is not None and actual_size != remote.size: + raise HFIntegrityError( + f"Existing {dest.name} has {actual_size} bytes; expected " + f"{remote.size}. The file was left unchanged." + ) + if expected_sha256 is not None: + actual_sha256 = HFClient._sha256(dest) + if actual_sha256.lower() != expected_sha256.lower(): + raise HFIntegrityError( + f"Existing {dest.name} has SHA-256 {actual_sha256}; " + f"expected {expected_sha256}. The file was left unchanged." + ) + + def _prepare_partial(self, part, meta_path, remote, resume): + expected_meta = _PartialMeta( + repo_id=remote.repo_id, + filename=remote.filename, + revision=remote.revision, + etag=remote.etag, + commit=remote.commit, + expected_size=remote.size, + ) + + if not resume: + self._remove_partial(part, meta_path) + else: + self._validate_partial(part, meta_path, expected_meta) + + if not part.exists(): + part.touch() + _atomic_json_write(meta_path, asdict(expected_meta)) + + return expected_meta + + def _download_with_retry( # noqa: PLR0913 + self, part, meta_path, expected_meta, reporter, *, cancelled, resume + ): + # Retry state includes partial provenance and caller cancellation policy. + # pylint: disable=too-many-arguments + remote = reporter.remote + filename = remote.filename + attempt = 0 + while True: + if cancelled and cancelled(): + raise HFCancelled(f"Download cancelled: {filename}") + + current = part.stat().st_size + if remote.size is not None and current > remote.size: + self._remove_partial(part, meta_path) + part.touch() + _atomic_json_write(meta_path, asdict(expected_meta)) + current = 0 + + range_headers: dict[str, str] = {} + if resume and current > 0: + range_headers["Range"] = f"bytes={current}-" + + try: + response = self.session.get( + remote.url, + headers=self._headers(range_headers), + stream=True, + allow_redirects=True, + timeout=self.timeout, + ) + + # A stale/exact-complete range can produce 416. + if response.status_code == HTTPStatus.REQUESTED_RANGE_NOT_SATISFIABLE: + if remote.size is not None and current == remote.size: + response.close() + break + response.close() + # Do not append to something the server rejects. + self._remove_partial(part, meta_path) + part.touch() + _atomic_json_write(meta_path, asdict(expected_meta)) + attempt += 1 + if attempt > self.max_retries: + raise HFIntegrityError( + f"Server rejected resume range for {filename!r}." + ) + continue + + if response.status_code in _RETRYABLE_STATUS: + delay = _retry_after(response) + response.close() + if attempt >= self.max_retries: + _raise_download_error(response, filename) + self._sleep_backoff(attempt, delay) + attempt += 1 + continue + + self._raise_hf_error( + response, + repo_id=remote.repo_id, + filename=filename, + ) + + self._stream_response(response, part, reporter, cancelled) + + # A cleanly closed response should be complete. Verify below. + break + + except ( + requests.ConnectionError, + requests.Timeout, + requests.exceptions.ChunkedEncodingError, + ) as exc: + if attempt >= self.max_retries: + raise HFError( + f"Network error while downloading {filename!r} after " + f"{self.max_retries + 1} attempts: {exc}" + ) from exc + self._sleep_backoff(attempt) + attempt += 1 + # Loop reopens .part and resumes from its current byte count. + + def _stream_response(self, response, part, reporter, cancelled): + current = part.stat().st_size + # Never append a full response when the server ignores Range. + if current > 0 and response.status_code == HTTPStatus.PARTIAL_CONTENT: + mode = "ab" + else: + mode = "wb" + current = 0 + + with response, part.open(mode) as fp: + for chunk in response.iter_content(chunk_size=self.chunk_size): + if cancelled and cancelled(): + fp.flush() + try: + os.fsync(fp.fileno()) + except OSError: + pass + raise HFCancelled(f"Download cancelled: {reporter.remote.filename}") + if not chunk: + continue + fp.write(chunk) + current += len(chunk) + reporter.report(current) + + def _request_with_retry( + self, method: str, url: str, **kwargs: Any + ) -> requests.Response: + last_exc: BaseException | None = None + + for attempt in range(self.max_retries + 1): + try: + response = self.session.request( + method, + url, + timeout=self.timeout, + **kwargs, + ) + except (requests.ConnectionError, requests.Timeout) as exc: + last_exc = exc + if attempt >= self.max_retries: + break + self._sleep_backoff(attempt) + continue + + if response.status_code not in _RETRYABLE_STATUS: + return response + + if attempt >= self.max_retries: + return response + + delay = _retry_after(response) + response.close() + self._sleep_backoff(attempt, delay) + + raise HFError(f"Network request failed: {last_exc}") from last_exc + + def _sleep_backoff(self, attempt: int, explicit: float | None = None) -> None: + if explicit is not None: + delay = explicit + else: + delay = self.backoff * (2**attempt) + delay *= random.uniform(0.8, 1.2) + time.sleep(min(delay, 30.0)) + + def _validate_partial( + self, + part: Path, + meta_path: Path, + expected: _PartialMeta, + ) -> None: + if not part.exists(): + if meta_path.exists(): + meta_path.unlink() + return + + if not meta_path.exists(): + # Unknown provenance: unsafe to resume. + part.unlink() + return + + try: + saved_raw = json.loads(meta_path.read_text(encoding="utf-8")) + saved = _PartialMeta(**saved_raw) + except Exception: + self._remove_partial(part, meta_path) + return + + same_identity = ( + saved.repo_id == expected.repo_id + and saved.filename == expected.filename + and saved.revision == expected.revision + ) + + # Prefer commit/etag as version identity. If HF didn't expose either, + # size still gives a weak but useful guard. + version_matches = True + if expected.commit and saved.commit: + version_matches = expected.commit == saved.commit + elif expected.etag and saved.etag: + version_matches = expected.etag == saved.etag + elif expected.expected_size is not None and saved.expected_size is not None: + version_matches = expected.expected_size == saved.expected_size + + if not same_identity or not version_matches: + self._remove_partial(part, meta_path) + + @staticmethod + def _remove_partial(part: Path, meta_path: Path) -> None: + for path in (part, meta_path): + try: + path.unlink() + except FileNotFoundError: + pass + + @staticmethod + def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as fp: + while True: + chunk = fp.read(1024 * 1024) + if not chunk: + break + digest.update(chunk) + return digest.hexdigest() + + def _verify_and_commit( + self, + part: Path, + dest: Path, + meta_path: Path, + *, + expected_size: int | None, + expected_sha256: str | None, + ) -> None: + # Paths and integrity expectations are explicit at the commit boundary. + # pylint: disable=too-many-arguments + actual_size = part.stat().st_size + + if expected_size is not None and actual_size != expected_size: + raise HFIntegrityError( + f"Incomplete download: expected {expected_size} bytes, " + f"got {actual_size} bytes. Partial file was kept for resume." + ) + + if expected_sha256 is not None: + actual = self._sha256(part) + if actual.lower() != expected_sha256.lower(): + raise HFIntegrityError( + f"SHA-256 mismatch for {dest.name}: expected " + f"{expected_sha256}, got {actual}. Partial file was kept." + ) + + os.replace(part, dest) + try: + meta_path.unlink() + except FileNotFoundError: + pass + + def _raise_hf_error( + self, + response: requests.Response, + *, + repo_id: str | None = None, + filename: str | None = None, + ) -> None: + status = response.status_code + if HTTPStatus.OK <= status < HTTPStatus.BAD_REQUEST: + return + + request_id = response.headers.get("X-Request-Id") or response.headers.get( + "X-Amzn-Trace-Id" + ) + + body = "" + try: + body = response.text[:4096] + except Exception: + pass + + lower = body.lower() + subject = repo_id or "Hugging Face resource" + if filename: + subject = f"{subject}/{filename}" + + suffix = f" [request id: {request_id}]" if request_id else "" + + if status == HTTPStatus.TOO_MANY_REQUESTS: + raise HFRateLimitError( + f"Hugging Face rate limit exceeded for {subject}.{suffix}" + ) + + # HF gated-resource responses are commonly 401/403 with an explanatory + # body. Detect this before the generic auth case. + if status in (401, 403) and ( + "gated" in lower + or "access to model" in lower + or "access to this model" in lower + or "request access" in lower + ): + model_page = self.model_url(repo_id) if repo_id else self.endpoint + raise HFGatedError( + f"Access to {subject} is gated. The signed-in Hugging Face user " + f"must be granted/accept access first: {model_page}{suffix}" + ) + + if status in (401, 403): + if self.token: + raise HFAuthError( + f"Hugging Face denied access to {subject}. The token may " + f"be invalid or lack permission.{suffix}" + ) + raise HFAuthError( + f"{subject} requires Hugging Face authentication.{suffix}" + ) + + if status == HTTPStatus.NOT_FOUND: + raise HFNotFoundError( + f"Hugging Face repository, revision, or file not found: " + f"{subject}.{suffix}" + ) + + message = f"Hugging Face returned HTTP {status} for {subject}" + if body: + # Keep server text useful but bounded. + compact = " ".join(body.split()) + message += f": {compact[:500]}" + raise HFError(message + suffix) + + +# Keep the convenience wrapper compatible with existing callers. +def download_hf_model( # noqa: PLR0913 + repo_id: str, + filename: str, + *, + revision: str = "main", + token: str | None = None, + destination: str | os.PathLike[str] | None = None, + progress: Callable[[DownloadProgress], None] | None = None, + cancelled: Callable[[], bool] | None = None, + overwrite: bool = False, + expected_sha256: str | None = None, +) -> str: + """Download one Hugging Face model file and return its local path as a string.""" + + # pylint: disable=too-many-arguments + client = HFClient(token=token) + remote = client.file_info(repo_id, filename, revision=revision) + lfs_info = client.git_lfs_info(repo_id, filename, revision=revision) + if lfs_info is not None: + if remote.size is not None and lfs_info["size"] != remote.size: + raise HFIntegrityError( + f"Conflicting sizes for {filename}: download metadata reports " + f"{remote.size}, Git LFS reports {lfs_info['size']}" + ) + if expected_sha256 is None: + expected_sha256 = lfs_info["sha256"] + + if destination is None: + destination = model_path(repo_id, filename) + else: + destination = Path(destination) + + path = client.download( + repo_id, + filename, + destination, + revision=revision, + overwrite=overwrite, + progress=progress, + cancelled=cancelled, + expected_sha256=expected_sha256, + ) + return str(path) + + +def format_bytes(value: int | None) -> str: + if value is None: + return "?" + n = float(value) + for unit in ("B", "KiB", "MiB", "GiB", "TiB"): + if n < _BYTES_PER_KIB or unit == "TiB": + return f"{n:.1f} {unit}" if unit != "B" else f"{int(n)} B" + n /= _BYTES_PER_KIB + return f"{n:.1f} TiB" + + +def format_eta(seconds: float | None) -> str: + if seconds is None: + return "?" + seconds = max(0, int(seconds)) + if seconds < _SECONDS_PER_MINUTE: + return f"{seconds}s" + minutes, sec = divmod(seconds, _SECONDS_PER_MINUTE) + if minutes < _MINUTES_PER_HOUR: + return f"{minutes}m {sec:02d}s" + hours, minutes = divmod(minutes, _MINUTES_PER_HOUR) + return f"{hours}h {minutes:02d}m" + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Download one file from Hugging Face.") + parser.add_argument("repo_id") + parser.add_argument("filename") + parser.add_argument("destination") + parser.add_argument("--revision", default="main") + parser.add_argument("--token", default=os.environ.get("HF_TOKEN")) + args = parser.parse_args() + + cli_client = HFClient(token=args.token) + + def show(p: DownloadProgress) -> None: + pct = f"{p.percent:5.1f}%" if p.percent is not None else " ? " + print( + f"\r{pct} {format_bytes(p.downloaded)} / {format_bytes(p.total)} " + f"{p.speed_mbps:.1f} MiB/s ETA {format_eta(p.eta)}", + end="", + flush=True, + ) + + result = cli_client.download( + args.repo_id, + args.filename, + args.destination, + revision=args.revision, + progress=show, + ) + print(f"\nSaved to {result}") diff --git a/pythonhere/ml_here/storage.py b/pythonhere/ml_here/storage.py new file mode 100644 index 0000000..daea186 --- /dev/null +++ b/pythonhere/ml_here/storage.py @@ -0,0 +1,145 @@ +"""Find ML model files managed by PythonHere.""" + +import os +import sys + + +def _android_models_directory(): + """Return the model directory belonging to the running Android app.""" + + from jnius import autoclass + + PythonActivity = autoclass("org.kivy.android.PythonActivity") + activity = PythonActivity.mActivity + if activity is None: + raise RuntimeError("A running PythonHere activity is required") + + external_files = activity.getExternalFilesDir(None) + if external_files is None: + raise RuntimeError("Android external app storage is unavailable") + + return os.path.join(str(external_files.getAbsolutePath()), "models") + + +def _is_android(): + return sys.platform == "android" or "ANDROID_ARGUMENT" in os.environ + + +def models_directory(create=False): + """Return PythonHere's platform-specific model directory. + + Android uses the app-specific external files directory. Linux uses + PythonHere's per-user application data directory. + """ + + if _is_android(): + path = _android_models_directory() + else: + path = os.path.expanduser("~/.local/share/pythonhere/models") + + path = os.path.abspath(path) + if create: + os.makedirs(path, exist_ok=True) + return path + + +def _relative_parts(value, label): + """Return safe POSIX-style path components for a remote identifier.""" + + parts = value.split("/") + if not value or any(part in {"", ".", ".."} for part in parts): + raise ValueError(f"{label} must be a relative path without dot components") + return parts + + +def model_path(repo_id, filename): + """Return the local path for a model identified by repository and file.""" + + path = os.path.join( + models_directory(), + *_relative_parts(repo_id, "repo_id"), + *_relative_parts(filename, "filename"), + ) + return os.path.abspath(path) + + +def require_model(repo_id, filename): + """Return an installed model path, or raise ``FileNotFoundError``.""" + + path = model_path(repo_id, filename) + if not os.path.isfile(path): + raise FileNotFoundError( + f"ML model is not installed: {repo_id}/{filename} ({path})" + ) + return path + + +def _model_extensions(extensions): + """Normalize an optional model-extension filter.""" + + if extensions is None: + return None + if isinstance(extensions, str): + extensions = (extensions,) + + normalized = set() + for extension in extensions: + if not isinstance(extension, str) or not extension: + raise ValueError("extensions must contain non-empty strings") + normalized_extension = extension.lower() + normalized.add( + normalized_extension + if normalized_extension.startswith(".") + else f".{normalized_extension}" + ) + return tuple(sorted(normalized)) + + +def _discover_directory(directory, extensions): + """Yield model files recursively beneath a directory.""" + + path = os.path.abspath(os.fspath(directory)) + if not os.path.isdir(path): + return + + def ignore_error(_error): + pass + + for root, directories, files in os.walk(path, onerror=ignore_error): + directories.sort(key=str.casefold) + for filename in files: + lower_filename = filename.lower() + if lower_filename.endswith((".part", ".part.json")): + continue + if extensions is None or lower_filename.endswith(extensions): + yield os.path.abspath(os.path.join(root, filename)) + + +def discover_models(extra_directories=(), *, extensions=".litertlm"): + """Find local model files, optionally filtered by filename extension. + + ``extensions`` may be one extension or an iterable, with or without the + leading dot. The default finds LiteRT-LM models. Pass ``None`` to return + all completed files. Temporary files belonging to an in-progress download + are always ignored. + """ + + if isinstance(extra_directories, (str, bytes, os.PathLike)): + extra_directories = (extra_directories,) + extensions = _model_extensions(extensions) + + models = [] + seen = set() + for directory in (models_directory(), *extra_directories): + for discovered_path in _discover_directory(directory, extensions): + key = os.path.normcase(discovered_path) + if key not in seen: + seen.add(key) + models.append(discovered_path) + return sorted( + models, + key=lambda path: (os.path.basename(path).casefold(), path.casefold()), + ) + + +__all__ = ("discover_models", "model_path", "models_directory", "require_model") diff --git a/tests/test_ml_here.py b/tests/test_ml_here.py new file mode 100644 index 0000000..f9dd979 --- /dev/null +++ b/tests/test_ml_here.py @@ -0,0 +1,416 @@ +import hashlib +import sys +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from types import SimpleNamespace + +import pytest +import requests + +from pythonhere.ml_here import ( + discover_models, + model_path, + models_directory, + require_model, + storage, +) +from pythonhere.ml_here.huggingface import ( + HFCancelled, + HFClient, + HFError, + HFRateLimitError, + RemoteFile, + download_hf_model, +) + + +def test_models_directory_uses_linux_user_data(monkeypatch, tmp_path): + monkeypatch.delenv("ANDROID_ARGUMENT", raising=False) + monkeypatch.setenv("HOME", str(tmp_path)) + + result = models_directory(create=True) + + assert result == str(tmp_path / ".local" / "share" / "pythonhere" / "models") + assert Path(result).is_dir() + + +def test_models_directory_uses_lowercase_android_directory(monkeypatch): + external_files = SimpleNamespace(getAbsolutePath=lambda: "/android/files") + activity = SimpleNamespace(getExternalFilesDir=lambda _kind: external_files) + python_activity = SimpleNamespace(mActivity=activity) + jnius = SimpleNamespace(autoclass=lambda _class_name: python_activity) + monkeypatch.setitem(sys.modules, "jnius", jnius) + monkeypatch.setattr(storage.sys, "platform", "android") + + assert models_directory() == "/android/files/models" + + +def test_discover_models_reads_pythonhere_directory(monkeypatch, tmp_path): + monkeypatch.delenv("ANDROID_ARGUMENT", raising=False) + monkeypatch.setenv("HOME", str(tmp_path)) + models = tmp_path / ".local" / "share" / "pythonhere" / "models" + repository = models / "owner" / "zebra" + extra = tmp_path / "extra" + repository.mkdir(parents=True) + extra.mkdir() + (repository / "zebra.litertlm").write_bytes(b"zebra") + (models / "model.tflite").write_bytes(b"tflite") + (models / "unfinished.tflite.part").write_bytes(b"partial") + (models / "unfinished.tflite.part.json").write_text("{}", encoding="utf-8") + (extra / "Alpha.LITERTLM").write_bytes(b"alpha") + + assert models_directory() == str(models) + assert discover_models(extra, extensions="litertlm") == [ + str(extra / "Alpha.LITERTLM"), + str(repository / "zebra.litertlm"), + ] + assert discover_models(extensions=(".tflite",)) == [str(models / "model.tflite")] + assert discover_models(extra) == [ + str(extra / "Alpha.LITERTLM"), + str(repository / "zebra.litertlm"), + ] + assert discover_models(extra, extensions=None) == [ + str(extra / "Alpha.LITERTLM"), + str(models / "model.tflite"), + str(repository / "zebra.litertlm"), + ] + + +def test_model_path_is_namespaced_and_does_not_create_directories( + monkeypatch, tmp_path +): + monkeypatch.delenv("ANDROID_ARGUMENT", raising=False) + monkeypatch.setenv("HOME", str(tmp_path)) + + result = model_path("owner/repository", "variants/model.litertlm") + + expected = ( + tmp_path + / ".local" + / "share" + / "pythonhere" + / "models" + / "owner" + / "repository" + / "variants" + / "model.litertlm" + ) + assert result == str(expected) + assert not expected.parent.exists() + + +@pytest.mark.parametrize( + ("repo_id", "filename"), + [ + ("../owner", "model.litertlm"), + ("owner/repository", "../model.litertlm"), + ("/owner/repository", "model.litertlm"), + ("owner/repository", "/model.litertlm"), + ], +) +def test_model_path_rejects_unsafe_components(monkeypatch, tmp_path, repo_id, filename): + monkeypatch.delenv("ANDROID_ARGUMENT", raising=False) + monkeypatch.setenv("HOME", str(tmp_path)) + + with pytest.raises(ValueError): + model_path(repo_id, filename) + + +def test_require_model_returns_installed_model(monkeypatch, tmp_path): + monkeypatch.delenv("ANDROID_ARGUMENT", raising=False) + monkeypatch.setenv("HOME", str(tmp_path)) + path = Path(model_path("owner/repository", "model.litertlm")) + path.parent.mkdir(parents=True) + path.write_bytes(b"model") + + assert require_model("owner/repository", "model.litertlm") == str(path) + + +def test_require_model_reports_missing_model(monkeypatch, tmp_path): + monkeypatch.delenv("ANDROID_ARGUMENT", raising=False) + monkeypatch.setenv("HOME", str(tmp_path)) + expected = model_path("owner/repository", "model.litertlm") + + with pytest.raises( + FileNotFoundError, + match=r"ML model is not installed: owner/repository/model\.litertlm", + ) as error: + require_model("owner/repository", "model.litertlm") + + assert str(error.value).endswith(f"({expected})") + + +@pytest.fixture +def model_server(): + content = b"portable LiteRT model fixture" + etag = hashlib.sha256(content).hexdigest() + + class Handler(BaseHTTPRequestHandler): + def do_HEAD(self): + self.send_response(200) + self.send_header("Content-Length", str(len(content))) + self.send_header("ETag", etag) + self.end_headers() + + def do_GET(self): + start = 0 + requested_range = self.headers.get("Range") + if requested_range: + start = int(requested_range.removeprefix("bytes=").removesuffix("-")) + self.send_response(206) + self.send_header( + "Content-Range", f"bytes {start}-{len(content) - 1}/{len(content)}" + ) + else: + self.send_response(200) + body = content[start:] + self.send_header("Content-Length", str(len(body))) + self.send_header("ETag", etag) + self.end_headers() + self.wfile.write(body) + + def log_message(self, _format, *_args): + pass + + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + yield server, content, etag + finally: + server.shutdown() + server.server_close() + thread.join() + + +def test_hf_client_downloads_and_resumes_on_desktop(model_server, tmp_path): + server, content, etag = model_server + endpoint = f"http://127.0.0.1:{server.server_port}" + destination = tmp_path / "model.litertlm" + part = tmp_path / "model.litertlm.part" + metadata = tmp_path / "model.litertlm.part.json" + partial_size = 9 + part.write_bytes(content[:partial_size]) + metadata.write_text( + "{" + '"repo_id":"owner/model",' + '"filename":"model.litertlm",' + '"revision":"main",' + f'"etag":"{etag}",' + '"commit":null,' + f'"expected_size":{len(content)}' + "}", + encoding="utf-8", + ) + client = HFClient(endpoint=endpoint, max_retries=0, chunk_size=4) + + result = client.download( + "owner/model", + "model.litertlm", + destination, + expected_sha256=etag, + ) + + assert result == destination + assert destination.read_bytes() == content + assert not part.exists() + assert not metadata.exists() + + +def test_download_hf_model_uses_portable_default_directory(monkeypatch, tmp_path): + models = tmp_path / ".local" / "share" / "pythonhere" / "models" + content = b"downloaded model" + monkeypatch.delenv("ANDROID_ARGUMENT", raising=False) + monkeypatch.setenv("HOME", str(tmp_path)) + monkeypatch.setattr( + HFClient, + "file_info", + lambda _self, repo_id, filename, *, revision: RemoteFile( + repo_id=repo_id, + filename=filename, + revision=revision, + size=len(content), + etag=None, + commit=None, + url="https://example.invalid/model.litertlm", + ), + ) + monkeypatch.setattr( + HFClient, + "git_lfs_info", + lambda _self, _repo_id, _filename, *, revision: None, + ) + + def fake_download(_self, _repo_id, _filename, destination, **_kwargs): + destination = Path(destination) + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(content) + return destination + + monkeypatch.setattr(HFClient, "download", fake_download) + + result = download_hf_model("owner/model", "nested/model.litertlm") + + assert result == str(models / "owner" / "model" / "nested" / "model.litertlm") + assert result == require_model("owner/model", "nested/model.litertlm") + assert Path(result).read_bytes() == content + + +def test_download_hf_model_accepts_non_litert_lm_files(monkeypatch, tmp_path): + monkeypatch.setattr( + HFClient, + "file_info", + lambda _self, repo_id, filename, *, revision: RemoteFile( + repo_id=repo_id, + filename=filename, + revision=revision, + size=5, + etag=None, + commit=None, + url="https://example.invalid/model.tflite", + ), + ) + monkeypatch.setattr( + HFClient, + "git_lfs_info", + lambda _self, _repo_id, _filename, *, revision: None, + ) + + destination = tmp_path / "model.tflite" + + def fake_download(_self, _repo_id, _filename, path, **_kwargs): + path = Path(path) + path.write_bytes(b"model") + return path + + monkeypatch.setattr(HFClient, "download", fake_download) + + assert download_hf_model( + "owner/model", "model.tflite", destination=destination + ) == str(destination) + + +def test_hf_cancellation_keeps_partial_and_resume_reports_progress( + model_server, tmp_path +): + server, content, etag = model_server + client = HFClient( + endpoint=f"http://127.0.0.1:{server.server_port}", chunk_size=4, max_retries=0 + ) + destination = tmp_path / "model.litertlm" + reports = [] + + with pytest.raises(HFCancelled): + client.download( + "owner/model", + "model.litertlm", + destination, + progress=reports.append, + progress_interval=0, + cancelled=lambda: bool(reports), + ) + + part = destination.with_suffix(".litertlm.part") + partial_size = part.stat().st_size + assert 0 < partial_size < len(content) + assert part.read_bytes() == content[:partial_size] + assert not destination.exists() + assert destination.with_suffix(".litertlm.part.json").exists() + + reports.clear() + client.download( + "owner/model", + "model.litertlm", + destination, + progress=reports.append, + progress_interval=0, + expected_sha256=etag, + ) + + assert destination.read_bytes() == content + assert reports[0].downloaded > partial_size + assert reports[-1].downloaded == len(content) + assert reports[-1].total == len(content) + assert reports[-1].percent == 100 + assert reports[-1].destination == str(destination) + assert not part.exists() + + +@pytest.fixture +def fake_hf_transfer(mocker): + content = b"abcdefgh" + session = mocker.Mock() + client = HFClient(session=session, max_retries=1, backoff=0) + mocker.patch.object( + client, + "file_info", + return_value=RemoteFile( + "owner/model", + "model.bin", + "main", + len(content), + None, + None, + "https://example.invalid/model.bin", + ), + ) + + def response(status, chunks=()): + result = mocker.MagicMock(spec=requests.Response) + result.status_code = status + result.headers = {} + + def stream(**_kwargs): + for chunk in chunks: + if isinstance(chunk, Exception): + raise chunk + yield chunk + + result.iter_content.side_effect = stream + return result + + return client, session, response, content + + +@pytest.mark.parametrize("resume_status", [200, 206]) +def test_hf_interrupted_stream_retries_without_duplicate_bytes( + fake_hf_transfer, tmp_path, resume_status +): + client, session, response, content = fake_hf_transfer + interrupted = response( + 200, [content[:4], requests.exceptions.ChunkedEncodingError("disconnected")] + ) + resumed = response( + resume_status, [content[4:] if resume_status == 206 else content] + ) + session.get.side_effect = [interrupted, resumed] + destination = tmp_path / "model.bin" + + client.download("owner/model", "model.bin", destination) + + assert destination.read_bytes() == content + assert session.get.call_count == 2 + assert session.get.call_args_list[1].kwargs["headers"]["Range"] == "bytes=4-" + assert interrupted.__exit__.called + assert resumed.__exit__.called + + +@pytest.mark.parametrize( + "status, error_type", [(429, HFRateLimitError), (503, HFError)] +) +def test_hf_exhausted_http_retries_preserve_error_and_partial( + fake_hf_transfer, tmp_path, status, error_type +): + client, session, response, _content = fake_hf_transfer + responses = [response(status), response(status)] + session.get.side_effect = responses + destination = tmp_path / "model.bin" + + with pytest.raises(error_type): + client.download("owner/model", "model.bin", destination) + + assert session.get.call_count == 2 + assert all(item.close.called for item in responses) + assert not destination.exists() + assert destination.with_suffix(".bin.part").exists() diff --git a/tests/test_pythonhere_skill.py b/tests/test_pythonhere_skill.py index a8435bf..98f077e 100644 --- a/tests/test_pythonhere_skill.py +++ b/tests/test_pythonhere_skill.py @@ -19,9 +19,11 @@ "jnius.md", "kivy-kv.md", "kivy-runtime.md", + "litert.md", "midi.md", "plyer.md", } +RUNTIME_PROMPT_NAMES = REFERENCE_NAMES - {"litert.md"} def test_pythonhere_skill_files_exist(): @@ -67,7 +69,7 @@ def test_pythonhere_skill_is_included_in_wheel(tmp_path): def test_pythonhere_skill_references_cover_runtime_prompts(): - for name in REFERENCE_NAMES: + for name in RUNTIME_PROMPT_NAMES: prompt = (PROMPTS_DIR / name).read_text() reference = (REFERENCES_DIR / name).read_text() diff --git a/uv.lock b/uv.lock index 7715d85..15181d2 100644 --- a/uv.lock +++ b/uv.lock @@ -1013,6 +1013,16 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/52/7d/7157f9bba6b455cfb4632ed411e199fc8b8977642c2b12082e1bd9e6d173/kiwisolver-1.5.0-pp311-pypy311_pp73-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:daae526907e262de627d8f70058a0f64acc9e2641c164c99c8f594b34a799a16", size = 77603, upload-time = "2026-03-09T13:15:50.945Z" }, ] +[[package]] +name = "litert-lm-api" +version = "0.16.0" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1d/d1/c444aa53f82b3b3850bafe6c087aabfc3e201ee01209f3e594cd8c2a476a/litert_lm_api-0.16.0-py3-none-android_23_arm64_v8a.whl", hash = "sha256:d07c80e415f08e71aa6a0c51b6db602a11e828591e2f36501340fdd35292b62a", size = 13804850, upload-time = "2026-08-11T18:00:27.522Z" }, + { url = "https://files.pythonhosted.org/packages/3a/07/fa43be00a7907dd0f9f2cfbcc9b1305198c1be6e5ef33b2604a622437915/litert_lm_api-0.16.0-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:5eb8c9faa5727730239591f8c912261ec7705512d5f30ec674586bc0005f2b00", size = 46085754, upload-time = "2026-08-11T18:00:40.22Z" }, + { url = "https://files.pythonhosted.org/packages/1e/80/494be9edb8b851ae4a7b2065c0133426beb3608fa39f9454a0f823db8c76/litert_lm_api-0.16.0-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:a5d58ff8e1c14057d6a8c1f0333372bc685361e6311ea87bfa49fc131cb00a95", size = 46835531, upload-time = "2026-08-11T18:00:46.745Z" }, +] + [[package]] name = "markdown-it-py" version = "4.2.0" @@ -1633,6 +1643,12 @@ dependencies = [ { name = "pillow", marker = "sys_platform == 'linux'" }, ] +[package.optional-dependencies] +litert = [ + { name = "litert-lm-api", marker = "sys_platform == 'linux'" }, + { name = "requests", marker = "sys_platform == 'linux'" }, +] + [package.dev-dependencies] dev = [ { name = "build", marker = "sys_platform == 'linux'" }, @@ -1664,8 +1680,11 @@ requires-dist = [ { name = "herethere", extras = ["magic"], specifier = ">=0.3.2" }, { name = "ipython" }, { name = "ipywidgets" }, + { name = "litert-lm-api", marker = "extra == 'litert'", specifier = "==0.16.0" }, { name = "pillow" }, + { name = "requests", marker = "extra == 'litert'" }, ] +provides-extras = ["litert"] [package.metadata.requires-dev] dev = [ From 3c43e8e29da924981f5676e148dc478e31423ea1 Mon Sep 17 00:00:00 2001 From: b3b Date: Tue, 8 Sep 2026 18:48:40 +0200 Subject: [PATCH 05/13] Use SourceForge mirror for FreeType downloads --- recipes/freetype/__init__.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 recipes/freetype/__init__.py diff --git a/recipes/freetype/__init__.py b/recipes/freetype/__init__.py new file mode 100644 index 0000000..5e358e8 --- /dev/null +++ b/recipes/freetype/__init__.py @@ -0,0 +1,18 @@ +from pythonforandroid.recipes.freetype import FreetypeRecipe + + +class FreetypeSourceForgeRecipe(FreetypeRecipe): + # FreeType officially publishes stable releases on both Savannah and + # SourceForge: + # https://freetype.org/download/ + # + # python-for-android normally downloads FreeType from Savannah. We use + # the official SourceForge release mirror instead because Savannah's + # download service has caused intermittent HTTP 502 build failures. + url = ( + "https://downloads.sourceforge.net/project/freetype/" + "freetype2/{version}/freetype-{version}.tar.gz" + ) + + +recipe = FreetypeSourceForgeRecipe() From 67a17e4b80b7606886d05adca4a3ca01f16e84ef Mon Sep 17 00:00:00 2001 From: b3b Date: Wed, 9 Sep 2026 14:38:29 +0200 Subject: [PATCH 06/13] Prepare 0.4.0 release --- CHANGELOG.rst | 10 + examples/litert.md | 137 +++++++++++ examples/litert_multimodal_lab.md | 388 ++++++++++++++++++++++++++++++ 3 files changed, 535 insertions(+) create mode 100644 examples/litert.md create mode 100644 examples/litert_multimodal_lab.md diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 5de080d..e3b7300 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,6 +1,16 @@ Changelog ========= +0.4.0 +----- + +This release adds support for running local AI models directly on Android +with Google's LiteRT LM. + +* Added LiteRT LM support for on-device language and multimodal models +* Added ``ml_here`` helpers for downloading and managing models from Hugging Face +* Added LiteRT LM usage guidance to the packaged ``pythonhere`` agent skill + 0.3.1 ----- diff --git a/examples/litert.md b/examples/litert.md new file mode 100644 index 0000000..0f0e466 --- /dev/null +++ b/examples/litert.md @@ -0,0 +1,137 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.19.3 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# On-device AI with LiteRT + +PythonHere bundles the +[LiteRT-LM](https://github.com/google-ai-edge/LiteRT-LM) Python library in its +Android app, so `.litertlm` models can run directly on the device. After a +model has been downloaded, inference does not require a network connection. + +PythonHere also provides +[model helpers](https://github.com/b3b/pythonhere/tree/main/pythonhere/ml_here) +for managing model storage and downloading model files from Hugging Face. +This example covers every public helper, then loads a small language model and +generates text with LiteRT-LM. Refer to the LiteRT-LM documentation for its +full inference API, including sampling, streaming, and benchmarking. + +For an interactive vision-language example using the Android camera, see the +[LiteRT multimodal lab](litert_multimodal_lab.md), the companion notebook for +the video *Run multimodal AI on Android with Python and LiteRT*. + +## Connect to PythonHere + +Load the Jupyter extension and connect to a running PythonHere app: + +```{code-cell} ipython3 +%load_ext pythonhere +%connect-there +``` + +## Inspect model storage + +`models_directory()` returns PythonHere's platform-specific model directory. +`model_path()` builds the managed path for a particular Hugging Face model, +and `discover_models()` lists models already present on the device. + +```{code-cell} ipython3 +%%there +from pprint import pprint as pp +from ml_here import ( + discover_models, + download_hf_model, + model_path, + models_directory, + require_model, +) + +MODEL_REPO = "litert-community/SmolLM2-135M-Instruct" +MODEL_FILE = "SmolLM2_135M_Instruct.litertlm" + +print(f"Model directory: {models_directory(create=True)}") +print(f"Managed path: {model_path(MODEL_REPO, MODEL_FILE)}") +print("Available LiteRT-LM models:") +pp(discover_models()) +``` + +## Download the model + +`download_hf_model()` downloads the model into its managed path. Downloads +can be resumed, and an existing verified file is reused. Because downloading +may take time, this cell runs on a worker so the Android UI stays responsive. + +```{code-cell} ipython3 +%%there --worker +def report_progress(value): + if value.percent is not None: + print(f"\rDownloading: {value.percent:.1f}%", end="", flush=True) + + +downloaded_path = download_hf_model( + repo_id=MODEL_REPO, + filename=MODEL_FILE, + progress=report_progress, +) + +print(f"\nDownloaded model: {downloaded_path}") +``` + +`require_model()` returns the model path if the file is available and raises +`FileNotFoundError` otherwise. Discover the device again to confirm that the +downloaded model is now included: + +```{code-cell} ipython3 +%%there +model_file = require_model(MODEL_REPO, MODEL_FILE) +print(f"Required model: {model_file}") +print("Available LiteRT-LM models:") +pp(discover_models()) +``` + +## Load the model + +Model loading and inference can block the app's UI thread, so they also run +with `%%there --worker`. + +```{code-cell} ipython3 +%%there --worker +import litert_lm + +engine = litert_lm.Engine(model_file) +pp(engine) +``` + +## Generate text + +Create a conversation and send a prompt. The model runs locally in the +PythonHere app, and only the generated response is returned to Jupyter. + +```{code-cell} ipython3 +%%there --worker +with engine.create_conversation( + max_output_tokens=128, +) as conversation: + response = conversation.send_message( + "What is the Kivy framework? Answer in one short paragraph." + ) + pp(response["content"][0]["text"]) +``` + +## Clean up + +Close the engine to release its native resources when it is no longer needed: + +```{code-cell} ipython3 +%%there --worker +engine.close() +``` diff --git a/examples/litert_multimodal_lab.md b/examples/litert_multimodal_lab.md new file mode 100644 index 0000000..e0a97af --- /dev/null +++ b/examples/litert_multimodal_lab.md @@ -0,0 +1,388 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.19.3 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# LiteRT multimodal lab + +Companion notebook for the video [*Run multimodal AI on Android with Python and LiteRT*](https://youtu.be/w_RZ0Y29A7I). + +## Connect to PythonHere + +```{code-cell} ipython3 +%load_ext pythonhere +%connect-there +``` + +## Show download progress + +```{code-cell} ipython3 +%%there kv +: + size_hint: .82, .82 + pos_hint: {'center_x': .5, 'center_y': .5} + + canvas: + Color: + rgba: .45, .52, .50, .16 + + Line: + width: dp(5) + circle: + self.center_x, \ + self.center_y, \ + min(self.width, self.height) * .34, \ + 0, \ + 360 + + Color: + rgba: .30, .40, .37, .95 if root.value > 0 else 0 + + Line: + width: dp(10) if root.value >= 100 else dp(9) + circle: + self.center_x, \ + self.center_y, \ + min(self.width, self.height) * .34, \ + 105, \ + 105 + 360 * min(max(root.value, 0), 100) / 100 + + Label: + text: "Ready" if root.value >= 100 else f"{root.value:3.0f}%" + font_size: min(root.width, root.height) * (.11 if root.value >= 100 else .13) + color: .25, .32, .30, .95 + center: root.center +``` + +```{code-cell} ipython3 +%%there +from kivy.properties import NumericProperty +from kivy.uix.widget import Widget + + +class DownloadProgress(Widget): + value = NumericProperty(0) + +root.clear_widgets() +progress = DownloadProgress() +root.add_widget(progress) +``` + +## Download the model + +```{code-cell} ipython3 +%%there --worker +from pprint import pprint as pp +from kivy.clock import mainthread +from ml_here import download_hf_model, require_model + +MODEL_REPO = "litert-community/SmolVLM2-500M" +MODEL_FILE = "SmolVLM2-500M.litertlm" + + +@mainthread +def update_progress(value): + progress.value = value.percent or 0.0 + + +download_hf_model( + repo_id=MODEL_REPO, + filename=MODEL_FILE, + progress=update_progress, +) + +pp(require_model(MODEL_REPO, MODEL_FILE)) +``` + +## Load the model + +```{code-cell} ipython3 +%%there --worker +import litert_lm +engine = litert_lm.Engine( + require_model(MODEL_REPO, MODEL_FILE), + backend=litert_lm.Backend.GPU(), + vision_backend=litert_lm.Backend.GPU(), + enable_benchmark=True, +) +pp(engine) +``` + +## Generate text + +### Create a streaming output view + +```{code-cell} ipython3 +%%there kv +: + size_hint: .88, .7 + pos_hint: {'center_x': .5, 'center_y': .5} + + Label: + markup: True + text: root.text + font_size: dp(21) + halign: "left" + valign: "top" + text_size: root.width, None + pos: root.pos + size: root.size +``` + +```{code-cell} ipython3 +%%there +from kivy.properties import StringProperty +from kivy.uix.widget import Widget +from kivy.clock import mainthread + + +class ModelOutput(Widget): + text = StringProperty("") + committed = StringProperty("") + newest = StringProperty("") + + @mainthread + def append_chunk(self, chunk): + self.committed += self.newest + self.newest = chunk + self.text = ( + f"[color=#E8EEF3]{self.committed}[/color]" + f"[color=#FFD343][b]{self.newest}[/b][/color]" + ) + +root.clear_widgets() +output = ModelOutput() +root.add_widget(output) +``` + +### Ask a text question + +```{code-cell} ipython3 +%%there --worker + +sampler = litert_lm.SamplerConfig( + temperature=0.7, + top_p=0.9, + top_k=40, +) + +with engine.create_conversation( + sampler_config=sampler, + max_output_tokens=128, +) as conversation: + for chunk in conversation.send_message_async( + "What is on-device AI? Give a direct answer in one short paragraph." + ): + output.append_chunk(chunk["content"][0]["text"]) + info = conversation.get_benchmark_info() + output.append_chunk("") +``` + +### Show benchmark results + +```{code-cell} ipython3 +%%there +print( + "\n\tBenchmark info for the conversation\n" + f"Init: {info.init_time_in_second:.2f}s\n" + f"TTFT: {info.time_to_first_token_in_second:.2f}s\n" + f"Prefill: {info.last_prefill_token_count} tokens " + f"@ {info.last_prefill_tokens_per_second:.1f} tok/s\n" + f"Decode: {info.last_decode_token_count} tokens " + f"@ {info.last_decode_tokens_per_second:.1f} tok/s" +) +``` + +## Describe a camera photo + +### Request camera permission + +```{code-cell} ipython3 +%%there +from threading import Event +from android.permissions import Permission, request_permission + +done = Event() +request_permission(Permission.CAMERA, lambda *_: done.set()) +done.wait() +``` + +### Preview and capture a photo + +```{code-cell} ipython3 +%%there kv +AnchorLayout: + anchor_x: "center" + anchor_y: "center" + + Camera: + id: camera + play: True + resolution: (640, 480) + fit_mode: "contain" + + size_hint: None, None + height: min(root.width, root.height * 3 / 4) + width: self.height * 4 / 3 + + canvas.before: + PushMatrix + Rotate: + angle: -90 + origin: self.center + + canvas.after: + PopMatrix +``` + +```{code-cell} ipython3 +%%there +camera = root.ids.camera +camera.play = False +``` + +```{code-cell} ipython3 +%%there +from os.path import abspath, getsize +from PIL import Image + +texture = camera.texture +image = Image.frombytes("RGBA", texture.size, texture.pixels) + +# Kivy textures use a bottom-left origin. +image = image.transpose(Image.Transpose.FLIP_TOP_BOTTOM) + +# Match the rotation applied to the Android camera preview. +image = image.rotate(-90, expand=True).convert("RGB") + +photo_path = abspath("from_camera.jpg") +image.save(photo_path, quality=90) + +print(f"Photo: {photo_path}") +print( + f"Image: {image.width} × {image.height}, " + f"{image.mode}, {getsize(photo_path) / 1024:.1f} KiB" +) +``` + +### Generate a description + +```{code-cell} ipython3 +%%there --worker +sampler = litert_lm.SamplerConfig( + temperature=0.7, + top_p=0.9, + top_k=40, +) + +with engine.create_conversation( + sampler_config=sampler, + max_output_tokens=96, +) as conversation: + response = conversation.send_message( + litert_lm.Contents.of( + "Describe the main object in this image clearly and concisely in 2-3 sentences.", + litert_lm.Content.ImageFile(absolute_path=photo_path), + ) + ) + print(response["content"][0]["text"]) +``` + +## Explore sampling variability + +### Generate responses with different temperatures and seeds + +```{code-cell} ipython3 +%%there --worker +prompt = ( + "Describe the main object in this image clearly and concisely " + "in 2-3 sentences." +) + +temperatures = [0.2, 0.5, 0.7, 1.0] +seeds = [1, 7, 42, 123, 999] + +experiment_results = [] + +for temperature in temperatures: + for seed in seeds: + sampler = litert_lm.SamplerConfig( + temperature=temperature, + top_p=0.9, + top_k=40, + seed=seed, + ) + + with engine.create_conversation( + sampler_config=sampler, + max_output_tokens=96, + ) as conversation: + response = conversation.send_message( + litert_lm.Contents.of( + prompt, + litert_lm.Content.ImageFile(absolute_path=photo_path), + ) + ) + + info = conversation.get_benchmark_info() + + experiment_results.append({ + "temperature": temperature, + "seed": seed, + "output": response["content"][0]["text"].strip(), + "ttft_s": info.time_to_first_token_in_second, + "prefill_tokens": info.last_prefill_token_count, + "prefill_tok_s": info.last_prefill_tokens_per_second, + "decode_tokens": info.last_decode_token_count, + "decode_tok_s": info.last_decode_tokens_per_second, + }) + +print(f"Done: {len(experiment_results)} runs") +``` + +### Compare the outputs + +```{code-cell} ipython3 +import pandas as pd + +experiment_results = %there get experiment_results + +df = pd.DataFrame(experiment_results) + +display( + df[ + [ + "temperature", + "seed", + "decode_tokens", + "output", + ] + ].style + .format({ + "temperature": "{:.1f}", + }) + .set_properties( + subset=["output"], + **{ + "white-space": "pre-wrap", + "text-align": "left", + }, + ) + .hide(axis="index") +) +``` + +## Clean up + +```{code-cell} ipython3 +%%there --worker +engine.close() +``` From 5eb7c30bc95218cf124e9a2243cb055a051c598d Mon Sep 17 00:00:00 2001 From: b3b Date: Thu, 17 Sep 2026 17:14:16 +0200 Subject: [PATCH 07/13] Add durable sequential task runner Add the `tasks_here` module, based on persist-queue, for persistent named task runs with retries, pause/resume, progress inspection, and restart recovery. --- buildozer.spec | 1 + examples/litert.md | 2 +- examples/tasks.md | 163 +++ pyproject.toml | 1 + pythonhere/.agents/skills/pythonhere/SKILL.md | 4 +- .../skills/pythonhere/references/tasks.md | 58 + pythonhere/tasks_here.py | 1273 +++++++++++++++++ tests/test_pythonhere_skill.py | 3 +- tests/test_tasks_here.py | 649 +++++++++ uv.lock | 11 + 10 files changed, 2162 insertions(+), 3 deletions(-) create mode 100644 examples/tasks.md create mode 100644 pythonhere/.agents/skills/pythonhere/references/tasks.md create mode 100644 pythonhere/tasks_here.py create mode 100644 tests/test_tasks_here.py diff --git a/buildozer.spec b/buildozer.spec index 877a0b3..f627b96 100644 --- a/buildozer.spec +++ b/buildozer.spec @@ -58,6 +58,7 @@ requirements = idna==3.18, # https://github.com/kivy/python-for-android/issues/3098 filetype==1.2.0, + persist-queue==1.1.0, litert_lm_api==0.16.0, diff --git a/examples/litert.md b/examples/litert.md index 0f0e466..b60ef3e 100644 --- a/examples/litert.md +++ b/examples/litert.md @@ -19,7 +19,7 @@ Android app, so `.litertlm` models can run directly on the device. After a model has been downloaded, inference does not require a network connection. PythonHere also provides -[model helpers](https://github.com/b3b/pythonhere/tree/main/pythonhere/ml_here) +[model helpers](https://github.com/b3b/pythonhere/tree/master/pythonhere/ml_here) for managing model storage and downloading model files from Hugging Face. This example covers every public helper, then loads a small language model and generates text with LiteRT-LM. Refer to the LiteRT-LM documentation for its diff --git a/examples/tasks.md b/examples/tasks.md new file mode 100644 index 0000000..6511687 --- /dev/null +++ b/examples/tasks.md @@ -0,0 +1,163 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.19.3 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# Durable sequential tasks + +`TaskRunner` runs tasks one at a time in the PythonHere process and persists +their inputs, results, errors, and retry state. Work continues if Jupyter +disconnects. After PythonHere restarts, completed tasks remain complete and an +interrupted task becomes runnable again. + +## Connect to PythonHere + +```{code-cell} ipython3 +%load_ext pythonhere +%connect-there +``` + +## Submit and start work + +Every task needs a unique nonempty string `id`. Tasks and returned results must +contain plain JSON-compatible values. + +```{code-cell} ipython3 +%%there +import time + +from tasks_here import TaskRunner + + +def execute_task(task, context): + time.sleep(1) + return { + "value": task["value"], + "square": task["value"] ** 2, + } + + +runner = TaskRunner.create("squares-example", max_attempts=3) +runner.add([{"id": str(value), "value": value} for value in range(1, 11)]) +runner.start(execute_task) +``` + +`start()` returns promptly while the runner processes tasks in its background +thread. + +The executor always receives a second argument. It is `None` when `start()` has +no setup callback. For expensive runtime resources, create them once per worker +session and reuse the returned context for every task and retry: + +```python +def setup(): + return create_runtime() + + +def execute_with_runtime(task, runtime): + return runtime.process(task) + + +runner.start(execute_with_runtime, setup=setup) +``` + +Setup runs in the background worker thread, so `start()` still returns promptly. +While setup executes, `runner.status()["state"]` is `"setting_up"`; after setup +succeeds it becomes `"running"` before the first task is claimed. +If pause is requested while setup is running, setup finishes and the worker exits +before claiming a task. A later `start()` calls setup again. Context is runtime +state: it is not persisted or included in results, and the runner does not close +it automatically. Applications that require deterministic resource cleanup must +manage that cleanup themselves. + +## Inspect progress and results + +```{code-cell} ipython3 +status = %there get runner.status() +status +``` + +Results can be inspected while work is still running: + +```{code-cell} ipython3 +results = %there get runner.results() +results +``` + +## Wait for completion + +Run this cell to wait up to 50 seconds while keeping the device's UI responsive: + +```{code-cell} ipython3 +%%there --worker +stopped = runner.wait(timeout=50) +print("Worker stopped:", stopped) +print(runner.status()) +``` + +If `stopped` is `False`, tasks are still running; run the cell again to keep +waiting. `True` means the worker has stopped, which can also happen after a +pause or an error. A `completed` state includes tasks that exhausted their +retries. Inspect any failures from the notebook: + +```{code-cell} ipython3 +failures = %there get runner.failed() +failures +``` + +## Pause and resume + +`pause()` lets the current task finish and stops before claiming another. Wait +for that graceful pause before inspecting its final paused state: + +```{code-cell} ipython3 +%%there --worker +runner.pause() +runner.wait(timeout=10) +print(runner.status()) +``` + +Resume the remaining tasks with the same executor: + +```{code-cell} ipython3 +%%there +runner.start(execute_task) +``` + +## Reopen after PythonHere restarts + +The task list and results are persistent, but Python callables and other runtime +objects are not. After restarting PythonHere, reconnect, recreate the executor, +open the named run, and start it again: + +```{code-cell} ipython3 +%%there +import time + +from tasks_here import TaskRunner + + +def execute_task(task, context): + time.sleep(1) + return { + "value": task["value"], + "square": task["value"] ** 2, + } + + +runner = TaskRunner.open("squares-example") +runner.start(execute_task) +``` + +Execution is at least once. If PythonHere stops after an executor begins but +before its result is committed, that task can run again. Executors with +irreversible side effects should therefore be idempotent or check durable state +before applying those effects. diff --git a/pyproject.toml b/pyproject.toml index 14fdd16..bf0793f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -26,6 +26,7 @@ dependencies = [ "ipython", "ipywidgets", "Pillow", + "persist-queue==1.1.0", ] [project.optional-dependencies] diff --git a/pythonhere/.agents/skills/pythonhere/SKILL.md b/pythonhere/.agents/skills/pythonhere/SKILL.md index 0a9c6fd..9d73a29 100644 --- a/pythonhere/.agents/skills/pythonhere/SKILL.md +++ b/pythonhere/.agents/skills/pythonhere/SKILL.md @@ -1,6 +1,6 @@ --- name: pythonhere -description: "Build, inspect, and debug PythonHere applications by executing Python through the `there` CLI in an already-running Kivy/Python-for-Android process. Use when a task targets a PythonHere device or `there.env` connection and involves live Kivy UI, KV language, Android APIs, Pyjnius, permissions, installed Android packages, media/files, Plyer device features, BLE with able, MIDI with midistream, or on-device AI with LiteRT-LM and `.litertlm` models." +description: "Build, inspect, and debug PythonHere applications by executing Python through the `there` CLI in an already-running Kivy/Python-for-Android process. Use when a task targets a PythonHere device or `there.env` connection and involves live Kivy UI, KV language, Android APIs, Pyjnius, permissions, installed Android packages, media/files, Plyer device features, BLE with able, MIDI with midistream, durable on-device task runs, or on-device AI with LiteRT-LM and `.litertlm` models." --- # Operate PythonHere with `there` @@ -42,6 +42,8 @@ when the task depends on it broadly or requires its exact current contents. - Consult [midi.md](references/midi.md) for MIDI or synthesizer work. - Consult [litert.md](references/litert.md) for PythonHere's ML model helpers and LiteRT-LM usage. +- Consult [tasks.md](references/tasks.md) for durable sequential work that must + continue after a client disconnect or recover after PythonHere restarts. Combine references when a feature genuinely needs details from several concerns; for example, an Android gallery may need permission, MediaStore, and diff --git a/pythonhere/.agents/skills/pythonhere/references/tasks.md b/pythonhere/.agents/skills/pythonhere/references/tasks.md new file mode 100644 index 0000000..dc5aaad --- /dev/null +++ b/pythonhere/.agents/skills/pythonhere/references/tasks.md @@ -0,0 +1,58 @@ +# Durable task runs + +Use `TaskRunner` for sequential work that must continue after the client +disconnects, retain progress across a PythonHere restart, or retry individual +items. + +## Start a run + +```python +from tasks_here import TaskRunner + +runner = TaskRunner.create("data-import", max_attempts=3) +runner.add([ + {"id": "part-1", "path": "one.json"}, + {"id": "part-2", "path": "two.json"}, +]) +runner.start(execute_task) +``` + +Tasks and results must contain plain JSON-compatible values. Every task needs a +unique nonempty string `id`. `start()` returns promptly and processes one task +at a time. Preserve the runner in a named global when later commands need it. + +Inspect `runner.status()`, `runner.results()`, `runner.get(id)`, or +`runner.failed()` through normal `there get` calls. `pause()` finishes the +current item and stops before claiming another. + +## Wait and inspect the outcome + +After starting the runner, wait in bounded intervals through the CLI: + +```bash +there --json --timeout 60 get --worker \ + "{'stopped': runner.wait(timeout=50), 'status': runner.status()}" +``` + +Here, `--worker` keeps the wait off the app's event loop. +Keep the CLI timeout longer than the wait timeout to allow time for connection +and response. If `stopped` is `false`, tasks continue running; repeat the command +to wait again. A `true` value only means the worker is no longer running (or was +never started), not that every task succeeded. Inspect `status.state`, +`status.failed`, and `status.worker_error`. A `completed` state includes tasks +that exhausted their retries; inspect `runner.failed()` for their errors. + +## Resume after restart + +After PythonHere restarts, reopen the named run, recreate resources and the +executor callable, then restart execution: + +```python +runner = TaskRunner.open("data-import") +runner.start(execute_task) +``` + +Execution is at least once: an item interrupted by process death can run again. +Make irreversible executor side effects idempotent or check their durable state +before applying them. The executor runs in a background thread; marshal Kivy UI +access to the main thread according to `kivy-runtime.md`. diff --git a/pythonhere/tasks_here.py b/pythonhere/tasks_here.py new file mode 100644 index 0000000..86f8575 --- /dev/null +++ b/pythonhere/tasks_here.py @@ -0,0 +1,1273 @@ +"""Durable sequential task execution for PythonHere. + +TaskRunner provides persistent named runs with retries, progress inspection, +and at-least-once recovery after process interruption. + +An optional setup callback can create runtime state once per worker session:: + + def setup(): + return create_runtime() + + def execute_task(task, runtime): + return runtime.process(task) + + runner.start(execute_task, setup=setup) + +Without setup, the executor still receives a second argument, whose value is +``None``:: + + def execute_task(task, context): + return task["value"] * 2 + + runner.start(execute_task) +""" + +from __future__ import annotations + +import copy +import json +import logging +import os +import re +import shutil +import sys +import threading +import time +import traceback +from collections.abc import Callable, Iterable, Mapping +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +from persistqueue import SQLiteAckQueue +from persistqueue.exceptions import Empty + +# pylint: disable=too-many-lines + +__all__ = [ + "TaskRunner", + "TaskRunnerError", + "TaskRunExistsError", + "TaskRunNotFoundError", + "DuplicateTaskError", + "TaskSubmissionError", + "TaskRunnerAlreadyRunningError", + "TaskRunnerBusyError", + "TaskRunnerClosedError", + "task_runs_directory", +] + + +log = logging.getLogger(__name__) + +_SCHEMA_VERSION = 1 +_RUN_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$") + +# persist-queue SQLiteAckQueue status values in 1.1.0. +# Keep these local rather than importing a private implementation class. +_PQ_INITED = "0" +_PQ_READY = "1" +_PQ_UNACK = "2" +_PQ_ACKED = "5" +_PQ_FAILED = "9" + +_REGISTRY_LOCK = threading.RLock() +_INSTANCES: dict[str, TaskRunner] = {} + +# Runs are exclusive process-wide by default so separate workloads cannot +# accidentally compete for a shared device or another constrained resource. +# Set exclusive=False when parallel independent runners are explicitly desired. +_EXECUTION_OWNER: dict[str, str] = {} + + +class TaskRunnerError(RuntimeError): + """Base error for TaskRunner.""" + + +class TaskRunExistsError(TaskRunnerError): + """A run with this name already exists.""" + + +class TaskRunNotFoundError(TaskRunnerError): + """The requested run does not exist.""" + + +class DuplicateTaskError(TaskRunnerError): + """A task id already exists in the run.""" + + +class TaskSubmissionError(TaskRunnerError): + """Storage failed during submission; inspect the run before resubmitting.""" + + def __init__(self, submitted_ids: list[str]): + self.submitted_ids = submitted_ids + super().__init__( + f"Submission failed after {len(submitted_ids)} confirmed writes; " + "inspect get(id) before resubmitting missing tasks" + ) + + +class TaskRunnerAlreadyRunningError(TaskRunnerError): + """This runner already has an active worker.""" + + +class TaskRunnerBusyError(TaskRunnerError): + """Another exclusive TaskRunner is already executing.""" + + +class TaskRunnerClosedError(TaskRunnerError): + """Operation attempted on a closed runner.""" + + +def _utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def task_runs_directory() -> Path: + """ + Return the default persistent TaskRunner directory. + + Override with PYTHONHERE_TASKS_DIR when needed. Android uses the current + application's private files directory; desktop uses its user data directory. + """ + configured = os.environ.get("PYTHONHERE_TASKS_DIR") + if configured: + return Path(configured).expanduser().resolve() + + if sys.platform == "android" or "ANDROID_ARGUMENT" in os.environ: + from android.storage import app_storage_path + + return Path(app_storage_path()) / "task-runs" + data_home = os.environ.get("XDG_DATA_HOME") + base = Path(data_home).expanduser() if data_home else Path.home() / ".local/share" + return base / "pythonhere/task-runs" + + +def _plain_value(value: Any) -> Any: + """Validate and snapshot portable values before writing or invoking user code.""" + + def check(item): + if item is None or isinstance(item, (bool, int, float, str)): + return + if isinstance(item, list): + for child in item: + check(child) + return + if isinstance(item, dict) and all(isinstance(key, str) for key in item): + for child in item.values(): + check(child) + return + raise TypeError("Tasks and results must contain plain JSON-compatible values") + + check(value) + return json.loads(json.dumps(value, allow_nan=False)) + + +def _normalize_root(root: str | os.PathLike[str] | None) -> Path: + if root is None: + return task_runs_directory() + return Path(root).expanduser().resolve() + + +def _validate_name(name: str) -> str: + if not isinstance(name, str) or not _RUN_NAME_RE.fullmatch(name): + raise ValueError(r"TaskRunner name must match [A-Za-z0-9][A-Za-z0-9._-]*") + if name in {".", ".."}: + raise ValueError("Invalid TaskRunner name") + return name + + +def _run_path(name: str, root: Path) -> Path: + return root / _validate_name(name) + + +def _registry_key(path: Path) -> str: + return str(path.resolve()) + + +def _atomic_write_json(path: Path, value: Mapping[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + + tmp = path.with_name(f".{path.name}.tmp-{os.getpid()}-{threading.get_ident()}") + + try: + with tmp.open("w", encoding="utf-8") as f: + json.dump( + value, + f, + indent=2, + sort_keys=True, + ensure_ascii=False, + ) + f.write("\n") + f.flush() + os.fsync(f.fileno()) + + os.replace(tmp, path) + finally: + try: + tmp.unlink() + except FileNotFoundError: + pass + + +def _read_json(path: Path) -> dict[str, Any]: + try: + with path.open("r", encoding="utf-8") as f: + value = json.load(f) + except FileNotFoundError as exc: + raise TaskRunNotFoundError(f"Task run metadata not found: {path}") from exc + + if not isinstance(value, dict): + raise TaskRunnerError(f"Invalid TaskRunner metadata: {path}") + + return value + + +def _status_name(status: Any) -> str: + status = str(status) + + if status in {_PQ_INITED, _PQ_READY}: + return "pending" + if status == _PQ_UNACK: + return "running" + if status == _PQ_ACKED: + return "done" + if status == _PQ_FAILED: + return "failed" + + return f"unknown:{status}" + + +class TaskRunner: + """ + Durable single-worker task runner. + + Use create() and open() instead of constructing this class directly. + + A run stores each task, its attempt history, result/error information, and + queue status on disk. SQLiteAckQueue provides durable acknowledgement and + recovery of tasks that were in-flight when the process died. + """ + + def __init__( + self, + *, + name: str, + root: Path, + metadata: dict[str, Any], + auto_resume: bool, + ) -> None: + self.name = name + self.root = root + self.path = _run_path(name, root) + self._meta_path = self.path / "meta.json" + self._queue_path = self.path / "queue" + + self.max_attempts = int(metadata["max_attempts"]) + self.exclusive = bool(metadata.get("exclusive", True)) + self._user_metadata = copy.deepcopy(metadata.get("metadata") or {}) + + self._lock = threading.RLock() + self._pause_requested = threading.Event() + self._thread: threading.Thread | None = None + self._current_task_id: str | None = None + self._current_pqid: int | None = None + self._closed = False + self._worker_error: dict[str, Any] | None = None + + self._state = str(metadata.get("state", "idle")) + self._created_at = str(metadata.get("created_at", _utc_now())) + + self.path.mkdir(parents=True, exist_ok=True) + + self._queue = SQLiteAckQueue( + str(self._queue_path), + auto_resume=auto_resume, + multithreading=True, + ) + + # There are two small commit windows: + # + # 1. result persisted, process dies before ack() + # 2. final error persisted, process dies before ack_failed() + # + # auto_resume makes both rows READY. Repair their queue status from the + # durable record so already committed work is not needlessly rerun. + self._recover_committed_records() + + # ------------------------------------------------------------------ + # Lifecycle + # ------------------------------------------------------------------ + + @classmethod + def create( # pylint: disable=too-many-arguments + cls, + name: str, + *, + max_attempts: int = 3, + metadata: Mapping[str, Any] | None = None, + root: str | os.PathLike[str] | None = None, + exclusive: bool = True, + ) -> TaskRunner: + """ + Create a new durable named run. + + Raises TaskRunExistsError when the name already exists. + """ + name = _validate_name(name) + root_path = _normalize_root(root) + path = _run_path(name, root_path) + key = _registry_key(path) + + if ( + not isinstance(max_attempts, int) + or isinstance(max_attempts, bool) + or max_attempts < 1 + ): + raise ValueError("max_attempts must be a positive integer") + + # Use the same portable value contract for user metadata. + user_metadata = _plain_value(dict(metadata or {})) + with _REGISTRY_LOCK: + if key in _INSTANCES or path.exists(): + raise TaskRunExistsError(f"Task run {name!r} already exists") + + path.mkdir(parents=True, exist_ok=False) + + created_at = _utc_now() + initial_meta = { + "schema_version": _SCHEMA_VERSION, + "name": name, + "created_at": created_at, + "updated_at": created_at, + "max_attempts": int(max_attempts), + "exclusive": bool(exclusive), + "state": "idle", + "metadata": user_metadata, + "summary": { + "total": 0, + "pending": 0, + "running": 0, + "completed": 0, + "failed": 0, + "progress": 0.0, + }, + "worker_error": None, + } + + try: + _atomic_write_json(path / "meta.json", initial_meta) + runner = cls( + name=name, + root=root_path, + metadata=initial_meta, + auto_resume=False, + ) + except Exception: + shutil.rmtree(path, ignore_errors=True) + raise + + _INSTANCES[key] = runner + + runner._refresh_meta(state="idle") + return runner + + @classmethod + def open( + cls, + name: str, + *, + root: str | os.PathLike[str] | None = None, + ) -> TaskRunner: + """ + Open an existing run. + + If this Python process already has the run open, the existing object is + returned. This is important: creating a second SQLiteAckQueue with + auto_resume=True while the first runner is actively executing could + reset its in-flight row. + """ + name = _validate_name(name) + root_path = _normalize_root(root) + path = _run_path(name, root_path) + key = _registry_key(path) + + with _REGISTRY_LOCK: + existing = _INSTANCES.get(key) + if existing is not None and not existing._closed: + return existing + + meta_path = path / "meta.json" + if not meta_path.exists(): + raise TaskRunNotFoundError(f"Task run {name!r} does not exist") + + metadata = _read_json(meta_path) + + if metadata.get("schema_version") != _SCHEMA_VERSION: + raise TaskRunnerError( + f"Unsupported TaskRunner schema version: " + f"{metadata.get('schema_version')!r}" + ) + + if metadata.get("name") != name: + raise TaskRunnerError( + f"TaskRunner metadata name mismatch in {meta_path}" + ) + + runner = cls( + name=name, + root=root_path, + metadata=metadata, + auto_resume=True, + ) + _INSTANCES[key] = runner + + counts = runner._counts() + previous_state = str(metadata.get("state", "idle")) + + if counts["total"] and ( + counts["completed"] + counts["failed"] == counts["total"] + ): + state = "completed" + elif previous_state == "paused": + state = "paused" + elif previous_state == "idle": + state = "idle" + else: + # A previous process said it was running (or was already marked + # interrupted), but this process has no worker for it. + state = "interrupted" + + runner._refresh_meta(state=state) + return runner + + @classmethod + def list( + cls, + *, + root: str | os.PathLike[str] | None = None, + ) -> list[dict[str, Any]]: + """ + List persisted runs without reopening their queues. + + Reading meta.json rather than constructing SQLiteAckQueue instances is + intentional: list() must never trigger auto-resume on a live run. + """ + root_path = _normalize_root(root) + if not root_path.exists(): + return [] + + result: list[dict[str, Any]] = [] + + for path in root_path.iterdir(): + if not path.is_dir(): + continue + + meta_path = path / "meta.json" + if not meta_path.is_file(): + continue + + try: + meta = _read_json(meta_path) + except Exception: + log.exception( + "TaskRunner: could not read metadata from %s", + meta_path, + ) + continue + + key = _registry_key(path) + with _REGISTRY_LOCK: + live = _INSTANCES.get(key) + + if live is not None and not live._closed: + try: + result.append(live.status()) + continue + except Exception: + log.exception( + "TaskRunner: could not inspect live run %s", + path.name, + ) + + summary = dict(meta.get("summary") or {}) + state = str(meta.get("state", "idle")) + + # Active states in persisted metadata cannot still be active in + # this process if no registered live instance exists. + if state in {"running", "setting_up"}: + state = "interrupted" + + result.append( + { + "name": meta.get("name", path.name), + "state": state, + "max_attempts": meta.get("max_attempts"), + "exclusive": meta.get("exclusive", True), + "created_at": meta.get("created_at"), + "updated_at": meta.get("updated_at"), + "metadata": copy.deepcopy(meta.get("metadata") or {}), + **summary, + } + ) + + result.sort( + key=lambda item: str(item.get("updated_at") or ""), + reverse=True, + ) + return result + + def close(self) -> None: + """ + Close local SQLite resources. + + A running worker cannot be closed. Closing does not delete the run. + """ + with self._lock: + self._ensure_open() + if self.is_running(): + raise TaskRunnerAlreadyRunningError("Cannot close a running TaskRunner") + + self._queue.close() + self._closed = True + + key = _registry_key(self.path) + with _REGISTRY_LOCK: + if _INSTANCES.get(key) is self: + _INSTANCES.pop(key, None) + + def delete(self) -> None: + """ + Permanently delete this run and all stored tasks/results. + + The runner must not be active. + """ + with self._lock: + self._ensure_open() + if self.is_running(): + raise TaskRunnerAlreadyRunningError( + "Cannot delete a running TaskRunner" + ) + + path = self.path + self.close() + shutil.rmtree(path) + + def __enter__(self) -> TaskRunner: + self._ensure_open() + return self + + def __exit__(self, exc_type, exc, tb) -> None: + self.close() + + # ------------------------------------------------------------------ + # Submission and execution + # ------------------------------------------------------------------ + + def add(self, tasks: Iterable[Mapping[str, Any]]) -> int: + """ + Durably add tasks. + + Each task must be a mapping containing a non-empty string ``id``. + Duplicate ids are rejected across the whole run. + + Validation failures write nothing. Storage failures may commit a prefix; + TaskSubmissionError reports confirmed IDs. Inspect get(id) before retrying. + Returns the number of tasks added. + """ + with self._lock: + self._ensure_open() + + if self.is_running(): + raise TaskRunnerAlreadyRunningError( + "Cannot add tasks while the runner is active" + ) + + existing_ids = { + record["task_id"] + for record in self._all_queue_records() + if isinstance(record.get("task_id"), str) + } + + prepared: list[dict[str, Any]] = [] + submitted_ids: set[str] = set() + + for original in tasks: + if not isinstance(original, Mapping): + raise TypeError( + f"Task must be a mapping, got {type(original).__name__}" + ) + + task = _plain_value(dict(original)) + task_id = task.get("id") + + if not isinstance(task_id, str) or not task_id: + raise ValueError("Each task must contain a non-empty string 'id'") + + if task_id in existing_ids or task_id in submitted_ids: + raise DuplicateTaskError(f"Duplicate task id: {task_id!r}") + + prepared.append( + { + "schema_version": _SCHEMA_VERSION, + "task_id": task_id, + "task": task, + "created_at": _utc_now(), + "attempts": [], + "result_present": False, + "result": None, + "completed_at": None, + } + ) + submitted_ids.add(task_id) + + confirmed_ids = [] + try: + for record in prepared: + self._queue.put(record) + confirmed_ids.append(record["task_id"]) + + if prepared: + self._pause_requested.clear() + self._worker_error = None + self._refresh_meta(state="idle") + except Exception as exc: + raise TaskSubmissionError(confirmed_ids) from exc + + return len(prepared) + + def start( + self, + execute: Callable[[dict[str, Any], Any], Any], + *, + setup: Callable[[], Any] | None = None, + ) -> TaskRunner: + """ + Start/resume sequential execution in a daemon background thread. + + The method returns immediately. + + ``setup()``, when supplied, runs once in the worker thread before any + task is claimed. Its return value is passed unchanged to every + ``execute(task, context)`` call in that worker session. Without setup, + context is ``None``. Executors must return plain JSON-compatible data. + Executor and result-validation errors consume the max_attempts failure + budget. Interrupted executions do not consume it. Retries run after + later ready rows, wrapping to the beginning when needed. + + The runner does not retain or clean up context after the worker exits. + Applications remain responsible for deterministic resource cleanup. + """ + if not callable(execute): + raise TypeError("execute must be callable") + if setup is not None and not callable(setup): + raise TypeError("setup must be callable or None") + + with self._lock: + self._ensure_open() + + if self.is_running(): + raise TaskRunnerAlreadyRunningError( + f"Task run {self.name!r} is already running" + ) + + # Repair a stale unack row left by an unexpected worker-thread + # failure in the same process, then repair any committed-but-not- + # acked records. + self._queue.resume_unack_tasks() + self._recover_committed_records() + + counts = self._counts() + if counts["pending"] == 0: + state = "completed" if counts["total"] > 0 else "idle" + self._refresh_meta(state=state) + return self + + self._claim_execution() + + try: + self._pause_requested.clear() + self._worker_error = None + self._current_task_id = None + self._current_pqid = None + initial_state = "setting_up" if setup is not None else "running" + self._refresh_meta(state=initial_state) + + thread = threading.Thread( + target=self._run_loop, + args=(execute, setup), + name=f"TaskRunner[{self.name}]", + daemon=True, + ) + self._thread = thread + + thread.start() + except Exception: + self._thread = None + self._release_execution() + self._state = "interrupted" + try: + self._refresh_meta(state="interrupted") + except Exception: + log.exception( + "TaskRunner %s: could not persist start failure", + self.name, + ) + raise + + return self + + def pause(self) -> None: + """ + Request a graceful pause. + + The current execute() call is not cancelled. The worker finishes the + current attempt and stops before taking another task. + """ + with self._lock: + self._ensure_open() + + if self.is_running(): + self._pause_requested.set() + else: + counts = self._counts() + if counts["pending"] > 0: + self._refresh_meta(state="paused") + + def wait(self, timeout: float | None = None) -> bool: + """ + Wait for the current worker thread. + + Returns True if it is no longer running, False on timeout. + """ + with self._lock: + self._ensure_open() + thread = self._thread + + if thread is None: + return True + + thread.join(timeout) + return not thread.is_alive() + + def is_running(self) -> bool: + thread = self._thread + return thread is not None and thread.is_alive() + + # ------------------------------------------------------------------ + # Inspection + # ------------------------------------------------------------------ + + @property + def metadata(self) -> dict[str, Any]: + return copy.deepcopy(self._user_metadata) + + def status(self) -> dict[str, Any]: + """Return a small plain dictionary suitable for ``%there get``.""" + with self._lock: + self._ensure_open() + + counts = self._counts() + + if self.is_running(): + state = "setting_up" if self._state == "setting_up" else "running" + elif ( + counts["total"] > 0 + and counts["completed"] + counts["failed"] == counts["total"] + ): + state = "completed" + else: + state = self._state + if state in {"running", "setting_up"}: + state = "interrupted" + + return { + "name": self.name, + "state": state, + **counts, + "current": self._current_task_id, + "pause_requested": self._pause_requested.is_set(), + "max_attempts": self.max_attempts, + "exclusive": self.exclusive, + "created_at": self._created_at, + "updated_at": self._meta_updated_at(), + "metadata": copy.deepcopy(self._user_metadata), + "worker_error": copy.deepcopy(self._worker_error), + "path": str(self.path), + } + + def results(self) -> list[dict[str, Any]]: + """ + Return all task records in submission order. + + This intentionally includes pending/running/failed tasks so the caller + can inspect a run before it is complete. + """ + with self._lock: + self._ensure_open() + rows = sorted(self._queue.queue(), key=lambda row: row["id"]) + return [self._public_record(row) for row in rows] + + def failed(self) -> list[dict[str, Any]]: + """Return permanently failed task records.""" + return [record for record in self.results() if record["status"] == "failed"] + + def get(self, task_id: str) -> dict[str, Any] | None: + """Return one task record by logical id, or None if not found.""" + if not isinstance(task_id, str): + raise TypeError("task_id must be a string") + + with self._lock: + self._ensure_open() + + for row in self._queue.queue(): + data = row.get("data") + if isinstance(data, dict) and data.get("task_id") == task_id: + return self._public_record(row) + + return None + + # ------------------------------------------------------------------ + # Worker internals + # ------------------------------------------------------------------ + + def _run_loop( # noqa: PLR0912, PLR0915 # pylint: disable=too-many-locals,too-many-branches,too-many-statements + self, + execute: Callable[[dict[str, Any], Any], Any], + setup: Callable[[], Any] | None, + ) -> None: + final_state = "interrupted" + + previous_id = None + phase = "setup" + try: + context = setup() if setup is not None else None + phase = "execution" + + if setup is not None: + with self._lock: + self._refresh_meta(state="running") + + while True: + with self._lock: + if self._pause_requested.is_set(): + break + try: + item = self._queue.get( + block=False, + raw=True, + id=previous_id, + next_in_order=previous_id is not None, + ) + except Empty: + final_state = "completed" + break + self._current_pqid = int(item["pqid"]) + + pqid = int(item["pqid"]) + previous_id = pqid + record = item["data"] + + if not isinstance(record, dict): + # This should never happen for a TaskRunner-created queue. + self._queue.ack_failed(id=pqid) + log.error( + "TaskRunner %s: invalid queue record %r", + self.name, + record, + ) + continue + + task = record.get("task") + task_id = record.get("task_id") + + if not isinstance(task, dict) or not isinstance(task_id, str): + self._queue.ack_failed(id=pqid) + log.error( + "TaskRunner %s: invalid task record pqid=%s", + self.name, + pqid, + ) + continue + + attempt_number = len(record.get("attempts") or []) + 1 + attempt = { + "number": attempt_number, + "started_at": _utc_now(), + "finished_at": None, + "duration": None, + "error": None, + } + + record.setdefault("attempts", []).append(attempt) + + with self._lock: + self._current_task_id = task_id + self._current_pqid = pqid + # Commit "attempt started" before entering arbitrary user + # code. A process kill from this point onward is visible + # during recovery. + self._queue.update({"pqid": pqid, "data": record}) + self._refresh_meta(state="running") + + started = time.monotonic() + log.info( + "TaskRunner %s: starting %s attempt %d/%d", + self.name, + task_id, + attempt_number, + self.max_attempts, + ) + + try: + result = _plain_value(execute(copy.deepcopy(task), context)) + except Exception as exc: + duration = time.monotonic() - started + + with self._lock: + attempt["finished_at"] = _utc_now() + attempt["duration"] = duration + attempt["error"] = { + "type": type(exc).__name__, + "message": str(exc), + "traceback": traceback.format_exc(), + } + + record["last_error"] = copy.deepcopy(attempt["error"]) + self._queue.update({"pqid": pqid, "data": record}) + + failure_count = self._failure_count(record) + + if failure_count >= self.max_attempts: + self._queue.ack_failed(id=pqid) + log.exception( + "TaskRunner %s: task %s failed " + "permanently after %d failures", + self.name, + task_id, + failure_count, + ) + else: + self._queue.nack(id=pqid) + log.warning( + "TaskRunner %s: task %s failed " + "(failure %d/%d, execution attempt %d): %s", + self.name, + task_id, + failure_count, + self.max_attempts, + attempt_number, + exc, + ) + + self._current_task_id = None + self._current_pqid = None + self._refresh_meta(state="running") + + else: + duration = time.monotonic() - started + + with self._lock: + attempt["finished_at"] = _utc_now() + attempt["duration"] = duration + record["result"] = result + record["result_present"] = True + record["completed_at"] = _utc_now() + record.pop("last_error", None) + + # Commit result before ack. If the process dies in the + # tiny window before ack(), open() recognizes this + # durable completion and repairs the queue status. + self._queue.update({"pqid": pqid, "data": record}) + self._queue.ack(id=pqid) + + self._current_task_id = None + self._current_pqid = None + self._refresh_meta(state="running") + + log.info( + "TaskRunner %s: completed %s in %.3fs", + self.name, + task_id, + duration, + ) + + if self._pause_requested.is_set(): + final_state = "paused" + + except BaseException as exc: + # Unexpected failures of runner machinery should not lose the + # currently claimed queue item. Return it to READY when possible. + if phase == "setup": + log.exception("TaskRunner %s: setup failed", self.name) + else: + log.exception( + "TaskRunner %s: worker stopped unexpectedly", + self.name, + ) + + with self._lock: + self._worker_error = { + "type": type(exc).__name__, + "message": str(exc), + "traceback": traceback.format_exc(), + "time": _utc_now(), + } + + if self._current_pqid is not None: + try: + self._queue.nack(id=self._current_pqid) + except Exception: + log.exception( + "TaskRunner %s: could not nack interrupted pqid=%s", + self.name, + self._current_pqid, + ) + + self._current_task_id = None + self._current_pqid = None + + final_state = "interrupted" + + finally: + with self._lock: + self._current_task_id = None + self._current_pqid = None + + # If no runnable work is left, terminal status wins over + # "paused". + try: + counts = self._counts() + if ( + counts["total"] > 0 + and counts["completed"] + counts["failed"] == counts["total"] + ): + final_state = "completed" + except Exception: + log.exception( + "TaskRunner %s: could not compute final status", + self.name, + ) + + try: + self._refresh_meta(state=final_state) + except Exception: + log.exception( + "TaskRunner %s: could not persist final metadata", + self.name, + ) + + self._release_execution() + + # ------------------------------------------------------------------ + # Persistence helpers + # ------------------------------------------------------------------ + + def _recover_committed_records(self) -> None: + """ + Repair READY rows whose result/final failure was already persisted. + + SQLiteAckQueue auto-resume intentionally turns old UNACK rows back to + READY. Usually they should be rerun. The exception is when TaskRunner + already committed a successful result or the final failed attempt and + the old process died immediately before ack()/ack_failed(). + """ + for row in self._queue.queue(): + if str(row.get("status")) not in { + _PQ_INITED, + _PQ_READY, + }: + continue + + pqid = int(row["id"]) + record = row.get("data") + + if not isinstance(record, dict): + continue + + if record.get("result_present") is True and record.get("completed_at"): + self._queue.ack(id=pqid) + continue + + attempts = record.get("attempts") + if not isinstance(attempts, list) or not attempts: + continue + + last_attempt = attempts[-1] + if not isinstance(last_attempt, dict): + continue + + # A process kill is an interrupted execution attempt, not an + # executor failure. Preserve it in history, but do not consume the + # max_attempts failure budget. + if ( + last_attempt.get("started_at") + and not last_attempt.get("finished_at") + and last_attempt.get("error") is None + and not last_attempt.get("interrupted_at") + ): + last_attempt["interrupted_at"] = _utc_now() + last_attempt["interrupted"] = True + self._queue.update({"pqid": pqid, "data": record}) + + if self._failure_count(record) >= self.max_attempts: + self._queue.ack_failed(id=pqid) + + # ack() and ack_failed() normally follow get(), which already removed + # the item from qsize(). Recovered items were put back into READY by + # auto-resume, so recalculate the public pending counter after repair. + self._queue.resume_unack_tasks() + + @staticmethod + def _failure_count(record: Mapping[str, Any]) -> int: + attempts = record.get("attempts") + if not isinstance(attempts, list): + return 0 + + return sum( + 1 + for attempt in attempts + if isinstance(attempt, dict) + and attempt.get("finished_at") + and attempt.get("error") is not None + ) + + def _all_queue_records(self) -> list[dict[str, Any]]: + records: list[dict[str, Any]] = [] + + for row in self._queue.queue(): + data = row.get("data") + if isinstance(data, dict): + records.append(data) + + return records + + def _counts(self) -> dict[str, Any]: + # Public count helpers do not deserialize prompts or results. qsize() + # includes persist-queue's newly inserted and retry-ready rows. + pending = self._queue.qsize() + running = self._queue.unack_count() + completed = self._queue.acked_count() + failed = self._queue.ack_failed_count() + + total = pending + running + completed + failed + terminal = completed + failed + + return { + "total": total, + "pending": pending, + "running": running, + "completed": completed, + "failed": failed, + "progress": (terminal / total) if total else 0.0, + } + + def _public_record( + self, + row: Mapping[str, Any], + ) -> dict[str, Any]: + record = row.get("data") + + if not isinstance(record, dict): + return { + "id": None, + "status": _status_name(row.get("status")), + "task": None, + "result": None, + "attempt_count": 0, + "attempts": [], + "error": { + "type": "TaskRunnerRecordError", + "message": "Invalid persisted task record", + }, + } + + attempts = copy.deepcopy(record.get("attempts") or []) + + durations = [ + attempt.get("duration") + for attempt in attempts + if isinstance(attempt, dict) + and isinstance(attempt.get("duration"), (int, float)) + ] + + result_present = bool(record.get("result_present")) + + return { + "id": record.get("task_id"), + "status": _status_name(row.get("status")), + "task": copy.deepcopy(record.get("task")), + "result": (copy.deepcopy(record.get("result")) if result_present else None), + "result_present": result_present, + "attempt_count": len(attempts), + "failure_count": self._failure_count(record), + "attempts": attempts, + "duration": durations[-1] if durations else None, + "total_duration": sum(durations), + "error": copy.deepcopy(record.get("last_error")), + "created_at": record.get("created_at"), + "completed_at": record.get("completed_at"), + } + + def _refresh_meta(self, *, state: str | None = None) -> None: + if state is not None: + self._state = state + + now = _utc_now() + counts = self._counts() + + meta = { + "schema_version": _SCHEMA_VERSION, + "name": self.name, + "created_at": self._created_at, + "updated_at": now, + "max_attempts": self.max_attempts, + "exclusive": self.exclusive, + "state": self._state, + "metadata": copy.deepcopy(self._user_metadata), + "summary": counts, + "worker_error": copy.deepcopy(self._worker_error), + } + + _atomic_write_json(self._meta_path, meta) + + def _meta_updated_at(self) -> str | None: + try: + return _read_json(self._meta_path).get("updated_at") + except Exception: + return None + + # ------------------------------------------------------------------ + # Process-wide execution ownership + # ------------------------------------------------------------------ + + def _claim_execution(self) -> None: + if not self.exclusive: + return + + key = _registry_key(self.path) + + with _REGISTRY_LOCK: + owner = _EXECUTION_OWNER.get("path") + if owner is not None and owner != key: + owner_name = Path(owner).name + raise TaskRunnerBusyError( + f"Another exclusive task run is active: {owner_name!r}" + ) + + _EXECUTION_OWNER["path"] = key + + def _release_execution(self) -> None: + if not self.exclusive: + return + + key = _registry_key(self.path) + + with _REGISTRY_LOCK: + if _EXECUTION_OWNER.get("path") == key: + _EXECUTION_OWNER.pop("path") + + def _ensure_open(self) -> None: + if self._closed: + raise TaskRunnerClosedError(f"Task run {self.name!r} is closed") diff --git a/tests/test_pythonhere_skill.py b/tests/test_pythonhere_skill.py index 98f077e..1345189 100644 --- a/tests/test_pythonhere_skill.py +++ b/tests/test_pythonhere_skill.py @@ -22,8 +22,9 @@ "litert.md", "midi.md", "plyer.md", + "tasks.md", } -RUNTIME_PROMPT_NAMES = REFERENCE_NAMES - {"litert.md"} +RUNTIME_PROMPT_NAMES = REFERENCE_NAMES - {"litert.md", "tasks.md"} def test_pythonhere_skill_files_exist(): diff --git a/tests/test_tasks_here.py b/tests/test_tasks_here.py new file mode 100644 index 0000000..0f809e1 --- /dev/null +++ b/tests/test_tasks_here.py @@ -0,0 +1,649 @@ +"""Tests for the durable sequential task runner.""" + +import subprocess +import sys +import threading +from types import ModuleType + +import pytest + + +@pytest.fixture +def module(): + import tasks_here as module + + yield module + for runner in list(module._INSTANCES.values()): + runner.pause() + assert runner.wait(5) + runner.close() + + +@pytest.fixture +def runner(module, tmp_path): + return module.TaskRunner.create("test", root=tmp_path) + + +def finish(runner, execute, *, setup=None): + runner.start(execute, setup=setup) + assert runner.wait(5) + assert runner.status()["worker_error"] is None + + +def test_retry_order_and_reopen(module, runner, tmp_path): + runner.add([{"id": "a"}, {"id": "b"}]) + calls = [] + + def execute(task, context): + assert context is None + calls.append(task["id"]) + if task["id"] == "a" and calls.count("a") == 1: + raise ValueError("temporary") + return task["id"] + + finish(runner, execute) + assert calls == ["a", "b", "a"] + runner.close() + reopened = module.TaskRunner.open("test", root=tmp_path) + assert reopened.status()["completed"] == 2 + assert reopened.get("a")["failure_count"] == 1 + assert [r["result"] for r in reopened.results()] == ["a", "b"] + + +def test_invalid_result_and_mutated_input_do_not_stop_run(runner): + runner.add([{"id": "bad"}, {"id": "good"}]) + + def execute(task, context): + assert context is None + if task["id"] == "bad": + task["oops"] = lambda: None + return lambda: None + return None + + finish(runner, execute) + assert runner.get("bad")["failure_count"] == 3 + assert runner.get("bad")["task"] == {"id": "bad"} + assert runner.get("bad")["status"] == "failed" + assert runner.get("good")["result_present"] is True + assert runner.status()["state"] == "completed" + + +@pytest.mark.parametrize( + "bad", + [ + {"id": "b", "value": lambda: None}, + {"id": "a"}, + {"value": 1}, + {"id": "b", "value": float("nan")}, + ], +) +def test_batch_validation_writes_nothing(runner, bad): + with pytest.raises((TypeError, ValueError, RuntimeError)): + runner.add([{"id": "a"}, bad]) + assert runner.status()["total"] == 0 + + +def test_storage_failure_reports_partial_submission(module, runner, monkeypatch): + put = runner._queue.put + + def broken_put(record): + if record["task_id"] == "b": + raise OSError("disk full") + return put(record) + + with monkeypatch.context() as patch: + patch.setattr(runner._queue, "put", broken_put) + with pytest.raises(module.TaskSubmissionError) as exc: + runner.add([{"id": "a"}, {"id": "b"}]) + assert exc.value.submitted_ids == ["a"] + assert runner.get("a") is not None + assert runner.get("b") is None + runner.add([{"id": "b"}]) + finish(runner, lambda task, context: task["id"]) + assert runner.status()["completed"] == 2 + + +def test_counts_do_not_load_payloads(runner, monkeypatch): + runner.add([{"id": "a"}]) + runner.start(lambda task, context: "ok") + assert runner.wait(5) + + def forbidden(): + pytest.fail("status deserialized queue payloads") + + monkeypatch.setattr(runner._queue, "queue", forbidden) + assert runner.status()["completed"] == 1 + runner._refresh_meta() + + +def test_pending_count_uses_public_queue_size(runner, monkeypatch): + runner.add([{"id": "a"}]) + monkeypatch.setattr(runner._queue, "qsize", lambda: 7) + + def forbidden(): + pytest.fail("pending count used ready_count instead of qsize") + + monkeypatch.setattr(runner._queue, "ready_count", forbidden) + assert runner.status()["pending"] == 7 + + +def test_results_are_sorted_by_queue_id(runner, monkeypatch): + runner.add([{"id": "a"}, {"id": "b"}, {"id": "c"}]) + queue = runner._queue.queue + monkeypatch.setattr(runner._queue, "queue", lambda: list(reversed(queue()))) + assert [record["id"] for record in runner.results()] == ["a", "b", "c"] + + +def test_start_failure_releases_execution(module, runner, tmp_path, monkeypatch): + runner.add([{"id": "a"}]) + other = module.TaskRunner.create("other", root=tmp_path) + other.add([{"id": "b"}]) + + def broken_meta(**kwargs): + raise OSError("disk full") + + with monkeypatch.context() as patch: + patch.setattr(runner, "_refresh_meta", broken_meta) + with pytest.raises(OSError): + runner.start(lambda task, context: None) + finish(other, lambda task, context: "ok") + finish(runner, lambda task, context: "ok") + + +def test_pause_and_same_process_open(module, runner, tmp_path): + entered = threading.Event() + release = threading.Event() + runner.add([{"id": "a"}, {"id": "b"}]) + + def execute(task, context): + assert context is None + entered.set() + assert release.wait(5) + return task["id"] + + runner.start(execute) + try: + assert entered.wait(5) + assert module.TaskRunner.open("test", root=tmp_path) is runner + runner.pause() + finally: + release.set() + assert runner.wait(5) + assert runner.status()["state"] == "paused" + assert runner.get("b")["attempt_count"] == 0 + finish(runner, lambda task, context: task["id"]) + + +def test_setup_context_is_shared_unvalidated_and_on_worker_thread(runner): + runner.add([{"id": "a"}, {"id": "b"}]) + setup_threads = [] + execute_threads = [] + contexts = [] + setup_calls = [] + lock = threading.Lock() + + def setup(): + setup_calls.append(True) + setup_threads.append(threading.get_ident()) + return {"lock": lock, "callable": lambda: 42} + + def execute(task, context): + contexts.append(context) + execute_threads.append(threading.get_ident()) + assert context["lock"] is lock + assert context["callable"]() == 42 + return task["id"] + + finish(runner, execute, setup=setup) + + assert len(setup_calls) == 1 + assert setup_threads[0] != threading.main_thread().ident + assert execute_threads == [setup_threads[0], setup_threads[0]] + assert contexts[0] is contexts[1] + + +def test_context_survives_executor_retry(runner): + runner.add([{"id": "a"}]) + contexts = [] + + def execute(task, context): + contexts.append(context) + if len(contexts) == 1: + raise RuntimeError("temporary") + return task["id"] + + finish(runner, execute, setup=object) + + assert len(contexts) == 2 + assert contexts[0] is contexts[1] + assert runner.get("a")["failure_count"] == 1 + + +def test_setup_failure_preserves_tasks_and_releases_execution( + module, runner, tmp_path, caplog +): + runner.add([{"id": "a"}, {"id": "b"}]) + caplog.set_level("ERROR", logger=module.__name__) + + def fail_setup(): + raise RuntimeError("setup failed") + + runner.start(lambda task, context: task["id"], setup=fail_setup) + assert runner.wait(5) + + status = runner.status() + assert status["state"] == "interrupted" + assert status["pending"] == 2 + assert status["worker_error"]["type"] == "RuntimeError" + assert status["worker_error"]["message"] == "setup failed" + assert all(record["attempt_count"] == 0 for record in runner.results()) + assert "TaskRunner test: setup failed" in caplog.messages + + other = module.TaskRunner.create("other", root=tmp_path) + other.add([{"id": "other"}]) + finish(other, lambda task, context: task["id"]) + + setup_calls = [] + + def setup(): + setup_calls.append(True) + return "ready" + + finish(runner, lambda task, context: context, setup=setup) + assert len(setup_calls) == 1 + assert runner.status()["worker_error"] is None + assert [record["result"] for record in runner.results()] == ["ready", "ready"] + + +def test_pause_during_setup_is_responsive_and_claims_no_task(module, runner, tmp_path): + entered = threading.Event() + release = threading.Event() + contexts = [] + executor_calls = [] + runner.add([{"id": "a"}, {"id": "b"}]) + + def setup(): + context = object() + contexts.append(context) + entered.set() + assert release.wait(5) + return context + + runner.start(lambda task, context: executor_calls.append(task["id"]), setup=setup) + try: + assert entered.wait(5) + assert module.TaskRunner.open("test", root=tmp_path) is runner + status = runner.status() + assert status["state"] == "setting_up" + assert status["current"] is None + assert all(record["attempt_count"] == 0 for record in runner.results()) + assert runner.wait(0.01) is False + + other = module.TaskRunner.create("other", root=tmp_path) + other.add([{"id": "other"}]) + with pytest.raises(module.TaskRunnerBusyError): + other.start(lambda task, context: None) + + runner.pause() + finally: + release.set() + + assert runner.wait(5) + assert runner.status()["state"] == "paused" + assert executor_calls == [] + assert all(record["attempt_count"] == 0 for record in runner.results()) + + finish( + runner, + lambda task, context: task["id"], + setup=lambda: contexts.append(object()) or contexts[-1], + ) + assert len(contexts) == 2 + assert contexts[0] is not contexts[1] + + +def test_setup_status_transitions_to_running_before_task(runner): + setup_entered = threading.Event() + release_setup = threading.Event() + execute_entered = threading.Event() + release_execute = threading.Event() + runner.add([{"id": "a"}, {"id": "b"}]) + + def setup(): + setup_entered.set() + assert release_setup.wait(5) + return object() + + def execute(task, context): + execute_entered.set() + assert release_execute.wait(5) + return task["id"] + + runner.start(execute, setup=setup) + try: + assert setup_entered.wait(5) + setting_up = runner.status() + assert setting_up["state"] == "setting_up" + assert setting_up["pending"] == 2 + assert setting_up["running"] == 0 + assert setting_up["current"] is None + + release_setup.set() + assert execute_entered.wait(5) + running = runner.status() + assert running["state"] == "running" + assert running["running"] == 1 + assert running["current"] == "a" + finally: + release_setup.set() + release_execute.set() + + assert runner.wait(5) + assert runner.status()["state"] == "completed" + + +def test_no_setup_goes_directly_to_running(runner): + entered = threading.Event() + release = threading.Event() + runner.add([{"id": "a"}]) + + def execute(task, context): + assert context is None + entered.set() + assert release.wait(5) + return task["id"] + + runner.start(execute) + try: + assert entered.wait(5) + assert runner.status()["state"] == "running" + finally: + release.set() + + assert runner.wait(5) + + +def test_setup_failure_takes_precedence_over_pause(runner): + entered = threading.Event() + release = threading.Event() + runner.add([{"id": "a"}]) + + def setup(): + entered.set() + assert release.wait(5) + raise RuntimeError("failed after pause") + + runner.start(lambda task, context: None, setup=setup) + try: + assert entered.wait(5) + assert runner.status()["state"] == "setting_up" + runner.pause() + finally: + release.set() + + assert runner.wait(5) + status = runner.status() + assert status["state"] == "interrupted" + assert status["worker_error"]["message"] == "failed after pause" + assert runner.get("a")["attempt_count"] == 0 + + +def test_no_work_and_rejected_starts_do_not_call_setup(module, tmp_path): + setup_calls = [] + + def setup(): + setup_calls.append(True) + + empty = module.TaskRunner.create("empty", root=tmp_path) + empty.start(lambda task, context: None, setup=setup) + assert empty.status()["state"] == "idle" + + completed = module.TaskRunner.create("completed", root=tmp_path) + completed.add([{"id": "a"}]) + finish(completed, lambda task, context: None) + completed.start(lambda task, context: None, setup=setup) + assert completed.status()["state"] == "completed" + + active = module.TaskRunner.create("active", root=tmp_path) + active.add([{"id": "a"}]) + entered = threading.Event() + release = threading.Event() + + def blocking_setup(): + entered.set() + assert release.wait(5) + + active.start(lambda task, context: None, setup=blocking_setup) + try: + assert entered.wait(5) + with pytest.raises(module.TaskRunnerAlreadyRunningError): + active.start(lambda task, context: None, setup=setup) + + blocked = module.TaskRunner.create("blocked", root=tmp_path) + blocked.add([{"id": "a"}]) + with pytest.raises(module.TaskRunnerBusyError): + blocked.start(lambda task, context: None, setup=setup) + finally: + active.pause() + release.set() + assert active.wait(5) + + closed = module.TaskRunner.create("closed", root=tmp_path) + closed.add([{"id": "a"}]) + closed.close() + with pytest.raises(module.TaskRunnerClosedError): + closed.start(lambda task, context: None, setup=setup) + + assert setup_calls == [] + + +def test_callback_validation_and_falsey_setup(module, runner, tmp_path): + runner.add([{"id": "a"}]) + before = runner.results() + + with pytest.raises(TypeError, match="execute must be callable"): + runner.start(None) + with pytest.raises(TypeError, match="setup must be callable or None"): + runner.start(lambda task, context: None, setup=object()) + + assert runner.results() == before + other = module.TaskRunner.create("other", root=tmp_path) + other.add([{"id": "b"}]) + finish(other, lambda task, context: None) + + class FalseySetup: + def __init__(self): + self.calls = 0 + + def __bool__(self): + return False + + def __call__(self): + self.calls += 1 + + setup = FalseySetup() + contexts = [] + finish( + runner, + lambda task, context: contexts.append(context), + setup=setup, + ) + assert setup.calls == 1 + assert contexts == [None] + + +def test_setup_failure_preserves_partially_completed_run(module, tmp_path): + runner = module.TaskRunner.create("mixed", root=tmp_path, max_attempts=1) + runner.add([{"id": "a"}, {"id": "b"}, {"id": "c"}]) + + def execute(task, context): + if task["id"] == "b": + runner.pause() + raise ValueError("permanent") + return task["id"] + + finish(runner, execute) + assert [record["status"] for record in runner.results()] == [ + "done", + "failed", + "pending", + ] + before = runner.results() + + def fail_setup(): + raise RuntimeError("cannot initialize") + + runner.start(lambda task, context: task["id"], setup=fail_setup) + assert runner.wait(5) + assert runner.results() == before + assert runner.status()["state"] == "interrupted" + + calls = [] + finish( + runner, + lambda task, context: calls.append(task["id"]) or task["id"], + setup=object, + ) + assert calls == ["c"] + assert runner.status()["worker_error"] is None + + +@pytest.mark.parametrize("point", ["execute", "ack", "ack_failed"]) +def test_abrupt_process_death(module, tmp_path, point): + code = """import sys, os +from pythonhere.tasks_here import TaskRunner as T +r = T.create("crash", root=sys.argv[1], max_attempts=1) +r.add([{"id":"a"}, {"id":"b"}, {"id":"c"}]) +point = sys.argv[2] +if point != "execute": + original = getattr(r._queue, point) + def stop(*args, **kwargs): + if r._current_task_id == "b": + os._exit(17) + return original(*args, **kwargs) + setattr(r._queue, point, stop) +def execute(task, context): + assert context == "child-context" + if task["id"] == "b": + if point == "execute": os._exit(17) + if point == "ack_failed": raise ValueError("permanent") + return task["id"] +r.start(execute, setup=lambda: "child-context") +r.wait(5) +""" + child = subprocess.run( + [sys.executable, "-c", code, str(tmp_path), point], timeout=10, check=False + ) + assert child.returncode == 17 + runner = module.TaskRunner.open("crash", root=tmp_path) + assert runner.get("a")["status"] == "done" + expected = {"execute": "pending", "ack": "done", "ack_failed": "failed"}[point] + assert runner.get("b")["status"] == expected + expected_recovery = { + "execute": {"pending": 2, "completed": 1, "failed": 0, "progress": 1 / 3}, + "ack": {"pending": 1, "completed": 2, "failed": 0, "progress": 2 / 3}, + "ack_failed": { + "pending": 1, + "completed": 1, + "failed": 1, + "progress": 2 / 3, + }, + }[point] + recovered_status = runner.status() + assert recovered_status["total"] == 3 + assert recovered_status["running"] == 0 + assert recovered_status["state"] == "interrupted" + for key, value in expected_recovery.items(): + assert recovered_status[key] == value + calls = [] + + def execute_recovered(task, context): + assert context == "parent-context" + calls.append(task["id"]) + return task["id"] + + finish( + runner, + execute_recovered, + setup=lambda: "parent-context", + ) + assert calls == (["b", "c"] if point == "execute" else ["c"]) + final_status = runner.status() + assert final_status["total"] == 3 + assert final_status["pending"] == 0 + assert final_status["running"] == 0 + assert final_status["completed"] == (2 if point == "ack_failed" else 3) + assert final_status["failed"] == (1 if point == "ack_failed" else 0) + assert final_status["progress"] == 1.0 + assert final_status["state"] == "completed" + if point == "execute": + assert runner.get("b")["attempt_count"] == 2 + assert runner.get("b")["failure_count"] == 0 + assert runner.get("b")["attempts"][0]["interrupted"] is True + + +def test_storage_paths(module, tmp_path, monkeypatch): + monkeypatch.delenv("PYTHONHERE_TASKS_DIR", raising=False) + monkeypatch.delenv("ANDROID_ARGUMENT", raising=False) + monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path)) + assert module.task_runs_directory() == tmp_path / "pythonhere/task-runs" + android = ModuleType("android") + storage = ModuleType("android.storage") + storage.app_storage_path = lambda: str(tmp_path / "actual-package") + monkeypatch.setitem(sys.modules, "android", android) + monkeypatch.setitem(sys.modules, "android.storage", storage) + monkeypatch.setenv("ANDROID_ARGUMENT", "1") + assert module.task_runs_directory() == tmp_path / "actual-package/task-runs" + monkeypatch.setenv("PYTHONHERE_TASKS_DIR", str(tmp_path / "override")) + assert module.task_runs_directory() == tmp_path / "override" + + +def test_stale_setting_up_state_is_interrupted(module, runner, tmp_path): + runner.add([{"id": "a"}]) + runner._refresh_meta(state="setting_up") + assert runner.status()["state"] == "interrupted" + runner.close() + + listed = next(item for item in module.TaskRunner.list(root=tmp_path)) + assert listed["state"] == "interrupted" + + reopened = module.TaskRunner.open("test", root=tmp_path) + assert reopened.status()["state"] == "interrupted" + + +def test_thread_start_failure_releases_execution(module, runner, tmp_path, monkeypatch): + runner.add([{"id": "a"}]) + + def broken_start(thread): + raise RuntimeError("cannot start thread") + + with monkeypatch.context() as patch: + patch.setattr(threading.Thread, "start", broken_start) + with pytest.raises(RuntimeError): + runner.start(lambda task, context: None, setup=object) + assert runner.status()["state"] == "interrupted" + assert module._read_json(runner._meta_path)["state"] == "interrupted" + other = module.TaskRunner.create("other", root=tmp_path) + other.add([{"id": "b"}]) + finish(other, lambda task, context: None) + finish(runner, lambda task, context: None) + + +def test_result_storage_failure_is_recoverable(runner, monkeypatch): + runner.add([{"id": "a"}, {"id": "b"}]) + update = runner._queue.update + + def broken_update(item, *args, **kwargs): + if item["data"].get("result_present"): + raise OSError("disk full") + return update(item, *args, **kwargs) + + with monkeypatch.context() as patch: + patch.setattr(runner._queue, "update", broken_update) + runner.start(lambda task, context: "ok") + assert runner.wait(5) + assert runner.status()["state"] == "interrupted" + assert runner.status()["worker_error"]["type"] == "OSError" + assert runner.get("b")["attempt_count"] == 0 + finish(runner, lambda task, context: "ok") + assert runner.status()["completed"] == 2 diff --git a/uv.lock b/uv.lock index 15181d2..6d557e2 100644 --- a/uv.lock +++ b/uv.lock @@ -1346,6 +1346,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/99/5d/8268b644392ee874ee82a635cd0df1773de230bde356c38de28e298392cc/parso-0.8.7-py2.py3-none-any.whl", hash = "sha256:a8926eb2a1b915486941fdbd31e86a4baf88fe8c210f25f2f35ecec5b574ca1c", size = 107025, upload-time = "2026-05-01T23:12:58.867Z" }, ] +[[package]] +name = "persist-queue" +version = "1.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2f/9e/865b2a173a272d2f52b0f50534e13c38c159877251a987e0863fc7376acd/persist_queue-1.1.0.tar.gz", hash = "sha256:4c042a3d39c9af4fa24497da76697fb4fff7abe6af04bcf55f099e0c23bc2c67", size = 39294, upload-time = "2025-10-25T13:21:28.339Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/07/88/7248345679ad5001cdc0211eb83303c62659f86ae7024170c0bc0afd4e4e/persist_queue-1.1.0-py3-none-any.whl", hash = "sha256:be431ad90cd57621be5563dcd2424e21d81db3bb8cdfb918ade722369d640763", size = 53076, upload-time = "2025-10-25T13:21:26.577Z" }, +] + [[package]] name = "pexpect" version = "4.9.0" @@ -1640,6 +1649,7 @@ dependencies = [ { name = "ipython", version = "8.39.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11' and sys_platform == 'linux'" }, { name = "ipython", version = "9.13.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11' and sys_platform == 'linux'" }, { name = "ipywidgets", marker = "sys_platform == 'linux'" }, + { name = "persist-queue", marker = "sys_platform == 'linux'" }, { name = "pillow", marker = "sys_platform == 'linux'" }, ] @@ -1681,6 +1691,7 @@ requires-dist = [ { name = "ipython" }, { name = "ipywidgets" }, { name = "litert-lm-api", marker = "extra == 'litert'", specifier = "==0.16.0" }, + { name = "persist-queue", specifier = "==1.1.0" }, { name = "pillow" }, { name = "requests", marker = "extra == 'litert'" }, ] From 6cb2539f4a71c2081086c3e1ed1e8df164d30727 Mon Sep 17 00:00:00 2001 From: b3b Date: Wed, 7 Oct 2026 17:32:37 +0200 Subject: [PATCH 08/13] Add task results JSON export helper --- examples/tasks.md | 27 +++++++++++++++++++++++++++ pythonhere/tasks_here.py | 21 ++++++++++++++++++++- tests/test_tasks_here.py | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 82 insertions(+), 1 deletion(-) diff --git a/examples/tasks.md b/examples/tasks.md index 6511687..cc502a1 100644 --- a/examples/tasks.md +++ b/examples/tasks.md @@ -92,6 +92,33 @@ results = %there get runner.results() results ``` +For larger results, export a JSON snapshot on the device and download the file: + +```{code-cell} ipython3 +%%there --worker +runner.export_results("task-results.json") +``` + +```{code-cell} ipython3 +%there download task-results.json ./task-results.json +``` + +Load the downloaded file in the notebook: + +```{code-cell} ipython3 +import json + +with open("task-results.json", encoding="utf-8") as f: + results = json.load(f) +``` + +The export includes all task records, including pending and failed tasks, in +submission order. Export after completion for final results, or during execution +for a snapshot. The helper writes UTF-8 JSON with readable Unicode characters +and atomically replaces an existing file. Relative paths use the device's current +working directory, which is PythonHere's upload directory by default. This avoids +a large `%there get` response, but still loads the full snapshot into device memory. + ## Wait for completion Run this cell to wait up to 50 seconds while keeping the device's UI responsive: diff --git a/pythonhere/tasks_here.py b/pythonhere/tasks_here.py index 86f8575..b32c508 100644 --- a/pythonhere/tasks_here.py +++ b/pythonhere/tasks_here.py @@ -185,7 +185,9 @@ def _registry_key(path: Path) -> str: return str(path.resolve()) -def _atomic_write_json(path: Path, value: Mapping[str, Any]) -> None: +def _atomic_write_json( + path: Path, value: Mapping[str, Any] | list[dict[str, Any]] +) -> None: path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_name(f".{path.name}.tmp-{os.getpid()}-{threading.get_ident()}") @@ -809,6 +811,23 @@ def results(self) -> list[dict[str, Any]]: rows = sorted(self._queue.queue(), key=lambda row: row["id"]) return [self._public_record(row) for row in rows] + def export_results(self, path: str | os.PathLike[str]) -> Path: + """Atomically save a results snapshot as UTF-8 JSON and return its path. + + Includes all task records in submission order, just like results(). + Relative paths use the current working directory (PythonHere's upload + directory by default), for retrieval with ``%there download``. + Parent directories are created and an existing file is replaced only + after a successful write. Run with ``%%there --worker`` for large runs. + + This avoids a large ``%there get`` response, but still materializes the + complete results snapshot in device memory. + """ + snapshot = self.results() + destination = Path(path) + _atomic_write_json(destination, snapshot) + return destination + def failed(self) -> list[dict[str, Any]]: """Return permanently failed task records.""" return [record for record in self.results() if record["status"] == "failed"] diff --git a/tests/test_tasks_here.py b/tests/test_tasks_here.py index 0f809e1..3939383 100644 --- a/tests/test_tasks_here.py +++ b/tests/test_tasks_here.py @@ -1,5 +1,6 @@ """Tests for the durable sequential task runner.""" +import json import subprocess import sys import threading @@ -30,6 +31,40 @@ def finish(runner, execute, *, setup=None): assert runner.status()["worker_error"] is None +def test_export_results_snapshot(runner, tmp_path): + runner.add([{"id": "a", "text": "Привет 🌍"}, {"id": "b"}]) + destination = tmp_path / "exports" / "results.json" + assert runner.export_results(destination) == destination + assert json.loads(destination.read_text(encoding="utf-8")) == runner.results() + assert "Привет 🌍" in destination.read_text(encoding="utf-8") + + finish(runner, lambda task, context: task["id"]) + runner.export_results(str(destination)) + records = json.loads(destination.read_text(encoding="utf-8")) + assert [record["result"] for record in records] == ["a", "b"] + assert all(record["status"] == "done" for record in records) + + +def test_export_results_empty(runner, tmp_path): + destination = runner.export_results(tmp_path / "empty.json") + assert json.loads(destination.read_text(encoding="utf-8")) == [] + + +def test_export_results_write_failure_preserves_file(runner, tmp_path, monkeypatch): + destination = tmp_path / "results.json" + destination.write_text("previous export", encoding="utf-8") + + def fail_dump(value, stream, **kwargs): + stream.write("partial") + raise OSError("disk full") + + monkeypatch.setattr(json, "dump", fail_dump) + with pytest.raises(OSError, match="disk full"): + runner.export_results(destination) + assert destination.read_text(encoding="utf-8") == "previous export" + assert list(tmp_path.glob(".results.json.tmp-*")) == [] + + def test_retry_order_and_reopen(module, runner, tmp_path): runner.add([{"id": "a"}, {"id": "b"}]) calls = [] From bdbac8832f98a8498c88cd9d46f14e688b54099c Mon Sep 17 00:00:00 2001 From: b3b Date: Wed, 14 Oct 2026 00:09:22 +0200 Subject: [PATCH 09/13] Show SSH host key fingerprint on connection screen --- pythonhere/main.py | 3 + pythonhere/server_here.py | 1 + pythonhere/ui_here/connection_address_here.kv | 40 +++++++ tests/test_main.py | 111 ++++++++++++++++++ tests/test_server_here.py | 6 + 5 files changed, 161 insertions(+) diff --git a/pythonhere/main.py b/pythonhere/main.py index 959219f..1c03c9b 100644 --- a/pythonhere/main.py +++ b/pythonhere/main.py @@ -26,6 +26,7 @@ from kivy.clock import Clock from kivy.config import Config, ConfigParser from kivy.logger import Logger +from kivy.properties import StringProperty # pylint: disable=no-name-in-module from patches_here import monkeypatch_kivy from server_here import run_ssh_server from window_here import reset_window_environment @@ -42,6 +43,8 @@ def configure_logging(): class PythonHereApp(App): """PythonHere main app.""" + ssh_host_key_sha256 = StringProperty("") + def __init__(self): super().__init__() self.server_task: asyncio.Task | None = None diff --git a/pythonhere/server_here.py b/pythonhere/server_here.py index 4975c44..c5bd62b 100644 --- a/pythonhere/server_here.py +++ b/pythonhere/server_here.py @@ -39,6 +39,7 @@ async def run_ssh_server(app): namespace=app.ssh_server_namespace, server_factory=PythonHereServer, ) + app.ssh_host_key_sha256 = server.host_key_sha256 except Exception as exc: Logger.error("PythonHere: SSH server start error") Logger.exception(exc) diff --git a/pythonhere/ui_here/connection_address_here.kv b/pythonhere/ui_here/connection_address_here.kv index 1ba4271..fa7f7e3 100644 --- a/pythonhere/ui_here/connection_address_here.kv +++ b/pythonhere/ui_here/connection_address_here.kv @@ -1,6 +1,9 @@ #:kivy 1.0 #:import ConnectionAddressLabel ui_here.connection_address_here.ConnectionAddressLabel #:import ConnectionAddressInfoBox ui_here.connection_address_here.ConnectionAddressInfoBox +#:import dp kivy.metrics.dp +#:import kivy_data_dir kivy.kivy_data_dir +#:import join os.path.join : text: f"{tc('↳', 3)} {tc(self.address, 2)} ({self.interface})" @@ -22,6 +25,7 @@ font_size: "30sp" ScrollView: + id: address_scroll do_scroll_x: False size_hint: 1, 1 @@ -30,3 +34,39 @@ orientation: "vertical" size_hint: 1, None height: self.minimum_size[1] + + BoxLayout: + id: fingerprint_footer + orientation: "vertical" + size_hint: 1, None + height: self.minimum_height + spacing: dp(6) + padding: 0, dp(16), dp(20), dp(20) + canvas.before: + Color: + rgba: 0.20, 0.24, 0.27, 1 + Line: + points: self.x, self.y + self.height, self.x + self.width - dp(20), self.y + self.height + width: dp(0.5) + + Label: + id: fingerprint_heading + text: "SSH host key fingerprint" + size_hint: 1, None + text_size: self.width, None + height: self.texture_size[1] + halign: "left" + font_size: "15sp" + color: 0.60, 0.64, 0.67, 1 + + Label: + id: fingerprint_value + text: app.ssh_host_key_sha256 + markup: False + size_hint: 1, None + text_size: self.width, None + height: self.texture_size[1] + halign: "left" + font_name: join(kivy_data_dir, 'fonts', 'RobotoMono-Regular.ttf') + font_size: "16sp" + color: 0.91, 0.94, 0.96, 1 diff --git a/tests/test_main.py b/tests/test_main.py index 72ce4b7..07dfe70 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -7,7 +7,13 @@ import pytest from asyncssh import PermissionDenied from enum_here import ScreenName, ServerState +from kivy.clock import Clock +from kivy.core.window import Window +from kivy.graphics import Line +from kivy.metrics import dp +from kivy.uix.label import Label from main import PythonHereApp, configure_logging, main +from ui_here.connection_address_here import ConnectionAddressInfoBox from ui_here.server_screen_here import ServerScreenManager from version_here import __version__ @@ -69,6 +75,111 @@ def test_server_screen_update_states(mocker): unschedule.assert_called_once_with(screen.update_event) +@pytest.mark.asyncio +async def test_connection_screen_shows_full_fingerprint_and_wraps(app_instance): + screen = app_instance.root.ids.here_screen_manager.get_screen(ServerState.ready) + box = next( + widget + for widget in screen.walk() + if isinstance(widget, ConnectionAddressInfoBox) + ) + fingerprint = app_instance.ssh_host_key_sha256 + assert fingerprint.startswith("SHA256:") + label = next( + widget + for widget in box.walk() + if isinstance(widget, Label) and widget.text == fingerprint + ) + assert not label.markup + + app_instance.ssh_host_key_sha256 = "SHA256:" + "a" * 43 + assert label.text == app_instance.ssh_host_key_sha256 + label.size_hint_x = None + label.width = 160 + label.texture_update() + Clock.tick() + + assert label.texture_size[0] <= label.width + assert label.texture_size[1] > label.font_size * 2 + assert label.height == label.texture_size[1] + + +@pytest.mark.asyncio +async def test_fingerprint_footer_stays_fixed_on_scroll_resize_and_navigation( + app_instance, +): + manager = app_instance.root.ids.here_screen_manager + manager.current = ServerState.ready + panel = manager.current_screen.children[0] + footer = panel.ids.fingerprint_footer + scroll = panel.ids.address_scroll + heading = panel.ids.fingerprint_heading + value = panel.ids.fingerprint_value + assert footer.parent is panel + assert scroll.parent is panel + assert not any( + isinstance(widget, Label) and "THERE_HOST_KEY_SHA256" in widget.text + for widget in panel.walk() + ) + for number in range(40): + panel.ids.address_list.add_widget( + Label(text=f"Address {number}", size_hint_y=None, height=dp(30)) + ) + + wrapped_height = None + for size in ((320, 640), (800, 480), (320, 640)): + Window.size = size + for _ in range(8): + await asyncio.sleep(0.02) + assert panel.width == pytest.approx(size[0]), ( + Window.size, + app_instance.root.size, + panel.size, + value.size, + ) + assert footer.y == pytest.approx(panel.y) + assert footer.height == pytest.approx(footer.minimum_height) + assert scroll.height > 0 + assert scroll.y == pytest.approx(footer.y + footer.height) + assert value.height == value.texture_size[1] + if size[0] == 320: + wrapped_height = value.height + else: + assert value.height < wrapped_height + + before_scroll = tuple(footer.pos), tuple(footer.size) + scroll.scroll_y = 0 + for _ in range(3): + await asyncio.sleep(0.02) + assert (tuple(footer.pos), tuple(footer.size)) == before_scroll + + for _ in range(3): + app_instance.root.switch_screen(ScreenName.settings) + await asyncio.sleep(0.02) + app_instance.root.switch_screen(ScreenName.here) + for _ in range(3): + await asyncio.sleep(0.02) + dividers = [ + instruction + for instruction in footer.canvas.before.children + if isinstance(instruction, Line) + ] + assert len(dividers) == 1 + divider = dividers[0] + assert divider.points == pytest.approx( + [ + footer.x, + footer.y + footer.height, + footer.x + footer.width - dp(20), + footer.y + footer.height, + ] + ) + assert heading.y + heading.height <= divider.points[1] - dp(16) + + # Allow the final screen transition to complete as it does in normal use. + await asyncio.sleep(0.5) + + @pytest.mark.asyncio async def test_code_line_executed(capfd, app_instance, there): await there.runcode("print('hello there')") diff --git a/tests/test_server_here.py b/tests/test_server_here.py index 761cce9..acf9c44 100644 --- a/tests/test_server_here.py +++ b/tests/test_server_here.py @@ -72,6 +72,8 @@ async def test_run_ssh_server_clears_config_ready_after_start_error(mocker): @pytest.mark.asyncio async def test_run_ssh_server_reports_wait_closed_error(mocker): class BrokenServer: + host_key_sha256 = "SHA256:test" + async def wait_closed(self): raise RuntimeError("server failed") @@ -84,6 +86,7 @@ async def wait_closed(self): start_server.assert_called_once() assert app.ssh_server_started.is_set() + assert app.ssh_host_key_sha256 == "SHA256:test" exception = show_exception_popup.call_args.args[0] assert isinstance(exception, RuntimeError) assert str(exception) == "server failed" @@ -124,6 +127,9 @@ async def test_new_host_key_is_ed25519_and_legacy_key_is_untouched( host_key = tmp_path / "ssh_host_key" assert asyncssh.read_private_key(host_key).get_algorithm() == "ssh-ed25519" + assert app.ssh_host_key_sha256 == asyncssh.read_private_key( + host_key + ).get_fingerprint("sha256") assert legacy_key.read_bytes() == legacy_contents running_app.on_ssh_connection_made.assert_called_once_with() finally: From e455a209b8281b2e30a14d283ba411288ee03eb4 Mon Sep 17 00:00:00 2001 From: b3b Date: Thu, 15 Oct 2026 12:13:33 +0200 Subject: [PATCH 10/13] Prepare 0.4.1 release --- CHANGELOG.rst | 15 ++++ buildozer.spec | 2 +- examples/README.md | 7 ++ examples/commands.md | 13 +++ examples/tasks.md | 202 +++++++++++++++++++++++++++++------------- examples/there-cli.md | 6 ++ pyproject.toml | 2 +- uv.lock | 8 +- 8 files changed, 188 insertions(+), 67 deletions(-) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index e3b7300..b6ff82c 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,6 +1,21 @@ Changelog ========= +0.4.1 +----- + +This release adds persistent task execution and SSH host-key fingerprint +display, and updates herethere. + +* Added ``tasks_here.TaskRunner`` for persistent sequential task execution, + with retries, pause/resume, progress inspection, and recovery after app restart +* Added ``TaskRunner.export_results()`` to save task results as a JSON file + for download from the device +* Added the SSH host-key SHA-256 fingerprint to the connection screen +* Updated ``herethere`` to 0.3.3, adding optional SSH host-key verification + and ``%there put`` / ``Client.put()`` for transferring local Python values + into the remote live namespace + 0.4.0 ----- diff --git a/buildozer.spec b/buildozer.spec index f627b96..fa026bf 100644 --- a/buildozer.spec +++ b/buildozer.spec @@ -38,7 +38,7 @@ requirements = # herethere dependencies asyncssh==2.23.1, python-dotenv==1.2.2, - herethere==0.3.2, + herethere==0.3.3, # asyncssh dependencies cryptography, typing_extensions, diff --git a/examples/README.md b/examples/README.md index 1128ea9..4b2287a 100644 --- a/examples/README.md +++ b/examples/README.md @@ -32,8 +32,15 @@ THERE_USERNAME=here # Password, as set in PythonHere app Settings section THERE_PASSWORD=xxx + +# Optional: verify the server fingerprint shown on the app's connection screen. +# THERE_HOST_KEY_SHA256=SHA256: ``` +Host-key verification is optional. Leave the line commented out unless you want +to enable it; see the [connection settings](commands.md#there-env-example) for +details. + ## When using with Docker Content of **examples** directory are not preserved. diff --git a/examples/commands.md b/examples/commands.md index 181c3d8..66b5430 100644 --- a/examples/commands.md +++ b/examples/commands.md @@ -49,8 +49,21 @@ THERE_USERNAME=here # Password, as set in PythonHere app Settings section THERE_PASSWORD=xxx + +# Optional: verify the server fingerprint shown on the app's connection screen. +# THERE_HOST_KEY_SHA256=SHA256: ``` +Host-key verification is optional; leave the line commented out for the usual +connection setup. To enable it, copy the SSH host-key fingerprint from +PythonHere's connection screen, replace the placeholder, and uncomment the line. +The client then checks the fingerprint before authentication on every connection +and reconnect. This setting works with both Jupyter and the `there` CLI. + +The fingerprint stays the same when the device's IP address changes. If the SSH +host key is replaced or regenerated, compare the new fingerprint with the one +shown in the app before updating the config. + +++ ## %there group of commands diff --git a/examples/tasks.md b/examples/tasks.md index cc502a1..6569601 100644 --- a/examples/tasks.md +++ b/examples/tasks.md @@ -28,7 +28,9 @@ interrupted task becomes runnable again. ## Submit and start work Every task needs a unique nonempty string `id`. Tasks and returned results must -contain plain JSON-compatible values. +contain plain JSON-compatible values. If `"squares-example"` already exists +from an earlier attempt, use a new name or delete the old run with the +[cleanup cell](#clean-up) at the end. ```{code-cell} ipython3 %%there @@ -39,6 +41,8 @@ from tasks_here import TaskRunner def execute_task(task, context): time.sleep(1) + if task["value"] == 5: + raise ValueError("Intentional example failure for value 5") return { "value": task["value"], "square": task["value"] ** 2, @@ -50,33 +54,12 @@ runner.add([{"id": str(value), "value": value} for value in range(1, 11)]) runner.start(execute_task) ``` -`start()` returns promptly while the runner processes tasks in its background -thread. - -The executor always receives a second argument. It is `None` when `start()` has -no setup callback. For expensive runtime resources, create them once per worker -session and reuse the returned context for every task and retry: - -```python -def setup(): - return create_runtime() - - -def execute_with_runtime(task, runtime): - return runtime.process(task) - - -runner.start(execute_with_runtime, setup=setup) -``` - -Setup runs in the background worker thread, so `start()` still returns promptly. -While setup executes, `runner.status()["state"]` is `"setting_up"`; after setup -succeeds it becomes `"running"` before the first task is claimed. -If pause is requested while setup is running, setup finishes and the worker exits -before claiming a task. A later `start()` calls setup again. Context is runtime -state: it is not persisted or included in results, and the runner does not close -it automatically. Applications that require deterministic resource cleanup must -manage that cleanup themselves. +`start()` returns promptly while tasks run one at a time in a background thread. +The task for value `5` deliberately fails. With `max_attempts=3`, the runner +tries it three times before marking it failed; the other nine tasks still run. +Including retries, this example takes about twelve seconds. Tasks continue +running between notebook cells, so the run may already be completed when you +inspect it. ## Inspect progress and results @@ -85,85 +68,118 @@ status = %there get runner.status() status ``` -Results can be inspected while work is still running: +You can inspect results before the whole run finishes: ```{code-cell} ipython3 results = %there get runner.results() results ``` -For larger results, export a JSON snapshot on the device and download the file: +To wait briefly before checking progress again: ```{code-cell} ipython3 %%there --worker -runner.export_results("task-results.json") +runner.wait(timeout=1) +print(runner.status()) ``` +This waits at most one second and returns sooner if the worker has stopped. + +## Pause and resume (optional) + +While tasks are still running, you can pause them. `pause()` lets the current +task finish, and `wait()` waits for the pause to take effect: + ```{code-cell} ipython3 -%there download task-results.json ./task-results.json +%%there --worker +runner.pause() +runner.wait() +print(runner.status()) ``` -Load the downloaded file in the notebook: +Resume any pending tasks with the same executor. Completed tasks are kept: ```{code-cell} ipython3 -import json - -with open("task-results.json", encoding="utf-8") as f: - results = json.load(f) +%%there +runner.start(execute_task) ``` -The export includes all task records, including pending and failed tasks, in -submission order. Export after completion for final results, or during execution -for a snapshot. The helper writes UTF-8 JSON with readable Unicode characters -and atomically replaces an existing file. Relative paths use the device's current -working directory, which is PythonHere's upload directory by default. This avoids -a large `%there get` response, but still loads the full snapshot into device memory. +If all tasks have already completed, there is nothing left to pause or resume. ## Wait for completion -Run this cell to wait up to 50 seconds while keeping the device's UI responsive: +Wait for all remaining work, then show the final counts. `--worker` keeps the +app's UI responsive while this cell waits: ```{code-cell} ipython3 %%there --worker -stopped = runner.wait(timeout=50) -print("Worker stopped:", stopped) -print(runner.status()) +runner.wait() +status = runner.status() +print("State:", status["state"]) +print("Completed:", status["completed"], "of", status["total"]) +print("Failed:", status["failed"]) ``` -If `stopped` is `False`, tasks are still running; run the cell again to keep -waiting. `True` means the worker has stopped, which can also happen after a -pause or an error. A `completed` state includes tasks that exhausted their -retries. Inspect any failures from the notebook: +Expected output: + +```text +State: completed +Completed: 9 of 10 +Failed: 1 +``` + +`wait()` returns when the worker stops. A `completed` state means all tasks +have been processed, including any that exhausted their retries; it does not +mean every task succeeded. Inspect the deliberately failed task: ```{code-cell} ipython3 failures = %there get runner.failed() failures ``` -## Pause and resume +The failed record has `id: "5"`, `attempt_count: 3`, `failure_count: 3`, +and the intentional `ValueError`. The other nine tasks have their square results. -`pause()` lets the current task finish and stops before claiming another. Wait -for that graceful pause before inspecting its final paused state: +## Export results + +For larger results, export a JSON snapshot on the device and download the file: ```{code-cell} ipython3 %%there --worker -runner.pause() -runner.wait(timeout=10) -print(runner.status()) +runner.export_results("task-results.json") +``` + +```{code-cell} ipython3 +%there download task-results.json ./task-results.json ``` -Resume the remaining tasks with the same executor: +Load the downloaded file in the notebook: ```{code-cell} ipython3 -%%there -runner.start(execute_task) +import json + +with open("task-results.json", encoding="utf-8") as f: + results = json.load(f) ``` +The export includes all task records, including pending and failed tasks, in +submission order. Export after completion for final results, or during execution +for a snapshot. Relative paths use the device's current working directory, +which is PythonHere's upload directory by default. For large runs, exporting +and downloading a file avoids transferring all results through `%there get`. + ## Reopen after PythonHere restarts The task list and results are persistent, but Python callables and other runtime objects are not. After restarting PythonHere, reconnect, recreate the executor, -open the named run, and start it again: +open the named run, and start it again. Completed tasks are kept; only +unfinished work runs again. If all ten tasks already finished, the run stays +completed. + +In this walkthrough, all tasks have already finished. Reopening shows that +the results and the failed task survived the restart. The task that exhausted +its retries stays failed; calling `start()` does not retry it again. To try recovery of unfinished work separately, +restart the app while a fresh run is executing, then reconnect and run this cell: ```{code-cell} ipython3 %%there @@ -174,6 +190,8 @@ from tasks_here import TaskRunner def execute_task(task, context): time.sleep(1) + if task["value"] == 5: + raise ValueError("Intentional example failure for value 5") return { "value": task["value"], "square": task["value"] ** 2, @@ -184,7 +202,69 @@ runner = TaskRunner.open("squares-example") runner.start(execute_task) ``` +Wait for any unfinished work, then inspect the saved results: + +```{code-cell} ipython3 +%%there --worker +runner.wait() +print(runner.status()) +``` + +```{code-cell} ipython3 +saved_results = %there get runner.results() +saved_results +``` + Execution is at least once. If PythonHere stops after an executor begins but before its result is committed, that task can run again. Executors with irreversible side effects should therefore be idempotent or check durable state before applying those effects. + +## Optional: reuse runtime resources + +The executor always receives a second argument. It is `None` when `start()` has +no setup callback. For expensive runtime resources, create them once per worker +session and reuse the returned context for every task and retry: + +```python +def setup(): + return create_runtime() + + +def execute_with_runtime(task, runtime): + return runtime.process(task) + + +runner.start(execute_with_runtime, setup=setup) +``` + +Setup runs in the background worker thread, so `start()` still returns promptly. +While setup executes, `runner.status()["state"]` is `"setting_up"`; after setup +succeeds it becomes `"running"` before the first task is claimed. +If pause is requested while setup is running, setup finishes and the worker exits +before claiming a task. A later `start()` calls setup again. Context is runtime +state: it is not persisted or included in results, and the runner does not close +it automatically. Applications that require deterministic resource cleanup must +manage that cleanup themselves. + +## Clean up + +When you are done inspecting the completed run, you can delete it to repeat +this example with the same name. Skip this cell to keep its saved results. +This deletes only `"squares-example"` and its tasks/results; other runs and +exported JSON files are untouched. + +```{code-cell} ipython3 +%%there --worker +from tasks_here import TaskRunner, TaskRunNotFoundError + +try: + saved_run = TaskRunner.open("squares-example") +except TaskRunNotFoundError: + print("The example run has already been deleted.") +else: + saved_run.delete() + print("Example run deleted. You can now run the example again.") +``` + +A running task run cannot be deleted. Finish or pause it first. diff --git a/examples/there-cli.md b/examples/there-cli.md index ee954d6..451c70c 100644 --- a/examples/there-cli.md +++ b/examples/there-cli.md @@ -29,6 +29,12 @@ there --json --config /path/to/there.env ping Options for the whole invocation, including `--json`, `--config`, `--timeout`, and `--max-output`, go before the command name. +Host-key verification is optional. To enable it, uncomment +`THERE_HOST_KEY_SHA256` in the +[`there.env` example](commands.md#there-env-example) and replace the placeholder +with the SSH host-key fingerprint shown on PythonHere's connection screen. +Leave the setting commented out for the usual connection setup. + ## Worker execution By default, `run` and `get` execute on the application's main thread. Blocking diff --git a/pyproject.toml b/pyproject.toml index bf0793f..e9bc903 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -22,7 +22,7 @@ classifiers = [ "Programming Language :: Python :: 3.14", ] dependencies = [ - "herethere[magic]>=0.3.2", + "herethere[magic]>=0.3.3", "ipython", "ipywidgets", "Pillow", diff --git a/uv.lock b/uv.lock index 6d557e2..a17150e 100644 --- a/uv.lock +++ b/uv.lock @@ -613,16 +613,16 @@ wheels = [ [[package]] name = "herethere" -version = "0.3.2" +version = "0.3.3" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "asyncssh", marker = "sys_platform == 'linux'" }, { name = "click", marker = "sys_platform == 'linux'" }, { name = "python-dotenv", marker = "sys_platform == 'linux'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2d/ef/241312c499ea63089cd8133f102322f8d4824d87d70431cfe52b3009c338/herethere-0.3.2.tar.gz", hash = "sha256:24c5e8d319103d0a8dc4fac9b3b267051c1395065d2990a449fa48a7bd2c0844", size = 63022, upload-time = "2026-08-24T16:33:11.802Z" } +sdist = { url = "https://files.pythonhosted.org/packages/8c/d5/df9024a5d2a43298cbeb5a644a8a0c1db4c929d93194fb031038d32f9c17/herethere-0.3.3.tar.gz", hash = "sha256:cd5e75289a49cad5205eaaaa92ed755b311cc940d87e937ee68a13b5a0df91bc", size = 66772, upload-time = "2026-10-14T17:59:54.388Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/41/b9/94950a1cb3fd7160d5684f86fb241f160a7e5004b1d02d83efe72ccace00/herethere-0.3.2-py3-none-any.whl", hash = "sha256:aeb24092eaa612d5f1f1ebabd6fa627509ce8d4f02fd6d13e32b218643e457ca", size = 65178, upload-time = "2026-08-24T16:33:10.712Z" }, + { url = "https://files.pythonhosted.org/packages/24/fd/abf0ad9ec2d35c159f60efef81f79c61f9cea3a1169c08c830f4875d2fd8/herethere-0.3.3-py3-none-any.whl", hash = "sha256:46037e0db517535882f9378961453758b55f15a57ae0de4a2646c741aac1ae00", size = 68014, upload-time = "2026-10-14T17:59:53.411Z" }, ] [package.optional-dependencies] @@ -1687,7 +1687,7 @@ docker = [ [package.metadata] requires-dist = [ - { name = "herethere", extras = ["magic"], specifier = ">=0.3.2" }, + { name = "herethere", extras = ["magic"], specifier = ">=0.3.3" }, { name = "ipython" }, { name = "ipywidgets" }, { name = "litert-lm-api", marker = "extra == 'litert'", specifier = "==0.16.0" }, From 60252fd4d230ec747386bab7851e13265dc4c7e1 Mon Sep 17 00:00:00 2001 From: b3b Date: Thu, 15 Oct 2026 13:34:15 +0200 Subject: [PATCH 11/13] Update docs --- examples/commands.md | 26 ++++++++++++++++++++++++++ examples/tasks.md | 34 ++++++++++++++++++---------------- examples/there-cli.md | 8 +------- 3 files changed, 45 insertions(+), 23 deletions(-) diff --git a/examples/commands.md b/examples/commands.md index 66b5430..88bd39e 100644 --- a/examples/commands.md +++ b/examples/commands.md @@ -138,6 +138,32 @@ root_size Use `%there get` for small and inspectable values. For large text, binary data, images, CSV files, or directories, write a remote file and use `%there download`. +### put + +Transfer a local notebook variable into PythonHere's live Python namespace: + +```{code-cell} +config = {"temperature": 0.2, "top_k": 40} +%there put config +``` + +The variable is then available to code running on the device: + +```{code-cell} +%%there +print(config) +``` + +An optional second name sets the remote variable name: + +```{code-cell} +local_tasks = [{"id": "a", "value": 1}, {"id": "b", "value": 2}] +%there put local_tasks device_tasks +``` + +`put` takes a local variable name, not an expression. Use it for small or +medium in-memory values. For large data or files, use `%there upload`. + ### kv ```{code-cell} diff --git a/examples/tasks.md b/examples/tasks.md index 6569601..2f5bdcc 100644 --- a/examples/tasks.md +++ b/examples/tasks.md @@ -20,7 +20,7 @@ interrupted task becomes runnable again. ## Connect to PythonHere -```{code-cell} ipython3 +```{code-cell} python %load_ext pythonhere %connect-there ``` @@ -32,7 +32,7 @@ contain plain JSON-compatible values. If `"squares-example"` already exists from an earlier attempt, use a new name or delete the old run with the [cleanup cell](#clean-up) at the end. -```{code-cell} ipython3 +```{code-cell} python %%there import time @@ -63,21 +63,22 @@ inspect it. ## Inspect progress and results -```{code-cell} ipython3 +```{code-cell} python status = %there get runner.status() status ``` You can inspect results before the whole run finishes: -```{code-cell} ipython3 +```{code-cell} python +:tags: ["hide-output"] results = %there get runner.results() results ``` To wait briefly before checking progress again: -```{code-cell} ipython3 +```{code-cell} python %%there --worker runner.wait(timeout=1) print(runner.status()) @@ -90,7 +91,7 @@ This waits at most one second and returns sooner if the worker has stopped. While tasks are still running, you can pause them. `pause()` lets the current task finish, and `wait()` waits for the pause to take effect: -```{code-cell} ipython3 +```{code-cell} python %%there --worker runner.pause() runner.wait() @@ -99,7 +100,7 @@ print(runner.status()) Resume any pending tasks with the same executor. Completed tasks are kept: -```{code-cell} ipython3 +```{code-cell} python %%there runner.start(execute_task) ``` @@ -111,7 +112,7 @@ If all tasks have already completed, there is nothing left to pause or resume. Wait for all remaining work, then show the final counts. `--worker` keeps the app's UI responsive while this cell waits: -```{code-cell} ipython3 +```{code-cell} python %%there --worker runner.wait() status = runner.status() @@ -132,7 +133,7 @@ Failed: 1 have been processed, including any that exhausted their retries; it does not mean every task succeeded. Inspect the deliberately failed task: -```{code-cell} ipython3 +```{code-cell} python failures = %there get runner.failed() failures ``` @@ -144,18 +145,18 @@ and the intentional `ValueError`. The other nine tasks have their square results For larger results, export a JSON snapshot on the device and download the file: -```{code-cell} ipython3 +```{code-cell} python %%there --worker runner.export_results("task-results.json") ``` -```{code-cell} ipython3 +```{code-cell} python %there download task-results.json ./task-results.json ``` Load the downloaded file in the notebook: -```{code-cell} ipython3 +```{code-cell} python import json with open("task-results.json", encoding="utf-8") as f: @@ -181,7 +182,7 @@ the results and the failed task survived the restart. The task that exhausted its retries stays failed; calling `start()` does not retry it again. To try recovery of unfinished work separately, restart the app while a fresh run is executing, then reconnect and run this cell: -```{code-cell} ipython3 +```{code-cell} python %%there import time @@ -204,13 +205,14 @@ runner.start(execute_task) Wait for any unfinished work, then inspect the saved results: -```{code-cell} ipython3 +```{code-cell} python %%there --worker runner.wait() print(runner.status()) ``` -```{code-cell} ipython3 +```{code-cell} python +:tags: ["hide-output"] saved_results = %there get runner.results() saved_results ``` @@ -254,7 +256,7 @@ this example with the same name. Skip this cell to keep its saved results. This deletes only `"squares-example"` and its tasks/results; other runs and exported JSON files are untouched. -```{code-cell} ipython3 +```{code-cell} python %%there --worker from tasks_here import TaskRunner, TaskRunNotFoundError diff --git a/examples/there-cli.md b/examples/there-cli.md index 451c70c..e3fb7c1 100644 --- a/examples/there-cli.md +++ b/examples/there-cli.md @@ -11,7 +11,7 @@ codes. ## Connect to the app Start PythonHere on the target device, then work from a directory containing a -[`there.env`](https://herethere.me/pythonhere/examples/commands.html#there-env-example) +[`there.env`](commands.md#there-env-example) connection file, or one of its descendants. Check the installed interface and target readiness: @@ -29,12 +29,6 @@ there --json --config /path/to/there.env ping Options for the whole invocation, including `--json`, `--config`, `--timeout`, and `--max-output`, go before the command name. -Host-key verification is optional. To enable it, uncomment -`THERE_HOST_KEY_SHA256` in the -[`there.env` example](commands.md#there-env-example) and replace the placeholder -with the SSH host-key fingerprint shown on PythonHere's connection screen. -Leave the setting commented out for the usual connection setup. - ## Worker execution By default, `run` and `get` execute on the application's main thread. Blocking From 8dc5b1d4c455064fe3e30734fb8239c0fe2ab8ab Mon Sep 17 00:00:00 2001 From: b3b Date: Fri, 30 Oct 2026 16:53:54 +0100 Subject: [PATCH 12/13] Add LiteRT benchmark notebooks with Pydantic Evals --- examples/litert_evals/README.md | 36 +++ examples/litert_evals/cruxeval.md | 407 +++++++++++++++++++++++++++++ examples/litert_evals/leetcode.md | 414 ++++++++++++++++++++++++++++++ examples/litert_evals/quiz.md | 286 +++++++++++++++++++++ 4 files changed, 1143 insertions(+) create mode 100644 examples/litert_evals/README.md create mode 100644 examples/litert_evals/cruxeval.md create mode 100644 examples/litert_evals/leetcode.md create mode 100644 examples/litert_evals/quiz.md diff --git a/examples/litert_evals/README.md b/examples/litert_evals/README.md new file mode 100644 index 0000000..81c1019 --- /dev/null +++ b/examples/litert_evals/README.md @@ -0,0 +1,36 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.19.3 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# Benchmarks with Pydantic Evals + +Companion notebooks for the [YouTube video](https://youtu.be/CSwZkyGWrhU). + +Test a model's Python skills from Jupyter, with inference running locally on +Android through PythonHere. Use Pydantic Evals to run a Python quiz, check +answers, and report results, then build custom evaluators for code-reasoning +tasks and programming challenges. For longer experiments, Task Runner generates +answers in the background on Android so you can fetch and evaluate them later. + +## Notebooks + +1. [Python quiz](quiz.md) +2. [CruxEval](cruxeval.md) +3. [LeetCode](leetcode.md) + +## Resources + +- [Pydantic Evals](https://pydantic.dev/docs/ai/evals/evals/) +- [LiteRT-LM](https://github.com/google-ai-edge/LiteRT-LM) +- [Qwen2.5-Coder-3B-Instruct (LiteRT-LM)](https://huggingface.co/litert-community/Qwen2.5-Coder-3B-Instruct) +- [CruxEval dataset](https://huggingface.co/datasets/cruxeval-org/cruxeval) +- [LeetCode dataset](https://huggingface.co/datasets/newfacade/LeetCodeDataset) diff --git a/examples/litert_evals/cruxeval.md b/examples/litert_evals/cruxeval.md new file mode 100644 index 0000000..c2892f7 --- /dev/null +++ b/examples/litert_evals/cruxeval.md @@ -0,0 +1,407 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.19.3 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# CruxEval + +Companion notebook for the video [*Benchmarking Local AI on Android with PythonHere and Pydantic Evals*](https://youtu.be/CSwZkyGWrhU). + +Ask a model to predict Python function outputs from the +[CruxEval dataset](https://huggingface.co/datasets/cruxeval-org/cruxeval). +Generate answers in the background on Android, then score them locally with +[Pydantic Evals](https://pydantic.dev/docs/ai/evals/evals/). + +## Connect and configure + +```{code-cell} ipython3 +# %pip install pydantic-evals datasets +``` + +```{code-cell} ipython3 +%load_ext pythonhere +%connect-there +``` + +We use the [LiteRT-LM version of Qwen2.5-Coder-3B-Instruct](https://huggingface.co/litert-community/Qwen2.5-Coder-3B-Instruct) +with greedy decoding (`top_k=1`), seed 42, +and a 128-token answer limit. `%there put` copies the run name and settings +to the device. + +`LIMIT=None` selects all 800 cases; set it to `3` for a short run. Reuse +`RUN_NAME` to resume, or choose a new name when changing the model, settings, +or selected cases. `REVISION` pins the dataset version. + +```{code-cell} ipython3 +import os +RUN_NAME = "cruxeval-qwen-direct-greedy-full-001" +LIMIT = None # All cases. +REVISION = "b96af0450242eb4da433032b90998f25588a5d0f" +settings = { + "model_repo": "litert-community/Qwen2.5-Coder-3B-Instruct", + "model_file": "Qwen2.5_Coder_3B_It.litertlm", + "sampler": {"temperature": 1.0, "top_p": 1.0, "top_k": 1, "seed": 42}, + "max_output_tokens": 128, +} +hf_token = os.environ.get("HF_TOKEN") + +%there put RUN_NAME +%there put settings +%there put hf_token +``` + +## Download the model + +```{code-cell} ipython3 +%%there --worker +from ml_here import download_hf_model, require_model + +try: + model = require_model(settings["model_repo"], settings["model_file"]) +except FileNotFoundError: + def report_progress(value): + if value.percent is not None: + print(f"\rDownloading: {value.percent:.1f}%", end="", flush=True) + + model = download_hf_model( + repo_id=settings["model_repo"], + filename=settings["model_file"], + token=hf_token, + progress=report_progress, + ) + +print(model) +``` + +## Load dataset and build prompts + +Each problem provides a function, an input, and an expected output. We use the +[CruxEval-O direct prompt](https://github.com/facebookresearch/cruxeval/blob/main/prompts.py) +to ask for the output; the expected answer stays local for scoring. + +```{code-cell} ipython3 +import ast +from datasets import load_dataset +from pprint import pprint as pp + +rows = load_dataset("cruxeval-org/cruxeval", revision=REVISION, split="test") +if LIMIT is not None: + rows = rows.select(range(LIMIT)) +problems = [dict(row) for row in rows] +assert len({p["id"] for p in problems}) == len(problems) +for p in problems: + ast.literal_eval(p["output"]) +pp(f"Selected {len(problems)} cases") +``` + +```{code-cell} ipython3 +def make_crux_prompt(inputs): + code, input = inputs["code"], inputs["input"] + instructions = ( + "You are given a Python function and an assertion containing an input " + "to the function. Complete the assertion with a literal (no unsimplified " + "expressions, no function calls) containing the output when executing " + "the provided code on the given input, even if the function is incorrect " + "or incomplete. Do NOT output any extra information. Provide the full " + "assertion with the correct output in [ANSWER] and [/ANSWER] tags, " + "following the examples." + ) + + return f"""{instructions} + +[PYTHON] +def f(n): + return n +assert f(17) == ?? +[/PYTHON] +[ANSWER] +assert f(17) == 17 +[/ANSWER] + +[PYTHON] +def f(s): + return s + "a" +assert f("x9j") == ?? +[/PYTHON] +[ANSWER] +assert f("x9j") == "x9ja" +[/ANSWER] + +[PYTHON] +{code} +assert f({input}) == ?? +[/PYTHON] +[ANSWER] +""" +``` + +```{code-cell} ipython3 +tasks = [{"id": p["id"], "prompt": make_crux_prompt(p)} for p in problems] +print(tasks[0]["prompt"]) +``` + +## Start/resume answers generation run + +`TaskRunner` saves answers on the device and continues after the notebook +disconnects. Reopening the same run resumes unfinished tasks. The engine is +shared across tasks, with a fresh conversation for each answer. + +```{code-cell} ipython3 +%there put tasks +``` + +```{code-cell} ipython3 +%%there +from tasks_here import TaskRunner, TaskRunExistsError + +try: + crux_runner = TaskRunner.create(RUN_NAME, max_attempts=3, metadata=settings) +except TaskRunExistsError: + crux_runner = TaskRunner.open(RUN_NAME) +if crux_runner.metadata != settings: + raise ValueError("Device settings differ; choose a new RUN_NAME") +existing = [r["task"] for r in crux_runner.results()] +if existing and existing != tasks: + raise ValueError("Device tasks differ; choose a new RUN_NAME") +if not existing: + crux_runner.add(tasks) +print(crux_runner.status()) +``` + +```{code-cell} ipython3 +%%there +import litert_lm +from ml_here import require_model + +def crux_setup(): + global crux_engine + if globals().get("crux_engine") is not None: + raise RuntimeError("Close previous crux_engine using the last cell before resuming") + crux_engine = litert_lm.Engine( + require_model(settings["model_repo"], settings["model_file"]), + backend=litert_lm.Backend.GPU(), enable_benchmark=True, + ) + return crux_engine + +def crux_execute(task, engine): + with engine.create_conversation( + sampler_config=litert_lm.SamplerConfig(**settings["sampler"]), + max_output_tokens=settings["max_output_tokens"], + ) as conversation: + response = conversation.send_message(task["prompt"]) + try: + info = conversation.get_benchmark_info() + benchmark = {k: getattr(info, k) for k in ( + "init_time_in_second", "time_to_first_token_in_second", + "last_prefill_token_count", "last_prefill_tokens_per_second", + "last_decode_token_count", "last_decode_tokens_per_second", + )} + benchmark_error = None + except Exception as exc: + benchmark, benchmark_error = None, str(exc) + return { + "output": "".join(b["text"] for b in response["content"] if "text" in b), + "benchmark": benchmark, "benchmark_error": benchmark_error, + } + +if not crux_runner.is_running(): + crux_runner.start(crux_execute, setup=crux_setup) +print(crux_runner.status()) +``` + +## Check progress and fetch the results + +You can fetch and score completed answers while generation continues. After +reconnecting, rerun the configuration and run-opening cells to access the saved +run; there is no need to start generation again just to retrieve answers. + +```{code-cell} ipython3 +%there get crux_runner.status() +``` + +```{code-cell} ipython3 +results = %there get crux_runner.results() +``` + +```{code-cell} ipython3 +pp(results[-1]) +``` + +## Score fetched answers locally + +Score `results` directly. TaskRunner keeps results on the phone, so you can +fetch them again later. No model calls or generated-code execution during scoring. + +We build a Pydantic Evals `Dataset` from completed answers and use a custom +`Evaluator` to extract each predicted Python literal and compare its value. +The report separates incorrect values from invalid answers that cannot be +parsed, such as unfinished literals or extra explanation. + +`generation_s` is elapsed time measured by TaskRunner around the final +`crux_execute` call on the device, including conversation setup and cleanup. +Engine loading and earlier retries are excluded. `decode_tokens_s` is the +decoding speed reported by LiteRT's benchmark. + +```{code-cell} ipython3 +import ast +import io +import tokenize +from dataclasses import dataclass + +from pydantic_evals import Case, Dataset, increment_eval_metric +from pydantic_evals.evaluators import Evaluator, EvaluationReason + + +def extract_crux_output(text): + # LiteRT returns the stop marker as text; upstream generation strips it. + candidate = text.split("[/ANSWER]", 1)[0] + if "[ANSWER]" in candidate: + candidate = candidate.split("[ANSWER]", 1)[1] + + # Find the assertion separator without splitting == inside quoted strings. + if candidate.strip().startswith("assert "): + lines = candidate.splitlines(keepends=True) + for token in tokenize.generate_tokens(io.StringIO(candidate).readline): + if token.type == tokenize.OP and token.string == "==": + row, column = token.end + candidate = "".join(lines[row - 1:])[column:] + break + + return ast.literal_eval(candidate.strip()) + + +@dataclass +class CruxLiteralMatch(Evaluator): + def evaluate(self, ctx): + expected = ast.literal_eval(ctx.expected_output) + + try: + actual = extract_crux_output(ctx.output) + except (SyntaxError, ValueError, TypeError, RecursionError, tokenize.TokenError) as exc: + return { + "passed": EvaluationReason(False, f"Invalid answer: {exc}"), + "failure": "invalid", + } + + if actual != expected: + return { + "passed": EvaluationReason( + False, + f"actual={actual!r}, expected={expected!r}", + ), + "failure": "incorrect", + } + + return {"passed": True} +``` + +```{code-cell} ipython3 +from collections import Counter +from pydantic_evals.evaluators import ReportEvaluator, ReportEvaluatorContext +from pydantic_evals.reporting.analyses import TableResult + +@dataclass +class CruxSummary(ReportEvaluator): + def evaluate(self, ctx: ReportEvaluatorContext): + counts = Counter() + + for case in ctx.report.cases: + assertion = case.assertions["passed"] + + if assertion.value: + counts["passed"] += 1 + else: + failure = case.labels.get("failure") + if failure is None: + raise ValueError( + f"Missing failure label for {case.name}" + ) + counts[failure.value] += 1 + + total = len(ctx.report.cases) + + return TableResult( + title="CruxEval results", + columns=["Scored", "Passed", "Pass rate", "Incorrect", "Invalid"], + rows=[[ + total, + counts["passed"], + f"{counts['passed'] / total:.1%}" if total else "N/A", + counts["incorrect"], + counts["invalid"], + ]], + ) +``` + +```{code-cell} ipython3 +answers = {r["id"]: r["result"]["output"] for r in results if r["status"] == "done"} +completed = {r["id"]: r for r in results if r["status"] == "done"} + +def saved_answer(case_id): + record = completed[case_id] + if record.get("duration") is not None: + increment_eval_metric("generation_s", record["duration"]) + benchmark = record["result"].get("benchmark") or {} + speed = benchmark.get("last_decode_tokens_per_second") + if speed is not None: + increment_eval_metric("decode_tokens_s", speed) + return answers[case_id] + +dataset = Dataset( + name="cruxeval_o_literal_demo", + cases=[Case(name=p["id"], inputs=p["id"], expected_output=p["output"]) + for p in problems if p["id"] in answers], + evaluators=[CruxLiteralMatch()], + report_evaluators=[CruxSummary()], +) +if not dataset.cases: + raise RuntimeError("No completed answers; check device status/errors") +report = await dataset.evaluate(saved_answer, max_concurrency=1) + +#report.print(include_durations=False, include_averages=True, include_reasons=True) +from dataclasses import replace +# Show the first eight cases; CruxSummary above covers all scored cases. +preview = replace(report, cases=report.cases[:8]) +preview.print(include_durations=False, include_averages=False, include_analyses=True, include_reasons=True) +``` + +```{code-cell} ipython3 +from rich.console import Console +from rich.table import Table +from rich.text import Text + +invalid = [ + c for c in report.cases + if c.labels.get("failure") is not None + and c.labels["failure"].value == "invalid" +] + +table = Table(title="Invalid answers") +table.add_column("Case", style="dim") +table.add_column("Output", overflow="fold") + +for case in invalid: + table.add_row( + case.name, + Text(repr(case.output)), + ) + +Console().print(table) +``` + +## Close the engine + +```{code-cell} ipython3 +%%there --worker +if globals().get("crux_engine"): + crux_engine.close() + crux_engine = None +``` diff --git a/examples/litert_evals/leetcode.md b/examples/litert_evals/leetcode.md new file mode 100644 index 0000000..fc63cb2 --- /dev/null +++ b/examples/litert_evals/leetcode.md @@ -0,0 +1,414 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.19.3 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# LeetCode + +Companion notebook for the video [*Benchmarking Local AI on Android with PythonHere and Pydantic Evals*](https://youtu.be/CSwZkyGWrhU). + +Generate Python solutions on Android using +[newfacade/LeetCodeDataset](https://huggingface.co/datasets/newfacade/LeetCodeDataset), +then run the dataset's tests locally with +[Pydantic Evals](https://pydantic.dev/docs/ai/evals/evals/). + +## Connect and configure + +```{code-cell} ipython3 +# %pip install pydantic-evals datasets +``` + +```{code-cell} ipython3 +%load_ext pythonhere +%connect-there +``` + +We use the [LiteRT-LM version of Qwen2.5-Coder-3B-Instruct](https://huggingface.co/litert-community/Qwen2.5-Coder-3B-Instruct) +with greedy decoding (`top_k=1`), seed 42, +and a 1,000-token answer limit. `%there put` copies the run name and settings +to the device. + +`LIMIT=None` selects the full test split; set it to `3` for a short run. +Reuse `RUN_NAME` to resume, or choose a new name when changing settings or +selected cases. `REVISION` pins the dataset version. + +```{code-cell} ipython3 +import os +RUN_NAME = "leetcode-qwen-greedy-full-001" +LIMIT = None # All cases. +REVISION = "215604aeed660029df7de2fea5a4d7b6ed476a08" +settings = { + "model_repo": "litert-community/Qwen2.5-Coder-3B-Instruct", + "model_file": "Qwen2.5_Coder_3B_It.litertlm", + "sampler": {"temperature": 1.0, "top_p": 1.0, "top_k": 1, "seed": 42}, + "max_output_tokens": 1000, + "dataset_revision": REVISION, +} +hf_token = os.environ.get("HF_TOKEN") + +%there put RUN_NAME +%there put settings +%there put hf_token +``` + +## Download the model + +```{code-cell} ipython3 +%%there --worker +from ml_here import download_hf_model, require_model + +try: + model = require_model(settings["model_repo"], settings["model_file"]) +except FileNotFoundError: + def report_progress(value): + if value.percent is not None: + print(f"\rDownloading: {value.percent:.1f}%", end="", flush=True) + + model = download_hf_model( + repo_id=settings["model_repo"], + filename=settings["model_file"], + token=hf_token, + progress=report_progress, + ) + +print(model) +``` + +## Load dataset and build prompts + +We send each problem's original `query` to the model. Tests stay local and +are used only for scoring. Inspect one prompt and its tests below. + +```{code-cell} ipython3 +from datasets import load_dataset +from pprint import pprint as pp + +rows = load_dataset("newfacade/LeetCodeDataset", revision=REVISION, split="test") +if LIMIT is not None: + rows = rows.select(range(LIMIT)) +problems = [dict(row) for row in rows] +assert problems, "No cases selected" +assert len({p["task_id"] for p in problems}) == len(problems) +pp(f"Selected {len(problems)} cases") +``` + +```{code-cell} ipython3 +print(problems[0]["query"]) +``` + +```{code-cell} ipython3 +print(problems[0]["test"]) +``` + +```{code-cell} ipython3 +tasks = [ + {"id": p["task_id"], "prompt": p["query"], + "metadata": {"difficulty": p["difficulty"].lower()}} + for p in problems +] +``` + +## Start/resume answers generation run + +`TaskRunner` saves answers on the device and continues after the notebook +disconnects. Starting the same named run processes unfinished tasks. The engine +is shared across tasks, with a fresh conversation for each solution. + +```{code-cell} ipython3 +%there put tasks +``` + +```{code-cell} ipython3 +%%there +from tasks_here import TaskRunner, TaskRunExistsError + +try: + leetcode_runner = TaskRunner.create(RUN_NAME, max_attempts=3, metadata=settings) +except TaskRunExistsError: + leetcode_runner = TaskRunner.open(RUN_NAME) + +existing = [r["task"] for r in leetcode_runner.results()] +if not existing: + leetcode_runner.add(tasks) + +``` + +```{code-cell} ipython3 +%%there +import litert_lm +from ml_here import require_model + +def leetcode_setup(): + global leetcode_engine + if globals().get("leetcode_engine") is not None: + raise RuntimeError("Close previous leetcode_engine using the last cell before resuming") + leetcode_engine = litert_lm.Engine( + require_model(settings["model_repo"], settings["model_file"]), + backend=litert_lm.Backend.GPU(), enable_benchmark=True, + ) + return leetcode_engine + +def leetcode_execute(task, engine): + with engine.create_conversation( + sampler_config=litert_lm.SamplerConfig(**settings["sampler"]), + max_output_tokens=settings["max_output_tokens"], + ) as conversation: + response = conversation.send_message(task["prompt"]) + try: + info = conversation.get_benchmark_info() + benchmark = {k: getattr(info, k) for k in ( + "init_time_in_second", "time_to_first_token_in_second", + "last_prefill_token_count", "last_prefill_tokens_per_second", + "last_decode_token_count", "last_decode_tokens_per_second", + )} + benchmark_error = None + except Exception as exc: + benchmark, benchmark_error = None, str(exc) + return { + "output": "".join(b["text"] for b in response["content"] if "text" in b), + "benchmark": benchmark, "benchmark_error": benchmark_error, + } + +if not leetcode_runner.is_running(): + leetcode_runner.start(leetcode_execute, setup=leetcode_setup) +print(leetcode_runner.status()) +``` + +## Check progress and fetch the results + +Completed answers can be fetched and scored while generation continues. +After reconnecting, rerun the configuration and run-opening cells to retrieve +saved answers without starting generation again. + +```{code-cell} ipython3 +%there get leetcode_runner.status() +``` + +```{code-cell} ipython3 +results = %there get leetcode_runner.results() +``` + +```{code-cell} ipython3 +pp(results[-1]) +``` + +## Score fetched answers locally + +We build a Pydantic Evals `Dataset` from completed answers. The custom +`LeetCodePass` evaluator extracts Python code and runs each solution with its +tests in a local subprocess, with a 10-second timeout. The difficulty summary +separates passes, assertion failures, invalid answers, syntax errors, runtime +errors, and timeouts. + +`generation_s` is TaskRunner's elapsed time around the final `leetcode_execute` +call on the device, including conversation setup and cleanup but excluding +engine loading and earlier retries. `decode_tokens_s` is the decoding speed +reported by LiteRT's benchmark. + +```{code-cell} ipython3 +import sys +import json +import re +import subprocess +from dataclasses import dataclass + +from pydantic_evals import Case, Dataset, increment_eval_metric +from pydantic_evals.evaluators import Evaluator, EvaluationReason + + +def extract_python_code(text): + fences = re.findall(r"```([^\n`]*)\n(.*?)```", text, flags=re.DOTALL) + if fences: + if len(fences) != 1 or fences[0][0].strip().lower() not in {"", "python", "py"}: + raise ValueError("Expected one Python code block") + code = fences[0][1].strip() + elif "```" in text: + raise ValueError("Incomplete code block") + else: + code = text.strip() + if not code: + raise ValueError("Empty code") + return code + + +def execute_problem(problem, code, timeout): + program = "\n".join([ + problem["prompt"], code, problem["test"], + f"check({problem['entry_point']})", + ]) + # Report success only after the complete program and tests return. + harness = f''' +import json +try: + exec(compile({program!r}, "", "exec"), {{}}) +except SyntaxError as exc: + result = {{"outcome": "syntax_error", "error": str(exc)}} +except AssertionError as exc: + result = {{"outcome": "test_failed", "error": "AssertionError: " + str(exc)}} +except BaseException as exc: + result = {{"outcome": "runtime_error", "error": type(exc).__name__ + ": " + str(exc)}} +else: + result = {{"outcome": "passed"}} +print("__TEST_RESULT__" + json.dumps(result)) +''' + try: + process = subprocess.run( + [sys.executable, "-I", "-"], input=harness, + text=True, capture_output=True, timeout=timeout, + ) + except subprocess.TimeoutExpired: + return {"outcome": "timeout", "error": f"Exceeded {timeout:g} seconds"} + for line in reversed(process.stdout.splitlines()): + if line.startswith("__TEST_RESULT__"): + return json.loads(line[len("__TEST_RESULT__"):]) + return {"outcome": "runtime_error", "error": process.stderr.strip() or "Tests did not finish"} + + +@dataclass +class LeetCodePass(Evaluator): + problems: dict + timeout: float = 10.0 + + def evaluate(self, ctx): + try: + code = extract_python_code(ctx.output) + except ValueError as exc: + return { + "passed": EvaluationReason(False, str(exc)), + "failure": "invalid", + } + + problem = self.problems[ctx.inputs] + result = execute_problem(problem, code, self.timeout) + if result["outcome"] == "passed": + return {"passed": True} + return { + "passed": EvaluationReason(False, result.get("error") or result["outcome"]), + "failure": result["outcome"], + } +``` + +```{code-cell} ipython3 +from collections import Counter +from pydantic_evals.evaluators import ReportEvaluator, ReportEvaluatorContext +from pydantic_evals.reporting.analyses import TableResult + + +@dataclass +class LeetCodeSummary(ReportEvaluator): + def evaluate(self, ctx: ReportEvaluatorContext): + categories = ["passed", "test_failed", "invalid", "syntax_error", + "runtime_error", "timeout"] + rows = [] + for difficulty in ["all", "easy", "medium", "hard"]: + cases = [c for c in ctx.report.cases + if difficulty == "all" or c.metadata["difficulty"] == difficulty] + if not cases: + continue + counts = Counter() + for case in cases: + if case.assertions["passed"].value: + counts["passed"] += 1 + else: + counts[case.labels["failure"].value] += 1 + rows.append([difficulty, len(cases), + *[round(100 * counts[name] / len(cases), 1) + for name in categories]]) + return TableResult( + title="LeetCode results by difficulty", + columns=["Difficulty", "N", "Passed %", "Assertion %", "Invalid %", + "Syntax %", "Runtime %", "Timeout %"], + rows=rows, + ) +``` + +```{code-cell} ipython3 +problems_by_id = {p["task_id"]: p for p in problems} +completed = {r["id"]: r for r in results if r["status"] == "done"} +for case_id, record in completed.items(): + if case_id not in problems_by_id or record["task"]["prompt"] != problems_by_id[case_id]["query"]: + raise ValueError("Fetched tasks differ from selected dataset") + +def saved_answer(case_id): + record = completed[case_id] + if record.get("duration") is not None: + increment_eval_metric("generation_s", record["duration"]) + benchmark = record["result"].get("benchmark") or {} + speed = benchmark.get("last_decode_tokens_per_second") + if speed is not None: + increment_eval_metric("decode_tokens_s", speed) + return record["result"]["output"] + +dataset = Dataset( + name="pythonhere-leetcode", + cases=[Case(name=p["task_id"], inputs=p["task_id"], + metadata={"difficulty": p["difficulty"].lower()}) + for p in problems if p["task_id"] in completed], + evaluators=[LeetCodePass(problems_by_id)], + report_evaluators=[LeetCodeSummary()], +) +if not dataset.cases: + raise RuntimeError("No completed answers; check device status/errors") +report = await dataset.evaluate(saved_answer, max_concurrency=1) + +# report.print(include_durations=False, include_averages=True, include_reasons=True) +from dataclasses import replace +# Show the first eight cases; LeetCodeSummary covers all scored cases. +preview = replace(report, cases=report.cases[:8]) +preview.print(include_durations=False, include_averages=False, include_analyses=True, include_reasons=True) +``` + +Show bad answers that are missing `class Solution`. + +```{code-cell} ipython3 +from rich.console import Console +from rich.table import Table +from rich.text import Text + +weird = [ + r["result"]["output"] + for r in results + if r["status"] == "done" + and "class Solution" not in r["result"]["output"] +] + +table = Table(title=f"Unexpected outputs ({len(weird)})") +table.add_column("#", style="dim", justify="right") +table.add_column("Output", overflow="fold") + +for r in results: + if r["status"] == "done": + s = r["result"]["output"] + if "class Solution" not in s: + table.add_row(r["id"], Text(repr(s[:300]))) + +Console().print(table) +``` + +Another bad answer from the video starts with `class Solution`, but keeps +adding nested loops until the output is cut off. Show that problem's saved answer: + +```{code-cell} ipython3 +example_id = "find-the-lexicographically-largest-string-from-the-box-i" +if example_id in completed: + print(completed[example_id]["result"]["output"]) +else: + print(f"No saved answer for {example_id} in this run.") +``` + +## Close the engine + +```{code-cell} ipython3 +%%there --worker +if globals().get("leetcode_engine") is not None: + leetcode_engine.close() + leetcode_engine = None +``` diff --git a/examples/litert_evals/quiz.md b/examples/litert_evals/quiz.md new file mode 100644 index 0000000..053a335 --- /dev/null +++ b/examples/litert_evals/quiz.md @@ -0,0 +1,286 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.19.3 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# Quiz + +Companion notebook for the video [*Benchmarking Local AI on Android with PythonHere and Pydantic Evals*](https://youtu.be/CSwZkyGWrhU). + +Run a six-question Python quiz against a model on your Android device, then +score its answers locally with [Pydantic Evals](https://pydantic.dev/docs/ai/evals/evals/). + +## Connect and configure + +```{code-cell} ipython3 +# %pip install pydantic-evals +``` + +```{code-cell} ipython3 +%load_ext pythonhere +%connect-there +``` + +```{code-cell} ipython3 +from herethere.everywhere import ConnectionConfig +from herethere.there import Client + +client = Client() +await client.connect(ConnectionConfig.load(path="there.env", prefix="there")) +await client.ping() +``` + +We use the [LiteRT-LM version of Qwen2.5-Coder-3B-Instruct](https://huggingface.co/litert-community/Qwen2.5-Coder-3B-Instruct), with greedy decoding +and a 16-token answer limit. `%there put` copies these settings to the device for model loading and inference. + +```{code-cell} ipython3 +import os + +settings = { + "model_repo": "litert-community/Qwen2.5-Coder-3B-Instruct", + "model_file": "Qwen2.5_Coder_3B_It.litertlm", + "sampler": {"temperature": 1.0, "top_p": 1.0, "top_k": 1, "seed": 42}, + "max_output_tokens": 16, +} +hf_token = os.environ.get("HF_TOKEN") + +%there put settings +%there put hf_token +``` + +## Download the model + +```{code-cell} ipython3 +%%there --worker +from ml_here import download_hf_model, require_model +try: + model = require_model(settings["model_repo"], settings["model_file"]) +except FileNotFoundError: + def report_progress(value): + if value.percent is not None: + print(f"\rDownloading: {value.percent:.1f}%", end="", flush=True) + + model = download_hf_model( + repo_id=settings["model_repo"], + filename=settings["model_file"], + token=hf_token, + progress=report_progress, + ) + +print(model) +``` + +## Load the model + +The engine stays loaded across questions, but each answer uses a fresh +conversation so questions are answered independently. + +```{code-cell} ipython3 +%%there --worker +import litert_lm +from ml_here import require_model + +if globals().get("quiz_engine") is not None: + quiz_engine.close() +quiz_engine = None + +quiz_engine = litert_lm.Engine( + require_model(settings["model_repo"], settings["model_file"]), + backend=litert_lm.Backend.GPU(), +) + +def quiz_answer(prompt): + with quiz_engine.create_conversation( + sampler_config=litert_lm.SamplerConfig(**settings["sampler"]), + max_output_tokens=settings["max_output_tokens"], + ) as conversation: + response = conversation.send_message(prompt) + return "".join(block["text"] for block in response["content"] if "text" in block) + +print(quiz_engine) +``` + +## Define questions + +For this simple quiz, we define the questions directly in a Pydantic Evals +`Dataset`. Each `Case` contains a question, answer choices, and the expected +letter; `EqualsExpected()` scores the model's response against that letter. + +```{code-cell} ipython3 +from typing_extensions import TypedDict + +from pydantic_evals import Case, Dataset +from pydantic_evals.evaluators import EqualsExpected + + +class QuestionInputs(TypedDict): + question: str + options: dict[str, str] + + +dataset = Dataset[QuestionInputs, str, None]( + name="python-quiz", + cases=[ + Case( + name="mutable-container", + inputs={ + "question": "Which built-in type is mutable?", + "options": { + "A": "tuple", + "B": "list", + "C": "str", + "D": "int", + }, + }, + expected_output="B", + ), + Case( + name="floor-division", + inputs={ + "question": "What is the value of 7 // 2 in Python 3?", + "options": { + "A": "3.5", + "B": "4", + "C": "2", + "D": "3", + }, + }, + expected_output="D", + ), + Case( + name="list-alias", + inputs={ + "question": ( + "What does this print?\n\n" + "a = [1, 2]\n" + "b = a\n" + "b.append(3)\n" + "print(a)" + ), + "options": { + "A": "[1, 2, 3]", + "B": "[1, 2]", + "C": "[3]", + "D": "None", + }, + }, + expected_output="A", + ), + Case( + name="empty-set", + inputs={ + "question": "Which expression creates an empty set?", + "options": { + "A": "{}", + "B": "[]", + "C": "set()", + "D": "()", + }, + }, + expected_output="C", + ), + Case( + name="mutable-default", + inputs={ + "question": ( + "What does the second call print?\n\n" + "def add(x, items=[]):\n" + " items.append(x)\n" + " return items\n\n" + "add(1)\n" + "print(add(2))" + ), + "options": { + "A": "[2]", + "B": "[1, 2]", + "C": "[]", + "D": "Raises TypeError", + }, + }, + expected_output="B", + ), + Case( + name="unpacking-comprehension-315", + inputs={ + "question": ( + "In Python 3.15, what does this print?\n\n" + "groups = [[1, 2], [3]]\n" + "print([*group for group in groups])" + ), + "options": { + "A": "SyntaxError", + "B": "[[1, 2], [3]]", + "C": "[1, 2, 3]", + "D": "TypeError", + }, + }, + expected_output="C", + ), + ], + evaluators=[EqualsExpected()], +) +``` + +## Define the task + +```{code-cell} ipython3 +def build_prompt(inputs: QuestionInputs) -> str: + options = "\n".join( + f"{letter}: {inputs['options'][letter]}" + for letter in "ABCD" + ) + return ( + "Answer the Python multiple-choice question.\n" + "Exactly one option is correct.\n" + "Reply with only A, B, C, or D. Do not explain.\n\n" + f"{inputs['question'].rstrip()}\n\n" + f"{options}\n\n" + "Answer:" + ) + +async def answer_question(inputs: QuestionInputs) -> str: + prompt = build_prompt(inputs) + response = await client.get_worker(f"quiz_answer({prompt!r})") + return response.strip() +``` + +Inspect the prompt and try one question: + +```{code-cell} ipython3 +example = dataset.cases[0] +print(build_prompt(example.inputs)) +``` + +```{code-cell} ipython3 +print(repr(await answer_question(example.inputs))) +``` + +## Run and inspect + +Scoring requires the expected letter alone, ignoring surrounding whitespace. +Extra explanation counts as a failed answer. Report durations include the client round trip. + +```{code-cell} ipython3 +report = await dataset.evaluate(answer_question, max_concurrency=1) +report.print(include_input=True, include_output=True, include_expected_output=True) +``` + +## Close the model and client + +```{code-cell} ipython3 +%%there --worker +quiz_engine.close() +quiz_engine = None +``` + +```{code-cell} ipython3 +await client.disconnect() +``` From fcaa6ddf7eb831181dc42111600e10bb8a699128 Mon Sep 17 00:00:00 2001 From: b3b Date: Fri, 20 Nov 2026 21:07:52 +0100 Subject: [PATCH 13/13] Add Android app inspector notebook --- examples/diy_app_inspector.md | 504 ++++++++++++++++++++++++++++++++++ 1 file changed, 504 insertions(+) create mode 100644 examples/diy_app_inspector.md diff --git a/examples/diy_app_inspector.md b/examples/diy_app_inspector.md new file mode 100644 index 0000000..cd0f295 --- /dev/null +++ b/examples/diy_app_inspector.md @@ -0,0 +1,504 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.19.3 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# DIY #1: App Inspector + +Companion notebook for the video [*Android DIY #1 — Where did that app come from?*](https://youtube.com/shorts/-wIceFaHI9w) + +Let's explore installed apps with PythonHere, see which installers Android associates with them, and build an interactive app browser. + +## Connect to Android + +Connect PythonHere to your phone and access Android's `PackageManager` to inspect installed apps. + +```{code-cell} ipython3 +%load_ext pythonhere +%connect-there +``` + +```{code-cell} ipython3 +%%there +from jnius import autoclass +from kivy.logger import Logger + +activity = autoclass("org.kivy.android.PythonActivity").mActivity +pm = activity.getPackageManager() +PackageManager = autoclass("android.content.pm.PackageManager") +ApplicationInfo = autoclass("android.content.pm.ApplicationInfo") +VERSION = autoclass("android.os.Build$VERSION") +print(PackageManager) +``` + +## Collect apps and installation sources + +Use Android's `PackageManager` to list installed apps and find their recorded installers. We'll use this information to group apps by installation source. + +```{code-cell} ipython3 +%%there +def installer_name(package): + try: + if VERSION.SDK_INT >= 30: + source = pm.getInstallSourceInfo(package) + return str(source.getInstallingPackageName() or "") + return str(pm.getInstallerPackageName(package) or "") + except Exception as exc: + Logger.warning(f"Packages: Install source unavailable for {package}: {exc}") + return "" + +print("PythonHere app installer is", installer_name("me.herethere.pythonhere")) +``` + +```{code-cell} ipython3 +%%there +packages = pm.getInstalledPackages(0) + +apps = [] +for package in packages: + info = package.applicationInfo + apps.append({ + "label": str(pm.getApplicationLabel(info)), + "package": str(package.packageName), + "system": bool(info.flags & ( + ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_UPDATED_SYSTEM_APP + )), + "installer": installer_name(str(package.packageName)), + }) +apps.sort(key=lambda row: (row["label"].casefold(), row["package"])) +print(f"{len(apps)} visible apps") +``` + +## Group apps by installer + +Group apps by their recorded installer, so we can explore which apps belong to each source. + +```{code-cell} ipython3 +%%there +apps_by_installer = {} +for row in apps: + installer = row["installer"] + if installer not in apps_by_installer: + apps_by_installer[installer] = [] + apps_by_installer[installer].append(row) + +print(f"{len(apps_by_installer)} installer groups") +``` + +## Show readable installer names + +Android identifies installers by package IDs, such as `com.android.vending` for Google Play Store. + +Let's show readable names where available and count the apps associated with each installer. + +```{code-cell} ipython3 +%%there +app_labels = {} +for row in apps: + app_labels[row["package"]] = row["label"] + +installers = [] +for package, installed_apps in apps_by_installer.items(): + if package: + label = app_labels.get(package) or package + else: + label = "No recorded installer" + installers.append({ + "package": package, + "label": label, + "count": len(installed_apps), + }) + +installers.sort(key=lambda installer: installer["label"].casefold()) +for installer in installers: + print(f"{installer['label']} ({installer['count']})") + print(f" {installer['package'] or '(not recorded)'}") +``` + +## Explore apps from one installer + +Let's look at apps associated with a particular installer. + +The example uses Samsung's `com.samsung.android.app.omcagent`. You can choose any installer from your own results. + +```{code-cell} ipython3 +%%there +selected_installer = "com.samsung.android.app.omcagent" +selected_apps = apps_by_installer.get(selected_installer, []) +print(f"{len(selected_apps)} apps") +for row in selected_apps: + print(f'{row["label"]:<32} {row["package"]}') +if not selected_apps: + print("No apps for this installer. Choose a package ID from the installer list above.") +``` + +## Open Android's App info + +Let's make each app card clickable, so tapping it opens Android's built-in **App info** screen. + +```{code-cell} ipython3 +%%there +from datetime import datetime + +from android.runnable import run_on_ui_thread +from kivy.clock import Clock +from kivy.properties import ObjectProperty, StringProperty +from kivy.uix.boxlayout import BoxLayout +from kivy.uix.behaviors import ButtonBehavior +from kivy.uix.label import Label +from kivy.uix.spinner import SpinnerOption + + +Intent = autoclass("android.content.Intent") +Uri = autoclass("android.net.Uri") +PythonActivity = autoclass("org.kivy.android.PythonActivity") +settings_status = {} + + +@run_on_ui_thread +def open_app_settings(package): + """Open Android's app-info page for the tapped card.""" + try: + activity = PythonActivity.mActivity + intent = Intent("android.settings.APPLICATION_DETAILS_SETTINGS") + intent.setData(Uri.parse("package:" + package)) + activity.startActivity(intent) + settings_status.update(ok=True, package=package, error=None) + except Exception as exc: + Logger.exception("Packages: Could not open app settings") + settings_status.update(ok=False, package=package, error=str(exc)) + Clock.schedule_once(show_settings_error) + + +def show_settings_error(_): + package_ui.ids.status.text = "Could not open app settings" + +# open_app_settings("me.herethere.pythonhere") +``` + +## Load app icons + +Use `PackageManager` to get each app's icon and display it in Kivy. We'll cache the icons to keep scrolling smooth. + +```{code-cell} ipython3 +%%there +from io import BytesIO +from kivy.core.image import Image as CoreImage + +Bitmap = autoclass("android.graphics.Bitmap") +BitmapConfig = autoclass("android.graphics.Bitmap$Config") +CompressFormat = autoclass("android.graphics.Bitmap$CompressFormat") +Canvas = autoclass("android.graphics.Canvas") +ByteArrayOutputStream = autoclass("java.io.ByteArrayOutputStream") + +icon_textures = {} # Reuse icons when a card appears again. +icon_errors = {} + + +def get_app_icon(package): + if package not in icon_textures and package not in icon_errors: + try: + drawable = pm.getApplicationIcon(package) + if drawable is None: # The optional mock has no real icons. + icon_errors[package] = "No Android icon" + return None + bitmap = Bitmap.createBitmap(64, 64, BitmapConfig.ARGB_8888) + stream = ByteArrayOutputStream() + try: + drawable.setBounds(0, 0, 64, 64) + drawable.draw(Canvas(bitmap)) + bitmap.compress(CompressFormat.PNG, 100, stream) + png = bytes(value & 0xFF for value in stream.toByteArray()) + finally: + stream.close() + bitmap.recycle() + icon_textures[package] = CoreImage(BytesIO(png), ext="png").texture + except Exception as exc: + Logger.exception(f"Packages: Icon unavailable for {package}") + icon_errors[package] = str(exc) + return icon_textures.get(package) +``` + +## Create app cards + +Each card will show an app's icon, name, package ID, version, and installation date. + +We'll use Kivy's `RecycleView` to make the list scrollable. Tap a card to open **App info**. + +```{code-cell} ipython3 +%%there +# Appearance is defined in the KV cell below. +class InstallerOption(SpinnerOption): + pass + + +class CardLabel(Label): + pass + +class InstallerCard(ButtonBehavior, BoxLayout): + title = StringProperty("") + package = StringProperty("") + initials = StringProperty("") + icon_texture = ObjectProperty(None, allownone=True) + summary = StringProperty("") + installed_text = StringProperty("") + + def on_package(self, *_): + # RecycleView calls this when the card is assigned another app. + self.icon_texture = get_app_icon(self.package) if self.package else None + + def on_release(self): + open_app_settings(self.package) +``` + +## Add an installer dropdown + +Create a dropdown with **All apps** and the available installers. Show the number of apps next to each option. + +```{code-cell} ipython3 +%%there +installer_options = {f"All apps ({len(apps)})": None} +for installer in installers: + name = installer["label"] + matching_names = [item for item in installers if item["label"] == name] + if len(matching_names) > 1: + name += f" [{installer['package']}]" + option = f"{name} ({installer['count']})" + installer_options[option] = installer["package"] +``` + +## Filter apps by installer + +Update the app list whenever an installer is selected from the dropdown. + +```{code-cell} ipython3 +%%there +# Called when the dropdown selection changes. +def render_packages(*_): + installer = installer_options[package_ui.ids.installer.text] + if installer is None: + matching_apps = apps + source_text = "All recorded install sources" + else: + matching_apps = apps_by_installer.get(installer, []) + source_text = installer or "Installer unknown" + package_ui.ids.source.text = source_text + count_text = f"{len(matching_apps)} apps" + package_ui.ids.status.text = ( + f"Demo data / {count_text}" if getattr(pm, "is_demo", False) else count_text + ) + cards = [] + for row in matching_apps: + detail = package_details.get(row["package"], {}) + summary = "System app" if row["system"] else "App" + if detail.get("version"): + summary += " / v" + detail["version"] + installed = detail.get("installed") + if installed: + installed_text = "Installed on " + installed + else: + installed_text = "Install date unavailable" + cards.append({ + "title": row["label"], + "package": row["package"], + "initials": row["label"][:2].upper(), + "summary": summary, + "installed_text": installed_text, + }) + package_ui.ids.results.data = cards + package_ui.ids.results.scroll_y = 1 +``` + +## Build the Android interface + +Use Kivy's KV language for the dropdown, scrollable cards, colors, and layout. + +```{code-cell} ipython3 +%%there kv -c +#:import dp kivy.metrics.dp +#:import rgba kivy.utils.get_color_from_hex + +# Shared text style keeps individual labels short. +: + font_size: '14sp' + color: rgba('#BDCCE3') + halign: 'left' + valign: 'middle' + text_size: self.size + shorten: True + shorten_from: 'right' + +: + height: dp(54) + font_size: '17sp' + halign: 'left' + padding: dp(18), 0 + text_size: self.width - dp(36), None + background_normal: '' + background_down: '' + background_color: rgba('#1F4D52') if self.state == 'down' else rgba('#171F2E') + color: rgba('#E0F0FF') + +: + orientation: 'vertical' + padding: dp(16) + spacing: dp(6) + size_hint_y: None + height: dp(164) + canvas.before: + Color: + rgba: rgba('#1F404A') if self.state == 'down' else rgba('#171F2E') + RoundedRectangle: + pos: self.pos + size: self.size + radius: [dp(16)] + BoxLayout: + size_hint_y: None + height: dp(44) + spacing: dp(12) + FloatLayout: + size_hint_x: None + width: dp(44) + Image: + texture: root.icon_texture + allow_stretch: True + size_hint: None, None + size: dp(40), dp(40) + pos_hint: {'center_x': 0.5, 'center_y': 0.5} + opacity: 1 if root.icon_texture else 0 + CardLabel: + text: root.initials if not root.icon_texture else '' + font_size: '20sp' + bold: True + color: rgba('#1AE6BD') + halign: 'center' + pos_hint: {'center_x': 0.5, 'center_y': 0.5} + CardLabel: + text: root.title + font_size: '21sp' + bold: True + color: 1, 1, 1, 1 + CardLabel: + text: root.package + font_size: '12sp' + color: rgba('#8FA8C9') + size_hint_y: None + height: dp(20) + CardLabel: + text: root.summary + font_size: '12sp' + color: rgba('#1AE6BD') + size_hint_y: None + height: dp(20) + CardLabel: + text: root.installed_text + valign: 'top' + max_lines: 2 + +BoxLayout: + orientation: 'vertical' + padding: dp(18), dp(14) + spacing: dp(10) + canvas.before: + Color: + rgba: rgba('#090D16') + Rectangle: + pos: self.pos + size: self.size + Spinner: + id: installer + font_size: '18sp' + size_hint_y: None + height: dp(58) + background_normal: '' + background_color: rgba('#171F2E') + color: rgba('#1AE6BD') + Label: + id: source + font_size: '11sp' + color: rgba('#8FA8C9') + halign: 'left' + text_size: self.size + valign: 'middle' + size_hint_y: None + height: dp(22) + shorten: True + shorten_from: 'right' + Label: + id: status + font_size: '18sp' + bold: True + halign: 'left' + text_size: self.size + size_hint_y: None + height: dp(28) + RecycleView: + id: results + viewclass: 'InstallerCard' + do_scroll_x: False + RecycleBoxLayout: + default_size: None, dp(164) + default_size_hint: 1, None + size_hint_y: None + height: self.minimum_height + orientation: 'vertical' + spacing: dp(10) +``` + +## Show the browser on the phone + +Browse installed apps, check their versions and installation dates, and filter them by installer. Tap an app to open its **App info** screen, then use Android Back to return. + +```{code-cell} ipython3 +%%there +# Read app versions and install dates. +package_details = {} +package_detail_errors = [] + +for package in packages: + name = str(package.packageName) + try: + installed = "" + if package.firstInstallTime: + installed = datetime.fromtimestamp( + package.firstInstallTime / 1000 + ).strftime("%Y-%m-%d") + package_details[name] = { + "version": str(package.versionName or ""), + "installed": installed, + } + except Exception as exc: + Logger.warning(f"Packages: Details unavailable for {name}: {exc}") + package_detail_errors.append({"package": name, "error": str(exc)}) + +print(next(iter(package_details.items()))) +print("Errors:", package_detail_errors) +``` + +```{code-cell} ipython3 +%%there +package_ui = root +spinner = package_ui.ids.installer +spinner.option_cls = InstallerOption +spinner.values = list(installer_options) + +spinner.text = spinner.values[0] # All apps +spinner.bind(text=render_packages) +render_packages() +``` + +## Preview the result + +Take a screenshot of the Android screen and display it here in Jupyter. + +```{code-cell} ipython3 +%there -d 1 screenshot -w 200 +```