Spaces:
Runtime error
Runtime error
File size: 13,388 Bytes
7663870 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 |
import os
import openai
import langchain
langchain.debug = False
os.environ["TOKENIZERS_PARALLELISM"] = "false"
os.environ["OPENAI_API_KEY"]
def save_docs(docs):
import shutil
import os
output_dir = "/home/user/app/docs/"
if os.path.exists(output_dir):
shutil.rmtree(output_dir)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for doc in docs:
shutil.copy(doc.name, output_dir)
return "Successful!"
global mdm_value
def process_docs():
from langchain.chat_models import ChatOpenAI
from langchain.chains import ConversationChain
import os
from docx import Document
global mdm_value
llm = ChatOpenAI(model_name="gpt-3.5-turbo-16k")
agent = ConversationChain(llm=llm, verbose=True)
folder_path = "/home/user/app/docs/"
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith(".docx") or file.endswith(".docx"):
word_file_path = os.path.join(root, file)
doc = Document(word_file_path)
text = []
for paragraph in doc.paragraphs:
text.append(paragraph.text)
doc_content = "\n".join(text)
one_word_propmt = """Classify into "MINIMAL", "LOW", "MODERATE", "HIGH". You should ALWAYS give only ONE option and NOTHING ELSE.
ONLY return ONE option. AWAYS answer in ONLY one word. DO NOT give full sentences.
ALWAYS give the answer in ALL UPPER CASE. DO NOT EVER give answer in any other case."""
#####################################################
instruction1 = """You are an expert at calculating the Risk of Complications and/or Morbidity or Mortality of the Patient Management Decisions Made at Visit (choose highest) You are provided with a detailed medical report. Classify it into "MINIMAL", "LOW", "MODERATE", and "HIGH" on the basis of the Given rules.
MINIMAL
Minimal risk of morbidity from additional diagnostic testing or treatment
Examples only
• Rest
• Gargles
• Elastic bandages
Superficial dressings
LOW
Low risk of morbidity from additional diagnostic testing or treatment
Examples only
OTC drugs
• Minor surgery w/no identified risk factors
• Physical/Occtherapy
MODERATE
MODERATE risk of morbidity from additional diagnostic testing or treatment
Examples only
Prescription drug management
Decision regarding minor surgery with identified patient or procedure risk factors
Decision regarding elective major surgery without identified patient or procedure risk factors
Diagnosis or treatment significantly limited by social determinants of health
HIGH
HIGH risk of morbidity from additional diagnostic testing or treatment
Examples only
Parenteral controlled substances (DEA controlled substance given by route other than digestive tract)
Drug therapy requiring intensive monitoring for toxicity
Decision regarding elective major surgery with identified patient or procedure risk factors
Decision regarding emergency major surgery
Decision regarding hospitalization or escalation of hospital level care (i.e. transfer to ICU)
Decision not to resuscitate or to deescalate care because of poor prognosis
Here is the Report """
instruction1 += "\n\n"
instruction1 += doc_content
instruction1 += "\n\n"
instruction1 += "Study it and just provide your answer"
response1 = agent.predict(input=instruction1)
instruction2 = one_word_propmt
instruction2 += "\n\n"
instruction2 += response1
response2 = agent.predict(input=instruction2) # main
#####################################################
instruction3 = """Calculate Amount and/or Complexity of Data to be Reviewed & Analyzed (choose highest criteria met). You are provided with a detailed medical report. Classify it into "MINIMAL", "LOW", "MODERATE", and "HIGH" on the basis of the Given rules.
CATEGORY 1
1. Review of prior external note(s) from each unique source (each unique source counted once, regardless of # of notes reviewed)
2. Review of the result(s) of each unique test
3. Ordering of each unique test (includes review of result, do not count in #2)
4. Assessment requiring an Independent historian
CATEGORY 2
Independent interpretation of tests performed by another physician/other qualified healthcare professional (not separately reported)
Do not count independent interpretation for a test billed or ordered by a colleague in the same specialty
CATEGORY 3
Discussion of management or test interpretation- with external physician/other qualified health care professional/ appropriate source (not separately reported)
Requires direct interactive exchange (not via intermediaries or notes)
MINIMAL
If Minimal or No Data Reviewed
LOW
if it meets any combination of 2 from items 1-3 Or Meet item 4 (independent historian)
1. Review of prior external note(s) from each unique source (each unique source counted once, regardless of # of notes reviewed)
2. Review of the result(s) of each unique test
3. Ordering of each unique test (includes review of result, do not count in #2)
4. Assessment requiring an Independent historian
MODERATE
Meet 1 of 3 categories below
Category 1: Meet any combination of 3 from items 1-4
Category 2: Independent interpretation of test
Category 3: Discussion management, or test interpretation (external)
HIGH
Meet 2 of 3 categories below
Category 1: Meet any combination of 3 from items 1-4
Category 2: Independent interpretation of test
Category 3: Discussion management, or test interpretation (external)
Here is the Report """
instruction3 += "\n\n"
instruction3 += doc_content
instruction3 += "\n\n"
instruction3 += "Study it and just provide your answer"
response3 = agent.predict(input=instruction3)
instruction4 = one_word_propmt
instruction4 += "\n\n"
instruction4 += response3
response4 = agent.predict(input=instruction4) # main
#####################################################
instruction5 = """You are an expert at calculating the complexity of medical problems based on Medical reports. You are provided with a detailed medical report. Classify it into "MINIMAL", "LOW", "MODERATE", and "HIGH" on the basis of the Given rules.
MINIMAL
1 self- limited or minor problem
(runs a definite or prescribed course, is transient in nature, and is not likely to permanently alter health status)
LOW
2 or more self-limited or minor problems; or
1 stable chronic illness (chronic illness which is at treatment goal for the specific patient); or
1 acute, uncomplicated illness or injury (full recovery w/out functional impairment is expected); or
Stable, acute illness (treatment newly or recently initiated, resolution may not be complete, but condition stable); or
Acute, uncomplicated illness or injury requiring hospital inpatient or observation level care (little to no risk of mortality with treatment, but treatment required is delivered in inpt or obs setting)
MODERATE
1 or more chronic illnesses with ex- acerbation, progression, or side effects of treatment (requires supportive care or attention to treatment for side effects); or
2 or more stable chronic illnesses; or
1 undiagnosed new problem with uncertain prognosis (likely to result in high risk of morbidity w/out tx); or
1 acute illness with systemic symptoms (illness that causes systemic symptoms and has high risk of morbidity without treatment); or
1 acute complicated injury (eval of body systems not part of injured organ, extensive injury, or multiple tx options are multiple and/ or associated with risk of morbidity
HIGH
• 1 or more chronic illness- es with severe exacerbation, progression, or side effects of treatment (significant risk of morbidity: may require escalation in level of care); or
1 acute or chronic illness or injury that poses a threat to life or bodily
function (in the near term without treatment e.g. AMI, pulmonary embolus, severe respiratory distress psychiatric illness with potential threat to self or others, peritonitis, acute renal failure)
Here is the Report """
instruction5 += "\n\n"
instruction5 += doc_content
instruction5 += "\n\n"
instruction5 += "Study it and just provide your answer"
response5 = agent.predict(input=instruction5)
instruction6 = one_word_propmt
instruction6 += "\n\n"
instruction6 += response5
response6 = agent.predict(input=instruction6) # main
######################################################
inputs = [response2, response4, response6]
sorted_inputs = sorted(
inputs, key=lambda x: ["MINIMAL", "LOW", "MODERATE", "HIGH"].index(x)
)
mdm_value = sorted_inputs[1]
print(mdm_value)
return (
"Successful!",
response1,
response2,
response3,
response4,
response5,
response6,
)
def get_code1(input):
global mdm_value
mdm_value = mdm_value
if input == "NEW" and mdm_value == "MINIMAL":
hcpcs_code = "99202"
elif input == "NEW" and mdm_value == "LOW":
hcpcs_code = "99203"
elif input == "NEW" and mdm_value == "MODERATE":
hcpcs_code = "99204"
elif input == "NEW" and mdm_value == "HIGH":
hcpcs_code = "99205"
elif input == "ESTABLISHED" and mdm_value == "MINIMAL":
hcpcs_code = "99212"
elif input == "ESTABLISHED" and mdm_value == "LOW":
hcpcs_code = "99213"
elif input == "ESTABLISHED" and mdm_value == "MODERATE":
hcpcs_code = "99214"
elif input == "ESTABLISHED" and mdm_value == "HIGH":
hcpcs_code = "99215"
return hcpcs_code
def get_code2(input):
if input == "20 min":
hcpcs_code = "99242"
elif input == "30 min":
hcpcs_code = "99243"
elif input == "40 min":
hcpcs_code = "99244"
elif input == "55 min":
hcpcs_code = "99245"
return hcpcs_code
import gradio as gr
css = """
.col{
max-width: 70%;
margin: 0 auto;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
"""
with gr.Blocks(css=css) as demo:
gr.Markdown("## <center>Medical assistant bot</center>")
with gr.Tab("Get help with medical documents"):
with gr.Column(elem_classes="col"):
with gr.Tab("Upload and Process Document"):
with gr.Row():
with gr.Column():
docs_upload_input = gr.Files(label="Upload File")
docs_upload_button = gr.Button("Upload")
docs_upload_output = gr.Textbox(label="Output")
docs_process_button = gr.Button("Process")
docs_process_output = gr.Textbox(label="Output")
gr.ClearButton(
[docs_upload_input, docs_upload_output, docs_process_output]
)
with gr.Column():
ai_output1 = gr.Textbox(label="Output 1")
ai_output2 = gr.Textbox(label="Output 2")
ai_output3 = gr.Textbox(label="Output 3")
ai_output4 = gr.Textbox(label="Output 4")
ai_output5 = gr.Textbox(label="Output 5")
ai_output6 = gr.Textbox(label="Output 6")
gr.ClearButton(
[
ai_output1,
ai_output2,
ai_output3,
ai_output4,
ai_output5,
ai_output6,
]
)
with gr.Tab("Get HCPCS Code (Primary Care Exception)"):
with gr.Column():
code_type_input1 = gr.Dropdown(choices=["NEW", "ESTABLISHED"])
code_type_button1 = gr.Button("Submit")
code_type_output1 = gr.Textbox(label="Output")
gr.ClearButton([code_type_input1, code_type_output1])
with gr.Tab("Get HCPCS Code (CONSULTATION)"):
with gr.Column():
code_type_input2 = gr.Dropdown(
choices=["20 min", "30 min", "40 min", "55 min"]
)
code_type_button2 = gr.Button("Submit")
code_type_output2 = gr.Textbox(label="Output")
gr.ClearButton([code_type_input2, code_type_output2])
#########################################################################################################
docs_upload_button.click(
save_docs, inputs=docs_upload_input, outputs=docs_upload_output
)
docs_process_button.click(
process_docs,
inputs=None,
outputs=[
docs_process_output,
ai_output1,
ai_output2,
ai_output3,
ai_output4,
ai_output5,
ai_output6,
],
)
code_type_button1.click(
get_code1, inputs=code_type_input1, outputs=code_type_output1
)
code_type_button2.click(
get_code2, inputs=code_type_input2, outputs=code_type_output2
)
#########################################################################################################
demo.queue()
demo.launch(debug=True, share=True)
|