ankur2402 commited on
Commit
f1f3cae
1 Parent(s): 7418cc1

Upload main.py

Browse files
Files changed (1) hide show
  1. main.py +267 -0
main.py ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from langchain.llms import OpenAI, Cohere
3
+ import os
4
+ from langchain.llms import OpenAI
5
+ from langchain.embeddings import OpenAIEmbeddings,CohereEmbeddings
6
+ from langchain.document_loaders import PyPDFLoader
7
+ from langchain.vectorstores import Chroma
8
+ from langchain.agents.agent_toolkits import (
9
+ create_vectorstore_agent,
10
+ VectorStoreToolkit,
11
+ VectorStoreInfo
12
+ )
13
+ from langchain.indexes import VectorstoreIndexCreator
14
+ import re
15
+
16
+ from langchain.agents import Tool
17
+ from langchain.tools import DuckDuckGoSearchRun
18
+ # from langchain.utilities import WikipediaAPIWrapper
19
+ from langchain.chains import RetrievalQA
20
+ from langchain.chat_models import ChatOpenAI
21
+ from langchain.agents import Tool
22
+ from langchain.agents import initialize_agent
23
+ from langchain.agents import AgentType
24
+ from langchain.memory import ConversationBufferMemory
25
+ from langchain.chat_models import ChatOpenAI
26
+ from langchain.prompts import ChatPromptTemplate
27
+ from typing import Dict, Union, Any, List
28
+
29
+ from langchain.callbacks.base import BaseCallbackHandler
30
+ from langchain.schema import AgentAction
31
+ from langchain.agents import AgentType, initialize_agent, load_tools
32
+ from langchain.callbacks import tracing_enabled
33
+ from langchain.llms import OpenAI
34
+ from langchain.chat_models import ChatOpenAI
35
+ from langchain import PromptTemplate
36
+ from fpdf import FPDF
37
+
38
+ st.title('MedTechAI')
39
+
40
+ persist_directory = ""
41
+ model = ""
42
+ with st.sidebar:
43
+ with st.form('Cohere/OpenAI'):
44
+ mod = st.radio('Choose OpenAI/Cohere', ('OpenAI', 'Cohere'))
45
+ api_key = st.text_input('Enter API key', type="password")
46
+ # model = st.radio('Choose Company', ('ArtisanAppetite foods', 'BMW','Titan Watches'))
47
+ submitted = st.form_submit_button("Submit")
48
+
49
+
50
+ # Check if API key is provided and set up the language model accordingly
51
+ if api_key:
52
+ if(mod=='OpenAI'):
53
+ os.environ["OPENAI_API_KEY"] = api_key
54
+ llm = OpenAI(temperature=0.1, verbose=True)
55
+ embeddings = OpenAIEmbeddings()
56
+ if(mod=='Cohere'):
57
+ os.environ["Cohere_API_KEY"] = api_key
58
+ llm = Cohere(cohere_api_key=api_key)
59
+ embeddings = CohereEmbeddings(cohere_api_key=api_key)
60
+
61
+
62
+ def report(Symptoms,history,age,gen,response):
63
+ prompt_updates=f"""
64
+
65
+ Patient's Symptoms: {Symptoms}
66
+ Medical History: {history}
67
+ Age: {age}
68
+ Gender: {gen}
69
+ Lab report: {response}
70
+
71
+ You are a medical lab report analyst.
72
+ Based on the information provided above, i.e., Patients Symptoms, Medical History, Age and gender, Write a detailed medical report of the patient.
73
+ 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'.
74
+ You can get more insights from the 'knowledge Base' tool about the patients medical lab reports.
75
+
76
+
77
+ Refer the below example to generate the report. You MUST follow this format::
78
+ example:
79
+ ```
80
+ Patient Information:
81
+ - Age: 45
82
+ - Gender: Male
83
+
84
+ Clinical History:
85
+ He reported a history of smoking for 20 years but quit 2 years ago. No known allergies or significant medical history were reported.
86
+
87
+ Laboratory Investigations:
88
+ - Complete Blood Count (CBC): Within normal limits.
89
+ - Chest X-ray: Right lower lobe consolidation suggestive of pneumonia.
90
+
91
+ Assessment:
92
+ Cholelithiasis (Gallstones).
93
+ Choledocholithiasis (Common bile duct stones).
94
+ Elevated liver enzymes, possibly indicative of liver involvement.
95
+
96
+
97
+ Recommendations:
98
+ 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.
99
+ 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.
100
+
101
+ Follow-Up:
102
+ The patient is scheduled for a follow-up appointment in two weeks to assess the progress of pneumonia treatment and to evaluate lung function.
103
+
104
+ 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.
105
+
106
+ ```
107
+ """
108
+ print("report")
109
+ model_name = "gpt-3.5-turbo-16k"
110
+ temperature = 0.0
111
+ llm = OpenAI(model_name=model_name, temperature=temperature)
112
+ out = llm(prompt_updates)
113
+
114
+ return out
115
+
116
+ def generate_pdf(text):
117
+ # Save FPDF() class into a variable pdf
118
+ pdf = FPDF()
119
+
120
+ # Add a page
121
+ pdf.add_page()
122
+ # Set style and size of font that you want in the PDF
123
+ pdf.set_font("Arial", size=12)
124
+
125
+ # Set left margin and right margin
126
+ pdf.set_left_margin(20)
127
+ pdf.set_right_margin(20)
128
+
129
+ # Add multi-cell with line break
130
+ pdf.multi_cell(0, 10, text)
131
+
132
+ # Move to the next line after the text
133
+ pdf.ln()
134
+
135
+ # Save the PDF with the given file name
136
+ pdf.output("output.pdf")
137
+
138
+
139
+ uploaded_file = st.file_uploader("Upload Your Reports", type=["pdf"])
140
+
141
+ Symptoms = st.text_area('Enter Symptoms')
142
+ history = st.text_area('Enter Medical History')
143
+ age = st.text_area('Enter Age')
144
+ gen = st.text_area('Enter Gender')
145
+
146
+ if st.button("Submit"):
147
+ if uploaded_file is not None:
148
+ file_contents = uploaded_file.read()
149
+ save_path = uploaded_file.name
150
+ with open(save_path, "wb") as f:
151
+ f.write(file_contents)
152
+ loader = PyPDFLoader(save_path)
153
+ # Split pages from pdf
154
+ pages = loader.load_and_split()
155
+ store = Chroma.from_documents(pages, embeddings)
156
+
157
+ qa = RetrievalQA.from_chain_type(
158
+ llm=llm,
159
+ chain_type="stuff",
160
+ retriever=store.as_retriever()
161
+ )
162
+
163
+ tools = [
164
+ Tool(
165
+ name='Knowledge Base',
166
+ func=qa.run,
167
+ description=(
168
+ 'use this tool when answering any queries to get '
169
+ 'more information about the topic'
170
+ )
171
+ ),
172
+ ]
173
+ agent_chain = initialize_agent(
174
+ tools = tools,
175
+ llm = llm,
176
+ # agent_instructions=agent_instructions,
177
+ agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
178
+ verbose=True,
179
+ # max_iterations=5,
180
+ handle_parsing_errors="Check your output and make sure it conforms!", #to fix the ouputParser error
181
+ # return_intermediate_steps=True
182
+ )
183
+
184
+ prm = """
185
+ The 'knowledge Base' tool contains the Lab report
186
+
187
+ Please analyze the uploaded lab report and provide the results for the following tests:
188
+
189
+ 1. Complete Blood Count (CBC):
190
+ - Hemoglobin level
191
+ - Red blood cell count
192
+ - White blood cell count
193
+ - Platelet count
194
+
195
+ 2. Basic Metabolic Panel (BMP) or Comprehensive Metabolic Panel (CMP):
196
+ - Glucose levels
197
+ - Creatinine level
198
+ - Blood urea nitrogen (BUN) level
199
+ - Sodium level
200
+ - Potassium level
201
+ - Chloride level
202
+
203
+ 3. Lipid Panel:
204
+ - LDL cholesterol level
205
+ - HDL cholesterol level
206
+ - Total cholesterol level
207
+ - Triglyceride level
208
+
209
+ 4. Thyroid Function Tests:
210
+ - TSH (Thyroid-stimulating hormone) level
211
+ - T3 level
212
+ - T4 level
213
+
214
+ 5. Liver Function Tests:
215
+ - AST (Aspartate aminotransferase) level
216
+ - ALT (Alanine aminotransferase) level
217
+ - Bilirubin level
218
+
219
+ 6. Blood Clotting and Coagulation Tests:
220
+ - INR (International Normalized Ratio)
221
+ - PT (Prothrombin Time)
222
+ - aPTT (Activated Partial Thromboplastin Time)
223
+
224
+ 7. Blood Protein Levels:
225
+ - Serum albumin level
226
+ - Globulin levels
227
+ - Albumin-to-globulin (A/G) ratio
228
+
229
+ 8. Vitamin and Mineral Levels:
230
+ - Vitamin D level
231
+ - Vitamin B12 level
232
+ - Iron level
233
+
234
+ 9. Inflammatory Markers:
235
+ - C-reactive protein (CRP) level
236
+ - Erythrocyte Sedimentation Rate (ESR)
237
+
238
+ 10. Hormone Levels:
239
+ - Testosterone level (if applicable)
240
+ - Estrogen level (if applicable)
241
+ - Cortisol level (if applicable)
242
+ - Insulin level (if applicable)
243
+
244
+ Look up at Normal level ranges for each of the tests and also the patients levels mentioned in results of the report.
245
+ what are the levels of patients of all the parameters and the normal level ranges given in the report.
246
+ You MUST mention the levels and the ranges
247
+ """
248
+
249
+ prompt = "Summarize the report"
250
+ index = VectorstoreIndexCreator().from_loaders([loader])
251
+ response = index.query(llm=OpenAI(model_name="gpt-3.5-turbo", temperature=0.2), question = prompt, chain_type = 'stuff')
252
+ response1 = agent_chain(prm)
253
+ res2 = report(Symptoms,history,age,gen,response1)
254
+
255
+ st.write('Medical Report')
256
+ st.write("")
257
+ st.write(response)
258
+ st.write(res2)
259
+ ans = response + res2
260
+ generate_pdf(ans)
261
+ st.write("PDF generated successfully! Click below to download.")
262
+ # Download link
263
+ with open("output.pdf", "rb") as f:
264
+ st.download_button("Download PDF", f.read(), file_name="output.pdf", mime="application/pdf")
265
+
266
+
267
+