testsAndMisc/linux_configuration/misc/testsAndMisc-bash/tools/_transcribe_probes.py
Krzysztof kuhy Rudnicki 4f2b0ccdf7 Dissolve linux_configuration/scripts/ and single_use/
Two levels of pure taxonomy carrying no information, and a 2-directory
cap leaves no room for them. Categories now sit directly under
linux_configuration/: features, fixes, utils, misc, fresh-install,
installers, diagnostics, gaming, boot_recovery, periodic_background, lib,
meta, tests. A script's own lib/ and tests/ are exempt from the cap, so
those stay put.

Depth violations 248 -> 139; roughly 40 of the remainder are inside
digital_wellbeing and hosts, deferred until the guard-lib repoint.

The moves are the easy half. What breaks is every path that counted
levels, and three classes of it had to be found by resolving paths rather
than reading diffs:

  - 52 relative `source` lines for lib/common.sh and lib/android.sh. The
    correct prefix differs per file: 40 were ../../ and 12 were ../../../,
    so a blanket replace would have fixed one set and broken the other.
  - REPO_ROOT in 7 fixes/lib/tests harnesses and setup_syncyomi_guard.sh,
    each walking up four levels from a directory now two levels shallower.
    This caused a real regression -- the fixes suite went red with
    "log_warn: command not found" -- caught by running it and comparing
    against the pre-move baseline worktree.
  - conftest.py's sys.path entries, which took the pytest gate down with
    14 collection errors, and the `# shellcheck source=` directives, which
    took shellcheck down with SC1091.

16 symlinks in $HOME broke, including the entire i3blocks bar. All
repointed, and cpu_monitor/memory/disk/time/volume were run to confirm
they emit real output rather than merely resolving.

Verified: 1798 tests pass at 100% coverage, 8 of 9 lib/tests suites pass
(the ninth needs the coverage jail, identically at baseline), pre-commit
is clean, and the two untracked secret configs are still ignored after
their gitignore paths changed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PJrqKERAo5QUeEHWS5Asgp
2026-08-23 18:53:30 +02:00

178 lines
4.9 KiB
Python
Executable File

#!/usr/bin/env python3
"""Dependency probes and audio/model operations for transcribe.sh.
Every optional dependency is reached through ``_try_import`` so this module
imports cleanly on a machine with none of them installed - which is what lets
it be unit-tested in CI.
"""
from __future__ import annotations
import array
import importlib
import logging
import math
import os
import sys
from typing import TYPE_CHECKING
import wave
if TYPE_CHECKING:
import types
logger = logging.getLogger(__name__)
def _try_import(name: str) -> types.ModuleType | None:
"""Attempt to import a module, returning None on failure."""
try:
return importlib.import_module(name)
except ImportError:
return None
def get_python_version() -> str:
"""Return Python major.minor version string."""
return f"{sys.version_info.major}.{sys.version_info.minor}"
def check_faster_whisper() -> bool:
"""Check if faster_whisper is importable. Exit 7 if not."""
return _try_import("faster_whisper") is not None
def check_diarization_deps() -> bool:
"""Check if diarization dependencies are available.
Returns False with warning if missing.
"""
_sf = _try_import("soundfile")
_sb = _try_import("speechbrain")
_torch = _try_import("torch")
if _sf is None or _sb is None or _torch is None:
logger.warning(
"Diarization deps missing offline; speaker labels will be skipped.",
)
return False
return True
def check_ctranslate2() -> bool:
"""Check if ctranslate2 is importable."""
return _try_import("ctranslate2") is not None
def print_deps_installed() -> None:
"""Print confirmation that Python dependencies are installed."""
logger.info("Python %s dependencies installed.", sys.version.split()[0])
def generate_sine_wav(
outfile: str,
frequency: float = 1000.0,
duration: int = 3,
sample_rate: int = 16000,
amplitude: float = 0.3,
) -> bool:
"""Generate a sine wave WAV file using only Python stdlib.
Args:
outfile: Output WAV file path
frequency: Tone frequency in Hz (default: 1000)
duration: Duration in seconds (default: 3)
sample_rate: Sample rate in Hz (default: 16000)
amplitude: Amplitude 0.0-1.0 (default: 0.3)
Returns:
True on success, False on failure
"""
try:
n_samples = sample_rate * duration
data = array.array(
"h",
[
int(
max(
-1.0,
min(
1.0,
amplitude
* math.sin(2 * math.pi * frequency * (i / sample_rate)),
),
)
* 32767
)
for i in range(n_samples)
],
)
with wave.open(outfile, "w") as wf:
wf.setnchannels(1)
wf.setsampwidth(2)
wf.setframerate(sample_rate)
wf.writeframes(data.tobytes())
except OSError:
logger.exception("Failed to generate WAV")
return False
return True
def prepare_model(model_name: str, model_dir: str) -> bool:
"""Download a whisper model for offline use.
Args:
model_name: Model name (tiny, base, small, medium, large-v3, etc.)
model_dir: Directory to store the model
Returns:
True on success, False on failure
"""
fw = _try_import("faster_whisper")
if fw is None:
logger.error("faster_whisper is not installed")
return False
try:
hf_logging = _try_import("huggingface_hub.logging")
if hf_logging is not None:
hf_logging.set_verbosity_info()
hh = _try_import("huggingface_hub")
if hh is not None:
hh.constants.HF_HUB_DISABLE_PROGRESS_BARS = False
os.environ["HF_HUB_DISABLE_PROGRESS_BARS"] = "0"
logger.info("Preparing model '%s' into %s", model_name, model_dir)
logger.info(
"Downloading model files (progress bar should appear below)...",
)
fw.WhisperModel(
model_name,
device="cpu",
compute_type="int8",
download_root=model_dir,
)
logger.info("Model prepared.")
except (OSError, RuntimeError):
logger.exception("Failed to prepare model")
return False
return True
def test_cuda() -> bool:
"""Test CUDA initialization with faster-whisper.
Returns:
True if CUDA works, False otherwise
"""
fw = _try_import("faster_whisper")
if fw is None:
logger.error("faster_whisper is not installed")
return False
try:
fw.WhisperModel("tiny", device="cuda", compute_type="float16")
logger.info("CUDA test init succeeded.")
except (OSError, RuntimeError):
logger.exception("CUDA test failed")
return False
return True