Download src/apps/educa/services/learning_analytics.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 23.7 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/apps/educa/services/learning_analytics.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/src/apps/educa/services/learning_analytics.py
-
curl -L -o learning_analytics.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/apps/educa/services/learning_analytics.py
23.7 kB
| """ | |
| Educa Module - Learning Analytics Service | |
| Educational data analytics, outcome prediction, engagement analysis, | |
| content optimization, and personalized learning recommendations. | |
| Standards Compliance: | |
| - Learning Analytics Standards (IMS Global) | |
| - xAPI (Experience API / Tin Can API) | |
| - SCORM (Sharable Content Object Reference Model) | |
| - Educational Data Mining Standards | |
| - Learning Record Store (LRS) Specifications | |
| Features: | |
| - Predictive learning analytics | |
| - Engagement tracking and analysis | |
| - Learning outcome prediction | |
| - Content effectiveness analysis | |
| - Personalized learning recommendations | |
| - At-risk learner identification | |
| - Curriculum optimization insights | |
| - Learning pathway analytics | |
| """ | |
| from dataclasses import dataclass, field | |
| from datetime import datetime, timedelta | |
| from enum import Enum | |
| from typing import Any, Dict, List, Optional, Tuple | |
| import structlog | |
| from collections import defaultdict | |
| import math | |
| logger = structlog.get_logger(__name__) | |
| class EngagementLevel(Enum): | |
| """Learner engagement classification""" | |
| HIGHLY_ENGAGED = "highly_engaged" | |
| ENGAGED = "engaged" | |
| MODERATELY_ENGAGED = "moderately_engaged" | |
| DISENGAGED = "disengaged" | |
| AT_RISK = "at_risk" | |
| class ContentType(Enum): | |
| """Learning content types""" | |
| VIDEO = "video" | |
| READING = "reading" | |
| INTERACTIVE = "interactive" | |
| SIMULATION = "simulation" | |
| QUIZ = "quiz" | |
| DISCUSSION = "discussion" | |
| CASE_STUDY = "case_study" | |
| class LearningBehavior(Enum): | |
| """Learning behavior patterns""" | |
| CONSISTENT = "consistent" # Regular, steady progress | |
| BINGE = "binge" # Intensive bursts | |
| PROCRASTINATOR = "procrastinator" # Last-minute | |
| STRUGGLING = "struggling" # Multiple attempts, low scores | |
| HIGH_ACHIEVER = "high_achiever" # Exceeds expectations | |
| class LearningEvent: | |
| """Individual learning event (xAPI-style)""" | |
| event_id: str | |
| learner_id: str | |
| timestamp: datetime | |
| verb: str # viewed, completed, attempted, passed, failed | |
| object_type: ContentType | |
| object_id: str | |
| duration_seconds: int = 0 | |
| score: Optional[float] = None | |
| completion: bool = False | |
| context: Dict[str, Any] = field(default_factory=dict) | |
| class EngagementMetrics: | |
| """Learner engagement metrics""" | |
| learner_id: str | |
| period_start: datetime | |
| period_end: datetime | |
| total_time_minutes: int = 0 | |
| sessions_count: int = 0 | |
| content_items_accessed: int = 0 | |
| completion_rate: float = 0.0 | |
| average_session_length_minutes: float = 0.0 | |
| days_active: int = 0 | |
| engagement_level: EngagementLevel = EngagementLevel.MODERATELY_ENGAGED | |
| last_activity: Optional[datetime] = None | |
| class ContentEffectiveness: | |
| """Content effectiveness analysis""" | |
| content_id: str | |
| content_type: ContentType | |
| total_views: int = 0 | |
| unique_learners: int = 0 | |
| average_completion_rate: float = 0.0 | |
| average_time_spent_minutes: float = 0.0 | |
| average_score: Optional[float] = None | |
| engagement_rate: float = 0.0 | |
| effectiveness_score: float = 0.0 # Composite 0-100 | |
| recommendations: List[str] = field(default_factory=list) | |
| class LearnerProfile: | |
| """Detailed learner analytics profile""" | |
| learner_id: str | |
| learning_behavior: LearningBehavior | |
| preferred_content_types: List[ContentType] = field(default_factory=list) | |
| peak_learning_times: List[int] = field(default_factory=list) # Hours of day | |
| average_score: float = 0.0 | |
| completion_rate: float = 0.0 | |
| at_risk: bool = False | |
| risk_factors: List[str] = field(default_factory=list) | |
| strengths: List[str] = field(default_factory=list) | |
| last_updated: datetime = field(default_factory=datetime.now) | |
| class PredictedOutcome: | |
| """Predicted learning outcome""" | |
| learner_id: str | |
| course_id: str | |
| predicted_score: float | |
| predicted_completion_probability: float | |
| confidence_level: float # 0-1 | |
| risk_level: str # low, medium, high | |
| contributing_factors: Dict[str, float] = field(default_factory=dict) | |
| recommended_interventions: List[str] = field(default_factory=list) | |
| class PersonalizedRecommendation: | |
| """Personalized learning recommendation""" | |
| recommendation_id: str | |
| learner_id: str | |
| content_id: str | |
| content_type: ContentType | |
| relevance_score: float # 0-1 | |
| reason: str | |
| estimated_time_minutes: int | |
| predicted_benefit: float # Expected improvement | |
| priority: str # high, medium, low | |
| class LearningAnalyticsService: | |
| """ | |
| Learning Analytics Service | |
| Provides educational data analytics, engagement tracking, outcome prediction, | |
| and personalized recommendations for medical education. | |
| """ | |
| def __init__(self): | |
| self.learning_events: Dict[str, LearningEvent] = {} | |
| self.engagement_metrics: Dict[str, EngagementMetrics] = {} | |
| self.content_effectiveness: Dict[str, ContentEffectiveness] = {} | |
| self.learner_profiles: Dict[str, LearnerProfile] = {} | |
| self.predicted_outcomes: Dict[str, PredictedOutcome] = {} | |
| self.recommendations: Dict[str, PersonalizedRecommendation] = {} | |
| def track_learning_event( | |
| self, | |
| learner_id: str, | |
| verb: str, | |
| object_type: ContentType, | |
| object_id: str, | |
| duration_seconds: int = 0, | |
| score: Optional[float] = None, | |
| completion: bool = False, | |
| context: Optional[Dict[str, Any]] = None | |
| ) -> LearningEvent: | |
| """Track learning event (xAPI-style)""" | |
| event_id = f"EVT-{datetime.now().strftime('%Y%m%d%H%M%S%f')}" | |
| event = LearningEvent( | |
| event_id=event_id, | |
| learner_id=learner_id, | |
| timestamp=datetime.now(), | |
| verb=verb, | |
| object_type=object_type, | |
| object_id=object_id, | |
| duration_seconds=duration_seconds, | |
| score=score, | |
| completion=completion, | |
| context=context or {} | |
| ) | |
| self.learning_events[event_id] = event | |
| # Update engagement metrics asynchronously (in production) | |
| self._update_engagement_metrics(learner_id) | |
| # Update content effectiveness | |
| self._update_content_effectiveness(object_id, object_type) | |
| logger.info("tracked_learning_event", learner_id=learner_id, verb=verb, value=object_type.value) | |
| return event | |
| def _update_engagement_metrics(self, learner_id: str): | |
| """Update engagement metrics for learner""" | |
| # Get recent events (last 30 days) | |
| thirty_days_ago = datetime.now() - timedelta(days=30) | |
| learner_events = [ | |
| e for e in self.learning_events.values() | |
| if e.learner_id == learner_id and e.timestamp >= thirty_days_ago | |
| ] | |
| if not learner_events: | |
| return | |
| # Calculate metrics | |
| total_time = sum(e.duration_seconds for e in learner_events) // 60 # Convert to minutes | |
| # Count sessions (gap > 30 minutes = new session) | |
| sorted_events = sorted(learner_events, key=lambda x: x.timestamp) | |
| sessions = 1 | |
| for i in range(1, len(sorted_events)): | |
| time_gap = (sorted_events[i].timestamp - sorted_events[i-1].timestamp).total_seconds() | |
| if time_gap > 1800: # 30 minutes | |
| sessions += 1 | |
| # Content items accessed | |
| content_items = len(set(e.object_id for e in learner_events)) | |
| # Completion rate | |
| completable_events = [e for e in learner_events if e.verb in ['attempted', 'completed']] | |
| completed_events = [e for e in completable_events if e.completion] | |
| completion_rate = (len(completed_events) / len(completable_events) * 100) if completable_events else 0 | |
| # Days active | |
| unique_days = len(set(e.timestamp.date() for e in learner_events)) | |
| # Average session length | |
| avg_session_length = total_time / sessions if sessions > 0 else 0 | |
| # Determine engagement level | |
| engagement_level = self._calculate_engagement_level( | |
| total_time, sessions, completion_rate, unique_days | |
| ) | |
| # Last activity | |
| last_activity = max(e.timestamp for e in learner_events) | |
| metrics = EngagementMetrics( | |
| learner_id=learner_id, | |
| period_start=thirty_days_ago, | |
| period_end=datetime.now(), | |
| total_time_minutes=total_time, | |
| sessions_count=sessions, | |
| content_items_accessed=content_items, | |
| completion_rate=completion_rate, | |
| average_session_length_minutes=avg_session_length, | |
| days_active=unique_days, | |
| engagement_level=engagement_level, | |
| last_activity=last_activity | |
| ) | |
| self.engagement_metrics[learner_id] = metrics | |
| def _calculate_engagement_level( | |
| self, | |
| total_time: int, | |
| sessions: int, | |
| completion_rate: float, | |
| days_active: int | |
| ) -> EngagementLevel: | |
| """Calculate engagement level classification""" | |
| # Scoring algorithm | |
| time_score = min(total_time / 300, 10) # Target 300 min/month | |
| session_score = min(sessions / 20, 10) # Target 20 sessions/month | |
| completion_score = completion_rate / 10 # 0-100 -> 0-10 | |
| consistency_score = min(days_active / 20, 10) # Target 20 days/month | |
| total_score = (time_score + session_score + completion_score + consistency_score) / 4 | |
| if total_score >= 8: | |
| return EngagementLevel.HIGHLY_ENGAGED | |
| elif total_score >= 6: | |
| return EngagementLevel.ENGAGED | |
| elif total_score >= 4: | |
| return EngagementLevel.MODERATELY_ENGAGED | |
| elif total_score >= 2: | |
| return EngagementLevel.DISENGAGED | |
| else: | |
| return EngagementLevel.AT_RISK | |
| def _update_content_effectiveness(self, content_id: str, content_type: ContentType): | |
| """Update content effectiveness metrics""" | |
| # Get all events for this content | |
| content_events = [ | |
| e for e in self.learning_events.values() | |
| if e.object_id == content_id | |
| ] | |
| if not content_events: | |
| return | |
| # Calculate metrics | |
| total_views = len([e for e in content_events if e.verb == 'viewed']) | |
| unique_learners = len(set(e.learner_id for e in content_events)) | |
| # Completion rate | |
| completable = [e for e in content_events if e.verb in ['attempted', 'completed']] | |
| completed = [e for e in completable if e.completion] | |
| completion_rate = (len(completed) / len(completable) * 100) if completable else 0 | |
| # Average time spent | |
| timed_events = [e for e in content_events if e.duration_seconds > 0] | |
| avg_time = sum(e.duration_seconds for e in timed_events) / len(timed_events) / 60 if timed_events else 0 | |
| # Average score | |
| scored_events = [e for e in content_events if e.score is not None] | |
| avg_score = sum(e.score for e in scored_events) / len(scored_events) if scored_events else None # type: ignore[attr-defined, misc, dict-item, abstract, type-var, union-attr] | |
| # Engagement rate (return viewers) | |
| learner_event_counts = {} # type: ignore[name-defined, index, return-value, var-annotated] | |
| for event in content_events: | |
| learner_event_counts[event.learner_id] = learner_event_counts.get(event.learner_id, 0) + 1 | |
| return_viewers = sum(1 for count in learner_event_counts.values() if count > 1) | |
| engagement_rate = (return_viewers / unique_learners * 100) if unique_learners > 0 else 0 | |
| # Calculate effectiveness score (composite) | |
| effectiveness_score = self._calculate_effectiveness_score( | |
| completion_rate, avg_score, engagement_rate | |
| ) | |
| # Generate recommendations | |
| recommendations = [] | |
| if completion_rate < 50: | |
| recommendations.append("Low completion rate - consider breaking into smaller segments") | |
| if avg_score and avg_score < 70: | |
| recommendations.append("Low average score - review content clarity and difficulty") | |
| if engagement_rate < 30: | |
| recommendations.append("Low engagement - add interactive elements") | |
| effectiveness = ContentEffectiveness( | |
| content_id=content_id, | |
| content_type=content_type, | |
| total_views=total_views, | |
| unique_learners=unique_learners, | |
| average_completion_rate=completion_rate, | |
| average_time_spent_minutes=avg_time, | |
| average_score=avg_score, | |
| engagement_rate=engagement_rate, | |
| effectiveness_score=effectiveness_score, | |
| recommendations=recommendations | |
| ) | |
| self.content_effectiveness[content_id] = effectiveness | |
| def _calculate_effectiveness_score( | |
| self, | |
| completion_rate: float, | |
| avg_score: Optional[float], | |
| engagement_rate: float | |
| ) -> float: | |
| """Calculate composite effectiveness score (0-100)""" | |
| # Weighted scoring | |
| completion_component = completion_rate * 0.4 | |
| engagement_component = engagement_rate * 0.3 | |
| score_component = (avg_score if avg_score else 75) * 0.3 # Default 75 if no scores | |
| effectiveness = completion_component + engagement_component + score_component | |
| return round(effectiveness, 1) | |
| def predict_learning_outcome( | |
| self, | |
| learner_id: str, | |
| course_id: str | |
| ) -> PredictedOutcome: | |
| """Predict learning outcome using analytics""" | |
| # Get learner engagement metrics | |
| engagement = self.engagement_metrics.get(learner_id) | |
| # Get learner profile | |
| profile = self.learner_profiles.get(learner_id) | |
| # Baseline prediction | |
| predicted_score = 75.0 # Default | |
| completion_probability = 0.7 # Default | |
| # Adjust based on engagement | |
| if engagement: | |
| if engagement.engagement_level == EngagementLevel.HIGHLY_ENGAGED: | |
| predicted_score += 10 | |
| completion_probability += 0.2 | |
| elif engagement.engagement_level == EngagementLevel.AT_RISK: | |
| predicted_score -= 15 | |
| completion_probability -= 0.3 | |
| # Completion rate factor | |
| completion_factor = (engagement.completion_rate - 70) / 10 | |
| predicted_score += completion_factor * 5 | |
| # Adjust based on profile | |
| if profile: | |
| predicted_score = (predicted_score + profile.average_score) / 2 | |
| if profile.at_risk: | |
| completion_probability -= 0.2 | |
| # Cap values | |
| predicted_score = max(0, min(100, predicted_score)) | |
| completion_probability = max(0, min(1, completion_probability)) | |
| # Determine risk level | |
| if completion_probability < 0.5 or predicted_score < 60: | |
| risk_level = "high" | |
| elif completion_probability < 0.7 or predicted_score < 75: | |
| risk_level = "medium" | |
| else: | |
| risk_level = "low" | |
| # Contributing factors | |
| factors = { | |
| 'engagement_level': 0.4, | |
| 'prior_performance': 0.3, | |
| 'completion_history': 0.2, | |
| 'time_management': 0.1 | |
| } | |
| # Recommendations | |
| interventions = [] | |
| if risk_level in ['medium', 'high']: | |
| interventions.append("Schedule check-in with advisor") | |
| interventions.append("Provide additional study resources") | |
| if engagement and engagement.sessions_count < 10: | |
| interventions.append("Encourage more frequent study sessions") | |
| prediction = PredictedOutcome( | |
| learner_id=learner_id, | |
| course_id=course_id, | |
| predicted_score=predicted_score, | |
| predicted_completion_probability=completion_probability, | |
| confidence_level=0.75, # Would be calculated from historical accuracy | |
| risk_level=risk_level, | |
| contributing_factors=factors, | |
| recommended_interventions=interventions | |
| ) | |
| prediction_id = f"{learner_id}-{course_id}" | |
| self.predicted_outcomes[prediction_id] = prediction | |
| logger.info(f"Predicted outcome for {learner_id}: {predicted_score:.1f} score, {risk_level} risk") | |
| return prediction | |
| def generate_recommendations( | |
| self, | |
| learner_id: str, | |
| limit: int = 5 | |
| ) -> List[PersonalizedRecommendation]: | |
| """Generate personalized content recommendations""" | |
| # Get learner profile | |
| profile = self.learner_profiles.get(learner_id) | |
| # Get engagement metrics | |
| engagement = self.engagement_metrics.get(learner_id) | |
| # Get learner's completed content | |
| learner_events = [ | |
| e for e in self.learning_events.values() | |
| if e.learner_id == learner_id and e.completion | |
| ] | |
| completed_content = set(e.object_id for e in learner_events) | |
| recommendations = [] | |
| # Find effective content not yet completed | |
| for content_id, effectiveness in self.content_effectiveness.items(): | |
| if content_id in completed_content: | |
| continue | |
| # Calculate relevance score | |
| relevance = effectiveness.effectiveness_score / 100 | |
| # Adjust for learner preferences | |
| if profile and effectiveness.content_type in profile.preferred_content_types: | |
| relevance += 0.2 | |
| # Cap relevance | |
| relevance = min(1.0, relevance) | |
| # Determine reason | |
| reason = f"High-performing content ({effectiveness.effectiveness_score:.0f}% effectiveness)" | |
| if profile and effectiveness.content_type in profile.preferred_content_types: | |
| reason += " matching your learning style" | |
| # Estimated benefit (simplified) | |
| predicted_benefit = relevance * 10 # 0-10 point improvement | |
| # Priority | |
| if relevance >= 0.8: | |
| priority = "high" | |
| elif relevance >= 0.6: | |
| priority = "medium" | |
| else: | |
| priority = "low" | |
| rec_id = f"REC-{learner_id}-{content_id}" | |
| recommendation = PersonalizedRecommendation( | |
| recommendation_id=rec_id, | |
| learner_id=learner_id, | |
| content_id=content_id, | |
| content_type=effectiveness.content_type, | |
| relevance_score=relevance, | |
| reason=reason, | |
| estimated_time_minutes=int(effectiveness.average_time_spent_minutes), | |
| predicted_benefit=predicted_benefit, | |
| priority=priority | |
| ) | |
| recommendations.append(recommendation) | |
| self.recommendations[rec_id] = recommendation | |
| # Sort by relevance and return top N | |
| recommendations.sort(key=lambda x: x.relevance_score, reverse=True) | |
| logger.info(f"Generated {len(recommendations[:limit])} recommendations for {learner_id}") | |
| return recommendations[:limit] | |
| def identify_at_risk_learners( | |
| self, | |
| threshold_days_inactive: int = 7 | |
| ) -> List[Dict[str, Any]]: | |
| """Identify learners at risk of not completing""" | |
| at_risk = [] | |
| now = datetime.now() | |
| for learner_id, engagement in self.engagement_metrics.items(): | |
| risk_factors = [] | |
| # Check engagement level | |
| if engagement.engagement_level in [EngagementLevel.DISENGAGED, EngagementLevel.AT_RISK]: | |
| risk_factors.append(f"Low engagement: {engagement.engagement_level.value}") | |
| # Check inactivity | |
| if engagement.last_activity: | |
| days_inactive = (now - engagement.last_activity).days | |
| if days_inactive >= threshold_days_inactive: | |
| risk_factors.append(f"Inactive for {days_inactive} days") | |
| # Check completion rate | |
| if engagement.completion_rate < 50: | |
| risk_factors.append(f"Low completion rate: {engagement.completion_rate:.1f}%") | |
| # If any risk factors, add to list | |
| if risk_factors: | |
| at_risk.append({ | |
| 'learner_id': learner_id, | |
| 'risk_level': 'high' if len(risk_factors) >= 2 else 'medium', | |
| 'risk_factors': risk_factors, | |
| 'last_activity': engagement.last_activity, | |
| 'recommended_actions': [ | |
| "Send re-engagement email", | |
| "Schedule advisor meeting", | |
| "Provide motivational content" | |
| ] | |
| }) | |
| # Sort by risk level | |
| at_risk.sort(key=lambda x: len(x['risk_factors']), reverse=True) # type: ignore[arg-type, assignment] | |
| logger.info(f"Identified {len(at_risk)} at-risk learners") | |
| return at_risk | |
| def get_analytics_dashboard( | |
| self, | |
| learner_id: str | |
| ) -> Dict[str, Any]: | |
| """Generate comprehensive analytics dashboard""" | |
| engagement = self.engagement_metrics.get(learner_id) | |
| profile = self.learner_profiles.get(learner_id) | |
| # Get predictions | |
| learner_predictions = [ | |
| pred for pred in self.predicted_outcomes.values() | |
| if pred.learner_id == learner_id | |
| ] | |
| # Get recommendations | |
| learner_recs = [ | |
| rec for rec in self.recommendations.values() | |
| if rec.learner_id == learner_id | |
| ] | |
| dashboard = { | |
| 'learner_id': learner_id, | |
| 'engagement': { | |
| 'level': engagement.engagement_level.value if engagement else 'unknown', | |
| 'total_time_hours': engagement.total_time_minutes / 60 if engagement else 0, | |
| 'sessions': engagement.sessions_count if engagement else 0, | |
| 'completion_rate': engagement.completion_rate if engagement else 0, | |
| 'days_active': engagement.days_active if engagement else 0 | |
| }, | |
| 'profile': { | |
| 'learning_behavior': profile.learning_behavior.value if profile else 'unknown', | |
| 'average_score': profile.average_score if profile else 0, | |
| 'at_risk': profile.at_risk if profile else False | |
| }, | |
| 'predictions': [ | |
| { | |
| 'course_id': pred.course_id, | |
| 'predicted_score': pred.predicted_score, | |
| 'risk_level': pred.risk_level | |
| } | |
| for pred in learner_predictions | |
| ], | |
| 'recommendations': [ | |
| { | |
| 'content_id': rec.content_id, | |
| 'priority': rec.priority, | |
| 'relevance': rec.relevance_score | |
| } | |
| for rec in sorted(learner_recs, key=lambda x: x.relevance_score, reverse=True)[:3] | |
| ] | |
| } | |
| return dashboard | |