138 lines
5.4 KiB
Python
138 lines
5.4 KiB
Python
"""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))
|