cjm-vad-adapter-interface 0.0.2__py3-none-any.whl

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 @@
1
+ __version__ = "0.0.2"
@@ -0,0 +1,41 @@
1
+ # Autogenerated by nbdev
2
+
3
+ d = { 'settings': { 'branch': 'main',
4
+ 'doc_baseurl': '/cjm-vad-adapter-interface',
5
+ 'doc_host': 'https://cj-mills.github.io',
6
+ 'git_url': 'https://github.com/cj-mills/cjm-vad-adapter-interface',
7
+ 'lib_path': 'cjm_vad_adapter_interface'},
8
+ 'syms': { 'cjm_vad_adapter_interface.adapter': { 'cjm_vad_adapter_interface.adapter.VADAdapter': ( 'adapter.html#vadadapter',
9
+ 'cjm_vad_adapter_interface/adapter.py'),
10
+ 'cjm_vad_adapter_interface.adapter.VADAdapter.__init__': ( 'adapter.html#vadadapter.__init__',
11
+ 'cjm_vad_adapter_interface/adapter.py'),
12
+ 'cjm_vad_adapter_interface.adapter.VADAdapter.detect_speech': ( 'adapter.html#vadadapter.detect_speech',
13
+ 'cjm_vad_adapter_interface/adapter.py'),
14
+ 'cjm_vad_adapter_interface.adapter.VADToolProtocol': ( 'adapter.html#vadtoolprotocol',
15
+ 'cjm_vad_adapter_interface/adapter.py'),
16
+ 'cjm_vad_adapter_interface.adapter.VADToolProtocol.detect_speech': ( 'adapter.html#vadtoolprotocol.detect_speech',
17
+ 'cjm_vad_adapter_interface/adapter.py'),
18
+ 'cjm_vad_adapter_interface.adapter.VADToolProtocol.get_current_config': ( 'adapter.html#vadtoolprotocol.get_current_config',
19
+ 'cjm_vad_adapter_interface/adapter.py')},
20
+ 'cjm_vad_adapter_interface.generic': { 'cjm_vad_adapter_interface.generic.GenericVADAdapter': ( 'generic.html#genericvadadapter',
21
+ 'cjm_vad_adapter_interface/generic.py'),
22
+ 'cjm_vad_adapter_interface.generic.GenericVADAdapter._get_storage': ( 'generic.html#genericvadadapter._get_storage',
23
+ 'cjm_vad_adapter_interface/generic.py'),
24
+ 'cjm_vad_adapter_interface.generic.GenericVADAdapter.detect_speech': ( 'generic.html#genericvadadapter.detect_speech',
25
+ 'cjm_vad_adapter_interface/generic.py')},
26
+ 'cjm_vad_adapter_interface.storage': { 'cjm_vad_adapter_interface.storage.VADRow': ( 'storage.html#vadrow',
27
+ 'cjm_vad_adapter_interface/storage.py'),
28
+ 'cjm_vad_adapter_interface.storage.VADStorage': ( 'storage.html#vadstorage',
29
+ 'cjm_vad_adapter_interface/storage.py'),
30
+ 'cjm_vad_adapter_interface.storage.VADStorage.__init__': ( 'storage.html#vadstorage.__init__',
31
+ 'cjm_vad_adapter_interface/storage.py'),
32
+ 'cjm_vad_adapter_interface.storage.VADStorage.get_cached': ( 'storage.html#vadstorage.get_cached',
33
+ 'cjm_vad_adapter_interface/storage.py'),
34
+ 'cjm_vad_adapter_interface.storage.VADStorage.list_jobs': ( 'storage.html#vadstorage.list_jobs',
35
+ 'cjm_vad_adapter_interface/storage.py'),
36
+ 'cjm_vad_adapter_interface.storage.VADStorage.save': ( 'storage.html#vadstorage.save',
37
+ 'cjm_vad_adapter_interface/storage.py'),
38
+ 'cjm_vad_adapter_interface.storage.VADStorage.save_with_logging': ( 'storage.html#vadstorage.save_with_logging',
39
+ 'cjm_vad_adapter_interface/storage.py'),
40
+ 'cjm_vad_adapter_interface.storage.VADStorage.verify_file': ( 'storage.html#vadstorage.verify_file',
41
+ 'cjm_vad_adapter_interface/storage.py')}}}
@@ -0,0 +1,71 @@
1
+ """The typed voice-activity-detection task contract — the `VADAdapter` ABC + the `VADToolProtocol` structural contract (capability-unit Option C, pass-2 Thread 3).
2
+
3
+ Docs: https://cj-mills.github.io/cjm-vad-adapter-interfaceadapter.html.md"""
4
+
5
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/adapter.ipynb.
6
+
7
+ # %% auto #0
8
+ __all__ = ['VADToolProtocol', 'VADAdapter']
9
+
10
+ # %% ../nbs/adapter.ipynb #a7b39b97
11
+ from abc import abstractmethod
12
+ from pathlib import Path
13
+ from typing import Any, ClassVar, Dict, Protocol, Union, runtime_checkable
14
+
15
+ from cjm_plugin_system.core.adapter import TaskAdapter
16
+
17
+ # Canonical home (stage 8 / PILLAR 1c): the data noun lives in
18
+ # cjm-capability-primitives, so the pure-compute tool depends on it, never on
19
+ # this adapter machinery.
20
+ from cjm_capability_primitives.vad import VADResult
21
+
22
+ # %% ../nbs/adapter.ipynb #edacb217
23
+ @runtime_checkable
24
+ class VADToolProtocol(Protocol):
25
+ """Structural contract for voice-activity-detection tool capabilities
26
+ (born-final at stage 8 — derived from the native tool surface).
27
+
28
+ Pure compute: `detect_speech` reads the model-ready audio + runs inference +
29
+ builds the typed result. `get_current_config` supplies the effective config
30
+ the generic adapter hashes for its cache key. Persistence is NOT here — the
31
+ adapter owns it (the native-surface seam)."""
32
+ def detect_speech(self, audio: Union[str, Path], **kwargs) -> VADResult: ...
33
+ def get_current_config(self) -> Dict[str, Any]: ...
34
+
35
+ # %% ../nbs/adapter.ipynb #9c358302
36
+ class VADAdapter(TaskAdapter):
37
+ """Typed voice-activity-detection task adapter: model-ready audio in,
38
+ `VADResult` out.
39
+
40
+ Input contract: the caller guarantees MODEL-READY audio — format /
41
+ sample-rate / channel handling happens upstream (ffmpeg `convert`), never
42
+ in the adapter or tool.
43
+
44
+ Native-surface model (stage 8 / PILLAR 1c): the TOOL is pure compute; the
45
+ ADAPTER owns the cache + persistence bookends (see `GenericVADAdapter`) +
46
+ the per-call `force` control. Storage resolves from the substrate-injected
47
+ `PLUGIN_DATA_DIR`; `db_path` is not on the tool protocol.
48
+
49
+ Implementations run in-worker beside their tool capability and are
50
+ constructed with the bound tool instance: `AdapterClass(tool)` (mirrors
51
+ `GraphStorageAdapter`). The result DTO is wire-registered ("vad.result"):
52
+ returned values cross the worker boundary typed.
53
+ """
54
+
55
+ task_name: ClassVar[str] = "vad"
56
+ required_tool_protocol: ClassVar[type] = VADToolProtocol
57
+
58
+ def __init__(
59
+ self,
60
+ tool: VADToolProtocol, # The bound tool capability instance (worker-side binding)
61
+ ):
62
+ self.tool = tool
63
+
64
+ @abstractmethod
65
+ def detect_speech(
66
+ self,
67
+ audio: Union[str, Path], # Path to MODEL-READY audio (converted upstream)
68
+ **kwargs, # Provenance + tool options
69
+ ) -> VADResult: # Typed VAD output
70
+ """Detect speech segments in model-ready audio."""
71
+ ...
@@ -0,0 +1,80 @@
1
+ """The generic (tool-agnostic) VAD adapter — cache-check, invoke the bound tool's pure-compute `detect_speech`, persist. Reused across every tool capability satisfying `VADToolProtocol`, exactly as `GenericTranscriptionAdapter` is reused across transcribers.
2
+
3
+ Docs: https://cj-mills.github.io/cjm-vad-adapter-interfacegeneric.html.md"""
4
+
5
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/generic.ipynb.
6
+
7
+ # %% auto #0
8
+ __all__ = ['GenericVADAdapter']
9
+
10
+ # %% ../nbs/generic.ipynb #81d6c059
11
+ import os
12
+ from pathlib import Path
13
+ from typing import Union
14
+
15
+ from cjm_plugin_system.core.wire import get_call_envelope
16
+ from cjm_plugin_system.utils.hashing import hash_file, hash_dict_canonical
17
+
18
+ from cjm_capability_primitives.vad import VADResult, TimeRange
19
+ from .adapter import VADAdapter
20
+ from .storage import VADStorage
21
+
22
+ # %% ../nbs/generic.ipynb #a11b0d2b
23
+ class GenericVADAdapter(VADAdapter):
24
+ """Generic VAD adapter: cache-check -> pure-compute tool -> persist.
25
+
26
+ Works against ANY tool satisfying `VADToolProtocol`. The bookends:
27
+
28
+ 1. cache check (file_path + file_hash + config_hash) BEFORE invoking the
29
+ tool, so a hit never loads the model;
30
+ 2. the tool's pure-compute `detect_speech` on a miss / forced call;
31
+ 3. `save_with_logging` (upsert by file_path + config_hash).
32
+
33
+ `config_hash` reuses `hash_dict_canonical(get_current_config())` (the SAME
34
+ canonical hash the fused-era plugin used). `force` rides
35
+ `CallEnvelope.control` (not a task kwarg, keeping `detect_speech(audio)`
36
+ pure). Storage lives at `<PLUGIN_DATA_DIR>/vad.db`; the substrate injects
37
+ the per-capability `PLUGIN_DATA_DIR` at spawn, so the adapter neither
38
+ hard-codes a path nor asks the tool for one.
39
+ """
40
+
41
+ def _get_storage(self) -> VADStorage:
42
+ """Lazily open the per-capability cache DB under the substrate-injected
43
+ PLUGIN_DATA_DIR (created at worker spawn)."""
44
+ if getattr(self, "_storage", None) is None:
45
+ db_path = os.path.join(os.environ["PLUGIN_DATA_DIR"], "vad.db")
46
+ self._storage = VADStorage(db_path)
47
+ return self._storage
48
+
49
+ def detect_speech(
50
+ self,
51
+ audio: Union[str, Path], # Path to MODEL-READY audio (converted upstream)
52
+ **kwargs, # Provenance + tool options
53
+ ) -> VADResult: # Typed VAD output
54
+ """Cache-check, invoke the bound tool's pure-compute `detect_speech`, persist."""
55
+ file_path = str(audio)
56
+ file_hash = hash_file(file_path)
57
+ config_hash = hash_dict_canonical(self.tool.get_current_config())
58
+
59
+ env = get_call_envelope()
60
+ force = bool(env.control.get("force")) if env is not None else False
61
+
62
+ storage = self._get_storage()
63
+ if not force:
64
+ cached = storage.get_cached(file_path, file_hash, config_hash)
65
+ if cached is not None:
66
+ return VADResult(
67
+ ranges=[TimeRange(**r) for r in (cached.ranges or [])],
68
+ metadata=cached.metadata or {},
69
+ )
70
+
71
+ # Pure compute on the tool (cache miss / forced).
72
+ result = self.tool.detect_speech(audio, **kwargs)
73
+
74
+ # Persist. Content-addressed row (no job_id); cache key is
75
+ # (file_path, config_hash) with file_hash for content-correctness.
76
+ storage.save_with_logging(
77
+ file_path=file_path, file_hash=file_hash, config_hash=config_hash,
78
+ ranges=[r.to_dict() for r in result.ranges], metadata=result.metadata,
79
+ )
80
+ return result
@@ -0,0 +1,202 @@
1
+ """Standardized SQLite storage for voice-activity-detection results with content hashing.
2
+
3
+ Docs: https://cj-mills.github.io/cjm-vad-adapter-interfacestorage.html.md"""
4
+
5
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/storage.ipynb.
6
+
7
+ # %% auto #0
8
+ __all__ = ['VADRow', 'VADStorage']
9
+
10
+ # %% ../nbs/storage.ipynb #80a9ba21
11
+ import json
12
+ import logging
13
+ import sqlite3
14
+ import time
15
+ from dataclasses import dataclass
16
+ from typing import Any, Dict, List, Optional
17
+
18
+ from cjm_plugin_system.utils.hashing import hash_file
19
+ # CR-14 follow-up: storage events are substrate-family accounts. The helpers
20
+ # below RECORD them (no-op outside a worker call span); the host journals
21
+ # them off the response header with worker_reported=True.
22
+ from cjm_plugin_system.core.journal_store import SubstrateEventType
23
+ from cjm_plugin_system.core.wire import record_account
24
+
25
+ # %% ../nbs/storage.ipynb #f4d22588
26
+ @dataclass
27
+ class VADRow:
28
+ """A single row from the vad_results table."""
29
+ file_path: str # Path to the analyzed (model-ready) audio file
30
+ file_hash: str # Hash of the analyzed file in "algo:hexdigest" format
31
+ config_hash: str # Hash of the VAD detection config used
32
+ ranges: Optional[List[Dict[str, Any]]] = None # Detected speech segments (serialized TimeRanges)
33
+ metadata: Optional[Dict[str, Any]] = None # VAD metadata
34
+ created_at: Optional[float] = None # Unix timestamp
35
+
36
+ # %% ../nbs/storage.ipynb #b11a2421
37
+ class VADStorage:
38
+ """Standardized SQLite storage for voice-activity-detection results."""
39
+
40
+ SCHEMA = """
41
+ CREATE TABLE IF NOT EXISTS vad_results (
42
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
43
+ file_path TEXT NOT NULL,
44
+ file_hash TEXT NOT NULL,
45
+ config_hash TEXT NOT NULL,
46
+ ranges JSON,
47
+ metadata JSON,
48
+ created_at REAL NOT NULL,
49
+ UNIQUE(file_path, config_hash)
50
+ )
51
+ """
52
+
53
+ INDEX = "CREATE INDEX IF NOT EXISTS idx_vad_file_path ON vad_results(file_path);"
54
+
55
+ def __init__(
56
+ self,
57
+ db_path: str # Absolute path to the SQLite database file
58
+ ):
59
+ """Initialize storage and create table if needed."""
60
+ self.db_path = db_path
61
+ with sqlite3.connect(self.db_path) as con:
62
+ con.execute(self.SCHEMA)
63
+ con.execute(self.INDEX)
64
+
65
+ def save(
66
+ self,
67
+ file_path: str, # Path to the analyzed audio file
68
+ file_hash: str, # Hash of the analyzed file in "algo:hexdigest" format
69
+ config_hash: str, # Hash of the VAD detection config
70
+ ranges: Optional[List[Dict[str, Any]]] = None, # Detected speech segments
71
+ metadata: Optional[Dict[str, Any]] = None # VAD metadata
72
+ ) -> None:
73
+ """Save or replace a VAD result (upsert by file_path + config_hash)."""
74
+ with sqlite3.connect(self.db_path) as con:
75
+ con.execute(
76
+ """INSERT OR REPLACE INTO vad_results
77
+ (file_path, file_hash, config_hash, ranges, metadata, created_at)
78
+ VALUES (?, ?, ?, ?, ?, ?)""",
79
+ (
80
+ file_path,
81
+ file_hash,
82
+ config_hash,
83
+ json.dumps(ranges) if ranges else None,
84
+ json.dumps(metadata) if metadata else None,
85
+ time.time()
86
+ )
87
+ )
88
+
89
+ def save_with_logging(
90
+ self,
91
+ *,
92
+ file_path: str, # Path to the analyzed audio file
93
+ file_hash: str, # Hash of the analyzed file in "algo:hexdigest" format
94
+ config_hash: str, # Hash of the VAD detection config
95
+ ranges: Optional[List[Dict[str, Any]]] = None, # Detected speech segments
96
+ metadata: Optional[Dict[str, Any]] = None, # VAD metadata
97
+ logger: Optional[logging.Logger] = None # Optional logger for success/failure messages
98
+ ) -> bool: # True if saved; False if the save failed (error logged, not raised)
99
+ """Save a result, logging success/failure. Failures are logged and swallowed (returns False).
100
+
101
+ CR-14 follow-up: records a RESULT_SAVED account either way (ok flag +
102
+ file/config references — the journal never carries content) so saves AND
103
+ swallowed save-failures become auditable journal rows."""
104
+ try:
105
+ self.save(
106
+ file_path=file_path,
107
+ file_hash=file_hash,
108
+ config_hash=config_hash,
109
+ ranges=ranges,
110
+ metadata=metadata,
111
+ )
112
+ record_account(SubstrateEventType.RESULT_SAVED.value, {
113
+ "ok": True, "file_path": file_path, "file_hash": file_hash,
114
+ "config_hash": config_hash,
115
+ })
116
+ if logger:
117
+ logger.info(f"Saved VAD result to DB ({file_path})")
118
+ return True
119
+ except Exception as e:
120
+ record_account(SubstrateEventType.RESULT_SAVED.value, {
121
+ "ok": False, "file_path": file_path, "file_hash": file_hash,
122
+ "config_hash": config_hash, "error": str(e),
123
+ })
124
+ if logger:
125
+ logger.error(f"Failed to save to DB: {e}")
126
+ return False
127
+
128
+ def get_cached(
129
+ self,
130
+ file_path: str, # Path to the audio file
131
+ file_hash: str, # Content hash of the file (cache miss if the file changed)
132
+ config_hash: str # Config hash to match
133
+ ) -> Optional[VADRow]: # Cached row or None
134
+ """Retrieve a content-correct cached VAD result.
135
+
136
+ Matches on file_path + file_hash + config_hash, so a changed file (new
137
+ file_hash) misses the cache even though a stale row may still exist at the
138
+ same (file_path, config_hash) — the next save() replaces it.
139
+
140
+ CR-14 follow-up: a hit records a CACHE_HIT account (the cache-serving
141
+ decision is an account-of-action)."""
142
+ with sqlite3.connect(self.db_path) as con:
143
+ cur = con.execute(
144
+ """SELECT file_path, file_hash, config_hash, ranges, metadata, created_at
145
+ FROM vad_results WHERE file_path = ? AND file_hash = ? AND config_hash = ?""",
146
+ (file_path, file_hash, config_hash)
147
+ )
148
+ row = cur.fetchone()
149
+ if not row:
150
+ return None
151
+ record_account(SubstrateEventType.CACHE_HIT.value, {
152
+ "file_path": file_path, "file_hash": file_hash,
153
+ "config_hash": config_hash,
154
+ })
155
+ return VADRow(
156
+ file_path=row[0],
157
+ file_hash=row[1],
158
+ config_hash=row[2],
159
+ ranges=json.loads(row[3]) if row[3] else None,
160
+ metadata=json.loads(row[4]) if row[4] else None,
161
+ created_at=row[5]
162
+ )
163
+
164
+ def list_jobs(
165
+ self,
166
+ limit: int = 100 # Maximum number of rows to return
167
+ ) -> List[VADRow]: # List of VAD rows
168
+ """List VAD results ordered by creation time (newest first)."""
169
+ results = []
170
+ with sqlite3.connect(self.db_path) as con:
171
+ cur = con.execute(
172
+ """SELECT file_path, file_hash, config_hash, ranges, metadata, created_at
173
+ FROM vad_results ORDER BY created_at DESC LIMIT ?""",
174
+ (limit,)
175
+ )
176
+ for row in cur:
177
+ results.append(VADRow(
178
+ file_path=row[0],
179
+ file_hash=row[1],
180
+ config_hash=row[2],
181
+ ranges=json.loads(row[3]) if row[3] else None,
182
+ metadata=json.loads(row[4]) if row[4] else None,
183
+ created_at=row[5]
184
+ ))
185
+ return results
186
+
187
+ def verify_file(
188
+ self,
189
+ file_path: str, # Path to the audio file
190
+ config_hash: str # Config hash to look up
191
+ ) -> Optional[bool]: # True if file matches, False if changed, None if not found
192
+ """Verify the analyzed file still matches the hash stored for (file_path, config_hash)."""
193
+ with sqlite3.connect(self.db_path) as con:
194
+ cur = con.execute(
195
+ """SELECT file_hash FROM vad_results
196
+ WHERE file_path = ? AND config_hash = ?""",
197
+ (file_path, config_hash)
198
+ )
199
+ row = cur.fetchone()
200
+ if not row:
201
+ return None
202
+ return hash_file(file_path) == row[0]
@@ -0,0 +1,276 @@
1
+ Metadata-Version: 2.4
2
+ Name: cjm-vad-adapter-interface
3
+ Version: 0.0.2
4
+ Summary: Typed voice-activity-detection task-adapter interface — VADAdapter ABC + GenericVADAdapter (cache/persist bookends around a pure-compute tool), the VADToolProtocol, and VAD persistence helpers. The VADResult data noun lives in cjm-capability-primitives.
5
+ Author-email: "Christian J. Mills" <9126128+cj-mills@users.noreply.github.com>
6
+ License: Apache-2.0
7
+ Project-URL: Repository, https://github.com/cj-mills/cjm-vad-adapter-interface
8
+ Project-URL: Documentation, https://cj-mills.github.io/cjm-vad-adapter-interface/
9
+ Keywords: nbdev
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Requires-Python: >=3.12
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: cjm_plugin_system>=0.0.46
16
+ Requires-Dist: cjm_capability_primitives>=0.0.3
17
+ Dynamic: license-file
18
+
19
+ # cjm-vad-adapter-interface
20
+
21
+
22
+ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
23
+
24
+ ## Install
25
+
26
+ ``` bash
27
+ pip install cjm_vad_adapter_interface
28
+ ```
29
+
30
+ ## Project Structure
31
+
32
+ nbs/
33
+ ├── adapter.ipynb # The typed voice-activity-detection task contract — the `VADAdapter` ABC + the `VADToolProtocol` structural contract (capability-unit Option C, pass-2 Thread 3).
34
+ ├── generic.ipynb # The generic (tool-agnostic) VAD adapter — cache-check, invoke the bound tool's pure-compute `detect_speech`, persist. Reused across every tool capability satisfying `VADToolProtocol`, exactly as `GenericTranscriptionAdapter` is reused across transcribers.
35
+ └── storage.ipynb # Standardized SQLite storage for voice-activity-detection results with content hashing.
36
+
37
+ Total: 3 notebooks
38
+
39
+ ## Module Dependencies
40
+
41
+ ``` mermaid
42
+ graph LR
43
+ adapter["adapter<br/>VAD Adapter"]
44
+ generic["generic<br/>Generic VAD Adapter"]
45
+ storage["storage<br/>VAD Storage"]
46
+
47
+ generic --> adapter
48
+ generic --> storage
49
+ ```
50
+
51
+ *2 cross-module dependencies detected*
52
+
53
+ ## CLI Reference
54
+
55
+ No CLI commands found in this project.
56
+
57
+ ## Module Overview
58
+
59
+ Detailed documentation for each module in the project:
60
+
61
+ ### VAD Adapter (`adapter.ipynb`)
62
+
63
+ > The typed voice-activity-detection task contract — the `VADAdapter`
64
+ > ABC + the `VADToolProtocol` structural contract (capability-unit
65
+ > Option C, pass-2 Thread 3).
66
+
67
+ #### Import
68
+
69
+ ``` python
70
+ from cjm_vad_adapter_interface.adapter import (
71
+ VADToolProtocol,
72
+ VADAdapter
73
+ )
74
+ ```
75
+
76
+ #### Classes
77
+
78
+ ``` python
79
+ @runtime_checkable
80
+ class VADToolProtocol(Protocol):
81
+ """
82
+ Structural contract for voice-activity-detection tool capabilities
83
+ (born-final at stage 8 — derived from the native tool surface).
84
+
85
+ Pure compute: `detect_speech` reads the model-ready audio + runs inference +
86
+ builds the typed result. `get_current_config` supplies the effective config
87
+ the generic adapter hashes for its cache key. Persistence is NOT here — the
88
+ adapter owns it (the native-surface seam).
89
+ """
90
+
91
+ def detect_speech(self, audio: Union[str, Path], **kwargs) -> VADResult: ...
92
+ def get_current_config(self) -> Dict[str, Any]: ...
93
+
94
+ def get_current_config(self) -> Dict[str, Any]: ...
95
+ ```
96
+
97
+ ``` python
98
+ class VADAdapter:
99
+ def __init__(
100
+ self,
101
+ tool: VADToolProtocol, # The bound tool capability instance (worker-side binding)
102
+ )
103
+ """
104
+ Typed voice-activity-detection task adapter: model-ready audio in,
105
+ `VADResult` out.
106
+
107
+ Input contract: the caller guarantees MODEL-READY audio — format /
108
+ sample-rate / channel handling happens upstream (ffmpeg `convert`), never
109
+ in the adapter or tool.
110
+
111
+ Native-surface model (stage 8 / PILLAR 1c): the TOOL is pure compute; the
112
+ ADAPTER owns the cache + persistence bookends (see `GenericVADAdapter`) +
113
+ the per-call `force` control. Storage resolves from the substrate-injected
114
+ `PLUGIN_DATA_DIR`; `db_path` is not on the tool protocol.
115
+
116
+ Implementations run in-worker beside their tool capability and are
117
+ constructed with the bound tool instance: `AdapterClass(tool)` (mirrors
118
+ `GraphStorageAdapter`). The result DTO is wire-registered ("vad.result"):
119
+ returned values cross the worker boundary typed.
120
+ """
121
+
122
+ def __init__(
123
+ self,
124
+ tool: VADToolProtocol, # The bound tool capability instance (worker-side binding)
125
+ )
126
+
127
+ def detect_speech(
128
+ self,
129
+ audio: Union[str, Path], # Path to MODEL-READY audio (converted upstream)
130
+ **kwargs, # Provenance + tool options
131
+ ) -> VADResult: # Typed VAD output
132
+ "Detect speech segments in model-ready audio."
133
+ ```
134
+
135
+ ### Generic VAD Adapter (`generic.ipynb`)
136
+
137
+ > The generic (tool-agnostic) VAD adapter — cache-check, invoke the
138
+ > bound tool’s pure-compute `detect_speech`, persist. Reused across
139
+ > every tool capability satisfying `VADToolProtocol`, exactly as
140
+ > `GenericTranscriptionAdapter` is reused across transcribers.
141
+
142
+ #### Import
143
+
144
+ ``` python
145
+ from cjm_vad_adapter_interface.generic import (
146
+ GenericVADAdapter
147
+ )
148
+ ```
149
+
150
+ #### Classes
151
+
152
+ ``` python
153
+ class GenericVADAdapter(VADAdapter):
154
+ """
155
+ Generic VAD adapter: cache-check -> pure-compute tool -> persist.
156
+
157
+ Works against ANY tool satisfying `VADToolProtocol`. The bookends:
158
+
159
+ 1. cache check (file_path + file_hash + config_hash) BEFORE invoking the
160
+ tool, so a hit never loads the model;
161
+ 2. the tool's pure-compute `detect_speech` on a miss / forced call;
162
+ 3. `save_with_logging` (upsert by file_path + config_hash).
163
+
164
+ `config_hash` reuses `hash_dict_canonical(get_current_config())` (the SAME
165
+ canonical hash the fused-era plugin used). `force` rides
166
+ `CallEnvelope.control` (not a task kwarg, keeping `detect_speech(audio)`
167
+ pure). Storage lives at `<PLUGIN_DATA_DIR>/vad.db`; the substrate injects
168
+ the per-capability `PLUGIN_DATA_DIR` at spawn, so the adapter neither
169
+ hard-codes a path nor asks the tool for one.
170
+ """
171
+
172
+ def detect_speech(
173
+ self,
174
+ audio: Union[str, Path], # Path to MODEL-READY audio (converted upstream)
175
+ **kwargs, # Provenance + tool options
176
+ ) -> VADResult: # Typed VAD output
177
+ "Cache-check, invoke the bound tool's pure-compute `detect_speech`, persist."
178
+ ```
179
+
180
+ ### VAD Storage (`storage.ipynb`)
181
+
182
+ > Standardized SQLite storage for voice-activity-detection results with
183
+ > content hashing.
184
+
185
+ #### Import
186
+
187
+ ``` python
188
+ from cjm_vad_adapter_interface.storage import (
189
+ VADRow,
190
+ VADStorage
191
+ )
192
+ ```
193
+
194
+ #### Classes
195
+
196
+ ``` python
197
+ @dataclass
198
+ class VADRow:
199
+ "A single row from the vad_results table."
200
+
201
+ file_path: str # Path to the analyzed (model-ready) audio file
202
+ file_hash: str # Hash of the analyzed file in "algo:hexdigest" format
203
+ config_hash: str # Hash of the VAD detection config used
204
+ ranges: Optional[List[Dict[str, Any]]] # Detected speech segments (serialized TimeRanges)
205
+ metadata: Optional[Dict[str, Any]] # VAD metadata
206
+ created_at: Optional[float] # Unix timestamp
207
+ ```
208
+
209
+ ``` python
210
+ class VADStorage:
211
+ def __init__(
212
+ self,
213
+ db_path: str # Absolute path to the SQLite database file
214
+ )
215
+ "Standardized SQLite storage for voice-activity-detection results."
216
+
217
+ def __init__(
218
+ self,
219
+ db_path: str # Absolute path to the SQLite database file
220
+ )
221
+ "Initialize storage and create table if needed."
222
+
223
+ def save(
224
+ self,
225
+ file_path: str, # Path to the analyzed audio file
226
+ file_hash: str, # Hash of the analyzed file in "algo:hexdigest" format
227
+ config_hash: str, # Hash of the VAD detection config
228
+ ranges: Optional[List[Dict[str, Any]]] = None, # Detected speech segments
229
+ metadata: Optional[Dict[str, Any]] = None # VAD metadata
230
+ ) -> None
231
+ "Save or replace a VAD result (upsert by file_path + config_hash)."
232
+
233
+ def save_with_logging(
234
+ self,
235
+ *,
236
+ file_path: str, # Path to the analyzed audio file
237
+ file_hash: str, # Hash of the analyzed file in "algo:hexdigest" format
238
+ config_hash: str, # Hash of the VAD detection config
239
+ ranges: Optional[List[Dict[str, Any]]] = None, # Detected speech segments
240
+ metadata: Optional[Dict[str, Any]] = None, # VAD metadata
241
+ logger: Optional[logging.Logger] = None # Optional logger for success/failure messages
242
+ ) -> bool: # True if saved; False if the save failed (error logged, not raised)
243
+ "Save a result, logging success/failure. Failures are logged and swallowed (returns False).
244
+
245
+ CR-14 follow-up: records a RESULT_SAVED account either way (ok flag +
246
+ file/config references — the journal never carries content) so saves AND
247
+ swallowed save-failures become auditable journal rows."
248
+
249
+ def get_cached(
250
+ self,
251
+ file_path: str, # Path to the audio file
252
+ file_hash: str, # Content hash of the file (cache miss if the file changed)
253
+ config_hash: str # Config hash to match
254
+ ) -> Optional[VADRow]: # Cached row or None
255
+ "Retrieve a content-correct cached VAD result.
256
+
257
+ Matches on file_path + file_hash + config_hash, so a changed file (new
258
+ file_hash) misses the cache even though a stale row may still exist at the
259
+ same (file_path, config_hash) — the next save() replaces it.
260
+
261
+ CR-14 follow-up: a hit records a CACHE_HIT account (the cache-serving
262
+ decision is an account-of-action)."
263
+
264
+ def list_jobs(
265
+ self,
266
+ limit: int = 100 # Maximum number of rows to return
267
+ ) -> List[VADRow]: # List of VAD rows
268
+ "List VAD results ordered by creation time (newest first)."
269
+
270
+ def verify_file(
271
+ self,
272
+ file_path: str, # Path to the audio file
273
+ config_hash: str # Config hash to look up
274
+ ) -> Optional[bool]: # True if file matches, False if changed, None if not found
275
+ "Verify the analyzed file still matches the hash stored for (file_path, config_hash)."
276
+ ```
@@ -0,0 +1,11 @@
1
+ cjm_vad_adapter_interface/__init__.py,sha256=QvlVh4JTl3JL7jQAja76yKtT-IvF4631ASjWY1wS6AQ,22
2
+ cjm_vad_adapter_interface/_modidx.py,sha256=iinf7Q-Nl57nr8ntxOlyUd1PJLa7LD5COIwn_DOsb18,5459
3
+ cjm_vad_adapter_interface/adapter.py,sha256=_gSHnymILAg4PKdESs0zRM5kG76iaK2b3xjKtQc5vIM,2987
4
+ cjm_vad_adapter_interface/generic.py,sha256=xf9c7F5O7qblB8kTYLpUFwIY-586lgD-RJe5BDEOavc,3530
5
+ cjm_vad_adapter_interface/storage.py,sha256=HGfV6kDsvTrMDyUI11TDqrAmg6htXuxiwrxYUBCmMyE,8444
6
+ cjm_vad_adapter_interface-0.0.2.dist-info/licenses/LICENSE,sha256=xV8xoN4VOL0uw9X8RSs2IMuD_Ss_a9yAbtGNeBWZwnw,11337
7
+ cjm_vad_adapter_interface-0.0.2.dist-info/METADATA,sha256=59uwvqM1rVnigLP_KVqK5w6zx4graeF9JkxmYC8oNmQ,10172
8
+ cjm_vad_adapter_interface-0.0.2.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
9
+ cjm_vad_adapter_interface-0.0.2.dist-info/entry_points.txt,sha256=GQMGeeaMpvhurqAf0_YAvBOcPvCt68mulFT6LTDG5F4,72
10
+ cjm_vad_adapter_interface-0.0.2.dist-info/top_level.txt,sha256=RiHRnpS0UJUNYsKvGcwtCYv0-WafF84rVofUIo00p6I,26
11
+ cjm_vad_adapter_interface-0.0.2.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [nbdev]
2
+ cjm_vad_adapter_interface = cjm_vad_adapter_interface._modidx:d
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2022, fastai
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1 @@
1
+ cjm_vad_adapter_interface