aysan98 commited on
Commit
acb0f46
Β·
verified Β·
1 Parent(s): 0528d78

Upload 3 files

Browse files
Files changed (3) hide show
  1. README (1).md +59 -0
  2. app (3).py +1048 -0
  3. requirements (1).txt +7 -0
README (1).md ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: GOBLET Visualizer Agent
3
+ emoji:
4
+ colorFrom: blue
5
+ colorTo: indigo
6
+ sdk: gradio
7
+ sdk_version: "4.36.0"
8
+ app_file: app.py
9
+ pinned: false
10
+ license: mit
11
+ short_description: Clinical oncology plot generator for GOBLET trial datasets
12
+ ---
13
+
14
+ # GOBLET Visualizer Agent
15
+
16
+ A clinical oncology visualization tool that generates publication-quality plots from GOBLET trial datasets.
17
+
18
+ ## Supported Plots
19
+
20
+ - **Swimmer Plot** β€” Treatment duration, response markers, and endpoints per patient
21
+ - **Waterfall Plot (Evaluable)** β€” Best % change from baseline, evaluable patients only
22
+ - **Waterfall Plot (All Patients)** β€” Best % change from baseline, all patients
23
+ - **Spider Plot** β€” Target lesion size change over time
24
+
25
+ ## Accepted File Formats
26
+
27
+ - Excel: `.xlsx`, `.xls`
28
+ - CSV: `.csv`
29
+ - Archive: `.zip` (or `.rar` if rarfile is available)
30
+
31
+ ## Required Excel Sheets
32
+
33
+ The dataset must contain the following sheets:
34
+
35
+ | Sheet | Description |
36
+ |-------|-------------|
37
+ | `DM` | Demographics β€” includes `Cohort - Code`, `Subject Id` |
38
+ | `EX1`–`EX5` | Exposure / treatment administration |
39
+ | `ET` | End of treatment |
40
+ | `EOS` | End of study |
41
+ | `RS` | Response assessments (`OVRLDAT`, `OVRLRESP`) |
42
+ | `BLTUT` | Baseline target lesion measurements |
43
+ | `BLTUNT` | Baseline non-target lesion locations |
44
+ | `TUT` | Tumour assessment follow-up |
45
+
46
+ ## Usage
47
+
48
+ 1. Upload your Excel file (or a ZIP/RAR containing it)
49
+ 2. Enter the study title and cohort number
50
+ 3. Select which plots to generate
51
+ 4. Click **Generate Plots**
52
+ 5. Download individual plots from each tab
53
+
54
+ ## Notes
55
+
56
+ - Data is processed in-memory and never stored or transmitted
57
+ - Cohort filtering uses the `Cohort - Code` column in the `DM` sheet
58
+ - Patients without a treatment start date are classified as **Replaced**
59
+ - Patients with baseline measurement, treatment dates, and at least one assessment are classified as **Evaluable**
app (3).py ADDED
@@ -0,0 +1,1048 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ import numpy as np
4
+ import matplotlib
5
+ matplotlib.use('Agg')
6
+ import matplotlib.pyplot as plt
7
+ from matplotlib.patches import Rectangle, FancyBboxPatch, Patch
8
+ from datetime import datetime, timedelta
9
+ import zipfile
10
+ import os
11
+ import io
12
+ import tempfile
13
+ import shutil
14
+
15
+ # ─── Try importing rarfile ───────────────────────────────────────────────────
16
+ try:
17
+ import rarfile
18
+ HAS_RARFILE = True
19
+ except ImportError:
20
+ HAS_RARFILE = False
21
+
22
+ # ─── Colour palette ──────────────────────────────────────────────────────────
23
+ COLOR_TREATMENT = '#1f4788'
24
+ COLOR_OFF_TREATMENT = '#808080'
25
+ RESPONSE_COLORS = {'CR': '#00CC00', 'PR': '#5a9bd4', 'SD': '#f0c929', 'PD': '#c41e3a'}
26
+ WATERFALL_COLORS = {'CR': '#1f4788', 'PR': '#5a9bd4', 'SD': '#f0c929', 'PD': '#c41e3a'}
27
+
28
+
29
+ # ════════════════════════════════════════════════════════════════════════════
30
+ # FILE HANDLING
31
+ # ════════════════════════════════════════════════════════════════════════════
32
+
33
+ def extract_archive(path: str, dest_dir: str) -> list[str]:
34
+ """Extract zip/rar; return list of extracted file paths."""
35
+ extracted = []
36
+ ext = os.path.splitext(path)[1].lower()
37
+
38
+ if ext == '.zip':
39
+ with zipfile.ZipFile(path, 'r') as zf:
40
+ zf.extractall(dest_dir)
41
+ extracted = [os.path.join(dest_dir, n) for n in zf.namelist()]
42
+
43
+ elif ext == '.rar':
44
+ if HAS_RARFILE:
45
+ with rarfile.RarFile(path, 'r') as rf:
46
+ rf.extractall(dest_dir)
47
+ extracted = [os.path.join(dest_dir, n) for n in rf.namelist()]
48
+ else:
49
+ # Convert: rename to zip and try β€” works only for unencrypted RAR2
50
+ zip_path = path.replace('.rar', '_converted.zip')
51
+ shutil.copy(path, zip_path)
52
+ try:
53
+ with zipfile.ZipFile(zip_path, 'r') as zf:
54
+ zf.extractall(dest_dir)
55
+ extracted = [os.path.join(dest_dir, n) for n in zf.namelist()]
56
+ except Exception:
57
+ raise ValueError(
58
+ "RAR extraction failed. Please install the 'rarfile' package "
59
+ "or convert the archive to ZIP before uploading."
60
+ )
61
+
62
+ return extracted
63
+
64
+
65
+ def resolve_excel_file(upload_path: str) -> str:
66
+ """
67
+ Given an uploaded file path, return path to the Excel file to process.
68
+ Handles: .xlsx, .xls, .csv, .zip, .rar
69
+ """
70
+ tmp_dir = tempfile.mkdtemp()
71
+ ext = os.path.splitext(upload_path)[1].lower()
72
+
73
+ if ext in ('.xlsx', '.xls'):
74
+ return upload_path
75
+
76
+ if ext == '.csv':
77
+ # Wrap CSV into a dict so downstream code still works
78
+ return upload_path # handled separately in load_sheets
79
+
80
+ if ext in ('.zip', '.rar'):
81
+ files = extract_archive(upload_path, tmp_dir)
82
+ for f in files:
83
+ if os.path.splitext(f)[1].lower() in ('.xlsx', '.xls'):
84
+ return f
85
+ raise ValueError("No Excel file found inside the archive.")
86
+
87
+ raise ValueError(f"Unsupported file format: {ext}")
88
+
89
+
90
+ def load_sheets(excel_path: str, cohort_number: int) -> dict:
91
+ """Load all required sheets from the Excel file."""
92
+ SHEET_NAMES = ['DM', 'EX1', 'EX2', 'EX3', 'EX4', 'EX5',
93
+ 'ET', 'EOS', 'RS', 'ACCM', 'MH', 'BLTUT', 'BLTUNT', 'TUT']
94
+ sheets = {}
95
+ for sheet in SHEET_NAMES:
96
+ try:
97
+ df = pd.read_excel(excel_path, sheet_name=sheet)
98
+ sheets[sheet] = df
99
+ except Exception:
100
+ sheets[sheet] = pd.DataFrame()
101
+
102
+ # Clean duplicate header rows
103
+ for sheet_name in sheets:
104
+ df = sheets[sheet_name]
105
+ if 'Subject Id' in df.columns:
106
+ sheets[sheet_name] = df[df['Subject Id'] != 'SubjectId'].reset_index(drop=True)
107
+
108
+ # Filter to specified cohort
109
+ if 'Cohort - Code' in sheets['DM'].columns:
110
+ sheets['DM']['Cohort - Code'] = pd.to_numeric(sheets['DM']['Cohort - Code'], errors='coerce')
111
+ sheets['DM'] = sheets['DM'][sheets['DM']['Cohort - Code'] == cohort_number].reset_index(drop=True)
112
+
113
+ return sheets
114
+
115
+
116
+ # ════════════════════════════════════════════════════════════════════════════
117
+ # HELPER FUNCTIONS
118
+ # ═══════════════════════════════════════════════��════════════════════════════
119
+
120
+ def parse_date_safe(date_val):
121
+ if pd.isna(date_val) or str(date_val).upper() in ['', 'UNK', 'UNKNOWN']:
122
+ return pd.NaT
123
+ if isinstance(date_val, (datetime, pd.Timestamp)):
124
+ return pd.to_datetime(date_val)
125
+ try:
126
+ return pd.to_datetime(str(date_val))
127
+ except Exception:
128
+ return pd.NaT
129
+
130
+
131
+ def calculate_months(start_date, end_date):
132
+ if pd.isna(start_date) or pd.isna(end_date):
133
+ return 0
134
+ return ((end_date - start_date).days + 1) / 30.4
135
+
136
+
137
+ def get_trtsdt(subject_id, sheets):
138
+ all_dates = []
139
+ for ex in ['EX1', 'EX2', 'EX3', 'EX4', 'EX5']:
140
+ df = sheets.get(ex, pd.DataFrame())
141
+ if df.empty:
142
+ continue
143
+ pt = df[df['Subject Id'] == subject_id].copy()
144
+ if pt.empty:
145
+ continue
146
+ perf_col = next((c for c in pt.columns if 'PERF' in c.upper() or c.lower() in ['performed', 'done']), None)
147
+ if perf_col:
148
+ pt = pt[pt[perf_col].astype(str).str.lower() == 'yes']
149
+ if pt.empty:
150
+ continue
151
+ for date_col in ['Start date', 'STDAT', 'Date', 'Event date']:
152
+ if date_col in pt.columns:
153
+ d = parse_date_safe(pt[date_col].iloc[0])
154
+ if not pd.isna(d):
155
+ all_dates.append(d)
156
+ break
157
+ return min(all_dates) if all_dates else pd.NaT
158
+
159
+
160
+ def get_trtedt(subject_id, sheets):
161
+ all_dates = []
162
+ for ex in ['EX1', 'EX2', 'EX3', 'EX4', 'EX5']:
163
+ df = sheets.get(ex, pd.DataFrame())
164
+ if df.empty:
165
+ continue
166
+ pt = df[df['Subject Id'] == subject_id].copy()
167
+ if pt.empty:
168
+ continue
169
+ perf_col = next((c for c in pt.columns if 'PERF' in c.upper() or c.lower() in ['performed', 'done']), None)
170
+ if perf_col:
171
+ pt = pt[pt[perf_col].astype(str).str.lower() == 'yes']
172
+ if pt.empty:
173
+ continue
174
+ for date_col in ['Start date', 'STDAT', 'Date', 'Event date']:
175
+ if date_col in pt.columns:
176
+ for val in pt[date_col]:
177
+ d = parse_date_safe(val)
178
+ if not pd.isna(d):
179
+ all_dates.append(d)
180
+ break
181
+ return max(all_dates) if all_dates else pd.NaT
182
+
183
+
184
+ # ════════════════════════════════════════════════════════════════════════════
185
+ # PATIENT PROCESSING
186
+ # ════════════════════════════════════════════════════════════════════════════
187
+
188
+ def process_patients(sheets: dict) -> list:
189
+ swimmer_data = []
190
+
191
+ for _, dm_row in sheets['DM'].iterrows():
192
+ subject_id = dm_row['Subject Id']
193
+ if pd.isna(subject_id):
194
+ continue
195
+
196
+ start_date = get_trtsdt(subject_id, sheets)
197
+
198
+ if pd.isna(start_date):
199
+ pt_ex3 = sheets['EX3'][sheets['EX3']['Subject Id'] == subject_id]
200
+ for col in ['Date', 'Start date', 'Event date']:
201
+ if col in pt_ex3.columns and len(pt_ex3) > 0:
202
+ start_date = parse_date_safe(pt_ex3[col].iloc[0])
203
+ if not pd.isna(start_date):
204
+ break
205
+
206
+ if pd.isna(start_date):
207
+ pt_bltut = sheets['BLTUT'][sheets['BLTUT']['Subject Id'] == subject_id]
208
+ baseline_sum = np.nan
209
+ if len(pt_bltut) > 0 and 'Sum of diameters' in pt_bltut.columns:
210
+ baseline_sum = pd.to_numeric(pt_bltut['Sum of diameters'].iloc[0], errors='coerce')
211
+ swimmer_data.append({
212
+ 'patient_id': subject_id, 'treatment_months': 0, 'responses': [],
213
+ 'best_response': 'NE', 'still_on_treatment': False, 'endpoint_type': 'none',
214
+ 'category': 'Replaced', 'liver_mets': False, 'off_treatment_end': None,
215
+ 'baseline_sum': baseline_sum, 'baseline_date': pd.NaT,
216
+ 'nadir': np.nan, 'best_pct_change': np.nan,
217
+ 'trtsdt': pd.NaT, 'trtedt': pd.NaT
218
+ })
219
+ continue
220
+
221
+ end_date = get_trtedt(subject_id, sheets)
222
+
223
+ still_on_treatment = True
224
+ endpoint_type = 'none'
225
+
226
+ pt_et = sheets['ET'][sheets['ET']['Subject Id'] == subject_id]
227
+ date_col_et = 'Date of last treatment'
228
+ reason_col_et = 'Primary reason for treatment discontinuation'
229
+
230
+ if len(pt_et) > 0:
231
+ if date_col_et in pt_et.columns:
232
+ et_date_val = pt_et.iloc[0][date_col_et]
233
+ if not pd.isna(et_date_val) and str(et_date_val).strip() not in ['', 'nan', 'NaT']:
234
+ still_on_treatment = False
235
+ if reason_col_et in pt_et.columns:
236
+ reason_val = str(pt_et.iloc[0][reason_col_et]).strip()
237
+ if reason_val not in ['', 'nan', 'NaT']:
238
+ endpoint_type = reason_val
239
+ still_on_treatment = False
240
+
241
+ if pd.isna(end_date):
242
+ pt_eos = sheets['EOS'][sheets['EOS']['Subject Id'] == subject_id]
243
+ if len(pt_eos) > 0 and 'Date of study discontinuation' in pt_eos.columns:
244
+ end_date = parse_date_safe(pt_eos['Date of study discontinuation'].iloc[0])
245
+ if pd.isna(end_date):
246
+ end_date = start_date + timedelta(days=30)
247
+
248
+ treatment_months = calculate_months(start_date, end_date)
249
+
250
+ responses = []
251
+ pt_rs = sheets['RS'][sheets['RS']['Subject Id'] == subject_id]
252
+ ovrldat_col = next((c for c in pt_rs.columns if 'OVRLDAT' in c.upper() or c == 'Overall response date'), None)
253
+ ovrlresp_col = next((c for c in pt_rs.columns if 'OVRLRESP' in c.upper() or c == 'Overall response'), None)
254
+
255
+ for _, row in pt_rs.iterrows():
256
+ resp_date = parse_date_safe(row.get(ovrldat_col, pd.NaT)) if ovrldat_col else pd.NaT
257
+ if pd.isna(resp_date):
258
+ continue
259
+ months = calculate_months(start_date, resp_date)
260
+ resp_abbrev = None
261
+ if ovrlresp_col:
262
+ resp_val = str(row.get(ovrlresp_col, '')).upper().strip()
263
+ if 'COMPLETE' in resp_val or resp_val == 'CR':
264
+ resp_abbrev = 'CR'
265
+ elif 'PARTIAL' in resp_val or resp_val == 'PR':
266
+ resp_abbrev = 'PR'
267
+ elif 'STABLE' in resp_val or resp_val == 'SD':
268
+ resp_abbrev = 'SD'
269
+ elif 'PROGRESSIVE' in resp_val or resp_val == 'PD':
270
+ resp_abbrev = 'PD'
271
+ else:
272
+ code = str(row.get('Overall response - Code', ''))
273
+ resp_abbrev = {'1': 'CR', '2': 'PR', '3': 'SD', '4': 'PD'}.get(code, None)
274
+ if resp_abbrev:
275
+ responses.append({'months': months, 'response': resp_abbrev, 'date': resp_date})
276
+
277
+ # Liver mets
278
+ liver_mets = False
279
+ liver_keywords = ['liver', 'hepatic']
280
+ liver_exclusions = ['lymph', 'lym ', 'ln ', ' ln', 'hilus', 'hilum', 'periportal',
281
+ 'paraaort', 'interaort', 'coeliac', 'celiac', 'hilar', 'portal vein']
282
+
283
+ for df_name in ['BLTUT', 'BLTUNT']:
284
+ pt_df = sheets[df_name][sheets[df_name]['Subject Id'] == subject_id]
285
+ if pt_df.empty:
286
+ continue
287
+ loc_cols = [c for c in pt_df.columns
288
+ if c == 'Location' or (c.startswith('Location.') and c[9:].isdigit())]
289
+ for _, row in pt_df.iterrows():
290
+ for col in loc_cols:
291
+ val = str(row.get(col, '')).lower()
292
+ if any(kw in val for kw in liver_keywords):
293
+ if not any(excl in val for excl in liver_exclusions):
294
+ liver_mets = True
295
+ break
296
+ if liver_mets:
297
+ break
298
+
299
+ # Baseline tumor
300
+ pt_bltut = sheets['BLTUT'][sheets['BLTUT']['Subject Id'] == subject_id]
301
+ baseline_sum = nadir = best_pct_change = np.nan
302
+ baseline_date = pd.NaT
303
+
304
+ if len(pt_bltut) > 0 and 'Sum of diameters' in pt_bltut.columns:
305
+ baseline_sum = pd.to_numeric(pt_bltut['Sum of diameters'].iloc[0], errors='coerce')
306
+ for c in pt_bltut.columns:
307
+ if 'date of assessment' in c.lower():
308
+ baseline_date = parse_date_safe(pt_bltut[c].iloc[0])
309
+ if not pd.isna(baseline_date):
310
+ break
311
+ if not pd.isna(baseline_sum) and baseline_sum > 0:
312
+ pt_tut = sheets['TUT'][sheets['TUT']['Subject Id'] == subject_id]
313
+ if len(pt_tut) > 0 and 'Sum of diameters' in pt_tut.columns:
314
+ sums = pd.to_numeric(pt_tut['Sum of diameters'], errors='coerce').dropna()
315
+ if len(sums) > 0:
316
+ nadir = sums.min()
317
+ best_pct_change = ((nadir - baseline_sum) / baseline_sum) * 100
318
+
319
+ best_response = 'NE'
320
+ if responses:
321
+ rank = {'CR': 1, 'PR': 2, 'SD': 3, 'PD': 4}
322
+ best_response = min(responses, key=lambda x: rank.get(x['response'], 999))['response']
323
+
324
+ has_baseline = not pd.isna(baseline_sum) and baseline_sum > 0
325
+ has_treatment = not pd.isna(start_date)
326
+ has_assessment = len(responses) >= 1
327
+ category = 'Evaluable' if (has_baseline and has_treatment and has_assessment) else 'Replaced'
328
+
329
+ off_treatment_end = None
330
+ if not still_on_treatment and responses:
331
+ last_resp = max(responses, key=lambda x: x['date'])
332
+ last_months = calculate_months(start_date, last_resp['date'])
333
+ if last_months > treatment_months:
334
+ off_treatment_end = last_months + 1
335
+
336
+ swimmer_data.append({
337
+ 'patient_id': subject_id,
338
+ 'treatment_months': treatment_months,
339
+ 'responses': responses,
340
+ 'best_response': best_response,
341
+ 'still_on_treatment': still_on_treatment,
342
+ 'endpoint_type': endpoint_type,
343
+ 'category': category,
344
+ 'liver_mets': liver_mets,
345
+ 'off_treatment_end': off_treatment_end,
346
+ 'baseline_sum': baseline_sum,
347
+ 'baseline_date': baseline_date,
348
+ 'nadir': nadir,
349
+ 'best_pct_change': best_pct_change,
350
+ 'trtsdt': start_date,
351
+ 'trtedt': end_date,
352
+ })
353
+
354
+ return swimmer_data
355
+
356
+
357
+ def build_dataframes(swimmer_data: list):
358
+ response_counts = []
359
+ for patient in swimmer_data:
360
+ for resp in patient['responses']:
361
+ response_counts.append({
362
+ 'patient_id': patient['patient_id'],
363
+ 'months_from_start': resp['months'],
364
+ 'response': resp['response'],
365
+ })
366
+
367
+ response_df = pd.DataFrame(response_counts)
368
+ if len(response_df) > 0:
369
+ assessment_counts = response_df.groupby('patient_id').size().reset_index(name='n_assessments')
370
+ else:
371
+ assessment_counts = pd.DataFrame(columns=['patient_id', 'n_assessments'])
372
+
373
+ swimmer_df = pd.DataFrame(swimmer_data)
374
+ swimmer_df = swimmer_df.merge(assessment_counts, on='patient_id', how='left')
375
+ swimmer_df['n_assessments'] = swimmer_df['n_assessments'].fillna(0).astype(int)
376
+ swimmer_df = swimmer_df.sort_values(['n_assessments', 'patient_id'],
377
+ ascending=[False, True]).reset_index(drop=True)
378
+
379
+ # Special reorder: 16-006 after 18-006
380
+ idx_16 = swimmer_df[swimmer_df['patient_id'].astype(str).str.contains('16-006', na=False)].index
381
+ idx_18 = swimmer_df[swimmer_df['patient_id'].astype(str).str.contains('18-006', na=False)].index
382
+ if len(idx_16) > 0 and len(idx_18) > 0 and idx_16[0] < idx_18[0]:
383
+ row = swimmer_df.loc[idx_16[0]].copy()
384
+ swimmer_df = swimmer_df.drop(idx_16[0]).reset_index(drop=True)
385
+ new_idx = swimmer_df[swimmer_df['patient_id'].astype(str).str.contains('18-006', na=False)].index[0]
386
+ swimmer_df = pd.concat([swimmer_df.iloc[:new_idx+1],
387
+ pd.DataFrame([row]),
388
+ swimmer_df.iloc[new_idx+1:]]).reset_index(drop=True)
389
+
390
+ swimmer_df['y_pos'] = range(len(swimmer_df)-1, -1, -1)
391
+ return swimmer_df, response_df
392
+
393
+
394
+ # ════════════════════════════════════════════════════════════════════════════
395
+ # PLOT FUNCTIONS
396
+ # ════════════════════════════════════════════════════════════════════════════
397
+
398
+ def create_swimmer_plot(swimmer_df, response_df, study_title, cohort_number):
399
+ evaluable_count = (swimmer_df['category'] == 'Evaluable').sum()
400
+ replaced_count = (swimmer_df['category'] == 'Replaced').sum()
401
+
402
+ max_months = swimmer_df['treatment_months'].max()
403
+ if swimmer_df['off_treatment_end'].notna().any():
404
+ max_months = max(max_months, swimmer_df['off_treatment_end'].max())
405
+ max_months += 2
406
+
407
+ fig, ax = plt.subplots(figsize=(16, max(10, len(swimmer_df) * 0.38)))
408
+ fig.patch.set_facecolor('#f8f9fb')
409
+ ax.set_facecolor('#f8f9fb')
410
+
411
+ ax.set_xlim(-5, max_months)
412
+ ax.set_ylim(-0.5, len(swimmer_df) - 0.5)
413
+ ax.set_xlabel('Months', fontsize=12, fontweight='bold', color='#1a1a2e')
414
+ ax.set_title(
415
+ f'Swimmer Plot β€” {study_title} Cohort {cohort_number}\nAll Patients | PDAC',
416
+ fontsize=14, fontweight='bold', color='#1a1a2e', pad=20
417
+ )
418
+ ax.set_xticks(range(0, int(np.ceil(max_months)) + 1, 3))
419
+ ax.set_yticks(swimmer_df['y_pos'])
420
+ y_colors = ['#1a1a2e' if cat == 'Evaluable' else '#c41e3a' for cat in swimmer_df['category']]
421
+ ax.set_yticklabels(swimmer_df['patient_id'], fontsize=7, fontweight='bold')
422
+ for tick_label, color in zip(ax.get_yticklabels(), y_colors):
423
+ tick_label.set_color(color)
424
+ ax.grid(axis='x', color='#aab4be', linestyle='--', linewidth=0.5, alpha=0.4)
425
+
426
+ for _, row in swimmer_df.iterrows():
427
+ y = row['y_pos']
428
+ ax.add_patch(Rectangle((0, y - 0.28), row['treatment_months'], 0.56,
429
+ facecolor=COLOR_TREATMENT, edgecolor='none'))
430
+ if pd.notna(row['off_treatment_end']) and not row['still_on_treatment']:
431
+ ax.add_patch(Rectangle(
432
+ (row['treatment_months'], y - 0.28),
433
+ row['off_treatment_end'] - row['treatment_months'], 0.56,
434
+ facecolor=COLOR_OFF_TREATMENT, edgecolor='none'))
435
+ if row['still_on_treatment']:
436
+ ax.plot(row['treatment_months'], y, marker='>', markersize=16,
437
+ color=COLOR_TREATMENT, markerfacecolor=COLOR_TREATMENT,
438
+ markeredgewidth=0, zorder=5)
439
+
440
+ if len(response_df) > 0:
441
+ for _, resp_row in response_df.iterrows():
442
+ if resp_row['response'] in RESPONSE_COLORS:
443
+ y_pos = swimmer_df[swimmer_df['patient_id'] == resp_row['patient_id']]['y_pos'].values
444
+ if len(y_pos) > 0:
445
+ color = RESPONSE_COLORS[resp_row['response']]
446
+ marker = {'CR': 'o', 'PR': 's', 'SD': '^', 'PD': 'D'}[resp_row['response']]
447
+ size = {'CR': 11, 'PR': 10, 'SD': 11, 'PD': 9}[resp_row['response']]
448
+ ax.plot(resp_row['months_from_start'], y_pos[0], marker=marker,
449
+ markersize=size, markerfacecolor=color,
450
+ markeredgecolor=color, markeredgewidth=1.5, zorder=4)
451
+
452
+ for _, row in swimmer_df.iterrows():
453
+ y = row['y_pos']
454
+ endpoint_x = row['off_treatment_end'] if pd.notna(row['off_treatment_end']) else row['treatment_months']
455
+ if pd.notna(row['endpoint_type']):
456
+ if row['endpoint_type'] == 'death':
457
+ ax.plot(endpoint_x, y, marker='x', markersize=11, markeredgewidth=2.5,
458
+ color='black', markerfacecolor='none', linestyle='None', zorder=6)
459
+ elif row['endpoint_type'] == 'lost_to_followup':
460
+ ax.plot(endpoint_x, y, marker='x', markersize=11, markeredgewidth=2.5,
461
+ color='#c41e3a', markerfacecolor='none', linestyle='None', zorder=6)
462
+
463
+ if evaluable_count > 0 and replaced_count > 0:
464
+ separator_y = len(swimmer_df) - evaluable_count - 0.5
465
+ ax.axhline(y=separator_y, color='#1a1a2e', linewidth=2.5, zorder=1)
466
+
467
+ col_x = [-3.5, -1.5]
468
+ ax.text(col_x[0], len(swimmer_df) + 0.5, 'RECIST\nResponse',
469
+ ha='center', va='bottom', fontsize=8, fontweight='bold', color='#1a1a2e')
470
+ ax.text(col_x[1], len(swimmer_df) + 0.5, 'Liver\nmets',
471
+ ha='center', va='bottom', fontsize=8, fontweight='bold', color='#1a1a2e')
472
+
473
+ for _, row in swimmer_df.iterrows():
474
+ y = row['y_pos']
475
+ resp_color = RESPONSE_COLORS.get(row['best_response'], '#888')
476
+ ax.text(col_x[0], y, row['best_response'],
477
+ ha='center', va='center', fontsize=7, fontweight='bold', color=resp_color)
478
+ liver_text = 'Y' if row['liver_mets'] else 'N'
479
+ ax.text(col_x[1], y, liver_text, ha='center', va='center', fontsize=7)
480
+
481
+ legend_elements = [
482
+ Patch(color=COLOR_TREATMENT, label='On Treatment'),
483
+ Patch(color=COLOR_OFF_TREATMENT, label='Off Treatment / On Study Follow-Up'),
484
+ plt.Line2D([0],[0], marker='>', color='w', markerfacecolor=COLOR_TREATMENT,
485
+ markersize=16, label='Still on Treatment', linestyle='None', markeredgewidth=0),
486
+ plt.Line2D([0],[0], marker='o', color='w', markerfacecolor=RESPONSE_COLORS['CR'],
487
+ markeredgecolor=RESPONSE_COLORS['CR'], markersize=11, markeredgewidth=1.5, label='CR', linestyle='None'),
488
+ plt.Line2D([0],[0], marker='s', color='w', markerfacecolor=RESPONSE_COLORS['PR'],
489
+ markeredgecolor=RESPONSE_COLORS['PR'], markersize=10, markeredgewidth=1.5, label='PR', linestyle='None'),
490
+ plt.Line2D([0],[0], marker='^', color='w', markerfacecolor=RESPONSE_COLORS['SD'],
491
+ markeredgecolor=RESPONSE_COLORS['SD'], markersize=11, markeredgewidth=1.5, label='SD', linestyle='None'),
492
+ plt.Line2D([0],[0], marker='D', color='w', markerfacecolor=RESPONSE_COLORS['PD'],
493
+ markeredgecolor=RESPONSE_COLORS['PD'], markersize=9, markeredgewidth=1.5, label='PD', linestyle='None'),
494
+ plt.Line2D([0],[0], marker='x', color='black', markersize=11, markeredgewidth=2.5,
495
+ markerfacecolor='none', label='Death', linestyle='None'),
496
+ plt.Line2D([0],[0], marker='x', color='#c41e3a', markersize=11, markeredgewidth=2.5,
497
+ markerfacecolor='none', label='Withdraw Consent / Lost to Follow Up', linestyle='None'),
498
+ ]
499
+ legend = ax.legend(handles=legend_elements, loc='center left', bbox_to_anchor=(1.02, 0.5),
500
+ fontsize=9, title='Legend', title_fontsize=10,
501
+ frameon=True, fancybox=False, borderpad=1, labelspacing=1.2)
502
+ legend.get_frame().set_linewidth(1.5)
503
+ legend.get_frame().set_edgecolor('#1a1a2e')
504
+
505
+ summary_text = (f"Summary\n"
506
+ f"Evaluable {evaluable_count:2d}\n"
507
+ f"Replaced {replaced_count:2d}\n"
508
+ f"Total Enrolled {len(swimmer_df):2d}")
509
+ summary_x = max_months - 8.0
510
+ ax.add_patch(FancyBboxPatch((summary_x, 0.5), 7.5, 6.5,
511
+ boxstyle="round,pad=0.2",
512
+ facecolor='#1f4788', edgecolor='#1a1a2e',
513
+ linewidth=2, zorder=10))
514
+ ax.text(summary_x + 3.75, 4.0, summary_text,
515
+ ha='center', va='center', fontsize=13, fontweight='bold',
516
+ color='white', family='monospace', zorder=11)
517
+
518
+ plt.tight_layout()
519
+ plt.subplots_adjust(right=0.82)
520
+
521
+ buf = io.BytesIO()
522
+ plt.savefig(buf, format='png', dpi=180, bbox_inches='tight')
523
+ plt.close(fig)
524
+ buf.seek(0)
525
+ return buf
526
+
527
+
528
+ def create_waterfall_plot(data, title_suffix, study_title, cohort_number):
529
+ if len(data) == 0:
530
+ return None
531
+
532
+ fig, ax = plt.subplots(figsize=(max(12, len(data) * 0.35), 8))
533
+ fig.patch.set_facecolor('#f8f9fb')
534
+ ax.set_facecolor('#f8f9fb')
535
+
536
+ y_max = max(100, data['best_pct_change'].max() + 10)
537
+ y_min = min(-100, data['best_pct_change'].min() - 10)
538
+ ax.set_xlim(0.5, len(data) + 0.5)
539
+ ax.set_ylim(y_min, y_max)
540
+ ax.set_ylabel('Best % Change from Baseline in Target Lesion', fontsize=11,
541
+ fontweight='bold', color='#1a1a2e')
542
+
543
+ resp_counts = data['best_response'].value_counts()
544
+ title = (f"{study_title} | Cohort {cohort_number} | Waterfall Plot {title_suffix}\n"
545
+ f"N={len(data)} CR: {resp_counts.get('CR',0)} PR: {resp_counts.get('PR',0)}"
546
+ f" SD: {resp_counts.get('SD',0)} PD: {resp_counts.get('PD',0)}")
547
+ ax.set_title(title, fontsize=12, fontweight='bold', color='#1a1a2e', pad=20)
548
+
549
+ ax.axhline(y=0, color='#1a1a2e', linewidth=2, zorder=1)
550
+ ax.axhline(y=20, color='#1a1a2e', linewidth=1.5, linestyle='--', zorder=1)
551
+ ax.axhline(y=-30, color='#1a1a2e', linewidth=1.5, linestyle='--', zorder=1)
552
+ ax.grid(axis='y', color='#aab4be', linestyle='--', linewidth=0.5, alpha=0.4)
553
+
554
+ x_pos = np.arange(1, len(data) + 1)
555
+ colors = data['best_response'].map(WATERFALL_COLORS).fillna('#888')
556
+ ax.bar(x_pos, data['best_pct_change'], width=0.8,
557
+ color=colors, edgecolor='#1a1a2e', linewidth=1.2, zorder=2)
558
+ ax.set_xticks(x_pos)
559
+ ax.set_xticklabels(data['patient_id'], rotation=90, fontsize=7)
560
+
561
+ legend_elements = [Patch(facecolor=WATERFALL_COLORS[r], edgecolor='#1a1a2e', label=r)
562
+ for r in ['CR', 'PR', 'SD', 'PD']]
563
+ leg = ax.legend(handles=legend_elements, loc='upper right',
564
+ title='Best Response', title_fontsize=10, fontsize=9,
565
+ frameon=True, fancybox=False, edgecolor='#1a1a2e')
566
+ leg.get_frame().set_linewidth(1.5)
567
+
568
+ info_y = y_min - (y_max - y_min) * 0.15
569
+ ax.text(-2.0, info_y, 'Liver\nmets', ha='left', va='top', fontsize=8, fontweight='bold')
570
+ for i, (_, row) in enumerate(data.iterrows()):
571
+ ax.text(x_pos[i], info_y, 'Y' if row['liver_mets'] else 'N',
572
+ ha='center', va='center', fontsize=7)
573
+
574
+ plt.tight_layout()
575
+ buf = io.BytesIO()
576
+ plt.savefig(buf, format='png', dpi=180, bbox_inches='tight')
577
+ plt.close(fig)
578
+ buf.seek(0)
579
+ return buf
580
+
581
+
582
+ def create_spider_plot(swimmer_data, swimmer_df, sheets, study_title, cohort_number):
583
+ cohort_ids = set(swimmer_df['patient_id'].unique())
584
+ spider_rows = []
585
+
586
+ for subject_id in cohort_ids:
587
+ pt_record = next((p for p in swimmer_data if p['patient_id'] == subject_id), None)
588
+ baseline_date = pt_record.get('baseline_date', pd.NaT) if pt_record else pd.NaT
589
+ baseline_sum = pt_record.get('baseline_sum', np.nan) if pt_record else np.nan
590
+
591
+ if pd.isna(baseline_sum) or baseline_sum == 0 or pd.isna(baseline_date):
592
+ continue
593
+
594
+ spider_rows.append({'patient_id': subject_id, 'months': 0, 'pct_change': 0})
595
+
596
+ pt_tut = sheets['TUT'][sheets['TUT']['Subject Id'] == subject_id]
597
+ tudat_col = next((c for c in pt_tut.columns if 'date of assessment' in c.lower()), None)
598
+ if not tudat_col:
599
+ tudat_col = next((c for c in pt_tut.columns if 'TUDAT' in c.upper()), None)
600
+
601
+ for _, row in pt_tut.iterrows():
602
+ current_sum = pd.to_numeric(row.get('Sum of diameters', np.nan), errors='coerce')
603
+ current_date = parse_date_safe(row.get(tudat_col, pd.NaT)) if tudat_col else pd.NaT
604
+ if pd.isna(current_sum) or pd.isna(current_date):
605
+ continue
606
+ months = ((current_date - baseline_date).days + 1) / 30.4
607
+ pct_change = ((current_sum - baseline_sum) / baseline_sum) * 100
608
+ spider_rows.append({'patient_id': subject_id, 'months': months, 'pct_change': pct_change})
609
+
610
+ if not spider_rows:
611
+ return None
612
+
613
+ spider_df = pd.DataFrame(spider_rows)
614
+ max_months_spider = spider_df['months'].max()
615
+ max_month_ceil = int(np.ceil(max_months_spider / 3) * 3)
616
+
617
+ fig, ax = plt.subplots(figsize=(10, 6))
618
+ fig.patch.set_facecolor('#f8f9fb')
619
+ ax.set_facecolor('#f8f9fb')
620
+
621
+ ax.set_xlim(0, max_month_ceil)
622
+ ax.set_ylim(-100, 100)
623
+ ax.set_xlabel('Months', fontsize=11, fontweight='bold', color='#1a1a2e')
624
+ ax.set_ylabel('Change from Baseline in Target Lesion, %', fontsize=11,
625
+ fontweight='bold', color='#1a1a2e')
626
+ ax.set_title(
627
+ f'{study_title} | Cohort {cohort_number} | Change in Target Lesion Size Over Time',
628
+ fontsize=12, fontweight='bold', color='#1a1a2e'
629
+ )
630
+ ax.set_xticks(range(0, max_month_ceil + 1, 3))
631
+ ax.set_yticks(range(-100, 101, 20))
632
+ ax.set_yticklabels([f'{y}%' for y in range(-100, 101, 20)])
633
+ ax.axhline(y=0, color='#1a1a2e', linewidth=1.5)
634
+ ax.axhline(y=-30, color='#1a1a2e', linewidth=1.5, linestyle='--')
635
+ ax.axhline(y=20, color='#1a1a2e', linewidth=1.5, linestyle='--')
636
+ ax.grid(True, color='#aab4be', linestyle='-', linewidth=0.5, alpha=0.3)
637
+
638
+ for pid in spider_df['patient_id'].unique():
639
+ pt_data = spider_df[spider_df['patient_id'] == pid].sort_values('months')
640
+ ax.plot(pt_data['months'], pt_data['pct_change'], color='#1f4788', linewidth=1.2, alpha=0.75)
641
+
642
+ ax.text(max_months_spider * 0.95, 25, '+20%: Cut-off for progressive disease',
643
+ ha='right', va='bottom', fontsize=9, color='#555')
644
+ ax.text(max_months_spider * 0.95, -35, '-30%: Cut-off for partial response',
645
+ ha='right', va='top', fontsize=9, color='#555')
646
+
647
+ plt.tight_layout()
648
+ buf = io.BytesIO()
649
+ plt.savefig(buf, format='png', dpi=180, bbox_inches='tight')
650
+ plt.close(fig)
651
+ buf.seek(0)
652
+ return buf
653
+
654
+
655
+ # ════════════════════════════════════════════════════════════════════════════
656
+ # MAIN PIPELINE
657
+ # ════════════════════════════════════════════════════════════════════════════
658
+
659
+ def run_pipeline(
660
+ file_obj,
661
+ study_title,
662
+ cohort_number,
663
+ make_swimmer,
664
+ make_waterfall_eval,
665
+ make_waterfall_all,
666
+ make_spider,
667
+ progress=gr.Progress(track_tqdm=True),
668
+ ):
669
+ if file_obj is None:
670
+ return [None] * 4 + ["Please upload a data file."]
671
+
672
+ if not any([make_swimmer, make_waterfall_eval, make_waterfall_all, make_spider]):
673
+ return [None] * 4 + ["Please select at least one plot to generate."]
674
+
675
+ study_title = study_title.strip() or "GOBLET"
676
+ cohort_number = int(cohort_number)
677
+
678
+ try:
679
+ progress(0.05, desc="Reading file...")
680
+ upload_path = file_obj.name if hasattr(file_obj, 'name') else str(file_obj)
681
+ excel_path = resolve_excel_file(upload_path)
682
+
683
+ progress(0.15, desc="Loading sheets...")
684
+ sheets = load_sheets(excel_path, cohort_number)
685
+
686
+ n_patients = len(sheets['DM'])
687
+ if n_patients == 0:
688
+ return [None]*4 + [f"No patients found for Cohort {cohort_number}. Check that the 'Cohort - Code' column exists and contains the value {cohort_number}."]
689
+
690
+ progress(0.30, desc=f"Processing {n_patients} patients...")
691
+ swimmer_data = process_patients(sheets)
692
+
693
+ progress(0.50, desc="Building data frames...")
694
+ swimmer_df, response_df = build_dataframes(swimmer_data)
695
+
696
+ out_swimmer = None
697
+ out_wf_eval = None
698
+ out_wf_all = None
699
+ out_spider = None
700
+
701
+ progress(0.60, desc="Generating swimmer plot...")
702
+ if make_swimmer:
703
+ buf = create_swimmer_plot(swimmer_df, response_df, study_title, cohort_number)
704
+ out_swimmer = _buf_to_tmp(buf, "swimmer.png")
705
+
706
+ progress(0.70, desc="Generating waterfall plots...")
707
+ waterfall_df = swimmer_df[
708
+ swimmer_df['baseline_sum'].notna() &
709
+ swimmer_df['nadir'].notna() &
710
+ (swimmer_df['baseline_sum'] != 0)
711
+ ].copy().sort_values('best_pct_change', ascending=False).reset_index(drop=True)
712
+
713
+ if make_waterfall_eval:
714
+ eval_data = waterfall_df[waterfall_df['category'] == 'Evaluable']
715
+ buf = create_waterfall_plot(eval_data, 'β€” Evaluable Patients', study_title, cohort_number)
716
+ if buf:
717
+ out_wf_eval = _buf_to_tmp(buf, "waterfall_evaluable.png")
718
+
719
+ if make_waterfall_all:
720
+ buf = create_waterfall_plot(waterfall_df, 'β€” All Patients', study_title, cohort_number)
721
+ if buf:
722
+ out_wf_all = _buf_to_tmp(buf, "waterfall_all.png")
723
+
724
+ progress(0.85, desc="Generating spider plot...")
725
+ if make_spider:
726
+ buf = create_spider_plot(swimmer_data, swimmer_df, sheets, study_title, cohort_number)
727
+ if buf:
728
+ out_spider = _buf_to_tmp(buf, "spider.png")
729
+
730
+ evaluable = (swimmer_df['category'] == 'Evaluable').sum()
731
+ replaced = (swimmer_df['category'] == 'Replaced').sum()
732
+ status = (
733
+ f"Done. Total patients: {len(swimmer_df)} | "
734
+ f"Evaluable: {evaluable} | Replaced: {replaced}"
735
+ )
736
+ progress(1.0, desc="Complete.")
737
+ return out_swimmer, out_wf_eval, out_wf_all, out_spider, status
738
+
739
+ except Exception as e:
740
+ import traceback
741
+ return [None]*4 + [f"Error: {str(e)}\n\n{traceback.format_exc()}"]
742
+
743
+
744
+ def _buf_to_tmp(buf: io.BytesIO, filename: str) -> str:
745
+ tmp = tempfile.NamedTemporaryFile(delete=False, suffix='.png')
746
+ tmp.write(buf.read())
747
+ tmp.flush()
748
+ tmp.close()
749
+ return tmp.name
750
+
751
+
752
+ # ════════════════════════════════════════════════════════════════════════════
753
+ # GRADIO UI
754
+ # ════════════════════════════════════════════════════════════════════════════
755
+
756
+ CSS = """
757
+ /* ── Root variables ─────────────────────────────── */
758
+ :root {
759
+ --clr-bg: #f0f4f8;
760
+ --clr-surface: #ffffff;
761
+ --clr-border: #c8d6e5;
762
+ --clr-primary: #1f4788;
763
+ --clr-accent: #2a7de1;
764
+ --clr-text: #1a1a2e;
765
+ --clr-muted: #5a6a7e;
766
+ --clr-success: #00875a;
767
+ --clr-danger: #c41e3a;
768
+ --radius: 10px;
769
+ --shadow: 0 2px 16px 0 rgba(31,71,136,0.10);
770
+ }
771
+
772
+ body, .gradio-container {
773
+ background: var(--clr-bg) !important;
774
+ font-family: 'IBM Plex Sans', 'Segoe UI', sans-serif !important;
775
+ }
776
+
777
+ /* ── Header ─────────────────────────────────────── */
778
+ .app-header {
779
+ background: linear-gradient(120deg, #1a2a4a 0%, #1f4788 60%, #2a7de1 100%);
780
+ border-radius: var(--radius);
781
+ padding: 36px 40px 28px;
782
+ margin-bottom: 28px;
783
+ box-shadow: var(--shadow);
784
+ position: relative;
785
+ overflow: hidden;
786
+ }
787
+ .app-header::before {
788
+ content: '';
789
+ position: absolute;
790
+ top: -40px; right: -40px;
791
+ width: 220px; height: 220px;
792
+ border-radius: 50%;
793
+ background: rgba(42,125,225,0.18);
794
+ pointer-events: none;
795
+ }
796
+ .app-header h1 {
797
+ color: #ffffff;
798
+ font-size: 1.9rem;
799
+ font-weight: 700;
800
+ letter-spacing: -0.5px;
801
+ margin: 0 0 4px;
802
+ }
803
+ .app-header p {
804
+ color: rgba(255,255,255,0.72);
805
+ font-size: 0.92rem;
806
+ margin: 0;
807
+ letter-spacing: 0.2px;
808
+ }
809
+ .app-header .tag {
810
+ display: inline-block;
811
+ background: rgba(255,255,255,0.15);
812
+ border: 1px solid rgba(255,255,255,0.3);
813
+ color: #fff;
814
+ font-size: 0.72rem;
815
+ font-weight: 600;
816
+ letter-spacing: 1.2px;
817
+ text-transform: uppercase;
818
+ padding: 3px 10px;
819
+ border-radius: 20px;
820
+ margin-bottom: 14px;
821
+ }
822
+
823
+ /* ── Panels ─────────────────────────────────────── */
824
+ .panel-card {
825
+ background: var(--clr-surface);
826
+ border: 1px solid var(--clr-border);
827
+ border-radius: var(--radius);
828
+ padding: 24px;
829
+ box-shadow: var(--shadow);
830
+ }
831
+ .section-label {
832
+ font-size: 0.72rem;
833
+ font-weight: 700;
834
+ letter-spacing: 1.4px;
835
+ text-transform: uppercase;
836
+ color: var(--clr-primary);
837
+ margin-bottom: 14px;
838
+ border-left: 3px solid var(--clr-accent);
839
+ padding-left: 8px;
840
+ }
841
+
842
+ /* ── Inputs ─────────────────────────────────────── */
843
+ label > span, .gr-form label span {
844
+ font-size: 0.82rem !important;
845
+ font-weight: 600 !important;
846
+ color: var(--clr-text) !important;
847
+ letter-spacing: 0.1px;
848
+ }
849
+ input[type="text"], input[type="number"] {
850
+ border: 1.5px solid var(--clr-border) !important;
851
+ border-radius: 7px !important;
852
+ font-size: 0.9rem !important;
853
+ background: #f8fafd !important;
854
+ transition: border-color 0.2s;
855
+ }
856
+ input[type="text"]:focus, input[type="number"]:focus {
857
+ border-color: var(--clr-accent) !important;
858
+ outline: none !important;
859
+ box-shadow: 0 0 0 3px rgba(42,125,225,0.12) !important;
860
+ }
861
+
862
+ /* ── File upload ─────────────────────────────────── */
863
+ .gr-file-upload {
864
+ border: 2px dashed var(--clr-border) !important;
865
+ border-radius: var(--radius) !important;
866
+ background: #f5f8fd !important;
867
+ transition: border-color 0.2s, background 0.2s;
868
+ }
869
+ .gr-file-upload:hover {
870
+ border-color: var(--clr-accent) !important;
871
+ background: #eef4ff !important;
872
+ }
873
+
874
+ /* ── Checkboxes ─────────────────────────────────── */
875
+ .gr-checkbox-group label {
876
+ font-size: 0.85rem !important;
877
+ color: var(--clr-text) !important;
878
+ }
879
+
880
+ /* ── Button ─────────────────────────────────────── */
881
+ button.primary, .gr-button-primary {
882
+ background: linear-gradient(135deg, #1f4788 0%, #2a7de1 100%) !important;
883
+ border: none !important;
884
+ border-radius: 8px !important;
885
+ color: #fff !important;
886
+ font-weight: 700 !important;
887
+ font-size: 0.92rem !important;
888
+ letter-spacing: 0.4px;
889
+ padding: 12px 28px !important;
890
+ box-shadow: 0 4px 14px rgba(31,71,136,0.25) !important;
891
+ transition: transform 0.15s, box-shadow 0.15s;
892
+ cursor: pointer;
893
+ }
894
+ button.primary:hover, .gr-button-primary:hover {
895
+ transform: translateY(-1px);
896
+ box-shadow: 0 6px 20px rgba(31,71,136,0.35) !important;
897
+ }
898
+
899
+ /* ── Status bar ─────────────────────────────────── */
900
+ .status-box textarea {
901
+ background: #f0f7ff !important;
902
+ border: 1.5px solid #b8d0f0 !important;
903
+ border-radius: 8px !important;
904
+ color: var(--clr-primary) !important;
905
+ font-size: 0.85rem !important;
906
+ font-family: 'IBM Plex Mono', monospace !important;
907
+ }
908
+
909
+ /* ── Image outputs ──────────────────────────────── */
910
+ .gr-image {
911
+ border-radius: var(--radius) !important;
912
+ border: 1px solid var(--clr-border) !important;
913
+ box-shadow: var(--shadow) !important;
914
+ overflow: hidden;
915
+ }
916
+
917
+ /* ── Tab labels ─────────────────────────────────── */
918
+ .tab-nav button {
919
+ font-size: 0.82rem !important;
920
+ font-weight: 600 !important;
921
+ letter-spacing: 0.3px;
922
+ color: var(--clr-muted) !important;
923
+ }
924
+ .tab-nav button.selected {
925
+ color: var(--clr-primary) !important;
926
+ border-bottom: 2.5px solid var(--clr-accent) !important;
927
+ }
928
+
929
+ /* ── Footer ─────────────────────────────────────── */
930
+ .app-footer {
931
+ text-align: center;
932
+ padding: 18px;
933
+ color: var(--clr-muted);
934
+ font-size: 0.78rem;
935
+ letter-spacing: 0.2px;
936
+ margin-top: 18px;
937
+ }
938
+ """
939
+
940
+ HEADER_HTML = """
941
+ <div class="app-header">
942
+ <div class="tag">Clinical Oncology Tooling</div>
943
+ <h1>GOBLET Visualizer Agent</h1>
944
+ <p>Upload your clinical trial dataset and generate publication-quality oncology plots instantly.</p>
945
+ </div>
946
+ """
947
+
948
+ FOOTER_HTML = """
949
+ <div class="app-footer">
950
+ GOBLET Visualizer Agent &nbsp;|&nbsp; Swimmer &middot; Waterfall &middot; Spider Plots &nbsp;|&nbsp;
951
+ Data is processed locally and never stored.
952
+ </div>
953
+ """
954
+
955
+ with gr.Blocks(css=CSS, title="GOBLET Visualizer Agent") as demo:
956
+
957
+ gr.HTML(HEADER_HTML)
958
+
959
+ with gr.Row():
960
+ # ── Left panel: inputs ────────────────────────────
961
+ with gr.Column(scale=1, min_width=300):
962
+ with gr.Group(elem_classes="panel-card"):
963
+ gr.HTML('<div class="section-label">Dataset Upload</div>')
964
+ file_input = gr.File(
965
+ label="Upload File",
966
+ file_types=[".xlsx", ".xls", ".csv", ".zip", ".rar"],
967
+ file_count="single",
968
+ )
969
+ gr.HTML(
970
+ '<p style="font-size:0.78rem;color:#5a6a7e;margin:6px 0 0;">'
971
+ 'Accepted formats: Excel (.xlsx/.xls), CSV, ZIP, RAR</p>'
972
+ )
973
+
974
+ with gr.Group(elem_classes="panel-card"):
975
+ gr.HTML('<div class="section-label">Study Parameters</div>')
976
+ study_title_input = gr.Textbox(
977
+ label="Study Title",
978
+ placeholder="e.g. GOBLET",
979
+ value="GOBLET",
980
+ )
981
+ cohort_input = gr.Number(
982
+ label="Cohort Number",
983
+ value=4,
984
+ minimum=1,
985
+ precision=0,
986
+ )
987
+
988
+ with gr.Group(elem_classes="panel-card"):
989
+ gr.HTML('<div class="section-label">Select Plots</div>')
990
+ plot_selector = gr.CheckboxGroup(
991
+ choices=[
992
+ "Swimmer Plot",
993
+ "Waterfall β€” Evaluable Patients",
994
+ "Waterfall β€” All Patients",
995
+ "Spider Plot",
996
+ ],
997
+ value=[
998
+ "Swimmer Plot",
999
+ "Waterfall β€” Evaluable Patients",
1000
+ "Waterfall β€” All Patients",
1001
+ "Spider Plot",
1002
+ ],
1003
+ label="",
1004
+ )
1005
+
1006
+ generate_btn = gr.Button("Generate Plots", variant="primary", size="lg")
1007
+
1008
+ status_box = gr.Textbox(
1009
+ label="Status",
1010
+ interactive=False,
1011
+ lines=2,
1012
+ elem_classes="status-box",
1013
+ )
1014
+
1015
+ # ── Right panel: outputs ──────────────────────────
1016
+ with gr.Column(scale=2):
1017
+ with gr.Tabs():
1018
+ with gr.Tab("Swimmer Plot"):
1019
+ swimmer_out = gr.Image(label="Swimmer Plot", type="filepath")
1020
+ with gr.Tab("Waterfall β€” Evaluable"):
1021
+ wf_eval_out = gr.Image(label="Waterfall (Evaluable)", type="filepath")
1022
+ with gr.Tab("Waterfall β€” All"):
1023
+ wf_all_out = gr.Image(label="Waterfall (All Patients)", type="filepath")
1024
+ with gr.Tab("Spider Plot"):
1025
+ spider_out = gr.Image(label="Spider Plot", type="filepath")
1026
+
1027
+ gr.HTML(FOOTER_HTML)
1028
+
1029
+ # ── Wire up ───────────────────────────────────────────
1030
+ def _run(file_obj, study_title, cohort_number, selected_plots):
1031
+ make_swimmer = "Swimmer Plot" in selected_plots
1032
+ make_wf_eval = "Waterfall β€” Evaluable Patients" in selected_plots
1033
+ make_wf_all = "Waterfall β€” All Patients" in selected_plots
1034
+ make_spider = "Spider Plot" in selected_plots
1035
+ return run_pipeline(
1036
+ file_obj, study_title, cohort_number,
1037
+ make_swimmer, make_wf_eval, make_wf_all, make_spider
1038
+ )
1039
+
1040
+ generate_btn.click(
1041
+ fn=_run,
1042
+ inputs=[file_input, study_title_input, cohort_input, plot_selector],
1043
+ outputs=[swimmer_out, wf_eval_out, wf_all_out, spider_out, status_box],
1044
+ )
1045
+
1046
+
1047
+ if __name__ == "__main__":
1048
+ demo.launch()
requirements (1).txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ gradio>=4.36.0
2
+ pandas>=2.0.0
3
+ numpy>=1.24.0
4
+ matplotlib>=3.7.0
5
+ openpyxl>=3.1.0
6
+ xlrd>=2.0.1
7
+ rarfile>=4.0