Skip to main content

OS Helper

🇫🇷 · 🇬🇧

CI License: BSD-3-Clause Python Local-first

OS Helper belongs to a collection of libraries called AI Helpers developed for building Artificial Intelligence.

🌍 AI Helpers

logo

OS Helper is a Python library that provides utility functions for working with different operating systems. It offers a set of tools to simplify common system operations, file handling, and OS-specific tasks.

The Promise

os-helper is part of a local-first, sovereignty-minded suite. Rather than market that, here is the honest, case-by-case reality:

  1. Guaranteed local. os-helper is a pure local filesystem / utility toolbox. Nothing is uploaded, there is no telemetry, and there is no account. The optional Tree Radar GUI reads your disk and renders the treemap locally in your browser (the server binds to 127.0.0.1 only); your paths, sizes, and content hashes never leave the machine.

  2. Not possible to be local: the caveats. Two helpers make outbound HTTP by design, because fetching something is their whole purpose: download_file() (it downloads a URL you hand it) and the URL-liveness checks (is_working_url() / check_url). get_user_ip() also calls a public echo service on purpose. These are the only network calls in the library, and you only trigger them by explicitly calling them. The Tree Radar page makes none either: its charting script (D3) ships inside the package and is served by the local app, so the treemap draws offline.

  3. Your decision. Nothing here forces the cloud. temporary_remote_file() can stage to S3/GCS/SFTP, but only when you wire it to a remote. If you build network behavior on top of os-helper, that is your choice, never a default.

Documentation

💻 Documentation

🗺️ Landscape

📋 Examples

🔐 Credentials Management

Features

Everything is a thin, well-typed, well-documented wrapper: no heavy system dependency, pure-Python across macOS / Linux / Windows.

  • OS detection: windows(), linux(), macos(), unix(), and platform_name() (darwin / linux / windows).

  • Hardware inspection: hardware_info() (one-call snapshot), plus its building blocks: cpu_count_logical(), cpu_count_physical(), cpu_model(), ram_gb(), gpu_vendor() (apple/nvidia/amd/intel/cpu), gpus() (name + VRAM per discrete GPU), apple_chip_name() / apple_unified_memory_gb() for Apple Silicon's shared memory pool. Live figures too: cpu_percent(), available_ram_gb(), disk_usage_gb(), gpu_utilization_percent() (Apple via IOKit, no sudo/powermetrics needed; NVIDIA via nvidia-smi; AMD via rocm-smi).

  • Process and command execution: system() (shell-free subprocess, captured stdout/stderr, optional exit-code and expected-output checks), openfile() (open with the OS default app), getpid(), get_nb_workers() (scikit-learn n_jobs convention, NB_WORKERS-overridable).

  • Paths: join(), folder_name_ext() (splits on the last dot only, so archive.tar.gz decomposes as archive.tar + gz, never collapsed to one multi-part extension), absolute2relative_path(), relative2absolute_path(), path_without_home(), recursive_glob().

  • Files and directories: file_exists(), dir_exists() (with emptiness checks), size_file(), checkfile(), copyfile(), make_directory(), remove_directory(), remove_files() (best-effort batch).

  • Temporary resources: temporary_filename() (context-managed, optional target directory), temporary_folder(), make_temporary_directory() (persistent, caller-owned cleanup), temporary_remote_file() (stage to S3/GCS/SFTP/anywhere with guaranteed remote cleanup).

  • Hashing: hash_string(), hashfile(), hashfolder() (RIPEMD-160 when available, BLAKE2b fallback; stable 40-char hex digests cross-platform).

  • Configuration loading: get_config() with a deterministic fallback order, JSON/YAML file (or folder), then .env files, then process environment. allow_ambient_env=False drops that last step down to the named .env files only, which is what the HTTP API does so a network caller cannot read the server's environment.

  • Localization: three mechanisms, one per shape of problem.

    • Catalog — Catalog.from_package() reads gettext .po/.mo catalogues keyed on the English source string, which is what the suite's GUIs use. Catalog.problems(used=...) reports a source the code asks for that no catalogue carries: the check that keeps a reworded sentence from silently half-reverting to English. compile_catalogs() writes the .mo itself, so GNU msgfmt is never a build dependency.
    • Locales — Locales.from_path() reads a locales/i18n.yaml holding every human-readable string in one place. It resolves a key for a locale with a deterministic fallback to the declared default, fills {placeholder} fields safely with render(), and reports every missing translation or mismatched placeholder at once with problems() — the check a CI job asserts on. Sections are named by the caller and mean nothing here, so one loader serves whatever each package keeps in its file.
    • Prompts — Prompts.from_path() reads one section of the same kind of YAML file as text a model reads. Each language of a prompt is written on its own rather than translated, so it is keyed on meaning (axis_prompt), never on the English wording that prompt engineering keeps rewriting. text() / render() resolve fr-CA to fr and accept system / user fields, bundle() returns every prompt for one language, and problems() reports a language that drops a {field} the code fills.

    The .po tooling behind Catalog is public too: parse_po(), write_po(), untranslated(), build_mo(), extract_sources() / extract_call_sites() (every English string the markup or the Python source asks for) and language_candidates().

  • Strings: emptystring() (None / empty / whitespace), asciistring() (accent-folding, filesystem-safe slugs).

  • Downloads and networking: download_file() (streaming with flat memory and an adaptive block size, resumable through a .part sidecar and HTTP Range, retried with backoff, renamed into place only once complete, optionally sha256-verified, skipped when the file is already there, progress bar; returns {path, content_type, bytes, sha256, resumed}), progress_bar() (shared byte-scaled tqdm factory, auto-quiet off-TTY), is_working_url(), get_user_ip().

  • Folder reporting and archiving: folder_description() (size map, Bootstrap index.html, and description.json), zip_folder() and its inverse unzip_folder() (refuses members that would escape the destination, idempotent on a populated folder).

  • Durations and timestamps: now_string(), format_size(), time2str(), str2time().

  • Timing and profiling: wall_timer(), cpu_timer(), gpu_timer() (CUDA events / Apple-Silicon MPS, lazy torch), and MATLAB-style tic() / toc().

  • Logging surface: init_logging() (colored console + file, named-logger and live-stream modes), verbosity() (integer level get/set), and debug() / info() / warning() / error() / critical() / check().

  • Multiple surfaces, one codebase: importable library, an HTTP API (os-helper-api, via [api]), MCP tools (os-helper-mcp, via [mcp]) and the Tree Radar GUI (os-helper-gui, via [gui]).

    The API and MCP surfaces expose only the safe, side-effect-free subset — hardware info, hashing, ASCII, formatting, URL check, config loading — with no filesystem mutation.

    There is deliberately no command line: os-helper is the suite's foundation, and every one of the sixteen other members reaches it by import os_helper as osh.

How it works

How os-helper works: the same call, whatever machine it lands on

Installation

Prerequisites: Python 3.10–3.13 and git, cross-platform (os-helper needs no heavy system dependency):

  • 🍎 macOS (Homebrew): brew install python git
  • 🐧 Ubuntu/Debian: sudo apt update && sudo apt install -y python3 python3-pip git
  • 🪟 Windows (PowerShell): winget install Python.Python.3.12 Git.Git

We recommend using Python environments. Check this link if you're unfamiliar with setting one up: 🥸 Tech tips.

pip install os-helper

From source (no PyPI)

git clone https://github.com/warith-harchaoui/os-helper.git
cd os-helper

pip install -e .

Quick start

Below are examples demonstrating how to use various features of the os_helper library. Make sure to import the library as osh before starting.

import os_helper as osh
  1. Set Verbosity and Check Operating System
# Attach a console handler first: verbosity() only sets the *level*, so
# without init_logging() the info() calls below are filtered out silently.
osh.init_logging()

# Set verbosity level to display debugging messages
osh.verbosity(3)

# Check if the system is Unix-based (Linux or macOS)
if osh.unix():
    osh.info("You are running on a Unix-based system.")
else:
    osh.info("You are not running on a Unix-based system.")
  1. Timestamp and File Existence Check
# Generate a formatted timestamp for logging
timestamp = osh.now_string("log")
osh.info(f"Current timestamp (log format): {timestamp}")

# Check if a file exists and is not empty
test_file = "example.txt"
if osh.file_exists(test_file, check_empty=True):
    osh.info(f"File {test_file} exists and is not empty.")
else:
    osh.error(f"File {test_file} does not exist or is empty.")
  1. Directory Creation and File Search
# Create a directory
test_dir = "test_directory"
osh.make_directory(test_dir)
osh.info(f"Directory {test_dir} created.")

# Perform recursive search for '.txt' files in the directory
matching_files = osh.recursive_glob(test_dir, "*.txt")
osh.info(f"Matching files: {matching_files}")
  1. Copy and Remove Files
# Copy a file from source to destination (the source has to exist first)
source_file = "source.txt"
with open(source_file, "w") as handle:
    handle.write("some content worth backing up")

destination_file = "backup_source.txt"
osh.copyfile(source_file, destination_file)
osh.info(f"File {source_file} copied to {destination_file}")

# Remove the copied file (each removal is logged at INFO level)
osh.remove_files([destination_file])
  1. Decompose a Path and Temporary File Creation
# Decompose a file path into folder, basename, and extension
folder, basename, ext = osh.folder_name_ext("/path/to/myfile.tar.gz")
osh.info(f"Folder: {folder}, Basename: {basename}, Extension: {ext}")

# Create and write to a temporary file
with osh.temporary_filename(suffix=".log") as temp_log:
    osh.info(f"Temporary file created at: {temp_log}")
    with open(temp_log, "w") as log_file:
        log_file.write("This is a temporary log entry.")
  1. Running System Commands
# Execute a system command and capture its output
cmd_output = osh.system("echo 'Hello, World!'")
osh.info(f"Command output: {cmd_output['out']}")
  1. Hashing Files and Strings
# Hash the contents of a file
file_to_hash = "testfile.txt"
if osh.file_exists(file_to_hash):
    file_hash = osh.hashfile(file_to_hash)
    osh.info(f"Hash of {file_to_hash}: {file_hash}")

# Hash a string with a specific length
hashed_string = osh.hash_string("MyTestString", size=8)
osh.info(f"Hashed string: {hashed_string}")
  1. ASCII String Conversion and Process ID
# Convert a string into a safe ASCII format
safe_string = osh.asciistring("Café-Con-Leche!", replacement_char="_")
osh.info(f"Safe ASCII string: {safe_string}")

# Get the current process ID
pid = osh.getpid()
osh.info(f"Current Process ID: {pid}")
  1. Check URL Validity and Zip Folder
# Check if a URL is valid and reachable
url = "https://www.example.com"
if osh.is_working_url(url):
    osh.info(f"The URL {url} is valid and reachable.")
else:
    osh.error(f"The URL {url} is not reachable.")

# Zip a folder (reusing the one created in step 3)
folder_to_zip = test_dir
zip_output = "test_directory_backup.zip"
osh.zip_folder(folder_to_zip, zip_output)
osh.info(f"Folder {folder_to_zip} zipped into {zip_output}")

Multi-surface exposure

os-helper is a library first. The same safe operations are also reachable over HTTP, as MCP tools, and through the Tree Radar GUI:

# Python library — the way every other suite member uses it
import os_helper as osh

There is no command line, on purpose: a shell wrapper around path exists or str ascii duplicated the shell's own vocabulary without adding anything, and the sixteen suite packages that import os_helper never called it.

HTTP API + MCP

The library's safe, side-effect-free operations (hardware info, hashing, ASCII normalization, size/time formatting, URL reachability, config loading; deliberately no filesystem-mutation endpoint) are also reachable over HTTP, and as MCP tools for any MCP-aware agent host:

pip install "os-helper[api]"
os-helper-api                    # -> http://127.0.0.1:8010 (docs at /docs)
curl http://127.0.0.1:8010/hardware
OS_HELPER_PORT=9000 os-helper-api  # or --host / --port; os-helper-api --help lists both

pip install "os-helper[mcp]"
os-helper-mcp                    # same app + an /mcp endpoint (fastapi-mcp)

Optional Tree Radar GUI

A first, real slice of the GUI.md plan ships as an optional surface: Tree Radar, a local disk-usage treemap dashboard. Each rectangle is a file or folder (area = size), colored by age, hash-dedupe status, or type family. It reads your disk and renders it in your browser; nothing is uploaded.

The GUI's web stack lives behind the [gui] extra so the core import os_helper stays lean (no FastAPI in the default install):

pip install "os-helper[gui]"

# Launch the local dashboard (loopback only), then open http://127.0.0.1:8017/gui
os-helper-gui --root ~/Downloads

The page speaks French and English. ?lang=fr / ?lang=en picks one, a flag in the header toggles between them, and a code no catalogue carries falls back to the default rather than failing. The English is the source, written in the markup itself; the French lives in os_helper/locales/fr/LC_MESSAGES/os_helper.po, a standard gettext catalogue read through os_helper.Catalog — the same loader the rest of the suite uses, so a translator works in the format every translation tool already speaks:

open http://127.0.0.1:8017/gui?lang=en

The remaining GUI milestones (Dedupe Lens actions, Config Explorer) stay described in GUI.md.

Use it as an agent skill

skills/os-helper/ packages os-helper as a Claude Skill and an OpenCode skill, so an agent can reach for it on your behalf. See skills/README.md to install it (symlink into ~/.claude/skills/ and ~/.opencode/skills/), and TRIGGERS.md for the exhaustive trigger catalogue — scripts/check_triggers.py keeps the skill's description in sync with it, and the test suite fails if a capability stops being named.

Author

Acknowledgements

Special thanks to Mohamed Chelali and Bachir Zerroug for fruitful discussions.

License

This project is licensed under the BSD-3-Clause License; see the LICENSE file for details.

The Tree Radar bundles D3 v7.9.0 (os_helper/static/d3.v7.min.js), © 2010-2023 Mike Bostock, under the ISC license reproduced in os_helper/static/d3.LICENSE.

Metadata

Release files for os-helper 4.1.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for os-helper 4.1.2
File Size Uploaded Provenance Actions
os_helper-4.1.2.tar.gz 265.5 kB Without provenance Details for os_helper-4.1.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for os-helper 4.1.2
File Interpreter ABI Platform Actions
os_helper-4.1.2-py3-none-any.whl Python 3 none any Details for os_helper-4.1.2-py3-none-any.whl

Total release size: 475.0 kB

Release files / os_helper-4.1.2.tar.gz

Download URL os_helper-4.1.2.tar.gz
Size 265.5 kB
Tags Source
SHA-256 checksum
How to use checksums
721adcf9a9b85d49ab60408fc18dc9d0449dac3bc2de541fe4d08459e7ec031d
BLAKE2b-256 checksum
How to use checksums
b3b92435d49fee31ffc9108523cc01e766e53c314453385396f2800f3302c7a2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.13

Release files / os_helper-4.1.2-py3-none-any.whl

Download URL os_helper-4.1.2-py3-none-any.whl
Size 209.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ab3c109532c34a3850fb5658937347c902f31f0fa49d30a2fa7742cab3c7064e
BLAKE2b-256 checksum
How to use checksums
b0170567aa942522cefee8e6e770f5b3c07b6aceaeb5ada722107772721170f4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.13

Security for os-helper 4.1.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

4.1.2 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page