Metadata-Version: 2.4
Name: krpano-xml
Version: 0.1.0
Summary: Type-safe object model for constructing, composing and serializing krpano 1.24 virtual-tour XML
Project-URL: Repository, https://github.com/bnkselfin/krpano-xml-py
Project-URL: Reference, https://github.com/bnkselfin/krpano-xml
Project-URL: Documentation, https://krpano.com/docu/xml/
Author: Claude (Anthropic)
License: MIT
License-File: LICENSE
Keywords: 360,krpano,panorama,virtual-tour,xml
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Multimedia :: Graphics
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Text Processing :: Markup :: XML
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown

# krpano-xml

Type-safe object model for constructing, composing and serializing
[krpano 1.24](https://krpano.com/docu/xml/) virtual-tour XML — a Python port
of the TypeScript `krpano-xml` reference implementation with a
**byte-identical serialization contract** (see [Parity](#parity)).

> **Built by Claude.** This library — architecture, implementation, test suite, tooling, docs, and examples — was built end-to-end by [Claude](https://www.anthropic.com/claude) (Anthropic's AI coding agent) in collaboration with [@bnkselfin](https://github.com/bnkselfin), as a port of the [TypeScript reference](https://github.com/bnkselfin/krpano-xml). The commit history documents the full build: a serialization contract proven byte-identical against the reference goldens, `mypy --strict` typing, and CI that smoke-tests the built wheel.

- Python ≥ 3.11, **zero runtime dependencies** (stdlib only).
- Fully type-annotated, `mypy --strict` clean, ships `py.typed`.
- Every krpano 1.24 appendix-schema attribute has a typed accessor with the
  krpano docs anchor and default in its docstring.

## Install

Not yet published to PyPI — install straight from GitHub:

```bash
pip install "git+https://github.com/bnkselfin/krpano-xml-py"
```

Or from a local clone (add `-e` for development):

```bash
git clone https://github.com/bnkselfin/krpano-xml-py
pip install ./krpano-xml-py
```

## Quickstart — a vtour in the droplet convention

```python
from krpano_xml import NavHotspot, VtourDocument, VtourView

tour = VtourDocument(title="Demo Tour")

tour.add_pano_scene(
    basename="living_room",
    title="Living Room",
    tile_size=512,
    level_sizes=[640, 1280, 2560],
    view=VtourView(hlookat=15, vlookat=-3, fov=110),
    hotspots=[NavHotspot(name="to_kitchen", ath=42, atv=4, target="scene_kitchen")],
)

print(tour.to_xml())          # pretty, tabs, XML declaration
print(tour.to_xml(pretty=False))  # minified
```

This emits the full MAKE-VTOUR-droplet structure: `skin/vtourskin.xml`
include, `<skin_settings>`, the droplet `startup` action, and a multires CUBE
scene wired to the conventional `panos/<basename>.tiles/` layout.

## The design

The classic-OOP reference maps onto Python like this:

- **Inheritance stays inheritance.** `KrpanoElement` is the base of every
  element: the ordered attribute store, children, optional text/CDATA body
  and the serialization entry point. `RenderableElement` carries everything
  layers and hotspots share; `ScreenElement` (→ `Layer`) adds screen-space
  positioning; `SphericalElement` (→ `Hotspot`) adds pano-space placement.
- **Attribute values are a tagged union** (`krpano_xml.values`): frozen
  dataclasses `Bool` / `Number` / `Int` / `Str` / `Color` / `Multi` /
  `Sentinel` / `Dynamic` / `Raw`, each owning its formatting rule — the
  escaper never sniffs strings. Plain Python values (`bool`, `int`, `float`,
  `str`, sequences) are coerced at the API boundary; you rarely construct
  variants by hand.
- **Typed accessors are generated, not hand-written.**
  `tools/gen_elements.py` reads the vendored reference schema
  (`tests/reference/schema.json`) and generates `_schema.py` (attribute
  tables), `enums.py` (`StrEnum`s) and `_accessors.py` — base classes with
  one real, typed `property` pair per attribute plus `TypedDict`-typed
  keyword-argument constructors. Real code, so mypy and IDEs see every
  accessor directly; `--check` mode guards drift in CI.
- **Keyword-argument constructors are the primary API**
  (`Scene("scene_1", title="Lobby")`, `Hotspot("h", ath=10, url="spot.png")`)
  — the reference's fluent chaining is replaced by Python idiom; a few
  chaining helpers remain where they read well (`hotspot.at(...)`,
  `view.look_at(...)`, `action.line(...)`). Emitted bytes are identical
  either way.
- **Enums are real `enum.StrEnum`s** (`BlendMode.SCREEN == "screen"`), with
  loose string passthrough always accepted.

## Escape hatch & custom attributes

Nothing is ever rejected — krpano plugins and the vtour skin define arbitrary
attributes:

```python
layer.set_attr("myplugin_speed", 3)                     # any attribute, coerced + escaped
layer.set_raw_attr("pre", "&#42;")                      # verbatim — caller owns validity
layer.set_attr_for("scale", 0.5, "mobile")              # device variant: scale.mobile="0.5"
layer.set_attr_for("url", "s.jpg", DeviceQuery.device("mobile").and_("webgl"))
layer.set_devices(DeviceQuery.not_("mobilevr"))         # whole-element devices="no-mobilevr"
hotspot.set_attr("ath", Get("spot_ath"))                # dynamic get:/calc:/link: values
```

## Serialization contract

These behaviors are deliberate, pinned by the vendored reference vectors and
goldens, and stable:

- **Total escaping (raw-in/escaped-out).** `set_attr` values are always raw
  text; every `&` `<` `>` `"` is escaped, including entity-looking input.
  `layer.set_attr("t", "&amp;")` → `t="&amp;amp;"` → reads back `&amp;`.
- **`set_raw_attr` emits verbatim — caller owns validity.**
- **Whitespace in attributes survives via character references.** Raw
  `\n`/`\t`/`\r` emit as `&#10;`/`&#9;`/`&#13;`.
- **XML-illegal control characters (`\x00`–`\x08`, `\x0B`, `\x0C`,
  `\x0E`–`\x1F`) are stripped on emission.**
- **Numbers always render in fixed notation** with shortest round-trip
  digits (`1e-7` → `0.0000001`, `1.23e21` → `1230000000000000000000`,
  `-0` → `0`); `NaN`/infinities map to krpano sentinels.
- **Colors normalize to uppercase `0xRRGGBB`/`0xAARRGGBB`** from `#f80`,
  `#ff8800`, `0x...` strings or integers.
- **Plain text bodies are line-based action code**: trimmed + re-indented
  when pretty, single-space-joined when minified. **Byte-exact bodies require
  CDATA** (`type="Javascript"` actions always use it).
- **`]]>` inside CDATA is split** across sections (`]]]]><![CDATA[>`) and
  re-joins on parse.
- **Duplicate names are emitted, and flagged** (`DUPLICATE_NAME`, per krpano
  array; scenes are independent scopes; `<plugin>` counts as `layer`).
- **`name="auto"` passes through verbatim**; for stable referenceable names
  use `doc.names.next("hotspot")` or `doc.assign_auto_names()`.
- **Deterministic output.** Same model → same bytes; `name`, `type`, `url`
  lead the attribute order, then insertion order, with device variants
  grouped after their base attribute.

## Vtour guide

`VtourDocument` mirrors the MAKE VTOUR droplet:

```python
tour = VtourDocument(
    title="Loft Tour",
    design_urls=["skin/vtourskin_design_flat_light.xml"],
    skin_settings={"thumbs": True, "gyro": True, "deeplinking": True},
)
tour.add_pano_scene(
    basename="lobby", lat=40.4093, lng=49.8671, heading=12,
    tile_size=512, level_sizes=[640, 1280, 2560],
    hotspots=[NavHotspot(name="to_hall", ath=40, atv=3, target="scene_hall")],
)
```

Conventions: scene names are `scene_<basename>`; previews/thumbs/tiles follow
`panos/<basename>.tiles/…` (all templates configurable); nav hotspots use the
skin's `skin_hotspotstyle` + `linkedscene`. Long-form multires via
`levels=[MultiresLevelSpec(...)]`.

## Parsing / round-trip

```python
doc = KrpanoDocument.parse(xml_text)   # expat-based, stdlib only
doc.get_scene("scene_alpha").ensure_view().fov = 95
xml = doc.to_xml()
```

Known elements map to their classes; unknown elements/attributes are
preserved losslessly (`GenericElement` + verbatim attributes). Entities and
numeric character references decode into plain strings; CDATA is preserved
(including `]]>`-split re-joining); pretty-print indentation is never
absorbed into bodies. Library-generated files round-trip **byte-identically**.

## Validation

```python
issues = doc.validate()                       # list[ValidationIssue] — warnings only
result = doc.serialize(validate=True)         # SerializeResult(xml=..., warnings=[...])
```

Checks: unknown attributes on known elements, enum values out of range,
colors not in `0x` form, boolean-shape strings, missing required attributes,
hotspots with no visual content (or degenerate polygons, or `rx/ry/rz`
without `distorted`), images with no source, and `DUPLICATE_NAME` collisions.
Dynamic values and parameterized forms (`blend(...)`) are exempt. Never
fatal, never blocks serialization.

## Fragments

Any element serializes standalone: `scene.to_xml()` emits a partial XML
fragment (no declaration) for composition into larger files.

## Examples

Ten runnable scripts in [`examples/`](examples/), each asserting
well-formedness with a stdlib expat parse and printing a byte count. Run any
of them directly: `python examples/01_quickstart.py`.

## Parity

The serialization contract, schema registry, goldens and test vectors are
defined by the TypeScript reference implementation at tag **v1.0.1**
(`e0431364aa102181743d8f78cdb89913d8c759d3`, recorded in
`tests/reference/REFERENCE_COMMIT`). The Python port serializes
**byte-identically** against the reference goldens; the deliberate,
documented divergences (full `action.scope` enum, depthmap/model/splats
placeholder status, Python-idiom API shape) live in [PARITY.md](PARITY.md).
