MedicalBot / app.py
ankur2402's picture
Update app.py
d3507e9 verified
import streamlit as st
from langchain.llms import OpenAI, Cohere
import os
from langchain.llms import OpenAI
from langchain.embeddings import OpenAIEmbeddings,CohereEmbeddings
from langchain.document_loaders import PyPDFLoader
from langchain.vectorstores import Chroma
from langchain.agents.agent_toolkits import (
create_vectorstore_agent,
VectorStoreToolkit,
VectorStoreInfo
)
from langchain.indexes import VectorstoreIndexCreator
import re
from langchain.agents import Tool
from langchain.tools import DuckDuckGoSearchRun
# from langchain.utilities import WikipediaAPIWrapper
from langchain.chains import RetrievalQA
from langchain.chat_models import ChatOpenAI
from langchain.agents import Tool
from langchain.agents import initialize_agent
from langchain.agents import AgentType
from langchain.memory import ConversationBufferMemory
from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from typing import Dict, Union, Any, List
from langchain.callbacks.base import BaseCallbackHandler
from langchain.schema import AgentAction
from langchain.agents import AgentType, initialize_agent, load_tools
# from langchain.callbacks import tracing_enabled
from langchain.llms import OpenAI
from langchain.chat_models import ChatOpenAI
from langchain import PromptTemplate
from fpdf import FPDF
st.title('MedTechAI')
persist_directory = ""
model = ""
with st.sidebar:
with st.form('Cohere/OpenAI'):
mod = st.radio('Choose OpenAI/Cohere', ('OpenAI', 'Cohere'))
api_key = st.text_input('Enter API key', type="password")
# model = st.radio('Choose Company', ('ArtisanAppetite foods', 'BMW','Titan Watches'))
submitted = st.form_submit_button("Submit")
# Check if API key is provided and set up the language model accordingly
if api_key:
if(mod=='OpenAI'):
os.environ["OPENAI_API_KEY"] = api_key
llm = OpenAI(temperature=0.1, verbose=True)
embeddings = OpenAIEmbeddings()
if(mod=='Cohere'):
os.environ["Cohere_API_KEY"] = api_key
llm = Cohere(cohere_api_key=api_key)
embeddings = CohereEmbeddings(cohere_api_key=api_key)
def report(Symptoms,history,age,gen,response):
prompt_updates=f"""
Patient's Symptoms: {Symptoms}
Medical History: {history}
Age: {age}
Gender: {gen}
Lab report: {response}
You are a medical lab report analyst.
Based on the information provided above, i.e., Patients Symptoms, Medical History, Age and gender, Write a detailed medical report of the patient.
The Lab report has the Normal levels of the test and the Patients levels of the test in the report. Compare them and give insights in the 'Laboratory Investigation section'.
You can get more insights from the 'knowledge Base' tool about the patients medical lab reports.
Refer the below example to generate the report. You MUST follow this format::
example:
```
Patient Information:
- Age: 45
- Gender: Male
Clinical History:
He reported a history of smoking for 20 years but quit 2 years ago. No known allergies or significant medical history were reported.
Laboratory Investigations:
- Complete Blood Count (CBC): Within normal limits.
- Chest X-ray: Right lower lobe consolidation suggestive of pneumonia.
Assessment:
Cholelithiasis (Gallstones).
Choledocholithiasis (Common bile duct stones).
Elevated liver enzymes, possibly indicative of liver involvement.
Recommendations:
The patient is advised to start a course of oral antibiotics (e.g., amoxicillin) for the treatment of pneumonia. Symptomatic relief can be achieved with over-the-counter cough suppressants and acetaminophen for chest discomfort. Follow-up chest X-ray is recommended in 2-3 weeks to monitor resolution of pneumonia.
Given the history of smoking and the mildly reduced lung function, the patient is encouraged to avoid smoke exposure, continue with regular exercise, and consider pulmonary rehabilitation to improve lung function.
Follow-Up:
The patient is scheduled for a follow-up appointment in two weeks to assess the progress of pneumonia treatment and to evaluate lung function.
This report is provided for fictional purposes only and is not a substitute for professional medical advice. Any resemblance to real individuals or situations is purely coincidental.
```
"""
print("report")
model_name = "gpt-3.5-turbo-16k"
temperature = 0.0
llm = OpenAI(model_name=model_name, temperature=temperature)
out = llm(prompt_updates)
return out
def generate_pdf(text):
# Save FPDF() class into a variable pdf
pdf = FPDF()
# Add a page
pdf.add_page()
# Set style and size of font that you want in the PDF
pdf.set_font("Arial", size=12)
# Set left margin and right margin
pdf.set_left_margin(20)
pdf.set_right_margin(20)
# Add multi-cell with line break
pdf.multi_cell(0, 10, text)
# Move to the next line after the text
pdf.ln()
# Save the PDF with the given file name
pdf.output("output.pdf")
uploaded_file = st.file_uploader("Upload Your Reports", type=["pdf"])
Symptoms = st.text_area('Enter Symptoms')
history = st.text_area('Enter Medical History')
age = st.text_area('Enter Age')
gen = st.text_area('Enter Gender')
if st.button("Submit"):
if uploaded_file is not None:
file_contents = uploaded_file.read()
save_path = uploaded_file.name
with open(save_path, "wb") as f:
f.write(file_contents)
loader = PyPDFLoader(save_path)
# Split pages from pdf
pages = loader.load_and_split()
store = Chroma.from_documents(pages, embeddings)
qa = RetrievalQA.from_chain_type(
llm=llm,
chain_type="stuff",
retriever=store.as_retriever()
)
tools = [
Tool(
name='Knowledge Base',
func=qa.run,
description=(
'use this tool when answering any queries to get '
'more information about the topic'
)
),
]
agent_chain = initialize_agent(
tools = tools,
llm = llm,
# agent_instructions=agent_instructions,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
verbose=True,
# max_iterations=5,
handle_parsing_errors="Check your output and make sure it conforms!", #to fix the ouputParser error
# return_intermediate_steps=True
)
prm = """
The 'knowledge Base' tool contains the Lab report
Please analyze the uploaded lab report and provide the results for the following tests:
1. Complete Blood Count (CBC):
- Hemoglobin level
- Red blood cell count
- White blood cell count
- Platelet count
2. Basic Metabolic Panel (BMP) or Comprehensive Metabolic Panel (CMP):
- Glucose levels
- Creatinine level
- Blood urea nitrogen (BUN) level
- Sodium level
- Potassium level
- Chloride level
3. Lipid Panel:
- LDL cholesterol level
- HDL cholesterol level
- Total cholesterol level
- Triglyceride level
4. Thyroid Function Tests:
- TSH (Thyroid-stimulating hormone) level
- T3 level
- T4 level
5. Liver Function Tests:
- AST (Aspartate aminotransferase) level
- ALT (Alanine aminotransferase) level
- Bilirubin level
6. Blood Clotting and Coagulation Tests:
- INR (International Normalized Ratio)
- PT (Prothrombin Time)
- aPTT (Activated Partial Thromboplastin Time)
7. Blood Protein Levels:
- Serum albumin level
- Globulin levels
- Albumin-to-globulin (A/G) ratio
8. Vitamin and Mineral Levels:
- Vitamin D level
- Vitamin B12 level
- Iron level
9. Inflammatory Markers:
- C-reactive protein (CRP) level
- Erythrocyte Sedimentation Rate (ESR)
10. Hormone Levels:
- Testosterone level (if applicable)
- Estrogen level (if applicable)
- Cortisol level (if applicable)
- Insulin level (if applicable)
Look up at Normal level ranges for each of the tests and also the patients levels mentioned in results of the report.
what are the levels of patients of all the parameters and the normal level ranges given in the report.
You MUST mention the levels and the ranges
"""
prompt = "Summarize the report"
index = VectorstoreIndexCreator().from_loaders([loader])
response = index.query(llm=OpenAI(model_name="gpt-3.5-turbo", temperature=0.2), question = prompt, chain_type = 'stuff')
response1 = agent_chain(prm)
res2 = report(Symptoms,history,age,gen,response1)
st.write('Medical Report')
st.write("")
st.write(response)
st.write(res2)
ans = response + res2
generate_pdf(ans)
st.write("PDF generated successfully! Click below to download.")
# Download link
with open("output.pdf", "rb") as f:
st.download_button("Download PDF", f.read(), file_name="output.pdf", mime="application/pdf")