divbase-lib 0.1.0.dev5__tar.gz → 0.1.2__tar.gz

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.
Files changed (22) hide show
  1. {divbase_lib-0.1.0.dev5 → divbase_lib-0.1.2}/.gitignore +21 -2
  2. {divbase_lib-0.1.0.dev5 → divbase_lib-0.1.2}/PKG-INFO +5 -5
  3. {divbase_lib-0.1.0.dev5 → divbase_lib-0.1.2}/pyproject.toml +3 -3
  4. divbase_lib-0.1.2/src/divbase_lib/__init__.py +1 -0
  5. {divbase_lib-0.1.0.dev5 → divbase_lib-0.1.2}/src/divbase_lib/api_schemas/auth.py +3 -0
  6. divbase_lib-0.1.2/src/divbase_lib/api_schemas/personal_access_tokens.py +42 -0
  7. {divbase_lib-0.1.0.dev5 → divbase_lib-0.1.2}/src/divbase_lib/api_schemas/project_versions.py +9 -6
  8. divbase_lib-0.1.2/src/divbase_lib/api_schemas/queries.py +210 -0
  9. {divbase_lib-0.1.0.dev5 → divbase_lib-0.1.2}/src/divbase_lib/api_schemas/s3.py +163 -18
  10. {divbase_lib-0.1.0.dev5 → divbase_lib-0.1.2}/src/divbase_lib/api_schemas/task_history.py +8 -7
  11. {divbase_lib-0.1.0.dev5 → divbase_lib-0.1.2}/src/divbase_lib/api_schemas/vcf_dimensions.py +15 -2
  12. {divbase_lib-0.1.0.dev5 → divbase_lib-0.1.2}/src/divbase_lib/divbase_constants.py +16 -3
  13. {divbase_lib-0.1.0.dev5 → divbase_lib-0.1.2}/src/divbase_lib/exceptions.py +8 -10
  14. {divbase_lib-0.1.0.dev5 → divbase_lib-0.1.2}/src/divbase_lib/metadata_validator.py +3 -3
  15. divbase_lib-0.1.2/src/divbase_lib/utils.py +142 -0
  16. divbase_lib-0.1.0.dev5/src/divbase_lib/__init__.py +0 -1
  17. divbase_lib-0.1.0.dev5/src/divbase_lib/api_schemas/queries.py +0 -66
  18. divbase_lib-0.1.0.dev5/src/divbase_lib/utils.py +0 -17
  19. {divbase_lib-0.1.0.dev5 → divbase_lib-0.1.2}/README.md +0 -0
  20. {divbase_lib-0.1.0.dev5 → divbase_lib-0.1.2}/src/divbase_lib/api_schemas/__init__.py +0 -0
  21. {divbase_lib-0.1.0.dev5 → divbase_lib-0.1.2}/src/divbase_lib/api_schemas/announcements.py +0 -0
  22. {divbase_lib-0.1.0.dev5 → divbase_lib-0.1.2}/src/divbase_lib/s3_checksums.py +0 -0
@@ -22,6 +22,9 @@ __pycache__/
22
22
  tests/fixtures/temp*
23
23
  tests/fixtures/merged*
24
24
  divbase_metadata_template*.tsv
25
+ # query results files
26
+ result_of_job_*.vcf.gz
27
+ result_of_job_*.log
25
28
 
26
29
  # query job config files
27
30
  bcftools_divbase_job_config.json
@@ -34,13 +37,29 @@ split_scaffold_files.txt
34
37
  scripts/benchmarking/*.yaml
35
38
  scripts/benchmarking/results
36
39
 
40
+ # pytest-cov generate files
41
+ .coverage
42
+ .coverage.*
43
+ htmlcov/
44
+ docker/coverage-data/
45
+
46
+ # log files written by docker compose, if env var set to do so (by default no)
47
+ docker/logs/*
48
+ !docker/logs/.gitkeep
49
+
37
50
  #MacOS artifacts
38
51
  .DS_Store
39
52
 
40
- # mkdocs build cache
53
+ # mkdocs/zensical build cache
41
54
  .cache/
42
- # mkdocs auto generated files
55
+ site/
56
+ # documentation site's auto generated files
43
57
  docs/cli/_auto_generated/*.md
58
+ docs/releases/index.md
59
+ docs/llms.txt
60
+ docs/llms-full.txt
61
+ docs/llms-users.txt
62
+
44
63
 
45
64
  # pypi
46
65
  dist/
@@ -1,8 +1,8 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: divbase-lib
3
- Version: 0.1.0.dev5
3
+ Version: 0.1.2
4
4
  Summary: Library module for Divbase
5
- Project-URL: Homepage, https://divbase.scilifelab.se
5
+ Project-URL: Homepage, https://divbase.scilifelab-2-prod.sys.kth.se
6
6
  Project-URL: Documentation, https://scilifelabdatacentre.github.io/divbase
7
7
  Project-URL: Repository, https://github.com/ScilifelabDataCentre/divbase
8
8
  Project-URL: Issues, https://github.com/ScilifelabDataCentre/divbase/issues
@@ -20,9 +20,9 @@ Classifier: Programming Language :: Python :: 3.14
20
20
  Requires-Python: >=3.12
21
21
  Requires-Dist: httpx==0.28.1
22
22
  Requires-Dist: pandas==2.3.3
23
- Requires-Dist: pydantic==2.12.5
23
+ Requires-Dist: pydantic==2.13.5
24
24
  Requires-Dist: pyyaml==6.0.3
25
- Requires-Dist: stamina==25.2.0
25
+ Requires-Dist: stamina==26.1.0
26
26
  Description-Content-Type: text/markdown
27
27
 
28
28
  # divbase-lib
@@ -10,9 +10,9 @@ requires-python = ">=3.12"
10
10
  dependencies = [
11
11
  "pyyaml==6.0.3",
12
12
  "pandas==2.3.3", # TODO - consider major version bump
13
- "pydantic==2.12.5",
13
+ "pydantic==2.13.5",
14
14
  "httpx==0.28.1",
15
- "stamina==25.2.0"
15
+ "stamina==26.1.0"
16
16
  ]
17
17
  dynamic = ["version"]
18
18
 
@@ -29,7 +29,7 @@ classifiers = [
29
29
  ]
30
30
 
31
31
  [project.urls]
32
- Homepage = "https://divbase.scilifelab.se"
32
+ Homepage = "https://divbase.scilifelab-2-prod.sys.kth.se"
33
33
  Documentation = "https://scilifelabdatacentre.github.io/divbase"
34
34
  Repository = "https://github.com/ScilifelabDataCentre/divbase"
35
35
  Issues = "https://github.com/ScilifelabDataCentre/divbase/issues"
@@ -0,0 +1 @@
1
+ __version__ = "0.1.2"
@@ -1,5 +1,8 @@
1
1
  """
2
2
  Schemas for login + access and refresh tokens
3
+
4
+ NOTE: Expiry fields are unix timestamps (not datetimes like the rest of the API returns).
5
+ This is to mirror how the JWT's stores the expiry, and it is convenient as the CLI stores these expiries locally as unix timestamps too.
3
6
  """
4
7
 
5
8
  from pydantic import BaseModel, Field
@@ -0,0 +1,42 @@
1
+ """
2
+ Schemas for personal access token related endpoints.
3
+ """
4
+
5
+ from pydantic import BaseModel, Field, model_validator
6
+ from typing_extensions import Self
7
+
8
+ # This needs to stay in sync with ProjectRoles in divbase-api.
9
+ # Redefined here to avoid a circular dependency on divbase-api.
10
+ ALLOWED_PROJECT_ROLES = ["read", "query", "edit", "manage"]
11
+
12
+
13
+ class PATPermissions(BaseModel):
14
+ """
15
+ Personal Access Token permissions model.
16
+ This is stored in the db as JSONB in the PersonalAccessTokenDB.permissions.
17
+
18
+ - all_projects: True = access all the user's projects with same role as user
19
+ False = access only the projects listed in `projects`.
20
+ - projects: {str(project_id): role_string}; only enforced when all_projects=False.
21
+ Where role_string must be a valid ProjectRoles enum value.
22
+ - task_history: endpoint level scope.
23
+ For the 2 task history routes not tied to a specific project.
24
+ (these are 'task-history id' and for 'task-history user')
25
+ """
26
+
27
+ all_projects: bool = False
28
+ projects: dict[str, str] = Field(default_factory=dict)
29
+ task_history: bool = False
30
+
31
+ @model_validator(mode="after")
32
+ def no_project_scope_if_all_projects_true(self) -> Self:
33
+ if self.all_projects and self.projects:
34
+ raise ValueError("cannot specify project scope if 'all_projects' is True")
35
+ return self
36
+
37
+ @model_validator(mode="after")
38
+ def validate_project_roles(self) -> Self:
39
+ for project_id, role_str in self.projects.items():
40
+ if role_str not in ALLOWED_PROJECT_ROLES:
41
+ raise ValueError(f"invalid role '{role_str}' for project {project_id}")
42
+ return self
@@ -4,6 +4,7 @@ Schemas for project versioning routes.
4
4
  Project versions are the state of all files in a project's storage bucket at a given time point.
5
5
  """
6
6
 
7
+ from datetime import datetime
7
8
  from typing import TypedDict
8
9
 
9
10
  from pydantic import BaseModel, Field
@@ -35,19 +36,20 @@ class ProjectBasicInfo(BaseModel):
35
36
  """Base model for describing a single project version, not for direct use in an endpoint."""
36
37
 
37
38
  name: str = Field(..., description="Version name")
38
- description: str | None = Field(..., description="Version description")
39
+ description: str | None = Field(None, description="Version description")
39
40
 
40
41
 
41
42
  class AddVersionResponse(ProjectBasicInfo):
42
43
  """Response model for adding a version."""
43
44
 
44
- created_at: str = Field(..., description="ISO timestamp when version was created")
45
+ created_at: datetime = Field(..., description="When the version was created")
45
46
 
46
47
 
47
48
  class ProjectVersionInfo(ProjectBasicInfo):
48
49
  """Basic information about a project version. You get a list of these when listing all versions in a project."""
49
50
 
50
- created_at: str = Field(..., description="ISO timestamp when version was created")
51
+ created_at: datetime = Field(..., description="When the version was created")
52
+ updated_at: datetime = Field(..., description="When the version was last updated")
51
53
  is_deleted: bool = Field(..., description="Whether this version has been soft-deleted")
52
54
 
53
55
 
@@ -63,7 +65,8 @@ class FileDetails(TypedDict):
63
65
  class ProjectVersionDetailResponse(ProjectBasicInfo):
64
66
  """Full information about a single project version, including the files at that version."""
65
67
 
66
- created_at: str = Field(..., description="ISO timestamp when version was created")
68
+ created_at: datetime = Field(..., description="When the version was created")
69
+ updated_at: datetime = Field(..., description="When the version was last updated")
67
70
  is_deleted: bool = Field(..., description="Whether this version has been soft-deleted")
68
71
  files: dict[str, FileDetails] = Field(
69
72
  ..., description="Info about all files at this version, including: version IDs, etags and file sizes"
@@ -78,10 +81,10 @@ class DeleteVersionResponse(BaseModel):
78
81
  False,
79
82
  description="Whether the version was already soft-deleted before this request",
80
83
  )
81
- date_deleted: str = Field(..., description="ISO timestamp of when the version was soft-deleted")
84
+ date_deleted: datetime = Field(..., description="When the version was soft-deleted")
82
85
 
83
86
 
84
87
  class UpdateVersionResponse(ProjectBasicInfo):
85
88
  """Response model for updating a version."""
86
89
 
87
- created_at: str = Field(..., description="ISO timestamp when version was created")
90
+ created_at: datetime = Field(..., description="When the version was created")
@@ -0,0 +1,210 @@
1
+ """
2
+ Schemas for query routes.
3
+ """
4
+
5
+ from typing import Any, Self
6
+
7
+ from pydantic import BaseModel, ConfigDict, field_validator, model_validator
8
+
9
+ from divbase_lib.utils import split_semicolon_bcftools_command_segments
10
+
11
+ # Shared helper functions and models
12
+
13
+
14
+ def validate_command_not_empty(command: str) -> str:
15
+ """
16
+ Validator function to ensure that the user-submitted bcftools command string is not empty or just whitespace.
17
+ If there are multiple segments separated by semicolons, it also validates that none of the segments are empty or whitespace.
18
+
19
+ Shared helper for command field validators in BcftoolsQueryRequest.command and BcftoolsQueryKwargs.command.
20
+ """
21
+ command_string = command.strip()
22
+ if command_string == "":
23
+ raise ValueError(
24
+ "The --command option must be a non-empty bcftools view string. "
25
+ 'If you only want to subset based on samples, use --command "view -s" in combination with one of the sample-selection options: --tsv-filter, --samples, --samples-file.'
26
+ )
27
+
28
+ segments = split_semicolon_bcftools_command_segments(command_string)
29
+ for position, segment in enumerate(segments, start=1):
30
+ if segment.strip() == "":
31
+ raise ValueError(
32
+ f"The --command option has an empty pipeline segment at position {position}. "
33
+ "Use semicolons only between complete bcftools view commands."
34
+ )
35
+
36
+ return command
37
+
38
+
39
+ class SharedBaseModel(BaseModel):
40
+ """Shared pydantic BaseModel for VCF query response and kwarg schemas."""
41
+
42
+ model_config = ConfigDict(
43
+ validate_assignment=True,
44
+ json_schema_extra={
45
+ "description": ("Exactly one sample-selection mode must be provided: tsv_filter, samples, or all_samples.")
46
+ },
47
+ )
48
+
49
+
50
+ # Request models
51
+ class SampleMetadataQueryRequest(BaseModel):
52
+ """Request model for sample metadata query route."""
53
+
54
+ tsv_filter: str
55
+ metadata_tsv_name: str
56
+
57
+
58
+ class BcftoolsQueryRequest(SharedBaseModel):
59
+ """
60
+ Request model for sample metadata query route.
61
+ See ConfigDict in SharedBaseModel for validation rules around tsv_filter and samples fields.
62
+ """
63
+
64
+ tsv_filter: str | None = None # Used for metadata mode only
65
+ metadata_tsv_name: str | None = None # Used for metadata mode only
66
+ command: str # bcftools command input with --command
67
+ samples: list[str] | None = None
68
+ all_samples: bool = False
69
+
70
+ @field_validator("command")
71
+ @classmethod
72
+ def validate_command(_cls, value: str) -> str:
73
+ return validate_command_not_empty(value)
74
+
75
+ @model_validator(mode="after")
76
+ def validate_sample_selection_mode(self) -> Self:
77
+ tsv_filter = self.tsv_filter
78
+ samples = self.samples
79
+ all_samples = self.all_samples
80
+
81
+ selection_count = 0
82
+ if tsv_filter is not None:
83
+ selection_count += 1
84
+ if samples is not None:
85
+ selection_count += 1
86
+ if all_samples:
87
+ selection_count += 1
88
+
89
+ if selection_count > 1:
90
+ raise ValueError("Only one of tsv_filter, samples, or all_samples may be provided.")
91
+ if selection_count == 0:
92
+ raise ValueError("One sample-selection mode must be provided (tsv_filter, samples, or all_samples).")
93
+
94
+ if tsv_filter is not None and self.metadata_tsv_name is None:
95
+ raise ValueError("metadata_tsv_name must be provided when tsv_filter is used.")
96
+
97
+ if samples is not None and len(samples) == 0:
98
+ raise ValueError("samples must contain at least one sample ID when provided.")
99
+
100
+ return self
101
+
102
+
103
+ # Models for task kwargs and task results. Reused in task history schemas too, hence pydantic models and not just dataclasses.
104
+ class SampleMetadataQueryKwargs(BaseModel):
105
+ """Keyword arguments for sample metadata query task. Used to pass info to Celery task, and also for recording task history."""
106
+
107
+ tsv_filter: str
108
+ metadata_tsv_name: str
109
+ bucket_name: str
110
+ project_id: int
111
+ project_name: str
112
+ user_id: int
113
+
114
+
115
+ class BcftoolsQueryKwargs(SharedBaseModel):
116
+ """
117
+ Keyword arguments for BCFtools query task. Used to pass info to Celery task, and also for recording task history.
118
+ See ConfigDict in SharedBaseModel for validation rules around tsv_filter and samples fields.
119
+ """
120
+
121
+ tsv_filter: str | None = None # Used for metadata mode only
122
+ metadata_tsv_name: str | None = None # Used for metadata mode only
123
+ command: str # bcftools command input with --command
124
+ bucket_name: str
125
+ project_id: int
126
+ project_name: str
127
+ user_id: int
128
+ job_id: int
129
+ samples: list[str] | None = None
130
+ all_samples: bool = False
131
+
132
+ @field_validator("command")
133
+ @classmethod
134
+ def validate_command(_cls, value: str) -> str:
135
+ return validate_command_not_empty(value)
136
+
137
+ @model_validator(mode="after")
138
+ def validate_sample_selection_mode(self) -> Self:
139
+ tsv_filter = self.tsv_filter
140
+ samples = self.samples
141
+ all_samples = self.all_samples
142
+
143
+ selection_count = 0
144
+ if tsv_filter is not None:
145
+ selection_count += 1
146
+ if samples is not None:
147
+ selection_count += 1
148
+ if all_samples:
149
+ selection_count += 1
150
+
151
+ if selection_count > 1:
152
+ raise ValueError("Only one of tsv_filter, samples, or all_samples may be provided.")
153
+ if selection_count == 0:
154
+ # Backward compatibility for historical task kwargs created before all_samples option was implemented.
155
+ # To ensure that task-history deserialization does not break for existing tasks.
156
+ # Could be handled by a backfilling migration instead.
157
+ self.all_samples = True
158
+ return self
159
+
160
+ if tsv_filter is not None and self.metadata_tsv_name is None:
161
+ raise ValueError("metadata_tsv_name must be provided when tsv_filter is used.")
162
+
163
+ if samples is not None and len(samples) == 0:
164
+ raise ValueError("samples must contain at least one sample ID when provided.")
165
+
166
+ return self
167
+
168
+
169
+ class SampleFileMappingResult(BaseModel):
170
+ sample_id: str
171
+ filename: str
172
+
173
+ @model_validator(mode="before")
174
+ @classmethod
175
+ def map_legacy_task_history_keys(cls, data: Any) -> Any:
176
+ """
177
+ Support historical task-history payloads that stored uppercase keys.
178
+ """
179
+ if not isinstance(data, dict):
180
+ return data
181
+
182
+ normalized = dict(data)
183
+ if "sample_id" not in normalized:
184
+ if "Sample_ID" in normalized:
185
+ normalized["sample_id"] = normalized["Sample_ID"]
186
+ elif "#Sample_ID" in normalized:
187
+ normalized["sample_id"] = normalized["#Sample_ID"]
188
+ if "filename" not in normalized and "Filename" in normalized:
189
+ normalized["filename"] = normalized["Filename"]
190
+
191
+ return normalized
192
+
193
+
194
+ class SampleMetadataQueryTaskResult(BaseModel):
195
+ """Metadata query task result details. Based on the return of tasks.sample_metadata_query."""
196
+
197
+ sample_and_filename_subset: list[SampleFileMappingResult]
198
+ unique_sample_ids: list[str]
199
+ unique_filenames: list[str]
200
+ query_message: str
201
+ warnings: list[str] = []
202
+ status: str | None = None
203
+
204
+
205
+ class BcftoolsQueryTaskResult(BaseModel):
206
+ """BCFtools query task result details. Based on the return of tasks.bcftools_query."""
207
+
208
+ output_file: str
209
+ status: str | None = None
210
+ log_file: str | None = None
@@ -9,37 +9,125 @@ Pre-signed upload URLs need to account for single vs multipart uploads hence all
9
9
 
10
10
  from datetime import datetime
11
11
 
12
- from pydantic import BaseModel, Field
12
+ from pydantic import BaseModel, Field, field_validator
13
13
 
14
- from divbase_lib.divbase_constants import S3_MULTIPART_CHUNK_SIZE
14
+ from divbase_lib.divbase_constants import (
15
+ MAX_S3_API_BATCH_SIZE,
16
+ S3_MULTIPART_CHUNK_SIZE,
17
+ SUPPORTED_DIVBASE_FILE_TYPES,
18
+ SUPPORTED_DIVBASE_FILE_TYPES_DISPLAY,
19
+ UNSUPPORTED_CHARACTERS_DISPLAY,
20
+ UNSUPPORTED_CHARACTERS_IN_FILENAMES,
21
+ )
15
22
 
16
23
  MB = 1024 * 1024
17
24
 
18
25
 
26
+ def validate_s3_object_name(name: str) -> str:
27
+ """Validate that the S3 object name does not contain unsupported characters."""
28
+ if name.startswith("/") or name.endswith("/"):
29
+ raise ValueError("Object name must not start or end with a '/'.")
30
+ if not any(name.endswith(ext) for ext in SUPPORTED_DIVBASE_FILE_TYPES):
31
+ raise ValueError(f"Object name must be one of the supported file types: {SUPPORTED_DIVBASE_FILE_TYPES_DISPLAY}")
32
+ if any(part in (".", "..") for part in name.split("/")):
33
+ raise ValueError("Object name cannot contain '.' or '..' as a folder path or file name.")
34
+ for char in UNSUPPORTED_CHARACTERS_IN_FILENAMES:
35
+ if char in name:
36
+ raise ValueError(
37
+ f"Object name contains unsupported characters. Unsupported: {UNSUPPORTED_CHARACTERS_DISPLAY}"
38
+ )
39
+ return name
40
+
41
+
42
+ def validate_s3_directory_name(name: str) -> str:
43
+ """Validate + clean a S3 directory name."""
44
+ if name.startswith("/"):
45
+ name = name[1:]
46
+ if not name.endswith("/"):
47
+ name = f"{name}/"
48
+
49
+ stripped = name.strip("/")
50
+ if not stripped:
51
+ raise ValueError("Directory name cannot be empty or '/'.")
52
+
53
+ if any(part in (".", "..") for part in name.split("/")):
54
+ raise ValueError(f"Directory '{name}' cannot contain '.' or '..' as a folder path.")
55
+
56
+ for char in UNSUPPORTED_CHARACTERS_IN_FILENAMES:
57
+ if char in name:
58
+ raise ValueError(
59
+ f"Directory name contains unsupported characters. Unsupported: {UNSUPPORTED_CHARACTERS_DISPLAY}"
60
+ )
61
+ return name
62
+
63
+
64
+ def validate_s3_object_prefix(prefix: str | None) -> str | None:
65
+ """Validate that the S3 object prefix does not contain unsupported characters."""
66
+ if not prefix:
67
+ return None
68
+ if any(part in (".", "..") for part in prefix.split("/")):
69
+ raise ValueError(f"Prefix '{prefix}' cannot contain '.' or '..' as a path segment.")
70
+ for char in UNSUPPORTED_CHARACTERS_IN_FILENAMES:
71
+ if char in prefix:
72
+ raise ValueError(f"Prefix contains unsupported characters. Unsupported: {UNSUPPORTED_CHARACTERS_DISPLAY}")
73
+ return prefix
74
+
75
+
19
76
  ## list objects models ##
77
+ class ObjectDetails(BaseModel):
78
+ """Details about a single object in an S3 bucket."""
79
+
80
+ name: str = Field(..., description="The name of the object in the bucket.")
81
+ size: int = Field(..., description="The size of the object in bytes.")
82
+ last_modified: datetime = Field(..., description="The date and time the object was last modified.")
83
+ etag: str = Field(..., description="The ETag of the object, which is the MD5 checksum.")
84
+
85
+
20
86
  class ListObjectsRequest(BaseModel):
21
87
  """Request model for listing objects in an S3 bucket."""
22
88
 
23
89
  prefix: str | None = Field(None, description="Optional prefix to filter objects by name.")
90
+ delimiter: str | None = Field(
91
+ None,
92
+ description="Delimiter for simulating a file-system view. Use '/' to do this. Leave as none to recursively list all files.",
93
+ )
24
94
  next_token: str | None = Field(
25
95
  None, description="Token to continue listing files from the end of a previous request."
26
96
  )
27
97
 
98
+ @field_validator("prefix")
99
+ @classmethod
100
+ def validate_prefix(cls, prefix: str | None) -> str | None:
101
+ return validate_s3_object_prefix(prefix)
28
102
 
29
- class ObjectDetails(BaseModel):
30
- """Details about a single object in an S3 bucket."""
31
-
32
- name: str = Field(..., description="The name of the object in the bucket.")
33
- size: int = Field(..., description="The size of the object in bytes.")
34
- last_modified: datetime = Field(..., description="The date and time the object was last modified.")
35
- etag: str = Field(..., description="The ETag of the object, which is the MD5 checksum.")
103
+ @field_validator("delimiter")
104
+ @classmethod
105
+ def validate_delimiter(cls, delimiter: str | None) -> str | None:
106
+ if delimiter is not None and delimiter != "/":
107
+ raise ValueError("Delimiter must be either None or '/'.")
108
+ return delimiter
36
109
 
37
110
 
38
111
  class ListObjectsResponse(BaseModel):
39
- """Response model for listing objects in an S3 bucket."""
112
+ """
113
+ Response model for listing objects in an S3 bucket.
114
+
115
+ When delimiter is omitted: files contains all matching objects, folders is always empty.
116
+ When delimiter='/' is used: files contains objects at the current level only, folders contains
117
+ common prefixes (simulated directories).
118
+ """
40
119
 
41
- objects: list[ObjectDetails] = Field(
42
- ..., description="A list of objects in the bucket.", min_length=0, max_length=1000
120
+ files: list[ObjectDetails] = Field(
121
+ ...,
122
+ description="Files at this level (or all files when no delimiter is used).",
123
+ min_length=0,
124
+ max_length=1000,
125
+ )
126
+ folders: list[str] = Field(
127
+ ...,
128
+ description="Simulated folder prefixes. Only populated when a delimiter is used.",
129
+ min_length=0,
130
+ max_length=1000,
43
131
  )
44
132
  next_token: str | None = Field(
45
133
  None, description="Token for fetching the next page of results. If None, no more results."
@@ -47,6 +135,17 @@ class ListObjectsResponse(BaseModel):
47
135
 
48
136
 
49
137
  ## list soft-deleted objects models ##
138
+ class ListDeletedObjectsRequest(BaseModel):
139
+ """Request model for listing soft-deleted objects in an S3 bucket."""
140
+
141
+ prefix: str | None = Field(None, description="Optional prefix to filter objects by name.")
142
+
143
+ @field_validator("prefix")
144
+ @classmethod
145
+ def validate_prefix(cls, prefix: str | None) -> str | None:
146
+ return validate_s3_object_prefix(prefix)
147
+
148
+
50
149
  class SoftDeletedObjectDetails(BaseModel):
51
150
  """Details about a single soft-deleted object in an S3 bucket."""
52
151
 
@@ -78,7 +177,7 @@ class DownloadObjectRequest(BaseModel):
78
177
  """Request model to download a single object using a pre-signed URL."""
79
178
 
80
179
  name: str = Field(..., description="Name of the object to be downloaded")
81
- version_id: str | None = Field(..., description="Version ID of the object, None if latest version")
180
+ version_id: str | None = Field(None, description="Version ID of the object, None if latest version")
82
181
 
83
182
 
84
183
  class PreSignedDownloadResponse(BaseModel):
@@ -86,17 +185,22 @@ class PreSignedDownloadResponse(BaseModel):
86
185
 
87
186
  name: str = Field(..., description="Name of the object to be downloaded")
88
187
  pre_signed_url: str = Field(..., description="Pre-signed URL for downloading the object")
89
- version_id: str | None = Field(..., description="Version ID of the object, None if latest version")
188
+ version_id: str | None = Field(None, description="Version ID of the object, None if latest version")
90
189
 
91
190
 
92
191
  ### Single-part upload models ###
93
192
  class UploadSinglePartObjectRequest(BaseModel):
94
193
  """Request model to upload a single object as a single part using a pre-signed URL."""
95
194
 
96
- name: str = Field(..., description="Name of the object to be uploaded")
97
- content_length: int = Field(..., description="Size of the file in bytes")
195
+ name: str = Field(..., min_length=3, max_length=255, description="Name of the object to be uploaded")
196
+ content_length: int = Field(..., ge=0, description="Size of the file in bytes")
98
197
  md5_hash: str | None = Field(None, description="Optional MD5 hash of the object for integrity check")
99
198
 
199
+ @field_validator("name")
200
+ @classmethod
201
+ def validate_s3_name(cls, name: str) -> str:
202
+ return validate_s3_object_name(name)
203
+
100
204
 
101
205
  class PreSignedSinglePartUploadResponse(BaseModel):
102
206
  """Response model to upload a single object as a single part using the pre-signed URL using PUT."""
@@ -110,8 +214,13 @@ class PreSignedSinglePartUploadResponse(BaseModel):
110
214
  class CreateMultipartUploadRequest(BaseModel):
111
215
  """Request model to create a multipart upload using pre-signed URLs."""
112
216
 
113
- name: str = Field(..., description="Name of the object to be uploaded")
114
- content_length: int = Field(..., description="Size of the file in bytes")
217
+ name: str = Field(..., min_length=3, max_length=255, description="Name of the object to be uploaded")
218
+ content_length: int = Field(..., ge=0, description="Size of the file in bytes")
219
+
220
+ @field_validator("name")
221
+ @classmethod
222
+ def validate_s3_name(cls, name: str) -> str:
223
+ return validate_s3_object_name(name)
115
224
 
116
225
 
117
226
  class CreateMultipartUploadResponse(BaseModel):
@@ -187,6 +296,42 @@ class AbortMultipartUploadResponse(BaseModel):
187
296
  upload_id: str = Field(..., description="Upload ID for the multipart upload that was aborted")
188
297
 
189
298
 
299
+ ### make directories models (remove directories done by standard soft delete) ###
300
+ class MakeDirectoriesRequest(BaseModel):
301
+ """Request model for making directories in the bucket."""
302
+
303
+ directories: list[str] = Field(
304
+ ...,
305
+ description=("List of directories to be created."),
306
+ min_length=1,
307
+ max_length=MAX_S3_API_BATCH_SIZE,
308
+ )
309
+
310
+ @field_validator("directories")
311
+ @classmethod
312
+ def validate_directories(cls, directories: list[str]) -> list[str]:
313
+ cleaned = []
314
+ for name in directories:
315
+ cleaned.append(validate_s3_directory_name(name))
316
+ return cleaned
317
+
318
+
319
+ class MakeDirectoriesResponse(BaseModel):
320
+ """Response model for making directories in the bucket."""
321
+
322
+ created: list[str] = Field(
323
+ ...,
324
+ description=(
325
+ "List of directories that were successfully created. This will include directories that already existed."
326
+ ),
327
+ )
328
+ failed: list[str] = Field(
329
+ ...,
330
+ description=("List of directories that could not be created."),
331
+ )
332
+
333
+
334
+ ### restore objects models ###
190
335
  class RestoreObjectsResponse(BaseModel):
191
336
  """Response model for restoring soft-deleted objects in a bucket."""
192
337
 
@@ -2,6 +2,7 @@
2
2
  Schemas for task history routes.
3
3
  """
4
4
 
5
+ from datetime import datetime
5
6
  from typing import Any, Optional, Union
6
7
 
7
8
  from pydantic import BaseModel
@@ -20,8 +21,10 @@ class TaskHistoryResult(BaseModel):
20
21
  Task details as returned by queries to the SQAlchemy+pg results backend.
21
22
  """
22
23
 
23
- id: int
24
- submitter_email: Optional[str] = None
24
+ id: int # This is TaskHistoryDB.id
25
+ created_at: datetime # NOTE: This comes from TaskHistoryDB, so cannot be None unlike the other datetimes here.
26
+ submitter_email: str
27
+ name: str
25
28
  status: Optional[str] = None
26
29
  result: Optional[
27
30
  Union[
@@ -33,8 +36,7 @@ class TaskHistoryResult(BaseModel):
33
36
  DimensionUpdateTaskResult,
34
37
  ]
35
38
  ] = None
36
- date_done: Optional[str] = None
37
- name: Optional[str] = None
39
+ date_done: Optional[datetime] = None
38
40
  args: Optional[str] = None
39
41
  kwargs: Optional[
40
42
  Union[
@@ -44,7 +46,6 @@ class TaskHistoryResult(BaseModel):
44
46
  ]
45
47
  ] = None
46
48
  worker: Optional[str] = None
47
- created_at: Optional[str] = None
48
- started_at: Optional[str] = None
49
- completed_at: Optional[str] = None
49
+ started_at: Optional[datetime] = None
50
+ completed_at: Optional[datetime] = None
50
51
  runtime: Optional[float] = None
@@ -17,11 +17,11 @@ class DimensionUpdateKwargs(BaseModel):
17
17
 
18
18
 
19
19
  class DimensionUpdateTaskResult(BaseModel):
20
- """Dimension update task result details. Based on the return of tasks.update_dimensions_index."""
20
+ """Dimension update task result details. Based on the return of tasks.update_vcf_dimensions_task."""
21
21
 
22
22
  status: Optional[str] = None
23
23
  VCF_files_added: Optional[list[str]] = Field(
24
- None, description="VCF files that were added to dimensions index by this job"
24
+ None, description="VCF files that were added to dimensions cache by this job"
25
25
  )
26
26
  VCF_files_skipped: Optional[list[str]] = Field(
27
27
  None, description="VCF files skipped by this job (previous DivBase-generated result VCFs)"
@@ -52,3 +52,16 @@ class DimensionsScaffoldsResult(BaseModel):
52
52
  """Result model for showing unique scaffolds across project VCFs."""
53
53
 
54
54
  unique_scaffolds: list[str] # Already sorted, by the CRUD function get_unique_scaffolds_by_project_async()
55
+
56
+
57
+ class DimensionsVCFFileEntry(BaseModel):
58
+ """A single VCF file entry in the unique VCF files response."""
59
+
60
+ vcf_file_s3_key: str
61
+ s3_version_id: str
62
+
63
+
64
+ class DimensionsVCFFilesResult(BaseModel):
65
+ """Result model for showing unique VCF file/version entries across project VCFs."""
66
+
67
+ unique_vcf_files: list[DimensionsVCFFileEntry]
@@ -32,12 +32,13 @@ LARGEST_FILE_UPLOADABLE_TO_DIVBASE_BYTES = 10_000 * S3_MULTIPART_CHUNK_SIZE
32
32
  # File types that DivBase supports
33
33
  # Whilst we can't realistically limit what file types a user actually uploads,
34
34
  # this is here to say what we know should work in DivBase.
35
- SUPPORTED_DIVBASE_FILE_TYPES = (".tsv", ".vcf.gz", ".csi", ".tbi")
36
-
35
+ SUPPORTED_DIVBASE_FILE_TYPES = (".tsv", ".vcf.gz", ".csi", ".tbi", ".txt", ".md")
36
+ SUPPORTED_DIVBASE_FILE_TYPES_DISPLAY = ", ".join(f"'{ext}'" for ext in SUPPORTED_DIVBASE_FILE_TYPES)
37
37
  # Characters that are not allowed in file names uploaded to DivBase
38
38
  # This is to prevent issues when users try to filter/query files on DivBase using these characters
39
39
  # or when downloading files (e.g. ":" is used to specify file versions when downloading files
40
- UNSUPPORTED_CHARACTERS_IN_FILENAMES = (":", "*", "?", "<", ">", "|", "\\")
40
+ UNSUPPORTED_CHARACTERS_IN_FILENAMES = (":", "*", "?", "<", ">", "|", "\\", "//", "@", "~")
41
+ UNSUPPORTED_CHARACTERS_DISPLAY = ", ".join(f"'{c}'" for c in UNSUPPORTED_CHARACTERS_IN_FILENAMES)
41
42
 
42
43
  # This prefix is used for all *.vcf.gz results files from a query job/task.
43
44
  # After the prefix comes the job id which is a rolling integer.
@@ -51,3 +52,15 @@ QUERY_RESULTS_FILE_PREFIX = "result_of_job_"
51
52
  # 2. Add an announcement about a new CLI version being available when the user logs in.
52
53
  # 3. Do Nothing as the user's CLI version is up to date.
53
54
  CLI_VERSION_HEADER_KEY = "X-CLI-Version"
55
+
56
+ # Personal Access Tokens (PATs) are used for passwordless auth with DivBase API
57
+ PAT_TOKEN_PREFIX = "divbase_pat_"
58
+
59
+ # Both divbase-api and divbase-worker(s) configs want to know if we are in a deployed environment or not
60
+ LOCAL_DEV_ENVIRONMENTS = ["local_dev", "test"]
61
+
62
+ # The default timezone and formats used for display (e.g. in the frontend, admin panel and in emails).
63
+ DIVBASE_SERVER_TIMEZONE = "Europe/Stockholm"
64
+ DEFAULT_DISPLAY_DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S %Z"
65
+ # divbase-cli uses user's local timezone for display
66
+ DEFAULT_CLI_DISPLAY_DATETIME_FORMAT = "%Y-%m-%d %H:%M %Z"
@@ -19,17 +19,16 @@ class BcftoolsEnvironmentError(Exception):
19
19
  f"No running container found with name {self.container_name}. Ensure the Docker image is available.\n"
20
20
  )
21
21
  super().__init__(error_message)
22
-
23
22
  self.error_message = error_message
24
23
 
25
- def __str__(self):
24
+ def __str__(self) -> str:
26
25
  return self.error_message
27
26
 
28
27
 
29
28
  class BcftoolsCommandError(Exception):
30
29
  """Raised when a bcftools command fails to execute properly."""
31
30
 
32
- def __init__(self, command: str, error_details: Exception = None):
31
+ def __init__(self, command: str, error_details: str | None = None):
33
32
  self.command = command
34
33
  self.error_details = error_details
35
34
 
@@ -38,11 +37,10 @@ class BcftoolsCommandError(Exception):
38
37
  error_message += f" with error details: {error_details}"
39
38
 
40
39
  super().__init__(error_message)
40
+ self.error_message = error_message
41
41
 
42
- def __str__(self):
43
- if hasattr(self.error_details, "stderr") and self.error_details.stderr:
44
- return f"bcftools command failed: '{self.command}' with error: {self.error_details.stderr}"
45
- return super().__str__()
42
+ def __str__(self) -> str:
43
+ return self.error_message
46
44
 
47
45
 
48
46
  class BcftoolsPipeEmptyCommandError(Exception):
@@ -53,7 +51,7 @@ class BcftoolsPipeEmptyCommandError(Exception):
53
51
  super().__init__(error_message)
54
52
  self.error_message = error_message
55
53
 
56
- def __str__(self):
54
+ def __str__(self) -> str:
57
55
  return self.error_message
58
56
 
59
57
 
@@ -85,7 +83,7 @@ class SidecarNoDataLoadedError(Exception):
85
83
  super().__init__(error_message)
86
84
  self.error_message = error_message
87
85
 
88
- def __str__(self):
86
+ def __str__(self) -> str:
89
87
  return self.error_message
90
88
 
91
89
 
@@ -137,7 +135,7 @@ class NoVCFFilesFoundError(Exception):
137
135
 
138
136
 
139
137
  class DimensionsNotUpToDateWithBucketError(Exception):
140
- """Raised when VCF files in a bucket are missing or outdated in the dimensions index."""
138
+ """Raised when VCF files in a bucket are missing or outdated in the dimensions cache."""
141
139
 
142
140
  pass
143
141
 
@@ -713,8 +713,8 @@ class SharedMetadataValidator:
713
713
  errors.append(
714
714
  ValidationMessage(
715
715
  ValidationCategory.DIMENSIONS,
716
- f"The following samples in the TSV were not found in the DivBase project's dimensions index ({examples}). "
717
- "DivBase requires that all samples in the TSV file must be present in the project's dimensions index to be used for queries."
716
+ f"The following samples in the TSV were not found in the DivBase project's dimensions cache ({examples}). "
717
+ "DivBase requires that all samples in the TSV file must be present in the project's dimensions cache to be used for queries."
718
718
  f"{full_output_hint}",
719
719
  )
720
720
  )
@@ -728,7 +728,7 @@ class SharedMetadataValidator:
728
728
  warnings.append(
729
729
  ValidationMessage(
730
730
  ValidationCategory.DIMENSIONS,
731
- f"The following samples in the DivBase project's dimensions index were not found in the TSV ({examples}). "
731
+ f"The following samples in the DivBase project's dimensions cache were not found in the TSV ({examples}). "
732
732
  "This is allowed for DivBase metadata TSV files, but please be aware that these samples will not be considered when making queries with this metadata file."
733
733
  f"{full_output_hint}",
734
734
  )
@@ -0,0 +1,142 @@
1
+ from datetime import datetime, timezone
2
+ from typing import Literal, TypeAlias
3
+ from zoneinfo import ZoneInfo
4
+
5
+ from divbase_lib.divbase_constants import (
6
+ DEFAULT_CLI_DISPLAY_DATETIME_FORMAT,
7
+ DEFAULT_DISPLAY_DATETIME_FORMAT,
8
+ DIVBASE_SERVER_TIMEZONE,
9
+ )
10
+
11
+ QuoteChar: TypeAlias = Literal["'", '"']
12
+
13
+
14
+ def set_default_timezone(dt: datetime) -> datetime:
15
+ """
16
+ If the datetime is naive (aka no timezone info), set it to UTC.
17
+ If it already has timezone info, return it unchanged.
18
+ """
19
+ if dt.tzinfo is None:
20
+ dt = dt.replace(tzinfo=timezone.utc)
21
+ return dt
22
+
23
+
24
+ def to_unix_timestamp(dt: datetime) -> int:
25
+ """
26
+ Convert a datetime to a unix timestamp (whole seconds since epoch, UTC).
27
+ Datetimes are assumed to be UTC timezone if not already a timezone aware object.
28
+ """
29
+ dt = set_default_timezone(dt)
30
+ return int(dt.timestamp())
31
+
32
+
33
+ def format_datetime(
34
+ dt: datetime,
35
+ desired_timezone: str = DIVBASE_SERVER_TIMEZONE,
36
+ format: str = DEFAULT_DISPLAY_DATETIME_FORMAT,
37
+ ) -> str:
38
+ """
39
+ Convert a datetime into a human-readable string in a given timezone.
40
+ Datetimes are assumed to be UTC timezone if not already a timezone aware object.
41
+ """
42
+ dt = set_default_timezone(dt)
43
+ return dt.astimezone(ZoneInfo(desired_timezone)).strftime(format)
44
+
45
+
46
+ def format_datetime_for_cli(dt: datetime, format: str = DEFAULT_CLI_DISPLAY_DATETIME_FORMAT) -> str:
47
+ """
48
+ Convert a datetime into a human-readable string in the user's local system timezone.
49
+
50
+ For use by DivBase CLI commands, which are run on the user's own machine and
51
+ should therefore display timestamps in their local timezone.
52
+ """
53
+ dt = set_default_timezone(dt)
54
+ return dt.astimezone().strftime(format)
55
+
56
+
57
+ def format_unix_timestamp_for_cli(unix_timestamp: int | float, fmt: str = DEFAULT_CLI_DISPLAY_DATETIME_FORMAT) -> str:
58
+ """Convert a unix timestamp into a human-readable string in the user's local system timezone."""
59
+ dt = datetime.fromtimestamp(unix_timestamp, tz=timezone.utc)
60
+ return format_datetime_for_cli(dt=dt, format=fmt)
61
+
62
+
63
+ def format_file_size(size_bytes: int | float | None, decimals: int = 2) -> str:
64
+ """
65
+ Converts a file size in bytes to a human-readable format.
66
+
67
+ Uses powers of 1000 so KB, MB, GB, TB and not 1024 KiB, MiB, GiB, TiB.
68
+ """
69
+ if size_bytes is None:
70
+ return "N/A"
71
+ if size_bytes == 0:
72
+ return "0 B"
73
+ power = 1000
74
+ n = 0
75
+ power_labels = {0: "", 1: "K", 2: "M", 3: "G", 4: "T"}
76
+ while size_bytes >= power and n < len(power_labels) - 1:
77
+ size_bytes /= power
78
+ n += 1
79
+ return f"{size_bytes:.{decimals}f} {power_labels[n]}B"
80
+
81
+
82
+ def format_duration(seconds: int) -> str:
83
+ """Format a duration in seconds for user facing messages"""
84
+ for unit_seconds, unit in ((3600, "hour"), (60, "minute")):
85
+ if seconds % unit_seconds == 0:
86
+ value = seconds // unit_seconds
87
+ return f"{value} {unit}{'s' if value != 1 else ''}"
88
+ return f"{seconds} seconds"
89
+
90
+
91
+ def split_semicolon_bcftools_command_segments(command: str) -> list[str]:
92
+ """
93
+ Split a user provided bcftools command string on semicolons while respecting quoted substrings.
94
+
95
+ bcftools view allows semicolons for certain options (e.g. -i 'FILTER="A;B"'), so we need to ensure that we only
96
+ split on semicolons that are not inside quotes.
97
+
98
+ --command "view -i 'FILTER=\"A;B\"'; view -r 1:1-1000"
99
+
100
+ Slides character by character through the command string to identify the true semicolon delimiters, whilst ignoring semicolons inside quotes.
101
+ The command strings are not that long, so we can afford to do this on a character level.
102
+ """
103
+ command_segments: list[str] = []
104
+ segment_chars: list[str] = []
105
+
106
+ single_quote = "'"
107
+ double_quote = '"'
108
+
109
+ # Possible states None = outside quotes, "'" = inside single-quoted substring, '"' = inside double-quoted substring.
110
+ open_quote_char: QuoteChar | None = None
111
+ is_escaped = False
112
+
113
+ for char in command:
114
+ if is_escaped:
115
+ segment_chars.append(char)
116
+ is_escaped = False
117
+ continue
118
+
119
+ # Handle backslash-escaped characters in the received command text.
120
+ # In single-quoted regions, backslashes are treated as literal chars.
121
+ if char == "\\" and open_quote_char != single_quote:
122
+ segment_chars.append(char)
123
+ is_escaped = True
124
+ continue
125
+
126
+ if char in (double_quote, single_quote):
127
+ segment_chars.append(char)
128
+ if open_quote_char is None:
129
+ open_quote_char = char
130
+ elif open_quote_char == char:
131
+ open_quote_char = None
132
+ continue
133
+
134
+ if char == ";" and open_quote_char is None:
135
+ command_segments.append("".join(segment_chars))
136
+ segment_chars = []
137
+ continue
138
+
139
+ segment_chars.append(char)
140
+
141
+ command_segments.append("".join(segment_chars))
142
+ return command_segments
@@ -1 +0,0 @@
1
- __version__ = "0.1.0.dev5"
@@ -1,66 +0,0 @@
1
- """
2
- Schemas for query routes.
3
- """
4
-
5
- from typing import Any, Optional
6
-
7
- from pydantic import BaseModel
8
-
9
-
10
- # Request models
11
- class SampleMetadataQueryRequest(BaseModel):
12
- """Request model for sample metadata query route."""
13
-
14
- tsv_filter: str
15
- metadata_tsv_name: str
16
-
17
-
18
- class BcftoolsQueryRequest(BaseModel):
19
- """Request model for sample metadata query route."""
20
-
21
- tsv_filter: str
22
- metadata_tsv_name: str
23
- command: str # TODO add field to decribe that this is bcftools commands
24
-
25
-
26
- # Models for task kwargs and task results. Reused in task history schemas too, hence pydantic models and not just dataclasses.
27
- class SampleMetadataQueryKwargs(BaseModel):
28
- """Keyword arguments for sample metadata query task. Used to pass info to Celery task, and also for recording task history."""
29
-
30
- tsv_filter: str
31
- metadata_tsv_name: str
32
- bucket_name: str
33
- project_id: int
34
- project_name: str
35
- user_id: int
36
-
37
-
38
- class BcftoolsQueryKwargs(BaseModel):
39
- """Keyword arguments for BCFtools query task. Used to pass info to Celery task, and also for recording task history."""
40
-
41
- tsv_filter: str
42
- command: str
43
- metadata_tsv_name: str
44
- bucket_name: str
45
- project_id: int
46
- project_name: str
47
- user_id: int
48
- job_id: int
49
-
50
-
51
- class SampleMetadataQueryTaskResult(BaseModel):
52
- """Metadata query task result details. Based on the return of tasks.sample_metadata_query."""
53
-
54
- sample_and_filename_subset: list[dict[str, Any]]
55
- unique_sample_ids: list[str]
56
- unique_filenames: list[str]
57
- query_message: str
58
- warnings: list[str] = []
59
- status: Optional[str] = None
60
-
61
-
62
- class BcftoolsQueryTaskResult(BaseModel):
63
- """BCFtools query task result details. Based on the return of tasks.bcftools_query."""
64
-
65
- output_file: str
66
- status: Optional[str] = None
@@ -1,17 +0,0 @@
1
- def format_file_size(size_bytes: int | float | None, decimals: int = 2) -> str:
2
- """
3
- Converts a file size in bytes to a human-readable format.
4
-
5
- Uses powers of 1000 so KB, MB, GB, TB and not 1024 KiB, MiB, GiB, TiB.
6
- """
7
- if size_bytes is None:
8
- return "N/A"
9
- if size_bytes == 0:
10
- return "0 B"
11
- power = 1000
12
- n = 0
13
- power_labels = {0: "", 1: "K", 2: "M", 3: "G", 4: "T"}
14
- while size_bytes >= power and n < len(power_labels) - 1:
15
- size_bytes /= power
16
- n += 1
17
- return f"{size_bytes:.{decimals}f} {power_labels[n]}B"
File without changes