Spaces:
Runtime error
Runtime error
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) | |