LongLAT / app.py
meghanaraok's picture
Update app.py
1b7fd32 verified
import torch
from torch import nn
import pandas as pd
import numpy as np
import gradio as gr
import matplotlib
import matplotlib.pyplot as plt
from LongLAT.models.modeling import CodingModel as LongLATCodingModel, CodingModelConfig as LongLATCodingModelConfig
from HiLATmain.models.modeling import CodingModel, CodingModelConfig
from LongHiLATmain.models.modeling import CodingModel as LongHiLATCodingModel, CodingModelConfig as LongHiLATCodingModelConfig
from run_coding import ModelArguments, DataTrainingArguments
from LongLAT.models.utils import segment_tokenize_dataset
from transformers import (
AutoConfig,
AutoTokenizer,
DataCollatorWithPadding,
EvalPrediction,
HfArgumentParser,
Trainer,
TrainingArguments,
AutoModel,
default_data_collator,
set_seed,
AutoModelForSequenceClassification
)
import hashlib
import colorsys
def hash_to_color(label):
hash_val = int(hashlib.sha256(label.encode('utf-8')).hexdigest(), 16)
hue = hash_val % 256 / 256.0
rgb = colorsys.hsv_to_rgb(hue, 0.3, 0.9)
hex_color = '#%02x%02x%02x' % tuple(int(c * 255) for c in rgb)
return hex_color
def get_coding_model_config(model_name, model_args, data_args, label_dict, num_labels):
model_config_mapping = {
"HiLAT": (CodingModelConfig, CodingModel),
"Long-HiLAT": (LongHiLATCodingModelConfig, LongHiLATCodingModel),
"Long-LAT": (LongLATCodingModelConfig, LongLATCodingModel)
}
config_class, model_class = model_config_mapping.get(model_name)
if config_class is None or model_class is None:
raise ValueError("Invalid model name")
config = config_class(
model_args.model_name_or_path,
model_args.tokenizer_name,
model_args.transformer_layer_update_strategy,
model_args.num_chunks_per_document,
data_args.max_seq_length,
model_args.dropout,
model_args.dropout_att,
model_args.d_model,
label_dict,
num_labels,
model_args.use_code_representation,
data_args.code_max_seq_length,
data_args.code_batch_size,
model_args.multi_head_attention,
model_args.chunk_attention,
model_args.linear_init_mean,
model_args.linear_init_std,
model_args.document_pooling_strategy,
model_args.multi_head_chunk_attention,
model_args.num_hidden_layers
)
return config, model_class
def normalize(num_list):
min_value = min(num_list)
max_value = max(num_list)
for i, val in enumerate(num_list):
num_list[i] = (val - min_value)/(max_value - min_value)*0.7
def parse_tokens(tokens):
# input a list of tokens. output index of words
words_indexes = []
word_start_idx = None
for i in range(len(tokens)):
token = tokens[i]
if token.startswith("▁"):
if word_start_idx == None:
word_start_idx = i
else:
word_end_idx = i
words_indexes.append((word_start_idx, word_end_idx))
word_start_idx = i
return words_indexes
def colorize(words, color_array):
cmap=matplotlib.cm.RdPu
template = '<span style="display: inline-block; color: black; background-color: {}">{}</span>'
colored_string = ''
color_array = torch.tensor(color_array)
for word, color_weight in zip(words, color_array.cpu().detach().numpy()):
color = matplotlib.colors.rgb2hex(cmap(color_weight)[:3])
colored_string += template.format(color, word + '&nbsp') if color_weight>0.035 else '<span style="display: inline-block; color: black;">' + word + '&nbsp</span>'
return colored_string
def visualize_attention(input_ids, tokenizer, outputs, predictions, label_dict):
tokens = []
tokens_attention = outputs['label_attention_weights'].squeeze()
print(tokens_attention.shape)
chunk_attention = outputs['chunk_attention_weights'].squeeze()
print(chunk_attention.shape)
inputs = input_ids.squeeze(0)
print(inputs.shape)
for i in range(len(inputs)):
tokens.append(tokenizer.convert_ids_to_tokens(inputs[i], True))
html_text = "<div>"
print(predictions)
for i in range(predictions.size):
if predictions[0, i] == 1:
code = label_dict.iloc[i]
code_no = code['icd9_code']
code_description = code['long_title']
tokens_attention_code = tokens_attention[:, i, :]
chunk_attetion_code = chunk_attention[i]
concat_tokens = []
concat_attention = []
for i in range(len(tokens)):
chunk_att = chunk_attetion_code[i]
concat_tokens.extend(tokens[i])
attention_numbers = tokens_attention_code[i, :len(tokens[i])] * chunk_att
concat_attention.extend(attention_numbers)
words_idx = parse_tokens(concat_tokens)
words = []
word_attention = []
for index in words_idx:
word = concat_tokens[index[0]: index[1]]
word = (''.join(word)).replace('▁', '')
attention = concat_attention[index[0]: index[1]]
words.append(word)
word_attention.append(sum(attention))
normalize(word_attention)
att_text = colorize(words, word_attention)
code_text = "<span style='color: blue; font-weight: bold'>Code: {} - {}</span><br/>".format(code_no, code_description)
html_text = html_text + code_text + att_text + '<br/>'
html_text = html_text + '</div>'
return html_text
def predict_icd(text_input, model_name, label_count):
labels = []
values = []
if label_count == "50":
labels = ['038.9', '244.9', '250.00', '272.0', '272.4', '276.1', '276.2', '285.1', '285.9', '287.5', '305.1', '311', '33.24', '36.15', '37.22', '38.91', '38.93', '39.61', '39.95', '401.9', '403.90', '410.71', '412', '414.01', '424.0', '427.31', '428.0', '45.13', '486', '496', '507.0', '511.9', '518.81', '530.81', '584.9', '585.9', '599.0', '88.56', '88.72', '93.9', '96.04', '96.6', '96.71', '96.72', '99.04', '99.15', '995.92', 'V15.82', 'V45.81', 'V58.61']
values = [0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0]
if label_count == "5":
labels = ['38.93', '401.9', '414.01', '427.31', '428.0']
values = [1, 0, 0, 0, 0]
label_map = {i: label for i, label in enumerate(labels)}
data_dict = {label: [] for label in labels}
for label, value in zip(labels, values):
data_dict[label].append(value)
data = pd.DataFrame(data_dict)
labels = data.iloc[:, 0:].apply(lambda x: [seg for seg in x], axis=1).tolist()
if 'text' not in data:
data.insert(0, 'text', text_input)
else:
data['text'] = text_input
text = data["text"].tolist()
model_path = "meghanaraok/"+model_name+"_"+label_count
#change
label_dict = pd.read_csv("data/mimic3/"+label_count+"/labels_dictionary_"+label_count+"_level_1.csv")
num_labels = label_dict.shape[0]
if model_name != "ClinicalLongformer":
config_json = "config/"+model_name+"_"+label_count+"/config.json"
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
model_args, data_args, training_args = parser.parse_json_file(json_file=config_json)
coding_model_config, model_class = get_coding_model_config(model_name, model_args, data_args, label_dict, label_dict.shape[0])
kwargs = {
"coding_model_config": coding_model_config,
"args": training_args
}
model = model_class.from_pretrained(model_path, **kwargs)
tokenizer = AutoTokenizer.from_pretrained(model_args.tokenizer_name, padding_side="right")
results = segment_tokenize_dataset(tokenizer, text, labels,
data_args.max_seq_length,
model_args.num_chunks_per_document)
input_ids = torch.tensor(results['input_ids'])
attention_mask = torch.tensor(results['attention_mask'])
token_type_ids = torch.tensor(results['token_type_ids'])
targets = torch.tensor(results['targets'])
targets = targets.float()
with torch.no_grad():
# input_ids = input_ids.to(torch.device("cuda:0"))
# attention_mask = attention_mask.to(torch.device("cuda:0"))
# token_type_ids = token_type_ids.to(torch.device("cuda:0"))
# targets = targets.to(torch.device("cuda:0"))
model_inputs = {
"input_ids": input_ids,
"attention_mask": attention_mask,
"token_type_ids": token_type_ids,
"targets": targets
}
outputs = model(**model_inputs)
else:
tokenizer = AutoTokenizer.from_pretrained('yikuan8/Clinical-Longformer',
padding='max_length',
truncation=False,
max_length=4096,
padding_side="right")
if label_count == "5":
model_path = "meghanaraok/ClinicalLongformer_5"
else:
model_path = "meghanaraok/ClinicalLongformer_50"
model = AutoModelForSequenceClassification.from_pretrained(model_path)
single_input_df = pd.DataFrame({'CombinedChunk': [text_input], 'labels': [[]]})
inputs = tokenizer(single_input_df['CombinedChunk'].tolist(), return_tensors='pt', padding=True, truncation=True, max_length=4096)
with torch.no_grad():
outputs = model(**inputs)
probabilities = nn.functional.sigmoid(outputs['logits'])
predictions = (probabilities >= 0.5).cpu().numpy().astype(int)
if "HiLAT" in model_name:
visualized_text = "<h2>Attention to tokens</h2>" + visualize_attention(input_ids, tokenizer, outputs, predictions, label_dict)
else:
visualized_text = "<div></div>"
predicted_labels = [label_map[i] for i, pred in enumerate(predictions[0]) if pred == 1]
label_probabilities = {label_map[i]: prob * 100 for i, prob in enumerate(probabilities[0]) if label_map[i] in predicted_labels}
y_pred = np.array(predicted_labels)
y_pred = "\n".join(y_pred)
label_dict_df = pd.read_csv("data/mimic3/50/labels_dictionary_50_level_1.csv")
label_dict = label_dict_df.set_index('icd9_code')['long_title'].to_dict()
predicted_labels_with_titles = [(label, label_dict.get(str(label), "Not Found")) for label in predicted_labels]
html_output ="<h2>ICD Codes</h2>"
for label, title in predicted_labels_with_titles:
label = str(label)
color = hash_to_color(label)
html_output += f"<div style='background-color: {color}; padding: 5px; margin-bottom: 5px;'>{label} - {title} <span style='float:right;'>{label_probabilities.get(label, 0):.2f}%</span></div>"
return html_output, visualized_text
sample_texts = {"Sample summary 1": "date of birth: sex: f service medicine allergies levofloxacin attending chief complaint dyspnea pneumonia major surgical or invasive procedure et tube change arterial line placement right ij line placement ir guided picc placement trach placement peg placement picc removed for fungemia single lumen picc placed history of present illness year old woman with history of asthma copd dm hypothyroidism with recent history significant for worsening dyspnea over past three months status post four courses of antibiotics and steroids for presumed copd exacerbation presenting to hospital on with acute worsening dyspnea intubated for respiratory distress and transferred to for further management as noted above she has a history of worsening dyspnea over the past few months that has been treated with antibiotics and steroids she presented to osh on with worsening dyspnea and had a fever to 103f and was started on ceftriaxone azithromycin for pneumonia and copd exacerbation she developed an increasing oxygen requirement however and initially required nasal canula on l o2 but later required face mask on l on her cxr which initially was read as negative for infiltrate progressively worsening with increasingly prominent diffuse bilateral infiltrates right greater than left she also had a negative chest cta with an oxygen requirement that was rising and worsening dyspnea she was transitioned to vanc zosyn levo and then vanc zosyn ceftaz ceftaz started levo on because of an allergy to levofloxacin it is unclear why she received double coverage for gram negatives she was also given methylprednisolone dose mg iv q8 then mg iv q8 afterward on she was admitted to the icu and intubated electively for hypoxia and sob sputum culture grew staph aureas that was mrsa per report influenza viral screen was negative phenylephrine was started because of hypotension to sbps in the 80s after being intubated and starting on propofol which had to be uptitrated for sedation she was transferred to on based on her family s wishes on arrival her ventilator settings were vt 500cc fio2 peep she was on phenylephrine at and rapidly weaned off her vs were vent past medical history copd asthma diabetes mellitus hyperlipidemia hypothyroidism gerd left breast cancer s p lumpectomy h syndrome per pcp social history she does not smoke or drink she lives with her husband family history non contributory physical exam vitals t bp p r o2 general intubated obese arousable heent ett sclera anicteric mmm oropharynx clear neck supple jvp not elevated no lad lungs soft inspiratory wheezes bilaterally no rales or rhonchi cv regularly irregular rate and rhythm normal s1 s2 no murmurs rubs gallops abdomen soft non tender non distended bowel sounds present no rebound tenderness or guarding no organomegaly ext warm well perfused pulses no clubbing cyanosis or edema pertinent results admission labs 36pm type art temp rates tidal vol peep o2 po2 pco2 ph total co2 base xs aado2 req o2 intubated intubated 22pm glucose urea n creat sodium potassium chloride total co2 anion gap 22pm calcium phosphate magnesium 22pm wbc rbc hgb hct mcv mch mchc rdw 22pm plt count 22pm pt ptt inr pt 09pm blood ck cpk ck mb notdone ctropnt 41pm blood ck cpk ck mb notdone ctropnt 00am blood ck cpk ck mb notdone ctropnt 50am blood caltibc ferritn trf 00pm blood fibrino 13am blood ret aut 15pm blood hapto 24am blood triglyc 27am blood triglyc 41am blood tsh 10am blood hba1c spep trace abnormal band in gamma region based on ife see separate report identified as monoclonal igg kappa now represents by densitometry roughly mg dl of total protein upep multiple protein bands seen with albumin predominating based on ife see separate report negative for bence protein immunofixation urine no definite m protein seen negative for bence protein bal flow cytometry there is an immuonphenotypically abnormal cd138 cd56 cell population that most likely represents the highly atypical plasmacytoid immunoblasts seen on giemsa stained cytocentrifuge preparation of the submitted bronchioalveolar lavage fluid the significance of this finding in the context of an acute viral illness is unclear although a reactive process is favored a lymphoproliferative disorder can not be ruled out repeat sampling for cell block preparation and immunohistochemical studies is recommended if clinically indicated bal bronchial washings cytology negative for maligt cells many neutrophils pulmonary macrophages lymphocytes and few multinucleated giant cells rare fungal organisms present consistent with species pm bronchoalveolar lavage gram stain final no polymorphonuclear leukocytes seen no microorganisms seen respiratory culture final ml oropharyngeal flora immunoflourescent test for pneumocystis jirovecii carinii final negative for pneumocystis jirovecii carinii fungal culture preliminary no fungus isolated rapid respiratory viral screen culture source nasopharyngeal swab respiratory viral culture final no respiratory viruses isolated culture screened for adenovirus influenza a b parainfluenza type and respiratory syncytial virus detection of viruses other than those listed above will only be performed on specific request please call virology at within week if additional testing is needed rapid respiratory viral antigen test final this is a corrected report respiratory viral antigen test is uninterpretable due to the lack of cells positive for swine like influenza a h1n1 virus by rt pcr at state lab previously reported as respiratory viral antigens not detected specimen screened for adeno parainfluenza influenza a b and rsv refer to respiratory viral culture for further information reported by phone to dr 12p am urine source catheter legionella urinary antigen final negative for legionella serogroup antigen pm sputum source endotracheal gram stain final pmns and epithelial cells 100x field per 1000x field gram negative rod s respiratory culture final oropharyngeal flora absent pseudomonas aeruginosa sparse growth pseudomonas aeruginosa cefepime i ceftazidime r ciprofloxacin r gentamicin s meropenem s piperacillin r tobramycin s am blood culture source line a line blood culture routine preliminary parapsilosis consultations with id are recommended for all blood cultures positive for staphylococcus aureus and species sensitivities performed on request aerobic bottle gram stain final reported by phone to dr 0800am budding yeast urine cx yeast cta chest no evidence of pe consolidation in the posterior segment of right upper lobe and superior segment of right lower lobe likely aspiration pneumonia atelectasis is in the bases of the lungs given the fact that there is no cardiomegaly or pleural effusions diffuse ground glass opacity is probably not cardiogenic in origin could be resolving noncardiogenic pulmonary edema or drug reaction reactive mediastinal lymphadenopathy ct chest overall improvement in extent of diffuse multifocal bilateral ground glass opacities with minimal areas of worsening opacities in the superior segment of the right lower lobe and in the left upper lobe unchanged mediastinal lymphadenopathy likely reactive signs of anemia bulky left adrenal fatty pancreas tiny liver hypodensity too small to characterize cta chest no pulmonary embolism marked interval worsening of multifocal bilateral ground glass opacities with new areas of consolidation in the bilateral lower lobes and right upper lobe likely reflecting progression of infectious process ct chest impression multifocal bilateral airspace opacities in the lungs grossly unchanged from the prior study tte the left atrium and right atrium are normal in cavity size suboptimal image quality agitated saline contrast injection at rest x did not demonstrate early appearance of contrast in the left atrium there is mild symmetric left ventricular hypertrophy with normal cavity size and global systolic function lvef due to suboptimal technical quality a focal wall motion abnormality cannot be fully excluded with normal free wall contractility the aortic valve leaflets appear structurally normal with good leaflet excursion and no aortic regurgitation the mitral valve appears structurally normal with trivial mitral regurgitation the pulmonary artery systolic pressure could not be quantified there is no pericardial effusion impression suboptimal image quality mild symmetric left ventricular hypertrophy with preserved global biventricular systolic function no definite intracardiac shunt identified tte the left atrium is normal in size left ventricular wall thickness cavity size and global systolic function are normal lvef there is no ventricular septal defect right ventricular chamber size and free wall motion are normal the aortic valve leaflets are mildly thickened but aortic stenosis is not present no aortic regurgitation is seen the mitral valve leaflets are mildly thickened there is no mitral valve prolapse trivial mitral regurgitation is seen there is mild pulmonary artery systolic hypertension there is no pericardial effusion there is an anterior space which most likely represents a fat pad impression normal global and regional biventricular systolic function no diastolic dysfunction or significant valvular disease seen mild pulmonary hypertension tte the left atrium is normal in size left ventricular wall thickness cavity size and regional global systolic function are normal lvef right ventricular chamber size and free wall motion are normal the aortic valve leaflets are mildly thickened but aortic stenosis is not present no masses or vegetations are seen on the aortic valve trace aortic regurgitation is seen the mitral valve leaflets are mildly thickened no mass or vegetation is seen on the mitral valve mild mitral regurgitation is seen no masses or vegetations are seen on the tricuspid valve but cannot be fully excluded due to suboptimal image quality the pulmonary artery systolic pressure could not be determined there is no pericardial effusion impression no vegetations seen suboptimal quality study normal global and regional biventricular systolic function ct head no acute intracranial pathology air fluid level seen in the sphenoid sinuses which may be the result of long term intubation or nasal feeding tube ct head no acute intracranial process if there is a high clinical concern for an infarct an mri with diffusion is recommended abd x ray findings a percutaneous feeding tube is present overlying the midabdominal region a non obstructive bowel gas pattern is visualized with no evidence of free intraperitoneal air abnormalities within the lung parenchyma are seen to better detail on the recent chest ct of earlier the same date hematology complete blood count wbc rbc hgb hct mcv mch mchc rdw plt ct 00am differential neuts lymphs monos eos baso 00am chemistry renal glucose glucose urean creat na k cl hco3 angap 00am antibiotics vanco 16pm brief hospital course year old woman with history of asthma copd dm hypothyroidism presenting to osh with acute on chronic dyspnea treated with antibiotics for pneumonia and intubated for worsening hypoxia and transferred for further management respiratory failure pneumonia she was intubated for worsening hypoxia on at the osh in the setting of pneumonia and worsening bilateral infiltrates her course was notable for progressive worsening of her respiratory status during her osh hospitalization along with development of bilateral infiltrates at the time of transfer her cxr large a a gradient and low pao2 fio2 were thought to be consistent with ards acute lung injury and mechanical ventilation settings targeted low tidal volumes and high respiratory rate however despite this her lung was compliant with low peak inspiratory pressures she was also very peep dependent culture data from the osh eventually demonstrated mrsa in her sputum culture and she was initially managed with vancomycin zosyn and then zosyn was discontinued and she was given a course of solumedrol because of her history of question copd a respiratory viral screen performed at the osh was negative and was repeated at the initial dfa test was negative but the sample was sent to the state lab and there it was positive for h1n1 the id service was consulted and recommended switching from vancomycin to linezolid and empirically completing a course of oseltamavir of note she also underwent a repeat chest cta that was negative for pe and a tte with a bubble study that was limited in quality but negative for intracardiac shunt she continued to require high peep with hypoxia if peep was lower than diuresis was tried several times with minimal change in peep linezolid was switched back to vancomycin given concern for lactic acidosis id then recommended switching to meropenem to cover resistent pseudomonal vap which she continued for a day course a picc line was placed on for long term antibiotics oseltamivir was discontinued on vanco was discontinued gradually able to wean down peep with improvement in bronchospastic episodes on increased sedation and a trach was placed by ip on sedatives eventually weaned off on and transitioned to fentanyl gtt and valium which too were weaned off to a mcg patch q72 hours this should be weaned further at her facility under the direction of the accepting md patient was transitioned to lasix iv boluses until cr and bun bumped then prn to keep her i os even although sputum cx with persistence of pseudomonas per id this was thought to represent colonization pt finished her day course of meropenem on single lumen picc was placed after a day line holiday afib with rvr patient developed af with rvr and hypotension chads score no evidence of pe on cta chest or right heart strain on echo normal atria she was started on hep gtt and amio loaded she remained in sinus rhythm for the majority of the rest of her stay aside from one further bout of afib heparin was discontinued at time of trach placement long term anticoagulation was not started as she is considered low risk s p conversion she was continued on amiodarone and asa volume overload the patient was volume overloaded after about week in the icu lasix gtt was started to have a smoother diuresis as bolus doses of 40mg iv lasix made her transiently hypotensive she was restarted on lasix gtt in setting of pressors which were eventually weaned off she was then transitioned to iv lasix boluses at 160mg iv tid until cr and bun bumped then transitioned to prn lasix boluses to keep i os even of note she was on acetazolamide for a few days due to metabolic alkosis but this was discontinued as bicarb normalizing please give iv lasix 160mg prn to keep fluid balance even fungemia patient began to spike fevers almost one month into her hospitalization she was started on oral fluconazole on due to persistent yeast positive urine cultures despite changing out foley catheters rij placed was pulled however blood cultures from a line grew out yeast presumptively not c albicans on her a line and picc were pulled id was re consulted and recommended switching to micafungin ophthalmology was consulted and did not see evidence of endopthalmitis tte was suboptimal but without e o endocarditis id did not think tee needed as blood cx grew c paraipsilosis changed to fluconazole iv to complete day course of antifungal last dose repeat blood cultures including mycolytic cultures showed no growth to date up until left arm weakness patient was noted to be moving all extremities except the left upper voluntarily on concern was for emoblic event given af as well as fungemia ct head was done which showed no acute process and a tte was without vegitations pt later observed to be moving all extremities and withdrawing to painful stimuli in l arm so no further work up pursued vaginal bleeding she was noted to have vaginal bleeding after a week in the hospital she was evaluated by ob gyn who could not find evidence of further bleeding a pelvic ultrasound was a very limited study but did not find any pathology she should follow up as an outpatient with her ob gyn for further workup hypertriglyceridemia tg elevated to in setting of propofol gtt pt initially switched to fentanyl and midazolam with improvement in tg she was changed back to propofol for vent weaning with continued improvement and subsequent normalization of tg prior to discontinuation atyical bal pathology tissue from bronch done on showed atypical plasmacytoid immunoblasts with abnormal cd138 cd56 cell population on flow cytometry significance unclear in in the context of an acute viral illness and a reactive process was favored although a lymphoproliferative disorder could not be ruled out repeat bronch on with path read of lymphocytes alveolar macrophages neutrophils and rare plasma cells with insufficient tissue for immunohistochemical characterization cytology negative for maligt cells diabetes required insulin drip temporarily for elevated blood glucose but transitioned back to iss with glargine with good control hypothyroidism continued levothyroxine communication patient husband is h son is c medications on admission singulair mg qhs prevacid mg daily levothyroxine mg daily d flonase sprays eat nostril daily advair on inh albuterol nebs prn janumet metformin and sitagliptin discharge medications lansoprazole mg capsule delayed release e c sig one capsule delayed release e c po once a day levothyroxine mcg tablet sig one tablet po daily daily ipratropium bromide mcg actuation aerosol sig puffs inhalation q4h every hours albuterol sulfate mcg actuation hfa aerosol inhaler sig two puff inhalation q4h every hours as needed for shortness of breath or wheezing aspirin mg tablet sig one tablet po daily daily meropenem mg recon soln sig five hundred mg intravenous q8h every hours for days last dose on fluconazole in saline iso osm mg ml piggyback sig four hundred mg intravenous once a day for days last dose on fentanyl mcg hr patch hr sig one patch hr transdermal q72h every hours for days please remove am of fentanyl mcg hr patch hr sig one patch hr transdermal q72h every hours for days please place amiodarone mg tablet sig one tablet po daily daily metoprolol tartrate mg tablet sig tablet po bid times a day nystatin unit ml suspension sig five ml po qid times a day as needed for sores acetaminophen mg tablet sig tablets po q6h every hours as needed for fever chlorhexidine gluconate mouthwash sig fifteen ml mucous membrane times a day docusate sodium mg ml liquid sig one hundred ml po bid times a day hold for loose stools senna mg tablet sig tablets po bid times a day as needed for constipation lactulose gram ml syrup sig thirty ml po tid times a day as needed for constipation insulin glargine unit ml cartridge sig forty units subcutaneous once a day insulin regular human unit ml insulin pen sig sliding scale as below subcutaneous every six hours adjust as needed amp d50 units units units units units units units units units notify m d heparin porcine unit ml solution sig units injection tid times a day discharge disposition extended care facility discharge diagnosis primary h1n1 swine flu pneumonia superinfection with mrsa pneumonia pseudomonas ventilator associated pneumonia parapsilosis fungemia line infection secondary copd asthma diabetes mellitus hyperlipidemia hypothyroidism gerd syndrome left breast cancer s p lumpectomy discharge condition stable on vented trach discharge instructions you were transferred from another hospital for further management of copd exacerbation and pneumonia requiring intubation you likely had swine flu which was complicated by mrsa pneumonia you later also developed a pseudomonas pneumonia you had a complicated icu course but your ventilator was able to be weaned down gradually given your continued need for respiratory support however a tracheostomy was placed and a peg tube in your stomach for nutrition lastly you were treated for a fungal blood infection as you are more stable now you are being discharged to a rehab for further care of note you had an episode of vaginal bleeding however you were examined by ob gyn with a negative pelvic ultrasound and no evidence of any more bleeding you should follow up with ob gyn as an outpatient for further evaluation antibiotic courses are as follows meropenem last dose fluconazole last dose most of your other medications were changed please refer to your new medication list and take all medications as prescribed please call your doctor or come to the ed if you develop chest pain difficulty breathing fevers dizziness loss of consciousness bleeding or any other concerning symptoms followup instructions please follow up with your pcp following your discharge from rehab his office number is please also schedule follow up with ob gyn on discharge from rehab the office number at is completed by ",
"Sample summary 2": "date of birth: sex: m service neurology allergies nkda chief complaint multifocal pontine and cerebrellar infarcts major surgical or invasive procedure pt arrived intubated trach peg multiple bals history of present illness per admitting resident information for the note was taken from the medical records from as well as the patient s daughter hpi year old male with significant medical problems including afib noncompliant on coumadin cad s p stent placement x6 chf with diastolic dysfunction htn morbid obesity alcoholism and dm was transferred from for possible intervention following cva briefly he presented to ed by ambulance on the morning of complaining of days of general malaise and abdominal pain and one bout of emesis he was prompted to call the ambulance after an episode of near syncope during micturition as well as tinnitus he was noted to be hypotensive upon arrival to the ed which resolved following fluid boluses work up in the ed with a head ct showed likely old parietal infarct and possible area of low attenuation in the central pons infarct ct of the abdomen and chest showed no evidence of aortic dissection on presentation his inr was pt 5s and ptt 1s at 35am on he was noted to have transient slurring of his speech with normal upper and lower extremity strength tone and sensation bilaterally he also had labile blood pressures becoming hypertensive to at his speech was still slurred with decreased lue and lle strength tone and sensation were normal and intact at that time at he began to have an expressive language difficulty along with his slurred speech his tongue was noticed to deviate to the right with right facial drooping as well as drooping of the right side of his mouth he also had a poor cough and difficulty clearing his secretions lue and lle strength were decreased to tone in lue and lle was flaccid sensation was intact at on his gag reflex was absent and his lue strength was still with flaccid tone at he was unable to keep his right eye closed against resistance and his lue and lle sensation was decreased mri and mra of the head and neck on the morning of showed possible basilar artery thrombosis with multiple infarcts in the brainstem and cerebellar hemispheres he was note to have abssent gag later in morning and he was intubated prior to arrival in icu for airway protection past medical history atrial fibrillation cad s p stent placement x6 htn chf with diastolic dysfunction morbid obesity alcoholism with enlarged liver dm borderline not on medications sleep apnea r eye blindness since childhood psh s p stent placement at r cea at social history social security disability habits long standing alcoholic and smoker daughter unable to quantify family history htn physical exam on admission t afebrile bp hr irregular o2sat on ventilator gen lying in bed intubated drowsy heent nc at anicteric neck no tenderness to palpation normal rom supple no carotid or vertebral bruit cv afib with heart rate 80s no murmurs gallops rubs lung decreased air entry on left abd bs soft nontender ext no edema cyanosis neurologic examination mental status intubated drowsy however follows commands such as opening eyes moving limbs other exam diificult owing to intubated status cranial nerves pupils equally round and reactive to light to mm bilaterally extraocular movements intact bilaterally no nystagmus trapezius normal bilaterally slight facial droop on right but difficcult to characterise given intubated status motor limited owing to intubated and sedated status he was actively moving his right arm and leg was not actively moving his left ul however partially cooperated with power testing he was noted to have full power in all major muscle groups on right and was antigravity on lul in deltoids and triceps but not against resistance same was noted in lll in ip and hamstrings sensation withdraws to pain bl reflexes hyper reflexic throughout l more than r with left toe downgoing and right toe mute coordination unable to test gait deferred neurological exam at time of discharge awake alert peg and tracheostomy in place brief general exam obese l subclavian line cta b no m g r obese soft abdomen nttp edematous in yues and les non pitting pt nods and shakes head but irreproducibly to questions and requests does not follow commands reproducibly titubation after nodding his head persists for seconds eomi 2mm b l brisk symmetric face tongue to midline responds to mimicking spontaneous fingermovement in l hand noxious stim to rue leads to withdrawal flexor of the lue to noxious bilaterally l foot wiggles toes spontaneously r to noxious only responds with grimace toes extensor bilaterally pertinent results admission labs wbc rbc hgb hct mcv mch mchc rdw glucose urea n creat sodium potassium chloride total co2 anion gap calcium phosphate magnesium pt ptt inr pt hypercoagulability evaluation prothrombin mutation negative factor v leiden negative crp mini bal gram stain final per 1000x field polymorphonuclear leukocytes per 1000x field gram negative rod s per 1000x field gram positive cocci in pairs respiratory culture final ml commensal respiratory flora sputum gram stain final this is a corrected report pmns and epithelial cells 100x field gram stain indicates extensive contamination with upper respiratory secretions bacterial culture results are invalid please submit another specimen previously reported as pmns and epithelial cells 100x field per 1000x field gram negative rod s per 1000x field gram positive rod s per 1000x field gram positive cocci in pairs respiratory culture final sparse growth commensal respiratory flora catheter tips no significant growth no significant growth pending blood cultures bottle staphylococcus coagulase negative isolated from one set only gram stain gram positive cocci in clusters bottle no growth bottle no growth bottle no growth bottle no growth bottle no growth bottle pending bottle pending urine cultures no growth mrsa screens no mrsa isolated discharge labs imaging mri a head and neck impression extensive confluent and multifocal infarcts involving the inferomedial aspect of both cerebellar hemispheres with signal characteristics suggesting that these are late acute or early subacute and correspond to the infarcts demonstrated on the study performed one day earlier no associated hemorrhage herniation or evidence of obstructive hydrocephalus abnormalities involving the vertebral arteries bilaterally with possible origin stenosis on the right and distal occlusion thrombosis on the left given the clinical context the latter in particular could reflect impacted embolic material from a more proximal source the 2d tof and the cranial portion of the enhanced cervical mra both suggest very poor flow in the distal left vertebral artery as well as throughout the basilar artery and its branches including the superior cerebellar vessels bilaterally which may relate to the embolic event above there is no finding on these sequences to specifically suggest vertebral arterial dissection which in general would not account for the bilaterality of the cerebellar hemispheric findings relatively mild atherosclerotic disease involving particularly the left common and internal carotid arteries with no flow limiting stenosis there is no flow limiting stenosis in the intracranial anterior circulation focal cystic encephalomalacia and surrounding gliosis involving the left frontovertex likely related to previous embolic infarct chest x ray impression ap chest reviewed in the absence of prior chest radiographs et tube is in standard placement left pic line tip projects over the anticipated location of the mid svc mediastinum and left hemithorax are very abnormal suggesting extensive mediastinal adenopathy and pleural abnormality perhaps lingular collapse overall the findings are strongly suggestive of extensive maligcy alternatively there could be widespread hemorrhage in both mediastinum and left pleural space right lung clear no pneumothorax ct torso impression et tube approximately cm above the carina left thyroid lobe nodule clinical correlation is recommended small bilateral pleural effusions and lower lobe consolidation versus atelectasis aspiration can have a similar appearance mediastinal and hilar lymph nodes measuring up to cm in short axis diameter these may be reactive but are nonspecific coronary artery calcifications and vascular calcifications trace pericardial effusion chest x ray severe cardiomegaly is stable widened mediastinum mainly due to increase in the mediastinal fat as seen in prior ct from is unchanged et tube remains at the level of the thoracic inlet right ij catheter tip is in the upper svc left retrocardiac opacities have improved consistent with improving previously large areas of atelectasis there is no pneumothorax or large pleural effusions chest x ray indication lymphadenopathy findings endotracheal tube terminates above the thoracic inlet level and could be advanced several centimeters for standard positioning cardiomediastinal contours remain widened based upon review of recent ct torso this appears to be due to extensive mediastinal lipomatosis mild volume overload is present dense left retrocardiac opacity has developed likely a combination of atelectasis and effusion transthoracic echo the left atrium is dilated the right atrium is moderately dilated there is mild symmetric left ventricular hypertrophy the left ventricular cavity is moderately dilated due to suboptimal technical quality a focal wall motion abnormality cannot be fully excluded lv systolic function appears depressed the right ventricular cavity is dilated with depressed free wall contractility the aortic valve leaflets are mildly thickened the aortic valve is not well seen there is no aortic valve stenosis significant aortic regurgitation is present but cannot be quantified the mitral valve leaflets are mildly thickened mitral regurgitation is present but cannot be quantified there is a trivial physiologic pericardial effusion impression poor technical quality due to patient s body habitus both ventricles are dilated and hypokinetic however exact function and size cannot be determined mitral and aortic regurgitation unable to quantify pulmonary artery systolic pressure could not be determined unable to assess if lv thrombus eeg impression this is a mildly abnormal extended routine eeg in the waking state there is occasional theta and delta frequency slowing in the right temporal regions and to a lesser degree there was also mild left temporal slowing consisting of theta frequencies the cardiac rhythm was irregularly irregular with frequent pvcs there were no epileptiform features on this study ct head findings there is no intracranial hemorrhage multifocal hypodensities within the pons and the cerebellum are consistent with the prior infarcts and are better assessed on previous mri left frontal area of cystic encephalomalacia is unchanged otherwise current white matter differentiation of the hemispheres is maintained the ventricles are unchanged in size and configuration there is no uncal or transtentorial herniation there are no fractures there is opacification of scattered ethmoid air cells and mucosal thickening of the sphenoid sinus and maxillary sinuses the mastoid air cells are under pneumatized and opacified impression no intracranial hemorrhage evolving pontine and cerebellar infarcts mastoid air cell opacification and paranasal sinus disease labs at time of discharge cbc 56a pt ptt inr brief hospital course mr is a year old gentleman with a past medical history including atrial fibrillation non compliant on coumadin inr diastolic dysfunction hypertension diet controlled dm and cad s p stenting who initially presented to with tinnitus and presyncope and was transferred to the when he was discovered to have multifocal infarcts involving the pons and both cerebellar hemispheres in the setting of poor posterior circulation he was admitted to the stroke service in the icu from to neuro following his arrival to the an mri and angiography of the head and neck was performed to better characterize the lesions the studies demonstrated extensive confluent and multifocal infarcts involving the pons and inferomedial aspect of both cerebellar hemispheres the strokes appreared in the context of abnormalities in the vertebral arteries possible origin stenosis on the right and distal occlusion thrombosis on the left with poor flow in the basilar artery and its branches including the superior cerebellar vessels there was no associated hemorrhage herniation or evidence of obstructive hydrocephalus the heparin drip initiated at was continued with an initial ptt goal of and subsequent goal of following the placement of a peg coumadin was started with a target inr of two to three the patient s neurological examination remained relatively constant he appeared alert and interactive he could follow basic midline and appendicular requests eg stick out your tongue and lift your right arm there was evidence of gaze evoked nystagmus he could voluntarily shake is head yes and no in addition to moving the distal aspect of his left upper extremity and left toes occasionally clonus was noted in the left upper extremity a bilateral extensor response was observed cvs the patient was monitored by telemetry which demonstrated chronic atrial fibrillation metoprolol was given for rate control and cardioprotection however minimal doses of the beta blocker were used in an attempt to allow a target systolic blood pressure of to a statin was continued per the patient s cardiologist and pcp aspirin and plavix were not necessary for prophylaxis for his cardiac stents and thus these meds were not started as the appearance of the vessel occlusions and infarcts were suggestive of embolic phenomena from a proximal source a transthoracic echocardiogram was performed due to the technical challenges of the study the presence of an lv thrombus could not be explored there is no comment regarding the presence of asd pfo and vegetations note was made of the irregularly irregular rhythm as noted above following the placement of the peg coumadin was started for the atrial fibrillation inr goal of ptt goal while bridging is resp upon arrival mr had an endotracheal tube placed to protect the airway the ett was transitioned to trach in the course of the hospitalization he required mmv respiratory support due to having been noted to have episodes of apnea while on trach mask these occured o n only and were of 30s min duration repeat hct on was performed to evaluate for pontine hemorrhage possibly affecting the respiratory centers this was negative it was felt that etiology was most likely due to pontine infarction will need further monitoring and weaning as tolerated if apneic episodes do not recur id in the course of the hospitalization the patient developed persistent fevers the peak wbc count was the bronchealveolar lavage revealed commensal respiratory flora urine cultures were repeatedly negative one of six blood cultures grew coagulase negative staph and the result was thought to reflect contamination two mrsa screens were negative two sputum cultures were negative and gram stains were considered contaminated by upper respiratory secretions two of three catheter tip cultures were negative iv tip catheter culture grew vre no blood cultures were positive vancomycin was discontinued and he was started on linezolid for a seven day course day with last day of although daily chest x rays failed to reveal clear evidence of the condition treatment with ciprofloxacin cefuroxime and vancomycin was initiated to treat presumed ventilator associated pneumonia he completed day course of ciprofloxacin and cerfuroxime and vancomycin on heme onc there was some concern that the patient could be hypercoaguable analyses for factor v leiden and the prothrombin gene mutation were negative it might be worth conducting a more thorough study eg protein c protein s anticardiolipin ab etc for potential coagulopathy in the non acute setting because the initial chest x ray was thought to show findings concerning for maligcy a ct torso was done the study showed non specific possibly reactive mediastinal and hilar lymph nodes measuring up to cm in short axis diameter there were also small bilateral pleural effusions and lower lobe consolidation versus atelectasis no further investigatory studies were pursued abd gi ultimately on a peg was placed by the interventional radiology service to provide nutrition tube feeds were administered endo insulin was administered by sliding scale with a goal of maintaining normoglycemia renal prior to discharge the lasix was restarted for diastolic dysfunction intermittently however was eventually discontinued due to no oxygen requirement rehabilitation the physical and occupational therapy teams participated in the patient s care code full hcp medications on admission coumadin 10mg qd simvastatin 80mg qd plavix 75mg qd lasix 40mg qd doxazosin 1mg qd nitroglycerin prn chest pain discharge medications chlorhexidine gluconate mouthwash sig one ml mucous membrane times a day miconazole nitrate powder sig one appl topical times a day white petrolatum mineral oil ointment sig one appl ophthalmic prn as needed as needed for dry eyes bisacodyl mg suppository sig one suppository rectal hs at bedtime as needed for constipation famotidine mg tablet sig one tablet po bid times a day simvastatin mg tablet sig two tablet po daily daily nystatin unit ml suspension sig five ml po qid times a day as needed for thrush glucagon human recombit mg recon soln sig one recon soln injection q15min as needed for hypoglycemia protocol multivitamin tx minerals tablet sig one tablet po daily daily metoprolol tartrate mg tablet sig one tablet po tid times a day linezolid mg tablet sig one tablet po q12h every hours last day dextrose gm iv prn hypoglycemia protocol sodium chloride flush ml iv q8h prn line flush peripheral line flush with ml normal saline every hours and prn heparin flush units ml ml iv prn line flush picc heparin dependent flush with 10ml normal saline followed by heparin as above daily and prn per lumen outpatient lab work patient will need inr monitoring to goal inr of cbc monitoring should be peroformed on weekly basis until inr is stable coumadin mg tablet sig one tablet po once a day insulin nph regular human unit ml suspension sig thirty u nph subcutaneous twice a day am and hs for nph and as per sliding scale regular discharge disposition extended care facility rehab center discharge diagnosis primary embolic strokes secondary atrial fibrillation cad htn chf discharge condition hemodynamically stable on ventilator support for tracheostomy neurological exam at time of discharge remarkable for awake alert eyes open tracks past midline mimicks as permitted by motor status but does not reproducibly follow verbal commands brainstem reflexes intact eomi nystagmus on b l gaze perrl 2mm face symmetric but weak able to stick out tongue scm b l is motor reflexes r paraplegia frimaces to noxious trace l finger and l toe movement dtrs increased on l mute on r toes extensor bilaterally discharge instructions you were admitted to after having suffered severe strokes to your cerebellum and your pons parts of your brain you were left with significant neurological deficits at time of discharge you were treated with medicatoins to treat your strokes in addition you had a course complicated by a lung infection and blood infection you were treated with antibiotics because you could not breathe on your own or eat on your own you underwent placement of a breathing tube tracheostomy and feeding tube peg you were started on multiple medications please take them as prescribed you were discharged to a rehabiliation facility for further treatment of your breathing and stroke should you develop any symptoms of concern to you please call your doctor or go to emergency room followup instructions neurology provider md phone at 1pm please call the office of dr danka to set up a follow up appointment after your discharge from rehabilitation completed by ",
"Sample summary 3": "date of birth: sex: f service neurosurgery allergies no known allergies adverse drug reactions attending chief complaint nausea vomiting major surgical or invasive procedure cerebral angiogram with coiling history of present illness 67f fell off step stool days ago and possible loc had laceration on back of head with much bleeding did not seek medical attention at that time has been nauseaous and vomiting since that time daughters brought to osh found diffuse sah and possible r mca distribution loaded with dilantin and transferred to ed and possible r mca distribution loaded with dilantin and transferred to ed past medical history high cholesterol social history married has three children family history parents deceased sister and children alive and well physical exam hunt and grade gcs e v motor o t bp hr r18 o2sats96 gen wd wn comfortable nad heent pupils eoms neck in hard collar extrem warm and well perfused no c c e neuro mental status awake and alert cooperative with exam normal affect orientation oriented to person place and date recall objects at minutes language speech fluent with good comprehension and repetition naming intact no dysarthria or paraphasic errors cranial nerves i not tested ii pupils equally round and reactive to light to mm bilaterally visual fields are full to confrontation iii iv vi extraocular movements intact bilaterally without nystagmus v vii facial strength and sensation intact and symmetric viii hearing intact to finger rub bilaterally ix x palatal elevation symmetrical sternocleidomastoid and trapezius normal bilaterally xii tongue midline without fasciculations motor normal bulk and tone bilaterally no abnormal movements tremors strength full power throughout no pronator drift sensation intact to light touch bilaterally toes downgoing bilaterally on the day of discharge alert and oriented to person place and time patient has full strength and sensation eoms are intact 2mm with brisk reaction bilaterally no pronator drift the patient ambulate with a steady gait and is out of bed to the chair this morning eating breakfast the patient ambulate independently and is out of bed to the pertinent results cta head impression subarachnoid hemorrhage seen on head ct ct angiography of the head demonstrates a x mm aneurysm at the anterior communicating artery with irregular contour study date of pm sinus bradycardia non diagnostic inferior q wave pattern may be a normal variant but cannot exclude prior inferior myocardial infarction left ventricular hypertrophy with marked repolarization abnormalities consistent with left ventricular strain pattern no previous tracing available for comparison read by intervals axes rate pr qrs qt qtc p qrs t ct cspine impression no evidence of acute fracture or dislocation of the cervical spine chest portable ap study date of pm impression mild lingular and bibasilar atelectasis no focal consolidation ct head impression post embolization of the acomm aneurysm sah stable cta head impression interval coiling of anterior communicating artery aneurysm there is no evidence of large vessel occlusion or significant vasospasm the coil pack obscures the aneurysm itself and some adjacent vessels of the anterior circle of persistent moderate hydrocephalus with intraventricular hemorrhage echo the left atrium is elongated no atrial septal defect is seen by 2d or color doppler there is mild symmetric left ventricular hypertrophy the left ventricular cavity size is normal regional left ventricular wall motion is normal left ventricular systolic function is hyperdynamic ef there is a very mild resting left ventricular outflow tract obstruction there is no ventricular septal defect right ventricular chamber size and free wall motion are normal the ascending aorta is mildly dilated the aortic arch is mildly dilated the aortic valve leaflets appear structurally normal with good leaflet excursion there is no valvular aortic stenosis the increased transaortic velocity is likely related to high cardiac output no aortic regurgitation is seen the mitral valve appears structurally normal with trivial mitral regurgitation the pulmonary artery systolic pressure could not be determined there is no pericardial effusion cta head w w o c recons study date of am impression no evidence to suggest vasospasm in the intracranial arterial vasculature further evolution of the subarachnoid and intraventricular hemorrhage 30pm blood wbc rbc hgb hct mcv mch mchc rdw plt ct 45pm blood neuts lymphs monos eos baso 30pm blood plt ct 30pm blood pt ptt inr pt 25am blood glucose urean creat na k cl hco3 angap 30pm blood glucose urean creat na k cl hco3 angap 12am blood glucose urean creat na k cl hco3 angap 43am blood glucose urean creat na k cl hco3 angap 16am blood glucose urean creat na k cl hco3 angap 41am blood glucose urean creat na k cl hco3 angap 01am blood glucose urean creat na k cl hco3 angap 20pm blood glucose urean creat na k cl hco3 angap 51am blood glucose urean creat na k cl hco3 angap 48pm blood glucose urean creat na k cl hco3 angap 45pm blood glucose urean creat na k cl hco3 angap a normal variant but cannot exclude prior inferior myocardial infarction left ventricular hypertrophy with marked repolarization abnormalities consistent with left ventricular strain pattern no previous tracing available for comparison brief hospital course ms is a year old woman who was admitted to the nsicu under the care of dr on after a fall with ct findings of sah and acomm aneurysm she was on dilantin for seizure prophylaxis a ua showed a uti and she was started on cipro seh had some heart block on ekg and some bradycardia in the icu she received a dilantin bolus for a low drug level on she underwent a cerebral angiogram with coiling immediately post angio she was lethargic a head ct was obtained which was stable as patient awoke from sedation her exam was stable on her dilantin level was cardiology consult was called for persistant htn and bradycardia they noted 3sec sinus pauses episodes of sinus arrest with ventricular escape with heart rate to 30s but sbp was stable at ekg showed changes consistent with left ventricular hypertrophy vs cerebral t waves consistent with sah they felt that her bradycardia and htn were consistent with effect from her sah they asked that her calcium channel blocker be stopped which it was on on at she was noted to have a new left facial droop and she was lethargic she had some right deltoid and grasp weakness this strength exam has varied during her admission cta was ordered there was no increase in ventricular size and no concern for vasospasm she was transfered to dr service on her icu course was uneventful she had serial tcds as of which have showed no evidence of vasospasms nimodipine was discontinued secondary to bradycardia and hypotension she completed her course of cipro for urinary tract infection the patients serum sodium was and her serum bun of on patient was transferred to the step down unit in stable condition the patient has a cta consistent with no evidence to suggest vasospasm in the intracranial arterial vasculature and further evolution of the subarachnoid and intraventricular hemorrhage the patient s serum sodium was and her serum bun of on the patients serum sodium was and her serum bun of on routine laboratory blood work was sent and a serum sodium was and her serum bun of sodium chloride tablets grams po bid were initiated for hyponatremia po intake was encouraged her floor course was otherwise uneventful now the day of discharge she is afebrile vital signs were stable and neuro exam stable she is tolerating a good oral diet and her pain is well controlled the patient has had a bowel movement and is voiding without difficulty the patient s serum sodium was and her serum bun of the patient had a point rise in her serum sodium since the day prior while on the sodium chloride tablets the patient will go home on this medication for days at a lower dose of gram with follow up with her primary care this week for follow up of hyponatremia elevated bun and hypertension she is set for discharge home the patient s daughter has concerns about the patients ability to amubulate around the house independently physical therapy assesed the patient prior to discharge the patient was able to ambulate independently but slowly she was able to climb up and down stairs the patient did not need assistance or use of cane or walker but continued to have high level balance and endurance difficulties it was recommended that the patient be discharged home with a course of physical therapy at home for high level balance and endurance the patients daughter was called at home and this was discussed in ma was contact at they will contact the patient either or tuesday medications on admission none discharge medications hydralazine mg tablet sig one tablet po q6h every hours disp tablet s refills acetaminophen mg tablet sig two tablet po q6h every hours as needed for pain do not exceed grams tylenol in hours bisacodyl mg tablet sig two tablet delayed release e c po daily daily as needed for constipation hold for loose stools disp tablet delayed release e c s refills oxycodone mg tablet sig tablets po every six hours as needed for pain do not drive while taking this medication di not take if lethargic disp tablet s refills docusate sodium mg capsule sig one capsule po tid times a day disp capsule s refills senna mg tablet sig one tablet po bid times a day hold for loose stools disp tablet s refills sodium chloride gram tablet sig one tablet po every twelve hours for days please follow up at your primary care physicians to follow your sodium level this week disp tablet s refills outpatient lab work please draw a chem wednesday to monitor bun slightly elevated the day of discharge and serum sodium trending down currently day of discharge while on sodium tablet repleation follow up with your primary care this week please make an appointment with your primary care physcian this week after having your labs drawn on wenesday to follow up your slightly elevated bun and low trending serum sodium and to eveluate further need of sodium chloride tablets po every hours and hypertension and initiation of hydralazine for treatment of high blood pressure during your hospital stay outpatient physical therapy physical therapy at home for high level balance and endurance discharge disposition home discharge diagnosis subarachnoid hemorrhage anterior comunicating artery aneurysm ruptured urinary tract infection bradycardia hyponatremia hypertension discharge condition mental status clear and coherent level of consciousness alert and interactive activity status ambulatory independent activity status ambulatory independent no use of walker or cane able to perform stairs independently continues to have high level balance endurance issues discharge instructions angiogram with embolization coiling ofanterior communicating artery medications continue all other medications you were taking before surgery unless otherwise directed you make take tylenol or prescribed pain medications for any post procedure pain or discomfort what activities you can and cannot do when you go home you may walk and go up and down stairs you may shower let the soapy water run over groin incision rinse and pat dry your incision may be left uncovered unless you have small amounts of drainage from the wound then place a dry dressing or band aid over the area that is draining as needed no heavy lifting pushing or pulling greater than lbs for week to allow groin puncture to heal after week you may resume sexual activity after week gradually increase your activities and distance walked as you can tolerate no driving until you are no longer taking pain medications what to report to office changes in vision loss of vision blurring double vision half vision slurring of speech or difficulty finding correct words to use severe headache or worsening headache not controlled by pain medication a sudden change in the ability to move or use your arm or leg or the ability to feel your arm or leg trouble swallowing breathing or talking numbness coldness or pain in lower extremities temperature greater than 5f for hours new or increased drainage from incision or white yellow or green drainage from incisions bleeding from groin puncture site sudden severe bleeding or swelling groin puncture site lie down keep leg straight and have someone apply firm pressure to area for minutes if bleeding stops call our office if bleeding does not stop call for transfer to closest emergency room angiogram with embolization coiling of anterior communicating followup instructions please follow up with dr in weeks with a mri mra of the brain protocol please call to make this appointment please follow up with you primary care physician this week as your serum bun has been slightly elevated and your serum sodium is has been trending slightly low you will be given a prescription to have your lab studies drawn and please follow up with you primary care by friday to dicuss you were also started on a medication for high blood pressure hydralazine please discuss further management of your hypertension at that time completed by md addendum this entire discharge summary is a duplicate of the discharge summary from earlier today with addendum added to brief hospital course as patient will have physical therapy at home for high level balance and endurance"}
def update_textbox(selected):
sample_text = sample_texts[selected]
text_input = (sample_text)
return text_input
with gr.Blocks() as demo:
gr.Markdown(
"""
# Improvised Transformer-based approach for ICD 9 code prediction
Select a model and use a sample Discharge Summary or copy your Discharge summary to predict the relevant ICD 9 codes.
""")
sample = gr.Dropdown(label="Select Sample Text", choices=sample_texts, info = "Use the selected sample text to Predict relevant ICD9 codes")
use_sample_btn = gr.Button("Use Sample Text")
text_input = gr.Textbox(label="Enter Medical summary")
use_sample_btn.click(fn =update_textbox, inputs=[sample], outputs=text_input)
model = gr.Radio(["HiLAT", "ClinicalLongformer", "Long-LAT", "Long-HiLAT"], label="Model", info="Select the model used for prediction")
label_count = gr.Radio(["5", "50"],label = "ICD Code Prediction Range", info="Select the number of top ICD codes to predict: either the top 5 or the top 50")
predict_btn = gr.Button("Predict")
output = gr.HTML(label="ICD Codes")
predict_btn.click(fn = predict_icd, inputs=[text_input, model, label_count], outputs=[output])
demo.launch(debug= True, share=True, width=600)