Files
yt-recommender/app/db.py
2026-12-03 02:08:44 +11:00

128 lines
4.0 KiB
Python

"""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)