diff --git a/CHANGELOG.md b/CHANGELOG.md index 76af3d8..f6339eb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,17 +9,6 @@ All notable changes to this project will be documented here. - Repair layouts before online discovery and during offline scans, imports, and manifest reconciliation. - Safely merge duplicate old/current paths, deduplicate identical data, and archive conflicting older files and artifacts. - Preserve orphaned and ID-less bundles without presenting them as current LMS activities. - -## 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. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c80513b..6478517 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -17,10 +17,3 @@ 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. diff --git a/README.md b/README.md index f5a4886..c9c591a 100644 --- a/README.md +++ b/README.md @@ -263,20 +263,11 @@ 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. - -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. +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. Long runs are designed to resume safely: -- Existing output is skipped only when its source metadata, Whisper model, - language, decoding profile, and prompt fingerprint still match. +- Existing output is skipped only when its source size and modification time, Whisper model, and language 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. @@ -295,15 +286,6 @@ 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 @@ -317,23 +299,9 @@ 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" ``` -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. +The `large` model needs substantial memory. Use `small` or `turbo` if the machine cannot load it. The first run may download model weights. ## Codex summaries @@ -434,7 +402,6 @@ 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] diff --git a/TRANSCRIPTION.md b/TRANSCRIPTION.md deleted file mode 100644 index 1979a36..0000000 --- a/TRANSCRIPTION.md +++ /dev/null @@ -1,131 +0,0 @@ -# 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. diff --git a/src/ravin/cli.py b/src/ravin/cli.py index 1018a3c..85767de 100644 --- a/src/ravin/cli.py +++ b/src/ravin/cli.py @@ -26,12 +26,7 @@ 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 ( - TRANSCRIPTION_PROFILES, - TranscriptionOptions, - format_transcription_result, - transcribe_courses, -) +from .transcribe import TranscriptionOptions, format_transcription_result, transcribe_courses def build_parser() -> argparse.ArgumentParser: @@ -98,20 +93,6 @@ 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)" ) @@ -322,27 +303,6 @@ 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, @@ -350,9 +310,6 @@ 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, diff --git a/src/ravin/transcribe.py b/src/ravin/transcribe.py index ff7ee16..11dab62 100644 --- a/src/ravin/transcribe.py +++ b/src/ravin/transcribe.py @@ -3,7 +3,6 @@ from __future__ import annotations import gc -import hashlib import json import os import shutil @@ -22,9 +21,6 @@ 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() @@ -121,7 +117,6 @@ 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 @@ -138,76 +133,6 @@ 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( @@ -250,9 +175,6 @@ 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 @@ -310,7 +232,6 @@ 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, @@ -331,7 +252,6 @@ 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), }, ) @@ -392,13 +312,12 @@ class CourseTranscriber: def _expected_metadata(self, job: TranscriptionJob) -> dict[str, Any]: source_stat = job.source.stat() return { - "schema_version": 2, + "schema_version": 1, "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", } @@ -469,7 +388,6 @@ class CourseTranscriber: "error": public_message, "model": self.options.model, "language": self.options.language, - "transcription_settings": _transcription_settings(self.options), "attempts": self.options.retries + 1, }, ) @@ -485,11 +403,6 @@ 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() @@ -516,9 +429,6 @@ 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 @@ -533,11 +443,7 @@ 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), - verbose=False, - **_decode_options(self.options, device), - ), + lambda: model.transcribe(str(job.source), language=self.options.language, verbose=False), job, "transcription", ) diff --git a/tests/test_ravin.py b/tests/test_ravin.py index 1c5309b..a9e3f9e 100644 --- a/tests/test_ravin.py +++ b/tests/test_ravin.py @@ -93,26 +93,9 @@ 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", - "--profile", - "balanced", - "--prompt", - "Expected terminology", - "--threads", - "4", - "--no-keep-awake", - ] - ) + transcribe = build_parser().parse_args(["transcribe", "44", "--model", "small", "--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]) diff --git a/tests/test_transcribe.py b/tests/test_transcribe.py index 6427ad1..09bddc3 100644 --- a/tests/test_transcribe.py +++ b/tests/test_transcribe.py @@ -20,12 +20,10 @@ 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: @@ -111,19 +109,12 @@ 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( @@ -148,45 +139,6 @@ 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"})