divbase-cli 0.1.0.dev3__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 CHANGED
@@ -1 +1 @@
1
- __version__ = "0.1.0.dev3"
1
+ __version__ = "0.1.0.dev4"
@@ -2,6 +2,7 @@
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
7
 
7
8
  import typer
@@ -9,7 +10,8 @@ from pydantic import SecretStr
9
10
  from typing_extensions import Annotated
10
11
 
11
12
  from divbase_cli.cli_config import cli_settings
12
- 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
13
15
  from divbase_cli.user_auth import (
14
16
  check_existing_session,
15
17
  login_to_divbase,
@@ -18,6 +20,8 @@ from divbase_cli.user_auth import (
18
20
  )
19
21
  from divbase_cli.user_config import load_user_config
20
22
 
23
+ logger = logging.getLogger(__name__)
24
+
21
25
  auth_app = typer.Typer(
22
26
  no_args_is_help=True, help="Login/logout of DivBase server. To register, visit https://divbase.scilifelab.se/."
23
27
  )
@@ -53,6 +57,13 @@ def login(
53
57
  return
54
58
 
55
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
+
56
67
  print(f"Logged in successfully as: {email}")
57
68
 
58
69
 
@@ -1,12 +1,20 @@
1
+ import csv
1
2
  import logging
3
+ from pathlib import Path
2
4
 
3
5
  import typer
4
6
  import yaml
7
+ from rich import print
5
8
 
6
9
  from divbase_cli.cli_commands.shared_args_options import PROJECT_NAME_OPTION
7
10
  from divbase_cli.config_resolver import resolve_project
8
11
  from divbase_cli.user_auth import make_authenticated_request
9
- from divbase_lib.api_schemas.vcf_dimensions import DimensionsShowResult
12
+ from divbase_lib.api_schemas.vcf_dimensions import (
13
+ DimensionsSamplesResult,
14
+ DimensionsScaffoldsResult,
15
+ DimensionsShowResult,
16
+ )
17
+ from divbase_lib.metadata_validator import SharedMetadataValidator
10
18
 
11
19
  logger = logging.getLogger(__name__)
12
20
 
@@ -49,6 +57,30 @@ def show_dimensions_index(
49
57
  help="If set, will show all unique scaffold names found across all the VCF files in the project.",
50
58
  )
51
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
+ ),
52
84
  project: str | None = PROJECT_NAME_OPTION,
53
85
  ) -> None:
54
86
  """
@@ -58,6 +90,57 @@ def show_dimensions_index(
58
90
 
59
91
  project_config = resolve_project(project_name=project)
60
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
143
+
61
144
  response = make_authenticated_request(
62
145
  method="GET",
63
146
  divbase_base_url=project_config.divbase_url,
@@ -74,6 +157,15 @@ def show_dimensions_index(
74
157
  record = entry
75
158
  break
76
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)
77
169
  print(yaml.safe_dump(record, sort_keys=False))
78
170
  else:
79
171
  print(
@@ -82,26 +174,17 @@ def show_dimensions_index(
82
174
  )
83
175
  return
84
176
 
85
- if unique_scaffolds:
86
- unique_scaffold_names = set()
87
- for entry in dimensions_info.get("indexed_files", []):
88
- unique_scaffold_names.update(entry.get("dimensions", {}).get("scaffolds", []))
89
-
90
- numeric_scaffold_names = []
91
- non_numeric_scaffold_names = []
92
- for scaffold in unique_scaffold_names:
93
- if scaffold.isdigit():
94
- numeric_scaffold_names.append(int(scaffold))
95
- else:
96
- non_numeric_scaffold_names.append(scaffold)
97
-
98
- unique_scaffold_names_sorted = [str(n) for n in sorted(numeric_scaffold_names)] + sorted(
99
- 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,
100
182
  )
101
-
102
- print(f"Unique scaffold names found across all the VCF files in the project:\n{unique_scaffold_names_sorted}")
103
183
  return
104
184
 
185
+ for entry in dimensions_info.get("indexed_files", []):
186
+ _truncate_sample_names_in_entry(entry, sample_names_limit)
187
+
105
188
  print(yaml.safe_dump(dimensions_info, sort_keys=False))
106
189
 
107
190
 
@@ -109,14 +192,23 @@ def _format_api_response_for_display_in_terminal(api_response: DimensionsShowRes
109
192
  """
110
193
  Convert the API response to a YAML-like format for display in the user's terminal.
111
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
+
112
201
  dimensions_list = []
113
202
  for entry in api_response.vcf_files:
203
+ scaffolds = entry.get("scaffolds", [])
204
+ sorted_scaffolds = sort_scaffolds(scaffolds)
114
205
  dimensions_entry = {
115
206
  "filename": entry["vcf_file_s3_key"],
116
207
  "file_version_ID_in_bucket": entry["s3_version_id"],
117
208
  "last_updated": entry.get("updated_at"),
118
209
  "dimensions": {
119
- "scaffolds": entry.get("scaffolds", []),
210
+ "scaffold_count": len(sorted_scaffolds),
211
+ "scaffolds": sorted_scaffolds,
120
212
  "sample_count": entry.get("sample_count", 0),
121
213
  "sample_names": entry.get("samples", []),
122
214
  "variants": entry.get("variant_count", 0),
@@ -137,3 +229,211 @@ def _format_api_response_for_display_in_terminal(api_response: DimensionsShowRes
137
229
  "indexed_files": dimensions_list,
138
230
  "skipped_files": skipped_list,
139
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))