-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscreens.py
More file actions
1244 lines (1138 loc) · 46.5 KB
/
Copy pathscreens.py
File metadata and controls
1244 lines (1138 loc) · 46.5 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
from __future__ import annotations
# import contextlib
import logging
import subprocess
from datetime import datetime
from functools import partial
from pathlib import Path
from typing import (
Any,
Callable,
Dict,
List,
NamedTuple,
Optional,
OrderedDict,
Type,
TypeVar,
)
from pydantic import BaseModel, ValidationError
from rich.box import SQUARE
from rich.panel import Panel
from textual.app import ScreenStackError
from textual.containers import VerticalScroll
from textual.message import Message
from textual.reactive import reactive
from textual.screen import Screen
from textual.widget import Widget
from textual.widgets import (
Button,
DataTable,
DirectoryTree,
Footer,
Header,
Input,
Label,
ProgressBar,
RadioButton,
RadioSet,
RichLog,
Static,
Switch,
Tree,
)
from werkzeug.utils import secure_filename
from murfey.client.contexts.spa import SPAModularContext
from murfey.client.contexts.tomo import TomographyContext
from murfey.client.destinations import determine_default_destination
from murfey.client.gain_ref import determine_gain_ref
from murfey.client.rsync import RSyncer
from murfey.util import posix_path
from murfey.util.client import (
capture_delete,
capture_get,
capture_post,
get_machine_config_client,
read_config,
)
from murfey.util.models import ProcessingParametersSPA, ProcessingParametersTomo
log = logging.getLogger("murfey.tui.screens")
ReactiveType = TypeVar("ReactiveType")
token = read_config()["Murfey"].get("token", "")
instrument_name = read_config()["Murfey"].get("instrument_name", "")
class InputResponse(NamedTuple):
question: str
allowed_responses: List[str] | None = None
default: str = ""
callback: Callable | None = None
key_change_callback: Callable | None = None
kwargs: dict | None = None
form: OrderedDict[str, Any] | None = None
model: BaseModel | None = None
class LogBook(RichLog):
class Log(Message):
def __init__(self, log_renderable):
self.renderable = log_renderable
super().__init__()
class InfoWidget(Widget):
text: reactive[str] = reactive("")
def __init__(self, text: str, **kwargs):
super().__init__(**kwargs)
self.text = text
def render(self) -> Panel:
return Panel(self.text, style=("on dark_magenta"), box=SQUARE)
def _key_change(self, input_char: str | None):
if input_char is None:
self.text = self.text[:-1]
return
self.text += input_char
class QuickPrompt:
def __init__(self, text: str, options: List[str]):
self._text = text
self._options = options
self.warn = False
def __repr__(self):
return repr(self._text)
def __str__(self):
return self._text
def __iter__(self):
return iter(self._options)
def __bool__(self):
return bool(self._text)
def validate_form(form: dict, model: BaseModel) -> bool:
try:
convert = lambda x: None if x == "None" else x
validated = model(**{k: convert(v) for k, v in form.items()})
log.info(validated.model_dump())
return True
except (AttributeError, ValidationError) as e:
log.warning(f"Form validation failed: {str(e)}")
return False
class _DirectoryTree(DirectoryTree):
valid_selection = reactive(False)
def __init__(self, *args, data_directories: List[Path] | None = None, **kwargs):
super().__init__(*args, **kwargs)
self._selected_path = self.path
self._data_directories = data_directories or []
def on_tree_node_selected(self, event: Tree.NodeSelected) -> None:
event.stop()
dir_entry = event.node.data.path
if dir_entry is None:
return
if dir_entry.is_dir():
self._selected_path = dir_entry
if not self._data_directories:
self.valid_selection = True
return
for d in self._data_directories:
if Path(self._selected_path).absolute().is_relative_to(d.absolute()):
self.valid_selection = True
break
else:
self.valid_selection = False
else:
self.valid_selection = False
class _DirectoryTreeGain(DirectoryTree):
valid_selection = reactive(False)
def __init__(self, gain_reference: Path, *args, **kwargs):
super().__init__(*args, **kwargs)
self._gain_reference = gain_reference
def on_tree_node_selected(self, event: Tree.NodeSelected) -> None:
event.stop()
dir_entry = event.node.data.path
if dir_entry is None:
return
if not dir_entry.is_dir():
self.valid_selection = True
self._gain_reference = dir_entry
else:
self.valid_selection = False
class LaunchScreen(Screen):
_launch_btn: Button | None = None
def __init__(
self, *args, basepath: Path = Path("."), add_basepath: bool = False, **kwargs
):
super().__init__(*args, **kwargs)
self._selected_dir = basepath
self._add_basepath = add_basepath
self._context: Type[SPAModularContext] | Type[TomographyContext]
self._context = SPAModularContext
def compose(self):
machine_data = capture_get(
base_url=str(self.app._environment.url.geturl()),
router_name="session_control.router",
function_name="machine_info_by_instrument",
token=token,
instrument_name=instrument_name,
).json()
self._dir_tree = _DirectoryTree(
str(self._selected_dir),
data_directories=machine_data.get("data_directories", []),
id="dir-select",
)
yield self._dir_tree
text_log = RichLog(id="selected-directories")
widgets = [text_log, Button("Clear", id="clear")]
text_log_block = VerticalScroll(*widgets, id="selected-directories-vert")
yield text_log_block
text_log.write("Selected directories:\n")
btn_disabled = True
for d in machine_data.get("data_directories", []):
if (
Path(self._dir_tree._selected_path)
.absolute()
.is_relative_to(Path(d).absolute())
or self.app._environment.processing_only_mode
):
btn_disabled = False
break
self._launch_btn = Button("Launch", id="launch", disabled=btn_disabled)
self._add_btn = Button("Add directory", id="add", disabled=btn_disabled)
self.watch(self._dir_tree, "valid_selection", self._check_valid_selection)
yield self._add_btn
yield self._launch_btn
yield Button("Quit", id="quit")
def on_mount(self):
if self._add_basepath:
self._add_directory(str(self._selected_dir))
def _check_valid_selection(self, valid: bool):
if self._add_btn:
if valid:
self._add_btn.disabled = False
else:
self._add_btn.disabled = True
def _add_directory(self, directory: str, add_destination: bool = True):
source = Path(self._dir_tree.path).absolute() / directory
if add_destination:
for s in self.app._environment.sources:
if source.is_relative_to(s):
return
self.app._environment.sources.append(source)
self.app._default_destinations[source] = f"{datetime.now().year}"
if self._launch_btn:
self._launch_btn.disabled = False
self.query_one("#selected-directories").write(str(source) + "\n")
def on_button_pressed(self, event: Button.Pressed) -> None:
if event.button.id == "quit":
self.app.clean_up_quit()
elif event.button.id == "add":
self._add_directory(self._dir_tree._selected_path)
elif event.button.id == "launch":
text = self.app._visit
visit_path = ""
transfer_routes = {}
for s, defd in self.app._default_destinations.items():
_default = determine_default_destination(
self.app._visit,
s,
defd,
self.app._environment,
self.app.analysers,
token,
touch=True,
)
visit_path = defd + f"/{text}"
if self.app._environment.processing_only_mode:
self.app._start_rsyncer(
Path(_default), _default, visit_path=visit_path
)
transfer_routes[s] = _default
self.app.install_screen(
DestinationSelect(transfer_routes, self._context),
"destination-select-screen",
)
self.app.pop_screen()
self.app.push_screen("destination-select-screen")
elif event.button.id == "clear":
sel_dir = self.query_one("#selected-directories")
for line in sel_dir.lines[1:]:
source = Path(line.text)
if source in self.app._environment.sources:
self.app._environment.sources.remove(source)
if self.app._default_destinations.get(source):
del self.app._default_destinations[source]
sel_dir.clear()
sel_dir.write("Selected directories:\n")
class ConfirmScreen(Screen):
def __init__(
self,
prompt: str,
*args,
params: dict | None = None,
pressed_callback: Callable | None = None,
button_names: dict | None = None,
push: str = "main",
**kwargs,
):
super().__init__(*args, **kwargs)
self._prompt = prompt
self._params = params or {}
self._callback = pressed_callback
self._button_names = button_names or {}
self._push = push
def compose(self):
if self._params:
dt = DataTable(id="prompt")
keys = list(self._params.keys())
dt.add_columns(*keys)
dt.add_rows([[self._params[k] for k in keys]])
yield dt
else:
yield Static(self._prompt, id="prompt")
yield Button(self._button_names.get("launch") or "Launch", id="launch")
yield Button(self._button_names.get("quit") or "Back", id="quit")
def on_button_pressed(self, event: Button.Pressed) -> None:
if event.button.id == "quit":
self.app.pop_screen()
self.app.uninstall_screen("confirm")
else:
while True:
try:
if self.app.screen._name == "main":
break
self.app.pop_screen()
except ScreenStackError:
break
if self._push:
log.info(f"Pushing screen {self._push}")
self.app.push_screen(self._push)
self.app.uninstall_screen("confirm")
if self._callback and event.button.id == "launch":
self._callback(params=self._params)
class ProcessingForm(Screen):
_form = reactive({})
_vert = None
def __init__(
self,
form: dict,
*args,
**kwargs,
):
super().__init__(*args, **kwargs)
self._form = form
self._inputs: Dict[Input, str] = {}
def compose(self):
inputs = []
analyser = list(self.app.analysers.values())[0]
for k in analyser._context.user_params + analyser._context.metadata_params:
t = k.label
inputs.append(Label(t, classes="label"))
if self._form.get(k.name) in ("true", "True", True):
i = Switch(value=True, classes="input", id=f"switch_{k.name}")
elif self._form.get(k.name) in ("false", "False", False):
i = Switch(value=False, classes="input", id=f"switch_{k.name}")
else:
i = Input(placeholder=t, classes="input", id=f"input_{k.name}")
default = self._form.get(k.name, str(k.default))
i.value = "None" if default is None else default
self._inputs[i] = k.name
inputs.append(i)
confirm_btn = Button("Confirm", id="confirm-btn")
if self._form.get("motion_corr_binning") == "2":
self._vert = VerticalScroll(
*inputs,
Label("Collected in counting mode:"),
Switch(id="superres", value=True, classes="input"),
confirm_btn,
id="input-form",
)
else:
self._vert = VerticalScroll(*inputs, confirm_btn, id="input-form")
yield self._vert
def _write_params(
self,
params: dict | None = None,
model: ProcessingParametersTomo | ProcessingParametersSPA | None = None,
):
if params:
try:
analyser = [a for a in self.app.analysers.values() if a._context][0]
except IndexError:
return
for k in analyser._context.user_params + analyser._context.metadata_params:
self.app.query_one("#info").write(f"{k.label}: {params.get(k.name)}")
self.app._start_dc(params)
if model == ProcessingParametersTomo:
capture_post(
base_url=str(self.app._environment.url.geturl()),
router_name="workflow.tomo_router",
function_name="register_tomo_proc_params",
token=token,
session_id=self.app._environment.murfey_session,
data=params,
)
elif model == ProcessingParametersSPA:
capture_post(
base_url=str(self.app._environment.url.geturl()),
router_name="workflow.spa_router",
function_name="register_spa_proc_params",
token=token,
session_id=self.app._environment.murfey_session,
data=params,
)
capture_post(
base_url=str(self.app._environment.url.geturl()),
router_name="workflow.spa_router",
function_name="flush_spa_processing",
token=token,
visit_name=self.app._environment.visit,
session_id=self.app._environment.murfey_session,
)
def on_switch_changed(self, event):
if event.switch.id == "superres":
pix_size = self.query_one("#input_pixel_size_on_image")
motion_corr_binning = self.query_one("#input_motion_corr_binning")
if event.value:
pix_size.value = str(float(pix_size.value) / 2)
motion_corr_binning.value = "2"
else:
pix_size.value = str(float(pix_size.value) * 2)
motion_corr_binning.value = "1"
else:
k = self._inputs[event.switch]
self._form[k] = event.value
def on_input_changed(self, event):
k = self._inputs[event.input]
self._form[k] = event.value
def on_button_pressed(self, event):
model = None
if self.app.analysers.get(Path(self._form.get("source", ""))):
if model := self.app.analysers[Path(self._form["source"])].parameters_model:
valid = validate_form(self._form, model)
if not valid:
return
if "confirm" not in self.app._installed_screens:
self.app.install_screen(
ConfirmScreen(
"Launch processing?",
params=self._form,
pressed_callback=partial(self._write_params, model=model),
),
"confirm",
)
self.app.push_screen("confirm")
class SwitchSelection(Screen):
def __init__(
self,
name: str,
elements: List[str],
switch_label: str,
switch_status: bool = True,
*args,
**kwargs,
):
super().__init__(*args, **kwargs)
self._elements = elements
self._switch_status = switch_status
self._switch_label = switch_label
self._name = name
def compose(self):
hovers = (
[
Button(e, id=f"btn-{self._name}-{e}", classes=f"btn-{self._name}")
for e in self._elements
]
if self._elements
else [Button("No elements found")]
)
yield VerticalScroll(*hovers, id=f"select-{self._name}")
yield Static(self._switch_label, id=f"label-{self._name}")
yield Switch(id=f"switch-{self._name}", value=self._switch_status)
def on_switch_changed(self, event):
self._switch_status = event.value
class SessionSelection(Screen):
def __init__(
self, sessions: List[str], sessions_with_client: List[str], *args, **kwargs
):
super().__init__(*args, **kwargs)
self._sessions = sessions
self._sessions_with_client = sessions_with_client
self._name = "session"
def compose(self):
hovers = (
[
Button(e, id=f"btn-{self._name}-{e}", classes=f"btn-{self._name}")
for e in self._sessions
]
if self._sessions
else [Button("No elements found")]
)
deletes = (
[
Button(
f"Remove {e}",
id=f"btn-{self._name}-{e}-del",
classes=f"btn-{self._name}",
)
for e in self._sessions
]
if self._sessions
else [Button("No elements found")]
)
yield VerticalScroll(
*[v for pair in zip(hovers, deletes) for v in pair],
id=f"select-{self._name}",
)
yield Button(
"New session", id=f"btn-{self._name}-new", classes=f"btn-{self._name}"
)
def on_button_pressed(self, event: Button.Pressed):
if event.button.id.endswith("new"):
session_id = None
self.app.pop_screen()
elif event.button.id.endswith("del"):
session_id = int(
str(event.button.label.split(":")[0]).replace("Remove ", "")
)
self.app.pop_screen()
self.app.install_screen(
ConfirmScreen(
(
f"Remove session {session_id} [WARNING: there are clients already using this session]"
if str(event.button.label) in self._sessions_with_client
else f"Remove session {session_id}"
),
pressed_callback=partial(self._remove_session, session_id),
button_names={"launch": "Yes"},
push="visit-select-screen",
),
"confirm",
)
self.app.push_screen("confirm")
return
else:
self.app._environment.murfey_session = int(
str(event.button.label.split(":")[0])
)
session_id = self.app._environment.murfey_session
self.app.pop_screen()
session_name = "Client connection"
self.app._environment.murfey_session = capture_post(
base_url=str(self.app._environment.url.geturl()),
router_name="session_control.router",
function_name="link_client_to_session",
token=token,
instrument_name=self.app._environment.instrument_name,
client_id=self.app._environment.client_id,
data={"session_id": session_id, "session_name": session_name},
).json()
def _remove_session(self, session_id: int, **kwargs):
capture_delete(
base_url=str(self.app._environment.url.geturl()),
router_name="session_control.router",
function_name="remove_session",
token=token,
session_id=session_id,
)
exisiting_sessions = capture_get(
base_url=str(self.app._environment.url.geturl()),
router_name="session_control.router",
function_name="get_sessions",
token=token,
).json()
self.app.uninstall_screen("session-select-screen")
if exisiting_sessions:
self.app.install_screen(
SessionSelection(
[
f"{s['session']['id']}: {s['session']['name']}"
for s in exisiting_sessions
],
[
f"{s['session']['id']}: {s['session']['name']}"
for s in exisiting_sessions
if s["clients"]
],
),
"session-select-screen",
)
self.app.push_screen("session-select-screen")
else:
session_name = "Client connection"
resp = capture_post(
base_url=str(self.app._environment.url.geturl()),
router_name="session_control.router",
function_name="link_client_to_session",
token=token,
instrument_name=self.app._environment.instrument_name,
client_id=self.app._environment.client_id,
data={"session_id": None, "session_name": session_name},
)
if resp:
self.app._environment.murfey_session = resp.json()
class VisitSelection(SwitchSelection):
def __init__(self, visits: List[str], *args, **kwargs):
super().__init__(
"visit",
visits,
"Create visit directory (suggested)",
*args,
**kwargs,
)
def on_button_pressed(self, event: Button.Pressed):
text = str(event.button.label)
self.app._visit = text
self.app._environment.visit = text
response = capture_post(
base_url=str(self.app._environment.url.geturl()),
router_name="session_control.router",
function_name="register_client_to_visit",
token=token,
visit_name=text,
data={"id": self.app._environment.client_id},
)
log.info(f"Posted visit registration: {response.status_code}")
machine_data = capture_get(
base_url=str(self.app._environment.url.geturl()),
router_name="session_control.router",
function_name="machine_info_by_instrument",
token=token,
instrument_name=instrument_name,
).json()
if self._switch_status:
self.app.install_screen(
DirectorySelection(
[
path
for path in machine_data.get("data_directories", [])
if Path(path).exists()
]
),
"directory-select",
)
self.app.pop_screen()
if machine_data.get("gain_reference_directory"):
self.app.install_screen(
GainReference(
determine_gain_ref(Path(machine_data["gain_reference_directory"])),
self._switch_status,
),
"gain-ref-select",
)
self.app.push_screen("gain-ref-select")
else:
if self._switch_status:
self.app.push_screen("directory-select")
else:
self.app.install_screen(LaunchScreen(basepath=Path("./")), "launcher")
self.app.push_screen("launcher")
if machine_data.get("upstream_data_directories"):
upstream_downloads = capture_get(
base_url=str(self.app._environment.url.geturl()),
router_name="session_control.correlative_router",
function_name="find_upstream_visits",
token=token,
session_id=self.app._environment.murfey_session,
).json()
self.app.install_screen(
UpstreamDownloads(upstream_downloads), "upstream-downloads"
)
self.app.push_screen("upstream-downloads")
class VisitCreation(Screen):
# This allows for the manual creation of a visit name when there is no LIMS system to provide it
# Shares a lot of code with VisitSelection, should be neatened up at some point
visit_name: reactive[str] = reactive("")
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def compose(self):
yield Input(placeholder="Visit name", classes="input-visit-name")
yield Button("Create visit", classes="btn-visit-create")
def on_input_changed(self, event):
self.visit_name = event.value
def on_button_pressed(self, event: Button.Pressed):
text = str(self.visit_name)
self.app._visit = text
self.app._environment.visit = text
response = capture_post(
base_url=str(self.app._environment.url.geturl()),
router_name="session_control.router",
function_name="register_client_to_visit",
token=token,
visit_name=text,
data={"id": self.app._environment.client_id},
)
log.info(f"Posted visit registration: {response.status_code}")
machine_data = capture_get(
base_url=str(self.app._environment.url.geturl()),
router_name="session_control.router",
function_name="machine_info_by_instrument",
token=token,
instrument_name=instrument_name,
).json()
self.app.install_screen(
DirectorySelection(
[
path
for path in machine_data.get("data_directories", [])
if Path(path).exists()
]
),
"directory-select",
)
self.app.pop_screen()
if machine_data.get("gain_reference_directory"):
self.app.install_screen(
GainReference(
determine_gain_ref(Path(machine_data["gain_reference_directory"])),
True,
),
"gain-ref-select",
)
self.app.push_screen("gain-ref-select")
else:
self.app.push_screen("directory-select")
if machine_data.get("upstream_data_directories"):
upstream_downloads = capture_get(
base_url=str(self.app._environment.url.geturl()),
router_name="session_control.correlative_router",
function_name="find_upstream_visits",
token=token,
session_id=self.app._environment.murfey_session,
).json()
self.app.install_screen(
UpstreamDownloads(upstream_downloads), "upstream-downloads"
)
self.app.push_screen("upstream-downloads")
class UpstreamDownloads(Screen):
def __init__(self, connected_visits: Dict[str, Path], *args, **kwargs):
super().__init__(*args, **kwargs)
self._connected_visits = connected_visits
def compose(self):
visit_buttons = [
Button(cv, classes="btn-directory") for cv in self._connected_visits.keys()
]
yield VerticalScroll(*visit_buttons)
yield Button("Skip", classes="btn-directory")
def on_button_pressed(self, event: Button.Pressed):
machine_data = capture_get(
base_url=str(self.app._environment.url.geturl()),
router_name="session_control.router",
function_name="machine_info_by_instrument",
token=token,
instrument_name=instrument_name,
).json()
if machine_data.get("upstream_data_download_directory"):
# Create the directory locally to save files to
download_dir = Path(machine_data["upstream_data_download_directory"]) / str(
event.button.label
)
download_dir.mkdir(exist_ok=True)
# Get the paths to the TIFF files generated previously under the same session ID
upstream_tiff_paths_response = capture_get(
base_url=str(self.app._environment.url.geturl()),
router_name="session_control.correlative_router",
function_name="gather_upstream_tiffs",
token=token,
visit_name=event.button.label,
session_id=self.app._environment.murfey_session,
)
upstream_tiff_paths = upstream_tiff_paths_response.json() or []
# Request to download the TIFF files found
for tp in upstream_tiff_paths:
(download_dir / tp).parent.mkdir(exist_ok=True, parents=True)
# Write TIFF to the specified file path
stream_response = capture_get(
base_url=str(self.app._environment.url.geturl()),
router_name="session_control.correlative_router",
function_name="get_tiff",
token=token,
visit_name=event.button.label,
session_id=self.app._environment.murfey_session,
tiff_path=tp,
)
# Write the file chunk-by-chunk to avoid hogging memory
with open(download_dir / tp, "wb") as utiff:
for chunk in stream_response.iter_content(chunk_size=32 * 1024**2):
utiff.write(chunk)
self.app.pop_screen()
class GainReference(Screen):
def __init__(self, gain_reference: Path, switch_status: bool, *args, **kwargs):
super().__init__(*args, **kwargs)
self._gain_reference = gain_reference
self._switch_status = switch_status
def compose(self):
self._dir_tree = _DirectoryTreeGain(
self._gain_reference,
str(self._gain_reference.parent.parent),
id="gain-select",
)
yield self._dir_tree
self._launch_btn = Button("Launch", id="launch")
self.watch(self._dir_tree, "valid_selection", self._check_valid_selection)
yield Button(
f"Suggested gain reference: {self._gain_reference.parent / self._gain_reference.name}",
id="suggested-gain-ref",
)
yield self._launch_btn
yield Button("No gain", id="skip-gain")
def _check_valid_selection(self, valid: bool):
if self._launch_btn:
if valid:
self._launch_btn.disabled = False
else:
self._launch_btn.disabled = True
def on_button_pressed(self, event):
if event.button.id == "skip-gain":
self.app.pop_screen()
else:
if event.button.id == "suggested-gain-ref":
self._dir_tree._gain_reference = self._gain_reference
visit_path = f"{datetime.now().year}/{self.app._environment.visit}"
# Set up rsync command
rsync_cmd = [
"rsync",
f"{posix_path(self._dir_tree._gain_reference)!r}",
f"{self.app._environment.rsync_url or self.app._environment.url.hostname}::{self.app._machine_config.get('rsync_module', 'data')}/{visit_path}/processing/{secure_filename(self._dir_tree._gain_reference.name)}",
]
# Encase in bash shell
cmd = ["bash", "-c", " ".join(rsync_cmd)]
if self.app._environment.demo:
log.info(f"Would perform {' '.join(cmd)}")
else:
# Run rsync subprocess
gain_rsync = subprocess.run(cmd)
if gain_rsync.returncode:
log.warning(
f"Gain reference file {posix_path(self._dir_tree._gain_reference)!r} was not successfully transferred to {visit_path}/processing"
)
process_gain_response = capture_post(
base_url=str(self.app._environment.url.geturl()),
router_name="file_io_instrument.router",
function_name="process_gain",
token=token,
session_id=self.app._environment.murfey_session,
data={
"gain_ref": str(self._dir_tree._gain_reference),
"eer": bool(
self.app._machine_config.get("external_executables_eer")
),
},
)
if str(process_gain_response.status_code).startswith("4"):
log.warning(
f"Gain processing failed: status code {process_gain_response.status_code}"
)
else:
log.info(
f"Gain reference file {process_gain_response.json().get('gain_ref')}"
)
self.app._environment.gain_ref = process_gain_response.json().get(
"gain_ref"
)
if self._switch_status:
self.app.push_screen("directory-select")
else:
self.app.install_screen(LaunchScreen(basepath=Path("./")), "launcher")
self.app.push_screen("launcher")
class DirectorySelection(SwitchSelection):
def __init__(self, directories: List[str], *args, **kwargs):
super().__init__(
"directory",
directories,
"Automatically transfer and trigger processing for new directories (recommended)",
*args,
**kwargs,
)
def on_button_pressed(self, event: Button.Pressed):
self.app._multigrid = self._switch_status
visit_dir = Path(str(event.button.label)).absolute() / self.app._visit
visit_dir.mkdir(exist_ok=True)
self.app._set_default_acquisition_directories(visit_dir)
machine_config = get_machine_config_client(
str(self.app._environment.url.geturl()),
token,
instrument_name=self.app._environment.instrument_name,
demo=self.app._environment.demo,
)
for dir in machine_config["create_directories"]:
(visit_dir / dir).mkdir(exist_ok=True)
self.app.install_screen(
LaunchScreen(basepath=visit_dir, add_basepath=True), "launcher"
)
self.app.pop_screen()
self.app.push_screen("launcher")
class DestinationSelect(Screen):
def __init__(
self,
transfer_routes: Dict[Path, str],
context: Type[SPAModularContext] | Type[TomographyContext],
*args,
destination_overrides: Optional[Dict[Path, str]] = None,
use_transfer_routes: bool = False,
**kwargs,
):
super().__init__(*args, **kwargs)
self._transfer_routes = transfer_routes
self._destination_overrides: Dict[Path, str] = destination_overrides or {}
self._user_params: Dict[str, str] = {}
self._inputs: Dict[Input, str] = {}
self._context = context
self._use_transfer_routes = use_transfer_routes
def compose(self):
bulk = []
with RadioSet():
yield RadioButton("SPA", value=self._context is SPAModularContext)
yield RadioButton("Tomography", value=self._context is TomographyContext)
if self.app._multigrid:
machine_config = get_machine_config_client(
str(self.app._environment.url.geturl()),
token,
instrument_name=self.app._environment.instrument_name,
)
destinations = []
if self._destination_overrides:
for k, v in self._destination_overrides.items():
destinations.append(v)
bulk.append(Label(f"Copy the source {k} to:"))
bulk.append(
Input(
value=v,
id=f"destination-{str(k)}",
classes="input-destination",
)
)
else:
for s in self._transfer_routes.keys():
for d in s.glob("*"):
if (
d.is_dir()
and d.name not in machine_config["create_directories"]
):
dest = determine_default_destination(
self.app._visit,
s,
f"{datetime.now().year}",
self.app._environment,
self.app.analysers,