peachfawn commited on
Commit
c567014
Β·
verified Β·
1 Parent(s): e1c3a42

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +2072 -8
app.py CHANGED
@@ -1,13 +1,2077 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import pandas as pd
3
 
4
- # Load Excel file
5
- df = pd.read_excel("Clinical_trial_DB_with_embeddings (20).xlsx")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
- # Function to return data
8
- def get_data():
9
- return df
10
 
11
- # Create Gradio Interface
12
- demo = gr.Interface(fn=get_data, inputs=[], outputs="dataframe")
13
- demo.launch()
 
1
+ # -*- coding: utf-8 -*-
2
+ """inclusion and exclusion criteria creation
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1c9JSnTukGHH0nC2U6pwEpc8T6LgGTJC6
8
+ """
9
+
10
+
11
+ import gradio as gr
12
+ import re
13
+ import torch
14
+ import re
15
+ import spacy
16
+
17
+ from transformers import AutoTokenizer, AutoModelForTokenClassification, pipeline, AutoModel, AutoConfig, AutoModelForCausalLM, TextStreamer
18
+ from sklearn.metrics.pairwise import cosine_similarity
19
+ from fuzzywuzzy import fuzz, process
20
+
21
+ from pyvis.network import Network
22
+ from math import radians, cos, sin
23
+ from google.colab import files
24
+
25
+ # Load your fine-tuned model from Hugging Face
26
+ # model_name = "peachfawn/llama3ClinicalTrialFinalFineTuned"
27
+ # tokenizer = AutoTokenizer.from_pretrained(model_name)
28
+ # model = AutoModelForCausalLM.from_pretrained(model_name).to("cuda") # Move to CUDA
29
+
30
+ """# Clinical Trials Web Scrapper
31
+
32
+ ## Description
33
+ The Web Scrapper uses Gradio and Selenium to retrieve and process clinical trial data. It integrates an LLM model for generating inclusion and exclusion criteria based on study objectives.
34
+
35
+ ### Key Features
36
+ - **Data Retrieval**: Fetches clinical trials data based on user-specified filters (condition, age, gender, phase, etc.).
37
+ - **Dynamic Download**: Downloads JSON and CSV formats for trial data and appends new data to an existing Excel file.
38
+ - **LLM Integration**: Uses a fine-tuned model to generate inclusion and exclusion criteria from study objectives.
39
+ - **User Interface**: A Gradio interface enables user inputs and shows generated criteria.
40
+
41
+ ### Requirements
42
+ - **Libraries**: `gradio`, `selenium`, `pandas`, and `transformers`.
43
+ - **Gradio Interface**: A multi-step UI that allows filtering, downloading, and criteria generation.
44
+
45
+ """
46
+
47
  import gradio as gr
48
+ import os
49
+ import time
50
+ import pandas as pd
51
+ from selenium import webdriver
52
+ from selenium.webdriver.common.by import By
53
+ from selenium.webdriver.support.ui import WebDriverWait
54
+ from selenium.webdriver.support import expected_conditions as EC
55
+ import json
56
+ from transformers import AutoTokenizer, AutoModelForCausalLM, TextStreamer
57
+
58
+ # Initialize an empty global variable to store extracted data
59
+ clinical_trials_data = []
60
+
61
+ # Mapping for filter values to their corresponding URL parameters
62
+ status_mapping_DB = {
63
+ "Not yet recruiting": "not",
64
+ "Recruiting": "rec",
65
+ "Active, not recruiting": "act",
66
+ "Completed": "com",
67
+ "Terminated": "ter",
68
+ "Enrolling by invitation": "enr",
69
+ "Suspended": "sus",
70
+ "Withdrawn": "wit",
71
+ "Unknown": "unk"
72
+ }
73
+
74
+ # Mapping for age values to their corresponding URL parameters
75
+ age_mapping_DB = {
76
+ "Child (birth - 17)": "child",
77
+ "Adult (18 - 64)": "adult",
78
+ "Older adult (65+)": "older"
79
+ }
80
+
81
+ # Mapping for gender values to their corresponding URL parameters
82
+ sex_mapping_DB = {
83
+ "All": "all",
84
+ "Female": "f",
85
+ "Male": "m"
86
+ }
87
+
88
+ # Mapping for study phase values to their corresponding URL parameters
89
+ phase_mapping_DB = {
90
+ "Early Phase 1": "0",
91
+ "Phase 1": "1",
92
+ "Phase 2": "2",
93
+ "Phase 3": "3",
94
+ "Phase 4": "4",
95
+ "Not applicable": "NA"
96
+ }
97
+
98
+ study_type_mapping_DB = {
99
+ "Interventional": "int",
100
+ "Observational": "obs",
101
+ "Patient registries": "obs_patreg",
102
+ "Expanded access": "exp",
103
+ "Individual patients": "exp_indiv",
104
+ "Intermediate-size population": "exp_inter",
105
+ "Treatment IND/Protocol": "exp_treat"
106
+ }
107
+
108
+ results_mapping_DB = {
109
+ "With results": "with",
110
+ "Without results": "without"
111
+ }
112
+
113
+ docs_mapping_DB = {
114
+ "Study protocols": "prot",
115
+ "Statistical analysis plans": "sap",
116
+ "Informed consent forms": "icf"
117
+ }
118
+
119
+ funder_type_mapping_DB = {
120
+ "NIH": "nih",
121
+ "Other U.S. federal agency": "fed",
122
+ "Industry": "industry",
123
+ "All others (individuals, universities, organizations)": "other"
124
+ }
125
+
126
+ # Set up Selenium driver
127
+ def setup_driver(download_dir):
128
+ chrome_options = webdriver.ChromeOptions()
129
+ prefs = {
130
+ "download.default_directory": download_dir,
131
+ "download.prompt_for_download": False,
132
+ "download.directory_upgrade": True,
133
+ "safebrowsing.enabled": True
134
+ }
135
+ chrome_options.add_experimental_option("prefs", prefs)
136
+ chrome_options.add_argument("--headless")
137
+ chrome_options.add_argument("--no-sandbox")
138
+ chrome_options.add_argument("--disable-dev-shm-usage")
139
+ return webdriver.Chrome(options=chrome_options)
140
+
141
+ # Retry logic for clicks
142
+ def safe_click(driver, by, selector, retries=3, delay=2):
143
+ for attempt in range(retries):
144
+ try:
145
+ element = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((by, selector)))
146
+ driver.execute_script("arguments[0].scrollIntoView(true);", element)
147
+ time.sleep(1) # Short delay after scrolling
148
+ element.click()
149
+ print(f"Clicked element {selector} on attempt {attempt + 1}")
150
+ return True
151
+ except Exception as e:
152
+ print(f"Attempt {attempt + 1} failed: {e}")
153
+ time.sleep(delay)
154
+ print(f"Failed to click element {selector} after {retries} retries.")
155
+ return False
156
+
157
+ # Download JSON file
158
+ def download_json_from_link(url):
159
+ project_dir = os.getcwd()
160
+ download_dir = os.path.join(project_dir, "downloads")
161
+ os.makedirs(download_dir, exist_ok=True)
162
+
163
+ driver = setup_driver(download_dir)
164
+
165
+ try:
166
+ driver.get(url)
167
+
168
+ open_modal_button = WebDriverWait(driver, 10).until(
169
+ EC.element_to_be_clickable((By.CLASS_NAME, "action-bar-button"))
170
+ )
171
+ open_modal_button.click()
172
+ print("Modal opened.")
173
+
174
+ json_option = WebDriverWait(driver, 10).until(
175
+ EC.presence_of_element_located((By.ID, "download-format-json"))
176
+ )
177
+ time.sleep(1) # Short delay to ensure stability
178
+ driver.execute_script("arguments[0].click();", json_option)
179
+ print("JSON format selected.")
180
+
181
+ download_button = WebDriverWait(driver, 10).until(
182
+ EC.element_to_be_clickable((By.CLASS_NAME, "primary-button"))
183
+ )
184
+ driver.execute_script("arguments[0].click();", download_button)
185
+ print("Download initiated.")
186
+
187
+ time.sleep(15) # Adjust based on download speed
188
+
189
+ downloaded_file_path = os.path.join(download_dir, "ctg-studies.json")
190
+ if os.path.exists(downloaded_file_path):
191
+ print(f"Found downloaded file: {downloaded_file_path}")
192
+ else:
193
+ print("Error: ctg-studies.json not found.")
194
+
195
+ except Exception as e:
196
+ print(f"Error: {e}")
197
+
198
+ finally:
199
+ driver.quit()
200
+ print("Browser closed.")
201
+
202
+ # Download CSV file
203
+ def download_csv_from_link(url):
204
+ new_rows = 0
205
+ project_dir = os.getcwd()
206
+ download_dir = os.path.join(project_dir, "downloads")
207
+ os.makedirs(download_dir, exist_ok=True)
208
+
209
+ driver = setup_driver(download_dir)
210
+
211
+ try:
212
+ driver.get(url)
213
+
214
+ if not safe_click(driver, By.CLASS_NAME, "action-bar-button"):
215
+ print("Failed to open modal for CSV.")
216
+ return
217
+ print("Modal opened for CSV.")
218
+
219
+ if not safe_click(driver, By.XPATH, "//button[contains(text(), 'Select all')]"):
220
+ print("Failed to select all fields for CSV.")
221
+ return
222
+ print("All fields selected for CSV.")
223
+
224
+ if not safe_click(driver, By.CLASS_NAME, "primary-button"):
225
+ print("Failed to initiate CSV download.")
226
+ return
227
+ print("Download initiated for CSV.")
228
+
229
+ time.sleep(15) # Adjust based on download speed
230
+
231
+ downloaded_file_path = os.path.join(download_dir, "ctg-studies.csv")
232
+ if os.path.exists(downloaded_file_path):
233
+ print(f"Found downloaded CSV file: {downloaded_file_path}")
234
+ print_file_contents(downloaded_file_path)
235
+ new_rows = append_to_excel(downloaded_file_path)
236
+
237
+ delete_file(downloaded_file_path)
238
+ else:
239
+ print("Error: CSV file not found.")
240
+ return new_rows
241
+
242
+ except Exception as e:
243
+ print(f"Error downloading CSV: {e}")
244
+
245
+ finally:
246
+ driver.quit()
247
+ print("Browser closed after CSV download.")
248
+
249
+ # Print file contents
250
+ def print_file_contents(file_path):
251
+ try:
252
+ data = pd.read_csv(file_path, encoding='utf-8')
253
+ print(f"Loaded data from {file_path}. Shape: {data.shape}")
254
+ print(data.head())
255
+ except Exception as e:
256
+ print(f"Error reading {file_path}: {e}")
257
+
258
+ # Append data to Excel file
259
+ def append_to_excel(new_file, main_file="clinical_trials_data_better_other.xlsx"):
260
+ try:
261
+ new_data = pd.read_csv(new_file, encoding='utf-8')
262
+ print(f"New data shape: {new_data.shape}")
263
+ if os.path.exists(main_file):
264
+ main_data = pd.read_excel(main_file)
265
+ print(f"Existing data shape: {main_data.shape}")
266
+
267
+ combined_data = pd.concat([main_data, new_data])
268
+ combined_data.drop_duplicates(subset=['NCT Number'], inplace=True)
269
+ new_rows_count = combined_data.shape[0] - main_data.shape[0]
270
+
271
+ print(f"Combined data shape after removing duplicates: {combined_data.shape}")
272
+ else:
273
+ print(f"{main_file} does not exist. Creating it.")
274
+ combined_data = new_data
275
+ new_rows_count = combined_data.shape[0] # All rows are new
276
+
277
+ combined_data.to_excel(main_file, index=False)
278
+ print(f"Data successfully saved to {main_file}.")
279
+ return new_rows_count
280
+
281
+ except pd.errors.EmptyDataError:
282
+ print(f"Error: {new_file} is empty or unreadable.")
283
+ except Exception as e:
284
+ print(f"Unexpected error: {e}")
285
+
286
+ # Delete file after processing
287
+ def delete_file(file_path):
288
+ try:
289
+ os.remove(file_path)
290
+ print(f"Deleted file: {file_path}")
291
+ except Exception as e:
292
+ print(f"Error deleting {file_path}: {e}")
293
+
294
+ def update_clinical_trials_with_json(json_file="/content/downloads/ctg-studies.json",
295
+ excel_file="clinical_trials_data_better_other.xlsx"):
296
+ try:
297
+ with open(json_file, 'r', encoding='utf-8') as f:
298
+ json_data = json.load(f)
299
+ print(f"Loaded JSON data from {json_file}.")
300
+
301
+ # Prepare data from JSON
302
+ new_entries = []
303
+ for trial in json_data:
304
+ nct_id = trial["protocolSection"]["identificationModule"].get("nctId")
305
+ detailed_description = trial["protocolSection"]["descriptionModule"].get("detailedDescription", "")
306
+ eligibility_criteria = trial["protocolSection"]["eligibilityModule"].get("eligibilityCriteria", "")
307
+
308
+ new_entries.append({
309
+ "NCT Number": nct_id,
310
+ "detailedDescription": detailed_description,
311
+ "eligibilityCriteria": eligibility_criteria
312
+ })
313
+
314
+ new_df = pd.DataFrame(new_entries)
315
+
316
+ # Check if the Excel file exists
317
+ if not os.path.exists(excel_file):
318
+ # If the file does not exist, save new_df as the initial data and return
319
+ new_df.to_excel(excel_file, index=False)
320
+ print(f"File {excel_file} created with initial data.")
321
+ return
322
+
323
+ # Load existing data
324
+ df = pd.read_excel(excel_file)
325
+ print(f"Loaded existing Excel data. Shape: {df.shape}")
326
+
327
+ # Merge existing data with new data on 'NCT Number', keeping all data
328
+ updated_df = pd.merge(df, new_df, on="NCT Number", how="outer", suffixes=('', '_new'))
329
+
330
+ # Update columns only where they are currently empty in the original data
331
+ if 'detailedDescription' in updated_df.columns and 'detailedDescription_new' in updated_df.columns:
332
+ updated_df['detailedDescription'] = updated_df['detailedDescription'].fillna(updated_df['detailedDescription_new'])
333
+
334
+ if 'eligibilityCriteria' in updated_df.columns and 'eligibilityCriteria_new' in updated_df.columns:
335
+ updated_df['eligibilityCriteria'] = updated_df['eligibilityCriteria'].fillna(updated_df['eligibilityCriteria_new'])
336
+
337
+ # Drop the '_new' columns after filling in the missing values
338
+ updated_df.drop(columns=['detailedDescription_new', 'eligibilityCriteria_new'], inplace=True, errors='ignore')
339
+
340
+ # Save the updated DataFrame back to the Excel file
341
+ updated_df.to_excel(excel_file, index=False)
342
+ print(f"Data successfully updated and saved to {excel_file}.")
343
+
344
+ except Exception as e:
345
+ print(f"Error updating Excel with JSON: {e}")
346
+
347
+
348
+ # Main function for Gradio
349
+ def process_page(condition, term, treatment, filters, age_ranges, sex, phases, study_types, results, docs, funder_type, numberOfTrialsPerBatch):
350
+ filter_query = ''
351
+ filter_parts = []
352
+
353
+ if filters:
354
+ filter_parts.append('status:' + ' '.join([status_mapping_DB[f] for f in filters if f in status_mapping_DB]))
355
+
356
+ if age_ranges:
357
+ filter_parts.append('ages:' + ' '.join([age_mapping_DB[a] for a in age_ranges if a in age_mapping_DB]))
358
+
359
+ if sex in ['Male', 'Female']:
360
+ filter_parts.append('sex:' + sex_mapping_DB[sex])
361
+
362
+ if phases:
363
+ filter_parts.append('phase:' + ' '.join([phase_mapping_DB[p] for p in phases if p in phase_mapping_DB]))
364
+
365
+ if study_types:
366
+ filter_parts.append('studyType:' + ' '.join([study_type_mapping_DB.get(st, st) for st in study_types]))
367
+
368
+ if results:
369
+ filter_parts.append('results:' + ' '.join([results_mapping_DB.get(r, r) for r in results]))
370
+
371
+ if docs:
372
+ filter_parts.append('docs:' + ' '.join([docs_mapping_DB.get(d, d) for d in docs]))
373
+
374
+ if funder_type:
375
+ filter_parts.append('funderType:' + ' '.join([funder_type_mapping_DB.get(f, f) for f in funder_type]))
376
+
377
+ if filter_parts:
378
+ filter_query = f"&aggFilters=" + ','.join(filter_parts)
379
+
380
+ url = f"https://clinicaltrials.gov/search?cond={condition}&term={term}&intr={treatment}&limit=100{filter_query}"
381
+ print(f"Constructed URL: {url}")
382
+
383
+ download_json_from_link(url)
384
+ new_rows = download_csv_from_link(url)
385
+ update_clinical_trials_with_json()
386
+ delete_file("/content/downloads/ctg-studies.json")
387
+
388
+ return new_rows, gr.update(visible=True)
389
+
390
+
391
+
392
+
393
+ #--------------------------------------------------------------------------------------------------
394
+
395
+ # Define a function to generate inclusion and exclusion criteria
396
+ def generate_output(user_input, model, tokenizer):
397
+ # Define the Alpaca prompt format
398
+ alpaca_prompt = """Below is a study objective that describes a clinical trial. Write an inclusion and exclusion criteria based on the given study objective.
399
+
400
+ ### Study Objective:
401
+ {}
402
+
403
+ ### Response (Inclusion and Exclusion Criteria):
404
+ {}"""
405
+
406
+ # Prepare the input for the model
407
+ inputs = tokenizer(
408
+ [
409
+ alpaca_prompt.format(
410
+ user_input, # The input from the eligibilityCriteria
411
+ "" # Leave the response section blank for now
412
+ )
413
+ ],
414
+ return_tensors="pt"
415
+ ).to("cuda")
416
+
417
+ # Use a text streamer to capture the output
418
+ text_streamer = TextStreamer(tokenizer)
419
+
420
+ # Generate text
421
+ generated_output = model.generate(**inputs, streamer=text_streamer, max_new_tokens=2000)
422
+
423
+ # Return the generated text
424
+ output_text = tokenizer.decode(generated_output[0], skip_special_tokens=True)
425
+ return output_text
426
+
427
+ # Process eligibility criteria based on column presence
428
+ def process_eligibility_criteria():
429
+ # Load the model and tokenizer
430
+ file_path = "/content/clinical_trials_data_better_other.xlsx"
431
+
432
+ # Load the Excel file
433
+ df = pd.read_excel(file_path)
434
+
435
+ # Determine if this is a new file (i.e., no 'Inclusion' or 'Exclusion' columns)
436
+ is_new_file = 'Inclusion' not in df.columns or 'Exclusion' not in df.columns
437
+
438
+ # Process all rows if this is a new file
439
+ if is_new_file:
440
+ df['Inclusion'] = pd.NA
441
+ df['Exclusion'] = pd.NA
442
+ data_to_process = df # Process all rows for new files
443
+ else:
444
+ # Process only rows where 'Inclusion' or 'Exclusion' is empty
445
+ data_to_process = df[df['Inclusion'].isna() | df['Exclusion'].isna()]
446
+
447
+ for idx, row in data_to_process.iterrows():
448
+ try:
449
+ generated_text = generate_output(row['eligibilityCriteria'], model, tokenizer)
450
+ inclusion_start = generated_text.find("Inclusion:") + len("Inclusion:")
451
+ exclusion_start = generated_text.find("Exclusion:")
452
+
453
+ inclusion_criteria = generated_text[inclusion_start:exclusion_start].strip()
454
+ exclusion_criteria = generated_text[exclusion_start + len("Exclusion:"):].strip()
455
+
456
+ df.at[idx, 'Inclusion'] = inclusion_criteria
457
+ df.at[idx, 'Exclusion'] = exclusion_criteria
458
+
459
+ except Exception as e:
460
+ print(f"Error processing row with ID {row['NCT Number']}: {e}")
461
+ df.at[idx, 'Inclusion'] = "N/A"
462
+ df.at[idx, 'Exclusion'] = "N/A"
463
+
464
+ # Save the updated DataFrame back to the file
465
+ df.to_excel(file_path, index=False)
466
+ print(f"\nAll required rows processed! Updated file saved to {file_path}")
467
+
468
+
469
+
470
+ """*query data"""
471
+
472
  import pandas as pd
473
 
474
+ # Load the Excel file
475
+ df = pd.read_excel('Clinical_trial_DB_with_embeddings.xlsx')
476
+
477
+ # # Function to query the data based on extracted keywords
478
+ # def query_data(extracted_params):
479
+ # filtered_df = df # Start with the entire DataFrame
480
+
481
+ # # Apply study status filter
482
+ # if extracted_params['status']:
483
+ # status_pattern = '|'.join(extracted_params['status'])
484
+ # filtered_df = filtered_df[filtered_df['Study Status'].str.contains(status_pattern, case=False, na=False)]
485
+
486
+ # # Apply age ranges filter
487
+ # if extracted_params['age_ranges']:
488
+ # age_pattern = '|'.join(extracted_params['age_ranges'])
489
+ # filtered_df = filtered_df[filtered_df['Age'].str.contains(age_pattern, case=False, na=False)]
490
+
491
+ # # Apply sex filter
492
+ # if extracted_params['sex']:
493
+ # filtered_df = filtered_df[filtered_df['Sex'].str.contains(extracted_params['sex'], case=False, na=False)]
494
+
495
+ # # Apply phases filter
496
+ # if extracted_params['phases']:
497
+ # phases_pattern = '|'.join(extracted_params['phases'])
498
+ # filtered_df = filtered_df[filtered_df['Phases'].str.contains(phases_pattern, case=False, na=False)]
499
+
500
+ # return filtered_df
501
+
502
+
503
+
504
+ from fuzzywuzzy import fuzz
505
+ import pandas as pd
506
+
507
+ def query_data(extracted_params, text):
508
+ filtered_df = df.copy() # Start with the entire DataFrame
509
+
510
+ # Apply study status filter
511
+ if extracted_params['status']:
512
+ status_pattern = '|'.join(extracted_params['status'])
513
+ filtered_df = filtered_df[filtered_df['Study Status'].str.contains(status_pattern, case=False, na=False)]
514
+
515
+ # Apply age ranges filter
516
+ if extracted_params['age_ranges']:
517
+ age_pattern = '|'.join(extracted_params['age_ranges'])
518
+ filtered_df = filtered_df[filtered_df['Age'].str.contains(age_pattern, case=False, na=False)]
519
+
520
+ # Apply sex filter
521
+ if extracted_params['sex']:
522
+ filtered_df = filtered_df[filtered_df['Sex'].str.contains(extracted_params['sex'], case=False, na=False)]
523
+
524
+ # Apply phases filter
525
+ if extracted_params['phases']:
526
+ phases_pattern = '|'.join(extracted_params['phases'])
527
+ filtered_df = filtered_df[filtered_df['Phases'].str.contains(phases_pattern, case=False, na=False)]
528
+
529
+ # Extract conditions from the text
530
+ conditions = extract_conditions(text) # Extract the phrase (e.g., ["brain cancer"])
531
+ # Ensure conditions is not empty and is a list
532
+ if conditions and isinstance(conditions, list):
533
+ # Check if "glioma" exists in the list and is not at index 0
534
+ if "glioma" in conditions and conditions[0] != "glioma":
535
+ # Remove "glioma" from its current position
536
+ conditions.remove("glioma")
537
+ # Insert "glioma" at index 0
538
+ conditions.insert(0, "glioma")
539
+ print(f"The conditions before the query IS IS IS -----> {conditions}")
540
+ # Apply substring matching on "Brief Summary"
541
+ if conditions and not filtered_df.empty:
542
+ search_condition = str(conditions[0]).lower().strip()
543
+
544
+ # Normalize "Brief Summary" column
545
+ filtered_df['Brief Summary'] = filtered_df['Brief Summary'].fillna("").str.lower()
546
+
547
+ # Check for substring matches
548
+ brief_summary_matches = []
549
+ for index, row in filtered_df.iterrows():
550
+ brief_summary = row['Brief Summary']
551
+ if search_condition in brief_summary: # Substring match
552
+ brief_summary_matches.append(index)
553
+ else:
554
+ # Fallback: Partial fuzzy matching for close matches
555
+ match_score = fuzz.partial_ratio(search_condition, brief_summary)
556
+ if match_score >= 70:
557
+ brief_summary_matches.append(index)
558
+
559
+ # Filter the DataFrame to only include rows with matching indices
560
+ filtered_df = filtered_df.loc[brief_summary_matches]
561
+
562
+ return filtered_df
563
+
564
+ def extract_from_excel_by_ids(ids):
565
+ """
566
+ Extract rows from an Excel file that match a given list of IDs.
567
+
568
+ Args:
569
+ ids (list): List of Clinical Trial IDs to filter the data by.
570
+
571
+ Returns:
572
+ pd.DataFrame: Filtered DataFrame containing only rows that match the provided IDs.
573
+ """
574
+ # Load the Excel data
575
+ df = pd.read_excel("Clinical_trial_DB_with_embeddings.xlsx")
576
+
577
+ # Filter the DataFrame by IDs
578
+ filtered_df = df[df['NCT Number'].isin(ids)]
579
+
580
+ return filtered_df
581
+
582
+ """LLAMA 3 MODEL"""
583
+
584
+
585
+
586
+ """# Clinical Criteria Conflict Detection
587
+
588
+ ## Description
589
+ This script uses Clinical BERT to detect conflicts between user-defined inclusion/exclusion criteria and clinical trial criteria. It leverages text embedding and cosine similarity to identify potential conflicts, particularly relevant in clinical trials for patient eligibility assessment.
590
+
591
+ ### Key Features
592
+ - **Model Loading**: Loads Bio_ClinicalBERT to create text embeddings for criteria comparison.
593
+ - **Data Cleaning**: Cleans criteria lists by removing special characters.
594
+ - **Conflict Detection**: Checks for conflicts between user and trial criteria, excluding age-based items, using cosine similarity for accuracy.
595
+
596
+ ### Requirements
597
+ - **Libraries**: `transformers`, `torch`, `sklearn`, and `re` for text processing and similarity calculations.
598
+ - **Criteria Check**: Prints detected conflicts with a similarity threshold of 0.85 to highlight potential eligibility mismatches.
599
+
600
+ """
601
+
602
+ class MedicalNER:
603
+ def __init__(self):
604
+ # Load Clinical BERT tokenizer and model for disease extraction (NER)
605
+ disease_model_name = 'emilyalsentzer/Bio_ClinicalBERT'
606
+ self.disease_tokenizer = AutoTokenizer.from_pretrained(disease_model_name)
607
+ self.disease_model = AutoModelForTokenClassification.from_pretrained("alvaroalon2/biobert_diseases_ner")
608
+
609
+ # Load a second model for age and gender extraction (Biomedical NER)
610
+ age_gender_model_name = 'd4data/biomedical-ner-all' # Model trained for biomedical NER
611
+ self.age_gender_tokenizer = AutoTokenizer.from_pretrained(age_gender_model_name)
612
+ self.age_gender_model = AutoModelForTokenClassification.from_pretrained(age_gender_model_name)
613
+
614
+ # Load Clinical BERT model for sentence embeddings
615
+ embedding_model_name = 'emilyalsentzer/Bio_ClinicalBERT'
616
+ self.embedding_tokenizer = AutoTokenizer.from_pretrained(embedding_model_name)
617
+ self.embedding_model = AutoModel.from_pretrained(embedding_model_name)
618
+
619
+ # Create pipelines
620
+ self.disease_pipeline = pipeline("ner", model=self.disease_model, tokenizer=self.disease_tokenizer)
621
+ self.age_gender_pipeline = pipeline("ner", model=self.age_gender_model, tokenizer=self.age_gender_tokenizer)
622
+
623
+ # Method to extract age and gender entities
624
+ def extract_age_gender(self, text):
625
+ age_gender_entities = self.age_gender_pipeline(text)
626
+ return age_gender_entities
627
+
628
+ # Method to dynamically convert descriptors like "twenties" or "thirties" to an age range
629
+ def descriptor_to_age_range(self, descriptor):
630
+ base_age = {"twenties": 20, "thirties": 30, "forties": 40, "fifties": 50, "sixties": 60, "seventies": 70, "eighties": 80, "nineties": 90}
631
+ if descriptor in base_age:
632
+ start_age = base_age[descriptor]
633
+ end_age = start_age + 9
634
+ return f"{start_age}-{end_age}"
635
+ return None
636
+
637
+ # Method to merge tokens like "late thirties" and extract age
638
+ def extract_age_from_entities(self, entities, text):
639
+ age = None
640
+ for i, entity in enumerate(entities):
641
+ if entity['entity'] == 'B-Age': # Found the start of an age entity
642
+ age = entity['word']
643
+ if i + 1 < len(entities) and entities[i + 1]['entity'] == 'I-Age':
644
+ age += " " + entities[i + 1]['word']
645
+
646
+ if not age:
647
+ # Check for numerical ages or descriptive ages like "late thirties"
648
+ age_match = re.search(r'\b(?:at|age|am|turning|around|about)\s*(\d+)\b', text, re.IGNORECASE)
649
+ if age_match:
650
+ age = age_match.group(1)
651
+ else:
652
+ # Corrected the regex to ensure both groups are captured properly
653
+ age_range_match = re.search(r'\b(early|mid|late)\s*(twenties|thirties|forties|fifties|sixties|seventies|eighties|nineties)\b', text, re.IGNORECASE)
654
+ if age_range_match:
655
+ # Ensure both groups are captured
656
+ descriptor = age_range_match.group(2).lower() if age_range_match.group(2) else None
657
+ if descriptor:
658
+ age_range = self.descriptor_to_age_range(descriptor)
659
+ if age_range:
660
+ if "early" in age_range_match.group(1).lower():
661
+ age = age_range.split('-')[0] # e.g., "30" for early thirties
662
+ elif "mid" in age_range_match.group(1).lower():
663
+ start, end = map(int, age_range.split('-'))
664
+ age = f"{start+2}-{end-2}" # e.g., "32-37" for mid-thirties
665
+ elif "late" in age_range_match.group(1).lower():
666
+ age = age_range.split('-')[1] # e.g., "39" for late thirties
667
+ return age
668
+
669
+ # Function to merge subword tokens back into full words and combine consecutive tokens
670
+ def merge_subwords_and_conditions(self, entities):
671
+ merged = []
672
+ current_phrase = ""
673
+ for entity in entities:
674
+ word = entity['word']
675
+ if word.startswith("##"):
676
+ current_phrase += word[2:] # Append subword without ##
677
+ else:
678
+ if current_phrase:
679
+ merged[-1] += current_phrase # Append the subword to the last word
680
+ current_phrase = ""
681
+ if len(merged) > 0 and entity['entity'] == 'I-DISEASE':
682
+ merged[-1] += " " + word # Merge consecutive disease tokens
683
+ else:
684
+ merged.append(word) # Start a new word/phrase
685
+ if current_phrase:
686
+ merged[-1] += current_phrase
687
+ return merged
688
+
689
+ # Method to remove exact and similar duplicates from a list of conditions
690
+ def remove_duplicates(self, conditions):
691
+ # Using a set to remove exact duplicates and retain unique conditions
692
+ unique_conditions = set(conditions)
693
+ cleaned_conditions = []
694
+
695
+ for condition in unique_conditions:
696
+ is_substring = False
697
+ for other_condition in unique_conditions:
698
+ if condition != other_condition and condition in other_condition:
699
+ is_substring = True
700
+ break
701
+ if not is_substring:
702
+ cleaned_conditions.append(condition)
703
+
704
+ return cleaned_conditions
705
+
706
+ # Method to extract conditions, treatments, age, and gender from text
707
+ def extract_info(self, text):
708
+ # Extract disease-related entities
709
+ disease_entities = self.disease_pipeline(text)
710
+ condition = []
711
+ treatment = []
712
+ for entity in disease_entities:
713
+ if entity['entity'] == 'B-DISEASE' or entity['entity'] == 'I-DISEASE':
714
+ condition.append(entity)
715
+ elif entity['entity'] == 'B-TREATMENT':
716
+ treatment.append(entity['word'])
717
+
718
+ # Extract age and gender using second model
719
+ age_gender_entities = self.extract_age_gender(text)
720
+ age = self.extract_age_from_entities(age_gender_entities, text)
721
+ sex = None
722
+ for entity in age_gender_entities:
723
+ if entity['entity'] == 'B-Sex':
724
+ sex = entity['word']
725
+
726
+ # Merge and clean condition entities
727
+ condition_words = self.merge_subwords_and_conditions(condition)
728
+ unique_conditions = self.remove_duplicates(condition_words)
729
+
730
+ return {
731
+ "Condition": unique_conditions,
732
+ "Treatment": treatment,
733
+ "Age": age,
734
+ "Sex": sex
735
+ }
736
+
737
+ # Method to compute sentence embeddings for a given condition
738
+ def get_sentence_embedding(self, condition):
739
+ inputs = self.embedding_tokenizer(condition, return_tensors='pt', truncation=True, max_length=128)
740
+ outputs = self.embedding_model(**inputs)
741
+ # Take the mean of the last hidden state to create a fixed-size vector
742
+ embeddings = outputs.last_hidden_state.mean(dim=1)
743
+ return embeddings
744
+
745
+ # Method to compute cosine similarity between two conditions
746
+ def compute_similarity(self, condition1, condition2):
747
+ embedding1 = self.get_sentence_embedding(condition1)
748
+ embedding2 = self.get_sentence_embedding(condition2)
749
+ similarity = cosine_similarity(embedding1.detach().numpy(), embedding2.detach().numpy())
750
+ return similarity[0][0]
751
+
752
+ # Method to compare conditions between two texts
753
+ def compare_conditions(self, text1, text2):
754
+ conditions_text1 = self.extract_info(text1)["Condition"]
755
+ conditions_text2 = self.extract_info(text2)["Condition"]
756
+
757
+ if not conditions_text1 or not conditions_text2:
758
+ print("No conditions extracted in one or both texts.")
759
+ return {
760
+ "Unmatched Conditions in Text 2": [],
761
+ "Conditions in Text 1": conditions_text1,
762
+ "Conditions in Text 2": conditions_text2
763
+ }
764
+
765
+
766
+
767
+ unmatched_conditions = []
768
+ for condition2 in conditions_text2:
769
+ found_match = False
770
+ for condition1 in conditions_text1:
771
+ similarity_score = self.compute_similarity(condition1, condition2)
772
+ if similarity_score > 0.95: # Threshold for similarity
773
+ found_match = True
774
+ break
775
+ if not found_match:
776
+ unmatched_conditions.append(condition2)
777
+
778
+ return {
779
+ "Unmatched Conditions in Text 2": unmatched_conditions,
780
+ "Conditions in Text 1": conditions_text1,
781
+ "Conditions in Text 2": conditions_text2
782
+ }
783
+
784
+
785
+
786
+
787
+
788
+ # Instantiate the MedicalNER class
789
+ ner = MedicalNER()
790
+ print(ner.compare_conditions("i am a male with coronary artery disease" , "The objective of our work to determine the mechanisms of myocardial infarction in women without obstructive coronary artery disease."))
791
+ # Define a function that extracts conditions from text
792
+ def extract_conditions(text):
793
+ # Run extract_info and get the "Condition" only
794
+ result = ner.extract_info(text)
795
+ conditions = result["Condition"]
796
+ return conditions
797
+
798
+
799
+
800
+ """# Enhanced Criteria Extraction and Matching
801
+
802
+ ## Description
803
+ This script utilizes spaCy for NLP processing to detect and map keywords related to clinical trial criteria. It includes updated mappings for statuses, age groups, gender, and trial phases. Using keyword and fuzzy matching, the script can accurately detect eligibility criteria for clinical trials based on text input.
804
+
805
+ ### Key Features
806
+ - **Model Loading**: Loads spaCy for text preprocessing and matching functions.
807
+ - **Keyword Mapping**: Direct and fuzzy matching for trial statuses, age groups, gender, and phases.
808
+ - **Age and Gender Detection**: Uses regex patterns to identify age ranges and gender in text.
809
+ - **Preprocessing**: Text is cleaned for uniform matching, supporting efficient keyword extraction.
810
+
811
+ ### Requirements
812
+ - **Libraries**: `spacy`, `re`, and `fuzzywuzzy` for text processing and similarity matching.
813
+ - **Criteria Check**: Maps text inputs to predefined categories for trial criteria, enhancing eligibility filtering.
814
+
815
+ """
816
+
817
+ # Load spaCy model
818
+ nlp = spacy.load("en_core_web_sm")
819
+
820
+ # Updated core keywords for filters
821
+ status_mapping = {
822
+ "Not yet recruiting": "NOT_YET_RECRUITING",
823
+ "Recruiting": "RECRUITING",
824
+ "Active, not recruiting": "ACTIVE",
825
+ "Completed": "COMPLETED",
826
+ "Terminated": "TERMINATED",
827
+ "Enrolling by invitation": "ENROLLING_BY_INVITATION",
828
+ "Suspended": "SUSPENDED",
829
+ "Withdrawn": "WITHDRAWN",
830
+ "Unknown": "UNKNOWN"
831
+ }
832
+
833
+ age_mapping = {
834
+ "Child (birth - 17)": "CHILD",
835
+ "Adult (18 - 64)": "ADULT",
836
+ "Older adult (65+)": "OLDER_ADULT"
837
+ }
838
+
839
+ sex_mapping = {
840
+ "All": "ALL",
841
+ "Female": "FEMALE",
842
+ "Male": "MALE"
843
+ }
844
+
845
+ phase_mapping = {
846
+ "Early Phase 1": "Early_Phase1",
847
+ "Phase 1": "PHASE1",
848
+ "Phase 2": "PHASE2",
849
+ "Phase 3": "PHASE3",
850
+ "Phase 4": "PHASE4",
851
+ "Not applicable": "NOT_APPLICABLE"
852
+ }
853
+
854
+ # Preprocessing text
855
+ def preprocess_text(text):
856
+ text = text.lower()
857
+ text = re.sub(r'\s+', ' ', text)
858
+ text = re.sub(r'[^\w\s]', '', text)
859
+ return text
860
+
861
+ # Keyword matching functions to return mapped values directly
862
+ def match_keywords(text, keyword_mapping):
863
+ matches = []
864
+ for key, value in keyword_mapping.items():
865
+ if key.lower() in text:
866
+ matches.append(value) # Return the mapped value directly
867
+ return matches
868
+
869
+ def fuzzy_match_keywords(text, keyword_mapping, threshold=80):
870
+ matches = []
871
+ for key, value in keyword_mapping.items():
872
+ best_match = process.extractOne(text, [key], scorer=fuzz.partial_ratio)
873
+ if best_match and best_match[1] >= threshold:
874
+ matches.append(value) # Return the mapped value directly
875
+ return matches
876
+
877
+ # Detect age ranges based on new mappings
878
+ def detect_age_ranges(text):
879
+ detected_ages = set()
880
+ if re.search(r'\bchild(ren)?\b|\bkid(s)?\b|\bteen(ager)?\b', text):
881
+ detected_ages.add("CHILD")
882
+ if re.search(r'\bolder adult(s)?\b|\b65 and older\b|\bover 65\b|\babove 65\b', text):
883
+ detected_ages.add("OLDER_ADULT")
884
+ elif re.search(r'\badult(s)?\b|\b18 to 65\b|\bbetween 18 and 65\b', text):
885
+ detected_ages.add("ADULT")
886
+ if "all ages" in text:
887
+ detected_ages.update(["CHILD", "ADULT", "OLDER_ADULT"])
888
+
889
+ # Match numeric age ranges and categorize accordingly
890
+ ages = re.findall(r'\b\d{1,2}\b', text)
891
+ for age in ages:
892
+ age = int(age)
893
+ if age < 18:
894
+ detected_ages.add("CHILD")
895
+ elif 19 <= age <= 64:
896
+ detected_ages.add("ADULT")
897
+ elif age > 64:
898
+ detected_ages.add("OLDER_ADULT")
899
+
900
+ return list(detected_ages)
901
+
902
+ # Detect gender with new mappings
903
+ def detect_gender(text):
904
+ detected_genders = []
905
+ if "female" in text:
906
+ detected_genders.append(sex_mapping["Female"])
907
+ if "male" in text:
908
+ detected_genders.append(sex_mapping["Male"])
909
+ if "all genders" in text or "all sexes" in text:
910
+ return sex_mapping["All"]
911
+ return detected_genders[0] if detected_genders else None
912
+
913
+ # Status matching
914
+ def match_status(text):
915
+ status_matches = match_keywords(text, status_mapping)
916
+ if not status_matches:
917
+ status_matches = fuzzy_match_keywords(text, status_mapping, threshold=80)
918
+ return status_matches
919
+
920
+ # Main function with improved matching logic
921
+ def extract_keywords_with_fuzzy_and_direct(text):
922
+ text = preprocess_text(text)
923
+ extracted_params = {
924
+ 'status': [],
925
+ 'age_ranges': [],
926
+ 'sex': None,
927
+ 'phases': [],
928
+ }
929
+
930
+ # Handle all-ages or all-phases cases
931
+ if "all ages" in text:
932
+ extracted_params['age_ranges'] = list(age_mapping.values())
933
+ if "all phases" in text:
934
+ extracted_params['phases'] = list(phase_mapping.values())
935
+
936
+ # Extract status
937
+ extracted_params['status'] = match_status(text)
938
+
939
+ # Extract age ranges
940
+ detected_ages = detect_age_ranges(text)
941
+ extracted_params['age_ranges'] = [value for key, value in age_mapping.items() if value in detected_ages]
942
+
943
+ # Extract gender
944
+ extracted_params['sex'] = detect_gender(text)
945
+
946
+ # Extract phases
947
+ if not extracted_params['phases']:
948
+ phase_matches = match_keywords(text, phase_mapping)
949
+ if not phase_matches:
950
+ phase_matches = fuzzy_match_keywords(text, phase_mapping)
951
+ extracted_params['phases'] = list(set(phase_matches))
952
+
953
+ # Remove "PHASE1" if "Early_Phase1" exists
954
+ if "Early_Phase1" in extracted_params['phases'] and "PHASE1" in extracted_params['phases']:
955
+ extracted_params['phases'].remove("PHASE1")
956
+
957
+ return extracted_params
958
+
959
+ # # Sample usage
960
+ # sample_texts = [
961
+ # "This study is for phase 1 and is curretnly not yet recurting",
962
+
963
+ # ]
964
+
965
+ # for text in sample_texts:
966
+ # extracted_params = extract_keywords_with_fuzzy_and_direct(text)
967
+ # print("Extracted Parameters:")
968
+ # print(extracted_params)
969
+ # print()
970
+ # Set up the Gradio interface
971
+
972
+ """# Clinical Criteria Conflict Detection
973
+
974
+ ## Description
975
+ This script uses Clinical BERT to detect conflicts between user-defined inclusion/exclusion criteria and clinical trial criteria. It leverages text embedding and cosine similarity to identify potential conflicts, particularly relevant in clinical trials for patient eligibility assessment.
976
+
977
+ ### Key Features
978
+ - **Model Loading**: Loads Bio_ClinicalBERT to create text embeddings for criteria comparison.
979
+ - **Data Cleaning**: Cleans criteria lists by removing special characters.
980
+ - **Conflict Detection**: Checks for conflicts between user and trial criteria, excluding age-based items, using cosine similarity for accuracy.
981
+
982
+ ### Requirements
983
+ - **Libraries**: `transformers`, `torch`, `sklearn`, and `re` for text processing and similarity calculations.
984
+ - **Criteria Check**: Prints detected conflicts with a similarity threshold of 0.85 to highlight potential eligibility mismatches.
985
+
986
+
987
+ """
988
+
989
+ from transformers import AutoTokenizer, AutoModel
990
+ import torch
991
+ from sklearn.metrics.pairwise import cosine_similarity
992
+ import re
993
+
994
+ # Load Clinical BERT model and tokenizer
995
+ tokenizer = AutoTokenizer.from_pretrained("emilyalsentzer/Bio_ClinicalBERT")
996
+ model = AutoModel.from_pretrained("emilyalsentzer/Bio_ClinicalBERT")
997
+
998
+ # Function to clean the list
999
+ def clean_list(criteria_list):
1000
+ pattern = r"[^a-zA-Z0-9\s?,.!-]"
1001
+ return [re.sub(pattern, '', item) for item in criteria_list]
1002
+
1003
+ # Function to embed text
1004
+ def embed_text(text):
1005
+ inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)
1006
+ with torch.no_grad():
1007
+ outputs = model(**inputs)
1008
+ embeddings = outputs.last_hidden_state.mean(dim=1).squeeze()
1009
+ return embeddings.numpy()
1010
+
1011
+ # Basic similarity function for simple comparison
1012
+ def calculate_similarity(item1, item2):
1013
+ item1_embedding = embed_text(item1)
1014
+ item2_embedding = embed_text(item2)
1015
+ similarity = cosine_similarity([item1_embedding], [item2_embedding])[0][0]
1016
+ return similarity
1017
+
1018
+ # Function to check conflict between user inclusion and trial exclusion criteria
1019
+ def check_inclusion_exclusion_conflict(user_inclusion, trial_exclusion):
1020
+ for user_item in user_inclusion:
1021
+ for trial_item in trial_exclusion:
1022
+ # Skip items containing 'age' or 'years old'
1023
+ if "age" in user_item.lower() or "years old" in user_item.lower():
1024
+ continue
1025
+ similarity = calculate_similarity(user_item, trial_item)
1026
+ if similarity > 0.85: # Using a basic threshold to decide a conflict
1027
+ print(f"Conflict detected between User Inclusion '{user_item}' and Trial Exclusion '{trial_item}' | Similarity: {similarity:.2f}")
1028
+ return True
1029
+ return False
1030
+
1031
+ # Function to check conflict between user exclusion and trial inclusion criteria
1032
+ def check_exclusion_inclusion_conflict(user_exclusion, trial_inclusion):
1033
+ for user_item in user_exclusion:
1034
+ for trial_item in trial_inclusion:
1035
+ # Skip items containing 'age' or 'years old'
1036
+ if "age" in user_item.lower() or "years old" in user_item.lower():
1037
+ continue
1038
+ similarity = calculate_similarity(user_item, trial_item)
1039
+ if similarity > 0.85: # Using a basic threshold to decide a conflict
1040
+ print(f"Conflict detected between User Exclusion '{user_item}' and Trial Inclusion '{trial_item}' | Similarity: {similarity:.2f}")
1041
+ return True
1042
+ return False
1043
+
1044
+ # Example criteria
1045
+ user_inclusion = ["18 years old", "type 2 diabetes", "heart failure"]
1046
+ trial_inclusion = ['* ST- segment elevation patients.', '* Patients who are candidate for add-on treatment with Mineralocorticoid receptor antagonists (MRAs) to improve cardiac remodeling.', '* Age of 18 years to 80 years.', '* Written informed consent of the subject to participate in the study.']
1047
+ trial_exclusion = ['* Contraindications to Mineralocorticoid receptor antagonists (MRA) including: serum potassium \\>5.5 mEq/L at initiation; CrCl Ò‰€30 mL/minute; concomitant use of strong CYP3A4 inhibitors; concomitant use with potassium supplements or potassium-sparing diuretics.', '* Mild-to-severe valvular stenosis or severe (grade III/IV) valvular regurgitation', '* Pregnant or nursing women.', "* Non cardiac disorders associated with increased growth factor (e.g., HIV, Alzheimer, Crohn's disease, Cancer, glomerulonephritis, glomerulosclerosis, diabetic nephropathy, muscle atrophy, fibrotic conditions and burns).", '* Patients with chronic heart failure with reduced ejection fraction (LVEF \\<40%).']
1048
+ user_exclusion = ["smoker", "history of cancer", "don't want Mineralocorticoid", "does not want too sign or write any consent form"]
1049
+
1050
+ # Clean criteria lists
1051
+ trial_inclusion = clean_list(trial_inclusion)
1052
+ trial_exclusion = clean_list(trial_exclusion)
1053
+ user_inclusion = clean_list(user_inclusion)
1054
+ user_exclusion = clean_list(user_exclusion)
1055
+
1056
+ # Check for conflicts
1057
+ inclusion_exclusion_conflict = check_inclusion_exclusion_conflict(user_inclusion, trial_exclusion)
1058
+ exclusion_inclusion_conflict = check_exclusion_inclusion_conflict(user_exclusion, trial_inclusion)
1059
+
1060
+ # Output results
1061
+ print(f"Inclusion-Exclusion Conflict Detected: {inclusion_exclusion_conflict}")
1062
+ print(f"Exclusion-Inclusion Conflict Detected: {exclusion_inclusion_conflict}")
1063
+
1064
+ """# Clinical Criteria Similarity and Disease Detection
1065
+
1066
+ ## Description
1067
+ This script leverages Clinical BERT for text embeddings and BioBERT for disease recognition to assess similarities between user and trial criteria. By identifying disease terms and applying weight adjustments, it enhances the accuracy of similarity scores between inclusion and exclusion criteria.
1068
+
1069
+ ### Key Features
1070
+ - **Model Integration**: Uses Clinical BERT for embedding criteria and BioBERT for Named Entity Recognition (NER) to detect diseases.
1071
+ - **Disease Detection**: Identifies disease terms in criteria and applies a similarity weight boost when disease terms match.
1072
+ - **Similarity Calculation**: Calculates average similarity scores between inclusion and exclusion criteria with a weight adjustment for disease matches.
1073
+
1074
+ ### Requirements
1075
+ - **Libraries**: `transformers`, `torch`, `sklearn`, and `re` for text processing, embedding, and similarity calculations.
1076
+ - **Enhanced Criteria Check**: Displays similarity scores and highlights disease term matches to aid in clinical eligibility assessment.
1077
+
1078
+ # Clinical Trial Evaluation and Conflict Detection
1079
+
1080
+ ## Description
1081
+ This script evaluates clinical trials by checking for conflicts and calculating similarity scores between user-defined criteria and trial criteria from a database. It combines Clinical BERT for text embeddings, BioBERT for disease recognition, and caching for faster similarity calculations.
1082
+
1083
+ ### Key Features
1084
+ - **Model Integration**: Uses Clinical BERT for embeddings and BioBERT for Named Entity Recognition to identify diseases.
1085
+ - **Conflict Detection**: Checks for conflicts between user inclusion/exclusion and trial inclusion/exclusion criteria.
1086
+ - **Disease Term Weighting**: Enhances similarity scores by applying a weight boost when disease terms match.
1087
+ - **Top Trial Recommendations**: Retrieves and sorts trials by similarity scores, recommending the top 10 most relevant trials.
1088
+
1089
+ ### Requirements
1090
+ - **Libraries**: `pandas`, `transformers`, `torch`, `sklearn`, `re`, and `ast` for text processing, data management, and similarity calculations.
1091
+ - **Efficient Processing**: Caches embeddings for quicker similarity calculations, making it suitable for large databases.
1092
+ """
1093
+
1094
+ import pandas as pd
1095
+ from transformers import AutoTokenizer, AutoModel, pipeline
1096
+ from sklearn.metrics.pairwise import cosine_similarity
1097
+ import re
1098
+ import ast
1099
+ import json
1100
+ import torch
1101
+ from ast import literal_eval
1102
+
1103
+ # Load Clinical BERT model and BioBERT NER pipeline
1104
+ clinical_tokenizer = AutoTokenizer.from_pretrained("emilyalsentzer/Bio_ClinicalBERT")
1105
+ clinical_model = AutoModel.from_pretrained("emilyalsentzer/Bio_ClinicalBERT")
1106
+ disease_pipeline = pipeline("ner", model="alvaroalon2/biobert_diseases_ner", tokenizer="alvaroalon2/biobert_diseases_ner")
1107
+
1108
+ def clean_list(criteria_list):
1109
+ # Keep medically relevant symbols and remove irrelevant ones
1110
+ pattern = r"[^a-zA-Z0-9\s()/%:+-.,]"
1111
+ return [re.sub(pattern, '', str(item)) for item in criteria_list if isinstance(item, str)]
1112
+
1113
+ # Function to parse JSON string embeddings from the DataFrame
1114
+ def parse_criteria(criteria_str):
1115
+ try:
1116
+ # Try parsing as JSON first
1117
+ return clean_list(json.loads(criteria_str))
1118
+ except (json.JSONDecodeError, TypeError):
1119
+ try:
1120
+ # Try evaluating Python-style list strings
1121
+ return clean_list(literal_eval(criteria_str))
1122
+ except (ValueError, SyntaxError):
1123
+ # Fallback to manual splitting
1124
+ return clean_list(criteria_str.split(','))
1125
+
1126
+ # Function to embed text in case embeddings are missing in the database
1127
+ def embed_text(text):
1128
+ inputs = clinical_tokenizer(text, return_tensors="pt", truncation=True, padding=True, max_length=512)
1129
+ with torch.no_grad():
1130
+ outputs = clinical_model(**inputs)
1131
+ # Use the [CLS] token embedding
1132
+ embeddings = outputs.last_hidden_state[:, 0, :].squeeze()
1133
+ return embeddings.numpy()
1134
+
1135
+ # Check conflict between user inclusion and trial exclusion
1136
+ def check_inclusion_exclusion_conflict(user_embeddings, trial_embeddings):
1137
+ for user_text, user_embedding in user_embeddings.items():
1138
+ for trial_text, trial_embedding in trial_embeddings.items():
1139
+ similarity = cosine_similarity([user_embedding], [trial_embedding])[0][0]
1140
+ if similarity > 0.90: # Conflict threshold
1141
+ print(f"Conflict detected: '{user_text}' vs '{trial_text}' | Similarity: {similarity:.2f}")
1142
+ return True
1143
+ return False
1144
+
1145
+ # Identify diseases and calculate similarity with weight boost
1146
+ def identify_disease_terms(criteria):
1147
+ disease_terms = set()
1148
+ for criterion in criteria:
1149
+ disease_entities = disease_pipeline(criterion)
1150
+ current_term = ""
1151
+ for entity in disease_entities:
1152
+ if entity['entity'] in ['B-DISEASE', 'I-DISEASE']:
1153
+ token = entity['word'].replace("##", "")
1154
+ if entity['entity'] == 'B-DISEASE':
1155
+ if current_term:
1156
+ disease_terms.add(current_term.strip())
1157
+ current_term = token
1158
+ else:
1159
+ current_term += token
1160
+ if current_term:
1161
+ disease_terms.add(current_term.strip())
1162
+ return disease_terms
1163
+
1164
+ def evaluate_trials(trial_data, user_inclusion, user_exclusion):
1165
+ top_trials = []
1166
+
1167
+ # Cache embeddings for user criteria
1168
+ user_inclusion_embeddings = {item: embed_text(item) for item in user_inclusion}
1169
+
1170
+ user_exclusion_embeddings = {item: embed_text(item) for item in user_exclusion}
1171
+
1172
+ # Identify disease terms from user criteria
1173
+ all_user_criteria = user_inclusion + user_exclusion
1174
+ disease_terms = identify_disease_terms(all_user_criteria)
1175
+
1176
+ for index, row in trial_data.iterrows():
1177
+ try:
1178
+
1179
+ # Parse trial inclusion and exclusion criteria
1180
+ trial_inclusion = parse_criteria(row['Inclusion']) if isinstance(row['Inclusion'], str) else []
1181
+ trial_exclusion = parse_criteria(row['Exclusion']) if isinstance(row['Exclusion'], str) else []
1182
+
1183
+
1184
+ # Embed trial criteria
1185
+ trial_inclusion_embeddings = {text: embed_text(text) for text in trial_inclusion}
1186
+ trial_exclusion_embeddings = {text: embed_text(text) for text in trial_exclusion}
1187
+
1188
+ # # Check conflicts
1189
+ conflict_with_exclusion = check_inclusion_exclusion_conflict(user_inclusion_embeddings, trial_exclusion_embeddings)
1190
+ conflict_with_inclusion = check_inclusion_exclusion_conflict(user_exclusion_embeddings, trial_inclusion_embeddings)
1191
+ if conflict_with_exclusion or conflict_with_inclusion:
1192
+ print(f"Conflict detected (Exclusion: {conflict_with_exclusion}, Inclusion: {conflict_with_inclusion}). Skipping trial.")
1193
+ continue
1194
+
1195
+ # Log similarities
1196
+ inclusion_scores = []
1197
+ exclusion_scores = []
1198
+
1199
+ # Calculate inclusion similarity
1200
+ for user_text, user_embedding in user_inclusion_embeddings.items():
1201
+ for trial_text, trial_embedding in trial_inclusion_embeddings.items():
1202
+ similarity = cosine_similarity([user_embedding], [trial_embedding])[0][0]
1203
+ if any(term in user_text.lower() and term in trial_text.lower() for term in disease_terms):
1204
+ similarity *= 1 # Weight boost for disease terms
1205
+ inclusion_scores.append((user_text, trial_text, similarity))
1206
+
1207
+ # Calculate exclusion similarity
1208
+ for user_text, user_embedding in user_exclusion_embeddings.items():
1209
+ for trial_text, trial_embedding in trial_exclusion_embeddings.items():
1210
+ similarity = cosine_similarity([user_embedding], [trial_embedding])[0][0]
1211
+ if any(term in user_text.lower() and term in trial_text.lower() for term in disease_terms):
1212
+ similarity *= 1 # Weight boost for disease terms
1213
+ exclusion_scores.append((user_text, trial_text, similarity))
1214
+
1215
+ # Calculate combined similarity
1216
+ inclusion_similarity = np.median([score[2] for score in inclusion_scores]) if inclusion_scores else 0
1217
+ exclusion_similarity = np.median([score[2] for score in exclusion_scores]) if exclusion_scores else 0
1218
+ combined_similarity = (inclusion_similarity + exclusion_similarity)
1219
+
1220
+ # Store trial details and similarity scores
1221
+ top_trials.append({
1222
+ 'NCT Number': row['NCT Number'],
1223
+ 'Study Title': row['Study Title'],
1224
+ 'Study URL': row['Study URL'],
1225
+ 'Combined Similarity': combined_similarity,
1226
+ 'Inclusion Scores': inclusion_scores,
1227
+ 'Exclusion Scores': exclusion_scores,
1228
+ 'Brief Summary': row['Brief Summary']
1229
+ })
1230
+ except Exception as e:
1231
+ print(f"Error processing trial index {index}, NCT Number: {row.get('NCT Number', 'Unknown')}: {e}")
1232
+
1233
+ # Sort and return top trials
1234
+ top_trials = sorted(top_trials, key=lambda x: x['Combined Similarity'], reverse=True)[:10]
1235
+
1236
+ return top_trials
1237
+
1238
+ import gradio as gr
1239
+ import pandas as pd
1240
+ import re
1241
+
1242
+ # Assuming `generate_output`, `query_data`, `extract_keywords_with_fuzzy_and_direct`, and `evaluate_trials` are defined as per your code above
1243
+
1244
+ # Combined function for Gradio
1245
+ def combined_gradio_function(user_input):
1246
+ # Step 1: Generate inclusion and exclusion criteria using the model
1247
+ criteria_output = generate_output(user_input, model,tokenizer)
1248
+
1249
+ # Step 2: Parse the inclusion and exclusion lists from the generated output
1250
+ inclusion_match = re.search(r"The inclusion list equals: \[(.*?)\]", criteria_output)
1251
+ exclusion_match = re.search(r"The exclusion list equals: \[(.*?)\]", criteria_output)
1252
+
1253
+ # Safely extract matches and convert them to lists if found
1254
+ inclusion_list = inclusion_match.group(1).split(", ") if inclusion_match else []
1255
+ exclusion_list = exclusion_match.group(1).split(", ") if exclusion_match else []
1256
+
1257
+ # Step 4: Query the database with extracted parameters to get the relevant subset
1258
+ queried_data = "something"
1259
+
1260
+
1261
+ # Step 5: Call evaluate_trials with queried_data and parsed criteria
1262
+ top_trials = evaluate_trials(queried_data, inclusion_list, exclusion_list)
1263
+
1264
+ # Format top trials for display
1265
+
1266
+ # Combine the criteria output and top trials into the final Gradio output
1267
+ return top_trials
1268
+
1269
+ def get_highest_similarity_per_trial(top_trials):
1270
+ """
1271
+ Find the highest similarity for each user criterion for each trial in top_trials.
1272
+
1273
+ Args:
1274
+ top_trials (list): A list of trial dictionaries, each containing 'Inclusion Scores' and 'Exclusion Scores'.
1275
+
1276
+ Returns:
1277
+ tuple: Two dictionaries:
1278
+ - trial_highest_scores_inclusion: Mapping trial IDs to highest inclusion similarity scores for each user criterion.
1279
+ - trial_highest_scores_exclusion: Mapping trial IDs to highest exclusion similarity scores for each user criterion.
1280
+ """
1281
+ trial_highest_scores_inclusion = {}
1282
+ trial_highest_scores_exclusion = {}
1283
+
1284
+ # Process each trial
1285
+ for trial in top_trials:
1286
+ trial_id = trial.get('NCT Number', 'Unknown ID')
1287
+
1288
+ # Initialize dictionaries for this trial
1289
+ trial_highest_scores_inclusion[trial_id] = {}
1290
+ trial_highest_scores_exclusion[trial_id] = {}
1291
+
1292
+ # Process Inclusion Scores
1293
+ inclusion_scores = trial.get('Inclusion Scores', [])
1294
+ for user_inclusion, trial_inclusion, similarity in inclusion_scores:
1295
+ # Check if current similarity is the highest for this user inclusion
1296
+ if user_inclusion in trial_highest_scores_inclusion[trial_id]:
1297
+ if similarity > trial_highest_scores_inclusion[trial_id][user_inclusion][0]:
1298
+ trial_highest_scores_inclusion[trial_id][user_inclusion] = (similarity, trial_inclusion)
1299
+ else:
1300
+ # Initialize with the current similarity
1301
+ trial_highest_scores_inclusion[trial_id][user_inclusion] = (similarity, trial_inclusion)
1302
+
1303
+ # Process Exclusion Scores
1304
+ exclusion_scores = trial.get('Exclusion Scores', [])
1305
+ for user_exclusion, trial_exclusion, similarity in exclusion_scores:
1306
+ # Check if current similarity is the highest for this user exclusion
1307
+ if user_exclusion in trial_highest_scores_exclusion[trial_id]:
1308
+ if similarity > trial_highest_scores_exclusion[trial_id][user_exclusion][0]:
1309
+ trial_highest_scores_exclusion[trial_id][user_exclusion] = (similarity, trial_exclusion)
1310
+ else:
1311
+ # Initialize with the current similarity
1312
+ trial_highest_scores_exclusion[trial_id][user_exclusion] = (similarity, trial_exclusion)
1313
+ return trial_highest_scores_inclusion, trial_highest_scores_exclusion
1314
+
1315
+
1316
+ def get_highest_similarity_from_top_trials(top_trials):
1317
+ """
1318
+ Process the Inclusion and Exclusion Scores in top_trials to find the highest similarity scores
1319
+ along with the corresponding user criteria for each trial criterion.
1320
+
1321
+ Args:
1322
+ top_trials (list): A list of trial dictionaries, each containing 'Inclusion Scores' and 'Exclusion Scores'.
1323
+
1324
+ Returns:
1325
+ tuple: Two dictionaries:
1326
+ - trial_highest_scores_inclusion: Mapping trial IDs to highest inclusion similarity scores.
1327
+ - trial_highest_scores_exclusion: Mapping trial IDs to highest exclusion similarity scores.
1328
+ """
1329
+ trial_highest_scores_inclusion = {}
1330
+ trial_highest_scores_exclusion = {}
1331
+
1332
+ for trial in top_trials:
1333
+ trial_id = trial.get('NCT Number', 'Unknown ID')
1334
+
1335
+ # Process Inclusion Scores
1336
+ inclusion_scores = trial.get('Inclusion Scores', [])
1337
+ highest_inclusion_scores = {}
1338
+ for user_inclusion, trial_inclusion, similarity in inclusion_scores:
1339
+ if trial_inclusion in highest_inclusion_scores:
1340
+ # Update if current similarity is higher
1341
+ if similarity > highest_inclusion_scores[trial_inclusion][0]:
1342
+ highest_inclusion_scores[trial_inclusion] = (similarity, user_inclusion)
1343
+ else:
1344
+ # Add trial inclusion with the current similarity and user inclusion
1345
+ highest_inclusion_scores[trial_inclusion] = (similarity, user_inclusion)
1346
+ trial_highest_scores_inclusion[trial_id] = highest_inclusion_scores
1347
+
1348
+ # Process Exclusion Scores
1349
+ exclusion_scores = trial.get('Exclusion Scores', [])
1350
+ highest_exclusion_scores = {}
1351
+ for user_exclusion, trial_exclusion, similarity in exclusion_scores:
1352
+ if trial_exclusion in highest_exclusion_scores:
1353
+ # Update if current similarity is higher
1354
+ if similarity > highest_exclusion_scores[trial_exclusion][0]:
1355
+ highest_exclusion_scores[trial_exclusion] = (similarity, user_exclusion)
1356
+ else:
1357
+ # Add trial exclusion with the current similarity and user exclusion
1358
+ highest_exclusion_scores[trial_exclusion] = (similarity, user_exclusion)
1359
+ trial_highest_scores_exclusion[trial_id] = highest_exclusion_scores
1360
+
1361
+ return trial_highest_scores_inclusion, trial_highest_scores_exclusion
1362
+
1363
+ from pyvis.network import Network
1364
+ from math import radians, cos, sin
1365
+
1366
+ def add_newlines(data_dict):
1367
+ """
1368
+ Adds a newline (\n) after every 10 words in each key and the first index of the tuple in the dictionary.
1369
+
1370
+ Args:
1371
+ data_dict (dict): Dictionary with keys as strings and values as tuples.
1372
+
1373
+ Returns:
1374
+ dict: Updated dictionary with newlines added in keys and the first index of the tuple.
1375
+ """
1376
+ def add_newlines(text):
1377
+ words = text.split()
1378
+ result = []
1379
+ for i in range(0, len(words), 10):
1380
+ result.append(" ".join(words[i:i + 10]))
1381
+ return "\n".join(result)
1382
+
1383
+ # Create a new dictionary with updated keys and values
1384
+ updated_dict = {
1385
+ add_newlines(key): (value[0], add_newlines(value[1]))
1386
+ for key, value in data_dict.items()
1387
+ }
1388
+
1389
+ return updated_dict
1390
+
1391
+
1392
+ def create_two_graphs_from_trials(trial_highest_inclusion, trial_highest_exclusion, output_file):
1393
+ """
1394
+ Creates two linear graphs:
1395
+ - Graph 1 (User Conditions) on the left.
1396
+ - Graph 2 (Trial Conditions) on the right.
1397
+ Links nodes with edges labeled by similarity scores without overlapping edges.
1398
+ Inclusion nodes are green, and exclusion nodes are red.
1399
+
1400
+ Parameters:
1401
+ trial_highest_inclusion (dict): Inclusion trial data in the specified format.
1402
+ trial_highest_exclusion (dict): Exclusion trial data in the specified format.
1403
+ output_file (str): File path to save the output graph visualization.
1404
+ """
1405
+ print(f"Creating two graphs from trials. Total trials: {len(trial_highest_inclusion)}")
1406
+ print(f"Creating two graphs from trials. Total trials: {len(trial_highest_exclusion)}")
1407
+
1408
+ inclusion_avg_score = sum(score for score, _ in trial_highest_inclusion.values()) / len(trial_highest_inclusion)
1409
+ exclusion_avg_score = sum(score for score, _ in trial_highest_exclusion.values()) / len(trial_highest_exclusion)
1410
+ overall_avg_score = (inclusion_avg_score + exclusion_avg_score) / 2
1411
+ incl = inclusion_avg_score - exclusion_avg_score #WHAT IS THIS?
1412
+
1413
+
1414
+ # Initialize Pyvis Network
1415
+ net = Network(height="800px", width="100%", directed=False, notebook=True)
1416
+ net.toggle_physics(False)
1417
+ font_size = 60
1418
+ # Track unique nodes
1419
+ user_condition_nodes = {}
1420
+ trial_condition_nodes = {}
1421
+
1422
+ # Node vertical positioning
1423
+ user_y_start = 0
1424
+ trial_y_start = 0
1425
+ vertical_spacing = 500 # Space between nodes
1426
+
1427
+
1428
+ net.add_node(
1429
+ "Inclusion_Overall_Score",
1430
+ label="Inclusion Overall Score "+str(round(inclusion_avg_score, 2)), # Text for the title
1431
+ shape="box",
1432
+ color={"background": "white", "border": "white"},
1433
+ font={"size": 80, "color": "black", "bold": True},
1434
+ x= -1000 , # Center the title
1435
+ y=-500 # Place it above the graph
1436
+ )
1437
+
1438
+ net.add_node(
1439
+ "Exclusion_Overall_Score",
1440
+ label="Exclusion Overall Score "+str(round(exclusion_avg_score, 2)), # Text for the title
1441
+ shape="box",
1442
+ color={"background": "white", "border": "white"},
1443
+ font={"size": 80, "color": "black", "bold": True},
1444
+ x= 1000 , # Center the title
1445
+ y=-500 # Place it above the graph
1446
+ )
1447
+
1448
+
1449
+ net.add_node(
1450
+ "Overall_Score",
1451
+ label="Overall Score "+str(round((overall_avg_score), 2)), # Text for the title
1452
+ shape="box",
1453
+ color={"background": "white", "border": "white"},
1454
+ font={"size": 80, "color": "black", "bold": True},
1455
+ x= 0 , # Center the title
1456
+ y=-800 # Place it above the graph
1457
+ )
1458
+
1459
+ net.add_node(
1460
+ "Trial criteria",
1461
+ label="Trial criteria", # Text for the title
1462
+ shape="box",
1463
+ color={"background": "white", "border": "white"},
1464
+ font={"size": 80, "color": "black", "bold": True},
1465
+ x= -1500 , # Center the title
1466
+ y=-100 # Place it above the graph
1467
+ )
1468
+
1469
+ net.add_node(
1470
+ "Patient criteria",
1471
+ label="Patient criteria", # Text for the title
1472
+ shape="box",
1473
+ color={"background": "white", "border": "white"},
1474
+ font={"size": 80, "color": "black", "bold": True},
1475
+ x= 1500 , # Center the title
1476
+ y=-100 # Place it above the graph
1477
+ )
1478
+ # Add Inclusion User Conditions (Graph 1)
1479
+ for idx, (user_condition, (similarity_score, trial_condition)) in enumerate(trial_highest_inclusion.items()):
1480
+ # User Condition Node (Green)
1481
+ if user_condition not in user_condition_nodes:
1482
+ x = -1500 # Left side for User Conditions
1483
+ y = user_y_start + len(user_condition_nodes) * vertical_spacing + (user_condition.count('\n') * 20)
1484
+ user_condition_nodes[user_condition] = {"x": x, "y": y}
1485
+ net.add_node(user_condition, label=user_condition, shape="box", color={"border": "black", "background": "green"},title=user_condition, x=x, y=y, font={'color': 'white', 'size': font_size})
1486
+
1487
+ # Trial Condition Node (Green)
1488
+ if trial_condition not in trial_condition_nodes:
1489
+ x = 1500 # Right side for Trial Conditions
1490
+ y = trial_y_start + len(trial_condition_nodes) * vertical_spacing + (trial_condition.count('\n') * 25)
1491
+ trial_condition_nodes[trial_condition] = {"x": x, "y": y}
1492
+ net.add_node(trial_condition, label=trial_condition, shape="box", color={"border": "black", "background": "green"}, title=trial_condition,x=x, y=y, font={'color': 'white', 'size': font_size})
1493
+
1494
+ # Add edge (Green for inclusion)
1495
+ net.add_edge(
1496
+ user_condition,
1497
+ trial_condition,
1498
+ label=f"{similarity_score:.2f}",
1499
+ color="green",
1500
+ width=similarity_score * 10,
1501
+ arrows="to",
1502
+ font={"size": 40}, # Adjust label font size
1503
+ )
1504
+
1505
+ # Add Exclusion User Conditions (Graph 1)
1506
+ for idx, (user_condition, (similarity_score, trial_condition)) in enumerate(trial_highest_exclusion.items()):
1507
+ # User Condition Node (Red)
1508
+ if user_condition not in user_condition_nodes:
1509
+ x = -1500 # Left side for User Conditions
1510
+ y = user_y_start + len(user_condition_nodes) * vertical_spacing
1511
+ user_condition_nodes[user_condition] = {"x": x, "y": y}
1512
+ net.add_node(user_condition, label=user_condition, shape="box", color={"border": "black", "background": "red"}, title=user_condition,x=x, y=y, font={'size': font_size})
1513
+
1514
+ # Trial Condition Node (Red)
1515
+ if trial_condition not in trial_condition_nodes:
1516
+ x = 1500 # Right side for Trial Conditions
1517
+ y = trial_y_start + len(trial_condition_nodes) * vertical_spacing
1518
+ trial_condition_nodes[trial_condition] = {"x": x, "y": y}
1519
+ net.add_node(trial_condition, label=trial_condition, shape="box", color={"border": "black", "background": "red"}, title=trial_condition,x=x, y=y, font={'size': font_size})
1520
+
1521
+ # Add edge (Red for exclusion)
1522
+ net.add_edge(
1523
+ user_condition,
1524
+ trial_condition,
1525
+ label=f"{similarity_score:.2f}",
1526
+ color="red",
1527
+ width=similarity_score * 10,
1528
+ arrows="to",
1529
+ font={"size": 40}, # Adjust label font size
1530
+
1531
+ )
1532
+
1533
+ # Save the graph to an HTML file
1534
+ net.show(output_file)
1535
+ print(f"Graph saved as: {output_file}")
1536
+ return output_file
1537
+
1538
+ """# Dynamic Clinical Trial Data Extraction and Chat-Based Questioning
1539
+
1540
+ ## Description
1541
+ This script provides a Gradio-based interactive interface for extracting clinical trial filters, conditions, and generating relevant questions based on unmatched conditions. It allows users to input text, process filters, and engage in a dynamic question-answer session to refine eligibility criteria.
1542
+
1543
+ ### Key Features
1544
+ - **Filter and Condition Extraction**: Uses fuzzy and direct matching to identify trial criteria and conditions from input text.
1545
+ - **Clinical Trial Matching**: Queries and compares user data with clinical trial summaries to identify unmatched conditions.
1546
+ - **Dynamic Question Generation**: Generates questions based on unmatched conditions to enhance trial eligibility refinement.
1547
+ - **Interactive Chat**: Provides an interactive session, allowing users to respond to questions until all relevant information is extracted.
1548
+
1549
+ ### Requirements
1550
+ - **Libraries**: `gradio`, `random`, and custom functions for keyword extraction, condition comparison, and trial querying.
1551
+ - **State Management**: Manages chat history and extraction status, resetting as needed for new sessions.
1552
+
1553
+ """
1554
+
1555
+ import gradio as gr
1556
+ import random
1557
+ import numpy as np
1558
+ # Global variable for user input text
1559
+ user_input_text = ""
1560
+ queried_data = None
1561
+ global_exclusion_list = []
1562
+ global_inclusion_list = []
1563
+ global_top_trials = []
1564
+ global_condition_context_mapping = {}
1565
+
1566
+ def get_initial_state():
1567
+ print("Initializing state...")
1568
+ return {
1569
+ "click_count": 0,
1570
+ "chat_history": [],
1571
+ "trials_extracted": False,
1572
+ "questions": [],
1573
+ "filters": "",
1574
+ "conditions": "",
1575
+ }
1576
+
1577
+
1578
+ def extract_condition_with_context(condition, text):
1579
+ """
1580
+ Locate a condition in the text and print its surrounding context.
1581
+
1582
+ Args:
1583
+ condition (str): The condition to search for in the text.
1584
+ text (str): The text where the condition should be located.
1585
+
1586
+ Returns:
1587
+ dict: A dictionary containing the condition, its sentence, and surrounding context.
1588
+ """
1589
+ # Ensure the condition is valid
1590
+ if not condition or not isinstance(condition, str):
1591
+ print("Invalid condition provided.")
1592
+ return None
1593
+
1594
+ # Ensure the text is valid
1595
+ if not text or not isinstance(text, str):
1596
+ print("Invalid text provided.")
1597
+ return None
1598
+
1599
+ # Split the text into sentences
1600
+ sentences = text.split('.')
1601
+
1602
+ # Locate the condition and find surrounding sentences
1603
+ for i, sentence in enumerate(sentences):
1604
+ if condition.lower() in sentence.lower():
1605
+ # Get surrounding sentences
1606
+ before = sentences[i - 1] if i > 0 else None
1607
+ after = sentences[i + 1] if i < len(sentences) - 1 else None
1608
+ context = {
1609
+ "Condition": condition,
1610
+ "Before": before.strip() if before else None,
1611
+ "Sentence": sentence.strip(),
1612
+ "After": after.strip() if after else None,
1613
+ }
1614
+
1615
+ # Print the context
1616
+
1617
+ return context
1618
+
1619
+ # If the condition was not found in the text
1620
+ return None
1621
+
1622
+
1623
+ def generate_questions_from_top_trials(top_trials, text):
1624
+ """
1625
+ Generate and return a list of all questions from the brief summaries of the top trials.
1626
+
1627
+ Args:
1628
+ top_trials (list): List of top trial details with brief summaries.
1629
+ text (str): Input text to compare and generate questions.
1630
+ """
1631
+ print(f"Generating questions from top trials. Input text: {text}")
1632
+ print(f"Top Trials: {top_trials}")
1633
+
1634
+ all_questions = []
1635
+ max_length = 512 # Max token limit for truncation
1636
+
1637
+ for trial in top_trials:
1638
+ trial_id = trial['NCT Number']
1639
+ study_title = trial['Study Title']
1640
+ brief_summary = trial.get('Brief Summary')
1641
+
1642
+ # Ensure the brief summary is not None
1643
+ if not brief_summary or not isinstance(brief_summary, str):
1644
+ print(f"Skipping trial {trial_id} due to invalid or missing brief summary.")
1645
+ continue
1646
+
1647
+ # Truncate brief summary to fit within model constraints
1648
+ tokens = clinical_tokenizer.tokenize(brief_summary)
1649
+ print(f"Tokens before truncation: {len(tokens)}")
1650
+ if len(tokens) > max_length:
1651
+ print(f"Truncating brief summary for trial {trial_id}.")
1652
+ brief_summary = clinical_tokenizer.convert_tokens_to_string(tokens[:max_length])
1653
+
1654
+ # Generate questions from the brief summary
1655
+ try:
1656
+ questions = ner.compare_conditions(text, brief_summary)
1657
+ unmatched_conditions = questions.get("Unmatched Conditions in Text 2", [])
1658
+
1659
+ for condition in unmatched_conditions:
1660
+
1661
+ context = extract_condition_with_context(condition, brief_summary)
1662
+ if context:
1663
+ # Add to the dictionary
1664
+ global_condition_context_mapping[condition] = {
1665
+ "Before": context["Before"],
1666
+ "Sentence": context["Sentence"],
1667
+ "After": context["After"],
1668
+ }
1669
+ # Dynamic question generation
1670
+ dynamic_questions = [
1671
+ f"Does she have {condition}?" for condition in unmatched_conditions
1672
+ ]
1673
+ except Exception as e:
1674
+ print(f"Error generating questions for Trial ID {trial_id}: {e}")
1675
+
1676
+ # Append questions to the result list
1677
+ all_questions.append({
1678
+ 'Trial ID': trial_id,
1679
+ 'Study Title': study_title,
1680
+ 'Questions': dynamic_questions
1681
+ })
1682
+
1683
+ # Flatten the list of all questions
1684
+ flat_questions = [question for trial in all_questions for question in trial['Questions']]
1685
+
1686
+ return flat_questions
1687
+
1688
+ def generate_text_from_filters(extracted_filters, conditions, dynamic_questions):
1689
+ """
1690
+ Generates a descriptive text based on the extracted filters, conditions, and dynamic questions.
1691
+
1692
+ Parameters:
1693
+ extracted_filters (dict): A dictionary containing extracted filter data with keys like
1694
+ 'age_ranges', 'sex', 'status', and 'phases'.
1695
+ conditions (list): A list of conditions being studied.
1696
+ dynamic_questions (list): A list of dynamic questions to be answered.
1697
+
1698
+ Returns:
1699
+ str: A descriptive text summarizing the extracted filters, conditions, and dynamic questions.
1700
+ """
1701
+ parts = [] # List to hold the text segments
1702
+
1703
+ # Handle age ranges
1704
+ if extracted_filters.get('age_ranges'):
1705
+ age_text = f"You are looking for a trial that is focused on {', '.join(extracted_filters['age_ranges'])}."
1706
+ parts.append(age_text)
1707
+
1708
+ # Handle sex
1709
+ if extracted_filters.get('sex'):
1710
+ sex_text = f"You identify as {extracted_filters['sex']}."
1711
+ parts.append(sex_text)
1712
+
1713
+ # Handle status
1714
+ if extracted_filters.get('status'):
1715
+ status_text = f"Your trial status preferences include {', '.join(extracted_filters['status'])}."
1716
+ parts.append(status_text)
1717
+
1718
+ # Handle phases
1719
+ if extracted_filters.get('phases'):
1720
+ phases_text = f"You are interested in trials from the phases {', '.join(extracted_filters['phases'])}."
1721
+ parts.append(phases_text)
1722
+
1723
+ # Handle conditions
1724
+ if conditions:
1725
+ conditions_text = f"You are looking for a trial that is currently studying the following conditions: {', '.join(conditions)}."
1726
+ parts.append(conditions_text)
1727
+
1728
+ # Handle dynamic questions
1729
+ questions_text = f"You have {len(dynamic_questions)} questions to answer. Are you ready?"
1730
+ parts.append(questions_text)
1731
+
1732
+ # Combine all parts into a single text with new lines
1733
+ final_text = "\n".join(parts)
1734
+
1735
+ return final_text
1736
+
1737
+ def filter_similar_questions(questions, threshold=0.9):
1738
+ """
1739
+ Remove similar questions from the list based on Clinical BERT embeddings.
1740
+
1741
+ Args:
1742
+ questions (list): List of questions to process.
1743
+ threshold (float): Cosine similarity threshold above which questions are considered similar.
1744
+
1745
+ Returns:
1746
+ list: Filtered list of questions with duplicates removed.
1747
+ """
1748
+ print(f"Filtering similar questions. Total questions: {len(questions)}")
1749
+ if not questions:
1750
+ return []
1751
+
1752
+ # Generate embeddings for each question
1753
+ embeddings = []
1754
+ for question in questions:
1755
+ inputs = clinical_tokenizer(question, return_tensors="pt", truncation=True, padding=True, max_length=512)
1756
+ with torch.no_grad():
1757
+ outputs = clinical_model(**inputs)
1758
+ embeddings.append(outputs.last_hidden_state.mean(dim=1).squeeze().numpy())
1759
+
1760
+ # Convert embeddings to a NumPy array
1761
+ embeddings = np.array(embeddings)
1762
+ print(f"Generated embeddings for questions.")
1763
+
1764
+ # Pairwise similarity matrix
1765
+ similarity_matrix = cosine_similarity(embeddings)
1766
+ print(f"Similarity matrix computed.")
1767
+
1768
+ # Keep track of indices to retain
1769
+ retain_indices = set(range(len(questions)))
1770
+
1771
+ for i in range(len(questions)):
1772
+ if i not in retain_indices:
1773
+ continue
1774
+ for j in range(i + 1, len(questions)):
1775
+ if j in retain_indices and similarity_matrix[i][j] > threshold:
1776
+ retain_indices.discard(j) # Remove similar question
1777
+
1778
+ # Return filtered questions
1779
+ filtered_questions = [questions[i] for i in sorted(retain_indices)]
1780
+ return filtered_questions
1781
+
1782
+ def extract_filters_conditions_and_questions(text):
1783
+ extracted_filters = extract_keywords_with_fuzzy_and_direct(text)
1784
+ queried_data = query_data(extracted_filters,text)
1785
+
1786
+ Brief_Summary = queried_data['Brief Summary'].tolist()
1787
+
1788
+ conditions = extract_conditions(text)
1789
+
1790
+ return extracted_filters, conditions, Brief_Summary, queried_data
1791
+
1792
+ def recommendation_function_creation(inclusion_list, exclusion_list, queried_data):
1793
+ top_trials = evaluate_trials(queried_data, inclusion_list, exclusion_list)
1794
+
1795
+ return top_trials
1796
+
1797
+ def extract_data(text, state):
1798
+ global user_input_text, queried_data, global_exclusion_list, global_inclusion_list
1799
+
1800
+ extracted_filters, conditions, clinical_trial_ids, queried_data = extract_filters_conditions_and_questions(text)
1801
+
1802
+
1803
+ if not clinical_trial_ids:
1804
+ state["trials_extracted"] = False
1805
+ return [(text, "No trials found. Please try again.")], "", "", "", state
1806
+
1807
+
1808
+ criteria_output = generate_output(text)
1809
+ inclusion_match = re.search(r"Inclusion: \[(.*?)\]", criteria_output)
1810
+ exclusion_match = re.search(r"Exclusion: \[(.*?)\]", criteria_output)
1811
+
1812
+ inclusion_list = inclusion_match.group(1).split(", ") if inclusion_match else []
1813
+ exclusion_list = exclusion_match.group(1).split(", ") if exclusion_match else []
1814
+ global_inclusion_list = inclusion_list
1815
+ global_exclusion_list = exclusion_list
1816
+
1817
+ top_trials = recommendation_function_creation(inclusion_list, exclusion_list,queried_data)
1818
+
1819
+ dynamic_questions = generate_questions_from_top_trials(top_trials, text)
1820
+
1821
+ dynamic_questions = list(dict.fromkeys(dynamic_questions))
1822
+
1823
+ dynamic_questions = filter_similar_questions(dynamic_questions)
1824
+
1825
+ user_info = generate_text_from_filters(extracted_filters,conditions,dynamic_questions)
1826
+ print(f"Questions after filtering: {dynamic_questions}")
1827
+ state["trials_extracted"] = True
1828
+ state["filters"] = extracted_filters
1829
+ state["conditions"] = conditions
1830
+ state["questions"] = dynamic_questions
1831
+ # If questions exist, save chat history and user input text
1832
+ if dynamic_questions:
1833
+ state["chat_history"].append((text, user_info))
1834
+ if not dynamic_questions:
1835
+ state["chat_history"].append((text, "Trials extracted. No questions need to be asked."))
1836
+
1837
+ user_input_text = " ".join([entry[0] for entry in state["chat_history"]])
1838
+
1839
+ return state["chat_history"], extracted_filters, conditions, dynamic_questions, state
1840
+
1841
+
1842
+ # Function to handle chat based on extracted questions
1843
+ def handle_chat(text, state):
1844
+ global user_input_text, global_inclusion_list, global_exclusion_list
1845
+ if state["click_count"] < len(state["questions"]):
1846
+ # Get the current question and extract condition
1847
+ current_question = state["questions"][state["click_count"]]
1848
+ condition = current_question.replace("Does he have ", "").strip("?") # Extract condition
1849
+
1850
+ # Format response based on user's input ("yes" or "no")
1851
+ response = text.strip().lower()
1852
+ if response == "yes":
1853
+ # Check if the condition exists in the condition_context_mapping dictionary
1854
+ if condition in global_condition_context_mapping:
1855
+ # Add the corresponding sentence to the global_inclusion_list
1856
+ global_inclusion_list.append(f"the patient agreed to having this condition: {condition} from the following description {global_condition_context_mapping[condition]['Sentence']}")
1857
+ else:
1858
+ global_inclusion_list.append(condition) # Add to inclusion
1859
+ elif response == "no":
1860
+ if condition in global_condition_context_mapping:
1861
+ # Add the corresponding sentence to the global_inclusion_list
1862
+ global_exclusion_list.append(f"the patient did not agreed to having this condition: {condition} from the following description {global_condition_context_mapping[condition]['Sentence']}")
1863
+ else:
1864
+ global_exclusion_list.append(condition) # Add to inclusion
1865
+
1866
+ # Format response based on user's input ("yes" or "no")
1867
+ formatted_response = f" , {text} have {condition} "
1868
+
1869
+ # Append formatted response to chat history and user_input_text
1870
+ state["chat_history"].append((text, current_question))
1871
+ user_input_text += f"{formatted_response} " # Accumulate all responses
1872
+
1873
+ # Move to the next question
1874
+ state["click_count"] += 1
1875
+ else:
1876
+ # End of questions handling
1877
+ state["chat_history"].append((text, "Thank you for answering all questions. Moving to extraction."))
1878
+ state["questions"] = []
1879
+
1880
+ user_input_text = user_input_text.strip() # Remove any trailing space
1881
+ return state["chat_history"], state["filters"], state["conditions"], state["questions"], state
1882
+
1883
+ # Main function to determine whether to extract data or continue chat
1884
+ def toggle_function(text, state):
1885
+ if not state["trials_extracted"]:
1886
+ return extract_data(text, state)
1887
+ elif state["questions"]:
1888
+
1889
+ return handle_chat(text, state)
1890
+ else:
1891
+ state["chat_history"].append((text, "Session has ended."))
1892
+ global user_input_text
1893
+ user_input_text = " ".join([entry[1] for entry in state["chat_history"] if isinstance(entry[1], str)]).strip()
1894
+ return state["chat_history"], state["filters"], state["conditions"], state["questions"], state
1895
+
1896
+ import pandas as pd
1897
+ import gradio as gr
1898
+
1899
+ def display_recommendations():
1900
+ global user_input_text, queried_data, global_inclusion_list, global_exclusion_list, global_top_trials
1901
+ top_trials = recommendation_function_creation(global_inclusion_list, global_exclusion_list, queried_data)
1902
+ global_top_trials = top_trials
1903
+ print(f"Top trials: {top_trials}")
1904
+ print(f"inclusion list: {global_inclusion_list}")
1905
+ print(f"exclusion list: {global_exclusion_list}")
1906
+ # Example usage
1907
+ result_inclusion, result_exclusion = get_highest_similarity_from_top_trials(top_trials)
1908
+ print(f" the results are vewlwiwjfqowifejoirewoiurhgwegw")
1909
+ print(result_inclusion)
1910
+ print(result_exclusion)
1911
+ # Convert to DataFrame
1912
+ if isinstance(top_trials, list) and all(isinstance(trial, dict) for trial in top_trials):
1913
+ top_trials_df = pd.DataFrame(top_trials)
1914
+ else:
1915
+ raise ValueError("Top trials is not in the expected list of dictionaries format.")
1916
+
1917
+ # Generate graph files
1918
+ graph_files = []
1919
+ for idx, trial_id in enumerate(top_trials_df["NCT Number"]): # Assuming "NCT Number" exists
1920
+ file_name = f"trial_graph_{idx + 1}.html"
1921
+ create_two_graphs_from_trials(
1922
+ add_newlines(result_inclusion.get(trial_id, {})),
1923
+ add_newlines(result_exclusion.get(trial_id, {})),
1924
+ file_name
1925
+ )
1926
+ graph_files.append(file_name)
1927
+ print(f"inclusions: {global_inclusion_list}")
1928
+ print(f"exclusions: {global_exclusion_list}")
1929
+ # Return the DataFrame and list of files
1930
+ return top_trials_df, graph_files
1931
+
1932
+
1933
+
1934
+ import gradio as gr
1935
+ from transformers import AutoTokenizer, AutoModelForCausalLM, TextStreamer
1936
+ import re
1937
+
1938
+ # Load your fine-tuned model from Hugging Face
1939
+ model_name = "peachfawn/llama3ClinicalTrialFinalFineTuned"
1940
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
1941
+ model = AutoModelForCausalLM.from_pretrained(model_name).to("cuda") # Move to CUDA
1942
+
1943
+ # Define the Alpaca prompt format
1944
+ alpaca_prompt = """Below is a study objective that describes a clinical trial. Write an inclusion and exclusion criteria based on the given study objective.
1945
+
1946
+ ### Study Objective:
1947
+ {}
1948
+
1949
+ ### Response (Inclusion and Exclusion Criteria):
1950
+ {}"""
1951
+
1952
+ # Define a function for the Gradio interface
1953
+ def generate_output(user_input):
1954
+ # Prepare the input for the model
1955
+ inputs = tokenizer(
1956
+ [
1957
+ alpaca_prompt.format(
1958
+ user_input, # The input from Gradio
1959
+ "" # Leave the input section blank for now
1960
+ )
1961
+ ],
1962
+ return_tensors="pt"
1963
+ ).to("cuda")
1964
+
1965
+ # Use a text streamer to capture the output
1966
+ text_streamer = TextStreamer(tokenizer)
1967
+
1968
+ # Generate text with controlled randomness
1969
+ generated_output = model.generate(
1970
+ **inputs,
1971
+ streamer=text_streamer,
1972
+ max_new_tokens=800,
1973
+ do_sample=True, # Allow sampling for diversity
1974
+ top_k=50, # Consider the top 50 tokens for each step
1975
+ top_p=0.9, # Use nucleus sampling with a threshold of 90%
1976
+ temperature=0.7 # Temperature to control randomness
1977
+ )
1978
+
1979
+ # Decode the generated text
1980
+ output_text = tokenizer.decode(generated_output[0], skip_special_tokens=True)
1981
+
1982
+ return output_text
1983
+
1984
+ # Tab 1: First Gradio Interface (with button visibility control)
1985
+ summary_text = "Here are the top recommended clinical trials based on your input."
1986
+
1987
+ with gr.Blocks() as demo:
1988
+ with gr.Tab("Criteria Filters"):
1989
+ # Define input components
1990
+ condition = gr.Textbox(label="Condition")
1991
+ term = gr.Textbox(label="Term")
1992
+ treatment = gr.Textbox(label="Treatment")
1993
+ study_status = gr.CheckboxGroup(
1994
+ ["Not yet recruiting", "Recruiting", "Active, not recruiting", "Completed", "Terminated",
1995
+ "Other", "Enrolling by invitation", "Suspended", "Withdrawn", "Unknown"], label="Study Status Filters"
1996
+ )
1997
+ age_ranges = gr.CheckboxGroup(
1998
+ ["Child (birth - 17)", "Adult (18 - 64)", "Older adult (65+)"], label="Age Ranges"
1999
+ )
2000
+ sex = gr.Radio(["All", "Female", "Male"], label="Sex")
2001
+ study_phase = gr.CheckboxGroup(
2002
+ ["Early Phase 1", "Phase 1", "Phase 2", "Phase 3", "Phase 4", "Not applicable"], label="Study Phase"
2003
+ )
2004
+ study_type = gr.CheckboxGroup(
2005
+ ["Interventional", "Observational", "Patient registries", "Expanded access", "Individual patients",
2006
+ "Intermediate-size population", "Treatment IND/Protocol"], label="Study Type"
2007
+ )
2008
+ study_results = gr.CheckboxGroup(
2009
+ ["With results", "Without results"], label="Study Results"
2010
+ )
2011
+ study_documents = gr.CheckboxGroup(
2012
+ ["Study protocols", "Statistical analysis plans", "Informed consent forms"], label="Study Documents"
2013
+ )
2014
+ funder_type = gr.CheckboxGroup(
2015
+ ["NIH", "Other U.S. federal agency", "Industry", "All others (individuals, universities, organizations)"], label="Funder Type"
2016
+ )
2017
+ trials_per_batch = gr.Slider(1, 100, step=1, label="Number of Trials Per Batch")
2018
+
2019
+ # Output text box and buttons
2020
+ output = gr.Textbox(label="Output")
2021
+ first_button = gr.Button("Submit")
2022
+ second_button = gr.Button("Create Inclusion and Exclusion Criteria", visible=False)
2023
+
2024
+ # First button triggers processing and shows the second button
2025
+ first_button.click(
2026
+ fn=process_page,
2027
+ inputs=[condition, term, treatment, study_status, age_ranges, sex, study_phase, study_type, study_results, study_documents, funder_type, trials_per_batch],
2028
+ outputs=[output, second_button]
2029
+ )
2030
+
2031
+ # Second button for additional functionality
2032
+ second_button.click(fn=process_eligibility_criteria, outputs=output)
2033
+
2034
+ # Tab 2: Second Gradio Interface (with chatbot layout)
2035
+ with gr.Tab("Question Generation & Chatbot"):
2036
+ extracted_filters = gr.Textbox(label="Extracted Filters")
2037
+ extracted_conditions = gr.Textbox(label="Extracted Conditions")
2038
+ generated_questions = gr.Textbox(label="Generated Questions")
2039
+ chat_output = gr.Chatbot(label="Chat Output")
2040
+
2041
+ input_text = gr.Textbox(label="Enter Text")
2042
+ submit_button = gr.Button("Submit")
2043
+ reset_button = gr.Button("Reset All")
2044
+
2045
+ # Submit button logic to call toggle_function
2046
+ submit_button.click(
2047
+ fn=toggle_function,
2048
+ inputs=[input_text, gr.State(get_initial_state())],
2049
+ outputs=[chat_output, extracted_filters, extracted_conditions, generated_questions, gr.State(get_initial_state())]
2050
+ )
2051
+
2052
+ # Reset button logic to reset the state
2053
+
2054
+
2055
+ # Third tab to display recommendation results in a tabular format
2056
+ with gr.Tab("Recommendation Results") as recommendation_tab:
2057
+ # DataFrame for clinical trials
2058
+ recommendation_dataframe = gr.DataFrame(label="Clinical Trials Data")
2059
+ # File output for graph downloads
2060
+ recommendation_files = gr.File(
2061
+ label="Download Graph Files",
2062
+ file_types=[".html"],
2063
+ type="filepath" # Correct type parameter
2064
+ )
2065
+
2066
+ # Set up the display function for the "Recommendation Results" tab
2067
+ recommendation_tab.select(
2068
+ fn=display_recommendations,
2069
+ inputs=None,
2070
+ outputs=[recommendation_dataframe, recommendation_files]
2071
+ )
2072
+
2073
+ # Launch the app
2074
 
 
 
 
2075
 
2076
+ # Launch the combined interface
2077
+ demo.launch(debug=True)