286 lines
11 KiB
Python
286 lines
11 KiB
Python
"""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
|