SreekarB commited on
Commit
274b69b
·
verified ·
1 Parent(s): d095221

Upload 8 files

Browse files
Files changed (2) hide show
  1. simple_app.py +0 -1
  2. simple_app_fixed.py +761 -0
simple_app.py CHANGED
@@ -1003,7 +1003,6 @@ def create_interface():
1003
 
1004
  # Audio input
1005
  audio_input = gr.Audio(type="filepath", label="Upload Audio Recording",
1006
- format="mp3,wav,ogg,webm",
1007
  elem_id="audio-input")
1008
 
1009
  # Transcribe button
 
1003
 
1004
  # Audio input
1005
  audio_input = gr.Audio(type="filepath", label="Upload Audio Recording",
 
1006
  elem_id="audio-input")
1007
 
1008
  # Transcribe button
simple_app_fixed.py ADDED
@@ -0,0 +1,761 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import boto3
3
+ import json
4
+ import re
5
+ import logging
6
+ import os
7
+ import tempfile
8
+ import shutil
9
+ import time
10
+ import uuid
11
+ from datetime import datetime
12
+
13
+ # Configure logging
14
+ logging.basicConfig(level=logging.INFO)
15
+ logger = logging.getLogger(__name__)
16
+
17
+ # Try to import ReportLab (needed for PDF generation)
18
+ try:
19
+ from reportlab.lib.pagesizes import letter
20
+ from reportlab.lib import colors
21
+ from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
22
+ from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
23
+ REPORTLAB_AVAILABLE = True
24
+ except ImportError:
25
+ logger.warning("ReportLab library not available - PDF export will be disabled")
26
+ REPORTLAB_AVAILABLE = False
27
+
28
+ # Try to import speech recognition for local audio processing
29
+ try:
30
+ import speech_recognition as sr
31
+ import pydub
32
+ SPEECH_RECOGNITION_AVAILABLE = True
33
+ except ImportError:
34
+ SPEECH_RECOGNITION_AVAILABLE = False
35
+
36
+ # AWS credentials for Bedrock API
37
+ AWS_ACCESS_KEY = os.getenv("AWS_ACCESS_KEY", "")
38
+ AWS_SECRET_KEY = os.getenv("AWS_SECRET_KEY", "")
39
+ AWS_REGION = os.getenv("AWS_REGION", "us-east-1")
40
+
41
+ # Initialize AWS clients if credentials are available
42
+ bedrock_client = None
43
+
44
+ if AWS_ACCESS_KEY and AWS_SECRET_KEY:
45
+ try:
46
+ # Initialize Bedrock client for AI analysis
47
+ bedrock_client = boto3.client(
48
+ 'bedrock-runtime',
49
+ aws_access_key_id=AWS_ACCESS_KEY,
50
+ aws_secret_access_key=AWS_SECRET_KEY,
51
+ region_name=AWS_REGION
52
+ )
53
+ logger.info("Bedrock client initialized successfully")
54
+ except Exception as e:
55
+ logger.error(f"Failed to initialize AWS clients: {str(e)}")
56
+
57
+ # Create data directories if they don't exist
58
+ DATA_DIR = os.environ.get("DATA_DIR", "patient_data")
59
+ DOWNLOADS_DIR = os.path.join(DATA_DIR, "downloads")
60
+ AUDIO_DIR = os.path.join(DATA_DIR, "audio")
61
+
62
+ def ensure_data_dirs():
63
+ """Ensure data directories exist"""
64
+ global DOWNLOADS_DIR, AUDIO_DIR
65
+ try:
66
+ os.makedirs(DATA_DIR, exist_ok=True)
67
+ os.makedirs(DOWNLOADS_DIR, exist_ok=True)
68
+ os.makedirs(AUDIO_DIR, exist_ok=True)
69
+ logger.info(f"Data directories created: {DATA_DIR}, {DOWNLOADS_DIR}, {AUDIO_DIR}")
70
+ except Exception as e:
71
+ logger.warning(f"Could not create data directories: {str(e)}")
72
+ # Fallback to tmp directory on HF Spaces
73
+ DOWNLOADS_DIR = os.path.join(tempfile.gettempdir(), "casl_downloads")
74
+ AUDIO_DIR = os.path.join(tempfile.gettempdir(), "casl_audio")
75
+ os.makedirs(DOWNLOADS_DIR, exist_ok=True)
76
+ os.makedirs(AUDIO_DIR, exist_ok=True)
77
+ logger.info(f"Using fallback directories: {DOWNLOADS_DIR}, {AUDIO_DIR}")
78
+
79
+ # Initialize data directories
80
+ ensure_data_dirs()
81
+
82
+ # Sample transcript for the demo
83
+ SAMPLE_TRANSCRIPT = """*PAR: today I would &-um like to talk about &-um a fun trip I took last &-um summer with my family.
84
+ *PAR: we went to the &-um &-um beach [//] no to the mountains [//] I mean the beach actually.
85
+ *PAR: there was lots of &-um &-um swimming and &-um sun.
86
+ *PAR: we [/] we stayed for &-um three no [//] four days in a &-um hotel near the water [: ocean] [*].
87
+ *PAR: my favorite part was &-um building &-um castles with sand.
88
+ *PAR: sometimes I forget [//] forgetted [: forgot] [*] what they call those things we built.
89
+ *PAR: my brother he [//] he helped me dig a big hole.
90
+ *PAR: we saw [/] saw fishies [: fish] [*] swimming in the water.
91
+ *PAR: sometimes I wonder [/] wonder where fishies [: fish] [*] go when it's cold.
92
+ *PAR: maybe they have [/] have houses under the water.
93
+ *PAR: after swimming we [//] I eat [: ate] [*] &-um ice cream with &-um chocolate things on top.
94
+ *PAR: what do you call those &-um &-um sprinkles! that's the word.
95
+ *PAR: my mom said to &-um that I could have &-um two scoops next time.
96
+ *PAR: I want to go back to the beach [/] beach next year."""
97
+
98
+ def read_cha_file(file_path):
99
+ """Read and parse a .cha transcript file"""
100
+ try:
101
+ with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
102
+ content = f.read()
103
+
104
+ # Extract participant lines (starting with *PAR:)
105
+ par_lines = []
106
+ for line in content.splitlines():
107
+ if line.startswith('*PAR:'):
108
+ par_lines.append(line)
109
+
110
+ # If no PAR lines found, just return the whole content
111
+ if not par_lines:
112
+ return content
113
+
114
+ return '\n'.join(par_lines)
115
+
116
+ except Exception as e:
117
+ logger.error(f"Error reading CHA file: {str(e)}")
118
+ return ""
119
+
120
+ def process_upload(file):
121
+ """Process an uploaded file (PDF, text, or CHA)"""
122
+ if file is None:
123
+ return ""
124
+
125
+ file_path = file.name
126
+ if file_path.endswith('.pdf'):
127
+ # For PDF, we would need PyPDF2 or similar
128
+ return "PDF upload not supported in this simple version"
129
+ elif file_path.endswith('.cha'):
130
+ return read_cha_file(file_path)
131
+ else:
132
+ with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
133
+ return f.read()
134
+
135
+ def call_bedrock(prompt, max_tokens=4096):
136
+ """Call the AWS Bedrock API to analyze text using Claude"""
137
+ if not bedrock_client:
138
+ return "AWS credentials not configured. Using demo response instead."
139
+
140
+ try:
141
+ body = json.dumps({
142
+ "anthropic_version": "bedrock-2023-05-31",
143
+ "max_tokens": max_tokens,
144
+ "messages": [
145
+ {
146
+ "role": "user",
147
+ "content": prompt
148
+ }
149
+ ],
150
+ "temperature": 0.3,
151
+ "top_p": 0.9
152
+ })
153
+
154
+ modelId = 'anthropic.claude-3-sonnet-20240229-v1:0'
155
+ response = bedrock_client.invoke_model(
156
+ body=body,
157
+ modelId=modelId,
158
+ accept='application/json',
159
+ contentType='application/json'
160
+ )
161
+ response_body = json.loads(response.get('body').read())
162
+ return response_body['content'][0]['text']
163
+ except Exception as e:
164
+ logger.error(f"Error in call_bedrock: {str(e)}")
165
+ return f"Error: {str(e)}"
166
+
167
+ def transcribe_audio_local(audio_path):
168
+ """Local audio transcription using speech_recognition library"""
169
+ if not SPEECH_RECOGNITION_AVAILABLE:
170
+ return generate_demo_transcription()
171
+
172
+ try:
173
+ r = sr.Recognizer()
174
+
175
+ # Convert audio to WAV if needed
176
+ if not audio_path.endswith('.wav'):
177
+ try:
178
+ audio = pydub.AudioSegment.from_file(audio_path)
179
+ wav_path = audio_path.rsplit('.', 1)[0] + '.wav'
180
+ audio.export(wav_path, format="wav")
181
+ audio_path = wav_path
182
+ except Exception as e:
183
+ logger.error(f"Error converting audio: {str(e)}")
184
+ return f"Error: Could not process audio file. {str(e)}"
185
+
186
+ # Transcribe audio
187
+ with sr.AudioFile(audio_path) as source:
188
+ audio_data = r.record(source)
189
+ try:
190
+ text = r.recognize_google(audio_data)
191
+ return format_transcription_as_chat(text)
192
+ except sr.UnknownValueError:
193
+ return "Error: Could not understand audio"
194
+ except sr.RequestError as e:
195
+ return f"Error: Could not request results; {e}"
196
+
197
+ except Exception as e:
198
+ logger.error(f"Error in local transcription: {str(e)}")
199
+ return generate_demo_transcription()
200
+
201
+ def format_transcription_as_chat(text):
202
+ """Format transcribed text into CHAT format"""
203
+ # Split text into sentences and format as participant speech
204
+ sentences = re.split(r'[.!?]+', text)
205
+ chat_lines = []
206
+
207
+ for sentence in sentences:
208
+ sentence = sentence.strip()
209
+ if sentence:
210
+ chat_lines.append(f"*PAR: {sentence}.")
211
+
212
+ return '\n'.join(chat_lines)
213
+
214
+ def generate_demo_transcription():
215
+ """Generate a simulated transcription response"""
216
+ return """*PAR: today I want to tell you about my favorite toy.
217
+ *PAR: it's a &-um teddy bear that I got for my birthday.
218
+ *PAR: he has &-um brown fur and a red bow.
219
+ *PAR: I like to sleep with him every night.
220
+ *PAR: sometimes I take him to school in my backpack.
221
+ *INV: what's your teddy bear's name?
222
+ *PAR: his name is &-um Brownie because he's brown."""
223
+
224
+ def generate_demo_response(prompt):
225
+ """Generate a response using Bedrock if available, otherwise return a demo response"""
226
+ # This function will attempt to call Bedrock, and only fall back to the demo response
227
+ # if Bedrock is not available or fails
228
+
229
+ # Try to call Bedrock first if client is available
230
+ if bedrock_client:
231
+ try:
232
+ return call_bedrock(prompt)
233
+ except Exception as e:
234
+ logger.error(f"Error calling Bedrock: {str(e)}")
235
+ logger.info("Falling back to demo response")
236
+ # Continue to fallback response if Bedrock call fails
237
+
238
+ # Fallback demo response
239
+ logger.warning("Using demo response - Bedrock client not available or call failed")
240
+ return """<SPEECH_FACTORS_START>
241
+ Difficulty producing fluent speech: 8, 65
242
+ Examples:
243
+ - "today I would &-um like to talk about &-um a fun trip I took last &-um summer with my family"
244
+ - "we went to the &-um &-um beach [//] no to the mountains [//] I mean the beach actually"
245
+
246
+ Word retrieval issues: 6, 72
247
+ Examples:
248
+ - "what do you call those &-um &-um sprinkles! that's the word"
249
+ - "sometimes I forget [//] forgetted [: forgot] [*] what they call those things we built"
250
+
251
+ Grammatical errors: 4, 58
252
+ Examples:
253
+ - "after swimming we [//] I eat [: ate] [*] &-um ice cream"
254
+ - "sometimes I forget [//] forgetted [: forgot] [*] what they call those things we built"
255
+
256
+ Repetitions and revisions: 5, 62
257
+ Examples:
258
+ - "we [/] we stayed for &-um three no [//] four days"
259
+ - "we went to the &-um &-um beach [//] no to the mountains [//] I mean the beach actually"
260
+ <SPEECH_FACTORS_END>
261
+
262
+ <CASL_SKILLS_START>
263
+ Lexical/Semantic Skills: Standard Score (92), Percentile Rank (30%), Average Performance
264
+ Examples:
265
+ - "what do you call those &-um &-um sprinkles! that's the word"
266
+ - "we went to the &-um &-um beach [//] no to the mountains [//] I mean the beach actually"
267
+
268
+ Syntactic Skills: Standard Score (87), Percentile Rank (19%), Low Average Performance
269
+ Examples:
270
+ - "my brother he [//] he helped me dig a big hole"
271
+ - "after swimming we [//] I eat [: ate] [*] &-um ice cream with &-um chocolate things on top"
272
+
273
+ Supralinguistic Skills: Standard Score (90), Percentile Rank (25%), Average Performance
274
+ Examples:
275
+ - "sometimes I wonder [/] wonder where fishies [: fish] [*] go when it's cold"
276
+ - "maybe they have [/] have houses under the water"
277
+ <CASL_SKILLS_END>
278
+
279
+ <TREATMENT_RECOMMENDATIONS_START>
280
+ - Implement word-finding strategies with semantic cuing focused on everyday objects and activities, using the patient's beach experience as a context (e.g., "sprinkles," "castles")
281
+ - Practice structured narrative tasks with visual supports to reduce revisions and improve sequencing
282
+ - Use sentence formulation exercises focusing on verb tense consistency (addressing errors like "forgetted" and "eat" for "ate")
283
+ - Incorporate self-monitoring techniques to help identify and correct grammatical errors
284
+ - Work on increasing vocabulary specificity (e.g., "things on top" to "sprinkles")
285
+ <TREATMENT_RECOMMENDATIONS_END>
286
+
287
+ <EXPLANATION_START>
288
+ This child demonstrates moderate word-finding difficulties with compensatory strategies including fillers ("&-um") and repetitions. The frequent use of self-corrections shows good metalinguistic awareness, but the pauses and repairs impact conversational fluency. Syntactic errors primarily involve verb tense inconsistency. Overall, the pattern suggests a mild-to-moderate language disorder with stronger receptive than expressive skills.
289
+ <EXPLANATION_END>
290
+
291
+ <ADDITIONAL_ANALYSIS_START>
292
+ The child shows relative strengths in maintaining topic coherence and conveying a complete narrative structure despite the language challenges. The pattern of errors suggests that word-finding difficulties and processing speed are primary concerns rather than conceptual or cognitive issues. Semantic network activities that strengthen word associations would likely be beneficial, particularly when paired with visual supports.
293
+ <ADDITIONAL_ANALYSIS_END>
294
+
295
+ <DIAGNOSTIC_IMPRESSIONS_START>
296
+ Based on the language sample, this child presents with a profile consistent with a mild-to-moderate expressive language disorder. The most prominent features include:
297
+
298
+ 1. Word-finding difficulties characterized by fillers, pauses, and self-corrections when attempting to retrieve specific vocabulary
299
+ 2. Grammatical challenges primarily affecting verb tense consistency and morphological markers
300
+ 3. Relatively intact narrative structure and topic maintenance
301
+
302
+ These findings suggest intervention should focus on word retrieval strategies, grammatical form practice, and continued support for narrative development, with an emphasis on fluency and self-monitoring.
303
+ <DIAGNOSTIC_IMPRESSIONS_END>
304
+
305
+ <ERROR_EXAMPLES_START>
306
+ Word-finding difficulties:
307
+ - "what do you call those &-um &-um sprinkles! that's the word"
308
+ - "we went to the &-um &-um beach [//] no to the mountains [//] I mean the beach actually"
309
+ - "there was lots of &-um &-um swimming and &-um sun"
310
+
311
+ Grammatical errors:
312
+ - "after swimming we [//] I eat [: ate] [*] &-um ice cream"
313
+ - "sometimes I forget [//] forgetted [: forgot] [*] what they call those things we built"
314
+ - "we saw [/] saw fishies [: fish] [*] swimming in the water"
315
+
316
+ Repetitions and revisions:
317
+ - "we [/] we stayed for &-um three no [//] four days"
318
+ - "I want to go back to the beach [/] beach next year"
319
+ - "sometimes I wonder [/] wonder where fishies [: fish] [*] go when it's cold"
320
+ <ERROR_EXAMPLES_END>"""
321
+
322
+ def parse_casl_response(response):
323
+ """Parse the LLM response for CASL analysis into structured data"""
324
+ # Extract speech factors section using section markers
325
+ speech_factors_section = ""
326
+ factors_pattern = re.compile(r"<SPEECH_FACTORS_START>(.*?)<SPEECH_FACTORS_END>", re.DOTALL)
327
+ factors_match = factors_pattern.search(response)
328
+
329
+ if factors_match:
330
+ speech_factors_section = factors_match.group(1).strip()
331
+ else:
332
+ speech_factors_section = "Error extracting speech factors from analysis."
333
+
334
+ # Extract CASL skills section
335
+ casl_section = ""
336
+ casl_pattern = re.compile(r"<CASL_SKILLS_START>(.*?)<CASL_SKILLS_END>", re.DOTALL)
337
+ casl_match = casl_pattern.search(response)
338
+
339
+ if casl_match:
340
+ casl_section = casl_match.group(1).strip()
341
+ else:
342
+ casl_section = "Error extracting CASL skills from analysis."
343
+
344
+ # Extract treatment recommendations
345
+ treatment_text = ""
346
+ treatment_pattern = re.compile(r"<TREATMENT_RECOMMENDATIONS_START>(.*?)<TREATMENT_RECOMMENDATIONS_END>", re.DOTALL)
347
+ treatment_match = treatment_pattern.search(response)
348
+
349
+ if treatment_match:
350
+ treatment_text = treatment_match.group(1).strip()
351
+ else:
352
+ treatment_text = "Error extracting treatment recommendations from analysis."
353
+
354
+ # Extract explanation section
355
+ explanation_text = ""
356
+ explanation_pattern = re.compile(r"<EXPLANATION_START>(.*?)<EXPLANATION_END>", re.DOTALL)
357
+ explanation_match = explanation_pattern.search(response)
358
+
359
+ if explanation_match:
360
+ explanation_text = explanation_match.group(1).strip()
361
+ else:
362
+ explanation_text = "Error extracting clinical explanation from analysis."
363
+
364
+ # Extract additional analysis
365
+ additional_analysis = ""
366
+ additional_pattern = re.compile(r"<ADDITIONAL_ANALYSIS_START>(.*?)<ADDITIONAL_ANALYSIS_END>", re.DOTALL)
367
+ additional_match = additional_pattern.search(response)
368
+
369
+ if additional_match:
370
+ additional_analysis = additional_match.group(1).strip()
371
+
372
+ # Extract diagnostic impressions
373
+ diagnostic_impressions = ""
374
+ diagnostic_pattern = re.compile(r"<DIAGNOSTIC_IMPRESSIONS_START>(.*?)<DIAGNOSTIC_IMPRESSIONS_END>", re.DOTALL)
375
+ diagnostic_match = diagnostic_pattern.search(response)
376
+
377
+ if diagnostic_match:
378
+ diagnostic_impressions = diagnostic_match.group(1).strip()
379
+
380
+ # Extract specific error examples
381
+ specific_errors_text = ""
382
+ errors_pattern = re.compile(r"<ERROR_EXAMPLES_START>(.*?)<ERROR_EXAMPLES_END>", re.DOTALL)
383
+ errors_match = errors_pattern.search(response)
384
+
385
+ if errors_match:
386
+ specific_errors_text = errors_match.group(1).strip()
387
+
388
+ # Create full report text
389
+ full_report = f"""
390
+ ## Speech Factors Analysis
391
+
392
+ {speech_factors_section}
393
+
394
+ ## CASL Skills Assessment
395
+
396
+ {casl_section}
397
+
398
+ ## Treatment Recommendations
399
+
400
+ {treatment_text}
401
+
402
+ ## Clinical Explanation
403
+
404
+ {explanation_text}
405
+ """
406
+
407
+ if additional_analysis:
408
+ full_report += f"\n## Additional Analysis\n\n{additional_analysis}"
409
+
410
+ if diagnostic_impressions:
411
+ full_report += f"\n## Diagnostic Impressions\n\n{diagnostic_impressions}"
412
+
413
+ if specific_errors_text:
414
+ full_report += f"\n## Detailed Error Examples\n\n{specific_errors_text}"
415
+
416
+ return {
417
+ 'speech_factors': speech_factors_section,
418
+ 'casl_data': casl_section,
419
+ 'treatment_suggestions': treatment_text,
420
+ 'explanation': explanation_text,
421
+ 'additional_analysis': additional_analysis,
422
+ 'diagnostic_impressions': diagnostic_impressions,
423
+ 'specific_errors': specific_errors_text,
424
+ 'full_report': full_report,
425
+ 'raw_response': response
426
+ }
427
+
428
+ def analyze_transcript(transcript, age, gender):
429
+ """Analyze a speech transcript using Claude"""
430
+ # CASL-2 assessment cheat sheet
431
+ cheat_sheet = """
432
+ # Speech-Language Pathologist Analysis Cheat Sheet
433
+
434
+ ## Types of Speech Patterns to Identify:
435
+
436
+ 1. Difficulty producing fluent, grammatical speech
437
+ - Fillers (um, uh) and pauses
438
+ - False starts and revisions
439
+ - Incomplete sentences
440
+
441
+ 2. Word retrieval issues
442
+ - Pauses before content words
443
+ - Circumlocutions (talking around a word)
444
+ - Word substitutions
445
+
446
+ 3. Grammatical errors
447
+ - Verb tense inconsistencies
448
+ - Subject-verb agreement errors
449
+ - Morphological errors (plurals, possessives)
450
+
451
+ 4. Repetitions and revisions
452
+ - Word or phrase repetitions [/]
453
+ - Self-corrections [//]
454
+ - Retracing
455
+
456
+ 5. Neologisms
457
+ - Made-up words
458
+ - Word blends
459
+
460
+ 6. Perseveration
461
+ - Inappropriate repetition of ideas
462
+ - Recurring themes
463
+
464
+ 7. Comprehension issues
465
+ - Topic maintenance difficulties
466
+ - Non-sequiturs
467
+ - Inappropriate responses
468
+ """
469
+
470
+ # Instructions for the analysis
471
+ instructions = """
472
+ Analyze this speech transcript to identify specific patterns and provide a detailed CASL-2 (Comprehensive Assessment of Spoken Language) assessment.
473
+
474
+ For each speech pattern you identify:
475
+ 1. Count the occurrences in the transcript
476
+ 2. Estimate a percentile (how typical/atypical this is for the age)
477
+ 3. Provide DIRECT QUOTES from the transcript as evidence
478
+
479
+ Then assess the following CASL-2 domains:
480
+
481
+ 1. Lexical/Semantic Skills:
482
+ - Assess vocabulary diversity, word-finding abilities, semantic precision
483
+ - Provide Standard Score (mean=100, SD=15), percentile rank, and performance level
484
+ - Include SPECIFIC QUOTES as evidence
485
+
486
+ 2. Syntactic Skills:
487
+ - Evaluate grammatical accuracy, sentence complexity, morphological skills
488
+ - Provide Standard Score, percentile rank, and performance level
489
+ - Include SPECIFIC QUOTES as evidence
490
+
491
+ 3. Supralinguistic Skills:
492
+ - Assess figurative language use, inferencing, and abstract reasoning
493
+ - Provide Standard Score, percentile rank, and performance level
494
+ - Include SPECIFIC QUOTES as evidence
495
+
496
+ YOUR RESPONSE MUST USE THESE EXACT SECTION MARKERS FOR PARSING:
497
+
498
+ <SPEECH_FACTORS_START>
499
+ Difficulty producing fluent, grammatical speech: (occurrences), (percentile)
500
+ Examples:
501
+ - "(direct quote from transcript)"
502
+ - "(direct quote from transcript)"
503
+
504
+ Word retrieval issues: (occurrences), (percentile)
505
+ Examples:
506
+ - "(direct quote from transcript)"
507
+ - "(direct quote from transcript)"
508
+
509
+ (And so on for each factor)
510
+ <SPEECH_FACTORS_END>
511
+
512
+ <CASL_SKILLS_START>
513
+ Lexical/Semantic Skills: Standard Score (X), Percentile Rank (X%), Performance Level
514
+ Examples:
515
+ - "(direct quote showing strength or weakness)"
516
+ - "(direct quote showing strength or weakness)"
517
+
518
+ Syntactic Skills: Standard Score (X), Percentile Rank (X%), Performance Level
519
+ Examples:
520
+ - "(direct quote showing strength or weakness)"
521
+ - "(direct quote showing strength or weakness)"
522
+
523
+ Supralinguistic Skills: Standard Score (X), Percentile Rank (X%), Performance Level
524
+ Examples:
525
+ - "(direct quote showing strength or weakness)"
526
+ - "(direct quote showing strength or weakness)"
527
+ <CASL_SKILLS_END>
528
+
529
+ <TREATMENT_RECOMMENDATIONS_START>
530
+ - (treatment recommendation)
531
+ - (treatment recommendation)
532
+ - (treatment recommendation)
533
+ <TREATMENT_RECOMMENDATIONS_END>
534
+
535
+ <EXPLANATION_START>
536
+ (brief diagnostic rationale based on findings)
537
+ <EXPLANATION_END>
538
+
539
+ <ADDITIONAL_ANALYSIS_START>
540
+ (specific insights that would be helpful for treatment planning)
541
+ <ADDITIONAL_ANALYSIS_END>
542
+
543
+ <DIAGNOSTIC_IMPRESSIONS_START>
544
+ (summarize findings across domains using specific examples and clear explanations)
545
+ <DIAGNOSTIC_IMPRESSIONS_END>
546
+
547
+ <ERROR_EXAMPLES_START>
548
+ (Copy all the specific quote examples here again, organized by error type or skill domain)
549
+ <ERROR_EXAMPLES_END>
550
+
551
+ MOST IMPORTANT:
552
+ 1. Use EXACTLY the section markers provided (like <SPEECH_FACTORS_START>) to make parsing reliable
553
+ 2. For EVERY factor and domain you analyze, you MUST provide direct quotes from the transcript as evidence
554
+ 3. Be very specific and cite the exact text
555
+ 4. Do not omit any of the required sections
556
+ """
557
+
558
+ # Prepare prompt for Claude with the user's role context
559
+ role_context = """
560
+ You are a speech pathologist, a healthcare professional who specializes in evaluating, diagnosing, and treating communication disorders, including speech, language, cognitive-communication, voice, swallowing, and fluency disorders. Your role is to help patients improve their speech and communication skills through various therapeutic techniques and exercises.
561
+
562
+ You are working with a student with speech impediments.
563
+
564
+ The most important thing is that you stay kind to the child. Be constructive and helpful rather than critical.
565
+ """
566
+
567
+ prompt = f"""
568
+ {role_context}
569
+
570
+ You are analyzing a transcript for a patient who is {age} years old and {gender}.
571
+
572
+ TRANSCRIPT:
573
+ {transcript}
574
+
575
+ {cheat_sheet}
576
+
577
+ {instructions}
578
+
579
+ Remember to be precise but compassionate in your analysis. Use direct quotes from the transcript for every factor and domain you analyze.
580
+ """
581
+
582
+ # Call the appropriate API or fallback to demo mode
583
+ response = generate_demo_response(prompt)
584
+
585
+ # Parse the response
586
+ results = parse_casl_response(response)
587
+
588
+ return results
589
+
590
+ def create_interface():
591
+ """Create the Gradio interface"""
592
+ # Set a theme compatible with Hugging Face Spaces
593
+ theme = gr.themes.Soft(
594
+ primary_hue="blue",
595
+ secondary_hue="indigo",
596
+ )
597
+
598
+ with gr.Blocks(title="Simple CASL Analysis Tool", theme=theme) as app:
599
+ gr.Markdown("# CASL Analysis Tool")
600
+ gr.Markdown("A simplified tool for analyzing speech transcripts and audio using CASL framework")
601
+
602
+ with gr.Tabs() as main_tabs:
603
+ # Analysis Tab
604
+ with gr.TabItem("Analysis", id=0):
605
+ with gr.Row():
606
+ with gr.Column(scale=1):
607
+ # Patient info
608
+ gr.Markdown("### Patient Information")
609
+ patient_name = gr.Textbox(label="Patient Name", placeholder="Enter patient name")
610
+ record_id = gr.Textbox(label="Record ID", placeholder="Enter record ID")
611
+
612
+ with gr.Row():
613
+ age = gr.Number(label="Age", value=8, minimum=1, maximum=120)
614
+ gender = gr.Radio(["male", "female", "other"], label="Gender", value="male")
615
+
616
+ assessment_date = gr.Textbox(
617
+ label="Assessment Date",
618
+ placeholder="MM/DD/YYYY",
619
+ value=datetime.now().strftime('%m/%d/%Y')
620
+ )
621
+ clinician_name = gr.Textbox(label="Clinician", placeholder="Enter clinician name")
622
+
623
+ # Transcript input
624
+ gr.Markdown("### Transcript")
625
+ sample_btn = gr.Button("Load Sample Transcript")
626
+ file_upload = gr.File(label="Upload transcript file (.txt or .cha)")
627
+ transcript = gr.Textbox(
628
+ label="Speech transcript (CHAT format preferred)",
629
+ placeholder="Enter transcript text or upload a file...",
630
+ lines=10
631
+ )
632
+
633
+ # Analysis button
634
+ analyze_btn = gr.Button("Analyze Transcript", variant="primary")
635
+
636
+ with gr.Column(scale=1):
637
+ # Results display
638
+ gr.Markdown("### Analysis Results")
639
+
640
+ analysis_output = gr.Markdown(label="Full Analysis")
641
+
642
+ # PDF export (only shown if ReportLab is available)
643
+ export_status = gr.Markdown("")
644
+ if REPORTLAB_AVAILABLE:
645
+ export_btn = gr.Button("Export as PDF", variant="secondary")
646
+ else:
647
+ gr.Markdown("⚠️ PDF export is disabled - ReportLab library is not installed")
648
+
649
+ # Transcription Tab
650
+ with gr.TabItem("Transcription", id=1):
651
+ with gr.Row():
652
+ with gr.Column(scale=1):
653
+ gr.Markdown("### Audio Transcription")
654
+ gr.Markdown("Upload an audio recording to automatically transcribe it in CHAT format")
655
+
656
+ # Patient's age helps with transcription accuracy
657
+ transcription_age = gr.Number(label="Patient Age", value=8, minimum=1, maximum=120,
658
+ info="For children under 10, special language models may be used")
659
+
660
+ # Audio input - FIXED: removed format parameter
661
+ audio_input = gr.Audio(type="filepath", label="Upload Audio Recording")
662
+
663
+ # Transcribe button
664
+ transcribe_btn = gr.Button("Transcribe Audio", variant="primary")
665
+
666
+ with gr.Column(scale=1):
667
+ # Transcription output
668
+ transcription_output = gr.Textbox(
669
+ label="Transcription Result",
670
+ placeholder="Transcription will appear here...",
671
+ lines=12
672
+ )
673
+
674
+ with gr.Row():
675
+ # Button to use transcription in analysis
676
+ copy_to_analysis_btn = gr.Button("Use for Analysis", variant="secondary")
677
+
678
+ # Status/info message
679
+ transcription_status = gr.Markdown("")
680
+
681
+ # Load sample transcript button
682
+ def load_sample():
683
+ return SAMPLE_TRANSCRIPT
684
+
685
+ sample_btn.click(load_sample, outputs=[transcript])
686
+
687
+ # File upload handler
688
+ file_upload.upload(process_upload, file_upload, transcript)
689
+
690
+ # Analysis button handler
691
+ def on_analyze_click(transcript_text, age_val, gender_val, patient_name_val, record_id_val, clinician_val, assessment_date_val):
692
+ if not transcript_text or len(transcript_text.strip()) < 50:
693
+ return "Error: Please provide a longer transcript for analysis."
694
+
695
+ try:
696
+ # Get the analysis results
697
+ results = analyze_transcript(transcript_text, age_val, gender_val)
698
+
699
+ # Return the full report
700
+ return results['full_report']
701
+
702
+ except Exception as e:
703
+ logger.exception("Error during analysis")
704
+ return f"Error during analysis: {str(e)}"
705
+
706
+ analyze_btn.click(
707
+ on_analyze_click,
708
+ inputs=[
709
+ transcript, age, gender,
710
+ patient_name, record_id, clinician_name, assessment_date
711
+ ],
712
+ outputs=[analysis_output]
713
+ )
714
+
715
+ # Transcription button handler
716
+ def on_transcribe_audio(audio_path, age_val):
717
+ try:
718
+ if not audio_path:
719
+ return "Please upload an audio file to transcribe.", "Error: No audio file provided."
720
+
721
+ # Process the audio file with local transcription
722
+ transcription = transcribe_audio_local(audio_path)
723
+
724
+ # Return status message based on whether it's a demo or real transcription
725
+ if not SPEECH_RECOGNITION_AVAILABLE:
726
+ status_msg = "⚠️ Demo mode: Using example transcription (speech_recognition not installed)"
727
+ else:
728
+ status_msg = "✅ Transcription completed successfully"
729
+
730
+ return transcription, status_msg
731
+ except Exception as e:
732
+ logger.exception("Error transcribing audio")
733
+ return f"Error: {str(e)}", f"❌ Transcription failed: {str(e)}"
734
+
735
+ # Connect the transcribe button to its handler
736
+ transcribe_btn.click(
737
+ on_transcribe_audio,
738
+ inputs=[audio_input, transcription_age],
739
+ outputs=[transcription_output, transcription_status]
740
+ )
741
+
742
+ # Copy transcription to analysis tab
743
+ def copy_to_analysis(transcription):
744
+ return transcription, gr.update(selected=0) # Switch to Analysis tab
745
+
746
+ copy_to_analysis_btn.click(
747
+ copy_to_analysis,
748
+ inputs=[transcription_output],
749
+ outputs=[transcript, main_tabs]
750
+ )
751
+
752
+ return app
753
+
754
+ if __name__ == "__main__":
755
+ # Check for AWS credentials
756
+ if not AWS_ACCESS_KEY or not AWS_SECRET_KEY:
757
+ print("NOTE: AWS credentials not found. The app will run in demo mode with simulated responses.")
758
+ print("To enable full functionality, set AWS_ACCESS_KEY and AWS_SECRET_KEY environment variables.")
759
+
760
+ app = create_interface()
761
+ app.launch(show_api=False) # Disable API tab for security