-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclem.py
More file actions
875 lines (792 loc) · 27.7 KB
/
clem.py
File metadata and controls
875 lines (792 loc) · 27.7 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
from __future__ import annotations
import re
import traceback
from ast import literal_eval
from importlib.metadata import EntryPoint # type hinting only
from logging import getLogger
from pathlib import Path
from typing import Literal, Optional, Type, Union
from backports.entry_points_selectable import entry_points
from fastapi import APIRouter
from pydantic import BaseModel, validator
from sqlalchemy.exc import NoResultFound
from sqlmodel import Session, select
from murfey.server import _transport_object
from murfey.server.murfey_db import murfey_db
from murfey.util import sanitise
from murfey.util.config import get_machine_config
from murfey.util.db import (
CLEMImageMetadata,
CLEMImageSeries,
CLEMImageStack,
CLEMLIFFile,
CLEMTIFFFile,
)
from murfey.util.db import Session as MurfeySession
# Set up logger
logger = getLogger("murfey.server.api.clem")
# Create APIRouter class object
router = APIRouter()
# Valid file types
valid_file_types = (
".lif",
".tif",
".tiff",
".xlif",
".xml",
)
"""
HELPER FUNCTIONS
"""
def validate_and_sanitise(
file: Path,
session_id: int,
db: Session,
) -> Path:
"""
Performs validation and sanitisation on the incoming file paths, ensuring that
no forbidden characters are present and that the the path points only to allowed
sections of the file server.
Returns the file path as a sanitised string that can be converted into a Path
object again.
NOTE: Due to the instrument name query, 'db' now needs to be passed as an
explicit variable to this function from within a FastAPI endpoint, as using the
instance that was imported directly won't load it in the correct state.
"""
# Resolve symlinks and directory changes to get full file path
full_path = Path(file).resolve()
# Use machine configuration to validate which file base paths are accepted from
instrument_name = (
db.exec(select(MurfeySession).where(MurfeySession.id == session_id))
.one()
.instrument_name
)
machine_config = get_machine_config(instrument_name=instrument_name)[
instrument_name
]
rsync_basepath = machine_config.rsync_basepath.resolve()
# Check that full file path doesn't contain unallowed characters
# Currently allows only:
# - words (alphanumerics and "_"; \w),
# - spaces (\s),
# - periods,
# - dashes,
# - forward slashes ("/")
if bool(re.fullmatch(r"^[\w\s\.\-/]+$", str(full_path))) is False:
raise ValueError(f"Unallowed characters present in {file}")
# Check that it's not accessing somehwere it's not allowed
if not str(full_path).startswith(str(rsync_basepath)):
raise ValueError(f"{file} points to a directory that is not permitted")
# Check that it is of a permitted file type
if f"{full_path.suffix}" not in valid_file_types:
raise ValueError(f"{full_path.suffix} is not a permitted file format")
return full_path
def get_db_entry(
db: Session,
# With the database search funcion having been moved out of the FastAPI
# endpoint, the database now has to be explicitly passed within the FastAPI
# endpoint function in order for it to be loaded in the correct state.
table: Type[
Union[
CLEMImageMetadata,
CLEMImageSeries,
CLEMImageStack,
CLEMLIFFile,
CLEMTIFFFile,
]
],
session_id: int,
file_path: Optional[Path] = None,
series_name: Optional[str] = None,
) -> Union[
CLEMImageMetadata,
CLEMImageSeries,
CLEMImageStack,
CLEMLIFFile,
CLEMTIFFFile,
]:
"""
Searches the CLEM workflow-related tables in the Murfey database for an entry that
matches the file path or series name within a given session. Returns the entry if
a match is found, otherwise register it as a new entry in the database.
"""
# Validate that parameters are provided correctly
if file_path is None and series_name is None:
raise ValueError(
"One of either 'file_path' or 'series_name' has to be provided"
)
if file_path is not None and series_name is not None:
raise ValueError("Only one of 'file_path' or 'series_name' should be provided")
# Validate file path if provided
if file_path is not None:
try:
file_path = validate_and_sanitise(file_path, session_id, db)
except Exception:
raise Exception
# Validate series name to use
if series_name is not None:
if bool(re.fullmatch(r"^[\w\s\.\-/]+$", series_name)) is False:
raise ValueError("One or more characters in the string are not permitted")
# Return database entry if it exists
try:
db_entry = (
db.exec(
select(table)
.where(table.session_id == session_id)
.where(table.file_path == str(file_path))
).one()
if file_path is not None
else db.exec(
select(table)
.where(table.session_id == session_id)
.where(table.series_name == series_name)
).one()
)
# Create and register new entry if not present
except NoResultFound:
db_entry = (
table(
file_path=str(file_path),
session_id=session_id,
)
if file_path is not None
else table(
series_name=series_name,
session_id=session_id,
)
)
db.add(db_entry)
db.commit()
except Exception:
raise Exception
return db_entry
"""
API ENDPOINTS FOR FILE REGISTRATION
"""
@router.post("/sessions/{session_id}/clem/lif_files")
def register_lif_file(
lif_file: Path,
session_id: int,
master_metadata: Optional[Path] = None,
child_metadata: list[Path] = [],
child_series: list[str] = [],
child_stacks: list[Path] = [],
db: Session = murfey_db,
):
# Return or register the LIF file entry
try:
clem_lif_file: CLEMLIFFile = get_db_entry(
db=db,
table=CLEMLIFFile,
session_id=session_id,
file_path=lif_file,
)
except Exception:
logger.error(
"Exception encountered while registering "
f"LIF file {sanitise(str(lif_file))!r}: \n"
f"{traceback.format_exc()}"
)
return False
# Add metadata information if provided
if master_metadata is not None:
try:
master_metadata = validate_and_sanitise(master_metadata, session_id, db)
clem_lif_file.master_metadata = str(master_metadata)
except Exception:
logger.warning(
"Unable to add master metadata information to database entry for "
f"LIF file {sanitise(str(lif_file))!r}: \n"
f"{traceback.format_exc()}"
)
# Register child metadata if provided
for metadata in child_metadata:
try:
metadata_db_entry: CLEMImageMetadata = get_db_entry(
db=db,
table=CLEMImageMetadata,
session_id=session_id,
file_path=metadata,
)
# Append to database entry
clem_lif_file.child_metadata.append(metadata_db_entry)
except Exception:
logger.warning(
"Unable to register "
f"metadata file {sanitise(str(metadata))!r} in association with "
f"LIF file {sanitise(str(lif_file))!r}: \n"
f"{traceback.format_exc()}"
)
continue
# Register child image series if provided
for series in child_series:
try:
series_db_entry: CLEMImageSeries = get_db_entry(
db=db,
table=CLEMImageSeries,
session_id=session_id,
series_name=series,
)
# Append to database entry
clem_lif_file.child_series.append(series_db_entry)
except Exception:
logger.warning(
"Unable to register "
f"metadata file {sanitise(series)!r} in association with "
f"LIF file {sanitise(str(lif_file))!r}: \n"
f"{traceback.format_exc()}"
)
continue
# Register child image stacks if provided
for stack in child_stacks:
try:
stack_db_entry: CLEMImageStack = get_db_entry(
db=db,
table=CLEMImageStack,
session_id=session_id,
file_path=stack,
)
# Append to database entry
clem_lif_file.child_stacks.append(stack_db_entry)
except Exception:
logger.warning(
"Unable to register "
f"image stack {sanitise(str(stack))!r} in association with "
f"LIF file {sanitise(str(lif_file))!r}: \n"
f"{traceback.format_exc()}"
)
continue
# Commit to database
db.add(clem_lif_file)
db.commit()
db.close()
return True
@router.post("/sessions/{session_id}/clem/tiff_files")
def register_tiff_file(
tiff_file: Path,
session_id: int,
associated_metadata: Optional[Path] = None,
associated_series: Optional[str] = None,
associated_stack: Optional[Path] = None,
db: Session = murfey_db,
):
# Get or register the database entry
try:
clem_tiff_file: CLEMTIFFFile = get_db_entry(
db=db,
table=CLEMTIFFFile,
session_id=session_id,
file_path=tiff_file,
)
except Exception:
logger.error(
"Exception encountered while registering "
f"TIFF file {sanitise(str(tiff_file))!r}: \n"
f"{traceback.format_exc()}"
)
return False
# Add metadata if provided
if associated_metadata is not None:
try:
metadata_db_entry: CLEMImageMetadata = get_db_entry(
db=db,
table=CLEMImageMetadata,
session_id=session_id,
file_path=associated_metadata,
)
# Link database entries
clem_tiff_file.associated_metadata = metadata_db_entry
except Exception:
logger.warning(
"Unable to register "
f"metadata file {sanitise(str(associated_metadata))!r} in association with "
f"TIFF file {sanitise(str(tiff_file))!r}: \n"
f"{traceback.format_exc()}"
)
# Add series information if provided
if associated_series is not None:
try:
series_db_entry: CLEMImageSeries = get_db_entry(
db=db,
table=CLEMImageSeries,
session_id=session_id,
series_name=associated_series,
)
# Link database entries
clem_tiff_file.child_series = series_db_entry
except Exception:
logger.warning(
"Unable to register "
f"CLEM series {sanitise(associated_series)!r} in association with "
f"TIFF file {sanitise(str(tiff_file))!r}: \n"
f"{traceback.format_exc()}"
)
# Add image stack information if provided
if associated_stack is not None:
try:
stack_db_entry: CLEMImageStack = get_db_entry(
db=db,
table=CLEMImageStack,
session_id=session_id,
file_path=associated_stack,
)
# Link database entries
clem_tiff_file.child_stack = stack_db_entry
except Exception:
logger.warning(
"Unable to register "
f"image stack {sanitise(str(associated_stack))!r} in association with "
f"{traceback.format_exc()}"
)
# Commit to database
db.add(clem_tiff_file)
db.commit()
db.close()
return True
@router.post("/sessions/{session_id}/clem/metadata_files")
def register_clem_metadata(
metadata_file: Path,
session_id: int,
parent_lif: Optional[Path] = None,
associated_tiffs: list[Path] = [],
associated_series: Optional[str] = None,
associated_stacks: list[Path] = [],
db: Session = murfey_db,
):
# Return database entry if it already exists
try:
clem_metadata: CLEMImageMetadata = get_db_entry(
db=db,
table=CLEMImageMetadata,
session_id=session_id,
file_path=metadata_file,
)
except Exception:
logger.error(
"Exception encountered while registering"
f"metadata file {sanitise(str(metadata_file))!r}"
f"{traceback.format_exc()}"
)
return False
# Register a parent LIF file if provided
if parent_lif is not None:
try:
lif_db_entry: CLEMLIFFile = get_db_entry(
db=db,
table=CLEMLIFFile,
session_id=session_id,
file_path=parent_lif,
)
# Link database entries
clem_metadata.parent_lif = lif_db_entry
except Exception:
logger.warning(
"Unable to register "
f"LIF file {sanitise(str(parent_lif))!r} in association with "
f"metadata file {sanitise(str(metadata_file))!r}: \n"
f"{traceback.format_exc()}"
)
# Register associated TIFF files if provided
for tiff in associated_tiffs:
try:
tiff_db_entry: CLEMTIFFFile = get_db_entry(
db=db,
table=CLEMTIFFFile,
session_id=session_id,
file_path=tiff,
)
# Append entry
clem_metadata.associated_tiffs.append(tiff_db_entry)
except Exception:
logger.warning(
"Unable to register "
f"TIFF file {sanitise(str(tiff))!r} in association with "
f"metadata file {sanitise(str(metadata_file))!r}: \n"
f"{traceback.format_exc()}"
)
continue
# Register associated image series if provided
if associated_series is not None:
try:
series_db_entry: CLEMImageSeries = get_db_entry(
db=db,
table=CLEMImageSeries,
session_id=session_id,
series_name=associated_series,
)
# The link can only be made from series-side; not sure why
series_db_entry.associated_metadata = clem_metadata
db.add(series_db_entry)
db.commit()
except Exception:
logger.warning(
"Unable to register "
f"CLEM series {sanitise(associated_series)!r} in association with "
f"metadata file {sanitise(str(metadata_file))!r}: \n"
f"{traceback.format_exc()}"
)
# Register associated image stacks if provided
for stack in associated_stacks:
try:
stack_db_entry: CLEMImageStack = get_db_entry(
db=db,
table=CLEMImageStack,
session_id=session_id,
file_path=stack,
)
clem_metadata.associated_stacks.append(stack_db_entry)
except Exception:
logger.warning(
"Unable to register "
f"image stack {sanitise(str(stack))!r} in association with "
f"metadata file {sanitise(str(metadata_file))!r}: \n"
f"{traceback.format_exc()}"
)
continue
# Commit to database
db.add(clem_metadata)
db.commit()
db.close()
return True
@router.post("/sessions/{session_id}/clem/image_series")
def register_image_series(
series_name: str,
session_id: int,
parent_lif: Optional[Path] = None,
parent_tiffs: list[Path] = [],
associated_metadata: Optional[Path] = None,
child_stacks: list[Path] = [],
db: Session = murfey_db,
):
# Get or register series
try:
clem_image_series: CLEMImageSeries = get_db_entry(
db=db,
table=CLEMImageSeries,
session_id=session_id,
series_name=series_name,
)
except Exception:
logger.error(
"Exception encountered while registering "
f"CLEM series {sanitise(series_name)!r}: \n"
f"{traceback.format_exc()}"
)
return False
# Register parent LIF file if provided
if parent_lif is not None:
try:
lif_db_entry: CLEMLIFFile = get_db_entry(
db=db,
table=CLEMLIFFile,
session_id=session_id,
file_path=parent_lif,
)
# Link entries
clem_image_series.parent_lif = lif_db_entry
except Exception:
logger.warning(
"Unable to register "
f"LIF file {sanitise(str(parent_lif))!r} in association with "
f"CLEM series {sanitise(series_name)!r}: \n"
f"{traceback.format_exc()}"
)
# Register parent TIFFs if provided
for tiff in parent_tiffs:
try:
tiff_db_entry: CLEMTIFFFile = get_db_entry(
db=db,
table=CLEMTIFFFile,
session_id=session_id,
file_path=tiff,
)
# Append entry
clem_image_series.parent_tiffs.append(tiff_db_entry)
except Exception:
logger.warning(
"Unable to register "
f"TIFF file {sanitise(str(tiff))!r} in association with "
f"CLEM series {sanitise(series_name)!r}: \n"
f"{traceback.format_exc()}"
)
continue # Try next item in loop
# Register associated metadata if provided
if associated_metadata is not None:
try:
metadata_db_entry: CLEMImageMetadata = get_db_entry(
db=db,
table=CLEMImageMetadata,
session_id=session_id,
file_path=associated_metadata,
)
# Link entries
clem_image_series.associated_metadata = metadata_db_entry
except Exception:
logger.warning(
"Unable to register "
f"metadata file {sanitise(str(associated_metadata))!r} in association with "
f"CLEM series {sanitise(series_name)!r}: \n"
f"{traceback.format_exc()}"
)
# Register child image stacks if provided
for stack in child_stacks:
try:
stack_db_entry: CLEMImageStack = get_db_entry(
db=db,
table=CLEMImageStack,
session_id=session_id,
file_path=stack,
)
# Append entry
clem_image_series.child_stacks.append(stack_db_entry)
except Exception:
logger.warning(
"Unable to register "
f"image stack {sanitise(str(stack))!r} in association with "
f"CLEM series {sanitise(series_name)!r}: \n"
f"{traceback.format_exc()}"
)
continue
# Register
db.add(clem_image_series)
db.commit()
db.close()
return True
@router.post("/sessions/{session_id}/clem/image_stacks")
def register_image_stack(
image_stack: Path,
session_id: int,
channel: Optional[str] = None,
parent_lif: Optional[Path] = None,
parent_tiffs: list[Path] = [],
associated_metadata: Optional[Path] = None,
parent_series: Optional[str] = None,
db: Session = murfey_db,
):
# Get or register image stack entry
try:
clem_image_stack: CLEMImageStack = get_db_entry(
db=db,
table=CLEMImageStack,
session_id=session_id,
file_path=image_stack,
)
except Exception:
logger.error(
"Exception encountered while registering "
f"image stack {sanitise(str(image_stack))!r}: \n"
f"{traceback.format_exc()}"
)
return False
# Register channel name if provided
if channel is not None:
clem_image_stack.channel_name = channel
# Register parent LIF file if provided
if parent_lif is not None:
try:
lif_db_entry: CLEMLIFFile = get_db_entry(
db=db,
table=CLEMLIFFile,
session_id=session_id,
file_path=parent_lif,
)
clem_image_stack.parent_lif = lif_db_entry
except Exception:
logger.warning(
"Unable to register "
f"LIF file {sanitise(str(parent_lif))!r} in association with "
f"image stack {sanitise(str(image_stack))!r}: \n"
f"{traceback.format_exc()}"
)
# Register parent TIFF files if provided
for tiff in parent_tiffs:
try:
tiff_db_entry: CLEMTIFFFile = get_db_entry(
db=db,
table=CLEMTIFFFile,
session_id=session_id,
file_path=tiff,
)
# Append entry
clem_image_stack.parent_tiffs.append(tiff_db_entry)
except Exception:
logger.warning(
"Unable to register "
f"TIFF file {sanitise(str(tiff))!r} in association with "
f"image stack {sanitise(str(image_stack))!r}: \n"
f"{traceback.format_exc()}"
)
continue
# Register associated metadata if provided
if associated_metadata is not None:
try:
metadata_db_entry: CLEMImageMetadata = get_db_entry(
db=db,
table=CLEMImageMetadata,
session_id=session_id,
file_path=associated_metadata,
)
# Link entries
clem_image_stack.associated_metadata = metadata_db_entry
except Exception:
logger.warning(
"Unable to register "
f"metadata file {sanitise(str(associated_metadata))!r} in association with "
f"image stack {sanitise(str(image_stack))!r}: \n"
f"{traceback.format_exc()}"
)
# Register parent series if provided
if parent_series is not None:
try:
series_db_entry: CLEMImageSeries = get_db_entry(
db=db,
table=CLEMImageSeries,
session_id=session_id,
series_name=parent_series,
)
# Link entries
clem_image_stack.parent_series = series_db_entry
except Exception:
logger.warning(
"Unable to register "
f"CLEM series {sanitise(parent_series)!r} in association with "
f"image stack {sanitise(str(image_stack))!r}: \n"
f"{traceback.format_exc()}"
)
# Register updates to entry
db.add(clem_image_stack)
db.commit()
db.close()
return True
"""
API ENDPOINTS FOR FILE PROCESSING
"""
@router.post(
"/sessions/{session_id}/clem/preprocessing/process_raw_lifs"
) # API posts to this URL
def process_raw_lifs(
session_id: int,
lif_file: Path,
db: Session = murfey_db,
):
try:
# Try and load relevant Murfey workflow
workflow: EntryPoint = list(
entry_points().select(
group="murfey.workflows", name="clem.process_raw_lifs"
)
)[0]
except IndexError:
raise RuntimeError("The relevant Murfey workflow was not found")
# Get instrument name from the database to load the correct config file
session_row: MurfeySession = db.exec(
select(MurfeySession).where(MurfeySession.id == session_id)
).one()
instrument_name = session_row.instrument_name
# Pass arguments along to the correct workflow
workflow.load()(
# Match the arguments found in murfey.workflows.clem.process_raw_lifs
file=lif_file,
root_folder="images",
session_id=session_id,
instrument_name=instrument_name,
messenger=_transport_object,
)
return True
class TIFFSeriesInfo(BaseModel):
series_name: str
tiff_files: list[Path]
series_metadata: Path
@router.post("/sessions/{session_id}/clem/preprocessing/process_raw_tiffs")
def process_raw_tiffs(
session_id: int,
tiff_info: TIFFSeriesInfo,
db: Session = murfey_db,
):
try:
# Try and load relevant Murfey workflow
workflow: EntryPoint = list(
entry_points().select(
group="murfey.workflows", name="clem.process_raw_tiffs"
)
)[0]
except IndexError:
raise RuntimeError("The relevant Murfey workflow was not found")
# Get instrument name from the database to load the correct config file
session_row: MurfeySession = db.exec(
select(MurfeySession).where(MurfeySession.id == session_id)
).one()
instrument_name = session_row.instrument_name
# Pass arguments to correct workflow
workflow.load()(
# Match the arguments found in murfey.workflows.clem.process_raw_tiffs
tiff_list=tiff_info.tiff_files,
root_folder="images",
session_id=session_id,
instrument_name=instrument_name,
metadata=tiff_info.series_metadata,
messenger=_transport_object,
)
return True
class AlignAndMergeParams(BaseModel):
# Processing parameters
series_name: str
images: list[Path]
metadata: Path
# Optional processing parameters
crop_to_n_frames: Optional[int] = None
align_self: Literal["enabled", ""] = ""
flatten: Literal["mean", "min", "max", ""] = ""
align_across: Literal["enabled", ""] = ""
@validator(
"images",
pre=True,
)
def parse_stringified_list(cls, value):
if isinstance(value, str):
try:
eval_result = literal_eval(value)
if isinstance(eval_result, list):
parent_tiffs = [Path(p) for p in eval_result]
return parent_tiffs
except (SyntaxError, ValueError):
raise ValueError("Unable to parse input")
# Return value as-is; if it fails, it fails
return value
@router.post("/sessions/{session_id}/clem/processing/align_and_merge_stacks")
def align_and_merge_stacks(
session_id: int,
align_and_merge_params: AlignAndMergeParams,
db: Session = murfey_db,
):
try:
# Try and load relevant Murfey workflow
workflow: EntryPoint = list(
entry_points().select(group="murfey.workflows", name="clem.align_and_merge")
)[0]
except IndexError:
raise RuntimeError("The relevant Murfey workflow was not found")
# Get instrument name from the database to load the correct config file
session_row: MurfeySession = db.exec(
select(MurfeySession).where(MurfeySession.id == session_id)
).one()
instrument_name = session_row.instrument_name
# Pass arguments to correct workflow
workflow.load()(
# Match the arguments found in murfey.workflows.clem.align_and_merge
# Session parameters
session_id=session_id,
instrument_name=instrument_name,
# Processing parameters
series_name=align_and_merge_params.series_name,
images=align_and_merge_params.images,
metadata=align_and_merge_params.metadata,
# Optional processing parameters
crop_to_n_frames=align_and_merge_params.crop_to_n_frames,
align_self=align_and_merge_params.align_self,
flatten=align_and_merge_params.flatten,
align_across=align_and_merge_params.align_across,
# Optional session parameters
messenger=_transport_object,
)
return True