Initial commit

This commit is contained in:
2026-12-03 02:08:44 +11:00
commit 0bf5ec81f7
41 changed files with 32195 additions and 0 deletions

22
.env Normal file
View File

@@ -0,0 +1,22 @@
# Copy to .env and adjust
TZ=Australia/Melbourne
RUN_HOUR=12
RUN_MINUTE=00
DAILY_COUNT=25
MAX_PER_CHANNEL=3
EXPLORE_SLOTS=3 # slots for videos from channels you don't follow
NEW_VIDEO_DAYS=7
NO_REPEAT_DAYS=14
EXCLUDE_SHORTS=true
MIN_DURATION_SEC=90
# Extra search topics for discovery (comma separated). Topics are also auto-derived.
DISCOVERY_TOPICS=
AUTO_TOPICS=5
# Ranking weights
W_CONTENT=0.60
W_CHANNEL=0.25
W_FRESH=0.10
WATCH_LATER_BOOST=0.15

22
.env.example Normal file
View File

@@ -0,0 +1,22 @@
# Copy to .env and adjust
TZ=Australia/Melbourne
RUN_HOUR=5
RUN_MINUTE=30
DAILY_COUNT=25
MAX_PER_CHANNEL=3
EXPLORE_SLOTS=3 # slots for videos from channels you don't follow
NEW_VIDEO_DAYS=7 # never recommend videos older than this (applies to Watch Later too)
NO_REPEAT_DAYS=14
EXCLUDE_SHORTS=true
MIN_DURATION_SEC=90
# Extra search topics for discovery (comma separated). Topics are also auto-derived.
DISCOVERY_TOPICS=
AUTO_TOPICS=5
# Ranking weights
W_CONTENT=0.60
W_CHANNEL=0.25
W_FRESH=0.10
WATCH_LATER_BOOST=0.15

17
Dockerfile Normal file
View File

@@ -0,0 +1,17 @@
FROM python:3.12-slim
# yt-dlp needs a JavaScript runtime (Deno) for full YouTube support
COPY --from=denoland/deno:bin /deno /usr/local/bin/deno
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 DATA_DIR=/data
WORKDIR /srv
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app ./app
RUN useradd -u 1000 -m recommender && mkdir -p /data && chown recommender /data
USER recommender
EXPOSE 8080
HEALTHCHECK CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8080/health')" || exit 1
CMD ["uvicorn", "app.web:app", "--host", "0.0.0.0", "--port", "8080"]

111
README.md Normal file
View File

@@ -0,0 +1,111 @@
# YouTube Daily 25
A self-hosted recommender that learns what you like from your **subscriptions, watch history and Watch Later**, and builds a list of **25 videos each morning**. You browse the list on a local web page and rate videos with 👍 / 👎 / ✓ to teach it.
Everything runs locally in Docker. You don't need a Google Cloud project or API key, and nothing is sent to an AI service.
## How it works
```
05:30 daily (APScheduler)
│
├─ yt-dlp + cookies ─► Watch History, Watch Later, Subscriptions feed, channel list
├─ RSS (public) ─► latest uploads + publish dates for every subscribed channel
├─ yt-dlp search ─► newest videos on your topics (discovery outside subscriptions)
│
├─ fastembed (bge-small, CPU) ─► vector per video title/description
├─ taste profile = weighted history + Watch Later + 👍 (minus 👎)
├─ score = content similarity + channel affinity + freshness (+ Watch Later boost)
└─ diversity pass: max 3 per channel, no near-duplicates, 3 discovery slots
│
▼
SQLite ─► web page at http://<host>:8080
```
**Why cookies?** The official YouTube Data API hasn't returned Watch History or Watch Later since 2016. yt-dlp reads those pages the same way your browser does, so it needs your signed-in cookies.
What it learns from, from strongest to weakest:
| Signal | Weight |
|---|---|
| 👍 in the app | 3.0 |
| ✓ Watched in the app, or on Watch Later | 1.5 |
| Watch history (recent counts more) | 0.3 – 1.3 |
| Opened from the app | 0.5 |
| 👎 in the app | pushes similar videos and that channel down |
## Setup
### 1. Export your YouTube cookies (the only credential)
`data/cookies.txt` must be a Netscape-format cookies file for a signed-in YouTube session. **Treat it like a password.** Anyone with it can act as your Google account on YouTube. It's git-ignored and only mounted into the container.
**Option A, most durable (recommended by yt-dlp).** This stops the browser rotating the cookies out from under you:
1. Open a **private/incognito window** and sign in to YouTube.
2. In the same tab, go to `https://www.youtube.com/robots.txt`.
3. Export cookies for youtube.com with an extension such as *Get cookies.txt LOCALLY* (Chrome) or *cookies.txt* (Firefox). Save as `data/cookies.txt`.
4. **Close the private window** and don't reuse that session.
**Option B, quick (from CachyOS, if yt-dlp is installed):**
```bash
yt-dlp --cookies-from-browser firefox --cookies ./data/cookies.txt \
--skip-download "https://www.youtube.com/feed/history"
```
Cookies exported this way can stop working after a few days or weeks, because the browser keeps rotating them.
When cookies expire, the page header shows "last run failed". Re-export them and click **Refresh from YouTube**.
### 2. Configure and start
```bash
cp .env.example .env # adjust run time, topics, weights
mkdir -p data && sudo chown 1000:1000 data # container runs as uid 1000
docker compose up -d --build
docker compose exec youtube-recommender python -m app.pipeline --check-cookies
```
Open `http://<docker-host>:8080`. On first start it builds a list right away. The first run downloads the embedding model (~70 MB) and embeds your history, which takes a few minutes. After that it runs every day at `RUN_HOUR:RUN_MINUTE` in `TZ`.
### Useful commands
```bash
docker compose logs -f # watch a run
docker compose exec youtube-recommender python -m app.pipeline # full run now
docker compose exec youtube-recommender python -m app.pipeline --skip-sync # re-rank only
```
In the web UI, **Re-rank** applies your latest ratings instantly. **Refresh from YouTube** pulls fresh data.
## Tuning (`.env`)
| Setting | Default | What it does |
|---|---|---|
| `DAILY_COUNT` | 25 | Videos per day |
| `MAX_PER_CHANNEL` | 3 | Stops one channel dominating |
| `EXPLORE_SLOTS` | 3 | Slots for channels you don't watch yet |
| `NEW_VIDEO_DAYS` | 7 | **Hard limit**: nothing older is ever recommended, including Watch Later items. Videos with no known upload date are skipped. |
| `NO_REPEAT_DAYS` | 14 | Don't re-suggest a video you skipped within this window |
| `EXCLUDE_SHORTS` / `MIN_DURATION_SEC` | true / 90 | Drops Shorts and very short videos |
| `DISCOVERY_TOPICS` | (empty) | Extra comma-separated search topics, e.g. `entra id,proxmox,splunk` |
| `AUTO_TOPICS` | 5 | Topics auto-derived from words that recur in what you watch |
| `W_CONTENT` / `W_CHANNEL` / `W_FRESH` | .60 / .25 / .10 | Ranking weights |
## Notes and limits
- **Unofficial access.** yt-dlp scrapes YouTube pages. It can break when YouTube changes things, so keep it updated by rebuilding the image now and then (`docker compose build --pull`). Request volume is low: a few page loads plus one RSS fetch per channel each day, with a 1-second delay between yt-dlp requests.
- **No login on the web page.** Keep it on your LAN or put it behind your reverse proxy with auth. It only exposes video lists and ratings, never the cookies.
- **Videos you watch elsewhere** show up in History on the next run and are removed from candidates automatically.
## Project layout
```
app/
config.py settings from env
youtube.py yt-dlp + RSS fetchers
db.py SQLite schema/helpers
embed.py fastembed text vectors
recommender.py taste profile, scoring, diversity selection, auto topics
pipeline.py daily job (sync -> embed -> rank); CLI entry point
web.py FastAPI UI/API + scheduler
templates/index.html
```

0
app/__init__.py Normal file
View File

52
app/config.py Normal file
View File

@@ -0,0 +1,52 @@
"""Settings, read from environment variables (see .env.example)."""
import os
from pathlib import Path
def _env(name: str, default: str) -> str:
return os.environ.get(name, default)
def _int(name: str, default: int) -> int:
return int(_env(name, str(default)))
def _float(name: str, default: float) -> float:
return float(_env(name, str(default)))
DATA_DIR = Path(_env("DATA_DIR", "./data")).resolve()
DB_PATH = DATA_DIR / "recommender.db"
COOKIES_FILE = Path(_env("COOKIES_FILE", str(DATA_DIR / "cookies.txt")))
MODEL_CACHE = DATA_DIR / "models"
TZ = _env("TZ", "Australia/Melbourne")
RUN_HOUR = _int("RUN_HOUR", 5)
RUN_MINUTE = _int("RUN_MINUTE", 30)
DAILY_COUNT = _int("DAILY_COUNT", 25)
MAX_PER_CHANNEL = _int("MAX_PER_CHANNEL", 3)
EXPLORE_SLOTS = _int("EXPLORE_SLOTS", 3) # slots reserved for discoveries
NEW_VIDEO_DAYS = _int("NEW_VIDEO_DAYS", 7) # hard limit: never recommend anything older (incl. Watch Later)
NO_REPEAT_DAYS = _int("NO_REPEAT_DAYS", 14) # don't re-suggest within N days
EXCLUDE_SHORTS = _env("EXCLUDE_SHORTS", "true").lower() == "true"
MIN_DURATION_SEC = _int("MIN_DURATION_SEC", 90)
HISTORY_LIMIT = _int("HISTORY_LIMIT", 500)
WATCH_LATER_LIMIT = _int("WATCH_LATER_LIMIT", 500)
SUBS_FEED_LIMIT = _int("SUBS_FEED_LIMIT", 300)
DISCOVERY_PER_QUERY = _int("DISCOVERY_PER_QUERY", 10)
DISCOVERY_TOPICS = [t.strip() for t in _env("DISCOVERY_TOPICS", "").split(",") if t.strip()]
AUTO_TOPICS = _int("AUTO_TOPICS", 5) # topics auto-derived from what you watch
EMBED_MODEL = _env("EMBED_MODEL", "BAAI/bge-small-en-v1.5")
# Ranking weights
W_CONTENT = _float("W_CONTENT", 0.60)
W_CHANNEL = _float("W_CHANNEL", 0.25)
W_FRESH = _float("W_FRESH", 0.10)
WATCH_LATER_BOOST = _float("WATCH_LATER_BOOST", 0.15)
DIVERSITY = _float("DIVERSITY", 0.25) # MMR penalty for near-duplicates
DATA_DIR.mkdir(parents=True, exist_ok=True)
MODEL_CACHE.mkdir(parents=True, exist_ok=True)

127
app/db.py Normal file
View File

@@ -0,0 +1,127 @@
"""SQLite storage: videos, your signals (history/likes/etc.), and daily lists."""
import sqlite3
import time
from contextlib import contextmanager
import numpy as np
from . import config
SCHEMA = """
CREATE TABLE IF NOT EXISTS videos (
id TEXT PRIMARY KEY,
title TEXT,
channel TEXT,
channel_id TEXT,
description TEXT,
duration INTEGER,
published INTEGER, -- unix ts, NULL if unknown
is_short INTEGER DEFAULT 0,
source TEXT, -- subs / rss / discovery / history / watch_later
first_seen INTEGER,
embedding BLOB
);
CREATE TABLE IF NOT EXISTS channels (
channel_id TEXT PRIMARY KEY,
name TEXT,
subscribed INTEGER DEFAULT 0
);
-- kind: history | watch_later | up | down | watched | opened
CREATE TABLE IF NOT EXISTS signals (
video_id TEXT,
kind TEXT,
ts INTEGER,
position INTEGER, -- order in history/watch-later feed (0 = most recent)
PRIMARY KEY (video_id, kind)
);
CREATE TABLE IF NOT EXISTS recommendations (
day TEXT,
rank INTEGER,
video_id TEXT,
score REAL,
reason TEXT,
PRIMARY KEY (day, video_id)
);
CREATE TABLE IF NOT EXISTS runs (
started INTEGER,
finished INTEGER,
status TEXT,
message TEXT
);
"""
@contextmanager
def connect():
conn = sqlite3.connect(config.DB_PATH, timeout=30)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL")
try:
yield conn
conn.commit()
finally:
conn.close()
def init():
with connect() as c:
c.executescript(SCHEMA)
def upsert_video(c, v: dict):
"""Insert or update metadata without clobbering existing non-null values."""
c.execute(
"""
INSERT INTO videos (id, title, channel, channel_id, description, duration,
published, is_short, source, first_seen)
VALUES (:id, :title, :channel, :channel_id, :description, :duration,
:published, :is_short, :source, :now)
ON CONFLICT(id) DO UPDATE SET
title = COALESCE(excluded.title, videos.title),
channel = COALESCE(excluded.channel, videos.channel),
channel_id = COALESCE(excluded.channel_id, videos.channel_id),
description = COALESCE(NULLIF(excluded.description, ''), videos.description),
duration = COALESCE(excluded.duration, videos.duration),
published = COALESCE(videos.published, excluded.published),
is_short = MAX(videos.is_short, excluded.is_short)
""",
{
"id": v["id"],
"title": v.get("title"),
"channel": v.get("channel"),
"channel_id": v.get("channel_id"),
"description": v.get("description") or "",
"duration": v.get("duration"),
"published": v.get("published"),
"is_short": int(bool(v.get("is_short"))),
"source": v.get("source"),
"now": int(time.time()),
},
)
def set_signal(c, video_id: str, kind: str, position: int | None = None):
c.execute(
"""INSERT INTO signals (video_id, kind, ts, position) VALUES (?, ?, ?, ?)
ON CONFLICT(video_id, kind) DO UPDATE SET position = excluded.position""",
(video_id, kind, int(time.time()), position),
)
def remove_signal(c, video_id: str, kind: str):
c.execute("DELETE FROM signals WHERE video_id = ? AND kind = ?", (video_id, kind))
def replace_feed_signals(c, kind: str, video_ids: list[str]):
"""Watch Later changes over time: keep it in sync with the live list."""
c.execute("DELETE FROM signals WHERE kind = ?", (kind,))
for pos, vid in enumerate(video_ids):
set_signal(c, vid, kind, pos)
def to_blob(vec: np.ndarray) -> bytes:
return np.asarray(vec, dtype=np.float32).tobytes()
def from_blob(blob: bytes | None) -> np.ndarray | None:
return None if blob is None else np.frombuffer(blob, dtype=np.float32)

52
app/embed.py Normal file
View File

@@ -0,0 +1,52 @@
"""Text embeddings for video titles/descriptions (local, CPU, no API)."""
import logging
import numpy as np
from . import config, db
log = logging.getLogger(__name__)
_model = None
def _get_model():
global _model
if _model is None:
from fastembed import TextEmbedding
log.info("loading embedding model %s", config.EMBED_MODEL)
_model = TextEmbedding(config.EMBED_MODEL, cache_dir=str(config.MODEL_CACHE))
return _model
def video_text(row) -> str:
desc = (row["description"] or "").replace("\n", " ")[:400]
return f"{row['title'] or ''}. Channel: {row['channel'] or ''}. {desc}"
def embed_texts(texts: list[str]) -> np.ndarray:
vecs = np.array(list(_get_model().embed(texts, batch_size=64)), dtype=np.float32)
norms = np.linalg.norm(vecs, axis=1, keepdims=True)
return vecs / np.clip(norms, 1e-9, None)
def embed_missing(batch: int = 256) -> int:
"""Embed every stored video that doesn't have a vector yet."""
total = 0
with db.connect() as c:
while True:
rows = c.execute(
"SELECT id, title, channel, description FROM videos "
"WHERE embedding IS NULL AND title IS NOT NULL LIMIT ?",
(batch,),
).fetchall()
if not rows:
break
vecs = embed_texts([video_text(r) for r in rows])
c.executemany(
"UPDATE videos SET embedding = ? WHERE id = ?",
[(db.to_blob(v), r["id"]) for v, r in zip(vecs, rows)],
)
c.commit()
total += len(rows)
log.info("embedded %d videos", total)
return total

137
app/pipeline.py Normal file
View File

@@ -0,0 +1,137 @@
"""Daily job: sync YouTube -> embed -> rank -> store today's list.
Run manually: python -m app.pipeline
"""
import logging
import threading
import time
from datetime import date
from . import config, db, embed, recommender, youtube
log = logging.getLogger(__name__)
_lock = threading.Lock()
def sync() -> dict:
stats = {}
# 1. Your taste signals: watch history + watch later (need cookies)
history = youtube.fetch_history()
watch_later = youtube.fetch_watch_later()
stats["history"], stats["watch_later"] = len(history), len(watch_later)
if not history:
log.warning("history came back empty - cookies may have expired")
# 2. Subscribed channels -> new uploads (RSS gives publish dates)
try:
channels = youtube.fetch_subscribed_channels()
except Exception as exc: # noqa: BLE001
log.warning("could not list subscribed channels: %s", exc)
channels = []
stats["channels"] = len(channels)
rss = youtube.fetch_rss([ch["channel_id"] for ch in channels])
subs_feed = youtube.fetch_subscription_feed()
stats["rss"], stats["subs_feed"] = len(rss), len(subs_feed)
with db.connect() as c:
if channels:
c.execute("UPDATE channels SET subscribed = 0")
for ch in channels:
c.execute(
"""INSERT INTO channels (channel_id, name, subscribed) VALUES (?, ?, 1)
ON CONFLICT(channel_id) DO UPDATE SET name = excluded.name, subscribed = 1""",
(ch["channel_id"], ch["name"]),
)
for v in history + watch_later + rss + subs_feed:
db.upsert_video(c, v)
# history: keep every video ever seen, refresh positions of the recent ones
for pos, v in enumerate(history):
db.set_signal(c, v["id"], "history", pos)
# watch later mirrors the live list (things you removed drop out)
if watch_later or not history:
db.replace_feed_signals(c, "watch_later", [v["id"] for v in watch_later])
# 3. Discovery: recent videos on your topics from outside your subscriptions
topics = list(dict.fromkeys(config.DISCOVERY_TOPICS + recommender.auto_topics()))
found = []
for t in topics:
found += youtube.search_recent(t)
time.sleep(1)
with db.connect() as c:
for v in found:
db.upsert_video(c, v)
stats["discovery_topics"], stats["discovery"] = topics, len(found)
# 4. Fill in missing upload dates (subs feed / search results often lack them)
# from each channel's RSS feed. Anything still undated is never recommended.
stats["dates_filled"] = fill_missing_dates(already_fetched={ch["channel_id"] for ch in channels})
return stats
def fill_missing_dates(already_fetched: set[str]) -> int:
with db.connect() as c:
rows = c.execute(
"""SELECT DISTINCT channel_id FROM videos
WHERE published IS NULL AND channel_id LIKE 'UC%'
AND first_seen >= ?
AND id NOT IN (SELECT video_id FROM signals WHERE kind = 'history')""",
(int(time.time()) - 2 * 86400,),
).fetchall()
# Channels already fetched this run are covered: their missing videos are older than RSS's last 15.
todo = [r[0] for r in rows if r[0] not in already_fetched]
rss = youtube.fetch_rss(todo) if todo else []
filled = 0
with db.connect() as c:
for v in rss:
cur = c.execute("UPDATE videos SET published = ? WHERE id = ? AND published IS NULL",
(v["published"], v["id"]))
filled += cur.rowcount
log.info("filled upload dates for %d videos from %d channel feeds", filled, len(todo))
return filled
def run(skip_sync: bool = False) -> dict:
if not _lock.acquire(blocking=False):
return {"status": "already running"}
started = int(time.time())
try:
db.init()
stats = {} if skip_sync else sync()
stats["embedded"] = embed.embed_missing()
stats["picked"] = recommender.recommend(date.today())
status, msg = "ok", str(stats)
log.info("run complete: %s", stats)
return {"status": "ok", **stats}
except youtube.CookieError as exc:
status, msg = "error", str(exc)
log.error(msg)
return {"status": "error", "message": msg}
except Exception as exc: # noqa: BLE001
status, msg = "error", repr(exc)
log.exception("run failed")
return {"status": "error", "message": msg}
finally:
with db.connect() as c:
c.execute("INSERT INTO runs VALUES (?, ?, ?, ?)", (started, int(time.time()), status, msg[:2000]))
_lock.release()
def is_running() -> bool:
return _lock.locked()
if __name__ == "__main__":
import argparse
import json
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
ap = argparse.ArgumentParser(description="Build today's YouTube list")
ap.add_argument("--skip-sync", action="store_true", help="re-rank without fetching from YouTube")
ap.add_argument("--check-cookies", action="store_true", help="only test that cookies work")
args = ap.parse_args()
if args.check_cookies:
ok = youtube.check_cookies()
print("cookies OK - signed in" if ok else "cookies NOT working - re-export them")
raise SystemExit(0 if ok else 1)
print(json.dumps(run(skip_sync=args.skip_sync), indent=2, default=str))

285
app/recommender.py Normal file
View File

@@ -0,0 +1,285 @@
"""Learn your taste from signals and pick the daily list.
Score = W_CONTENT * content similarity to what you watch/like
+ W_CHANNEL * how much you watch that channel
+ W_FRESH * how new the video is
(+ boost if it's on your Watch Later)
Then a diversity pass (MMR + per-channel cap) picks the final list,
keeping a few slots for discoveries outside your usual channels.
"""
import math
import re
import time
from collections import Counter, defaultdict
from datetime import date, timedelta
import numpy as np
from . import config, db
POSITIVE_WEIGHTS = {"up": 3.0, "watched": 1.5, "watch_later": 1.5, "opened": 0.5}
NEGATIVE_WEIGHT = 3.0
DAY = 86400
STOPWORDS = set("""
a an the and or but of to in on for with at by from as is are was were be been it its this that
these those you your i my me we our they their he she his her them how what why when where who
which vs vs. new video videos official full part episode ep live best top first last more most
just get got make made can will not no yes all any one two three into out up down over about
after before than then so do does did have has had amp quot s t
""".split())
# ---------------------------------------------------------------- profile
def _history_weight(position: int | None) -> float:
pos = position or 0
return 0.3 + math.exp(-pos / 150) # recent history counts more
def build_profile(c):
"""Return positive/negative vectors, per-channel affinity and labelled history."""
rows = c.execute(
"""SELECT s.video_id, s.kind, s.position, v.title, v.channel, v.channel_id, v.embedding
FROM signals s JOIN videos v ON v.id = s.video_id"""
).fetchall()
pos_vecs, pos_w, pos_titles = [], [], []
neg_vecs = []
chan = defaultdict(float)
for r in rows:
key = r["channel_id"] or r["channel"]
vec = db.from_blob(r["embedding"])
if r["kind"] == "down":
if key:
chan[key] -= NEGATIVE_WEIGHT
if vec is not None:
neg_vecs.append(vec)
continue
w = _history_weight(r["position"]) if r["kind"] == "history" else POSITIVE_WEIGHTS.get(r["kind"], 0)
if key:
chan[key] += w
if vec is not None:
pos_vecs.append(vec)
pos_w.append(w)
pos_titles.append(r["title"] or "")
profile = {
"pos": np.array(pos_vecs) if pos_vecs else None,
"pos_w": np.array(pos_w) if pos_w else None,
"pos_titles": pos_titles,
"neg": np.array(neg_vecs) if neg_vecs else None,
"centroid": None,
"channel": {},
}
if pos_vecs:
cen = (profile["pos"] * profile["pos_w"][:, None]).sum(0)
profile["centroid"] = cen / max(np.linalg.norm(cen), 1e-9)
top = max((v for v in chan.values() if v > 0), default=0)
for k, v in chan.items():
profile["channel"][k] = (math.log1p(v) / math.log1p(top)) if v > 0 and top else min(v, 0) / 10
return profile
# ---------------------------------------------------------------- candidates
def load_candidates(c, today: date):
now = int(time.time())
since_new = now - config.NEW_VIDEO_DAYS * DAY
no_repeat = (today - timedelta(days=config.NO_REPEAT_DAYS)).isoformat()
wl_no_repeat = (today - timedelta(days=3)).isoformat()
rows = c.execute(
f"""
SELECT v.*, (wl.video_id IS NOT NULL) AS on_watch_later,
COALESCE(ch.subscribed, 0) AS subscribed
FROM videos v
LEFT JOIN signals wl ON wl.video_id = v.id AND wl.kind = 'watch_later'
LEFT JOIN channels ch ON ch.channel_id = v.channel_id
WHERE v.embedding IS NOT NULL
-- hard age limit: upload date must be known and within NEW_VIDEO_DAYS
AND v.published IS NOT NULL
AND v.published >= :since_new
AND v.id NOT IN (SELECT video_id FROM signals
WHERE kind IN ('history', 'watched', 'down'))
AND (
(wl.video_id IS NULL
AND v.id NOT IN (SELECT video_id FROM recommendations
WHERE day >= :no_repeat AND day < :today))
OR (wl.video_id IS NOT NULL
AND v.id NOT IN (SELECT video_id FROM recommendations
WHERE day >= :wl_no_repeat AND day < :today))
)
{"AND v.is_short = 0" if config.EXCLUDE_SHORTS else ""}
AND (v.duration IS NULL OR v.duration >= :min_dur)
""",
{
"since_new": since_new, "no_repeat": no_repeat,
"wl_no_repeat": wl_no_repeat, "today": today.isoformat(),
"min_dur": config.MIN_DURATION_SEC if config.EXCLUDE_SHORTS else 0,
},
).fetchall()
return rows
# ---------------------------------------------------------------- scoring
def score_candidates(rows, profile):
now = time.time()
if not rows:
return []
E = np.stack([db.from_blob(r["embedding"]) for r in rows])
content = np.zeros(len(rows))
nearest = [None] * len(rows)
if profile["pos"] is not None:
sims = E @ profile["pos"].T # (cands, positives)
k = min(5, sims.shape[1])
topk = np.sort(sims, axis=1)[:, -k:].mean(1) # captures multiple interests
cen = E @ profile["centroid"]
content = 0.5 * topk + 0.5 * cen
best = sims.argmax(1)
for i, j in enumerate(best):
if sims[i, j] > 0.8:
nearest[i] = profile["pos_titles"][j]
if profile["neg"] is not None:
neg = (E @ profile["neg"].T).max(1)
content -= np.clip(neg - 0.75, 0, None) * 2.0 # push away from 👎-like items
# Embedding sims sit in a narrow band (unrelated titles still ~0.6),
# so rescale to 0..1 across today's candidates.
if len(rows) > 1 and content.std() > 1e-6:
lo, hi = np.percentile(content, 5), np.percentile(content, 95)
content = np.clip((content - lo) / max(hi - lo, 1e-6), 0, 1)
scored = []
for i, r in enumerate(rows):
key = r["channel_id"] or r["channel"]
aff = profile["channel"].get(key, 0.0)
if r["published"]:
fresh = math.exp(-max(now - r["published"], 0) / DAY / 3)
else:
fresh = 0.5
if r["on_watch_later"]:
fresh = max(fresh, 0.3)
s = config.W_CONTENT * content[i] + config.W_CHANNEL * aff + config.W_FRESH * fresh
if r["on_watch_later"]:
s += config.WATCH_LATER_BOOST
if r["subscribed"]:
s += 0.03
scored.append({
"row": r, "vec": E[i], "score": float(s), "content": float(content[i]),
"affinity": aff, "nearest": nearest[i],
})
return scored
def _reason(item) -> str:
r = item["row"]
if r["on_watch_later"]:
return "On your Watch Later"
if item.get("explore"):
return "New discovery outside your usual channels"
if item["nearest"]:
t = item["nearest"]
return f"Similar to “{t[:70]}{'…' if len(t) > 70 else ''}”"
if item["affinity"] > 0.5:
return f"You watch {r['channel']} a lot"
if r["subscribed"]:
return "New from a channel you subscribe to"
return "Matches your interests"
def select(scored, n=config.DAILY_COUNT):
"""Greedy MMR with a per-channel cap, plus reserved exploration slots."""
explore_n = min(config.EXPLORE_SLOTS, n)
main_n = n - explore_n
def pick(pool, k, chosen, per_channel):
out = []
pool = sorted(pool, key=lambda x: x["score"], reverse=True)[:400]
while pool and len(out) < k:
best, best_val = None, -1e9
for it in pool:
key = it["row"]["channel_id"] or it["row"]["channel"]
if per_channel[key] >= config.MAX_PER_CHANNEL:
continue
red = max((float(it["vec"] @ c["vec"]) for c in chosen), default=0)
val = it["score"] - config.DIVERSITY * max(red - 0.5, 0) * 2
if val > best_val:
best, best_val = it, val
if best is None:
break
pool.remove(best)
chosen.append(best)
out.append(best)
per_channel[best["row"]["channel_id"] or best["row"]["channel"]] += 1
return out
chosen: list = []
per_channel: Counter = Counter()
main = pick(scored, main_n, chosen, per_channel)
picked_ids = {x["row"]["id"] for x in main}
explore_pool = [
dict(x, explore=True, score=x["content"])
for x in scored
if x["row"]["id"] not in picked_ids and x["affinity"] <= 0 and not x["row"]["on_watch_later"]
]
explore = pick(explore_pool, explore_n, chosen, per_channel)
# Top up from the main pool if there weren't enough discoveries.
if len(main) + len(explore) < n:
rest = [x for x in scored if x["row"]["id"] not in {y["row"]["id"] for y in chosen}]
main += pick(rest, n - len(main) - len(explore), chosen, per_channel)
final = sorted(main, key=lambda x: x["score"], reverse=True)
# Sprinkle discoveries through the list rather than dumping them at the end.
for i, ex in enumerate(explore):
final.insert(min(len(final), 4 + i * 7), ex)
for it in final:
it["reason"] = _reason(it)
return final[:n]
def recommend(today: date | None = None) -> int:
today = today or date.today()
with db.connect() as c:
profile = build_profile(c)
rows = load_candidates(c, today)
picks = select(score_candidates(rows, profile))
c.execute("DELETE FROM recommendations WHERE day = ?", (today.isoformat(),))
c.executemany(
"INSERT INTO recommendations (day, rank, video_id, score, reason) VALUES (?, ?, ?, ?, ?)",
[(today.isoformat(), i + 1, p["row"]["id"], p["score"], p["reason"])
for i, p in enumerate(picks)],
)
return len(picks)
# ---------------------------------------------------------------- discovery topics
def auto_topics(n: int = config.AUTO_TOPICS) -> list[str]:
"""Pick search topics from words/phrases that recur in what you watch and like."""
if n <= 0:
return []
with db.connect() as c:
titles = [r[0] for r in c.execute(
"""SELECT v.title FROM signals s JOIN videos v ON v.id = s.video_id
WHERE s.kind IN ('up', 'watched', 'watch_later')
OR (s.kind = 'history' AND COALESCE(s.position, 0) < 200)"""
) if r[0]]
uni, bi = Counter(), Counter()
for t in titles:
words = [w for w in re.findall(r"[a-z0-9][a-z0-9+#.-]*", t.lower())
if w not in STOPWORDS and len(w) > 2 and not w.isdigit()]
uni.update(set(words))
bi.update({f"{a} {b}" for a, b in zip(words, words[1:])})
topics = [p for p, cnt in bi.most_common(n * 2) if cnt >= 3][:n]
for w, cnt in uni.most_common(n * 3):
if len(topics) >= n:
break
if cnt >= 3 and not any(w in t for t in topics):
topics.append(w)
return topics

117
app/templates/index.html Normal file
View File

@@ -0,0 +1,117 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Daily 25 · {{ day }}</title>
<link rel="icon" href="/favicon.ico">
<link rel="shortcut icon" href="/favicon.ico">
<style>
:root { --bg:#0f0f10; --card:#1a1a1d; --muted:#9a9aa3; --text:#ececf1; --accent:#ff4d4d; --ok:#3ecf8e; }
* { box-sizing: border-box; }
body { margin:0; font:15px/1.4 system-ui, -apple-system, "Segoe UI", sans-serif; background:var(--bg); color:var(--text); }
header { display:flex; flex-wrap:wrap; gap:12px; align-items:center; justify-content:space-between;
padding:16px 24px; border-bottom:1px solid #2a2a2f; position:sticky; top:0; background:var(--bg); z-index:2; }
h1 { font-size:20px; margin:0; } h1 span { color:var(--accent); }
.meta { color:var(--muted); font-size:13px; }
.controls { display:flex; gap:8px; align-items:center; }
select, button { background:#26262b; color:var(--text); border:1px solid #34343a; border-radius:8px; padding:7px 12px; font:inherit; cursor:pointer; }
button:hover { border-color:#55555e; }
main { display:grid; grid-template-columns:repeat(auto-fill, minmax(300px, 1fr)); gap:18px; padding:24px; }
.card { background:var(--card); border-radius:12px; overflow:hidden; display:flex; flex-direction:column; transition:opacity .2s; }
.card.down { opacity:.35; } .card.watched { opacity:.6; }
.thumb { position:relative; display:block; aspect-ratio:16/9; background:#000; }
.thumb img { width:100%; height:100%; object-fit:cover; display:block; }
.rank { position:absolute; top:8px; left:8px; background:rgba(0,0,0,.75); padding:2px 8px; border-radius:6px; font-weight:600; }
.dur { position:absolute; bottom:8px; right:8px; background:rgba(0,0,0,.8); padding:1px 6px; border-radius:4px; font-size:12px; }
.body { padding:12px 14px; flex:1; display:flex; flex-direction:column; gap:6px; }
.title { font-weight:600; color:var(--text); text-decoration:none; display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; overflow:hidden; }
.chan { color:var(--muted); font-size:13px; }
.reason { font-size:12px; color:#c9b2ff; }
.actions { display:flex; gap:6px; padding:0 14px 14px; }
.actions button { flex:1; padding:6px 0; }
.actions button.on[data-kind=up] { background:#1f3b2f; border-color:var(--ok); }
.actions button.on[data-kind=down] { background:#3b1f1f; border-color:var(--accent); }
.actions button.on[data-kind=watched] { background:#1f2a3b; border-color:#5b8cff; }
.empty { padding:60px 24px; text-align:center; color:var(--muted); grid-column:1/-1; }
.err { color:var(--accent); }
</style>
</head>
<body>
<header>
<div>
<h1>Daily <span>25</span> · {{ day }}</h1>
<div class="meta">
{{ n_ratings }} ratings so far · refreshes daily at {{ run_time }}
{% if running %} · <strong>building list…</strong>{% endif %}
{% if last_run and last_run.status == 'error' %} · <span class="err">last run failed: {{ last_run.message[:160] }}</span>{% endif %}
</div>
</div>
<div class="controls">
<select onchange="location.href='/?day='+this.value">
{% for d in days %}<option value="{{ d }}" {% if d == day %}selected{% endif %}>{{ d }}</option>{% endfor %}
</select>
<button onclick="runNow(true)" title="Re-rank using your latest 👍/👎 (fast)">Re-rank</button>
<button onclick="runNow(false)" title="Fetch from YouTube and rebuild (slow)">Refresh from YouTube</button>
</div>
</header>
<main>
{% for v in videos %}
<div class="card {% if v.down %}down{% endif %} {% if v.watched %}watched{% endif %}" id="c-{{ v.id }}">
<a class="thumb" href="https://www.youtube.com/watch?v={{ v.id }}" target="_blank" rel="noopener" onclick="send('{{ v.id }}','opened',true)">
<img loading="lazy" src="https://i.ytimg.com/vi/{{ v.id }}/mqdefault.jpg" alt="">
<span class="rank">#{{ v.rank }}</span>
{% if v.duration_str %}<span class="dur">{{ v.duration_str }}</span>{% endif %}
</a>
<div class="body">
<a class="title" href="https://www.youtube.com/watch?v={{ v.id }}" target="_blank" rel="noopener" onclick="send('{{ v.id }}','opened',true)">{{ v.title }}</a>
<div class="chan">{{ v.channel or '' }}{% if v.age %} · {{ v.age }}{% endif %}</div>
<div class="reason">{{ v.reason }}</div>
</div>
<div class="actions">
<button data-kind="up" class="{% if v.up %}on{% endif %}" onclick="toggle(this,'{{ v.id }}')" title="More like this">👍</button>
<button data-kind="down" class="{% if v.down %}on{% endif %}" onclick="toggle(this,'{{ v.id }}')" title="Less like this">👎</button>
<button data-kind="watched" class="{% if v.watched %}on{% endif %}" onclick="toggle(this,'{{ v.id }}')" title="Mark as watched">✓ Watched</button>
</div>
</div>
{% else %}
<div class="empty">
{% if running %}Building your first list. This page will refresh by itself.
{% else %}No list yet. Click <b>Refresh from YouTube</b>.{% endif %}
</div>
{% endfor %}
</main>
<script>
async function send(id, kind, on) {
try {
await fetch('/api/feedback', {method:'POST', headers:{'Content-Type':'application/json'},
body: JSON.stringify({video_id:id, kind:kind, on:on})});
} catch (e) { console.error(e); }
}
function toggle(btn, id) {
const kind = btn.dataset.kind, on = !btn.classList.contains('on');
const card = document.getElementById('c-' + id);
if (on && (kind === 'up' || kind === 'down')) {
card.querySelectorAll('button[data-kind=up],button[data-kind=down]').forEach(b => b.classList.remove('on'));
card.classList.remove('down');
}
btn.classList.toggle('on', on);
if (kind === 'down') card.classList.toggle('down', on);
if (kind === 'watched') card.classList.toggle('watched', on);
send(id, kind, on);
}
async function runNow(rerank) {
await fetch('/api/run?rerank_only=' + rerank, {method:'POST'});
setTimeout(() => location.href = '/', 800);
}
{% if running %}
(async function poll() {
const s = await (await fetch('/api/status')).json();
if (!s.running) location.href = '/'; else setTimeout(poll, 5000);
})();
{% endif %}
</script>
</body>
</html>

155
app/web.py Normal file
View File

@@ -0,0 +1,155 @@
"""Web UI + daily scheduler. Run: uvicorn app.web:app --host 0.0.0.0 --port 8080"""
import logging
import threading
from contextlib import asynccontextmanager
from datetime import date, datetime
from pathlib import Path
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
from fastapi import FastAPI, HTTPException, Request
import requests
from fastapi.responses import FileResponse, HTMLResponse, Response
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel
from . import config, db, pipeline
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
log = logging.getLogger("web")
templates = Jinja2Templates(directory=str(Path(__file__).parent / "templates"))
scheduler = BackgroundScheduler(timezone=config.TZ)
FEEDBACK_KINDS = {"up", "down", "watched", "opened"}
def _run_in_background(skip_sync: bool = False):
threading.Thread(target=pipeline.run, kwargs={"skip_sync": skip_sync}, daemon=True).start()
@asynccontextmanager
async def lifespan(_app: FastAPI):
db.init()
scheduler.add_job(pipeline.run, CronTrigger(hour=config.RUN_HOUR, minute=config.RUN_MINUTE),
id="daily", replace_existing=True, misfire_grace_time=3600)
scheduler.start()
with db.connect() as c:
has_today = c.execute("SELECT 1 FROM recommendations WHERE day = ? LIMIT 1",
(date.today().isoformat(),)).fetchone()
if not has_today:
log.info("no list for today yet - building one now")
_run_in_background()
yield
scheduler.shutdown(wait=False)
app = FastAPI(title="YouTube Daily 25", lifespan=lifespan)
def _fmt_duration(sec):
if not sec:
return ""
h, rem = divmod(int(sec), 3600)
m, s = divmod(rem, 60)
return f"{h}:{m:02d}:{s:02d}" if h else f"{m}:{s:02d}"
def _fmt_age(ts):
if not ts:
return ""
days = (datetime.now() - datetime.fromtimestamp(ts)).days
return "today" if days <= 0 else ("yesterday" if days == 1 else f"{days} days ago")
@app.get("/", response_class=HTMLResponse)
def index(request: Request, day: str | None = None):
with db.connect() as c:
days = [r[0] for r in c.execute(
"SELECT DISTINCT day FROM recommendations ORDER BY day DESC LIMIT 14")]
day = day or (days[0] if days else date.today().isoformat())
rows = c.execute(
"""SELECT r.rank, r.reason, r.score, v.*,
MAX(CASE WHEN s.kind = 'up' THEN 1 END) AS up,
MAX(CASE WHEN s.kind = 'down' THEN 1 END) AS down,
MAX(CASE WHEN s.kind = 'watched' THEN 1 END) AS watched
FROM recommendations r
JOIN videos v ON v.id = r.video_id
LEFT JOIN signals s ON s.video_id = r.video_id
WHERE r.day = ?
GROUP BY r.video_id ORDER BY r.rank""",
(day,),
).fetchall()
last_run = c.execute("SELECT * FROM runs ORDER BY started DESC LIMIT 1").fetchone()
n_ratings = c.execute(
"SELECT COUNT(*) FROM signals WHERE kind IN ('up','down','watched')").fetchone()[0]
videos = [dict(r, duration_str=_fmt_duration(r["duration"]), age=_fmt_age(r["published"]))
for r in rows]
return templates.TemplateResponse(request, "index.html", {
"videos": videos, "day": day, "days": days, "running": pipeline.is_running(),
"last_run": dict(last_run) if last_run else None, "n_ratings": n_ratings,
"run_time": f"{config.RUN_HOUR:02d}:{config.RUN_MINUTE:02d}",
})
class Feedback(BaseModel):
video_id: str
kind: str
on: bool = True
@app.post("/api/feedback")
def feedback(fb: Feedback):
if fb.kind not in FEEDBACK_KINDS:
raise HTTPException(400, "unknown feedback kind")
with db.connect() as c:
if not c.execute("SELECT 1 FROM videos WHERE id = ?", (fb.video_id,)).fetchone():
raise HTTPException(404, "unknown video")
if fb.on:
if fb.kind in ("up", "down"): # thumbs are mutually exclusive
db.remove_signal(c, fb.video_id, "down" if fb.kind == "up" else "up")
db.set_signal(c, fb.video_id, fb.kind)
else:
db.remove_signal(c, fb.video_id, fb.kind)
return {"ok": True}
@app.post("/api/run")
def run_now(rerank_only: bool = False):
if pipeline.is_running():
return {"status": "already running"}
_run_in_background(skip_sync=rerank_only)
return {"status": "started"}
@app.get("/api/status")
def status():
with db.connect() as c:
last = c.execute("SELECT * FROM runs ORDER BY started DESC LIMIT 1").fetchone()
return {"running": pipeline.is_running(), "last_run": dict(last) if last else None}
FAVICON_SRC = "https://www.youtube.com/favicon.ico"
FAVICON_CACHE = config.DATA_DIR / "favicon.ico"
@app.get("/favicon.ico", include_in_schema=False)
@app.get("/apple-touch-icon.png", include_in_schema=False)
def favicon():
"""Serve the icon from our own origin (speed-dial tiles and some browsers
only look at /favicon.ico). Fetched from YouTube once, then cached in data/."""
if not FAVICON_CACHE.exists():
try:
r = requests.get(FAVICON_SRC, timeout=10)
r.raise_for_status()
FAVICON_CACHE.write_bytes(r.content)
except Exception as exc: # noqa: BLE001
log.warning("could not fetch favicon: %s", exc)
return Response(status_code=404)
return FileResponse(FAVICON_CACHE, media_type="image/x-icon",
headers={"Cache-Control": "public, max-age=604800"})
@app.get("/health")
def health():
return {"ok": True}

172
app/youtube.py Normal file
View File

@@ -0,0 +1,172 @@
"""Read your YouTube data with yt-dlp (using cookies) and public RSS feeds.
No Google API key or OAuth is needed: History and Watch Later aren't
available through the official API, so everything goes through yt-dlp.
"""
import logging
import re
import time
import xml.etree.ElementTree as ET
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
import requests
from yt_dlp import YoutubeDL
from . import config
log = logging.getLogger(__name__)
FEED_HISTORY = "https://www.youtube.com/feed/history"
FEED_WATCH_LATER = "https://www.youtube.com/playlist?list=WL"
FEED_SUBSCRIPTIONS = "https://www.youtube.com/feed/subscriptions"
FEED_CHANNELS = "https://www.youtube.com/feed/channels"
RSS_URL = "https://www.youtube.com/feeds/videos.xml?channel_id={}"
ATOM = {
"a": "http://www.w3.org/2005/Atom",
"yt": "http://www.youtube.com/xml/schemas/2015",
"media": "http://search.yahoo.com/mrss/",
}
VIDEO_ID = re.compile(r"^[A-Za-z0-9_-]{11}$")
class CookieError(RuntimeError):
pass
def _ydl_opts(limit: int, use_cookies: bool = True) -> dict:
opts = {
"extract_flat": "in_playlist",
"skip_download": True,
"quiet": True,
"no_warnings": True,
"ignoreerrors": True,
"playlistend": limit,
"lazy_playlist": True,
"sleep_interval_requests": 1, # be gentle with your account
}
if use_cookies:
if not config.COOKIES_FILE.exists():
raise CookieError(
f"cookies file not found at {config.COOKIES_FILE}. "
"See README: 'Export your YouTube cookies'."
)
opts["cookiefile"] = str(config.COOKIES_FILE)
return opts
def _flat(url: str, limit: int, use_cookies: bool = True) -> list[dict]:
with YoutubeDL(_ydl_opts(limit, use_cookies)) as ydl:
info = ydl.extract_info(url, download=False)
if not info:
return []
return [e for e in (info.get("entries") or []) if e][:limit]
def _normalise(entry: dict, source: str) -> dict | None:
vid = entry.get("id")
if not vid or not VIDEO_ID.match(vid):
return None
url = entry.get("url") or ""
duration = entry.get("duration")
ts = entry.get("timestamp") or entry.get("release_timestamp")
return {
"id": vid,
"title": entry.get("title"),
"channel": entry.get("channel") or entry.get("uploader"),
"channel_id": entry.get("channel_id") or entry.get("uploader_id"),
"description": entry.get("description") or "",
"duration": int(duration) if duration else None,
"published": int(ts) if ts else None,
"is_short": "/shorts/" in url,
"source": source,
}
def _clean(entries: list[dict], source: str) -> list[dict]:
out = []
for e in entries:
v = _normalise(e, source)
if v:
out.append(v)
return out
def check_cookies() -> bool:
"""True if the cookies give a signed-in session (History is readable)."""
try:
return bool(_flat(FEED_HISTORY, 1))
except Exception as exc: # noqa: BLE001
log.warning("cookie check failed: %s", exc)
return False
def fetch_history(limit: int = config.HISTORY_LIMIT) -> list[dict]:
return _clean(_flat(FEED_HISTORY, limit), "history")
def fetch_watch_later(limit: int = config.WATCH_LATER_LIMIT) -> list[dict]:
return _clean(_flat(FEED_WATCH_LATER, limit), "watch_later")
def fetch_subscription_feed(limit: int = config.SUBS_FEED_LIMIT) -> list[dict]:
return _clean(_flat(FEED_SUBSCRIPTIONS, limit), "subs")
def fetch_subscribed_channels() -> list[dict]:
chans = []
for e in _flat(FEED_CHANNELS, 2000):
cid = e.get("channel_id") or e.get("id")
if cid and cid.startswith("UC"):
chans.append({"channel_id": cid, "name": e.get("channel") or e.get("title")})
return chans
def _rss_one(channel_id: str) -> list[dict]:
try:
r = requests.get(RSS_URL.format(channel_id), timeout=15)
if r.status_code != 200:
return []
root = ET.fromstring(r.content)
except Exception: # noqa: BLE001
return []
out = []
for e in root.findall("a:entry", ATOM):
vid = e.findtext("yt:videoId", namespaces=ATOM)
link = e.find("a:link", ATOM)
href = link.get("href", "") if link is not None else ""
pub = e.findtext("a:published", namespaces=ATOM)
group = e.find("media:group", ATOM)
desc = group.findtext("media:description", namespaces=ATOM) if group is not None else ""
out.append({
"id": vid,
"title": e.findtext("a:title", namespaces=ATOM),
"channel": e.findtext("a:author/a:name", namespaces=ATOM),
"channel_id": channel_id,
"description": (desc or "")[:1000],
"duration": None,
"published": int(datetime.fromisoformat(pub).timestamp()) if pub else None,
"is_short": "/shorts/" in href,
"source": "rss",
})
return [v for v in out if v["id"]]
def fetch_rss(channel_ids: list[str], workers: int = 8) -> list[dict]:
"""Latest ~15 uploads per channel with publish dates. No cookies, no quota."""
with ThreadPoolExecutor(max_workers=workers) as pool:
results = pool.map(_rss_one, channel_ids)
return [v for batch in results for v in batch]
def search_recent(query: str, limit: int = config.DISCOVERY_PER_QUERY) -> list[dict]:
"""Newest search results for a topic (discovery outside your subscriptions)."""
try:
entries = _flat(f"ytsearchdate{limit}:{query}", limit, use_cookies=False)
except Exception as exc: # noqa: BLE001
log.warning("search %r failed: %s", query, exc)
return []
# Search results usually have no exact upload date; the pipeline fills it
# from the channel's RSS feed. Undated videos are never recommended.
return _clean(entries, "discovery")

53
data/cookies.txt Normal file
View File

@@ -0,0 +1,53 @@
# Netscape HTTP Cookie File
# This file is generated by yt-dlp. Do not edit.
.youtube.com TRUE / TRUE 1811608700 __Secure-1PSIDTS sidts-CjUBnJZzamFDk8hYOxWaGoo9BNRIRTUn2Ja44wdKHNo3Yf0OP4zGZoMwzAdtGHK99LgAgg3IGhAA
.youtube.com TRUE / TRUE 1811608700 __Secure-3PSIDTS sidts-CjUBnJZzamFDk8hYOxWaGoo9BNRIRTUn2Ja44wdKHNo3Yf0OP4zGZoMwzAdtGHK99LgAgg3IGhAA
.youtube.com TRUE / FALSE 1811608700 HSID AZq_jbTBVmFUbhQnp
.youtube.com TRUE / TRUE 1811608700 SSID ANO5j7nQLctqs-PsM
.youtube.com TRUE / FALSE 1811608700 APISID t1kqgCO2tlTHLf4C/AlFgheIiPzNbXFL4a
.youtube.com TRUE / TRUE 1811608700 SAPISID Bb9nLT8mP2zXQc9L/AlEE0Jlo6wqqoUkgo
.youtube.com TRUE / TRUE 1811608700 __Secure-1PAPISID Bb9nLT8mP2zXQc9L/AlEE0Jlo6wqqoUkgo
.youtube.com TRUE / TRUE 1811608700 __Secure-3PAPISID Bb9nLT8mP2zXQc9L/AlEE0Jlo6wqqoUkgo
.youtube.com TRUE / FALSE 1811608700 SID g.a000FQlWJ9HTNZd3fC_MXlmhnocrc_kvZzIQUDybgqFT4zRhCFeEE899ZwQvUnyvent34GbF9gACgYKAb0SARcSFQHGX2MifB95DvnTbUqsb9x2FdVlpRoVAUF8yKoPau3FDKQg5oBFLKbNYk-H0076
.youtube.com TRUE / TRUE 1811608700 __Secure-1PSID g.a000FQlWJ9HTNZd3fC_MXlmhnocrc_kvZzIQUDybgqFT4zRhCFeE606IyvXYBQ4_9E8x22Ug2wACgYKAcESARcSFQHGX2MiGarLvPp8hjN1YE3xitHl4hoVAUF8yKq0Fx2iLuTYOjEMCsypM1gu0076
.youtube.com TRUE / TRUE 1811608700 __Secure-3PSID g.a000FQlWJ9HTNZd3fC_MXlmhnocrc_kvZzIQUDybgqFT4zRhCFeEyH7r05Gp2ZMx9fUNaVP9IgACgYKAVASARcSFQHGX2MiXbAWyGXon1Gsx6y2o0BmcRoVAUF8yKrOeLjvg3tcvjTjohUoTwiB0076
.youtube.com TRUE / TRUE 1811608701 LOGIN_INFO AFmmF2swRQIgBb1XHK1wm9l2KNPJVrGjhiDpBfajs7JlrBdrhsQg-wUCIQCuxSE9xS1HS9uj5PQn7GhJhvpYCD1yCzFVq_PA8VNIUg:QUQ3MjNmenhZSWp2X0FrQ3NFdElUT3BSNlFhTVd1NXVTNUxVTnd5QVZGVzg0Nmk1bXUxS0ZrTHBHd25MM0MtTDlCS1o0YXpyVXY4UHZHbkJaVmd1RWdPcTdOdVJ6S1lZYXp6Nm5SQUQzdjFZR01SM0R5V0R5OW44a0tUbkVzZTJFUmJxN0k0dm1XYnRGbHpkd0lWWExKSzN3VWZ3ZU5iWkdB
.youtube.com TRUE / FALSE 0 PREF f6=40000080&tz=UTC&hl=en
.youtube.com TRUE / FALSE 1827709239 SIDCC APD_SKHvSwahREWTX6LDiyeH5Pg7O6NTz33NLZZuTkqYx-1vjTzY7QUjn-zwi8blw3v_qC4Rdw
.youtube.com TRUE / TRUE 1827709239 __Secure-1PSIDCC APD_SKEu6QWe0yfN8j3cwArZu1kdXLkliA3_YYp8hbOsoaTN5t_8w0t8VbTrQPPJ_Lo8dUvz
.youtube.com TRUE / TRUE 1827709239 __Secure-3PSIDCC APD_SKEJG67GzvHmBrOySjmnZH2bqvUoXLy6K1zrgKLphHqIAZYJ-3uXSwEG-m_t2cO39ACzLg
.youtube.com TRUE / TRUE 0 YSC Pp3KcYH3RRw
.youtube.com TRUE / TRUE 1811725239 VISITOR_INFO1_LIVE fbVjnWDMhmA
.youtube.com TRUE / TRUE 1811725239 VISITOR_PRIVACY_METADATA CgJBVRIEGgAgDg%3D%3D
.youtube.com TRUE / TRUE 1811725200 __Secure-YNID CtoBCAUSjAEBDB6PDLn2SdNNEsrmnw9W5WWmPdmLAUrLQAtJH0BJgn1XrnFLF0e4Eyp5ZlFmQoINDrwv7D0OUN9ff-aX82VFh21Oi-hQnTYV_v4NOZTa5bXpqfqbJqZzuva6gJBK9PU_ztZWcJZtE2AWru2BPEqA53Disqbw8FNu-3Cxn1G7EHu9mjkbtIeVPCqmrSgFMkUBHFj1amOaAYoOMGLke345cmsOEBJnVYBZn7h-fDbW1l9BSk9H10ybYp9lgTC7Nev4zqhulGLdeWFXdbJC7pQJJpzG5Qg
.youtube.com TRUE / TRUE 1811725200 __Secure-ROLLOUT_TOKEN CM_Ly9q9-Zay9gEQwqbzupCwmAMYuoC7zMKzmAM%3D
accounts.google.com FALSE / TRUE 1798648667 OTZ 8895878_12_12_133440_16_395520
accounts.google.com FALSE / TRUE 1811608699 __Host-GAPS 1:EWOD05NkXEUkJCiLWK1KPnCtXmTbSKXGMflRs96pXrfZBmb36iZvi1WSeM-ZMxZjZmUW-_2fXwOh3mkeg6NdHAzZlMWNNw:S1imGa_0-2VDkbBS
accounts.google.com FALSE / TRUE 1811608699 SMSV ADHTe-CVLN9gqda_4ZT5nJF-4jriRToBWhJg4ewlfPQxmWlBOoAHlQXWsC-Vt__Dv3ddwpX3VYbesxVnASKw2CQ3ZX7JiQxL1wP1niRi1ijzq_VFC53HPMI
accounts.google.com FALSE / TRUE 1811608699 LSID s.AU|s.youtube:g.a000FQlWJx8YKBkfXKL87fQbGF3JpT5Hbwh8eZoiMykjNSHK7t5ihETYahyUW8eV1gxqSfIQhwACgYKAbkSARcSFQHGX2MiJEofkdcX1uvi_I1-6gkJkhoVAUF8yKpiIfJeuz6BTa53OFee1SfF0076
accounts.google.com FALSE / TRUE 1811608699 __Host-1PLSID s.AU|s.youtube:g.a000FQlWJx8YKBkfXKL87fQbGF3JpT5Hbwh8eZoiMykjNSHK7t5iyESDtcxNl01z_grU5-iLaAACgYKASMSARcSFQHGX2MiwGse451k8E3rge7OaP0x7RoVAUF8yKoMdVoOUdowWciYofYzOdo70076
accounts.google.com FALSE / TRUE 1811608699 __Host-3PLSID s.AU|s.youtube:g.a000FQlWJx8YKBkfXKL87fQbGF3JpT5Hbwh8eZoiMykjNSHK7t5iircnfhpTPGylLjDhLVYiZwACgYKAWQSARcSFQHGX2MijUzOpXjHvzDQRH9fsjSWBxoVAUF8yKqQPm7xMNsej92wkxXsLt-F0076
accounts.google.com FALSE / TRUE 1811608699 ACCOUNT_CHOOSER AFx_qI6eEcJ138wPIhQbvxvzg7E7QansyOeSAgPFp_7P8z-4grF65qtnwIpahpTHAJgYQ-TcPRXgn3rrqjsFU7PU08-EFuPXPjXkt5GiSLbDpVZLkOik3S-sXyapaQwJNJ1-qbKhDWjRnJ2URmh0QfrijjS46vz7gA
.google.com TRUE / FALSE 1811608699 SID g.a000FQlWJ9HTNZd3fC_MXlmhnocrc_kvZzIQUDybgqFT4zRhCFeEE899ZwQvUnyvent34GbF9gACgYKAb0SARcSFQHGX2MifB95DvnTbUqsb9x2FdVlpRoVAUF8yKoPau3FDKQg5oBFLKbNYk-H0076
.google.com TRUE / TRUE 1811608699 __Secure-1PSID g.a000FQlWJ9HTNZd3fC_MXlmhnocrc_kvZzIQUDybgqFT4zRhCFeE606IyvXYBQ4_9E8x22Ug2wACgYKAcESARcSFQHGX2MiGarLvPp8hjN1YE3xitHl4hoVAUF8yKq0Fx2iLuTYOjEMCsypM1gu0076
.google.com TRUE / TRUE 1811608699 __Secure-3PSID g.a000FQlWJ9HTNZd3fC_MXlmhnocrc_kvZzIQUDybgqFT4zRhCFeEyH7r05Gp2ZMx9fUNaVP9IgACgYKAVASARcSFQHGX2MiXbAWyGXon1Gsx6y2o0BmcRoVAUF8yKrOeLjvg3tcvjTjohUoTwiB0076
.google.com TRUE / FALSE 1811608699 HSID AV25-mWBBHcNtHDlv
.google.com TRUE / TRUE 1811608699 SSID AdrQe4I8SRL-DI2aZ
.google.com TRUE / FALSE 1811608699 APISID t1kqgCO2tlTHLf4C/AlFgheIiPzNbXFL4a
.google.com TRUE / TRUE 1811608699 SAPISID Bb9nLT8mP2zXQc9L/AlEE0Jlo6wqqoUkgo
.google.com TRUE / TRUE 1811608699 __Secure-1PAPISID Bb9nLT8mP2zXQc9L/AlEE0Jlo6wqqoUkgo
.google.com TRUE / TRUE 1811608699 __Secure-3PAPISID Bb9nLT8mP2zXQc9L/AlEE0Jlo6wqqoUkgo
.google.com TRUE / FALSE 1811608699 SIDCC APD_SKGzigez89os7R8QruKLBsf8BQy4r90sin2bL2cAQhljJgF6Lj2XLpanonmS74w6hyQy
.google.com TRUE / TRUE 1811608699 __Secure-1PSIDCC APD_SKGye5Pn8p4v1j93akE43S7TDT8sPEAuGMMqVF6SMOhCtTy21Oi-C11pb4lnzBgBKdtZHw
.google.com TRUE / TRUE 1811608699 __Secure-3PSIDCC APD_SKFFX4m3IhKa88skzLA3FDeZ7NJZ-qPZX3LovLV_gCVQJR7qg86EEK96C8csCh2gWCp0
.google.com.au TRUE / FALSE 1811608700 HSID AZq_jbTBVmFUbhQnp
.google.com.au TRUE / TRUE 1811608700 SSID ANO5j7nQLctqs-PsM
.google.com.au TRUE / FALSE 1811608700 APISID t1kqgCO2tlTHLf4C/AlFgheIiPzNbXFL4a
.google.com.au TRUE / TRUE 1811608700 SAPISID Bb9nLT8mP2zXQc9L/AlEE0Jlo6wqqoUkgo
.google.com.au TRUE / TRUE 1811608700 __Secure-1PAPISID Bb9nLT8mP2zXQc9L/AlEE0Jlo6wqqoUkgo
.google.com.au TRUE / TRUE 1811608700 __Secure-3PAPISID Bb9nLT8mP2zXQc9L/AlEE0Jlo6wqqoUkgo
.google.com.au TRUE / TRUE 1811608700 NID CuwBCAESngEBM9Agl4affG-sqXnevScv9b6wV0Hd6AKQkowIxSDVcNrtW0_fpkXIHPnnFlgr9reXieTsuT2u9VYQT-icVmlyBDtpVD6wyWNIzXT281hXz-b3nryj4CqXTp9-6aH54F0wgRrLCSdtMMmOy-ecZ5BEg45tvYYl7nJDkNa8AyiAK9c1rO0qm8uCLw-4ekzq_X44HFT3NUHLL7_fGcUahygBMkUBcEpCz9DYQw2GgXuhBJcjHGaxDA-CcpNUKRkBAB2LyH5HhLEJk5b_1bbWfvl2bHVo-Z8GgBloNJN3zlimU6JM4vf16AE
.google.com.au TRUE / FALSE 1811608700 SID g.a000FQlWJ9HTNZd3fC_MXlmhnocrc_kvZzIQUDybgqFT4zRhCFeEE899ZwQvUnyvent34GbF9gACgYKAb0SARcSFQHGX2MifB95DvnTbUqsb9x2FdVlpRoVAUF8yKoPau3FDKQg5oBFLKbNYk-H0076
.google.com.au TRUE / TRUE 1811608700 __Secure-1PSID g.a000FQlWJ9HTNZd3fC_MXlmhnocrc_kvZzIQUDybgqFT4zRhCFeE606IyvXYBQ4_9E8x22Ug2wACgYKAcESARcSFQHGX2MiGarLvPp8hjN1YE3xitHl4hoVAUF8yKq0Fx2iLuTYOjEMCsypM1gu0076
.google.com.au TRUE / TRUE 1811608700 __Secure-3PSID g.a000FQlWJ9HTNZd3fC_MXlmhnocrc_kvZzIQUDybgqFT4zRhCFeEyH7r05Gp2ZMx9fUNaVP9IgACgYKAVASARcSFQHGX2MiXbAWyGXon1Gsx6y2o0BmcRoVAUF8yKrOeLjvg3tcvjTjohUoTwiB0076

BIN
data/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

4
data/models/CACHEDIR.TAG Normal file
View File

@@ -0,0 +1,4 @@
Signature: 8a477f597d28d172789f06886806bc55
# This file is a cache directory tag created by huggingface_hub.
# For information about cache directory tags, see:
# https://bford.info/cachedir/

View File

@@ -0,0 +1 @@
1

View File

@@ -0,0 +1 @@
models--Qdrant--bge-small-en-v1.5-onnx-Q/blobs/51f1bd0addd6e859e42c2c8021a5e5461385bb676a649f4b269aa445449f2431

View File

@@ -0,0 +1,31 @@
{
"_name_or_path": "BAAI/bge-small-en-v1.5",
"architectures": [
"BertModel"
],
"attention_probs_dropout_prob": 0.1,
"classifier_dropout": null,
"hidden_act": "gelu",
"hidden_dropout_prob": 0.1,
"hidden_size": 384,
"id2label": {
"0": "LABEL_0"
},
"initializer_range": 0.02,
"intermediate_size": 1536,
"label2id": {
"LABEL_0": 0
},
"layer_norm_eps": 1e-12,
"max_position_embeddings": 512,
"model_type": "bert",
"num_attention_heads": 12,
"num_hidden_layers": 12,
"pad_token_id": 0,
"position_embedding_type": "absolute",
"torch_dtype": "float32",
"transformers_version": "4.36.2",
"type_vocab_size": 2,
"use_cache": true,
"vocab_size": 30522
}

View File

@@ -0,0 +1 @@
../../blobs/aa/aaca296ced1def8c4e3df6cb215f78017b69427da86a9b725e77e8f68665ca8d

View File

@@ -0,0 +1,57 @@
{
"added_tokens_decoder": {
"0": {
"content": "[PAD]",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"100": {
"content": "[UNK]",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"101": {
"content": "[CLS]",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"102": {
"content": "[SEP]",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
},
"103": {
"content": "[MASK]",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false,
"special": true
}
},
"clean_up_tokenization_spaces": true,
"cls_token": "[CLS]",
"do_basic_tokenize": true,
"do_lower_case": true,
"mask_token": "[MASK]",
"model_max_length": 512,
"never_split": null,
"pad_token": "[PAD]",
"sep_token": "[SEP]",
"strip_accents": null,
"tokenize_chinese_chars": true,
"tokenizer_class": "BertTokenizer",
"unk_token": "[UNK]"
}

View File

@@ -0,0 +1,37 @@
{
"cls_token": {
"content": "[CLS]",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
"mask_token": {
"content": "[MASK]",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
"pad_token": {
"content": "[PAD]",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
"sep_token": {
"content": "[SEP]",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
},
"unk_token": {
"content": "[UNK]",
"lstrip": false,
"normalized": false,
"rstrip": false,
"single_word": false
}
}

View File

@@ -0,0 +1 @@
{"snapshots/aa8f8b060edb00e03bfdd08813a2949946c8ba55/config.json": {"size": 706, "blob_id": "0d7726d0cdccb62ee17c03bd1595cff07199b8f8"}, "snapshots/aa8f8b060edb00e03bfdd08813a2949946c8ba55/special_tokens_map.json": {"size": 695, "blob_id": "9bbecc17cabbcbd3112c14d6982b51403b264bfa"}, "snapshots/aa8f8b060edb00e03bfdd08813a2949946c8ba55/tokenizer_config.json": {"size": 1242, "blob_id": "75305659f7795d4549f0e23688b52fa20a32f925"}, "snapshots/aa8f8b060edb00e03bfdd08813a2949946c8ba55/tokenizer.json": {"size": 711396, "blob_id": "688882a79f44442ddc1f60d70334a7ff5df0fb47"}, "snapshots/aa8f8b060edb00e03bfdd08813a2949946c8ba55/model_optimized.onnx": {"size": 66465124, "blob_id": "94f6925f5e2ad78878198fa757195c25f74d6bc2"}}

View File

@@ -0,0 +1 @@
aa8f8b060edb00e03bfdd08813a2949946c8ba55

View File

@@ -0,0 +1 @@
../../blobs/0d7726d0cdccb62ee17c03bd1595cff07199b8f8

View File

@@ -0,0 +1 @@
../../blobs/51f1bd0addd6e859e42c2c8021a5e5461385bb676a649f4b269aa445449f2431

View File

@@ -0,0 +1 @@
../../blobs/9bbecc17cabbcbd3112c14d6982b51403b264bfa

View File

@@ -0,0 +1 @@
../../blobs/688882a79f44442ddc1f60d70334a7ff5df0fb47

View File

@@ -0,0 +1 @@
../../blobs/75305659f7795d4549f0e23688b52fa20a32f925

View File

@@ -0,0 +1,44 @@
{
"format_version": 1,
"files": {
".gitattributes": {
"size": 1519,
"blob_id": "a6344aac8c09253b3b630fb776ae94478aa0275b"
},
"README.md": {
"size": 900,
"blob_id": "7cb06d09a9326eb4f63654b255d4889895b90db9"
},
"config.json": {
"size": 706,
"blob_id": "0d7726d0cdccb62ee17c03bd1595cff07199b8f8"
},
"model_optimized.onnx": {
"size": 66465124,
"blob_id": "94f6925f5e2ad78878198fa757195c25f74d6bc2",
"lfs_sha256": "51f1bd0addd6e859e42c2c8021a5e5461385bb676a649f4b269aa445449f2431",
"lfs_size": 66465124,
"xet_hash": "aaca296ced1def8c4e3df6cb215f78017b69427da86a9b725e77e8f68665ca8d"
},
"ort_config.json": {
"size": 1272,
"blob_id": "ca62fa095648efcf2709136afcd942d98744eb3f"
},
"special_tokens_map.json": {
"size": 695,
"blob_id": "9bbecc17cabbcbd3112c14d6982b51403b264bfa"
},
"tokenizer.json": {
"size": 711396,
"blob_id": "688882a79f44442ddc1f60d70334a7ff5df0fb47"
},
"tokenizer_config.json": {
"size": 1242,
"blob_id": "75305659f7795d4549f0e23688b52fa20a32f925"
},
"vocab.txt": {
"size": 231508,
"blob_id": "fb140275c155a9c7c5a3b3e0e77a9e839594a938"
}
}
}

BIN
data/recommender.db Normal file

Binary file not shown.

10
docker-compose.yml Normal file
View File

@@ -0,0 +1,10 @@
services:
youtube-recommender:
build: .
container_name: youtube-recommender
restart: unless-stopped
env_file: .env
ports:
- "8888:8080"
volumes:
- ./data:/data # SQLite DB, model cache and cookies.txt live here

8
requirements.txt Normal file
View File

@@ -0,0 +1,8 @@
yt-dlp[default]>=2025.11.12
fastembed>=0.4
numpy>=1.26
requests>=2.31
fastapi>=0.110
uvicorn[standard]>=0.29
jinja2>=3.1
apscheduler>=3.10,<4