Spaces:
Running
Running
File size: 17,675 Bytes
65b04d6 9e589ba 65b04d6 06803fa 65b04d6 4db2bb6 65b04d6 568a4d9 65b04d6 4db2bb6 65b04d6 4db2bb6 65b04d6 b27958e 65b04d6 4db2bb6 65b04d6 4db2bb6 65b04d6 4db2bb6 65b04d6 4db2bb6 65b04d6 4db2bb6 65b04d6 4db2bb6 65b04d6 4db2bb6 65b04d6 4db2bb6 65b04d6 4db2bb6 65b04d6 4db2bb6 65b04d6 4db2bb6 65b04d6 4db2bb6 65b04d6 4db2bb6 65b04d6 4db2bb6 65b04d6 4db2bb6 65b04d6 4db2bb6 65b04d6 4db2bb6 65b04d6 06803fa 65b04d6 06803fa 65b04d6 06803fa 65b04d6 06803fa 65b04d6 4db2bb6 06803fa 65b04d6 4db2bb6 06803fa 65b04d6 06803fa 65b04d6 06803fa 568a4d9 a4a3603 4db2bb6 a4a3603 4db2bb6 a4a3603 4db2bb6 a4a3603 568a4d9 4db2bb6 568a4d9 4db2bb6 568a4d9 4db2bb6 568a4d9 4db2bb6 568a4d9 | 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 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 | """
Topic Classifier โ maps dynamic LLM-extracted topics to predefined UI categories.
Usage:
from src.categorization.topic_classifier import classify_topic, get_primary_category
topics = ["Python", "Machine Learning", "Neural Networks"]
result = classify_topic(topics)
# => "Technology & AI"
Categories:
Technology & AI | Business & Finance | Education | Science
Productivity & Self-Growth | Health & Wellness | Sports & Fitness
Entertainment | History | Philosophy | Arts & Culture
"""
from typing import List, Set
from src.utils.logger import setup_logger
logger = setup_logger(__name__)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# PREDEFINED CATEGORIES
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
CATEGORIES = [
"Technology & AI",
"Business & Finance",
"Education",
"Science",
"Productivity & Self-Growth",
"Health & Wellness",
"Sports & Fitness",
"Entertainment",
"History",
"Philosophy",
"Arts & Culture",
]
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# KEYWORD โ CATEGORY MAPPING (English + Arabic)
# All keywords are stored lowercase for case-insensitive matching.
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
_KEYWORD_MAP: dict[str, str] = {}
def _register(category: str, keywords: list[str]):
"""Register a list of keywords for a category (lowercase)."""
for kw in keywords:
_KEYWORD_MAP[kw.lower()] = category
# โโ Technology & AI โโ
_register("Technology & AI", [
# English
"ai", "artificial intelligence", "machine learning", "deep learning",
"neural network", "neural networks", "nlp", "natural language processing",
"computer vision", "robotics", "automation", "algorithm", "algorithms",
"python", "javascript", "typescript", "java", "c++", "rust", "golang", "go",
"programming", "coding", "software", "software engineering", "web development",
"frontend", "backend", "full stack", "fullstack", "devops", "cloud",
"cloud computing", "aws", "azure", "gcp", "docker", "kubernetes",
"database", "sql", "nosql", "mongodb", "api", "rest api", "graphql",
"cybersecurity", "security", "hacking", "encryption", "blockchain",
"cryptocurrency", "bitcoin", "ethereum", "web3", "metaverse",
"data science", "data analysis", "data engineering", "big data",
"iot", "internet of things", "5g", "hardware", "semiconductor",
"gpu", "chip", "processor", "tech", "technology", "computing",
"linux", "git", "github", "open source", "framework", "react",
"vue", "angular", "node", "nodejs", "django", "flask", "fastapi",
"tensorflow", "pytorch", "llm", "large language model", "chatgpt",
"gpt", "copilot", "transformer", "diffusion model",
"generative ai", "prompt engineering", "fine tuning", "rag",
"mobile development", "android", "ios", "swift", "kotlin", "flutter", "dart",
# Arabic
"ุฐูุงุก ุงุตุทูุงุนู", "ุชุนูู
ุขูู", "ุชุนูู
ุนู
ูู", "ุจุฑู
ุฌุฉ", "ุชูููุฉ", "ุชูููููุฌูุง",
"ุฎูุงุฑุฒู
ูุฉ", "ุญุงุณูุจ", "ุดุจูุงุช ุนุตุจูุฉ", "ุจูุงูุงุช", "ุฃู
ู ุณูุจุฑุงูู",
"ุญูุณุจุฉ ุณุญุงุจูุฉ", "ุชุทููุฑ ุจุฑู
ุฌูุงุช", "ุชุทููุฑ ููุจ", "ููุงุนุฏ ุจูุงูุงุช",
])
# โโ Business & Finance โโ
_register("Business & Finance", [
# English
"business", "finance", "economics", "economy", "stock", "stocks",
"stock market", "trading", "investing", "investment", "real estate",
"entrepreneurship", "startup", "startups", "marketing", "digital marketing",
"seo", "branding", "sales", "revenue", "profit", "accounting",
"budgeting", "money", "wealth", "financial", "banking", "bank",
"fintech", "venture capital", "vc", "ipo", "merger", "acquisition",
"management", "leadership", "strategy", "e-commerce", "ecommerce",
"supply chain", "logistics", "consulting", "mba", "corporate",
"tax", "taxes", "inflation", "gdp", "interest rate", "forex",
"commodity", "commodities", "portfolio", "dividend", "bond", "bonds",
"freelancing", "freelance", "passive income", "side hustle",
# Arabic
"ุฃุนู
ุงู", "ุชุฌุงุฑุฉ", "ุงูุชุตุงุฏ", "ู
ุงููุฉ", "ุงุณุชุซู
ุงุฑ", "ุฃุณูู
", "ุจูุฑุตุฉ",
"ุชุณููู", "ุฑูุงุฏุฉ ุฃุนู
ุงู", "ู
ุดุฑูุน", "ุชู
ููู", "ู
ุญุงุณุจุฉ", "ุจูู", "ุนูุงุฑุงุช",
"ุฑุจุญ", "ุฏุฎู", "ู
ูุฒุงููุฉ",
])
# โโ Education โโ
_register("Education", [
# English
"education", "learning", "teaching", "school", "university", "college",
"academic", "study", "studying", "exam", "exams", "course",
"tutorial", "lecture", "scholarship", "degree", "phd", "thesis",
"curriculum", "pedagogy", "classroom", "student", "teacher",
"grammar", "language", "linguistics",
# Arabic
"ุชุนููู
", "ุชุนูู
", "ู
ุฏุฑุณุฉ", "ุฌุงู
ุนุฉ", "ุฏุฑุงุณุฉ", "ุงู
ุชุญุงู", "ู
ููุฌ",
"ู
ุญุงุถุฑุฉ", "ุทุงูุจ", "ู
ุนูู
",
])
# โโ Science โโ
_register("Science", [
# English
"science", "physics", "chemistry", "biology", "math", "mathematics",
"statistics", "calculus", "algebra", "geometry", "astronomy", "space",
"nasa", "quantum", "quantum physics", "quantum computing",
"neuroscience", "genetics", "evolution", "ecology", "geology",
"climate", "climate change", "environment", "engineering",
"mechanical engineering", "electrical engineering", "civil engineering",
"experiment", "laboratory", "lab", "hypothesis", "theory",
"research", "psychology", "sociology", "anthropology",
# Arabic
"ุนููู
", "ููุฒูุงุก", "ููู
ูุงุก", "ุฃุญูุงุก", "ุฑูุงุถูุงุช", "ุจุญุซ",
"ููุฏุณุฉ", "ููู", "ุจูุฆุฉ", "ุนูู
ููุณ",
])
# โโ Productivity & Self-Growth โโ
_register("Productivity & Self-Growth", [
# English
"productivity", "self improvement", "self-improvement", "self growth",
"self-growth", "personal development", "motivation", "discipline",
"habits", "habit", "time management", "goal setting", "goals",
"mindset", "focus", "concentration", "efficiency", "organization",
"planning", "journaling", "morning routine", "routine", "success",
"self help", "self-help", "life coaching", "coaching", "mentoring",
"mentor", "minimalism", "mindfulness",
"emotional intelligence", "communication skills", "public speaking",
"negotiation", "critical thinking", "problem solving", "creativity",
"decision making", "confidence", "resilience", "work-life balance",
"burnout", "career", "career development", "skill building",
# Arabic
"ุฅูุชุงุฌูุฉ", "ุชุทููุฑ ุฐุงุช", "ุชุญููุฒ", "ุนุงุฏุงุช", "ุฅุฏุงุฑุฉ ุงูููุช",
"ุฃูุฏุงู", "ุชุฑููุฒ", "ูุฌุงุญ", "ุชุฎุทูุท", "ุซูุฉ ุจุงูููุณ",
"ู
ูุงุฑุงุช", "ุชูููุฑ", "ุฅุจุฏุงุน",
])
# โโ Health & Wellness โโ
_register("Health & Wellness", [
# English
"health", "wellness", "mental health", "therapy", "depression",
"anxiety", "stress", "sleep", "yoga", "pilates", "meditation",
"diet", "nutrition", "calories", "protein", "vitamins",
"supplements", "weight loss", "fitness",
"medicine", "medical", "doctor", "hospital", "surgery", "disease",
"virus", "vaccine", "pandemic", "covid", "cancer", "diabetes",
"heart", "cardio", "physical therapy", "rehabilitation",
"first aid", "pharmacy", "drug", "prescription",
# Arabic
"ุตุญุฉ", "ุชุบุฐูุฉ", "ุญู
ูุฉ", "ุตุญุฉ ููุณูุฉ", "ุนูุงุฌ", "ุทุจ",
"ู
ุณุชุดูู", "ููู
", "ููุชุงู
ููุงุช", "ููุบุง",
])
# โโ Sports & Fitness โโ
_register("Sports & Fitness", [
# English
"sports", "football", "soccer", "basketball", "tennis", "baseball",
"cricket", "rugby", "boxing", "mma", "ufc", "wrestling",
"olympics", "world cup", "premier league", "nba", "nfl",
"exercise", "workout", "gym", "bodybuilding", "crossfit",
"running", "marathon", "swimming", "cycling", "hiking",
# Arabic
"ุฑูุงุถุฉ", "ุชู
ุงุฑูู", "ููุงูุฉ", "ูุฑุฉ ูุฏู
", "ุณุจุงุญุฉ",
])
# โโ Entertainment โโ
_register("Entertainment", [
# English
"entertainment", "movie", "movies", "film", "films", "cinema",
"tv", "television", "series", "netflix", "streaming", "anime",
"manga", "gaming", "video games", "esports", "twitch", "youtube",
"podcast", "music", "song", "album", "concert",
"celebrity", "comedy", "humor", "drama", "reality tv",
"social media", "tiktok", "instagram", "influencer", "content creator",
"vlog", "vlogging", "pop culture",
# Arabic
"ุชุฑููู", "ุฃููุงู
", "ุณููู
ุง", "ู
ุณูุณูุงุช", "ุฃูุนุงุจ", "ู
ูุณููู",
"ููู
ูุฏูุง", "ููุชููุจ",
])
# โโ History โโ
_register("History", [
# English
"history", "ancient", "medieval", "civilization", "empire",
"world war", "revolution", "archaeology", "historical",
"dynasty", "colonialism", "independence", "heritage",
# Arabic
"ุชุงุฑูุฎ", "ุญุถุงุฑุฉ", "ุฅู
ุจุฑุงุทูุฑูุฉ", "ุซูุฑุฉ", "ุขุซุงุฑ", "ุชุฑุงุซ",
])
# โโ Philosophy โโ
_register("Philosophy", [
# English
"philosophy", "ethics", "morality", "existentialism", "stoicism",
"metaphysics", "epistemology", "logic", "consciousness",
"free will", "determinism", "nihilism", "virtue",
# Arabic
"ููุณูุฉ", "ุฃุฎูุงู", "ูุฌูุฏูุฉ", "ู
ูุทู", "ูุนู",
])
# โโ Arts & Culture โโ
_register("Arts & Culture", [
# English
"art", "artist", "painting", "sculpture", "gallery", "museum",
"photography", "design", "graphic design", "illustration",
"architecture", "interior design", "fashion", "style", "beauty",
"makeup", "skincare", "travel", "tourism", "food", "cooking",
"recipe", "restaurant", "cuisine", "diy", "crafts",
"culture", "literature", "lifestyle", "luxury",
# Arabic
"ูู", "ุชุตู
ูู
", "ุชุตููุฑ", "ุณูุฑ", "ุทุจุฎ", "ุฃุฒูุงุก",
"ุฌู
ุงู", "ุซูุงูุฉ",
])
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# PUBLIC API
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def classify_topic(topics: List[str]) -> str:
"""
Map a list of dynamically extracted topics to a SINGLE predefined UI category.
Returns the single best-matching category (the first match in CATEGORIES order).
Falls back to "Education & Science" if no match is found.
Args:
topics: List of topic strings from the LLM (e.g. ["Python", "Deep Learning"]).
Returns:
A single category string.
Example:
>>> classify_topic(["Python", "Machine Learning", "Neural Networks"])
"Technology & AI"
>>> classify_topic(["Investing", "AI Stocks"])
"Business & Finance"
"""
matched: Set[str] = set()
for topic in topics:
topic_lower = topic.lower().strip()
# 1. Exact match
if topic_lower in _KEYWORD_MAP:
matched.add(_KEYWORD_MAP[topic_lower])
continue
# 2. Substring match โ check if any keyword appears inside the topic
for keyword, category in _KEYWORD_MAP.items():
if keyword in topic_lower or topic_lower in keyword:
matched.add(category)
break
if not matched:
return "Education"
# Return the first match in CATEGORIES order for consistency
for cat in CATEGORIES:
if cat in matched:
return cat
return "Education"
def classify_topics(topics: List[str]) -> List[str]:
"""Backward-compatible wrapper โ returns a single-element list."""
return [classify_topic(topics)]
def get_primary_category(topics: List[str]) -> str:
"""
Return the single best-matching category for the given topics.
Alias for classify_topic().
"""
return classify_topic(topics)
def classify_topic_groq(title: str, summary: str) -> str:
"""Classify video into one of the predefined categories using the Groq API.
Bypasses the local Zero-Shot classification model entirely.
"""
if not title and not summary:
return "Education"
try:
from src.utils.model_loader import get_groq_client
client = get_groq_client()
# Build prompt
categories_str = "\n".join(f"- {cat}" for cat in CATEGORIES)
prompt = (
"You are an expert content categorization AI.\n"
"Your task is to classify a video into exactly ONE of the following categories:\n"
f"{categories_str}\n\n"
f"Video Title: {title}\n"
f"Video Summary:\n{summary}\n\n"
"Instructions:\n"
"1. Reply with ONLY the exact name of the category from the list above.\n"
"2. Do not write any introduction, explanation, quote marks, punctuation, or extra text.\n"
"3. The output must be exactly one of the listed categories."
)
messages = [
{"role": "user", "content": prompt}
]
logger.info("๐ข Requesting category classification from Groq API...")
chat_completion = client.chat.completions.create(
model="llama-3.3-70b-versatile",
messages=messages,
max_tokens=30,
temperature=0.0,
)
reply = (chat_completion.choices[0].message.content or "").strip()
# Clean quotes if any
reply = reply.strip("'\"")
# Validate that the reply is in the CATEGORIES list
for cat in CATEGORIES:
if reply.lower() == cat.lower():
logger.info("๐ท๏ธ Groq classification: %s", cat)
return cat
# If not exact match, try substring matching
for cat in CATEGORIES:
if cat.lower() in reply.lower():
logger.info("๐ท๏ธ Groq classification (substring match): %s", cat)
return cat
logger.warning("โ ๏ธ Groq returned invalid category: %s โ falling back", reply)
return "Education"
except Exception as e:
logger.error("โ Groq category classification failed: %s", e, exc_info=True)
return "Education"
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# ZERO-SHOT CLASSIFICATION (mDeBERTa fallback)
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def classify_topic_zeroshot(text: str) -> str:
"""Classify free-form text into one of the predefined UI categories
using the mDeBERTa zero-shot classification pipeline.
Args:
text: Free-form text (transcript excerpt, note body, etc.)
Returns:
The best-matching category string from CATEGORIES.
"""
if not text or not text.strip():
return "Education"
try:
from src.utils.model_loader import get_classifier_pipeline
classifier = get_classifier_pipeline()
# Truncate to ~500 chars for speed on CPU
result = classifier(
text[:500],
candidate_labels=CATEGORIES,
multi_label=False,
)
best_label = result["labels"][0]
best_score = result["scores"][0]
logger.info(
"๐ท๏ธ Zero-shot classification: %s (score=%.3f)", best_label, best_score
)
return best_label
except Exception as e:
logger.warning("โ ๏ธ Zero-shot classification failed: %s โ falling back", e)
return "Education"
def classify_topic_hybrid(topics: List[str], text: str = "") -> str:
"""Best-of-both-worlds classifier.
1. First tries fast keyword matching via ``classify_topic(topics)``.
2. If the result is the generic fallback ("Education") AND
``text`` is provided, runs the mDeBERTa zero-shot classifier on
the text for a more nuanced result.
Args:
topics: List of topic strings (from the summarization pipeline).
text: Optional free-form text for zero-shot fallback.
Returns:
A single category string from CATEGORIES.
"""
keyword_result = classify_topic(topics)
# If keyword matching gave a confident answer, use it
if keyword_result != "Education":
return keyword_result
# If we have text, try zero-shot as a fallback
if text and text.strip():
return classify_topic_zeroshot(text)
return keyword_result
|