import torch
from torch import nn
import pandas as pd
import numpy as np
import gradio as gr
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 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)
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 ="
ICD Codes
"
for label, title in predicted_labels_with_titles:
label = str(label)
color = hash_to_color(label)
html_output += f"{label} - {title} {label_probabilities.get(label, 0):.2f}%
"
return html_output
sample_texts = {"Sample summary 1": "service medicine allergies nsaids sulfa sulfonamide antibiotics attending chief complaint transfer from neurosurg to micu for acute renal failure major surgical or invasive procedure ivc filter placement central line placement arterial line placement hemodialysis intubation mechanical ventilation history of present illness 85m with prior dvt htn and ckd was admitted to nebh with decreased appetite and le swelling found to have extensive dvt and acute on chronic rf was started on heparin gtt and yesterday was noted to have a right facial droop and increased dysarthria r sided weakness and somnolence he developed what appeared to be a r sided seizure and then a grand mal seizure in the ct scanner at the osh he was intubated for airway protection and transferred to to the neurosurgery service he was noted to be hypotensive after intubation without sedation prior to transfer and was started on neo an aline was placed also prior to transfer this morning the neurosurgery attending asked that the micu take over his care given the complexity of his medical problems on eval he was intubated and sedated does not follow commands not on sedation although received mg of iv ativan within the past hours for possible seizure per his son who is at his bedside he was doing well until about months ago at which point they noticed a pound weight loss and hematuria bladder cancer was discovered and he had a cystoscopic removal of tumor weeks ago his son noted that he was increasingly tired w decreased appetite and le swelling he fell and hit his head about week ago but his son noticed only a small cut and so did not have him evaluated over the week prior to admission he became unable to walk and needed a wheelchair to get around past medical history htn thoracic and abdominal aortic aneurysm h o transitional cell bladder cancer ckd h o lumbar laminectomy tertiary hyperparathyroidism bph dvt in the past s p ivc filter placement bilateral cataracts s p removal glaucoma s p l tkr unclear per records pvd fem bipass social history was living independently prior to weeks ago physical exam admission exam general intubated and sedated bites down on ett heent sclera anicteric pinpoit pupils oropharynx clear neck supple jvp not elevated no lad lungs clear to auscultation bilaterally no wheezes rales ronchi cv regular 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 cool feet bilaterally w eschar on r great toe lle swelling w edema not able to palpate pedal pulses doplerable lle dp pt and r dp pertinent results admission labs 58pm blood wbc rbc hgb hct mcv mch mchc rdw plt ct 58pm blood neuts lymphs monos eos baso 58pm blood pt ptt inr pt 58pm blood glucose urean creat na k cl hco3 angap 58pm blood alt ast ck cpk alkphos amylase totbili 58pm blood ck mb ctropnt 38am blood ck mb ctropnt 23pm blood ck mb ctropnt 58pm blood albumin calcium phos mg 58pm blood free t4 58pm blood tsh 58pm blood phenyto 08pm blood type art po2 pco2 ph caltco2 base xs 08pm blood lactate radiology studies ct head on admission findings a mixed but predomitly hyperdense collection overlies the entire left cerebral hemisphere measuring up to mm in greatest transverse dimension and extending along the left tentorium it is consistent with a predomitly acute subdural hematoma this exerts mass effect upon the left hemisphere predomitly in the frontal and temporal lobes with effacement of the underlying cerebral sulci and mild left frontal edema there is a mild rightward shift of the anterior falx septum pellucidum and third ventricle there is mild mass effect upon the left lateral ventricle no intraventricular hemorrhagic extension and no parenchymal hemorrhage is identified prominence of the cerebral sulci is compatible with age related involutional change periventricular regions of hypodensity are compatible with chronic microvascular ischemic change no fracture is identified the paranasal sinuses and mastoid air cells are well aerated the orbits are unremarkable endotracheal and nasogastric tubes are noted impression large acute subdural hematoma along the convexity and tentorium with mass effect as described above ct head on for follow up findings an evolving subdural hematoma along the left cerebral convexity again likely extends along the left tentorium cerebelli minimal mm rightward midline shift is unchanged ventricular and sulcal caliber is unchanged and no new intracranial hemorrhage is identified moderate to severe periventricular white matter hypodensity is consistent with chronic small vessel ischemic changes atherosclerotic calcifications involve the cavernous carotids and intracranial vertebral arteries bilaterally the imaged portions of the paranasal sinuses appear well aerated impression evolving left cerebral convexity subdural hematoma with unchanged minimal mass effect stable compared to the ct from mri head findings areas of slow flow and restricted diffusion are seen in the right posterior parietal periatrial region with high signal on diffusion images and low signal on adc map indicative of acute infarcts small acute infarcts are also seen in right parietal and left frontal lobes there is subacute subdural hematoma identified extending from frontal to occipital region on the left with a maximum width of approximately cm to cm at the convexity with indentation on the sulci increased signal along the sulci may indicate small amount of subarachnoid hemorrhage or stasis of the csf secondary to subdural small amount of subdural collection is also seen along the left side of the tentorium there is no midline shift seen moderate to severe brain atrophy and moderate changes of small vessel disease are identified there is no midline shift sagittal t2 images were obtained to evaluate the brainstem but are limited by motion changes of cervical spondylosis are visualized which are further evaluated with cervical spine mri bilateral basal ganglia lacunes are seen impression small areas of restricted diffusion in the left frontal lobe right parietal lobe and left periatrial region suggestive of embolic infarcts left sided subdural hematoma extending from frontal to occipital region with obliteration of adjacent sulci no midline shift brain atrophy and small vessel disease mri c spine impression limited study due to motion multilevel degenerative change is seen moderate spinal stenosis at c4 and mild to moderate spinal stenosis at c5 and c6 with extrinsic indentation on the spinal cord postoperative changes with posterior bony bar at c3 slightly indenting the spinal cord atrophic changes in the spinal cord at c3 level echos the left atrium is elongated left ventricular wall thicknesses and cavity size are normal there is mild regional left ventricular systolic dysfunction with focal hypokinesis of the basal inferior and inferolateral walls the remaining segments contract normally lvef right ventricular chamber size and free wall motion are normal the ascending aorta is mildly dilated the descending thoracic aorta is mildly dilated the aortic valve leaflets are mildly thickened but aortic stenosis is not present there is no aortic valve stenosis mild aortic regurgitation is seen the mitral valve leaflets are structurally normal there is no mitral valve prolapse trivial mitral regurgitation is seen there is mild pulmonary artery systolic hypertension there is no pericardial effusion impression normal left ventricular cavity size with mild regional systolic dysfunction c w cad pda distribution dilated ascending and descending thoracic aorta mild pulmonary artery systolic hypertension the left atrium is elongated left ventricular wall thicknesses and cavity size are normal there is mild regional left ventricular systolic dysfunction with hypokinesis of the inferior and inferolateral walls the remaining segments contract normally lvef right ventricular chamber size and free wall motion are normal the ascending aorta is mildly dilated the aortic valve leaflets are mildly thickened but aortic stenosis is not present mild aortic regurgitation is seen the mitral valve leaflets are mildly thickened trivial mitral regurgitation is seen the estimated pulmonary artery systolic pressure is normal there is no pericardial effusion compared with the prior study images reviewed of a prominent left pleural effusion is now identified and the estimated pulmonary artery systolic pressure is lower left ventricular wall motion is similar lower extremity cath comments access via lfa via 4f catheter imaging of the distal aorta with a omniflush catheter at l1 revealed mild aortic disease with no renal artery stenosis the iliacs were very tortuous on both sides but without flow limiting lesions the cfa s were without lesions imaging of the right leg with a slip cath in the right sfa revealed a mid sfa 10cm occlusion there was a high grade popliteal lesion and single vessel run off to the foot via a peroneal there was only very faint filling of plantars and dp referral to vascular surgery for right leg bka final diagnosis right sfa occlusion with severe infra popliteal disease renal us impression probably no hydronephrosis ct abdomen and pelvis follow up findings cc of contrast was administered through g tube there is no contrast extravasation extensive pneumoperitoneum is again noted however this is unchanged from the prior examination from the previous day there is bilateral pleural effusion small in quantity not significantly changed from the prior study the unenhanced liver and spleen appear unremarkable there is bilateral hydronephrosis and mild hydroureter this is likely on the basis of the significant wall thickening seen in the urinary bladder aneurysmal abdominal aorta at the diaphragmatic crura is unchanged from prior study with atherosclerotic changes the gallbladder appears dilated though unchanged from the prior study again noted is prominence of the left psoas muscle with an area of hypodensity which may represent fluid collection however infection cannot be excluded there is no evidence of bowel dilatation ivc filter is again noted there are degenerative endplate changes in the thoracolumbar spine impression no evidence for g tube extravasation no interval change in enlargement of the left psoas muscle with hypodense collection in the left flank while this may represent old hematoma a loculated infected collection cannot be excluded and intravenous contrast would be necessary for additional evaluation again noted mild bilateral hydronephrosis which is likely secondary to significant bladder wall thickening unchanged pneumoperitoneum ct chest impression dilated ascending aorta and thoracoabdominal junction bilateral psoas hematoma much larger on the left extending in the retroperitoneum labs on discharge chms added agap wbc hct plt all have been stable over the last several days estgfr click for details ck mb trop t comments ctropnt called 303am ctropnt ctropnt ng ml suggests acute mi ca mg p alt ap tbili alb ast ldh dbili tprot lip serum asa etoh acetmnphn benzo barb tricyc negative comments positive tricyclic results represent potentially toxic levels therapeutic tricyclic levels will typically have negative results tsh free t4 phenytoin pt ptt inr fibrinogen of note in microbiology pt only grew albicans in urine otherwise all cultures were negative without any obvious organism brief hospital course year old gentleman with cri htn bladder ca and known r transferred from nebh with subdural hematoma seizures and new acute on chronic renal failure requiring dialysis he was transfered to our neurosurgical service then micu for evaluation of altered mental status and sepsis altered mental status ams began with the development of a sdh after treatment of extensive lle dvt with a heparin gtt the patient was transfered to the micu on neurosurgery was the initial primary team then consulting and based on family discussions and repeat head imaging no intervention was performed his neurologic status did improve over time but persistent deficits lead to subsequent neurologic consultation the following problems were addressed by the neurology team for his encephalopathy toxic metabolic work up identified the following possible etiologies yeast uti pna r le necrosis l dvt esrd on hd his sedating medications were limited a repeat routine eeg demonstrated no evidence of subclinical sz activity mri of the brain however demonstrated small areas of restricted diffusion in the left frontal love right parietal love and left periatal region suggestive of embolic infarcts improving sdh for his strokes mri of the brain demonstrated actute embolic infarcts a subsequent tte on demonstrated regional left ventricular systolic dysfunction consistent with coronary artery disease a left atrial thrombus cannot be excluded by tte if clinically indicated a tee would better assess for this possibility no significant change from prior carotid ultrasound noted less than stenosis in the right and left internal carotid arteries mra was held due to concern for acute on chronic renal disease the patient was placed on asa to treat the embolic strokes after consultation with neurosurgery for his quadraparesis mri of the c spine multilevel degenerative change is seen with moderate spinal stenosis at c4 and mild to moderate spinal stenosis at c5 and c6 with extrinsic indentation on the spinal cord and postoperative changes with posterior bony bar at c3 slightly indenting the spinal cord atrophic changes in the spinal cord at c3 level the patient was transferred to the micu minimally responsive to stimuli on intermittent ativan he was intubated for airway protection and maintained on pressure support with minimal requirements his altered mental status was attributed to a combination of new subdural hematoma which remained stable throughout admission and resulting seizure activity on transfer he is responsive to questions with the appropriateness of his garbled answers uncertain as treatment for the seizures he was started on keppra and should be continued on this until neurology follow up is arranged the dose is keppra mg subdural hematoma after discovery of an extensive dvt of the lle at an osh the patient was started on a heparin gtt he subsequently developed right facial droop and increased dysarthria r sided weakness and somnolence he developed what appeared to be a r sided seizure and then a grand mal seizure in the ct scanner at the osh he was intubated for airway protection and transferred to to the neurosurgery service he was noted to be hypotensive after intubation without sedation prior to transfer and was started on neo heparin was stopped due to head bleed and ivc filter placed the patient developed a subdural hematoma at the outside hospital presumed secondary to heparin therapy for a dvt neurosurgery was the initial primary team then consulting and based on family discussions and repeat head imaging no intervention was performed the hematomas were stable on transfer see below for seizure treatment related to hematoma seizures the patient developed right sided seizures likely due to his subdural hematoma as confirmed by eeg and neuro consult the patient was started on ativan dilantin and keppra for seizure control he will be tapered off of dilantin transitioned to keppra and the ativan held acute on chronic renal failure acute on chronic kidney failure likely due to contrast induced nephropathy despite pretreatment with ivf and bicarb the patient was admitted with temporary hd line in place after days of hd he was seen by our renal service and dialyzed once through the temporary line with no further indication for dialysis at the time of transfer the patient developed a fever of unknown origin and the temperary hd line was pulled due to concern that it would be seeded by infection he subsequently developed fluid overload resistent to medical therapy nephrology then saw him and placed a permanent hd line and received regular hd he develops moderated hypotension during hd but was otherwise asymptomatic the plan is to continue monday and thursday dialysis indefinitely for now the renal team will directly contact the receiving rehab facility about dialysis information pneumonia gram suggestive of infection treated with days of vanc zosyn followed by unasyn with a resolution of white count and no fevers early in the admission he did have another infection of unclear source which resulted in sepsis and a second transfer to the micu see below for details of that infection right toe eschar unable to palpate doppler pulses and concern is for arterial insufficiency vascular consulted follow recs suggested nitropaste only no intervention given bleed and contraindication for heparin due to intermittant hypotension the nitropaste was discontinued he went for catheterization which demonstrated severe diffuse disease not amenable to stenting due to prior sdh patient was not a candidate for anticoagulation prelim report on us showed sfa occlusion with reconstitution distal to popliteal dvt the patient was found to have extensive dvt and acute on chronic rf was started on heparin gtt and subsequently developed a sdh the heparin was stopped and an ivc filter was placed in he does not have signs of pe with good oxygenation on room air hematuria insetting of change of and care the patient also has a history of bladder cancer urology saw patient earlier in admission several u as were positive for yeast infection the patient had a prolonged course of oral fluconazole and topical miconazole the yeast infection cleared on subsequent u a but per urology recs he is to complete a day course of fluconazole the end date of fluconazole is days from day of discharge on he should not have his foley changed once at rehab as it was placed with cystoscopy and is a difficult change he should follow up with urology in weeks after his fluconazole is completed for reevaluation of need for foley in setting of arf he does still make small amounts of urine inability to swollow possibly multifactorial with left sided sdh and acute embolic areas of infarction in addition to severe cervical spinal stenosis speach and swallow evaluation occurred on more than one occasion and he was unable to protect his airway and did not have a gag reflex after a significant amount of time with an ng tube and multiple conversations with the son her received a g tube he is receiving tube feeds and reached his goal rate hypotension developed within two days of g tube placement and in the setting of penile instrumentation etiology could be from a number of cuases including bleeding in the setting of his recent g tube placement hypovolemia perhaps increased vagal tone from bladder distention sepsis from gangrenous foot and acs a ct of his abdomen demonstrated a fluid collection that was not consistent with blood by but could not differentiate between sterile fluid collection or an abscess without contrast the patient received fluid boluses narcan to reverse the potential effects of the 1mg of i v morphine the patient received in addition the patient had blood and urine cultures the urine culture wa positive for bacteria and wbcs rbcs the patient remained persistently hypotensive despite ivf and was transferred to the micu for concern for urosepsis see below for micu course anemia hct in setting of hemodilution and hematuria no further hematuria overnight after foley replaced by urology iron studies were obtained and were consistent with anemia of chronic disease the hct remained stable thrombocytopenia resolved micu admission patient was transferred to micu on for hypotension in the setting of concern for sepsis with a possible complication of the g tube placement imaging did not show problems with the g tube placement and patient became afebrile and resolved leukocytosis on vanc zosyn fluconazole surgery followed and determined that the g tube was safe to use pressures were map and sbp in 90s higher than pressures on admission pressure throughout the course of hospitalization have not been greater than sbp sepsis his hypotension that resulted in transfer to the micu was likely urosepsis although no organism was ever grown in culture other sources could have been the intraabdominal fluid collection although surgery consulted and did not think it was an infection he responded to a course of vanco and zosyn and should complete a two week course of the antibiotics the end date is he had a midline placed for abx administration he recovered quickly without any need for pressure support he was not dialyzed during this time because of his hypotension but has been dialyzed the last two days prior to discharge and was run even he maintained his bps during this time pneumoperitoneum on ct scan during imaging while working up his hypotension ct revealed pneumoperitoneum around the g tube placement he had a benign abdomen exam and it was not thought to be cause of his hypotension his tube feeds were initially held but with surgery following along were restarted several days prior to discharge he quickly reached goal and did not have high residuals svt the day prior to discharge the patient developed transient episodes of svt with rates of the episodes last approximately minutes and were asymptomatic to the patient he maintained a normal blood pressure during these episodes most of the episodes broke with vagal manuevers or with a spontaneous pvc we started diltiazem for rate control at a very low dose as to not drop his blood pressures he tolerated the diltiazem well and should be continued on it in summary y o m who presented after anticoagulated dvt resulted in sdh also found to have old strokes now with resultant quadraparesis had seizures that were treated with keppra also initially had a pneumonia s p treatment while receiving imaging during workup of these above issues developed acute on chronic renal failure and started on hd now due for monday and thursday dialysis had workup of ischemic feet showed diseased vasculature but no intervention done no infection of necrotic toes was recovering well but after g tube placement had hypotension likely from sepsis of unclear etiology although urine most likely source has known yeast infection in bladder urology following and has permanent foley cath in is being treated with vanco and zosyn and fluconazole for sepsis had svts treated with diltiazem so once at rehab he should continue his antibiotic course of vanco zosyn and fluconazole he can start pt ot he should follow up with neuro urology and his pcp medications on admission oxycodone calcitrol prilosec mentax avocat flomax timoptic travatan dyazide vitamin d vitamin b12 on transfer lorazepam mg iv once duration doses order date iv access temporary central access icu location left subclavian date inserted order date lorazepam mg iv q4h seizure activity hold if oversedated order date ml ns continuous at ml hr order date magnesium sulfate gm iv once duration doses order date ml ns bolus ml over mins order date norepinephrine mcg kg min iv drip titrate to sbp 100mmhg order date ml ns bolus ml over mins order date pantoprazole mg iv q24h order date ml ns bolus ml over mins order date phenytoin mg iv q8h hold am dose until trough level back order date acetaminophen mg pr q4h prn fever or pain order date piperacillin tazobactam na g iv once duration doses awaiting id approval id approval is required for this order order date calcium gluconate gm ml d5w iv once duration doses order date pneumococcal vac polyvalent ml im asdir order date chlorhexidine gluconate oral rinse ml oral use only if patient is on mechanical ventilation order date sodium chloride flush ml iv q8h prn line flush peripheral line flush with ml normal saline every hours and prn order date influenza virus vaccine ml im asdir follow influenza protocol document administration in poe order date sodium chloride flush ml iv prn line flush temporary central access icu flush with 10ml normal saline daily and prn order date insulin sc per insulin flowsheet sliding scale order date vancomycin mg iv once duration doses order date discharge medications latanoprost drops one drop ophthalmic hs at bedtime timolol maleate drops one drop ophthalmic times a day lidocaine mg patch adhesive patch medicated one adhesive patch medicated topical qd apply to mid back heparin porcine unit ml solution one injection times a day calcium carbonate mg ml mg suspension one po tid times a day miconazole nitrate powder one appl topical tid times a day as needed cholecalciferol vitamin d3 unit tablet two tablet po daily daily aspirin mg tablet one tablet po daily daily acetylcysteine mg ml solution one ml miscellaneous q6h every hours as needed for cough simvastatin mg tablet two tablet po daily daily ipratropium bromide solution one inhalation q6h every hours lansoprazole mg tablet rapid dissolve dr one tablet rapid dissolve dr daily daily levetiracetam mg ml solution five hundred mg po bid times a day fluconazole mg tablet one tablet po q48h every hours for days monitor for interaction with statin watch for ck elevation or rhabdo vancomycin in dextrose gram ml piggyback one gram intravenous hd protocol hd protochol through piperacillin tazobactam gram recon soln one intravenous twice a day through insulin lispro unit ml solution per sliding scale subcutaneous asdir as directed please see sliding scale epoetin alfa unit ml solution at hemodialysis injection asdir as directed verapamil mg tablet one tablet po q12h every hours discharge disposition extended care facility rehab center discharge diagnosis deep venous thrombosis subdural hemorrhage seizure disorder end stage renal disease on hemodialysis svt treated with vagal maneuvers discharge condition vital signs were stable sbp occassionally drops to 80s but pt is without change in mental status patient with g tube in place patient is communicative with non verbal signs afebrile completing course of antibiotics discharge instructions you were admitted initially at with decreased appetite and leg swelling you were found to have extensive dvt and acute on chronic renal failure you were later noted to have right sided weakness and somnolence developed what appeared to be a right sided seizure and then a grand mal seizure you were intubated for airway protection and transferred to here we treated you for your seizures we found that they were likley caused by a large subdural hematoma in your brain you also developed renal failure and needed to start hemodialysis he placed a gtube in your stomach to feed you we also needed to treat you for a severe infection that caused your blood pressure to get low you were on antibiotics and improved you will now continue to recover at rehabilitation complete your course of antibiotics and work on your strength please return to the hospital or call your doctor if you have temperature greater than shortness of breath worsening difficulty with swallowing chest pain abdominal pain diarrhea or any other symptoms that you are concerned about followup instructions please call to make an appointment with dr urologist for follow up weeks after discharge please call to make and appointment with dr neurology for follow up for weeks after discharge md completed by ",
"Sample summary 2": "date of birth: sex: m service medicine allergies percocet erythromycin base a c e inhibitors nsaids attending chief complaint fevers rigors major surgical or invasive procedure dialysis bilateral hematoma and right lower quadrant hematoma incision and drainage left arm picc placement history of present illness year old male with a history of end stage renal disease of unknown etiology on hd htn prior history of hodgkin s disease gout peptic ulcer disease hypothyroidism depression presenting with fevers after right subclavian hd line was placed by transplant surgery days prior to admission mr went for his first hd treatment after new line placement day prior to admission with temps to he also developed rigors this morning and presented to his fever climbed to and was given vancomycin blood cultures from his hd line and was given fluid boluses and was then transferred to given that his nephrologist and transplant team are here in the ed his heart rates were in the 130s with a rectal temperature of he was visibly in rigors and not endorsing any pain otherwise he received tylenol and ativan for his rigors zosyn was added on to his vancomycin transplant team pulled his hd line and tip was sent for culture an ekg done in the ed showed st elevations in avf and lead iii with st depressions in v1 and v2 however these resolved on repeat ekg set of troponins was elevated to with no prior troponins to compare to ck mb was of normal fraction cards was consulted and they felt the troponin elevation was in the setting of chronic renal failure and demand ischemia in setting of tachycardia aspirin was given they did not recommend anticoagulation in setting of demand iv vancomycin was redosed and l of iv fluids were given vitals in the ed were hr bp rr satting ra past medical history chronic renal failure cr baseline followed by dr at no kidney biopsy hypertension hodgkin s disease s p chemotherapy with and radiation reportedly as a result of chemo treatment left him with numbness below the waist depression with one prior psych hospitalization h o suicidal attempt with narcotics overdose left eye blindness evaluated in ed on with functional overlay back pain right flank pain requiring chronic narcotics as per pt unknown etiology hypothyroidism gout tear post radiation pancreatitis chronic anemia social history pt lives with his wife and his children he is on disability used to work as emt pt denies tobacco alcohol or illicit drug use family history father s p renal transplant hypertensive nephropathy mother depression and alcohol dependence two sons ages and with renal dysplasia no history of deafness or cystic kidney disease physical exam admission physical exam vs hr 120s bp ra rr temp gen in nad lying in bed heent anicteric oropharynx clear cardiac tachycardic no murmurs appreciable chest old suture evident from prior line placement pulm clear in anterior fields abd soft and nontender ext no edema noted discharge physical exam vs tm tc bp hr rr s02 ra gen lying in bed comfortable apparing cardiac muffled s1 and s2 rrr systolic murmur at the apex as well as llsb cardiac friction rub present lungs crackles at the bases but otherwise clear abdomen mod firm and distended two incision sites in rlq and llq show staples in place without drainage minimal tenderness around rlq incision ue significant erythema and swelling in lue le dp radial pulses trace swelling in bilat le pertinent results admission results cbc wbc rbc hgb hct mcv mch mchc rdw plt ct neuts lymphs monos eos baso coags pt ptt inr pt chem glucose urean creat na k cl hco3 angap lfts alt ast ck cpk alkphos totbili lytes calcium phos mg abx vanco lactate cardiac markers 58pm blood ctropnt 42am blood ck mb mb indx ctropnt 37am blood ck mb ctropnt 00pm blood ck mb ctropnt 55am blood ck mb ctropnt 01pm blood ck mb ctropnt 51pm blood ck mb ctropnt 12am blood ck mb ctropnt 27am blood ck mb ctropnt 36am blood ck mb ctropnt 40am blood ck mb ctropnt 59am blood ck mb ctropnt relevant results 55am blood esr 55am blood crp 15pm blood aca igg aca igm 30am blood aca igg aca igm 30am blood lupus pos 58pm blood lipase 55am blood lipase 20am blood lipase 30am blood hapto 55am blood hba1c eag 55am blood triglyc hdl chol hd ldlcalc 27am blood hbsag negative hbsab positive hav ab positive 27am blood hcv ab negative micro pm blood culture final report blood culture routine final staph aureus coag consultations with id are recommended for all blood cultures positive for staphylococcus aureus and species final sensitivities staphylococcus species may develop resistance during prolonged therapy with quinolones therefore isolates that are initially susceptible may become resistant within three to four days after initiation of therapy testing of repeat isolates may be warranted sensitivities mic expressed in mcg ml staph aureus coag clindamycin s erythromycin s gentamicin s levofloxacin s oxacillin s trimethoprim sulfa s aerobic bottle gram stain final reported by phone to at 35pm on gram positive cocci in clusters anaerobic bottle gram stain final gram positive cocci in clusters pm catheter tip iv aerobic anaerobic final report wound culture final staph aureus coag colonies staphylococcus species may develop resistance during prolonged therapy with quinolones therefore isolates that are initially susceptible may become resistant within three to four days after initiation of therapy testing of repeat isolates may be warranted sensitivities mic expressed in mcg ml staph aureus coag clindamycin s erythromycin s gentamicin s levofloxacin s oxacillin s trimethoprim sulfa s cardiology tte the left atrium is elongated the right atrium is moderately dilated no atrial septal defect is seen by 2d or color doppler left ventricular wall thicknesses are normal the left ventricular cavity is moderately dilated lv systolic function appears depressed ejection fraction percent secondary to severe hypokinesis of the inferior septum inferior free wall and posterior wall there is no ventricular septal defect right ventricular chamber size is normal with depressed free wall contractility the aortic valve leaflets appear structurally normal with good leaflet excursion and no aortic stenosis no masses or vegetations are seen on the aortic valve but cannot be fully excluded due to suboptimal image quality mild aortic regurgitation is seen the mitral valve appears structurally normal with trivial mitral regurgitation there is no mitral valve prolapse no masses or vegetations are seen on the mitral valve but cannot be fully excluded due to suboptimal image quality no masses or vegetations are seen on the tricuspid valve but cannot be fully excluded due to suboptimal image quality no masses or vegetations are seen on the pulmonic valve but cannot be fully excluded due to suboptimal image quality there is no pericardial effusion impression no obvious vegetation but suboptimal study tee no atrial septal defect is seen by 2d or color doppler left ventricular wall thickness cavity size and global systolic function are normal lvef right ventricular chamber size and free wall motion are normal the aortic valve leaflets appear structurally normal with good leaflet excursion no masses or vegetations are seen on the aortic valve no aortic regurgitation is seen the mitral valve leaflets are structurally normal no mass or vegetation is seen on the mitral valve mild mitral regurgitation is seen no vegetations or abscess normal biventricular systolic function mild mitral regurgitation radiology u s r hd graft patent right upper extremity av graft with no stenosis no evidence of abscess u s rue and r ij nonocclusive thrombus seen in the mid right internal jugular vein no evidence of perigraft abscess of hd graft u s bilateral hips no hip joint effusion on the left or right side slight asymmetry of psoas muscle on the right suspicious for a psoas paraspinal process mri bilateral thighs bilateral heterogeneous fluid collections in the iliacus muscles most consistent with abscesses right greater than left fluid fluid levels with areas of t1 hyperintensity suggest the presence of internal hemorrhage and or proteinaceous debris collection on the right extends into the iliopsoas bursa with associated myositis and small area of focal fluid near the rectus femoris origin no evidence of hip effusions ct of pelvis large right and small left iliac muscle abscess with percutaneous drain in place on the right right iliac abscess extends inferiorly distal to the inguinal ligament but does not reach the iliopsoas insertion site at the lesser trochanter left iliac muscle abscess ends about cm distal to the inguinal ligament ct of pelvis right iliopsoas pigtail catheter removal and subsequent washout now with packing surgicell gauze in place and a skin staple closure over it this was confirmed with the description in the operative note as well as with at on right subcutaneous fat fluid collection with air fluid level and hematocrit suggestive of hematoma extensive subcutaneous gas likely postoperative although gas producing infection cannot be ruled out pelvic arteriogram pelvic arteriograms without signs of active bleeding no embolization was performed l groin u s there is a x x cm collection with a fluid fluid level within the left groin suggestive of a hematoma there is no internal vascularity there is no connection with the underlying vessels the underlying left common femoral artery and vein demonstrate normal waveforms and are patent abd u s multiple superficial hypoechoic fluid collections in the right lower quadrant adjacent to the incision one of which measures cm with complex features located above the right inguinal fold raising question of abscess this site has been marked for possible aspiration although not definitely amenable to drainage given internal echoes abd ct two fluid collections in the right anterior abdominal wall one may be residual hematoma the other may be fluid infection is not excluded multiple locules of air within the right iliacus muscle some of which may be post operative the remaining may be related to surgical packing with surgicel a small amount of air may be intraperitoneal persistent large amount of air in the anterior abdominal wall fascititis is not excluded heterogeneous attenuation of the left iliacus muscle may reflect residual hematoma at the site but no locules of air within the left iliacus small amount of free fluid within the pelvis mrv chest without contrast no findings of svc thrombosis no contrast was administered due to diminished gfr reidentification of nonocclusive chronic appearing thrombosis in the mid right jugular vein better appreciated on the previously performed ultrasound moderate left pleural effusion and pericardial effusion abdominal ultrasound a cm fluid collection in the subcutaneous fat of the right lower quadrant tte the left atrium is normal in size the estimated right atrial pressure is 15mmhg left ventricular wall thicknesses and cavity size are normal there is moderate regional left ventricular systolic dysfunction with basal to mid akinesis of the inferior wall there is mild hypokinesis of the remaining segments lvef the estimated cardiac index is normal 5l min m2 right ventricular chamber size is normal with mild global free wall hypokinesis the diameters of aorta at the sinus ascending and arch levels are normal the aortic valve leaflets appear structurally normal with good leaflet excursion and no aortic regurgitation the mitral valve leaflets are structurally normal mild mitral regurgitation is seen the pulmonary artery systolic pressure could not be determined there is a moderate sized pericardial effusion no right ventricular diastolic collapse is seen there is brief right atrial diastolic collapse there is significant accentuated respiratory variation in mitral tricuspid valve inflows consistent with impaired ventricular filling compared with the prior study images reviewed of there is a moderate sized pericardial effusion without frank tamponade ekg sinus tachycardia left bundle branch block since the previous tracing of there is probably no significant change tte the left atrium is mildly dilated the estimated right atrial pressure is 20mmhg left ventricular wall thicknesses are normal the left ventricular cavity size is normal there is moderate to severe global left ventricular hypokinesis lvef right ventricular chamber size is normal with depressed free wall contractility 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 the estimated pulmonary artery systolic pressure is normal there is a moderate sized pericardial effusion there are no echocardiographic signs of tamponade no right ventricular diastolic collapse is seen there is brief right atrial diastolic invagination compared with the findings of the prior study images reviewed of the pericardial effusion is slightly smaller tte the estimated right atrial pressure is 10mmhg there is mild regional left ventricular systolic dysfunction with basal to mid inferoseptal inferior and inferolateral hypokinesis overall left ventricular systolic function is mildly depressed lvef right ventricular chamber size is normal with borderline normal free wall function there is a moderate sized pericardial effusion no right ventricular diastolic collapse is seen there is brief right atrial diastolic collapse there is significant accentuated respiratory variation in mitral tricuspid valve inflows consistent with impaired ventricular filling compared with the prior study images reviewed of the pericardial effusion size is similar without tamponade the left ventricular systolic function may be slightly improved upper extremity us with doppler short segment of nonocclusive thrombus along the left basilic picc in the upper arm discharge labs 24am blood wbc rbc hgb hct mcv mch mchc rdw plt ct 24am blood pt ptt inr pt 24am blood glucose urean creat na k cl hco3 angap 24am blood calcium phos mg brief hospital course year old with a complicated medical history including prior hodgkins htn pud hypothyroidism depression hx of lupus anticoagulant requring warfarin use and esrd of unclear etiology on transferred from osh to ed on two days prior to presentation the patient had a right ij tunneled hd line placed placed by dr transplant surgery one day prior to presentation went to hd with fevers had rigors morning of presentation on and went to mssa line sepsis patient was initially admitted directly to the micu for concern of line sepsis in the setting of fevers and rigors transplant surgery was notified and removed newly placed subclavian line osh blood cultures grew staph aureus and patient was started on vancomycin while sensitivities were pending blood cultures at were taken prior to antibiotic administration these cultures also grew gram positive cocci patient continued to spike intermittent fevers surveillance cultures were taken daily while in the micu a tte was completed and did not indicate any valvular abnormalities however it did show focal areas of hypokinesis and a depressed ef as noted below tee was arranged with cardiology and showed no vegetations on day of transfer to floor patient was also started on nafcillin as cultures came back mssa plan was complete a week course of antibiotics for mssa bacteremia with nafcillin being used while in hospital and then transition to cefazolin with hemodialysis once patient was discharged as noted below abx were changed for days to emperic vanco cefepime due to concerns for thigh and abdominal abscess but patient was transitioned back to nafcillin ciprofloxacin and flagyl once the culture data from these thigh abdomen collections was negative the patient was transitioned from nafcillin to cefazolin prior to discharge cefazolin ciprofloxacin and flagyl were to be continued until cefazolin to be given with hd grams on monday and wednesday and g on friday was contact directly regarding the cefazolin as it was left out of his discharge medication list pericardial effusion patient had mrv of chest to evaluate for clot burden which revealed an incidental pericardial effusion pulsus physiology was difficult to detect as patient had av graft in right extremity and a picc line in his left extremity a tte was subsequently perfromed to characterize the effusion more carefully and revealed a cm pericardial effusion without evidence of tamponade though brief right atrial collapse was noted a repeat tte hours later revealed a slightly smaller effusion with only right atrial involution appreciated a third tte was performed on the day of discharge approximately houurs later which again showed a slightly smaller pericardial effusion with noted brief right atrial diastolic collapse a copy of the most recent tte report was sent with the patient at to communicate with him regarding follow up the patient is to have repeat ttes on and a follow up cardiology appointment was made for the patient on troponin leak on admission patient had ekg changes concerning for cardiac ischemia initial troponins were elevated although ck mb was within normal limits cardiology was notified in the ed and said that the troponin level was consistent with esrd and demand ischemia as patient was tachycardic for a prolonged period however tte demonstrated inferior wall hypokinesis with ef of which made it appear that the patient had a cardiac event prior to admission and still had elevated troponins from this event because of no renal clearance pt was started on full strength asa high dose atorvastatin beta blocker and kept on heparin drip which had already been started for below coagulation issues cardiology initially planned to perform cardiac catheterization during his hospitalization but tee done to evaluate for endocarditis a few days after initially tte no longer showed evidence of hypokinetic wall segments and showed and ef bringing back to the forefront the idea that perhaps the patient had not had a cardiac event and had merely spilled troponins in the setting of some coronary disease exacerbated by tachycardia septic physiology and esrd decision was made for no coronary intervention and atorvastatin dose was decreased in setting of elevated lfts troponins continued to slowly trend down although never really resolved during the hospitalization likely secondary to his esrd late in this hospital course the troponins were no longer followed heparin was stopped as patient developed hematomas as per below and it was felt that the risk to bleeding was more significant that risk of clotting ttes were performed per above the last tte on day of discharge revealed an ef of cardiology follow up per above esrd renal was notified upon admission and patient received a line holiday while in the micu receiving abx electrolytes were monitored plan was for patient to restart normal mwf schedule using mature graft of r upper extremity however ptt was on morning of planned graft access and infectious disease was also concerned about the possibility that graft infected in the setting of bacteremia as a result a temporary l subclavian tunneled hd catheter was placed by ir and used for two hd sessions while ptt was brought under better control and u s of r vascular graft was done to r o infection u s showed no evidence of perigraft abscess of fluid collection so graft was used for hd starting on temporary hd line was removed after successful use of the graft pt was continued on mwf hd schedule for throughout his hospitalization antibiotics to be given at hd after discharge as per above coagulopathy at time of admission pt was on therapeutic warfarin with presenting inr of per patient report he was on this medication because of anti phospholipid hypercoag state that had been discovered at hospital as part of a work up to determine why he kept clotting off hd access grafts fistulas pt warfarin was held at presentation to because of need for multiple procedures and pt was placed on heparin gtt this was continued through much of hospitalization but pt still developed multiple thrombotic complications in the icu difficulty threading a l ij line led team to believe there must be a clot in the l ij additionally a non occlusive thrombus in r ij at site of recent central line was found on u s pt later developed significant r hip thigh pain with some swelling ultra sound of the area showed and asymmetry that was suspicious for a psoas paraspinal process as a result f u mri of the r hip thigh was performed and showed bilateral heterogeneous fluid collections in the iliacus muscles most consistent with abscesses right greater than left fluid fluid levels with areas of t1 hyperintensity suggest the presence of internal hemorrhage and or proteinaceous debris collection on the right extends into the iliopsoas bursa with associated myositis and small area of focal fluid near the rectus femoris origin because patient was febrile with significant pain in the area ct guided ir drainage of r thigh abscesses were performed on with drain placed in the r side a follow up ct on showed persistence of fluid and in light of continuing fevers and concern for permanent neurologic damage to nerve structures in the area orthopedic surgery took pt to the or to debride the abscesses during surgery these were found to be hematomas r l from the or pt was transferred to the tsicu due to hypotension sbp down to the s and complications from bleeding which continued to ooze during surgery preventing initial closure of the wound in the tsicu mr was placed on peripheral pressors initially due to access issues and was also transfused blood products due to hct drop and hypotension also he had an elevated white count and fevers left femoral line was placed on additionally was switched from nafcillin to vancomycin cefepime on with suggestion of a day course switch made at id s suggestion due to concern of possible infected hematomas at sites of abscesses these abx continued until slightly longer than initially planned because concern for a wound infection had developed in the interim as noted below pressors d c d morning of and the pt s vs remained stable and afebrile had pelvic arteriograms performed to assess for possible bleeds which were negative went back to the or on to have packing removed from washout on cultures ultimately negative from this source and hematomas seemed to have spontaneously formed while on heparin gtt pt was transfered back to the floor but shortly thereafter developed pain in l groin and significant rlq pain with surrounding skin erythema induration and dusky changes ultra sound of l groin showed a small hematoma which had formed at site of femoral line removal the day before there was no vessel aneurysm and the hematoma was not connected to other vascular structures so since small no intervention was undertaken ultra sound of abdomen showed multiple superficial hypoechoic fluid collections in the rightnlower quadrant adjacent to the recent surgical incision one of which measured cm withcomplex features located above the right inguinal fold raising question of abscess a ct of abdomen with contrast showed two fluid collections in r ant abdominal wall one likely hematoma with the other containing fluid that could not have infection excluded because pt has having recurrence of fever spikes there was concern for post surgical abscess orthopedics took pt back to the or on for i d of the wound and found it to be a hematoma not abscess cultures were sent but like previous hematoma cultures remained negatived the heparin gtt was eventually disconinued as the risk of bleeding was considered greater than the risk of clotting hematology was consulted as an inpatient but had low suspicion for a hypercoaguable state the patient was discharged with the contact information to make a follow up appointment so that his possible anti phospholipid syndrome could be evaluated more appropriately as an outpatient pain control pt with significant pain control issues during hospitalization mostly related to pain at sites of various hematoma formations initially pain was controlled with iv morphine but this was ultimately changed to dilaudid because of pt s poor renal function dilaudid pca was initiated when difficulty controlling pain with iv pushes pt then started on long acting oxycontin which was uptitrated in effort to provide more consistent pain control dilaudid pca weaned as long acting pos uptitrated and pt ultimately transitioned over to po dilaudid for breakthrough pain as better control was achieved the patient was eventually transitioned to oxycontin for pain control the patient reported significantly improved pain late in his hospital course left upper extremity thrombosis the day prior to discharge the patient had left upper extremity swelling and mild surround erythema an us was ordered for evaluation of a thrombosis and revealed a short segment of nonocclusive thrombus along the left basilic picc in the upper arm per report good flow was noted around the picc line the picc line was pulled as it was considered the most likely source of the thrombosis no anticoagulation was persued due to above issues and due to its non occlusive nature and thought that it would resolve after the picc line was removed medications on admission albuterol allopurinol mg daily nephrocaps caps daily calcium acetate mg daily citalopram mg daily vicodin levothyroxine mcg daily morphine mg daily pantoprazole mg daily trazodone mg qhs venlafaxine mg daily coumadin alternating colace senna discharge disposition extended care facility discharge diagnosis primary diagnosis mssa methicillin sensitive staphylococcus aureus bacteremia bilateral psoas and right lower quadrant hematomas pericardial effusion myocardial ischemia secondary diagnoses end stage renal disease possible lupus anticoagulant anti phospholipid antibody syndrome discharge condition mental status clear and coherent level of consciousness alert and interactive activity status ambulatory independent discharge instructions mr you were admitted to with a bloodstream infection that was most likely from your tunneled hd line blood cultures revealed a bacteria called staphylococcus aureus that was sensitive to the antibiotic nafcillin you were treated with nafcillin throughout most of your stay but were transitioned to cefazolin prior to discharge you will need to continue cefazolin as instructed below on admission to the hospital you were also on coumadin for a possible diagnosis of anti phospholipid antibody syndrome as you subsequently developed several hematomas during your hospitalization this medication was discontinued and the hematology service was consulted the diagnosis of anti phospholipid antibody syndrome is difficult to make as an inpatient you will need to follow up with the hematology department as an outpatient and the information has been provided below the following changes were made to your medications start cefazolin grams with hemodialysis on mondays and wednesdays and grams with hemodialysis on fridays you will need this antibiotic for a total of two weeks from stop this medication on stop taking vancomycin which you were admitted on from the outside hospital your senna was increased from tablet by mouth twice a day for constipation to tablets twice a day for constipation stop taking the cefazolin that you were admitted on and continue as directed above stop taking morphine sulfate mg intravenously every four hours for pain start taking oxycontin mg by mouth every hours start taking docusate sodium mg by mouth twice a day for constipation start taking atorvastatin mg by mouth once a day for hyperlipidemia start taking ciprofloxacin mg by mouth once a day for days start this medication on and stop on start taking metronidazole mg by mouth every eight hours for days you will need one dose the evening of otherwise you will need to take this medication three times a day from to start taking trazodone mg by mouth at night as needed for insomnia start taking nephrocaps b complex vitamin c folic acid tab by mouth daily start taking calcium acetate mg take two capsules three times a day with meals start taking sevelamer carbonate mg take one tablet by mouth three times a day with meals start taking nitroglycerin mg tablets take one tablet every five minutes as needed for chest pain do not exceed tablets in a minute period given the severity of your renal failure you will also need to receive epoetin alfa with dialysis this medication will not appear on your medication list in the following documents as it was dosed and administered according to protocols no other changes were made to your other medications while in the hospital and you should continue taking all other medications as previously prescribed followup instructions please keep all follow up appointments as below please call the hematology oncology department at to establish a follow up appointment in the hemostasis and clinic for further evaluation of the possible anti phospholipid antibody syndrome please call the orthopedics department at to make a follow up appointment the appointment should be for approximately one month from the date of discharge and should be made with the the nurse practitioner please keep the infectious disease appointment as below department infectious disease when monday at am with md building lm bldg campus west best parking garage below are instructions for the labs that will need to be sent to the infectious disease department prior to your appintment on outpatient antibiotic regimen and projected duration and dose cefazolin 2g with dialysis on mo we 3g with dialysis on friday start date stop date required laboratory monitoring lab tests cbc bun crea lfts esr and crp frequency qweekly all laboratory results should be faxed to infectious disease r ns at patient will need weekly monitoring of his pericardial effusion with a transthoracic echocardiogram please communicate this information to the md 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)