From 314b099142f4adac0622a15fb21b4a250cb327ac Mon Sep 17 00:00:00 2001 From: Meghdad <61308304+MeghdadFadaee@users.noreply.github.com> Date: Tue, 4 Aug 2026 22:37:41 +0330 Subject: [PATCH] feat: unify course scanning and add manifest-based public library --- .env.example | 5 + .github/workflows/ci.yml | 7 +- .gitignore | 1 + CHANGELOG.md | 10 + README.md | 67 +++++- pyproject.toml | 12 +- src/ravin/cli.py | 68 +++++- src/ravin/constants.py | 2 +- src/ravin/scan.py | 15 +- src/ravin/transcribe.py | 500 +++++++++++++++++++++++++++++++++++++++ tests/test_ravin.py | 4 + tests/test_transcribe.py | 195 +++++++++++++++ 12 files changed, 872 insertions(+), 14 deletions(-) create mode 100644 src/ravin/transcribe.py create mode 100644 tests/test_transcribe.py diff --git a/.env.example b/.env.example index fa603b5..67c705c 100644 --- a/.env.example +++ b/.env.example @@ -4,3 +4,8 @@ RAVIN_PASSWORD="" RAVIN_LOGIN_URL="https://lms.ravinacademy.com/" RAVIN_USER_AGENT="" RAVIN_COOKIE="" + +# Optional defaults for `ravin transcribe`. +WHISPER_MODEL="large" +WHISPER_DEVICE="auto" +WHISPER_LANGUAGE="fa" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 98a472f..b040c65 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,10 +26,10 @@ jobs: python-version: ${{ matrix.python-version }} - name: Run tests - run: python -m unittest -v + run: python -m unittest discover -s tests -v - name: Check syntax - run: python -m py_compile ravin_downloader.py + run: python -m compileall -q src tests - name: Confirm secrets stay untracked run: | @@ -41,4 +41,5 @@ jobs: - name: Verify package installation run: | python -m pip install . - ravin-downloader --version + ravin --version + ravin transcribe --help diff --git a/.gitignore b/.gitignore index a24622a..bff65da 100644 --- a/.gitignore +++ b/.gitignore @@ -127,6 +127,7 @@ celerybeat.pid # Environments .env +.ravin/ .ravin-browser-profile/ .venv env/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 998ad47..a61e18c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ All notable changes to this project will be documented here. +## 0.7.0 - 2026-08-04 + +- Add a manifest-driven `ravin transcribe` command using OpenAI Whisper. +- Discover downloaded video and audio in LMS order and update course manifests after every result. +- Resume safely by matching source metadata, Whisper model, and language before skipping completed transcripts. +- Validate media with FFprobe, retry individual failures, continue with later lessons, and persist private run state and error logs. +- Record failed transcript state in course manifests without exposing machine-specific paths. +- Keep macOS awake during long runs and preserve atomic transcript and metadata writes across interruption. +- Add the optional `transcribe` dependency group for the large Whisper and PyTorch runtime. + ## 0.6.0 - 2026-08-04 - Replace the separate course, file, and library builders with one `ravin scan` command. diff --git a/README.md b/README.md index 6c17fb0..2c82453 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Ravin Moodle Downloader -A small command-line client for scanning authorized Moodle courses, downloading their files, and browsing them in a private static learning library. It defaults to Ravin Academy and can target another Moodle base URL with `--site`. +A small command-line client for scanning authorized Moodle courses, downloading and transcribing their files, and browsing them in a private static learning library. It defaults to Ravin Academy and can target another Moodle base URL with `--site`. The client tries Moodle's mobile API first, falls back to its authenticated web interface, and can establish a real browser session for sites protected by Cloudflare. @@ -14,6 +14,7 @@ Requirements: - Python 3.10 or newer - An active enrollment on the target Moodle site - Zen, Firefox, Chrome, Chromium, or Brave for automatic browser login +- FFmpeg when using local Whisper transcription From the repository root: @@ -23,12 +24,20 @@ python3 -m pip install . This installs the `ravin` command and its browser automation dependency. The equivalent module entry point is `python3 -m ravin`. +Whisper and PyTorch are large, platform-specific dependencies, so install them only on the machine that will transcribe media: + +```bash +brew install ffmpeg +python3 -m pip install '.[transcribe]' +``` + ## Quick start ```bash ravin login ravin scan ravin download COURSE_ID +ravin transcribe COURSE_ID ravin serve --open ``` @@ -102,6 +111,60 @@ The scanner reports each applicable file, transcript, summary, and assessment as The downloader updates the course manifest after every completed file. A final offline scan reconciles all totals, so an interrupted run still retains useful progress. +## Whisper transcription + +After downloading a course, transcribe its video and audio in LMS order: + +```bash +ravin transcribe 44 +``` + +The command reads local course manifests and does not contact or log in to the LMS. With no course IDs it processes all local courses: + +```bash +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. + +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. +- 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. +- Transcript and metadata writes are atomic, so interruption cannot leave a completed-looking partial file. +- macOS sleep is prevented by default while transcription is active. +- `SIGINT` and `SIGTERM` preserve completed work and write an interrupted state for the next run. + +Private run state, the final summary, and the append-only error log live under `.ravin/transcribe/`, outside the served `public/` directory. Rerun the same command to skip completed work and retry failures. + +Useful options: + +```bash +# Preview pending lessons without loading Whisper. +ravin transcribe 44 --dry-run + +# Use a smaller model or automatic language detection. +ravin transcribe 44 --model small --language auto + +# Replace even matching transcripts. +ravin transcribe 44 --overwrite + +# Change the retry count or allow macOS to sleep. +ravin transcribe 44 --retries 4 --no-keep-awake +``` + +The defaults can also be stored in `.env`: + +```dotenv +WHISPER_MODEL="large" +WHISPER_DEVICE="auto" +WHISPER_LANGUAGE="fa" +``` + +The `large` model needs substantial memory. Use `small` or `turbo` if the machine cannot load it. The first run may download model weights. + ## Static learning library The web interface is already present in the tracked `public/` directory. Generate or refresh its private data, then serve it: @@ -162,6 +225,7 @@ When an older generated `library/courses.json` exists and `public/` has no manif 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] ravin serve [--host ADDRESS] [--port PORT] [--open] [--public PATH] ``` @@ -180,6 +244,7 @@ src/ravin/ ├── paths.py # portable content paths and artifacts ├── catalog.py # remote course catalog construction ├── scan.py # manifests and local state reconciliation +├── transcribe.py # resilient manifest-driven Whisper batches ├── migration.py # previous-layout migration ├── server.py # local range-aware HTTP server └── models.py # shared value objects and errors diff --git a/pyproject.toml b/pyproject.toml index 9b9a869..16ce26b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,13 +4,13 @@ build-backend = "setuptools.build_meta" [project] name = "ravin-moodle-downloader" -version = "0.6.0" -description = "Scan, download, and browse authorized Moodle course materials" +version = "0.7.0" +description = "Scan, download, transcribe, and browse authorized Moodle course materials" readme = "README.md" requires-python = ">=3.10" license = "MIT" authors = [{name = "Meghdad Fadaee"}] -keywords = ["moodle", "downloader", "lms", "education"] +keywords = ["moodle", "downloader", "lms", "education", "whisper", "transcription"] classifiers = [ "Development Status :: 3 - Alpha", "Environment :: Console", @@ -26,6 +26,12 @@ classifiers = [ ] dependencies = ["selenium>=4.46,<5"] +[project.optional-dependencies] +transcribe = [ + "openai-whisper==20250625", + "torch==2.13.0", +] + [project.scripts] ravin = "ravin.cli:main" diff --git a/src/ravin/cli.py b/src/ravin/cli.py index a8607ea..425b77a 100644 --- a/src/ravin/cli.py +++ b/src/ravin/cli.py @@ -4,6 +4,7 @@ from __future__ import annotations import argparse import json +import os import sys from pathlib import Path @@ -20,6 +21,7 @@ from .migration import migrate_library_to_public from .models import MoodleError from .scan import format_scan, scan_offline, scan_output, scan_remote, update_download_state from .server import _serve_library +from .transcribe import TranscriptionOptions, format_transcription_result, transcribe_courses def build_parser() -> argparse.ArgumentParser: @@ -71,6 +73,40 @@ def build_parser() -> argparse.ArgumentParser: download_parser.add_argument("--retries", type=int, default=5, help="retry interrupted files (default: 5)") download_parser.add_argument("--json", action="store_true", help="print downloaded paths as JSON") + transcribe_parser = subparsers.add_parser( + "transcribe", + help="transcribe downloaded course media with Whisper", + ) + transcribe_parser.add_argument( + "course_ids", nargs="*", type=int, help="optional course IDs; defaults to all local courses" + ) + transcribe_parser.add_argument("--public", type=Path, default=Path("public"), help="public web root") + transcribe_parser.add_argument("--model", help="Whisper model; defaults to WHISPER_MODEL or large") + transcribe_parser.add_argument( + "--device", choices=("auto", "cpu", "cuda", "mps"), help="compute device; defaults to auto" + ) + transcribe_parser.add_argument( + "--language", help="Whisper language code; use 'auto' for detection (default: fa)" + ) + transcribe_parser.add_argument( + "--retries", type=int, default=2, help="additional attempts per failed file (default: 2)" + ) + transcribe_parser.add_argument("--overwrite", action="store_true", help="replace matching transcripts") + transcribe_parser.add_argument("--dry-run", action="store_true", help="show pending media without loading Whisper") + transcribe_parser.add_argument( + "--keep-awake", + action=argparse.BooleanOptionalAction, + default=sys.platform == "darwin", + help="prevent macOS sleep while running (default: enabled on macOS)", + ) + transcribe_parser.add_argument( + "--validate-media", + action=argparse.BooleanOptionalAction, + default=True, + help="check for a readable audio stream with ffprobe (default: enabled)", + ) + transcribe_parser.add_argument("--json", action="store_true", help="print the final result as JSON") + serve_parser = subparsers.add_parser("serve", help="serve the public learning library locally") serve_parser.add_argument("--public", type=Path, default=Path("public"), help="public web root") serve_parser.add_argument("--host", default="127.0.0.1", help="local bind address") @@ -118,7 +154,7 @@ def main(argv: list[str] | None = None) -> int: return 0 public = getattr(args, "public", Path("public")).expanduser().resolve() - if args.command in {"scan", "download"}: + if args.command in {"scan", "download", "transcribe"}: _maybe_migrate(public) if args.command == "scan" and args.offline: @@ -126,6 +162,36 @@ def main(argv: list[str] | None = None) -> int: print(json.dumps(scan_output(catalog), ensure_ascii=False, indent=2) if args.json else format_scan(catalog)) return 0 + if args.command == "transcribe": + env_values = _load_env_file(args.env_file) + model = args.model or env_values.get("WHISPER_MODEL") or os.getenv("WHISPER_MODEL") or "large" + device = args.device or env_values.get("WHISPER_DEVICE") or os.getenv("WHISPER_DEVICE") or "auto" + language_value = ( + args.language + if args.language is not None + 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 + result = transcribe_courses( + TranscriptionOptions( + public=public, + course_ids=tuple(args.course_ids), + model=model, + device=device, + language=language, + retries=args.retries, + overwrite=args.overwrite, + dry_run=args.dry_run, + keep_awake=args.keep_awake, + validate_media=args.validate_media, + ) + ) + print( + json.dumps(result.to_dict(), ensure_ascii=False, indent=2) + if args.json else format_transcription_result(result) + ) + return result.exit_code + args.env_values = _load_env_file(args.env_file) if args.command == "login": _client, mode = _authenticate_browser_session(args) diff --git a/src/ravin/constants.py b/src/ravin/constants.py index 0789967..652778f 100644 --- a/src/ravin/constants.py +++ b/src/ravin/constants.py @@ -5,7 +5,7 @@ from pathlib import Path DEFAULT_SITE = "https://training.ravinacademy.com" DEFAULT_RAVIN_LOGIN_URL = "https://lms.ravinacademy.com/" -__version__ = "0.6.0" +__version__ = "0.7.0" USER_AGENT = f"RavinMoodleDownloader/{__version__} (+personal Moodle client)" DOWNLOADABLE_MODULES = {"resource", "folder", "page", "book"} DEFAULT_ENV_FILE = Path.cwd() / ".env" diff --git a/src/ravin/scan.py b/src/ravin/scan.py index af5480f..aeb80d9 100644 --- a/src/ravin/scan.py +++ b/src/ravin/scan.py @@ -94,8 +94,11 @@ def _artifact_state(activity_directory: Path, kind: str, applicable: bool) -> st artifacts = activity_directory / "artifacts" if kind == "transcript": transcript = artifacts / "transcript.fa.txt" + failed = (artifacts / ".transcript.error.json").is_file() if not transcript.is_file(): - return "missing" if applicable else "not_applicable" + if not applicable: + return "not_applicable" + return "error" if failed else "missing" metadata = _read_json_object(artifacts / "transcript.meta.json") source_files: list[Path] = [] source_name = metadata.get("source") if metadata else None @@ -114,14 +117,14 @@ def _artifact_state(activity_directory: Path, kind: str, applicable: bool) -> st if path.is_file() and not path.name.endswith(".part") ) if not metadata or not source_files: - return "stale" + return "error" if failed else "stale" source_stat = source_files[0].stat() expected_size = metadata.get("source_size") expected_mtime = metadata.get("source_mtime_ns") if expected_size is not None and int(expected_size) != source_stat.st_size: - return "stale" + return "error" if failed else "stale" if expected_mtime is not None and int(expected_mtime) != source_stat.st_mtime_ns: - return "stale" + return "error" if failed else "stale" return "complete" if kind == "summary": @@ -232,7 +235,9 @@ def _reconcile_course(public: Path, course: dict[str, Any]) -> dict[str, Any]: state_counts["assessments"]["complete"] += int(questions_state == "complete") state_counts["partial"] += int(download_state == "partial") state_counts["stale"] += sum(value == "stale" for value in (transcript_state, summary_state)) - state_counts["errors"] += int(download_state == "error") + state_counts["errors"] += sum( + value == "error" for value in (download_state, transcript_state, summary_state, questions_state) + ) kind = str(item.get("kind") or "activity") type_counts[kind] = type_counts.get(kind, 0) + 1 diff --git a/src/ravin/transcribe.py b/src/ravin/transcribe.py new file mode 100644 index 0000000..5222f80 --- /dev/null +++ b/src/ravin/transcribe.py @@ -0,0 +1,500 @@ +"""Resilient manifest-driven Whisper transcription.""" + +from __future__ import annotations + +import gc +import json +import os +import shutil +import signal +import subprocess +import sys +import tempfile +import time +from contextlib import contextmanager +from dataclasses import asdict, dataclass +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Callable, Iterator + +from .models import MoodleError +from .paths import _read_json_object +from .scan import scan_offline + + +def _utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def _atomic_text(path: Path, content: str, *, mode: int | None = None) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary_path: Path | None = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + dir=path.parent, + prefix=f".{path.name}.", + suffix=".tmp", + delete=False, + ) as temporary: + temporary.write(content) + temporary.flush() + os.fsync(temporary.fileno()) + temporary_path = Path(temporary.name) + if mode is not None: + os.chmod(temporary_path, mode) + os.replace(temporary_path, path) + finally: + if temporary_path is not None: + temporary_path.unlink(missing_ok=True) + + +def _atomic_json(path: Path, value: dict[str, Any], *, mode: int | None = None) -> None: + _atomic_text(path, json.dumps(value, ensure_ascii=False, indent=2) + "\n", mode=mode) + + +def _append_json_line(path: Path, value: dict[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("a", encoding="utf-8") as output: + output.write(json.dumps(value, ensure_ascii=False) + "\n") + output.flush() + os.fsync(output.fileno()) + + +def _compact_error(error: BaseException, limit: int = 4000) -> str: + message = str(error).strip() or type(error).__name__ + return message if len(message) <= limit else message[:limit] + "\n... error truncated ..." + + +@contextmanager +def _exclusive_lock(path: Path) -> Iterator[None]: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("a+", encoding="utf-8") as lock: + try: + import fcntl + + fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError as exc: + lock.seek(0) + owner = lock.read().strip() or "unknown" + raise MoodleError(f"another transcription run is active (PID {owner})") from exc + except (ImportError, OSError): + pass + lock.seek(0) + lock.truncate() + lock.write(str(os.getpid())) + lock.flush() + yield + + +def _start_caffeinate(enabled: bool) -> subprocess.Popen[bytes] | None: + executable = shutil.which("caffeinate") + if not enabled or sys.platform != "darwin" or not executable: + return None + return subprocess.Popen( + [executable, "-i", "-w", str(os.getpid())], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + + +def _select_device(torch: Any, requested: str) -> str: + device = requested.casefold() + if device == "auto": + if torch.cuda.is_available(): + return "cuda" + if torch.backends.mps.is_available(): + return "mps" + return "cpu" + if device == "cuda" and not torch.cuda.is_available(): + raise MoodleError("CUDA was requested, but no CUDA device is available") + if device == "mps" and not torch.backends.mps.is_available(): + raise MoodleError("MPS was requested, but Apple Metal acceleration is unavailable") + if device not in {"cpu", "cuda", "mps"}: + raise MoodleError("--device must be one of: auto, cpu, cuda, mps") + return device + + +def _load_model(model_name: str, requested_device: str) -> tuple[Any, Any, str]: + try: + import torch + import whisper + except ImportError as exc: + raise MoodleError( + "Whisper support is not installed; run `python3 -m pip install '.[transcribe]'`" + ) from exc + device = _select_device(torch, requested_device) + print(f"Loading Whisper model {model_name!r} on {device}...", file=sys.stderr) + try: + model = whisper.load_model(model_name, device=device) + except Exception as exc: + raise MoodleError(f"could not load Whisper model {model_name!r}: {_compact_error(exc)}") from exc + return model, torch, device + + +def _validate_media(source: Path) -> None: + try: + result = subprocess.run( + [ + "ffprobe", "-v", "error", "-select_streams", "a:0", + "-show_entries", "stream=index", "-of", "csv=p=0", str(source), + ], + capture_output=True, + text=True, + timeout=90, + ) + except FileNotFoundError as exc: + raise MoodleError("FFmpeg is required; install it with `brew install ffmpeg`") from exc + if result.returncode != 0: + reason = result.stderr.strip().splitlines()[-1:] or ["invalid media file"] + raise ValueError(reason[0]) + if not result.stdout.strip(): + raise ValueError("media file contains no audio stream") + + +@dataclass(frozen=True) +class TranscriptionJob: + course_id: int + activity_id: int | None + key: str + title: str + source: Path + transcript: Path + metadata: Path + error_marker: Path + + def label(self) -> str: + return f"course {self.course_id} / {self.key} / {self.source.name}" + + +@dataclass(frozen=True) +class TranscriptionOptions: + public: Path + course_ids: tuple[int, ...] = () + model: str = "large" + device: str = "auto" + language: str | None = "fa" + retries: int = 2 + overwrite: bool = False + dry_run: bool = False + keep_awake: bool = sys.platform == "darwin" + validate_media: bool = True + + +@dataclass +class TranscriptionResult: + status: str + total: int = 0 + succeeded: int = 0 + skipped: int = 0 + failed: int = 0 + unavailable: int = 0 + exit_code: int = 0 + + def to_dict(self) -> dict[str, Any]: + return asdict(self) + + +class CourseTranscriber: + def __init__( + self, + options: TranscriptionOptions, + *, + model_loader: Callable[[str, str], tuple[Any, Any, str]] = _load_model, + media_validator: Callable[[Path], None] = _validate_media, + sleeper: Callable[[float], None] = time.sleep, + ) -> None: + self.options = options + self.public = options.public.expanduser().resolve() + self.model_loader = model_loader + self.media_validator = media_validator + self.sleeper = sleeper + self.runtime_root = self.public.parent / ".ravin" / "transcribe" + self.state_path = self.runtime_root / "state.json" + self.summary_path = self.runtime_root / "summary.json" + self.errors_path = self.runtime_root / "errors.jsonl" + self.started_at = _utc_now() + self.result = TranscriptionResult(status="starting") + self.current_index = 0 + self.current_job: TranscriptionJob | None = None + self._torch: Any | None = None + + def _write_state(self) -> None: + _atomic_json( + self.state_path, + { + **self.result.to_dict(), + "pid": os.getpid(), + "started_at": self.started_at, + "updated_at": _utc_now(), + "model": self.options.model, + "device": self.options.device, + "language": self.options.language, + "course_ids": list(self.options.course_ids), + "current_index": self.current_index, + "current": self.current_job.label() if self.current_job else None, + }, + ) + + def _finish(self, status: str, exit_code: int) -> TranscriptionResult: + self.result.status = status + self.result.exit_code = exit_code + self.current_job = None + self._write_state() + _atomic_json( + self.summary_path, + { + **self.result.to_dict(), + "started_at": self.started_at, + "finished_at": _utc_now(), + "model": self.options.model, + "device": self.options.device, + "language": self.options.language, + "course_ids": list(self.options.course_ids), + }, + ) + return self.result + + def _discover_jobs(self) -> list[TranscriptionJob]: + courses_root = self.public / "courses" + selected = set(self.options.course_ids) + manifests = sorted(courses_root.glob("*/manifest.json")) + jobs: list[TranscriptionJob] = [] + found: set[int] = set() + unavailable = 0 + for manifest_path in manifests: + manifest = _read_json_object(manifest_path) + course = manifest.get("course") + if not isinstance(course, dict): + continue + course_id = int(course.get("id") or 0) + if selected and course_id not in selected: + continue + found.add(course_id) + for section in course.get("sections", []): + for item in section.get("items", []): + if item.get("kind") not in {"video", "audio"}: + continue + key = str(item.get("key") or item.get("bundle_path", "").removeprefix("content/")) + activity = courses_root / str(course_id) / "content" / key + expected = activity / "files" / str(item.get("filename") or "") + candidates = sorted( + path for path in (activity / "files").glob("*") + if path.is_file() and not path.name.endswith(".part") + ) + source = expected if expected.is_file() else (candidates[0] if len(candidates) == 1 else None) + if source is None: + unavailable += 1 + continue + artifacts = activity / "artifacts" + jobs.append( + TranscriptionJob( + course_id=course_id, + activity_id=item.get("activity_id"), + key=key, + title=str(item.get("title") or source.name), + source=source, + transcript=artifacts / "transcript.fa.txt", + metadata=artifacts / "transcript.meta.json", + error_marker=artifacts / ".transcript.error.json", + ) + ) + missing = selected - found + if missing: + raise MoodleError(f"course manifest(s) not found: {', '.join(str(value) for value in sorted(missing))}") + if not found: + raise MoodleError(f"no course manifests found in {courses_root}; run `ravin scan` first") + self.result.unavailable = unavailable + return jobs + + def _expected_metadata(self, job: TranscriptionJob) -> dict[str, Any]: + source_stat = job.source.stat() + return { + "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, + "transcript": "transcript.fa.txt", + } + + def _has_matching_transcript(self, job: TranscriptionJob) -> bool: + if not job.transcript.is_file() or not job.metadata.is_file(): + return False + metadata = _read_json_object(job.metadata) + try: + expected = self._expected_metadata(job) + except OSError: + return False + return all(metadata.get(key) == value for key, value in expected.items()) + + def _clear_accelerator_cache(self) -> None: + gc.collect() + if self._torch is None: + return + try: + if self._torch.cuda.is_available(): + self._torch.cuda.empty_cache() + if self._torch.backends.mps.is_available(): + self._torch.mps.empty_cache() + except Exception: + pass + + def _with_retries(self, operation: Callable[[], Any], job: TranscriptionJob, stage: str) -> Any: + attempts = self.options.retries + 1 + for attempt in range(1, attempts + 1): + try: + return operation() + except KeyboardInterrupt: + raise + except Exception as exc: + self._clear_accelerator_cache() + if attempt == attempts: + raise + delay = min(2 ** (attempt - 1), 30) + print( + f" {stage} attempt {attempt}/{attempts} failed: {_compact_error(exc)}; " + f"retrying in {delay}s", + file=sys.stderr, + ) + self.sleeper(delay) + raise AssertionError("unreachable") + + def _record_failure(self, job: TranscriptionJob, error: BaseException) -> None: + message = _compact_error(error) + private_record = { + "failed_at": _utc_now(), + "course_id": job.course_id, + "activity_id": job.activity_id, + "activity_key": job.key, + "source": job.source.relative_to(self.public).as_posix(), + "error_type": type(error).__name__, + "error": message, + "model": self.options.model, + "language": self.options.language, + "attempts": self.options.retries + 1, + } + _append_json_line(self.errors_path, private_record) + public_message = message.replace(str(job.source), job.source.name) + _atomic_json( + job.error_marker, + { + "schema_version": 1, + "failed_at": private_record["failed_at"], + "error_type": private_record["error_type"], + "error": public_message, + "model": self.options.model, + "language": self.options.language, + "attempts": self.options.retries + 1, + }, + ) + self.result.failed += 1 + + def _write_transcript(self, job: TranscriptionJob, text: str, device: str) -> None: + metadata = self._expected_metadata(job) + metadata.update({"device": device, "generated_at": _utc_now()}) + _atomic_text(job.transcript, text.strip() + "\n", mode=0o644) + _atomic_json(job.metadata, metadata, mode=0o644) + job.error_marker.unlink(missing_ok=True) + + def run(self) -> TranscriptionResult: + if self.options.retries < 0: + raise MoodleError("--retries cannot be negative") + if not self.options.dry_run: + scan_offline(self.public, self.options.course_ids) + jobs = self._discover_jobs() + self.result.total = len(jobs) + matching = {job for job in jobs if not self.options.overwrite and self._has_matching_transcript(job)} + if not self.options.dry_run: + for job in matching: + job.error_marker.unlink(missing_ok=True) + self.result.skipped = len(matching) + pending = [job for job in jobs if job not in matching] + + if self.options.dry_run: + for job in pending: + # Keep stdout machine-readable when the CLI is used with --json. + print(f"would transcribe: {job.label()}", file=sys.stderr) + self.result.status = "dry_run" + return self.result + if not pending: + return self._finish("completed", 0) + if self.options.validate_media and not shutil.which("ffprobe"): + raise MoodleError("FFmpeg is required; install it with `brew install ffmpeg`") + + self.result.status = "running" + self._write_state() + try: + model, self._torch, device = self.model_loader(self.options.model, self.options.device) + except Exception: + self._finish("failed_to_start", 2) + raise + for index, job in enumerate(jobs, start=1): + self.current_index = index + if job in matching: + continue + self.current_job = job + self._write_state() + print(f"[{index}/{len(jobs)}] {job.title} ({job.source.name})", file=sys.stderr) + try: + 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), + job, + "transcription", + ) + text = str(result.get("text") or "").strip() + self._write_transcript(job, text, str(getattr(model, "device", device))) + self.result.succeeded += 1 + print(" completed", file=sys.stderr) + except KeyboardInterrupt: + return self._finish("interrupted", 130) + except Exception as exc: + self._record_failure(job, exc) + print(f" failed permanently; continuing: {_compact_error(exc)}", file=sys.stderr) + finally: + scan_offline(self.public, [job.course_id]) + self.current_job = None + self._write_state() + + status = "completed_with_errors" if self.result.failed else "completed" + return self._finish(status, 1 if self.result.failed else 0) + + +def _raise_keyboard_interrupt(_signum: int, _frame: Any) -> None: + raise KeyboardInterrupt + + +def transcribe_courses(options: TranscriptionOptions) -> TranscriptionResult: + transcriber = CourseTranscriber(options) + if options.dry_run: + return transcriber.run() + caffeinate = _start_caffeinate(options.keep_awake and not options.dry_run) + previous_sigterm: Any = None + signal_installed = False + if hasattr(signal, "SIGTERM"): + try: + previous_sigterm = signal.getsignal(signal.SIGTERM) + signal.signal(signal.SIGTERM, _raise_keyboard_interrupt) + signal_installed = True + except ValueError: + pass + try: + with _exclusive_lock(transcriber.runtime_root / "run.lock"): + return transcriber.run() + finally: + if signal_installed and previous_sigterm is not None: + signal.signal(signal.SIGTERM, previous_sigterm) + if caffeinate is not None: + caffeinate.terminate() + + +def format_transcription_result(result: TranscriptionResult) -> str: + return ( + f"Transcription {result.status}: {result.succeeded} succeeded, " + f"{result.skipped} skipped, {result.failed} failed, " + f"{result.unavailable} unavailable ({result.total} local media files)." + ) diff --git a/tests/test_ravin.py b/tests/test_ravin.py index 1491e63..43e2f9f 100644 --- a/tests/test_ravin.py +++ b/tests/test_ravin.py @@ -93,6 +93,10 @@ 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"]) + self.assertEqual(transcribe.course_ids, [44]) + self.assertEqual(transcribe.model, "small") + self.assertFalse(transcribe.keep_awake) serve = build_parser().parse_args(["serve", "--port", "9000"]) self.assertEqual(serve.port, 9000) diff --git a/tests/test_transcribe.py b/tests/test_transcribe.py new file mode 100644 index 0000000..2b0cc1e --- /dev/null +++ b/tests/test_transcribe.py @@ -0,0 +1,195 @@ +from __future__ import annotations + +import json +import os +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) + +from ravin.transcribe import CourseTranscriber, TranscriptionOptions + + +class FakeModel: + device = "test-device" + + def __init__(self, failures: set[str] | None = None, *, interrupt: bool = False) -> None: + self.failures = failures or set() + self.interrupt = interrupt + self.calls: list[str] = [] + + def transcribe(self, source: str, **_kwargs: object) -> dict[str, str]: + name = Path(source).name + self.calls.append(name) + if self.interrupt: + raise KeyboardInterrupt + if name in self.failures: + raise RuntimeError(f"cannot decode {name}") + return {"text": f"transcript for {name}"} + + +class TranscriptionTests(unittest.TestCase): + def setUp(self) -> None: + self.temporary_directory = tempfile.TemporaryDirectory() + self.root = Path(self.temporary_directory.name) + self.public = self.root / "public" + + def tearDown(self) -> None: + self.temporary_directory.cleanup() + + def write_course(self, filenames: list[str]) -> None: + items = [] + for position, filename in enumerate(filenames, start=1): + activity_id = 4900 + position + key = f"002--{position:03d}--{activity_id}" + source = self.public / "courses" / "44" / "content" / key / "files" / filename + source.parent.mkdir(parents=True) + source.write_bytes(filename.encode("utf-8")) + items.append( + { + "filename": filename, + "kind": "video", + "activity_type": "resource", + "title": f"Lesson {position}", + "section_number": 2, + "activity_position": position, + "activity_id": activity_id, + "key": key, + "bundle_path": f"content/{key}", + } + ) + manifest_path = self.public / "courses" / "44" / "manifest.json" + manifest_path.parent.mkdir(parents=True, exist_ok=True) + manifest_path.write_text( + json.dumps( + { + "schema_version": 1, + "course": { + "id": 44, + "fullname": "Network +", + "section_count": 1, + "activity_count": len(items), + "sections": [{"number": 2, "name": "Lessons", "items": items}], + }, + } + ), + encoding="utf-8", + ) + + def options(self, **overrides: object) -> TranscriptionOptions: + values: dict[str, object] = { + "public": self.public, + "course_ids": (44,), + "model": "tiny", + "device": "cpu", + "language": "fa", + "retries": 2, + "keep_awake": False, + } + values.update(overrides) + return TranscriptionOptions(**values) + + def transcriber(self, model: FakeModel, **overrides: object) -> CourseTranscriber: + return CourseTranscriber( + self.options(**overrides), + model_loader=lambda _name, _device: (model, None, "cpu"), + media_validator=lambda _source: None, + sleeper=lambda _delay: None, + ) + + def test_success_updates_artifacts_manifest_and_resumes(self) -> None: + self.write_course(["lesson.mp4"]) + model = FakeModel() + result = self.transcriber(model).run() + + self.assertEqual(result.exit_code, 0) + self.assertEqual(result.succeeded, 1) + self.assertEqual(model.calls, ["lesson.mp4"]) + 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.assertNotIn(str(self.root), json.dumps(metadata)) + self.assertEqual(os.stat(transcript).st_mode & 0o777, 0o644) + manifest = json.loads( + (self.public / "courses" / "44" / "manifest.json").read_text(encoding="utf-8") + ) + item = manifest["course"]["sections"][0]["items"][0] + self.assertEqual(item["state"]["transcript"], "complete") + self.assertTrue(item["transcribed"]) + + second_loader_called = False + + def second_loader(_name: str, _device: str) -> tuple[object, object, str]: + nonlocal second_loader_called + second_loader_called = True + raise AssertionError("matching transcripts must skip model loading") + + second = CourseTranscriber( + self.options(), + model_loader=second_loader, + media_validator=lambda _source: None, + ).run() + self.assertEqual(second.skipped, 1) + self.assertFalse(second_loader_called) + + 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"}) + result = self.transcriber(model).run() + + self.assertEqual(result.exit_code, 1) + self.assertEqual(result.succeeded, 1) + self.assertEqual(result.failed, 1) + self.assertEqual(model.calls.count("bad.mp4"), 3) + self.assertEqual(model.calls.count("good.mp4"), 1) + bad_artifacts = self.public / "courses" / "44" / "content" / "002--001--4901" / "artifacts" + good_artifacts = self.public / "courses" / "44" / "content" / "002--002--4902" / "artifacts" + self.assertTrue((bad_artifacts / ".transcript.error.json").is_file()) + self.assertFalse((bad_artifacts / "transcript.fa.txt").exists()) + self.assertTrue((good_artifacts / "transcript.fa.txt").is_file()) + manifest = json.loads( + (self.public / "courses" / "44" / "manifest.json").read_text(encoding="utf-8") + ) + bad_item, good_item = manifest["course"]["sections"][0]["items"] + self.assertEqual(bad_item["state"]["transcript"], "error") + self.assertEqual(good_item["state"]["transcript"], "complete") + self.assertEqual(manifest["course"]["states"]["errors"], 1) + self.assertTrue((self.root / ".ravin" / "transcribe" / "errors.jsonl").is_file()) + + def test_keyboard_interrupt_preserves_state_for_resume(self) -> None: + self.write_course(["lesson.mp4", "later.mp4"]) + model = FakeModel(interrupt=True) + transcriber = self.transcriber(model) + result = transcriber.run() + + self.assertEqual(result.status, "interrupted") + self.assertEqual(result.exit_code, 130) + self.assertEqual(model.calls, ["lesson.mp4"]) + state = json.loads(transcriber.state_path.read_text(encoding="utf-8")) + self.assertEqual(state["status"], "interrupted") + + def test_dry_run_does_not_load_model_or_write_runtime_state(self) -> None: + self.write_course(["lesson.mp4"]) + + def forbidden_loader(_name: str, _device: str) -> tuple[object, object, str]: + raise AssertionError("dry-run must not load Whisper") + + transcriber = CourseTranscriber( + self.options(dry_run=True), + model_loader=forbidden_loader, + media_validator=lambda _source: None, + ) + result = transcriber.run() + + self.assertEqual(result.status, "dry_run") + self.assertEqual(result.total, 1) + self.assertFalse(transcriber.runtime_root.exists()) + + +if __name__ == "__main__": + unittest.main()