Add YouTube channel ingestion
This commit is contained in:
@@ -122,6 +122,18 @@ It does not use private cookies or browser sessions by default. If a site needs
|
|||||||
|
|
||||||

|

|
||||||
|
|
||||||
|
## YouTube Ingestion
|
||||||
|
|
||||||
|
Mnemazine can ingest a YouTube channel and turn every video into a transcript note, then keep pulling new uploads automatically:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 scripts/kb-yt-harvest.py "https://www.youtube.com/@SomeChannel" --all --subscribe
|
||||||
|
```
|
||||||
|
|
||||||
|
It pulls subtitles first (near-zero cost) and falls back to local whisper when a video has no usable captions. Each video becomes one inbox note named `yt_<date>_<id>_<title>.md`. A subscribed channel is then polled by `scripts/kb-yt-watch.py` over RSS, harvesting only new uploads — optionally on a daily launchd schedule.
|
||||||
|
|
||||||
|
It fetches public videos only and uses no cookies or account sessions by default. See [YouTube Ingestion](docs/youtube-ingestion.md).
|
||||||
|
|
||||||
## Knowledge Quality Contract
|
## Knowledge Quality Contract
|
||||||
|
|
||||||
The vault must contain final knowledge, not raw material.
|
The vault must contain final knowledge, not raw material.
|
||||||
@@ -212,6 +224,7 @@ That matters because a real memory must be reproducible. A note should be able t
|
|||||||
- [Architecture](docs/architecture.md)
|
- [Architecture](docs/architecture.md)
|
||||||
- [Token Economics](docs/token-economics.md)
|
- [Token Economics](docs/token-economics.md)
|
||||||
- [Website Ingestion](docs/site-ingestion.md)
|
- [Website Ingestion](docs/site-ingestion.md)
|
||||||
|
- [YouTube Ingestion](docs/youtube-ingestion.md)
|
||||||
- [Obsidian Vault](docs/obsidian.md)
|
- [Obsidian Vault](docs/obsidian.md)
|
||||||
- [Apple Vision OCR](docs/apple-vision.md)
|
- [Apple Vision OCR](docs/apple-vision.md)
|
||||||
- [Graphify](docs/graphify.md)
|
- [Graphify](docs/graphify.md)
|
||||||
|
|||||||
@@ -0,0 +1,90 @@
|
|||||||
|
# YouTube Ingestion
|
||||||
|
|
||||||
|
Mnemazine can ingest a YouTube channel and turn every video into a transcript
|
||||||
|
note in the inbox, then keep pulling new uploads automatically.
|
||||||
|
|
||||||
|
Two scripts, both pure CLI (no model tokens spent here):
|
||||||
|
|
||||||
|
- `scripts/kb-yt-harvest.py` — backfill a channel (or a single video) now.
|
||||||
|
- `scripts/kb-yt-watch.py` — poll subscribed channels for new uploads.
|
||||||
|
|
||||||
|
## Backfill A Channel
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# newest 50 videos (default cap), and subscribe for future uploads
|
||||||
|
python3 scripts/kb-yt-harvest.py "https://www.youtube.com/@SomeChannel" --subscribe
|
||||||
|
|
||||||
|
# the whole channel
|
||||||
|
python3 scripts/kb-yt-harvest.py "https://www.youtube.com/@SomeChannel" --all --subscribe
|
||||||
|
|
||||||
|
# a single video
|
||||||
|
python3 scripts/kb-yt-harvest.py "https://www.youtube.com/watch?v=VIDEO_ID"
|
||||||
|
```
|
||||||
|
|
||||||
|
For each video it writes one note to the inbox top level, named
|
||||||
|
`yt_<upload_date>_<video_id>_<title>.md`, with frontmatter (`source`, `channel`,
|
||||||
|
`video_id`, `upload_date`, `transcript_method`). The pipeline then studies them
|
||||||
|
like any other inbox item.
|
||||||
|
|
||||||
|
Transcript source, cheapest first:
|
||||||
|
|
||||||
|
1. **Subtitles** via yt-dlp (`ru`, `en`; manual preferred over auto) — near-zero cost.
|
||||||
|
2. **Local whisper** fallback when a video has no usable subtitles.
|
||||||
|
|
||||||
|
A per-channel yt-dlp download-archive guarantees each video is harvested once,
|
||||||
|
whether by backfill or the watch loop.
|
||||||
|
|
||||||
|
## Watch For New Uploads
|
||||||
|
|
||||||
|
`--subscribe` registers a channel in `.mnemazine/cache/kb-yt/channels.json`.
|
||||||
|
The watcher reads each channel's RSS feed (last 15 uploads), diffs against the
|
||||||
|
archive, and harvests only what is new:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 scripts/kb-yt-watch.py --dry-run # show what would be harvested
|
||||||
|
python3 scripts/kb-yt-watch.py --harvest-only # harvest new, do not study
|
||||||
|
python3 scripts/kb-yt-watch.py # harvest new, then study
|
||||||
|
```
|
||||||
|
|
||||||
|
After harvesting, the watcher studies the inbox with
|
||||||
|
`node scripts/mnemazine-run.mjs` (override with `MNEMAZINE_STUDY_CMD`).
|
||||||
|
|
||||||
|
### Daily Schedule (macOS launchd)
|
||||||
|
|
||||||
|
Generate a concrete agent from the template (machine paths stay out of the repo):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sed -e "s#__PYTHON__#$(command -v python3)#g" \
|
||||||
|
-e "s#__NODE_BIN__#$(dirname "$(command -v node)")#g" \
|
||||||
|
-e "s#__ROOT__#$PWD#g" \
|
||||||
|
-e "s#__INBOX__#$PWD/inbox#g" \
|
||||||
|
scripts/com.mnemazine.kb-yt-watch.plist.template \
|
||||||
|
> ~/Library/LaunchAgents/com.mnemazine.kb-yt-watch.plist
|
||||||
|
launchctl load ~/Library/LaunchAgents/com.mnemazine.kb-yt-watch.plist
|
||||||
|
```
|
||||||
|
|
||||||
|
It runs daily at 09:00 in `--harvest-only` mode.
|
||||||
|
|
||||||
|
## Paths
|
||||||
|
|
||||||
|
| What | Where |
|
||||||
|
|------|-------|
|
||||||
|
| Notes | `$MNEMAZINE_INBOX` (default `ROOT/inbox`) |
|
||||||
|
| State (subscriptions, archive) | `ROOT/.mnemazine/cache/kb-yt/` (gitignored) |
|
||||||
|
|
||||||
|
Set `MNEMAZINE_INBOX` to point harvested notes at a different inbox.
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
`yt-dlp`, `ffmpeg`, and `openai-whisper` on `PATH` (`curl` is used for RSS).
|
||||||
|
See [Installation](installation.md).
|
||||||
|
|
||||||
|
## Safety
|
||||||
|
|
||||||
|
Only public videos are fetched. Subtitles and metadata are public data. The
|
||||||
|
default path uses no cookies or account sessions — do not feed private,
|
||||||
|
age-gated, or members-only content through a knowledge pipeline.
|
||||||
|
|
||||||
|
If yt-dlp hits "Sign in to confirm you're not a bot" on some videos, install a
|
||||||
|
browser-impersonation backend (`yt-dlp` curl_cffi extra); the harvester falls
|
||||||
|
back to whisper when subtitles cannot be fetched.
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||||
|
<!--
|
||||||
|
kb-yt-watch — daily YouTube channel watcher for Mnemazine (launchd template).
|
||||||
|
|
||||||
|
This is a TEMPLATE. launchd needs absolute paths, so generate a concrete
|
||||||
|
plist locally (machine-specific paths stay out of the repo):
|
||||||
|
|
||||||
|
sed -e "s#__PYTHON__#$(command -v python3)#g" \
|
||||||
|
-e "s#__NODE_BIN__#$(dirname "$(command -v node)")#g" \
|
||||||
|
-e "s#__ROOT__#$PWD#g" \
|
||||||
|
-e "s#__INBOX__#$PWD/inbox#g" \
|
||||||
|
scripts/com.mnemazine.kb-yt-watch.plist.template \
|
||||||
|
> ~/Library/LaunchAgents/com.mnemazine.kb-yt-watch.plist
|
||||||
|
launchctl load ~/Library/LaunchAgents/com.mnemazine.kb-yt-watch.plist
|
||||||
|
|
||||||
|
Deactivate:
|
||||||
|
launchctl unload ~/Library/LaunchAgents/com.mnemazine.kb-yt-watch.plist
|
||||||
|
|
||||||
|
Runs daily at 09:00 in --harvest-only mode: harvests new videos into the
|
||||||
|
inbox but does NOT auto-study. Remove --harvest-only (and set
|
||||||
|
MNEMAZINE_STUDY_CMD) to study automatically.
|
||||||
|
-->
|
||||||
|
<plist version="1.0">
|
||||||
|
<dict>
|
||||||
|
<key>Label</key>
|
||||||
|
<string>com.mnemazine.kb-yt-watch</string>
|
||||||
|
<key>ProgramArguments</key>
|
||||||
|
<array>
|
||||||
|
<string>__PYTHON__</string>
|
||||||
|
<string>__ROOT__/scripts/kb-yt-watch.py</string>
|
||||||
|
<string>--harvest-only</string>
|
||||||
|
</array>
|
||||||
|
<key>StartCalendarInterval</key>
|
||||||
|
<dict>
|
||||||
|
<key>Hour</key>
|
||||||
|
<integer>9</integer>
|
||||||
|
<key>Minute</key>
|
||||||
|
<integer>0</integer>
|
||||||
|
</dict>
|
||||||
|
<key>EnvironmentVariables</key>
|
||||||
|
<dict>
|
||||||
|
<key>PATH</key>
|
||||||
|
<string>__NODE_BIN__:/usr/local/bin:/usr/bin:/bin</string>
|
||||||
|
<key>MNEMAZINE_ROOT</key>
|
||||||
|
<string>__ROOT__</string>
|
||||||
|
<key>MNEMAZINE_INBOX</key>
|
||||||
|
<string>__INBOX__</string>
|
||||||
|
</dict>
|
||||||
|
<key>StandardOutPath</key>
|
||||||
|
<string>__ROOT__/.mnemazine/cache/kb-yt/watch.log</string>
|
||||||
|
<key>StandardErrorPath</key>
|
||||||
|
<string>__ROOT__/.mnemazine/cache/kb-yt/watch.err</string>
|
||||||
|
<key>RunAtLoad</key>
|
||||||
|
<false/>
|
||||||
|
</dict>
|
||||||
|
</plist>
|
||||||
Executable
+276
@@ -0,0 +1,276 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""kb-yt-harvest — YouTube channel/video harvester for Mnemazine.
|
||||||
|
|
||||||
|
Enumerate a channel (or take a single video), pull the transcript
|
||||||
|
(subtitles first, local whisper fallback), and drop one Markdown note per
|
||||||
|
video into the Mnemazine inbox for the refinement pipeline to study.
|
||||||
|
|
||||||
|
Dedup via a per-channel yt-dlp download-archive file: a video is harvested
|
||||||
|
once, whether caught by the initial backfill or the RSS watch loop.
|
||||||
|
|
||||||
|
Pure CLI under the hood (yt-dlp + whisper + ffmpeg) — no model tokens spent here.
|
||||||
|
|
||||||
|
Paths follow the Mnemazine convention (see scripts/mnemazine-run.mjs):
|
||||||
|
MNEMAZINE_ROOT repo root (default: this script's repo)
|
||||||
|
MNEMAZINE_INBOX inbox dir (default: ROOT/inbox)
|
||||||
|
state ROOT/.mnemazine/cache/kb-yt/ (gitignored)
|
||||||
|
|
||||||
|
Notes land at the inbox top level (the pipeline census is non-recursive),
|
||||||
|
named yt_<upload_date>_<video_id>_<title>.md.
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
kb-yt-harvest.py <channel-or-video-url> [--limit N | --all] [--subscribe] [--out DIR]
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(os.environ.get("MNEMAZINE_ROOT") or Path(__file__).resolve().parent.parent)
|
||||||
|
INBOX = Path(os.environ.get("MNEMAZINE_INBOX") or ROOT / "inbox")
|
||||||
|
STATE_DIR = ROOT / ".mnemazine" / "cache" / "kb-yt"
|
||||||
|
ARCHIVE_DIR = STATE_DIR / "archive"
|
||||||
|
CHANNELS_JSON = STATE_DIR / "channels.json"
|
||||||
|
DEFAULT_BACKFILL_CAP = 50
|
||||||
|
SUB_LANGS = "ru,en"
|
||||||
|
NET = ["--retries", "2", "--socket-timeout", "15"]
|
||||||
|
|
||||||
|
|
||||||
|
def run(cmd):
|
||||||
|
return subprocess.run(cmd, capture_output=True, text=True)
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_dirs():
|
||||||
|
for d in (STATE_DIR, ARCHIVE_DIR):
|
||||||
|
d.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
def slugify(s):
|
||||||
|
s = re.sub(r"[^\w\-]+", "_", (s or "").strip(), flags=re.UNICODE)
|
||||||
|
return re.sub(r"_+", "_", s).strip("_")[:60] or "video"
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_url(url):
|
||||||
|
"""Append /videos to a bare channel URL so we enumerate uploads, not tabs."""
|
||||||
|
if any(k in url for k in ("watch?v=", "/shorts/", "list=")):
|
||||||
|
return url
|
||||||
|
if re.search(r"/(@[\w.\-]+|channel/[\w\-]+|c/[\w\-]+|user/[\w\-]+)/?$", url):
|
||||||
|
return url.rstrip("/") + "/videos"
|
||||||
|
return url
|
||||||
|
|
||||||
|
|
||||||
|
def channel_meta_from_video(url):
|
||||||
|
"""Resolve (channel_id, channel_slug) via a full extract of one video.
|
||||||
|
Flat-playlist entries lack channel_id/uploader_id, so we ask a real video —
|
||||||
|
one request, and it reliably carries channel_id (required for the RSS feed)."""
|
||||||
|
r = run(["yt-dlp", "--skip-download", "--no-warnings",
|
||||||
|
"--print", "%(channel_id)s\t%(channel)s", *NET, url])
|
||||||
|
lines = [ln for ln in (r.stdout or "").splitlines() if ln.strip()]
|
||||||
|
if not lines:
|
||||||
|
return None, "channel"
|
||||||
|
p = lines[0].split("\t")
|
||||||
|
cid = p[0] if p and p[0] not in ("", "NA") else None
|
||||||
|
name = p[1] if len(p) > 1 and p[1] not in ("", "NA") else "channel"
|
||||||
|
return cid, slugify(name)
|
||||||
|
|
||||||
|
|
||||||
|
def read_upload_date(wd):
|
||||||
|
"""Read upload_date captured via yt-dlp --print-to-file during fetch (0 extra requests).
|
||||||
|
The subtitle path does not emit info.json, so a dedicated sidecar is the reliable source."""
|
||||||
|
f = wd / "upload_date.txt"
|
||||||
|
if f.exists():
|
||||||
|
d = f.read_text(encoding="utf-8", errors="ignore").strip()
|
||||||
|
if re.fullmatch(r"\d{8}", d):
|
||||||
|
return d
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def enumerate_videos(url, cap=None):
|
||||||
|
"""List videos as dicts (id, title, upload_date, url). Channel order = newest first."""
|
||||||
|
cmd = ["yt-dlp", "--flat-playlist",
|
||||||
|
"--print", "%(id)s\t%(title)s\t%(upload_date)s", *NET]
|
||||||
|
if cap:
|
||||||
|
cmd += ["--playlist-end", str(cap)]
|
||||||
|
cmd.append(url)
|
||||||
|
r = run(cmd)
|
||||||
|
vids = []
|
||||||
|
for ln in (r.stdout or "").splitlines():
|
||||||
|
p = ln.split("\t")
|
||||||
|
if p and p[0]:
|
||||||
|
vids.append({
|
||||||
|
"id": p[0],
|
||||||
|
"title": p[1] if len(p) > 1 and p[1] else p[0],
|
||||||
|
"upload_date": p[2] if len(p) > 2 and p[2] != "NA" else "",
|
||||||
|
"url": f"https://www.youtube.com/watch?v={p[0]}",
|
||||||
|
})
|
||||||
|
return vids
|
||||||
|
|
||||||
|
|
||||||
|
def already_done(archive_file, vid_id):
|
||||||
|
if not archive_file.exists():
|
||||||
|
return False
|
||||||
|
return f"youtube {vid_id}" in archive_file.read_text(encoding="utf-8", errors="ignore")
|
||||||
|
|
||||||
|
|
||||||
|
def mark_done(archive_file, vid_id):
|
||||||
|
archive_file.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
with archive_file.open("a", encoding="utf-8") as f:
|
||||||
|
f.write(f"youtube {vid_id}\n")
|
||||||
|
|
||||||
|
|
||||||
|
def vtt_to_text(vtt):
|
||||||
|
"""Strip WEBVTT structure + inline tags, dedup consecutive lines (auto-subs repeat)."""
|
||||||
|
out = []
|
||||||
|
for ln in vtt.splitlines():
|
||||||
|
ln = ln.strip()
|
||||||
|
if not ln or ln == "WEBVTT" or "-->" in ln:
|
||||||
|
continue
|
||||||
|
if re.match(r"^\d+$", ln) or ln.startswith(("Kind:", "Language:", "NOTE")):
|
||||||
|
continue
|
||||||
|
ln = re.sub(r"<[^>]+>", "", ln)
|
||||||
|
ln = re.sub(r"\s*(align|position):\S+", "", ln).strip()
|
||||||
|
if ln and (not out or out[-1] != ln):
|
||||||
|
out.append(ln)
|
||||||
|
return "\n".join(out).strip() or None
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_subtitles(vid_url, wd):
|
||||||
|
"""Download subtitles, pick best track (ru>en, manual>auto). Return text or None."""
|
||||||
|
base = str(wd / "sub")
|
||||||
|
run(["yt-dlp", "--skip-download", "--write-subs", "--write-auto-subs",
|
||||||
|
"--print-to-file", "%(upload_date)s", str(wd / "upload_date.txt"),
|
||||||
|
"--sub-langs", SUB_LANGS, "--sub-format", "vtt", *NET,
|
||||||
|
"-o", base + ".%(ext)s", vid_url])
|
||||||
|
cands = list(wd.glob("sub*.vtt"))
|
||||||
|
if not cands:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def score(p):
|
||||||
|
n = p.name
|
||||||
|
s = 0
|
||||||
|
if ".ru" in n:
|
||||||
|
s -= 4
|
||||||
|
if ".en" in n:
|
||||||
|
s -= 2
|
||||||
|
if "auto" in n or "-orig" in n:
|
||||||
|
s += 1
|
||||||
|
return s
|
||||||
|
|
||||||
|
best = sorted(cands, key=score)[0]
|
||||||
|
return vtt_to_text(best.read_text(encoding="utf-8", errors="ignore"))
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_whisper(vid_url, wd):
|
||||||
|
"""Fallback: download audio, transcribe with local whisper. Return text or None."""
|
||||||
|
run(["yt-dlp", "-f", "bestaudio", "-x", "--audio-format", "mp3",
|
||||||
|
"--print-to-file", "%(upload_date)s", str(wd / "upload_date.txt"),
|
||||||
|
*NET, "-o", str(wd / "audio.%(ext)s"), vid_url])
|
||||||
|
audio = [a for a in wd.glob("audio.*")
|
||||||
|
if a.suffix.lower() in (".mp3", ".m4a", ".webm", ".opus", ".wav", ".aac")]
|
||||||
|
if not audio:
|
||||||
|
return None
|
||||||
|
run(["whisper", str(audio[0]), "--model", "small",
|
||||||
|
"--output_format", "txt", "--output_dir", str(wd)])
|
||||||
|
txts = [t for t in wd.glob("*.txt") if t.name != "upload_date.txt"]
|
||||||
|
if not txts:
|
||||||
|
return None
|
||||||
|
return txts[0].read_text(encoding="utf-8", errors="ignore").strip() or None
|
||||||
|
|
||||||
|
|
||||||
|
def write_note(inbox, channel, vid, text, method):
|
||||||
|
inbox.mkdir(parents=True, exist_ok=True)
|
||||||
|
date = vid["upload_date"] or "00000000"
|
||||||
|
fpath = inbox / f"yt_{date}_{vid['id']}_{slugify(vid['title'])}.md"
|
||||||
|
title = vid["title"].replace("\n", " ")
|
||||||
|
now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||||
|
note = (
|
||||||
|
"---\n"
|
||||||
|
f"source: {vid['url']}\n"
|
||||||
|
f"channel: {channel}\n"
|
||||||
|
f"video_id: {vid['id']}\n"
|
||||||
|
f"title: {title}\n"
|
||||||
|
f"upload_date: {date}\n"
|
||||||
|
f"transcript_method: {method}\n"
|
||||||
|
f"harvested: {now}\n"
|
||||||
|
"type: youtube-transcript\n"
|
||||||
|
"---\n\n"
|
||||||
|
f"# {title}\n\n{vid['url']}\n\n{text}\n"
|
||||||
|
)
|
||||||
|
fpath.write_text(note, encoding="utf-8")
|
||||||
|
return fpath
|
||||||
|
|
||||||
|
|
||||||
|
def register_channel(cid, handle, url):
|
||||||
|
data = []
|
||||||
|
if CHANNELS_JSON.exists():
|
||||||
|
data = json.loads(CHANNELS_JSON.read_text(encoding="utf-8"))
|
||||||
|
if any(c.get("channel_id") == cid for c in data):
|
||||||
|
return
|
||||||
|
data.append({
|
||||||
|
"channel_id": cid,
|
||||||
|
"handle": handle,
|
||||||
|
"url": url,
|
||||||
|
"rss": f"https://www.youtube.com/feeds/videos.xml?channel_id={cid}",
|
||||||
|
"added": datetime.now(timezone.utc).strftime("%Y-%m-%d"),
|
||||||
|
})
|
||||||
|
CHANNELS_JSON.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||||
|
print(f"registered for RSS watch: {handle} ({cid})")
|
||||||
|
|
||||||
|
|
||||||
|
def harvest(url, inbox, cap, subscribe):
|
||||||
|
ensure_dirs()
|
||||||
|
url = normalize_url(url)
|
||||||
|
vids = enumerate_videos(url, cap=cap)
|
||||||
|
if not vids:
|
||||||
|
print("ERROR: no videos found / could not enumerate", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
cid, handle = channel_meta_from_video(vids[0]["url"])
|
||||||
|
archive_file = ARCHIVE_DIR / f"{cid or handle}.txt"
|
||||||
|
print(f"channel={handle} id={cid} listed={len(vids)} cap={cap or 'ALL'} inbox={inbox}")
|
||||||
|
|
||||||
|
done = skipped = failed = 0
|
||||||
|
for v in vids:
|
||||||
|
if already_done(archive_file, v["id"]):
|
||||||
|
skipped += 1
|
||||||
|
continue
|
||||||
|
with tempfile.TemporaryDirectory() as td:
|
||||||
|
wd = Path(td)
|
||||||
|
text, method = fetch_subtitles(v["url"], wd), "subtitles"
|
||||||
|
if not text:
|
||||||
|
text, method = fetch_whisper(v["url"], wd), "whisper"
|
||||||
|
if not text:
|
||||||
|
failed += 1
|
||||||
|
print(f" FAIL {v['id']} {v['title'][:48]}")
|
||||||
|
continue
|
||||||
|
if not v["upload_date"]:
|
||||||
|
v["upload_date"] = read_upload_date(wd)
|
||||||
|
p = write_note(inbox, handle, v, text, method)
|
||||||
|
mark_done(archive_file, v["id"])
|
||||||
|
done += 1
|
||||||
|
print(f" OK [{method}] {v['id']} -> {p.name}")
|
||||||
|
|
||||||
|
if subscribe and cid:
|
||||||
|
register_channel(cid, handle, url)
|
||||||
|
print(f"DONE harvested={done} skipped={skipped} failed={failed} inbox={inbox}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
ap = argparse.ArgumentParser(description="YouTube harvester for Mnemazine")
|
||||||
|
ap.add_argument("url", help="channel URL (@handle / channel/ / c/ / user/) or a single video URL")
|
||||||
|
ap.add_argument("--out", default=str(INBOX), help="inbox dir (default: $MNEMAZINE_INBOX or ROOT/inbox)")
|
||||||
|
ap.add_argument("--limit", type=int, default=None, help="cap N newest videos (backfill guard)")
|
||||||
|
ap.add_argument("--all", action="store_true", help="full backfill (override default cap of 50)")
|
||||||
|
ap.add_argument("--subscribe", action="store_true", help="register channel for RSS watch")
|
||||||
|
a = ap.parse_args()
|
||||||
|
cap = None if a.all else (a.limit if a.limit is not None else DEFAULT_BACKFILL_CAP)
|
||||||
|
sys.exit(harvest(a.url, Path(a.out).expanduser(), cap, a.subscribe))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
Executable
+113
@@ -0,0 +1,113 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""kb-yt-watch — poll registered YouTube channels for new videos.
|
||||||
|
|
||||||
|
For each channel in ROOT/.mnemazine/cache/kb-yt/channels.json: read its RSS
|
||||||
|
feed (last 15 uploads), diff against the per-channel archive, and harvest only
|
||||||
|
the new ones via kb-yt-harvest.py (which dedups again through the same archive).
|
||||||
|
If anything new was harvested and study mode is on, run the Mnemazine pipeline
|
||||||
|
so the fresh drops are studied into the vault.
|
||||||
|
|
||||||
|
Meant to run from launchd / cron (daily). RSS is the cheap "anything new?"
|
||||||
|
signal — no scraping, no bot risk. Heavy work happens only on new videos.
|
||||||
|
|
||||||
|
Paths follow the Mnemazine convention (MNEMAZINE_ROOT / MNEMAZINE_INBOX).
|
||||||
|
|
||||||
|
Flags:
|
||||||
|
--dry-run report what would be harvested, do nothing
|
||||||
|
--harvest-only harvest new videos but do NOT run the study pipeline
|
||||||
|
|
||||||
|
Env:
|
||||||
|
MNEMAZINE_STUDY_CMD shell command to study the inbox after harvest
|
||||||
|
(default: node ROOT/scripts/mnemazine-run.mjs)
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(os.environ.get("MNEMAZINE_ROOT") or Path(__file__).resolve().parent.parent)
|
||||||
|
STATE_DIR = ROOT / ".mnemazine" / "cache" / "kb-yt"
|
||||||
|
ARCHIVE_DIR = STATE_DIR / "archive"
|
||||||
|
CHANNELS_JSON = STATE_DIR / "channels.json"
|
||||||
|
HARVESTER = ROOT / "scripts" / "kb-yt-harvest.py"
|
||||||
|
WATCH_LIMIT = 15
|
||||||
|
|
||||||
|
|
||||||
|
def rss_video_ids(cid, n=WATCH_LIMIT):
|
||||||
|
"""Fetch the channel RSS via curl (system certs — framework-python urllib
|
||||||
|
fails on SSL cert verification on macOS). Return newest video IDs."""
|
||||||
|
url = f"https://www.youtube.com/feeds/videos.xml?channel_id={cid}"
|
||||||
|
r = subprocess.run(["curl", "-sS", "--max-time", "20", url],
|
||||||
|
capture_output=True, text=True)
|
||||||
|
if r.returncode != 0:
|
||||||
|
print(f" RSS error {cid}: {r.stderr.strip()[:120]}", file=sys.stderr)
|
||||||
|
return []
|
||||||
|
return re.findall(r"<yt:videoId>([^<]+)</yt:videoId>", r.stdout)[:n]
|
||||||
|
|
||||||
|
|
||||||
|
def archived_ids(cid):
|
||||||
|
f = ARCHIVE_DIR / f"{cid}.txt"
|
||||||
|
if not f.exists():
|
||||||
|
return set()
|
||||||
|
out = set()
|
||||||
|
for ln in f.read_text(encoding="utf-8", errors="ignore").splitlines():
|
||||||
|
parts = ln.split()
|
||||||
|
if parts:
|
||||||
|
out.add(parts[-1])
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def study_inbox():
|
||||||
|
cmd = os.environ.get("MNEMAZINE_STUDY_CMD")
|
||||||
|
if cmd:
|
||||||
|
print(f"new videos harvested -> {cmd}")
|
||||||
|
subprocess.run(cmd, shell=True)
|
||||||
|
else:
|
||||||
|
runner = ROOT / "scripts" / "mnemazine-run.mjs"
|
||||||
|
print(f"new videos harvested -> node {runner}")
|
||||||
|
subprocess.run(["node", str(runner)])
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
args = sys.argv[1:]
|
||||||
|
dry = "--dry-run" in args
|
||||||
|
study = "--harvest-only" not in args
|
||||||
|
|
||||||
|
if not CHANNELS_JSON.exists():
|
||||||
|
print("no channels registered")
|
||||||
|
return 0
|
||||||
|
channels = json.loads(CHANNELS_JSON.read_text(encoding="utf-8"))
|
||||||
|
|
||||||
|
any_new = False
|
||||||
|
for ch in channels:
|
||||||
|
cid, url, handle = ch["channel_id"], ch["url"], ch.get("handle", "?")
|
||||||
|
top = rss_video_ids(cid)
|
||||||
|
have = archived_ids(cid)
|
||||||
|
fresh = [v for v in top if v not in have]
|
||||||
|
if not fresh:
|
||||||
|
print(f"{handle}: no new")
|
||||||
|
continue
|
||||||
|
if dry:
|
||||||
|
print(f"{handle}: would harvest {len(fresh)} new (rss={len(top)} archived={len(have)})")
|
||||||
|
continue
|
||||||
|
print(f"{handle}: {len(fresh)} new -> harvest")
|
||||||
|
subprocess.run([sys.executable, str(HARVESTER), url, "--limit", str(WATCH_LIMIT)])
|
||||||
|
any_new = True
|
||||||
|
|
||||||
|
if dry:
|
||||||
|
print("(dry-run, nothing harvested)")
|
||||||
|
return 0
|
||||||
|
if not any_new:
|
||||||
|
print("nothing new across all channels")
|
||||||
|
return 0
|
||||||
|
if study:
|
||||||
|
study_inbox()
|
||||||
|
else:
|
||||||
|
print("new videos harvested (harvest-only; run the pipeline when ready)")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -27,6 +27,8 @@ Do not write raw OCR, copied fragments, noisy transcripts, or unverified paste d
|
|||||||
8. Update Graphify when available.
|
8. Update Graphify when available.
|
||||||
9. Produce a short action brief when the new knowledge implies work.
|
9. Produce a short action brief when the new knowledge implies work.
|
||||||
|
|
||||||
|
YouTube channels can be auto-harvested into the inbox as transcript notes (`docs/youtube-ingestion.md`); they then flow through this same workflow.
|
||||||
|
|
||||||
## Note Shape
|
## Note Shape
|
||||||
|
|
||||||
Every durable note should contain:
|
Every durable note should contain:
|
||||||
|
|||||||
Reference in New Issue
Block a user