feat(transcribe): improve accuracy, performance, and prompt privacy

- add accurate, balanced, and fast Whisper profiles
- improve long-audio decoding and hallucination control
- add privacy-safe prompts and cache invalidation
- enable accelerator-aware FP16 and configurable CPU threads
- document transcription practices and prepare release 0.15.0
This commit is contained in:
Meghdad committed 2026-08-27 20:38:57 +03:30
1 parent 3c59bea0f0
commit dc89eace0a
10 files changed
+393 -10

No files matched your search

+10
View File
@@ -2,6 +2,16 @@
All notable changes to this project will be documented here.
## 0.15.0 - 2026-08-27
- Add accurate, balanced, and fast Whisper decoding profiles.
- Improve long-audio accuracy with beam search, temperature fallback, timestamped
hallucination control, and disabled previous-window conditioning.
- Add opt-in domain prompts, privacy-safe prompt fingerprints, accelerator-aware
FP16, and configurable CPU threads.
- Invalidate cached transcripts when output-affecting transcription settings
change and document the transcription accuracy and privacy policy.
## 0.14.0 - 2026-08-13
- Add `ravin import URL` for restoring backups and updating course mirrors from direct export links.
+7
View File
@@ -17,3 +17,10 @@ Contributions are welcome. Keep changes focused, dependency-free where practical
5. Open a pull request describing the problem, approach, and test coverage.
Tests must use synthetic data. Do not include real course content, account identifiers, session values, or credentials in fixtures or issue reports.
## Transcription changes
Read [TRANSCRIPTION.md](TRANSCRIPTION.md) before modifying Whisper models,
decoding parameters, prompts, media preprocessing, or transcript cache metadata.
Transcription tests and examples must use neutral synthetic terminology rather
than vocabulary copied from private course recordings.
+36 -3
View File
@@ -240,11 +240,20 @@ The command reads local course manifests and does not contact or log in to the L
ravin transcribe
```
Each successful lesson produces `artifacts/transcript.fa.txt` and portable `artifacts/transcript.meta.json`. The course manifest and global catalog are reconciled after every file, so the transcript becomes available in the library immediately.
Each successful lesson produces `artifacts/transcript.fa.txt` and portable
`artifacts/transcript.meta.json`. The course manifest and global catalog are
reconciled after every file, so the transcript becomes available in the library
immediately.
The default `accurate` profile uses beam search, difficult-window fallback,
word-level timestamps, silence hallucination controls, and protection against
error propagation between long-audio windows. Domain prompts are disabled by
default and must be supplied explicitly.
Long runs are designed to resume safely:
- Existing output is skipped only when its source size and modification time, Whisper model, and language still match.
- Existing output is skipped only when its source metadata, Whisper model,
language, decoding profile, and prompt fingerprint still match.
- FFprobe validates the audio stream before Whisper starts.
- Each failed validation or transcription is retried twice by default, for three total attempts.
- A permanently failed lesson is recorded and the next lesson still runs.
@@ -263,6 +272,15 @@ ravin transcribe 44 --dry-run
# Use a smaller model or automatic language detection.
ravin transcribe 44 --model small --language auto
# Use the final-quality profile with expected domain terminology.
ravin transcribe 44 --profile accurate --prompt "Expected terms and proper nouns"
# Produce a faster draft with an explicit accuracy trade-off.
ravin transcribe 44 --model turbo --profile balanced
# Benchmark an explicit CPU thread count.
ravin transcribe 44 --threads 8
# Replace even matching transcripts.
ravin transcribe 44 --overwrite
@@ -276,9 +294,23 @@ The defaults can also be stored in `.env`:
WHISPER_MODEL="large"
WHISPER_DEVICE="auto"
WHISPER_LANGUAGE="fa"
WHISPER_PROFILE="accurate"
# WHISPER_THREADS="8"
# WHISPER_INITIAL_PROMPT="Expected domain terminology and proper nouns"
```
The `large` model needs substantial memory. Use `small` or `turbo` if the machine cannot load it. The first run may download model weights.
Available profiles are `accurate`, `balanced`, and `fast`. The `large` model
needs substantial memory. Use `small` or `turbo` only when the speed and memory
trade-off is acceptable. CUDA and Apple Metal are selected automatically when
available; FP16 is enabled only on supported accelerators. The first run may
download model weights.
The full prompt is never written to transcript metadata. A SHA-256 fingerprint
is stored instead, allowing safe cache invalidation without publishing course
vocabulary. Do not put credentials or secrets in a transcription prompt.
See [TRANSCRIPTION.md](TRANSCRIPTION.md) before changing Whisper settings,
preprocessing, cache behavior, or transcription tests.
## Codex summaries
@@ -379,6 +411,7 @@ ravin login
ravin scan [COURSE_ID ...] [--offline] [--json] [--public PATH]
ravin download COURSE_ID [--overwrite] [--retries N] [--json] [--public PATH]
ravin transcribe [COURSE_ID ...] [--model MODEL] [--device DEVICE] [--language LANGUAGE]
[--profile {accurate,balanced,fast}] [--prompt TEXT] [--threads N]
ravin summarize [COURSE_ID ...] [--model MODEL] [--retries N] [--timeout SECONDS]
ravin questions [COURSE_ID] [ACTIVITY_ID] [QUESTIONS.md] [--file ATTACHMENT ...]
ravin recording [COURSE_ID] [ACTIVITY_ID] [VIDEO]
+131
View File
@@ -0,0 +1,131 @@
# Transcription Accuracy, Performance, and Privacy
This policy applies to contributors and AI agents changing Ravin's local Whisper
pipeline.
## Required behavior
- Preserve source media. Preprocessing must write a separate temporary file.
- Use an explicit language when it is known. `--language auto` is available when
it is genuinely unknown.
- Keep domain prompts optional and disabled by default.
- Never commit prompts, examples, filenames, or transcript fragments copied from
private course recordings.
- Keep raw transcripts separate from summaries and interpreted study material.
- Treat uncertain proper nouns, numbers, and technical terms as uncertain.
- Test every quality change on representative, licensed or synthetic audio.
- Include every output-affecting option in cache metadata.
## Decoding profiles
The shared implementation is in `src/ravin/transcribe.py`.
### Accurate
The default final-quality profile uses:
```python
temperature = (0.0, 0.2, 0.4, 0.6, 0.8, 1.0)
beam_size = 5
best_of = 5
patience = 1.0
condition_on_previous_text = False
word_timestamps = True
hallucination_silence_threshold = 1.5
```
Disabling previous-text conditioning reduces repetition loops, timestamp drift,
and propagation of a bad window through long lectures. Word timestamps allow
Whisper to suppress likely hallucinations over long silence.
### Balanced
Balanced mode uses a smaller beam and temperature range without word timestamp
alignment. It is suitable for routine batch work when `accurate` is too slow.
### Fast
Fast mode uses deterministic greedy decoding without beam search or word
timestamps. It is intended for drafts, not final study material.
Do not silently replace `large-v3` with `turbo`. A model change is an explicit
quality trade-off.
## Prompt privacy
`--prompt` and `WHISPER_INITIAL_PROMPT` may contain expected terminology and
proper nouns. A prompt can improve spelling, but it can also bias Whisper toward
words that were not spoken.
- Keep prompts short and relevant.
- Compare prompted output with a trusted reference or an unprompted run.
- Never include passwords, tokens, cookies, or private account information.
- Never hard-code vocabulary derived from a private course.
- Store only a SHA-256 prompt fingerprint in metadata, never the prompt text.
Neutral example:
```bash
ravin transcribe 44 --prompt "Expected networking terms and protocol names"
```
## Device and performance rules
- `--device auto` prefers CUDA, then Apple Metal, then CPU.
- FP16 is enabled on CUDA and MPS, and disabled on CPU.
- The model must be loaded once per run and reused for all pending media.
- `--threads` and `WHISPER_THREADS` are optional CPU tuning controls. Benchmark
them because higher values are not always faster.
- MPS fallback is enabled before importing PyTorch so unsupported operations can
run on CPU instead of failing the complete transcription.
- Completed matching outputs must remain resumable and must not reload Whisper.
## Source inspection and preprocessing
Before adding filters, inspect the media:
```bash
ffprobe -v error \
-show_entries format=duration,size,bit_rate:stream=codec_name,sample_rate,channels \
-of default=noprint_wrappers=1 AUDIO
ffmpeg -hide_banner -i AUDIO -af volumedetect -f null -
ffmpeg -hide_banner -i AUDIO \
-af silencedetect=noise=-38dB:d=0.45 -f null -
```
Repeated peaks at `0.0 dB` can indicate clipping. Denoising, normalization,
frequency filtering, silence removal, and VAD must be validated by comparison;
blind preprocessing can remove quiet speech and word boundaries.
## Cache and metadata
Transcript cache matching must include:
- Source size and modification time
- Model and language
- Transcription settings schema version
- Accuracy profile
- Whether a prompt was set
- Prompt SHA-256 fingerprint
Changing any of these values must regenerate the transcript. Runtime state may
remain private under `.ravin/transcribe/`, while public artifact metadata must be
portable and must not expose absolute paths or raw prompts.
## Validation checklist
Before handing off a transcription change, verify:
- [ ] Known language selection and automatic detection both work.
- [ ] Accurate mode forwards beam, fallback, and hallucination settings.
- [ ] Fast mode does not accidentally enable beam search.
- [ ] CPU uses FP32 and accelerators use FP16.
- [ ] Prompt text is absent from metadata, state, summaries, and errors.
- [ ] A changed profile or prompt invalidates cached output.
- [ ] Empty or truncated output is handled as a result requiring review.
- [ ] Retry, interruption, atomic writes, and resume behavior still pass tests.
- [ ] Tests contain only synthetic course data and neutral terminology.
- [ ] `python3 -m unittest discover -s tests -v` passes.
- [ ] `python3 -m compileall -q src tests` passes.
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "ravin-moodle-downloader"
version = "0.14.0"
version = "0.15.0"
description = "Scan, download, transcribe, summarize, and organize authorized Moodle course materials"
readme = "README.md"
requires-python = ">=3.10"
+44 -1
View File
@@ -26,7 +26,12 @@ from .recordings import format_recording_result, import_recording, recording_wiz
from .scan import format_scan, scan_offline, scan_output, scan_remote, update_download_state
from .server import _serve_library
from .summarize import SummaryOptions, format_summary_result, summarize_courses
from .transcribe import TranscriptionOptions, format_transcription_result, transcribe_courses
from .transcribe import (
TRANSCRIPTION_PROFILES,
TranscriptionOptions,
format_transcription_result,
transcribe_courses,
)
def build_parser() -> argparse.ArgumentParser:
@@ -93,6 +98,20 @@ def build_parser() -> argparse.ArgumentParser:
transcribe_parser.add_argument(
"--language", help="Whisper language code; use 'auto' for detection (default: fa)"
)
transcribe_parser.add_argument(
"--profile",
choices=TRANSCRIPTION_PROFILES,
help="decoding profile; defaults to WHISPER_PROFILE or accurate",
)
transcribe_parser.add_argument(
"--prompt",
help="expected domain vocabulary and proper nouns; empty disables the environment prompt",
)
transcribe_parser.add_argument(
"--threads",
type=int,
help="PyTorch CPU thread count; defaults to WHISPER_THREADS or the PyTorch default",
)
transcribe_parser.add_argument(
"--retries", type=int, default=2, help="additional attempts per failed file (default: 2)"
)
@@ -303,6 +322,27 @@ def main(argv: list[str] | None = None) -> int:
else env_values.get("WHISPER_LANGUAGE", os.getenv("WHISPER_LANGUAGE", "fa"))
)
language = None if not language_value or language_value.casefold() == "auto" else language_value
profile = (
args.profile
or env_values.get("WHISPER_PROFILE")
or os.getenv("WHISPER_PROFILE")
or "accurate"
).casefold()
prompt_value = (
args.prompt
if args.prompt is not None
else env_values.get("WHISPER_INITIAL_PROMPT", os.getenv("WHISPER_INITIAL_PROMPT"))
)
initial_prompt = prompt_value.strip() if prompt_value and prompt_value.strip() else None
threads_value: str | int | None = (
args.threads
if args.threads is not None
else env_values.get("WHISPER_THREADS", os.getenv("WHISPER_THREADS"))
)
try:
threads = int(threads_value) if threads_value not in (None, "") else None
except (TypeError, ValueError) as exc:
raise MoodleError("WHISPER_THREADS must be a positive integer") from exc
result = transcribe_courses(
TranscriptionOptions(
public=public,
@@ -310,6 +350,9 @@ def main(argv: list[str] | None = None) -> int:
model=model,
device=device,
language=language,
profile=profile,
initial_prompt=initial_prompt,
threads=threads,
retries=args.retries,
overwrite=args.overwrite,
dry_run=args.dry_run,
+1 -1
View File
@@ -5,7 +5,7 @@ from pathlib import Path
DEFAULT_SITE = "https://training.ravinacademy.com"
DEFAULT_RAVIN_LOGIN_URL = "https://lms.ravinacademy.com/"
__version__ = "0.14.0"
__version__ = "0.15.0"
USER_AGENT = f"RavinMoodleDownloader/{__version__} (+personal Moodle client)"
DOWNLOADABLE_MODULES = {"resource", "folder", "page", "book"}
LIVE_CLASS_MODULES = {"bigbluebuttonbn", "zoom", "teamsmeeting", "webexactivity"}
+96 -2
View File
@@ -3,6 +3,7 @@
from __future__ import annotations
import gc
import hashlib
import json
import os
import shutil
@@ -21,6 +22,9 @@ from .models import MoodleError
from .paths import _clean_name, _read_json_object
from .scan import scan_offline
TRANSCRIPTION_PROFILES = ("accurate", "balanced", "fast")
TRANSCRIPTION_SETTINGS_VERSION = 1
def _utc_now() -> str:
return datetime.now(timezone.utc).isoformat()
@@ -117,6 +121,7 @@ def _select_device(torch: Any, requested: str) -> str:
def _load_model(model_name: str, requested_device: str) -> tuple[Any, Any, str]:
os.environ.setdefault("PYTORCH_ENABLE_MPS_FALLBACK", "1")
try:
import torch
import whisper
@@ -133,6 +138,76 @@ def _load_model(model_name: str, requested_device: str) -> tuple[Any, Any, str]:
return model, torch, device
def _configure_threads(torch: Any, requested: int | None) -> int | None:
if torch is None:
return None
if requested is not None:
if requested < 1:
raise MoodleError("--threads must be a positive integer")
torch.set_num_threads(requested)
return int(torch.get_num_threads())
def _transcription_settings(options: "TranscriptionOptions") -> dict[str, Any]:
initial_prompt = options.initial_prompt.strip() if options.initial_prompt else None
prompt_fingerprint = (
hashlib.sha256(initial_prompt.encode("utf-8")).hexdigest()
if initial_prompt
else None
)
return {
"version": TRANSCRIPTION_SETTINGS_VERSION,
"profile": options.profile,
"initial_prompt_set": initial_prompt is not None,
"initial_prompt_sha256": prompt_fingerprint,
}
def _decode_options(
options: "TranscriptionOptions",
device: str,
) -> dict[str, Any]:
common: dict[str, Any] = {
"language": options.language,
"task": "transcribe",
"condition_on_previous_text": False,
"fp16": device in {"cuda", "mps"},
"compression_ratio_threshold": 2.4,
"logprob_threshold": -1.0,
"no_speech_threshold": 0.6,
}
initial_prompt = options.initial_prompt.strip() if options.initial_prompt else None
if initial_prompt:
common.update(
initial_prompt=initial_prompt,
carry_initial_prompt=True,
)
if options.profile == "accurate":
common.update(
temperature=(0.0, 0.2, 0.4, 0.6, 0.8, 1.0),
beam_size=5,
best_of=5,
patience=1.0,
word_timestamps=True,
hallucination_silence_threshold=1.5,
)
elif options.profile == "balanced":
common.update(
temperature=(0.0, 0.2, 0.4),
beam_size=3,
best_of=3,
patience=1.0,
word_timestamps=False,
)
else:
common.update(
temperature=0.0,
word_timestamps=False,
)
return common
def _validate_media(source: Path) -> None:
try:
result = subprocess.run(
@@ -175,6 +250,9 @@ class TranscriptionOptions:
model: str = "large"
device: str = "auto"
language: str | None = "fa"
profile: str = "accurate"
initial_prompt: str | None = None
threads: int | None = None
retries: int = 2
overwrite: bool = False
dry_run: bool = False
@@ -232,6 +310,7 @@ class CourseTranscriber:
"model": self.options.model,
"device": self.options.device,
"language": self.options.language,
"transcription_settings": _transcription_settings(self.options),
"course_ids": list(self.options.course_ids),
"current_index": self.current_index,
"current": self.current_job.label() if self.current_job else None,
@@ -252,6 +331,7 @@ class CourseTranscriber:
"model": self.options.model,
"device": self.options.device,
"language": self.options.language,
"transcription_settings": _transcription_settings(self.options),
"course_ids": list(self.options.course_ids),
},
)
@@ -312,12 +392,13 @@ class CourseTranscriber:
def _expected_metadata(self, job: TranscriptionJob) -> dict[str, Any]:
source_stat = job.source.stat()
return {
"schema_version": 1,
"schema_version": 2,
"source": f"../files/{job.source.name}",
"source_size": source_stat.st_size,
"source_mtime_ns": source_stat.st_mtime_ns,
"model": self.options.model,
"language": self.options.language,
"transcription_settings": _transcription_settings(self.options),
"transcript": "transcript.fa.txt",
}
@@ -388,6 +469,7 @@ class CourseTranscriber:
"error": public_message,
"model": self.options.model,
"language": self.options.language,
"transcription_settings": _transcription_settings(self.options),
"attempts": self.options.retries + 1,
},
)
@@ -403,6 +485,11 @@ class CourseTranscriber:
def run(self) -> TranscriptionResult:
if self.options.retries < 0:
raise MoodleError("--retries cannot be negative")
if self.options.profile not in TRANSCRIPTION_PROFILES:
choices = ", ".join(TRANSCRIPTION_PROFILES)
raise MoodleError(f"--profile must be one of: {choices}")
if self.options.threads is not None and self.options.threads < 1:
raise MoodleError("--threads must be a positive integer")
if not self.options.dry_run:
scan_offline(self.public, self.options.course_ids)
jobs = self._discover_jobs()
@@ -429,6 +516,9 @@ class CourseTranscriber:
self._write_state()
try:
model, self._torch, device = self.model_loader(self.options.model, self.options.device)
active_threads = _configure_threads(self._torch, self.options.threads)
if device == "cpu" and active_threads is not None:
print(f"Using {active_threads} CPU thread(s).", file=sys.stderr)
except Exception:
self._finish("failed_to_start", 2)
raise
@@ -443,7 +533,11 @@ class CourseTranscriber:
if self.options.validate_media:
self._with_retries(lambda: self.media_validator(job.source), job, "validation")
result = self._with_retries(
lambda: model.transcribe(str(job.source), language=self.options.language, verbose=False),
lambda: model.transcribe(
str(job.source),
verbose=False,
**_decode_options(self.options, device),
),
job,
"transcription",
)
+18 -1
View File
@@ -93,9 +93,26 @@ class ParserTests(unittest.TestCase):
download = build_parser().parse_args(["download", "44", "--retries", "2"])
self.assertEqual(download.course_id, 44)
self.assertEqual(download.retries, 2)
transcribe = build_parser().parse_args(["transcribe", "44", "--model", "small", "--no-keep-awake"])
transcribe = build_parser().parse_args(
[
"transcribe",
"44",
"--model",
"small",
"--profile",
"balanced",
"--prompt",
"Expected terminology",
"--threads",
"4",
"--no-keep-awake",
]
)
self.assertEqual(transcribe.course_ids, [44])
self.assertEqual(transcribe.model, "small")
self.assertEqual(transcribe.profile, "balanced")
self.assertEqual(transcribe.prompt, "Expected terminology")
self.assertEqual(transcribe.threads, 4)
self.assertFalse(transcribe.keep_awake)
summarize = build_parser().parse_args(["summarize", "44", "--model", "gpt-test"])
self.assertEqual(summarize.course_ids, [44])
+49 -1
View File
@@ -20,10 +20,12 @@ class FakeModel:
self.failures = failures or set()
self.interrupt = interrupt
self.calls: list[str] = []
self.call_options: list[dict[str, object]] = []
def transcribe(self, source: str, **_kwargs: object) -> dict[str, str]:
def transcribe(self, source: str, **kwargs: object) -> dict[str, str]:
name = Path(source).name
self.calls.append(name)
self.call_options.append(kwargs)
if self.interrupt:
raise KeyboardInterrupt
if name in self.failures:
@@ -109,12 +111,19 @@ class TranscriptionTests(unittest.TestCase):
self.assertEqual(result.exit_code, 0)
self.assertEqual(result.succeeded, 1)
self.assertEqual(model.calls, ["lesson.mp4"])
self.assertEqual(model.call_options[0]["beam_size"], 5)
self.assertFalse(model.call_options[0]["condition_on_previous_text"])
self.assertTrue(model.call_options[0]["word_timestamps"])
self.assertFalse(model.call_options[0]["fp16"])
artifacts = self.public / "courses" / "44" / "content" / "002--001--4901" / "artifacts"
transcript = artifacts / "transcript.fa.txt"
metadata = json.loads((artifacts / "transcript.meta.json").read_text(encoding="utf-8"))
self.assertEqual(transcript.read_text(encoding="utf-8"), "transcript for lesson.mp4\n")
self.assertEqual(metadata["source"], "../files/lesson.mp4")
self.assertEqual(metadata["transcript"], "transcript.fa.txt")
self.assertEqual(metadata["schema_version"], 2)
self.assertEqual(metadata["transcription_settings"]["profile"], "accurate")
self.assertFalse(metadata["transcription_settings"]["initial_prompt_set"])
self.assertNotIn(str(self.root), json.dumps(metadata))
self.assertEqual(os.stat(transcript).st_mode & 0o777, 0o644)
manifest = json.loads(
@@ -139,6 +148,45 @@ class TranscriptionTests(unittest.TestCase):
self.assertEqual(second.skipped, 1)
self.assertFalse(second_loader_called)
def test_prompt_is_fingerprinted_and_invalidates_cached_output(self) -> None:
self.write_course(["lesson.mp4"])
private_prompt = "Confidential course vocabulary"
first_model = FakeModel()
first = self.transcriber(first_model, initial_prompt=private_prompt).run()
self.assertEqual(first.succeeded, 1)
artifacts = self.public / "courses" / "44" / "content" / "002--001--4901" / "artifacts"
metadata = json.loads((artifacts / "transcript.meta.json").read_text(encoding="utf-8"))
serialized = json.dumps(metadata)
self.assertNotIn(private_prompt, serialized)
settings = metadata["transcription_settings"]
self.assertTrue(settings["initial_prompt_set"])
self.assertEqual(len(settings["initial_prompt_sha256"]), 64)
self.assertEqual(first_model.call_options[0]["initial_prompt"], private_prompt)
second_model = FakeModel()
second = self.transcriber(
second_model,
initial_prompt="Different vocabulary",
).run()
self.assertEqual(second.succeeded, 1)
self.assertEqual(second.skipped, 0)
self.assertEqual(second_model.calls, ["lesson.mp4"])
def test_fast_profile_uses_greedy_decoding(self) -> None:
self.write_course(["lesson.mp4"])
model = FakeModel()
result = self.transcriber(model, profile="fast").run()
self.assertEqual(result.succeeded, 1)
options = model.call_options[0]
self.assertEqual(options["temperature"], 0.0)
self.assertNotIn("beam_size", options)
self.assertFalse(options["word_timestamps"])
def test_permanent_failure_is_retried_recorded_and_does_not_stop_batch(self) -> None:
self.write_course(["bad.mp4", "good.mp4"])
model = FakeModel({"bad.mp4"})