lore-ai 0.1.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.
__init__.py ADDED
File without changes
audio/normalise.py ADDED
@@ -0,0 +1,45 @@
1
+ import subprocess
2
+ from pathlib import Path
3
+ import imageio_ffmpeg
4
+
5
+
6
+ class AudioNormaliseError(Exception):
7
+ """Raised when audio normalization fails."""
8
+
9
+ pass
10
+
11
+
12
+ def normalise(input_path: Path, output_path: Path) -> None:
13
+ """
14
+ Normalise audio to 16kHz mono PCM with EBU R128 loudness normalisation.
15
+ This is required for optimal faster-whisper transcription of archival audio.
16
+ """
17
+ ffmpeg_exe = imageio_ffmpeg.get_ffmpeg_exe()
18
+
19
+ cmd = [
20
+ ffmpeg_exe,
21
+ "-y", # Overwrite output files
22
+ "-i",
23
+ str(input_path),
24
+ "-af",
25
+ "loudnorm", # EBU R128 loudness normalization
26
+ "-ar",
27
+ "16000", # 16 kHz sample rate
28
+ "-ac",
29
+ "1", # Mono (1 channel)
30
+ "-acodec",
31
+ "pcm_s16le", # 16-bit PCM
32
+ str(output_path),
33
+ ]
34
+
35
+ try:
36
+ # Run ffmpeg subprocess, capturing output for error reporting
37
+ subprocess.run(
38
+ cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
39
+ )
40
+ except subprocess.CalledProcessError as e:
41
+ raise AudioNormaliseError(
42
+ f"FFmpeg failed with exit code {e.returncode}:\n{e.stderr}"
43
+ )
44
+ except Exception as e:
45
+ raise AudioNormaliseError(f"Failed to execute FFmpeg: {str(e)}")
audio/player.py ADDED
@@ -0,0 +1,49 @@
1
+ from PyQt6.QtCore import QObject, pyqtSignal, QUrl
2
+ from PyQt6.QtMultimedia import QMediaPlayer, QAudioOutput
3
+
4
+
5
+ class AudioPlayer(QObject):
6
+ """
7
+ AudioPlayer wraps QMediaPlayer to provide precise playback control
8
+ and frequent position updates for UI syncing.
9
+ """
10
+
11
+ position_changed = pyqtSignal(int)
12
+ duration_changed = pyqtSignal(int)
13
+ state_changed = pyqtSignal(QMediaPlayer.PlaybackState)
14
+
15
+ def __init__(self, parent=None):
16
+ super().__init__(parent)
17
+ self._player = QMediaPlayer(self)
18
+ self._audio_output = QAudioOutput(self)
19
+ self._player.setAudioOutput(self._audio_output)
20
+
21
+ # Fire position_changed every 50ms for tight waveform/transcript sync
22
+ self._player.positionChanged.connect(self.position_changed.emit)
23
+ self._player.durationChanged.connect(self.duration_changed.emit)
24
+ self._player.playbackStateChanged.connect(self.state_changed.emit)
25
+
26
+ # In PyQt6, notify interval can be set via QTimer, but QMediaPlayer handles it intrinsically or via positionChanged
27
+ # Actually QMediaPlayer in Qt6 emits positionChanged rapidly during playback.
28
+
29
+ def load(self, file_path: str):
30
+ self._player.setSource(QUrl.fromLocalFile(file_path))
31
+
32
+ def play(self):
33
+ self._player.play()
34
+
35
+ def pause(self):
36
+ self._player.pause()
37
+
38
+ def seek(self, ms: int):
39
+ self._player.setPosition(ms)
40
+
41
+ def position_ms(self) -> int:
42
+ return self._player.position()
43
+
44
+ def duration_ms(self) -> int:
45
+ return self._player.duration()
46
+
47
+ def set_volume(self, volume: float):
48
+ """Volume between 0.0 and 1.0"""
49
+ self._audio_output.setVolume(volume)
@@ -0,0 +1,150 @@
1
+ Metadata-Version: 2.4
2
+ Name: lore-ai
3
+ Version: 0.1.2
4
+ Summary: Privacy-first, local-only oral history transcription.
5
+ Author: Digital Heritage Lab
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/mabo-du/lore
8
+ Project-URL: Documentation, https://github.com/mabo-du/lore/blob/main/USER_GUIDE.md
9
+ Project-URL: Repository, https://github.com/mabo-du/lore.git
10
+ Project-URL: Issue Tracker, https://github.com/mabo-du/lore/issues
11
+ Keywords: oral-history,transcription,whisper,archival,offline
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Education
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
20
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
+ Requires-Python: >=3.12
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: faster-whisper
25
+ Requires-Dist: PyQt6
26
+ Requires-Dist: imageio-ffmpeg
27
+ Requires-Dist: platformdirs
28
+ Requires-Dist: lxml
29
+ Requires-Dist: numpy
30
+ Requires-Dist: tsdownsample
31
+ Requires-Dist: pyannote-audio==3.3.2
32
+ Requires-Dist: resemblyzer>=0.1.4
33
+ Requires-Dist: gliner2-onnx>=0.1.1
34
+ Requires-Dist: llama-cpp-python>=0.3.25
35
+ Requires-Dist: sqlite-vec>=0.1.9
36
+ Requires-Dist: fastembed>=0.8.0
37
+ Requires-Dist: cryptography>=42.0
38
+ Provides-Extra: diarization
39
+ Requires-Dist: pyannote-audio; extra == "diarization"
40
+ Requires-Dist: Resemblyzer; extra == "diarization"
41
+ Dynamic: license-file
42
+
43
+ <div align="center">
44
+ <img src="https://img.shields.io/badge/Local_First-100%25-brightgreen.svg?style=for-the-badge" alt="Local First">
45
+ <img src="https://img.shields.io/badge/Python-3.12+-blue.svg?style=for-the-badge&logo=python" alt="Python 3.12+">
46
+ <img src="https://img.shields.io/badge/PyQt6-UI-blueviolet.svg?style=for-the-badge" alt="PyQt6">
47
+ <img src="https://img.shields.io/badge/License-MIT-yellow.svg?style=for-the-badge" alt="MIT License">
48
+ <img src="https://img.shields.io/github/actions/workflow/status/mabo-du/lore/ci.yml?branch=main&style=for-the-badge" alt="CI">
49
+ <img src="https://img.shields.io/pypi/v/lore-ai.svg?style=for-the-badge" alt="PyPI">
50
+
51
+ <h1>Lore 🎙️</h1>
52
+
53
+ <p><strong>Privacy-First, Local-Only Oral History Transcription & Archiving</strong></p>
54
+ </div>
55
+
56
+ ---
57
+
58
+ **Lore** is a desktop application designed for historians, archivists, and researchers. It provides state-of-the-art AI transcription, speaker diarization, named entity recognition, and translation—**100% offline, on your own hardware.**
59
+
60
+ No data leaves your computer. No cloud subscriptions. Just powerful, open-source AI packaged into a clean, intuitive PyQt6 interface.
61
+
62
+ <img src="https://raw.githubusercontent.com/mabo-du/lore/main/docs/images/lore_main.png" alt="Lore Main Window" width="800">
63
+
64
+ ## ✨ Features
65
+
66
+ - 🎧 **Offline Transcription:** Powered by `faster-whisper`, optimized for CPU inference with low memory overhead (< 8GB RAM).
67
+ - 🗣️ **Speaker Diarization:** Automatically identifies and labels different speakers using `pyannote.audio`.
68
+ - 🔍 **Word-Level Confidence:** Low-confidence words are visually highlighted so you can quickly spot potential hallucinations.
69
+ - 🌍 **Local Translation:** Translate transcripts to over 200 languages completely offline using Meta's `NLLB-200` model.
70
+ - 📖 **Custom Vocabulary:** Provide local jargon, proper nouns, and historical terms to guide Whisper's decoding graph for maximum accuracy.
71
+ - 🏷️ **Named Entity Recognition:** Uses `GLiNER` to automatically extract people, organizations, dates, and locations.
72
+ - 📦 **Archival Exporting:** Export your work to the **OHMS XML** format or create an **RFC 8493 BagIt** archival package with SHA-256 checksum verification.
73
+ - 🔎 **Global Archive Search:** A unified SQLite database (`FTS5` + `sqlite-vec`) lets you instantly search across all your past projects using keyword or semantic/conceptual search.
74
+
75
+ ## 🚀 Installation
76
+
77
+ ### Option 1: Pre-built Installers (Recommended)
78
+
79
+ Download the installer for your platform from the [latest release](https://github.com/mabo-du/lore/releases/latest):
80
+
81
+ | Platform | Installer |
82
+ |----------|-----------|
83
+ | 🪟 **Windows** | `lore-windows-x86_64.zip` — Extract and run `lore.exe` |
84
+ | 🍎 **macOS** | `lore-macos-arm64.tar.gz` — Extract and run `lore` |
85
+ | 🐧 **Linux** | `lore-linux-x86_64.tar.gz` — Extract and run `lore` |
86
+
87
+ ### Option 2: Install from PyPI
88
+
89
+ ```bash
90
+ pip install lore-ai
91
+ lore
92
+ ```
93
+
94
+ ### Option 3: Install from Source
95
+
96
+ Lore requires **Python 3.12+** and is cross-platform (Windows, macOS, Linux).
97
+
98
+ 1. **Clone the repository:**
99
+ ```bash
100
+ git clone https://github.com/mabo-du/lore.git
101
+ cd lore
102
+ ```
103
+
104
+ 2. **Set up a virtual environment:**
105
+ ```bash
106
+ python -m venv .venv
107
+ source .venv/bin/activate # On Windows: .venv\Scripts\activate
108
+ ```
109
+
110
+ 3. **Install the application:**
111
+ ```bash
112
+ pip install -e .
113
+ ```
114
+
115
+ ## 🎮 Usage
116
+
117
+ Start the Lore application:
118
+
119
+ ```bash
120
+ lore
121
+ ```
122
+
123
+ Or launch from your system's application menu if installed via the pre-built installer.
124
+
125
+ 1. **Select an Audio File:** Click "Browse" to select any standard audio format (WAV, MP3, M4A, OGG, FLAC).
126
+ 2. **Configure Settings:** Click the ⚙️ Settings icon to set your Custom Vocabulary and speaker diarization preferences.
127
+
128
+ <img src="https://raw.githubusercontent.com/mabo-du/lore/main/docs/images/lore_settings.png" alt="Lore Settings" width="400">
129
+
130
+ 3. **Transcribe & Diarize:** Click "Transcribe" on the toolbar. If recording has multiple speakers, check the "Enable Speaker Diarization" box.
131
+ 4. **Edit & Review:** Play the audio, click on segments to edit them, and review any low-confidence words highlighted in red.
132
+ 5. **Translate:** Select a target language from the dropdown and click "Translate" for fully offline translation.
133
+ 6. **Export:** Fill out the Metadata panel and export to **OHMS XML** or an Archival **BagIt Package**.
134
+
135
+ For detailed instructions, see the [User Guide](USER_GUIDE.md).
136
+
137
+ ## 🏗️ Architecture
138
+
139
+ Lore is designed with strict sequential memory management to run on older hardware.
140
+ - Models are loaded into memory one at a time (e.g., Whisper loads, transcribes, unloads → NLLB loads, translates, unloads).
141
+ - Heavy use of CTranslate2 (INT8 quantization) ensures models run blazingly fast without needing a dedicated GPU.
142
+ - The UI runs asynchronously using PyQt6's `QThread` and Signals, keeping the interface completely responsive during heavy AI workloads.
143
+
144
+ ## 🤝 Contributing
145
+
146
+ Lore is an open-source project. We welcome pull requests, bug reports, and feature requests. Please see our [User Guide](USER_GUIDE.md) for more detailed workflows and documentation on the codebase.
147
+
148
+ ## 📜 License
149
+
150
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
@@ -0,0 +1,34 @@
1
+ __init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ main.py,sha256=spCRCxWGemZ_-HEevm_YsaK4HzX6tGdxTxI_mwbptfI,498
3
+ audio/normalise.py,sha256=9cAraDZLmtZLRK2k8EWqa8l5fBijW0gVNLSJJuFykR0,1283
4
+ audio/player.py,sha256=UI5wJ3GBJMcxBk46HBXxBUqjUjLk1KRewuCH5LGxbsM,1684
5
+ lore_ai-0.1.2.dist-info/licenses/LICENSE,sha256=w-C0_pWcTlDR35tDQTYslatZ-F98zvvXBbTIRhUEjF8,1074
6
+ lore_core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ lore_core/audio_classifier.py,sha256=JYbQoiixuCFxHp3qi1KkIRgcJmDFpI4jfd13dqyApTs,4518
8
+ lore_core/bagit_exporter.py,sha256=fTTj1v6dsYhIaBzQZBeWAzYEqNBdP20iZkgbVtWSz04,3283
9
+ lore_core/diarization.py,sha256=dqV7Up3IrNmULR3-e2JhKijvMex2_6MO-3aohECmktM,4881
10
+ lore_core/engine.py,sha256=6ORbGtPJ-G9-uak3w4gQikqLmHcfpDdU3ogmqmoh6PM,2376
11
+ lore_core/global_search.py,sha256=qqgBvVaIutHcQ1uC1fXNywxLqNaR1WXaQwpTQDecHo0,7056
12
+ lore_core/languages.py,sha256=-fybKmEuCIQxxuZvdC-0aq_D7JFrAIdN3gQNkjgS99w,1319
13
+ lore_core/llm_worker.py,sha256=aKmi1ad5Ivqrc45XB0FuH4LMyyleJkHaJBOfnAgvdo8,3215
14
+ lore_core/ner_worker.py,sha256=h-p4oC1o3xaIY-D__2eaSJ_euSwZBKrs49mKmV4Eod8,2730
15
+ lore_core/ohms_exporter.py,sha256=_G_CYfzILsDybggyO84WN7_VsginSSqNL8McyuiGHQ0,6024
16
+ lore_core/rag_worker.py,sha256=j4hO0SsMKW6-Y7B1sV6VlvF9kJnHZK1hFncbBJ7_hgE,3123
17
+ lore_core/taxonomy_manager.py,sha256=bbp90orKk-hieqn-7LhFRhqOKBtJimLMZ-e0-9tvizE,5143
18
+ lore_core/translation_worker.py,sha256=DQpd11BcXAYkrd4tygYaXV9OHMbLOpHGBnD2T6nyP-U,3970
19
+ lore_core/exporters/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
20
+ transcription/worker.py,sha256=eQ7aKjwwnvgfm1mx9NzTiurbok4FVYyvkP6Wv_k62e0,3475
21
+ ui/file_picker.py,sha256=39JwM4_jyqOMt5uf6j5pweR2vrG87FENxq7FmWleLd4,3387
22
+ ui/global_search_dialog.py,sha256=jFZ_4UXS9D41I0R56mKzm8rhRAGZox22RGa9y4ErAck,5246
23
+ ui/main_window.py,sha256=hFxHoE0_0_wMNfcXBm-XJ9a9tv8EcogmxeQUysd88l8,18115
24
+ ui/metadata_widget.py,sha256=EzO-2uDlleDRrEBf_hrsViM0kLLsDEm8Lrgis04lqiI,4714
25
+ ui/settings_dialog.py,sha256=5hs4SF1VB43W-PQ7xsr_6XhON9VkOcIJhkn9096vSmc,4629
26
+ ui/transcript_widget.py,sha256=dsIDhj-xxNPad2rv_N1TDjjjnyRk0Owvva3Xkg2oAKg,8526
27
+ ui/waveform_widget.py,sha256=yvCBl1v0_G5nKgwKoYoVX7AzT-dabIOn5Nt8GbBG0UU,5014
28
+ utils/model_manager.py,sha256=c2V-8KjxPOqbVz9E_LuVUiBPHjtbZZyAfokzApB8sWY,4209
29
+ utils/token_vault.py,sha256=9jEvmY0jPDVyc7qgJVT1epnuhrKMoYC0UoOEqFbaX48,1692
30
+ lore_ai-0.1.2.dist-info/METADATA,sha256=sqO3Lvp3M8_6AGuCJq4WnQE778uFuvx3Xx7mRNEmIqg,6916
31
+ lore_ai-0.1.2.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
32
+ lore_ai-0.1.2.dist-info/entry_points.txt,sha256=Dmpa-951VDrnOQeHc2KGQKYzUA6CiTH5AFlJmWgEicw,39
33
+ lore_ai-0.1.2.dist-info/top_level.txt,sha256=uPjWM9Tov2ewh98GMSFo8VsaW2nCSYvYkCzgBOk3_iw,53
34
+ lore_ai-0.1.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
+ [console_scripts]
2
+ lore = src.main:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Lore Contributors
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,7 @@
1
+ __init__
2
+ audio
3
+ lore_core
4
+ main
5
+ transcription
6
+ ui
7
+ utils
lore_core/__init__.py ADDED
File without changes
@@ -0,0 +1,126 @@
1
+ from pathlib import Path
2
+ import wave
3
+ import numpy as np
4
+ import onnxruntime as ort
5
+ from PyQt6.QtCore import QThread, pyqtSignal
6
+
7
+ from models.transcript import Segment
8
+ from utils.model_manager import ModelManager
9
+
10
+
11
+ class AudioClassifyWorker(QThread):
12
+ """
13
+ Runs YAMNet Audio Classification in a background thread to detect Non-Verbal events.
14
+ Emits events like [Laughter] and [Crying].
15
+ """
16
+
17
+ event_detected = pyqtSignal(Segment)
18
+ finished = pyqtSignal()
19
+ error = pyqtSignal(str)
20
+
21
+ def __init__(self, audio_path: Path, parent=None):
22
+ super().__init__(parent)
23
+ self.audio_path = audio_path
24
+ # We only care about laughter and crying indices
25
+ self.target_indices = {
26
+ 13: "Laughter",
27
+ 14: "Laughter",
28
+ 17: "Laughter",
29
+ 19: "Crying",
30
+ 20: "Crying",
31
+ }
32
+ self.threshold = 0.35 # Confidence threshold
33
+
34
+ def run(self):
35
+ try:
36
+ model_path_str = ModelManager.ensure_model("YAMNet")
37
+ onnx_file = Path(model_path_str) / "yamnet.onnx"
38
+
39
+ # CPU only
40
+ session = ort.InferenceSession(
41
+ str(onnx_file), providers=["CPUExecutionProvider"]
42
+ )
43
+ input_name = session.get_inputs()[0].name
44
+
45
+ # Read 16kHz Mono PCM Audio
46
+ with wave.open(str(self.audio_path), "rb") as wf:
47
+ framerate = wf.getframerate()
48
+ if framerate != 16000:
49
+ raise ValueError(f"YAMNet requires 16000Hz, got {framerate}Hz")
50
+ if wf.getnchannels() != 1:
51
+ raise ValueError("YAMNet requires Mono audio")
52
+
53
+ n_frames = wf.getnframes()
54
+ audio_data = wf.readframes(n_frames)
55
+
56
+ # Convert to float32 [-1.0, 1.0]
57
+ audio_np = (
58
+ np.frombuffer(audio_data, dtype=np.int16).astype(np.float32) / 32768.0
59
+ )
60
+
61
+ # YAMNet can process arbitrary length 1D array
62
+ outputs = session.run(None, {input_name: audio_np})
63
+ scores = outputs[0] # Shape (N, 521)
64
+
65
+ # Each frame in YAMNet is roughly 0.48s hop size
66
+ hop_size_s = 0.48
67
+
68
+ # Process frames and merge contiguous events of the same type
69
+ current_event = None
70
+ current_start_s = 0.0
71
+
72
+ for frame_idx, frame_scores in enumerate(scores):
73
+ frame_time_s = frame_idx * hop_size_s
74
+
75
+ # Find the target class with the highest score above threshold
76
+ best_class = None
77
+ best_score = 0.0
78
+ for idx, label in self.target_indices.items():
79
+ if (
80
+ frame_scores[idx] > self.threshold
81
+ and frame_scores[idx] > best_score
82
+ ):
83
+ best_score = frame_scores[idx]
84
+ best_class = label
85
+
86
+ if best_class:
87
+ if current_event == best_class:
88
+ # Continue event
89
+ pass
90
+ else:
91
+ # Close previous event if exists
92
+ if current_event:
93
+ self._emit_event(
94
+ current_event, current_start_s, frame_time_s
95
+ )
96
+ # Start new event
97
+ current_event = best_class
98
+ current_start_s = frame_time_s
99
+ else:
100
+ if current_event:
101
+ # Close previous event
102
+ self._emit_event(current_event, current_start_s, frame_time_s)
103
+ current_event = None
104
+
105
+ # Close hanging event
106
+ if current_event:
107
+ self._emit_event(
108
+ current_event, current_start_s, (len(scores)) * hop_size_s
109
+ )
110
+
111
+ self.finished.emit()
112
+
113
+ except Exception as e:
114
+ self.error.emit(str(e))
115
+
116
+ def _emit_event(self, event_label: str, start_s: float, end_s: float):
117
+ # Only emit events that last at least 0.5s to avoid spurious noise
118
+ duration = end_s - start_s
119
+ if duration >= 0.48:
120
+ segment = Segment(
121
+ start_ms=int(start_s * 1000),
122
+ end_ms=int(end_s * 1000),
123
+ text=f"[{event_label}]",
124
+ speaker_label="SYSTEM",
125
+ )
126
+ self.event_detected.emit(segment)
@@ -0,0 +1,88 @@
1
+ import shutil
2
+ import hashlib
3
+ from pathlib import Path
4
+ from datetime import datetime
5
+ from models.transcript import Transcript
6
+ from lore_core.ohms_exporter import OhmsExporter
7
+
8
+
9
+ class BagItPackager:
10
+ """
11
+ Creates a BagIt (RFC 8493) compliant package for the transcript and audio.
12
+ """
13
+
14
+ def __init__(self):
15
+ self.version = "1.0"
16
+ self.encoding = "UTF-8"
17
+
18
+ def _hash_file(self, file_path: Path) -> str:
19
+ """Calculate SHA-256 hash of a file."""
20
+ hasher = hashlib.sha256()
21
+ with open(file_path, "rb") as f:
22
+ for chunk in iter(lambda: f.read(4096), b""):
23
+ hasher.update(chunk)
24
+ return hasher.hexdigest()
25
+
26
+ def create_bag(
27
+ self,
28
+ audio_path: Path,
29
+ transcript: Transcript,
30
+ output_dir: Path,
31
+ project_id: str,
32
+ ):
33
+ """
34
+ Generates a BagIt structure at output_dir.
35
+ """
36
+ output_dir = Path(output_dir)
37
+ bag_dir = output_dir / f"lore_bag_{project_id}"
38
+
39
+ # Ensure we start clean
40
+ if bag_dir.exists():
41
+ shutil.rmtree(bag_dir)
42
+
43
+ bag_dir.mkdir(parents=True)
44
+ data_dir = bag_dir / "data"
45
+ data_dir.mkdir()
46
+
47
+ # 1. Copy audio payload
48
+ bag_audio_path = data_dir / audio_path.name
49
+ shutil.copy2(audio_path, bag_audio_path)
50
+
51
+ # 2. Export OHMS XML payload
52
+ bag_xml_path = data_dir / "transcript.xml"
53
+ OhmsExporter.export(transcript, {"title": project_id}, bag_xml_path)
54
+
55
+ # 3. Create bagit.txt
56
+ with open(bag_dir / "bagit.txt", "w", encoding="utf-8") as f:
57
+ f.write(f"BagIt-Version: {self.version}\n")
58
+ f.write(f"Tag-File-Character-Encoding: {self.encoding}\n")
59
+
60
+ # 4. Create bag-info.txt
61
+ with open(bag_dir / "bag-info.txt", "w", encoding="utf-8") as f:
62
+ f.write("Source-Organization: Lore Oral History App\n")
63
+ f.write(f"Bagging-Date: {datetime.now().strftime('%Y-%m-%d')}\n")
64
+ f.write(f"External-Identifier: {project_id}\n")
65
+ # Calculate total payload size and oxum
66
+ audio_size = bag_audio_path.stat().st_size
67
+ xml_size = bag_xml_path.stat().st_size
68
+ total_size = audio_size + xml_size
69
+ f.write(f"Payload-Oxum: {total_size}.2\n")
70
+ f.write(f"Bag-Size: {total_size / (1024 * 1024):.2f} MB\n")
71
+
72
+ # 5. Create payload manifest (manifest-sha256.txt)
73
+ with open(bag_dir / "manifest-sha256.txt", "w", encoding="utf-8") as f:
74
+ audio_hash = self._hash_file(bag_audio_path)
75
+ xml_hash = self._hash_file(bag_xml_path)
76
+ f.write(f"{audio_hash} data/{bag_audio_path.name}\n")
77
+ f.write(f"{xml_hash} data/transcript.xml\n")
78
+
79
+ # 6. Create tag manifest (tagmanifest-sha256.txt)
80
+ with open(bag_dir / "tagmanifest-sha256.txt", "w", encoding="utf-8") as f:
81
+ bagit_hash = self._hash_file(bag_dir / "bagit.txt")
82
+ baginfo_hash = self._hash_file(bag_dir / "bag-info.txt")
83
+ manifest_hash = self._hash_file(bag_dir / "manifest-sha256.txt")
84
+ f.write(f"{bagit_hash} bagit.txt\n")
85
+ f.write(f"{baginfo_hash} bag-info.txt\n")
86
+ f.write(f"{manifest_hash} manifest-sha256.txt\n")
87
+
88
+ return bag_dir
@@ -0,0 +1,130 @@
1
+ from pathlib import Path
2
+ from typing import List, Tuple, Optional
3
+
4
+ # We import these inside the functions to avoid massive load times or crashes if missing
5
+
6
+
7
+ class DiarizationEngine:
8
+ def __init__(self, use_pyannote: bool = False, hf_token: Optional[str] = None):
9
+ self.use_pyannote = use_pyannote
10
+ self.hf_token = hf_token
11
+
12
+ def run_diarization(self, audio_path: Path) -> List[Tuple[float, float, str]]:
13
+ """
14
+ Runs diarization on the given audio file.
15
+ Returns a list of (start_s, end_s, speaker_label) tuples.
16
+ """
17
+ if self.use_pyannote:
18
+ return self._run_pyannote(audio_path)
19
+ else:
20
+ return self._run_resemblyzer(audio_path)
21
+
22
+ def _run_pyannote(self, audio_path: Path) -> List[Tuple[float, float, str]]:
23
+ if not self.hf_token:
24
+ raise ValueError("HuggingFace token is required for Pyannote.")
25
+
26
+ import torch
27
+ from pyannote.audio import Pipeline
28
+
29
+ # Initialize pipeline (loads from HuggingFace cache or downloads if missing)
30
+ pipeline = Pipeline.from_pretrained(
31
+ "pyannote/speaker-diarization-3.1", use_auth_token=self.hf_token
32
+ )
33
+
34
+ if pipeline is None:
35
+ raise RuntimeError(
36
+ "Failed to load Pyannote pipeline. Check your token and license acceptance."
37
+ )
38
+
39
+ # Send to CPU (or GPU if available, but we'll stick to CPU for reliability)
40
+ pipeline.to(torch.device("cpu"))
41
+
42
+ diarization = pipeline(str(audio_path))
43
+
44
+ results = []
45
+ for turn, _, speaker in diarization.itertracks(yield_label=True):
46
+ results.append((turn.start, turn.end, speaker))
47
+
48
+ return results
49
+
50
+ def _run_resemblyzer(self, audio_path: Path) -> List[Tuple[float, float, str]]:
51
+ """
52
+ Lightweight, ungated fallback using Resemblyzer.
53
+ Since Resemblyzer is just an embedding extractor, we cluster the embeddings manually.
54
+ """
55
+ from resemblyzer import VoiceEncoder, preprocess_wav
56
+ from sklearn.cluster import KMeans
57
+
58
+ encoder = VoiceEncoder("cpu")
59
+ wav = preprocess_wav(str(audio_path))
60
+
61
+ # Extract embeddings using a sliding window.
62
+ _, cont_embeds, wav_splits = encoder.embed_utterance(
63
+ wav, return_partials=True, rate=16
64
+ )
65
+
66
+ if len(cont_embeds) == 0:
67
+ return [(0.0, len(wav) / 16000.0, "SPEAKER_00")]
68
+
69
+ # We assume 2 speakers for oral history by default in Resemblyzer fallback
70
+ clusterer = KMeans(n_clusters=2, n_init=10, random_state=42)
71
+ labels = clusterer.fit_predict(cont_embeds)
72
+
73
+ # Guard against length mismatch between embeddings and wav_splits
74
+ if len(cont_embeds) != len(wav_splits):
75
+ return [(0.0, len(wav) / 16000.0, "SPEAKER_00")]
76
+
77
+ results = []
78
+ # Reconstruct timestamps based on wav_splits which are in samples
79
+ sample_rate = 16000
80
+ for (split, label) in zip(wav_splits, labels):
81
+ start_s = split.start / sample_rate
82
+ end_s = split.stop / sample_rate
83
+ speaker = f"SPEAKER_{label:02d}"
84
+
85
+ # Merge contiguous segments with same speaker
86
+ if (
87
+ results
88
+ and results[-1][2] == speaker
89
+ and (start_s - results[-1][1] < 0.5)
90
+ ):
91
+ results[-1] = (results[-1][0], end_s, speaker)
92
+ else:
93
+ results.append((start_s, end_s, speaker))
94
+
95
+ return results
96
+
97
+ @staticmethod
98
+ def align_speakers_to_segments(
99
+ segments: List["Segment"], # noqa: F821
100
+ diarization_results: List[Tuple[float, float, str]],
101
+ ) -> None:
102
+ """
103
+ Aligns coarse speaker turns to fine-grained ASR segments.
104
+ Modifies the 'speaker_label' property of the provided Segments in place.
105
+ """
106
+ if not diarization_results:
107
+ return
108
+
109
+ for seg in segments:
110
+ seg_mid = (seg.start_ms + seg.end_ms) / 2000.0 # Midpoint in seconds
111
+
112
+ # Find which diarization segment contains this midpoint
113
+ assigned_speaker = None
114
+ for d_start, d_end, speaker in diarization_results:
115
+ if d_start <= seg_mid <= d_end:
116
+ assigned_speaker = speaker
117
+ break
118
+
119
+ # If the midpoint falls in a gap, find the closest segment
120
+ if not assigned_speaker:
121
+ closest_speaker = None
122
+ min_dist = float("inf")
123
+ for d_start, d_end, speaker in diarization_results:
124
+ dist = min(abs(d_start - seg_mid), abs(d_end - seg_mid))
125
+ if dist < min_dist:
126
+ min_dist = dist
127
+ closest_speaker = speaker
128
+ assigned_speaker = closest_speaker
129
+
130
+ seg.speaker_label = assigned_speaker