fractal-server 1.4.9__py3-none-any.whl → 2.0.0a0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- fractal_server/__init__.py +1 -1
- fractal_server/app/models/__init__.py +4 -7
- fractal_server/app/models/linkuserproject.py +9 -0
- fractal_server/app/models/security.py +6 -0
- fractal_server/app/models/state.py +1 -1
- fractal_server/app/models/v1/__init__.py +10 -0
- fractal_server/app/models/{dataset.py → v1/dataset.py} +5 -5
- fractal_server/app/models/{job.py → v1/job.py} +5 -5
- fractal_server/app/models/{project.py → v1/project.py} +5 -5
- fractal_server/app/models/{task.py → v1/task.py} +7 -2
- fractal_server/app/models/{workflow.py → v1/workflow.py} +5 -5
- fractal_server/app/models/v2/__init__.py +20 -0
- fractal_server/app/models/v2/dataset.py +55 -0
- fractal_server/app/models/v2/job.py +51 -0
- fractal_server/app/models/v2/project.py +31 -0
- fractal_server/app/models/v2/task.py +93 -0
- fractal_server/app/models/v2/workflow.py +43 -0
- fractal_server/app/models/v2/workflowtask.py +90 -0
- fractal_server/app/routes/{admin.py → admin/v1.py} +42 -42
- fractal_server/app/routes/admin/v2.py +275 -0
- fractal_server/app/routes/api/v1/__init__.py +7 -7
- fractal_server/app/routes/api/v1/_aux_functions.py +2 -2
- fractal_server/app/routes/api/v1/dataset.py +44 -37
- fractal_server/app/routes/api/v1/job.py +12 -12
- fractal_server/app/routes/api/v1/project.py +23 -21
- fractal_server/app/routes/api/v1/task.py +24 -14
- fractal_server/app/routes/api/v1/task_collection.py +16 -14
- fractal_server/app/routes/api/v1/workflow.py +24 -24
- fractal_server/app/routes/api/v1/workflowtask.py +10 -10
- fractal_server/app/routes/api/v2/__init__.py +28 -0
- fractal_server/app/routes/api/v2/_aux_functions.py +497 -0
- fractal_server/app/routes/api/v2/apply.py +220 -0
- fractal_server/app/routes/api/v2/dataset.py +310 -0
- fractal_server/app/routes/api/v2/images.py +212 -0
- fractal_server/app/routes/api/v2/job.py +200 -0
- fractal_server/app/routes/api/v2/project.py +205 -0
- fractal_server/app/routes/api/v2/task.py +222 -0
- fractal_server/app/routes/api/v2/task_collection.py +229 -0
- fractal_server/app/routes/api/v2/workflow.py +398 -0
- fractal_server/app/routes/api/v2/workflowtask.py +269 -0
- fractal_server/app/routes/aux/_job.py +1 -1
- fractal_server/app/runner/async_wrap.py +27 -0
- fractal_server/app/runner/exceptions.py +129 -0
- fractal_server/app/runner/executors/local/__init__.py +3 -0
- fractal_server/app/runner/{_local → executors/local}/executor.py +2 -2
- fractal_server/app/runner/executors/slurm/__init__.py +3 -0
- fractal_server/app/runner/{_slurm → executors/slurm}/_batching.py +1 -1
- fractal_server/app/runner/executors/slurm/_check_jobs_status.py +72 -0
- fractal_server/app/runner/{_slurm → executors/slurm}/_executor_wait_thread.py +3 -4
- fractal_server/app/runner/{_slurm → executors/slurm}/_slurm_config.py +3 -152
- fractal_server/app/runner/{_slurm → executors/slurm}/_subprocess_run_as_user.py +1 -1
- fractal_server/app/runner/{_slurm → executors/slurm}/executor.py +9 -9
- fractal_server/app/runner/filenames.py +6 -0
- fractal_server/app/runner/set_start_and_last_task_index.py +39 -0
- fractal_server/app/runner/task_files.py +105 -0
- fractal_server/app/runner/{__init__.py → v1/__init__.py} +36 -49
- fractal_server/app/runner/{_common.py → v1/_common.py} +13 -120
- fractal_server/app/runner/{_local → v1/_local}/__init__.py +6 -6
- fractal_server/app/runner/{_local → v1/_local}/_local_config.py +6 -7
- fractal_server/app/runner/{_local → v1/_local}/_submit_setup.py +1 -5
- fractal_server/app/runner/v1/_slurm/__init__.py +310 -0
- fractal_server/app/runner/{_slurm → v1/_slurm}/_submit_setup.py +3 -9
- fractal_server/app/runner/v1/_slurm/get_slurm_config.py +163 -0
- fractal_server/app/runner/v1/common.py +117 -0
- fractal_server/app/runner/{handle_failed_job.py → v1/handle_failed_job.py} +8 -8
- fractal_server/app/runner/v2/__init__.py +337 -0
- fractal_server/app/runner/v2/_local/__init__.py +169 -0
- fractal_server/app/runner/v2/_local/_local_config.py +118 -0
- fractal_server/app/runner/v2/_local/_submit_setup.py +52 -0
- fractal_server/app/runner/v2/_slurm/__init__.py +157 -0
- fractal_server/app/runner/v2/_slurm/_submit_setup.py +83 -0
- fractal_server/app/runner/v2/_slurm/get_slurm_config.py +179 -0
- fractal_server/app/runner/v2/components.py +5 -0
- fractal_server/app/runner/v2/deduplicate_list.py +24 -0
- fractal_server/app/runner/v2/handle_failed_job.py +156 -0
- fractal_server/app/runner/v2/merge_outputs.py +41 -0
- fractal_server/app/runner/v2/runner.py +264 -0
- fractal_server/app/runner/v2/runner_functions.py +339 -0
- fractal_server/app/runner/v2/runner_functions_low_level.py +134 -0
- fractal_server/app/runner/v2/task_interface.py +43 -0
- fractal_server/app/runner/v2/v1_compat.py +21 -0
- fractal_server/app/schemas/__init__.py +4 -42
- fractal_server/app/schemas/v1/__init__.py +42 -0
- fractal_server/app/schemas/{applyworkflow.py → v1/applyworkflow.py} +18 -18
- fractal_server/app/schemas/{dataset.py → v1/dataset.py} +30 -30
- fractal_server/app/schemas/{dumps.py → v1/dumps.py} +8 -8
- fractal_server/app/schemas/{manifest.py → v1/manifest.py} +5 -5
- fractal_server/app/schemas/{project.py → v1/project.py} +9 -9
- fractal_server/app/schemas/{task.py → v1/task.py} +12 -12
- fractal_server/app/schemas/{task_collection.py → v1/task_collection.py} +7 -7
- fractal_server/app/schemas/{workflow.py → v1/workflow.py} +38 -38
- fractal_server/app/schemas/v2/__init__.py +34 -0
- fractal_server/app/schemas/v2/dataset.py +88 -0
- fractal_server/app/schemas/v2/dumps.py +87 -0
- fractal_server/app/schemas/v2/job.py +113 -0
- fractal_server/app/schemas/v2/manifest.py +109 -0
- fractal_server/app/schemas/v2/project.py +36 -0
- fractal_server/app/schemas/v2/task.py +121 -0
- fractal_server/app/schemas/v2/task_collection.py +105 -0
- fractal_server/app/schemas/v2/workflow.py +78 -0
- fractal_server/app/schemas/v2/workflowtask.py +118 -0
- fractal_server/config.py +5 -10
- fractal_server/images/__init__.py +50 -0
- fractal_server/images/tools.py +86 -0
- fractal_server/main.py +11 -3
- fractal_server/migrations/versions/4b35c5cefbe3_tmp_is_v2_compatible.py +39 -0
- fractal_server/migrations/versions/56af171b0159_v2.py +217 -0
- fractal_server/migrations/versions/876f28db9d4e_tmp_split_task_and_wftask_meta.py +68 -0
- fractal_server/migrations/versions/974c802f0dd0_tmp_workflowtaskv2_type_in_db.py +37 -0
- fractal_server/migrations/versions/9cd305cd6023_tmp_workflowtaskv2.py +40 -0
- fractal_server/migrations/versions/a6231ed6273c_tmp_args_schemas_in_taskv2.py +42 -0
- fractal_server/migrations/versions/b9e9eed9d442_tmp_taskv2_type.py +37 -0
- fractal_server/migrations/versions/e3e639454d4b_tmp_make_task_meta_non_optional.py +50 -0
- fractal_server/tasks/__init__.py +0 -5
- fractal_server/tasks/endpoint_operations.py +13 -19
- fractal_server/tasks/utils.py +35 -0
- fractal_server/tasks/{_TaskCollectPip.py → v1/_TaskCollectPip.py} +3 -3
- fractal_server/tasks/{background_operations.py → v1/background_operations.py} +18 -50
- fractal_server/tasks/v1/get_collection_data.py +14 -0
- fractal_server/tasks/v2/_TaskCollectPip.py +103 -0
- fractal_server/tasks/v2/background_operations.py +382 -0
- fractal_server/tasks/v2/get_collection_data.py +14 -0
- {fractal_server-1.4.9.dist-info → fractal_server-2.0.0a0.dist-info}/METADATA +3 -4
- fractal_server-2.0.0a0.dist-info/RECORD +166 -0
- fractal_server/app/runner/_slurm/.gitignore +0 -2
- fractal_server/app/runner/_slurm/__init__.py +0 -150
- fractal_server/app/runner/common.py +0 -311
- fractal_server-1.4.9.dist-info/RECORD +0 -97
- /fractal_server/app/runner/{_slurm → executors/slurm}/remote.py +0 -0
- {fractal_server-1.4.9.dist-info → fractal_server-2.0.0a0.dist-info}/LICENSE +0 -0
- {fractal_server-1.4.9.dist-info → fractal_server-2.0.0a0.dist-info}/WHEEL +0 -0
- {fractal_server-1.4.9.dist-info → fractal_server-2.0.0a0.dist-info}/entry_points.txt +0 -0
@@ -0,0 +1,310 @@
|
|
1
|
+
import json
|
2
|
+
from pathlib import Path
|
3
|
+
from typing import Optional
|
4
|
+
|
5
|
+
from fastapi import APIRouter
|
6
|
+
from fastapi import Depends
|
7
|
+
from fastapi import HTTPException
|
8
|
+
from fastapi import Response
|
9
|
+
from fastapi import status
|
10
|
+
from sqlmodel import select
|
11
|
+
|
12
|
+
from ....db import AsyncSession
|
13
|
+
from ....db import get_async_db
|
14
|
+
from ....models.v2 import DatasetV2
|
15
|
+
from ....models.v2 import JobV2
|
16
|
+
from ....models.v2 import ProjectV2
|
17
|
+
from ....schemas.v2 import DatasetCreateV2
|
18
|
+
from ....schemas.v2 import DatasetReadV2
|
19
|
+
from ....schemas.v2 import DatasetUpdateV2
|
20
|
+
from ....schemas.v2.dataset import DatasetStatusReadV2
|
21
|
+
from ....schemas.v2.dataset import WorkflowTaskStatusTypeV2
|
22
|
+
from ....security import current_active_user
|
23
|
+
from ....security import User
|
24
|
+
from ._aux_functions import _get_dataset_check_owner
|
25
|
+
from ._aux_functions import _get_project_check_owner
|
26
|
+
from ._aux_functions import _get_submitted_jobs_statement
|
27
|
+
from ._aux_functions import _get_workflow_check_owner
|
28
|
+
from fractal_server.app.runner.filenames import HISTORY_FILENAME
|
29
|
+
|
30
|
+
router = APIRouter()
|
31
|
+
|
32
|
+
|
33
|
+
@router.post(
|
34
|
+
"/project/{project_id}/dataset/",
|
35
|
+
response_model=DatasetReadV2,
|
36
|
+
status_code=status.HTTP_201_CREATED,
|
37
|
+
)
|
38
|
+
async def create_dataset(
|
39
|
+
project_id: int,
|
40
|
+
dataset: DatasetCreateV2,
|
41
|
+
user: User = Depends(current_active_user),
|
42
|
+
db: AsyncSession = Depends(get_async_db),
|
43
|
+
) -> Optional[DatasetReadV2]:
|
44
|
+
"""
|
45
|
+
Add new dataset to current project
|
46
|
+
"""
|
47
|
+
await _get_project_check_owner(
|
48
|
+
project_id=project_id, user_id=user.id, db=db
|
49
|
+
)
|
50
|
+
db_dataset = DatasetV2(project_id=project_id, **dataset.dict())
|
51
|
+
db.add(db_dataset)
|
52
|
+
await db.commit()
|
53
|
+
await db.refresh(db_dataset)
|
54
|
+
await db.close()
|
55
|
+
|
56
|
+
return db_dataset
|
57
|
+
|
58
|
+
|
59
|
+
@router.get(
|
60
|
+
"/project/{project_id}/dataset/",
|
61
|
+
response_model=list[DatasetReadV2],
|
62
|
+
)
|
63
|
+
async def read_dataset_list(
|
64
|
+
project_id: int,
|
65
|
+
history: bool = True,
|
66
|
+
user: User = Depends(current_active_user),
|
67
|
+
db: AsyncSession = Depends(get_async_db),
|
68
|
+
) -> Optional[list[DatasetReadV2]]:
|
69
|
+
"""
|
70
|
+
Get dataset list for given project
|
71
|
+
"""
|
72
|
+
# Access control
|
73
|
+
project = await _get_project_check_owner(
|
74
|
+
project_id=project_id, user_id=user.id, db=db
|
75
|
+
)
|
76
|
+
# Find datasets of the current project. Note: this select/where approach
|
77
|
+
# has much better scaling than refreshing all elements of
|
78
|
+
# `project.dataset_list` - ref
|
79
|
+
# https://github.com/fractal-analytics-platform/fractal-server/pull/1082#issuecomment-1856676097.
|
80
|
+
stm = select(DatasetV2).where(DatasetV2.project_id == project.id)
|
81
|
+
res = await db.execute(stm)
|
82
|
+
dataset_list = res.scalars().all()
|
83
|
+
await db.close()
|
84
|
+
if not history:
|
85
|
+
for ds in dataset_list:
|
86
|
+
setattr(ds, "history", [])
|
87
|
+
return dataset_list
|
88
|
+
|
89
|
+
|
90
|
+
@router.get(
|
91
|
+
"/project/{project_id}/dataset/{dataset_id}/",
|
92
|
+
response_model=DatasetReadV2,
|
93
|
+
)
|
94
|
+
async def read_dataset(
|
95
|
+
project_id: int,
|
96
|
+
dataset_id: int,
|
97
|
+
user: User = Depends(current_active_user),
|
98
|
+
db: AsyncSession = Depends(get_async_db),
|
99
|
+
) -> Optional[DatasetReadV2]:
|
100
|
+
"""
|
101
|
+
Get info on a dataset associated to the current project
|
102
|
+
"""
|
103
|
+
output = await _get_dataset_check_owner(
|
104
|
+
project_id=project_id,
|
105
|
+
dataset_id=dataset_id,
|
106
|
+
user_id=user.id,
|
107
|
+
db=db,
|
108
|
+
)
|
109
|
+
dataset = output["dataset"]
|
110
|
+
await db.close()
|
111
|
+
return dataset
|
112
|
+
|
113
|
+
|
114
|
+
@router.patch(
|
115
|
+
"/project/{project_id}/dataset/{dataset_id}/",
|
116
|
+
response_model=DatasetReadV2,
|
117
|
+
)
|
118
|
+
async def update_dataset(
|
119
|
+
project_id: int,
|
120
|
+
dataset_id: int,
|
121
|
+
dataset_update: DatasetUpdateV2,
|
122
|
+
user: User = Depends(current_active_user),
|
123
|
+
db: AsyncSession = Depends(get_async_db),
|
124
|
+
) -> Optional[DatasetReadV2]:
|
125
|
+
"""
|
126
|
+
Edit a dataset associated to the current project
|
127
|
+
"""
|
128
|
+
|
129
|
+
output = await _get_dataset_check_owner(
|
130
|
+
project_id=project_id,
|
131
|
+
dataset_id=dataset_id,
|
132
|
+
user_id=user.id,
|
133
|
+
db=db,
|
134
|
+
)
|
135
|
+
db_dataset = output["dataset"]
|
136
|
+
|
137
|
+
for key, value in dataset_update.dict(exclude_unset=True).items():
|
138
|
+
setattr(db_dataset, key, value)
|
139
|
+
|
140
|
+
await db.commit()
|
141
|
+
await db.refresh(db_dataset)
|
142
|
+
await db.close()
|
143
|
+
return db_dataset
|
144
|
+
|
145
|
+
|
146
|
+
@router.delete(
|
147
|
+
"/project/{project_id}/dataset/{dataset_id}/",
|
148
|
+
status_code=204,
|
149
|
+
)
|
150
|
+
async def delete_dataset(
|
151
|
+
project_id: int,
|
152
|
+
dataset_id: int,
|
153
|
+
user: User = Depends(current_active_user),
|
154
|
+
db: AsyncSession = Depends(get_async_db),
|
155
|
+
) -> Response:
|
156
|
+
"""
|
157
|
+
Delete a dataset associated to the current project
|
158
|
+
"""
|
159
|
+
output = await _get_dataset_check_owner(
|
160
|
+
project_id=project_id,
|
161
|
+
dataset_id=dataset_id,
|
162
|
+
user_id=user.id,
|
163
|
+
db=db,
|
164
|
+
)
|
165
|
+
dataset = output["dataset"]
|
166
|
+
|
167
|
+
# Fail if there exist jobs that are submitted and in relation with the
|
168
|
+
# current dataset.
|
169
|
+
stm = _get_submitted_jobs_statement().where(JobV2.dataset_id == dataset_id)
|
170
|
+
res = await db.execute(stm)
|
171
|
+
jobs = res.scalars().all()
|
172
|
+
if jobs:
|
173
|
+
string_ids = str([job.id for job in jobs])[1:-1]
|
174
|
+
raise HTTPException(
|
175
|
+
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
176
|
+
detail=(
|
177
|
+
f"Cannot delete dataset {dataset.id} because it "
|
178
|
+
f"is linked to active job(s) {string_ids}."
|
179
|
+
),
|
180
|
+
)
|
181
|
+
|
182
|
+
# Cascade operations: set foreign-keys to null for jobs which are in
|
183
|
+
# relationship with the current dataset
|
184
|
+
stm = select(JobV2).where(JobV2.dataset_id == dataset_id)
|
185
|
+
res = await db.execute(stm)
|
186
|
+
jobs = res.scalars().all()
|
187
|
+
for job in jobs:
|
188
|
+
job.dataset_id = None
|
189
|
+
await db.merge(job)
|
190
|
+
await db.commit()
|
191
|
+
|
192
|
+
# Delete dataset
|
193
|
+
await db.delete(dataset)
|
194
|
+
await db.commit()
|
195
|
+
|
196
|
+
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
197
|
+
|
198
|
+
|
199
|
+
@router.get("/dataset/", response_model=list[DatasetReadV2])
|
200
|
+
async def get_user_datasets(
|
201
|
+
history: bool = True,
|
202
|
+
user: User = Depends(current_active_user),
|
203
|
+
db: AsyncSession = Depends(get_async_db),
|
204
|
+
) -> list[DatasetReadV2]:
|
205
|
+
"""
|
206
|
+
Returns all the datasets of the current user
|
207
|
+
"""
|
208
|
+
stm = select(DatasetV2)
|
209
|
+
stm = stm.join(ProjectV2).where(
|
210
|
+
ProjectV2.user_list.any(User.id == user.id)
|
211
|
+
)
|
212
|
+
|
213
|
+
res = await db.execute(stm)
|
214
|
+
dataset_list = res.scalars().all()
|
215
|
+
await db.close()
|
216
|
+
if not history:
|
217
|
+
for ds in dataset_list:
|
218
|
+
setattr(ds, "history", [])
|
219
|
+
return dataset_list
|
220
|
+
|
221
|
+
|
222
|
+
@router.get(
|
223
|
+
"/project/{project_id}/dataset/{dataset_id}/status/",
|
224
|
+
response_model=DatasetStatusReadV2,
|
225
|
+
)
|
226
|
+
async def get_workflowtask_status(
|
227
|
+
project_id: int,
|
228
|
+
dataset_id: int,
|
229
|
+
user: User = Depends(current_active_user),
|
230
|
+
db: AsyncSession = Depends(get_async_db),
|
231
|
+
) -> Optional[DatasetStatusReadV2]:
|
232
|
+
"""
|
233
|
+
Extract the status of all `WorkflowTask`s that ran on a given `DatasetV2`.
|
234
|
+
"""
|
235
|
+
# Get the dataset DB entry
|
236
|
+
output = await _get_dataset_check_owner(
|
237
|
+
project_id=project_id,
|
238
|
+
dataset_id=dataset_id,
|
239
|
+
user_id=user.id,
|
240
|
+
db=db,
|
241
|
+
)
|
242
|
+
dataset = output["dataset"]
|
243
|
+
|
244
|
+
# Check whether there exists a job such that
|
245
|
+
# 1. `job.dataset_id == dataset_id`, and
|
246
|
+
# 2. `job.status` is submitted
|
247
|
+
# If one such job exists, it will be used later. If there are multiple
|
248
|
+
# jobs, raise an error.
|
249
|
+
stm = _get_submitted_jobs_statement().where(JobV2.dataset_id == dataset_id)
|
250
|
+
res = await db.execute(stm)
|
251
|
+
running_jobs = res.scalars().all()
|
252
|
+
if len(running_jobs) == 0:
|
253
|
+
running_job = None
|
254
|
+
elif len(running_jobs) == 1:
|
255
|
+
running_job = running_jobs[0]
|
256
|
+
else:
|
257
|
+
string_ids = str([job.id for job in running_jobs])[1:-1]
|
258
|
+
raise HTTPException(
|
259
|
+
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
260
|
+
detail=(
|
261
|
+
f"Cannot get WorkflowTaskV2 statuses as DatasetV2 {dataset.id}"
|
262
|
+
f" is linked to multiple active jobs: {string_ids}."
|
263
|
+
),
|
264
|
+
)
|
265
|
+
|
266
|
+
# Initialize empty dictionary for WorkflowTaskV2 status
|
267
|
+
workflow_tasks_status_dict: dict = {}
|
268
|
+
|
269
|
+
# Lowest priority: read status from DB, which corresponds to jobs that are
|
270
|
+
# not running
|
271
|
+
history = dataset.history
|
272
|
+
for history_item in history:
|
273
|
+
wftask_id = history_item["workflowtask"]["id"]
|
274
|
+
wftask_status = history_item["status"]
|
275
|
+
workflow_tasks_status_dict[wftask_id] = wftask_status
|
276
|
+
|
277
|
+
# If a job is running, then gather more up-to-date information
|
278
|
+
if running_job is not None:
|
279
|
+
# Get the workflow DB entry
|
280
|
+
running_workflow = await _get_workflow_check_owner(
|
281
|
+
project_id=project_id,
|
282
|
+
workflow_id=running_job.workflow_id,
|
283
|
+
user_id=user.id,
|
284
|
+
db=db,
|
285
|
+
)
|
286
|
+
# Mid priority: Set all WorkflowTask's that are part of the running job
|
287
|
+
# as "submitted"
|
288
|
+
start = running_job.first_task_index
|
289
|
+
end = running_job.last_task_index + 1
|
290
|
+
for wftask in running_workflow.task_list[start:end]:
|
291
|
+
workflow_tasks_status_dict[
|
292
|
+
wftask.id
|
293
|
+
] = WorkflowTaskStatusTypeV2.SUBMITTED
|
294
|
+
|
295
|
+
# Highest priority: Read status updates coming from the running-job
|
296
|
+
# temporary file. Note: this file only contains information on
|
297
|
+
# # WorkflowTask's that ran through successfully.
|
298
|
+
tmp_file = Path(running_job.working_dir) / HISTORY_FILENAME
|
299
|
+
try:
|
300
|
+
with tmp_file.open("r") as f:
|
301
|
+
history = json.load(f)
|
302
|
+
except FileNotFoundError:
|
303
|
+
history = []
|
304
|
+
for history_item in history:
|
305
|
+
wftask_id = history_item["workflowtask"]["id"]
|
306
|
+
wftask_status = history_item["status"]
|
307
|
+
workflow_tasks_status_dict[wftask_id] = wftask_status
|
308
|
+
|
309
|
+
response_body = DatasetStatusReadV2(status=workflow_tasks_status_dict)
|
310
|
+
return response_body
|
@@ -0,0 +1,212 @@
|
|
1
|
+
from typing import Any
|
2
|
+
from typing import Optional
|
3
|
+
|
4
|
+
from fastapi import APIRouter
|
5
|
+
from fastapi import Depends
|
6
|
+
from fastapi import HTTPException
|
7
|
+
from fastapi import Response
|
8
|
+
from fastapi import status
|
9
|
+
from pydantic import BaseModel
|
10
|
+
from pydantic import Field
|
11
|
+
from sqlalchemy.orm.attributes import flag_modified
|
12
|
+
|
13
|
+
from ._aux_functions import _get_dataset_check_owner
|
14
|
+
from fractal_server.app.db import AsyncSession
|
15
|
+
from fractal_server.app.db import get_async_db
|
16
|
+
from fractal_server.app.security import current_active_user
|
17
|
+
from fractal_server.app.security import User
|
18
|
+
from fractal_server.images import Filters
|
19
|
+
from fractal_server.images import SingleImage
|
20
|
+
from fractal_server.images.tools import match_filter_SingleImage
|
21
|
+
|
22
|
+
router = APIRouter()
|
23
|
+
|
24
|
+
|
25
|
+
class ImagePage(BaseModel):
|
26
|
+
|
27
|
+
total_count: int
|
28
|
+
page_size: int
|
29
|
+
current_page: int
|
30
|
+
|
31
|
+
attributes: dict[str, list[Any]]
|
32
|
+
types: list[str]
|
33
|
+
|
34
|
+
images: list[SingleImage]
|
35
|
+
|
36
|
+
|
37
|
+
class ImageQuery(BaseModel):
|
38
|
+
path: Optional[str]
|
39
|
+
filters: Filters = Field(default_factory=Filters)
|
40
|
+
|
41
|
+
|
42
|
+
@router.post(
|
43
|
+
"/project/{project_id}/dataset/{dataset_id}/images/",
|
44
|
+
status_code=status.HTTP_201_CREATED,
|
45
|
+
)
|
46
|
+
async def post_new_image(
|
47
|
+
project_id: int,
|
48
|
+
dataset_id: int,
|
49
|
+
new_image: SingleImage,
|
50
|
+
user: User = Depends(current_active_user),
|
51
|
+
db: AsyncSession = Depends(get_async_db),
|
52
|
+
) -> Response:
|
53
|
+
|
54
|
+
output = await _get_dataset_check_owner(
|
55
|
+
project_id=project_id, dataset_id=dataset_id, user_id=user.id, db=db
|
56
|
+
)
|
57
|
+
dataset = output["dataset"]
|
58
|
+
|
59
|
+
if new_image.path in dataset.image_paths:
|
60
|
+
raise HTTPException(
|
61
|
+
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
62
|
+
detail=(
|
63
|
+
f"Image with path '{new_image.path}' "
|
64
|
+
f"already in DatasetV2 {dataset_id}",
|
65
|
+
),
|
66
|
+
)
|
67
|
+
|
68
|
+
dataset.images.append(new_image.dict())
|
69
|
+
flag_modified(dataset, "images")
|
70
|
+
|
71
|
+
await db.merge(dataset)
|
72
|
+
await db.commit()
|
73
|
+
|
74
|
+
return Response(status_code=status.HTTP_201_CREATED)
|
75
|
+
|
76
|
+
|
77
|
+
@router.post(
|
78
|
+
"/project/{project_id}/dataset/{dataset_id}/images/query/",
|
79
|
+
response_model=ImagePage,
|
80
|
+
status_code=status.HTTP_200_OK,
|
81
|
+
)
|
82
|
+
async def query_dataset_images(
|
83
|
+
project_id: int,
|
84
|
+
dataset_id: int,
|
85
|
+
use_dataset_filters: bool = False, # query param
|
86
|
+
page: int = 1, # query param
|
87
|
+
page_size: Optional[int] = None, # query param
|
88
|
+
query: Optional[ImageQuery] = None, # body
|
89
|
+
user: User = Depends(current_active_user),
|
90
|
+
db: AsyncSession = Depends(get_async_db),
|
91
|
+
) -> ImagePage:
|
92
|
+
|
93
|
+
if page < 1:
|
94
|
+
raise HTTPException(
|
95
|
+
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
96
|
+
detail=f"Invalid pagination parameter: page={page} < 1",
|
97
|
+
)
|
98
|
+
|
99
|
+
output = await _get_dataset_check_owner(
|
100
|
+
project_id=project_id, dataset_id=dataset_id, user_id=user.id, db=db
|
101
|
+
)
|
102
|
+
dataset = output["dataset"]
|
103
|
+
images = dataset.images
|
104
|
+
|
105
|
+
if use_dataset_filters is True:
|
106
|
+
images = [
|
107
|
+
image
|
108
|
+
for image in images
|
109
|
+
if match_filter_SingleImage(
|
110
|
+
SingleImage(**image), Filters(**dataset.filters)
|
111
|
+
)
|
112
|
+
]
|
113
|
+
|
114
|
+
attributes = {}
|
115
|
+
for image in images:
|
116
|
+
for k, v in image["attributes"].items():
|
117
|
+
attributes.setdefault(k, []).append(v)
|
118
|
+
for k, v in attributes.items():
|
119
|
+
attributes[k] = list(set(v))
|
120
|
+
|
121
|
+
types = list(
|
122
|
+
set(type for image in images for type in image["types"].keys())
|
123
|
+
)
|
124
|
+
|
125
|
+
if query is not None:
|
126
|
+
|
127
|
+
if query.path is not None:
|
128
|
+
image = next(
|
129
|
+
(image for image in images if image["path"] == query.path),
|
130
|
+
None,
|
131
|
+
)
|
132
|
+
if image is None:
|
133
|
+
images = []
|
134
|
+
else:
|
135
|
+
images = [image]
|
136
|
+
|
137
|
+
if query.filters.attributes or query.filters.types:
|
138
|
+
images = [
|
139
|
+
image
|
140
|
+
for image in images
|
141
|
+
if match_filter_SingleImage(
|
142
|
+
SingleImage(**image),
|
143
|
+
Filters(**query.filters.dict()),
|
144
|
+
)
|
145
|
+
]
|
146
|
+
|
147
|
+
total_count = len(images)
|
148
|
+
|
149
|
+
if page_size is not None:
|
150
|
+
if page_size <= 0:
|
151
|
+
raise HTTPException(
|
152
|
+
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
153
|
+
detail=(
|
154
|
+
f"Invalid pagination parameter: page_size={page_size} <= 0"
|
155
|
+
),
|
156
|
+
)
|
157
|
+
else:
|
158
|
+
page_size = total_count
|
159
|
+
|
160
|
+
if total_count == 0:
|
161
|
+
page = 1
|
162
|
+
page_size = 0
|
163
|
+
else:
|
164
|
+
last_page = (total_count // page_size) + (total_count % page_size > 0)
|
165
|
+
if page > last_page:
|
166
|
+
page = last_page
|
167
|
+
offset = (page - 1) * page_size
|
168
|
+
images = images[offset : offset + page_size] # noqa E203
|
169
|
+
|
170
|
+
return ImagePage(
|
171
|
+
total_count=total_count,
|
172
|
+
current_page=page,
|
173
|
+
page_size=page_size,
|
174
|
+
attributes=attributes,
|
175
|
+
types=types,
|
176
|
+
images=images,
|
177
|
+
)
|
178
|
+
|
179
|
+
|
180
|
+
@router.delete(
|
181
|
+
"/project/{project_id}/dataset/{dataset_id}/images/",
|
182
|
+
status_code=status.HTTP_204_NO_CONTENT,
|
183
|
+
)
|
184
|
+
async def delete_dataset_images(
|
185
|
+
project_id: int,
|
186
|
+
dataset_id: int,
|
187
|
+
path: str,
|
188
|
+
user: User = Depends(current_active_user),
|
189
|
+
db: AsyncSession = Depends(get_async_db),
|
190
|
+
) -> Response:
|
191
|
+
|
192
|
+
output = await _get_dataset_check_owner(
|
193
|
+
project_id=project_id, dataset_id=dataset_id, user_id=user.id, db=db
|
194
|
+
)
|
195
|
+
dataset = output["dataset"]
|
196
|
+
|
197
|
+
image_to_remove = next(
|
198
|
+
(image for image in dataset.images if image["path"] == path), None
|
199
|
+
)
|
200
|
+
if image_to_remove is None:
|
201
|
+
raise HTTPException(
|
202
|
+
status_code=status.HTTP_404_NOT_FOUND,
|
203
|
+
detail=f"No image with path '{path}' in DatasetV2 {dataset_id}.",
|
204
|
+
)
|
205
|
+
|
206
|
+
dataset.images.remove(image_to_remove)
|
207
|
+
flag_modified(dataset, "images")
|
208
|
+
|
209
|
+
await db.merge(dataset)
|
210
|
+
await db.commit()
|
211
|
+
|
212
|
+
return Response(status_code=status.HTTP_204_NO_CONTENT)
|