Metadata-Version: 2.4
Name: pythontk
Version: 0.27.3
Summary: Python toolkit for DCC pipelines: files, math, geometry, images, video and audio, plus PBR texture, glTF/USD export and shot-timeline engines.
Author-email: Ryan Simpson <m3trik@outlook.com>
License-Expression: MIT
Project-URL: Homepage, https://github.com/m3trik/pythontk
Project-URL: Repository, https://github.com/m3trik/pythontk
Project-URL: Changelog, https://github.com/m3trik/pythontk/blob/main/CHANGELOG.md
Project-URL: Issues, https://github.com/m3trik/pythontk/issues
Keywords: m3trik,python-library,dcc,technical-art,pbr,gltf,usd,lightmap
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: POSIX :: Linux
Classifier: Intended Audience :: Developers
Classifier: Topic :: Multimedia :: Graphics
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.24
Requires-Dist: Pillow>=9.1
Provides-Extra: mesh
Requires-Dist: pymeshlab>=2023.12; extra == "mesh"
Provides-Extra: cad
Requires-Dist: cadquery-ocp-novtk<9,>=8.0.1; python_version >= "3.11" and extra == "cad"
Provides-Extra: mcp
Requires-Dist: mcp<3,>=2.3; python_version >= "3.10" and extra == "mcp"
Dynamic: license-file

[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
[![PyPI](https://img.shields.io/pypi/v/pythontk.svg)](https://pypi.org/project/pythontk/)
[![Python](https://img.shields.io/badge/Python-3.9+-blue.svg)](https://www.python.org/)
[![Tests](https://img.shields.io/badge/Tests-9673%20passed-brightgreen.svg)](../tests/)
![Platform](https://img.shields.io/badge/Platform-Windows%2C%20Linux-lightgrey.svg)

# pythontk

<!-- short_description_start -->
*The host-free core of a game-art tooling ecosystem: the engines Maya and Blender share (PBR texture maps, shot timelines, scene export, a live WebXR preview) over composable primitives for files, geometry, images, video and audio.*
<!-- short_description_end -->

Pure Python: no Qt, no DCC imports, two hard dependencies (`numpy`, `Pillow`). Everything heavier (FFmpeg, OpenCV, rembg, PyMeshLab) is optional and gates only its own feature, so the core runs the same in `mayapy`, Blender's Python, a CI runner or a bare venv.

## Where it sits

pythontk is the bottom of the chain `pythontk → uitk → mayatk / blendertk → tentacle` (also `pythontk → unitytk` and `uitk → extapps`): everything above imports it, and it imports nothing above it. Whatever a tool does that needs no host is written here once, so Maya and Blender run the same shot timeline, texture conversion and export checks, and that code is tested with no DCC installed.

<!-- diagram:ecosystem/pythontk -->
<!-- Generated by m3trik/scripts/generate_readme_diagrams.py from the workspace's declarations: change those and re-run it, never this block. -->
<p align="center">
<a href="https://github.com/m3trik/m3trik#readme"><picture><source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/m3trik/m3trik/main/docs/diagrams/ecosystem-pythontk-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/m3trik/m3trik/main/docs/diagrams/ecosystem-pythontk-light.svg"><img alt="pythontk (highlighted) in the ecosystem: uitk requires pythontk; unitytk requires pythontk; mayatk requires uitk; blendertk requires uitk; tentacle requires uitk; extapps requires uitk; tentacle installs mayatk as its [maya] extra; tentacle installs blendertk as its [blender] extra; tentacle opens extapps by name (its [apps] extra) and never imports it; mayatk and blendertk share a mirrored API. tentacle and extapps are products, which nothing imports." src="https://raw.githubusercontent.com/m3trik/m3trik/main/docs/diagrams/ecosystem-pythontk-light.svg" width="781"></picture></a>
</p>
<!-- /diagram:ecosystem/pythontk -->

Two kinds of code live here. The `*_utils` packages are general primitives, placed by the data they work on, so the sharpest-frame extractor is in `vid_utils` and usable with no photogrammetry in sight. `core_utils/engines/` holds the models both hosts drive: texture maps, shots, scene export, rig intent, lighting, instancing.

## Install

```bash
pip install pythontk
```

Both dependencies are declared without a ceiling, so installing into a host's own interpreter (`mayapy -m pip install pythontk`) leaves the `numpy` the host already has untouched. Every public name is reached from the package root and loaded on first use.

<details>
<summary><b>Optional dependencies</b>, each gating one feature</summary>

- `FFmpeg` (on PATH): audio conversion and compositing, video compression
- `OpenCV`: video frame extraction, image curation, exposure equalization
- `rembg`: background masks (`MaskGenerator`)
- `PyMeshLab`: mesh measure, repair, remesh, decimate, bake and deviation (`MeshOps`; the `pythontk[mesh]` extra)
- `OpenCascade`: STEP / IGES to per-part meshes and an assembled GLB (`CadImport`; the `pythontk[cad]` extra)
- `xatlas`: UV island packing (`UvPack`)
- `toktx` (KTX-Software): KTX2 / Basis Universal encoding (`Ktx2Encoder`)
- `paramiko`: SSH client · `keyring`: credential storage

Installing into a `--target` directory plans a full standalone closure and would replace a host's `numpy`: use `ptk.PackageManager.install_targeted`, which plans against the host interpreter instead.

</details>

## The design, and what it buys

- **A host is an adapter, with a pure-Python default.** A shared engine reaches Maya or Blender through a small protocol whose default needs no host at all. The shot timeline, the exporter's run and the texture engine are therefore written once and tested with no DCC installed, and a host library only binds them.
- **A contract is declared once and generated everywhere.** The records a delivered file carries are declared here. Unity's C# and the WebXR viewer's JavaScript read them through types generated from that declaration, and CI fails when one drifts.
- **A port is held to its reference.** A model that also runs in C# or JavaScript must reproduce cases its Python reference generates at test time (`Conformance`), so no port is measured against a stale copy.
- **An operation plans before it changes anything.** Every named action has a dry run that returns its plan. Over MCP the plans and the changes are two servers, so a client can allow every plan and still be asked before each change.
- **The API is read, never listed.** `ApiSurface` reads every package's public API from its source, importing nothing. One reader answers `api.search`, measures each release's API change and serves `.help()` on a class, so there is no committed API file to go stale.
- **A retirement or a patch carries its own expiry.** A moved name's error says where it went, and a deprecation holds a version and a date that CI enforces (`Deprecation`). A patch to code we do not own carries a probe that reproduces the bug, so the upstream fix fails a test that names the patch to delete (`UpstreamPatch`).
- **Examples that cannot rot.** `DocAudit` checks every attribute chain and keyword argument in a markdown file's code blocks against the live package. This README's examples, and the outputs it shows, are held by it in the test suite.

## What it does

### Texture maps: identify, convert, pack

`MapFactory` reads a folder of texture files as map sets. It names each file's map type from its filename (50 types under hundreds of spellings, with DirectX and OpenGL normals told apart), converts between workflows, and packs channels for an engine.

```python
import pythontk as ptk

# Identify map types from filenames
ptk.MapFactory.resolve_map_type("character_Normal_DirectX.png")  # "Normal_DirectX"
ptk.MapFactory.resolve_map_type("material_BC.tga")               # "Base_Color"
ptk.MapFactory.resolve_map_type("car_Coat_Roughness.png")        # "Clearcoat_Roughness"
# A batch is read as one set, so a set NAMED for a lobe word keeps its base maps
ptk.MapFactory.resolve_map_types(["Hero_Coat_BaseColor.png", "Hero_Coat_Roughness.png"])
# {"Hero_Coat_BaseColor.png": "Base_Color", "Hero_Coat_Roughness.png": "Roughness"}

# Spec/Gloss → Metal/Rough
base_color, metallic, roughness = ptk.MapFactory.convert_spec_gloss_to_pbr(
    specular_map="specular.png", glossiness_map="gloss.png", diffuse_map="diffuse.png",
)

# Bump/height → normal map
ptk.MapFactory.convert_bump_to_normal("height.png", output_format="opengl", intensity=1.5)

# Pack grayscale maps into the channels of one image
ptk.ImgUtils.pack_channels(
    channel_files={"R": "ao.png", "G": "roughness.png", "B": "metallic.png"},
    output_path="packed_ORM.png",
)
```

Map types, workflow handlers and conversions are registered, so a new one is added without editing the engine ([worked example](../examples/texture_factory_extensibility_example.py)). The panels over these engines (Map Converter, Map Packer, Map Compositor) are [extapps](https://github.com/m3trik/extapps)'.

### Capture ingest: the sharpest frames, without the duplicates

Frames for photogrammetry from a video. Taking every Nth frame keeps blurred frames and repeats the view wherever the camera stood still. `FrameExtractor` takes the sharpest frame from each window of footage instead, and `ImageCurator` then drops near-duplicates and the blurriest of what is left:

```python
frames = ptk.FrameExtractor().extract_frames_sharpest(
    "capture.mp4", "frames/", window_sec=1.0,   # sharpest frame per second of footage
)

curated_dirs = ptk.ImageCurator().curate(
    ["frames/"], "curated/",
    hash_threshold=5,                 # Hamming distance on dHash: near-duplicates cluster
    sharpness_floor_percentile=10,    # drop the blurriest tenth of the survivors
)
```

`ExposureEqualizer` matches exposure and white balance across image sets, and `MaskGenerator` cuts background masks (it needs `rembg`).

### A scene in a headset, live

The [live WebXR preview](webxr_preview.md) is the pipeline behind the preview buttons in Maya and Blender. It converts an export to glTF and serves it from a loopback server with a bundled three.js viewer. A tab left open in a browser or a PC-tethered headset picks up each new push without a reload, and baked lightmaps arrive with it, though glTF has no slot for them.

### Engines both hosts share

- **Shots and build sheets.** A procedure written as a sheet (a CSV file or a Google Sheet) is read into shots, with the keys its text asks for planned. Other readers take the same sheet for their own work, so the format is declared once: [Build sheets](build_sheets.md).
- **Scene export.** The run of fixes and checks both hosts' Scene Exporters share, and [the format](../pythontk/core_utils/engines/scene_export/DELIVERABLE_FORMAT.md) of the records a delivered file carries.
- **Look match.** Light a baked scene to match a reference image. Each light is baked once as a layer, and light adds, so any mix of them is a weighted sum: predicted in milliseconds and compared with the reference region by region. [Look match](look_match.md).
- **Narration.** Lines of text spoken into WAV files by an open-source engine on this machine, so a scene's narration is heard before anyone records it and the text goes nowhere: [Narration](narration.md).
- **Mesh and CAD files.** FBX to GLB with glTF repair (`MeshConvert`), STEP / IGES to per-part meshes and an assembled GLB (`CadImport`), and USDZ written with no USD library (`UsdzPackager`).

### One API for scripts and agents

Every public function of every installed package is found by a search that reads the source and imports nothing:

```bash
python -m pythontk ops run api.search query="triangle count"
```

`python -m pythontk ops mcp` serves the search, a console in each host and the operations to an agent over MCP. A call a host application runs goes to an instance started for it, never to one a person has open: [setup and use](https://github.com/m3trik/m3trik/blob/main/docs/AGENT_INSTRUCTIONS.md).

### One filtering language

The same include / exclude wildcards filter lists, dicts, directory walks and image sets, so a filter learned once is the filter everywhere:

```python
ptk.filter_list(
    ["mesh_main", "mesh_backup", "mesh_LOD0", "cube_old"],
    inc=["mesh_*", "cube_*"],
    exc=["*_backup", "*_old"],
)
# ['mesh_main', 'mesh_LOD0']
```

Every package above also builds on what is here for app hand-off (`HandoffBridge`: send, save-as and round trip from one export pipeline), cooperative cancellation (`CancelScope`), plugin-hosted JSON-RPC whose two ends ship together (`RpcClient`, `RpcPlugin`), presets (`PresetStore`) and agent instructions kept as a checked tree (`AgentInstructions`).

<details>
<summary><b>Package map</b>: where each thing lives</summary>

| Package | What it covers |
|---|---|
| `audio_utils` | FFmpeg-backed conversion, composite WAV building, silence trimming, waveform envelopes |
| [`core_utils`](../pythontk/core_utils/README.md) | The infrastructure layer: mixins (`LoggingMixin`, `HelpMixin`, `SingletonMixin`), the one public-API reader (`ApiSurface`), operations and their command-line and MCP front ends (`operation_catalog`), `PythonConsole`, `listify`, package bootstrap, hot-reload, app orchestration (`AppLauncher`, `HandoffBridge`), cooperative cancellation (`CancelScope`), task pipeline, process output streaming, config/template stores, QC gates, `ExecutionMonitor`, hierarchy diffing, color primitives — plus the shared domain engines (`shots`, `scene_export`, `instancing`, `textures`, `rig_graph`, `key_stash`, `lighting`) |
| [`file_utils`](../pythontk/file_utils/README.md) | Filtered directory traversal, atomic writes, policy-scoped temp artifacts (`TempArtifacts`), cloud-placeholder detection, FBX→GLB conversion + glTF repair (`MeshConvert`), zero-dependency USD/USDZ authoring, UV unwrapping, project workspaces, embedded metadata |
| `geo_utils` | Pure geometry — `Polyline` (order/resample/smooth/simplify, arc-length sampling), `PointCloud` (PCA, clustering), `RailSurface` (line-pair framing), `PlateEmitter`, and the UV-layout family in `geo_utils/uv/` (`UvPack` island packing, `UvBudget` map-count planning, `UvCombine` several texture sets' islands packed into one atlas, `UvTransfer` texel remap, `TransferRun` the UV-or-texture transfer run both hosts share, `CylinderSeams` tube / turned-part seam placement) |
| `img_utils` | Pillow-backed image ops, channel packing, atlas layout/assembly, KTX2 encoding (`Ktx2Encoder`), exposure equalization, image curation, mask generation |
| `iter_utils` | Flatten, dedupe, wildcard filtering of lists/dicts, integer-sequence collapse |
| `math_utils` | Vectors, clustering, remap/lerp/clamp, rotation math in one convention (`Quaternion`: quaternions, matrices, Euler, `euler_near` for keyed rotation), easing curves (`ProgressionCurves`), band-limited noise, morph-weight math (`Weights`), safe expression evaluation |
| [`net_utils`](../pythontk/net_utils/README.md) | SSH client, both ends of the plugin-hosted JSON-RPC protocol + DCC plugin installer, credentials, port/RDP helpers, URL file reads (`RemoteFile`, Google Sheets share links), [live WebXR preview server](webxr_preview.md) |
| `str_utils` | Sanitizing, batch rename, affix handling, `FuzzyMatcher`, hotkey-token parsing |
| `vid_utils` | Frame rate probing, compression, sharpest-frame extraction |

The three linked packages carry their own READMEs. The whole public surface, read from the installed source: `python -m pythontk ops run api.search "query=<words>"`, or `python -m pythontk --index`.

</details>

---

## Guides

| Guide | What it covers |
|---|---|
| [Live WebXR preview](webxr_preview.md) | The DCC to glTF to headset pipeline: how a lightmap rides a format with no slot for one, what the scene's records repair, the size and memory budget |
| [Look match](look_match.md) | The light layers and their mix, the prediction held to the real viewer, region scores, fits and solves, the rig a mix is saved as |
| [Build sheets](build_sheets.md) | The procedure sheet every reader takes the same way: templates, columns, step IDs, names, takes, guidance phrases |
| [Narration](narration.md) | Text spoken into WAV files on this machine: a file per line, a pronunciation list, a record per line |

## Links

- **Full API:** `python -m pythontk ops run api.search "query=<words>"` (the installed source, searched)
- **Changelog:** [`CHANGELOG.md`](../CHANGELOG.md)
- **Contributor / AI-agent guide:** [`AGENTS.md`](../AGENTS.md)
- **PyPI:** https://pypi.org/project/pythontk/
- **Issues:** https://github.com/m3trik/pythontk/issues

## License

MIT — see [LICENSE](../LICENSE).
