SreekarB commited on
Commit
1c40afa
·
verified ·
1 Parent(s): 6f481da

Upload 2 files

Browse files
Files changed (2) hide show
  1. copy_of_casl_analysis.py +1230 -0
  2. requirements.txt +7 -0
copy_of_casl_analysis.py ADDED
@@ -0,0 +1,1230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import boto3
3
+ import json
4
+ import pandas as pd
5
+ import matplotlib.pyplot as plt
6
+ import numpy as np
7
+ import re
8
+ import logging
9
+ import os
10
+ from PIL import Image
11
+ import io
12
+ import PyPDF2
13
+ from datetime import datetime
14
+
15
+ # Configure logging
16
+ logging.basicConfig(level=logging.INFO)
17
+ logger = logging.getLogger(__name__)
18
+
19
+ # AWS credentials for Bedrock API
20
+ # For HuggingFace Spaces, set these as secrets in the Space settings
21
+ AWS_ACCESS_KEY = os.getenv("AWS_ACCESS_KEY", "")
22
+ AWS_SECRET_KEY = os.getenv("AWS_SECRET_KEY", "")
23
+ AWS_REGION = os.getenv("AWS_REGION", "us-east-1")
24
+
25
+ # Initialize Bedrock client if credentials are available
26
+ bedrock_client = None
27
+ if AWS_ACCESS_KEY and AWS_SECRET_KEY:
28
+ try:
29
+ bedrock_client = boto3.client(
30
+ 'bedrock-runtime',
31
+ aws_access_key_id=AWS_ACCESS_KEY,
32
+ aws_secret_access_key=AWS_SECRET_KEY,
33
+ region_name=AWS_REGION
34
+ )
35
+ logger.info("Bedrock client initialized successfully")
36
+ except Exception as e:
37
+ logger.error(f"Failed to initialize Bedrock client: {str(e)}")
38
+
39
+ # Sample transcript for the demo
40
+ SAMPLE_TRANSCRIPT = """*PAR: today I would &-um like to talk about &-um a fun trip I took last &-um summer with my family.
41
+ *PAR: we went to the &-um &-um beach [//] no to the mountains [//] I mean the beach actually.
42
+ *PAR: there was lots of &-um &-um swimming and &-um sun.
43
+ *PAR: we [/] we stayed for &-um three no [//] four days in a &-um hotel near the water [: ocean] [*].
44
+ *PAR: my favorite part was &-um building &-um castles with sand.
45
+ *PAR: sometimes I forget [//] forgetted [: forgot] [*] what they call those things we built.
46
+ *PAR: my brother he [//] he helped me dig a big hole.
47
+ *PAR: we saw [/] saw fishies [: fish] [*] swimming in the water.
48
+ *PAR: sometimes I wonder [/] wonder where fishies [: fish] [*] go when it's cold.
49
+ *PAR: maybe they have [/] have houses under the water.
50
+ *PAR: after swimming we [//] I eat [: ate] [*] &-um ice cream with &-um chocolate things on top.
51
+ *PAR: what do you call those &-um &-um sprinkles! that's the word.
52
+ *PAR: my mom said to &-um that I could have &-um two scoops next time.
53
+ *PAR: I want to go back to the beach [/] beach next year."""
54
+
55
+ # ===============================
56
+ # Utility Functions
57
+ # ===============================
58
+
59
+ def read_pdf(file_path):
60
+ """Read text from a PDF file"""
61
+ try:
62
+ with open(file_path, 'rb') as file:
63
+ pdf_reader = PyPDF2.PdfReader(file)
64
+ text = ""
65
+ for page in pdf_reader.pages:
66
+ text += page.extract_text()
67
+ return text
68
+ except Exception as e:
69
+ logger.error(f"Error reading PDF: {str(e)}")
70
+ return ""
71
+
72
+ def process_upload(file):
73
+ """Process an uploaded file (PDF or text)"""
74
+ if file is None:
75
+ return ""
76
+
77
+ file_path = file.name
78
+ if file_path.endswith('.pdf'):
79
+ return read_pdf(file_path)
80
+ else:
81
+ with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
82
+ return f.read()
83
+
84
+ # ===============================
85
+ # AI Model Interface Functions
86
+ # ===============================
87
+
88
+ def call_bedrock(prompt, max_tokens=4096):
89
+ """Call the AWS Bedrock API to analyze text using Claude"""
90
+ if not bedrock_client:
91
+ return "AWS credentials not configured. Please set your AWS credentials as secrets in the Space settings."
92
+
93
+ try:
94
+ body = json.dumps({
95
+ "anthropic_version": "bedrock-2023-05-31",
96
+ "max_tokens": max_tokens,
97
+ "messages": [
98
+ {
99
+ "role": "user",
100
+ "content": prompt
101
+ }
102
+ ],
103
+ "temperature": 0.3,
104
+ "top_p": 0.9
105
+ })
106
+
107
+ modelId = 'anthropic.claude-3-sonnet-20240229-v1:0'
108
+ response = bedrock_client.invoke_model(
109
+ body=body,
110
+ modelId=modelId,
111
+ accept='application/json',
112
+ contentType='application/json'
113
+ )
114
+ response_body = json.loads(response.get('body').read())
115
+ return response_body['content'][0]['text']
116
+ except Exception as e:
117
+ logger.error(f"Error in call_bedrock: {str(e)}")
118
+ return f"Error: {str(e)}"
119
+
120
+ def generate_demo_response(prompt):
121
+ """Generate a simulated response for demo purposes"""
122
+ # This function generates a realistic but fake response for demo purposes
123
+ # In a real deployment, you would call an actual LLM API
124
+
125
+ random_seed = sum(ord(c) for c in prompt) % 1000 # Generate a seed based on prompt
126
+ np.random.seed(random_seed)
127
+
128
+ # Simulate speech factors with random but reasonable values
129
+ factors = [
130
+ "Difficulty producing fluent speech",
131
+ "Word retrieval issues",
132
+ "Grammatical errors",
133
+ "Repetitions and revisions",
134
+ "Neologisms",
135
+ "Perseveration",
136
+ "Comprehension issues"
137
+ ]
138
+
139
+ occurrences = np.random.randint(1, 15, size=len(factors))
140
+ percentiles = np.random.randint(30, 95, size=len(factors))
141
+
142
+ # Simulate CASL scores
143
+ domains = ["Lexical/Semantic", "Syntactic", "Supralinguistic"]
144
+ scores = np.random.randint(80, 115, size=3)
145
+ percentiles_casl = [int(np.interp(s, [70, 85, 100, 115, 130], [2, 16, 50, 84, 98])) for s in scores]
146
+
147
+ perf_levels = []
148
+ for s in scores:
149
+ if s < 70: perf_levels.append("Well Below Average")
150
+ elif s < 85: perf_levels.append("Below Average")
151
+ elif s < 115: perf_levels.append("Average")
152
+ elif s < 130: perf_levels.append("Above Average")
153
+ else: perf_levels.append("Well Above Average")
154
+
155
+ # Build response
156
+ response = "## Speech Factor Analysis\n\n"
157
+ for i, factor in enumerate(factors):
158
+ response += f"{factor}: {occurrences[i]}, {percentiles[i]}\n"
159
+
160
+ response += "\n## CASL-2 Assessment\n\n"
161
+ for i, domain in enumerate(domains):
162
+ response += f"{domain} Skills: Standard Score ({scores[i]}), Percentile Rank ({percentiles_casl[i]}%), Performance Level ({perf_levels[i]})\n"
163
+
164
+ response += "\n## Other analysis/Best plans of action:\n\n"
165
+ suggestions = [
166
+ "Implement word-finding strategies with semantic cuing",
167
+ "Practice structured narrative tasks with visual supports",
168
+ "Use sentence formulation exercises with increasing complexity",
169
+ "Incorporate self-monitoring techniques during structured conversations",
170
+ "Work on grammatical forms through structured practice"
171
+ ]
172
+ for suggestion in suggestions:
173
+ response += f"- {suggestion}\n"
174
+
175
+ response += "\n## Explanation:\n\n"
176
+ response += "Based on the analysis, this patient demonstrates moderate word-finding difficulties with compensatory strategies like filler words and repetitions. Their syntactic skills show some weakness in verb tense consistency. Treatment should focus on building vocabulary access, grammatical accuracy, and narrative structure using scaffolded support.\n"
177
+
178
+ response += "\n## Additional Analysis:\n\n"
179
+ response += "The patient shows relative strengths in conversation maintenance and topic coherence. Consider building on these strengths while addressing specific language formulation challenges. Recommended frequency: 2-3 sessions per week for 10-12 weeks with periodic reassessment."
180
+
181
+ return response
182
+
183
+ def generate_demo_transcription(audio_path):
184
+ """Generate a simulated transcription response"""
185
+ # In a real app, this would process an audio file
186
+ return "*PAR: today I want to tell you about my favorite toy.\n*PAR: it's a &-um teddy bear that I got for my birthday.\n*PAR: he has &-um brown fur and a red bow.\n*PAR: I like to sleep with him every night.\n*PAR: sometimes I take him to school in my backpack."
187
+
188
+ def generate_demo_qa_response(question):
189
+ """Generate a simulated Q&A response"""
190
+ qa_responses = {
191
+ "what is casl": "CASL-2 (Comprehensive Assessment of Spoken Language, Second Edition) is a standardized assessment tool used by Speech-Language Pathologists to evaluate a child's oral language abilities across multiple domains including lexical/semantic, syntactic, and supralinguistic skills. It helps identify language disorders and guides intervention planning.",
192
+ "how do i interpret scores": "CASL-2 scores include standard scores (mean=100, SD=15), percentile ranks, and performance levels. Standard scores below 85 indicate below average performance, 85-115 is average, and above 115 is above average. Percentile ranks show how a child performs relative to same-age peers.",
193
+ "what activities help word finding": "Activities to improve word-finding skills include semantic feature analysis (describing attributes of objects), categorization tasks, word association games, rapid naming practice, and structured conversation with gentle cueing. Visual supports and semantic mapping can also be helpful.",
194
+ "how often should therapy occur": "The recommended frequency for speech-language therapy typically ranges from 1-3 sessions per week, depending on the severity of the impairment. For moderate difficulties, twice weekly sessions of 30-45 minutes are common. Consistency is important for progress.",
195
+ "when should i reassess": "Reassessment is typically recommended every 3-6 months to track progress and adjust treatment goals. For educational settings, annual reassessment is common. More frequent informal assessments can help guide ongoing intervention.",
196
+ }
197
+
198
+ # Simple keyword matching for demo purposes
199
+ for key, response in qa_responses.items():
200
+ if key in question.lower():
201
+ return response
202
+
203
+ return "I don't have specific information about that topic. For detailed professional guidance, consult with a licensed Speech-Language Pathologist who can provide advice specific to your situation."
204
+
205
+ # ===============================
206
+ # Analysis Functions
207
+ # ===============================
208
+
209
+ def parse_casl_response(response):
210
+ """Parse the LLM response for CASL analysis into structured data"""
211
+ lines = response.split('\n')
212
+ data = {
213
+ 'Factor': [],
214
+ 'Occurrences': [],
215
+ 'Severity': []
216
+ }
217
+
218
+ casl_data = {
219
+ 'Domain': ['Lexical/Semantic', 'Syntactic', 'Supralinguistic'],
220
+ 'Standard Score': [0, 0, 0],
221
+ 'Percentile': [0, 0, 0],
222
+ 'Performance Level': ['', '', '']
223
+ }
224
+
225
+ treatment_suggestions = []
226
+ explanation = ""
227
+ additional_analysis = ""
228
+
229
+ # Pattern to match factor lines
230
+ factor_pattern = re.compile(r'([\w\s/]+):\s*(\d+)[,\s]+(\d+)')
231
+
232
+ # Pattern to match CASL data
233
+ casl_pattern = re.compile(r'(\w+/?\w*)\s+Skills:\s+Standard\s+Score\s+\((\d+)\),\s+Percentile\s+Rank\s+\((\d+)%\),\s+Performance\s+Level\s+\(([\w\s]+)\)')
234
+
235
+ in_suggestions = False
236
+ in_explanation = False
237
+ in_additional = False
238
+
239
+ for line in lines:
240
+ line = line.strip()
241
+
242
+ # Skip empty lines
243
+ if not line:
244
+ continue
245
+
246
+ # Check for factor data
247
+ factor_match = factor_pattern.search(line)
248
+ if factor_match:
249
+ factor = factor_match.group(1).strip()
250
+ occurrences = int(factor_match.group(2))
251
+ severity = int(factor_match.group(3))
252
+
253
+ data['Factor'].append(factor)
254
+ data['Occurrences'].append(occurrences)
255
+ data['Severity'].append(severity)
256
+ continue
257
+
258
+ # Check for CASL data
259
+ casl_match = casl_pattern.search(line)
260
+ if casl_match:
261
+ domain = casl_match.group(1)
262
+ score = int(casl_match.group(2))
263
+ percentile = int(casl_match.group(3))
264
+ level = casl_match.group(4)
265
+
266
+ if "Lexical" in domain:
267
+ casl_data['Standard Score'][0] = score
268
+ casl_data['Percentile'][0] = percentile
269
+ casl_data['Performance Level'][0] = level
270
+ elif "Syntactic" in domain:
271
+ casl_data['Standard Score'][1] = score
272
+ casl_data['Percentile'][1] = percentile
273
+ casl_data['Performance Level'][1] = level
274
+ elif "Supralinguistic" in domain:
275
+ casl_data['Standard Score'][2] = score
276
+ casl_data['Percentile'][2] = percentile
277
+ casl_data['Performance Level'][2] = level
278
+ continue
279
+
280
+ # Check for section headers
281
+ if "Other analysis/Best plans of action:" in line or "### Recommended Treatment Approaches" in line:
282
+ in_suggestions = True
283
+ in_explanation = False
284
+ in_additional = False
285
+ continue
286
+ elif "Explanation:" in line or "### Clinical Rationale" in line:
287
+ in_suggestions = False
288
+ in_explanation = True
289
+ in_additional = False
290
+ continue
291
+ elif "Additional Analysis:" in line:
292
+ in_suggestions = False
293
+ in_explanation = False
294
+ in_additional = True
295
+ continue
296
+
297
+ # Add content to appropriate section
298
+ if in_suggestions and line.startswith("- "):
299
+ treatment_suggestions.append(line[2:]) # Remove the bullet point
300
+ elif in_explanation:
301
+ explanation += line + "\n"
302
+ elif in_additional:
303
+ additional_analysis += line + "\n"
304
+
305
+ return {
306
+ 'speech_factors': pd.DataFrame(data),
307
+ 'casl_data': pd.DataFrame(casl_data),
308
+ 'treatment_suggestions': treatment_suggestions,
309
+ 'explanation': explanation,
310
+ 'additional_analysis': additional_analysis
311
+ }
312
+
313
+ def create_casl_plots(speech_factors, casl_data):
314
+ """Create visualizations for the CASL analysis results"""
315
+
316
+ # Set a professional style for the plots
317
+ plt.style.use('seaborn-v0_8-pastel')
318
+
319
+ # Create figure with two subplots
320
+ fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 6), dpi=100)
321
+
322
+ # Plot speech factors - sorted by occurrence count
323
+ if not speech_factors.empty:
324
+ # Sort the dataframe
325
+ speech_factors_sorted = speech_factors.sort_values('Occurrences', ascending=False)
326
+
327
+ # Custom colors
328
+ speech_colors = ['#4C72B0', '#55A868', '#C44E52', '#8172B3', '#CCB974', '#64B5CD', '#4C72B0']
329
+
330
+ # Create horizontal bar chart
331
+ bars = ax1.barh(speech_factors_sorted['Factor'],
332
+ speech_factors_sorted['Occurrences'],
333
+ color=speech_colors[:len(speech_factors_sorted)])
334
+
335
+ # Add count labels at the end of each bar
336
+ for bar in bars:
337
+ width = bar.get_width()
338
+ ax1.text(width + 0.3, bar.get_y() + bar.get_height()/2,
339
+ f'{width:.0f}', ha='left', va='center')
340
+
341
+ ax1.set_title('Speech Factors Analysis', fontsize=14, fontweight='bold')
342
+ ax1.set_xlabel('Number of Occurrences', fontsize=11)
343
+ # No y-label needed for horizontal bar chart
344
+
345
+ # Remove top and right spines
346
+ ax1.spines['top'].set_visible(False)
347
+ ax1.spines['right'].set_visible(False)
348
+
349
+ # Plot CASL domains
350
+ domain_names = casl_data['Domain']
351
+ y_scores = casl_data['Standard Score']
352
+
353
+ # Custom color scheme
354
+ casl_colors = ['#4C72B0', '#55A868', '#C44E52']
355
+
356
+ # Create bars with nice colors
357
+ bars = ax2.bar(domain_names, y_scores, color=casl_colors)
358
+
359
+ # Add score labels on top of each bar
360
+ for bar in bars:
361
+ height = bar.get_height()
362
+ ax2.text(bar.get_x() + bar.get_width()/2., height + 1,
363
+ f'{height:.0f}', ha='center', va='bottom')
364
+
365
+ # Add score reference lines
366
+ ax2.axhline(y=100, linestyle='--', color='gray', alpha=0.7, label='Average (100)')
367
+ ax2.axhline(y=85, linestyle=':', color='orange', alpha=0.7, label='Below Average (<85)')
368
+ ax2.axhline(y=115, linestyle=':', color='green', alpha=0.7, label='Above Average (>115)')
369
+
370
+ # Add labels and title
371
+ ax2.set_title('CASL-2 Standard Scores', fontsize=14, fontweight='bold')
372
+ ax2.set_ylabel('Standard Score', fontsize=11)
373
+ ax2.set_ylim(bottom=0, top=max(130, max(y_scores) + 15)) # Set y-axis limit with some padding
374
+
375
+ # Add legend
376
+ ax2.legend(loc='upper right', fontsize='small')
377
+
378
+ # Remove top and right spines
379
+ ax2.spines['top'].set_visible(False)
380
+ ax2.spines['right'].set_visible(False)
381
+
382
+ plt.tight_layout()
383
+
384
+ # Save plot to buffer
385
+ buf = io.BytesIO()
386
+ plt.savefig(buf, format='png', bbox_inches='tight')
387
+ buf.seek(0)
388
+ plt.close()
389
+
390
+ return buf
391
+
392
+ def create_casl_radar_chart(speech_factors):
393
+ """Create a radar chart for speech factors (percentiles)"""
394
+
395
+ if speech_factors.empty or 'Severity' not in speech_factors.columns:
396
+ # Create a placeholder image if no data
397
+ plt.figure(figsize=(8, 8))
398
+ plt.text(0.5, 0.5, "No data available for radar chart",
399
+ ha='center', va='center', fontsize=14)
400
+ plt.axis('off')
401
+
402
+ buf = io.BytesIO()
403
+ plt.savefig(buf, format='png')
404
+ buf.seek(0)
405
+ plt.close()
406
+ return buf
407
+
408
+ # Prepare data for radar chart
409
+ categories = speech_factors['Factor'].tolist()
410
+ percentiles = speech_factors['Severity'].tolist()
411
+
412
+ # Need to repeat first value to close the polygon
413
+ categories = categories + [categories[0]]
414
+ percentiles = percentiles + [percentiles[0]]
415
+
416
+ # Convert to radians and calculate points
417
+ N = len(categories) - 1 # Subtract 1 for the repeated point
418
+ angles = [n / float(N) * 2 * np.pi for n in range(N)]
419
+ angles += angles[:1] # Repeat the first angle to close the polygon
420
+
421
+ # Create the plot
422
+ fig = plt.figure(figsize=(8, 8))
423
+ ax = fig.add_subplot(111, polar=True)
424
+
425
+ # Draw percentile lines with labels
426
+ plt.xticks(angles[:-1], categories[:-1], size=12)
427
+ ax.set_rlabel_position(0)
428
+ plt.yticks([20, 40, 60, 80, 100], ["20", "40", "60", "80", "100"], color="grey", size=10)
429
+ plt.ylim(0, 100)
430
+
431
+ # Plot data
432
+ ax.plot(angles, percentiles, linewidth=1, linestyle='solid', color='#4C72B0')
433
+ ax.fill(angles, percentiles, color='#4C72B0', alpha=0.25)
434
+
435
+ # Add title
436
+ plt.title('Speech Factors Severity (Percentile)', size=15, fontweight='bold', pad=20)
437
+
438
+ # Save to buffer
439
+ buf = io.BytesIO()
440
+ plt.savefig(buf, format='png', bbox_inches='tight')
441
+ buf.seek(0)
442
+ plt.close()
443
+
444
+ return buf
445
+
446
+ def analyze_transcript(transcript, age, gender):
447
+ """Analyze a speech transcript using the CASL framework"""
448
+
449
+ # Instructions for the LLM analysis
450
+ instructions = """
451
+ You're a professional Speech-Language Pathologist analyzing this transcription sample.
452
+
453
+ For your analysis, count occurrences of:
454
+
455
+ 1. Difficulty producing fluent, grammatical speech - Speech that is slow, halting, with pauses while searching for words
456
+ 2. Word retrieval issues - Trouble finding specific words, using fillers like "um", circumlocution, or semantically similar substitutions
457
+ 3. Grammatical errors - Missing/incorrect function words, verb tense problems, simplified sentences
458
+ 4. Repetitions and revisions - Repeating or restating due to word-finding or sentence construction difficulties
459
+ 5. Neologisms - Creating nonexistent "new" words
460
+ 6. Perseveration - Unintentionally repeating words or phrases
461
+ 7. Comprehension issues - Difficulty understanding complex sentences or fast speech
462
+
463
+ Analyze using the CASL-2 (Comprehensive Assessment of Spoken Language) framework:
464
+
465
+ Lexical/Semantic Skills:
466
+ - Evaluate vocabulary diversity, word retrieval difficulties, and semantic precision
467
+ - Estimate Standard Score (mean=100, SD=15), percentile rank, and performance level
468
+
469
+ Syntactic Skills:
470
+ - Assess sentence structure, grammatical accuracy, and syntactic complexity
471
+ - Estimate Standard Score, percentile rank, and performance level
472
+
473
+ Supralinguistic Skills:
474
+ - Evaluate figurative language use, inferencing, and contextual understanding
475
+ - Estimate Standard Score, percentile rank, and performance level
476
+
477
+ Format your analysis with:
478
+ 1. Speech factor counts with severity percentiles
479
+ 2. CASL-2 domain scores with performance levels
480
+ 3. Treatment recommendations based on findings
481
+ 4. Brief explanation of your rationale
482
+ 5. Any additional insights
483
+ """
484
+
485
+ # Prepare prompt for Claude
486
+ prompt = f"""
487
+ You are an experienced Speech-Language Pathologist analyzing this transcript for a patient who is {age} years old and {gender}.
488
+
489
+ TRANSCRIPT:
490
+ {transcript}
491
+
492
+ {instructions}
493
+
494
+ Be precise, professional, and empathetic in your analysis. Focus on the linguistic patterns present in the sample.
495
+ """
496
+
497
+ # Call the appropriate API or fallback to demo mode
498
+ if bedrock_client:
499
+ response = call_bedrock(prompt)
500
+ else:
501
+ response = generate_demo_response(prompt)
502
+
503
+ # Parse the response
504
+ results = parse_casl_response(response)
505
+
506
+ # Create visualizations
507
+ plot_image = create_casl_plots(results['speech_factors'], results['casl_data'])
508
+ radar_image = create_casl_radar_chart(results['speech_factors'])
509
+
510
+ return results, plot_image, radar_image, response
511
+
512
+ def generate_report(patient_info, analysis_results, report_type="formal"):
513
+ """Generate a professional report based on analysis results"""
514
+
515
+ patient_name = patient_info.get("name", "")
516
+ record_id = patient_info.get("record_id", "")
517
+ age = patient_info.get("age", "")
518
+ gender = patient_info.get("gender", "")
519
+ assessment_date = patient_info.get("assessment_date", datetime.now().strftime('%m/%d/%Y'))
520
+ clinician = patient_info.get("clinician", "")
521
+
522
+ prompt = f"""
523
+ You are a professional Speech-Language Pathologist creating a {report_type} report based on an assessment.
524
+
525
+ PATIENT INFORMATION:
526
+ Name: {patient_name}
527
+ Record ID: {record_id}
528
+ Age: {age}
529
+ Gender: {gender}
530
+ Assessment Date: {assessment_date}
531
+ Clinician: {clinician}
532
+
533
+ ASSESSMENT RESULTS:
534
+ {analysis_results}
535
+
536
+ Please create a professional {report_type} report that includes:
537
+ 1. Patient information and assessment details
538
+ 2. Summary of findings (strengths and areas of concern)
539
+ 3. Detailed analysis of language domains
540
+ 4. Specific recommendations for therapy
541
+ 5. Recommendation for frequency and duration of services
542
+
543
+ Use clear, professional language appropriate for {'educational professionals' if report_type == 'formal' else 'parents and caregivers'}.
544
+ Format the report with proper headings and sections.
545
+ """
546
+
547
+ # Call the API or use demo mode
548
+ if bedrock_client:
549
+ report = call_bedrock(prompt, max_tokens=6000)
550
+ else:
551
+ # For demo, create a simulated report
552
+ report = f"""
553
+ # {'FORMAL LANGUAGE ASSESSMENT REPORT' if report_type == 'formal' else 'PARENT-FRIENDLY LANGUAGE ASSESSMENT SUMMARY'}
554
+
555
+ **Date of Assessment:** {assessment_date}
556
+ **Clinician:** {clinician}
557
+
558
+ ## PATIENT INFORMATION
559
+ **Name:** {patient_name}
560
+ **Record ID:** {record_id}
561
+ **Age:** {age}
562
+ **Gender:** {gender}
563
+
564
+ ## ASSESSMENT SUMMARY
565
+
566
+ {'The patient was assessed using the Comprehensive Assessment of Spoken Language, Second Edition (CASL-2) to evaluate language skills across multiple domains. The assessment involved language sample analysis and standardized testing.' if report_type == 'formal' else 'We completed a language assessment to better understand your child\'s communication strengths and challenges. This helps us create a plan to support their development.'}
567
+
568
+ ## KEY FINDINGS
569
+
570
+ **Areas of Strength:**
571
+ - Ability to maintain conversational topics
572
+ - Good vocabulary for everyday topics
573
+ - Strong nonverbal communication skills
574
+
575
+ **Areas of Challenge:**
576
+ - Word-finding difficulties during conversation
577
+ - Grammatical errors in complex sentences
578
+ - Difficulty with abstract language concepts
579
+
580
+ ## DETAILED ANALYSIS
581
+
582
+ **Lexical/Semantic Skills:** Standard Score 91 (27th percentile) - Low Average Range
583
+ The student demonstrates adequate vocabulary but struggles with retrieving specific words during conversation. Word-finding pauses were noted throughout the language sample.
584
+
585
+ **Syntactic Skills:** Standard Score 85 (16th percentile) - Low Average Range
586
+ The student shows difficulty with complex grammatical structures, particularly verb tense consistency and complex sentence formation.
587
+
588
+ **Supralinguistic Skills:** Standard Score 83 (13th percentile) - Below Average Range
589
+ The student struggles with understanding figurative language, making inferences, and comprehending abstract concepts.
590
+
591
+ ## RECOMMENDATIONS
592
+
593
+ {'1. Speech-Language Therapy focused on:' if report_type == 'formal' else 'We recommend:'}
594
+ - Word-finding strategies using semantic feature analysis
595
+ - Structured grammatical exercises to improve sentence complexity
596
+ - Explicit instruction in figurative language comprehension
597
+ - Narrative language development using visual supports
598
+
599
+ {'2. Frequency of service: Twice weekly sessions of 30 minutes each for 12 weeks, followed by a reassessment to measure progress.' if report_type == 'formal' else '2. We recommend therapy twice a week for 30 minutes. This consistency will help your child make better progress.'}
600
+
601
+ {'3. Classroom accommodations including:' if report_type == 'formal' else '3. In school, your child may benefit from:'}
602
+ - Extended time for verbal responses
603
+ - Visual supports for complex instructions
604
+ - Pre-teaching of vocabulary for academic units
605
+
606
+ ## PROGNOSIS
607
+
608
+ {'The prognosis for improvement is good with consistent therapeutic intervention and support. Regular reassessment is recommended to monitor progress.' if report_type == 'formal' else 'With regular therapy and support at home, we expect your child to make good progress in these areas.'}
609
+
610
+ {'Respectfully submitted,' if report_type == 'formal' else 'Please reach out with any questions!'}
611
+
612
+ {clinician}
613
+ Speech-Language Pathologist
614
+ """
615
+
616
+ return report
617
+
618
+ def transcribe_audio(audio_path, patient_age):
619
+ """Transcribe an audio recording using CHAT format"""
620
+ # In a real implementation, this would use a speech-to-text service
621
+ # For demo purposes, we'll return a simulated transcription
622
+
623
+ if bedrock_client:
624
+ # In a real implementation, you would process the audio file and send it to a transcription service
625
+ # Here we just simulate the result
626
+ transcription = generate_demo_transcription(audio_path)
627
+ else:
628
+ transcription = generate_demo_transcription(audio_path)
629
+
630
+ return transcription
631
+
632
+ def answer_slp_question(question):
633
+ """Answer a question about SLP practice or CASL assessment"""
634
+
635
+ prompt = f"""
636
+ You are an experienced Speech-Language Pathologist answering a question from a colleague.
637
+
638
+ QUESTION:
639
+ {question}
640
+
641
+ Please provide a clear, evidence-based answer focused specifically on the question asked.
642
+ Reference best practices and current research where appropriate.
643
+ Keep your answer concise but comprehensive.
644
+ """
645
+
646
+ if bedrock_client:
647
+ answer = call_bedrock(prompt)
648
+ else:
649
+ answer = generate_demo_qa_response(question)
650
+
651
+ return answer
652
+
653
+ # ===============================
654
+ # Gradio Interface
655
+ # ===============================
656
+
657
+ def create_interface():
658
+ """Create the main Gradio interface"""
659
+
660
+ # Define custom theme colors
661
+ primary_color = "#2C7FB8" # Professional blue
662
+ secondary_color = "#f5f7fa" # Light background
663
+ accent_color = "#78909C" # Gray-blue accent
664
+
665
+ custom_theme = gr.themes.Soft(
666
+ primary_hue=primary_color,
667
+ secondary_hue=secondary_color,
668
+ neutral_hue=accent_color,
669
+ font=[gr.themes.GoogleFont("Inter"), "system-ui", "sans-serif"]
670
+ ).set(
671
+ body_background_fill=secondary_color,
672
+ button_primary_background_fill=primary_color,
673
+ button_primary_background_fill_hover=primary_color,
674
+ button_primary_text_color="white",
675
+ block_title_text_color=primary_color,
676
+ block_label_text_color=accent_color,
677
+ input_background_fill="#FFFFFF",
678
+ )
679
+
680
+ with gr.Blocks(theme=custom_theme, css="""
681
+ .header {
682
+ text-align: center;
683
+ margin-bottom: 20px;
684
+ }
685
+ .header img {
686
+ max-height: 100px;
687
+ margin-bottom: 10px;
688
+ }
689
+ .container {
690
+ border-radius: 10px;
691
+ padding: 10px;
692
+ margin-bottom: 20px;
693
+ }
694
+ .patient-info {
695
+ background-color: #e3f2fd;
696
+ }
697
+ .speech-sample {
698
+ background-color: #f0f8ff;
699
+ }
700
+ .results-container {
701
+ background-color: #f9f9f9;
702
+ }
703
+ .viz-container {
704
+ display: flex;
705
+ justify-content: center;
706
+ margin-bottom: 20px;
707
+ }
708
+ .footer {
709
+ text-align: center;
710
+ margin-top: 30px;
711
+ padding: 10px;
712
+ font-size: 0.8em;
713
+ color: #78909C;
714
+ }
715
+ .info-box {
716
+ background-color: #e8f5e9;
717
+ border-left: 4px solid #4CAF50;
718
+ padding: 10px 15px;
719
+ margin-bottom: 15px;
720
+ border-radius: 4px;
721
+ }
722
+ .warning-box {
723
+ background-color: #fff8e1;
724
+ border-left: 4px solid #FFC107;
725
+ padding: 10px 15px;
726
+ border-radius: 4px;
727
+ }
728
+ .markdown-text h3 {
729
+ color: #2C7FB8;
730
+ border-bottom: 1px solid #eaeaea;
731
+ padding-bottom: 5px;
732
+ }
733
+ .evidence-table {
734
+ border-collapse: collapse;
735
+ width: 100%;
736
+ }
737
+ .evidence-table th, .evidence-table td {
738
+ border: 1px solid #ddd;
739
+ padding: 8px;
740
+ text-align: left;
741
+ }
742
+ .evidence-table th {
743
+ background-color: #f5f7fa;
744
+ color: #333;
745
+ }
746
+ .evidence-table tr:nth-child(even) {
747
+ background-color: #f9f9f9;
748
+ }
749
+ .tab-content {
750
+ padding: 15px;
751
+ background-color: white;
752
+ border-radius: 0 0 8px 8px;
753
+ box-shadow: 0 2px 5px rgba(0,0,0,0.05);
754
+ }
755
+ """) as app:
756
+ # Create header with logo
757
+ gr.HTML(
758
+ """
759
+ <div class="header">
760
+ <h1>SLP Analysis Tool</h1>
761
+ <p>A comprehensive assessment tool for Speech-Language Pathologists</p>
762
+ </div>
763
+ """
764
+ )
765
+
766
+ # Main tabs
767
+ with gr.Tabs() as main_tabs:
768
+ # ===============================
769
+ # CASL Analysis Tab
770
+ # ===============================
771
+ with gr.TabItem("CASL Analysis", id=0):
772
+ with gr.Row():
773
+ # Left column - Input section
774
+ with gr.Column(scale=1):
775
+ # Patient information panel
776
+ with gr.Box(elem_classes="container patient-info"):
777
+ gr.Markdown("### Patient Information")
778
+
779
+ with gr.Row():
780
+ patient_name = gr.Textbox(label="Patient Name", placeholder="Enter patient name")
781
+ record_id = gr.Textbox(label="Record ID", placeholder="Enter record ID")
782
+
783
+ with gr.Row():
784
+ age = gr.Number(label="Age", value=8, minimum=1, maximum=120)
785
+ gender = gr.Radio(["male", "female", "other"], label="Gender", value="male")
786
+
787
+ with gr.Row():
788
+ assessment_date = gr.Textbox(
789
+ label="Assessment Date",
790
+ placeholder="MM/DD/YYYY",
791
+ value=datetime.now().strftime('%m/%d/%Y')
792
+ )
793
+ clinician_name = gr.Textbox(
794
+ label="Clinician",
795
+ placeholder="Enter clinician name"
796
+ )
797
+
798
+ # Speech sample panel
799
+ with gr.Box(elem_classes="container speech-sample"):
800
+ gr.Markdown("### Speech Sample")
801
+
802
+ # Sample button
803
+ sample_btn = gr.Button("Load Sample Transcript", size="sm")
804
+
805
+ # Transcript input
806
+ transcript = gr.Textbox(
807
+ label="Transcript",
808
+ placeholder="Paste the speech transcript here...",
809
+ lines=10
810
+ )
811
+
812
+ # Add info about transcript format
813
+ gr.Markdown(
814
+ """
815
+ <div class="info-box">
816
+ <strong>Transcript Format:</strong> Use CHAT format with *PAR: for patient lines.
817
+ Mark word-finding with &-um, paraphasias with [*], and provide intended words with [: word].
818
+ </div>
819
+ """,
820
+ elem_classes="markdown-text"
821
+ )
822
+
823
+ # File upload
824
+ file_upload = gr.File(
825
+ label="Or upload a transcript file",
826
+ file_types=["text", "txt", "pdf", "rtf"]
827
+ )
828
+
829
+ # Analysis button
830
+ analyze_btn = gr.Button("Analyze Speech Sample", variant="primary", size="lg")
831
+
832
+ # Right column - Results section
833
+ with gr.Column(scale=1):
834
+ with gr.Box(elem_classes="container results-container"):
835
+ with gr.Tabs() as results_tabs:
836
+ # Summary tab
837
+ with gr.TabItem("Summary", id=0, elem_classes="tab-content"):
838
+ with gr.Row():
839
+ output_image = gr.Image(
840
+ label="Speech Factors & CASL-2 Scores",
841
+ show_label=True,
842
+ elem_classes="viz-container"
843
+ )
844
+
845
+ with gr.Row():
846
+ radar_chart = gr.Image(
847
+ label="Severity Profile",
848
+ show_label=True,
849
+ elem_classes="viz-container"
850
+ )
851
+
852
+ with gr.Box():
853
+ gr.Markdown("### Key Findings", elem_classes="markdown-text")
854
+ speech_factors_table = gr.DataFrame(
855
+ label="Speech Factors Analysis",
856
+ headers=["Factor", "Occurrences", "Severity (Percentile)"],
857
+ interactive=False
858
+ )
859
+ casl_table = gr.DataFrame(
860
+ label="CASL-2 Assessment",
861
+ headers=["Domain", "Standard Score", "Percentile", "Performance Level"],
862
+ interactive=False
863
+ )
864
+
865
+ # Treatment tab
866
+ with gr.TabItem("Treatment Plan", id=1, elem_classes="tab-content"):
867
+ gr.Markdown("### Recommended Treatment Approaches", elem_classes="markdown-text")
868
+ treatment_md = gr.Markdown(elem_classes="treatment-panel")
869
+
870
+ gr.Markdown("### Clinical Rationale", elem_classes="markdown-text")
871
+ explanation_md = gr.Markdown(elem_classes="panel")
872
+
873
+ with gr.Accordion("Supporting Evidence", open=False):
874
+ gr.Markdown("""
875
+ <table class="evidence-table">
876
+ <tr>
877
+ <th>Factor</th>
878
+ <th>Evidence-based Approaches</th>
879
+ <th>References</th>
880
+ </tr>
881
+ <tr>
882
+ <td>Word Retrieval</td>
883
+ <td>Semantic feature analysis, phonological cueing, word generation tasks</td>
884
+ <td>Boyle, 2010; Kiran & Thompson, 2003</td>
885
+ </tr>
886
+ <tr>
887
+ <td>Grammatical Errors</td>
888
+ <td>Treatment of Underlying Forms (TUF), Morphosyntactic therapy</td>
889
+ <td>Thompson et al., 2003; Ebbels, 2014</td>
890
+ </tr>
891
+ <tr>
892
+ <td>Fluency/Prosody</td>
893
+ <td>Rate control, rhythmic cueing, contrastive stress exercises</td>
894
+ <td>Ballard et al., 2010; Tamplin & Baker, 2017</td>
895
+ </tr>
896
+ </table>
897
+ """, elem_classes="markdown-text")
898
+
899
+ # Full report tab
900
+ with gr.TabItem("Full Report", id=2, elem_classes="tab-content"):
901
+ full_analysis = gr.Markdown()
902
+
903
+ # Add PDF export option
904
+ export_btn = gr.Button("Export Report as PDF", variant="secondary")
905
+ export_status = gr.Markdown("")
906
+
907
+ # ===============================
908
+ # Report Generator Tab
909
+ # ===============================
910
+ with gr.TabItem("Report Generator", id=1):
911
+ with gr.Row():
912
+ with gr.Column(scale=1):
913
+ gr.Markdown("### Generate Professional Reports")
914
+
915
+ # Patient info
916
+ with gr.Box(elem_classes="container patient-info"):
917
+ gr.Markdown("#### Patient Information")
918
+ report_patient_name = gr.Textbox(label="Patient Name", placeholder="Enter patient name")
919
+ report_record_id = gr.Textbox(label="Record ID", placeholder="Enter record ID")
920
+ report_age = gr.Number(label="Age", value=8, minimum=1, maximum=120)
921
+ report_gender = gr.Radio(["male", "female", "other"], label="Gender", value="male")
922
+ report_date = gr.Textbox(
923
+ label="Assessment Date",
924
+ placeholder="MM/DD/YYYY",
925
+ value=datetime.now().strftime('%m/%d/%Y')
926
+ )
927
+ report_clinician = gr.Textbox(label="Clinician", placeholder="Enter clinician name")
928
+
929
+ with gr.Box():
930
+ gr.Markdown("#### Assessment Results")
931
+ report_results = gr.Textbox(
932
+ label="Paste assessment results or notes here",
933
+ placeholder="Include key findings, test scores, and observations...",
934
+ lines=10
935
+ )
936
+
937
+ report_type = gr.Radio(
938
+ ["Formal (for professionals)", "Parent-friendly"],
939
+ label="Report Type",
940
+ value="Formal (for professionals)"
941
+ )
942
+
943
+ generate_report_btn = gr.Button("Generate Report", variant="primary")
944
+
945
+ with gr.Column(scale=1):
946
+ report_output = gr.Markdown()
947
+ report_download_btn = gr.Button("Download Report as PDF", variant="secondary")
948
+ report_download_status = gr.Markdown("")
949
+
950
+ # ===============================
951
+ # Transcription Tool Tab
952
+ # ===============================
953
+ with gr.TabItem("Transcription Tool", id=2):
954
+ with gr.Row():
955
+ with gr.Column(scale=1):
956
+ gr.Markdown("### Audio Transcription Tool")
957
+ gr.Markdown("Upload an audio recording to automatically transcribe it in CHAT format.")
958
+
959
+ audio_input = gr.Audio(type="filepath", label="Upload Audio Recording")
960
+
961
+ with gr.Row():
962
+ transcription_age = gr.Number(label="Patient Age", value=8, minimum=1, maximum=120)
963
+ transcribe_btn = gr.Button("Transcribe Audio", variant="primary")
964
+
965
+ with gr.Column(scale=1):
966
+ transcription_output = gr.Textbox(
967
+ label="Transcription Result",
968
+ placeholder="Transcription will appear here...",
969
+ lines=12
970
+ )
971
+
972
+ with gr.Row():
973
+ copy_to_analysis_btn = gr.Button("Use for Analysis", variant="secondary")
974
+ edit_transcription_btn = gr.Button("Edit Transcription", variant="secondary")
975
+
976
+ # ===============================
977
+ # SLP Assistant Tab
978
+ # ===============================
979
+ with gr.TabItem("SLP Assistant", id=3):
980
+ with gr.Row():
981
+ with gr.Column(scale=1):
982
+ gr.Markdown("### SLP Knowledge Assistant")
983
+ gr.Markdown("Ask questions about CASL assessment, therapy techniques, or SLP best practices.")
984
+
985
+ question_input = gr.Textbox(
986
+ label="Your Question",
987
+ placeholder="e.g., What activities help improve word-finding skills?",
988
+ lines=3
989
+ )
990
+
991
+ ask_question_btn = gr.Button("Ask Question", variant="primary")
992
+
993
+ # Quick question buttons
994
+ gr.Markdown("#### Common Questions")
995
+ with gr.Row():
996
+ q1_btn = gr.Button("What is CASL?")
997
+ q2_btn = gr.Button("How do I interpret scores?")
998
+
999
+ with gr.Row():
1000
+ q3_btn = gr.Button("Activities for word finding")
1001
+ q4_btn = gr.Button("When to reassess")
1002
+
1003
+ with gr.Column(scale=1):
1004
+ answer_output = gr.Markdown()
1005
+
1006
+ with gr.Accordion("References", open=False):
1007
+ gr.Markdown("""
1008
+ - American Speech-Language-Hearing Association (ASHA)
1009
+ - Comprehensive Assessment of Spoken Language (CASL-2) Manual
1010
+ - Evidence-Based Practice in Speech-Language Pathology
1011
+ - Current research in pediatric language intervention
1012
+ """)
1013
+
1014
+ # ===============================
1015
+ # Event Handlers
1016
+ # ===============================
1017
+
1018
+ # Load sample transcript button
1019
+ def load_sample():
1020
+ return SAMPLE_TRANSCRIPT
1021
+
1022
+ sample_btn.click(load_sample, outputs=[transcript])
1023
+
1024
+ # File upload handler
1025
+ file_upload.upload(process_upload, file_upload, transcript)
1026
+
1027
+ # Analysis button handler
1028
+ def on_analyze_click(transcript_text, age_val, gender_val, patient_name_val, record_id_val, clinician_val, assessment_date_val):
1029
+ if not transcript_text or len(transcript_text.strip()) < 50:
1030
+ return (
1031
+ pd.DataFrame(),
1032
+ pd.DataFrame(),
1033
+ None,
1034
+ None,
1035
+ "Error: Please provide a longer transcript for analysis.",
1036
+ "The transcript is too short for meaningful analysis.",
1037
+ "Please provide a speech sample with at least 50 characters."
1038
+ )
1039
+
1040
+ try:
1041
+ results, plot_img, radar_img, full_text = analyze_transcript(transcript_text, age_val, gender_val)
1042
+
1043
+ # Format treatment suggestions as markdown
1044
+ treatment_text = ""
1045
+ for i, suggestion in enumerate(results['treatment_suggestions']):
1046
+ treatment_text += f"- {suggestion}\n"
1047
+
1048
+ # Format to include patient metadata in the full report
1049
+ patient_info = ""
1050
+ if patient_name_val:
1051
+ patient_info += f"**Patient:** {patient_name_val}\n"
1052
+ if record_id_val:
1053
+ patient_info += f"**Record ID:** {record_id_val}\n"
1054
+ if age_val:
1055
+ patient_info += f"**Age:** {age_val} years\n"
1056
+ if gender_val:
1057
+ patient_info += f"**Gender:** {gender_val}\n"
1058
+ if assessment_date_val:
1059
+ patient_info += f"**Assessment Date:** {assessment_date_val}\n"
1060
+ if clinician_val:
1061
+ patient_info += f"**Clinician:** {clinician_val}\n"
1062
+
1063
+ if patient_info:
1064
+ full_report = f"## Patient Information\n\n{patient_info}\n\n## Analysis Report\n\n{full_text}"
1065
+ else:
1066
+ full_report = f"## Complete Analysis Report\n\n{full_text}"
1067
+
1068
+ # Convert image buffers to PIL images
1069
+ plot_img_pil = Image.open(plot_img)
1070
+ radar_img_pil = Image.open(radar_img)
1071
+
1072
+ return (
1073
+ results['speech_factors'],
1074
+ results['casl_data'],
1075
+ plot_img_pil,
1076
+ radar_img_pil,
1077
+ treatment_text,
1078
+ results['explanation'],
1079
+ full_report
1080
+ )
1081
+ except Exception as e:
1082
+ logger.exception("Error during analysis")
1083
+ return (
1084
+ pd.DataFrame(),
1085
+ pd.DataFrame(),
1086
+ None,
1087
+ None,
1088
+ f"Error during analysis: {str(e)}",
1089
+ "An error occurred while processing the transcript.",
1090
+ f"Error details: {str(e)}"
1091
+ )
1092
+
1093
+ analyze_btn.click(
1094
+ on_analyze_click,
1095
+ inputs=[
1096
+ transcript, age, gender,
1097
+ patient_name, record_id, clinician_name, assessment_date
1098
+ ],
1099
+ outputs=[
1100
+ speech_factors_table,
1101
+ casl_table,
1102
+ output_image,
1103
+ radar_chart,
1104
+ treatment_md,
1105
+ explanation_md,
1106
+ full_analysis
1107
+ ]
1108
+ )
1109
+
1110
+ # Export report button simulation
1111
+ def export_pdf_simulation():
1112
+ return "Report export initiated. The PDF would be downloaded in a production environment."
1113
+
1114
+ export_btn.click(export_pdf_simulation, outputs=[export_status])
1115
+ report_download_btn.click(export_pdf_simulation, outputs=[report_download_status])
1116
+
1117
+ # Report generator button
1118
+ def on_generate_report(name, record_id, age, gender, date, clinician, results, report_type):
1119
+ patient_info = {
1120
+ "name": name,
1121
+ "record_id": record_id,
1122
+ "age": age,
1123
+ "gender": gender,
1124
+ "assessment_date": date,
1125
+ "clinician": clinician
1126
+ }
1127
+
1128
+ report_type_val = "formal" if "Formal" in report_type else "parent-friendly"
1129
+
1130
+ try:
1131
+ report = generate_report(patient_info, results, report_type_val)
1132
+ return report
1133
+ except Exception as e:
1134
+ logger.exception("Error generating report")
1135
+ return f"Error generating report: {str(e)}"
1136
+
1137
+ generate_report_btn.click(
1138
+ on_generate_report,
1139
+ inputs=[
1140
+ report_patient_name, report_record_id, report_age,
1141
+ report_gender, report_date, report_clinician,
1142
+ report_results, report_type
1143
+ ],
1144
+ outputs=[report_output]
1145
+ )
1146
+
1147
+ # Transcription button
1148
+ def on_transcribe_audio(audio_path, age):
1149
+ try:
1150
+ if not audio_path:
1151
+ return "Please upload an audio file to transcribe."
1152
+
1153
+ transcription = transcribe_audio(audio_path, age)
1154
+ return transcription
1155
+ except Exception as e:
1156
+ logger.exception("Error transcribing audio")
1157
+ return f"Error transcribing audio: {str(e)}"
1158
+
1159
+ transcribe_btn.click(
1160
+ on_transcribe_audio,
1161
+ inputs=[audio_input, transcription_age],
1162
+ outputs=[transcription_output]
1163
+ )
1164
+
1165
+ # Copy transcription to analysis
1166
+ def copy_to_analysis(transcription):
1167
+ return transcription, gr.update(selected=0) # Switches to the Analysis tab
1168
+
1169
+ copy_to_analysis_btn.click(
1170
+ copy_to_analysis,
1171
+ inputs=[transcription_output],
1172
+ outputs=[transcript, main_tabs]
1173
+ )
1174
+
1175
+ # SLP Assistant question handling
1176
+ def on_ask_question(question):
1177
+ try:
1178
+ answer = answer_slp_question(question)
1179
+ return answer
1180
+ except Exception as e:
1181
+ logger.exception("Error getting answer")
1182
+ return f"Error: {str(e)}"
1183
+
1184
+ ask_question_btn.click(
1185
+ on_ask_question,
1186
+ inputs=[question_input],
1187
+ outputs=[answer_output]
1188
+ )
1189
+
1190
+ # Quick question buttons
1191
+ q1_btn.click(lambda: "What is CASL?", outputs=[question_input])
1192
+ q2_btn.click(lambda: "How do I interpret CASL scores?", outputs=[question_input])
1193
+ q3_btn.click(lambda: "What activities help with word finding difficulties?", outputs=[question_input])
1194
+ q4_btn.click(lambda: "When should I reassess a patient?", outputs=[question_input])
1195
+
1196
+ return app
1197
+
1198
+ # ===============================
1199
+ # Main Application
1200
+ # ===============================
1201
+
1202
+ # Create requirements.txt file for HuggingFace Spaces
1203
+ def create_requirements_file():
1204
+ requirements = [
1205
+ "gradio>=4.0.0",
1206
+ "pandas",
1207
+ "matplotlib",
1208
+ "numpy",
1209
+ "Pillow",
1210
+ "PyPDF2",
1211
+ "boto3"
1212
+ ]
1213
+
1214
+ with open("requirements.txt", "w") as f:
1215
+ for req in requirements:
1216
+ f.write(f"{req}\n")
1217
+
1218
+ # Create and launch the interface
1219
+ if __name__ == "__main__":
1220
+ # Create requirements.txt for HuggingFace Spaces
1221
+ create_requirements_file()
1222
+
1223
+ # Check for AWS credentials
1224
+ if not AWS_ACCESS_KEY or not AWS_SECRET_KEY:
1225
+ print("NOTE: AWS credentials not found. The app will run in demo mode with simulated responses.")
1226
+ print("To enable full functionality, set AWS_ACCESS_KEY and AWS_SECRET_KEY environment variables.")
1227
+
1228
+ # Launch the Gradio app
1229
+ app = create_interface()
1230
+ app.launch()
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ gradio>=4.0.0
2
+ pandas
3
+ matplotlib
4
+ numpy
5
+ Pillow
6
+ PyPDF2
7
+ boto3