-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathcuration.py
More file actions
1840 lines (1476 loc) · 66.1 KB
/
curation.py
File metadata and controls
1840 lines (1476 loc) · 66.1 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
"""
Curation Task dataclasses for managing Curation Tasks in Synapse.
Curation tasks are used to guide data contributors through the process of contributing
data or metadata in Synapse.
"""
from dataclasses import dataclass, field, replace
from typing import Any, AsyncGenerator, Dict, Generator, Optional, Protocol, Union
from opentelemetry import trace
from synapseclient import Synapse
from synapseclient.api import (
create_curation_task,
delete_curation_task,
delete_grid_session,
get_curation_task,
list_curation_tasks,
list_grid_sessions,
update_curation_task,
)
from synapseclient.core.async_utils import (
async_to_sync,
skip_async_to_sync,
wrap_async_generator_to_sync_generator,
)
from synapseclient.core.constants.concrete_types import (
CREATE_GRID_REQUEST,
FILE_BASED_METADATA_TASK_PROPERTIES,
GRID_RECORD_SET_EXPORT_REQUEST,
LIST_GRID_SESSIONS_REQUEST,
LIST_GRID_SESSIONS_RESPONSE,
RECORD_BASED_METADATA_TASK_PROPERTIES,
)
from synapseclient.core.utils import delete_none_keys, merge_dataclass_entities
from synapseclient.models.mixins.asynchronous_job import AsynchronousCommunicator
from synapseclient.models.recordset import ValidationSummary
from synapseclient.models.table_components import Query
@dataclass
class FileBasedMetadataTaskProperties:
"""
A CurationTaskProperties for file-based data, describing where data is uploaded
and a view which contains the annotations.
Represents a [Synapse FileBasedMetadataTaskProperties](https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/curation/metadata/FileBasedMetadataTaskProperties.html).
Attributes:
upload_folder_id: The synId of the folder where data files of this type are to be uploaded
file_view_id: The synId of the FileView that shows all data of this type
"""
upload_folder_id: Optional[str] = None
"""The synId of the folder where data files of this type are to be uploaded"""
file_view_id: Optional[str] = None
"""The synId of the FileView that shows all data of this type"""
def fill_from_dict(
self, synapse_response: Union[Dict[str, Any], Any]
) -> "FileBasedMetadataTaskProperties":
"""
Converts a response from the REST API into this dataclass.
Arguments:
synapse_response: The response from the REST API.
Returns:
The FileBasedMetadataTaskProperties object.
"""
self.upload_folder_id = synapse_response.get("uploadFolderId", None)
self.file_view_id = synapse_response.get("fileViewId", None)
return self
def to_synapse_request(self) -> Dict[str, Any]:
"""
Converts this dataclass to a dictionary suitable for a Synapse REST API request.
Returns:
A dictionary representation of this object for API requests.
"""
request_dict = {"concreteType": FILE_BASED_METADATA_TASK_PROPERTIES}
if self.upload_folder_id is not None:
request_dict["uploadFolderId"] = self.upload_folder_id
if self.file_view_id is not None:
request_dict["fileViewId"] = self.file_view_id
return request_dict
@dataclass
class RecordBasedMetadataTaskProperties:
"""
A CurationTaskProperties for record-based metadata.
Represents a [Synapse RecordBasedMetadataTaskProperties](https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/curation/metadata/RecordBasedMetadataTaskProperties.html).
Attributes:
record_set_id: The synId of the RecordSet that will contain all record-based metadata
"""
record_set_id: Optional[str] = None
"""The synId of the RecordSet that will contain all record-based metadata"""
def fill_from_dict(
self, synapse_response: Union[Dict[str, Any], Any]
) -> "RecordBasedMetadataTaskProperties":
"""
Converts a response from the REST API into this dataclass.
Arguments:
synapse_response: The response from the REST API.
Returns:
The RecordBasedMetadataTaskProperties object.
"""
self.record_set_id = synapse_response.get("recordSetId", None)
return self
def to_synapse_request(self) -> Dict[str, Any]:
"""
Converts this dataclass to a dictionary suitable for a Synapse REST API request.
Returns:
A dictionary representation of this object for API requests.
"""
request_dict = {"concreteType": RECORD_BASED_METADATA_TASK_PROPERTIES}
if self.record_set_id is not None:
request_dict["recordSetId"] = self.record_set_id
return request_dict
def _create_task_properties_from_dict(
properties_dict: Dict[str, Any],
) -> Union[FileBasedMetadataTaskProperties, RecordBasedMetadataTaskProperties]:
"""
Factory method to create the appropriate FileBasedMetadataTaskProperties/RecordBasedMetadataTaskProperties
based on the concreteType.
Arguments:
properties_dict: Dictionary containing task properties data
Returns:
The appropriate FileBasedMetadataTaskProperties/RecordBasedMetadataTaskProperties instance
"""
concrete_type = properties_dict.get("concreteType", "")
if concrete_type == FILE_BASED_METADATA_TASK_PROPERTIES:
return FileBasedMetadataTaskProperties().fill_from_dict(properties_dict)
elif concrete_type == RECORD_BASED_METADATA_TASK_PROPERTIES:
return RecordBasedMetadataTaskProperties().fill_from_dict(properties_dict)
else:
raise ValueError(
f"Unknown concreteType for CurationTaskProperties: {concrete_type}"
)
async def _get_existing_curation_task_id(
project_id: str,
data_type: str,
synapse_client: Optional[Synapse] = None,
) -> Optional[int]:
"""
Helper function to find an existing curation task by project_id and data_type.
Arguments:
project_id: The synId of the project.
data_type: The data type to search for.
synapse_client: The Synapse client to use.
Returns:
The task_id if found, None otherwise.
"""
async for task_dict in list_curation_tasks(
project_id=project_id, synapse_client=synapse_client
):
if task_dict.get("dataType") == data_type:
return task_dict.get("taskId")
return None
class CurationTaskSynchronousProtocol(Protocol):
def get(self, *, synapse_client: Optional[Synapse] = None) -> "CurationTask":
"""
Gets a CurationTask from Synapse by ID.
Arguments:
synapse_client: If not passed in and caching was not disabled by
`Synapse.allow_client_caching(False)` this will use the last created
instance from the Synapse class constructor.
Returns:
CurationTask: The CurationTask object.
Raises:
ValueError: If the CurationTask object does not have a task_id.
Example: Get a curation task by ID
```python
from synapseclient import Synapse
from synapseclient.models import CurationTask
syn = Synapse()
syn.login()
task = CurationTask(task_id=123).get()
print(task.data_type)
print(task.instructions)
```
"""
return self
def delete(
self,
delete_source: bool = False,
*,
synapse_client: Optional[Synapse] = None,
) -> None:
"""
Deletes a CurationTask from Synapse.
Arguments:
delete_source: If True, the associated source data (EntityView or RecordSet) will also be deleted
if the task is a FileBasedMetadataTask or RecordBasedMetadataTask respectively. Defaults to False.
synapse_client: If not passed in and caching was not disabled by
`Synapse.allow_client_caching(False)` this will use the last created
instance from the Synapse class constructor.
Raises:
ValueError: If the CurationTask object does not have a task_id.
Example: Delete a curation task
```python
from synapseclient import Synapse
from synapseclient.models import CurationTask
syn = Synapse()
syn.login()
task = CurationTask(task_id=123)
task.delete()
```
Example: Delete a curation task and its associated data source
```python
from synapseclient import Synapse
from synapseclient.models import CurationTask
syn = Synapse()
syn.login()
task = CurationTask(task_id=123)
task.delete(delete_source=True)
```
"""
return None
def store(self, *, synapse_client: Optional[Synapse] = None) -> "CurationTask":
"""
Creates a new CurationTask or updates an existing one on Synapse.
This method implements non-destructive updates. If a CurationTask with the same
project_id and data_type exists and this instance hasn't been retrieved from
Synapse before, it will merge the existing task data with the current instance
before updating.
Arguments:
synapse_client: If not passed in and caching was not disabled by
`Synapse.allow_client_caching(False)` this will use the last created
instance from the Synapse class constructor.
Returns:
CurationTask: The CurationTask object.
Example: Create a new file-based curation task
```python
from synapseclient import Synapse
from synapseclient.models import CurationTask, FileBasedMetadataTaskProperties
syn = Synapse()
syn.login()
# Create file-based task properties
file_properties = FileBasedMetadataTaskProperties(
upload_folder_id="syn1234567",
file_view_id="syn2345678"
)
# Create the curation task
task = CurationTask(
project_id="syn9876543",
data_type="genomics_data",
instructions="Upload your genomics files to the specified folder",
task_properties=file_properties
)
task = task.store()
print(f"Created task with ID: {task.task_id}")
```
Example: Create a new record-based curation task
```python
from synapseclient import Synapse
from synapseclient.models import CurationTask, RecordBasedMetadataTaskProperties
syn = Synapse()
syn.login()
# Create record-based task properties
record_properties = RecordBasedMetadataTaskProperties(
record_set_id="syn3456789"
)
# Create the curation task
task = CurationTask(
project_id="syn9876543",
data_type="clinical_data",
instructions="Fill out the clinical data form",
task_properties=record_properties
)
task = task.store()
print(f"Created task with ID: {task.task_id}")
```
Example: Update an existing curation task
```python
from synapseclient import Synapse
from synapseclient.models import CurationTask
syn = Synapse()
syn.login()
# Get existing task and update
task = CurationTask(task_id=123).get()
task.instructions = "Updated instructions for data contributors"
task = task.store()
```
"""
return self
@classmethod
def list(
cls,
project_id: str,
*,
synapse_client: Optional[Synapse] = None,
) -> Generator["CurationTask", None, None]:
"""
Generator that yields CurationTasks for a project as they become available.
Arguments:
project_id: The synId of the project.
synapse_client: If not passed in and caching was not disabled by
`Synapse.allow_client_caching(False)` this will use the last created
instance from the Synapse class constructor.
Yields:
CurationTask objects as they are retrieved from the API.
Example: List all curation tasks in a project
```python
from synapseclient import Synapse
from synapseclient.models import CurationTask
syn = Synapse()
syn.login()
# List all curation tasks in the project
for task in CurationTask.list(project_id="syn9876543"):
print(f"Task ID: {task.task_id}")
print(f"Data Type: {task.data_type}")
print(f"Instructions: {task.instructions}")
print("---")
```
"""
yield from wrap_async_generator_to_sync_generator(
async_gen_func=cls.list_async,
project_id=project_id,
synapse_client=synapse_client,
)
@dataclass
@async_to_sync
class CurationTask(CurationTaskSynchronousProtocol):
"""
The CurationTask provides instructions for a Data Contributor on how data or metadata
of a specific type should be both added to a project and curated.
Represents a [Synapse CurationTask](https://rest-docs.synapse.org/org/sagebionetworks/repo/model/curation/CurationTask.html).
Attributes:
task_id: The unique identifier issued to this task when it was created
data_type: Will match the data type that a contributor plans to contribute
project_id: The synId of the project
instructions: Instructions to the data contributor
task_properties: The properties of a CurationTask. This can be either
FileBasedMetadataTaskProperties or RecordBasedMetadataTaskProperties.
etag: Synapse employs an Optimistic Concurrency Control (OCC) scheme to handle
concurrent updates. Since the E-Tag changes every time an entity is updated
it is used to detect when a client's current representation of an entity is
out-of-date.
created_on: (Read Only) The date this task was created
modified_on: (Read Only) The date this task was last modified
created_by: (Read Only) The ID of the user that created this task
modified_by: (Read Only) The ID of the user that last modified this task
Example: Complete curation task workflow
```python
from synapseclient import Synapse
from synapseclient.models import CurationTask, FileBasedMetadataTaskProperties
syn = Synapse()
syn.login()
# Create a new file-based curation task
file_properties = FileBasedMetadataTaskProperties(
upload_folder_id="syn1234567",
file_view_id="syn2345678"
)
task = CurationTask(
project_id="syn9876543",
data_type="genomics_data",
instructions="Upload your genomics files and complete metadata",
task_properties=file_properties
)
task = task.store()
print(f"Created task: {task.task_id}")
# Later, retrieve and update the task
existing_task = CurationTask(task_id=task.task_id).get()
existing_task.instructions = "Updated instructions with new requirements"
existing_task.store()
# List all tasks in the project
for project_task in CurationTask.list(project_id="syn9876543"):
print(f"Task: {project_task.data_type} - {project_task.task_id}")
```
"""
task_id: Optional[int] = None
"""The unique identifier issued to this task when it was created"""
data_type: Optional[str] = None
"""Will match the data type that a contributor plans to contribute. The dataType must be unique within a project"""
project_id: Optional[str] = None
"""The synId of the project"""
instructions: Optional[str] = None
"""Instructions to the data contributor"""
task_properties: Optional[
Union[FileBasedMetadataTaskProperties, RecordBasedMetadataTaskProperties]
] = None
"""The properties of a CurationTask"""
etag: Optional[str] = None
"""Synapse employs an Optimistic Concurrency Control (OCC) scheme to handle concurrent updates. Since the E-Tag changes every time an entity is updated it is used to detect when a client's current representation of an entity is out-of-date"""
created_on: Optional[str] = None
"""(Read Only) The date this task was created"""
modified_on: Optional[str] = None
"""(Read Only) The date this task was last modified"""
created_by: Optional[str] = None
"""(Read Only) The ID of the user that created this task"""
modified_by: Optional[str] = None
"""(Read Only) The ID of the user that last modified this task"""
assignee_principal_id: Optional[str] = None
"""The principal ID of the user or team assigned to this task. Null if unassigned. For metadata
tasks, determines the owner of the grid session. Team members can all join grid sessions
owned by their team, while user-owned grid sessions are restricted to that user only."""
_last_persistent_instance: Optional["CurationTask"] = field(
default=None, repr=False, compare=False
)
"""The last persistent instance of this object. This is used to determine if the
object has been changed and needs to be updated in Synapse."""
@property
def has_changed(self) -> bool:
"""Determines if the object has been changed and needs to be updated in Synapse."""
return (
not self._last_persistent_instance or self._last_persistent_instance != self
)
def _set_last_persistent_instance(self) -> None:
"""Stash the last time this object interacted with Synapse. This is used to
determine if the object has been changed and needs to be updated in Synapse."""
del self._last_persistent_instance
self._last_persistent_instance = replace(self)
def fill_from_dict(
self, synapse_response: Union[Dict[str, Any], Any]
) -> "CurationTask":
"""
Converts a response from the REST API into this dataclass.
Arguments:
synapse_response: The response from the REST API.
Returns:
The CurationTask object.
"""
self.task_id = (
int(synapse_response.get("taskId", None))
if synapse_response.get("taskId", None)
else None
)
self.data_type = synapse_response.get("dataType", None)
self.project_id = synapse_response.get("projectId", None)
self.instructions = synapse_response.get("instructions", None)
self.etag = synapse_response.get("etag", None)
self.created_on = synapse_response.get("createdOn", None)
self.modified_on = synapse_response.get("modifiedOn", None)
self.created_by = synapse_response.get("createdBy", None)
self.modified_by = synapse_response.get("modifiedBy", None)
self.assignee_principal_id = synapse_response.get("assigneePrincipalId", None)
task_properties_dict = synapse_response.get("taskProperties", None)
if task_properties_dict:
self.task_properties = _create_task_properties_from_dict(
task_properties_dict
)
return self
def to_synapse_request(self) -> Dict[str, Any]:
"""
Converts this dataclass to a dictionary suitable for a Synapse REST API request.
Returns:
A dictionary representation of this object for API requests.
"""
request_dict = {}
request_dict["taskId"] = self.task_id
request_dict["dataType"] = self.data_type
request_dict["projectId"] = self.project_id
request_dict["instructions"] = self.instructions
request_dict["etag"] = self.etag
request_dict["createdOn"] = self.created_on
request_dict["modifiedOn"] = self.modified_on
request_dict["createdBy"] = self.created_by
request_dict["modifiedBy"] = self.modified_by
request_dict["assigneePrincipalId"] = self.assignee_principal_id
if self.task_properties is not None:
request_dict["taskProperties"] = self.task_properties.to_synapse_request()
delete_none_keys(request_dict)
return request_dict
async def get_async(
self, *, synapse_client: Optional[Synapse] = None
) -> "CurationTask":
"""
Gets a CurationTask from Synapse by ID.
Arguments:
synapse_client: If not passed in and caching was not disabled by
`Synapse.allow_client_caching(False)` this will use the last created
instance from the Synapse class constructor.
Returns:
CurationTask: The CurationTask object.
Raises:
ValueError: If the CurationTask object does not have a task_id.
Example: Get a curation task asynchronously
```python
import asyncio
from synapseclient import Synapse
from synapseclient.models import CurationTask
syn = Synapse()
syn.login()
async def main():
task = await CurationTask(task_id=123).get_async()
print(f"Data type: {task.data_type}")
print(f"Instructions: {task.instructions}")
asyncio.run(main())
```
"""
if not self.task_id:
raise ValueError("task_id is required to get a CurationTask")
trace.get_current_span().set_attributes(
{
"synapse.task_id": str(self.task_id),
}
)
task_result = await get_curation_task(
task_id=self.task_id, synapse_client=synapse_client
)
self.fill_from_dict(synapse_response=task_result)
self._set_last_persistent_instance()
return self
async def delete_async(
self,
delete_source: bool = False,
*,
synapse_client: Optional[Synapse] = None,
) -> None:
"""
Deletes a CurationTask from Synapse.
Arguments:
delete_source: If True, the associated source data (EntityView or RecordSet) will also be deleted
if the task is a FileBasedMetadataTask or RecordBasedMetadataTask respectively. Defaults to False.
synapse_client: If not passed in and caching was not disabled by
`Synapse.allow_client_caching(False)` this will use the last created
instance from the Synapse class constructor.
Raises:
ValueError: If the CurationTask object does not have a task_id.
ValueError: If delete_source is True but the task properties are not properly set
to identify the source to delete.
Example: Delete a curation task asynchronously
```python
import asyncio
from synapseclient import Synapse
from synapseclient.models import CurationTask
syn = Synapse()
syn.login()
async def main():
task = CurationTask(task_id=123)
await task.delete_async()
print("Task deleted successfully")
asyncio.run(main())
```
Example: Delete a curation task and its associated data source asynchronously
```python
import asyncio
from synapseclient import Synapse
from synapseclient.models import CurationTask
syn = Synapse()
syn.login()
async def main():
task = CurationTask(task_id=123)
await task.delete_async(delete_source=True)
print("Task and record set deleted successfully")
asyncio.run(main())
```
"""
if not self.task_id:
raise ValueError("task_id is required to delete a CurationTask")
trace.get_current_span().set_attributes(
{
"synapse.task_id": str(self.task_id),
}
)
if delete_source:
if not self.task_properties:
await self.get_async(synapse_client=synapse_client)
if isinstance(self.task_properties, FileBasedMetadataTaskProperties):
if not self.task_properties.file_view_id:
raise ValueError(
"Cannot delete Fileview: "
"'file_view_id' attribute is missing."
)
from synapseclient.models import EntityView
await EntityView(id=self.task_properties.file_view_id).delete_async(
synapse_client=synapse_client
)
elif isinstance(self.task_properties, RecordBasedMetadataTaskProperties):
if not self.task_properties.record_set_id:
raise ValueError(
"Cannot delete RecordSet: "
"'record_set_id' attribute is missing."
)
from synapseclient.models import RecordSet
await RecordSet(id=self.task_properties.record_set_id).delete_async(
synapse_client=synapse_client
)
else:
raise ValueError(
"'task_property' attribute is None. "
"Deletion only supports FileBasedMetadataTaskProperties or "
"RecordBasedMetadataTaskProperties."
)
await delete_curation_task(task_id=self.task_id, synapse_client=synapse_client)
async def store_async(
self, *, synapse_client: Optional[Synapse] = None
) -> "CurationTask":
"""
Creates a new CurationTask or updates an existing one on Synapse.
This method implements non-destructive updates. If a CurationTask with the same
project_id and data_type exists and this instance hasn't been retrieved from
Synapse before, it will merge the existing task data with the current instance
before updating.
Arguments:
synapse_client: If not passed in and caching was not disabled by
`Synapse.allow_client_caching(False)` this will use the last created
instance from the Synapse class constructor.
Returns:
CurationTask: The CurationTask object.
Example: Create a new curation task asynchronously
```python
import asyncio
from synapseclient import Synapse
from synapseclient.models import CurationTask, FileBasedMetadataTaskProperties
syn = Synapse()
syn.login()
async def main():
# Create file-based task properties
file_properties = FileBasedMetadataTaskProperties(
upload_folder_id="syn1234567",
file_view_id="syn2345678"
)
# Create and store the curation task
task = CurationTask(
project_id="syn9876543",
data_type="genomics_data",
instructions="Upload your genomics files to the specified folder",
task_properties=file_properties
)
task = await task.store_async()
print(f"Created task with ID: {task.task_id}")
asyncio.run(main())
```
"""
if not self.project_id:
raise ValueError("project_id is required")
if not self.data_type:
raise ValueError("data_type is required")
trace.get_current_span().set_attributes(
{
"synapse.data_type": self.data_type or "",
"synapse.project_id": self.project_id or "",
"synapse.task_id": str(self.task_id) if self.task_id else "",
}
)
if (
not self._last_persistent_instance
and not self.task_id
and (
existing_task_id := await _get_existing_curation_task_id(
project_id=self.project_id,
data_type=self.data_type,
synapse_client=synapse_client,
)
)
and (
existing_task := await CurationTask(task_id=existing_task_id).get_async(
synapse_client=synapse_client
)
)
):
merge_dataclass_entities(source=existing_task, destination=self)
if self.task_id:
task_result = await update_curation_task(
task_id=self.task_id,
curation_task=self.to_synapse_request(),
synapse_client=synapse_client,
)
self.fill_from_dict(synapse_response=task_result)
self._set_last_persistent_instance()
return self
else:
if not self.project_id:
raise ValueError("project_id is required to create a CurationTask")
if not self.data_type:
raise ValueError("data_type is required to create a CurationTask")
if not self.instructions:
raise ValueError("instructions is required to create a CurationTask")
if not self.task_properties:
raise ValueError("task_properties is required to create a CurationTask")
task_result = await create_curation_task(
curation_task=self.to_synapse_request(),
synapse_client=synapse_client,
)
self.fill_from_dict(synapse_response=task_result)
self._set_last_persistent_instance()
return self
@skip_async_to_sync
@classmethod
async def list_async(
cls,
project_id: str,
*,
synapse_client: Optional[Synapse] = None,
) -> AsyncGenerator["CurationTask", None]:
"""
Generator that yields CurationTasks for a project as they become available.
Arguments:
project_id: The synId of the project.
synapse_client: If not passed in and caching was not disabled by
`Synapse.allow_client_caching(False)` this will use the last created
instance from the Synapse class constructor.
Yields:
CurationTask objects as they are retrieved from the API.
Example: List all curation tasks in a project asynchronously
```python
import asyncio
from synapseclient import Synapse
from synapseclient.models import CurationTask
syn = Synapse()
syn.login()
async def main():
# List all curation tasks in the project
async for task in CurationTask.list_async(project_id="syn9876543"):
print(f"Task ID: {task.task_id}")
print(f"Data Type: {task.data_type}")
print(f"Instructions: {task.instructions}")
print("---")
asyncio.run(main())
```
"""
trace.get_current_span().set_attributes(
{
"synapse.project_id": project_id,
}
)
async for task_dict in list_curation_tasks(
project_id=project_id, synapse_client=synapse_client
):
task = cls().fill_from_dict(synapse_response=task_dict)
yield task
@dataclass
class CreateGridRequest(AsynchronousCommunicator):
"""
Start a job to create a new Grid session.
Represents a [Synapse CreateGridRequest](https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/grid/CreateGridRequest.html).
Attributes:
concrete_type: The concrete type for the request
record_set_id: When provided, the grid will be initialized using the CSV file
stored for the given record set id
initial_query: Initialize a grid session from an EntityView.
Mutually exclusive with record_set_id.
session_id: The session ID of the created grid (populated from response)
"""
concrete_type: str = CREATE_GRID_REQUEST
"""The concrete type for the request"""
record_set_id: Optional[str] = None
"""When provided, the grid will be initialized using the CSV file stored for
the given record set id. The grid columns will match the header of the CSV.
Optional, if present the initialQuery cannot be included."""
initial_query: Optional[Query] = None
"""Initialize a grid session from an EntityView.
Mutually exclusive with record_set_id."""
session_id: Optional[str] = None
"""The session ID of the created grid (populated from response)"""
_grid_session_data: Optional[Dict[str, Any]] = field(default=None, compare=False)
"""Internal storage of the full grid session data from the response for later use."""
def fill_from_dict(
self, synapse_response: Union[Dict[str, Any], Any]
) -> "CreateGridRequest":
"""
Converts a response from the REST API into this dataclass.
Arguments:
synapse_response: The response from the REST API.
Returns:
The CreateGridRequest object.
"""
# Extract session ID from the response body
grid_session_data = synapse_response.get("gridSession", {})
self.session_id = grid_session_data.get("sessionId", None)
# Store the full grid session data for later use
self._grid_session_data = grid_session_data
return self
def fill_grid_session_from_response(self, grid_session: "Grid") -> "Grid":
"""
Fills a GridSession object with data from the stored response.
Arguments:
grid_session: The GridSession object to populate.
Returns:
The populated GridSession object.
"""
if not hasattr(self, "_grid_session_data"):
return grid_session
data = self._grid_session_data
grid_session.session_id = data.get("sessionId", None)
grid_session.started_by = data.get("startedBy", None)
grid_session.started_on = data.get("startedOn", None)
grid_session.etag = data.get("etag", None)
grid_session.modified_on = data.get("modifiedOn", None)
grid_session.last_replica_id_client = data.get("lastReplicaIdClient", None)
grid_session.last_replica_id_service = data.get("lastReplicaIdService", None)
grid_session.grid_json_schema_id = data.get("gridJsonSchema$Id", None)
grid_session.source_entity_id = data.get("sourceEntityId", None)
return grid_session
def to_synapse_request(self) -> Dict[str, Any]:
"""
Converts this dataclass to a dictionary suitable for a Synapse REST API request.
Returns:
A dictionary representation of this object for API requests.
"""
request_dict = {"concreteType": self.concrete_type}
request_dict["recordSetId"] = self.record_set_id
request_dict["initialQuery"] = (
self.initial_query.to_synapse_request() if self.initial_query else None
)
delete_none_keys(request_dict)
return request_dict
@dataclass
class GridRecordSetExportRequest(AsynchronousCommunicator):
"""
A request to export a grid created from a record set back to the original record set.
A CSV file will be generated and set as a new version of the recordset.
Represents a [Synapse GridRecordSetExportRequest](https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/grid/GridRecordSetExportRequest.html).
Attributes: