import streamlit as st from langchain.llms import CTransformers import os from langchain.embeddings import HuggingFaceEmbeddings 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.agents import Tool from langchain.agents import initialize_agent from langchain.agents import AgentType from langchain.memory import ConversationBufferMemory 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.chat_models import ChatOpenAI from langchain import PromptTemplate from fpdf import FPDF st.title('MedTechAI') persist_directory = "" embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2", model_kwargs={'device': 'cpu'}) print(""" Duplicated space from WeekendAI/MedicalBot https://huggingface.co/spaces/WeekendAI/MedicalBot This version has been disconnected from OpenAI and needs no API key. This uses the TheBloke/Llama-2-7B-Chat-GGML model and the sentence-transformers/all-MiniLM-L6-v2 HuggingFaceEmbeddings """) 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") llm = CTransformers(model = "TheBloke/Llama-2-7B-Chat-GGML",model_type="llama",max_new_tokens = 2048,temperature = 0.5) 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")