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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
import gradio as gr
import boto3
import json
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import re
import logging
import os
import pickle
import csv
from PIL import Image
import io
import PyPDF2
import uuid
from datetime import datetime

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# AWS credentials for Bedrock API
# For HuggingFace Spaces, set these as secrets in the Space settings
AWS_ACCESS_KEY = os.getenv("AWS_ACCESS_KEY", "")
AWS_SECRET_KEY = os.getenv("AWS_SECRET_KEY", "")
AWS_REGION = os.getenv("AWS_REGION", "us-east-1")

# Initialize Bedrock client if credentials are available
bedrock_client = None
if AWS_ACCESS_KEY and AWS_SECRET_KEY:
    try:
        bedrock_client = boto3.client(
            'bedrock-runtime',
            aws_access_key_id=AWS_ACCESS_KEY,
            aws_secret_access_key=AWS_SECRET_KEY,
            region_name=AWS_REGION
        )
        logger.info("Bedrock client initialized successfully")
    except Exception as e:
        logger.error(f"Failed to initialize Bedrock client: {str(e)}")

# Sample transcript for the demo
SAMPLE_TRANSCRIPT = """*PAR: today I would &-um like to talk about &-um a fun trip I took last &-um summer with my family.
*PAR: we went to the &-um &-um beach [//] no to the mountains [//] I mean the beach actually.
*PAR: there was lots of &-um &-um swimming and &-um sun.
*PAR: we [/] we stayed for &-um three no [//] four days in a &-um hotel near the water [: ocean] [*].
*PAR: my favorite part was &-um building &-um castles with sand.
*PAR: sometimes I forget [//] forgetted [: forgot] [*] what they call those things we built.
*PAR: my brother he [//] he helped me dig a big hole.
*PAR: we saw [/] saw fishies [: fish] [*] swimming in the water.
*PAR: sometimes I wonder [/] wonder where fishies [: fish] [*] go when it's cold.
*PAR: maybe they have [/] have houses under the water.
*PAR: after swimming we [//] I eat [: ate] [*] &-um ice cream with &-um chocolate things on top.
*PAR: what do you call those &-um &-um sprinkles! that's the word.
*PAR: my mom said to &-um that I could have &-um two scoops next time.
*PAR: I want to go back to the beach [/] beach next year."""

# ===============================
# Database and Storage Functions
# ===============================

# Create data directories if they don't exist
DATA_DIR = "patient_data"
RECORDS_FILE = os.path.join(DATA_DIR, "patient_records.csv")
ANALYSES_DIR = os.path.join(DATA_DIR, "analyses")

def ensure_data_dirs():
    """Ensure data directories exist"""
    os.makedirs(DATA_DIR, exist_ok=True)
    os.makedirs(ANALYSES_DIR, exist_ok=True)
    
    # Create records file if it doesn't exist
    if not os.path.exists(RECORDS_FILE):
        with open(RECORDS_FILE, 'w', newline='') as f:
            writer = csv.writer(f)
            writer.writerow([
                "ID", "Name", "Record ID", "Age", "Gender", 
                "Assessment Date", "Clinician", "Analysis Date", "File Path"
            ])

# Initialize data directories
ensure_data_dirs()

def save_patient_record(patient_info, analysis_results, transcript):
    """Save patient record to storage"""
    try:
        # Generate unique ID for the record
        record_id = str(uuid.uuid4())
        
        # Extract patient information
        name = patient_info.get("name", "")
        patient_id = patient_info.get("record_id", "")
        age = patient_info.get("age", "")
        gender = patient_info.get("gender", "")
        assessment_date = patient_info.get("assessment_date", "")
        clinician = patient_info.get("clinician", "")
        
        # Create filename for the analysis data
        filename = f"analysis_{record_id}.pkl"
        filepath = os.path.join(ANALYSES_DIR, filename)
        
        # Save analysis data
        with open(filepath, 'wb') as f:
            pickle.dump({
                "patient_info": patient_info,
                "analysis_results": analysis_results,
                "transcript": transcript,
                "timestamp": datetime.now().isoformat(),
            }, f)
        
        # Add record to CSV file
        with open(RECORDS_FILE, 'a', newline='') as f:
            writer = csv.writer(f)
            writer.writerow([
                record_id, name, patient_id, age, gender, 
                assessment_date, clinician, datetime.now().strftime('%Y-%m-%d'),
                filepath
            ])
        
        return record_id
    
    except Exception as e:
        logger.error(f"Error saving patient record: {str(e)}")
        return None

def load_patient_record(record_id):
    """Load patient record from storage"""
    try:
        # Find the record in the CSV file
        with open(RECORDS_FILE, 'r', newline='') as f:
            reader = csv.reader(f)
            next(reader)  # Skip header
            for row in reader:
                if row[0] == record_id:
                    file_path = row[8]
                    
                    # Load and return the data
                    with open(file_path, 'rb') as f:
                        return pickle.load(f)
        
        return None
    
    except Exception as e:
        logger.error(f"Error loading patient record: {str(e)}")
        return None

def get_all_patient_records():
    """Return a list of all patient records"""
    try:
        records = []
        if os.path.exists(RECORDS_FILE):
            with open(RECORDS_FILE, 'r', newline='') as f:
                reader = csv.reader(f)
                next(reader)  # Skip header
                for row in reader:
                    records.append({
                        "id": row[0],
                        "name": row[1],
                        "record_id": row[2],
                        "age": row[3],
                        "gender": row[4],
                        "assessment_date": row[5],
                        "clinician": row[6],
                        "analysis_date": row[7]
                    })
        return records
    
    except Exception as e:
        logger.error(f"Error getting patient records: {str(e)}")
        return []

# ===============================
# Utility Functions
# ===============================

def read_pdf(file_path):
    """Read text from a PDF file"""
    try:
        with open(file_path, 'rb') as file:
            pdf_reader = PyPDF2.PdfReader(file)
            text = ""
            for page in pdf_reader.pages:
                text += page.extract_text()
            return text
    except Exception as e:
        logger.error(f"Error reading PDF: {str(e)}")
        return ""

def read_cha_file(file_path):
    """Read and parse a .cha transcript file"""
    try:
        with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
            content = f.read()
            
        # Extract participant lines (starting with *PAR:)
        par_lines = []
        for line in content.splitlines():
            if line.startswith('*PAR:'):
                par_lines.append(line)
                
        # If no PAR lines found, just return the whole content
        if not par_lines:
            return content
            
        return '\n'.join(par_lines)
    
    except Exception as e:
        logger.error(f"Error reading CHA file: {str(e)}")
        return ""

def process_upload(file):
    """Process an uploaded file (PDF, text, or CHA)"""
    if file is None:
        return ""
    
    file_path = file.name
    if file_path.endswith('.pdf'):
        return read_pdf(file_path)
    elif file_path.endswith('.cha'):
        return read_cha_file(file_path)
    else:
        with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
            return f.read()

# ===============================
# AI Model Interface Functions
# ===============================

def call_bedrock(prompt, max_tokens=4096):
    """Call the AWS Bedrock API to analyze text using Claude"""
    if not bedrock_client:
        return "AWS credentials not configured. Please set your AWS credentials as secrets in the Space settings."
    
    try:
        body = json.dumps({
            "anthropic_version": "bedrock-2023-05-31",
            "max_tokens": max_tokens,
            "messages": [
                {
                    "role": "user",
                    "content": prompt
                }
            ],
            "temperature": 0.3,
            "top_p": 0.9
        })

        modelId = 'anthropic.claude-3-sonnet-20240229-v1:0'
        response = bedrock_client.invoke_model(
            body=body, 
            modelId=modelId, 
            accept='application/json', 
            contentType='application/json'
        )
        response_body = json.loads(response.get('body').read())
        return response_body['content'][0]['text']
    except Exception as e:
        logger.error(f"Error in call_bedrock: {str(e)}")
        return f"Error: {str(e)}"

def generate_demo_response(prompt):
    """Generate a simulated response for demo purposes"""
    # This function generates a realistic but fake response for demo purposes
    # In a real deployment, you would call an actual LLM API
    
    random_seed = sum(ord(c) for c in prompt) % 1000  # Generate a seed based on prompt
    np.random.seed(random_seed)
    
    # Simulate speech factors with random but reasonable values
    factors = [
        "Difficulty producing fluent speech",
        "Word retrieval issues",
        "Grammatical errors",
        "Repetitions and revisions",
        "Neologisms",
        "Perseveration",
        "Comprehension issues"
    ]
    
    occurrences = np.random.randint(1, 15, size=len(factors))
    percentiles = np.random.randint(30, 95, size=len(factors))
    
    # Simulate CASL scores
    domains = ["Lexical/Semantic", "Syntactic", "Supralinguistic"]
    scores = np.random.randint(80, 115, size=3)
    percentiles_casl = [int(np.interp(s, [70, 85, 100, 115, 130], [2, 16, 50, 84, 98])) for s in scores]
    
    perf_levels = []
    for s in scores:
        if s < 70: perf_levels.append("Well Below Average")
        elif s < 85: perf_levels.append("Below Average")
        elif s < 115: perf_levels.append("Average")
        elif s < 130: perf_levels.append("Above Average")
        else: perf_levels.append("Well Above Average")
    
    # Build response
    response = "## Speech Factor Analysis\n\n"
    for i, factor in enumerate(factors):
        response += f"{factor}: {occurrences[i]}, {percentiles[i]}\n"
    
    response += "\n## CASL-2 Assessment\n\n"
    for i, domain in enumerate(domains):
        response += f"{domain} Skills: Standard Score ({scores[i]}), Percentile Rank ({percentiles_casl[i]}%), Performance Level ({perf_levels[i]})\n"
    
    response += "\n## Other analysis/Best plans of action:\n\n"
    suggestions = [
        "Implement word-finding strategies with semantic cuing",
        "Practice structured narrative tasks with visual supports",
        "Use sentence formulation exercises with increasing complexity",
        "Incorporate self-monitoring techniques during structured conversations",
        "Work on grammatical forms through structured practice"
    ]
    for suggestion in suggestions:
        response += f"- {suggestion}\n"
    
    response += "\n## Explanation:\n\n"
    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"
    
    response += "\n## Additional Analysis:\n\n"
    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."
    
    return response

def generate_demo_transcription(audio_path):
    """Generate a simulated transcription response"""
    # In a real app, this would process an audio file
    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."

def generate_demo_qa_response(question):
    """Generate a simulated Q&A response"""
    qa_responses = {
        "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.",
        "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.",
        "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.",
        "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.",
        "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.",
    }
    
    # Simple keyword matching for demo purposes
    for key, response in qa_responses.items():
        if key in question.lower():
            return response
    
    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."

# ===============================
# Analysis Functions
# ===============================

def parse_casl_response(response):
    """Parse the LLM response for CASL analysis into structured data"""
    lines = response.split('\n')
    data = {
        'Factor': [],
        'Occurrences': [],
        'Severity': [],
        'Examples': []  # Added field for error examples
    }
    
    casl_data = {
        'Domain': ['Lexical/Semantic', 'Syntactic', 'Supralinguistic'],
        'Standard Score': [0, 0, 0],
        'Percentile': [0, 0, 0],
        'Performance Level': ['', '', ''],
        'Examples': ['', '', '']  # Added field for specific examples
    }
    
    treatment_suggestions = []
    explanation = ""
    additional_analysis = ""
    specific_errors = {}  # Track specific error examples by factor
    raw_response = response  # Store the complete raw LLM response
    
    # Pattern to match factor lines - updated to potentially capture examples
    factor_pattern = re.compile(r'([\w\s/]+):\s*(\d+)[,\s]+(\d+)(?:\s*-\s*(.+))?')
    
    # Pattern to match CASL data
    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]+)\)')
    
    # Pattern to find examples
    example_pattern = re.compile(r'(?:Example|Examples|observed|observed in)[^\"\'"]*[\"\']([^\"\']*)[\"\']')
    error_pattern = re.compile(r'(?:error|errors|difficulty|difficulties)[^\"\'"]*[\"\']([^\"\']*)[\"\']')
    
    current_factor = None
    current_domain = None
    in_suggestions = False
    in_explanation = False
    in_additional = False
    in_examples = False
    
    for i, line in enumerate(lines):
        line = line.strip()
        
        # Skip empty lines
        if not line:
            continue
            
        # Check for factor data
        factor_match = factor_pattern.search(line)
        if factor_match:
            factor = factor_match.group(1).strip()
            occurrences = int(factor_match.group(2))
            severity = int(factor_match.group(3))
            example = factor_match.group(4) if factor_match.group(4) else ""
            
            # Look ahead to find examples for this factor
            if not example:
                # Check next few lines for examples
                for j in range(i+1, min(i+5, len(lines))):
                    next_line = lines[j].strip()
                    if next_line and ('"' in next_line or "'" in next_line):
                        example_match = example_pattern.search(next_line)
                        if example_match:
                            example = example_match.group(1)
                            break
                        error_match = error_pattern.search(next_line)
                        if error_match:
                            example = error_match.group(1)
                            break
            
            data['Factor'].append(factor)
            data['Occurrences'].append(occurrences)
            data['Severity'].append(severity)
            data['Examples'].append(example)
            specific_errors[factor] = example
            current_factor = factor
            continue
            
        # Check for CASL data
        casl_match = casl_pattern.search(line)
        if casl_match:
            domain = casl_match.group(1)
            score = int(casl_match.group(2))
            percentile = int(casl_match.group(3))
            level = casl_match.group(4)
            
            domain_examples = ""
            # Look ahead for examples related to this domain
            for j in range(i+1, min(i+10, len(lines))):
                next_line = lines[j].strip()
                if "Domain:" in next_line or casl_pattern.search(next_line):
                    break
                if ('"' in next_line or "'" in next_line) and "example" in next_line.lower():
                    example_match = re.search(r'[\"\']([^\"\']*)[\"\']', next_line)
                    if example_match:
                        domain_examples = example_match.group(1)
                        break
            
            if "Lexical" in domain:
                casl_data['Standard Score'][0] = score
                casl_data['Percentile'][0] = percentile
                casl_data['Performance Level'][0] = level
                casl_data['Examples'][0] = domain_examples
                current_domain = "Lexical/Semantic"
            elif "Syntactic" in domain:
                casl_data['Standard Score'][1] = score
                casl_data['Percentile'][1] = percentile
                casl_data['Performance Level'][1] = level
                casl_data['Examples'][1] = domain_examples
                current_domain = "Syntactic"
            elif "Supralinguistic" in domain:
                casl_data['Standard Score'][2] = score
                casl_data['Percentile'][2] = percentile
                casl_data['Performance Level'][2] = level
                casl_data['Examples'][2] = domain_examples
                current_domain = "Supralinguistic"
            continue
        
        # Check for section headers
        if "Other analysis/Best plans of action:" in line or "### Recommended Treatment Approaches" in line or "Treatment Recommendations:" in line:
            in_suggestions = True
            in_explanation = False
            in_additional = False
            in_examples = False
            continue
        elif "Explanation:" in line or "### Clinical Rationale" in line or "Clinical Rationale:" in line:
            in_suggestions = False
            in_explanation = True
            in_additional = False
            in_examples = False
            continue
        elif "Additional Analysis:" in line or "Further Observations:" in line:
            in_suggestions = False
            in_explanation = False
            in_additional = True
            in_examples = False
            continue
        elif "Examples:" in line or "Specific Errors:" in line:
            in_suggestions = False
            in_explanation = False
            in_additional = False
            in_examples = True
            continue
            
        # Add content to appropriate section
        if in_suggestions:
            if line.startswith("- "):
                treatment_suggestions.append(line[2:])  # Remove the bullet point
            elif line.startswith("•"):
                treatment_suggestions.append(line[1:].strip())  # Remove bullet and trim
            elif line and not line.startswith("#"):
                # Non-empty, non-header lines might be treatment suggestions without bullets
                treatment_suggestions.append(line)
        elif in_explanation:
            explanation += line + "\n"
        elif in_additional:
            additional_analysis += line + "\n"
        elif in_examples and current_factor and not specific_errors.get(current_factor):
            # Look for quoted examples in the examples section
            if '"' in line or "'" in line:
                example_match = re.search(r'[\"\']([^\"\']*)[\"\']', line)
                if example_match:
                    specific_errors[current_factor] = example_match.group(1)
                    # Update the examples in the dataframe
                    if current_factor in data['Factor']:
                        idx = data['Factor'].index(current_factor)
                        data['Examples'][idx] = example_match.group(1)
        
        # Continuously look for examples with quotes regardless of section
        if ('"' in line or "'" in line) and current_factor:
            if re.search(rf'{current_factor}.*[\"\']([^\"\']*)[\"\']', line, re.IGNORECASE):
                example_match = re.search(r'[\"\']([^\"\']*)[\"\']', line)
                if example_match:
                    specific_errors[current_factor] = example_match.group(1)
                    # Update in dataframe
                    if current_factor in data['Factor']:
                        idx = data['Factor'].index(current_factor)
                        data['Examples'][idx] = example_match.group(1)
    
    # Process specific errors and examples if they're presented as a list later in the text
    for i, line in enumerate(lines):
        if "examples of errors" in line.lower() or "error examples" in line.lower():
            # Look through next few lines for examples
            for j in range(i+1, min(i+15, len(lines))):
                example_line = lines[j].strip()
                if not example_line or example_line.startswith("#"):
                    continue
                    
                # Look for factors mentioned with examples
                for factor in data['Factor']:
                    if factor.lower() in example_line.lower() and ('"' in example_line or "'" in example_line):
                        example_match = re.search(r'[\"\']([^\"\']*)[\"\']', example_line)
                        if example_match:
                            idx = data['Factor'].index(factor)
                            data['Examples'][idx] = example_match.group(1)
                            specific_errors[factor] = example_match.group(1)
    
    return {
        'speech_factors': pd.DataFrame(data),
        'casl_data': pd.DataFrame(casl_data),
        'treatment_suggestions': treatment_suggestions,
        'explanation': explanation,
        'additional_analysis': additional_analysis,
        'specific_errors': specific_errors,
        'raw_response': raw_response  # Include the full LLM response
    }

def create_casl_plots(speech_factors, casl_data):
    """Create visualizations for the CASL analysis results"""
    
    # Set a professional style for the plots
    plt.style.use('seaborn-v0_8-pastel')
    
    # Create figure with two subplots
    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 6), dpi=100)
    
    # Plot speech factors - sorted by occurrence count
    if not speech_factors.empty:
        # Sort the dataframe
        speech_factors_sorted = speech_factors.sort_values('Occurrences', ascending=False)
        
        # Custom colors
        speech_colors = ['#4C72B0', '#55A868', '#C44E52', '#8172B3', '#CCB974', '#64B5CD', '#4C72B0']
        
        # Create horizontal bar chart
        bars = ax1.barh(speech_factors_sorted['Factor'], 
               speech_factors_sorted['Occurrences'], 
               color=speech_colors[:len(speech_factors_sorted)])
        
        # Add count labels at the end of each bar
        for i, bar in enumerate(bars):
            width = bar.get_width()
            factor = speech_factors_sorted.iloc[i]['Factor']
            
            # Get severity percentile for this factor
            severity = speech_factors_sorted.iloc[i]['Severity']
            
            # Label with both count and severity percentile
            ax1.text(width + 0.3, bar.get_y() + bar.get_height()/2, 
                    f'{width:.0f} ({severity}%)', ha='left', va='center')
            
            # Add example as annotation if available
            if 'Examples' in speech_factors_sorted.columns:
                example = speech_factors_sorted.iloc[i]['Examples']
                if example and len(example) > 0:
                    # Add a small marker to indicate example exists
                    ax1.text(0.5, bar.get_y() + bar.get_height()/2, 
                            '★', ha='center', va='center', color='#C44E52', 
                            fontsize=8, fontweight='bold')
        
        ax1.set_title('Speech Factors Analysis', fontsize=14, fontweight='bold')
        ax1.set_xlabel('Number of Occurrences', fontsize=11)
        # No y-label needed for horizontal bar chart
        
        # Remove top and right spines
        ax1.spines['top'].set_visible(False)
        ax1.spines['right'].set_visible(False)
        
        # Add a footnote about the star symbol
        ax1.annotate('★ = Example available in details panel', xy=(0, -0.1), xycoords='axes fraction', 
                   fontsize=8, ha='left', va='center', color='#C44E52')
    
    # Plot CASL domains
    domain_names = casl_data['Domain']
    y_scores = casl_data['Standard Score']
    percentiles = casl_data['Percentile']
    
    # Custom color scheme
    casl_colors = ['#4C72B0', '#55A868', '#C44E52']
    
    # Create bars with nice colors
    bars = ax2.bar(domain_names, y_scores, color=casl_colors)
    
    # Add score labels on top of each bar
    for i, bar in enumerate(bars):
        height = bar.get_height()
        score = y_scores.iloc[i]
        percentile = percentiles.iloc[i]
        
        # Label with both score and percentile
        ax2.text(bar.get_x() + bar.get_width()/2., height + 1,
                f'{score:.0f} ({percentile}%)', ha='center', va='bottom')
        
        # Add a star marker if example exists
        if 'Examples' in casl_data.columns:
            example = casl_data.iloc[i]['Examples']
            if example and len(example) > 0:
                ax2.text(bar.get_x() + bar.get_width()/2., height/2,
                        '★', ha='center', va='center', color='white', 
                        fontsize=12, fontweight='bold')
    
    # Add score reference lines
    ax2.axhline(y=100, linestyle='--', color='gray', alpha=0.7, label='Average (100)')
    ax2.axhline(y=85, linestyle=':', color='orange', alpha=0.7, label='Below Average (<85)')
    ax2.axhline(y=115, linestyle=':', color='green', alpha=0.7, label='Above Average (>115)')
    
    # Add labels and title
    ax2.set_title('CASL-2 Standard Scores', fontsize=14, fontweight='bold')
    ax2.set_ylabel('Standard Score', fontsize=11)
    ax2.set_ylim(bottom=0, top=max(130, max(y_scores) + 15))  # Set y-axis limit with some padding
    
    # Add legend
    ax2.legend(loc='upper right', fontsize='small')
    
    # Remove top and right spines
    ax2.spines['top'].set_visible(False)
    ax2.spines['right'].set_visible(False)
    
    # Add overall figure title
    fig.suptitle('Speech Analysis Results', fontsize=16, fontweight='bold', y=0.98)
    
    # Add a subtitle with note about examples
    plt.figtext(0.5, 0.01, '★ indicates specific examples available in the Error Examples panel', 
                ha='center', fontsize=9, fontstyle='italic')
    
    plt.tight_layout(rect=[0, 0.03, 1, 0.95])  # Adjust layout to make room for suptitle
    
    # Save plot to buffer
    buf = io.BytesIO()
    plt.savefig(buf, format='png', bbox_inches='tight')
    buf.seek(0)
    plt.close()
    
    return buf

def create_casl_radar_chart(speech_factors):
    """Create a radar chart for speech factors (percentiles)"""
    
    if speech_factors.empty or 'Severity' not in speech_factors.columns:
        # Create a placeholder image if no data
        plt.figure(figsize=(8, 8))
        plt.text(0.5, 0.5, "No data available for radar chart", 
                ha='center', va='center', fontsize=14)
        plt.axis('off')
        
        buf = io.BytesIO()
        plt.savefig(buf, format='png')
        buf.seek(0)
        plt.close()
        return buf
    
    # Prepare data for radar chart
    categories = speech_factors['Factor'].tolist()
    percentiles = speech_factors['Severity'].tolist()
    
    # Need to repeat first value to close the polygon
    categories = categories + [categories[0]]
    percentiles = percentiles + [percentiles[0]]
    
    # Convert to radians and calculate points
    N = len(categories) - 1  # Subtract 1 for the repeated point
    angles = [n / float(N) * 2 * np.pi for n in range(N)]
    angles += angles[:1]  # Repeat the first angle to close the polygon
    
    # Create the plot
    fig = plt.figure(figsize=(8, 8))
    ax = fig.add_subplot(111, polar=True)
    
    # Draw percentile lines with labels
    plt.xticks(angles[:-1], categories[:-1], size=12)
    ax.set_rlabel_position(0)
    plt.yticks([20, 40, 60, 80, 100], ["20", "40", "60", "80", "100"], color="grey", size=10)
    plt.ylim(0, 100)
    
    # Plot data
    ax.plot(angles, percentiles, linewidth=1, linestyle='solid', color='#4C72B0')
    ax.fill(angles, percentiles, color='#4C72B0', alpha=0.25)
    
    # Add title
    plt.title('Speech Factors Severity (Percentile)', size=15, fontweight='bold', pad=20)
    
    # Save to buffer
    buf = io.BytesIO()
    plt.savefig(buf, format='png', bbox_inches='tight')
    buf.seek(0)
    plt.close()
    
    return buf

def analyze_transcript(transcript, age, gender):
    """Analyze a speech transcript using the CASL framework"""
    
    # CHAT transcription symbol cheat sheet
    cheat_sheet = """
    CHAT TRANSCRIPTION SYMBOL SUMMARY -- Abridged for AphasiaBank

    Basic Utterance Terminators
    .    period
    ?    question
    !    exclamation

    Special Utterance Terminators
    +…    trailing off
    +..?    trailing off of a question
    +/.    interruption by another speaker
    +/?    interruption of a question by another speaker
    +//.    self-interruption
    +//?    self-interruption of a question
    +"/.    quotation follows on next line
    +"    quoted utterance occurs on this line (use at beginning of utterance
        as link, not a terminator)
    +<    lazy overlap marking (at beginning of utterance that overlapped the
        the previous utterance)

    @n    neologism (e.g., sakov@n)
    exclamations    common ones:  ah, aw, haha, ow, oy, sh, ugh, uhoh
    interjections    common ones:  mhm, uhhuh, hm, uhuh
    fillers    common ones:  &-um, &-uh
    letters    s@l
    letter sequence    abcdefg@k
    xxx    unintelligible speech, not treated as a word
    www        untranscribed material (e.g., looking through pictures, talking with
            spouse), must be followed by %exp tier (see below)
    &+sounds    phonological fragment (&+sh &+w  we came home)

    Scoped Symbols
    [: text]    target/intended word for errors (e.g., tried [: cried])
    [*]    error (e.g., paraphasia -- wɛk@u [: wet] [*])
    [/]    retracing without correction (e.g., simple repetition)
        put repeated items between <> unless only one word was repeated
    [//]    retracing with correction (e.g., simple word or grammar change)
        put changed items between <> unless only one word was changed
    """
    
    # Instructions for the LLM analysis
    instructions = """
    You are a speech pathologist analyzing this transcription sample. Provide a detailed analysis focused on specific quotes from the transcript.

    The factors of speech that you need to count are:

    1. Difficulty producing fluent, grammatical speech - speech that is slow, halting, with pauses while searching for words
    2. Word retrieval issues - trouble thinking of specific words, use of filler words like um, circumlocution, semantically similar word substitutions
    3. Grammatical errors - missing/incorrect function words, problems with verb tenses, conjugation, agreement, simplified sentences
    4. Repetitions and revisions - repeating or restating words, phrases or sentences due to trouble finding the right words
    5. Neologisms - creating nonexistent "new" words
    6. Perseveration - unintentionally repeating words or phrases over and over
    7. Comprehension issues - trouble understanding complex sentences, fast speech, relying more on context and cues

    For each factor, provide:
    - Number of occurrences
    - Severity percentile (estimate based on your clinical judgment)
    - At least 2-3 specific quotes from the transcript as examples

    Then evaluate using the CASL-2 Speech and Language Analysis Framework across these domains:

    1. Lexical/Semantic Skills:
       - Assess vocabulary diversity, word-finding abilities, semantic precision
       - Provide Standard Score (mean=100, SD=15), percentile rank, and performance level
       - Include SPECIFIC QUOTES as evidence

    2. Syntactic Skills:
       - Evaluate grammatical accuracy, sentence complexity, morphological skills
       - Provide Standard Score, percentile rank, and performance level
       - Include SPECIFIC QUOTES as evidence

    3. Supralinguistic Skills:
       - Assess figurative language use, inferencing, and abstract reasoning
       - Provide Standard Score, percentile rank, and performance level
       - Include SPECIFIC QUOTES as evidence

    YOUR RESPONSE MUST USE THESE EXACT SECTION MARKERS FOR PARSING:

    <SPEECH_FACTORS_START>
    Difficulty producing fluent, grammatical speech: (occurrences), (percentile)
    Examples:
    - "(direct quote from transcript)"
    - "(direct quote from transcript)"
    
    Word retrieval issues: (occurrences), (percentile)
    Examples:
    - "(direct quote from transcript)"
    - "(direct quote from transcript)"
    
    (And so on for each factor)
    <SPEECH_FACTORS_END>
    
    <CASL_SKILLS_START>
    Lexical/Semantic Skills: Standard Score (X), Percentile Rank (X%), Performance Level
    Examples:
    - "(direct quote showing strength or weakness)"
    - "(direct quote showing strength or weakness)"
    
    Syntactic Skills: Standard Score (X), Percentile Rank (X%), Performance Level
    Examples:
    - "(direct quote showing strength or weakness)"
    - "(direct quote showing strength or weakness)"
    
    Supralinguistic Skills: Standard Score (X), Percentile Rank (X%), Performance Level
    Examples:
    - "(direct quote showing strength or weakness)"
    - "(direct quote showing strength or weakness)"
    <CASL_SKILLS_END>
    
    <TREATMENT_RECOMMENDATIONS_START>
    - (treatment recommendation)
    - (treatment recommendation)
    - (treatment recommendation)
    <TREATMENT_RECOMMENDATIONS_END>
    
    <EXPLANATION_START>
    (brief diagnostic rationale based on findings)
    <EXPLANATION_END>
    
    <ADDITIONAL_ANALYSIS_START>
    (specific insights that would be helpful for treatment planning)
    <ADDITIONAL_ANALYSIS_END>
    
    <DIAGNOSTIC_IMPRESSIONS_START>
    (summarize findings across domains using specific examples and clear explanations)
    <DIAGNOSTIC_IMPRESSIONS_END>
    
    <ERROR_EXAMPLES_START>
    (Copy all the specific quote examples here again, organized by error type or skill domain)
    <ERROR_EXAMPLES_END>
    
    MOST IMPORTANT: 
    1. Use EXACTLY the section markers provided (like <SPEECH_FACTORS_START>) to make parsing reliable
    2. For EVERY factor and domain you analyze, you MUST provide direct quotes from the transcript as evidence
    3. Be very specific and cite the exact text
    4. Do not omit any of the required sections
    """
    
    # Prepare prompt for Claude with the user's role context
    role_context = """
    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.

    You are working with a student with speech impediments.

    The most important thing is that you stay kind to the child. Be constructive and helpful rather than critical.
    """
    
    prompt = f"""
    {role_context}
    
    You are analyzing a transcript for a patient who is {age} years old and {gender}.
    
    TRANSCRIPT:
    {transcript}
    
    {cheat_sheet}
    
    {instructions}
    
    Remember to be precise but compassionate in your analysis. Use direct quotes from the transcript for every factor and domain you analyze.
    """
    
    # Call the appropriate API or fallback to demo mode
    if bedrock_client:
        response = call_bedrock(prompt)
    else:
        response = generate_demo_response(prompt)
    
    # Parse the response
    results = parse_casl_response(response)
    
    # Create visualizations
    plot_image = create_casl_plots(results['speech_factors'], results['casl_data'])
    radar_image = create_casl_radar_chart(results['speech_factors'])
    
    return results, plot_image, radar_image, response

def generate_report(patient_info, analysis_results, report_type="formal"):
    """Generate a professional report based on analysis results"""
    
    patient_name = patient_info.get("name", "")
    record_id = patient_info.get("record_id", "")
    age = patient_info.get("age", "")
    gender = patient_info.get("gender", "")
    assessment_date = patient_info.get("assessment_date", datetime.now().strftime('%m/%d/%Y'))
    clinician = patient_info.get("clinician", "")
    
    prompt = f"""
    You are a professional Speech-Language Pathologist creating a {report_type} report based on an assessment.
    
    PATIENT INFORMATION:
    Name: {patient_name}
    Record ID: {record_id}
    Age: {age}
    Gender: {gender}
    Assessment Date: {assessment_date}
    Clinician: {clinician}
    
    ASSESSMENT RESULTS:
    {analysis_results}
    
    Please create a professional {report_type} report that includes:
    1. Patient information and assessment details
    2. Summary of findings (strengths and areas of concern)
    3. Detailed analysis of language domains
    4. Specific recommendations for therapy
    5. Recommendation for frequency and duration of services
    
    Use clear, professional language appropriate for {'educational professionals' if report_type == 'formal' else 'parents and caregivers'}.
    Format the report with proper headings and sections.
    """
    
    # Call the API or use demo mode
    if bedrock_client:
        report = call_bedrock(prompt, max_tokens=6000)
    else:
        # For demo, create a simulated report
        if report_type == 'formal':
            report = f"""
            # FORMAL LANGUAGE ASSESSMENT REPORT
            
            **Date of Assessment:** {assessment_date}
            **Clinician:** {clinician}
            
            ## PATIENT INFORMATION
            **Name:** {patient_name}
            **Record ID:** {record_id}
            **Age:** {age}
            **Gender:** {gender}
            
            ## ASSESSMENT SUMMARY
            
            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.
            
            ## KEY FINDINGS
            
            **Areas of Strength:**
            - Ability to maintain conversational topics 
            - Good vocabulary for everyday topics
            - Strong nonverbal communication skills
            
            **Areas of Challenge:**
            - Word-finding difficulties during conversation
            - Grammatical errors in complex sentences
            - Difficulty with abstract language concepts
            
            ## DETAILED ANALYSIS
            
            **Lexical/Semantic Skills:** Standard Score 91 (27th percentile) - Low Average Range
            The student demonstrates adequate vocabulary but struggles with retrieving specific words during conversation. Word-finding pauses were noted throughout the language sample.
            
            **Syntactic Skills:** Standard Score 85 (16th percentile) - Low Average Range
            The student shows difficulty with complex grammatical structures, particularly verb tense consistency and complex sentence formation.
            
            **Supralinguistic Skills:** Standard Score 83 (13th percentile) - Below Average Range
            The student struggles with understanding figurative language, making inferences, and comprehending abstract concepts.
            
            ## RECOMMENDATIONS
            
            1. Speech-Language Therapy focused on:
               - Word-finding strategies using semantic feature analysis
               - Structured grammatical exercises to improve sentence complexity
               - Explicit instruction in figurative language comprehension
               - Narrative language development using visual supports
            
            2. Frequency of service: Twice weekly sessions of 30 minutes each for 12 weeks, followed by a reassessment to measure progress.
            
            3. Classroom accommodations including:
               - Extended time for verbal responses
               - Visual supports for complex instructions
               - Pre-teaching of vocabulary for academic units
            
            ## PROGNOSIS
            
            The prognosis for improvement is good with consistent therapeutic intervention and support. Regular reassessment is recommended to monitor progress.
            
            Respectfully submitted,
            
            {clinician}
            Speech-Language Pathologist
            """
        else:
            report = f"""
            # PARENT-FRIENDLY LANGUAGE ASSESSMENT SUMMARY
            
            **Date of Assessment:** {assessment_date}
            **Clinician:** {clinician}
            
            ## PATIENT INFORMATION
            **Name:** {patient_name}
            **Record ID:** {record_id}
            **Age:** {age}
            **Gender:** {gender}
            
            ## ASSESSMENT SUMMARY
            
            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.
            
            ## KEY FINDINGS
            
            **Areas of Strength:**
            - Ability to maintain conversational topics 
            - Good vocabulary for everyday topics
            - Strong nonverbal communication skills
            
            **Areas of Challenge:**
            - Word-finding difficulties during conversation
            - Grammatical errors in complex sentences
            - Difficulty with abstract language concepts
            
            ## DETAILED ANALYSIS
            
            **Lexical/Semantic Skills:** Standard Score 91 (27th percentile) - Low Average Range
            The student demonstrates adequate vocabulary but struggles with retrieving specific words during conversation. Word-finding pauses were noted throughout the language sample.
            
            **Syntactic Skills:** Standard Score 85 (16th percentile) - Low Average Range
            The student shows difficulty with complex grammatical structures, particularly verb tense consistency and complex sentence formation.
            
            **Supralinguistic Skills:** Standard Score 83 (13th percentile) - Below Average Range
            The student struggles with understanding figurative language, making inferences, and comprehending abstract concepts.
            
            ## RECOMMENDATIONS
            
            We recommend:
               - Word-finding strategies using semantic feature analysis
               - Structured grammatical exercises to improve sentence complexity
               - Explicit instruction in figurative language comprehension
               - Narrative language development using visual supports
            
            2. We recommend therapy twice a week for 30 minutes. This consistency will help your child make better progress.
            
            3. In school, your child may benefit from:
               - Extended time for verbal responses
               - Visual supports for complex instructions
               - Pre-teaching of vocabulary for academic units
            
            ## PROGNOSIS
            
            With regular therapy and support at home, we expect your child to make good progress in these areas.
            
            Please reach out with any questions!
            
            {clinician}
            Speech-Language Pathologist
            """
    
    return report

def transcribe_audio(audio_path, patient_age):
    """Transcribe an audio recording using CHAT format"""
    # In a real implementation, this would use a speech-to-text service
    # For demo purposes, we'll return a simulated transcription
    
    if bedrock_client:
        # In a real implementation, you would process the audio file and send it to a transcription service
        # Here we just simulate the result
        transcription = generate_demo_transcription(audio_path)
    else:
        transcription = generate_demo_transcription(audio_path)
    
    return transcription

def answer_slp_question(question):
    """Answer a question about SLP practice or CASL assessment"""
    
    prompt = f"""
    You are an experienced Speech-Language Pathologist answering a question from a colleague.
    
    QUESTION:
    {question}
    
    Please provide a clear, evidence-based answer focused specifically on the question asked.
    Reference best practices and current research where appropriate.
    Keep your answer concise but comprehensive.
    """
    
    if bedrock_client:
        answer = call_bedrock(prompt)
    else:
        answer = generate_demo_qa_response(question)
    
    return answer

# ===============================
# Gradio Interface
# ===============================

def create_interface():
    """Create the main Gradio interface"""
    
    # Use a simple theme with default colors
    custom_theme = gr.themes.Soft(
        font=[gr.themes.GoogleFont("Inter"), "system-ui", "sans-serif"]
    )
    
    with gr.Blocks(theme=custom_theme, css="""
        .header {
            text-align: center;
            margin-bottom: 20px;
        }
        .header img {
            max-height: 100px;
            margin-bottom: 10px;
        }
        .container {
            border-radius: 10px;
            padding: 10px;
            margin-bottom: 20px;
        }
        .patient-info {
            background-color: #e3f2fd;
        }
        .speech-sample {
            background-color: #f0f8ff;
        }
        .results-container {
            background-color: #f9f9f9; 
        }
        .viz-container {
            display: flex;
            justify-content: center;
            margin-bottom: 20px;
        }
        .footer {
            text-align: center;
            margin-top: 30px;
            padding: 10px;
            font-size: 0.8em;
            color: #78909C;
        }
        .info-box {
            background-color: #e8f5e9;
            border-left: 4px solid #4CAF50;
            padding: 10px 15px;
            margin-bottom: 15px;
            border-radius: 4px;
        }
        .warning-box {
            background-color: #fff8e1;
            border-left: 4px solid #FFC107;
            padding: 10px 15px;
            border-radius: 4px;
        }
        .markdown-text h3 {
            color: #2C7FB8;
            border-bottom: 1px solid #eaeaea;
            padding-bottom: 5px;
        }
        .evidence-table {
            border-collapse: collapse;
            width: 100%;
        }
        .evidence-table th, .evidence-table td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        .evidence-table th {
            background-color: #f5f7fa;
            color: #333;
        }
        .evidence-table tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        .tab-content {
            padding: 15px;
            background-color: white;
            border-radius: 0 0 8px 8px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.05);
        }
    """) as app:
        # Create header with logo
        gr.HTML(
            """
            <div class="header">
                <h1>SLP Analysis Tool</h1>
                <p>A comprehensive assessment tool for Speech-Language Pathologists</p>
            </div>
            """
        )
        
        # Main tabs
        with gr.Tabs() as main_tabs:
            # ===============================
            # CASL Analysis Tab
            # ===============================
            with gr.TabItem("CASL Analysis", id=0):
                with gr.Row():
                    # Left column - Input section
                    with gr.Column(scale=1):
                        # Patient information panel
                        with gr.Group(elem_classes="container patient-info"):
                            gr.Markdown("### Patient Information")
                            
                            with gr.Row():
                                patient_name = gr.Textbox(label="Patient Name", placeholder="Enter patient name")
                                record_id = gr.Textbox(label="Record ID", placeholder="Enter record ID")
                            
                            with gr.Row():
                                age = gr.Number(label="Age", value=8, minimum=1, maximum=120)
                                gender = gr.Radio(["male", "female", "other"], label="Gender", value="male")
                            
                            with gr.Row():
                                assessment_date = gr.Textbox(
                                    label="Assessment Date", 
                                    placeholder="MM/DD/YYYY", 
                                    value=datetime.now().strftime('%m/%d/%Y')
                                )
                                clinician_name = gr.Textbox(
                                    label="Clinician", 
                                    placeholder="Enter clinician name"
                                )
                        
                        # Speech sample panel
                        with gr.Group(elem_classes="container speech-sample"):
                            gr.Markdown("### Speech Sample")
                            
                            # Sample button
                            sample_btn = gr.Button("Load Sample Transcript", size="sm")
                            
                            # Transcript input
                            transcript = gr.Textbox(
                                label="Transcript", 
                                placeholder="Paste the speech transcript here...",
                                lines=10
                            )
                            
                            # Add info about transcript format
                            gr.Markdown(
                                """
                                <div class="info-box">
                                    <strong>Transcript Format:</strong> Use CHAT format with *PAR: for patient lines. 
                                    Mark word-finding with &-um, paraphasias with [*], and provide intended words with [: word].
                                </div>
                                """,
                                elem_classes="markdown-text"
                            )
                            
                            # File upload
                            file_upload = gr.File(
                                label="Or upload a transcript file", 
                                file_types=["text", "txt", "pdf", "rtf"]
                            )
                            
                            # Analysis button
                            analyze_btn = gr.Button("Analyze Speech Sample", variant="primary", size="lg")
                    
                    # Right column - Results section
                    with gr.Column(scale=1):
                        with gr.Group(elem_classes="container results-container"):
                            with gr.Tabs() as results_tabs:
                                # Summary tab
                                with gr.TabItem("Summary", id=0, elem_classes="tab-content"):
                                    with gr.Group():
                                        gr.Markdown("### Key Findings", elem_classes="markdown-text")
                                        speech_factors_md = gr.Markdown(elem_classes="markdown-text")
                                        
                                    with gr.Accordion("CASL Assessment Results", open=True):
                                        casl_results_md = gr.Markdown(elem_classes="markdown-text")
                                    
                                    with gr.Accordion("Detailed Error Examples", open=True):
                                        specific_errors_md = gr.Markdown(elem_classes="markdown-text")
                                
                                # Treatment tab
                                with gr.TabItem("Treatment Plan", id=1, elem_classes="tab-content"):
                                    gr.Markdown("### Recommended Treatment Approaches", elem_classes="markdown-text")
                                    treatment_md = gr.Markdown(elem_classes="treatment-panel")
                                    
                                    gr.Markdown("### Clinical Rationale", elem_classes="markdown-text")
                                    explanation_md = gr.Markdown(elem_classes="panel")
                                    
                                    with gr.Accordion("Supporting Evidence", open=False):
                                        gr.Markdown("""
                                        <table class="evidence-table">
                                          <tr>
                                            <th>Factor</th>
                                            <th>Evidence-based Approaches</th>
                                            <th>References</th>
                                          </tr>
                                          <tr>
                                            <td>Word Retrieval</td>
                                            <td>Semantic feature analysis, phonological cueing, word generation tasks</td>
                                            <td>Boyle, 2010; Kiran & Thompson, 2003</td>
                                          </tr>
                                          <tr>
                                            <td>Grammatical Errors</td>
                                            <td>Treatment of Underlying Forms (TUF), Morphosyntactic therapy</td>
                                            <td>Thompson et al., 2003; Ebbels, 2014</td>
                                          </tr>
                                          <tr>
                                            <td>Fluency/Prosody</td>
                                            <td>Rate control, rhythmic cueing, contrastive stress exercises</td>
                                            <td>Ballard et al., 2010; Tamplin & Baker, 2017</td>
                                          </tr>
                                        </table>
                                        """, elem_classes="markdown-text")
                                
                                # Full report tab
                                with gr.TabItem("Full Report", id=2, elem_classes="tab-content"):
                                    full_analysis = gr.Markdown()
                                    
                                    # Add PDF export option
                                    export_btn = gr.Button("Export Report as PDF", variant="secondary")
                                    export_status = gr.Markdown("")
                                
                                # Raw LLM Output tab
                                with gr.TabItem("Raw LLM Output", id=3, elem_classes="tab-content"):
                                    gr.Markdown("### Complete Model Output", elem_classes="markdown-text")
                                    gr.Markdown("This tab shows the unprocessed output from the AI model for debugging purposes.")
                                    raw_llm_output = gr.Textbox(
                                        label="Raw AI Output",
                                        lines=20,
                                        interactive=False
                                    )
            
            # ===============================
            # Patient Records Tab
            # ===============================
            with gr.TabItem("Patient Records", id=1):
                with gr.Row():
                    with gr.Column(scale=1):
                        gr.Markdown("### Patient Records")
                        
                        # Records table
                        patient_records_table = gr.Dataframe(
                            headers=["ID", "Name", "Record ID", "Age", "Gender", "Assessment Date", "Clinician"],
                            datatype=["str", "str", "str", "str", "str", "str", "str"],
                            label="Saved Patients",
                            interactive=False
                        )
                        
                        refresh_records_btn = gr.Button("Refresh Records", size="sm")
                        records_status = gr.Markdown("")
                        
                        # Record selection
                        selected_record_id = gr.Textbox(label="Selected Record ID", visible=False)
                        load_record_btn = gr.Button("Load Selected Record", variant="primary")
                    
                    with gr.Column(scale=1):
                        # Record details
                        record_details = gr.Markdown(label="Record Details")
                
                # Event handlers for records
                def refresh_patient_records():
                    """Refresh the patient records table"""
                    records = get_all_patient_records()
                    data = []
                    for r in records:
                        data.append([
                            r["id"], r["name"], r["record_id"], 
                            r["age"], r["gender"], r["assessment_date"], r["clinician"]
                        ])
                    df = pd.DataFrame(data)
                    status_msg = f"Found {len(data)} patient records."
                    return df, status_msg
                
                refresh_records_btn.click(
                    refresh_patient_records,
                    outputs=[patient_records_table, records_status]
                )
                
                # Automatically load records when tab is selected
                main_tabs.select(
                    lambda tab_id: refresh_patient_records() if tab_id == 1 else (pd.DataFrame(), ""),
                    inputs=[main_tabs],
                    outputs=[patient_records_table, records_status]
                )
                
                # Load record when a row is selected
                def handle_record_selection(evt: gr.SelectData, records):
                    if records is None or len(records) == 0:
                        return "", "No record selected."
                    
                    selected_row = evt.index[0]
                    if selected_row < len(records):
                        record_id = records.iloc[selected_row, 0]
                        
                        # Load the record to show details
                        record_data = load_patient_record(record_id)
                        if record_data:
                            patient_info = record_data.get("patient_info", {})
                            
                            # Format record details as markdown
                            details = f"""
                            ## Selected Patient Record
                            
                            **Name:** {patient_info.get('name', 'N/A')}  
                            **Record ID:** {patient_info.get('record_id', 'N/A')}  
                            **Age:** {patient_info.get('age', 'N/A')}  
                            **Gender:** {patient_info.get('gender', 'N/A')}  
                            **Assessment Date:** {patient_info.get('assessment_date', 'N/A')}  
                            **Clinician:** {patient_info.get('clinician', 'N/A')}  
                            **Analyzed:** {record_data.get('timestamp', 'Unknown')}
                            
                            ### Preview
                            
                            This record contains:
                            - Speech transcript analysis
                            - CASL assessment results
                            - Treatment recommendations
                            
                            Click "Load Selected Record" to view the full analysis.
                            """
                            
                            return record_id, details
                        
                        return record_id, f"Selected record: {record_id}"
                    
                    return "", "Invalid selection."
                
                patient_records_table.select(
                    handle_record_selection,
                    inputs=[patient_records_table],
                    outputs=[selected_record_id, record_details]
                )
                
                # Load record into analysis tab
                def load_patient_record_to_analysis(record_id):
                    if not record_id:
                        return gr.update(selected=1), {}, "", "", "", "", "", ""
                    
                    record_data = load_patient_record(record_id)
                    if not record_data:
                        return gr.update(selected=1), "", "", "", "male", "", "", ""
                    
                    # Extract data
                    patient_info = record_data.get("patient_info", {})
                    transcript_text = record_data.get("transcript", "")
                    analysis_results = record_data.get("analysis_results", {})
                    
                    # Create status message for the record loading
                    status_msg = f"✅ Record loaded successfully: {patient_info.get('name', 'Unknown')} ({record_id})"
                    
                    # Now we should also load the analysis results
                    # In a future version, we would need to update all analysis outputs here as well
                    
                    return (
                        gr.update(selected=0),  # Switch to analysis tab
                        patient_info.get("name", ""),
                        patient_info.get("record_id", ""),
                        patient_info.get("age", ""),
                        patient_info.get("gender", "male"),
                        patient_info.get("assessment_date", ""),
                        patient_info.get("clinician", ""),
                        transcript_text,
                        status_msg
                    )
                
                load_record_btn.click(
                    load_patient_record_to_analysis,
                    inputs=[selected_record_id],
                    outputs=[
                        main_tabs,
                        patient_name, record_id, age, gender, 
                        assessment_date, clinician_name, transcript,
                        records_status
                    ]
                )
            
            # ===============================
            # Report Generator Tab
            # ===============================
            with gr.TabItem("Report Generator", id=2):
                with gr.Row():
                    with gr.Column(scale=1):
                        gr.Markdown("### Generate Professional Reports")
                        
                        # Patient info
                        with gr.Group(elem_classes="container patient-info"):
                            gr.Markdown("#### Patient Information")
                            report_patient_name = gr.Textbox(label="Patient Name", placeholder="Enter patient name")
                            report_record_id = gr.Textbox(label="Record ID", placeholder="Enter record ID")
                            report_age = gr.Number(label="Age", value=8, minimum=1, maximum=120)
                            report_gender = gr.Radio(["male", "female", "other"], label="Gender", value="male")
                            report_date = gr.Textbox(
                                label="Assessment Date", 
                                placeholder="MM/DD/YYYY", 
                                value=datetime.now().strftime('%m/%d/%Y')
                            )
                            report_clinician = gr.Textbox(label="Clinician", placeholder="Enter clinician name")
                        
                        with gr.Group():
                            gr.Markdown("#### Assessment Results")
                            report_results = gr.Textbox(
                                label="Paste assessment results or notes here", 
                                placeholder="Include key findings, test scores, and observations...",
                                lines=10
                            )
                            
                            report_type = gr.Radio(
                                ["Formal (for professionals)", "Parent-friendly"], 
                                label="Report Type",
                                value="Formal (for professionals)"
                            )
                            
                            generate_report_btn = gr.Button("Generate Report", variant="primary")
                    
                    with gr.Column(scale=1):
                        report_output = gr.Markdown()
                        report_download_btn = gr.Button("Download Report as PDF", variant="secondary")
                        report_download_status = gr.Markdown("")
            
            # ===============================
            # Transcription Tool Tab
            # ===============================
            with gr.TabItem("Transcription Tool", id=3):
                with gr.Row():
                    with gr.Column(scale=1):
                        gr.Markdown("### Audio Transcription Tool")
                        gr.Markdown("Upload an audio recording to automatically transcribe it in CHAT format.")
                        
                        audio_input = gr.Audio(type="filepath", label="Upload Audio Recording")
                        
                        with gr.Row():
                            transcription_age = gr.Number(label="Patient Age", value=8, minimum=1, maximum=120)
                            transcribe_btn = gr.Button("Transcribe Audio", variant="primary")
                    
                    with gr.Column(scale=1):
                        transcription_output = gr.Textbox(
                            label="Transcription Result", 
                            placeholder="Transcription will appear here...",
                            lines=12
                        )
                        
                        with gr.Row():
                            copy_to_analysis_btn = gr.Button("Use for Analysis", variant="secondary")
                            edit_transcription_btn = gr.Button("Edit Transcription", variant="secondary")
            
            # ===============================
            # SLP Assistant Tab
            # ===============================
            with gr.TabItem("SLP Assistant", id=4):
                with gr.Row():
                    with gr.Column(scale=1):
                        gr.Markdown("### SLP Knowledge Assistant")
                        gr.Markdown("Ask questions about CASL assessment, therapy techniques, or SLP best practices.")
                        
                        question_input = gr.Textbox(
                            label="Your Question", 
                            placeholder="e.g., What activities help improve word-finding skills?",
                            lines=3
                        )
                        
                        ask_question_btn = gr.Button("Ask Question", variant="primary")
                        
                        # Quick question buttons
                        gr.Markdown("#### Common Questions")
                        with gr.Row():
                            q1_btn = gr.Button("What is CASL?")
                            q2_btn = gr.Button("How do I interpret scores?")
                        
                        with gr.Row():
                            q3_btn = gr.Button("Activities for word finding")
                            q4_btn = gr.Button("When to reassess")
                    
                    with gr.Column(scale=1):
                        answer_output = gr.Markdown()
                        
                        with gr.Accordion("References", open=False):
                            gr.Markdown("""
                            - American Speech-Language-Hearing Association (ASHA)
                            - Comprehensive Assessment of Spoken Language (CASL-2) Manual
                            - Evidence-Based Practice in Speech-Language Pathology
                            - Current research in pediatric language intervention
                            """)
        
        # ===============================
        # Event Handlers
        # ===============================
        
        # Load sample transcript button
        def load_sample():
            return SAMPLE_TRANSCRIPT
        
        sample_btn.click(load_sample, outputs=[transcript])
        
        # File upload handler
        file_upload.upload(process_upload, file_upload, transcript)
        
        # Analysis button handler
        def on_analyze_click(transcript_text, age_val, gender_val, patient_name_val, record_id_val, clinician_val, assessment_date_val):
            if not transcript_text or len(transcript_text.strip()) < 50:
                return (
                    "Error: Please provide a longer transcript for analysis.",
                    "The transcript is too short for meaningful analysis.",
                    "Please provide a speech sample with at least 50 characters.",
                    "Error: Insufficient data",
                    "Please provide a speech sample with at least 50 characters.",
                    "",
                    "",
                    ""
                )
            
            try:
                # Get the raw analysis response
                results, _, _, full_text = analyze_transcript(transcript_text, age_val, gender_val)
                
                # Extract speech factors section using section markers
                speech_factors_section = ""
                factors_pattern = re.compile(r"<SPEECH_FACTORS_START>(.*?)<SPEECH_FACTORS_END>", re.DOTALL)
                factors_match = factors_pattern.search(full_text)
                
                if factors_match:
                    speech_factors_section = factors_match.group(1).strip()
                else:
                    # Fallback to old pattern if markers aren't found
                    old_factors_pattern = re.compile(r"(Difficulty producing fluent.*?)(?:Evaluation of CASL Skills|<CASL_SKILLS_START>)", re.DOTALL)
                    old_factors_match = old_factors_pattern.search(full_text)
                    if old_factors_match:
                        speech_factors_section = old_factors_match.group(1).strip()
                    else:
                        speech_factors_section = "Error extracting speech factors from analysis."
                
                # Extract CASL skills section
                casl_section = ""
                casl_pattern = re.compile(r"<CASL_SKILLS_START>(.*?)<CASL_SKILLS_END>", re.DOTALL)
                casl_match = casl_pattern.search(full_text)
                
                if casl_match:
                    casl_section = casl_match.group(1).strip()
                else:
                    # Fallback pattern
                    old_casl_pattern = re.compile(r"(?:Evaluation of CASL Skills:|Lexical/Semantic Skills:)(.*?)(?:Other analysis/Best plans of action:|<TREATMENT_RECOMMENDATIONS_START>)", re.DOTALL)
                    old_casl_match = old_casl_pattern.search(full_text)
                    if old_casl_match:
                        casl_section = old_casl_match.group(1).strip()
                        # Add a header if it's missing
                        if not casl_section.startswith("Lexical"):
                            casl_section = "Evaluation of CASL Skills:\n\n" + casl_section
                    else:
                        casl_section = "Error extracting CASL skills from analysis."
                
                # Extract treatment recommendations
                treatment_text = ""
                treatment_pattern = re.compile(r"<TREATMENT_RECOMMENDATIONS_START>(.*?)<TREATMENT_RECOMMENDATIONS_END>", re.DOTALL)
                treatment_match = treatment_pattern.search(full_text)
                
                if treatment_match:
                    treatment_text = "### Treatment Recommendations\n\n" + treatment_match.group(1).strip()
                else:
                    # Fallback pattern
                    old_treatment_pattern = re.compile(r"(?:Other analysis/Best plans of action:)(.*?)(?:Explanation:|<EXPLANATION_START>)", re.DOTALL)
                    old_treatment_match = old_treatment_pattern.search(full_text)
                    if old_treatment_match:
                        treatment_text = "### Treatment Recommendations\n\n" + old_treatment_match.group(1).strip()
                    elif 'treatment_suggestions' in results:
                        treatment_text = "### Treatment Recommendations\n\n"
                        for suggestion in results['treatment_suggestions']:
                            treatment_text += f"- {suggestion}\n"
                
                # Extract explanation section
                explanation_text = "### Clinical Rationale\n\n"
                explanation_pattern = re.compile(r"<EXPLANATION_START>(.*?)<EXPLANATION_END>", re.DOTALL)
                explanation_match = explanation_pattern.search(full_text)
                
                if explanation_match:
                    explanation_text += explanation_match.group(1).strip()
                else:
                    # Fallback pattern
                    old_explanation_pattern = re.compile(r"(?:Explanation:)(.*?)(?:Additional Analysis:|<ADDITIONAL_ANALYSIS_START>)", re.DOTALL)
                    old_explanation_match = old_explanation_pattern.search(full_text)
                    if old_explanation_match:
                        explanation_text += old_explanation_match.group(1).strip()
                    else:
                        explanation_text += results.get('explanation', "No explanation provided.")
                
                # Extract additional analysis
                additional_analysis = ""
                additional_pattern = re.compile(r"<ADDITIONAL_ANALYSIS_START>(.*?)<ADDITIONAL_ANALYSIS_END>", re.DOTALL)
                additional_match = additional_pattern.search(full_text)
                
                if additional_match:
                    additional_analysis = additional_match.group(1).strip()
                    explanation_text += "\n\n### Additional Analysis\n\n" + additional_analysis
                else:
                    # Fallback pattern
                    old_additional_pattern = re.compile(r"(?:Additional Analysis:)(.*?)(?:Diagnostic Impressions:|<DIAGNOSTIC_IMPRESSIONS_START>)", re.DOTALL)
                    old_additional_match = old_additional_pattern.search(full_text)
                    if old_additional_match:
                        explanation_text += "\n\n### Additional Analysis\n\n" + old_additional_match.group(1).strip()
                    elif 'additional_analysis' in results:
                        explanation_text += "\n\n### Additional Analysis\n\n" + results.get('additional_analysis', "")
                
                # Extract diagnostic impressions
                diagnostic_impressions = ""
                diagnostic_pattern = re.compile(r"<DIAGNOSTIC_IMPRESSIONS_START>(.*?)<DIAGNOSTIC_IMPRESSIONS_END>", re.DOTALL)
                diagnostic_match = diagnostic_pattern.search(full_text)
                
                if diagnostic_match:
                    diagnostic_impressions = diagnostic_match.group(1).strip()
                    # Add to the explanation section
                    explanation_text += "\n\n### Diagnostic Impressions\n\n" + diagnostic_impressions
                
                # Extract specific error examples
                specific_errors_text = "## Detailed Error Examples\n\n"
                
                # First try the dedicated section
                errors_pattern = re.compile(r"<ERROR_EXAMPLES_START>(.*?)<ERROR_EXAMPLES_END>", re.DOTALL)
                errors_match = errors_pattern.search(full_text)
                
                if errors_match:
                    specific_errors_text += errors_match.group(1).strip()
                else:
                    # Fallback to extracting examples from the text
                    example_sections = re.findall(r"Examples:\s*\n((?:- \".*\"\s*\n)+)", full_text)
                    for section in example_sections:
                        specific_errors_text += section + "\n"
                    
                    if not example_sections:
                        specific_errors_text += "No specific error examples were found in the analysis."
                
                # Save the record to storage
                patient_info = {
                    "name": patient_name_val,
                    "record_id": record_id_val,
                    "age": age_val,
                    "gender": gender_val,
                    "assessment_date": assessment_date_val,
                    "clinician": clinician_val
                }
                
                saved_id = save_patient_record(patient_info, results, transcript_text)
                
                save_message = ""
                if saved_id:
                    save_message = f"""
                    ✅ Patient record saved successfully.
                    
                    **System ID:** {saved_id}
                    **Patient:** {patient_name_val or "Unnamed"} 
                    **Record ID:** {record_id_val or "Not provided"}
                    
                    You can access this record later in the Patient Records tab.
                    """
                else:
                    save_message = "⚠️ Failed to save patient record. Please check data directory permissions."
                
                # Format to include patient metadata in the full report
                patient_info_text = ""
                if patient_name_val:
                    patient_info_text += f"**Patient:** {patient_name_val}\n"
                if record_id_val:
                    patient_info_text += f"**Record ID:** {record_id_val}\n"
                if age_val:
                    patient_info_text += f"**Age:** {age_val} years\n"
                if gender_val:
                    patient_info_text += f"**Gender:** {gender_val}\n"
                if assessment_date_val:
                    patient_info_text += f"**Assessment Date:** {assessment_date_val}\n"
                if clinician_val:
                    patient_info_text += f"**Clinician:** {clinician_val}\n"
                if saved_id:
                    patient_info_text += f"**System ID:** {saved_id}\n"
                
                if patient_info_text:
                    full_report = f"## Patient Information\n\n{patient_info_text}\n\n## Analysis Report\n\n{full_text}"
                else:
                    full_report = f"## Complete Analysis Report\n\n{full_text}"
                
                # Get the raw LLM response for debugging
                raw_output = full_text
                
                return (
                    speech_factors_section,
                    casl_section,
                    treatment_text,
                    explanation_text,
                    full_report,
                    save_message,
                    specific_errors_text,
                    raw_output
                )
            except Exception as e:
                logger.exception("Error during analysis")
                error_message = f"Error during analysis: {str(e)}"
                return (
                    f"Error: {str(e)}",
                    "Error: Analysis failed. Please check input data.",
                    "Error: Treatment analysis not available.",
                    "An error occurred while processing the transcript.",
                    f"Error details: {str(e)}",
                    "",
                    "",
                    f"Analysis failed with error: {error_message}\n\nPlease check your transcript format and try again."
                )
        
        analyze_btn.click(
            on_analyze_click,
            inputs=[
                transcript, age, gender, 
                patient_name, record_id, clinician_name, assessment_date
            ],
            outputs=[
                speech_factors_md,
                casl_results_md,
                treatment_md,
                explanation_md,
                full_analysis,
                export_status,
                specific_errors_md,
                raw_llm_output
            ]
        )
        
        # Export report functionality
        def export_pdf(report_text, patient_name="Patient", record_id=""):
            try:
                from reportlab.lib.pagesizes import letter
                from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
                from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
                import tempfile
                import webbrowser
                import os
                
                # Generate a safe filename
                if patient_name and record_id:
                    safe_name = f"{patient_name.replace(' ', '_')}_{record_id}"
                elif patient_name:
                    safe_name = patient_name.replace(' ', '_')
                else:
                    safe_name = f"speech_analysis_{datetime.now().strftime('%Y%m%d%H%M%S')}"
                
                # Create a temporary file for the PDF
                temp_dir = tempfile.gettempdir()
                pdf_path = os.path.join(temp_dir, f"{safe_name}.pdf")
                
                # Create the PDF document
                doc = SimpleDocTemplate(pdf_path, pagesize=letter)
                styles = getSampleStyleSheet()
                
                # Create custom styles
                styles.add(ParagraphStyle(
                    name='Heading1',
                    parent=styles['Heading1'],
                    fontSize=16,
                    spaceAfter=12
                ))
                
                styles.add(ParagraphStyle(
                    name='Heading2',
                    parent=styles['Heading2'],
                    fontSize=14,
                    spaceAfter=10,
                    spaceBefore=10
                ))
                
                styles.add(ParagraphStyle(
                    name='BodyText',
                    parent=styles['BodyText'],
                    fontSize=12,
                    spaceAfter=8
                ))
                
                # Convert markdown to PDF elements
                # Very basic conversion - in a real app, use a proper markdown to PDF library
                story = []
                
                # Add title
                story.append(Paragraph("Speech Language Assessment Report", styles['Title']))
                story.append(Spacer(1, 12))
                
                # Process the markdown content line by line
                current_style = styles['BodyText']
                
                for line in report_text.split('\n'):
                    # Skip empty lines
                    if not line.strip():
                        story.append(Spacer(1, 6))
                        continue
                        
                    # Check for headings
                    if line.startswith('# '):
                        story.append(Paragraph(line[2:], styles['Heading1']))
                    elif line.startswith('## '):
                        story.append(Paragraph(line[3:], styles['Heading2']))
                    elif line.startswith('- '):
                        # Bullet points
                        story.append(Paragraph('• ' + line[2:], styles['BodyText']))
                    elif line.startswith('**') and line.endswith('**'):
                        # Bold text - assuming it's a short line like a heading
                        text = line.replace('**', '')
                        story.append(Paragraph(f"<b>{text}</b>", styles['BodyText']))
                    else:
                        # Regular text
                        story.append(Paragraph(line, styles['BodyText']))
                
                # Build the PDF
                doc.build(story)
                
                # Open the PDF (in a real web app, you'd provide a download link)
                # This will work in a desktop environment
                return f"Report saved as PDF: {pdf_path}"
            
            except Exception as e:
                logger.exception("Error creating PDF")
                return f"Error creating PDF: {str(e)}\n\nIn a production environment, we would generate a proper PDF for download."
        
        # Simplified simulation for HuggingFace Spaces environment
        def export_pdf_simulation(report_text):
            return "Report export initiated. In a production environment, a PDF would be generated and downloaded."
        
        # Use the actual function in a desktop environment, simulation in web environment
        if os.getenv("SPACE_ID"):  # Check if running on HuggingFace Spaces
            export_btn.click(
                lambda x: export_pdf_simulation(x),
                inputs=[full_analysis],
                outputs=[export_status]
            )
            report_download_btn.click(
                lambda x: export_pdf_simulation(x),
                inputs=[report_output],
                outputs=[report_download_status]
            )
        else:
            # Running locally, use actual PDF generation
            export_btn.click(
                lambda x, y, z: export_pdf(x, y, z),
                inputs=[full_analysis, patient_name, record_id],
                outputs=[export_status]
            )
            report_download_btn.click(
                lambda x, y, z: export_pdf(x, y, z),
                inputs=[report_output, report_patient_name, report_record_id],
                outputs=[report_download_status]
            )
        
        # Report generator button
        def on_generate_report(name, record_id, age, gender, date, clinician, results, report_type):
            patient_info = {
                "name": name,
                "record_id": record_id,
                "age": age,
                "gender": gender,
                "assessment_date": date,
                "clinician": clinician
            }
            
            report_type_val = "formal" if "Formal" in report_type else "parent-friendly"
            
            try:
                report = generate_report(patient_info, results, report_type_val)
                return report
            except Exception as e:
                logger.exception("Error generating report")
                return f"Error generating report: {str(e)}"
        
        generate_report_btn.click(
            on_generate_report,
            inputs=[
                report_patient_name, report_record_id, report_age,
                report_gender, report_date, report_clinician,
                report_results, report_type
            ],
            outputs=[report_output]
        )
        
        # Transcription button
        def on_transcribe_audio(audio_path, age):
            try:
                if not audio_path:
                    return "Please upload an audio file to transcribe."
                
                transcription = transcribe_audio(audio_path, age)
                return transcription
            except Exception as e:
                logger.exception("Error transcribing audio")
                return f"Error transcribing audio: {str(e)}"
        
        transcribe_btn.click(
            on_transcribe_audio,
            inputs=[audio_input, transcription_age],
            outputs=[transcription_output]
        )
        
        # Copy transcription to analysis
        def copy_to_analysis(transcription):
            return transcription, gr.update(selected=0)  # Switches to the Analysis tab
        
        copy_to_analysis_btn.click(
            copy_to_analysis,
            inputs=[transcription_output],
            outputs=[transcript, main_tabs]
        )
        
        # SLP Assistant question handling
        def on_ask_question(question):
            try:
                answer = answer_slp_question(question)
                return answer
            except Exception as e:
                logger.exception("Error getting answer")
                return f"Error: {str(e)}"
        
        ask_question_btn.click(
            on_ask_question,
            inputs=[question_input],
            outputs=[answer_output]
        )
        
        # Quick question buttons
        q1_btn.click(lambda: "What is CASL?", outputs=[question_input])
        q2_btn.click(lambda: "How do I interpret CASL scores?", outputs=[question_input])
        q3_btn.click(lambda: "What activities help with word finding difficulties?", outputs=[question_input])
        q4_btn.click(lambda: "When should I reassess a patient?", outputs=[question_input])
        
    return app

# ===============================
# Main Application
# ===============================

# Create requirements.txt file for HuggingFace Spaces
def create_requirements_file():
    requirements = [
        "gradio>=4.0.0",
        "pandas",
        "matplotlib",
        "numpy",
        "Pillow",
        "PyPDF2",
        "boto3",
        "reportlab",
        "uuid"
    ]
    
    with open("requirements.txt", "w") as f:
        for req in requirements:
            f.write(f"{req}\n")

# Create and launch the interface
if __name__ == "__main__":
    # Create requirements.txt for HuggingFace Spaces
    create_requirements_file()
    
    # Check for AWS credentials
    if not AWS_ACCESS_KEY or not AWS_SECRET_KEY:
        print("NOTE: AWS credentials not found. The app will run in demo mode with simulated responses.")
        print("To enable full functionality, set AWS_ACCESS_KEY and AWS_SECRET_KEY environment variables.")
    
    # Launch the Gradio app
    app = create_interface()
    app.launch()