~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
feat: Add Link Analytics and AI Domain Classification (Issue #648)
LearningCircuit6732acf99222
diff --git a/src/local_deep_research/domain_classifier/__init__.py b/src/local_deep_research/domain_classifier/__init__.pynew file mode 100644index 0000000000..176c2a67ee--- /dev/null+++ b/src/local_deep_research/domain_classifier/__init__.py@@ -0,0 +1,6 @@+"""Domain classifier module for categorizing domains using LLM."""++from .classifier import DomainClassifier+from .models import DomainClassification++__all__ = ["DomainClassifier", "DomainClassification"]diff --git a/src/local_deep_research/domain_classifier/classifier.py b/src/local_deep_research/domain_classifier/classifier.pynew file mode 100644index 0000000000..e369705c47--- /dev/null+++ b/src/local_deep_research/domain_classifier/classifier.py@@ -0,0 +1,484 @@+"""Domain classifier using LLM for categorization."""++import json+from typing import List, Dict, Optional+from loguru import logger+from sqlalchemy.orm import Session+from ..database.session_context import get_user_db_session+from ..database.models import ResearchResource+from .models import DomainClassification+from ..config.llm_config import get_llm+++# Predefined categories for domain classification+DOMAIN_CATEGORIES = {+ "Academic & Research": [+ "University/Education",+ "Scientific Journal",+ "Research Institution",+ "Academic Database",+ ],+ "News & Media": [+ "General News",+ "Tech News",+ "Business News",+ "Entertainment News",+ "Local/Regional News",+ ],+ "Reference & Documentation": [+ "Encyclopedia",+ "Technical Documentation",+ "API Documentation",+ "Tutorial/Guide",+ "Dictionary/Glossary",+ ],+ "Social & Community": [+ "Social Network",+ "Forum/Discussion",+ "Q&A Platform",+ "Blog Platform",+ "Personal Blog",+ ],+ "Business & Commerce": [+ "E-commerce",+ "Corporate Website",+ "B2B Platform",+ "Financial Service",+ "Marketing/Advertising",+ ],+ "Technology": [+ "Software Development",+ "Cloud Service",+ "Open Source Project",+ "Tech Company",+ "Developer Tools",+ ],+ "Government & Organization": [+ "Government Agency",+ "Non-profit",+ "International Organization",+ "Think Tank",+ "Industry Association",+ ],+ "Entertainment & Lifestyle": [+ "Streaming Service",+ "Gaming",+ "Sports",+ "Arts & Culture",+ "Travel & Tourism",+ ],+ "Professional & Industry": [+ "Healthcare",+ "Legal",+ "Real Estate",+ "Manufacturing",+ "Energy & Utilities",+ ],+ "Other": ["Personal Website", "Miscellaneous", "Unknown"],+}+++class DomainClassifier:+ """Classify domains using LLM with predefined categories."""++ def __init__(self, username: str, settings_snapshot: dict = None):+ """Initialize the domain classifier.++ Args:+ username: Username for database session+ settings_snapshot: Settings snapshot for LLM configuration+ """+ self.username = username+ self.settings_snapshot = settings_snapshot+ self.llm = None++ def _get_llm(self):+ """Get or initialize LLM instance."""+ if self.llm is None:+ self.llm = get_llm(settings_snapshot=self.settings_snapshot)+ return self.llm++ def _get_domain_samples(+ self, domain: str, session: Session, limit: int = 5+ ) -> List[Dict]:+ """Get sample resources from a domain.++ Args:+ domain: Domain to get samples for+ session: Database session+ limit: Maximum number of samples++ Returns:+ List of resource samples+ """+ resources = (+ session.query(ResearchResource)+ .filter(ResearchResource.url.like(f"%{domain}%"))+ .limit(limit)+ .all()+ )++ samples = []+ for resource in resources:+ samples.append(+ {+ "title": resource.title or "Untitled",+ "url": resource.url,+ "preview": resource.content_preview[:200]+ if resource.content_preview+ else None,+ }+ )++ return samples++ def _build_classification_prompt(+ self, domain: str, samples: List[Dict]+ ) -> str:+ """Build prompt for LLM classification.++ Args:+ domain: Domain to classify+ samples: Sample resources from the domain++ Returns:+ Formatted prompt string+ """+ # Format categories for prompt+ categories_text = []+ for main_cat, subcats in DOMAIN_CATEGORIES.items():+ subcats_text = ", ".join(subcats)+ categories_text.append(f"{main_cat}: {subcats_text}")++ # Format samples+ samples_text = []+ for i, sample in enumerate(samples[:5], 1):+ samples_text.append(f"{i}. Title: {sample['title']}")+ if sample.get("preview"):+ samples_text.append(f" Preview: {sample['preview'][:100]}...")++ prompt = f"""Classify the following domain into one of the predefined categories.++Domain: {domain}++Sample content from this domain:+{chr(10).join(samples_text) if samples_text else "No samples available"}++Available Categories:+{chr(10).join(categories_text)}++Respond with a JSON object containing:+- "category": The main category (e.g., "News & Media")+- "subcategory": The specific subcategory (e.g., "Tech News")+- "confidence": A confidence score between 0 and 1+- "reasoning": A brief explanation (max 100 words) of why this classification was chosen++Focus on accuracy. If uncertain, use "Other" category with "Unknown" subcategory.++JSON Response:"""++ return prompt++ def classify_domain(+ self, domain: str, force_update: bool = False+ ) -> Optional[DomainClassification]:+ """Classify a single domain using LLM.++ Args:+ domain: Domain to classify+ force_update: If True, reclassify even if already exists++ Returns:+ DomainClassification object or None if failed+ """+ try:+ with get_user_db_session(self.username) as session:+ # Check if already classified+ existing = (+ session.query(DomainClassification)+ .filter_by(domain=domain)+ .first()+ )++ if existing and not force_update:+ logger.info(+ f"Domain {domain} already classified as {existing.category}"+ )+ return existing++ # Get sample resources+ samples = self._get_domain_samples(domain, session)++ # Build prompt and get classification+ prompt = self._build_classification_prompt(domain, samples)+ llm = self._get_llm()++ response = llm.invoke(prompt)++ # Extract content from response+ if hasattr(response, "content"):+ response_text = response.content+ else:+ response_text = str(response)++ # Parse JSON response+ try:+ result = json.loads(response_text)+ except json.JSONDecodeError:+ # Try to extract JSON from response+ import re++ json_match = re.search(r"\{.*\}", response_text, re.DOTALL)+ if json_match:+ result = json.loads(json_match.group())+ else:+ raise ValueError(+ "Could not parse JSON from LLM response"+ )++ # Create or update classification+ if existing:+ existing.category = result.get("category", "Other")+ existing.subcategory = result.get("subcategory", "Unknown")+ existing.confidence = float(result.get("confidence", 0.5))+ existing.reasoning = result.get("reasoning", "")+ existing.sample_titles = json.dumps(+ [s["title"] for s in samples]+ )+ existing.sample_count = len(samples)+ classification = existing+ else:+ classification = DomainClassification(+ domain=domain,+ category=result.get("category", "Other"),+ subcategory=result.get("subcategory", "Unknown"),+ confidence=float(result.get("confidence", 0.5)),+ reasoning=result.get("reasoning", ""),+ sample_titles=json.dumps([s["title"] for s in samples]),+ sample_count=len(samples),+ )+ session.add(classification)++ session.commit()+ logger.info(+ f"Classified {domain} as {classification.category}/{classification.subcategory} with confidence {classification.confidence}"+ )+ return classification++ except Exception:+ logger.exception(f"Error classifying domain {domain}")+ return None++ def classify_all_domains(+ self, force_update: bool = False, progress_callback=None+ ) -> Dict:+ """Classify all unique domains in the database.++ Args:+ force_update: If True, reclassify all domains+ progress_callback: Optional callback function for progress updates++ Returns:+ Dictionary with classification results+ """+ results = {+ "total": 0,+ "classified": 0,+ "failed": 0,+ "skipped": 0,+ "domains": [],+ }++ try:+ with get_user_db_session(self.username) as session:+ # Get all unique domains+ from urllib.parse import urlparse++ resources = session.query(ResearchResource.url).distinct().all()+ domains = set()++ for (url,) in resources:+ if url:+ try:+ parsed = urlparse(url)+ domain = parsed.netloc.lower()+ if domain.startswith("www."):+ domain = domain[4:]+ if domain:+ domains.add(domain)+ except:+ continue++ results["total"] = len(domains)+ logger.info(+ f"Found {results['total']} unique domains to process"+ )++ # Classify each domain ONE BY ONE+ for i, domain in enumerate(sorted(domains), 1):+ logger.info(+ f"Processing domain {i}/{results['total']}: {domain}"+ )++ if progress_callback:+ progress_callback(+ {+ "current": i,+ "total": results["total"],+ "domain": domain,+ "percentage": (i / results["total"]) * 100,+ }+ )++ try:+ # Check if already classified+ if not force_update:+ existing = (+ session.query(DomainClassification)+ .filter_by(domain=domain)+ .first()+ )+ if existing:+ results["skipped"] += 1+ results["domains"].append(+ {+ "domain": domain,+ "status": "skipped",+ "category": existing.category,+ "subcategory": existing.subcategory,+ }+ )+ logger.info(+ f"Domain {domain} already classified, skipping"+ )+ continue++ # Classify this single domain+ classification = self.classify_domain(+ domain, force_update+ )++ if classification:+ results["classified"] += 1+ results["domains"].append(+ {+ "domain": domain,+ "status": "classified",+ "category": classification.category,+ "subcategory": classification.subcategory,+ "confidence": classification.confidence,+ }+ )+ logger.info(+ f"Successfully classified {domain} as {classification.category}"+ )+ else:+ results["failed"] += 1+ results["domains"].append(+ {"domain": domain, "status": "failed"}+ )+ logger.warning(+ f"Failed to classify domain {domain}"+ )++ except Exception as e:+ logger.exception(f"Error classifying domain {domain}")+ results["failed"] += 1+ results["domains"].append(+ {+ "domain": domain,+ "status": "failed",+ "error": str(e),+ }+ )++ logger.info(+ f"Classification complete: {results['classified']} classified, {results['skipped']} skipped, {results['failed']} failed"+ )+ return results++ except Exception as e:+ logger.exception("Error in classify_all_domains")+ results["error"] = str(e)+ return results++ def get_classification(self, domain: str) -> Optional[DomainClassification]:+ """Get existing classification for a domain.++ Args:+ domain: Domain to look up++ Returns:+ DomainClassification object or None if not found+ """+ try:+ with get_user_db_session(self.username) as session:+ return (+ session.query(DomainClassification)+ .filter_by(domain=domain)+ .first()+ )+ except Exception:+ logger.exception(f"Error getting classification for {domain}")+ return None++ def get_all_classifications(self) -> List[DomainClassification]:+ """Get all domain classifications.++ Returns:+ List of all DomainClassification objects+ """+ try:+ with get_user_db_session(self.username) as session:+ return (+ session.query(DomainClassification)+ .order_by(+ DomainClassification.category,+ DomainClassification.domain,+ )+ .all()+ )+ except Exception:+ logger.exception("Error getting all classifications")+ return []++ def get_categories_summary(self) -> Dict:+ """Get summary of domain classifications by category.++ Returns:+ Dictionary with category counts and domains+ """+ try:+ with get_user_db_session(self.username) as session:+ classifications = session.query(DomainClassification).all()++ summary = {}+ for classification in classifications:+ cat = classification.category+ if cat not in summary:+ summary[cat] = {+ "count": 0,+ "domains": [],+ "subcategories": {},+ }++ summary[cat]["count"] += 1+ summary[cat]["domains"].append(+ {+ "domain": classification.domain,+ "subcategory": classification.subcategory,+ "confidence": classification.confidence,+ }+ )++ subcat = classification.subcategory+ if subcat:+ if subcat not in summary[cat]["subcategories"]:+ summary[cat]["subcategories"][subcat] = 0+ summary[cat]["subcategories"][subcat] += 1++ return summary++ except Exception:+ logger.exception("Error getting categories summary")+ return {}diff --git a/src/local_deep_research/domain_classifier/models.py b/src/local_deep_research/domain_classifier/models.pynew file mode 100644index 0000000000..bff8b2d446--- /dev/null+++ b/src/local_deep_research/domain_classifier/models.py@@ -0,0 +1,46 @@+"""Database models for domain classification."""++from sqlalchemy import Column, String, DateTime, Text, Float, Integer, Index+from sqlalchemy.sql import func+from ..database.models import Base+++class DomainClassification(Base):+ """Store domain classifications generated by LLM."""++ __tablename__ = "domain_classifications"++ id = Column(Integer, primary_key=True, autoincrement=True)+ domain = Column(String(255), unique=True, nullable=False, index=True)+ category = Column(String(100), nullable=False)+ subcategory = Column(String(100))+ confidence = Column(Float, default=0.0)+ reasoning = Column(Text) # Store LLM's reasoning for the classification+ sample_titles = Column(Text) # JSON array of sample titles from this domain+ sample_count = Column(+ Integer, default=0+ ) # Number of resources used for classification+ created_at = Column(DateTime(timezone=True), server_default=func.now())+ updated_at = Column(DateTime(timezone=True), onupdate=func.now())++ # Create index for faster lookups+ __table_args__ = (Index("idx_domain_category", "domain", "category"),)++ def to_dict(self):+ """Convert to dictionary for JSON serialization."""+ return {+ "id": self.id,+ "domain": self.domain,+ "category": self.category,+ "subcategory": self.subcategory,+ "confidence": self.confidence,+ "reasoning": self.reasoning,+ "sample_titles": self.sample_titles,+ "sample_count": self.sample_count,+ "created_at": self.created_at.isoformat()+ if self.created_at+ else None,+ "updated_at": self.updated_at.isoformat()+ if self.updated_at+ else None,+ }diff --git a/src/local_deep_research/web/routes/metrics_routes.py b/src/local_deep_research/web/routes/metrics_routes.pyindex c11d551d5a..67555a2380 100644--- a/src/local_deep_research/web/routes/metrics_routes.py+++ b/src/local_deep_research/web/routes/metrics_routes.py@@ -11,9 +11,11 @@ from ...database.models import (RateLimitEstimate,Research,ResearchRating,+ ResearchResource,ResearchStrategy,TokenUsage,)+from ...domain_classifier import DomainClassifier, DomainClassificationfrom ...database.session_context import get_user_db_sessionfrom ...metrics import TokenCounterfrom ...metrics.query_utils import get_time_filter_condition@@ -26,6 +28,266 @@ from ..utils.templates import render_template_with_defaultsmetrics_bp = Blueprint("metrics", __name__, url_prefix="/metrics")+def classify_domain_smart(domain, title=None, content_preview=None):+ """+ Smart domain classification that uses multiple signals.+ Returns a dict with primary category and confidence scores for each category.+ """+ domain_lower = domain.lower()++ # Initialize scores for each category+ scores = {+ "academic": 0,+ "news": 0,+ "documentation": 0,+ "forum": 0,+ "blog": 0,+ "government": 0,+ "commercial": 0,+ "social": 0,+ "code": 0,+ "general": 0,+ }++ # Academic indicators+ academic_domains = {+ ".edu": 30,+ "arxiv.org": 50,+ "scholar.google": 40,+ "pubmed": 45,+ "jstor.org": 45,+ "sciencedirect": 40,+ "springer": 35,+ "nature.com": 40,+ "ieee.org": 40,+ "acm.org": 40,+ "researchgate": 35,+ "academia.edu": 35,+ "ncbi.nlm": 45,+ "plos.org": 40,+ "science.org": 40,+ ".ac.": 25,+ "university": 20,+ "journal": 15,+ "research": 10,+ }++ # News indicators+ news_domains = {+ "cnn.": 40,+ "bbc.": 40,+ "reuters": 40,+ "nytimes": 40,+ "wsj.": 40,+ "guardian": 35,+ "bloomberg": 35,+ "forbes": 30,+ "techcrunch": 30,+ "theverge": 30,+ "wired": 30,+ "arstechnica": 30,+ "news": 20,+ "daily": 15,+ "times": 10,+ "post": 10,+ "herald": 10,+ }++ # Documentation/Reference indicators+ doc_domains = {+ "wikipedia": 45,+ "docs.": 40,+ "documentation": 40,+ "readthedocs": 40,+ "gitbook": 35,+ "developer": 30,+ "api.": 30,+ "reference": 25,+ "guide": 20,+ "tutorial": 20,+ "manual": 20,+ "w3.org": 35,+ "mdn.mozilla": 40,+ "help.": 25,+ "support.": 20,+ }++ # Forum/Community indicators+ forum_domains = {+ "stackoverflow": 50,+ "reddit": 45,+ "stackexchange": 45,+ "quora": 40,+ "discourse": 35,+ "forum": 30,+ "community": 25,+ "discuss": 25,+ "answers": 20,+ "askubuntu": 40,+ "superuser": 40,+ }++ # Blog/Personal indicators+ blog_domains = {+ "medium.com": 40,+ "wordpress": 35,+ "blogspot": 35,+ "substack": 35,+ "dev.to": 35,+ "hashnode": 30,+ "ghost.io": 30,+ "blog": 25,+ "personal": 20,+ "portfolio": 15,+ }++ # Government/Official indicators+ gov_domains = {+ ".gov": 50,+ ".mil": 45,+ ".int": 40,+ "europa.eu": 35,+ "who.int": 40,+ "un.org": 40,+ "worldbank": 35,+ "imf.org": 35,+ ".gc.ca": 40,+ ".gov.uk": 40,+ ".gov.au": 40,+ }++ # Code/Repository indicators+ code_domains = {+ "github.com": 50,+ "gitlab": 45,+ "bitbucket": 45,+ "sourceforge": 40,+ "npm": 35,+ "pypi.org": 35,+ "crates.io": 35,+ "rubygems": 35,+ "packagist": 30,+ "nuget": 30,+ "maven": 30,+ }++ # Social Media indicators+ social_domains = {+ "twitter": 45,+ "x.com": 45,+ "facebook": 45,+ "linkedin": 45,+ "instagram": 40,+ "youtube": 40,+ "tiktok": 35,+ "pinterest": 35,+ "tumblr": 30,+ "discord": 30,+ "slack": 30,+ }++ # Commercial/Business indicators+ commercial_domains = {+ "amazon": 40,+ "ebay": 35,+ "shopify": 35,+ "store": 25,+ "shop": 25,+ "buy": 20,+ "sale": 20,+ ".com": 5,+ "product": 15,+ "service": 15,+ "pricing": 20,+ }++ # Calculate scores based on domain patterns+ domain_groups = [+ (academic_domains, "academic"),+ (news_domains, "news"),+ (doc_domains, "documentation"),+ (forum_domains, "forum"),+ (blog_domains, "blog"),+ (gov_domains, "government"),+ (code_domains, "code"),+ (social_domains, "social"),+ (commercial_domains, "commercial"),+ ]++ for patterns, category in domain_groups:+ for pattern, weight in patterns.items():+ if pattern in domain_lower:+ scores[category] += weight++ # Boost scores based on title/content if available+ if title:+ title_lower = title.lower()+ if any(+ word in title_lower+ for word in ["paper", "study", "analysis", "research"]+ ):+ scores["academic"] += 15+ if any(+ word in title_lower+ for word in ["breaking", "latest", "update", "report"]+ ):+ scores["news"] += 15+ if any(+ word in title_lower+ for word in ["how to", "guide", "tutorial", "documentation"]+ ):+ scores["documentation"] += 15++ # Find primary category+ max_score = max(scores.values())+ if max_score == 0:+ primary_category = "general"+ else:+ primary_category = max(scores, key=scores.get)++ # Normalize scores to percentages+ total_score = sum(scores.values()) or 1+ confidence_scores = {+ k: round(v / total_score * 100, 1) for k, v in scores.items()+ }++ # Create detailed categorization+ result = {+ "primary": primary_category,+ "confidence": confidence_scores,+ "top_categories": sorted(+ [+ (cat, score)+ for cat, score in confidence_scores.items()+ if score > 10+ ],+ key=lambda x: x[1],+ reverse=True,+ )[:3],+ }++ # Simplified category for backward compatibility+ # Map to our original 4 categories+ category_mapping = {+ "academic": "academic",+ "news": "news",+ "documentation": "reference",+ "government": "reference",+ "forum": "reference",+ "blog": "general",+ "code": "reference",+ "social": "general",+ "commercial": "general",+ "general": "general",+ }++ result["simple_category"] = category_mapping.get(+ primary_category, "general"+ )++ return result++def get_rating_analytics(period="30d", research_mode="all", username=None):"""Get rating analytics for the specified period and research mode."""try:@@ -125,6 +387,280 @@ def get_rating_analytics(period="30d", research_mode="all", username=None):}+def get_link_analytics(period="30d", username=None):+ """Get link analytics from research resources."""+ try:+ if not username:+ username = flask_session.get("username")++ if not username:+ return {+ "link_analytics": {+ "top_domains": [],+ "total_unique_domains": 0,+ "avg_links_per_research": 0,+ "domain_distribution": {},+ "source_type_analysis": {},+ "academic_vs_general": {},+ "total_links": 0,+ "error": "No user session",+ }+ }++ # Calculate date range+ days_map = {"7d": 7, "30d": 30, "90d": 90, "365d": 365, "all": None}+ days = days_map.get(period, 30)++ with get_user_db_session(username) as session:+ # Base query+ query = session.query(ResearchResource)++ # Apply time filter+ if days:+ cutoff_date = datetime.now(UTC) - timedelta(days=days)+ query = query.filter(+ ResearchResource.created_at >= cutoff_date.isoformat()+ )++ # Get all resources+ resources = query.all()++ if not resources:+ return {+ "link_analytics": {+ "top_domains": [],+ "total_unique_domains": 0,+ "avg_links_per_research": 0,+ "domain_distribution": {},+ "source_type_analysis": {},+ "academic_vs_general": {},+ "total_links": 0,+ }+ }++ # Extract domains from URLs+ from urllib.parse import urlparse++ domain_counts = {}+ domain_researches = {} # Track which researches used each domain+ source_types = {}+ academic_sources = 0+ general_sources = 0+ news_sources = 0+ reference_sources = 0+ temporal_data = {} # Track links over time+ content_types = {} # Track content types+ domain_connections = {} # Track domain co-occurrences+ quality_metrics = {+ "with_title": 0,+ "with_preview": 0,+ "with_both": 0,+ "total": 0,+ }++ for resource in resources:+ if resource.url:+ try:+ parsed = urlparse(resource.url)+ domain = parsed.netloc.lower()+ # Remove www. prefix+ if domain.startswith("www."):+ domain = domain[4:]++ # Count domains+ domain_counts[domain] = domain_counts.get(domain, 0) + 1++ # Track research IDs for each domain+ if domain not in domain_researches:+ domain_researches[domain] = set()+ domain_researches[domain].add(resource.research_id)++ # Track temporal data (daily counts)+ if resource.created_at:+ date_str = resource.created_at[+ :10+ ] # Extract YYYY-MM-DD+ temporal_data[date_str] = (+ temporal_data.get(date_str, 0) + 1+ )++ # Categorize sources with smart classification+ classification = classify_domain_smart(+ domain, resource.title, resource.content_preview+ )+ simple_cat = classification["simple_category"]++ if simple_cat == "academic":+ academic_sources += 1+ elif simple_cat == "news":+ news_sources += 1+ elif simple_cat == "reference":+ reference_sources += 1+ else:+ general_sources += 1++ # Track source type from metadata if available+ if resource.source_type:+ source_types[resource.source_type] = (+ source_types.get(resource.source_type, 0) + 1+ )++ # Track quality metrics+ quality_metrics["total"] += 1+ if resource.title:+ quality_metrics["with_title"] += 1+ if resource.content_preview:+ quality_metrics["with_preview"] += 1+ if resource.title and resource.content_preview:+ quality_metrics["with_both"] += 1++ # Track content type from classification+ if "primary" in classification:+ primary_cat = classification["primary"]+ content_types[primary_cat] = (+ content_types.get(primary_cat, 0) + 1+ )++ # Track domain co-occurrences for network visualization+ research_id = resource.research_id+ if research_id not in domain_connections:+ domain_connections[research_id] = []+ domain_connections[research_id].append(domain)++ except Exception as e:+ logger.warning(f"Error parsing URL {resource.url}: {e}")++ # Sort domains by count and get top 10+ sorted_domains = sorted(+ domain_counts.items(), key=lambda x: x[1], reverse=True+ )+ top_10_domains = sorted_domains[:10]++ # Calculate domain distribution (top domains vs others)+ top_10_count = sum(count for _, count in top_10_domains)+ others_count = len(resources) - top_10_count++ # Get unique research IDs to calculate average+ unique_research_ids = set(r.research_id for r in resources)+ avg_links = (+ len(resources) / len(unique_research_ids)+ if unique_research_ids+ else 0+ )++ # Prepare temporal trend data (sorted by date)+ temporal_trend = sorted(+ [+ {"date": date, "count": count}+ for date, count in temporal_data.items()+ ],+ key=lambda x: x["date"],+ )++ # Get most recent research for each top domain and classifications+ domain_recent_research = {}+ domain_classifications = {}+ with get_user_db_session(username) as session:+ from ...database.models import Research++ # Get classifications for all domains+ all_classifications = session.query(DomainClassification).all()+ for classification in all_classifications:+ domain_classifications[classification.domain] = {+ "category": classification.category,+ "subcategory": classification.subcategory,+ "confidence": classification.confidence,+ }++ for domain, _ in top_10_domains:+ if domain in domain_researches:+ research_ids = list(domain_researches[domain])[+ :3+ ] # Get up to 3 recent researches+ researches = (+ session.query(Research)+ .filter(Research.id.in_(research_ids))+ .all()+ )+ domain_recent_research[domain] = [+ {+ "id": r.id,+ "query": r.query[:50]+ if r.query+ else "Research",+ }+ for r in researches+ ]++ return {+ "link_analytics": {+ "top_domains": [+ {+ "domain": domain,+ "count": count,+ "percentage": round(+ count / len(resources) * 100, 1+ ),+ "research_count": len(+ domain_researches.get(domain, set())+ ),+ "recent_researches": domain_recent_research.get(+ domain, []+ ),+ "classification": domain_classifications.get(+ domain, None+ ),+ }+ for domain, count in top_10_domains+ ],+ "total_unique_domains": len(domain_counts),+ "avg_links_per_research": round(avg_links, 1),+ "domain_distribution": {+ "top_10": top_10_count,+ "others": others_count,+ },+ "source_type_analysis": source_types,+ "academic_vs_general": {+ "academic": academic_sources,+ "news": news_sources,+ "reference": reference_sources,+ "general": general_sources,+ },+ "total_links": len(resources),+ "total_researches": len(unique_research_ids),+ "temporal_trend": temporal_trend,+ "domain_metrics": {+ domain: {+ "usage_count": count,+ "usage_percentage": round(+ count / len(resources) * 100, 1+ ),+ "research_diversity": len(+ domain_researches.get(domain, set())+ ),+ "frequency_rank": rank + 1,+ }+ for rank, (domain, count) in enumerate(top_10_domains)+ },+ }+ }++ except Exception:+ logger.exception("Error getting link analytics")+ return {+ "link_analytics": {+ "top_domains": [],+ "total_unique_domains": 0,+ "avg_links_per_research": 0,+ "domain_distribution": {},+ "source_type_analysis": {},+ "academic_vs_general": {},+ "total_links": 0,+ "error": "Failed to retrieve link analytics",+ }+ }++def get_available_strategies():"""Get list of all available search strategies from the search system."""# This list comes from the AdvancedSearchSystem.__init__ method@@ -771,6 +1307,130 @@ def api_current_rate_limits():), 500+@metrics_bp.route("/api/metrics/research/<string:research_id>/links")+@login_required+def api_research_link_metrics(research_id):+ """Get link analytics for a specific research."""+ try:+ username = flask_session.get("username")+ if not username:+ return jsonify(+ {"status": "error", "message": "No user session found"}+ ), 401++ with get_user_db_session(username) as session:+ # Get all resources for this specific research+ resources = (+ session.query(ResearchResource)+ .filter(ResearchResource.research_id == research_id)+ .all()+ )++ if not resources:+ return jsonify(+ {+ "status": "success",+ "data": {+ "total_links": 0,+ "unique_domains": 0,+ "domains": [],+ "source_types": {},+ },+ }+ )++ # Extract domain information+ from urllib.parse import urlparse++ domain_counts = {}+ source_types = {+ "academic": 0,+ "news": 0,+ "reference": 0,+ "general": 0,+ }++ for resource in resources:+ if resource.url:+ try:+ parsed = urlparse(resource.url)+ domain = parsed.netloc.lower()+ if domain.startswith("www."):+ domain = domain[4:]++ domain_counts[domain] = domain_counts.get(domain, 0) + 1++ # Categorize source+ if any(+ ext in domain+ for ext in [+ ".edu",+ "arxiv.org",+ "scholar.google",+ "pubmed",+ ]+ ):+ source_types["academic"] += 1+ elif any(+ news in domain+ for news in ["news", "cnn.", "bbc.", "reuters."]+ ):+ source_types["news"] += 1+ elif any(+ ref in domain+ for ref in ["wikipedia.", "docs.", "documentation."]+ ):+ source_types["reference"] += 1+ else:+ source_types["general"] += 1+ except:+ pass++ # Sort domains by count+ sorted_domains = sorted(+ domain_counts.items(), key=lambda x: x[1], reverse=True+ )++ return jsonify(+ {+ "status": "success",+ "data": {+ "total_links": len(resources),+ "unique_domains": len(domain_counts),+ "domains": [+ {+ "domain": domain,+ "count": count,+ "percentage": round(+ count / len(resources) * 100, 1+ ),+ }+ for domain, count in sorted_domains[+ :20+ ] # Top 20 domains+ ],+ "source_types": source_types,+ "resources": [+ {+ "title": r.title or "Untitled",+ "url": r.url,+ "preview": r.content_preview[:200]+ if r.content_preview+ else None,+ }+ for r in resources[:10] # First 10 resources+ ],+ },+ }+ )++ except Exception:+ logger.exception("Error getting research link metrics")+ return jsonify(+ {"status": "error", "message": "Failed to retrieve link metrics"}+ ), 500++@metrics_bp.route("/api/metrics/research/<string:research_id>")@login_requireddef api_research_metrics(research_id):@@ -1594,3 +2254,228 @@ def api_cost_analytics():),200,) # Return 200 to avoid breaking the UI+++@metrics_bp.route("/links")+@login_required+def link_analytics():+ """Display link analytics page."""+ return render_template_with_defaults("pages/link_analytics.html")+++@metrics_bp.route("/api/link-analytics")+@login_required+def api_link_analytics():+ """Get link analytics data."""+ try:+ username = flask_session.get("username")+ if not username:+ return jsonify(+ {"status": "error", "message": "No user session found"}+ ), 401++ period = request.args.get("period", "30d")++ # Get link analytics data+ link_data = get_link_analytics(period, username)++ return jsonify(+ {+ "status": "success",+ "data": link_data["link_analytics"],+ "period": period,+ }+ )++ except Exception:+ logger.exception("Error getting link analytics")+ return (+ jsonify(+ {+ "status": "error",+ "message": "An internal error occurred. Please try again later.",+ }+ ),+ 500,+ )+++@metrics_bp.route("/api/domain-classifications", methods=["GET"])+@login_required+def api_get_domain_classifications():+ """Get all domain classifications."""+ try:+ username = flask_session.get("username")+ if not username:+ return jsonify(+ {"status": "error", "message": "No user session found"}+ ), 401++ classifier = DomainClassifier(username)+ classifications = classifier.get_all_classifications()++ return jsonify(+ {+ "status": "success",+ "classifications": [c.to_dict() for c in classifications],+ "total": len(classifications),+ }+ )++ except Exception:+ logger.exception("Error getting domain classifications")+ return jsonify(+ {"status": "error", "message": "Failed to retrieve classifications"}+ ), 500+++@metrics_bp.route("/api/domain-classifications/summary", methods=["GET"])+@login_required+def api_get_classifications_summary():+ """Get summary of domain classifications by category."""+ try:+ username = flask_session.get("username")+ if not username:+ return jsonify(+ {"status": "error", "message": "No user session found"}+ ), 401++ classifier = DomainClassifier(username)+ summary = classifier.get_categories_summary()++ return jsonify({"status": "success", "summary": summary})++ except Exception:+ logger.exception("Error getting classifications summary")+ return jsonify(+ {"status": "error", "message": "Failed to retrieve summary"}+ ), 500+++@metrics_bp.route("/api/domain-classifications/classify", methods=["POST"])+@login_required+def api_classify_domains():+ """Trigger classification of a specific domain or batch classification."""+ try:+ username = flask_session.get("username")+ if not username:+ return jsonify(+ {"status": "error", "message": "No user session found"}+ ), 401++ data = request.get_json() or {}+ domain = data.get("domain")+ force_update = data.get("force_update", False)+ batch_mode = data.get("batch", False)++ # Get settings snapshot for LLM configuration+ from ..services.settings_manager import SettingsManager+ from ...database.session_context import get_user_db_session++ with get_user_db_session(username) as db_session:+ settings_manager = SettingsManager(db_session=db_session)+ settings_snapshot = settings_manager.get_all_settings()++ classifier = DomainClassifier(+ username, settings_snapshot=settings_snapshot+ )++ if domain and not batch_mode:+ # Classify single domain+ logger.info(f"Classifying single domain: {domain}")+ classification = classifier.classify_domain(domain, force_update)+ if classification:+ return jsonify(+ {+ "status": "success",+ "classification": classification.to_dict(),+ }+ )+ else:+ return jsonify(+ {+ "status": "error",+ "message": f"Failed to classify domain: {domain}",+ }+ ), 400+ elif batch_mode:+ # Batch classification - this should really be a background task+ # For now, we'll just return immediately and let the frontend poll+ logger.info("Starting batch classification of all domains")+ results = classifier.classify_all_domains(force_update)++ return jsonify({"status": "success", "results": results})+ else:+ return jsonify(+ {+ "status": "error",+ "message": "Must provide either 'domain' or set 'batch': true",+ }+ ), 400++ except Exception as e:+ logger.exception("Error classifying domains")+ return jsonify({"status": "error", "message": str(e)}), 500+++@metrics_bp.route("/api/domain-classifications/progress", methods=["GET"])+@login_required+def api_classification_progress():+ """Get progress of domain classification task."""+ try:+ username = flask_session.get("username")+ if not username:+ return jsonify(+ {"status": "error", "message": "No user session found"}+ ), 401++ # Get counts of classified vs unclassified domains+ with get_user_db_session(username) as session:+ # Count total unique domains+ from urllib.parse import urlparse++ resources = session.query(ResearchResource.url).distinct().all()+ domains = set()+ all_domains = []++ for (url,) in resources:+ if url:+ try:+ parsed = urlparse(url)+ domain = parsed.netloc.lower()+ if domain.startswith("www."):+ domain = domain[4:]+ if domain:+ domains.add(domain)+ except:+ continue++ all_domains = sorted(list(domains))+ total_domains = len(domains)++ # Count classified domains+ classified_count = session.query(DomainClassification).count()++ return jsonify(+ {+ "status": "success",+ "progress": {+ "total_domains": total_domains,+ "classified": classified_count,+ "unclassified": total_domains - classified_count,+ "percentage": round(+ (classified_count / total_domains * 100)+ if total_domains > 0+ else 0,+ 1,+ ),+ "all_domains": all_domains, # Return all domains for classification+ },+ }+ )++ except Exception:+ logger.exception("Error getting classification progress")+ return jsonify(+ {"status": "error", "message": "Failed to retrieve progress"}+ ), 500diff --git a/src/local_deep_research/web/static/js/components/details.js b/src/local_deep_research/web/static/js/components/details.jsindex ae1f904e02..0d2de3a496 100644--- a/src/local_deep_research/web/static/js/components/details.js+++ b/src/local_deep_research/web/static/js/components/details.js@@ -35,6 +35,118 @@return id;}+ // Load link analytics for the research+ async function loadLinkAnalytics(researchId) {+ try {+ console.log('Loading link analytics for research:', researchId);++ const response = await fetch(`/metrics/api/metrics/research/${researchId}/links`);+ if (!response.ok) {+ console.error('Failed to load link analytics:', response.status);+ return;+ }++ const result = await response.json();+ if (result.status !== 'success') {+ console.error('Error loading link analytics:', result.message);+ return;+ }++ const data = result.data;++ // Show the link analytics section+ document.getElementById('link-analytics-section').style.display = 'block';++ // Update summary metrics+ document.getElementById('total-links').textContent = data.total_links || 0;+ document.getElementById('unique-domains').textContent = data.unique_domains || 0;+ document.getElementById('academic-sources').textContent = data.source_types?.academic || 0;+ document.getElementById('news-sources').textContent = data.source_types?.news || 0;++ // Display domain list+ const domainList = document.getElementById('domain-list');+ if (data.domains && data.domains.length > 0) {+ domainList.innerHTML = data.domains.map(domain => `+ <div style="display: flex; justify-content: space-between; align-items: center; padding: 0.75rem; border-bottom: 1px solid var(--border-color);">+ <span style="font-weight: 500;">${domain.domain}</span>+ <div style="display: flex; gap: 1rem; align-items: center;">+ <span style="background: var(--primary-color); color: white; padding: 0.25rem 0.5rem; border-radius: 0.25rem; font-size: 0.875rem;">+ ${domain.count} links+ </span>+ <span style="color: var(--text-secondary); font-size: 0.875rem;">+ ${domain.percentage}%+ </span>+ </div>+ </div>+ `).join('');+ } else {+ domainList.innerHTML = '<div style="text-align: center; color: var(--text-secondary); padding: 1rem;">No domain data available</div>';+ }++ // Display resource samples+ const resourceSample = document.getElementById('resource-sample');+ if (data.resources && data.resources.length > 0) {+ resourceSample.innerHTML = data.resources.map(resource => `+ <div style="padding: 0.75rem; border-bottom: 1px solid var(--border-color);">+ <div style="font-weight: 500; margin-bottom: 0.25rem;">${resource.title}</div>+ <a href="${resource.url}" target="_blank" style="color: var(--primary-color); text-decoration: none; font-size: 0.875rem; word-break: break-all;">+ ${resource.url}+ </a>+ ${resource.preview ? `<div style="color: var(--text-secondary); font-size: 0.875rem; margin-top: 0.5rem;">${resource.preview}</div>` : ''}+ </div>+ `).join('');+ } else {+ resourceSample.innerHTML = '<div style="text-align: center; color: var(--text-secondary); padding: 1rem;">No resource samples available</div>';+ }++ // Create source type pie chart+ if (data.source_types) {+ const ctx = document.getElementById('source-type-chart');+ if (ctx) {+ new Chart(ctx, {+ type: 'pie',+ data: {+ labels: ['Academic', 'News', 'Reference', 'General'],+ datasets: [{+ data: [+ data.source_types.academic || 0,+ data.source_types.news || 0,+ data.source_types.reference || 0,+ data.source_types.general || 0+ ],+ backgroundColor: [+ 'rgba(107, 70, 193, 0.8)',+ 'rgba(245, 158, 11, 0.8)',+ 'rgba(59, 130, 246, 0.8)',+ 'rgba(16, 185, 129, 0.8)'+ ],+ borderColor: [+ 'rgba(107, 70, 193, 1)',+ 'rgba(245, 158, 11, 1)',+ 'rgba(59, 130, 246, 1)',+ 'rgba(16, 185, 129, 1)'+ ],+ borderWidth: 1+ }]+ },+ options: {+ responsive: true,+ maintainAspectRatio: false,+ plugins: {+ legend: {+ position: 'bottom'+ }+ }+ }+ });+ }+ }++ } catch (error) {+ console.error('Error loading link analytics:', error);+ }+ }+// Load research metrics dataasync function loadResearchMetrics() {try {@@ -951,6 +1063,9 @@// Load research metricsloadResearchMetrics();+ // Load link analytics for this research+ loadLinkAnalytics(researchId);+// Load context overflow dataloadContextOverflowData(researchId);diff --git a/src/local_deep_research/web/templates/pages/details.html b/src/local_deep_research/web/templates/pages/details.htmlindex f0dc53ee59..6503ef15d2 100644--- a/src/local_deep_research/web/templates/pages/details.html+++ b/src/local_deep_research/web/templates/pages/details.html@@ -341,6 +341,58 @@</div></div>+ <!-- Link Analytics Section -->+ <div class="card metrics-section" id="link-analytics-section" style="display: none;">+ <div class="card-header">+ <h2><i class="fas fa-link"></i> Link & Domain Analytics</h2>+ </div>+ <div class="card-content">+ <!-- Link Metrics Summary -->+ <div class="metrics-grid" id="link-metrics-summary">+ <div class="metric-card">+ <div class="metric-label">Total Links</div>+ <div class="metric-value" id="total-links">0</div>+ </div>+ <div class="metric-card">+ <div class="metric-label">Unique Domains</div>+ <div class="metric-value" id="unique-domains">0</div>+ </div>+ <div class="metric-card">+ <div class="metric-label">Academic Sources</div>+ <div class="metric-value" id="academic-sources">0</div>+ </div>+ <div class="metric-card">+ <div class="metric-label">News Sources</div>+ <div class="metric-value" id="news-sources">0</div>+ </div>+ </div>++ <!-- Domain Distribution -->+ <div style="margin-top: 2rem;">+ <h3><i class="fas fa-globe"></i> Top Domains Used</h3>+ <div id="domain-list" style="max-height: 400px; overflow-y: auto;">+ <!-- Domain items will be populated here -->+ </div>+ </div>++ <!-- Source Type Breakdown -->+ <div style="margin-top: 2rem;">+ <h3><i class="fas fa-chart-pie"></i> Source Type Distribution</h3>+ <div class="chart-container" style="height: 250px; max-width: 400px; margin: 0 auto;">+ <canvas id="source-type-chart"></canvas>+ </div>+ </div>++ <!-- Recent Resources Sample -->+ <div style="margin-top: 2rem;">+ <h3><i class="fas fa-file-text"></i> Sample Resources</h3>+ <div id="resource-sample" style="max-height: 300px; overflow-y: auto;">+ <!-- Resource samples will be populated here -->+ </div>+ </div>+ </div>+ </div>+<!-- Token Metrics Section --><div class="card metrics-section" id="token-metrics-section" style="display: none;"><div class="card-header">diff --git a/src/local_deep_research/web/templates/pages/link_analytics.html b/src/local_deep_research/web/templates/pages/link_analytics.htmlnew file mode 100644index 0000000000..b3aad95865--- /dev/null+++ b/src/local_deep_research/web/templates/pages/link_analytics.html@@ -0,0 +1,1257 @@+{% extends "base.html" %}++{% block title %}Link Analytics - Deep Research System{% endblock %}++{% block extra_head %}+<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>+<style>+ .link-analytics-container {+ max-width: 1200px;+ margin: 0 auto;+ padding: 2rem;+ }++ .metrics-header {+ background: var(--gradient-bg);+ color: var(--text-primary);+ padding: 2rem;+ border-radius: 0.75rem;+ margin-bottom: 2rem;+ text-align: center;+ border: 1px solid var(--border-color);+ box-shadow: var(--card-shadow);+ }++ .metrics-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));+ gap: 1.5rem;+ margin-bottom: 2rem;+ }++ .metric-card {+ background: var(--bg-secondary);+ border-radius: 0.75rem;+ padding: 1.5rem;+ box-shadow: var(--card-shadow);+ border: 1px solid var(--border-color);+ transition: transform 0.2s ease;+ }++ .metric-card:hover {+ transform: translateY(-2px);+ }++ .metric-card h3 {+ margin-top: 0;+ color: var(--text-primary);+ border-bottom: 2px solid var(--border-color);+ padding-bottom: 0.75rem;+ margin-bottom: 1rem;+ font-size: 1.125rem;+ }++ .chart-container {+ position: relative;+ height: 300px;+ margin-bottom: 1rem;+ }++ .overall-stats {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));+ gap: 1.25rem;+ margin-bottom: 2rem;+ }++ .stat-item {+ text-align: center;+ padding: 1rem;+ background: var(--bg-tertiary);+ border-radius: 0.5rem;+ border: 1px solid var(--border-color);+ }++ .stat-value {+ font-size: 1.5rem;+ font-weight: bold;+ color: var(--accent-primary);+ display: block;+ }++ .stat-label {+ font-size: 0.75rem;+ color: var(--text-secondary);+ margin-top: 0.25rem;+ text-transform: uppercase;+ letter-spacing: 0.05em;+ }++ .domain-list {+ max-height: 400px;+ overflow-y: auto;+ }++ .domain-item {+ display: flex;+ justify-content: space-between;+ align-items: center;+ padding: 0.75rem;+ border-bottom: 1px solid var(--border-color);+ transition: background-color 0.2s ease;+ }++ .domain-item:hover {+ background-color: var(--bg-tertiary);+ }++ .domain-item:last-child {+ border-bottom: none;+ }++ .domain-name {+ font-weight: 500;+ color: var(--text-primary);+ flex: 1;+ }++ .domain-count {+ background: var(--accent-primary);+ color: white;+ padding: 0.25rem 0.5rem;+ border-radius: 0.25rem;+ font-size: 0.875rem;+ margin-left: 0.5rem;+ }++ .domain-percentage {+ color: var(--text-secondary);+ font-size: 0.875rem;+ margin-left: 0.5rem;+ }++ .domain-item-expanded {+ flex-direction: column;+ align-items: stretch;+ padding: 1rem;+ background: var(--bg-tertiary);+ border-radius: 0.5rem;+ margin-bottom: 0.75rem;+ }++ .domain-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-bottom: 0.5rem;+ }++ .domain-stats {+ display: flex;+ gap: 1rem;+ align-items: center;+ }++ .metric-badge {+ display: inline-flex;+ align-items: center;+ gap: 0.25rem;+ padding: 0.25rem 0.5rem;+ background: var(--bg-secondary);+ color: var(--text-primary);+ border: 1px solid var(--border-color);+ border-radius: 0.5rem;+ font-size: 0.75rem;+ font-weight: 500;+ }++ .metric-badge.frequency {+ background: linear-gradient(135deg, #6b46c1, #9061f9);+ color: white;+ border: none;+ }++ .metric-badge.diversity {+ background: linear-gradient(135deg, #3b82f6, #60a5fa);+ color: white;+ border: none;+ }++ .metric-badge.rank {+ background: var(--bg-tertiary);+ color: var(--text-secondary);+ }++ .research-links {+ margin-top: 0.5rem;+ padding-top: 0.5rem;+ border-top: 1px solid var(--border-color);+ }++ .research-links-title {+ font-size: 0.75rem;+ color: var(--text-secondary);+ margin-bottom: 0.25rem;+ text-transform: uppercase;+ letter-spacing: 0.05em;+ }++ .research-link {+ display: inline-block;+ margin: 0.25rem 0.5rem 0.25rem 0;+ padding: 0.25rem 0.5rem;+ background: var(--bg-secondary);+ border: 1px solid var(--border-color);+ border-radius: 0.25rem;+ color: var(--accent-primary);+ text-decoration: none;+ font-size: 0.8125rem;+ transition: all 0.2s;+ }++ .research-link:hover {+ background: var(--accent-primary);+ color: white;+ transform: translateY(-1px);+ }++ .source-type-bar {+ display: flex;+ align-items: center;+ margin: 0.5rem 0;+ gap: 0.75rem;+ }++ .source-type-label {+ min-width: 100px;+ font-weight: 500;+ color: var(--text-secondary);+ font-size: 0.875rem;+ }++ .source-type-progress {+ flex: 1;+ height: 20px;+ background: var(--bg-tertiary);+ border-radius: 0.5rem;+ overflow: hidden;+ }++ .source-type-fill {+ height: 100%;+ transition: width 0.3s ease;+ border-radius: 0.5rem;+ }++ .source-type-fill.academic {+ background: linear-gradient(90deg, #6b46c1, #9061f9);+ }++ .source-type-fill.news {+ background: linear-gradient(90deg, #f59e0b, #fbbf24);+ }++ .source-type-fill.reference {+ background: linear-gradient(90deg, #3b82f6, #60a5fa);+ }++ .source-type-fill.general {+ background: linear-gradient(90deg, #10b981, #34d399);+ }++ .source-type-count {+ font-weight: 500;+ min-width: 40px;+ text-align: right;+ color: var(--text-secondary);+ font-size: 0.875rem;+ }++ .period-selector {+ margin-bottom: 1.5rem;+ }++ .period-selector label {+ color: var(--text-secondary);+ margin-right: 0.5rem;+ font-weight: 500;+ }++ .period-selector select {+ padding: 0.5rem 1rem;+ border: 1px solid var(--border-color);+ border-radius: 0.375rem;+ background: var(--bg-secondary);+ color: var(--text-primary);+ cursor: pointer;+ transition: border-color 0.2s ease;+ }++ .period-selector select:focus {+ outline: none;+ border-color: var(--accent-primary);+ box-shadow: 0 0 0 3px rgba(110, 79, 246, 0.1);+ }++ .loading {+ text-align: center;+ padding: 2.5rem;+ color: var(--text-secondary);+ background: var(--bg-secondary);+ border-radius: 0.5rem;+ border: 1px solid var(--border-color);+ }++ .error {+ background: rgba(250, 92, 124, 0.1);+ color: var(--error-color);+ padding: 1rem;+ border-radius: 0.5rem;+ margin: 1.25rem 0;+ border: 1px solid rgba(250, 92, 124, 0.2);+ }++ @media (max-width: 768px) {+ .metrics-grid {+ grid-template-columns: 1fr;+ }++ .overall-stats {+ grid-template-columns: repeat(2, 1fr);+ }++ .link-analytics-container {+ padding: 1rem;+ }+ }++ /* Modal styles for classification dialog */+ .modal {+ display: none;+ position: fixed;+ z-index: 1000;+ left: 0;+ top: 0;+ width: 100%;+ height: 100%;+ background-color: rgba(0, 0, 0, 0.5);+ backdrop-filter: blur(5px);+ }++ .modal-content {+ position: relative;+ background-color: var(--bg-secondary);+ margin: 5% auto;+ padding: 2rem;+ border-radius: 0.75rem;+ width: 80%;+ max-width: 600px;+ box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);+ border: 1px solid var(--border-color);+ }++ .modal-header {+ margin-bottom: 1.5rem;+ }++ .modal-header h2 {+ margin: 0;+ color: var(--text-primary);+ }++ .close-modal {+ position: absolute;+ right: 1.5rem;+ top: 1.5rem;+ font-size: 1.5rem;+ cursor: pointer;+ color: var(--text-secondary);+ transition: color 0.2s;+ }++ .close-modal:hover {+ color: var(--text-primary);+ }++ .progress-bar {+ width: 100%;+ height: 30px;+ background: var(--bg-tertiary);+ border-radius: 0.5rem;+ overflow: hidden;+ margin: 1rem 0;+ }++ .progress-fill {+ height: 100%;+ background: linear-gradient(90deg, var(--accent-primary), #9061f9);+ transition: width 0.3s ease;+ display: flex;+ align-items: center;+ justify-content: center;+ color: white;+ font-weight: 500;+ }++ .classification-log {+ max-height: 300px;+ overflow-y: auto;+ background: var(--bg-tertiary);+ border-radius: 0.5rem;+ padding: 1rem;+ margin-top: 1rem;+ font-size: 0.875rem;+ }++ .log-entry {+ padding: 0.5rem;+ border-bottom: 1px solid var(--border-color);+ }++ .log-entry:last-child {+ border-bottom: none;+ }++ .log-entry.success {+ color: #22c55e;+ }++ .log-entry.error {+ color: #ef4444;+ }++ .classified-badge {+ display: inline-block;+ padding: 0.2rem 0.5rem;+ background: linear-gradient(135deg, #22c55e, #34d399);+ color: white;+ border-radius: 0.25rem;+ font-size: 0.75rem;+ font-weight: 500;+ margin-left: 0.5rem;+ }+</style>+{% endblock %}++{% block content %}+<div class="link-analytics-container">+ <div class="metrics-header">+ <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px;">+ <h1>🔗 Link Analytics Dashboard</h1>+ <a href="/metrics/" style="background: var(--bg-tertiary); color: var(--text-primary); padding: 0.5rem 1rem; border-radius: 0.375rem; text-decoration: none; font-size: 0.875rem; border: 1px solid var(--border-color); transition: background-color 0.2s ease;">+ ← Back to Metrics+ </a>+ </div>+ <p>Analyze sources and domains used in your research sessions</p>+ </div>++ <div class="period-selector" style="display: flex; justify-content: space-between; align-items: center;">+ <div>+ <label for="period-select">Time Period: </label>+ <select id="period-select">+ <option value="7d">Last 7 days</option>+ <option value="30d" selected>Last 30 days</option>+ <option value="90d">Last 3 months</option>+ <option value="365d">Last year</option>+ <option value="all">All time</option>+ </select>+ </div>+ <div>+ <button id="classify-domains-btn" class="btn" style="background: var(--accent-primary); color: white; padding: 0.5rem 1rem; border-radius: 0.375rem; border: none; cursor: pointer; font-size: 0.875rem;">+ <i class="fas fa-brain"></i> Classify Domains with AI+ </button>+ <span id="classification-status" style="margin-left: 1rem; font-size: 0.875rem; color: var(--text-secondary);"></span>+ </div>+ </div>++ <div id="loading" class="loading">+ <div>Loading link analytics data...</div>+ </div>++ <div id="error" class="error" style="display: none;"></div>++ <div id="content" style="display: none;">+ <!-- Overall Statistics -->+ <div class="metric-card">+ <h3>📊 Overall Link Statistics</h3>+ <div class="overall-stats">+ <div class="stat-item">+ <span class="stat-value" id="total-links">0</span>+ <div class="stat-label">Total Links</div>+ </div>+ <div class="stat-item">+ <span class="stat-value" id="unique-domains">0</span>+ <div class="stat-label">Unique Domains</div>+ </div>+ <div class="stat-item">+ <span class="stat-value" id="avg-links">0</span>+ <div class="stat-label">Avg Links/Research</div>+ </div>+ <div class="stat-item">+ <span class="stat-value" id="total-researches">0</span>+ <div class="stat-label">Total Researches</div>+ </div>+ </div>+ </div>++ <div class="metrics-grid">+ <!-- Top Domains Chart -->+ <div class="metric-card">+ <h3>🌐 Top 10 Domains</h3>+ <div class="chart-container">+ <canvas id="top-domains-chart"></canvas>+ </div>+ </div>++ <!-- Domain Distribution Pie Chart -->+ <div class="metric-card">+ <h3>📊 Domain Distribution</h3>+ <div class="chart-container">+ <canvas id="domain-distribution-chart"></canvas>+ </div>+ </div>++ <!-- Temporal Trend Chart -->+ <div class="metric-card" style="grid-column: span 2;">+ <h3>📈 Links Over Time</h3>+ <div class="chart-container">+ <canvas id="temporal-trend-chart"></canvas>+ </div>+ </div>++ <!-- Source Type Analysis -->+ <div class="metric-card">+ <h3>📚 Source Type Analysis</h3>+ <div id="source-type-bars">+ <div class="source-type-bar">+ <div class="source-type-label">Academic</div>+ <div class="source-type-progress">+ <div class="source-type-fill academic" id="academic-fill" style="width: 0%;"></div>+ </div>+ <div class="source-type-count" id="academic-count">0</div>+ </div>+ <div class="source-type-bar">+ <div class="source-type-label">News</div>+ <div class="source-type-progress">+ <div class="source-type-fill news" id="news-fill" style="width: 0%;"></div>+ </div>+ <div class="source-type-count" id="news-count">0</div>+ </div>+ <div class="source-type-bar">+ <div class="source-type-label">Reference</div>+ <div class="source-type-progress">+ <div class="source-type-fill reference" id="reference-fill" style="width: 0%;"></div>+ </div>+ <div class="source-type-count" id="reference-count">0</div>+ </div>+ <div class="source-type-bar">+ <div class="source-type-label">General</div>+ <div class="source-type-progress">+ <div class="source-type-fill general" id="general-fill" style="width: 0%;"></div>+ </div>+ <div class="source-type-count" id="general-count">0</div>+ </div>+ </div>+ <div class="chart-container" style="margin-top: 1.5rem;">+ <canvas id="source-type-chart"></canvas>+ </div>+ </div>++ <!-- Top Domains List with Research Info -->+ <div class="metric-card" style="grid-column: span 2;">+ <h3>🔍 Domain Details & Research Connections</h3>+ <div class="domain-list" id="domain-list" style="max-height: 600px;">+ <!-- Domain items will be populated here -->+ </div>+ </div>+ </div>+ </div>+</div>++<!-- Domain Classification Modal -->+<div id="classification-modal" class="modal">+ <div class="modal-content">+ <span class="close-modal">×</span>+ <div class="modal-header">+ <h2><i class="fas fa-brain"></i> AI Domain Classification</h2>+ <p style="color: var(--text-secondary); margin-top: 0.5rem;">+ The AI will analyze and categorize each domain based on its content and purpose.+ </p>+ </div>++ <div id="classification-info">+ <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 1rem; margin-bottom: 1.5rem;">+ <div style="background: var(--bg-tertiary); padding: 1rem; border-radius: 0.5rem;">+ <div style="font-size: 1.5rem; font-weight: bold; color: var(--accent-primary);" id="total-domains-count">0</div>+ <div style="font-size: 0.875rem; color: var(--text-secondary);">Total Domains</div>+ </div>+ <div style="background: var(--bg-tertiary); padding: 1rem; border-radius: 0.5rem;">+ <div style="font-size: 1.5rem; font-weight: bold; color: #22c55e;" id="classified-count">0</div>+ <div style="font-size: 0.875rem; color: var(--text-secondary);">Already Classified</div>+ </div>+ </div>++ <div id="classification-options" style="margin-bottom: 1.5rem;">+ <label style="display: flex; align-items: center; cursor: pointer;">+ <input type="checkbox" id="force-reclassify" style="margin-right: 0.5rem;">+ <span>Force reclassification of all domains (overwrite existing)</span>+ </label>+ </div>++ <button id="start-classification" class="btn" style="width: 100%; background: var(--accent-primary); color: white; padding: 0.75rem; border-radius: 0.5rem; border: none; cursor: pointer; font-size: 1rem;">+ <i class="fas fa-play"></i> Start Classification+ </button>+ </div>++ <div id="classification-progress" style="display: none;">+ <div class="progress-bar">+ <div class="progress-fill" id="progress-fill" style="width: 0%;">0%</div>+ </div>++ <div style="text-align: center; margin-bottom: 1rem;">+ <span id="current-domain" style="color: var(--text-secondary);"></span>+ </div>++ <div class="classification-log" id="classification-log">+ <!-- Log entries will be added here -->+ </div>++ <button id="stop-classification" class="btn" style="width: 100%; background: #ef4444; color: white; padding: 0.75rem; border-radius: 0.5rem; border: none; cursor: pointer; font-size: 1rem; margin-top: 1rem;">+ <i class="fas fa-stop"></i> Stop Classification+ </button>+ </div>++ <div id="classification-complete" style="display: none; text-align: center;">+ <i class="fas fa-check-circle" style="font-size: 3rem; color: #22c55e; margin-bottom: 1rem;"></i>+ <h3>Classification Complete!</h3>+ <p style="color: var(--text-secondary); margin: 1rem 0;">+ Successfully classified <span id="final-classified">0</span> domains.+ </p>+ <button id="close-complete" class="btn" style="background: var(--accent-primary); color: white; padding: 0.75rem 1.5rem; border-radius: 0.5rem; border: none; cursor: pointer;">+ <i class="fas fa-check"></i> Done+ </button>+ </div>+ </div>+</div>++<script>+let topDomainsChart = null;+let domainDistributionChart = null;+let sourceTypeChart = null;+let temporalTrendChart = null;++async function loadLinkAnalytics(period = '30d') {+ const loading = document.getElementById('loading');+ const content = document.getElementById('content');+ const error = document.getElementById('error');++ loading.style.display = 'block';+ content.style.display = 'none';+ error.style.display = 'none';++ try {+ const response = await fetch(`/metrics/api/link-analytics?period=${period}`);+ const result = await response.json();++ if (result.status === 'success') {+ const data = result.data;++ // Update overall statistics+ document.getElementById('total-links').textContent = data.total_links || 0;+ document.getElementById('unique-domains').textContent = data.total_unique_domains || 0;+ document.getElementById('avg-links').textContent = data.avg_links_per_research || 0;+ document.getElementById('total-researches').textContent = data.total_researches || 0;++ // Update source type bars+ const sourceTypes = data.academic_vs_general || {};+ const total = sourceTypes.academic + sourceTypes.news + sourceTypes.reference + sourceTypes.general || 1;++ updateSourceTypeBar('academic', sourceTypes.academic || 0, total);+ updateSourceTypeBar('news', sourceTypes.news || 0, total);+ updateSourceTypeBar('reference', sourceTypes.reference || 0, total);+ updateSourceTypeBar('general', sourceTypes.general || 0, total);++ // Update charts+ updateTopDomainsChart(data.top_domains || []);+ updateDomainDistributionChart(data.domain_distribution || {});+ updateSourceTypeChart(sourceTypes);+ updateTemporalTrendChart(data.temporal_trend || []);++ // Update enhanced domain list with research info+ updateEnhancedDomainList(data.top_domains || [], data.domain_metrics || {});++ loading.style.display = 'none';+ content.style.display = 'block';+ } else {+ throw new Error(result.message || 'Failed to load data');+ }+ } catch (err) {+ console.error('Error loading link analytics:', err);+ error.textContent = 'Failed to load link analytics data. Please try again later.';+ error.style.display = 'block';+ loading.style.display = 'none';+ }+}++function updateSourceTypeBar(type, count, total) {+ const percentage = total > 0 ? (count / total * 100) : 0;+ document.getElementById(`${type}-fill`).style.width = `${percentage}%`;+ document.getElementById(`${type}-count`).textContent = count;+}++function updateTopDomainsChart(domains) {+ const ctx = document.getElementById('top-domains-chart').getContext('2d');++ if (topDomainsChart) {+ topDomainsChart.destroy();+ }++ topDomainsChart = new Chart(ctx, {+ type: 'bar',+ data: {+ labels: domains.map(d => d.domain),+ datasets: [{+ label: 'Number of Links',+ data: domains.map(d => d.count),+ backgroundColor: 'rgba(107, 70, 193, 0.6)',+ borderColor: 'rgba(107, 70, 193, 1)',+ borderWidth: 1+ }]+ },+ options: {+ responsive: true,+ maintainAspectRatio: false,+ scales: {+ y: {+ beginAtZero: true,+ ticks: {+ stepSize: 1+ }+ },+ x: {+ ticks: {+ maxRotation: 45,+ minRotation: 45+ }+ }+ },+ plugins: {+ legend: {+ display: false+ },+ tooltip: {+ callbacks: {+ afterLabel: function(context) {+ const domain = domains[context.dataIndex];+ return `${domain.percentage}% of total`;+ }+ }+ }+ }+ }+ });+}++function updateDomainDistributionChart(distribution) {+ const ctx = document.getElementById('domain-distribution-chart').getContext('2d');++ if (domainDistributionChart) {+ domainDistributionChart.destroy();+ }++ const labels = [];+ const data = [];++ if (distribution.top_10 > 0) {+ labels.push('Top 10 Domains');+ data.push(distribution.top_10);+ }++ if (distribution.others > 0) {+ labels.push('Other Domains');+ data.push(distribution.others);+ }++ if (data.length === 0) {+ labels.push('No Data');+ data.push(1);+ }++ domainDistributionChart = new Chart(ctx, {+ type: 'doughnut',+ data: {+ labels: labels,+ datasets: [{+ data: data,+ backgroundColor: [+ 'rgba(107, 70, 193, 0.8)',+ 'rgba(144, 97, 249, 0.8)'+ ],+ borderColor: [+ 'rgba(107, 70, 193, 1)',+ 'rgba(144, 97, 249, 1)'+ ],+ borderWidth: 1+ }]+ },+ options: {+ responsive: true,+ maintainAspectRatio: false,+ plugins: {+ legend: {+ position: 'bottom'+ }+ }+ }+ });+}++function updateSourceTypeChart(sourceTypes) {+ const ctx = document.getElementById('source-type-chart').getContext('2d');++ if (sourceTypeChart) {+ sourceTypeChart.destroy();+ }++ sourceTypeChart = new Chart(ctx, {+ type: 'pie',+ data: {+ labels: ['Academic', 'News', 'Reference', 'General'],+ datasets: [{+ data: [+ sourceTypes.academic || 0,+ sourceTypes.news || 0,+ sourceTypes.reference || 0,+ sourceTypes.general || 0+ ],+ backgroundColor: [+ 'rgba(107, 70, 193, 0.8)',+ 'rgba(245, 158, 11, 0.8)',+ 'rgba(59, 130, 246, 0.8)',+ 'rgba(16, 185, 129, 0.8)'+ ],+ borderColor: [+ 'rgba(107, 70, 193, 1)',+ 'rgba(245, 158, 11, 1)',+ 'rgba(59, 130, 246, 1)',+ 'rgba(16, 185, 129, 1)'+ ],+ borderWidth: 1+ }]+ },+ options: {+ responsive: true,+ maintainAspectRatio: false,+ plugins: {+ legend: {+ position: 'bottom'+ }+ }+ }+ });+}++function updateTemporalTrendChart(trendData) {+ const ctx = document.getElementById('temporal-trend-chart').getContext('2d');++ if (temporalTrendChart) {+ temporalTrendChart.destroy();+ }++ if (trendData.length === 0) {+ return;+ }++ temporalTrendChart = new Chart(ctx, {+ type: 'line',+ data: {+ labels: trendData.map(d => d.date),+ datasets: [{+ label: 'Links Collected',+ data: trendData.map(d => d.count),+ borderColor: 'rgba(107, 70, 193, 1)',+ backgroundColor: 'rgba(107, 70, 193, 0.1)',+ borderWidth: 2,+ fill: true,+ tension: 0.3,+ pointRadius: 4,+ pointHoverRadius: 6+ }]+ },+ options: {+ responsive: true,+ maintainAspectRatio: false,+ scales: {+ y: {+ beginAtZero: true,+ ticks: {+ stepSize: 1+ }+ },+ x: {+ ticks: {+ maxRotation: 45,+ minRotation: 0,+ autoSkip: true,+ maxTicksLimit: 15+ }+ }+ },+ plugins: {+ legend: {+ display: false+ },+ tooltip: {+ callbacks: {+ title: function(context) {+ return 'Date: ' + context[0].label;+ },+ label: function(context) {+ return 'Links: ' + context.parsed.y;+ }+ }+ }+ }+ }+ });+}++function updateEnhancedDomainList(domains, domainMetrics) {+ const container = document.getElementById('domain-list');+ container.innerHTML = '';++ if (domains.length === 0) {+ container.innerHTML = '<div style="text-align: center; color: var(--text-secondary); padding: 1rem;">No domain data available</div>';+ return;+ }++ domains.forEach(domain => {+ const metrics = domainMetrics[domain.domain] || {};+ const usageCount = metrics.usage_count || domain.count || 0;+ const usagePercentage = metrics.usage_percentage || domain.percentage || 0;+ const researchDiversity = metrics.research_diversity || domain.research_count || 0;+ const rank = metrics.frequency_rank || 0;++ const item = document.createElement('div');+ item.className = 'domain-item-expanded';++ let researchLinksHtml = '';+ if (domain.recent_researches && domain.recent_researches.length > 0) {+ researchLinksHtml = `+ <div class="research-links">+ <div class="research-links-title">Recent Researches (${researchDiversity} total)</div>+ ${domain.recent_researches.map(r => `+ <a href="/research/${r.id}" class="research-link" title="${r.query}">+ ${r.query.length > 30 ? r.query.substring(0, 30) + '...' : r.query}+ </a>+ `).join('')}+ </div>+ `;+ }++ // Add classification if available+ let classificationHtml = '';+ if (domain.classification) {+ classificationHtml = `+ <span class="classified-badge" title="${domain.classification.subcategory} (${Math.round(domain.classification.confidence * 100)}% confidence)">+ ${domain.classification.category}+ </span>+ `;+ }++ item.innerHTML = `+ <div class="domain-header">+ <span class="domain-name" style="font-size: 1rem; font-weight: 600;">+ ${rank ? `#${rank}` : ''} <a href="https://${domain.domain}" target="_blank" rel="noopener noreferrer" style="color: var(--accent-primary); text-decoration: none; border-bottom: 1px dotted var(--accent-primary); transition: all 0.2s ease;" onmouseover="this.style.borderBottom='2px solid var(--accent-primary)'" onmouseout="this.style.borderBottom='1px dotted var(--accent-primary)'">${domain.domain}</a>+ ${classificationHtml}+ </span>+ <div class="domain-stats">+ <span class="metric-badge frequency">+ 📊 ${usageCount} uses (${usagePercentage}%)+ </span>+ <span class="metric-badge diversity">+ 🔍 ${researchDiversity} researches+ </span>+ </div>+ </div>+ ${researchLinksHtml}+ `;+ container.appendChild(item);+ });+}++// Event listener for period selector+document.getElementById('period-select').addEventListener('change', (e) => {+ loadLinkAnalytics(e.target.value);+});++// Load initial data+loadLinkAnalytics('30d');++// Domain Classification functionality+let classificationInProgress = false;+let domainsToClassify = [];+let currentDomainIndex = 0;++// Modal elements+const modal = document.getElementById('classification-modal');+const classifyBtn = document.getElementById('classify-domains-btn');+const closeModal = document.querySelector('.close-modal');+const startBtn = document.getElementById('start-classification');+const stopBtn = document.getElementById('stop-classification');+const closeCompleteBtn = document.getElementById('close-complete');++// Show modal when classify button is clicked+classifyBtn.addEventListener('click', async () => {+ modal.style.display = 'block';+ await loadClassificationProgress();+});++// Close modal+closeModal.addEventListener('click', () => {+ if (!classificationInProgress) {+ modal.style.display = 'none';+ }+});++closeCompleteBtn.addEventListener('click', () => {+ modal.style.display = 'none';+ // Reload the page to show updated classifications+ loadLinkAnalytics(document.getElementById('period-select').value);+});++// Load classification progress+async function loadClassificationProgress() {+ try {+ const response = await fetch('/metrics/api/domain-classifications/progress');+ const result = await response.json();++ if (result.status === 'success') {+ const progress = result.progress;+ document.getElementById('total-domains-count').textContent = progress.total_domains;+ document.getElementById('classified-count').textContent = progress.classified;++ // Update status text+ const statusText = document.getElementById('classification-status');+ if (progress.classified > 0) {+ statusText.textContent = `${progress.classified}/${progress.total_domains} domains classified`;+ statusText.style.color = '#22c55e';+ }+ }+ } catch (error) {+ console.error('Error loading classification progress:', error);+ }+}++// Start classification+startBtn.addEventListener('click', async () => {+ const forceReclassify = document.getElementById('force-reclassify').checked;++ // Hide info, show progress+ document.getElementById('classification-info').style.display = 'none';+ document.getElementById('classification-progress').style.display = 'block';+ document.getElementById('classification-complete').style.display = 'none';++ classificationInProgress = true;++ // Get list of domains to classify+ try {+ const response = await fetch('/metrics/api/domain-classifications/progress');+ const result = await response.json();++ if (result.status === 'success') {+ const totalDomains = result.progress.total_domains;++ // Start classification process+ await classifyAllDomains(forceReclassify);+ }+ } catch (error) {+ console.error('Error starting classification:', error);+ addLogEntry(`Error: ${error.message}`, 'error');+ }+});++// Stop classification+stopBtn.addEventListener('click', () => {+ classificationInProgress = false;+ addLogEntry('Classification stopped by user', 'error');+});++// Classify all domains+async function classifyAllDomains(forceUpdate = false) {+ const logContainer = document.getElementById('classification-log');+ logContainer.innerHTML = '';++ try {+ // Get all domains from the progress endpoint which now includes all domains+ const progressResponse = await fetch('/metrics/api/domain-classifications/progress');+ const progressResult = await progressResponse.json();++ if (progressResult.status === 'success' && progressResult.progress.all_domains) {+ // Get all domains from the progress endpoint+ const allDomains = new Set(progressResult.progress.all_domains);++ // Get existing classifications to check which need updating+ if (!forceUpdate) {+ const classResponse = await fetch('/metrics/api/domain-classifications');+ const classResult = await classResponse.json();++ if (classResult.status === 'success') {+ const classified = new Set(classResult.classifications.map(c => c.domain));+ // Remove already classified domains+ classified.forEach(d => allDomains.delete(d));+ }+ }++ domainsToClassify = Array.from(allDomains);+ const totalToClassify = domainsToClassify.length;++ if (totalToClassify === 0) {+ addLogEntry('All domains are already classified!', 'success');+ showClassificationComplete(0);+ return;+ }++ addLogEntry(`Starting classification of ${totalToClassify} domains...`, 'success');++ let classified = 0;+ let failed = 0;++ for (let i = 0; i < domainsToClassify.length && classificationInProgress; i++) {+ const domain = domainsToClassify[i];+ const progress = ((i + 1) / totalToClassify) * 100;++ // Update progress bar+ document.getElementById('progress-fill').style.width = `${progress}%`;+ document.getElementById('progress-fill').textContent = `${Math.round(progress)}%`;+ document.getElementById('current-domain').textContent = `Classifying: ${domain}`;++ try {+ // Get CSRF token if it exists+ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content;++ // Classify single domain+ const headers = {+ 'Content-Type': 'application/json',+ };++ if (csrfToken) {+ headers['X-CSRFToken'] = csrfToken;+ }++ const response = await fetch('/metrics/api/domain-classifications/classify', {+ method: 'POST',+ headers: headers,+ credentials: 'same-origin', // Include cookies for session+ body: JSON.stringify({+ domain: domain,+ force_update: forceUpdate+ })+ });++ if (!response.ok) {+ const errorText = await response.text();+ console.error(`HTTP error! status: ${response.status}, body: ${errorText}`);+ failed++;+ addLogEntry(`✗ ${domain}: HTTP ${response.status} error`, 'error');+ continue;+ }++ const result = await response.json();++ if (result.status === 'success') {+ classified++;+ const cat = result.classification.category;+ const subcat = result.classification.subcategory;+ addLogEntry(`✓ ${domain}: ${cat} / ${subcat}`, 'success');+ } else {+ failed++;+ addLogEntry(`✗ ${domain}: ${result.message || 'Classification failed'}`, 'error');+ }++ // Small delay to avoid overwhelming the server+ await new Promise(resolve => setTimeout(resolve, 1000)); // Increased delay++ } catch (error) {+ console.error(`Error classifying ${domain}:`, error);+ failed++;+ addLogEntry(`✗ ${domain}: ${error.message}`, 'error');+ }+ }++ if (classificationInProgress) {+ showClassificationComplete(classified);+ }++ }+ } catch (error) {+ console.error('Error during classification:', error);+ addLogEntry(`Fatal error: ${error.message}`, 'error');+ }++ classificationInProgress = false;+}++// Add log entry+function addLogEntry(message, type = 'info') {+ const logContainer = document.getElementById('classification-log');+ const entry = document.createElement('div');+ entry.className = `log-entry ${type}`;+ entry.textContent = message;+ logContainer.appendChild(entry);+ logContainer.scrollTop = logContainer.scrollHeight;+}++// Show classification complete+function showClassificationComplete(count) {+ document.getElementById('classification-progress').style.display = 'none';+ document.getElementById('classification-complete').style.display = 'block';+ document.getElementById('final-classified').textContent = count;+}++// Update domain display to show classifications+async function loadClassificationsAndUpdateDisplay() {+ try {+ const response = await fetch('/metrics/api/domain-classifications');+ const result = await response.json();++ if (result.status === 'success') {+ const classifications = {};+ result.classifications.forEach(c => {+ classifications[c.domain] = c;+ });++ // Update domain list to show classifications+ const domainItems = document.querySelectorAll('.domain-item-expanded');+ domainItems.forEach(item => {+ const domainName = item.querySelector('.domain-name');+ if (domainName) {+ const domainText = domainName.textContent.replace(/^#\d+\s*/, '').trim();+ if (classifications[domainText]) {+ const classification = classifications[domainText];+ // Add classification badge+ if (!domainName.querySelector('.classified-badge')) {+ const badge = document.createElement('span');+ badge.className = 'classified-badge';+ badge.textContent = classification.category;+ badge.title = `${classification.subcategory} (${Math.round(classification.confidence * 100)}% confidence)`;+ domainName.appendChild(badge);+ }+ }+ }+ });+ }+ } catch (error) {+ console.error('Error loading classifications:', error);+ }+}++// Load classifications when data is loaded+const originalUpdateEnhancedDomainList = updateEnhancedDomainList;+updateEnhancedDomainList = function(domains, domainMetrics) {+ originalUpdateEnhancedDomainList(domains, domainMetrics);+ // Load and display classifications+ loadClassificationsAndUpdateDisplay();+};+</script>+{% endblock %}diff --git a/src/local_deep_research/web/templates/pages/metrics.html b/src/local_deep_research/web/templates/pages/metrics.htmlindex 56603b2038..2df6912728 100644--- a/src/local_deep_research/web/templates/pages/metrics.html+++ b/src/local_deep_research/web/templates/pages/metrics.html@@ -397,6 +397,9 @@<a href="/metrics/context-overflow" style="background: linear-gradient(135deg, #ff9800 0%, #f44336 100%); color: white; padding: 8px 16px; border-radius: 6px; text-decoration: none; font-size: 0.875rem; transition: transform 0.2s;">⚠️ Context Overflow</a>+ <a href="/metrics/links" style="background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 100%); color: white; padding: 8px 16px; border-radius: 6px; text-decoration: none; font-size: 0.875rem; transition: transform 0.2s;">+ 🔗 Link Analytics+ </a></div><div style="display: flex; gap: 2rem; align-items: center;"><!-- Research Mode Filter -->diff --git a/src/local_deep_research/web/templates/settings_dashboard.html b/src/local_deep_research/web/templates/settings_dashboard.htmlindex 89dae531d3..568f781fe6 100644--- a/src/local_deep_research/web/templates/settings_dashboard.html+++ b/src/local_deep_research/web/templates/settings_dashboard.html@@ -54,6 +54,7 @@<div class="settings-tab" data-tab="search">Search Engines</div><div class="settings-tab" data-tab="report">Reports</div><div class="settings-tab" data-tab="app">Application</div>+ <div class="settings-tab" data-tab="domains">Domain Classification</div></div><form id="settings-form" class="settings-form" method="POST" action="{{ url_for('settings.save_settings') }}">diff --git a/tests/test_link_analytics.py b/tests/test_link_analytics.pynew file mode 100644index 0000000000..cf7d03c3dc--- /dev/null+++ b/tests/test_link_analytics.py@@ -0,0 +1,425 @@+"""Tests for the link analytics feature."""++import json+from datetime import datetime, timedelta, UTC+from unittest.mock import MagicMock, patch++import pytest+from flask import Flask++from src.local_deep_research.database.models import ResearchResource+from src.local_deep_research.web.routes.metrics_routes import (+ get_link_analytics,+ metrics_bp,+)+++def app():+ """Create Flask app for testing."""+ app = Flask(__name__)+ app.config["TESTING"] = True+ app.config["SECRET_KEY"] = "test-secret-key"+ app.register_blueprint(metrics_bp)++ # Mock login_required decorator+ with patch(+ "src.local_deep_research.web.auth.decorators.login_required",+ lambda f: f,+ ):+ yield app+++def client(app):+ """Create test client."""+ return app.test_client()+++def mock_session():+ """Mock Flask session."""+ with patch(+ "src.local_deep_research.web.routes.metrics_routes.flask_session"+ ) as mock:+ mock.get.return_value = "test_user"+ yield mock+++def mock_resources():+ """Create mock research resources."""+ resources = []+ domains = [+ "example.com",+ "docs.python.org",+ "stackoverflow.com",+ "github.com",+ "arxiv.org",+ "wikipedia.org",+ "news.ycombinator.com",+ "medium.com",+ "reddit.com",+ "google.com",+ ]++ # Create resources with various domains+ for i in range(50):+ resource = MagicMock(spec=ResearchResource)+ resource.url = f"https://{domains[i % len(domains)]}/path/{i}"+ resource.research_id = f"research_{i // 5}" # 10 resources per research+ resource.source_type = ["web", "academic", "news", "reference"][i % 4]+ resource.created_at = (+ datetime.now(UTC) - timedelta(days=i)+ ).isoformat()+ resource.title = f"Resource {i}"+ resource.content_preview = f"Content preview for resource {i}"+ resources.append(resource)++ return resources+++class TestLinkAnalytics:+ """Test link analytics functionality."""++ def test_get_link_analytics_no_session(self):+ """Test analytics without user session."""+ result = get_link_analytics(username=None)++ assert "link_analytics" in result+ assert result["link_analytics"]["error"] == "No user session"+ assert result["link_analytics"]["total_links"] == 0++ def test_get_link_analytics_empty_data(self):+ """Test analytics with no resources."""+ with patch(+ "src.local_deep_research.web.routes.metrics_routes.get_user_db_session"+ ) as mock_session:+ mock_db = MagicMock()+ mock_db.query.return_value.all.return_value = []+ mock_session.return_value.__enter__.return_value = mock_db++ result = get_link_analytics(username="test_user")++ assert "link_analytics" in result+ analytics = result["link_analytics"]+ assert analytics["total_links"] == 0+ assert analytics["total_unique_domains"] == 0+ assert analytics["avg_links_per_research"] == 0+ assert len(analytics["top_domains"]) == 0++ def test_get_link_analytics_with_data(self, mock_resources):+ """Test analytics with mock resources."""+ with patch(+ "src.local_deep_research.web.routes.metrics_routes.get_user_db_session"+ ) as mock_session:+ mock_db = MagicMock()+ mock_db.query.return_value.all.return_value = mock_resources+ mock_session.return_value.__enter__.return_value = mock_db++ result = get_link_analytics(period="30d", username="test_user")++ assert "link_analytics" in result+ analytics = result["link_analytics"]++ # Check basic metrics+ assert analytics["total_links"] == 50+ assert analytics["total_unique_domains"] == 10+ assert analytics["avg_links_per_research"] > 0++ # Check top domains+ assert len(analytics["top_domains"]) <= 10+ assert all("domain" in d for d in analytics["top_domains"])+ assert all("count" in d for d in analytics["top_domains"])+ assert all("percentage" in d for d in analytics["top_domains"])++ # Check source type analysis+ assert "academic_vs_general" in analytics+ source_types = analytics["academic_vs_general"]+ assert "academic" in source_types+ assert "news" in source_types+ assert "reference" in source_types+ assert "general" in source_types++ def test_get_link_analytics_time_filter(self, mock_resources):+ """Test analytics with time period filter."""+ with patch(+ "src.local_deep_research.web.routes.metrics_routes.get_user_db_session"+ ) as mock_session:+ mock_db = MagicMock()++ # Filter to only recent resources (last 7 days)+ recent_resources = [r for r in mock_resources[:7]]+ mock_db.query.return_value.filter.return_value.all.return_value = (+ recent_resources+ )+ mock_session.return_value.__enter__.return_value = mock_db++ result = get_link_analytics(period="7d", username="test_user")++ assert "link_analytics" in result+ analytics = result["link_analytics"]+ assert analytics["total_links"] == 7++ def test_get_link_analytics_domain_extraction(self):+ """Test correct domain extraction from URLs."""+ resources = [+ MagicMock(+ url="https://www.example.com/path",+ research_id="1",+ source_type=None,+ ),+ MagicMock(+ url="http://docs.python.org/3/",+ research_id="1",+ source_type=None,+ ),+ MagicMock(+ url="https://github.com/user/repo",+ research_id="1",+ source_type=None,+ ),+ MagicMock(+ url="https://www.github.com/another",+ research_id="1",+ source_type=None,+ ),+ ]++ with patch(+ "src.local_deep_research.web.routes.metrics_routes.get_user_db_session"+ ) as mock_session:+ mock_db = MagicMock()+ mock_db.query.return_value.all.return_value = resources+ mock_session.return_value.__enter__.return_value = mock_db++ result = get_link_analytics(username="test_user")+ analytics = result["link_analytics"]++ # Should remove www. prefix and count properly+ top_domains = {+ d["domain"]: d["count"] for d in analytics["top_domains"]+ }+ assert "github.com" in top_domains+ assert (+ top_domains["github.com"] == 2+ ) # Both www and non-www counted together++ def test_get_link_analytics_source_categorization(self):+ """Test correct categorization of sources."""+ resources = [+ MagicMock(+ url="https://arxiv.org/paper1",+ research_id="1",+ source_type=None,+ ),+ MagicMock(+ url="https://scholar.google.com/paper2",+ research_id="1",+ source_type=None,+ ),+ MagicMock(+ url="https://university.edu/research",+ research_id="1",+ source_type=None,+ ),+ MagicMock(+ url="https://cnn.com/news", research_id="1", source_type=None+ ),+ MagicMock(+ url="https://bbc.co.uk/article",+ research_id="1",+ source_type=None,+ ),+ MagicMock(+ url="https://wikipedia.org/topic",+ research_id="1",+ source_type=None,+ ),+ MagicMock(+ url="https://docs.python.org/3/",+ research_id="1",+ source_type=None,+ ),+ MagicMock(+ url="https://example.com/page",+ research_id="1",+ source_type=None,+ ),+ ]++ with patch(+ "src.local_deep_research.web.routes.metrics_routes.get_user_db_session"+ ) as mock_session:+ mock_db = MagicMock()+ mock_db.query.return_value.all.return_value = resources+ mock_session.return_value.__enter__.return_value = mock_db++ result = get_link_analytics(username="test_user")+ analytics = result["link_analytics"]++ source_types = analytics["academic_vs_general"]+ assert source_types["academic"] == 3 # arxiv, scholar, .edu+ assert source_types["news"] == 2 # cnn, bbc+ assert source_types["reference"] == 2 # wikipedia, docs+ assert source_types["general"] == 1 # example.com+++class TestLinkAnalyticsAPI:+ """Test link analytics API endpoints."""++ def test_api_link_analytics_no_session(self, client):+ """Test API without user session."""+ with patch(+ "src.local_deep_research.web.routes.metrics_routes.flask_session"+ ) as mock_session:+ mock_session.get.return_value = None++ response = client.get("/metrics/api/link-analytics")+ assert response.status_code == 401+ data = json.loads(response.data)+ assert data["status"] == "error"++ def test_api_link_analytics_success(self, client, mock_session):+ """Test successful API call."""+ with patch(+ "src.local_deep_research.web.routes.metrics_routes.get_link_analytics"+ ) as mock_analytics:+ mock_analytics.return_value = {+ "link_analytics": {+ "total_links": 100,+ "total_unique_domains": 25,+ "avg_links_per_research": 5.5,+ "top_domains": [+ {+ "domain": "example.com",+ "count": 20,+ "percentage": 20.0,+ }+ ],+ "domain_distribution": {"top_10": 80, "others": 20},+ "source_type_analysis": {},+ "academic_vs_general": {+ "academic": 30,+ "news": 20,+ "reference": 25,+ "general": 25,+ },+ "total_researches": 18,+ }+ }++ response = client.get("/metrics/api/link-analytics?period=30d")+ assert response.status_code == 200++ data = json.loads(response.data)+ assert data["status"] == "success"+ assert data["period"] == "30d"+ assert "data" in data+ assert data["data"]["total_links"] == 100++ def test_api_link_analytics_error_handling(self, client, mock_session):+ """Test API error handling."""+ with patch(+ "src.local_deep_research.web.routes.metrics_routes.get_link_analytics"+ ) as mock_analytics:+ mock_analytics.side_effect = Exception("Database error")++ response = client.get("/metrics/api/link-analytics")+ assert response.status_code == 500++ data = json.loads(response.data)+ assert data["status"] == "error"++ def test_link_analytics_page(self, client, mock_session):+ """Test link analytics page endpoint."""+ with patch(+ "src.local_deep_research.web.routes.metrics_routes.render_template_with_defaults"+ ) as mock_render:+ mock_render.return_value = "mocked template"++ response = client.get("/metrics/links")+ assert response.status_code == 200+ mock_render.assert_called_once_with("pages/link_analytics.html")+++class TestLinkAnalyticsHelpers:+ """Test helper functions for link analytics."""++ def test_average_calculation(self):+ """Test average links per research calculation."""+ resources = [+ MagicMock(+ url="https://example.com/1",+ research_id="research_1",+ source_type=None,+ ),+ MagicMock(+ url="https://example.com/2",+ research_id="research_1",+ source_type=None,+ ),+ MagicMock(+ url="https://example.com/3",+ research_id="research_2",+ source_type=None,+ ),+ MagicMock(+ url="https://example.com/4",+ research_id="research_2",+ source_type=None,+ ),+ MagicMock(+ url="https://example.com/5",+ research_id="research_2",+ source_type=None,+ ),+ ]++ with patch(+ "src.local_deep_research.web.routes.metrics_routes.get_user_db_session"+ ) as mock_session:+ mock_db = MagicMock()+ mock_db.query.return_value.all.return_value = resources+ mock_session.return_value.__enter__.return_value = mock_db++ result = get_link_analytics(username="test_user")+ analytics = result["link_analytics"]++ # 5 resources across 2 researches = 2.5 average+ assert analytics["avg_links_per_research"] == 2.5+ assert analytics["total_researches"] == 2++ def test_domain_distribution_calculation(self):+ """Test domain distribution calculation."""+ # Create resources with varying domain frequencies+ resources = []+ for i in range(15):+ if i < 8:+ domain = "popular.com"+ elif i < 12:+ domain = "medium.com"+ else:+ domain = f"other{i}.com"+ resources.append(+ MagicMock(+ url=f"https://{domain}/path",+ research_id="1",+ source_type=None,+ )+ )++ with patch(+ "src.local_deep_research.web.routes.metrics_routes.get_user_db_session"+ ) as mock_session:+ mock_db = MagicMock()+ mock_db.query.return_value.all.return_value = resources+ mock_session.return_value.__enter__.return_value = mock_db++ result = get_link_analytics(username="test_user")+ analytics = result["link_analytics"]++ # Check distribution+ distribution = analytics["domain_distribution"]+ assert distribution["top_10"] == 15 # All domains fit in top 10+ assert distribution["others"] == 0