TomSmail commited on
Commit
ce70f59
1 Parent(s): 086f50a

feat: add user frontend

Browse files
Files changed (1) hide show
  1. app.py +185 -0
app.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from concrete.ml.deployment import FHEModelClient
3
+ from pathlib import Path
4
+ import numpy as np
5
+ import gradio as gr
6
+ import requests
7
+ from sklearn.preprocessing import OneHotEncoder
8
+
9
+ # Store the server's URL
10
+ SERVER_URL = "http://127.0.0.1:7860/"
11
+ CURRENT_DIR = Path(__file__).parent
12
+ DEPLOYMENT_DIR = CURRENT_DIR / "deployment_files"
13
+ KEYS_DIR = DEPLOYMENT_DIR / ".fhe_keys"
14
+ CLIENT_DIR = DEPLOYMENT_DIR / "client_dir"
15
+ SERVER_DIR = DEPLOYMENT_DIR / "server_dir"
16
+
17
+
18
+ USER_ID = "user_id"
19
+ EXAMPLE_CLINICAL_TRIAL_LINK = "https://www.trials4us.co.uk/ongoing-clinical-trials/recruiting-healthy-adults-c23026?_gl=1*1ysp815*_up*MQ..&gclid=Cj0KCQjwr9m3BhDHARIsANut04bHqi5zE3sjS3f8JK2WRN3YEgY4bTfWbvTdZTxkUTSISxXX5ZWL7qEaAowwEALw_wcB&gbraid=0AAAAAD3Qci2k_3IERmM6U1FGDuYVayZWH"
20
+
21
+
22
+
23
+
24
+ # Define possible categories for fields without predefined categories
25
+ additional_categories = {
26
+ "Gender": ["Male", "Female", "Other"],
27
+ "Ethnicity": ["White", "Black or African American", "Asian", "American Indian or Alaska Native", "Native Hawaiian or Other Pacific Islander", "Other"],
28
+ "Geographic_Location": ["North America", "South America", "Europe", "Asia", "Africa", "Australia", "Antarctica"],
29
+ "Smoking_Status": ["Never", "Former", "Current"],
30
+ "Diagnoses_ICD10": ["E11.9", "I10", "J45.909", "M54.5", "F32.9", "K21.9"],
31
+ "Medications": ["Metformin", "Lisinopril", "Atorvastatin", "Amlodipine", "Omeprazole", "Simvastatin", "Levothyroxine", "None"],
32
+ "Allergies": ["Penicillin", "Peanuts", "Shellfish", "Latex", "Bee stings", "None"],
33
+ "Previous_Treatments": ["Chemotherapy", "Radiation Therapy", "Surgery", "Physical Therapy", "Immunotherapy", "None"],
34
+ "Alcohol_Consumption": ["None", "Occasionally", "Regularly", "Heavy"],
35
+ "Exercise_Habits": ["Sedentary", "Light", "Moderate", "Active", "Very Active"],
36
+ "Diet": ["Omnivore", "Vegetarian", "Vegan", "Pescatarian", "Keto", "Mediterranean"],
37
+ "Functional_Status": ["Independent", "Assisted", "Dependent"],
38
+ "Previous_Trial_Participation": ["Yes", "No"]
39
+ }
40
+
41
+ # Define the input components for the form
42
+ age_input = gr.Slider(minimum=18, maximum=100, label="Age ", step=1)
43
+ gender_input = gr.Radio(choices=additional_categories["Gender"], label="Gender")
44
+ ethnicity_input = gr.Radio(choices=additional_categories["Ethnicity"], label="Ethnicity")
45
+ geographic_location_input = gr.Radio(choices=additional_categories["Geographic_Location"], label="Geographic Location")
46
+ diagnoses_icd10_input = gr.CheckboxGroup(choices=additional_categories["Diagnoses_ICD10"], label="Diagnoses (ICD-10)")
47
+ medications_input = gr.CheckboxGroup(choices=additional_categories["Medications"], label="Medications")
48
+ allergies_input = gr.CheckboxGroup(choices=additional_categories["Allergies"], label="Allergies")
49
+ previous_treatments_input = gr.CheckboxGroup(choices=additional_categories["Previous_Treatments"], label="Previous Treatments")
50
+ blood_glucose_level_input = gr.Slider(minimum=0, maximum=300, label="Blood Glucose Level", step=1)
51
+ blood_pressure_systolic_input = gr.Slider(minimum=80, maximum=200, label="Blood Pressure (Systolic)", step=1)
52
+ blood_pressure_diastolic_input = gr.Slider(minimum=40, maximum=120, label="Blood Pressure (Diastolic)", step=1)
53
+ bmi_input = gr.Slider(minimum=10, maximum=50, label="BMI ", step=1)
54
+ smoking_status_input = gr.Radio(choices=additional_categories["Smoking_Status"], label="Smoking Status")
55
+ alcohol_consumption_input = gr.Radio(choices=additional_categories["Alcohol_Consumption"], label="Alcohol Consumption")
56
+ exercise_habits_input = gr.Radio(choices=additional_categories["Exercise_Habits"], label="Exercise Habits")
57
+ diet_input = gr.Radio(choices=additional_categories["Diet"], label="Diet")
58
+ condition_severity_input = gr.Slider(minimum=1, maximum=10, label="Condition Severity", step=1)
59
+ functional_status_input = gr.Radio(choices=additional_categories["Functional_Status"], label="Functional Status")
60
+ previous_trial_participation_input = gr.Radio(choices=additional_categories["Previous_Trial_Participation"], label="Previous Trial Participation")
61
+
62
+
63
+ def encrypt_array(user_symptoms: np.ndarray, user_id: str) -> bytes:
64
+ """
65
+ Encrypt the user symptoms vector.
66
+
67
+ Args:
68
+ user_symptoms (np.ndarray): The vector of symptoms provided by the user.
69
+ user_id (str): The current user's ID.
70
+
71
+ Returns:
72
+ bytes: Encrypted and serialized symptoms.
73
+ """
74
+
75
+ # Retrieve the client API
76
+ client = FHEModelClient(path_dir=DEPLOYMENT_DIR, key_dir=KEYS_DIR / f"{user_id}")
77
+ client.load()
78
+
79
+ # Ensure the symptoms are properly formatted as an array
80
+ user_symptoms = np.array(user_symptoms).reshape(1, -1)
81
+
82
+ # Encrypt and serialize the symptoms
83
+ encrypted_quantized_user_symptoms = client.quantize_encrypt_serialize(user_symptoms)
84
+
85
+ # Ensure the encryption process returned bytes
86
+ assert isinstance(encrypted_quantized_user_symptoms, bytes)
87
+
88
+ # Save the encrypted data to a file (optional)
89
+ encrypted_input_path = KEYS_DIR / f"{user_id}/encrypted_input"
90
+ with encrypted_input_path.open("wb") as f:
91
+ f.write(encrypted_quantized_user_symptoms)
92
+
93
+ # Return the encrypted data
94
+ return encrypted_quantized_user_symptoms
95
+
96
+
97
+ def decrypt_result(encrypted_answer: bytes, user_id: str) -> bool:
98
+ """
99
+ Decrypt the encrypted result.
100
+
101
+ Args:
102
+ encrypted_answer (bytes): The encrypted result.
103
+ user_id (str): The current user's ID.
104
+
105
+ Returns:
106
+ bool: The decrypted result.
107
+ """
108
+
109
+ # Retrieve the client API
110
+ client = FHEModelClient(path_dir=DEPLOYMENT_DIR, key_dir=KEYS_DIR / f"{user_id}")
111
+ client.load()
112
+
113
+ # Decrypt the result
114
+ decrypted_result = client.decrypt_deserialize(encrypted_answer)
115
+
116
+ # Return the decrypted result
117
+ return decrypted_result
118
+
119
+
120
+
121
+ def encode_categorical_data(data):
122
+ categories = ["Gender", "Ethnicity", "Geographic_Location", "Smoking_Status", "Alcohol_Consumption", "Exercise_Habits", "Diet", "Functional_Status", "Previous_Trial_Participation"]
123
+ encoded_data = []
124
+ for i in range(len(categories)):
125
+ sub_cats = additional_categories[categories[i]]
126
+ if data[i] in sub_cats:
127
+ encoded_data.append(sub_cats.index(data[i]) + 1)
128
+ else:
129
+ encoded_data.append(0)
130
+
131
+ return encoded_data
132
+
133
+
134
+ def process_patient_data(age, gender, ethnicity, geographic_location, diagnoses_icd10, medications, allergies, previous_treatments, blood_glucose_level, blood_pressure_systolic, blood_pressure_diastolic, bmi, smoking_status, alcohol_consumption, exercise_habits, diet, condition_severity, functional_status, previous_trial_participation):
135
+
136
+ # Encode the data
137
+ categorical_data = [gender, ethnicity, geographic_location, smoking_status, alcohol_consumption, exercise_habits, diet, functional_status, previous_trial_participation]
138
+ print(f"Categorical data: {categorical_data}")
139
+ encoded_categorical_data = encode_categorical_data(categorical_data)
140
+ numerical_data = np.array([age, blood_glucose_level, blood_pressure_systolic, blood_pressure_diastolic, bmi, condition_severity])
141
+ print(f"Numerical data: {numerical_data}")
142
+ print(f"One-hot encoded data: {encoded_categorical_data}")
143
+ combined_data = np.hstack((numerical_data, encoded_categorical_data))
144
+ print(f"Combined data: {combined_data}")
145
+ encrypted_array = encrypt_array(combined_data, "user_id")
146
+
147
+ # Send the encrypted data to the server
148
+ response = requests.post(SERVER_URL, data=encrypted_array)
149
+
150
+ # Check if the data was sent successfully
151
+ if response.status_code == 200:
152
+ print("Data sent successfully.")
153
+ else:
154
+ print("Error sending data.")
155
+
156
+ # Decrypt the result
157
+ decrypted_result = decrypt_result(response.content, USER_ID)
158
+
159
+ # If the answer is True, return the link
160
+ if decrypted_result:
161
+ return (
162
+ f"Encrypted data: {encrypted_array}",
163
+ f"Decrypted result: {decrypted_result}",
164
+ f"You may now access the link to the [clinical trial]({EXAMPLE_CLINICAL_TRIAL_LINK})"
165
+ )
166
+ else:
167
+ return (
168
+ f"Encrypted data: {encrypted_array}",
169
+ f"Decrypted result: {decrypted_result}",
170
+ f"Unfortunately, there are no clinical trials available for the provided criteria."
171
+ )
172
+
173
+ # Create the Gradio interface
174
+ demo = gr.Interface(
175
+ fn=process_patient_data,
176
+ inputs=[
177
+ age_input, gender_input, ethnicity_input, geographic_location_input, diagnoses_icd10_input, medications_input, allergies_input, previous_treatments_input, blood_glucose_level_input, blood_pressure_systolic_input, blood_pressure_diastolic_input, bmi_input, smoking_status_input, alcohol_consumption_input, exercise_habits_input, diet_input, condition_severity_input, functional_status_input, previous_trial_participation_input
178
+ ],
179
+ outputs="text",
180
+ title="Patient Data Criteria Form",
181
+ description="Please fill in the criteria for the type of patients you are looking for."
182
+ )
183
+
184
+ # Launch the app
185
+ demo.launch()