File size: 9,448 Bytes
f1f3cae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3507e9
f1f3cae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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")