Реализовал offline diarization вместо одной заглушки.
This commit is contained in:
parent
f59d348754
commit
a5665f6739
15
README.md
15
README.md
|
|
@ -12,7 +12,7 @@ Local pipeline for processing call recordings on Windows and Linux.
|
|||
- Normalizes audio to WAV PCM 16 kHz mono before transcription.
|
||||
- Detects silence spans and retries long or gappy transcripts with overlapping chunks.
|
||||
- Transcribes audio with Faster-Whisper.
|
||||
- Adds placeholder diarization and emotion artifacts.
|
||||
- Adds optional offline WhisperX/pyannote diarization and placeholder emotion artifacts.
|
||||
- Produces rule-based scorecard classification.
|
||||
- Exports results as JSON, CSV, and Markdown.
|
||||
|
||||
|
|
@ -21,7 +21,7 @@ Local pipeline for processing call recordings on Windows and Linux.
|
|||
- Local file source only.
|
||||
- SQLite state tracking.
|
||||
- Faster-Whisper transcription.
|
||||
- Placeholder diarization and emotion.
|
||||
- Optional offline diarization and placeholder emotion.
|
||||
- Rule-based classification.
|
||||
- JSON, CSV, and Markdown exports.
|
||||
|
||||
|
|
@ -63,6 +63,7 @@ Example paths in `configs/example.toml`:
|
|||
- `processing.direction_filter` controls whether the pipeline processes `incoming`, `outgoing`, or `all` calls.
|
||||
- `validation.min_duration_seconds` sets the minimum audio length accepted for processing.
|
||||
- `audio_preprocess` controls normalization, silence detection, chunk size, overlap, and the optional forced-alignment fallback.
|
||||
- `diarization` controls optional speaker diarization. Runtime is offline: configure `backend = "whisperx"` and point `model_path` at a local pyannote/WhisperX-compatible diarization pipeline directory before setting `enabled = true`.
|
||||
|
||||
The default config lives at [`configs/example.toml`](configs/example.toml). Keep custom config values absolute as well.
|
||||
|
||||
|
|
@ -98,7 +99,13 @@ The default config lives at [`configs/example.toml`](configs/example.toml). Keep
|
|||
./.venv/bin/b24calls transcribe
|
||||
```
|
||||
|
||||
6. Export final artifacts.
|
||||
6. Optionally run or re-run diarization for completed transcripts.
|
||||
|
||||
```bash
|
||||
./.venv/bin/b24calls diarize --force
|
||||
```
|
||||
|
||||
7. Export final artifacts.
|
||||
|
||||
```bash
|
||||
./.venv/bin/b24calls export --formats json,csv,markdown
|
||||
|
|
@ -114,6 +121,7 @@ For a complete end-to-end local smoke run, execute the commands in this order af
|
|||
- `spool` - stages validated files into spool.
|
||||
- `transcribe` - runs Faster-Whisper and writes transcript artifacts.
|
||||
- `transcribe` also writes preprocessing metadata and uses chunked retry when the first pass leaves large gaps.
|
||||
- `diarize` - updates only the top-level `diarization` object inside completed transcript JSON artifacts.
|
||||
- `export` - renders JSON, CSV, and Markdown outputs.
|
||||
- `process`, `run-once` - reserved for later orchestration.
|
||||
|
||||
|
|
@ -129,6 +137,7 @@ The pipeline writes artifacts under the configured output directory.
|
|||
SQLite tracks artifact records for these files in the `artifacts` table.
|
||||
|
||||
The transcript and export payloads include the source direction so downstream reporting can distinguish incoming and outgoing calls.
|
||||
When enabled, diarization is stored as a separate top-level `diarization` object; existing source metadata, preprocessing metadata, and transcription payloads are left unchanged.
|
||||
|
||||
## Developer Workflow
|
||||
|
||||
|
|
|
|||
|
|
@ -46,6 +46,16 @@ forced_alignment_enabled = false
|
|||
forced_alignment_gap_threshold_seconds = 10.0
|
||||
forced_alignment_min_coverage_ratio = 0.85
|
||||
|
||||
[diarization]
|
||||
enabled = false
|
||||
backend = "whisperx"
|
||||
model_path = ""
|
||||
cache_dir = "/mnt/c/models/diarization"
|
||||
min_speakers = 1
|
||||
max_speakers = 4
|
||||
device = "auto"
|
||||
require_local_model = true
|
||||
|
||||
[bitrix24]
|
||||
enabled = true
|
||||
base_url = "https://tp-portal.ru/rest/1720/dimk7zpx5wt6p4kf/"
|
||||
|
|
|
|||
|
|
@ -16,6 +16,11 @@ dependencies = [
|
|||
"faster-whisper>=1.1.0",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
diarization = [
|
||||
"whisperx>=3.3.0",
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
b24calls = "b24calls.cli:main"
|
||||
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ from .db.storage import SQLiteStorage
|
|||
from .audio.validation import validate_pending_audio_files
|
||||
from .doctor import run_doctor
|
||||
from .discovery import discover_bitrix24_audio_files, discover_local_audio_files
|
||||
from .diarization import diarize_completed_audio_files
|
||||
from .logging_setup import configure_logging
|
||||
from .export import export_completed_audio_files
|
||||
from .stt import TranscriptionError, transcribe_pending_audio_files
|
||||
|
|
@ -92,6 +93,19 @@ def _build_parser() -> argparse.ArgumentParser:
|
|||
default=None,
|
||||
help="Optional maximum number of audio files to process",
|
||||
)
|
||||
diarize_parser = subparsers.add_parser("diarize", help="Run optional diarization for completed transcripts")
|
||||
add_direction_argument(diarize_parser)
|
||||
diarize_parser.add_argument(
|
||||
"--limit",
|
||||
type=int,
|
||||
default=None,
|
||||
help="Optional maximum number of completed transcript artifacts to process",
|
||||
)
|
||||
diarize_parser.add_argument(
|
||||
"--force",
|
||||
action="store_true",
|
||||
help="Re-run diarization even when a completed diarization object already exists",
|
||||
)
|
||||
spool_parser = subparsers.add_parser("spool", help="Stage validated audio files into spool")
|
||||
add_direction_argument(spool_parser)
|
||||
process_parser = subparsers.add_parser("process", help="Process files end-to-end (placeholder)")
|
||||
|
|
@ -211,6 +225,24 @@ def main(argv: Sequence[str] | None = None) -> int:
|
|||
print(f"skipped_terminal: {summary.skipped_terminal}")
|
||||
print(f"failed: {summary.failed}")
|
||||
return 0
|
||||
if args.command == "diarize":
|
||||
settings = load_settings(config_path=args.config, env_path=args.env)
|
||||
configure_logging(settings.logging)
|
||||
storage = SQLiteStorage(settings.paths.database_path)
|
||||
storage.ensure_initialized()
|
||||
summary = diarize_completed_audio_files(
|
||||
storage,
|
||||
settings,
|
||||
limit=args.limit,
|
||||
direction_filter=args.direction or settings.processing.direction_filter,
|
||||
force=bool(args.force),
|
||||
)
|
||||
print("diarization summary")
|
||||
print(f"scanned: {summary.scanned}")
|
||||
print(f"diarized: {summary.diarized}")
|
||||
print(f"skipped_existing: {summary.skipped_existing}")
|
||||
print(f"failed: {summary.failed}")
|
||||
return 1 if summary.failed else 0
|
||||
if args.command == "export":
|
||||
settings = load_settings(config_path=args.config, env_path=args.env)
|
||||
configure_logging(settings.logging)
|
||||
|
|
|
|||
|
|
@ -82,6 +82,18 @@ class AudioPreprocessConfig:
|
|||
forced_alignment_min_coverage_ratio: float = 0.85
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DiarizationConfig:
|
||||
enabled: bool = False
|
||||
backend: str = "whisperx"
|
||||
model_path: Path | None = None
|
||||
cache_dir: Path = Path("./models/diarization")
|
||||
min_speakers: int | None = None
|
||||
max_speakers: int | None = None
|
||||
device: str = "auto"
|
||||
require_local_model: bool = True
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Bitrix24Config:
|
||||
enabled: bool = False
|
||||
|
|
@ -105,6 +117,7 @@ class Settings:
|
|||
models: ModelConfig
|
||||
local_source: LocalSourceConfig
|
||||
bitrix24: Bitrix24Config
|
||||
diarization: DiarizationConfig = field(default_factory=DiarizationConfig)
|
||||
audio_preprocess: AudioPreprocessConfig = field(default_factory=AudioPreprocessConfig)
|
||||
processing: ProcessingConfig = field(default_factory=ProcessingConfig)
|
||||
validation: ValidationConfig = field(default_factory=ValidationConfig)
|
||||
|
|
@ -165,6 +178,15 @@ def _parse_int(value: Any, default: int) -> int:
|
|||
return default
|
||||
|
||||
|
||||
def _parse_optional_int(value: Any) -> int | None:
|
||||
if value is None or value == "":
|
||||
return None
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _parse_extensions(value: Any, default: tuple[str, ...]) -> tuple[str, ...]:
|
||||
if value is None:
|
||||
return default
|
||||
|
|
@ -264,6 +286,7 @@ def load_settings(
|
|||
processing_section = raw.get("processing", {})
|
||||
validation_section = raw.get("validation", {})
|
||||
audio_preprocess_section = raw.get("audio_preprocess", {})
|
||||
diarization_section = raw.get("diarization", {})
|
||||
bitrix24_section = raw.get("bitrix24", {})
|
||||
|
||||
logging_config = LoggingConfig(
|
||||
|
|
@ -429,6 +452,37 @@ def load_settings(
|
|||
),
|
||||
)
|
||||
|
||||
diarization_config = DiarizationConfig(
|
||||
enabled=_parse_bool(
|
||||
os.environ.get("B24CALLS_DIARIZATION_ENABLED"),
|
||||
bool(diarization_section.get("enabled", False)),
|
||||
),
|
||||
backend=str(os.environ.get("B24CALLS_DIARIZATION_BACKEND", diarization_section.get("backend", "whisperx"))),
|
||||
model_path=_resolve_absolute_path(
|
||||
os.environ.get("B24CALLS_DIARIZATION_MODEL_PATH", diarization_section.get("model_path")),
|
||||
"diarization.model_path",
|
||||
),
|
||||
cache_dir=_resolve_required_path(
|
||||
_resolve_absolute_path(
|
||||
os.environ.get("B24CALLS_DIARIZATION_CACHE_DIR", diarization_section.get("cache_dir")),
|
||||
"diarization.cache_dir",
|
||||
),
|
||||
project_root,
|
||||
(project_root / DiarizationConfig.cache_dir).resolve(),
|
||||
),
|
||||
min_speakers=_parse_optional_int(
|
||||
os.environ.get("B24CALLS_DIARIZATION_MIN_SPEAKERS", diarization_section.get("min_speakers"))
|
||||
),
|
||||
max_speakers=_parse_optional_int(
|
||||
os.environ.get("B24CALLS_DIARIZATION_MAX_SPEAKERS", diarization_section.get("max_speakers"))
|
||||
),
|
||||
device=str(os.environ.get("B24CALLS_DIARIZATION_DEVICE", diarization_section.get("device", "auto"))),
|
||||
require_local_model=_parse_bool(
|
||||
os.environ.get("B24CALLS_DIARIZATION_REQUIRE_LOCAL_MODEL"),
|
||||
bool(diarization_section.get("require_local_model", True)),
|
||||
),
|
||||
)
|
||||
|
||||
bitrix24_config = Bitrix24Config(
|
||||
enabled=_parse_bool(
|
||||
os.environ.get("B24CALLS_BITRIX24_ENABLED"),
|
||||
|
|
@ -477,5 +531,6 @@ def load_settings(
|
|||
processing=processing_config,
|
||||
validation=validation_config,
|
||||
bitrix24=bitrix24_config,
|
||||
diarization=diarization_config,
|
||||
audio_preprocess=audio_preprocess_config,
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,5 +1,31 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from .backend import (
|
||||
DiarizationBackendInfo,
|
||||
DiarizationBackendUnavailable,
|
||||
DiarizationError,
|
||||
DiarizationModelError,
|
||||
DiarizationRunResult,
|
||||
SpeakerTurn,
|
||||
WhisperXDiarizationBackend,
|
||||
build_diarization,
|
||||
normalize_diarization_output,
|
||||
)
|
||||
from .placeholder import build_placeholder_diarization
|
||||
from .pipeline import DiarizationBatchSummary, DiarizationEntry, diarize_completed_audio_files
|
||||
|
||||
__all__ = ["build_placeholder_diarization"]
|
||||
__all__ = [
|
||||
"DiarizationBackendInfo",
|
||||
"DiarizationBackendUnavailable",
|
||||
"DiarizationBatchSummary",
|
||||
"DiarizationEntry",
|
||||
"DiarizationError",
|
||||
"DiarizationModelError",
|
||||
"DiarizationRunResult",
|
||||
"SpeakerTurn",
|
||||
"WhisperXDiarizationBackend",
|
||||
"build_diarization",
|
||||
"build_placeholder_diarization",
|
||||
"diarize_completed_audio_files",
|
||||
"normalize_diarization_output",
|
||||
]
|
||||
|
|
|
|||
|
|
@ -0,0 +1,517 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Iterable, Iterator, Mapping, Protocol, Sequence
|
||||
import importlib
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
|
||||
from ..config import Settings
|
||||
from .placeholder import build_placeholder_diarization
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class DiarizationError(RuntimeError):
|
||||
"""Raised when diarization cannot be completed."""
|
||||
|
||||
|
||||
class DiarizationBackendUnavailable(DiarizationError):
|
||||
"""Raised when the configured diarization backend is not installed."""
|
||||
|
||||
|
||||
class DiarizationModelError(DiarizationError):
|
||||
"""Raised when the configured diarization model cannot be used locally."""
|
||||
|
||||
|
||||
def _utc_now() -> str:
|
||||
return datetime.now(timezone.utc).replace(microsecond=0).isoformat()
|
||||
|
||||
|
||||
def _count_words(text: str | None) -> int:
|
||||
if not text:
|
||||
return 0
|
||||
return len([token for token in text.split() if token.strip()])
|
||||
|
||||
|
||||
def _detect_cuda_available() -> bool:
|
||||
try:
|
||||
import torch # type: ignore
|
||||
except Exception:
|
||||
return shutil.which("nvidia-smi") is not None
|
||||
|
||||
try:
|
||||
return bool(torch.cuda.is_available())
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def resolve_diarization_device(settings: Settings) -> str:
|
||||
requested = settings.diarization.device.strip().lower()
|
||||
if requested in {"cpu", "cuda"}:
|
||||
return requested
|
||||
if requested != "auto":
|
||||
logger.warning("unknown diarization device requested, falling back to auto", extra={"device": requested})
|
||||
if settings.runtime.allow_cuda and _detect_cuda_available():
|
||||
return "cuda"
|
||||
return "cpu"
|
||||
|
||||
|
||||
@contextmanager
|
||||
def offline_model_runtime(cache_dir: Path | None = None) -> Iterator[None]:
|
||||
"""Force common ML loaders to avoid network access while diarization runs."""
|
||||
|
||||
keys = (
|
||||
"HF_HUB_OFFLINE",
|
||||
"TRANSFORMERS_OFFLINE",
|
||||
"HF_DATASETS_OFFLINE",
|
||||
"HF_HOME",
|
||||
"TORCH_HOME",
|
||||
"PYANNOTE_CACHE",
|
||||
)
|
||||
previous = {key: os.environ.get(key) for key in keys}
|
||||
os.environ["HF_HUB_OFFLINE"] = "1"
|
||||
os.environ["TRANSFORMERS_OFFLINE"] = "1"
|
||||
os.environ["HF_DATASETS_OFFLINE"] = "1"
|
||||
if cache_dir is not None:
|
||||
resolved_cache_dir = Path(cache_dir).expanduser().resolve()
|
||||
resolved_cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
os.environ["HF_HOME"] = str(resolved_cache_dir)
|
||||
os.environ["TORCH_HOME"] = str(resolved_cache_dir / "torch")
|
||||
os.environ["PYANNOTE_CACHE"] = str(resolved_cache_dir / "pyannote")
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
for key, value in previous.items():
|
||||
if value is None:
|
||||
os.environ.pop(key, None)
|
||||
else:
|
||||
os.environ[key] = value
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SpeakerTurn:
|
||||
speaker: str
|
||||
start_seconds: float
|
||||
end_seconds: float
|
||||
|
||||
@property
|
||||
def duration_seconds(self) -> float:
|
||||
return max(0.0, self.end_seconds - self.start_seconds)
|
||||
|
||||
def as_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"speaker": self.speaker,
|
||||
"start_seconds": self.start_seconds,
|
||||
"end_seconds": self.end_seconds,
|
||||
"duration_seconds": self.duration_seconds,
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DiarizationBackendInfo:
|
||||
name: str
|
||||
requested_backend: str
|
||||
model_path: str | None
|
||||
device: str
|
||||
offline: bool = True
|
||||
is_placeholder: bool = False
|
||||
|
||||
def as_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"name": self.name,
|
||||
"requested_backend": self.requested_backend,
|
||||
"model_path": self.model_path,
|
||||
"device": self.device,
|
||||
"offline": self.offline,
|
||||
"is_placeholder": self.is_placeholder,
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DiarizationRunResult:
|
||||
backend: DiarizationBackendInfo
|
||||
turns: tuple[SpeakerTurn, ...]
|
||||
raw_info: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
class DiarizationBackend(Protocol):
|
||||
def describe(self) -> DiarizationBackendInfo:
|
||||
...
|
||||
|
||||
def diarize(
|
||||
self,
|
||||
audio_path: str | Path,
|
||||
*,
|
||||
min_speakers: int | None = None,
|
||||
max_speakers: int | None = None,
|
||||
) -> DiarizationRunResult:
|
||||
...
|
||||
|
||||
|
||||
def _require_local_model_path(settings: Settings) -> Path:
|
||||
model_path = settings.diarization.model_path
|
||||
if model_path is None:
|
||||
raise DiarizationModelError("diarization.model_path must point to a local model directory")
|
||||
resolved = Path(model_path).expanduser().resolve()
|
||||
if not resolved.exists():
|
||||
raise DiarizationModelError(f"local diarization model does not exist: {resolved}")
|
||||
return resolved
|
||||
|
||||
|
||||
def _load_whisperx_pipeline_factory() -> Callable[..., Any]:
|
||||
try:
|
||||
whisperx = importlib.import_module("whisperx")
|
||||
except ImportError as exc:
|
||||
raise DiarizationBackendUnavailable(
|
||||
"whisperx is not installed; install the optional diarization dependencies"
|
||||
) from exc
|
||||
|
||||
direct = getattr(whisperx, "DiarizationPipeline", None)
|
||||
if callable(direct):
|
||||
return direct
|
||||
|
||||
try:
|
||||
diarize_module = importlib.import_module("whisperx.diarize")
|
||||
except ImportError as exc:
|
||||
raise DiarizationBackendUnavailable("whisperx.diarize is not available") from exc
|
||||
|
||||
pipeline = getattr(diarize_module, "DiarizationPipeline", None)
|
||||
if not callable(pipeline):
|
||||
raise DiarizationBackendUnavailable("whisperx diarization pipeline is not available")
|
||||
return pipeline
|
||||
|
||||
|
||||
def _instantiate_whisperx_pipeline(factory: Callable[..., Any], *, model_path: Path, device: str) -> Any:
|
||||
attempts = (
|
||||
{"model_name": str(model_path), "use_auth_token": None, "device": device},
|
||||
{"model_name": str(model_path), "device": device},
|
||||
{"model": str(model_path), "device": device},
|
||||
)
|
||||
last_exc: TypeError | None = None
|
||||
for kwargs in attempts:
|
||||
try:
|
||||
return factory(**kwargs)
|
||||
except TypeError as exc:
|
||||
last_exc = exc
|
||||
continue
|
||||
assert last_exc is not None
|
||||
raise last_exc
|
||||
|
||||
|
||||
def _normalize_mapping_turns(items: Iterable[Mapping[str, Any]]) -> tuple[SpeakerTurn, ...]:
|
||||
turns: list[SpeakerTurn] = []
|
||||
for item in items:
|
||||
start = item.get("start", item.get("start_seconds"))
|
||||
end = item.get("end", item.get("end_seconds"))
|
||||
speaker = item.get("speaker", item.get("label", item.get("speaker_id", "SPEAKER_UNKNOWN")))
|
||||
if start is None or end is None:
|
||||
continue
|
||||
try:
|
||||
start_seconds = float(start)
|
||||
end_seconds = float(end)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if end_seconds < start_seconds:
|
||||
continue
|
||||
turns.append(SpeakerTurn(speaker=str(speaker), start_seconds=start_seconds, end_seconds=end_seconds))
|
||||
return tuple(sorted(turns, key=lambda item: (item.start_seconds, item.end_seconds, item.speaker)))
|
||||
|
||||
|
||||
def _normalize_pyannote_annotation(value: Any) -> tuple[SpeakerTurn, ...]:
|
||||
itertracks = getattr(value, "itertracks", None)
|
||||
if not callable(itertracks):
|
||||
return ()
|
||||
turns: list[SpeakerTurn] = []
|
||||
for segment, _track, speaker in itertracks(yield_label=True):
|
||||
try:
|
||||
start_seconds = float(segment.start)
|
||||
end_seconds = float(segment.end)
|
||||
except (AttributeError, TypeError, ValueError):
|
||||
continue
|
||||
if end_seconds >= start_seconds:
|
||||
turns.append(SpeakerTurn(str(speaker), start_seconds, end_seconds))
|
||||
return tuple(sorted(turns, key=lambda item: (item.start_seconds, item.end_seconds, item.speaker)))
|
||||
|
||||
|
||||
def normalize_diarization_output(value: Any) -> tuple[SpeakerTurn, ...]:
|
||||
if value is None:
|
||||
return ()
|
||||
|
||||
if hasattr(value, "to_dict"):
|
||||
try:
|
||||
records = value.to_dict("records")
|
||||
except TypeError:
|
||||
records = None
|
||||
if isinstance(records, list):
|
||||
return _normalize_mapping_turns(item for item in records if isinstance(item, Mapping))
|
||||
|
||||
if isinstance(value, (list, tuple)):
|
||||
return _normalize_mapping_turns(item for item in value if isinstance(item, Mapping))
|
||||
|
||||
annotation_turns = _normalize_pyannote_annotation(value)
|
||||
if annotation_turns:
|
||||
return annotation_turns
|
||||
|
||||
return ()
|
||||
|
||||
|
||||
class WhisperXDiarizationBackend:
|
||||
"""Offline WhisperX diarization wrapper.
|
||||
|
||||
WhisperX delegates speaker diarization to pyannote. To keep runtime offline,
|
||||
this wrapper requires a local model path by default and forces the common
|
||||
Hugging Face offline environment flags while loading and running the model.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
settings: Settings,
|
||||
*,
|
||||
pipeline_factory: Callable[..., Any] | None = None,
|
||||
) -> None:
|
||||
self._settings = settings
|
||||
self._device = resolve_diarization_device(settings)
|
||||
self._model_path = _require_local_model_path(settings)
|
||||
self._cache_dir = settings.diarization.cache_dir
|
||||
self._factory = pipeline_factory or _load_whisperx_pipeline_factory()
|
||||
try:
|
||||
with offline_model_runtime(self._cache_dir):
|
||||
self._pipeline = _instantiate_whisperx_pipeline(
|
||||
self._factory,
|
||||
model_path=self._model_path,
|
||||
device=self._device,
|
||||
)
|
||||
except DiarizationError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise DiarizationModelError(f"failed to load local diarization model: {exc}") from exc
|
||||
|
||||
def describe(self) -> DiarizationBackendInfo:
|
||||
return DiarizationBackendInfo(
|
||||
name="whisperx",
|
||||
requested_backend=self._settings.diarization.backend,
|
||||
model_path=str(self._model_path),
|
||||
device=self._device,
|
||||
)
|
||||
|
||||
def diarize(
|
||||
self,
|
||||
audio_path: str | Path,
|
||||
*,
|
||||
min_speakers: int | None = None,
|
||||
max_speakers: int | None = None,
|
||||
) -> DiarizationRunResult:
|
||||
resolved_audio = Path(audio_path).expanduser().resolve()
|
||||
if not resolved_audio.exists():
|
||||
raise DiarizationError(f"audio file does not exist: {resolved_audio}")
|
||||
|
||||
kwargs: dict[str, Any] = {}
|
||||
if min_speakers is not None:
|
||||
kwargs["min_speakers"] = int(min_speakers)
|
||||
if max_speakers is not None:
|
||||
kwargs["max_speakers"] = int(max_speakers)
|
||||
|
||||
try:
|
||||
with offline_model_runtime(self._cache_dir):
|
||||
raw = self._pipeline(str(resolved_audio), **kwargs)
|
||||
except Exception as exc:
|
||||
raise DiarizationError(f"diarization failed: {exc}") from exc
|
||||
|
||||
turns = normalize_diarization_output(raw)
|
||||
return DiarizationRunResult(
|
||||
backend=self.describe(),
|
||||
turns=turns,
|
||||
raw_info={
|
||||
"turn_count": len(turns),
|
||||
"min_speakers": min_speakers,
|
||||
"max_speakers": max_speakers,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def create_diarization_backend(settings: Settings) -> DiarizationBackend:
|
||||
backend = settings.diarization.backend.strip().lower()
|
||||
if backend in {"whisperx", "pyannote", "whisperx_pyannote"}:
|
||||
return WhisperXDiarizationBackend(settings)
|
||||
raise DiarizationBackendUnavailable(
|
||||
f"unsupported diarization backend: {settings.diarization.backend}; expected whisperx"
|
||||
)
|
||||
|
||||
|
||||
def _segment_index(segment: Mapping[str, Any], fallback: int) -> int:
|
||||
value = segment.get("index", fallback)
|
||||
try:
|
||||
return int(value)
|
||||
except (TypeError, ValueError):
|
||||
return fallback
|
||||
|
||||
|
||||
def _segment_bounds(segment: Mapping[str, Any]) -> tuple[float, float] | None:
|
||||
start = segment.get("start_seconds", segment.get("start"))
|
||||
end = segment.get("end_seconds", segment.get("end"))
|
||||
if start is None or end is None:
|
||||
return None
|
||||
try:
|
||||
start_seconds = float(start)
|
||||
end_seconds = float(end)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
if end_seconds < start_seconds:
|
||||
return None
|
||||
return start_seconds, end_seconds
|
||||
|
||||
|
||||
def _overlap_seconds(first: tuple[float, float], second: tuple[float, float]) -> float:
|
||||
return max(0.0, min(first[1], second[1]) - max(first[0], second[0]))
|
||||
|
||||
|
||||
def _build_segments(
|
||||
turns: Sequence[SpeakerTurn],
|
||||
transcript_segments: Sequence[Mapping[str, Any]],
|
||||
) -> tuple[dict[str, Any], ...]:
|
||||
indexed_segments = [
|
||||
(_segment_index(segment, fallback), segment, bounds)
|
||||
for fallback, segment in enumerate(transcript_segments)
|
||||
if (bounds := _segment_bounds(segment)) is not None
|
||||
]
|
||||
|
||||
payload_segments: list[dict[str, Any]] = []
|
||||
for index, turn in enumerate(turns):
|
||||
turn_bounds = (turn.start_seconds, turn.end_seconds)
|
||||
matched: list[tuple[int, Mapping[str, Any]]] = []
|
||||
for transcript_index, segment, bounds in indexed_segments:
|
||||
if _overlap_seconds(turn_bounds, bounds) > 0:
|
||||
matched.append((transcript_index, segment))
|
||||
text = " ".join(str(segment.get("text") or "").strip() for _, segment in matched).strip()
|
||||
payload_segments.append(
|
||||
{
|
||||
"index": index,
|
||||
"speaker": turn.speaker,
|
||||
"start_seconds": turn.start_seconds,
|
||||
"end_seconds": turn.end_seconds,
|
||||
"duration_seconds": turn.duration_seconds,
|
||||
"text": text,
|
||||
"transcript_segment_indexes": [transcript_index for transcript_index, _ in matched],
|
||||
"is_placeholder": False,
|
||||
}
|
||||
)
|
||||
return tuple(payload_segments)
|
||||
|
||||
|
||||
def _failure_payload(
|
||||
*,
|
||||
audio_file_id: int,
|
||||
source_id: str,
|
||||
transcript_text: str | None,
|
||||
transcript_segments: Sequence[Mapping[str, Any]] | None,
|
||||
duration_seconds: float | None,
|
||||
backend_name: str,
|
||||
error: Exception,
|
||||
) -> dict[str, Any]:
|
||||
segments = tuple(transcript_segments or ())
|
||||
now = _utc_now()
|
||||
return {
|
||||
"artifact_type": "diarization",
|
||||
"artifact_format": "json",
|
||||
"artifact_version": 1,
|
||||
"backend": {
|
||||
"name": backend_name,
|
||||
"requested_backend": backend_name,
|
||||
"model_path": None,
|
||||
"device": "unknown",
|
||||
"offline": True,
|
||||
"is_placeholder": False,
|
||||
},
|
||||
"status": "failed",
|
||||
"is_placeholder": False,
|
||||
"speaker_count": 0,
|
||||
"speakers": [],
|
||||
"segments": [],
|
||||
"transcript_summary": {
|
||||
"audio_file_id": int(audio_file_id),
|
||||
"source_id": source_id,
|
||||
"text_length": len(transcript_text or ""),
|
||||
"word_count": _count_words(transcript_text),
|
||||
"duration_seconds": duration_seconds,
|
||||
"segment_count": len(segments),
|
||||
},
|
||||
"error": str(error),
|
||||
"created_at": now,
|
||||
"updated_at": now,
|
||||
}
|
||||
|
||||
|
||||
def build_diarization(
|
||||
*,
|
||||
settings: Settings,
|
||||
audio_path: str | Path,
|
||||
audio_file_id: int,
|
||||
source_id: str,
|
||||
transcript_text: str | None = None,
|
||||
transcript_segments: Sequence[Mapping[str, Any]] | None = None,
|
||||
duration_seconds: float | None = None,
|
||||
backend: DiarizationBackend | None = None,
|
||||
) -> dict[str, Any]:
|
||||
if not settings.diarization.enabled:
|
||||
return build_placeholder_diarization(
|
||||
audio_file_id=audio_file_id,
|
||||
source_id=source_id,
|
||||
transcript_text=transcript_text,
|
||||
transcript_segments=transcript_segments,
|
||||
duration_seconds=duration_seconds,
|
||||
)
|
||||
|
||||
selected_backend = backend
|
||||
try:
|
||||
if selected_backend is None:
|
||||
selected_backend = create_diarization_backend(settings)
|
||||
run = selected_backend.diarize(
|
||||
audio_path,
|
||||
min_speakers=settings.diarization.min_speakers,
|
||||
max_speakers=settings.diarization.max_speakers,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.exception(
|
||||
"optional diarization failed",
|
||||
extra={"audio_file_id": audio_file_id, "source_id": source_id},
|
||||
)
|
||||
return _failure_payload(
|
||||
audio_file_id=audio_file_id,
|
||||
source_id=source_id,
|
||||
transcript_text=transcript_text,
|
||||
transcript_segments=transcript_segments,
|
||||
duration_seconds=duration_seconds,
|
||||
backend_name=settings.diarization.backend,
|
||||
error=exc,
|
||||
)
|
||||
|
||||
segments = _build_segments(run.turns, tuple(transcript_segments or ()))
|
||||
speakers = sorted({turn.speaker for turn in run.turns})
|
||||
now = _utc_now()
|
||||
return {
|
||||
"artifact_type": "diarization",
|
||||
"artifact_format": "json",
|
||||
"artifact_version": 1,
|
||||
"backend": run.backend.as_dict(),
|
||||
"status": "done",
|
||||
"is_placeholder": False,
|
||||
"speaker_count": len(speakers),
|
||||
"speakers": speakers,
|
||||
"segments": list(segments),
|
||||
"transcript_summary": {
|
||||
"audio_file_id": int(audio_file_id),
|
||||
"source_id": source_id,
|
||||
"text_length": len(transcript_text or ""),
|
||||
"word_count": _count_words(transcript_text),
|
||||
"duration_seconds": duration_seconds,
|
||||
"segment_count": len(segments),
|
||||
},
|
||||
"raw_info": dict(run.raw_info),
|
||||
"created_at": now,
|
||||
"updated_at": now,
|
||||
}
|
||||
|
|
@ -0,0 +1,265 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from hashlib import sha256
|
||||
from pathlib import Path
|
||||
from typing import Any, Mapping
|
||||
import json
|
||||
import logging
|
||||
|
||||
from ..config import Settings
|
||||
from ..db.storage import ArtifactRecord, SQLiteStorage
|
||||
from ..direction import allowed_directions_for_filter
|
||||
from .backend import DiarizationBackend, build_diarization
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
TRANSCRIPT_ARTIFACT_KIND = "transcript"
|
||||
TRANSCRIPT_ARTIFACT_FORMAT = "json"
|
||||
|
||||
|
||||
def _json_dumps(value: Any) -> str:
|
||||
return json.dumps(value, ensure_ascii=False, sort_keys=True, indent=2, default=str)
|
||||
|
||||
|
||||
def _file_sha256(path: Path, chunk_size: int = 1024 * 1024) -> str:
|
||||
digest = sha256()
|
||||
with path.open("rb") as handle:
|
||||
for chunk in iter(lambda: handle.read(chunk_size), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def _as_mapping(value: Any) -> dict[str, Any]:
|
||||
return dict(value) if isinstance(value, Mapping) else {}
|
||||
|
||||
|
||||
def _as_list(value: Any) -> list[Any]:
|
||||
return list(value) if isinstance(value, list) else []
|
||||
|
||||
|
||||
def _load_payload(path: Path) -> dict[str, Any]:
|
||||
loaded = json.loads(path.read_text(encoding="utf-8"))
|
||||
if not isinstance(loaded, Mapping):
|
||||
raise ValueError(f"transcript artifact is not a JSON object: {path}")
|
||||
return dict(loaded)
|
||||
|
||||
|
||||
def _pick_audio_path(payload: Mapping[str, Any]) -> Path | None:
|
||||
preprocess = _as_mapping(payload.get("preprocess"))
|
||||
normalization = _as_mapping(preprocess.get("normalization"))
|
||||
for candidate in (
|
||||
normalization.get("normalized_path"),
|
||||
_as_mapping(payload.get("spool")).get("path"),
|
||||
_as_mapping(payload.get("source_file")).get("path"),
|
||||
):
|
||||
if not candidate:
|
||||
continue
|
||||
path = Path(str(candidate)).expanduser().resolve()
|
||||
if path.exists():
|
||||
return path
|
||||
return None
|
||||
|
||||
|
||||
def _should_skip(payload: Mapping[str, Any], *, force: bool) -> bool:
|
||||
if force:
|
||||
return False
|
||||
diarization = _as_mapping(payload.get("diarization"))
|
||||
return diarization.get("status") == "done" and diarization.get("is_placeholder") is False
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DiarizationEntry:
|
||||
audio_file_id: int
|
||||
source_id: str
|
||||
status: str
|
||||
artifact_id: int | None
|
||||
artifact_path: Path | None
|
||||
message: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DiarizationBatchSummary:
|
||||
scanned: int = 0
|
||||
diarized: int = 0
|
||||
skipped_existing: int = 0
|
||||
failed: int = 0
|
||||
entries: tuple[DiarizationEntry, ...] = field(default_factory=tuple)
|
||||
|
||||
|
||||
def diarize_completed_audio_files(
|
||||
storage: SQLiteStorage,
|
||||
settings: Settings,
|
||||
*,
|
||||
backend: DiarizationBackend | None = None,
|
||||
limit: int | None = None,
|
||||
direction_filter: str | None = None,
|
||||
force: bool = False,
|
||||
) -> DiarizationBatchSummary:
|
||||
selected_direction_filter = direction_filter or settings.processing.direction_filter
|
||||
rows = storage.list_audio_files_by_statuses(
|
||||
("done",),
|
||||
directions=allowed_directions_for_filter(selected_direction_filter),
|
||||
)
|
||||
if limit is not None:
|
||||
rows = rows[: max(limit, 0)]
|
||||
|
||||
entries: list[DiarizationEntry] = []
|
||||
diarized = 0
|
||||
skipped_existing = 0
|
||||
failed = 0
|
||||
|
||||
logger.info(
|
||||
"starting diarization batch",
|
||||
extra={
|
||||
"scanned": len(rows),
|
||||
"enabled": settings.diarization.enabled,
|
||||
"backend": settings.diarization.backend,
|
||||
"direction_filter": selected_direction_filter,
|
||||
"force": force,
|
||||
},
|
||||
)
|
||||
|
||||
for row in rows:
|
||||
audio_file_id = int(row["id"])
|
||||
source_id = str(row["source_id"])
|
||||
transcript_artifact = storage.get_artifact(audio_file_id, TRANSCRIPT_ARTIFACT_KIND, TRANSCRIPT_ARTIFACT_FORMAT)
|
||||
if transcript_artifact is None:
|
||||
failed += 1
|
||||
entries.append(
|
||||
DiarizationEntry(audio_file_id, source_id, "failed", None, None, "transcript artifact not found")
|
||||
)
|
||||
continue
|
||||
|
||||
artifact_path = Path(str(transcript_artifact["file_path"])).expanduser().resolve()
|
||||
if not artifact_path.exists():
|
||||
failed += 1
|
||||
entries.append(
|
||||
DiarizationEntry(
|
||||
audio_file_id,
|
||||
source_id,
|
||||
"failed",
|
||||
int(transcript_artifact["id"]),
|
||||
artifact_path,
|
||||
"transcript artifact file is missing",
|
||||
)
|
||||
)
|
||||
continue
|
||||
|
||||
try:
|
||||
payload = _load_payload(artifact_path)
|
||||
except Exception as exc:
|
||||
failed += 1
|
||||
entries.append(
|
||||
DiarizationEntry(
|
||||
audio_file_id,
|
||||
source_id,
|
||||
"failed",
|
||||
int(transcript_artifact["id"]),
|
||||
artifact_path,
|
||||
str(exc),
|
||||
)
|
||||
)
|
||||
continue
|
||||
|
||||
if _should_skip(payload, force=force):
|
||||
skipped_existing += 1
|
||||
entries.append(
|
||||
DiarizationEntry(
|
||||
audio_file_id,
|
||||
source_id,
|
||||
"skipped_existing",
|
||||
int(transcript_artifact["id"]),
|
||||
artifact_path,
|
||||
"diarization already exists",
|
||||
)
|
||||
)
|
||||
continue
|
||||
|
||||
audio_path = _pick_audio_path(payload)
|
||||
if audio_path is None:
|
||||
failed += 1
|
||||
entries.append(
|
||||
DiarizationEntry(
|
||||
audio_file_id,
|
||||
source_id,
|
||||
"failed",
|
||||
int(transcript_artifact["id"]),
|
||||
artifact_path,
|
||||
"audio file for diarization not found",
|
||||
)
|
||||
)
|
||||
continue
|
||||
|
||||
transcription = _as_mapping(payload.get("transcription"))
|
||||
segments = [
|
||||
dict(item) if isinstance(item, Mapping) else {"value": item}
|
||||
for item in _as_list(transcription.get("segments"))
|
||||
]
|
||||
diarization = build_diarization(
|
||||
settings=settings,
|
||||
backend=backend,
|
||||
audio_path=audio_path,
|
||||
audio_file_id=audio_file_id,
|
||||
source_id=source_id,
|
||||
transcript_text=str(transcription.get("text") or ""),
|
||||
transcript_segments=segments,
|
||||
duration_seconds=(
|
||||
transcription.get("duration_seconds")
|
||||
or _as_mapping(payload.get("source_file")).get("duration_seconds")
|
||||
),
|
||||
)
|
||||
payload["diarization"] = diarization
|
||||
artifact_path.write_text(_json_dumps(payload), encoding="utf-8")
|
||||
storage.upsert_artifact(
|
||||
ArtifactRecord(
|
||||
audio_file_id=audio_file_id,
|
||||
kind=TRANSCRIPT_ARTIFACT_KIND,
|
||||
format=TRANSCRIPT_ARTIFACT_FORMAT,
|
||||
file_path=artifact_path,
|
||||
checksum_sha256=_file_sha256(artifact_path),
|
||||
metadata={
|
||||
"artifact_type": TRANSCRIPT_ARTIFACT_KIND,
|
||||
"format": TRANSCRIPT_ARTIFACT_FORMAT,
|
||||
"diarization_status": diarization.get("status"),
|
||||
"diarization_backend": _as_mapping(diarization.get("backend")).get("name"),
|
||||
},
|
||||
)
|
||||
)
|
||||
|
||||
if diarization.get("status") == "failed":
|
||||
failed += 1
|
||||
status = "failed"
|
||||
message = str(diarization.get("error") or "diarization failed")
|
||||
else:
|
||||
diarized += 1
|
||||
status = "diarized"
|
||||
message = "diarization written"
|
||||
entries.append(
|
||||
DiarizationEntry(
|
||||
audio_file_id,
|
||||
source_id,
|
||||
status,
|
||||
int(transcript_artifact["id"]),
|
||||
artifact_path,
|
||||
message,
|
||||
)
|
||||
)
|
||||
|
||||
summary = DiarizationBatchSummary(
|
||||
scanned=len(rows),
|
||||
diarized=diarized,
|
||||
skipped_existing=skipped_existing,
|
||||
failed=failed,
|
||||
entries=tuple(entries),
|
||||
)
|
||||
logger.info(
|
||||
"diarization batch completed",
|
||||
extra={
|
||||
"scanned": summary.scanned,
|
||||
"diarized": summary.diarized,
|
||||
"skipped_existing": summary.skipped_existing,
|
||||
"failed": summary.failed,
|
||||
},
|
||||
)
|
||||
return summary
|
||||
|
|
@ -149,6 +149,31 @@ def _detect_runtime(settings: Settings) -> CheckResult:
|
|||
return CheckResult("runtime", status, message, details)
|
||||
|
||||
|
||||
def _check_diarization(settings: Settings) -> CheckResult:
|
||||
details = {
|
||||
"enabled": str(settings.diarization.enabled).lower(),
|
||||
"backend": settings.diarization.backend,
|
||||
"model_path": _format_path(settings.diarization.model_path),
|
||||
"require_local_model": str(settings.diarization.require_local_model).lower(),
|
||||
}
|
||||
if not settings.diarization.enabled:
|
||||
return CheckResult("diarization", "ok", "diarization disabled", details)
|
||||
|
||||
if settings.diarization.backend.strip().lower() not in {"whisperx", "pyannote", "whisperx_pyannote"}:
|
||||
return CheckResult("diarization", "error", "unsupported diarization backend", details)
|
||||
|
||||
if settings.diarization.model_path is None:
|
||||
return CheckResult("diarization", "error", "diarization.model_path is required for offline runtime", details)
|
||||
if not settings.diarization.model_path.exists():
|
||||
return CheckResult("diarization", "error", "local diarization model does not exist", details)
|
||||
|
||||
whisperx_spec = importlib.util.find_spec("whisperx")
|
||||
if whisperx_spec is None:
|
||||
return CheckResult("diarization", "error", "whisperx is not installed", details)
|
||||
|
||||
return CheckResult("diarization", "ok", "offline diarization model is configured", details)
|
||||
|
||||
|
||||
def _build_report(settings: Settings) -> DoctorReport:
|
||||
checks = (
|
||||
_check_python(),
|
||||
|
|
@ -162,6 +187,7 @@ def _build_report(settings: Settings) -> DoctorReport:
|
|||
_check_directory(settings.paths.log_dir, "paths.log_dir"),
|
||||
_check_file_parent(settings.paths.database_path, "paths.database_path"),
|
||||
_detect_runtime(settings),
|
||||
_check_diarization(settings),
|
||||
)
|
||||
return DoctorReport(settings=settings, checks=checks)
|
||||
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ from ..direction import allowed_directions_for_filter
|
|||
from ..config import Settings
|
||||
from ..db.storage import ArtifactRecord, JobRecord, SQLiteStorage
|
||||
from ..classification import build_scorecard_classification
|
||||
from ..diarization import build_placeholder_diarization
|
||||
from ..diarization import build_diarization
|
||||
from ..emotion import build_placeholder_emotion
|
||||
from ..spool.lifecycle import SpoolLifecycle
|
||||
from .faster_whisper_backend import (
|
||||
|
|
@ -60,6 +60,7 @@ def _file_sha256(path: Path, chunk_size: int = 1024 * 1024) -> str:
|
|||
def _build_transcript_payload(
|
||||
row: Any,
|
||||
*,
|
||||
settings: Settings,
|
||||
audio_path: Path,
|
||||
result: TranscriptionResult,
|
||||
backend_info: FasterWhisperBackendInfo,
|
||||
|
|
@ -70,7 +71,9 @@ def _build_transcript_payload(
|
|||
) -> dict[str, Any]:
|
||||
source_metadata = _load_metadata_json(str(row["metadata_json"]))
|
||||
source_direction = str(row["direction"])
|
||||
diarization = build_placeholder_diarization(
|
||||
diarization = build_diarization(
|
||||
settings=settings,
|
||||
audio_path=preprocess_result.normalized_path,
|
||||
audio_file_id=int(row["id"]),
|
||||
source_id=str(row["source_id"]),
|
||||
transcript_text=result.text,
|
||||
|
|
@ -741,6 +744,7 @@ def transcribe_pending_audio_files(
|
|||
|
||||
payload = _build_transcript_payload(
|
||||
current_row,
|
||||
settings=settings,
|
||||
audio_path=audio_spool_path,
|
||||
result=final_result,
|
||||
backend_info=backend_info,
|
||||
|
|
|
|||
|
|
@ -56,6 +56,16 @@ class ConfigLoadingTests(unittest.TestCase):
|
|||
[validation]
|
||||
min_duration_seconds = 7.5
|
||||
|
||||
[diarization]
|
||||
enabled = true
|
||||
backend = "whisperx"
|
||||
model_path = "{(root / 'models' / 'diarization' / 'pipeline').as_posix()}"
|
||||
cache_dir = "{(root / 'models' / 'diarization').as_posix()}"
|
||||
min_speakers = 1
|
||||
max_speakers = 3
|
||||
device = "cpu"
|
||||
require_local_model = true
|
||||
|
||||
[bitrix24]
|
||||
enabled = true
|
||||
base_url = "https://example.invalid/rest/1/token/"
|
||||
|
|
@ -91,6 +101,14 @@ class ConfigLoadingTests(unittest.TestCase):
|
|||
self.assertEqual(settings.local_source.outgoing_patterns, ("outgoing/**",))
|
||||
self.assertEqual(settings.processing.direction_filter, "incoming")
|
||||
self.assertEqual(settings.validation.min_duration_seconds, 7.5)
|
||||
self.assertTrue(settings.diarization.enabled)
|
||||
self.assertEqual(settings.diarization.backend, "whisperx")
|
||||
self.assertEqual(settings.diarization.model_path, (root / "models" / "diarization" / "pipeline").resolve())
|
||||
self.assertEqual(settings.diarization.cache_dir, (root / "models" / "diarization").resolve())
|
||||
self.assertEqual(settings.diarization.min_speakers, 1)
|
||||
self.assertEqual(settings.diarization.max_speakers, 3)
|
||||
self.assertEqual(settings.diarization.device, "cpu")
|
||||
self.assertTrue(settings.diarization.require_local_model)
|
||||
self.assertTrue(settings.bitrix24.enabled)
|
||||
self.assertEqual(settings.bitrix24.base_url, "https://example.invalid/rest/1/token/")
|
||||
self.assertEqual(settings.bitrix24.rate_limit_per_second, 0.5)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,205 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from hashlib import sha256
|
||||
from pathlib import Path
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from b24calls.config import (
|
||||
Bitrix24Config,
|
||||
DiarizationConfig,
|
||||
LoggingConfig,
|
||||
LocalSourceConfig,
|
||||
ModelConfig,
|
||||
PathsConfig,
|
||||
RuntimeConfig,
|
||||
Settings,
|
||||
)
|
||||
from b24calls.db.storage import ArtifactRecord, AudioFileRecord, SQLiteStorage
|
||||
from b24calls.diarization import (
|
||||
DiarizationBackendInfo,
|
||||
DiarizationRunResult,
|
||||
SpeakerTurn,
|
||||
build_diarization,
|
||||
diarize_completed_audio_files,
|
||||
normalize_diarization_output,
|
||||
)
|
||||
|
||||
|
||||
def _build_settings(root: Path, *, enabled: bool = True) -> Settings:
|
||||
model_path = root / "models" / "diarization" / "pipeline"
|
||||
model_path.mkdir(parents=True, exist_ok=True)
|
||||
return Settings(
|
||||
project_root=root,
|
||||
config_path=root / "configs" / "example.toml",
|
||||
env_path=None,
|
||||
logging=LoggingConfig(level="INFO", console=False, file=None, structured=True),
|
||||
paths=PathsConfig(
|
||||
spool_dir=root / "spool",
|
||||
output_dir=root / "output",
|
||||
log_dir=root / "logs",
|
||||
database_path=root / "data" / "b24calls.sqlite3",
|
||||
),
|
||||
runtime=RuntimeConfig(device="auto", allow_cuda=False, compute_type="default"),
|
||||
models=ModelConfig(directory=root / "models", whisper_model="large-v3", download_missing=False),
|
||||
local_source=LocalSourceConfig(directory=root / "input" / "calls", extensions=(".wav",), recursive=True),
|
||||
bitrix24=Bitrix24Config(),
|
||||
diarization=DiarizationConfig(
|
||||
enabled=enabled,
|
||||
backend="whisperx",
|
||||
model_path=model_path,
|
||||
cache_dir=root / "models" / "diarization",
|
||||
min_speakers=1,
|
||||
max_speakers=2,
|
||||
device="cpu",
|
||||
require_local_model=True,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class _FakeDiarizationBackend:
|
||||
turns: tuple[SpeakerTurn, ...]
|
||||
|
||||
def describe(self) -> DiarizationBackendInfo:
|
||||
return DiarizationBackendInfo(
|
||||
name="fake-whisperx",
|
||||
requested_backend="whisperx",
|
||||
model_path="/tmp/local-model",
|
||||
device="cpu",
|
||||
)
|
||||
|
||||
def diarize(
|
||||
self,
|
||||
audio_path: str | Path,
|
||||
*,
|
||||
min_speakers: int | None = None,
|
||||
max_speakers: int | None = None,
|
||||
) -> DiarizationRunResult:
|
||||
return DiarizationRunResult(
|
||||
backend=self.describe(),
|
||||
turns=self.turns,
|
||||
raw_info={"min_speakers": min_speakers, "max_speakers": max_speakers},
|
||||
)
|
||||
|
||||
|
||||
class DiarizationTests(unittest.TestCase):
|
||||
def test_normalize_mapping_turns_from_whisperx_shape(self) -> None:
|
||||
turns = normalize_diarization_output(
|
||||
[
|
||||
{"start": 1.2, "end": 2.4, "speaker": "SPEAKER_01"},
|
||||
{"start": 0.0, "end": 1.2, "speaker": "SPEAKER_00"},
|
||||
]
|
||||
)
|
||||
|
||||
self.assertEqual([turn.speaker for turn in turns], ["SPEAKER_00", "SPEAKER_01"])
|
||||
self.assertEqual(turns[0].start_seconds, 0.0)
|
||||
self.assertEqual(turns[1].end_seconds, 2.4)
|
||||
|
||||
def test_build_diarization_adds_separate_done_object_with_transcript_links(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp_dir:
|
||||
root = Path(tmp_dir)
|
||||
settings = _build_settings(root)
|
||||
audio_path = root / "audio.wav"
|
||||
audio_path.write_bytes(b"audio")
|
||||
backend = _FakeDiarizationBackend(
|
||||
turns=(
|
||||
SpeakerTurn("SPEAKER_00", 0.0, 1.0),
|
||||
SpeakerTurn("SPEAKER_01", 1.0, 2.0),
|
||||
)
|
||||
)
|
||||
|
||||
payload = build_diarization(
|
||||
settings=settings,
|
||||
backend=backend,
|
||||
audio_path=audio_path,
|
||||
audio_file_id=7,
|
||||
source_id="call-7",
|
||||
transcript_text="Привет мир",
|
||||
transcript_segments=[
|
||||
{"index": 0, "start_seconds": 0.0, "end_seconds": 1.0, "text": "Привет"},
|
||||
{"index": 1, "start_seconds": 1.0, "end_seconds": 2.0, "text": "мир"},
|
||||
],
|
||||
duration_seconds=2.0,
|
||||
)
|
||||
|
||||
self.assertEqual(payload["artifact_type"], "diarization")
|
||||
self.assertEqual(payload["status"], "done")
|
||||
self.assertFalse(payload["is_placeholder"])
|
||||
self.assertEqual(payload["backend"]["name"], "fake-whisperx")
|
||||
self.assertEqual(payload["speaker_count"], 2)
|
||||
self.assertEqual(payload["segments"][0]["text"], "Привет")
|
||||
self.assertEqual(payload["segments"][1]["transcript_segment_indexes"], [1])
|
||||
self.assertEqual(payload["raw_info"]["min_speakers"], 1)
|
||||
self.assertEqual(payload["raw_info"]["max_speakers"], 2)
|
||||
|
||||
def test_diarize_completed_audio_files_updates_only_diarization_section(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp_dir:
|
||||
root = Path(tmp_dir)
|
||||
settings = _build_settings(root)
|
||||
storage = SQLiteStorage(settings.paths.database_path)
|
||||
storage.ensure_initialized()
|
||||
audio_path = root / "spool" / "done" / "call.wav"
|
||||
audio_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
audio_path.write_bytes(b"audio")
|
||||
audio_file_id = storage.upsert_audio_file(
|
||||
AudioFileRecord(
|
||||
source_type="local",
|
||||
source_id="call.wav",
|
||||
checksum_sha256=sha256(audio_path.read_bytes()).hexdigest(),
|
||||
file_name="call.wav",
|
||||
file_path=audio_path,
|
||||
file_size_bytes=audio_path.stat().st_size,
|
||||
validation_status="done",
|
||||
spool_path=audio_path,
|
||||
duration_seconds=2.0,
|
||||
)
|
||||
)
|
||||
transcript_path = settings.paths.output_dir / "transcripts" / f"{audio_file_id:09d}.json"
|
||||
transcript_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
original_transcription = {
|
||||
"text": "Привет мир",
|
||||
"duration_seconds": 2.0,
|
||||
"segments": [
|
||||
{"index": 0, "start_seconds": 0.0, "end_seconds": 1.0, "text": "Привет"},
|
||||
{"index": 1, "start_seconds": 1.0, "end_seconds": 2.0, "text": "мир"},
|
||||
],
|
||||
}
|
||||
original_source_metadata = {"kept": True}
|
||||
transcript_payload = {
|
||||
"artifact_type": "transcript",
|
||||
"audio_file_id": audio_file_id,
|
||||
"source_id": "call.wav",
|
||||
"spool": {"path": str(audio_path)},
|
||||
"transcription": original_transcription,
|
||||
"source_metadata": original_source_metadata,
|
||||
"diarization": {"status": "placeholder", "is_placeholder": True},
|
||||
}
|
||||
transcript_path.write_text(json.dumps(transcript_payload, ensure_ascii=False), encoding="utf-8")
|
||||
storage.upsert_artifact(
|
||||
ArtifactRecord(
|
||||
audio_file_id=audio_file_id,
|
||||
kind="transcript",
|
||||
format="json",
|
||||
file_path=transcript_path,
|
||||
checksum_sha256=sha256(transcript_path.read_bytes()).hexdigest(),
|
||||
)
|
||||
)
|
||||
backend = _FakeDiarizationBackend(turns=(SpeakerTurn("SPEAKER_00", 0.0, 2.0),))
|
||||
|
||||
summary = diarize_completed_audio_files(storage, settings, backend=backend)
|
||||
|
||||
self.assertEqual(summary.scanned, 1)
|
||||
self.assertEqual(summary.diarized, 1)
|
||||
self.assertEqual(summary.failed, 0)
|
||||
updated = json.loads(transcript_path.read_text(encoding="utf-8"))
|
||||
self.assertEqual(updated["transcription"], original_transcription)
|
||||
self.assertEqual(updated["source_metadata"], original_source_metadata)
|
||||
self.assertEqual(updated["diarization"]["status"], "done")
|
||||
self.assertEqual(updated["diarization"]["segments"][0]["speaker"], "SPEAKER_00")
|
||||
|
||||
|
||||
if __name__ == "__main__": # pragma: no cover
|
||||
unittest.main()
|
||||
Loading…
Reference in New Issue