File size: 6,406 Bytes
4848a6a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
#!/usr/bin/env python3

"""
Advanced features that can be added to the CASL Voice Bot application.
This module contains extensions that SLPs might want to add to the base system.
"""

import os
import pandas as pd
import datetime
import json
from pathlib import Path

class SessionRecorder:
    """Records session data for later analysis and progress tracking"""
    
    def __init__(self, storage_dir="session_data"):
        self.storage_dir = storage_dir
        Path(storage_dir).mkdir(exist_ok=True)
        self.current_session = {
            "timestamp": datetime.datetime.now().isoformat(),
            "student_id": None,
            "transcript": [],
            "assessment": {}
        }
    
    def set_student_id(self, student_id):
        """Set the student ID for the current session"""
        self.current_session["student_id"] = student_id
    
    def add_transcript_entry(self, speaker, text):
        """Add an entry to the transcript"""
        self.current_session["transcript"].append({
            "timestamp": datetime.datetime.now().isoformat(),
            "speaker": speaker,
            "text": text
        })
    
    def add_assessment_note(self, category, note):
        """Add an assessment note for a CASL-2 category"""
        if category not in self.current_session["assessment"]:
            self.current_session["assessment"][category] = []
        
        self.current_session["assessment"][category].append({
            "timestamp": datetime.datetime.now().isoformat(),
            "note": note
        })
    
    def save_session(self):
        """Save the current session to a JSON file"""
        student_id = self.current_session["student_id"] or "anonymous"
        timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"{student_id}_{timestamp}.json"
        
        with open(os.path.join(self.storage_dir, filename), 'w') as f:
            json.dump(self.current_session, f, indent=2)
        
        return filename


class CASLAnalyzer:
    """Analyzes transcripts based on CASL-2 framework categories"""
    
    def __init__(self):
        self.categories = {
            "lexical_semantic": {
                "description": "Vocabulary knowledge and word meanings",
                "keywords": ["synonym", "antonym", "vocabulary", "word choice", "meaning"]
            },
            "syntactic": {
                "description": "Grammar and sentence structure",
                "keywords": ["grammar", "sentence", "verb tense", "agreement", "structure"]
            },
            "supralinguistic": {
                "description": "Higher-level language skills",
                "keywords": ["inference", "figurative", "metaphor", "context", "implied"]
            },
            "pragmatic": {
                "description": "Social use of language",
                "keywords": ["conversation", "social", "turn-taking", "appropriate", "context"]
            }
        }
    
    def categorize_text(self, text):
        """Categorize text into CASL-2 framework categories"""
        result = {}
        
        for category, info in self.categories.items():
            score = 0
            for keyword in info["keywords"]:
                if keyword.lower() in text.lower():
                    score += 1
            
            if score > 0:
                result[category] = score
        
        return result
    
    def generate_summary(self, transcript):
        """Generate a summary of the transcript based on CASL-2 categories"""
        all_text = " ".join([entry["text"] for entry in transcript])
        categorization = self.categorize_text(all_text)
        
        summary = {
            "categories_covered": list(categorization.keys()),
            "focus_areas": sorted(categorization.items(), key=lambda x: x[1], reverse=True),
            "recommendations": []
        }
        
        # Generate recommendations based on categories covered
        for category in self.categories:
            if category not in categorization:
                summary["recommendations"].append(
                    f"Consider adding more {self.categories[category]['description']} exercises"
                )
        
        return summary


class VoiceMetricsAnalyzer:
    """Analyzes voice metrics for speech patterns"""
    
    def __init__(self):
        self.metrics = {
            "word_count": 0,
            "unique_words": set(),
            "sentence_count": 0,
            "average_words_per_sentence": 0,
            "hesitations": 0,
            "speech_rate": 0  # words per minute
        }
    
    def analyze_text(self, text, duration_seconds=None):
        """Analyze text for speech metrics"""
        # Count words
        words = text.split()
        self.metrics["word_count"] = len(words)
        self.metrics["unique_words"] = set(word.lower() for word in words)
        
        # Count sentences
        sentences = [s.strip() for s in text.replace("!", ".").replace("?", ".").split(".") if s.strip()]
        self.metrics["sentence_count"] = len(sentences)
        
        # Calculate average words per sentence
        if self.metrics["sentence_count"] > 0:
            self.metrics["average_words_per_sentence"] = self.metrics["word_count"] / self.metrics["sentence_count"]
        
        # Count hesitations ("um", "uh", "like", etc.)
        hesitation_markers = ["um", "uh", "er", "like", "you know"]
        self.metrics["hesitations"] = sum(1 for word in words if word.lower() in hesitation_markers)
        
        # Calculate speech rate if duration is provided
        if duration_seconds:
            self.metrics["speech_rate"] = (self.metrics["word_count"] / duration_seconds) * 60
        
        return self.metrics
    
    def get_summary(self):
        """Get a summary of the voice metrics analysis"""
        return {
            "word_count": self.metrics["word_count"],
            "vocabulary_diversity": len(self.metrics["unique_words"]) / max(1, self.metrics["word_count"]),
            "average_words_per_sentence": self.metrics["average_words_per_sentence"],
            "hesitation_frequency": self.metrics["hesitations"] / max(1, self.metrics["word_count"]),
            "speech_rate": self.metrics["speech_rate"]
        }


# These classes can be imported and used to extend the base CASL Voice Bot with additional features