/
commands.py
1597 lines (1405 loc) · 52.7 KB
/
commands.py
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 python3
"""
Contains abstracted functions which is primarily used by the CLI. However, they can
be separately imported and used in other contexts.
There is a mix of functions which directly call `click.echo` vs returning responses to
the caller (e.g. CLI). We should move towards the latter pattern.
"""
import json
import locale
import os
import re
import sys
import time
import warnings
import zipfile
from collections import OrderedDict
from contextlib import contextmanager
from os.path import abspath, expanduser, isfile
import click
import requests
from click.exceptions import BadParameter
from jinja2 import Environment, PackageLoader
from transcriptic import routes
from transcriptic.auth import StrateosSign
from transcriptic.config import AnalysisException, Connection
from transcriptic.english import AutoprotocolParser
from transcriptic.util import ascii_encode, flatmap, iter_json, makedirs
def submit(
api: Connection,
file: str,
project: str,
title: str = None,
test: bool = None,
pm: str = None,
):
"""
Submit your run to the project specified.
If successful, returns the formatted url link to the created run.
Parameters
----------
api: Connection
API context used for making base calls
file: str
Name of file to read from. Use `-` if reading from standard input.
project: str
`ProjectId` to submit this json to.
title: str, optional
If specified, Title of the created run.
test: bool, optional
If true, submit as a test run.
pm: str, optional
If specified, `PaymentId` to be used.
"""
if pm is not None and not is_valid_payment_method(api, pm):
raise RuntimeError(
"Payment method is invalid. Please specify a payment "
"method from `transcriptic payments` or not specify the "
"`--payment` flag to use the default payment method."
)
valid_project_id = get_project_id(api, project)
if not valid_project_id:
raise RuntimeError(f"Invalid project {project} specified")
with click.open_file(file, "r") as f:
try:
protocol = json.loads(f.read())
except ValueError:
raise RuntimeError(
"Error: Could not submit since your manifest.json "
"file is improperly formatted."
)
try:
req_json = api.submit_run(
protocol,
project_id=valid_project_id,
title=title,
test_mode=test,
payment_method_id=pm,
)
run_id = req_json["id"]
formatted_url = api.url(f"{valid_project_id}/runs/{run_id}")
return formatted_url
except AnalysisException as e:
raise RuntimeError(e.message)
def release(api, name=None, package=None):
deflated = zipfile.ZIP_DEFLATED
if name:
filename = f"release_{name}"
else:
filename = "release"
if os.path.isfile(filename + ".zip"):
new = click.prompt(
f"You already have a release named {filename} in "
f"this directory, make another one? [y/n]",
default="y",
)
if new == "y":
num_existing = sum([1 for x in os.listdir(".") if filename in x])
filename = filename + "_" + str(num_existing)
else:
return
click.echo("Compressing all files in this directory...")
zf = zipfile.ZipFile(filename + ".zip", "w", deflated)
for (path, dirs, files) in os.walk("."):
for f in files:
if ".zip" not in f:
zf.write(os.path.join(path, f))
zf.close()
click.echo("Archive %s created." % (filename + ".zip"))
if package:
package_id = get_package_id(api, package) or get_package_name(api, package)
upload_release(api, filename + ".zip", package_id)
def upload_release(api, archive, package):
"""Upload a release archive to a package."""
try:
package_id = get_package_id(api, package.lower()) or get_package_name(
api, package.lower()
)
package_name = get_package_name(api, package_id.lower()) or get_package_id(
api, package_id.lower()
)
click.echo(f"Uploading {archive} to {package_name}")
except AttributeError:
click.echo("Error: Invalid package id or name.")
return
with click.progressbar(
None,
100,
"Upload Progress",
show_eta=False,
width=70,
fill_char="|",
empty_char="-",
) as bar:
bar.update(40)
file = open(os.path.basename(archive), "rb")
upload_id = api.upload_to_uri(
file, "application/zip, application/octet-stream", archive, archive
)
bar.update(20)
try:
up = api.post_release(
data=json.dumps({"release": {"upload_id": upload_id}}),
package_id=package_id,
)
re = up["id"]
except (ValueError, PermissionError) as err:
if type(err) == ValueError:
click.echo(
"\nError: There was a problem uploading your release."
"\nVerify that your manifest.json file is properly "
"formatted and that all previews in your manifest "
"produce valid Autoprotocol by using the "
"`transcriptic preview` and/or `transcriptic analyze` "
"commands."
)
elif type(err) == PermissionError:
click.echo("\n" + str(err))
return
bar.update(20)
time.sleep(10)
status = api.get_release_status(
package_id=package_id, release_id=re, timestamp=int(time.time())
)
errors = status["validation_errors"]
bar.update(30)
if errors:
click.echo(
"\nPackage upload to %s unsuccessful. "
"The following error(s) was returned: \n%s"
% (
get_package_name(api, package_id),
("\n").join(e.get("message", "[Unknown]") for e in errors),
)
)
else:
click.echo(
"\nPackage uploaded successfully! \n"
"Visit %s to publish." % api.url("packages/%s" % package_id)
)
def protocols(api, local, json_flag):
"""List protocols within your manifest or organization."""
if not local:
protocol_objs = api.get_protocols()
else:
manifest = load_manifest()
if "protocols" not in list(manifest.keys()) or not manifest["protocols"]:
click.echo(
"Your manifest.json file doesn't contain any protocols or"
" is improperly formatted."
)
return
protocol_objs = manifest["protocols"]
if json_flag:
click.echo(json.dumps(protocol_objs))
else:
click.echo(
"\n{:^60}".format(
"Protocols within this {}:".format(
"organization" if not local else "manifest"
)
)
)
click.echo(f"{'':-^60}")
for p in protocol_objs:
if p.get("display_name"):
display_str = f"{p['name']} ({p.get('display_name')})"
else:
display_str = p["name"]
click.echo(f"{display_str}\n{'':-^60}")
def packages(api, i):
"""List packages in your organization."""
response = api.packages()
# there's probably a better way to do this
package_names = OrderedDict(
sorted(list({"yours": {}, "theirs": {}}.items()), key=lambda t: len(t[0]))
)
for pack in response:
n = str(pack["name"]).lower().replace(f"com.{api.organization_id}.", "")
latest = str(pack["latest_version"]) if pack["latest_version"] else "-"
if pack.get("owner") and pack["owner"]["email"] == api.email:
package_names["yours"][n] = {}
package_names["yours"][n]["id"] = str(pack["id"])
package_names["yours"][n]["latest"] = latest
else:
package_names["theirs"][n] = {}
package_names["theirs"][n]["id"] = str(pack["id"])
package_names["theirs"][n]["latest"] = latest
if i:
return dict(
list(package_names["yours"].items()) + list(package_names["theirs"].items())
)
else:
for category, packages in list(package_names.items()):
if category == "yours":
click.echo("\n{:^90}".format("YOUR PACKAGES:\n"))
click.echo(
f"{'PACKAGE NAME':^30}"
+ "|"
+ f"{'PACKAGE ID':^30}"
+ "|"
+ f"{'LATEST PUBLISHED RELEASE':^30}"
)
click.echo(f"{'':-^90}")
elif category == "theirs" and list(packages.values()):
click.echo("\n{:^90}".format("OTHER PACKAGES IN YOUR ORG:\n"))
click.echo(
f"{'PACKAGE NAME':^30}"
+ "|"
+ f"{'PACKAGE ID':^30}"
+ "|"
+ f"{'LATEST PUBLISHED RELEASE':^30}"
)
click.echo(f"{'':-^90}")
for name, p in list(packages.items()):
click.echo(
f"{name:<30}" + "|" + f"{p['id']:^30}" + "|" + f"{p['latest']:^30}"
)
click.echo(f"{'':-^90}")
def create_package(api, description, name):
"""Create a new empty protocol package"""
existing = api.packages()
for p in existing:
if name == p["name"].split(".")[-1]:
click.echo(
f"You already have an existing package with the name "
f'"{name}". Please choose a different package name.'
)
return
try:
new_pack = api.create_package(name, description)
if new_pack:
click.echo(
"New package '%s' created with id %s \n"
"View it at %s"
% (name, new_pack["id"], api.url("packages/%s" % new_pack["id"]))
)
else:
click.echo("There was an error creating this package.")
except Exception as err:
click.echo("\n" + str(err))
def delete_package(api, name, force):
"""Delete an existing protocol package"""
package_id = get_package_id(api, name)
if package_id:
try:
if not force:
click.confirm(
"Are you sure you want to permanently delete the package "
"'%s'? All releases within will be lost."
% get_package_name(api, package_id),
default=False,
abort=True,
)
click.confirm("Are you really really sure?", default=True)
del_pack = api.delete_package(package_id=package_id)
if del_pack:
click.echo("Package deleted.")
else:
click.echo("There was a problem deleting this package.")
except Exception as err:
click.echo("\n" + str(err))
def generate_protocol(name):
"""Generate a python protocol scaffold"""
# TODO we should update click to be like rails
# transcriptic generate protocol FOO
# transcriptic generate other_type FOO
env = Environment(loader=PackageLoader("transcriptic", "templates"))
template_infos = [
{"template_name": "manifest.json.jinja", "file_name": "manifest.json"},
{"template_name": "protocol.py.jinja", "file_name": f"{name}.py"},
{"template_name": "requirements.txt.jinja", "file_name": "requirements.txt"},
]
# make directory for protocol
dirname = name
makedirs(dirname, exist_ok=True)
# write __init__ package file
open(f"{dirname}/{'__init__.py'}", "w").write("")
for template_info in template_infos:
template_name = template_info["template_name"]
file_name = template_info["file_name"]
template = env.get_template(template_name)
file = open(f"{dirname}/{file_name}", "w")
output = template.render(name=name)
file.write(output)
click.echo(f"Successfully generated protocol '{name}'!")
click.echo("Testing the protocol is as easy as:")
click.echo("")
click.echo(f"\tcd {name}")
click.echo("\tpip install -r requirements.txt")
click.echo(f"\ttranscriptic preview {name}")
click.echo(f"\ttranscriptic launch --local {name} -p SOME_PROJECT_ID")
def upload_dataset(api, file_path, title, run_id, tool, version):
"""Uploads specified file as an analysis dataset to the specified run."""
resp = api.upload_dataset_from_filepath(
file_path=file_path,
title=title,
run_id=run_id,
analysis_tool=tool,
analysis_tool_version=version,
)
try:
data_id = resp["data"]["id"]
run_route = api.url(f"/api/runs/{run_id}?fields[runs]=project_id")
run_resp = api.get(run_route)
project = run_resp["data"]["attributes"]["project_id"]
datasets_route = api.get_route("datasets", project_id=project, run_id=run_id)
data_url = f"{datasets_route}/analysis/{data_id}"
click.echo(f"Dataset uploaded to {data_url}")
except KeyError:
click.echo("An unexpected response was returned from the server. ")
def projects(
api: Connection,
i: any = None,
json_flag: bool = False,
names_only: bool = False,
):
"""
List the projects in your organization.
When no options are specified, returns a summarized format.
Parameters
----------
api: Connection
API context used for making base calls
i: any, optional
DEPRECATED option. See `names_only`.
json_flag: bool, optional
Returns the full response which is json formatted.
names_only: bool, optional
Returns a `project_id: project_name` mapping.
"""
if i:
warnings.warn(
"`i` will be deprecated in the future. Please use `names_only` instead.",
FutureWarning,
)
names_only = True
response = api.projects()
proj_id_names = {}
all_proj = {}
for proj in response:
status = " (archived)" if proj["archived_at"] else ""
proj_id_names[proj["id"]] = proj["name"]
all_proj[proj["id"]] = proj["name"] + status
if names_only:
return proj_id_names
elif json_flag:
return response
else:
return all_proj
def runs(api, project_name, json_flag):
"""List the runs that exist in a project"""
project_id = get_project_id(api, project_name)
run_list = []
if project_id:
req = api.runs(project_id=project_id)
if not req:
click.echo(f"Project '{project_name}' is empty.")
return
for r in req:
run_list.append(
[
r["title"] or "(Untitled)",
r["id"],
r["completed_at"].split("T")[0]
if r["completed_at"]
else r["created_at"].split("T")[0],
r["status"].replace("_", " "),
]
)
if json_flag:
extraction = map(
lambda x: {
"title": x["title"] or "(Untitled)",
"id": x["id"],
"completed_at": x["completed_at"] if x["completed_at"] else None,
"created_at": x["created_at"],
"status": x["status"],
},
req,
)
return click.echo(json.dumps(extraction))
else:
click.echo(
"\n{:^120}".format(
"Runs in Project '%s':\n" % get_project_name(api, project_id)
)
)
click.echo(
f"{'RUN TITLE':^30}"
+ "|"
+ f"{'RUN ID':^30}"
+ "|"
+ f"{'RUN DATE':^30}"
+ "|"
+ f"{'RUN STATUS':^30}"
)
click.echo(f"{'':-^120}")
for run in run_list:
click.echo(
f"{run[0]:^30}"
+ "|"
+ f"{run[1]:^30}"
+ "|"
+ f"{run[2]:^30}"
+ "|"
+ f"{run[3]:^30}"
)
click.echo(f"{'':-^120}")
def create_project(api, name, dev):
"""Create a new empty project."""
existing = api.projects()
for p in existing:
if name == p["name"].split(".")[-1]:
click.confirm(
f"You already have an existing project with the name '{name}'. "
f"Are you sure you want to create another one?",
default=False,
abort=True,
)
break
try:
new_proj = api.create_project(name)
click.echo(
"New%s project '%s' created with id %s \nView it at %s"
% (
" pilot" if dev else "",
name,
new_proj["id"],
api.url("%s" % (new_proj["id"])),
)
)
except RuntimeError:
click.echo("There was an error creating this project.")
def delete_project(api, name, force):
"""Delete an existing project."""
project_id = get_project_id(api, name)
if project_id:
if not force:
click.confirm(
"Are you sure you want to permanently delete '%s'?"
% get_project_name(api, project_id),
default=False,
abort=True,
)
if api.delete_project(project_id=str(project_id)):
click.echo("Project deleted.")
else:
click.confirm(
"Could not delete project. This may be because it contains \
runs. Try archiving it instead?",
default=False,
abort=True,
)
if api.archive_project(project_id=str(project_id)):
click.echo("Project archived.")
else:
click.echo("Could not archive project!")
def resources(api, query):
"""Search catalog of provisionable resources"""
resource_req = api.resources(query)
if resource_req["results"]:
kit_req = api.kits(query)
if not kit_req["results"]:
common_name = resource_req["results"][0]["name"]
kit_req = api.kits(common_name)
flat_items = list(
flatmap(
lambda x: [
{
"name": y["resource"]["name"],
"id": y["resource"]["id"],
"vendor": x["vendor"]["name"]
if "vendor" in list(x.keys())
else "",
}
for y in x["kit_items"]
if (y["provisionable"] and not y["reservable"])
],
kit_req["results"],
)
)
rs_id_list = [rs["id"] for rs in resource_req["results"]]
matched_resources = []
for item in flat_items:
if item["id"] in rs_id_list and item not in matched_resources:
matched_resources.append(item)
if matched_resources:
click.echo(f"Results for '{query}':")
click.echo(
f"{'Resource Name':^40}"
+ "|"
+ f"{'Vendor':^40}"
+ "|"
+ f"{'Resource ID':^40}"
)
click.echo(f"{'':-^120}")
for resource in matched_resources:
click.echo(
f"{ascii_encode(resource['name']):^40}"
+ "|"
+ f"{ascii_encode(resource['vendor']):^40}"
+ "|"
+ f"{ascii_encode(resource['id']):^40}"
)
click.echo(f"{'':-^120}")
else:
click.echo(f"No usable resource for '{query}'.")
else:
click.echo(f"No results for '{query}'.")
def inventory(api, include_aliquots, show_status, retrieve_all, query):
"""Search organization for inventory"""
inventory_req = api.inventory(query)
num_pages = inventory_req["num_pages"]
per_page = inventory_req["per_page"]
results = inventory_req["results"]
max_results_bound = num_pages * per_page
num_prefiltered = len(results)
if retrieve_all:
for i in range(1, num_pages):
click.echo(
f"Retrieved {i * per_page} records out of "
f"{max_results_bound} total for '{query}'...\r",
nl=False,
)
inventory_req = api.inventory(query, page=i)
results.extend(inventory_req["results"])
click.echo()
if include_aliquots:
results = [c if "label" in c else c["container"] for c in results]
else:
results = [c for c in results if "label" in c]
results = [i for n, i in enumerate(results) if i not in results[n + 1 :]]
if results:
def truncate_time(d, k):
old_time = d[k]
d[k] = old_time.split("T")[0]
return d
results = [truncate_time(c, "created_at") for c in results]
barcode_present = any(c["barcode"] for c in results)
keys = ["label", "id", "container_type_id", "storage_condition", "created_at"]
if barcode_present:
keys.insert(2, "barcode")
if show_status:
keys.append("status")
friendly_keys = {k: k.split("_")[0] for k in keys}
spacing = {
k: max(len(friendly_keys[k]), max([len(str(c[k])) for c in results]))
for k in keys
}
spacing = {k: (v // 2 + 1) * 2 + 1 for k, v in spacing.items()}
sum_spacing = sum(spacing.values()) + (len(keys) - 1) * 3 + 1
spacing = {k: "{:^%s}" % v for k, v in spacing.items()}
sum_spacing = "{:-^%s}" % sum_spacing
click.echo(f"Results for '{query}':")
click.echo(" | ".join([spacing[k].format(friendly_keys[k]) for k in keys]))
click.echo(sum_spacing.format(""))
for c in results:
click.echo(
" | ".join([spacing[k].format(ascii_encode(c[k])) for k in keys])
)
click.echo(sum_spacing.format(""))
if not retrieve_all:
if num_pages > 1:
click.echo(
f"Retrieved {num_prefiltered} records out of "
f"{max_results_bound} total (use the --retrieve_all "
f"flag to request all records)."
)
else:
if retrieve_all:
click.echo(f"No results for '{query}'.")
else:
if num_pages > 1:
click.echo(
f"Retrieved {num_prefiltered} records out of "
f"{max_results_bound} total but all were filtered "
f"out. Use the --retrieve_all flag to request all "
f"records."
)
else:
click.echo(
"All records were filtered out. Use flags to modify your search"
)
def payments(api):
"""Lists available payment methods"""
methods = api.payment_methods()
click.echo(f"{'Method':^50}" + "|" + f"{'Expiry':^20}" + "|" + f"{'Id':^20}")
click.echo(f"{'':-^90}")
if len(methods) == 0:
print_stderr("No payment methods found.")
return
for method in methods:
if method["type"] == "CreditCard":
description = (
f"{method['credit_card_type']} ending with "
f"{method['credit_card_last_4']}"
)
elif method["type"] == "PurchaseOrder":
description = f"Purchase Order \"{method['description']}\""
else:
description = method["description"]
if method["is_default?"]:
description += " (Default)"
if not method["is_valid"]:
description += " (Invalid)"
click.echo(
f"{ascii_encode(description):^50}"
+ "|"
+ f"{ascii_encode(method['expiry']):^20}"
+ "|"
+ f"{ascii_encode(method['id']):^20}"
)
def init(path):
"""Initialize a directory with a manifest.json file."""
manifest_data = OrderedDict(
format="python",
license="MIT",
protocols=[
{
"name": "SampleProtocol",
"version": "0.0.1",
"display_name": "Sample Protocol",
"description": "This is a protocol.",
"command_string": "python sample_protocol.py",
"inputs": {},
"preview": {"refs": {}, "parameters": {}},
}
],
)
try:
os.makedirs(path)
except OSError:
click.echo("Specified directory already exists.")
if isfile(f"{path}/manifest.json"):
click.confirm(
"This directory already contains a manifest.json file, "
"would you like to overwrite it with an empty one? ",
default=False,
abort=True,
)
with open(f"{path}/manifest.json", "w+") as f:
click.echo("Creating empty manifest.json...")
f.write(json.dumps(dict(manifest_data), indent=2))
click.echo("manifest.json created")
def analyze(api, file, test):
"""Analyze a block of Autoprotocol JSON."""
with click.open_file(file, "r") as f:
try:
protocol = json.loads(f.read())
except ValueError:
click.echo(
"Error: The Autoprotocol you're trying to analyze is "
"not properly formatted. \n"
"Check that your manifest.json file is "
"valid JSON and/or your script "
"doesn't print anything other than pure Autoprotocol "
"to standard out."
)
return
try:
analysis = api.analyze_run(protocol, test_mode=test)
click.echo("\u2713 Protocol analyzed")
format_analysis(analysis)
except Exception as err:
click.echo("\n" + str(err))
def preview(api, protocol_name, view, dye_test):
"""Preview the Autoprotocol output of protocol in the current package."""
manifest, protocol = load_manifest_and_protocol(protocol_name)
try:
inputs = protocol["preview"]
except KeyError:
click.echo(
"Error: The manifest.json you're trying to preview doesn't "
'contain a "preview" section'
)
return
run_protocol(api, manifest, protocol, inputs, view, dye_test)
def summarize(api, file, html, tree, lookup, runtime):
with click.open_file(file, "r") as f:
try:
protocol = json.loads(f.read())
except ValueError:
click.echo("The autoprotocol you're trying to summarize is invalid.")
return
if html:
url = ProtocolPreview(protocol, api).preview_url
click.echo(f"View your protocol here {url}")
return
parser = AutoprotocolParser(protocol, api=api)
if tree:
import multiprocessing
print("\nGenerating Job Tree...")
p = multiprocessing.Process(target=parser.job_tree)
p.start()
# Wait for <runtime_allowance> seconds or until process finishes
p.join(runtime)
# If thread is still active
if p.is_alive():
print("Still running... Aborting tree construction.")
print(
"Please allow for more runtime allowance, or opt for no tree construction.\n"
)
# Terminate
p.terminate()
p.join()
else:
print("\nYour Job Tree is complete!\n")
def compile(protocol_name, args):
"""Compile a protocol by passing it a config file (without submitting or
analyzing)."""
manifest, protocol = load_manifest_and_protocol(protocol_name)
try:
command = protocol["command_string"]
except KeyError:
click.echo(
'Error: Your manifest.json file does not have a "command_string" \
key.'
)
return
from subprocess import call
call(["bash", "-c", command + " " + " ".join(args)])
def launch(
api,
protocol,
project,
title,
save_input,
local,
accept_quote,
params,
pm=None,
test=None,
pkg=None,
):
"""Configure and launch a protocol either using the local manifest file or remotely.
If no parameters are specified, uses the webapp to select the inputs."""
# Validate payment method
if pm is not None and not is_valid_payment_method(api, pm):
print_stderr(
"Payment method is invalid. Please specify a payment "
"method from `transcriptic payments` or not specify the "
"`--payment` flag to use the default payment method."
)
return
# Load protocol from local file if not remote and load from listed protocols otherwise
if local:
manifest, protocol_obj = load_manifest_and_protocol(protocol)
else:
print_stderr(f"Searching for {protocol}...")
protocol_list = api.get_protocols()
matched_protocols = [
p
for p in protocol_list
if (p["name"] == protocol and (pkg is None or p["package_id"] == pkg))
]
if len(matched_protocols) == 0:
print_stderr(
f"Protocol {protocol} in "
f"{f'package {pkg}' if pkg else 'unspecified package'} "
f"was not found."
)
return
elif len(matched_protocols) > 1:
print_stderr("More than one match found. Using the first match.")
else:
print_stderr("Protocol found.")
protocol_obj = matched_protocols[0]
# If parameters are not specified, use quick launch to get inputs
if not params:
# Project is required for quick launch
if not project:
click.echo("Project field is required if parameters file is not specified.")
return
project = get_project_id(api, project)
if not project:
return
# Creates web browser and generates inputs for quick_launch
quick_launch = _get_quick_launch(api, protocol_obj, project)
# Save the protocol input locally if the user specified the save_input option
if save_input:
try:
with click.open_file(save_input, "w") as f:
f.write(
json.dumps(
dict(parameters=quick_launch["raw_inputs"]), indent=2
)
)
except Exception as e:
print_stderr("\nUnable to save inputs: %s" % str(e))
if not local:
# For remote execution, use input params file if specified, else use quick_launch inputs
if not params:
params = dict(parameters=quick_launch["raw_inputs"])
# Save parameters to file if specified
if save_input:
try:
with click.open_file(save_input, "w") as f:
f.write(json.dumps(params, indent=2))
except Exception as e:
print_stderr("\nUnable to save inputs: %s" % str(e))
else:
try:
params = json.loads(params.read())
except ValueError:
print_stderr(
"Unable to load parameters given. "
"File is probably incorrectly formatted."
)
return
req_id, launch_protocol = _get_launch_request(api, params, protocol_obj, test)
# Check for generation errors
generation_errs = launch_protocol["generation_errors"]
if len(generation_errs) > 0:
for errors in generation_errs:
click.echo("\n\n" + str(errors["message"]))
click.echo("\nPlease fix the above errors and try again.")
return
# Confirm proceeding with purchase
if not accept_quote:
click.echo("\n\nCost Breakdown")
resp = api.analyze_launch_request(req_id, test_mode=test)
click.echo(price(resp))
confirmed = click.confirm(
"Would you like to continue with launching the protocol",
prompt_suffix="? ",
default=False,
)
if not confirmed:
return
# Project is required for run submission
if not project:
click.echo("\nProject field is required for run submission.")
return
project = get_project_id(api, project)
if not project:
return
from time import gmtime, strftime
if title:
run_title = title
else:
run_title = f"{protocol}_{strftime('%b_%d_%Y', gmtime())}"
try:
req_json = api.submit_launch_request(
req_id,
protocol_id=protocol_obj["id"],
project_id=project,
title=run_title,
test_mode=test,
payment_method_id=pm,
)
run_id = req_json["id"]
click.echo("\nRun created: %s" % api.url("%s/runs/%s" % (project, run_id)))
except Exception as err:
click.echo("\n" + str(err))
else:
print_stderr("\nGenerating Autoprotocol....\n")
if not params:
run_protocol(api, manifest, protocol_obj, quick_launch["inputs"])
else:
"""