feat(home): yt-transcribe tool + watcher (captions-first, X via gallery-dl)
- yt-transcribe: YouTube/X/local-file transcription. Captions first (yt-dlp; X serves auto-captions via its twitter extractor), Whisper fallback (whisper-cli reusing OpenSuperWhisper's ggml model), reclip download reuse, INDEX.md + --list/--index for id->title mapping. - watcher: launchd every 5 min over media/video on the Unraid share, sidecar .txt per download, marker-guarded, stale-marker purge. - Code executes from the nix store via stable ~/.local/bin symlinks: launchd EPERMs on SMB exec; share stays data-only. - brews: declare yt-dlp, whisper.cpp, gallery-dl (cleanup=zap removes undeclared formulas).
This commit is contained in:
1 parent
9264bd0adf
commit
9821fde02b
4 files changed
+462
-1
No files matched your search
@@ -45,6 +45,7 @@
|
||||
onActivation.extraFlags = [ "--force" ];
|
||||
brews = [
|
||||
"ffmpeg"
|
||||
"gallery-dl" # X/Twitter media download for yt-transcribe (X video needs auth yt-dlp can't get)
|
||||
"gh"
|
||||
"herdr"
|
||||
# Client-only psql for read-only DB investigation. libpq is the keg-only
|
||||
@@ -58,6 +59,8 @@
|
||||
"tea" # Gitea CLI - PRs for firstmate crewmates on unraid.local:3003
|
||||
"tmux"
|
||||
"treehouse"
|
||||
"whisper-cpp" # whisper-cli for yt-transcribe (reuses OpenSuperWhisper's model)
|
||||
"yt-dlp" # yt-transcribe engine; same engine reclip runs in its container
|
||||
];
|
||||
casks = [
|
||||
# Codex desktop home: the standalone Codex.app was folded into the ChatGPT
|
||||
@@ -72,5 +75,24 @@
|
||||
"wezterm"
|
||||
];
|
||||
};
|
||||
|
||||
# yt-transcribe-watcher: scans reclip's download dir (media/video on the
|
||||
# Unraid share) every 5 min and transcribes new media files (Whisper — a
|
||||
# bare download carries no captions). Runs the nix-store copy through a
|
||||
# stable ~/.local/bin symlink — launchd can neither exec from the SMB share
|
||||
# (EPERM) nor reach into TCC-protected ~/Documents. Silent exit when the
|
||||
# share is unmounted.
|
||||
launchd.user.agents."yt-transcribe-watcher" = {
|
||||
command = "/Users/laptran/.local/bin/yt-transcribe-watcher";
|
||||
serviceConfig = {
|
||||
StartInterval = 300;
|
||||
StandardOutPath = "/tmp/yt-transcribe-watcher.out";
|
||||
StandardErrorPath = "/tmp/yt-transcribe-watcher.err";
|
||||
EnvironmentVariables = {
|
||||
HOME = "/Users/laptran";
|
||||
PATH = "/usr/bin:/bin:/usr/sbin:/sbin";
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
@@ -4,6 +4,14 @@ let
|
||||
home = config.home.homeDirectory;
|
||||
dotfiles = "${home}/.dotfiles";
|
||||
firstmateHome = "${home}/Documents/firstmate";
|
||||
# yt-transcribe: captions-first transcription for YouTube/X/local media.
|
||||
# Source of truth is this repo's home/bin scripts; nix copies them into the
|
||||
# store so every context (launchd, shells) executes from local disk. Stable
|
||||
# ~/.local/bin symlinks below survive store-path changes between rebuilds.
|
||||
ytTranscribe = pkgs.runCommand "yt-transcribe" { } ''
|
||||
install -Dm755 ${./home/bin/yt-transcribe} $out/bin/yt-transcribe
|
||||
install -Dm755 ${./home/bin/yt-transcribe-watcher} $out/bin/yt-transcribe-watcher
|
||||
'';
|
||||
in
|
||||
|
||||
{
|
||||
@@ -24,7 +32,7 @@ in
|
||||
nerd-fonts.hack
|
||||
ngrok # reverse TCP tunnel so the phone can SSH in over cellular (unfree)
|
||||
beets # music tagger / library organizer + navidrome sync plugin
|
||||
];
|
||||
] ++ [ ytTranscribe ];
|
||||
fonts.fontconfig.enable = true;
|
||||
home.sessionVariables.EDITOR = "nvim";
|
||||
|
||||
@@ -51,6 +59,10 @@ in
|
||||
oc2 = "${home}/.local/bin/oc2";
|
||||
# Sync ~/Music into the beets library on Unraid (requires NAS mounted).
|
||||
sync-music = "~/.local/bin/sync-music";
|
||||
# Transcribe a YouTube/X URL or a local media file. Tool code lives in
|
||||
# this repo (nix store); the Unraid share holds only data — mount it at
|
||||
# /Volumes/data (or set YT_SHARE_ROOT for a different mount point).
|
||||
yt-transcribe = "${home}/.local/bin/yt-transcribe";
|
||||
# Start the reverse tunnel so you can SSH into this Mac from your phone.
|
||||
# Run once when you go remote: `ngrok-tunnel`. Reads authtoken from
|
||||
# ~/.config/ngrok (set once per machine with `ngrok config add-authtoken <TOK>`)
|
||||
@@ -192,6 +204,15 @@ in
|
||||
source = config.lib.file.mkOutOfStoreSymlink "${dotfiles}/home/bin/security-audit-sandbox";
|
||||
force = true;
|
||||
};
|
||||
# Stable symlinks for yt-transcribe: launchd and shells exec these from local
|
||||
# disk. The repo's home/bin scripts are the source of truth — a repo edit
|
||||
# takes effect on the next rebuild; the Unraid share holds only data.
|
||||
home.file.".local/bin/yt-transcribe" = {
|
||||
source = "${ytTranscribe}/bin/yt-transcribe";
|
||||
};
|
||||
home.file.".local/bin/yt-transcribe-watcher" = {
|
||||
source = "${ytTranscribe}/bin/yt-transcribe-watcher";
|
||||
};
|
||||
home.file.".grok/AGENTS.md" = {
|
||||
source = config.lib.file.mkOutOfStoreSymlink "${dotfiles}/home/AGENTS.md";
|
||||
force = true;
|
||||
|
||||
Executable
+339
@@ -0,0 +1,339 @@
|
||||
#!/usr/bin/env bash
|
||||
# ============================================================================
|
||||
# yt-transcribe — repeatable YouTube/X transcription
|
||||
#
|
||||
# Strategy: captions first (exact text, fast); Whisper fallback ONLY when no
|
||||
# captions exist, reusing the OpenSuperWhisper model already on this Mac.
|
||||
# Accepts a URL (YouTube, X/Twitter, anything yt-dlp supports) OR a local
|
||||
# media file (skips straight to Whisper; used by the watcher for reclip
|
||||
# downloads).
|
||||
#
|
||||
# Usage:
|
||||
# yt-transcribe <url-or-file> # transcript → media/transcripts/<id>/ (URL)
|
||||
# # or <file>.txt sidecar (file)
|
||||
# yt-transcribe <url> --lang de # prefer German captions
|
||||
# yt-transcribe <url> --srt # also produce an .srt (whisper path)
|
||||
# yt-transcribe <url> --force # redo even if transcript exists
|
||||
#
|
||||
# X/Twitter: X has no public captions and now requires auth for most video
|
||||
# extraction, so URLs on x.com/twitter.com go through gallery-dl (set
|
||||
# YT_COOKIES=/path/to/cookies.txt for locked/NSFW/older tweets; exported
|
||||
# cookies.txt format from a browser extension works for both yt-dlp and
|
||||
# gallery-dl).
|
||||
#
|
||||
# Outputs (URL mode) in <share>/media/transcripts/<id>/:
|
||||
# <id>.txt plain transcript (always)
|
||||
# <id>.vtt raw captions (captions path)
|
||||
# <id>.srt subtitles (whisper path, with --srt)
|
||||
# <id>.metadata.json provenance: title, channel, source, date
|
||||
#
|
||||
# Dependencies (declared in dotfiles configuration.nix homebrew.brews):
|
||||
# yt-dlp, gallery-dl (X only), whisper-cli (whisper-cpp), ffmpeg (fallback only)
|
||||
# Whisper model: auto-detected from OpenSuperWhisper's model store,
|
||||
# or WHISPER_MODEL=/path/to/ggml-*.bin, or --model.
|
||||
# Env overrides: YT_SHARE_ROOT (data share mount, default /Volumes/data),
|
||||
# YT_TRANSCRIBE_ROOT (transcript root), YT_MEDIA_DIR (reclip download dir),
|
||||
# YT_COOKIES (cookies.txt for yt-dlp/gallery-dl).
|
||||
# Index: `yt-transcribe --list` prints id->title mapping; --index rewrites
|
||||
# INDEX.md next to the transcripts; both modes + the watcher refresh it.
|
||||
# ============================================================================
|
||||
set -euo pipefail
|
||||
|
||||
# --- locate the data share ---------------------------------------------------
|
||||
# The tool lives in this repo (installed into the nix store by the dotfiles
|
||||
# rebuild; stable symlink at ~/.local/bin/yt-transcribe). The Unraid share
|
||||
# holds only data — media and transcripts.
|
||||
SHARE_ROOT="${YT_SHARE_ROOT:-/Volumes/data}"
|
||||
OUT_ROOT="${YT_TRANSCRIBE_ROOT:-$SHARE_ROOT/media/transcripts}"
|
||||
|
||||
# --- PATH: cover Homebrew on Apple Silicon / Intel (launchd PATH too) ------
|
||||
for p in /opt/homebrew/bin /usr/local/bin; do
|
||||
[ -d "$p" ] && [[ ":$PATH:" != *":$p:"* ]] && PATH="$p:$PATH"
|
||||
done
|
||||
|
||||
LANG_PREF="en"
|
||||
KEEP_SRT=false
|
||||
FORCE=false
|
||||
DO_INDEX=false
|
||||
DO_LIST=false
|
||||
WHISPER_MODEL_ARG=""
|
||||
INPUT=""
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--lang) LANG_PREF="$2"; shift 2 ;;
|
||||
--srt) KEEP_SRT=true; shift ;;
|
||||
--force) FORCE=true; shift ;;
|
||||
--model) WHISPER_MODEL_ARG="$2"; shift 2 ;;
|
||||
--index) DO_INDEX=true; shift ;;
|
||||
--list) DO_LIST=true; shift ;;
|
||||
-h|--help) grep '^# ' "$0" | sed 's/^# //'; exit 0 ;;
|
||||
*) INPUT="$1"; shift ;;
|
||||
esac
|
||||
done
|
||||
[ -n "$INPUT" ] || $DO_INDEX || $DO_LIST || { echo "usage: yt-transcribe <url-or-file> [--lang L] [--srt] [--force] [--model ggml.bin] [--index|--list]" >&2; exit 1; }
|
||||
|
||||
# --- transcript index (INDEX.md / --list) -----------------------------------
|
||||
rebuild_index() {
|
||||
python3 - "$OUT_ROOT" "${YT_MEDIA_DIR:-$SHARE_ROOT/media/video}" <<'PY'
|
||||
import json, os, sys, time
|
||||
out_root, scan_dir = sys.argv[1], sys.argv[2]
|
||||
rows = []
|
||||
for dirpath, _, files in os.walk(out_root):
|
||||
for fn in files:
|
||||
if fn.endswith(".metadata.json"):
|
||||
try:
|
||||
d = json.load(open(os.path.join(dirpath, fn), encoding="utf-8"))
|
||||
except Exception:
|
||||
continue
|
||||
rows.append((d.get("transcribed_at") or "", d))
|
||||
rows.sort(key=lambda r: r[0], reverse=True)
|
||||
clean = lambda s: (s or "").replace("|", "/").replace("`", "/")
|
||||
L = ["# Transcript Index", "",
|
||||
"URL transcripts live in `media/transcripts/<id>/` — the `<id>.txt` is the",
|
||||
"transcript, `<id>.metadata.json` has full provenance. Local files keep their",
|
||||
"`.txt` sidecar next to the media file.", "",
|
||||
"## URL transcripts", "", "| transcribed | id | title | channel | source |", "|---|---|---|---|---|"]
|
||||
for ts, d in rows:
|
||||
L.append(f'| {ts} | `{clean(d.get("id"))}` | {clean(d.get("title"))} | {clean(d.get("channel"))} | {clean(d.get("source"))} |')
|
||||
L += ["", "## Local media files (sidecar .txt in media/video)", "", "| file | modified |", "|---|---|"]
|
||||
found = False
|
||||
for dirpath, dirs, files in os.walk(scan_dir):
|
||||
dirs[:] = [d for d in dirs if not d.startswith(".")]
|
||||
for fn in sorted(files):
|
||||
if fn.endswith(".txt"):
|
||||
found = True
|
||||
p = os.path.join(dirpath, fn)
|
||||
mt = time.strftime("%Y-%m-%d", time.localtime(os.path.getmtime(p)))
|
||||
L.append(f"| `{clean(fn)}` | {mt} |")
|
||||
if not found:
|
||||
L.append("| _(none yet — the watcher adds one per download)_ | |")
|
||||
print("\n".join(L))
|
||||
PY
|
||||
}
|
||||
if $DO_INDEX || $DO_LIST; then
|
||||
mkdir -p "$OUT_ROOT"
|
||||
if $DO_LIST; then
|
||||
rebuild_index
|
||||
else
|
||||
rebuild_index > "$OUT_ROOT/INDEX.md"
|
||||
echo "== index rebuilt: $OUT_ROOT/INDEX.md"
|
||||
fi
|
||||
exit 0
|
||||
fi
|
||||
|
||||
need() { command -v "$1" >/dev/null || { echo "MISSING DEP: $1 — install it first" >&2; exit 2; }; }
|
||||
|
||||
DL_ARGS=()
|
||||
[ -n "${YT_COOKIES:-}" ] && DL_ARGS=(--cookies "$YT_COOKIES")
|
||||
|
||||
resolve_model() {
|
||||
local MODEL="${WHISPER_MODEL_ARG:-${WHISPER_MODEL:-}}"
|
||||
if [ -z "$MODEL" ]; then
|
||||
MODEL="$(find "$HOME/Library/Application Support/ru.starmel.OpenSuperWhisper/whisper-models" \
|
||||
-name 'ggml-*.bin' 2>/dev/null | head -1 || true)"
|
||||
fi
|
||||
printf '%s' "$MODEL"
|
||||
}
|
||||
|
||||
# whisper_transcribe <wav> <out-stem> — writes <out-stem>.txt (and .srt w/ --srt)
|
||||
whisper_transcribe() {
|
||||
local WAV="$1" STEM="$2" MODEL
|
||||
MODEL="$(resolve_model)"
|
||||
[ -n "$MODEL" ] && [ -f "$MODEL" ] || {
|
||||
echo "ERROR: no whisper model. Download one (e.g. ggml-large-v3-turbo.bin from huggingface.co/ggerganov/whisper.cpp)" >&2
|
||||
echo " and pass --model or set WHISPER_MODEL." >&2; exit 4; }
|
||||
echo ">> model: $MODEL"
|
||||
local WARGS=(-m "$MODEL" -f "$WAV" -of "$STEM" -otxt)
|
||||
$KEEP_SRT && WARGS+=(-osrt)
|
||||
echo ">> transcribing with whisper-cli (this is the slow part)..."
|
||||
whisper-cli "${WARGS[@]}" 2>>"$(dirname "$STEM")/whisper.log"
|
||||
[ -s "$STEM.txt" ] || { echo "ERROR: whisper produced no text" >&2; exit 6; }
|
||||
}
|
||||
|
||||
TMPD="$(mktemp -d)"
|
||||
cleanup() { rm -rf "$TMPD"; }
|
||||
trap cleanup EXIT
|
||||
|
||||
SOURCE=""
|
||||
SOURCE_PREFIX=""
|
||||
if [ -f "$INPUT" ]; then
|
||||
# ==========================================================================
|
||||
# FILE MODE — local media (reclip download, screen recording, anything)
|
||||
# ==========================================================================
|
||||
need ffmpeg; need whisper-cli
|
||||
SRC_FILE="$INPUT"
|
||||
STEM="$(basename "$SRC_FILE")"
|
||||
STEM="${STEM%.*}"
|
||||
OUT_DIR="$(cd "$(dirname "$SRC_FILE")" && pwd)"
|
||||
TXT="$OUT_DIR/$STEM.txt"
|
||||
if [ -s "$TXT" ] && ! $FORCE; then
|
||||
echo "== already transcribed: $TXT (use --force to redo)"
|
||||
exit 0
|
||||
fi
|
||||
echo ">> file mode: $SRC_FILE"
|
||||
echo ">> converting to 16 kHz mono wav..."
|
||||
ffmpeg -y -loglevel error -i "$SRC_FILE" -ac 1 -ar 16000 "$TMPD/in.wav"
|
||||
whisper_transcribe "$TMPD/in.wav" "$OUT_DIR/$STEM"
|
||||
SOURCE="whisper-local"
|
||||
rebuild_index > "$OUT_ROOT/INDEX.md" 2>/dev/null || true
|
||||
echo "== done: $TXT (source: $SOURCE)"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# ==========================================================================
|
||||
# URL MODE
|
||||
# ==========================================================================
|
||||
need yt-dlp
|
||||
URL="$INPUT"
|
||||
IS_X=false
|
||||
case "$URL" in
|
||||
*x.com/*|*twitter.com/*|*//t.co/*) IS_X=true ;;
|
||||
esac
|
||||
|
||||
# --- metadata (yt-dlp; gallery-dl for X when yt-dlp can't) -------------------
|
||||
VIDEO_ID=""; TITLE=""; CHANNEL=""
|
||||
if META="$(yt-dlp --no-playlist --skip-download --no-warnings "${DL_ARGS[@]}" \
|
||||
--print "id=%(id)s" --print "title=%(title)s" --print "channel=%(channel|uploader)s" "$URL" 2>/dev/null)"; then
|
||||
VIDEO_ID="$(printf '%s\n' "$META" | sed -n 's/^id=//p')"
|
||||
TITLE="$(printf '%s\n' "$META" | sed -n 's/^title=//p')"
|
||||
CHANNEL="$(printf '%s\n' "$META" | sed -n 's/^channel=//p')"
|
||||
fi
|
||||
|
||||
if $IS_X && [ -z "$VIDEO_ID" ]; then
|
||||
# X/Twitter via gallery-dl
|
||||
need gallery-dl
|
||||
echo ">> X URL — resolving via gallery-dl: $URL"
|
||||
VIDEO_ID="$(printf '%s' "$URL" | grep -oE 'status(es)?/[0-9]+' | grep -oE '[0-9]+' | head -1 || true)"
|
||||
if [ -z "$VIDEO_ID" ] && GJ="$(gallery-dl -j "$URL" 2>/dev/null | head -1)"; then
|
||||
VIDEO_ID="$(printf '%s' "$GJ" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('tweet_id',''))" 2>/dev/null || true)"
|
||||
TITLE="$(printf '%s' "$GJ" | python3 -c "import json,sys; d=json.load(sys.stdin); print((d.get('content') or '')[:200])" 2>/dev/null || true)"
|
||||
CHANNEL="$(printf '%s' "$GJ" | python3 -c "import json,sys; d=json.load(sys.stdin); a=d.get('author') or {}; print(a.get('nick') or a.get('name') or '')" 2>/dev/null || true)"
|
||||
fi
|
||||
[ -n "$VIDEO_ID" ] || { echo "ERROR: could not resolve a tweet id from: $URL" >&2; exit 3; }
|
||||
fi
|
||||
# Fill X title/channel from gallery-dl metadata when yt-dlp gave none
|
||||
if $IS_X && { [ -z "$TITLE" ] || [ -z "$CHANNEL" ] || [ "$CHANNEL" = "uploader" ]; } && command -v gallery-dl >/dev/null; then
|
||||
GJ="$(gallery-dl -j "$URL" 2>/dev/null | head -1 || true)"
|
||||
if [ -n "$GJ" ]; then
|
||||
XMETA="$(printf '%s' "$GJ" | python3 -c '
|
||||
import json, sys
|
||||
def walk(o):
|
||||
if isinstance(o, dict):
|
||||
if "author" in o or "tweet_id" in o:
|
||||
yield o
|
||||
for v in o.values(): yield from walk(v)
|
||||
elif isinstance(o, list):
|
||||
for v in o: yield from walk(v)
|
||||
items = list(walk(json.load(sys.stdin)))
|
||||
d = items[-1] if items else {}
|
||||
a = d.get("author") or {}
|
||||
print(d.get("tweet_id") or "")
|
||||
print((d.get("content") or "").replace("\n", " ")[:200])
|
||||
print(a.get("nick") or a.get("name") or "")
|
||||
' 2>/dev/null || true)"
|
||||
if [ -n "$XMETA" ]; then
|
||||
[ -z "$VIDEO_ID" ] && VIDEO_ID="$(printf '%s\n' "$XMETA" | sed -n '1p')"
|
||||
[ -z "$TITLE" ] && TITLE="$(printf '%s\n' "$XMETA" | sed -n '2p')"
|
||||
if [ -z "$CHANNEL" ] || [ "$CHANNEL" = "uploader" ]; then
|
||||
CHANNEL="$(printf '%s\n' "$XMETA" | sed -n '3p')"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
TITLE="${TITLE:-x.com post}"
|
||||
CHANNEL="${CHANNEL:-x.com}"
|
||||
OUT_DIR="$OUT_ROOT/$VIDEO_ID"
|
||||
mkdir -p "$OUT_DIR"
|
||||
TXT="$OUT_DIR/$VIDEO_ID.txt"
|
||||
else
|
||||
[ -n "$VIDEO_ID" ] || { echo "ERROR: yt-dlp could not resolve the URL (private, geo-blocked, or unsupported?)" >&2; exit 3; }
|
||||
OUT_DIR="$OUT_ROOT/$VIDEO_ID"
|
||||
mkdir -p "$OUT_DIR"
|
||||
TXT="$OUT_DIR/$VIDEO_ID.txt"
|
||||
fi
|
||||
|
||||
if [ -s "$TXT" ] && ! $FORCE; then
|
||||
echo "== already transcribed: $TXT (use --force to redo)"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# --- path 1: captions -------------------------------------------------------
|
||||
echo ">> trying captions ($LANG_PREF)..."
|
||||
yt-dlp --no-playlist --skip-download --no-warnings "${DL_ARGS[@]}" \
|
||||
--write-subs --write-auto-subs \
|
||||
--sub-langs "$LANG_PREF" --sub-format "vtt" \
|
||||
-o "$OUT_DIR/%(id)s.%(ext)s" "$URL" 2>/dev/null || true
|
||||
VTT="$(find "$OUT_DIR" -maxdepth 1 -name "$VIDEO_ID.$LANG_PREF.vtt" | head -1)"
|
||||
if [ -z "$VTT" ]; then
|
||||
# exact code missing (e.g. video tagged en-US only) — broaden once, keep best, delete the rest
|
||||
yt-dlp --no-playlist --skip-download --no-warnings "${DL_ARGS[@]}" \
|
||||
--write-subs --write-auto-subs \
|
||||
--sub-langs "$LANG_PREF.*" --sub-format "vtt" \
|
||||
-o "$OUT_DIR/%(id)s.%(ext)s" "$URL" 2>/dev/null || true
|
||||
VTT="$(find "$OUT_DIR" -maxdepth 1 -name "$VIDEO_ID.$LANG_PREF-*.vtt" | sort | head -1)"
|
||||
find "$OUT_DIR" -maxdepth 1 -name "$VIDEO_ID.*.vtt" ! -path "$VTT" -delete 2>/dev/null || true
|
||||
fi
|
||||
if [ -n "$VTT" ]; then
|
||||
echo ">> captions found: $(basename "$VTT") -> converting"
|
||||
python3 - "$VTT" "$TXT" <<'PY'
|
||||
import re, sys
|
||||
src, dst = sys.argv[1], sys.argv[2]
|
||||
out, prev = [], None
|
||||
for raw in open(src, encoding="utf-8", errors="replace"):
|
||||
line = raw.strip()
|
||||
if (not line or "-->" in line or line.startswith(("WEBVTT", "Kind:", "Language:", "NOTE", "STYLE"))
|
||||
or re.match(r"^\d+$", line)):
|
||||
continue
|
||||
line = re.sub(r"<[^>]+>", "", line) # strip inline tags
|
||||
if line and line != prev:
|
||||
out.append(line); prev = line
|
||||
text = " ".join(out)
|
||||
open(dst, "w", encoding="utf-8").write(text + "\n")
|
||||
print(f" {len(text.split())} words")
|
||||
PY
|
||||
if $IS_X; then SOURCE="x-captions"; else SOURCE="youtube-captions"; fi
|
||||
else
|
||||
# --- path 2: Whisper fallback --------------------------------------------
|
||||
echo ">> no captions — falling back to Whisper"
|
||||
need ffmpeg; need whisper-cli
|
||||
MEDIA_DIR="${YT_MEDIA_DIR:-$SHARE_ROOT/media/video}" # e.g. reclip's downloads on the share
|
||||
echo ">> checking $MEDIA_DIR for an existing download..."
|
||||
LOCAL_MEDIA="$(find "$MEDIA_DIR" -maxdepth 4 -iname "*$VIDEO_ID*" \
|
||||
\( -iname '*.mp4' -o -iname '*.mkv' -o -iname '*.webm' -o -iname '*.m4a' \
|
||||
-o -iname '*.mp3' -o -iname '*.flac' -o -iname '*.mov' -o -iname '*.avi' -o -iname '*.wav' \) \
|
||||
2>/dev/null | head -1 || true)"
|
||||
WAV="$TMPD/in.wav"
|
||||
if [ -n "$LOCAL_MEDIA" ]; then
|
||||
echo ">> reusing existing file: $LOCAL_MEDIA"
|
||||
ffmpeg -y -loglevel error -i "$LOCAL_MEDIA" -ac 1 -ar 16000 "$WAV"
|
||||
elif $IS_X && command -v gallery-dl >/dev/null; then
|
||||
echo ">> downloading X media via gallery-dl..."
|
||||
gallery-dl "${DL_ARGS[@]}" \
|
||||
--filter "extension not in ('jpg','jpeg','png','webp','gif')" \
|
||||
-o "filename={tweet_id}.{extension}" \
|
||||
-D "$TMPD" "$URL"
|
||||
XMEDIA="$(find "$TMPD" -maxdepth 1 -type f \( -iname '*.mp4' -o -iname '*.m4a' -o -iname '*.mov' -o -iname '*.webm' \) | sort | tail -1)"
|
||||
[ -n "$XMEDIA" ] || { echo "ERROR: gallery-dl found no video (private tweet? set YT_COOKIES=/path/to/cookies.txt)" >&2; exit 5; }
|
||||
ffmpeg -y -loglevel error -i "$XMEDIA" -ac 1 -ar 16000 "$WAV"
|
||||
SOURCE_PREFIX="gallery-dl"
|
||||
else
|
||||
echo ">> not found — downloading audio (16 kHz mono)..."
|
||||
yt-dlp --no-playlist --no-warnings "${DL_ARGS[@]}" -x --audio-format wav \
|
||||
--postprocessor-args "ffmpeg:-ac 1 -ar 16000" \
|
||||
-o "$TMPD/%(id)s.%(ext)s" "$URL"
|
||||
fi
|
||||
[ -f "$WAV" ] || { echo "ERROR: audio acquisition failed" >&2; exit 5; }
|
||||
whisper_transcribe "$WAV" "$OUT_DIR/$VIDEO_ID"
|
||||
SOURCE="${SOURCE_PREFIX:+$SOURCE_PREFIX+}whisper-local"
|
||||
fi
|
||||
|
||||
# --- provenance --------------------------------------------------------------
|
||||
TRANSCRIBED_AT="$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
|
||||
python3 - "$VIDEO_ID" "$TITLE" "$CHANNEL" "$URL" "$SOURCE" "$LANG_PREF" "$TRANSCRIBED_AT" \
|
||||
> "$OUT_DIR/$VIDEO_ID.metadata.json" <<'PY'
|
||||
import json, sys
|
||||
keys = ["id", "title", "channel", "url", "source", "lang_pref", "transcribed_at"]
|
||||
print(json.dumps(dict(zip(keys, sys.argv[1:])), indent=2, ensure_ascii=False))
|
||||
PY
|
||||
|
||||
echo "== done: $TXT (source: $SOURCE)"
|
||||
rebuild_index > "$OUT_ROOT/INDEX.md" 2>/dev/null || true
|
||||
Executable
+79
@@ -0,0 +1,79 @@
|
||||
#!/usr/bin/env bash
|
||||
# ============================================================================
|
||||
# yt-transcribe-watcher — watch the reclip download dir and transcribe new
|
||||
# files automatically. Runs every 5 min via launchd (nix-darwin
|
||||
# launchd.user.agents."yt-transcribe-watcher") or by hand: `yt-transcribe-watcher`
|
||||
# (installed on PATH / ~/.local/bin by the dotfiles rebuild).
|
||||
#
|
||||
# For each media file in media/video without a sidecar .txt:
|
||||
# - skips files still being written (mtime < 120 s ago)
|
||||
# - marks work with <stem>.transcribing so overlapping runs can't double up
|
||||
# - calls yt-transcribe in file mode (ffmpeg -> whisper-cli, model reused
|
||||
# from OpenSuperWhisper)
|
||||
# Files downloaded by reclip carry no captions, so this is always Whisper.
|
||||
# Env: YT_MEDIA_DIR (scan dir), YT_DRY_RUN=1 (log-only pass), YT_COOKIES,
|
||||
# WHISPER_MODEL — all passed through to yt-transcribe.
|
||||
# ============================================================================
|
||||
set -uo pipefail
|
||||
|
||||
SHARE_ROOT="${YT_SHARE_ROOT:-/Volumes/data}"
|
||||
SCAN_DIR="${YT_MEDIA_DIR:-$SHARE_ROOT/media/video}"
|
||||
MAIN="$(dirname "${BASH_SOURCE[0]}")/yt-transcribe"
|
||||
STATE_DIR="$HOME/.local/state/yt-transcribe"
|
||||
LOG="$STATE_DIR/watcher.log"
|
||||
mkdir -p "$STATE_DIR"
|
||||
|
||||
[ -d "$SCAN_DIR" ] || exit 0 # share not mounted — silent, retry next tick
|
||||
[ -x "$MAIN" ] || { echo "missing $MAIN" >&2; exit 1; }
|
||||
|
||||
log() {
|
||||
printf '[%s] %s\n' "$(date '+%F %T')" "$*" >> "$LOG" 2>/dev/null || true
|
||||
# keep the log bounded
|
||||
if [ -f "$LOG" ] && [ "$(stat -f %z "$LOG" 2>/dev/null || echo 0)" -gt 512000 ]; then
|
||||
tail -c 256000 "$LOG" > "$LOG.tmp" 2>/dev/null && mv "$LOG.tmp" "$LOG" 2>/dev/null || true
|
||||
fi
|
||||
}
|
||||
|
||||
shopt -s nullglob
|
||||
COUNT=0
|
||||
while IFS= read -r -d '' f; do
|
||||
STEM="${f%.*}"
|
||||
TXT="$STEM.txt"
|
||||
MARKER="$STEM.transcribing"
|
||||
[ -s "$TXT" ] && continue
|
||||
NOW="$(date +%s)"
|
||||
if [ -e "$MARKER" ]; then
|
||||
MM="$(stat -f %m "$MARKER" 2>/dev/null || stat -c %Y "$MARKER" 2>/dev/null || echo 0)"
|
||||
if [ $((NOW - MM)) -gt 10800 ]; then
|
||||
log "stale marker purged (crashed run): $(basename "$MARKER")"
|
||||
rm -f "$MARKER"
|
||||
else
|
||||
continue
|
||||
fi
|
||||
fi
|
||||
MTIME="$(stat -f %m "$f" 2>/dev/null || stat -c %Y "$f" 2>/dev/null || echo 0)"
|
||||
if [ $((NOW - MTIME)) -lt 120 ]; then
|
||||
log "skip (still downloading): $(basename "$f")"
|
||||
continue
|
||||
fi
|
||||
if [ "${YT_DRY_RUN:-0}" = "1" ]; then
|
||||
log "DRY-RUN would transcribe: $f"
|
||||
continue
|
||||
fi
|
||||
touch "$MARKER" 2>/dev/null || continue
|
||||
COUNT=$((COUNT + 1))
|
||||
log "transcribing: $f"
|
||||
if "$MAIN" "$f" >>"$LOG" 2>&1; then
|
||||
log "ok: $TXT"
|
||||
"$MAIN" --index >/dev/null 2>&1 || true
|
||||
else
|
||||
log "FAILED: $f"
|
||||
fi
|
||||
rm -f "$MARKER"
|
||||
done < <(find "$SCAN_DIR" -maxdepth 3 -type f \
|
||||
\( -iname '*.mp4' -o -iname '*.mkv' -o -iname '*.webm' -o -iname '*.m4a' \
|
||||
-o -iname '*.mp3' -o -iname '*.flac' -o -iname '*.mov' -o -iname '*.avi' -o -iname '*.wav' -o -iname '*.ts' \) \
|
||||
-print0 2>/dev/null)
|
||||
|
||||
[ "$COUNT" -gt 0 ] && log "done: $COUNT file(s) transcribed"
|
||||
exit 0
|
||||
Reference in new issue
Block a user