Spaces:
Sleeping
Sleeping
File size: 17,360 Bytes
368277b da3a984 368277b da3a984 368277b 9685fdc 368277b b58981e 368277b |
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 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 |
from typing import List, Dict, Any
from smolagents import CodeAgent, InferenceClientModel, tool
import os
import json
from pathlib import Path
from datetime import datetime
AI_CATEGORIES = {
"research_breakthroughs": {
"name": "Research & Breakthroughs",
"description": "Novel papers, theoretical advances, new architectures, state-of-the-art results.",
"keywords": [
"paper",
"arxiv",
"research",
"breakthrough",
"novel",
"theory",
"architecture",
"state-of-the-art",
"sota",
"academic",
"study",
"findings",
"discovery",
],
},
"model_releases": {
"name": "Model Releases & Updates",
"description": "Launches of new large-language or vision models, version upgrades, open-source checkpoints.",
"keywords": [
"model",
"release",
"launch",
"gpt",
"llm",
"vision",
"checkpoint",
"open-source",
"version",
"update",
"huggingface",
"anthropic",
"openai",
"google",
"meta",
],
},
"tools_frameworks": {
"name": "Tools, Frameworks & Platforms",
"description": "SDKs, libraries, cloud services, developer toolkits, hosting/serving solutions.",
"keywords": [
"sdk",
"library",
"framework",
"platform",
"toolkit",
"api",
"cloud",
"hosting",
"serving",
"deployment",
"infrastructure",
"docker",
"kubernetes",
"aws",
"azure",
"gcp",
],
},
"applications_industry": {
"name": "Applications & Industry Use Cases",
"description": "AI in healthcare, finance, manufacturing, marketing, robotics—real-world deployments.",
"keywords": [
"healthcare",
"finance",
"manufacturing",
"marketing",
"robotics",
"deployment",
"use-case",
"industry",
"application",
"real-world",
"production",
"enterprise",
"business",
],
},
"regulation_ethics": {
"name": "Regulation, Ethics & Policy",
"description": "Government guidelines, ethical debates, bias/fairness studies, compliance news.",
"keywords": [
"regulation",
"ethics",
"policy",
"government",
"guidelines",
"bias",
"fairness",
"compliance",
"law",
"legal",
"governance",
"responsible",
"ai-safety",
"alignment",
],
},
"investment_funding": {
"name": "Investment, Funding & M&A",
"description": "Venture rounds, strategic investments, acquisitions, startup valuations.",
"keywords": [
"investment",
"funding",
"venture",
"acquisition",
"m&a",
"startup",
"valuation",
"series",
"round",
"investor",
"vc",
"private-equity",
"ipo",
"financing",
],
},
"benchmarks_leaderboards": {
"name": "Benchmarks & Leaderboards",
"description": "Performance comparisons, academic/industry challenges, leaderboard standings.",
"keywords": [
"benchmark",
"leaderboard",
"performance",
"comparison",
"evaluation",
"metric",
"score",
"ranking",
"competition",
"challenge",
"test",
"dataset",
],
},
"community_events": {
"name": "Community, Events & Education",
"description": "Conferences, workshops, hackathons, courses, tutorials, webinars.",
"keywords": [
"conference",
"workshop",
"hackathon",
"course",
"tutorial",
"webinar",
"education",
"community",
"event",
"meetup",
"training",
"learning",
"certification",
],
},
"security_privacy": {
"name": "Security, Privacy & Safety",
"description": "Adversarial attacks, defensive techniques, data-privacy breakthroughs, AI safety research.",
"keywords": [
"security",
"privacy",
"safety",
"adversarial",
"attack",
"defense",
"vulnerability",
"protection",
"encryption",
"data-privacy",
"gdpr",
"cybersecurity",
],
},
"market_trends": {
"name": "Market Trends & Analysis",
"description": "Adoption rates, market forecasts, analyst reports, surveys on AI usage.",
"keywords": [
"market",
"trends",
"analysis",
"forecast",
"survey",
"adoption",
"report",
"analyst",
"growth",
"statistics",
"usage",
"metrics",
"insights",
],
},
}
def get_cache_file_path():
"""Returns the path for the bookmark cache file."""
data_dir = Path("data")
data_dir.mkdir(exist_ok=True)
return str(data_dir / "ai_bookmarks_cache.json")
def load_cache():
"""Loads the bookmark cache from JSON file."""
cache_file = get_cache_file_path()
if os.path.exists(cache_file):
try:
with open(cache_file, "r", encoding="utf-8") as f:
return json.load(f)
except Exception as e:
print(f"Error loading cache: {e}")
return {"bookmarks": [], "last_updated": None}
def save_cache(cache_data):
"""Saves the bookmark cache to JSON file."""
cache_file = get_cache_file_path()
try:
with open(cache_file, "w", encoding="utf-8") as f:
json.dump(cache_data, f, indent=2, ensure_ascii=False)
return True
except Exception as e:
print(f"Error saving cache: {e}")
return False
def categorize_bookmark(bookmark: Dict[str, Any]) -> str:
"""
Categorizes a single bookmark based on title and URL using keyword matching.
Args:
bookmark: Dictionary containing bookmark data with title and url fields.
Returns:
String key of the most likely category, or 'uncategorized' if no match found.
"""
title = bookmark.get("title", "").lower()
url = bookmark.get("url", "").lower()
text_to_analyze = f"{title} {url}"
category_scores = {}
# Score each category based on keyword matches
for category_key, category_data in AI_CATEGORIES.items():
score = 0
keywords = category_data["keywords"]
for keyword in keywords:
# Count occurrences of each keyword
keyword_count = text_to_analyze.count(keyword.lower())
score += keyword_count
# Bonus for exact matches in title
if keyword.lower() in title:
score += 2
category_scores[category_key] = score
# Find the category with the highest score
if max(category_scores.values()) > 0:
return max(category_scores, key=category_scores.get)
else:
return "uncategorized"
@tool
def categorize_all_bookmarks() -> Dict[str, Any]:
"""
Categorizes all bookmarks in the cache and adds category information to each bookmark.
Updates the cache file with categorized bookmarks.
Returns:
Dictionary with categorization results and statistics.
"""
try:
cache = load_cache()
bookmarks = cache.get("bookmarks", [])
if not bookmarks:
return {"status": "error", "message": "No bookmarks found in cache"}
categorized_count = 0
category_stats = {}
# Initialize category stats
for category_key in AI_CATEGORIES.keys():
category_stats[category_key] = 0
category_stats["uncategorized"] = 0
# Categorize each bookmark
for bookmark in bookmarks:
category = categorize_bookmark(bookmark)
bookmark["category"] = category
bookmark["category_name"] = AI_CATEGORIES.get(category, {}).get("name", "Uncategorized")
category_stats[category] += 1
if category != "uncategorized":
categorized_count += 1
# Update cache with categorized bookmarks
cache["bookmarks"] = bookmarks
cache["last_categorized"] = datetime.now().isoformat()
cache["categorization_stats"] = category_stats
if save_cache(cache):
return {
"status": "success",
"message": f"Successfully categorized {categorized_count} out of {len(bookmarks)} bookmarks",
"total_bookmarks": len(bookmarks),
"categorized_bookmarks": categorized_count,
"uncategorized_bookmarks": category_stats["uncategorized"],
"category_breakdown": category_stats,
}
else:
return {"status": "error", "message": "Failed to save categorized bookmarks to cache"}
except Exception as e:
return {"status": "error", "message": f"Error categorizing bookmarks: {str(e)}"}
@tool
def get_bookmarks_by_category(category: str) -> List[Dict[str, Any]]:
"""
Gets all bookmarks belonging to a specific category.
Args:
category: Category key (e.g., 'research_breakthroughs') or category name (e.g., 'Research & Breakthroughs')
Returns:
List of bookmarks in the specified category.
"""
cache = load_cache()
bookmarks = cache.get("bookmarks", [])
if not bookmarks:
return []
# Check if category is a key or name
category_key = None
if category in AI_CATEGORIES:
category_key = category
else:
# Search by category name
for key, data in AI_CATEGORIES.items():
if data["name"].lower() == category.lower():
category_key = key
break
if not category_key and category.lower() != "uncategorized":
return []
# Filter bookmarks by category
filtered_bookmarks = []
for bookmark in bookmarks:
bookmark_category = bookmark.get("category", "uncategorized")
if (category_key and bookmark_category == category_key) or (
category.lower() == "uncategorized" and bookmark_category == "uncategorized"
):
filtered_bookmarks.append(bookmark)
return filtered_bookmarks
@tool
def get_category_statistics() -> Dict[str, Any]:
"""
Gets statistics about bookmark categorization.
Returns:
Dictionary with categorization statistics and category information.
"""
cache = load_cache()
bookmarks = cache.get("bookmarks", [])
if not bookmarks:
return {"error": "No bookmarks found in cache"}
# Calculate current category distribution
category_counts = {}
for category_key in AI_CATEGORIES.keys():
category_counts[category_key] = 0
category_counts["uncategorized"] = 0
categorized_bookmarks = 0
for bookmark in bookmarks:
category = bookmark.get("category", "uncategorized")
category_counts[category] += 1
if category != "uncategorized":
categorized_bookmarks += 1
# Prepare detailed category info
category_details = {}
for key, data in AI_CATEGORIES.items():
category_details[key] = {
"name": data["name"],
"description": data["description"],
"count": category_counts[key],
"percentage": round((category_counts[key] / len(bookmarks)) * 100, 2) if bookmarks else 0,
}
return {
"total_bookmarks": len(bookmarks),
"categorized_bookmarks": categorized_bookmarks,
"uncategorized_bookmarks": category_counts["uncategorized"],
"categorization_rate": round((categorized_bookmarks / len(bookmarks)) * 100, 2) if bookmarks else 0,
"last_categorized": cache.get("last_categorized"),
"category_details": category_details,
"available_categories": list(AI_CATEGORIES.keys()),
}
@tool
def recategorize_bookmark(bookmark_id: str, new_category: str) -> Dict[str, Any]:
"""
Manually recategorizes a specific bookmark.
Args:
bookmark_id: ID of the bookmark to recategorize
new_category: New category key (e.g., 'research_breakthroughs') or 'uncategorized'
Returns:
Dictionary with recategorization result.
"""
try:
cache = load_cache()
bookmarks = cache.get("bookmarks", [])
# Find the bookmark
bookmark_found = False
for bookmark in bookmarks:
if bookmark.get("id") == bookmark_id:
# Validate new category
if new_category == "uncategorized" or new_category in AI_CATEGORIES:
old_category = bookmark.get("category", "uncategorized")
bookmark["category"] = new_category
bookmark["category_name"] = AI_CATEGORIES.get(new_category, {}).get("name", "Uncategorized")
bookmark["manually_categorized"] = True
bookmark["recategorized_at"] = datetime.now().isoformat()
bookmark_found = True
# Save updated cache
if save_cache(cache):
return {
"status": "success",
"message": f"Bookmark '{bookmark.get('title', 'Unknown')}' recategorized from '{old_category}' to '{new_category}'",
"bookmark_title": bookmark.get("title"),
"old_category": old_category,
"new_category": new_category,
}
else:
return {"status": "error", "message": "Failed to save recategorized bookmark"}
else:
return {"status": "error", "message": f"Invalid category: {new_category}"}
if not bookmark_found:
return {"status": "error", "message": f"Bookmark with ID '{bookmark_id}' not found"}
except Exception as e:
return {"status": "error", "message": f"Error recategorizing bookmark: {str(e)}"}
@tool
def get_uncategorized_bookmarks() -> List[Dict[str, Any]]:
"""
Gets all bookmarks that are currently uncategorized.
Returns:
List of uncategorized bookmarks.
"""
cache = load_cache()
bookmarks = cache.get("bookmarks", [])
uncategorized = []
for bookmark in bookmarks:
if bookmark.get("category", "uncategorized") == "uncategorized":
uncategorized.append(bookmark)
return uncategorized
@tool
def search_bookmarks_by_category_and_query(category: str, query: str) -> List[Dict[str, Any]]:
"""
Search bookmarks within a specific category using a query.
Args:
category: Category key or name to search within
query: Search term to find in bookmark titles or URLs
Returns:
List of matching bookmarks within the specified category.
"""
# First get bookmarks by category
category_bookmarks = get_bookmarks_by_category(category)
if not category_bookmarks:
return []
# Then search within those bookmarks
query_lower = query.lower()
matching_bookmarks = []
for bookmark in category_bookmarks:
title = bookmark.get("title", "").lower()
url = bookmark.get("url", "").lower()
if query_lower in title or query_lower in url:
matching_bookmarks.append(bookmark)
return matching_bookmarks
# Instantiate the Categoriser CodeAgent
categoriser_agent = CodeAgent(
model=InferenceClientModel(
provider="nebius",
token=os.environ["HF_TOKEN"],
),
tools=[
categorize_all_bookmarks,
get_bookmarks_by_category,
get_category_statistics,
recategorize_bookmark,
get_uncategorized_bookmarks,
search_bookmarks_by_category_and_query,
],
name="categoriser_agent",
description="Specializes in categorizing AI news and bookmarks into 10 predefined categories: Research & Breakthroughs, Model Releases & Updates, Tools/Frameworks/Platforms, Applications & Industry Use Cases, Regulation/Ethics/Policy, Investment/Funding/M&A, Benchmarks & Leaderboards, Community/Events/Education, Security/Privacy/Safety, and Market Trends & Analysis. Uses keyword-based categorization and provides tools for managing and searching categorized content.",
max_steps=10,
additional_authorized_imports=["json", "datetime", "re", "pathlib"],
# Reduce verbosity
stream_outputs=False,
max_print_outputs_length=300,
)
|