Skip to main content

Interactive Video Backend Core

Interactive Video Labs Logo

PyPI Version License PyPI Downloads

interactive-video-backend-core is a framework-agnostic Python library for storing and resuming interactive video sessions. It provides Pydantic data models, decision transition validation, state reconstruction, and an async SQLAlchemy session repository for use with frameworks and databases such as FastAPI and PostgreSQL or SQLite.

The package is designed to complement @interactive-video-labs/core, the framework-agnostic TypeScript player used by interactive video applications.


Features

  • Decision ledger: Persist each user choice with session, video, node, choice, playback timestamp, and optional metadata.
  • Session resume: Reconstruct the latest node and playback timestamp for a user session.
  • Transition validation: Verify that a submitted choice belongs to the choices allowed for the current node.
  • Pydantic models: Use typed, validated submission and resume response models.
  • Async SQLAlchemy storage: Work with async database sessions and SQLAlchemy 2.x.
  • Framework agnostic: Integrate the core with FastAPI, Django, Litestar, or another Python backend.
  • Chronological state recovery: Rebuild state even when decision records arrive out of order.

Requirements

  • Python 3.10 or newer
  • Pydantic 2.x
  • SQLAlchemy 2.x

Installation

Poetry

poetry add interactive-video-backend-core

pip

pip install interactive-video-backend-core

Quick Start

1. Create the database tables

from sqlalchemy.ext.asyncio import (
    AsyncEngine,
    create_async_engine,
)

from interactive_video_backend_core.orm_models import Base


engine: AsyncEngine = create_async_engine(
    "sqlite+aiosqlite:///./interactive_video.db"
)

async def initialize_database():
    async with engine.begin() as connection:
        await connection.run_sync(Base.metadata.create_all)

2. Save a decision

from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker

from interactive_video_backend_core.models import DecisionSubmission
from interactive_video_backend_core.storage_sqlalchemy import (
    SQLAlchemySessionRepository,
)

session_factory = async_sessionmaker(engine, class_=AsyncSession)


async def save_decision():
    decision = DecisionSubmission(
        user_id="user-123",
        session_id="session-456",
        video_id="video-789",
        node_id="question-1",
        choice_id="answer-b",
        timestamp=12.5,
        metadata={"source": "web"},
    )

    async with session_factory() as session:
        repository = SQLAlchemySessionRepository(session)
        await repository.save_decision(decision)

3. Restore session state

async def resume_session():
    async with session_factory() as session:
        repository = SQLAlchemySessionRepository(session)
        state = await repository.get_session_state(
            user_id="user-123",
            session_id="session-456",
        )

    if state is not None:
        print(state.last_node_id)
        print(state.last_timestamp)
        print(state.decision_history)

The repository returns None when no decision exists for the supplied user and session.


Decision Transition Validation

Use DecisionLedgerEngine.validate_transition() when a node defines the choices that may be selected:

from interactive_video_backend_core.logic import DecisionLedgerEngine

DecisionLedgerEngine.validate_transition(
    current_node="question-1",
    choice_id="answer-b",
    allowed_choices=["answer-a", "answer-b"],
)

An invalid choice raises ValueError:

Invalid choice 'answer-c' for node 'question-1'.

State Reconstruction

DecisionLedgerEngine.reconstruct_state() returns the last node and playback timestamp according to chronological playback time:

from interactive_video_backend_core.logic import DecisionLedgerEngine

node_id, timestamp = DecisionLedgerEngine.reconstruct_state(decisions)

If the decision list is empty, the engine returns ("start", 0.0).


Storage Interface

AbstractSessionRepository defines the framework-independent persistence contract:

from interactive_video_backend_core.models import (
    DecisionSubmission,
    SessionResumeResponse,
)
from interactive_video_backend_core.storage import AbstractSessionRepository


class MySessionRepository(AbstractSessionRepository):
    async def save_decision(
        self,
        decision: DecisionSubmission,
    ) -> None:
        ...

    async def get_session_state(
        self,
        user_id: str,
        session_id: str,
    ) -> SessionResumeResponse | None:
        ...

Implement this interface when your application needs a different database, API-backed store, or custom persistence behavior.


Data Models

DecisionSubmission

Field Type Description
user_id str Identifier of the viewer
session_id str Identifier of the viewing session
video_id str Identifier of the interactive video
node_id str Node or checkpoint reached by the viewer
choice_id str Selected branch or answer
timestamp float Playback timestamp in seconds
metadata dict[str, Any] | None Optional application-specific metadata

SessionResumeResponse

Field Type Description
user_id str Identifier of the viewer
session_id str Identifier of the viewing session
video_id str Identifier of the most recently recorded video
last_node_id str Latest reconstructed node
last_timestamp float Latest reconstructed playback timestamp
decision_history list[DecisionSubmission] Decisions ordered by playback timestamp
updated_at datetime Timestamp of the latest database record

SQLAlchemy Schema

The included ORM model stores decisions in the ivl_decision_ledger table:

  • id
  • user_id
  • session_id
  • video_id
  • node_id
  • choice_id
  • timestamp
  • metadata_json
  • created_at

Indexes are created for user_id and session_id to support session state lookup.


Development

Clone the repository and install the development dependencies:

git clone https://github.com/interactive-video-labs/interactive-video-backend-core.git
cd interactive-video-backend-core
poetry install

Run the test suite:

poetry run pytest

For linting and project conventions, see DEVELOPER.md and CONTRIBUTING.md.


Project Structure

interactive-video-backend-core/
├── interactive_video_backend_core/
│   ├── __init__.py
│   ├── logic.py
│   ├── models.py
│   ├── orm_models.py
│   ├── storage.py
│   └── storage_sqlalchemy.py
├── tests/
│   ├── conftest.py
│   ├── test_logic.py
│   └── test_storage.py
├── pyproject.toml
└── README.md

Contributing

Contributions are welcome. Please review CONTRIBUTING.md before submitting an issue or pull request.


License

This project is licensed under the MIT License.

Metadata

Release files for interactive-video-labs-core 0.2.0

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

Source distribution (sdist)

Source distribution for interactive-video-labs-core 0.2.0
File Size Uploaded Provenance Actions
interactive_video_labs_core-0.2.0.tar.gz 5.9 kB With provenance Details for interactive_video_labs_core-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for interactive-video-labs-core 0.2.0
File Interpreter ABI Platform Actions
interactive_video_labs_core-0.2.0-py3-none-any.whl Python 3 none any Details for interactive_video_labs_core-0.2.0-py3-none-any.whl

Total release size: 14.2 kB

Release files / interactive_video_labs_core-0.2.0.tar.gz

Download URL interactive_video_labs_core-0.2.0.tar.gz
Size 5.9 kB
Tags Source
SHA-256 checksum
How to use checksums
c41b719996a7812fa57e57069e3ada5c18c2a9e57a91d4515b101a0797220fed
BLAKE2b-256 checksum
How to use checksums
71a67cdcf4d2237958820284e0b1a4fc7c00e0a8b0b4ddcad58ca2d284477691
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 21, 2026.

Transparency log

Release files / interactive_video_labs_core-0.2.0-py3-none-any.whl

Download URL interactive_video_labs_core-0.2.0-py3-none-any.whl
Size 8.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
92d7d9626a219a29f86fc7bbe5783766a4bbb190c0210992c5b3408aa6fa7731
BLAKE2b-256 checksum
How to use checksums
dc74126078138f49fe5b21de9db940738d82c664a2a6a8244e1ef5cdc25b3296
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 21, 2026.

Transparency log

Security for interactive-video-labs-core 0.2.0

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.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for interactive_video_labs_core-0.2.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 21, 2026.

Transparency log

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

0.2.0 This release

2 release files Full 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