levelian-study / study_classifier.py
Letscooktechmodels's picture
Upload 3 files
9be1790 verified
Raw History Blame Contribute Delete
13.6 kB
"""
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",
}