divbase-cli 0.1.0.dev2__py3-none-any.whl → 0.1.0.dev4__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.
- divbase_cli/__init__.py +1 -1
- divbase_cli/cli_commands/auth_cli.py +16 -10
- divbase_cli/cli_commands/dimensions_cli.py +322 -26
- divbase_cli/cli_commands/file_cli.py +488 -101
- divbase_cli/cli_commands/query_cli.py +14 -9
- divbase_cli/cli_commands/shared_args_options.py +23 -0
- divbase_cli/cli_commands/task_history_cli.py +3 -8
- divbase_cli/cli_commands/user_config_cli.py +14 -44
- divbase_cli/cli_commands/version_cli.py +98 -37
- divbase_cli/cli_config.py +27 -9
- divbase_cli/cli_exceptions.py +37 -22
- divbase_cli/config_resolver.py +10 -10
- divbase_cli/divbase_cli.py +1 -1
- divbase_cli/retries.py +34 -0
- divbase_cli/services/__init__.py +0 -0
- divbase_cli/services/announcements.py +46 -0
- divbase_cli/services/pre_signed_urls.py +456 -0
- divbase_cli/services/project_versions.py +103 -0
- divbase_cli/services/s3_files.py +442 -0
- divbase_cli/user_auth.py +104 -46
- divbase_cli/user_config.py +20 -9
- divbase_cli/utils.py +28 -0
- {divbase_cli-0.1.0.dev2.dist-info → divbase_cli-0.1.0.dev4.dist-info}/METADATA +3 -4
- divbase_cli-0.1.0.dev4.dist-info/RECORD +28 -0
- {divbase_cli-0.1.0.dev2.dist-info → divbase_cli-0.1.0.dev4.dist-info}/WHEEL +1 -1
- divbase_cli/pre_signed_urls.py +0 -169
- divbase_cli/services.py +0 -219
- divbase_cli-0.1.0.dev2.dist-info/RECORD +0 -22
- {divbase_cli-0.1.0.dev2.dist-info → divbase_cli-0.1.0.dev4.dist-info}/entry_points.txt +0 -0
divbase_cli/__init__.py
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
__version__ = "0.1.0.
|
|
1
|
+
__version__ = "0.1.0.dev4"
|
|
@@ -2,16 +2,16 @@
|
|
|
2
2
|
CLI subcommand for managing user auth with DivBase server.
|
|
3
3
|
"""
|
|
4
4
|
|
|
5
|
+
import logging
|
|
5
6
|
from datetime import datetime
|
|
6
|
-
from pathlib import Path
|
|
7
7
|
|
|
8
8
|
import typer
|
|
9
9
|
from pydantic import SecretStr
|
|
10
10
|
from typing_extensions import Annotated
|
|
11
11
|
|
|
12
|
-
from divbase_cli.cli_commands.user_config_cli import CONFIG_FILE_OPTION
|
|
13
12
|
from divbase_cli.cli_config import cli_settings
|
|
14
|
-
from divbase_cli.cli_exceptions import AuthenticationError
|
|
13
|
+
from divbase_cli.cli_exceptions import AuthenticationError, DivBaseAPIConnectionError, DivBaseAPIError
|
|
14
|
+
from divbase_cli.services.announcements import get_and_display_announcements
|
|
15
15
|
from divbase_cli.user_auth import (
|
|
16
16
|
check_existing_session,
|
|
17
17
|
login_to_divbase,
|
|
@@ -20,6 +20,8 @@ from divbase_cli.user_auth import (
|
|
|
20
20
|
)
|
|
21
21
|
from divbase_cli.user_config import load_user_config
|
|
22
22
|
|
|
23
|
+
logger = logging.getLogger(__name__)
|
|
24
|
+
|
|
23
25
|
auth_app = typer.Typer(
|
|
24
26
|
no_args_is_help=True, help="Login/logout of DivBase server. To register, visit https://divbase.scilifelab.se/."
|
|
25
27
|
)
|
|
@@ -30,7 +32,6 @@ def login(
|
|
|
30
32
|
email: str,
|
|
31
33
|
password: Annotated[str, typer.Option(prompt=True, hide_input=True)],
|
|
32
34
|
divbase_url: str = typer.Option(cli_settings.DIVBASE_API_URL, help="DivBase server URL to connect to."),
|
|
33
|
-
config_file: Path = CONFIG_FILE_OPTION,
|
|
34
35
|
force: bool = typer.Option(False, "--force", "-f", help="Force login again even if already logged in"),
|
|
35
36
|
):
|
|
36
37
|
"""
|
|
@@ -43,7 +44,7 @@ def login(
|
|
|
43
44
|
secret_password = SecretStr(password)
|
|
44
45
|
del password # avoid user passwords showing up in error messages etc...
|
|
45
46
|
|
|
46
|
-
config = load_user_config(
|
|
47
|
+
config = load_user_config()
|
|
47
48
|
|
|
48
49
|
if not force:
|
|
49
50
|
session_expires_at = check_existing_session(divbase_url=divbase_url, config=config)
|
|
@@ -55,7 +56,14 @@ def login(
|
|
|
55
56
|
print("Login cancelled.")
|
|
56
57
|
return
|
|
57
58
|
|
|
58
|
-
login_to_divbase(email=email, password=secret_password, divbase_url=divbase_url
|
|
59
|
+
login_to_divbase(email=email, password=secret_password, divbase_url=divbase_url)
|
|
60
|
+
|
|
61
|
+
try:
|
|
62
|
+
get_and_display_announcements(divbase_base_url=divbase_url)
|
|
63
|
+
except (DivBaseAPIError, DivBaseAPIConnectionError):
|
|
64
|
+
# lets not fail the login process if announcements are not working.
|
|
65
|
+
logger.error("Failed to get announcements after login. Error was: ", exc_info=True)
|
|
66
|
+
|
|
59
67
|
print(f"Logged in successfully as: {email}")
|
|
60
68
|
|
|
61
69
|
|
|
@@ -69,13 +77,11 @@ def logout():
|
|
|
69
77
|
|
|
70
78
|
|
|
71
79
|
@auth_app.command("whoami")
|
|
72
|
-
def whoami(
|
|
73
|
-
config_file: Path = CONFIG_FILE_OPTION,
|
|
74
|
-
):
|
|
80
|
+
def whoami():
|
|
75
81
|
"""
|
|
76
82
|
Return information about the currently logged-in user.
|
|
77
83
|
"""
|
|
78
|
-
config = load_user_config(
|
|
84
|
+
config = load_user_config()
|
|
79
85
|
logged_in_url = config.logged_in_url
|
|
80
86
|
|
|
81
87
|
# TODO - move logged in check to the make_authenticated_request function?
|
|
@@ -1,14 +1,20 @@
|
|
|
1
|
+
import csv
|
|
1
2
|
import logging
|
|
2
3
|
from pathlib import Path
|
|
3
4
|
|
|
4
5
|
import typer
|
|
5
6
|
import yaml
|
|
7
|
+
from rich import print
|
|
6
8
|
|
|
7
|
-
from divbase_cli.cli_commands.
|
|
8
|
-
from divbase_cli.cli_commands.version_cli import PROJECT_NAME_OPTION
|
|
9
|
+
from divbase_cli.cli_commands.shared_args_options import PROJECT_NAME_OPTION
|
|
9
10
|
from divbase_cli.config_resolver import resolve_project
|
|
10
11
|
from divbase_cli.user_auth import make_authenticated_request
|
|
11
|
-
from divbase_lib.api_schemas.vcf_dimensions import
|
|
12
|
+
from divbase_lib.api_schemas.vcf_dimensions import (
|
|
13
|
+
DimensionsSamplesResult,
|
|
14
|
+
DimensionsScaffoldsResult,
|
|
15
|
+
DimensionsShowResult,
|
|
16
|
+
)
|
|
17
|
+
from divbase_lib.metadata_validator import SharedMetadataValidator
|
|
12
18
|
|
|
13
19
|
logger = logging.getLogger(__name__)
|
|
14
20
|
|
|
@@ -22,11 +28,10 @@ dimensions_app = typer.Typer(
|
|
|
22
28
|
@dimensions_app.command("update")
|
|
23
29
|
def update_dimensions_index(
|
|
24
30
|
project: str | None = PROJECT_NAME_OPTION,
|
|
25
|
-
config_file: Path = CONFIG_FILE_OPTION,
|
|
26
31
|
) -> None:
|
|
27
32
|
"""Calculate and add the dimensions of a VCF file to the dimensions index file in the project."""
|
|
28
33
|
|
|
29
|
-
project_config = resolve_project(project_name=project
|
|
34
|
+
project_config = resolve_project(project_name=project)
|
|
30
35
|
|
|
31
36
|
response = make_authenticated_request(
|
|
32
37
|
method="PUT",
|
|
@@ -52,15 +57,89 @@ def show_dimensions_index(
|
|
|
52
57
|
help="If set, will show all unique scaffold names found across all the VCF files in the project.",
|
|
53
58
|
)
|
|
54
59
|
),
|
|
60
|
+
unique_samples: bool = (
|
|
61
|
+
typer.Option(
|
|
62
|
+
False,
|
|
63
|
+
"--unique-samples",
|
|
64
|
+
help="If set, will show all unique sample names found across all the VCF files in the project.",
|
|
65
|
+
)
|
|
66
|
+
),
|
|
67
|
+
sample_names_limit: int = typer.Option(
|
|
68
|
+
20,
|
|
69
|
+
"--sample-names-limit",
|
|
70
|
+
min=1,
|
|
71
|
+
help="Maximum number of sample names to display per list in terminal output.",
|
|
72
|
+
),
|
|
73
|
+
sample_names_output: str | None = typer.Option(
|
|
74
|
+
None,
|
|
75
|
+
"--sample-names-output",
|
|
76
|
+
help="Write full sample names to file instead of truncating in terminal output. "
|
|
77
|
+
"Mutually exclusive with --sample-names-stdout.",
|
|
78
|
+
),
|
|
79
|
+
sample_names_stdout: bool = typer.Option(
|
|
80
|
+
False,
|
|
81
|
+
"--sample-names-stdout",
|
|
82
|
+
help="Print full sample names to stdout (useful for piping). Mutually exclusive with --sample-names-output.",
|
|
83
|
+
),
|
|
55
84
|
project: str | None = PROJECT_NAME_OPTION,
|
|
56
|
-
config_file: Path = CONFIG_FILE_OPTION,
|
|
57
85
|
) -> None:
|
|
58
86
|
"""
|
|
59
87
|
Show the dimensions index file for a project.
|
|
60
88
|
When running --unique-scaffolds, the sorting separates between numeric and non-numeric scaffold names.
|
|
61
89
|
"""
|
|
62
90
|
|
|
63
|
-
project_config = resolve_project(project_name=project
|
|
91
|
+
project_config = resolve_project(project_name=project)
|
|
92
|
+
|
|
93
|
+
# These two options are mutually exclusive. But due to how typer handles options, this error will only be raised if --sample-names-output has an input value (i.e. path).
|
|
94
|
+
# If the path is missing, it will raise an error about the missing path argument instead...
|
|
95
|
+
if sample_names_output and sample_names_stdout:
|
|
96
|
+
typer.echo("Use only one of --sample-names-output or --sample-names-stdout.", err=True)
|
|
97
|
+
raise typer.Exit(code=1)
|
|
98
|
+
|
|
99
|
+
if unique_samples:
|
|
100
|
+
response = make_authenticated_request(
|
|
101
|
+
method="GET",
|
|
102
|
+
divbase_base_url=project_config.divbase_url,
|
|
103
|
+
api_route=f"v1/vcf-dimensions/projects/{project_config.name}/samples",
|
|
104
|
+
)
|
|
105
|
+
unique_sample_names_sorted = DimensionsSamplesResult(**response.json()).unique_samples
|
|
106
|
+
sample_count = len(unique_sample_names_sorted)
|
|
107
|
+
|
|
108
|
+
if sample_names_output:
|
|
109
|
+
output_path = Path(sample_names_output)
|
|
110
|
+
output_path.write_text("\n".join(unique_sample_names_sorted) + "\n")
|
|
111
|
+
print(f"Wrote {sample_count} unique sample names to: {output_path}")
|
|
112
|
+
return
|
|
113
|
+
|
|
114
|
+
if sample_names_stdout:
|
|
115
|
+
print("\n".join(unique_sample_names_sorted))
|
|
116
|
+
return
|
|
117
|
+
|
|
118
|
+
if sample_count > sample_names_limit:
|
|
119
|
+
preview = unique_sample_names_sorted[:sample_names_limit]
|
|
120
|
+
print(
|
|
121
|
+
f"Unique sample names found across all the VCF files in the project (count: {sample_count}, showing first {sample_names_limit}):\n{preview}\n"
|
|
122
|
+
f"To view all, use --sample-names-output <FILE> or --sample-names-stdout."
|
|
123
|
+
)
|
|
124
|
+
return
|
|
125
|
+
|
|
126
|
+
print(
|
|
127
|
+
f"Unique sample names found across all the VCF files in the project (count: {sample_count}):\n{unique_sample_names_sorted}"
|
|
128
|
+
)
|
|
129
|
+
return
|
|
130
|
+
|
|
131
|
+
if unique_scaffolds:
|
|
132
|
+
response = make_authenticated_request(
|
|
133
|
+
method="GET",
|
|
134
|
+
divbase_base_url=project_config.divbase_url,
|
|
135
|
+
api_route=f"v1/vcf-dimensions/projects/{project_config.name}/scaffolds",
|
|
136
|
+
)
|
|
137
|
+
unique_scaffold_names_sorted = DimensionsScaffoldsResult(**response.json()).unique_scaffolds
|
|
138
|
+
scaffold_count = len(unique_scaffold_names_sorted)
|
|
139
|
+
print(
|
|
140
|
+
f"Unique scaffold names found across all the VCF files in the project (count: {scaffold_count}):\n{unique_scaffold_names_sorted}"
|
|
141
|
+
)
|
|
142
|
+
return
|
|
64
143
|
|
|
65
144
|
response = make_authenticated_request(
|
|
66
145
|
method="GET",
|
|
@@ -78,34 +157,34 @@ def show_dimensions_index(
|
|
|
78
157
|
record = entry
|
|
79
158
|
break
|
|
80
159
|
if record:
|
|
160
|
+
if sample_names_output or sample_names_stdout:
|
|
161
|
+
_write_or_print_sample_names(
|
|
162
|
+
indexed_files=[record],
|
|
163
|
+
sample_names_output=sample_names_output,
|
|
164
|
+
sample_names_stdout=sample_names_stdout,
|
|
165
|
+
)
|
|
166
|
+
return
|
|
167
|
+
|
|
168
|
+
_truncate_sample_names_in_entry(record, sample_names_limit)
|
|
81
169
|
print(yaml.safe_dump(record, sort_keys=False))
|
|
82
170
|
else:
|
|
83
171
|
print(
|
|
84
172
|
f"No entry found for filename: {filename}. Please check that the filename is correct and that it is a VCF file (extension: .vcf or .vcf.gz)."
|
|
85
|
-
"\nHint: use 'divbase-cli files
|
|
173
|
+
"\nHint: use 'divbase-cli files ls' to view all files in the project."
|
|
86
174
|
)
|
|
87
175
|
return
|
|
88
176
|
|
|
89
|
-
if
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
numeric_scaffold_names = []
|
|
95
|
-
non_numeric_scaffold_names = []
|
|
96
|
-
for scaffold in unique_scaffold_names:
|
|
97
|
-
if scaffold.isdigit():
|
|
98
|
-
numeric_scaffold_names.append(int(scaffold))
|
|
99
|
-
else:
|
|
100
|
-
non_numeric_scaffold_names.append(scaffold)
|
|
101
|
-
|
|
102
|
-
unique_scaffold_names_sorted = [str(n) for n in sorted(numeric_scaffold_names)] + sorted(
|
|
103
|
-
non_numeric_scaffold_names
|
|
177
|
+
if sample_names_output or sample_names_stdout:
|
|
178
|
+
_write_or_print_sample_names(
|
|
179
|
+
indexed_files=dimensions_info.get("indexed_files", []),
|
|
180
|
+
sample_names_output=sample_names_output,
|
|
181
|
+
sample_names_stdout=sample_names_stdout,
|
|
104
182
|
)
|
|
105
|
-
|
|
106
|
-
print(f"Unique scaffold names found across all the VCF files in the project:\n{unique_scaffold_names_sorted}")
|
|
107
183
|
return
|
|
108
184
|
|
|
185
|
+
for entry in dimensions_info.get("indexed_files", []):
|
|
186
|
+
_truncate_sample_names_in_entry(entry, sample_names_limit)
|
|
187
|
+
|
|
109
188
|
print(yaml.safe_dump(dimensions_info, sort_keys=False))
|
|
110
189
|
|
|
111
190
|
|
|
@@ -113,14 +192,23 @@ def _format_api_response_for_display_in_terminal(api_response: DimensionsShowRes
|
|
|
113
192
|
"""
|
|
114
193
|
Convert the API response to a YAML-like format for display in the user's terminal.
|
|
115
194
|
"""
|
|
195
|
+
|
|
196
|
+
def sort_scaffolds(scaffolds: list[str]) -> list[str]:
|
|
197
|
+
numeric = sorted([int(s) for s in scaffolds if s.isdigit()])
|
|
198
|
+
non_numeric = sorted([s for s in scaffolds if not s.isdigit()])
|
|
199
|
+
return [str(n) for n in numeric] + non_numeric
|
|
200
|
+
|
|
116
201
|
dimensions_list = []
|
|
117
202
|
for entry in api_response.vcf_files:
|
|
203
|
+
scaffolds = entry.get("scaffolds", [])
|
|
204
|
+
sorted_scaffolds = sort_scaffolds(scaffolds)
|
|
118
205
|
dimensions_entry = {
|
|
119
206
|
"filename": entry["vcf_file_s3_key"],
|
|
120
207
|
"file_version_ID_in_bucket": entry["s3_version_id"],
|
|
121
208
|
"last_updated": entry.get("updated_at"),
|
|
122
209
|
"dimensions": {
|
|
123
|
-
"
|
|
210
|
+
"scaffold_count": len(sorted_scaffolds),
|
|
211
|
+
"scaffolds": sorted_scaffolds,
|
|
124
212
|
"sample_count": entry.get("sample_count", 0),
|
|
125
213
|
"sample_names": entry.get("samples", []),
|
|
126
214
|
"variants": entry.get("variant_count", 0),
|
|
@@ -141,3 +229,211 @@ def _format_api_response_for_display_in_terminal(api_response: DimensionsShowRes
|
|
|
141
229
|
"indexed_files": dimensions_list,
|
|
142
230
|
"skipped_files": skipped_list,
|
|
143
231
|
}
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
@dimensions_app.command("create-metadata-template")
|
|
235
|
+
def create_metadata_template_with_project_samples_names(
|
|
236
|
+
output_path: Path | None = typer.Option(
|
|
237
|
+
None,
|
|
238
|
+
"--output",
|
|
239
|
+
"-o",
|
|
240
|
+
file_okay=True,
|
|
241
|
+
dir_okay=False,
|
|
242
|
+
resolve_path=True,
|
|
243
|
+
help="Path to the output TSV file to create. Defaults to sample_metadata_<project_name>.tsv in the current directory. If a file already exists at the given path, you will be prompted to confirm if you want to overwrite it.",
|
|
244
|
+
),
|
|
245
|
+
project: str | None = PROJECT_NAME_OPTION,
|
|
246
|
+
) -> None:
|
|
247
|
+
"""
|
|
248
|
+
Create a template sample metadata file (TSV format) pre-filled with the sample names from the project's VCF files based on the information stored in the project's VCF dimensions cache. Tip: run 'divbase-cli dimensions update' first to ensure that the VCF dimensions areup-to-date.
|
|
249
|
+
"""
|
|
250
|
+
|
|
251
|
+
project_config = resolve_project(project_name=project)
|
|
252
|
+
|
|
253
|
+
if output_path is None:
|
|
254
|
+
output_path = Path.cwd() / f"sample_metadata_{project_config.name}.tsv"
|
|
255
|
+
|
|
256
|
+
response = make_authenticated_request(
|
|
257
|
+
method="GET",
|
|
258
|
+
divbase_base_url=project_config.divbase_url,
|
|
259
|
+
api_route=f"v1/vcf-dimensions/projects/{project_config.name}/samples",
|
|
260
|
+
)
|
|
261
|
+
unique_sample_names_sorted = DimensionsSamplesResult(**response.json()).unique_samples
|
|
262
|
+
|
|
263
|
+
sample_count = len(unique_sample_names_sorted)
|
|
264
|
+
print(
|
|
265
|
+
f"There were {sample_count} unique samples found in the dimensions file for the {project_config.name} project."
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
if sample_count == 0:
|
|
269
|
+
# Fallback in case there are no samples in the dimensions index. If no dimensions entry for the project
|
|
270
|
+
# VCFDimensionsEntryMissingError will be returned. But for some reason, there are no samples in the VCF, this will catch that.
|
|
271
|
+
print("No samples found for this project. No file written.")
|
|
272
|
+
return
|
|
273
|
+
|
|
274
|
+
# Check if file exists and prompt user for confirmation
|
|
275
|
+
if output_path.exists():
|
|
276
|
+
overwrite = typer.confirm(f"File '{output_path}' already exists. Do you want to overwrite it?")
|
|
277
|
+
if not overwrite:
|
|
278
|
+
print("File not written. Exiting.")
|
|
279
|
+
return
|
|
280
|
+
|
|
281
|
+
with open(output_path, mode="w", newline="") as tsvfile:
|
|
282
|
+
writer = csv.writer(tsvfile, delimiter="\t")
|
|
283
|
+
writer.writerow(["#Sample_ID"])
|
|
284
|
+
for sample in unique_sample_names_sorted:
|
|
285
|
+
writer.writerow([sample])
|
|
286
|
+
|
|
287
|
+
print(f"A sample metadata template with these sample names was written to: {output_path}")
|
|
288
|
+
|
|
289
|
+
# TODO perhaps add a message on how to fill in additional columns and how to upload the metadata file to DivBase?
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
@dimensions_app.command("validate-metadata-file")
|
|
293
|
+
def validate_metadata_template_versus_dimensions_and_formatting_constraints(
|
|
294
|
+
input_path: Path = typer.Argument(
|
|
295
|
+
...,
|
|
296
|
+
exists=True,
|
|
297
|
+
file_okay=True,
|
|
298
|
+
dir_okay=False,
|
|
299
|
+
resolve_path=True,
|
|
300
|
+
help="Path to the input TSV file to validate.",
|
|
301
|
+
),
|
|
302
|
+
untruncated: bool = typer.Option(
|
|
303
|
+
False,
|
|
304
|
+
"--untruncated",
|
|
305
|
+
help="Show full (untruncated) validator lists (including sample mismatches and grouped warning row/value previews).",
|
|
306
|
+
),
|
|
307
|
+
project: str | None = PROJECT_NAME_OPTION,
|
|
308
|
+
) -> None:
|
|
309
|
+
"""
|
|
310
|
+
Validate a sample metadata TSV file (before you upload it to the project's data store) to check that it will work with DivBase queries.
|
|
311
|
+
"""
|
|
312
|
+
# Client-side validation of a sidecar metadata TSV file, intended to be run before upload to DivBase.
|
|
313
|
+
# Uses the SharedMetadataValidator (that is also used on the server-side) which checks for formatting errors and also validates that the sample names
|
|
314
|
+
# in the TSV file match the sample names in the dimensions index for the project
|
|
315
|
+
|
|
316
|
+
project_config = resolve_project(project_name=project)
|
|
317
|
+
|
|
318
|
+
print(f"Validating local metadata file: {input_path}")
|
|
319
|
+
print(f"Project: {project_config.name}\n")
|
|
320
|
+
|
|
321
|
+
response = make_authenticated_request(
|
|
322
|
+
method="GET",
|
|
323
|
+
divbase_base_url=project_config.divbase_url,
|
|
324
|
+
api_route=f"v1/vcf-dimensions/projects/{project_config.name}/samples",
|
|
325
|
+
)
|
|
326
|
+
unique_sample_names = DimensionsSamplesResult(**response.json()).unique_samples
|
|
327
|
+
|
|
328
|
+
dimensions_sample_preview_limit = None if untruncated else 20
|
|
329
|
+
|
|
330
|
+
shared_validator = SharedMetadataValidator(
|
|
331
|
+
file_path=input_path,
|
|
332
|
+
project_samples=set(unique_sample_names),
|
|
333
|
+
skip_dimensions_check=False,
|
|
334
|
+
dimensions_sample_preview_limit=dimensions_sample_preview_limit,
|
|
335
|
+
)
|
|
336
|
+
result = shared_validator.load_and_validate()
|
|
337
|
+
|
|
338
|
+
errors = [error_entry.message for error_entry in result.errors]
|
|
339
|
+
warnings = [warning_entry.message for warning_entry in result.warnings]
|
|
340
|
+
stats = result.stats
|
|
341
|
+
numeric_cols = result.numeric_columns
|
|
342
|
+
string_cols = result.string_columns
|
|
343
|
+
mixed_cols = result.mixed_type_columns
|
|
344
|
+
|
|
345
|
+
print("[bold cyan]VALIDATION SUMMARY:[/bold cyan]")
|
|
346
|
+
print(
|
|
347
|
+
f" Total columns: {getattr(stats, 'total_columns', 0)} ({getattr(stats, 'user_defined_columns', 0)} user-defined + 1 Sample_ID column)"
|
|
348
|
+
)
|
|
349
|
+
|
|
350
|
+
samples_in_tsv = getattr(stats, "samples_in_tsv", 0)
|
|
351
|
+
samples_matching = getattr(stats, "samples_matching_project", 0)
|
|
352
|
+
total_project = getattr(stats, "total_project_samples", 0)
|
|
353
|
+
|
|
354
|
+
print(
|
|
355
|
+
f" Samples matching project VCF dimensions: {samples_matching}/{samples_in_tsv} (project has {total_project} total)"
|
|
356
|
+
)
|
|
357
|
+
|
|
358
|
+
print(f" Numeric columns ({len(numeric_cols)}): {', '.join(numeric_cols) if numeric_cols else 'None'}")
|
|
359
|
+
print(f" String columns ({len(string_cols)}): {', '.join(string_cols) if string_cols else 'None'}")
|
|
360
|
+
print(
|
|
361
|
+
f" Mixed-type columns treated as string ({len(mixed_cols)}): {', '.join(mixed_cols) if mixed_cols else 'None'}"
|
|
362
|
+
)
|
|
363
|
+
|
|
364
|
+
if getattr(stats, "has_multi_values", False):
|
|
365
|
+
print(" Multi-value cells: Yes (Python list notation detected)")
|
|
366
|
+
else:
|
|
367
|
+
print(" Multi-value cells: No")
|
|
368
|
+
|
|
369
|
+
empty_cells = getattr(stats, "empty_cells_per_column", {})
|
|
370
|
+
if empty_cells:
|
|
371
|
+
print(
|
|
372
|
+
f" User-defined columns with empty cells ({len(empty_cells)}): {', '.join(f'{col} ({count})' for col, count in empty_cells.items())}"
|
|
373
|
+
)
|
|
374
|
+
|
|
375
|
+
print()
|
|
376
|
+
|
|
377
|
+
if errors:
|
|
378
|
+
print("[red bold]ERRORS (must be fixed):[/red bold]")
|
|
379
|
+
for error in errors:
|
|
380
|
+
print(f" - {error}")
|
|
381
|
+
print()
|
|
382
|
+
|
|
383
|
+
if warnings:
|
|
384
|
+
print("[yellow bold]WARNINGS (should be reviewed):[/yellow bold]")
|
|
385
|
+
for warning in warnings:
|
|
386
|
+
print(f" - {warning}")
|
|
387
|
+
print()
|
|
388
|
+
|
|
389
|
+
if not errors and not warnings:
|
|
390
|
+
print(
|
|
391
|
+
"[green bold]Validation passed![/green bold] The metadata file meets all DivBase requirements. The file is ready to be uploaded to your DivBase project with 'divbase-cli files upload'"
|
|
392
|
+
)
|
|
393
|
+
elif errors:
|
|
394
|
+
print("[red bold]Validation failed![/red bold] Please fix the errors above before uploading.")
|
|
395
|
+
raise typer.Exit(code=1)
|
|
396
|
+
else:
|
|
397
|
+
print("[yellow bold]Validation passed with warnings![/yellow bold] Review the warnings above.")
|
|
398
|
+
|
|
399
|
+
# TODO: Add information about how to upload the validated metadata file to DivBase
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def _truncate_sample_names_in_entry(entry: dict, sample_names_limit: int) -> None:
|
|
403
|
+
"""
|
|
404
|
+
Truncate sample names output in terminal, while preserving full counts.
|
|
405
|
+
"""
|
|
406
|
+
dimensions = entry.get("dimensions", {})
|
|
407
|
+
sample_names = dimensions.get("sample_names", [])
|
|
408
|
+
if len(sample_names) > sample_names_limit:
|
|
409
|
+
dimensions["sample_names"] = sample_names[:sample_names_limit]
|
|
410
|
+
dimensions["sample_names_note"] = (
|
|
411
|
+
f"Showing first {sample_names_limit} of {len(sample_names)} samples. "
|
|
412
|
+
"Use --sample-names-output <FILE> or --sample-names-stdout to view all."
|
|
413
|
+
)
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
def _write_or_print_sample_names(
|
|
417
|
+
indexed_files: list[dict],
|
|
418
|
+
sample_names_output: str | None,
|
|
419
|
+
sample_names_stdout: bool,
|
|
420
|
+
) -> None:
|
|
421
|
+
"""
|
|
422
|
+
Export full sample names data from divbase-cli dimensions show
|
|
423
|
+
either to a file or to stdout. If used without --unique-samples, it will also include the filename that each sample occurs in.
|
|
424
|
+
"""
|
|
425
|
+
lines: list[str] = []
|
|
426
|
+
for entry in indexed_files:
|
|
427
|
+
file_name = entry.get("filename", "")
|
|
428
|
+
sample_names = entry.get("dimensions", {}).get("sample_names", [])
|
|
429
|
+
for sample_name in sample_names:
|
|
430
|
+
lines.append(f"{file_name}\t{sample_name}")
|
|
431
|
+
|
|
432
|
+
if sample_names_output:
|
|
433
|
+
output_path = Path(sample_names_output)
|
|
434
|
+
output_path.write_text("\n".join(lines) + ("\n" if lines else ""))
|
|
435
|
+
print(f"Wrote {len(lines)} sample-name rows to: {output_path}")
|
|
436
|
+
return
|
|
437
|
+
|
|
438
|
+
if sample_names_stdout:
|
|
439
|
+
print("\n".join(lines))
|