desinez commited on
Commit
baacb24
·
1 Parent(s): 3cf2829

updating frontend

Browse files
Files changed (1) hide show
  1. frontend/app.py +136 -290
frontend/app.py CHANGED
@@ -1,5 +1,5 @@
1
  import dash
2
- from dash import dcc, html, Input, Output, State, dash_table
3
  import dash_bootstrap_components as dbc
4
  import pandas as pd
5
  import json
@@ -8,229 +8,158 @@ import io
8
  import os
9
 
10
  # --- IN-MEMORY BACKEND HOOKS ---
 
11
  from backend.main import storage
12
  from backend.PvDeepSetNet.src.DeepSets import run_prediction
13
 
14
- # Initialize App with basic styling and FontAwesome icons
15
  app = dash.Dash(
16
  __name__,
17
- external_stylesheets=[dbc.themes.FLATLY, dbc.icons.FONT_AWESOME],
18
  title="PvRecNet",
19
  suppress_callback_exceptions=True,
 
20
  requests_pathname_prefix="/",
21
  routes_pathname_prefix="/"
22
  )
23
 
24
- # --- BASE SIDEBAR CONTAINER STYLE ---
25
- SIDEBAR_STYLE = {
26
- "position": "fixed",
27
- "top": 0,
28
- "left": 0,
29
- "bottom": 0,
30
- "width": "20rem",
31
- "padding": "3rem 1.5rem",
32
- "zIndex": 100
33
- }
34
-
35
- CONTENT_STYLE = {
36
- "margin-left": "22rem",
37
- "margin-right": "2rem",
38
- "padding": "3rem 1rem",
39
- }
40
-
41
- # --- APPLICABLE COMPONENTS TEMPLATE ---
42
- sidebar = html.Div(
43
- [
44
- html.Div([
45
- html.H2("PvRecNet", className="display-6 font-weight-bold mb-0", style={"color": "#2dd4bf"}),
46
- html.P("Malaria Recurrence Platform", id="sidebar-subtitle", className="small mt-1"),
47
- ], className="mb-5"),
48
-
49
- html.Hr(style={"marginBottom": "2rem"}),
50
-
51
- dbc.Nav(
52
- [
53
- dbc.NavLink([html.I(className="fas fa-home me-3"), "Dashboard"], href="/", active="exact", className="py-3 px-4 mb-2 rounded"),
54
- dbc.NavLink([html.I(className="fas fa-book me-3"), "Guidelines"], href="/help", active="exact", className="py-3 px-4 mb-2 rounded"),
55
- ],
56
- vertical=True,
57
- pills=True,
58
- className="flex-column"
59
- ),
60
-
61
- # Theme Switch Component Setup
62
- html.Div([
63
- html.Hr(style={"marginBottom": "1.5rem"}),
64
- html.Label([html.I(className="fas fa-adjust me-2"), "Interface Theme"], id="theme-label", className="small d-block mb-2 font-weight-bold"),
65
- dbc.RadioItems(
66
- id="theme-toggle",
67
- options=[
68
- {"label": " Dark Mode", "value": "dark"},
69
- {"label": " Light Mode", "value": "light"},
70
- ],
71
- value="dark",
72
- inline=True
73
- )
74
- ], style={"position": "absolute", "bottom": "4rem", "left": "1.5rem", "width": "80%"}),
75
-
76
- html.Div(
77
- html.Small("System Context: Operational (2026)", id="sidebar-footer", className="text-muted"),
78
- style={"position": "absolute", "bottom": "1.5rem", "left": "1.5rem"}
79
- )
80
- ],
81
- id="sidebar-panel",
82
- style=SIDEBAR_STYLE,
83
- )
84
-
85
  app.layout = html.Div([
86
- dcc.Location(id='url', refresh=False),
87
- dcc.Store(id='theme-store', storage_type='session', data='dark'),
88
- sidebar,
89
  dcc.Store(id='dataset-id-store', storage_type='session'),
90
- html.Div(id='page-content', style=CONTENT_STYLE)
91
- ], id="main-container")
92
 
93
-
94
- # --- PAGE 1: ORIGINAL HELP & GUIDELINES PAGE ---
95
  def render_help_page():
96
  return dbc.Container([
97
- # Back Button
98
- dbc.Button("← Back to System", href="/", color="link", className="mt-4 p-0 text-decoration-none text-info"),
99
-
100
- html.Div([
101
- # Header Section
102
- html.Div([
103
- html.H1("System Guidelines & Documentation", className="display-5 text-primary"),
104
- html.P([
105
- "PvRecNet is a deep learning-based model for ",
106
- html.B(html.I("Plasmodium vivax")),
107
- " recurrence classification."
108
- ], className="lead"),
109
- ], className="mb-5"),
110
-
111
- # Visual Appeal: Use Cards for Sections
112
- dbc.Row([
113
- # Section: Description
114
- dbc.Col([
115
- html.H5("Model Description", className="text-info"),
116
- html.P([
117
- "Our architecture differentiates between ",
118
- html.B("Recrudescence, Relapse, and Reinfection"),
119
- ". It is trained on probabilistic outputs from ",
120
- html.A("Pv3Rs", href="https://github.com/aimeertaylor/Pv3Rs", target="_blank"),
121
- " to ensure robust genomic classification."
122
- ]),
123
- ], md=6),
124
 
125
- # Section: Data Requirements
126
- dbc.Col([
127
- html.H5("Data Requirements", className="text-info"),
128
- html.P("Your dataset must contain these exact columns:"),
129
  html.Div([
130
- dbc.Badge("patient_id", color="primary", className="me-1"),
131
- dbc.Badge("episode", color="primary", className="me-1"),
132
- dbc.Badge("marker", color="primary", className="me-1"),
133
- dbc.Badge("allele", color="primary", className="me-1"),
134
- dbc.Badge("region", color="primary", className="me-1"),
135
- ], className="mb-3"),
136
- html.Small("Note: marker = loci, allele = haplotype, region = country.", className="text-muted")
137
- ], md=6),
138
- ], className="mb-4"),
139
-
140
- html.Hr(),
141
-
142
- # Section: Limitations
143
- html.H4("⚠️ Scope & Limitations", className="mt-4 text-warning"),
144
- html.Ul([
145
- html.Li([html.B("Dependency on Pv3Rs: "), "Since the model is trained on the probabilistic outputs of Pv3Rs, its accuracy is bounded by Pv3Rs. Systematic errors in Pv3Rs may be replicated."]),
146
- html.Li([html.B("Data Requirements: "), "Currently works only with amplicon sequencing datasets containing multiple markers and alleles."]),
147
- html.Li([html.B("Episode Constraints: "), "Designed specifically for paired-episode classifications; it does not address scenarios with more than two episodes per individual as a single classification."]),
148
- html.Li([html.B("Generalization: "), "The model may not generalize well to genetic markers or alleles unobserved during training."]),
149
- html.Li([html.B("Protocol Dependent: "), "Trained specifically on ", html.A("pvAmpSeq", href="https://pubmed.ncbi.nlm.nih.gov/40492072/", target="_blank"), "; it only generalizes when using the same markers and allele names specified in that protocol."]),
150
- ], className="text-secondary"),
151
-
152
- # Sample Dataset Section
153
- dbc.Card([
154
- dbc.CardBody([
155
  dbc.Row([
 
156
  dbc.Col([
157
- html.H4("Practice with Sample Data", className="card-title text-dark"),
158
- html.P("Download our demonstration file to see how the markers and episodes should be formatted.", className="text-dark"),
159
- ], md=8),
 
 
 
 
 
 
 
 
160
  dbc.Col([
161
- dbc.Button(
162
- "📥 Download Sample CSV",
163
- id="download-sample-btn",
164
- color="success",
165
- className="w-100 mt-2"
166
- ),
167
- dcc.Download(id="download-sample-csv"),
168
- ], md=4),
169
- ])
170
- ])
171
- ], color="light", className="mt-5 border-start border-success border-4"),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
 
173
- ], className="p-5 bg-white shadow-sm rounded-3 mb-5")
 
 
174
  ], fluid=True)
175
 
176
-
177
- # --- PAGE 2: ORIGINAL MAIN SYSTEM LAYOUT ---
178
  def render_main_app():
179
  return dbc.Container([
180
  dbc.Row([
181
- dbc.Col(html.H1("PvRecNet", className="my-4", style={"color":'#2dd4bf'}), width=10),
182
- dbc.Col(html.A("Help & Guidelines", href="/help", id="help-nav-link", style={"marginTop": "30px", "display": "block", "fontWeight": "500"}), width=2)
183
  ]),
184
 
185
  dbc.Tabs(id="main-tabs", active_tab="tab-intro", children=[
186
  # Tab 0: Welcome / Landing
187
- dbc.Tab(label="Welcome", tab_id="tab-intro", active_label_style={"color": '#2dd4bf', "fontWeight": "bold"}, children=[
188
  dbc.Container([
189
  dbc.Row([
190
  dbc.Col([
191
  html.Div([
192
- html.H2("Welcome to PvRecNet", className="display-5 mt-5", style={"color":'#2dd4bf'}),
193
  html.P("Deep Learning support for Malaria Recurrence Classification.", className="lead"),
194
  html.P([
195
  "Please see our ",
196
- html.A("Help Page", href="/help", style={"fontWeight": "bold", "color": "#2dd4bf"}),
197
  " to understand exactly how the system works and how to format your data."
198
  ]),
199
  html.Hr(),
200
  dbc.Button("Get Started →", id="get-started-btn", color="primary", size="lg", className="mt-3 shadow")
201
- ], className="p-5 border rounded-3 text-center card-panel-box")
202
  ], md=8, className="offset-md-2")
203
  ])
204
  ], fluid=True)
205
  ]),
206
 
207
  # Tab 1: Prediction Workflow
208
- dbc.Tab(label="Prediction Workflow", tab_id="tab-predict", active_label_style={"color": '#2dd4bf', "fontWeight": "bold"}, children=[
209
  dbc.Row([
210
  dbc.Col([
211
  dbc.Card([
212
  dbc.CardHeader(html.B("Step 1: Upload Data")),
213
  dbc.CardBody([
214
- # Premium Upload Component layout restored
215
- dcc.Upload(
216
- id='upload-data',
217
- children=html.Div([
218
- html.I(className="fas fa-cloud-upload-alt display-6 d-block mb-2 text-muted"),
219
- 'Drag & Drop Matrix or ', html.Span('Browse Files', style={"color": "#2dd4bf", "textDecoration": "underline"})
220
- ]),
221
- style={
222
- 'width': '100%', 'height': '140px', 'lineHeight': '24px',
223
- 'borderWidth': '2px', 'borderStyle': 'dashed', 'borderRadius': '12px',
224
- 'textAlign': 'center', 'background': '#0f172a', 'paddingTop': '30px',
225
- 'borderColor': 'rgba(45, 212, 191, 0.2)', 'cursor': 'pointer'
226
- }
227
- ),
228
  html.Div(id='upload-status', className="mt-2"),
229
  html.Hr(),
230
- dbc.Button("Run Deep Sets Prediction", id="predict-btn", disabled=True, className="w-100 font-weight-bold shadow-sm",
231
- style={"backgroundColor": "#2dd4bf", "borderColor": "#2dd4bf", "color": "#0f172a"})
232
  ])
233
- ], className="card-panel-box")
234
  ], md=4),
235
  dbc.Col([
236
  dbc.Card([
@@ -239,64 +168,41 @@ def render_main_app():
239
  id='preview-table', columns=[], data=[], export_format='csv', editable=True,
240
  filter_action="native", sort_action="native", page_size=10,
241
  style_table={'height': '350px', 'overflowY': 'auto'},
242
- ), type="dot"))
243
- ], className="card-panel-box")
 
 
244
  ], md=8)
245
  ], className="mt-4"),
246
- dbc.Row(dbc.Col(dbc.Card([dbc.CardHeader(html.B("Step 3: Model Results")), dbc.CardBody(dcc.Loading(id="prediction-output", type="graph"))], className="mt-4 mb-5 card-panel-box"), width=12))
247
  ]),
248
  ])
249
  ], fluid=True)
250
 
251
-
252
- # --- THEME STORE STATE ROUTER ---
253
- @app.callback(
254
- Output('theme-store', 'data'),
255
- Input('theme-toggle', 'value')
256
- )
257
- def save_theme_preference(theme_val):
258
- return theme_val
259
-
260
-
261
- # --- MAIN LAYOUT RESPONSIVE STYLE CONFIGURATOR ---
262
  @app.callback(
263
- [Output('main-container', 'style'),
264
- Output('sidebar-panel', 'style'),
265
- Output('preview-table', 'style_header'),
266
- Output('preview-table', 'style_cell'),
267
- Output('theme-label', 'style'),
268
- Output('theme-toggle', 'className'),
269
- Output('sidebar-subtitle', 'className'),
270
- Output('sidebar-footer', 'className'),
271
- Output('help-nav-link', 'className')],
272
- Input('theme-store', 'data')
273
  )
274
- def apply_theme_parameters(theme):
275
- if theme == 'light':
276
- bg_main, color_main, bg_sidebar, border_sidebar = "#f8fafc", "#0f172a", "#e2e8f0", "1px solid #cbd5e1"
277
- header_table, cell_table = '#cbd5e1', '#ffffff'
278
- text_table, border_table = '#0f172a', '#94a3b8'
279
- lbl_clr = {"color": "#475569"}
280
- radio_class = "text-secondary small"
281
- sub_class, foot_class, link_class = "small text-muted mt-1", "text-muted", "text-muted"
282
- else: # Dark Theme Configuration
283
- bg_main, color_main, bg_sidebar, border_sidebar = "#0f172a", "#f8fafc", "#1e293b", "1px solid rgba(45, 212, 191, 0.1)"
284
- header_table, cell_table = '#1e293b', '#0f172a'
285
- text_table, border_table = '#f8fafc', '#334155'
286
- lbl_clr = {"color": "#f8fafc"}
287
- radio_class = "text-white small"
288
- sub_class, foot_class, link_class = "small text-white-50 mt-1", "text-white-50", "text-white-50"
289
-
290
- container_css = {"background": bg_main, "color": color_main, "minHeight": "100vh", "transition": "all 0.3s ease"}
291
- sidebar_css = {**SIDEBAR_STYLE, "background-color": bg_sidebar, "borderRight": border_sidebar, "transition": "all 0.3s ease"}
292
 
293
- th_style = {'backgroundColor': header_table, 'color': '#2dd4bf', 'fontWeight': 'bold', 'border': f'1px solid {border_table}'}
294
- td_style = {'backgroundColor': cell_table, 'color': text_table, 'textAlign': 'left', 'border': f'1px solid {border_table}', 'padding': '10px'}
 
295
 
296
- return container_css, sidebar_css, th_style, td_style, lbl_clr, radio_class, sub_class, foot_class, link_class
297
-
298
 
299
- # --- CORE PAGES ROUTER CALLBACK ---
300
  @app.callback(
301
  Output('page-content', 'children'),
302
  Input('url', 'pathname')
@@ -307,7 +213,6 @@ def display_page(pathname):
307
  else:
308
  return render_main_app()
309
 
310
-
311
  # --- NAVIGATION CALLBACK ---
312
  @app.callback(
313
  Output("main-tabs", "active_tab"),
@@ -317,32 +222,11 @@ def display_page(pathname):
317
  def navigate_to_predict(n_clicks):
318
  return "tab-predict" if n_clicks else "tab-intro"
319
 
 
320
 
321
- # --- SAMPLE TEMPLATE CONTROLLER ---
322
- @app.callback(
323
- Output("download-sample-csv", "data"),
324
- Input("download-sample-btn", "n_clicks"),
325
- prevent_initial_call=True,
326
- )
327
- def download_sample_data(n_clicks):
328
- current_dir = os.path.dirname(os.path.abspath(__file__))
329
- if os.path.basename(current_dir) == 'frontend':
330
- base_dir = os.path.dirname(current_dir)
331
- else:
332
- base_dir = current_dir
333
-
334
- sample_path = os.path.join(base_dir, 'backend', 'PvDeepSetNet', 'datasets', 'GUI_sample_dataset.csv')
335
- if not os.path.exists(sample_path):
336
- sample_path = os.path.join(base_dir, 'backend', 'PvDeepSetNet', 'src', 'DeepSets', 'datasets', 'GUI_sample_dataset.csv')
337
-
338
- sample_df = pd.read_csv(sample_path)
339
- return dcc.send_data_frame(sample_df.to_csv, "pvrecnet_sample_data.csv", index=False)
340
-
341
-
342
- # --- FUNCTIONAL DATA UPLOAD STORAGE INTERFACE ---
343
  @app.callback(
344
  [Output('dataset-id-store', 'data'), Output('upload-status', 'children'), Output('predict-btn', 'disabled'),
345
- Output('preview-table', 'data'), Output('preview-table', 'columns')],
346
  [Input('upload-data', 'contents')], [State('upload-data', 'filename')], prevent_initial_call=True
347
  )
348
  def handle_upload(contents, filename):
@@ -350,65 +234,37 @@ def handle_upload(contents, filename):
350
  try:
351
  decoded = base64.b64decode(contents.split(',')[1])
352
  df = pd.read_csv(io.BytesIO(decoded))
353
- cols = [{"name": i, "id": i, "editable": True} for i in df.columns]
354
 
355
- # Save raw dataframe binary directly into memory store context
356
  dataset_id = "ds_001"
357
  storage[dataset_id] = decoded
358
 
359
- status = dbc.Alert(f"Ready: {filename}", color="success", className="mt-2")
360
- return dataset_id, status, False, df.to_dict('records'), cols
361
  except Exception as e:
362
- return None, dbc.Alert(f"Error parsing file: {str(e)}", color="danger"), True, [], []
363
 
364
-
365
- # --- ANALYTICAL WORKFLOW EXECUTOR AND PLOTLY GRAPH CONFIGURATOR ---
366
  @app.callback(
367
  Output('prediction-output', 'children'),
368
  Input('predict-btn', 'n_clicks'),
369
- [State('dataset-id-store', 'data'), State('theme-store', 'data')],
370
  prevent_initial_call=True
371
  )
372
- def run_predict(n_clicks, dataset_id, theme):
373
  try:
 
374
  file_bytes = storage.get(dataset_id)
375
  if not file_bytes:
376
  return dbc.Alert("Error: Dataset context could not be located in application memory storage.", color="danger")
377
 
378
  df = pd.read_csv(io.BytesIO(file_bytes))
 
 
379
  model_output = run_prediction(df)
380
 
381
  fig1 = model_output.get('donut_plot')
382
  fig2 = model_output.get('distribution_plot')
383
 
384
- # Assign high-contrast layout configurations explicitly overriding layout dict traces
385
- chart_text = '#cbd5e1' if theme == 'dark' else '#0f172a'
386
-
387
- # Explicit full dictionary configuration injection strategy to ensure plot elements change cleanly
388
- for fig in [fig1, fig2]:
389
- if fig:
390
- if hasattr(fig, 'update_layout'):
391
- fig.update_layout(
392
- paper_bgcolor='rgba(0,0,0,0)',
393
- plot_bgcolor='rgba(0,0,0,0)',
394
- font=dict(color=chart_text, size=12),
395
- legend=dict(
396
- font=dict(color=chart_text),
397
- bgcolor='rgba(0,0,0,0)',
398
- itemwidth=40
399
- )
400
- )
401
- elif isinstance(fig, dict):
402
- if 'layout' not in fig:
403
- fig['layout'] = {}
404
- fig['layout']['paper_bgcolor'] = 'rgba(0,0,0,0)'
405
- fig['layout']['plot_bgcolor'] = 'rgba(0,0,0,0)'
406
- fig['layout']['font'] = {'color': chart_text, 'size': 12}
407
- fig['layout']['legend'] = {
408
- 'font': {'color': chart_text},
409
- 'bgcolor': 'rgba(0,0,0,0)'
410
- }
411
-
412
  df_res = pd.DataFrame(model_output['results_table'])
413
  prob_cols = ['C_marg', 'L_marg', 'I_marg']
414
 
@@ -416,35 +272,25 @@ def run_predict(n_clicks, dataset_id, theme):
416
  if col in df_res.columns:
417
  df_res[col] = df_res[col].map(lambda x: f"{x:.4f}" if pd.notnull(x) else x)
418
 
419
- # Style context tables matching selected dashboard background themes
420
- cell_bg = '#0f172a' if theme == 'dark' else '#ffffff'
421
- cell_text = '#cbd5e1' if theme == 'dark' else '#0f172a'
422
- hdr_bg = '#1e293b' if theme == 'dark' else '#cbd5e1'
423
- border_clr = '#334155' if theme == 'dark' else '#94a3b8'
424
-
425
  table = dash_table.DataTable(
426
  data=df_res.to_dict('records'),
427
  columns=[{"name": i, "id": i} for i in df_res.columns],
428
  export_format='csv',
429
  page_size=10,
430
  style_table={'height': '400px', 'overflowY': 'auto'},
431
- style_header={'backgroundColor': hdr_bg, 'color': '#2dd4bf', 'fontWeight': 'bold', 'border': f'1px solid {border_clr}'},
432
- style_cell={'backgroundColor': cell_bg, 'color': cell_text, 'textAlign': 'left', 'border': f'1px solid {border_clr}'}
433
  )
434
 
435
  return html.Div([
436
  dbc.Row([
437
- dbc.Col([
438
- dcc.Graph(figure=fig1, config={'displayModeBar': False}) if fig1 else html.Div("Donut Plot Unavailable", className="text-muted small"),
439
- html.Hr(style={"borderColor": "rgba(248,250,252,0.1)"}),
440
- dcc.Graph(figure=fig2, config={'displayModeBar': False}) if fig2 else html.Div("Distribution Plot Unavailable", className="text-muted small")
441
- ], md=5),
442
  dbc.Col(table, md=7)
443
  ])
444
  ])
445
  except Exception as e:
446
  return dbc.Alert(f"Prediction Pipeline Error: {str(e)}", color="danger")
447
 
448
-
449
  if __name__ == '__main__':
 
450
  app.run_server(debug=True, port=8050)
 
1
  import dash
2
+ from dash import dcc, html, Input, Output, State, dash_table, callback_context
3
  import dash_bootstrap_components as dbc
4
  import pandas as pd
5
  import json
 
8
  import os
9
 
10
  # --- IN-MEMORY BACKEND HOOKS ---
11
+ # Importing directly from backend skips the internal network interface barriers
12
  from backend.main import storage
13
  from backend.PvDeepSetNet.src.DeepSets import run_prediction
14
 
15
+ # 1. Initialize App with Hugging Face proxy configurations
16
  app = dash.Dash(
17
  __name__,
18
+ external_stylesheets=[dbc.themes.FLATLY],
19
  title="PvRecNet",
20
  suppress_callback_exceptions=True,
21
+ # Crucial parameters for WSGI middleware hosting:
22
  requests_pathname_prefix="/",
23
  routes_pathname_prefix="/"
24
  )
25
 
26
+ # 2. Define the Main App Layout (Navigation + Page Container)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  app.layout = html.Div([
28
+ dcc.Location(id='url', refresh=False), # Tracks the URL
 
 
29
  dcc.Store(id='dataset-id-store', storage_type='session'),
30
+ html.Div(id='page-content') # Where different pages will be rendered
31
+ ])
32
 
33
+ # --- PAGE 1: THE HELP / GUIDELINE PAGE ---
 
34
  def render_help_page():
35
  return dbc.Container([
36
+ dbc.Row([
37
+ dbc.Col([
38
+ # Back Button
39
+ dbc.Button("← Back to System", href="/", color="link", className="mt-4 p-0 text-decoration-none"),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
+ html.Div([
42
+ # Header Section
 
 
43
  html.Div([
44
+ html.H1("System Guidelines & Documentation", className="display-5 text-primary"),
45
+ html.P([
46
+ "PvRecNet is a deep learning-based model for ",
47
+ html.B(html.I("Plasmodium vivax")),
48
+ " recurrence classification."
49
+ ], className="lead"),
50
+ ], className="mb-5"),
51
+
52
+ # Visual Appeal: Use Cards for Sections
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  dbc.Row([
54
+ # Section: Description
55
  dbc.Col([
56
+ html.H5("Model Description", className="text-info"),
57
+ html.P([
58
+ "Our architecture differentiates between ",
59
+ html.B("Recrudescence, Relapse, and Reinfection"),
60
+ ". It is trained on probabilistic outputs from ",
61
+ html.A("Pv3Rs", href="https://github.com/aimeertaylor/Pv3Rs", target="_blank"),
62
+ " to ensure robust genomic classification."
63
+ ]),
64
+ ], md=6),
65
+
66
+ # Section: Data Requirements
67
  dbc.Col([
68
+ html.H5("Data Requirements", className="text-info"),
69
+ html.P("Your dataset must contain these exact columns:"),
70
+ html.Div([
71
+ dbc.Badge("patient_id", color="primary", className="me-1"),
72
+ dbc.Badge("episode", color="primary", className="me-1"),
73
+ dbc.Badge("marker", color="primary", className="me-1"),
74
+ dbc.Badge("allele", color="primary", className="me-1"),
75
+ dbc.Badge("region", color="primary", className="me-1"),
76
+ ], className="mb-3"),
77
+ html.Small("Note: marker = loci, allele = haplotype, region = country.", className="text-muted")
78
+ ], md=6),
79
+ ], className="mb-4"),
80
+
81
+ html.Hr(),
82
+
83
+ # Section: Limitations
84
+ html.H4("⚠️ Scope & Limitations", className="mt-4 text-warning"),
85
+ html.Ul([
86
+ html.Li([html.B("Dependency on Pv3Rs: "), "Since the model is trained on the probabilistic outputs of Pv3Rs, its accuracy is bounded by Pv3Rs. Systematic errors in Pv3Rs may be replicated."]),
87
+ html.Li([html.B("Data Requirements: "), "Currently works only with amplicon sequencing datasets containing multiple markers and alleles."]),
88
+ html.Li([html.B("Episode Constraints: "), "Designed specifically for paired-episode classifications; it does not address scenarios with more than two episodes per individual as a single classification."]),
89
+ html.Li([html.B("Generalization: "), "The model may not generalize well to genetic markers or alleles unobserved during training."]),
90
+ html.Li([html.B("Protocol Dependent: "), "Trained specifically on ", html.A("pvAmpSeq", href="https://pubmed.ncbi.nlm.nih.gov/40492072/", target="_blank"), "; it only generalizes when using the same markers and allele names specified in that protocol."]),
91
+ ], className="text-secondary"),
92
+
93
+ # Sample Dataset Section
94
+ dbc.Card([
95
+ dbc.CardBody([
96
+ dbc.Row([
97
+ dbc.Col([
98
+ html.H4("Practice with Sample Data", className="card-title"),
99
+ html.P("Download our demonstration file to see how the markers and episodes should be formatted."),
100
+ ], md=8),
101
+ dbc.Col([
102
+ dbc.Button(
103
+ "📥 Download Sample CSV",
104
+ id="download-sample-btn",
105
+ color="success",
106
+ className="w-100 mt-2"
107
+ ),
108
+ dcc.Download(id="download-sample-csv"),
109
+ ], md=4),
110
+ ])
111
+ ])
112
+ ], color="light", className="mt-5 border-start border-success border-4"),
113
 
114
+ ], className="p-5 bg-white shadow-sm rounded-3 mb-5")
115
+ ], md=10, className="offset-md-1")
116
+ ])
117
  ], fluid=True)
118
 
119
+ # --- PAGE 2: THE MAIN SYSTEM (Tabs) ---
 
120
  def render_main_app():
121
  return dbc.Container([
122
  dbc.Row([
123
+ dbc.Col(html.H1("PvRecNet", className="text-center my-4", style={"color":'#113d59'}), width=10),
124
+ dbc.Col(html.A("Help & Guidelines", href="/help", className="text-muted", style={"marginTop": "30px", "display": "block"}), width=2)
125
  ]),
126
 
127
  dbc.Tabs(id="main-tabs", active_tab="tab-intro", children=[
128
  # Tab 0: Welcome / Landing
129
+ dbc.Tab(label="Welcome", tab_id="tab-intro", active_label_style={"color": '#113d59', "fontWeight": "bold"}, children=[
130
  dbc.Container([
131
  dbc.Row([
132
  dbc.Col([
133
  html.Div([
134
+ html.H2("Welcome to PvRecNet", className="display-5 mt-5", style={"color":'#113d59'}),
135
  html.P("Deep Learning support for Malaria Recurrence Classification.", className="lead"),
136
  html.P([
137
  "Please see our ",
138
+ html.A("Help Page", href="/help", style={"fontWeight": "bold"}),
139
  " to understand exactly how the system works and how to format your data."
140
  ]),
141
  html.Hr(),
142
  dbc.Button("Get Started →", id="get-started-btn", color="primary", size="lg", className="mt-3 shadow")
143
+ ], className="p-5 bg-light border rounded-3 text-center")
144
  ], md=8, className="offset-md-2")
145
  ])
146
  ], fluid=True)
147
  ]),
148
 
149
  # Tab 1: Prediction Workflow
150
+ dbc.Tab(label="Prediction Workflow", tab_id="tab-predict", children=[
151
  dbc.Row([
152
  dbc.Col([
153
  dbc.Card([
154
  dbc.CardHeader(html.B("Step 1: Upload Data")),
155
  dbc.CardBody([
156
+ dcc.Upload(id='upload-data', children=html.Div(['Drag/Drop or Select CSV']),
157
+ style={'width': '100%', 'height': '60px', 'lineHeight': '60px', 'borderWidth': '1px', 'borderStyle': 'dashed', 'borderRadius': '5px', 'textAlign': 'center'}),
 
 
 
 
 
 
 
 
 
 
 
 
158
  html.Div(id='upload-status', className="mt-2"),
159
  html.Hr(),
160
+ dbc.Button("Run Deep Sets Prediction", id="predict-btn", color="primary", disabled=True, className="w-100")
 
161
  ])
162
+ ])
163
  ], md=4),
164
  dbc.Col([
165
  dbc.Card([
 
168
  id='preview-table', columns=[], data=[], export_format='csv', editable=True,
169
  filter_action="native", sort_action="native", page_size=10,
170
  style_table={'height': '350px', 'overflowY': 'auto'},
171
+ style_header={'backgroundColor': '#f8f9fa', 'fontWeight': 'bold'},
172
+ style_cell={'textAlign': 'left', 'padding': '10px'}
173
+ )))
174
+ ])
175
  ], md=8)
176
  ], className="mt-4"),
177
+ dbc.Row(dbc.Col(dbc.Card([dbc.CardHeader(html.B("Step 3: Model Results")), dbc.CardBody(dcc.Loading(id="prediction-output"))], className="mt-4 mb-5"), width=12))
178
  ]),
179
  ])
180
  ], fluid=True)
181
 
 
 
 
 
 
 
 
 
 
 
 
182
  @app.callback(
183
+ Output("download-sample-csv", "data"),
184
+ Input("download-sample-btn", "n_clicks"),
185
+ prevent_initial_call=True,
 
 
 
 
 
 
 
186
  )
187
+ def download_sample_data(n_clicks):
188
+ current_dir = os.path.dirname(os.path.abspath(__file__))
189
+
190
+ # Adapt structural finding context for either local execution or Docker volumes
191
+ if os.path.basename(current_dir) == 'frontend':
192
+ base_dir = os.path.dirname(current_dir)
193
+ else:
194
+ base_dir = current_dir
195
+
196
+ sample_path = os.path.join(base_dir, 'backend', 'PvDeepSetNet', 'datasets', 'GUI_sample_dataset.csv')
 
 
 
 
 
 
 
 
197
 
198
+ # Fallback to internal module package tracking if paths nested differently
199
+ if not os.path.exists(sample_path):
200
+ sample_path = os.path.join(base_dir, 'backend', 'PvDeepSetNet', 'src', 'DeepSets', 'datasets', 'GUI_sample_dataset.csv')
201
 
202
+ sample_df = pd.read_csv(sample_path)
203
+ return dcc.send_data_frame(sample_df.to_csv, "pvrecnet_sample_data.csv", index=False)
204
 
205
+ # --- ROUTER CALLBACK ---
206
  @app.callback(
207
  Output('page-content', 'children'),
208
  Input('url', 'pathname')
 
213
  else:
214
  return render_main_app()
215
 
 
216
  # --- NAVIGATION CALLBACK ---
217
  @app.callback(
218
  Output("main-tabs", "active_tab"),
 
222
  def navigate_to_predict(n_clicks):
223
  return "tab-predict" if n_clicks else "tab-intro"
224
 
225
+ # --- FUNCTIONAL CALLBACKS ---
226
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
227
  @app.callback(
228
  [Output('dataset-id-store', 'data'), Output('upload-status', 'children'), Output('predict-btn', 'disabled'),
229
+ Output('preview-table', 'data'), Output('preview-table', 'columns'), Output('preview-table', 'fixed_rows')],
230
  [Input('upload-data', 'contents')], [State('upload-data', 'filename')], prevent_initial_call=True
231
  )
232
  def handle_upload(contents, filename):
 
234
  try:
235
  decoded = base64.b64decode(contents.split(',')[1])
236
  df = pd.read_csv(io.BytesIO(decoded))
237
+ cols = [{"name": i, "id": i, "editable": True, "type": 'numeric' if pd.api.types.is_numeric_dtype(df[i]) else 'text'} for i in df.columns]
238
 
239
+ # Save file contents straight into the global shared storage dictionary
240
  dataset_id = "ds_001"
241
  storage[dataset_id] = decoded
242
 
243
+ return dataset_id, dbc.Alert(f"Ready: {filename}", color="success"), False, df.to_dict('records'), cols, {'headers': True}
 
244
  except Exception as e:
245
+ return None, dbc.Alert(f"Error parsing file: {str(e)}", color="danger"), True, [], [], {'headers': False}
246
 
 
 
247
  @app.callback(
248
  Output('prediction-output', 'children'),
249
  Input('predict-btn', 'n_clicks'),
250
+ State('dataset-id-store', 'data'),
251
  prevent_initial_call=True
252
  )
253
+ def run_predict(n_clicks, dataset_id):
254
  try:
255
+ # Retrieve the dataset straight from memory
256
  file_bytes = storage.get(dataset_id)
257
  if not file_bytes:
258
  return dbc.Alert("Error: Dataset context could not be located in application memory storage.", color="danger")
259
 
260
  df = pd.read_csv(io.BytesIO(file_bytes))
261
+
262
+ # Run the imported machine learning predictor natively
263
  model_output = run_prediction(df)
264
 
265
  fig1 = model_output.get('donut_plot')
266
  fig2 = model_output.get('distribution_plot')
267
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
268
  df_res = pd.DataFrame(model_output['results_table'])
269
  prob_cols = ['C_marg', 'L_marg', 'I_marg']
270
 
 
272
  if col in df_res.columns:
273
  df_res[col] = df_res[col].map(lambda x: f"{x:.4f}" if pd.notnull(x) else x)
274
 
 
 
 
 
 
 
275
  table = dash_table.DataTable(
276
  data=df_res.to_dict('records'),
277
  columns=[{"name": i, "id": i} for i in df_res.columns],
278
  export_format='csv',
279
  page_size=10,
280
  style_table={'height': '400px', 'overflowY': 'auto'},
281
+ style_cell={'textAlign': 'left'}
 
282
  )
283
 
284
  return html.Div([
285
  dbc.Row([
286
+ dbc.Col([dcc.Graph(figure=fig1) if fig1 else html.Div(),
287
+ dcc.Graph(figure=fig2) if fig2 else html.Div()], md=5),
 
 
 
288
  dbc.Col(table, md=7)
289
  ])
290
  ])
291
  except Exception as e:
292
  return dbc.Alert(f"Prediction Pipeline Error: {str(e)}", color="danger")
293
 
 
294
  if __name__ == '__main__':
295
+ # Local fallback runner
296
  app.run_server(debug=True, port=8050)