-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy path__main__.py
More file actions
executable file
·1461 lines (1368 loc) · 43 KB
/
__main__.py
File metadata and controls
executable file
·1461 lines (1368 loc) · 43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
import logging
import os
import json
import sys
from datetime import datetime
import inspect
# from rich.prompt import Confirm
import click
import relecov_tools.config_json
import relecov_tools.download
import relecov_tools.log_summary
import rich.console
import rich.traceback
import relecov_tools.config_json
import relecov_tools.utils
import relecov_tools.read_lab_metadata
import relecov_tools.download
import relecov_tools.validate
import relecov_tools.mail
import relecov_tools.map
import relecov_tools.upload_database
import relecov_tools.read_bioinfo_metadata
import relecov_tools.metadata_homogeneizer
import relecov_tools.gisaid_upload
import relecov_tools.ena_upload
import relecov_tools.pipeline_manager
import relecov_tools.build_schema
import relecov_tools.metadata_precheck
import relecov_tools.wrapper
import relecov_tools.upload_results
import relecov_tools.base_module
log = logging.getLogger()
# Set up rich stderr console
stderr = rich.console.Console(
stderr=True, force_terminal=relecov_tools.utils.rich_force_colors()
)
__version__ = "1.7.2dev"
# IMPORTANT: When defining a Click command function in this script,
# you MUST include both 'ctx' (for @click.pass_context) and ALL the parameters
# defined by @click.option decorators in the function signature.
# Example:
# @click.pass_context
# def my_command(ctx, param1, param2, ...):
# ...
# This is required for correct argument passing and to avoid runtime errors.
# Set up merge config with extra plus CLI
def merge_with_extra_config(ctx, add_extra_config=False):
"""
Build the **final** argument dictionary that will be passed
to the Click‐command callback.
Priority order (highest → lowest):
1. CLI arguments
2. extra_config.json → "commands" (user overrides)
3. configuration.json → "params" (defaults)
Empty strings ('') are normalised to None and any key that is not
part of the callback's signature is silently dropped.
"""
# ── 1. Load configuration (with or without extra_config) ────────────
config = relecov_tools.config_json.ConfigJson(extra_config=add_extra_config)
ctx.obj["config"] = config.json_data # keep full config for later use
command_name = ctx.command.name.replace("-", "_") # e.g. "read-lab-metadata"
command_params = ctx.params # dict with CLI args
# ── 2. Pull defaults + overrides for this command ───────────────────
# If the block was migrated to the new "params/commands" layout,
# flatten it respecting the priority commands > params.
topic_block = config.json_data.get(command_name, {})
if isinstance(topic_block, dict) and (
"params" in topic_block or "commands" in topic_block
):
extra_args = dict(topic_block.get("params", {})) # defaults
extra_args.update(topic_block.get("commands", {})) # > overrides
else:
# Legacy (flat) section – still supported.
extra_args = topic_block
# ── 3. Merge with CLI (CLI > all) ──────────────────────────────────
merged = dict(extra_args)
for k, v in command_params.items():
if v is not None: # CLI value always wins (except None means “not given”)
merged[k] = v
# ── 4. Normalise empty strings to None ──────────────────────────────
for k, v in merged.items():
if v == "":
merged[k] = None
# ── 5. Strip out keys that are not in the callback's signature ─────
func = ctx.command.callback
sig = inspect.signature(func)
valid_keys = sig.parameters.keys()
filtered = {k: v for k, v in merged.items() if k in valid_keys}
return filtered
def run_relecov_tools():
# Set up the rich traceback
rich.traceback.install(console=stderr, width=200, word_wrap=True, extra_lines=1)
# Print nf-core header
# stderr.print("\n[green]{},--.[grey39]/[green],-.".format(" " * 42), highlight=False)
stderr.print(
r"[blue] ___ ___ ___ ___ ___ ",
highlight=False,
)
stderr.print(
r"[blue] \ |-[grey39]-| [blue] | \ | | | | | | \ / ",
highlight=False,
)
stderr.print(
r"[blue] \ \ [grey39]/ [blue] |__ / |__ | |___ | | | \ / ",
highlight=False,
)
stderr.print(
r"[blue] / [grey39] / [blue] \ | \ | | | | | | \ / ",
highlight=False,
)
stderr.print(
r"[blue] / [grey39] |-[blue]-| | \ |___ |___ |___ |___ |___| \/ ",
highlight=False,
)
# stderr.print("[green] `._,._,'\n", highlight=False)
stderr.print(
"\n" r"[grey39] RELECOV-tools version {}".format(__version__),
highlight=False,
)
# Lanch the click cli
relecov_tools_cli()
# Customise the order of subcommands for --help
class CustomHelpOrder(click.Group):
def __init__(self, *args, **kwargs):
self.help_priorities = {}
super(CustomHelpOrder, self).__init__(*args, **kwargs)
def get_help(self, ctx):
self.list_commands = self.list_commands_for_help
return super(CustomHelpOrder, self).get_help(ctx)
def list_commands_for_help(self, ctx):
"""reorder the list of commands when listing the help"""
commands = super(CustomHelpOrder, self).list_commands(ctx)
return (
c[1]
for c in sorted(
(self.help_priorities.get(command, 1000), command)
for command in commands
)
)
def command(self, *args, **kwargs):
"""Behaves the same as `click.Group.command()` except capture
a priority for listing command names in help.
"""
help_priority = kwargs.pop("help_priority", 1000)
help_priorities = self.help_priorities
def decorator(f):
cmd = super(CustomHelpOrder, self).command(*args, **kwargs)(f)
help_priorities[cmd.name] = help_priority
return cmd
return decorator
@click.group(cls=CustomHelpOrder)
@click.version_option(relecov_tools.__version__)
@click.option(
"-v",
"--verbose",
is_flag=True,
default=False,
help="Print verbose output to the console.",
)
@click.option(
"-l",
"--log-path",
default=None,
help="Creates log file in given folder. Uses default path in config or tmp if empty.",
)
@click.option(
"-d",
"--debug",
is_flag=True,
default=False,
help="Show the full traceback on error for debugging purposes.",
)
@click.option(
"-h",
"--hex-code",
default=None,
help="Define hexadecimal code. This might overwrite existing files with the same hex-code",
)
@click.pass_context
def relecov_tools_cli(ctx, verbose, log_path, debug, hex_code):
if debug:
# Set the base logger to output everything
level = logging.DEBUG
else:
# Set the base logger to hide DEBUG messages
level = logging.INFO
log.setLevel(level)
if verbose:
stream_handler = relecov_tools.base_module.BaseModule.set_log_handler(
None, level=level, only_stream=True
)
log.addHandler(stream_handler)
if hex_code is not None:
relecov_tools.base_module.BaseModule._global_hex_code = str(hex_code)
# Set up logs to a file if we asked for one
called_module = str(ctx.invoked_subcommand).replace("-", "_")
if os.path.isfile(relecov_tools.config_json.ConfigJson._extra_config_path):
config = relecov_tools.config_json.ConfigJson(extra_config=True)
else:
config = relecov_tools.config_json.ConfigJson()
logs_config = config.get_topic_data("generic", "logs_config")
default_outpath = logs_config.get("default_outpath", "/tmp/relecov_tools")
if log_path is None:
log_path = logs_config.get("modules_outpath", {}).get(called_module)
if not log_path:
log_path = os.path.join(default_outpath, called_module)
else:
relecov_tools.base_module.BaseModule._cli_log_path_param = log_path
current_datetime = datetime.today().strftime("%Y%m%d%-H%M%S")
log_filepath = os.path.join(
log_path, "_".join([called_module, current_datetime]) + ".log"
)
try:
os.makedirs(log_path, exist_ok=True)
log_fh = relecov_tools.base_module.BaseModule.set_log_handler(
log_filepath, level=level
)
log.addHandler(log_fh)
except Exception:
log_filepath = os.path.join(
default_outpath, "_".join([called_module, "temp"]) + ".log"
)
os.makedirs(default_outpath, exist_ok=True)
log_fh = relecov_tools.base_module.BaseModule.set_log_handler(
log_filepath, level=level
)
log.addHandler(log_fh)
log.warning(f"Invalid --log-path {log_path}. Using {log_filepath} instead")
relecov_tools.base_module.BaseModule._cli_log_file = os.path.realpath(log_filepath)
cli_command = " ".join(sys.argv)
relecov_tools.base_module.BaseModule._cli_command = cli_command
relecov_tools.base_module.BaseModule._current_version = __version__
ctx.ensure_object(dict) # Asegura que ctx.obj es un diccionario
ctx.obj["debug"] = debug # Guarda el flag de debug
# sftp
@relecov_tools_cli.command(help_priority=2)
@click.option("-u", "--user", help="User name for login to sftp server")
@click.option("-p", "--password", help="password for the user to login")
@click.option(
"-f",
"--conf_file",
help="Configuration file (not params file)",
)
@click.option(
"-d",
"--download_option",
default=None,
multiple=False,
help="Select the download option: [download_only, download_clean, delete_only]. \
download_only will only download the files \
download_clean will remove files from sftp after download \
delete_only will only delete the files",
)
@click.option(
"-o",
"--output_dir",
"--output-dir",
"--output_folder",
"--out-folder",
"--output_location",
"--output_path",
"--out_dir",
"--output",
"output_dir",
type=click.Path(file_okay=False, resolve_path=True),
help="Directory where the generated output will be saved",
)
@click.option(
"-t",
"--target_folders",
is_flag=False,
flag_value="ALL",
default=None,
help='Flag: Select which folders will be targeted giving [paths] or via prompt. For multiple folders use ["folder1", "folder2"]',
)
@click.option(
"-s",
"--subfolder",
default=None,
help="Flag: Specify which subfolder to process",
)
@click.pass_context
def download(
ctx,
user,
password,
conf_file,
download_option,
output_dir,
target_folders,
subfolder,
):
"""Download files located in sftp server."""
debug = ctx.obj.get("debug", False)
args_merged = merge_with_extra_config(
ctx=ctx,
add_extra_config=True,
)
try:
download = relecov_tools.download.Download(**args_merged)
download.execute_process()
except Exception as e:
if debug:
log.exception(f"EXCEPTION FOUND: {e}")
raise
else:
log.exception(f"EXCEPTION FOUND: {e}")
stderr.print(f"EXCEPTION FOUND: {e}")
sys.exit(1)
@relecov_tools_cli.command(help_priority=3)
@click.option("-u", "--user", help="User name for login to sftp server")
@click.option("-p", "--password", help="Password for the user to login")
@click.option(
"-f",
"--conf_file",
help="Configuration file (not params file)",
)
@click.option(
"-o",
"--output_dir",
"--output-dir",
"--output_folder",
"--out-folder",
"--output_location",
"--output_path",
"--out_dir",
"--output",
"output_dir",
type=click.Path(file_okay=False, resolve_path=True),
help="Directory where the generated output and logs will be saved",
)
@click.option(
"-t",
"--target_folders",
is_flag=False,
flag_value="ALL",
default=None,
help='Flag: Select which folders will be targeted giving [paths] or via prompt. For multiple folders use ["folder1", "folder2"]',
)
@click.option(
"--export-excel/--no-export-excel",
default=False,
help="Generate an Excel summary alongside the JSON report",
)
@click.pass_context
def metadata_precheck(
ctx,
user,
password,
conf_file,
output_dir,
target_folders,
export_excel,
):
"""Inspect remote metadata Excels and report missing required data."""
debug = ctx.obj.get("debug", False)
args_merged = merge_with_extra_config(
ctx=ctx,
add_extra_config=True,
)
try:
precheck = relecov_tools.metadata_precheck.MetadataPrecheck(**args_merged)
precheck.execute_process()
except Exception as e:
if debug:
log.exception(f"EXCEPTION FOUND: {e}")
raise
else:
log.exception(f"EXCEPTION FOUND: {e}")
stderr.print(f"EXCEPTION FOUND: {e}")
sys.exit(1)
# metadata
@relecov_tools_cli.command(help_priority=3)
@click.option(
"-m",
"--metadata_file",
type=click.Path(),
help="file containing metadata",
)
@click.option(
"-s",
"--sample_list_file",
type=click.Path(),
help="Json with the additional metadata to add to the received user metadata",
)
@click.option(
"-o",
"--output_dir",
"--output-dir",
"--output_folder",
"--out-folder",
"--output_location",
"--output_path",
"--out_dir",
"--output",
"output_dir",
type=click.Path(file_okay=False, resolve_path=True),
help="Directory where the generated output will be saved",
)
@click.option(
"-f",
"--files-folder",
default=None,
type=click.Path(),
help="Path to folder where samples files are located",
)
@click.pass_context
def read_lab_metadata(ctx, metadata_file, sample_list_file, output_dir, files_folder):
"""
Create the json compliant to the relecov schema from the Metadata file.
"""
# Merge arguments
args_merged = merge_with_extra_config(ctx=ctx, add_extra_config=True)
debug = ctx.obj.get("debug", False)
try:
new_metadata = relecov_tools.read_lab_metadata.LabMetadata(**args_merged)
new_metadata.create_metadata_json()
except Exception as e:
if debug:
log.exception(f"EXCEPTION FOUND: {e}")
raise
else:
log.exception(f"EXCEPTION FOUND: {e}")
stderr.print(f"EXCEPTION FOUND: {e}")
sys.exit(1)
# validation
@relecov_tools_cli.command(help_priority=4)
@click.option("-j", "--json_file", help="Json file to validate")
@click.option(
"-s", "--json_schema_file", help="Path to the JSON Schema file used for validation"
)
@click.option(
"-m",
"--metadata",
type=click.Path(),
help="Origin file containing metadata",
)
@click.option(
"-o",
"--output_dir",
"--output-dir",
"--output_folder",
"--out-folder",
"--output_location",
"--output_path",
"--out_dir",
"--output",
"output_dir",
type=click.Path(file_okay=False, resolve_path=True),
help="Directory where the generated output will be saved",
)
@click.option(
"-e",
"--excel_sheet",
required=False,
default=None,
help="Optional: Name of the sheet in excel file to validate.",
)
@click.option(
"-u",
"--upload_files",
is_flag=True,
default=False,
help="Wether to upload the resulting files from validation process or not.",
)
@click.option(
"-l",
"--logsum_file",
required=False,
default=None,
help="Required if --upload_files. Path to the log_summary.json file merged from all previous processes, used to check for invalid samples.",
)
@click.option(
"-s",
"--samples_json",
type=click.Path(exists=True, dir_okay=False, resolve_path=True),
required=False,
help="Optional: Path to samples_data*.json to auto-detect corrupted files.",
)
@click.option(
"-c",
"--check_db",
is_flag=True,
default=False,
help="Check if the processed samples are already uploaded to platform database and make invalid those that are already there",
)
@click.pass_context
def validate(
ctx,
json_file,
json_schema_file,
metadata,
output_dir,
excel_sheet,
upload_files,
logsum_file,
samples_json,
check_db,
):
"""Validate json file against schema."""
debug = ctx.obj.get("debug", False)
args_merged = merge_with_extra_config(ctx=ctx, add_extra_config=True)
try:
validation = relecov_tools.validate.Validate(**args_merged)
validation.execute_validation_process()
except Exception as e:
if debug:
log.exception(f"EXCEPTION FOUND: {e}")
raise
else:
log.exception(f"EXCEPTION FOUND: {e}")
stderr.print(f"EXCEPTION FOUND: {e}")
sys.exit(1)
# send-email
@relecov_tools_cli.command(help_priority=4)
@click.option(
"-v",
"--validate_file",
required=True,
type=click.Path(exists=True),
help="Path to the validation summary json file (validate_log_summary.json)",
)
@click.option(
"-r",
"--receiver_email",
required=False,
help="Recipient's e-mail address (optional). If not provided, it will be extracted from the institutions guide.",
)
@click.option(
"-a",
"--attachments",
multiple=True,
type=click.Path(exists=True),
help="Path to file",
)
@click.option(
"-t",
"--template_path",
type=click.Path(exists=True),
required=False,
default=None,
help="Path to relecov-tools templates folder (optional)",
)
@click.option(
"-p",
"--email_psswd",
help="Password for bioinformatica@isciii.es",
required=False,
default=None,
)
@click.option(
"-n",
"--additional_notes",
type=click.Path(exists=True),
required=False,
help="Path to a .txt file with additional notes to include in the email (optional).",
)
@click.pass_context
def send_mail(
ctx,
validate_file,
receiver_email,
attachments,
template_path,
email_psswd,
additional_notes,
):
"""
Send a sample validation report by mail.
"""
debug = ctx.obj.get("debug", False)
args_merged = merge_with_extra_config(ctx=ctx, add_extra_config=True)
# Get arguments to use them here
validate_file = args_merged.get("validate_file")
receiver_email = args_merged.get("receiver_email")
attachments = args_merged.get("attachments")
template_path = args_merged.get("template_path")
email_psswd = args_merged.get("email_psswd")
additional_notes = args_merged.get("additional_notes")
template_choice = click.prompt(
"Select the type of template:\n1. Validation with errors\n2. Validation successful",
type=int,
default=1,
show_choices=False,
)
if template_choice not in [1, 2]:
raise ValueError("Error: invalid option.")
# Determinar el template a usar
if template_choice == 1:
template_name = "template_with_errors_relecov.j2"
else:
template_name = "template_success_relecov.j2"
additional_info = ""
if additional_notes:
with open(additional_notes, "r", encoding="utf-8") as f:
additional_info = f.read().strip()
else:
if click.confirm(
"Would you like to add a .txt file with additional notes?", default=False
):
notes_path = click.prompt(
"Enter the path to the .txt file", type=click.Path(exists=True)
)
with open(notes_path, "r", encoding="utf-8") as f:
additional_info = f.read().strip()
elif click.confirm(
"Would you like to write additional notes manually?", default=False
):
additional_info = click.prompt("Enter additional information").strip()
try:
mail_result = relecov_tools.mail.run_mail(
validate_file=validate_file,
receiver_email=receiver_email,
attachments=list(attachments) if attachments else [],
template_path=template_path,
email_psswd=email_psswd,
additional_info=additional_info,
template_name=template_name,
stderr=stderr,
)
except Exception as e:
if debug:
log.exception(f"EXCEPTION FOUND: {e}")
raise
else:
log.exception(f"EXCEPTION FOUND: {e}")
stderr.print(f"EXCEPTION FOUND: {e}")
sys.exit(1)
else:
log_path = mail_result.get("log_path")
batch_log = mail_result.get("batch_log_path")
if log_path:
log.info(f"Mail log stored at {log_path}")
if batch_log:
log.info(f"Mail log copied to batch folder: {batch_log}")
# mapping to ENA schema
@relecov_tools_cli.command(help_priority=5)
@click.option("-p", "--origin_schema", help="File with the origin (relecov) schema")
@click.option(
"-j", "--json_data", "json_file", help="File with the json data to convert"
)
@click.option(
"-d",
"--destination_schema",
type=click.Choice(["ENA", "GISAID", "other"], case_sensitive=True),
help="schema to be mapped",
)
@click.option("-f", "--schema_file", help="file with the custom schema")
@click.option(
"-o",
"--output_dir",
"--output-dir",
"--output_folder",
"--out-folder",
"--output_location",
"--output_path",
"--out_dir",
"--output",
"output_dir",
type=click.Path(file_okay=False, resolve_path=True),
help="Directory where the generated output will be saved",
)
@click.pass_context
def map(ctx, origin_schema, json_file, destination_schema, schema_file, output_dir):
"""Convert data between phage plus schema to ENA, GISAID, or any other schema"""
debug = ctx.obj.get("debug", False)
args_merged = merge_with_extra_config(ctx=ctx, add_extra_config=True)
try:
new_schema = relecov_tools.map.Map(**args_merged)
new_schema.map_to_data_to_new_schema()
except Exception as e:
if debug:
log.exception(f"EXCEPTION FOUND: {e}")
raise
else:
log.exception(f"EXCEPTION FOUND: {e}")
stderr.print(f"EXCEPTION FOUND: {e}")
sys.exit(1)
# upload to ENA
@relecov_tools_cli.command(help_priority=6)
@click.option("-u", "--user", help="user name for login to ena")
@click.option("-p", "--password", help="password for the user to login")
@click.option("-c", "--center", help="center name")
@click.option("-e", "--ena_json", help="where the validated json is")
@click.option("-t", "--template_path", help="Path to ENA templates folder")
@click.option(
"-a",
"--action",
type=click.Choice(["ADD", "MODIFY", "CANCEL", "RELEASE"], case_sensitive=False),
help="select one of the available options",
)
@click.option("--dev", is_flag=True, default=False, help="Test submission")
@click.option("--upload_fastq", is_flag=True, default=False, help="Upload fastq files")
@click.option("-m", "--metadata_types", help="List of metadata xml types to submit")
@click.option(
"-o",
"--output_dir",
"--output-dir",
"--output_folder",
"--out-folder",
"--output_location",
"--output_path",
"--out_dir",
"--output",
"output_dir",
type=click.Path(file_okay=False, resolve_path=True),
help="Directory where the generated output will be saved",
)
@click.pass_context
def upload_to_ena(
ctx,
user,
password,
center,
ena_json,
template_path,
dev,
action,
metadata_types,
upload_fastq,
output_dir,
):
"""parse data to create xml files to upload to ena"""
debug = ctx.obj.get("debug", False)
args_merged = merge_with_extra_config(ctx=ctx, add_extra_config=True)
try:
upload_ena = relecov_tools.ena_upload.EnaUpload(**args_merged)
upload_ena.upload()
except Exception as e:
if debug:
log.exception(f"EXCEPTION FOUND: {e}")
raise
else:
log.exception(f"EXCEPTION FOUND: {e}")
stderr.print(f"EXCEPTION FOUND: {e}")
sys.exit(1)
# upload to GISAID
@relecov_tools_cli.command(help_priority=7)
@click.option("-u", "--user", help="user name for login")
@click.option("-p", "--password", help="password for the user to login")
@click.option("-c", "--client_id", help="client-ID provided by clisupport@gisaid.org")
@click.option("-t", "--token", help="path to athentication token")
@click.option("-e", "--gisaid_json", help="path to validated json mapped to GISAID")
@click.option(
"-i",
"--input_path",
help="path to fastas folder or multifasta file",
)
@click.option(
"-o",
"--output_dir",
"--output-dir",
"--output_folder",
"--out-folder",
"--output_location",
"--output_path",
"--out_dir",
"--output",
"output_dir",
type=click.Path(file_okay=False, resolve_path=True),
help="Directory where the generated output will be saved",
)
@click.option(
"-f",
"--frameshift",
type=click.Choice(["catch_all", "catch_none", "catch_novel"], case_sensitive=False),
help="frameshift notification",
)
@click.option(
"-x",
"--proxy_config",
help="introduce your proxy credentials as: username:password@proxy:port",
required=False,
)
@click.option(
"--single",
is_flag=True,
default=False,
help="input is a folder with several fasta files. Default: False",
)
@click.option(
"--gzip",
is_flag=True,
default=False,
help="input fasta is gziped. Default: False",
)
@click.pass_context
def upload_to_gisaid(
ctx,
user,
password,
client_id,
token,
gisaid_json,
input_path,
output_dir,
frameshift,
proxy_config,
single,
gzip,
):
"""parsed data to create files to upload to gisaid"""
debug = ctx.obj.get("debug", False)
args_merged = merge_with_extra_config(ctx=ctx, add_extra_config=True)
try:
upload_gisaid = relecov_tools.gisaid_upload.GisaidUpload(**args_merged)
upload_gisaid.gisaid_upload()
except Exception as e:
if debug:
log.exception(f"EXCEPTION FOUND: {e}")
raise
else:
log.exception(f"EXCEPTION FOUND: {e}")
stderr.print(f"EXCEPTION FOUND: {e}")
sys.exit(1)
# update_db
@relecov_tools_cli.command(help_priority=9)
@click.option("-j", "--json", help="data in json format")
@click.option(
"-t",
"--type",
type=click.Choice(["sample", "bioinfodata", "variantdata"]),
multiple=False,
default=None,
help="Select the type of information to upload to database",
)
@click.option(
"-plat",
"--platform",
type=click.Choice(
[
"iskylims",
"relecov",
]
),
multiple=False,
default=None,
help="name of the platform where data is uploaded",
)
@click.option("-u", "--user", help="user name for login")
@click.option("-p", "--password", help="password for the user to login")
@click.option("-s", "--server_url", help="url of the platform server")
@click.option(
"-f",
"--full_update",
is_flag=True,
default=False,
help="Sequentially run every update option",
)
@click.option(
"-l",
"--long_table",
default=None,
help="Long_table.json file from read-bioinfo-metadata + viralrecon",
)
@click.pass_context
def update_db(
ctx, user, password, json, type, platform, server_url, full_update, long_table
):
"""upload the information included in json file to the database"""
debug = ctx.obj.get("debug", False)
args_merged = merge_with_extra_config(ctx=ctx, add_extra_config=True)
try:
update_database_obj = relecov_tools.upload_database.UploadDatabase(
**args_merged
)
update_database_obj.update_db()
except Exception as e:
if debug:
log.exception(f"EXCEPTION FOUND: {e}")
raise
else:
log.exception(f"EXCEPTION FOUND: {e}")
stderr.print(f"EXCEPTION FOUND: {e}")
sys.exit(1)
# read metadata bioinformatics
@relecov_tools_cli.command(help_priority=10)
@click.option(
"-j",
"--json_file",
type=click.Path(),
help="json file containing lab metadata",
)
@click.option(
"-s", "--json_schema_file", help="Path to the JSON Schema file used for validation"
)
@click.option("-i", "--input_folder", type=click.Path(), help="Path to input files")
@click.option(
"-o",
"--output_dir",
"--output-dir",
"--output_folder",
"--out-folder",
"--output_location",
"--output_path",
"--out_dir",
"--output",
"output_dir",
type=click.Path(file_okay=False, resolve_path=True),
help="Directory where the generated output will be saved",
)
@click.option("-p", "--software_name", help="Name of the software/pipeline used.")
@click.option(
"--update",
is_flag=True,
default=False,
help="If the output file already exists, ask if you want to update it.",
)
@click.option(
"--soft_validation",
is_flag=True,
default=False,
help="If the module should continue even if any sample does not validate.",
)
@click.pass_context
def read_bioinfo_metadata(
ctx,
json_file,
json_schema_file,
input_folder,
output_dir,
software_name,
update,
soft_validation,
):
"""
Create the json compliant from the Bioinfo Metadata.
"""
# Merge arguments
args_merged = merge_with_extra_config(
ctx=ctx,
add_extra_config=True,
)
debug = ctx.obj.get("debug", False)
try:
new_bioinfo_metadata = relecov_tools.read_bioinfo_metadata.BioinfoMetadata(
**args_merged
)