Spaces:
Sleeping
Sleeping
File size: 13,636 Bytes
9be1790 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 | """
Levelian YouTube Study Mode — Official Category & Semantic Classifier.
3-Tier Authoritative Resolution (cached 30 days in SQLite):
1. Official YouTube Data API v3 (YOUTUBE_API_KEY) -> exact categoryId (27=Education, 28=Science & Tech, 20=Gaming, etc.)
2. Public YouTube watch metadata ("category":"Education") when videoId is known ($0 cost)
3. Fast AI Semantic Classifier (Gemini / OpenAI / Groq text model, <300ms) over (title, channel, category).
"""
from __future__ import annotations
import json
import os
import re
import sqlite3
import threading
import time
import urllib.parse
import urllib.request
from pathlib import Path
YT_CATEGORY_NAMES: dict[str, str] = {
"1": "Film & Animation",
"2": "Autos & Vehicles",
"10": "Music",
"15": "Pets & Animals",
"17": "Sports",
"19": "Travel & Events",
"20": "Gaming",
"22": "People & Blogs",
"23": "Comedy",
"24": "Entertainment",
"25": "News & Politics",
"26": "Howto & Style",
"27": "Education",
"28": "Science & Technology",
"29": "Nonprofits & Activism",
}
STUDY_CATEGORY_IDS = {"27", "28"}
DISTRACTION_CATEGORY_IDS = {"1", "10", "17", "20", "23", "24"}
_STUDY_CACHE_LOCK = threading.Lock()
_VIDEO_ID_RE = re.compile(r"^[A-Za-z0-9_-]{11}$")
def init_study_cache(db_path: Path) -> None:
with _STUDY_CACHE_LOCK:
conn = sqlite3.connect(str(db_path), timeout=5)
try:
conn.execute("PRAGMA journal_mode=WAL;")
conn.execute(
"""
CREATE TABLE IF NOT EXISTS study_video_cache (
cache_key TEXT PRIMARY KEY,
verdict TEXT NOT NULL,
category TEXT NOT NULL,
category_id TEXT NOT NULL,
confidence REAL NOT NULL,
reason TEXT NOT NULL,
source TEXT NOT NULL,
fetched_at INTEGER NOT NULL
);
"""
)
conn.commit()
finally:
conn.close()
def _norm_key(video_id: str, title: str, channel: str) -> str:
if video_id and _VIDEO_ID_RE.match(video_id):
return f"vid::{video_id}"
t = re.sub(r"[^a-z0-9]+", " ", (title or "").lower()).strip()[:90]
c = re.sub(r"[^a-z0-9]+", " ", (channel or "").lower()).strip()[:50]
return f"tc::{t}::{c}"
def _cache_get(key: str, db_path: Path) -> dict | None:
now = int(time.time())
with _STUDY_CACHE_LOCK:
conn = sqlite3.connect(str(db_path), timeout=5)
try:
row = conn.execute(
"SELECT verdict, category, category_id, confidence, reason, source, fetched_at FROM study_video_cache WHERE cache_key = ?",
(key,),
).fetchone()
if not row or now - int(row[6]) > 30 * 24 * 3600:
return None
return {
"verdict": row[0],
"category": row[1],
"categoryId": row[2],
"confidence": float(row[3]),
"reason": row[4],
"source": row[5],
"cached": True,
}
finally:
conn.close()
def _cache_put(key: str, res: dict, db_path: Path) -> None:
now = int(time.time())
with _STUDY_CACHE_LOCK:
conn = sqlite3.connect(str(db_path), timeout=5)
try:
conn.execute(
"""
INSERT OR REPLACE INTO study_video_cache
(cache_key, verdict, category, category_id, confidence, reason, source, fetched_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""",
(
key,
str(res.get("verdict") or "UNCERTAIN"),
str(res.get("category") or "Unknown")[:60],
str(res.get("categoryId") or "")[:10],
float(res.get("confidence") or 0.5),
str(res.get("reason") or "")[:160],
str(res.get("source") or "classifier")[:40],
now,
),
)
conn.commit()
finally:
conn.close()
def fetch_youtube_api_category(video_id: str, title: str, channel: str, yt_key: str) -> dict | None:
"""Tier 1: Official YouTube Data API v3 lookup -> exact categoryId."""
if not yt_key:
return None
vid = video_id if (video_id and _VIDEO_ID_RE.match(video_id)) else ""
try:
if not vid and (title or channel):
q = urllib.parse.quote(f"{title} {channel}".strip()[:100])
s_url = f"https://www.googleapis.com/youtube/v3/search?part=snippet&type=video&maxResults=1&q={q}&key={urllib.parse.quote(yt_key)}"
with urllib.request.urlopen(urllib.request.Request(s_url), timeout=4.5) as resp:
items = json.loads(resp.read().decode("utf-8")).get("items") or []
if items:
vid = str((items[0].get("id") or {}).get("videoId") or "")
if not vid or not _VIDEO_ID_RE.match(vid):
return None
v_url = f"https://www.googleapis.com/youtube/v3/videos?part=snippet&id={vid}&fields=items(id,snippet(title,channelTitle,categoryId))&key={urllib.parse.quote(yt_key)}"
with urllib.request.urlopen(urllib.request.Request(v_url), timeout=4.5) as resp:
items = json.loads(resp.read().decode("utf-8")).get("items") or []
if not items:
return None
snip = items[0].get("snippet") or {}
cat_id = str(snip.get("categoryId") or "")
cat_name = YT_CATEGORY_NAMES.get(cat_id, "Unknown")
return {
"videoId": vid,
"title": str(snip.get("title") or title),
"channel": str(snip.get("channelTitle") or channel),
"categoryId": cat_id,
"category": cat_name,
"source": "youtube-data-api-v3",
}
except Exception:
return None
def fetch_public_youtube_category(video_id: str) -> dict | None:
"""Tier 2: Zero-cost public YouTube watch page category extractor when videoId is known."""
if not video_id or not _VIDEO_ID_RE.match(video_id):
return None
url = f"https://www.youtube.com/watch?v={video_id}"
req = urllib.request.Request(
url,
headers={
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
"Accept-Language": "en-US,en;q=0.9",
},
)
try:
with urllib.request.urlopen(req, timeout=5.5) as resp:
html = resp.read(1_500_000).decode("utf-8", errors="ignore")
m_cat = re.search(r'"category":"([^"\\]{2,40})"', html)
if not m_cat:
m_cat = re.search(r'itemprop="genre"\s+content="([^"]{2,40})"', html)
if not m_cat:
return None
cat_name = m_cat.group(1).replace("\\u0026", "&")
cat_id = next((k for k, v in YT_CATEGORY_NAMES.items() if v.lower() == cat_name.lower()), "")
return {
"videoId": video_id,
"categoryId": cat_id,
"category": cat_name,
"source": "youtube-public-metadata",
}
except Exception:
return None
def _call_fast_text_llm(title: str, channel: str, yt_category: str, env_reader) -> dict | None:
"""Tier 3: Ultra-fast (<300ms) text semantic classifier using Groq / Gemini / OpenAI."""
prompt = (
"Classify whether this YouTube video is EDUCATIONAL/STUDY (courses, lectures, tutorials, programming, math, science, "
"exam prep, documentaries, skills, languages, academic explanations) OR DISTRACTION (gaming, music videos, comedy, "
"pranks, vlogs, entertainment, movies, sports highlights, celebrity gossip, memes, clickbait).\n"
f"Title: {title[:180]}\nChannel: {channel[:80]}\nYouTube Category: {yt_category or 'Unknown'}\n"
'Return STRICT JSON ONLY: {"verdict":"STUDY|DISTRACTION","category":"Education|Science & Technology|Gaming|Music|Entertainment|Comedy|Sports|Lifestyle","confidence":0.95,"reason":"short 4-8 word reason"}'
)
# 1. Groq fast text model (openai/gpt-oss-20b has huge RPM/TPM and <200ms latency)
groq_key = env_reader("GROQ_API_KEY")
if groq_key:
for model_id in ("openai/gpt-oss-20b", "qwen/qwen3.8-27b"):
try:
payload = {
"model": model_id,
"temperature": 0.0,
"max_completion_tokens": 160,
"messages": [{"role": "user", "content": prompt}],
}
req = urllib.request.Request(
"https://api.groq.com/openai/v1/chat/completions",
data=json.dumps(payload).encode("utf-8"),
headers={"Authorization": f"Bearer {groq_key}", "Content-Type": "application/json", "User-Agent": "LevelianStudy/1.0"},
method="POST",
)
with urllib.request.urlopen(req, timeout=7.0) as resp:
raw = json.loads(resp.read().decode("utf-8"))
txt = (raw["choices"][0]["message"].get("content") or "").strip()
m_json = re.search(r"\{.*\}", txt, re.DOTALL)
if not m_json:
continue
parsed = json.loads(m_json.group(0))
v = str(parsed.get("verdict") or "").upper()
if v in ("STUDY", "DISTRACTION"):
return {
"verdict": v,
"category": str(parsed.get("category") or yt_category or "Unknown"),
"confidence": float(parsed.get("confidence") or 0.88),
"reason": str(parsed.get("reason") or f"Classified as {v}"),
"source": f"ai-study-{model_id.split('/')[-1]}",
}
except Exception:
continue
# 2. Gemini Flash fallback if GEMINI_API_KEY is configured
gem_key = env_reader("GEMINI_API_KEY")
if gem_key:
try:
url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key={urllib.parse.quote(gem_key)}"
payload = {
"contents": [{"parts": [{"text": prompt}]}],
"generationConfig": {"temperature": 0.0, "maxOutputTokens": 120, "responseMimeType": "application/json"},
}
req = urllib.request.Request(url, data=json.dumps(payload).encode("utf-8"), headers={"Content-Type": "application/json"}, method="POST")
with urllib.request.urlopen(req, timeout=6.0) as resp:
raw = json.loads(resp.read().decode("utf-8"))
txt = raw["candidates"][0]["content"]["parts"][0]["text"].strip()
parsed = json.loads(txt)
v = str(parsed.get("verdict") or "").upper()
if v in ("STUDY", "DISTRACTION"):
return {
"verdict": v,
"category": str(parsed.get("category") or yt_category or "Unknown"),
"confidence": float(parsed.get("confidence") or 0.9),
"reason": str(parsed.get("reason") or f"Classified as {v}"),
"source": "gemini-study-classifier",
}
except Exception:
pass
return None
def classify_youtube_study(
video_id: str,
title: str,
channel: str,
db_path: Path,
env_reader,
) -> dict:
"""Main entry: Cache -> YouTube Data API v3 -> Public YouTube Category -> Fast AI Classifier."""
init_study_cache(db_path)
key = _norm_key(video_id, title, channel)
cached = _cache_get(key, db_path)
if cached:
return cached
yt_meta = fetch_youtube_api_category(video_id, title, channel, env_reader("YOUTUBE_API_KEY"))
if not yt_meta and video_id:
yt_meta = fetch_public_youtube_category(video_id)
cat_id = str((yt_meta or {}).get("categoryId") or "")
cat_name = str((yt_meta or {}).get("category") or "")
eff_title = str((yt_meta or {}).get("title") or title or "").strip()
eff_channel = str((yt_meta or {}).get("channel") or channel or "").strip()
# Fast authoritative category decision when YouTube gives an unmistakable category
if cat_id in STUDY_CATEGORY_IDS:
res = {
"verdict": "STUDY",
"category": cat_name,
"categoryId": cat_id,
"confidence": 0.96,
"reason": f"YouTube category: {cat_name}",
"source": (yt_meta or {}).get("source", "youtube"),
}
_cache_put(key, res, db_path)
return res
if cat_id in DISTRACTION_CATEGORY_IDS:
res = {
"verdict": "DISTRACTION",
"category": cat_name,
"categoryId": cat_id,
"confidence": 0.96,
"reason": f"YouTube category: {cat_name}",
"source": (yt_meta or {}).get("source", "youtube"),
}
_cache_put(key, res, db_path)
return res
# Otherwise (ambiguous category like People & Blogs / Howto, or title+channel only) -> Fast AI Semantic Classifier
ai_res = _call_fast_text_llm(eff_title, eff_channel, cat_name, env_reader)
if ai_res:
ai_res["categoryId"] = cat_id
_cache_put(key, ai_res, db_path)
return ai_res
return {
"verdict": "UNCERTAIN",
"category": cat_name or "Unknown",
"categoryId": cat_id,
"confidence": 0.0,
"reason": "Insufficient metadata",
"source": "fallback",
}
|