import streamlit as st import boto3 import json import pandas as pd import plotly.express as px from io import BytesIO import openpyxl import fitz # PyMuPDF import logging from datetime import datetime from streamlit_lottie import st_lottie import requests import base64 from botocore.exceptions import ClientError import whisper import tempfile import os from moviepy.editor import VideoFileClip from pydub import AudioSegment import re # Configure logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) # AWS credentials # Initialize AWS clients s3 = boto3.client('s3', aws_access_key_id=AWS_ACCESS_KEY, aws_secret_access_key=AWS_SECRET_KEY, region_name=AWS_REGION) bedrock = boto3.client('bedrock-runtime', aws_access_key_id=AWS_ACCESS_KEY, aws_secret_access_key=AWS_SECRET_KEY, region_name=AWS_REGION) # Load Whisper model model = whisper.load_model("base") # Helper functions files = { } def load_lottie_url(url: str): r = requests.get(url) if r.status_code != 200: return None return r.json() def read_pdf(file): if isinstance(file, str): document = fitz.open(file) else: document = fitz.open(stream=file.read(), filetype="pdf") text = "" for page_num in range(len(document)): page = document.load_page(page_num) text += page.get_text() return text intro = read_pdf(files["intro"]) anomia = read_pdf(files["anomia"]) utterances = read_pdf(files["utterances"]) preservation = read_pdf(files["preservation"]) mit = read_pdf(files["mit"]) agrammatism = read_pdf(files["agrammatism"]) wernicke = read_pdf(files["wernicke"]) ac = read_pdf(files["ac"]) misc = read_pdf(files["misc"]) example_report = read_pdf(files["example_report"]) example_patients = read_pdf(files["example_patients"]) palpa = """The PALPA (Psycholinguistic Assessment of Language Processing in Aphasia) is a comprehensive tool used by speech-language pathologists and researchers to assess various aspects of language processing in individuals with aphasia. It consists of a series of tasks designed to evaluate different language functions, such as comprehension, repetition, naming, and more nuanced aspects like phonological and semantic processing. Overview of PALPA Subscores Comprehension Subscores: Single Word Comprehension: Assesses the ability to understand individual words. Sentence Comprehension: Evaluates comprehension of syntactically complex sentences. Repetition Subscores: Word Repetition: Measures the ability to repeat single words accurately. Phrase Repetition: Assesses repetition of short phrases or sentences. Naming Subscores: Object Naming: Tests the ability to name objects, often categorized by semantic category (e.g., animals, tools). Action Naming: Evaluates naming of actions or verbs. Responsive Naming: Assesses naming abilities based on descriptions or cues. Phonological Processing Subscores: Phoneme Discrimination: Tests the ability to distinguish between similar phonemes. Phonological Blending: Assesses the ability to blend phonemes into meaningful units. Semantic Processing Subscores: Word-to-Picture Matching: Evaluates matching words to corresponding pictures. Category Fluency: Measures the ability to generate words within a semantic category. Synonym Judgment: Assesses understanding of semantic relationships between words. The subscores in PALPA refer to the specific domains or components of language that are assessed within each task. These subscores help clinicians and researchers pinpoint the specific areas of language impairment in individuals with aphasia. For example, in a naming task, subscores might indicate the accuracy of naming objects in different categories (e.g., animals, tools) or the types of errors made during naming attempts (e.g., phonemic errors, semantic paraphasias). Each subscore provides detailed information about the nature and severity of language impairments, which is crucial for developing tailored treatment plans and understanding the underlying mechanisms of aphasia in each individual. """ bnt = """ The Boston Naming Test (BNT) is a standardized neuropsychological assessment designed to evaluate the ability to name objects presented in picture format. Developed by Kaplan, Goodglass, and Weintraub, it is widely used in clinical settings to assess language impairments, particularly in individuals with aphasia and other neurological conditions affecting language. Key Features of the BNT: 1. Test Format: - The BNT consists of a set of 60 line drawings of objects. These drawings range from common items (e.g., animals, tools) to more complex or less familiar objects. - Participants are asked to name each picture aloud. 2. Administration: - The test is typically administered one-on-one by a clinician or trained professional. - Each picture is presented individually, and the participant's responses are recorded for scoring purposes. 3. Scoring: - Scores on the BNT are based on the number of correctly named items out of 60. - Errors made during naming are categorized into different types: - Semantic Errors: Naming related but incorrect items (e.g., calling a "lion" a "tiger"). - Phonemic Paraphasias: Naming errors where the response is phonologically related to the correct name (e.g., saying "tiger" instead of "lion"). - Circumlocutions: Describing the object instead of naming it. - Perseverations: Repeating the same incorrect response for different items. 4. Clinical Application: - Diagnostic Use: The BNT helps clinicians identify and classify language impairments, particularly deficits in object naming. - Treatment Planning: Results from the BNT guide the development of targeted intervention strategies. For example, if a patient shows a pattern of semantic errors, therapy might focus on semantic feature analysis or semantic association techniques. - Progress Monitoring: Regular administration of the BNT allows clinicians to track changes in naming abilities over time, assessing the effectiveness of interventions and adjusting treatment plans accordingly. - Research Tool: Beyond clinical use, the BNT is also utilized in research settings to investigate language processing and cognitive functions across different populations. 5. Normative Data: Normative data for the BNT provides benchmarks for comparing individual performance to age- and education-matched peers, enhancing the interpretation of test results in clinical and research contexts. Overall, the Boston Naming Test is a valuable tool for assessing and understanding naming abilities in individuals with aphasia and other language disorders, providing critical information for treatment planning and research in neuropsychology and speech-language pathology.""" wab = """The WAB (Western Aphasia Battery) is a comprehensive and widely used assessment tool designed to evaluate language abilities in individuals with aphasia. Developed by Kertesz in 1982 and revised in 2006, the WAB assesses various aspects of language function to provide a detailed profile of language impairment. Here’s an overview of the WAB and its clinical application: Key Features of the WAB: 1. Components: Subtest 1. Spontaneous speech Task Description Scoring 1. Conversational question: The client verbally responds to 6 personal questions. There are 2 scoring sections for Spontaneous speech: Information content and Fluency, grammatical competence, and paraphasias.For Information content:10 points are given if all 6 questions were answered correctly with sentences of normal length and complexity, as well as a reasonably complete description of the picture. Nine points are given if all 6 questions were answered correctly, as well as an almost complete description of the picture. Eight points are given if 5 questions were answered correctly, with an incomplete description of the picture. Seven points are given if 4 questions were answered correctly, as well as at least 6 items in the picture being mentioned. Six points are given if 4 questions were answered correctly, as well as some response to the picture. Five points are given if 3 questions were answered correctly, as well as some response to the picture. Four points are given if 3 questions were answered correctly. Three points are given if 2 questions were answered correctly. Two points are given if 1 question is answered correctly. One point is given for incomplete responses. No points are given for no information. For Fluency, grammatical competence, and paraphasias: Scoring is from 0 to 10. Ten points are given for sentences of normal length and complexity, without slowing down, stopping, or articulatory difficulty, and no paraphasias. As sentences become less lengthy and complex, more slow, and with paraphasias, less points are given. Please see the test manual for further information. 2. Personal description: The client describes a picture in the stimulus book. Subtest 2. Auditory verbal comprehension Task Description Scoring 1. Yes/No questions: The client must answer personal, environment and general questions with a Yes or No. If the client corrects themselves, the last answer is scored. Three points are given for each correct answer. If the answer is ambiguous, 0 points are given. The examiner also marks whether the response was verbal, gestural, or eye blink. 2. Auditory word recognition: The client is shown 6 real objects, as well as cards of pictured objects, forms, letters, numbers and colors. The client must point to what the examiner says. There are 6 items in each category: real objects, drawn objects, forms, letters, numbers, colors, furniture, body parts, fingers and right-left body parts. One point is given to each item pointed to correctly. For the right-left category, the client must get both the side and the body part correct to receive the point. Maximum score is 60. 3. Sequential commands: The client must execute 11 commands that increase in difficulty and length. There are scores associated to the segments in each of the listed commands. Points are given for each correct execution. Please see the test booklet for further information. Maximum score is 80. Subtest 3. Repetition Description Scoring 1. The client must repeat words, phrases and sentences of increasing difficulty (from single words to a complex sentence), with a total of 15 items. As length and difficulty increases, more points are given to the client for correct repetition. Two points are given if an item is incompletely repeated. One point is taken off for errors in the sequence of words, or for every literal paraphasia. Maximum score is 100.Scoring takes phonemic errors into account by permitting partial credit. Subtest 4. Naming and word finding Task Description Scoring 1. Object naming: Show 20 objects from various categories to client, and ask them to name them one at a time. If there is no response to the visual stimulus, the examiner allows the client to touch the stimulus. If there still isn’t a correct response, the examiner presents a phonemic or semantic cue. A maximum of 20 seconds if given to the client to respond. Three points are given if named correctly (or with a minor articulatory error); 2 points are given for a recognizable phonemic paraphasia; 1 point is given if the client needed a tactile or phonemic cue to respond correctly. Maximum score is 60.Permits sequential tactile and phonemic cueing for the patient who cannot provide the proper name upon initial confrontation with the object, yielding qualitatively useful information without sacrificing the integrity of the scoring system. 2. Word fluency: The client must name as many animals as they can in one minute. One point is given for each animal names, even if it is distorted by literal paraphasia. Maximum score is 20. 3. Sentence completion: The client must complete sentences read to them. Two points are given for correct responses; 1 point is given for phonemic paraphasias. Reasonable alternatives are accepted. Maximum score is 10. 4. Responsive speech: The client must answer 5 sentences read to them. Two points are given for acceptable responses; 1 point is given for phonemic paraphasias. Maximum score is 10. 2. Administration: - The WAB is administered by a trained clinician in a structured manner, usually over multiple sessions. - Each component is evaluated through standardized tasks and scoring criteria. 3. Scoring: - Scores on the WAB provide an overall Aphasia Quotient (AQ), which reflects the severity and type of aphasia. - Subscores are also provided for each component (Spontaneous Speech, Auditory Verbal Comprehension, Repetition, Naming), offering detailed insights into specific language deficits. 4. Clinical Application: - Diagnostic Use: The WAB helps clinicians diagnose aphasia and classify its type and severity based on standardized criteria. - Treatment Planning: Results from the WAB guide the development of personalized treatment goals and strategies. For instance, if a patient scores low on auditory comprehension, therapy might focus on auditory discrimination and comprehension tasks. - Progress Monitoring: Regular administration of the WAB allows clinicians to track changes in language abilities over time, assessing the effectiveness of interventions and modifying treatment plans as needed. - Research Tool: The WAB is also utilized in research settings to study language recovery, neuroplasticity, and the effectiveness of different therapeutic interventions. 5. Normative Data: Normative data for the WAB provides benchmarks for comparing individual performance to age- and education-matched peers, enhancing the interpretation of test results in clinical and research contexts. Overall, the Western Aphasia Battery is a comprehensive tool for assessing and understanding the complex language impairments associated with aphasia, providing valuable information for diagnosis, treatment planning, and research in the fields of neuropsychology and speech-language pathology.""" information = f""" Broca's Aphasia: - Spontaneous speech: Non-fluent, effortful, telegraphic - Auditory comprehension: Relatively preserved, especially for simple material - Repetition: Impaired - Naming: Difficult, with frequent pauses - Reading: Often preserved for single words, difficulty with sentences - Writing: Severely impaired, similar to speech output Typical errors: Agrammatism, word-finding difficulties, articulation problems Associated brain region: Posterior inferior frontal gyrus (Broca's area) Case example: A 55-year-old right-handed man presents with halting, effortful speech following a left frontal lobe stroke. He can understand simple commands but struggles to produce complete sentences, often omitting function words and inflections. Wernicke's Aphasia: - Spontaneous speech: Fluent, often with excessive output - Auditory comprehension: Severely impaired - Repetition: Impaired - Naming: Impaired, with semantic paraphasias - Reading: Often impaired, especially for comprehension - Writing: Impaired, with semantic errors and jargon Typical errors: Semantic paraphasias, neologisms, jargon Associated brain region: Posterior superior temporal gyrus (Wernicke's area) Case example: A 70-year-old woman presents with fluent but largely incomprehensible speech following a left temporal lobe stroke. She speaks at length but with little meaningful content, and has significant difficulty understanding even simple commands. Conduction Aphasia: - Spontaneous speech: Fluent with phonemic paraphasias - Auditory comprehension: Relatively preserved - Repetition: Severely impaired - Naming: Mildly impaired, with phonemic errors - Reading: Often preserved, especially for comprehension - Writing: Impaired, with phonemic errors Typical errors: Frequent phonemic paraphasias, repetition attempts and self-corrections Associated brain region: Arcuate fasciculus or left supramarginal gyrus Case example: A 62-year-old woman presents with fluent speech but significant difficulty repeating words and phrases. She understands spoken language well but makes frequent sound-based errors in her speech, often attempting to correct herself. Global Aphasia: - Spontaneous speech: Severely impaired, often limited to stereotyped utterances - Auditory comprehension: Severely impaired - Repetition: Severely impaired - Naming: Severely impaired - Reading: Severely impaired - Writing: Severely impaired Typical errors: Minimal meaningful verbal output, severe impairment across all language domains Associated brain region: Extensive damage to perisylvian language areas Case example: A 75-year-old man presents with almost no meaningful speech output following a large left hemisphere stroke. He is unable to follow commands, name objects, or engage in any form of written language. Anomic Aphasia: - Spontaneous speech: Fluent but with word-finding pauses - Auditory comprehension: Preserved - Repetition: Relatively preserved - Naming: Significantly impaired - Reading: Often preserved - Writing: Mild to moderate impairment, mainly in word retrieval Typical errors: Frequent word-finding difficulties, circumlocutions Associated brain region: Various, often involving the angular gyrus or temporal-parietal junction Case example: A 58-year-old woman presents with fluent speech but frequent pauses as she struggles to retrieve specific words, especially nouns. Her comprehension and repetition abilities are intact. Transcortical Sensory Aphasia: - Spontaneous speech: Fluent but often empty or irrelevant - Auditory comprehension: Impaired - Repetition: Preserved (key distinguishing feature) - Naming: Impaired - Reading: Impaired comprehension - Writing: Impaired Typical errors: Poor comprehension with preserved repetition, semantic paraphasias Associated brain region: Watershed area between middle cerebral and posterior cerebral arteries Case example: A 68-year-old man presents with fluent but often irrelevant speech. He has difficulty understanding complex commands but can repeat even long sentences accurately. Transcortical Motor Aphasia: - Spontaneous speech: Non-fluent, reduced output - Auditory comprehension: Relatively preserved - Repetition: Preserved - Naming: Impaired - Reading: Often preserved for comprehension - Writing: Impaired Typical errors: Reduced speech initiation, preserved repetition Associated brain region: Frontal lobe, anterior or superior to Broca's area Case example: A 72-year-old woman presents with reduced speech output and difficulty initiating conversation. However, she can repeat phrases and sentences without difficulty and shows good comprehension. 1. Fluency vs. Non-fluency - Fluent: Wernicke's, Conduction, Anomic, Transcortical Sensory - Non-fluent: Broca's, Global, Transcortical Motor 2. Comprehension - Good: Broca's, Conduction, Anomic, Transcortical Motor - Poor: Wernicke's, Global, Transcortical Sensory 3. Repetition - Impaired: Broca's, Wernicke's, Conduction, Global - Preserved: Anomic, Transcortical Sensory, Transcortical Motor 4. Naming - Severely Impaired: Wernicke's, Global, Anomic - Moderately Impaired: Broca's, Conduction, Transcortical types Every type of aphasia is equally common and it differs on a patient by patient basis. Provide your classification and a detailed justification based on the patient's performance across all domains. """ cleaned_content = "" # Format the answer answer_info = f""" Information: {cleaned_content}. When I refer to the spreadsheet, use the {example_patients} file to compare the transcript I am giving you. This is a file of aphasic patients of all types, ages, genders, and range of severity. Based on your comparison to these patients, determine the aphasia type and WAB score. Can you analyze the entire spreadsheet. And every row Compare the transcript to the spreadsheet. Give me the top 3 rows that you think align with this patient in transcript. Look only at the PAR lines for this Look only at the PAR lines for this. Each row has language, gender, aphasia type, WAB Score, Transcript. Compare the symptoms of the transcript to the last column of each row in this file to find which symptoms match the spreadsheet. Then, look at the other information. List: Look only at the PAR lines for this. I want you to compare the entire sections. Look towards the ending of the transcript in fact. there is more content there (row in the spreadsheet; Display the first 3 lines and the line that you think connects the transcript the best) (row in the spreadsheet; Display the first 3 lines and the line that you think connects the transcript the best) (row in the spreadsheet; Display the first 3 lines and the line that you think connects the transcript the best) Symptoms: You seem to be confusing word retreival issues and paraphasias/neologisms/Comprehension issues. Try to fixt this 1. Fluency of speech: Is the speech effortful and non-fluent (like in Broca's aphasia) or more fluent but with errors (like in conduction or Wernicke's aphasia)? (number of occurrences), severity percentile (numerical) 2. Comprehension abilities: How well does the patient understand spoken language? This helps differentiate receptive (e.g. Wernicke's) from expressive (e.g. Broca's) aphasias.(number of occurrences), severity percentile (numerical) 3. Repetition skills: Ability to repeat words and phrases is a key diagnostic feature, particularly impaired in conduction aphasia.(number of occurrences), severity percentile (numerical) 4. Naming abilities: Word-finding difficulties are common in many aphasias, but the nature and severity can vary.(number of occurrences), severity percentile (numerical) 5. Presence and types of paraphasias: Phonemic paraphasias (sound errors) vs. semantic paraphasias (meaning-related errors) can point to different aphasia types.(number of occurrences), severity percentile (numerical) 6. Awareness of errors: Whether the patient recognizes and attempts to correct their errors.(number of occurrences), severity percentile (numerical) 7. Agrammatism: The degree to which grammatical structure is impaired.(number of occurrences), severity percentile (numerical) 8. Automatic speech: Ability to produce overlearned phrases or sequences.(number of occurrences), severity percentile (numerical) 9. Reading and writing abilities: These can be differentially affected in various aphasia types.(number of occurrences), severity percentile (numerical) 10. Overall pattern of strengths and weaknesses across language domains.(number of occurrences), severity percentile (numerical) For accurate diagnosis, it's crucial to consider the full pattern of deficits and preserved abilities across all these areas, rather than relying too heavily on any single feature. A comprehensive language assessment considering all these factors is essential for proper aphasia classification. Symptom Severity Rating: Rate the following factors on a scale of 0-10: Fluency: (insert score here; scale of 0-10) Comprehension: (insert score here; scale of 0-10) Repetition: (insert score here; scale of 0-10) Naming: (insert score here; scale of 0-10) Global Aphasia Fluency: 0-5 Comprehension: 0-3.9 Repetition: 0-4.9 Naming: 0-6 Broca's Aphasia Fluency: 0-9 Comprehension: 5-10 Repetition: 0-6 Naming: 0-8 Wernicke's Aphasia Fluency: 0-3 Comprehension: 0-9 Repetition: 3-10 Naming: 0-6 Transcortical Motor Aphasia Fluency: 0-5 Comprehension: 4-10 Repetition: 8-10 Naming: 0-8 Transcortical Sensory Aphasia Fluency: 5-10 Comprehension: 0-6.9 Repetition: 8-10 Naming: 0-9 Mixed Transcortical Aphasia Fluency: 5-10 Comprehension: 0-6.9 Repetition: 8-10 Naming: 0-9 Conduction Aphasia Fluency: 5-10 Comprehension: 7-10 Repetition: 0-8 Naming: 0-9 Anomic Aphasia Fluency: 7-10 Comprehension: 8-10 Repetition: 8-10 Naming: 0-9 Aphasia Classification: 1. Is speech fluent? A fluency disorder is an interruption in the flow of speaking characterized by atypical rate, rhythm, and disfluencies (e.g., repetitions of sounds, syllables, words, and phrases; sound prolongations; and blocks), which may also be accompanied by excessive tension, speaking avoidance, struggle behaviors, and secondary mannerisms (American Speech-Language-Hearing Association [ASHA], 1993). People with fluency disorders also frequently experience psychological, emotional, social, and functional impacts as a result of their communication disorder (Tichenor & Yaruss, 2019a). Make sure that you use the timestamps at the end of the transcripts to do this. Yes -> Check comprehension No -> Check comprehension for non-fluent types 2. Fluent types: - Poor comprehension, poor repetition -> Wernicke's - Poor comprehension, good repetition -> Transcortical Sensory - Good comprehension, poor repetition -> Conduction - Good comprehension, good repetition -> Anomic 3. Non-fluent types: - Poor comprehension -> Global - Good comprehension, poor repetition -> Broca's - Good comprehension, good repetition -> Transcortical Motor Aphasia Classification Trial: (insert type of aphasia) Provide your classification with detailed justification based on performance across all domains. If all of the symptoms are less than 7 occurances, there is no aphasia It is important to look at not just the symptoms but thte content of the speech too. Is what the patient is saying make sense? Do they loose track of the topic? Are they frustrated? Initial Aphasia Diagnosis: Provide 4 types of aphasia it could be. Transcortical Motor Aphasia. Don't forget about Wernicke's aphasia orGlobal aphasia or Transcortical Motor Aphasia or Transcortical Sensory Aphasia Initial Aphasia Types. For each of these types, compare back to the spreadsheet and check this transcript agaiinst every one of the transcripts for that type of aphasia. I dont Wernicke's Aphasia (insert type of aphasia or no aphasia) (insert type of aphasia or no aphasia) Considerations for Alternate Aphasias: List reasons for considering each alternate aphasia. Include detailed comparisons and rationale. Reevaluate the initial diagnosis if substantial evidence supports an alternate type. Type of aphasia: Present this in the format of "Type of Aphasia: (insert aphasia type here)" Provide a confidence score as well. If confidence is below 90% it is another type of aphasia. Keep trying to figure it out. Compare the transcript to the spreadsheet to determine aphasia type and WAB score. WAB Score Determination: Spontaneous Speech: Content Fluency Auditory Verbal Comprehension: Yes/No Questions Auditory Word Recognition Sequential Commands Repetition: Words Phrases Sentences Naming and Word Finding: Object Naming Word Fluency Sentence Completion Responsive Speech Aphasia Quotient (AQ): Overall score indicating the severity of aphasia. 1. Start at WAB score of 5; not 50 because wab can be lower than 50 2. Increase in 10-point intervals, comparing to the spreadsheet. Go all the way to 100 3. Provide reasoning for each step 4. When a suitable interval is found after going all the way to 100, refine by 5-point, then 1-point increments, then 0.1 point increments. 5. Remember: WAB scores can be below 60 or above 93.8 (no aphasia) 6. Determine a score based on the the following studies: The WAB has four subdomains: (1) spontaneous speech; (2) auditory comprehension; (3) repetition; and (4) naming designed to determine the presence of aphasia and judge the type of linguistic deficit and measure the severity of language impairment. The full score of spontaneous speech is 20, including fluency and content of information. The 200 points of auditory comprehension consist of 60 points of Yes–No questions, 60 points of auditory word recognition, and 80 points of sequential commands. The total score of repetition is 100. A total of 100 points are given for naming, including 60 points for object naming, 20 points for fluency of words, 10 points for sentence completion, and 10 points for responsive speech. The calculation formula of the aphasia quotient is “AQ = (Spontaneous + Comprehension ÷ 20 + Repetition ÷ 10 + Naming ÷ 10) × 2”. All of the items result in a range of possible scores from 0 to 100. Combined with the clinical data of stroke patients, those whose aphasia quotient is less than 93.8 can be judged as aphasia, and the smaller the aphasia quotient, the more serious the aphasia. In addition, the WAB-AQ is commonly used to measure recovery, although there is a discrepancy between clinical impression and WAB in the classification of aphasia, the superiority of WAB is that it can quantify language damage. 7. Determine a score by comparing this patient with the participants in the spreadsheet. 8. Compare the 3 scores and determine a final score. Show your thoughts below: WAB Score 1: WAB Score 2: WAB Score 3: WAB Score: Present this in the format of "Estimated WAB Score: (insert number on scale of 0-100 here)". Note that WAB scores can range widely and are not limited to 50-80. IMPORTANT: WAB SCORE IS NOT RELATED TO TYPE OF APHASIA Final Type of aphasia: Based on the WAB score and the original aphasia type, make any changes that you think would be mandatory. If you are borderline 93.8, check if the no aphasia option makes sense. Use the spreadsheet Treatment Suggestions: Provide treatment suggestions in a list, with a description for each therapy. Include a detailed explanation for choosing each treatment, citing the aphasia manual and patient symptoms. Explanation: (Provide a detailed explanation here for the therapist, ensuring it is useful and practical, citing the manual where appropriate). """ def excel_to_json(file): data = {} testing_dates = {} try: workbook = openpyxl.load_workbook(file, data_only=True) logger.info(f"Workbook loaded successfully. Sheets: {workbook.sheetnames}") for sheet in workbook.worksheets: logger.info(f"Processing sheet: {sheet.title}") # Step 1: Identify date columns date_columns = {} for col in range(1, sheet.max_column + 1): cell_value = sheet.cell(row=1, column=col).value logger.debug(f"Column {col}, Header: {cell_value}") if isinstance(cell_value, str) and "Date:" in cell_value: category, date_str = cell_value.split("Date:") category = category.strip() date_str = date_str.strip() try: date = datetime.strptime(date_str, "%m/%Y").date().isoformat() date_columns[col] = (category, date) if category not in testing_dates: testing_dates[category] = [] testing_dates[category].append(date) logger.info(f"Found date column: {category}, {date}") except ValueError: logger.warning(f"Could not parse date: {date_str}") logger.info(f"Identified date columns: {date_columns}") # Step 2: Process rows based on identified date columns current_main_category = None current_section = None current_subsection = None for row_idx, row in enumerate(sheet.iter_rows(min_row=2, values_only=True), start=2): if not any(row): continue logger.debug(f"Processing row {row_idx}: {row}") # Check if this row is a main category if row[0] and isinstance(row[0], str) and row[0] not in date_columns: current_main_category = row[0] current_section = None current_subsection = None logger.info(f"New main category: {current_main_category}") continue # Process data for each date column for col, (category, date) in date_columns.items(): if date not in data: data[date] = {} if category not in data[date]: data[date][category] = {} if current_main_category: if current_main_category not in data[date][category]: data[date][category][current_main_category] = {} # Identify sections and subsections if row[1] and not row[2]: current_section = row[1] current_subsection = None logger.debug(f"New section: {current_section}") elif row[1] and row[2]: current_subsection = row[1] logger.debug(f"New subsection: {current_subsection}") # Process test scores if row[1] and row[2]: key = row[1] max_score = row[2] raw_score = row[col] if len(row) > col else None if raw_score is not None: value = { "Max Score": parse_value(max_score), "Raw Score": parse_value(raw_score) } logger.debug(f"Processed score: {key} - {value}") if current_main_category: if current_section not in data[date][category][current_main_category]: data[date][category][current_main_category][current_section] = {} if current_subsection: if current_subsection not in data[date][category][current_main_category][current_section]: data[date][category][current_main_category][current_section][current_subsection] = {} data[date][category][current_main_category][current_section][current_subsection][key] = value else: data[date][category][current_main_category][current_section][key] = value else: if current_section not in data[date][category]: data[date][category][current_section] = {} if current_subsection: if current_subsection not in data[date][category][current_section]: data[date][category][current_section][current_subsection] = {} data[date][category][current_section][current_subsection][key] = value else: data[date][category][current_section][key] = value # Clean the data structure data = clean_dict(data) logger.info("Data processing completed") except Exception as e: logger.error(f"An error occurred: {str(e)}", exc_info=True) raise return data, testing_dates def parse_value(value): if value is None or value == '': return None if isinstance(value, (int, float)): return value if isinstance(value, str): if value.replace('.', '').isdigit(): return float(value) if '.' in value else int(value) elif value.endswith('%'): return float(value.rstrip('%')) / 100 return value def json_to_text(json_obj, indent_level=0): text_lines = [] indent_space = " " # 4 spaces for indentation if isinstance(json_obj, dict): for key, value in json_obj.items(): if value is not None: # Ensure value is not None text_lines.append(f"{indent_space * indent_level}{key}:") text_lines.extend(json_to_text(value, indent_level + 1)) elif isinstance(json_obj, list): for index, item in enumerate(json_obj): if item is not None: # Ensure item is not None text_lines.append(f"{indent_space * indent_level}[{index}]:") text_lines.extend(json_to_text(item, indent_level + 1)) else: text_lines.append(f"{indent_space * indent_level}{json_obj}") return text_lines def clean_dict(d): if isinstance(d, dict): return {k: clean_dict(v) for k, v in d.items() if clean_dict(v) not in [None, {}, []]} return d def transcribe_audio(file): with tempfile.NamedTemporaryFile(delete=False, suffix=file.name[file.name.rfind('.'):]) as tmp_file: tmp_file.write(file.getvalue()) tmp_file_path = tmp_file.name audio_path = tmp_file_path # Convert MP4 to WAV if necessary if file.name.lower().endswith('.mp4'): video = VideoFileClip(tmp_file_path) audio_path = tmp_file_path + ".wav" video.audio.write_audiofile(audio_path) os.remove(tmp_file_path) elif file.name.lower().endswith('.mp3'): audio = AudioSegment.from_mp3(tmp_file_path) audio_path = tmp_file_path + ".wav" audio.export(audio_path, format="wav") os.remove(tmp_file_path) # Transcribe audio with speaker detection result = model.transcribe(audio_path, verbose=True) # Combine transcription with speaker detection combined_result = [] current_speaker = None current_text = "" for segment in result["segments"]: if segment.get("speaker") != current_speaker: if current_text: combined_result.append(f"Speaker {current_speaker}: {current_text.strip()}") current_speaker = segment.get("speaker", "Unknown") current_text = segment["text"] else: current_text += " " + segment["text"] # Add the last segment if current_text: combined_result.append(f"Speaker {current_speaker}: {current_text.strip()}") # Clean up temporary files os.remove(audio_path) return "\n".join(combined_result) def call_bedrock(prompt): try: body = json.dumps({ "anthropic_version": "bedrock-2023-05-31", "max_tokens": 4096, "messages": [ { "role": "user", "content": prompt } ], "temperature": 0.3, "top_p": 0.9 }) modelId = 'anthropic.claude-3-5-sonnet-20240620-v1:0' response = bedrock.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)}") raise def clean_transcript(input_text): # Keep only lines with speaker labels (*INV:, *PAR:) and their content cleaned_lines = re.findall(r'^\*[A-Z]+:.*$', input_text, re.MULTILINE) # Remove various artifacts and clean up the lines cleaned_lines = [re.sub(r'\d+_\d+$|•\d+_\d+•|\[.*?\]|&=.*?(?:\s|$)|&-\w+|\+<|\(\.\.\)|\.\.\.|‡', '', line) for line in cleaned_lines] # Remove leading/trailing whitespace and any remaining punctuation at the end cleaned_lines = [re.sub(r'^\s+|\s+$|[,\.!?]+$', '', line) for line in cleaned_lines] # Remove empty lines and lines with only punctuation/spaces cleaned_lines = [line for line in cleaned_lines if re.search(r'[a-zA-Z]', line)] return '\n'.join(cleaned_lines) # UI Components def set_page_config(): st.set_page_config( page_title="LingoDx - Advanced Aphasia Analysis", page_icon="🧠", layout="wide", initial_sidebar_state="expanded" ) def apply_custom_css(): st.markdown(""" """, unsafe_allow_html=True) def display_home(): st.title("Welcome to LingoDx") col1, col2 = st.columns(2) with col1: st.markdown(""" ### Our Mission LingoDx is committed to revolutionizing the landscape of aphasia diagnosis and treatment. We empower speech-language pathologists with cutting-edge AI technology to provide more accurate, efficient, and personalized care for individuals with aphasia. ### Key Features: - 🎙️ Advanced Speech-to-Text Analysis - 🧠 AI-Powered Aphasia Diagnosis - 💡 Personalized Treatment Suggestions - 📝 Detailed Patient Reports - ❓ Intelligent Q&A System for Patients and Caregivers """) with col2: pass if st.button("Start New Analysis"): st.session_state['current_stage'] = 'upload' st.rerun() def upload_data(): st.header("Upload Patient Data") col1, col2 = st.columns([2, 1]) with col1: mode = st.radio( "Select input mode:", ("Audio Only", "Excel Only", "Audio + Excel", "Transcript") ) audio_file = None excel_file = None transcript_input = None if mode in ["Audio Only", "Audio + Excel"]: audio_file = st.file_uploader("Upload audio/video file for transcription", type=['wav', 'mp3', 'mp4']) if mode in ["Excel Only", "Audio + Excel"]: excel_file = st.file_uploader("Upload patient data Excel file", type=['xlsx']) if mode == "Transcript": transcript_input = st.file_uploader("Choose a file", type=["txt", "rtf", "cha"]) notes = st.text_area("Additional Notes", "Enter any additional notes here...") with col2: pass # Check if the required data is provided based on the selected mode data_provided = False if mode == "Audio Only" and audio_file is not None: data_provided = True elif mode == "Excel Only" and excel_file is not None: data_provided = True elif mode == "Audio + Excel" and audio_file is not None and excel_file is not None: data_provided = True elif mode == "Transcript" and transcript_input: data_provided = True if data_provided: with st.spinner('Processing data...'): transcription = None json_data = None testing_dates = None if mode in ["Audio Only", "Audio + Excel"] and audio_file: transcription = transcribe_audio(audio_file) st.success("Audio transcribed with speaker detection successfully!") with st.expander("View Transcription"): st.write(transcription) if mode in ["Excel Only", "Audio + Excel"] and excel_file: json_data, testing_dates = excel_to_json(excel_file) if json_data is not None: st.success("Excel data processed successfully!") with st.expander("View Processed Data"): st.json(json_data) if testing_dates: with st.expander("View Testing Dates"): for category, dates in testing_dates.items(): st.write(f"- {category}: {', '.join(dates)}") else: st.error("Failed to process the Excel file. Please check the file format and try again.") return if mode == "Transcript" and transcript_input: content = transcript_input.read().decode("utf-8") transcription = clean_transcript(content) st.success("Transcript processed successfully!") with st.expander("View Cleaned Transcript"): st.write(transcription) # Store the processed data in session state st.session_state['input_mode'] = mode if transcription: st.session_state['cleaned_content'] = transcription if json_data: st.session_state['testing_dates'] = testing_dates st.session_state['cleaned_content'] = json_data st.session_state['notes'] = notes st.info("Data has been processed and stored. You can now proceed to the Analysis section.") if st.button("Proceed to Analysis"): st.session_state['current_stage'] = 'analysis_report' st.rerun() else: st.warning(f"Please provide the required {'audio file' if mode in ['Audio Only', 'Audio + Excel'] else ''}" f"{'Excel file' if mode in ['Excel Only', 'Audio + Excel'] else ''}" f"{'transcript' if mode == 'Transcript' else ''} to continue.") def run_analysis_and_generate_report(): st.header("Analysis, Treatment, and Report") if 'input_mode' not in st.session_state: st.warning("Please upload data first.") return col1, col2 = st.columns([3, 1]) with col1: mode = st.session_state['input_mode'] transcription = st.session_state.get('transcription', '') cleaned_content = st.session_state.get('cleaned_content', {}) notes = st.session_state.get('notes', '') with st.spinner("Analyzing patient data..."): # Analysis prompt analysis_prompt = f""" Analyze the following patient data for aphasia: Input Mode: {mode} {'Transcription: ' + transcription if transcription else ''} {'Test Results: ' + json.dumps(cleaned_content, indent=2) if cleaned_content else ''} Additional Notes: {notes} Please provide a comprehensive analysis of the patient's aphasia symptoms, including potential type and severity. Consider both the transcribed speech and the test results in your analysis. 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. In this scenario, you will be working with a patient who has the following speech disorder or issue: Aphasia Consider the notes when diagnosing the specific type of aphasia {notes} What is aphasia? Aphasia is a disorder that results from damage to portions of the brain that are responsible for language. For most people, these areas are on the left side of the brain. Aphasia usually occurs suddenly, often following a stroke or head injury, but it may also develop slowly, as the result of a brain tumor or a progressive neurological disease. The disorder impairs the expression and understanding of language as well as reading and writing. Aphasia may co-occur with speech disorders, such as dysarthria or apraxia of speech, which also result from brain damage. Who can acquire aphasia? Most people who have aphasia are middle-aged or older, but anyone can acquire it, including young children. About 1 million people in the United States currently have aphasia, and nearly 180,000 Americans acquire it each year, according to the National Aphasia Association. What causes aphasia? Aphasia is caused by damage to one or more of the language areas of the brain. Most often, the cause of the brain injury is a stroke. A stroke occurs when a blood clot or a leaking or burst vessel cuts off blood flow to part of the brain. Brain cells die when they do not receive their normal supply of blood, which carries oxygen and important nutrients. Other causes of brain injury are severe blows to the head, brain tumors, gunshot wounds, brain infections, and progressive neurological disorders, such as Alzheimer's disease. Based on the test scores that I give you, determine the type of aphasia: Here is what each test score means: {wab} {bnt} {palpa} Determine the following based on the test scores. 1. Fluency vs. Non-fluency - Fluent: Wernicke's, Conduction, Anomic, Transcortical Sensory - Non-fluent: Broca's, Global, Transcortical Motor 2. Comprehension - Good: Broca's, Conduction, Anomic, Transcortical Motor - Poor: Wernicke's, Global, Transcortical Sensory 3. Repetition - Impaired: Broca's, Wernicke's, Conduction, Global - Preserved: Anomic, Transcortical Sensory, Transcortical Motor 4. Naming - Severely Impaired: Wernicke's, Global, Anomic - Moderately Impaired: Broca's, Conduction, Transcortical types Use the factors above to determine the aphasia. Make sure that you show your wok and tell me which one you picked and why I want you to grade through the factors above and output that. Here are the patients test scores: {cleaned_content} If speech samples are provided, feel free to use that in the diagnosis as well. Based on the information provided, please do the following: {information} Do this using {answer_info} provided. By implementing these improvements, Document 2 could become even more informative and useful for patients, providing a comprehensive, understandable, and actionable report of their condition and treatment plan. """ analysis_response = call_bedrock(analysis_prompt) # Treatment prompt treatment_prompt = f""" Based on the following aphasia analysis and patient data, suggest a comprehensive treatment plan: Analysis: {analysis_response} Patient Data: {json.dumps(cleaned_content, indent=2)} Additional Notes: {notes} Please provide detailed treatment suggestions, including specific exercises, therapy techniques, and goals for the patient. 1. Non-fluent speech: - Melodic Intonation Therapy (MIT) {mit} - Utterance-based therapy {utterances} 2. Word retrieval issues: - Techniques from Anomia therapy {anomia} - Strategies from Intro to Aphasia Therapy {intro} 3. Grammatical errors: - Agrammatism therapy {agrammatism} - Techniques from Utterance-based therapy 4. Repetitions and revisions: - Strategies from Preservation therapy {preservation} - Techniques from Anomia therapy 5. Paraphasias: - Relevant techniques from Wernicke's Aphasia therapy {wernicke} - Strategies from Anomia therapy 6. Neologisms: - Approaches from Wernicke's Aphasia therapy - Techniques from Intro to Aphasia Therapy 7. Perseveration: - Strategies from Preservation therapy {preservation} - Techniques from Intro to Aphasia Therapy {intro} 8. Comprehension issues: - Auditory Comprehension therapy - Techniques from Wernicke's Aphasia therapy Be creative. There are hundreds of ways to treat each and every symptom. Use the miscellaneous therapies as well. {misc} For each suggested therapy, provide: - Brief description of the therapy - How it specifically addresses the patient's symptom - Expected benefits based on the patient's presentation emember the even if there are a couple errors here or there, it can still be that type of aphasia. Ensure suggestions are tailored to the patient's specific symptoms and severity. Use the Intro to Aphasia Therapy {intro} for general principles and approaches that might apply across different symptoms. When suggesting therapies, consider: 1. The patient's specific type of aphasia 2. The severity of their symptoms (based on WAB score and symptom analysis) 3. Any notable strengths that could be leveraged in therapy 4. Potential for combining techniques from different manuals for a comprehensive approach Format it like this: 1. Comprehension Issues: Therapy: Auditory Comprehension Therapy Description: This therapy focuses on improving the patient's ability to understand spoken language through structured exercises that gradually increase in complexity. How it addresses the symptom: B.B.'s comprehension score (125/200) indicates significant difficulty in understanding spoken language, which is characteristic of Wernicke's Aphasia. Expected benefits: Improved ability to understand spoken language in daily life, which can enhance overall communication and reduce frustration. Specific approach: Start with simple yes/no questions about familiar topics Progress to following one-step commands, then multi-step commands Use visual aids to support comprehension Gradually introduce more complex language and abstract concepts 2. Word Retrieval Issues: Therapy: Semantic Feature Analysis (from Anomia Therapy) Description: This technique involves analyzing the features of objects or concepts to strengthen semantic networks and improve word retrieval. How it addresses the symptom: B.B.'s naming score (58/100) suggests moderate difficulty in word retrieval, which is common in Wernicke's Aphasia. Expected benefits: Improved ability to access and produce target words, potentially reducing the occurrence of paraphasias and enhancing overall expressive language. Specific approach: Present a target word (e.g., "dog") Guide B.B. to generate related semantic features (e.g., "has fur", "barks", "is a pet") Use these features as cues for word retrieval in future sessions Gradually increase the complexity of target words 3. Paraphasias and Neologisms: Therapy: Phonological Component Analysis (adapted from Wernicke's Aphasia Therapy) Description: This approach focuses on the sound structure of words to improve word production accuracy. How it addresses the symptom: Paraphasias and neologisms are common in Wernicke's Aphasia, and B.B.'s moderate naming difficulties suggest these may be present. Expected benefits: Reduced occurrence of paraphasias and neologisms, leading to more accurate and effective verbal communication. Specific approach: Present a target word and analyze its phonological components (number of syllables, initial sound, rhyming words) Practice producing words with similar phonological structures Use minimal pair exercises to distinguish between similar-sounding words Incorporate self-monitoring techniques to help B.B. recognize and correct errors 4. Repetition Difficulties: Therapy: Repetition Therapy (from Utterance-based Therapy) Description: This therapy involves structured repetition exercises that gradually increase in complexity. How it addresses the symptom: B.B.'s repetition score (52/100) indicates significant difficulty in this area, which is common in Wernicke's Aphasia. Expected benefits: Improved ability to repeat words and phrases accurately, which can support overall language production and comprehension. Specific approach: Start with single words, progressing to short phrases and sentences Use visual and written cues to support repetition Incorporate rhythmic and melodic elements to facilitate repetition (drawing from Melodic Intonation Therapy) Gradually reduce cues as B.B.'s performance improves 5. Overall Language Use: Therapy: Conversational Coaching (from Intro to Aphasia Therapy) Description: This approach focuses on improving functional communication in everyday situations. How it addresses the symptom: While not addressing a specific symptom, this therapy can help B.B. integrate skills learned in other therapies into real-life communication. Expected benefits: Improved ability to communicate effectively in daily life, increased confidence, and better social interaction. Specific approach: Practice common conversational scenarios (e.g., ordering at a restaurant, talking to a neighbor) Teach and practice communication repair strategies Incorporate multimodal communication (gestures, writing, drawing) to support verbal communication Gradually increase the complexity and length of conversational exchanges These therapies should be implemented in a structured program, with regular reassessment to track progress and adjust the treatment plan as needed. The focus should be on functional communication and improving B.B.'s ability to participate in daily activities and social interactions. Provide a rationale for each therapy choice, explaining why it's particularly suited to this patient's needs based on their specific presentation of aphasia. When generating responses, consider the patient's current level of ability and gradually increase the complexity of tasks. Provide positive reinforcement and corrective feedback as needed.""" treatment_response = call_bedrock(treatment_prompt) # Report prompt report_prompt = f""" Using the analysis: {analysis_response} and the treatment suggestions: {treatment_response}, write a medical report about the patient Here is the original data: {st.session_state['cleaned_content']} Use the original content for citations for why you wrote what you wrote. Name: Date of Birth: 03/15/1952 Age: 52 Background Information Date of CVA: 11/7/2004 Handedness: Right Clinician: University of Texas at Austin Aphasia Research Laboratory Department of Communications Sciences & Disorders Evaluation Report XX is a 52 year old, right-handed male who lives in Austin with his wife. He has three sons, all of whom no longer live at his residence. He is self-employed and operates his own plumbing business. Mr. XX suffered a left hemisphere cerebral vascular accident on November 7, 2004. He was hospitalized for approximately six days and thereafter, re- ceived outpatient speech therapy for a period of 2 weeks that focused on repetition, nam- ing, word-finding, and writing to dictation. Mr. XX reports continued verbal expression difficulties, including word finding and paraphasias, as well as writing abilities similar to his verbal expression. He also reports no problems with auditory comprehension, gestur- al expression or reading. Mr. XX came to the evaluation to see if further treatment was recommended. Medical History As previously mentioned, Mr. XX experienced a stroke in the left frontal parietal region on November 7, 2004. An MRI strongly suggested an embolism, although no source was found. Mr. XX’s Factor V Leiden heterozygous state was believed to be the precipitating factor in his embolic stroke. His vessels were normal and he had no other risk factors other than obesity and moderate hyperlipidemia. He had extremely high cholesterol and triglycerides, which have since returned to normal with the maintenance of a low fat, low cholesterol diet and Lipitor therapy (10mg at bedtime). Medical examination on January 4, 2005 revealed mild expressive aphasia, intact reading abilities, excellent dexterity, sub- tle right-side dysdiadochokinesis, no dysmetria or dyssynergia, symmetrical reflexes, and a regular heart rhythm. Mr. XX currently takes 325mg of aspirin and Lipitor daily. Behavior During Evaluation Mr. XX came in for the evaluation a total of four times, including three sessions for two hours each, as well as one final session for 1.25 hours. He was pleasant and cooperative and performed all tests administered. Mr. XX did not display evidence of fatigue or anx- iety throughout the testing. Tests Administered (See attachment for references) Western Aphasia Battery, WAB (Kertesz, A., 1982) - Intended purpose of the WAB is to evaluate several aspects of language con- tent, fluency, auditory comprehension, repetition and naming, reading, writ- ing, and praxis. Boston Naming Test, BNT (Kaplan, E., Goodglass, H., & Weintraub, S., 2001) - Intended purpose of the BNT is to evaluate picture naming responses and categorize the type of errors made. Psycholinguistic Assessments of Language Processing in Aphasia, PALPA (Kay, J., Lesser, M., & Coltheart, 1992) - Intended purpose is to evaluate language processing skills in individuals with aphasia. Sections of the test appropriate for this assessment were used. The Pyramids and Palm Trees Test, PPT (Howard, D. & Patterson, K., 1992) - Intended purpose is to assess an individual’s ability to access detailed seman- tic representations from words and pictures. Dynamic Assessment - To evaluate Mr. XX’s functional ability to write names, addresses, and tele- phone numbers to dictation as it pertains to his occupation. Summary of Evaluation Results (See attachment for scores) Fluency A language sample was obtained to evaluate Mr. XX’s ability to fluently relay his thoughts when retelling a familiar wordless picture book story, Cinderella. Mr. XX’s speech was characterized by frequent phonemic paraphasias (distorting a word by substi- tuting, omitting, or adding phonemic elements) when telling the story. For example, he said “Cindereda,” “Cinderlessa” and “Cinderessa” for the word “Cinderella.” He was able to self-correct his phonemic paraphasias on most occasions. Mr. XX’s speech was also characterized by pauses and filler words such as “uh” while accessing words. Mr. XX’s fluency was also evaluated on a subtest of the WAB. The spontaneous speech subtest is designed to elicit conversational speech in reply to questions asked in the con- text of an interview and a picture description. He scored 19 out of 20 possible points on the subtest. His account of the picture consisted of naming the people, objects, and ac- tions and describing their interactions with ample detail. Mr. XX demonstrated moderate use of phonemic paraphasias during this task, including mostly complete, relevant, and grammatical sentences of high complexity and only occasional hesitations. He received a fluency score of 9 out of 10 possible points. Comprehension Mr. XX’s auditory word comprehension was intact for yes/no questions (60/60) and audi- tory word recognition (60/60) on the WAB, as well as relatively intact for sequential commands (75/80). Mr. XX’s ability to discriminate between non-word (67/72) and real word (67/70) minimal pairs was relatively intact on the subtests of the PALPA. The audi- tory lexical decision task on the PALPA for both words (57/60) and non-words (56/60), as well as discriminating between words based on morphology (56/60), were of minimal difficulty for Mr. XX. In the latter task, morphological endings were added to words to transform them into non-words. The auditory lexical decision task examined Mr.’s XX’s ability to identify real words versus nonwords. In addition, he had no difficulty with the spoken word picture matching section (40/40) or the written word picture matching sec- tion (40/40) of the PALPA. These subtests assessed Mr. XX’s semantic comprehension abilities by requiring him to identify the picture that correctly matched the written or spo- ken word from among several distracter items. Throughout the session, Mr. XX dis- played understanding of task directions and rarely asked the clinician to repeat the direc- tions throughout various tasks. Naming On the Boston Naming Test, Mr. XX had minimal difficulty spontaneously naming (58/60) the pictures, although phonological paraphasias were frequently noted during the assessment. For example, Mr. XX said “beaber” for “beaver” and “tripot” for “tripod.” He was able to self-correct his phonemic paraphasias on all occasions. Mr. XX produced the correct response following a stimulus cue on five occasions, often indicating that he al- ready knew the function of each object. On two occasions, phonemic cues were provided to aid response accuracy. Mr. XX scored above the mean for individuals in the same age group. On the WAB, Mr. XX’s object naming (60/60), sentence completion (10/10), and respon- sive speech (9/10) were relatively intact. He did not demonstrate any difficulty in these areas. Mr. XX did, however, demonstrate difficulty with word fluency, which was as- sessed by his ability to name as many animals as possible in the time limit of one minute (12/20). Additionally, he had no difficulty naming letters (52/52), yet demonstrated some trouble producing sounds made by various letters (42/52) on the PALPA. Semantic Processing Mr. XX’s semantic processing abilities, or abilities to retrieve complete and correct se- mantic information, were relatively intact as determined by all three subtests of the Pyramids and Palm Trees Test. The test consists of triads of items, in which one item, given at the top, must be matched with one of two others. The two choices are semanti- cally related, whereas the item at the top is usually from a different category. The choice is then made on the basis of a semantic property or association shared by the given item and the target item. Three subtests were administered. Mr. XX had relatively consistent accuracy on all subtests, scoring 49 out of 52 on the three written words subtest, 49 out of 52 on the 1 written word, two pictures subtest, and 51 out of 52 on the three pictures sub- test. Mr. XX’s semantic comprehension abilities were also shown to be relatively intact by subtests of the PALPA. He had no difficulty listening to spoken words and pointing to the matching picture (40/40) or reading words and identifying the matching picture (40/40). He also experienced minimal difficulty with the Auditory Synonym Judgments subtest (57/60) or the Written Synonyms Judgments subtest (59/60) of the PALPA. The former subtest assessed Mr. XX’s ability to judge whether two spoken words are close in mean- ing, whereas the latter subtest assessed his ability to determine whether two written words are close in meaning. Reading Overall, his various reading skills were relatively intact. The reading comprehension of sentences subtest (40/40) and reading commands subtest (18.5/20) of the WAB demon- strated that Mr. XX’s abilities in these areas were relatively preserved. On subtests of the PALPA, he exhibited relatively intact skills in reading one (7/8), two (8/8) and three (8/8) syllable words, as well as three (6/6), four (6/6), five (6/6), and six (6/6) letter words. Mr. XX demonstrated great difficulty on the task involving reading non-words of 3, 4, 5, and 6 letters, scoring 10 out of 24 possible points. He had numerous phonemic paraphasias when reading the words aloud and experienced more difficulty as the words increased in length. On the “three written words” subtest (49/52) of the PPT, he displayed a relatively intact ability to select semantically related words upon reading three written choices. Writing Overall Mr. XX demonstrated relatively intact writing skills. On the subtests of the WAB, Mr. XX demonstrated relatively preserved skills in writing on request (6/6) and writing to dictation (7.5/10). His written output describing a picture was grammatically and seman- tically appropriate. However, his score (20.5/34) reflected his slowed rate of written pro- duction, making it difficult to complete the task in the amount of time allotted. Because Mr. XX’s occupation often requires him to take phone orders and record names, addresses, and telephone numbers, this functional ability was assessed. Mr. XX’s ability to write notes to dictation was also evaluated through dynamic assessment procedures. He participated in two simulated telephone conversations with the examiner, one in which information was presented at a fast rate, and another in which information was presented more slowly. During the task, Mr. XX spontaneously applied many strategies that helped facilitate accurate transcription of information. For example, during the first trial, Mr. XX indicated to his communication partner that information was being con- veyed too quickly. He asked for multiple repetitions of the data when necessary and in- formed his listener when he was ready to receive additional information. Mr. XX indi- cated that he had worked on these strategies in previous therapy. In addition to the strategies mentioned above, it was also recommended that he repeat information back to his communication partner in order to confirm accurate spelling and recording of infor- mation. Although Mr. XX’s ability to write to dictation appeared relatively intact, it was recommended that he continue to use his strategies when taking messages in order to fa- cilitate accurate transcription. Spelling On the PALPA, Mr. XX demonstrated great difficulty spelling nonwords, scoring 5 out of 24 possible points. He demonstrated nearly equal difficulty spelling both regular words such as wind (15/20), as well as spelling irregular words such as giraffe (14/20). Howev- er, he had minimal difficulty spelling picture names to dictation (36/40) and writing pic- ture names (36/40). He reported that he experienced pre-morbid spelling difficulties. Repetition Mr. XX demonstrated relatively intact ability to repeat words as evidenced on the PALPA (40/40). However, difficulty was demonstrated when repeating words, phrases, and sen- tences on the WAB (82/100), as well as when repeating non-words on the PALPA (26/30). Apraxia Battery The apraxia subtest of the WAB evaluated Mr. XX’s ability to complete skilled or prac- ticed movements that involve the upper limbs (i.e., make a fist) and/or face (i.e., close your eyes) and sometimes require instrumental (i.e., use a comb) or complex (i.e., pretend to drive a car) actions. Mr. XX had no difficulty with these tasks and scored 60 out of 60 possible points. Clinical Impressions According to the results of the WAB, Mr. XX displays characteristics of anomic aphasia. He presented with relatively fluent speech marked by a primary deficit of frequent pho- nemic paraphasias. Mr. XX demonstrated difficulty repeating non-words, phrases, and sentences, as they also included numerous phonemic paraphasias. Additionally, he dis- played a phonological processing deficit given impaired performance with spelling, re- peating, reading, and writing non-words across all tests. No other significant deficits were noted in reading, writing, or visual lexical decision making. Mr. XX also demon- strated relatively intact comprehension skills, intact semantic processing skills, and no significant naming deficits. Additional strengths include his ability to self-cue and self- correct phonemic paraphasias in order to reduce the errors in his speech, as well as his tendency to use strategies that facilitate accurate dictation (i.e., asking for multiple repeti- tions of information). Recommendations: Given Mr. XX’s high-level communication skills, he does not qualify for experimental treatment in the aphasia lab at this time. It is recommended that he continue to facilitate effective communication by using strategies such as asking for multiple repetitions of in- formation when necessary, slowing his rate of speech, indicating when he is ready to re- ceive information when writing to dictation and repeating information back to his listener in order to confirm accurate dictation. He and his wife were provided with information regarding the evaluation. Make this something a patient can use. It has to be friendly, and reassuring. It has to take their considerations into play as listed here {notes}. Follow the example in the example report: {example_report} Make the report look like this(this patient is not the one you shoud follow: {example_report} You cannot be unsure about what you are telling them. Write everything in long full paragraphs. The report should include the following sections: Patient Information (only include if available) Background Information (only include if available) Medical History (only include if available) Behavior During Evaluation (only include if available) Tests Administered Summary of Evaluation Results (Write it all in full length paragraphs) - Fluency (2 short paragraphs) - Comprehension (2 short paragraphs) - Naming (2 short paragraphs) - Semantic Processing (2 short paragraphs) - Reading (1 paragraph) - Writing (1 paragraph) - Spelling (1 paragraph) - Repetition (1 paragraph) - Apraxia Battery (1 paragraph) Take the patient notes into consideration: {notes} Give me a report for this patient based on the information I have given you. If there is anything you don't know, don't add it. Make this report as comprehensive and long as possible. Write what each of the scores mean in the tests in your analysis of results section. """ report_response = call_bedrock(report_prompt) st.subheader("Comprehensive Patient Report") st.write(report_response + treatment_response) st.session_state['report_response'] = report_response # Download button for the report report_text = report_response.encode() b64 = base64.b64encode(report_text).decode() href = f'Download Report' st.markdown(href, unsafe_allow_html=True) with col2: lottie_url = "https://assets3.lottiefiles.com/packages/lf20_q5pk6p1k.json" lottie_json = load_lottie_url(lottie_url) st_lottie(lottie_json, height=300) def run_qa(): st.header("Q&A System") if 'report_response' not in st.session_state: st.warning("Please generate a patient report first.") return question = st.text_input("Ask a question about the patient, aphasia, or suggested therapies:") if question: with st.spinner("Generating answer..."): context = f""" Patient Report: {st.session_state['report_response']} """ prompt = f""" Based on the following context information, please answer the following question: Context: {context} Question: {question} Please provide a comprehensive and informative answer. """ response = call_bedrock(prompt) st.subheader("Answer") st.write(response) # Save Q&A if 'qa_history' not in st.session_state: st.session_state['qa_history'] = [] st.session_state['qa_history'].append((question, response)) st.success("Q&A saved successfully!") # Display Q&A history if 'qa_history' in st.session_state and st.session_state['qa_history']: st.subheader("Q&A History") for i, (q, a) in enumerate(st.session_state['qa_history'], 1): with st.expander(f"Q&A {i}: {q[:50]}..."): st.write(f"Q: {q}") st.write(f"A: {a}") def display_qa_resources(): st.header("Q&A and Resources") tab1, tab2 = st.tabs(["Q&A System", "Resource Center"]) with tab1: run_qa() with tab2: resource_center() def resource_center(): st.header("Resource Center") col1, col2 = st.columns([3, 1]) with col1: st.write(""" Welcome to the LingoDx Resource Center. Here you'll find valuable information and resources for both patients and caregivers dealing with aphasia. """) col_a, col_b = st.columns(2) with col_a: st.subheader("For Patients") st.markdown(""" - [Aphasia Recovery Connection](https://www.aphasiarecoveryconnection.org/) - [National Aphasia Association](https://www.aphasia.org/) - [Aphasia Hope Foundation](https://www.aphasiahope.org/) - [Tactus Therapy Apps](https://tactustherapy.com/apps/) """) with col_b: st.subheader("For Caregivers") st.markdown(""" - [ASHA Aphasia Caregiver Guide](https://www.asha.org/public/speech/disorders/aphasia-caregiver-guide/) - [Aphasia Center of California](https://www.aphasiacenter.org/resources-for-caregivers/) - [Lingraphica - Aphasia Caregiver Guide](https://www.aphasia.com/aphasia-resource-library/aphasia-caregivers-guide/) - [Caregiver Action Network](https://caregiveraction.org/) """) st.subheader("Educational Videos") video_col1, video_col2 = st.columns(2) with video_col1: st.video("https://www.youtube.com/watch?v=zjkgSCIXo3k") with video_col2: st.video("https://www.youtube.com/watch?v=CqmW9cYZNZs") with col2: lottie_url = "https://assets9.lottiefiles.com/packages/lf20_kdx6cani.json" lottie_json = load_lottie_url(lottie_url) st_lottie(lottie_json, height=300) def adaptive_resources(): st.subheader("Personalized Resources") if 'report_response' not in st.session_state: st.warning("Please complete the analysis and generate a report first.") return # Extract key information from the report analysis_prompt = f""" Based on the following patient report, please extract and summarize the following information: 1. Type of aphasia 2. Severity (mild, moderate, severe) 3. Key symptoms (list up to 5) 4. Main areas for improvement (list up to 3) Patient Report: {st.session_state['report_response']} Please provide the information in a simple list format. """ analysis_response = call_bedrock(analysis_prompt) st.write("Patient Information:") st.write(analysis_response) # Generate personalized resources resources_prompt = f""" Based on the following patient information: {analysis_response} Please suggest personalized resources for each of the following categories: 1. Mobile Apps (2-3 suggestions) 2. Websites (2-3 suggestions) 3. Home Exercises (2-3 suggestions) 4. Communication Techniques (2-3 suggestions) 5. Caregiver Resources (2-3 suggestions) For each resource, provide: - Name - A link to the resource - Brief description (1-2 sentences) - Why it's particularly helpful for this patient Please format each category as a section with bullet points for each resource. """ resources_response = call_bedrock(resources_prompt) st.subheader("Personalized Resources") st.write(resources_response) # Additional personalized content st.subheader("Daily Communication Tips") tips_prompt = f""" Based on the patient information provided earlier: {analysis_response} Provide 5 practical daily communication tips for the patient and their caregivers. These tips should be specific to the patient's symptoms and areas for improvement. Format each tip as a bullet point. """ tips_response = call_bedrock(tips_prompt) st.write(tips_response) def display_qa_resources(): st.header("Q&A and Resources") tab1, tab2, tab3 = st.tabs(["Q&A System", "Adaptive Resources", "General Resource Center"]) with tab1: run_qa() with tab2: adaptive_resources() with tab3: resource_center() def main(): set_page_config() apply_custom_css() # Initialize session state if 'current_stage' not in st.session_state: st.session_state['current_stage'] = 'home' if 'cleaned_content' not in st.session_state: st.session_state['cleaned_content'] = {} # Top navigation bar using Streamlit components col1, col2, col3, col4, col5 = st.columns(5) with col1: if st.button("Home"): st.session_state['current_stage'] = 'home' st.rerun() with col2: pass with col3: if st.button("Upload Data"): st.session_state['current_stage'] = 'upload' st.rerun() with col4: if st.button("Analysis & Report"): st.session_state['current_stage'] = 'analysis_report' st.rerun() with col5: if st.button("Q&A / Resources"): st.session_state['current_stage'] = 'qa_resources' st.rerun() # Main content if st.session_state['current_stage'] == 'home': display_home() elif st.session_state['current_stage'] == 'upload': upload_data() elif st.session_state['current_stage'] == 'analysis_report': run_analysis_and_generate_report() elif st.session_state['current_stage'] == 'qa_resources': display_qa_resources() if __name__ == "__main__": main()