interactive-video-backend-core 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Interactive video labs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,313 @@
1
+ Metadata-Version: 2.4
2
+ Name: interactive-video-backend-core
3
+ Version: 0.1.0
4
+ Summary: Framework-agnostic Python backend core and storage adapters for syncing interactive video state and decision ledgers
5
+ License: MIT
6
+ License-File: LICENSE
7
+ Author: Taj
8
+ Author-email: tajulislamj200@gmail.com
9
+ Requires-Python: >=3.10,<4.0
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Programming Language :: Python :: 3.14
17
+ Classifier: Programming Language :: Python :: 3.15
18
+ Requires-Dist: pydantic (>=2.0)
19
+ Requires-Dist: sqlalchemy (>=2.0)
20
+ Project-URL: Homepage, https://github.com/interactive-video-labs
21
+ Project-URL: Repository, https://github.com/interactive-video-labs/interactive-video-backend-core
22
+ Description-Content-Type: text/markdown
23
+
24
+ # Interactive Video Backend Core
25
+
26
+ <p align="center">
27
+ <img src="https://raw.githubusercontent.com/interactive-video-labs/docs/main/logo.svg" width="200" alt="Interactive Video Labs Logo" />
28
+ </p>
29
+
30
+ <p align="center">
31
+ <img src="https://img.shields.io/pypi/v/interactive-video-backend-core" alt="PyPI Version" />
32
+ <img src="https://img.shields.io/pypi/l/interactive-video-backend-core" alt="License" />
33
+ <img src="https://img.shields.io/pypi/dm/interactive-video-backend-core" alt="PyPI Downloads" />
34
+ </p>
35
+
36
+ `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.
37
+
38
+ The package is designed to complement [`@interactive-video-labs/core`](https://github.com/interactive-video-labs/interactive-video-core), the framework-agnostic TypeScript player used by interactive video applications.
39
+
40
+ ---
41
+
42
+ ## Features
43
+
44
+ - **Decision ledger:** Persist each user choice with session, video, node, choice, playback timestamp, and optional metadata.
45
+ - **Session resume:** Reconstruct the latest node and playback timestamp for a user session.
46
+ - **Transition validation:** Verify that a submitted choice belongs to the choices allowed for the current node.
47
+ - **Pydantic models:** Use typed, validated submission and resume response models.
48
+ - **Async SQLAlchemy storage:** Work with async database sessions and SQLAlchemy 2.x.
49
+ - **Framework agnostic:** Integrate the core with FastAPI, Django, Litestar, or another Python backend.
50
+ - **Chronological state recovery:** Rebuild state even when decision records arrive out of order.
51
+
52
+ ---
53
+
54
+ ## Requirements
55
+
56
+ - Python 3.10 or newer
57
+ - Pydantic 2.x
58
+ - SQLAlchemy 2.x
59
+
60
+ ---
61
+
62
+ ## Installation
63
+
64
+ ### Poetry
65
+
66
+ ```bash
67
+ poetry add interactive-video-backend-core
68
+ ```
69
+
70
+ ### pip
71
+
72
+ ```bash
73
+ pip install interactive-video-backend-core
74
+ ```
75
+
76
+ ---
77
+
78
+ ## Quick Start
79
+
80
+ ### 1. Create the database tables
81
+
82
+ ```python
83
+ from sqlalchemy.ext.asyncio import (
84
+ AsyncEngine,
85
+ create_async_engine,
86
+ )
87
+
88
+ from interactive_video_backend_core.orm_models import Base
89
+
90
+
91
+ engine: AsyncEngine = create_async_engine(
92
+ "sqlite+aiosqlite:///./interactive_video.db"
93
+ )
94
+
95
+ async def initialize_database():
96
+ async with engine.begin() as connection:
97
+ await connection.run_sync(Base.metadata.create_all)
98
+ ```
99
+
100
+ ### 2. Save a decision
101
+
102
+ ```python
103
+ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
104
+
105
+ from interactive_video_backend_core.models import DecisionSubmission
106
+ from interactive_video_backend_core.storage_sqlalchemy import (
107
+ SQLAlchemySessionRepository,
108
+ )
109
+
110
+ session_factory = async_sessionmaker(engine, class_=AsyncSession)
111
+
112
+
113
+ async def save_decision():
114
+ decision = DecisionSubmission(
115
+ user_id="user-123",
116
+ session_id="session-456",
117
+ video_id="video-789",
118
+ node_id="question-1",
119
+ choice_id="answer-b",
120
+ timestamp=12.5,
121
+ metadata={"source": "web"},
122
+ )
123
+
124
+ async with session_factory() as session:
125
+ repository = SQLAlchemySessionRepository(session)
126
+ await repository.save_decision(decision)
127
+ ```
128
+
129
+ ### 3. Restore session state
130
+
131
+ ```python
132
+ async def resume_session():
133
+ async with session_factory() as session:
134
+ repository = SQLAlchemySessionRepository(session)
135
+ state = await repository.get_session_state(
136
+ user_id="user-123",
137
+ session_id="session-456",
138
+ )
139
+
140
+ if state is not None:
141
+ print(state.last_node_id)
142
+ print(state.last_timestamp)
143
+ print(state.decision_history)
144
+ ```
145
+
146
+ The repository returns `None` when no decision exists for the supplied user and session.
147
+
148
+ ---
149
+
150
+ ## Decision Transition Validation
151
+
152
+ Use `DecisionLedgerEngine.validate_transition()` when a node defines the choices that may be selected:
153
+
154
+ ```python
155
+ from interactive_video_backend_core.logic import DecisionLedgerEngine
156
+
157
+ DecisionLedgerEngine.validate_transition(
158
+ current_node="question-1",
159
+ choice_id="answer-b",
160
+ allowed_choices=["answer-a", "answer-b"],
161
+ )
162
+ ```
163
+
164
+ An invalid choice raises `ValueError`:
165
+
166
+ ```text
167
+ Invalid choice 'answer-c' for node 'question-1'.
168
+ ```
169
+
170
+ ---
171
+
172
+ ## State Reconstruction
173
+
174
+ `DecisionLedgerEngine.reconstruct_state()` returns the last node and playback timestamp according to chronological playback time:
175
+
176
+ ```python
177
+ from interactive_video_backend_core.logic import DecisionLedgerEngine
178
+
179
+ node_id, timestamp = DecisionLedgerEngine.reconstruct_state(decisions)
180
+ ```
181
+
182
+ If the decision list is empty, the engine returns `("start", 0.0)`.
183
+
184
+ ---
185
+
186
+ ## Storage Interface
187
+
188
+ `AbstractSessionRepository` defines the framework-independent persistence contract:
189
+
190
+ ```python
191
+ from interactive_video_backend_core.models import (
192
+ DecisionSubmission,
193
+ SessionResumeResponse,
194
+ )
195
+ from interactive_video_backend_core.storage import AbstractSessionRepository
196
+
197
+
198
+ class MySessionRepository(AbstractSessionRepository):
199
+ async def save_decision(
200
+ self,
201
+ decision: DecisionSubmission,
202
+ ) -> None:
203
+ ...
204
+
205
+ async def get_session_state(
206
+ self,
207
+ user_id: str,
208
+ session_id: str,
209
+ ) -> SessionResumeResponse | None:
210
+ ...
211
+ ```
212
+
213
+ Implement this interface when your application needs a different database, API-backed store, or custom persistence behavior.
214
+
215
+ ---
216
+
217
+ ## Data Models
218
+
219
+ ### `DecisionSubmission`
220
+
221
+ | Field | Type | Description |
222
+ | --- | --- | --- |
223
+ | `user_id` | `str` | Identifier of the viewer |
224
+ | `session_id` | `str` | Identifier of the viewing session |
225
+ | `video_id` | `str` | Identifier of the interactive video |
226
+ | `node_id` | `str` | Node or checkpoint reached by the viewer |
227
+ | `choice_id` | `str` | Selected branch or answer |
228
+ | `timestamp` | `float` | Playback timestamp in seconds |
229
+ | `metadata` | `dict[str, Any] \| None` | Optional application-specific metadata |
230
+
231
+ ### `SessionResumeResponse`
232
+
233
+ | Field | Type | Description |
234
+ | --- | --- | --- |
235
+ | `user_id` | `str` | Identifier of the viewer |
236
+ | `session_id` | `str` | Identifier of the viewing session |
237
+ | `video_id` | `str` | Identifier of the most recently recorded video |
238
+ | `last_node_id` | `str` | Latest reconstructed node |
239
+ | `last_timestamp` | `float` | Latest reconstructed playback timestamp |
240
+ | `decision_history` | `list[DecisionSubmission]` | Decisions ordered by playback timestamp |
241
+ | `updated_at` | `datetime` | Timestamp of the latest database record |
242
+
243
+ ---
244
+
245
+ ## SQLAlchemy Schema
246
+
247
+ The included ORM model stores decisions in the `ivl_decision_ledger` table:
248
+
249
+ - `id`
250
+ - `user_id`
251
+ - `session_id`
252
+ - `video_id`
253
+ - `node_id`
254
+ - `choice_id`
255
+ - `timestamp`
256
+ - `metadata_json`
257
+ - `created_at`
258
+
259
+ Indexes are created for `user_id` and `session_id` to support session state lookup.
260
+
261
+ ---
262
+
263
+ ## Development
264
+
265
+ Clone the repository and install the development dependencies:
266
+
267
+ ```bash
268
+ git clone https://github.com/interactive-video-labs/interactive-video-backend-core.git
269
+ cd interactive-video-backend-core
270
+ poetry install
271
+ ```
272
+
273
+ Run the test suite:
274
+
275
+ ```bash
276
+ poetry run pytest
277
+ ```
278
+
279
+ For linting and project conventions, see [DEVELOPER.md](DEVELOPER.md) and [CONTRIBUTING.md](CONTRIBUTING.md).
280
+
281
+ ---
282
+
283
+ ## Project Structure
284
+
285
+ ```text
286
+ interactive-video-backend-core/
287
+ ├── interactive_video_backend_core/
288
+ │ ├── __init__.py
289
+ │ ├── logic.py
290
+ │ ├── models.py
291
+ │ ├── orm_models.py
292
+ │ ├── storage.py
293
+ │ └── storage_sqlalchemy.py
294
+ ├── tests/
295
+ │ ├── conftest.py
296
+ │ ├── test_logic.py
297
+ │ └── test_storage.py
298
+ ├── pyproject.toml
299
+ └── README.md
300
+ ```
301
+
302
+ ---
303
+
304
+ ## Contributing
305
+
306
+ Contributions are welcome. Please review [CONTRIBUTING.md](CONTRIBUTING.md) before submitting an issue or pull request.
307
+
308
+ ---
309
+
310
+ ## License
311
+
312
+ This project is licensed under the [MIT License](LICENSE).
313
+
@@ -0,0 +1,289 @@
1
+ # Interactive Video Backend Core
2
+
3
+ <p align="center">
4
+ <img src="https://raw.githubusercontent.com/interactive-video-labs/docs/main/logo.svg" width="200" alt="Interactive Video Labs Logo" />
5
+ </p>
6
+
7
+ <p align="center">
8
+ <img src="https://img.shields.io/pypi/v/interactive-video-backend-core" alt="PyPI Version" />
9
+ <img src="https://img.shields.io/pypi/l/interactive-video-backend-core" alt="License" />
10
+ <img src="https://img.shields.io/pypi/dm/interactive-video-backend-core" alt="PyPI Downloads" />
11
+ </p>
12
+
13
+ `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.
14
+
15
+ The package is designed to complement [`@interactive-video-labs/core`](https://github.com/interactive-video-labs/interactive-video-core), the framework-agnostic TypeScript player used by interactive video applications.
16
+
17
+ ---
18
+
19
+ ## Features
20
+
21
+ - **Decision ledger:** Persist each user choice with session, video, node, choice, playback timestamp, and optional metadata.
22
+ - **Session resume:** Reconstruct the latest node and playback timestamp for a user session.
23
+ - **Transition validation:** Verify that a submitted choice belongs to the choices allowed for the current node.
24
+ - **Pydantic models:** Use typed, validated submission and resume response models.
25
+ - **Async SQLAlchemy storage:** Work with async database sessions and SQLAlchemy 2.x.
26
+ - **Framework agnostic:** Integrate the core with FastAPI, Django, Litestar, or another Python backend.
27
+ - **Chronological state recovery:** Rebuild state even when decision records arrive out of order.
28
+
29
+ ---
30
+
31
+ ## Requirements
32
+
33
+ - Python 3.10 or newer
34
+ - Pydantic 2.x
35
+ - SQLAlchemy 2.x
36
+
37
+ ---
38
+
39
+ ## Installation
40
+
41
+ ### Poetry
42
+
43
+ ```bash
44
+ poetry add interactive-video-backend-core
45
+ ```
46
+
47
+ ### pip
48
+
49
+ ```bash
50
+ pip install interactive-video-backend-core
51
+ ```
52
+
53
+ ---
54
+
55
+ ## Quick Start
56
+
57
+ ### 1. Create the database tables
58
+
59
+ ```python
60
+ from sqlalchemy.ext.asyncio import (
61
+ AsyncEngine,
62
+ create_async_engine,
63
+ )
64
+
65
+ from interactive_video_backend_core.orm_models import Base
66
+
67
+
68
+ engine: AsyncEngine = create_async_engine(
69
+ "sqlite+aiosqlite:///./interactive_video.db"
70
+ )
71
+
72
+ async def initialize_database():
73
+ async with engine.begin() as connection:
74
+ await connection.run_sync(Base.metadata.create_all)
75
+ ```
76
+
77
+ ### 2. Save a decision
78
+
79
+ ```python
80
+ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
81
+
82
+ from interactive_video_backend_core.models import DecisionSubmission
83
+ from interactive_video_backend_core.storage_sqlalchemy import (
84
+ SQLAlchemySessionRepository,
85
+ )
86
+
87
+ session_factory = async_sessionmaker(engine, class_=AsyncSession)
88
+
89
+
90
+ async def save_decision():
91
+ decision = DecisionSubmission(
92
+ user_id="user-123",
93
+ session_id="session-456",
94
+ video_id="video-789",
95
+ node_id="question-1",
96
+ choice_id="answer-b",
97
+ timestamp=12.5,
98
+ metadata={"source": "web"},
99
+ )
100
+
101
+ async with session_factory() as session:
102
+ repository = SQLAlchemySessionRepository(session)
103
+ await repository.save_decision(decision)
104
+ ```
105
+
106
+ ### 3. Restore session state
107
+
108
+ ```python
109
+ async def resume_session():
110
+ async with session_factory() as session:
111
+ repository = SQLAlchemySessionRepository(session)
112
+ state = await repository.get_session_state(
113
+ user_id="user-123",
114
+ session_id="session-456",
115
+ )
116
+
117
+ if state is not None:
118
+ print(state.last_node_id)
119
+ print(state.last_timestamp)
120
+ print(state.decision_history)
121
+ ```
122
+
123
+ The repository returns `None` when no decision exists for the supplied user and session.
124
+
125
+ ---
126
+
127
+ ## Decision Transition Validation
128
+
129
+ Use `DecisionLedgerEngine.validate_transition()` when a node defines the choices that may be selected:
130
+
131
+ ```python
132
+ from interactive_video_backend_core.logic import DecisionLedgerEngine
133
+
134
+ DecisionLedgerEngine.validate_transition(
135
+ current_node="question-1",
136
+ choice_id="answer-b",
137
+ allowed_choices=["answer-a", "answer-b"],
138
+ )
139
+ ```
140
+
141
+ An invalid choice raises `ValueError`:
142
+
143
+ ```text
144
+ Invalid choice 'answer-c' for node 'question-1'.
145
+ ```
146
+
147
+ ---
148
+
149
+ ## State Reconstruction
150
+
151
+ `DecisionLedgerEngine.reconstruct_state()` returns the last node and playback timestamp according to chronological playback time:
152
+
153
+ ```python
154
+ from interactive_video_backend_core.logic import DecisionLedgerEngine
155
+
156
+ node_id, timestamp = DecisionLedgerEngine.reconstruct_state(decisions)
157
+ ```
158
+
159
+ If the decision list is empty, the engine returns `("start", 0.0)`.
160
+
161
+ ---
162
+
163
+ ## Storage Interface
164
+
165
+ `AbstractSessionRepository` defines the framework-independent persistence contract:
166
+
167
+ ```python
168
+ from interactive_video_backend_core.models import (
169
+ DecisionSubmission,
170
+ SessionResumeResponse,
171
+ )
172
+ from interactive_video_backend_core.storage import AbstractSessionRepository
173
+
174
+
175
+ class MySessionRepository(AbstractSessionRepository):
176
+ async def save_decision(
177
+ self,
178
+ decision: DecisionSubmission,
179
+ ) -> None:
180
+ ...
181
+
182
+ async def get_session_state(
183
+ self,
184
+ user_id: str,
185
+ session_id: str,
186
+ ) -> SessionResumeResponse | None:
187
+ ...
188
+ ```
189
+
190
+ Implement this interface when your application needs a different database, API-backed store, or custom persistence behavior.
191
+
192
+ ---
193
+
194
+ ## Data Models
195
+
196
+ ### `DecisionSubmission`
197
+
198
+ | Field | Type | Description |
199
+ | --- | --- | --- |
200
+ | `user_id` | `str` | Identifier of the viewer |
201
+ | `session_id` | `str` | Identifier of the viewing session |
202
+ | `video_id` | `str` | Identifier of the interactive video |
203
+ | `node_id` | `str` | Node or checkpoint reached by the viewer |
204
+ | `choice_id` | `str` | Selected branch or answer |
205
+ | `timestamp` | `float` | Playback timestamp in seconds |
206
+ | `metadata` | `dict[str, Any] \| None` | Optional application-specific metadata |
207
+
208
+ ### `SessionResumeResponse`
209
+
210
+ | Field | Type | Description |
211
+ | --- | --- | --- |
212
+ | `user_id` | `str` | Identifier of the viewer |
213
+ | `session_id` | `str` | Identifier of the viewing session |
214
+ | `video_id` | `str` | Identifier of the most recently recorded video |
215
+ | `last_node_id` | `str` | Latest reconstructed node |
216
+ | `last_timestamp` | `float` | Latest reconstructed playback timestamp |
217
+ | `decision_history` | `list[DecisionSubmission]` | Decisions ordered by playback timestamp |
218
+ | `updated_at` | `datetime` | Timestamp of the latest database record |
219
+
220
+ ---
221
+
222
+ ## SQLAlchemy Schema
223
+
224
+ The included ORM model stores decisions in the `ivl_decision_ledger` table:
225
+
226
+ - `id`
227
+ - `user_id`
228
+ - `session_id`
229
+ - `video_id`
230
+ - `node_id`
231
+ - `choice_id`
232
+ - `timestamp`
233
+ - `metadata_json`
234
+ - `created_at`
235
+
236
+ Indexes are created for `user_id` and `session_id` to support session state lookup.
237
+
238
+ ---
239
+
240
+ ## Development
241
+
242
+ Clone the repository and install the development dependencies:
243
+
244
+ ```bash
245
+ git clone https://github.com/interactive-video-labs/interactive-video-backend-core.git
246
+ cd interactive-video-backend-core
247
+ poetry install
248
+ ```
249
+
250
+ Run the test suite:
251
+
252
+ ```bash
253
+ poetry run pytest
254
+ ```
255
+
256
+ For linting and project conventions, see [DEVELOPER.md](DEVELOPER.md) and [CONTRIBUTING.md](CONTRIBUTING.md).
257
+
258
+ ---
259
+
260
+ ## Project Structure
261
+
262
+ ```text
263
+ interactive-video-backend-core/
264
+ ├── interactive_video_backend_core/
265
+ │ ├── __init__.py
266
+ │ ├── logic.py
267
+ │ ├── models.py
268
+ │ ├── orm_models.py
269
+ │ ├── storage.py
270
+ │ └── storage_sqlalchemy.py
271
+ ├── tests/
272
+ │ ├── conftest.py
273
+ │ ├── test_logic.py
274
+ │ └── test_storage.py
275
+ ├── pyproject.toml
276
+ └── README.md
277
+ ```
278
+
279
+ ---
280
+
281
+ ## Contributing
282
+
283
+ Contributions are welcome. Please review [CONTRIBUTING.md](CONTRIBUTING.md) before submitting an issue or pull request.
284
+
285
+ ---
286
+
287
+ ## License
288
+
289
+ This project is licensed under the [MIT License](LICENSE).
@@ -0,0 +1,24 @@
1
+ from typing import List
2
+ from interactive_video_backend_core.models import DecisionSubmission
3
+
4
+ class DecisionLedgerEngine:
5
+ """Pure business logic engine for interactive video decision flows."""
6
+
7
+ @staticmethod
8
+ def validate_transition(current_node: str, choice_id: str, allowed_choices: List[str]) -> bool:
9
+ """Ensures the submitted choice is a valid branch path."""
10
+ if choice_id not in allowed_choices:
11
+ raise ValueError(f"Invalid choice '{choice_id}' for node '{current_node}'.")
12
+ return True
13
+
14
+ @staticmethod
15
+ def reconstruct_state(decisions: List[DecisionSubmission]) -> tuple[str, float]:
16
+ """Reconstructs the last known valid state from a time-ordered ledger."""
17
+ if not decisions:
18
+ return "start", 0.0
19
+
20
+ # Sort chronologically just in case
21
+ sorted_decisions = sorted(decisions, key=lambda d: d.timestamp)
22
+ latest = sorted_decisions[-1]
23
+
24
+ return latest.node_id, latest.timestamp
@@ -0,0 +1,21 @@
1
+ from datetime import datetime
2
+ from typing import Any, Dict, Optional
3
+ from pydantic import BaseModel, Field
4
+
5
+ class DecisionSubmission(BaseModel):
6
+ user_id: str
7
+ session_id: str
8
+ video_id: str
9
+ node_id: str
10
+ choice_id: str
11
+ timestamp: float = Field(..., description="Playback timestamp in seconds")
12
+ metadata: Optional[Dict[str, Any]] = None
13
+
14
+ class SessionResumeResponse(BaseModel):
15
+ user_id: str
16
+ session_id: str
17
+ video_id: str
18
+ last_node_id: str
19
+ last_timestamp: float
20
+ decision_history: list[DecisionSubmission] = []
21
+ updated_at: datetime
@@ -0,0 +1,26 @@
1
+ from datetime import datetime, timezone
2
+ from typing import Any
3
+
4
+ from sqlalchemy import JSON, DateTime, Float, String
5
+ from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
6
+
7
+
8
+ class Base(DeclarativeBase):
9
+ pass
10
+
11
+
12
+ class DecisionModel(Base):
13
+ __tablename__ = "ivl_decision_ledger"
14
+
15
+ id: Mapped[str] = mapped_column(String, primary_key=True)
16
+ user_id: Mapped[str] = mapped_column(String, index=True)
17
+ session_id: Mapped[str] = mapped_column(String, index=True)
18
+ video_id: Mapped[str] = mapped_column(String)
19
+ node_id: Mapped[str] = mapped_column(String)
20
+ choice_id: Mapped[str] = mapped_column(String)
21
+ timestamp: Mapped[float] = mapped_column(Float)
22
+ metadata_json: Mapped[dict[str, Any] | None] = mapped_column(JSON, nullable=True)
23
+ created_at: Mapped[datetime] = mapped_column(
24
+ DateTime,
25
+ default=lambda: datetime.now(timezone.utc),
26
+ )
@@ -0,0 +1,16 @@
1
+ from abc import ABC, abstractmethod
2
+ from typing import List, Optional
3
+ from interactive_video_backend_core.models import DecisionSubmission, SessionResumeResponse
4
+
5
+ class AbstractSessionRepository(ABC):
6
+ """Abstract storage interface. Host frameworks implement this using their own DB session."""
7
+
8
+ @abstractmethod
9
+ async def save_decision(self, decision: DecisionSubmission) -> None:
10
+ """Persists a new decision to the ledger."""
11
+ pass
12
+
13
+ @abstractmethod
14
+ async def get_session_state(self, user_id: str, session_id: str) -> Optional[SessionResumeResponse]:
15
+ """Retrieves the full decision ledger and latest state for multi-device resume."""
16
+ pass
@@ -0,0 +1,76 @@
1
+ import uuid
2
+ from typing import Optional
3
+
4
+ from sqlalchemy import select
5
+ from sqlalchemy.ext.asyncio import AsyncSession
6
+
7
+ from interactive_video_backend_core.logic import DecisionLedgerEngine
8
+ from interactive_video_backend_core.models import (
9
+ DecisionSubmission,
10
+ SessionResumeResponse,
11
+ )
12
+ from interactive_video_backend_core.orm_models import DecisionModel
13
+ from interactive_video_backend_core.storage import AbstractSessionRepository
14
+
15
+
16
+ class SQLAlchemySessionRepository(AbstractSessionRepository):
17
+ """SQLAlchemy implementation of the session and decision storage layer."""
18
+
19
+ def __init__(self, session: AsyncSession):
20
+ self.db = session
21
+
22
+ async def save_decision(self, decision: DecisionSubmission) -> None:
23
+ """Persists a new decision entry into the database ledger."""
24
+ db_decision = DecisionModel(
25
+ id=str(uuid.uuid4()),
26
+ user_id=decision.user_id,
27
+ session_id=decision.session_id,
28
+ video_id=decision.video_id,
29
+ node_id=decision.node_id,
30
+ choice_id=decision.choice_id,
31
+ timestamp=decision.timestamp,
32
+ metadata_json=decision.metadata
33
+ )
34
+ self.db.add(db_decision)
35
+ await self.db.commit()
36
+
37
+ async def get_session_state(self, user_id: str, session_id: str) -> Optional[SessionResumeResponse]:
38
+ """Queries the decision ledger and reconstructs the latest state for multi-device resume."""
39
+ stmt = (
40
+ select(DecisionModel)
41
+ .where(DecisionModel.user_id == user_id)
42
+ .where(DecisionModel.session_id == session_id)
43
+ .order_by(DecisionModel.timestamp.asc())
44
+ )
45
+ result = await self.db.execute(stmt)
46
+ rows = result.scalars().all()
47
+
48
+ if not rows:
49
+ return None
50
+
51
+ # Convert ORM rows back to core Pydantic DecisionSubmission models
52
+ decisions = [
53
+ DecisionSubmission(
54
+ user_id=row.user_id,
55
+ session_id=row.session_id,
56
+ video_id=row.video_id,
57
+ node_id=row.node_id,
58
+ choice_id=row.choice_id,
59
+ timestamp=row.timestamp,
60
+ metadata=row.metadata_json
61
+ )
62
+ for row in rows
63
+ ]
64
+
65
+ # Use pure core logic to compute the current playback state
66
+ last_node_id, last_timestamp = DecisionLedgerEngine.reconstruct_state(decisions)
67
+
68
+ return SessionResumeResponse(
69
+ user_id=user_id,
70
+ session_id=session_id,
71
+ video_id=rows[-1].video_id,
72
+ last_node_id=last_node_id,
73
+ last_timestamp=last_timestamp,
74
+ decision_history=decisions,
75
+ updated_at=rows[-1].created_at
76
+ )
@@ -0,0 +1,37 @@
1
+ [tool.poetry]
2
+ name = "interactive-video-backend-core"
3
+ version = "0.1.0"
4
+ description = "Framework-agnostic Python backend core and storage adapters for syncing interactive video state and decision ledgers"
5
+ authors = ["Taj <tajulislamj200@gmail.com>"]
6
+ readme = "README.md"
7
+ license = "MIT"
8
+ homepage = "https://github.com/interactive-video-labs"
9
+ repository = "https://github.com/interactive-video-labs/interactive-video-backend-core"
10
+ packages = [{ include = "interactive_video_backend_core", from = "." }]
11
+
12
+ [tool.poetry.dependencies]
13
+ python = "^3.10"
14
+ pydantic = ">=2.0"
15
+ sqlalchemy = ">=2.0"
16
+
17
+ [tool.poetry.group.dev.dependencies]
18
+ pytest = "^9.0.0"
19
+ pytest-asyncio = "^1.0.0"
20
+ aiosqlite = "^0.22.0"
21
+ httpx = "^0.28.0"
22
+
23
+ [tool.pyright]
24
+ useLibraryCodeForTypes = true
25
+ exclude = [".cache", "dist", ".venv"]
26
+
27
+ [tool.ruff]
28
+ select = ["E", "W", "F", "I", "B", "C4", "ARG", "SIM"]
29
+ ignore = ["W291", "W292", "W293"]
30
+
31
+ [tool.pytest.ini_options]
32
+ asyncio_mode = "auto"
33
+ testpaths = ["tests"]
34
+
35
+ [build-system]
36
+ requires = ["poetry-core"]
37
+ build-backend = "poetry.core.masonry.api"