-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1931 lines (1763 loc) · 72.6 KB
/
app.py
File metadata and controls
1931 lines (1763 loc) · 72.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
from typing import Dict, List, Tuple, Optional
import dash
from dash import Dash, html, dcc, dash_table, Input, Output, State, no_update, ALL
from dash.dependencies import ClientsideFunction
import dash_bootstrap_components as dbc
import pymongo
import json
from bson import ObjectId
import uuid
import pandas as pd
from flask import request, make_response
import io
import csv
# Simple in-memory cache to pass data to the pygwalker page
PYGWALKER_CACHE: Dict[str, List[Dict]] = {}
def build_mongodb_uri(
uri_from_user: Optional[str],
host: Optional[str],
port: Optional[str],
username: Optional[str],
password: Optional[str],
database_name: Optional[str],
auth_source: Optional[str] = None,
) -> str:
"""
Build a MongoDB connection URI from either a full URI provided by the user,
or individual connection fields.
"""
if uri_from_user and uri_from_user.strip():
return uri_from_user.strip()
resolved_host = (host or "localhost").strip()
resolved_port = (port or "27017").strip()
resolved_username = (username or "").strip()
resolved_password = (password or "").strip()
resolved_db_name = (database_name or "").strip()
resolved_auth_source = (auth_source or "").strip()
# No auth case
if not resolved_username:
return f"mongodb://{resolved_host}:{resolved_port}/"
# Auth case; include authSource using explicit value or the database name when provided
effective_auth_source = resolved_auth_source or resolved_db_name
if effective_auth_source:
return (
f"mongodb://{resolved_username}:{resolved_password}"
f"@{resolved_host}:{resolved_port}/?authSource={effective_auth_source}"
)
return f"mongodb://{resolved_username}:{resolved_password}@{resolved_host}:{resolved_port}/"
def fetch_sacred_experiment_names(
client: pymongo.MongoClient, database_name: str
) -> List[str]:
"""
Return a sorted list of experiment names stored by Sacred.
Sacred's MongoObserver stores runs in the 'runs' collection with the field 'experiment.name'.
"""
db = client[database_name]
if "runs" not in db.list_collection_names():
# Fallback: return empty list if no runs collection present
return []
names = db["runs"].distinct("experiment.name")
# Filter out empty/None and sort
cleaned = sorted([n for n in names if isinstance(n, str) and n.strip()])
return cleaned
def fetch_config_keys(client: pymongo.MongoClient, database_name: str) -> List[str]:
"""
Return sorted list of distinct top-level keys found in the 'config' field of Sacred runs.
"""
db = client[database_name]
if "runs" not in db.list_collection_names():
return []
pipeline = [
{"$match": {"config": {"$type": "object"}}},
{"$project": {"cfg": {"$objectToArray": "$config"}}},
{"$unwind": "$cfg"},
{"$group": {"_id": "$cfg.k"}},
{"$project": {"_id": 0, "k": "$_id"}},
{"$sort": {"k": 1}},
]
keys = [doc["k"] for doc in db["runs"].aggregate(pipeline)]
return keys
def fetch_runs_docs(client: pymongo.MongoClient, database_name: str, limit: int = 500) -> List[Dict]:
"""
Fetch a subset of runs with experiment name and config for table rendering.
"""
db = client[database_name]
if "runs" not in db.list_collection_names():
return []
cursor = db["runs"].find({}, {"experiment.name": 1, "config": 1, "info.metrics": 1, "info.result": 1}).limit(limit)
runs: List[Dict] = []
for doc in cursor:
exp_name = None
exp = doc.get("experiment")
if isinstance(exp, dict):
exp_name = exp.get("name")
if not isinstance(exp_name, str):
exp_name = ""
cfg = doc.get("config")
cfg = cfg if isinstance(cfg, dict) else {}
info = doc.get("info") if isinstance(doc.get("info", {}), dict) else {}
metrics = (info or {}).get("metrics", None)
result = (info or {}).get("result", None)
runs.append({"experiment": exp_name, "config": cfg, "metrics": metrics, "result": result})
return runs
def fetch_metrics_list(client: pymongo.MongoClient, database_name: str, limit: int = 1000) -> List[Dict]:
"""
Fetch available metrics from the 'metrics' collection.
Returns a list of dicts with at least {'id': str, 'name': str}.
"""
db = client[database_name]
if "metrics" not in db.list_collection_names():
return []
items: List[Dict] = []
try:
cursor = db["metrics"].find({}, {"_id": 1, "name": 1, "title": 1}).limit(limit)
for doc in cursor:
_id = str(doc.get("_id"))
name = doc.get("name") or doc.get("title") or _id
if not isinstance(name, str):
name = str(name)
items.append({"id": _id, "name": name})
# Sort by name
items.sort(key=lambda x: x.get("name", ""))
except Exception:
# On any error, return empty list to avoid breaking UI
return []
return items
def collect_metric_ids_from_runs(runs: List[Dict]) -> List[str]:
ids = set()
for r in runs or []:
m = r.get("metrics", None)
if isinstance(m, dict):
for val in m.values():
if isinstance(val, dict) and val.get("id") is not None:
ids.add(str(val.get("id")))
elif isinstance(val, (str, ObjectId)):
ids.add(str(val))
elif isinstance(m, list):
for item in m:
if not isinstance(item, dict):
continue
mid = item.get("id") or item.get("_id")
if mid is not None:
ids.add(str(mid))
return sorted(ids)
def fetch_metrics_values_map(client: pymongo.MongoClient, database_name: str, id_strs: List[str]) -> Dict[str, Dict]:
if not id_strs:
return {}
db = client[database_name]
if "metrics" not in db.list_collection_names():
return {}
object_ids = []
for s in id_strs:
try:
object_ids.append(ObjectId(s))
except Exception:
# skip invalid ObjectId strings
continue
if not object_ids:
return {}
values_by_id: Dict[str, Dict] = {}
for doc in db["metrics"].find({"_id": {"$in": object_ids}}, {"values": 1, "steps": 1}):
values_by_id[str(doc.get("_id"))] = {
"values": doc.get("values", []),
"steps": doc.get("steps", []),
}
return values_by_id
def build_table_from_runs(runs: List[Dict], selected_keys: List[str]) -> Tuple[List[Dict], List[Dict]]:
"""
Build DataTable columns and rows based on selected configuration keys.
Returns (columns, data_rows).
"""
columns = [{"name": "Experiment", "id": "experiment"}] + [
{"name": key, "id": key} for key in selected_keys
]
rows: List[Dict] = []
for run in runs:
row = {"experiment": run.get("experiment", "")}
cfg = run.get("config", {}) or {}
if not isinstance(cfg, dict):
cfg = {}
for key in selected_keys:
row[key] = cfg.get(key)
rows.append(row)
return columns, rows
def attempt_connect_and_list(
uri: str, database_name: str
) -> Tuple[str, Dict, List[Dict]]:
"""
Try to connect to MongoDB using the provided URI and list Sacred experiments.
Returns: (status_text, style_dict, table_rows)
"""
try:
client = pymongo.MongoClient(uri, serverSelectionTimeoutMS=5000)
# Force connection attempt
client.admin.command("ping")
except Exception as exc:
return (
f"Connection failed: {exc}",
{"color": "#b00020"}, # red
[],
)
try:
experiment_names = fetch_sacred_experiment_names(client, database_name)
count = len(experiment_names)
status = (
f"Connected. Database '{database_name}' contains {count} Sacred experiment(s)."
if count > 0
else f"Connected. Database '{database_name}' contains no Sacred experiments."
)
style = {"color": "#1b5e20"} # green
rows = [{"experiment": name} for name in experiment_names]
return status, style, rows
except Exception as exc:
return (
f"Connected, but failed to query experiments: {exc}",
{"color": "#b00020"},
[],
)
app = Dash(
__name__,
external_stylesheets=[
dbc.themes.LUX,
dbc.icons.BOOTSTRAP, # Bootstrap Icons via dbc helper
"https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css", # fallback
],
)
server = app.server
DEFAULT_DB_NAME = os.environ.get("SACRED_DB_NAME", "sacred")
app.layout = dbc.Container(
[
dcc.Store(id="creds-store", storage_type="local"),
dcc.Store(id="ui-store", storage_type="local"),
dcc.Store(id="db-history", storage_type="local"),
dcc.Store(id="runs-cache", storage_type="memory"),
dcc.Store(id="config-keys-store", storage_type="local"),
dcc.Store(id="filters-store", storage_type="local"),
dcc.Store(id="metrics-store", storage_type="memory"),
dcc.Store(id="metrics-values-store", storage_type="memory"),
dcc.Store(id="metrics-selected-store", storage_type="local"),
dcc.Store(id="experiments-page-size-store", storage_type="local"),
dcc.Store(id="metrics-page-size-store", storage_type="local"),
dcc.Store(id="results-store", storage_type="memory"),
dcc.Interval(id="init-tick", interval=0, n_intervals=0, max_intervals=1),
dbc.Navbar(
dbc.Container(
[
dbc.NavbarBrand("Sacred Experiments Browser", class_name="mb-0 h4 text-dark"),
dbc.Button("Database credentials", id="toggle-connection", color="link", class_name="mb-0 h5 p-0"),
]
),
color="light",
sticky="top",
class_name="mb-3",
),
dbc.Collapse(
id="connection-collapse",
is_open=True,
children=dbc.Row(
[
dbc.Col(
dbc.Card(
dbc.CardBody(
[
html.P("Enter your MongoDB credentials or a MongoDB URI."),
dbc.Row(
[
dbc.Col(
dcc.Input(
id="uri-input",
placeholder="MongoDB URI (e.g. mongodb+srv://user:pass@cluster/db?authSource=admin)",
type="text",
value="",
style={"width": "100%"},
),
width=12,
),
],
class_name="mb-2",
),
dbc.Row(
[
dbc.Col(dcc.Input(id="host-input", placeholder="Host (default: localhost)", type="text", value="", style={"width": "100%"}), md=6),
dbc.Col(dcc.Input(id="port-input", placeholder="Port (default: 27017)", type="text", value="", style={"width": "100%"}), md=6),
],
class_name="mb-2",
),
dbc.Row(
[
dbc.Col(dcc.Input(id="username-input", placeholder="Username (optional)", type="text", value="", style={"width": "100%"}), md=6),
dbc.Col(dcc.Input(id="password-input", placeholder="Password (optional)", type="password", value="", style={"width": "100%"}), md=6),
],
class_name="mb-2",
),
dbc.Row(
[
dbc.Col(dcc.Input(id="authsource-input", placeholder="Auth source (default: database name)", type="text", value="", style={"width": "100%"}), md=12),
],
class_name="mb-2",
),
dbc.Row(
[
dbc.Col(
dbc.Checklist(
options=[
{"label": "Save credentials", "value": "save"},
],
value=[],
id="save-options",
switch=True,
),
md=12,
),
],
class_name="mb-2",
),
dbc.Row(
[
dbc.Col(dbc.Button("Clear saved", id="clear-saved-button", color="link", n_clicks=0), width="auto"),
],
class_name="g-2 align-items-center",
),
]
),
class_name="mb-3",
),
md=6,
),
dbc.Col(
dbc.Card(
dbc.CardBody([]),
class_name="mb-3",
),
md=6,
),
],
class_name="g-2",
),
),
# Top row: database name with autocomplete + Connect + status
dbc.Row(
[
dbc.Col(
[
dbc.Label("Database"),
dbc.Input(id="db-name-input", placeholder=f"Database name (default: {DEFAULT_DB_NAME})", type="text", list="db-name-list"),
html.Datalist(id="db-name-list"),
],
md=4,
),
dbc.Col(
[
dbc.Label(" "),
dbc.Button("Connect", id="connect-button", color="primary", n_clicks=0, class_name="d-block"),
],
md=2,
),
dbc.Col(
[
dbc.Label(" "),
dbc.Alert(id="status-alert", is_open=False, color="light", class_name="mb-0"),
],
md=6,
),
],
class_name="g-2 align-items-end mb-3",
),
# Config keys selector under a single collapsible card
dbc.Card(
[
dbc.CardHeader(
html.Div(
[
html.Span("Select Keys"),
html.I(className="ms-auto bi bi-chevron-down"),
],
id="toggle-select-keys",
n_clicks=0,
className="d-flex align-items-center",
style={"cursor": "pointer", "fontSize": "1.25rem", "fontWeight": "600"},
)
),
dbc.Collapse(
dbc.CardBody(
dbc.Row(
[
dbc.Col(
dbc.Card(
[
dbc.CardHeader("Available config keys ([type] [distinct value counts])"),
dbc.CardBody(
[
dcc.Dropdown(
id="config-keys-select",
options=[],
value=[],
multi=True,
placeholder="Select config keys...",
),
html.Div(id="config-keys-none-note", style={"color": "#666", "marginTop": "0.25rem", "marginBottom": "0.75rem"}),
dbc.Button("Check/Uncheck all", id="config-keys-toggle-all", size="sm", color="secondary", class_name="mb-2"),
dbc.ListGroup(id="available-keys", style={"display": "none"}),
]
),
]
),
md=4,
),
dbc.Col(
dbc.Card(
[
dbc.CardHeader("Selected keys"),
dbc.CardBody(dbc.ListGroup(id="selected-keys")),
]
),
md=8,
),
]
)
),
id="select-keys-collapse",
is_open=True,
),
],
class_name="mb-3",
),
dbc.Card(
[
dbc.CardHeader(
html.Div(
[
html.Span("Experiments"),
html.I(className="ms-auto bi bi-chevron-down"),
],
id="toggle-experiments",
n_clicks=0,
className="d-flex align-items-center",
style={"cursor": "pointer", "fontSize": "1.25rem", "fontWeight": "600"},
)
),
dbc.Collapse(
dbc.CardBody(
[
html.Div(
[
dbc.Row(
[
dbc.Col(dbc.Button("Check/Uncheck all results", id="results-toggle-all", size="sm", color="secondary"), width="auto"),
dbc.Col(dcc.Dropdown(id="results-select", options=[], value=[], multi=True, placeholder="Select result keys...")),
],
id="results-controls-row",
class_name="g-2 mb-1 align-items-center",
),
dbc.Row(
[
dbc.Col(
[
dbc.Label("Number of rows"),
dcc.Input(id="experiments-page-size-input", type="number", value=10, min=1, step=1, style={"width": "80px", "marginLeft": "8px"}),
],
width="auto",
),
],
class_name="g-2 mb-1 align-items-center",
),
html.Div(id="results-none-note", style={"color": "#666", "marginTop": "0.25rem", "marginBottom": "0.25rem"}),
]
),
dash_table.DataTable(
id="experiments-table",
columns=[{"name": "Experiment", "id": "experiment"}],
data=[],
page_size=20,
style_table={"overflowX": "auto", "width": "100%"},
style_cell={"textAlign": "left", "padding": "8px"},
style_header={"fontWeight": "bold"},
),
html.Div(
[
dbc.Button("Open in Pygwalker", id="open-pygwalker-exp-btn", color="primary", class_name="mt-2 me-2"),
dbc.Button("Download dataset", id="download-exp-open", color="secondary", class_name="mt-2"),
]
),
dbc.Modal(
[
dbc.ModalHeader("Download CSV"),
dbc.ModalBody(
dbc.Input(id="download-exp-filename", type="text", placeholder="experiments.csv", value="experiments.csv")
),
dbc.ModalFooter(
[
dbc.Button("Cancel", id="download-exp-cancel", class_name="me-2"),
dbc.Button("Download", id="download-exp-confirm", color="primary"),
]
),
],
id="download-exp-modal",
is_open=False,
),
dcc.Download(id="download-exp-csv"),
]
),
id="experiments-collapse",
is_open=True,
),
],
class_name="mb-3",
),
dbc.Card(
[
dbc.CardHeader(
html.Div(
[
html.Span("Metrics"),
html.I(className="ms-auto bi bi-chevron-down"),
],
id="toggle-metrics",
n_clicks=0,
className="d-flex align-items-center",
style={"cursor": "pointer", "fontSize": "1.25rem", "fontWeight": "600"},
)
),
dbc.Collapse(
dbc.CardBody(
[
html.Div(
[
dbc.Row(
[
dbc.Col(dbc.Button("Check/Uncheck all metrics", id="metrics-toggle-all", size="sm", color="secondary"), width="auto"),
dbc.Col(dcc.Dropdown(id="metrics-select", options=[], value=[], multi=True, placeholder="Select metrics...")),
],
id="metrics-controls-row",
class_name="g-2 align-items-center",
),
html.Div(id="metrics-none-note", style={"color": "#666", "marginTop": "0.5rem"}),
]
),
html.Hr(),
html.Div("Per-step metrics table", style={"fontWeight": "600", "marginBottom": "0.5rem"}),
dbc.Row(
[
dbc.Col(
[
dbc.Label("Number of rows"),
dcc.Input(id="metrics-page-size-input", type="number", value=10, min=1, step=1, style={"width": "80px", "marginLeft": "8px"}),
],
width="auto",
),
],
class_name="g-2 align-items-center",
),
dash_table.DataTable(
id="metrics-steps-table",
columns=[{"name": "Experiment", "id": "experiment"}],
data=[],
page_size=20,
style_table={"overflowX": "auto", "width": "100%"},
style_cell={"textAlign": "left", "padding": "8px"},
style_header={"fontWeight": "bold"},
),
html.Div(
[
dbc.Button("Open in Pygwalker", id="open-pygwalker-btn", color="primary", class_name="mt-2 me-2"),
dbc.Button("Download dataset", id="download-steps-open", color="secondary", class_name="mt-2"),
]
),
# Download modal
dbc.Modal(
[
dbc.ModalHeader("Download CSV"),
dbc.ModalBody(
dbc.Input(id="download-steps-filename", type="text", placeholder="metrics_steps.csv", value="metrics_steps.csv")
),
dbc.ModalFooter(
[
dbc.Button("Cancel", id="download-steps-cancel", class_name="me-2"),
dbc.Button("Download", id="download-steps-confirm", color="primary"),
]
),
],
id="download-steps-modal",
is_open=False,
),
dcc.Download(id="download-steps-csv"),
dcc.Store(id="pygwalker-url"),
html.Div(id="pygwalker-open-dummy", style={"display": "none"}),
]
),
id="metrics-collapse",
is_open=True,
),
],
class_name="mb-3",
),
],
fluid=True,
)
# Open pygwalker URL in a new tab (client-side via ClientsideFunction)
app.clientside_callback(
ClientsideFunction(namespace="pyg", function_name="open"),
Output("pygwalker-open-dummy", "children"),
Input("pygwalker-url", "data"),
)
# Pygwalker page route
@server.route("/pygwalker")
def pygwalker_route():
try:
key = request.args.get("id", "").strip()
data = PYGWALKER_CACHE.get(key, [])
df = pd.DataFrame(data or [])
try:
from pygwalker.api.html import to_html
html_str = to_html(df, title="Metrics Steps Explorer")
except Exception as exc:
html_str = f"""
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>Pygwalker unavailable</title></head>
<body>
<h2>Pygwalker is not available</h2>
<p>Install it with: <code>pip install pygwalker</code></p>
<h3>Preview DataFrame (first 100 rows)</h3>
<pre>{df.head(100).to_string(index=False)}</pre>
</body>
</html>
""".strip()
resp = make_response(html_str)
resp.headers["Content-Type"] = "text/html; charset=utf-8"
return resp
except Exception as exc:
resp = make_response(f"Failed to render pygwalker page: {exc}")
resp.headers["Content-Type"] = "text/plain; charset=utf-8"
return resp, 500
@app.callback(
Output("status-alert", "children"),
Output("status-alert", "color"),
Output("status-alert", "is_open"),
Output("runs-cache", "data"),
Output("config-keys-store", "data"),
Output("metrics-store", "data"),
Output("metrics-values-store", "data"),
Output("results-store", "data"),
Input("connect-button", "n_clicks"),
Input("init-tick", "n_intervals"),
State("uri-input", "value"),
State("host-input", "value"),
State("port-input", "value"),
State("username-input", "value"),
State("password-input", "value"),
State("authsource-input", "value"),
State("db-name-input", "value"),
State("creds-store", "data"),
State("db-history", "data"),
State("config-keys-store", "data"),
prevent_initial_call=False,
)
def on_connect_click(
n_clicks: int,
n_intervals: int,
uri_value: str,
host_value: str,
port_value: str,
username_value: str,
password_value: str,
auth_source_value: str,
db_name_value: str,
saved_creds,
db_history,
existing_config_store,
):
ctx = dash.callback_context # type: ignore
triggered = ctx.triggered[0]["prop_id"].split(".")[0] if ctx.triggered else None
# If nothing triggered yet, show a neutral message
if triggered is None:
initial_text = "Connecting..."
return initial_text, "light", True, dash.no_update, dash.no_update, dash.no_update, dash.no_update, dash.no_update
auto_triggered = (triggered == "init-tick")
# Resolve DB name: prefer current input, then saved creds, then history, then default
resolved_db_name = (db_name_value or "").strip()
if not resolved_db_name:
saved_db_name = ""
try:
saved_db_name = ((saved_creds or {}).get("db_name") or "").strip() if isinstance(saved_creds, dict) else ""
except Exception:
saved_db_name = ""
if saved_db_name:
resolved_db_name = saved_db_name
elif db_history and isinstance(db_history, list) and len(db_history) > 0:
resolved_db_name = db_history[0]
else:
resolved_db_name = DEFAULT_DB_NAME
# Resolve credentials
if auto_triggered and saved_creds:
uri_from_user = (saved_creds or {}).get("uri") or uri_value
host = (saved_creds or {}).get("host") or host_value
port = (saved_creds or {}).get("port") or port_value
username = (saved_creds or {}).get("username") or username_value
password = (saved_creds or {}).get("password") or password_value
auth_source = (saved_creds or {}).get("authSource") or auth_source_value
else:
uri_from_user = uri_value
host = host_value
port = port_value
username = username_value
password = password_value
auth_source = auth_source_value
# Build URI and attempt connection
uri = build_mongodb_uri(
uri_from_user=uri_from_user,
host=host,
port=port,
username=username,
password=password,
database_name=resolved_db_name,
auth_source=auth_source,
)
try:
client = pymongo.MongoClient(uri, serverSelectionTimeoutMS=5000)
client.admin.command("ping")
except Exception as exc:
status_text = f"Connection failed: {exc}"
return status_text, "danger", True, dash.no_update, dash.no_update, dash.no_update, dash.no_update, dash.no_update
# Connected - fetch keys and runs
try:
keys = fetch_config_keys(client, resolved_db_name)
runs = fetch_runs_docs(client, resolved_db_name)
# Compute distinct metric names from runs' info.metrics
metric_names = set()
for r in runs:
m = r.get("metrics", None)
if isinstance(m, dict):
# dict: use keys as names
for k in m.keys():
if isinstance(k, str) and k.strip():
metric_names.add(k)
elif isinstance(m, list):
# list: expect dicts with 'name'
for item in m:
if isinstance(item, dict):
nm = item.get("name")
if isinstance(nm, str) and nm.strip():
metric_names.add(nm)
metrics = sorted(metric_names)
# Collect referenced metric ids and fetch their values arrays
metric_ids = collect_metric_ids_from_runs(runs)
metrics_values_map = fetch_metrics_values_map(client, resolved_db_name, metric_ids)
# Distinct result keys
result_keys = set()
for r in runs:
res = r.get("result", None)
if isinstance(res, dict):
for k in res.keys():
if isinstance(k, str) and k.strip():
result_keys.add(k)
results_keys_sorted = sorted(result_keys)
count = len(runs)
status_text = f"Connected. Database '{resolved_db_name}' has {count} run(s)."
# Preserve previously selected keys (intersect with available)
existing_selected = []
if existing_config_store and isinstance(existing_config_store, dict):
existing_selected = list(existing_config_store.get("selected", []) or [])
merged_selected = [k for k in existing_selected if k in set(keys)]
config_store = {"available": keys, "selected": merged_selected}
return status_text, "success", True, runs, config_store, metrics, metrics_values_map, results_keys_sorted
except Exception as exc:
status_text = f"Connected, but failed to query runs/config keys: {exc}"
return status_text, "danger", True, dash.no_update, dash.no_update, dash.no_update, dash.no_update, dash.no_update
@app.callback(
Output("experiments-table", "columns"),
Output("experiments-table", "data"),
Input("runs-cache", "data"),
Input("config-keys-store", "data"),
Input("filters-store", "data"),
Input("results-select", "value"),
)
def refresh_table(runs_cache, config_store, filters_store, selected_result_keys):
runs = runs_cache or []
selected = (config_store or {}).get("selected", [])
# Apply filters to runs before building table
active_filters = filters_store or {}
def row_passes_filters(run_cfg: Dict) -> bool:
for key in selected:
f = active_filters.get(key) if isinstance(active_filters, dict) else None
if not f:
continue
value = run_cfg.get(key, None) if isinstance(run_cfg, dict) else None
# Boolean filter
mode = f.get("mode") if isinstance(f, dict) else None
if mode in ("true", "false"):
if not isinstance(value, bool):
return False
desired = (mode == "true")
if value != desired:
return False
# Numeric filter
has_min = "min" in f and f.get("min") is not None
has_max = "max" in f and f.get("max") is not None
if has_min or has_max:
if not isinstance(value, (int, float)) or isinstance(value, bool):
return False
if has_min and value < f.get("min"):
return False
if has_max and value > f.get("max"):
return False
# String filter (multi-select)
values = f.get("values") if isinstance(f, dict) else None
if isinstance(values, list) and len(values) > 0:
if not isinstance(value, str):
return False
if value not in values:
return False
return True
filtered_runs = []
for run in runs:
cfg = run.get("config", {}) or {}
if row_passes_filters(cfg):
filtered_runs.append(run)
columns, rows = build_table_from_runs(filtered_runs, selected)
# Optionally include selected results columns from info.result
result_keys = [k for k in (selected_result_keys or []) if isinstance(k, str) and k.strip()]
if len(result_keys) > 0:
for key in result_keys:
columns.append({"name": key, "id": f"result:{key}"})
for idx, run in enumerate(filtered_runs):
if idx >= len(rows):
continue
r = run.get("result", None)
if not isinstance(r, dict) or len(r) == 0:
for key in result_keys:
rows[idx][f"result:{key}"] = ""
else:
for key in result_keys:
val = r.get(key, None)
if val is None:
rows[idx][f"result:{key}"] = ""
else:
try:
rows[idx][f"result:{key}"] = json.dumps(val, ensure_ascii=False, default=str) if isinstance(val, (list, dict)) else val
except Exception:
rows[idx][f"result:{key}"] = str(val)
return columns, rows
@app.callback(
Output("download-exp-modal", "is_open"),
Input("download-exp-open", "n_clicks"),
Input("download-exp-cancel", "n_clicks"),
Input("download-exp-confirm", "n_clicks"),
State("download-exp-modal", "is_open"),
prevent_initial_call=True,
)
def toggle_download_exp_modal(open_clicks, cancel_clicks, confirm_clicks, is_open):
return not is_open
@app.callback(
Output("download-exp-csv", "data"),
Input("download-exp-confirm", "n_clicks"),
State("download-exp-filename", "value"),
State("experiments-table", "columns"),
State("experiments-table", "data"),
prevent_initial_call=True,
)
def download_exp_csv(n_clicks, filename, columns, data_rows):
if not n_clicks:
return no_update
rows = data_rows or []
cols = columns or []
if len(rows) == 0 or len(cols) == 0:
return no_update
col_ids = [c.get("id") for c in cols if isinstance(c, dict) and c.get("id")]
col_names = [c.get("name", c.get("id")) for c in cols]
buf = io.StringIO()
writer = csv.writer(buf)
writer.writerow(col_names)
def stringify(v):
if isinstance(v, (list, dict, tuple)):
try:
return json.dumps(v, ensure_ascii=False, default=str)
except Exception:
return str(v)
return v
for row in rows:
writer.writerow([stringify(row.get(cid, "")) for cid in col_ids])
csv_str = buf.getvalue()
buf.close()
safe_name = (filename or "").strip() or "experiments.csv"
if not safe_name.lower().endswith(".csv"):
safe_name += ".csv"
return dcc.send_string(csv_str, safe_name)
@app.callback(
Output("metrics-steps-table", "columns"),
Output("metrics-steps-table", "data"),
Input("runs-cache", "data"),
Input("config-keys-store", "data"),
Input("filters-store", "data"),
Input("metrics-select", "value"),
Input("metrics-values-store", "data"),
)
def refresh_metrics_steps_table(runs_cache, config_store, filters_store, selected_metrics_names, metrics_values_map):
runs = runs_cache or []
selected = (config_store or {}).get("selected", [])
metrics_values_map = metrics_values_map or {}
selected_metrics = [m for m in (selected_metrics_names or []) if isinstance(m, str) and m.strip()]
# Apply same filters as experiments table
active_filters = filters_store or {}
def row_passes_filters(run_cfg: Dict) -> bool:
for key in selected:
f = active_filters.get(key) if isinstance(active_filters, dict) else None
if not f:
continue
value = run_cfg.get(key, None) if isinstance(run_cfg, dict) else None
mode = f.get("mode") if isinstance(f, dict) else None
if mode in ("true", "false"):
if not isinstance(value, bool):
return False
desired = (mode == "true")
if value != desired:
return False
has_min = "min" in f and f.get("min") is not None
has_max = "max" in f and f.get("max") is not None
if has_min or has_max:
if not isinstance(value, (int, float)) or isinstance(value, bool):
return False
if has_min and value < f.get("min"):
return False
if has_max and value > f.get("max"):
return False
values = f.get("values") if isinstance(f, dict) else None
if isinstance(values, list) and len(values) > 0:
if not isinstance(value, str):