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

156 lines
5.7 KiB
Python

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