ramji-srotas
commited on
Commit
•
5e273da
1
Parent(s):
9d35eee
Uploading files to have ingestion and all files
Browse files- .gitattributes +1 -0
- app.py +58 -0
- ctg-studies.json +3 -0
- inference.py +263 -0
- requirements.txt +7 -0
.gitattributes
CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
36 |
+
ctg-studies.json filter=lfs diff=lfs merge=lfs -text
|
app.py
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import random
|
3 |
+
import time
|
4 |
+
from inference import main
|
5 |
+
import torch
|
6 |
+
import gc
|
7 |
+
import os
|
8 |
+
import json
|
9 |
+
|
10 |
+
# Function to clear GPU memory
|
11 |
+
def clear_gpu_memory():
|
12 |
+
if torch.cuda.is_available():
|
13 |
+
torch.cuda.empty_cache()
|
14 |
+
|
15 |
+
# Function to clear CPU memory and run garbage collection
|
16 |
+
def clear_cpu_memory():
|
17 |
+
gc.collect() # Run garbage collection to clean up unused objects
|
18 |
+
|
19 |
+
def response_generator(prompt):
|
20 |
+
history = []
|
21 |
+
if os.path.exists('history.json'):
|
22 |
+
with open('history.json', "r") as f:
|
23 |
+
history = json.load(f)
|
24 |
+
|
25 |
+
bot_response, history = main(prompt,history)
|
26 |
+
with open('history.json', "w") as f:
|
27 |
+
json.dump(history, f, indent=4)
|
28 |
+
clear_gpu_memory()
|
29 |
+
clear_cpu_memory()
|
30 |
+
response = random.choice(
|
31 |
+
[
|
32 |
+
bot_response
|
33 |
+
]
|
34 |
+
)
|
35 |
+
yield response
|
36 |
+
|
37 |
+
st.title("Clinical Trial Information Bot")
|
38 |
+
|
39 |
+
# Initialize chat history
|
40 |
+
if "messages" not in st.session_state:
|
41 |
+
st.session_state.messages = []
|
42 |
+
|
43 |
+
for message in st.session_state.messages:
|
44 |
+
with st.chat_message(message["role"]):
|
45 |
+
st.markdown(message["content"])
|
46 |
+
|
47 |
+
|
48 |
+
# Accept user input
|
49 |
+
if prompt := st.chat_input("You can ask your question's here!!"):
|
50 |
+
# Add user message to chat history
|
51 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
52 |
+
# Display user message in chat message container
|
53 |
+
with st.chat_message("user"):
|
54 |
+
st.markdown(prompt)
|
55 |
+
|
56 |
+
with st.chat_message("assistant"):
|
57 |
+
response = st.write_stream(response_generator(prompt))
|
58 |
+
st.session_state.messages.append({"role": "assistant", "content": response})
|
ctg-studies.json
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:77e1f2b44faa4533b05b74f397e357837b14e81f3f12d8a09a100f910299a34d
|
3 |
+
size 313383362
|
inference.py
ADDED
@@ -0,0 +1,263 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
2 |
+
from langchain.vectorstores import Chroma
|
3 |
+
from langchain.embeddings import HuggingFaceEmbeddings
|
4 |
+
from langchain.chains import RetrievalQA
|
5 |
+
from langchain.schema import Document
|
6 |
+
import json
|
7 |
+
import re
|
8 |
+
from tqdm import tqdm
|
9 |
+
|
10 |
+
embedding_model = HuggingFaceEmbeddings(model_name="abhinand/MedEmbed-small-v0.1")
|
11 |
+
chroma_dir = "./chroma_trials_data_version_3"
|
12 |
+
chroma_db = Chroma(
|
13 |
+
embedding_function = embedding_model,
|
14 |
+
persist_directory=chroma_dir
|
15 |
+
)
|
16 |
+
|
17 |
+
def normalize_clinical_trial_data(data):
|
18 |
+
# Extract relevant sections
|
19 |
+
identification = data["protocolSection"]["identificationModule"]
|
20 |
+
description = data["protocolSection"]["descriptionModule"]
|
21 |
+
eligibility = data["protocolSection"]["eligibilityModule"]
|
22 |
+
locations = data["protocolSection"]["contactsLocationsModule"]["locations"][0]
|
23 |
+
inclusions_exclusions = eligibility.get("eligibilityCriteria", "").split("Exclusion Criteria:")
|
24 |
+
inclusions = ""
|
25 |
+
exclusions = ""
|
26 |
+
if len(inclusions_exclusions) >1:
|
27 |
+
exclusions = inclusions_exclusions[1]
|
28 |
+
inclusions = inclusions_exclusions[0].split("Inclusion Criteria:")
|
29 |
+
if len(inclusions)>0:
|
30 |
+
inclusions = inclusions[-1]
|
31 |
+
|
32 |
+
# Build normalized dictionary
|
33 |
+
normalized_data = {
|
34 |
+
"title": identification.get("officialTitle", ""),
|
35 |
+
"summary": description.get("briefSummary", ""),
|
36 |
+
"min_age": eligibility.get("minimumAge", ""),
|
37 |
+
"max_age": eligibility.get("maximumAge", ""),
|
38 |
+
"gender": eligibility.get("sex", ""),
|
39 |
+
"inclusions": inclusions,
|
40 |
+
"exclusions": exclusions,
|
41 |
+
"facility": locations.get("facility", ""),
|
42 |
+
"status": locations.get("status", ""),
|
43 |
+
"city": locations.get("city", ""),
|
44 |
+
"state": locations.get("state", ""),
|
45 |
+
"country": locations.get("country", ""),
|
46 |
+
"contacts": "\n".join([
|
47 |
+
f'Name: {contact.get("name", "")}, Role: {contact.get("role", "")}, Phone: {contact.get("phone", "")}, Email: {contact.get("email", "")}' for contact in locations.get("contacts", [])
|
48 |
+
])
|
49 |
+
|
50 |
+
}
|
51 |
+
|
52 |
+
return normalized_data
|
53 |
+
|
54 |
+
def store_data_in_chroma(raw_data):
|
55 |
+
documents = []
|
56 |
+
count = 0
|
57 |
+
for record in tqdm(raw_data):
|
58 |
+
try:
|
59 |
+
normalized_record = normalize_clinical_trial_data(record)
|
60 |
+
content = f"""Title: {normalized_record['title']}
|
61 |
+
Summary: {normalized_record['summary']}
|
62 |
+
Inclusions: {normalized_record['inclusions']}
|
63 |
+
Exclusions: {normalized_record['exclusions']}
|
64 |
+
Contacts: {normalized_record['contacts']}
|
65 |
+
Acceptable Age Range: {normalized_record['min_age']}- {normalized_record['max_age']}
|
66 |
+
"""
|
67 |
+
# Facility: {normalized_record['facility']}
|
68 |
+
# City: {normalized_record['city']}
|
69 |
+
# State: {normalized_record['state']}
|
70 |
+
# Country: {normalized_record['country']}
|
71 |
+
# Gender: {normalized_record['gender']}
|
72 |
+
# print(content)
|
73 |
+
metadata = {
|
74 |
+
"facility": normalized_record['facility'],
|
75 |
+
"status": normalized_record['status'],
|
76 |
+
"city": normalized_record['city'],
|
77 |
+
"state": normalized_record['state'],
|
78 |
+
"country": normalized_record['country']
|
79 |
+
}
|
80 |
+
documents.append(
|
81 |
+
Document(
|
82 |
+
page_content=content, metadata=metadata
|
83 |
+
)
|
84 |
+
)
|
85 |
+
count+=1
|
86 |
+
if count > 500:
|
87 |
+
break
|
88 |
+
except Exception as e:
|
89 |
+
print(e)
|
90 |
+
print("Document_size", len(documents))
|
91 |
+
chroma_db.add_documents(documents)
|
92 |
+
chroma_db.persist()
|
93 |
+
print('Data store in ChormaDB Successfully')
|
94 |
+
|
95 |
+
|
96 |
+
def get_unique_city_state_country():
|
97 |
+
results = chroma_db._collection.get(include=["metadatas"])
|
98 |
+
metadata = {'city': [], 'state':[], 'country':[]}
|
99 |
+
for doc in results['metadatas']:
|
100 |
+
metadata['city'].append(doc['city'])
|
101 |
+
metadata['state'].append(doc['state'])
|
102 |
+
metadata['country'].append(doc['country'])
|
103 |
+
|
104 |
+
return list(set(metadata['city'])),list(set(metadata['state'])), list(set(metadata['country']))
|
105 |
+
|
106 |
+
|
107 |
+
with open("ctg-studies.json", "r") as d:
|
108 |
+
raw_data = json.load(d)
|
109 |
+
store_data_in_chroma(raw_data)
|
110 |
+
|
111 |
+
city, state, country = get_unique_city_state_country()
|
112 |
+
|
113 |
+
model_name = "Qwen/Qwen2.5-0.5B-Instruct"
|
114 |
+
model = AutoModelForCausalLM.from_pretrained(
|
115 |
+
model_name,
|
116 |
+
torch_dtype="auto",
|
117 |
+
device_map="auto"
|
118 |
+
)
|
119 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
120 |
+
|
121 |
+
metadata_extraction_system_prompt = f"""You are an advanced information extractor.
|
122 |
+
Your task is to analyze the user input and extract location details (city, state, or country).
|
123 |
+
Ground_Data:
|
124 |
+
1. city: {city},
|
125 |
+
2. state: {state},
|
126 |
+
3. country: {country}
|
127 |
+
|
128 |
+
Instructions:
|
129 |
+
1. If a specific location type (e.g., city, state, or country) is not mentioned in the input, set its value to "".
|
130 |
+
2. Always include the keys "city", "state", and "country" in the output.
|
131 |
+
3. Match the values of "city", "state", and "country" strictly with the corresponding categories in the Ground_Data:
|
132 |
+
- Assign a value to "city" only if it matches any entry in Ground_Data["city"].
|
133 |
+
- Assign a value to "state" only if it matches any entry in Ground_Data["state"].
|
134 |
+
- Assign a value to "country" only if it matches any entry in Ground_Data["country"].
|
135 |
+
4. If a term does not match any entry in the Ground_Data for its category, leave it as "".
|
136 |
+
5. Do not make assumptions or infer any details not explicitly stated in the input.
|
137 |
+
|
138 |
+
For Example:
|
139 |
+
Input: "Changchun City, China"
|
140 |
+
Output: {{"city": "Changchun", "state": "", "country": "China"}}
|
141 |
+
Reason: state is not available
|
142 |
+
|
143 |
+
Input: "What do you think about United States?"
|
144 |
+
Output: {{"city": "", "state": "", "country": "United States"}}
|
145 |
+
Wrong Output: {{"city": "", "state": "United States", "country": ""}}
|
146 |
+
Reason: United States is not available in state Ground_Data
|
147 |
+
|
148 |
+
Your response MUST be directly parsed using **json.loads** nothing else.
|
149 |
+
"""
|
150 |
+
|
151 |
+
final_response_system_prompt = """You are an AI assistant specialized in providing information about ongoing clinical trials.
|
152 |
+
You will assist users by extracting relevant details from the provided clinical trial documents.
|
153 |
+
|
154 |
+
Key Instructions:
|
155 |
+
1. Use only the information explicitly stated in the documents.
|
156 |
+
2. Do not rely on general knowledge or assumptions.
|
157 |
+
3. If the user requests information not covered by the documents, ask clarifying questions or inform them that the required data is not available.
|
158 |
+
4. When presenting information, include specific details like trial titles, eligibility criteria, contact details, and locations, ensuring they align with the users query.
|
159 |
+
5. Keep responses concise and tailored to the users request.
|
160 |
+
6. Avoid speculation or providing unrelated information.
|
161 |
+
|
162 |
+
Available Information:
|
163 |
+
1. Clinical trial details, including titles, summaries, eligibility criteria, exclusions, and contact information.
|
164 |
+
2. Contacts for trial coordination, including their roles, phone numbers, and emails.
|
165 |
+
Use these documents as your sole source of truth to address user queries.
|
166 |
+
"""
|
167 |
+
|
168 |
+
fallback_system_prompt = f"""
|
169 |
+
You are an AI assistant specialized in providing information about ongoing clinical trials.
|
170 |
+
You will assist users by extracting relevant details from the provided clinical trial documents.
|
171 |
+
|
172 |
+
If the documents are empty and user has any city, state or country specified in question
|
173 |
+
ask for some verification questions based on location
|
174 |
+
Ground_Data:
|
175 |
+
1. city: {city},
|
176 |
+
2. state: {state},
|
177 |
+
3. country: {country}
|
178 |
+
"""
|
179 |
+
|
180 |
+
|
181 |
+
def generate_llm_response(messages):
|
182 |
+
|
183 |
+
text = tokenizer.apply_chat_template(
|
184 |
+
messages,
|
185 |
+
tokenize=False,
|
186 |
+
add_generation_prompt=True
|
187 |
+
)
|
188 |
+
model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
|
189 |
+
generated_ids = model.generate(
|
190 |
+
**model_inputs,
|
191 |
+
max_new_tokens=512,
|
192 |
+
do_sample=False
|
193 |
+
)
|
194 |
+
generated_ids = [
|
195 |
+
output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
|
196 |
+
]
|
197 |
+
response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
198 |
+
|
199 |
+
return response
|
200 |
+
|
201 |
+
def query_chroma_dynamic(question):
|
202 |
+
search_kwargs = {"k": 5}
|
203 |
+
extracted_metadata = {}
|
204 |
+
messages = [
|
205 |
+
{
|
206 |
+
"role": "system",
|
207 |
+
"content": metadata_extraction_system_prompt
|
208 |
+
},
|
209 |
+
{"role": "user", "content": f"{question}"}
|
210 |
+
]
|
211 |
+
llm_response = generate_llm_response(messages)
|
212 |
+
print("Extraction LLM Response: ", llm_response)
|
213 |
+
try:
|
214 |
+
extracted_metadata = json.loads(llm_response.replace('`','').replace('json',''))
|
215 |
+
except Exception as e:
|
216 |
+
print(e, llm_response, type(llm_response))
|
217 |
+
|
218 |
+
if len(extracted_metadata) > 0:
|
219 |
+
cleaned_data = []
|
220 |
+
for k, v in extracted_metadata.items():
|
221 |
+
if len(v)>0:
|
222 |
+
cleaned_data.append({k:v})
|
223 |
+
if len(cleaned_data) > 1:
|
224 |
+
search_kwargs["filter"] = {"$and": cleaned_data}
|
225 |
+
elif len(cleaned_data) == 1:
|
226 |
+
search_kwargs["filter"] = cleaned_data[0]
|
227 |
+
else:
|
228 |
+
cleaned_data = extracted_metadata.copy()
|
229 |
+
retriever = chroma_db.as_retriever(
|
230 |
+
search_kwargs=search_kwargs
|
231 |
+
)
|
232 |
+
retrieved_results = retriever.get_relevant_documents(question)
|
233 |
+
if retrieved_results == 0:
|
234 |
+
retriever = chroma_db.as_retriever(
|
235 |
+
search_kwargs={"k":5}
|
236 |
+
)
|
237 |
+
retrieved_results = retriever.get_relevant_documents(question)
|
238 |
+
|
239 |
+
return retrieved_results
|
240 |
+
|
241 |
+
|
242 |
+
def main(user_input, history):
|
243 |
+
retrieved_results = query_chroma_dynamic(user_input)
|
244 |
+
if len(retrieved_results) > 0:
|
245 |
+
context = '\n\n'.join([f"Document{i+1}:\n{doc.page_content}" for i, doc in enumerate(retrieved_results)])
|
246 |
+
final_response_message = [{
|
247 |
+
"role": "system",
|
248 |
+
"content": f"{final_response_system_prompt}"
|
249 |
+
}]
|
250 |
+
else:
|
251 |
+
context = "Sorry I couldnt find any documents from database"
|
252 |
+
final_response_message = [{
|
253 |
+
"role": "system",
|
254 |
+
"content": f"{fallback_system_prompt}"
|
255 |
+
}]
|
256 |
+
for i in history[-4:]:
|
257 |
+
final_response_message.append(i)
|
258 |
+
final_response_message.append({"role": "user", "content": f"\nDocuments:\n{context}\n\n{user_input}"})
|
259 |
+
|
260 |
+
final_response = generate_llm_response(final_response_message)
|
261 |
+
history.append({"role": "user", "content": f"\nDocuments:\n{context}\n\n{user_input}"})
|
262 |
+
history.append({"role": "assistant", "content": f"{final_response}"})
|
263 |
+
return final_response, history
|
requirements.txt
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
streamlit
|
2 |
+
sentence-transformers
|
3 |
+
transformers
|
4 |
+
langchain
|
5 |
+
langchain-community
|
6 |
+
chromadb
|
7 |
+
accelerate
|