From 9c9512a7e040f8247d259bdc6f9cf55d5d276baf Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Wed, 15 Jul 2020 12:48:12 +0100 Subject: Load metadata locally without pkg_resources --- bh20simplewebuploader/main.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) (limited to 'bh20simplewebuploader/main.py') diff --git a/bh20simplewebuploader/main.py b/bh20simplewebuploader/main.py index 77e345b..8b5781a 100644 --- a/bh20simplewebuploader/main.py +++ b/bh20simplewebuploader/main.py @@ -227,8 +227,13 @@ def generate_form(schema, options): # At startup, we need to load the metadata schema from the uploader module, so we can make a form for it -METADATA_SCHEMA = yaml.safe_load(pkg_resources.resource_stream("bh20sequploader", "bh20seq-schema.yml")) -METADATA_OPTION_DEFINITIONS = yaml.safe_load(pkg_resources.resource_stream("bh20sequploader", "bh20seq-options.yml")) +if os.path.isfile("bh20sequploader/bh20seq-schema.yml"): + METADATA_SCHEMA = yaml.safe_load(open("bh20sequploader/bh20seq-schema.yml","r").read()) + METADATA_OPTION_DEFINITIONS = yaml.safe_load(open("bh20sequploader/bh20seq-options.yml","r").read()) +else: + METADATA_SCHEMA = yaml.safe_load(pkg_resources.resource_stream("bh20sequploader", "bh20seq-schema.yml")) + METADATA_OPTION_DEFINITIONS = yaml.safe_load(pkg_resources.resource_stream("bh20sequploader", "bh20seq-options.yml")) +print(METADATA_SCHEMA,file=sys.stderr) FORM_ITEMS = generate_form(METADATA_SCHEMA, METADATA_OPTION_DEFINITIONS) @app.route('/') -- cgit v1.2.3 From b9691c7deae30bd6422fb7b0681572b7b6f78ae3 Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Wed, 15 Jul 2020 14:16:11 +0100 Subject: Web: add license to input form --- bh20sequploader/bh20seq-schema.yml | 3 ++- bh20simplewebuploader/main.py | 3 ++- example/minimal_metadata_example.yaml | 6 +++++- 3 files changed, 9 insertions(+), 3 deletions(-) (limited to 'bh20simplewebuploader/main.py') diff --git a/bh20sequploader/bh20seq-schema.yml b/bh20sequploader/bh20seq-schema.yml index b3d4d12..29ac22c 100644 --- a/bh20sequploader/bh20seq-schema.yml +++ b/bh20sequploader/bh20seq-schema.yml @@ -15,7 +15,7 @@ $graph: fields: license_type: doc: License types as defined in https://wiki.creativecommons.org/images/d/d6/Ccrel-1.0.pdf - type: string? + type: string jsonldPredicate: _id: https://creativecommons.org/ns#License title: @@ -258,6 +258,7 @@ $graph: virus: virusSchema technology: technologySchema submitter: submitterSchema + license: licenseSchema id: doc: The subject (eg the fasta/fastq file) that the metadata describes type: string diff --git a/bh20simplewebuploader/main.py b/bh20simplewebuploader/main.py index 8b5781a..8a6794e 100644 --- a/bh20simplewebuploader/main.py +++ b/bh20simplewebuploader/main.py @@ -47,6 +47,7 @@ def type_to_heading(type_name): Turn a type name like "sampleSchema" from the metadata schema into a human-readable heading. """ + print(type_name,file=sys.stderr) # Remove camel case decamel = re.sub('([A-Z])', r' \1', type_name) # Split @@ -233,7 +234,7 @@ if os.path.isfile("bh20sequploader/bh20seq-schema.yml"): else: METADATA_SCHEMA = yaml.safe_load(pkg_resources.resource_stream("bh20sequploader", "bh20seq-schema.yml")) METADATA_OPTION_DEFINITIONS = yaml.safe_load(pkg_resources.resource_stream("bh20sequploader", "bh20seq-options.yml")) -print(METADATA_SCHEMA,file=sys.stderr) +# print(METADATA_SCHEMA,file=sys.stderr) FORM_ITEMS = generate_form(METADATA_SCHEMA, METADATA_OPTION_DEFINITIONS) @app.route('/') diff --git a/example/minimal_metadata_example.yaml b/example/minimal_metadata_example.yaml index 51f8a87..1b46cc7 100644 --- a/example/minimal_metadata_example.yaml +++ b/example/minimal_metadata_example.yaml @@ -1,5 +1,9 @@ id: placeholder + +license: + license_type: http://creativecommons.org/licenses/by/4.0/ + host: host_species: http://purl.obolibrary.org/obo/NCBITaxon_9606 @@ -15,4 +19,4 @@ technology: sample_sequencing_technology: [http://www.ebi.ac.uk/efo/EFO_0008632] submitter: - authors: [John Doe] \ No newline at end of file + authors: [John Doe] -- cgit v1.2.3 From f0dd283c31acfcc34b967b7a81167e0543d06364 Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Thu, 16 Jul 2020 10:53:19 +0100 Subject: Add edit icon to text on github Closes #76 --- bh20simplewebuploader/main.py | 13 +++++++++---- bh20simplewebuploader/static/image/edit.png | Bin 0 -> 2452 bytes bh20simplewebuploader/static/main.css | 14 ++++++++++++++ bh20simplewebuploader/templates/blog.html | 4 +--- 4 files changed, 24 insertions(+), 7 deletions(-) create mode 100644 bh20simplewebuploader/static/image/edit.png (limited to 'bh20simplewebuploader/main.py') diff --git a/bh20simplewebuploader/main.py b/bh20simplewebuploader/main.py index 8a6794e..0f521d0 100644 --- a/bh20simplewebuploader/main.py +++ b/bh20simplewebuploader/main.py @@ -444,8 +444,12 @@ def receive_files(): finally: shutil.rmtree(dest_dir) -def get_html_body(fn): - buf = "" + +def edit_button(url,text="Edit text!"): + return '

'+text+'!

' + +def get_html_body(fn,source="https://github.com/arvados/bh20-seq-resource/tree/master/doc"): + buf = edit_button(source) in_body = False begin_body = re.compile(r"",re.IGNORECASE) end_body = re.compile(r"(|.*=\"postamble\")",re.IGNORECASE) @@ -457,6 +461,7 @@ def get_html_body(fn): buf += line elif begin_body.match(line): in_body = True + buf += edit_button(source) return buf @app.route('/download') @@ -549,13 +554,13 @@ def blog_page(): blog_content = request.args.get('id') # e.g. using-covid-19-pubseq-part3 buf = None; if blog_content: - buf = get_html_body('doc/blog/'+blog_content+'.html') + buf = get_html_body('doc/blog/'+blog_content+'.html',"https://github.com/arvados/bh20-seq-resource/blob/master/doc/blog/"+blog_content+".org") return render_template('blog.html',menu='BLOG',embed=buf,blog=blog_content) @app.route('/about') def about_page(): - buf = get_html_body('doc/web/about.html') + buf = get_html_body('doc/web/about.html','https://github.com/arvados/bh20-seq-resource/blob/master/doc/web/about.org') return render_template('about.html',menu='ABOUT',embed=buf) ## diff --git a/bh20simplewebuploader/static/image/edit.png b/bh20simplewebuploader/static/image/edit.png new file mode 100644 index 0000000..571b08c Binary files /dev/null and b/bh20simplewebuploader/static/image/edit.png differ diff --git a/bh20simplewebuploader/static/main.css b/bh20simplewebuploader/static/main.css index b9b27f4..47fb408 100644 --- a/bh20simplewebuploader/static/main.css +++ b/bh20simplewebuploader/static/main.css @@ -377,3 +377,17 @@ div.status { vertical-align: top; border-bottom: 1px solid #ddd; } + +.editbutton { + float: right; + text-align: right; + background-color: lightgrey; + border: 2px solid #4CAF50; + border-radius: 12px; + color: black; + padding: 5px 32px; + // text-decoration: none; + display: inline-block; + font-size: 16px; + box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19); +} diff --git a/bh20simplewebuploader/templates/blog.html b/bh20simplewebuploader/templates/blog.html index dbc0b99..823f8a1 100644 --- a/bh20simplewebuploader/templates/blog.html +++ b/bh20simplewebuploader/templates/blog.html @@ -9,9 +9,7 @@ {{ embed|safe }}
-

- Other blog entries: -

+

Other blog entries

{% else %} {% include 'blurb.html' %} -- cgit v1.2.3 From 8d995b271f20d15b2b6a7845ade22c396a383da3 Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Thu, 16 Jul 2020 11:01:08 +0100 Subject: Add edit link for download page --- bh20simplewebuploader/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'bh20simplewebuploader/main.py') diff --git a/bh20simplewebuploader/main.py b/bh20simplewebuploader/main.py index 0f521d0..8089883 100644 --- a/bh20simplewebuploader/main.py +++ b/bh20simplewebuploader/main.py @@ -466,7 +466,7 @@ def get_html_body(fn,source="https://github.com/arvados/bh20-seq-resource/tree/m @app.route('/download') def download_page(): - buf = get_html_body('doc/web/download.html') + buf = get_html_body('doc/web/download.html','https://github.com/arvados/bh20-seq-resource/blob/master/doc/web/download.org') return render_template('resource.html',menu='DOWNLOAD',embed=buf) def pending_table(output, items): -- cgit v1.2.3 From 53ff8af0843942d83dff9fd5b95d1ae98e80fe27 Mon Sep 17 00:00:00 2001 From: Peter Amstutz Date: Thu, 16 Jul 2020 11:48:35 -0400 Subject: Refactor analysis code into a class Arvados-DCO-1.1-Signed-off-by: Peter Amstutz --- bh20seqanalyzer/main.py | 597 ++++++++++++++++++++++-------------------- bh20simplewebuploader/main.py | 28 +- 2 files changed, 326 insertions(+), 299 deletions(-) (limited to 'bh20simplewebuploader/main.py') diff --git a/bh20seqanalyzer/main.py b/bh20seqanalyzer/main.py index 0b52e6b..f2bb234 100644 --- a/bh20seqanalyzer/main.py +++ b/bh20seqanalyzer/main.py @@ -16,277 +16,306 @@ logging.basicConfig(format="[%(asctime)s] %(levelname)s %(message)s", datefmt="% level=logging.INFO) logging.getLogger("googleapiclient.discovery").setLevel(logging.WARN) -def validate_upload(api, collection, validated_project, - fastq_project, fastq_workflow_uuid, - revalidate): - col = arvados.collection.Collection(collection["uuid"]) - - if not revalidate and collection["properties"].get("status") in ("validated", "rejected"): - return False - - # validate the collection here. Check metadata, etc. - logging.info("Validating upload '%s' (%s)" % (collection["name"], collection["uuid"])) - - errors = [] - - if collection["owner_uuid"] != validated_project: - dup = api.collections().list(filters=[["owner_uuid", "=", validated_project], - ["portable_data_hash", "=", col.portable_data_hash()]]).execute() - if dup["items"]: - # This exact collection has been uploaded before. - errors.append("Duplicate of %s" % ([d["uuid"] for d in dup["items"]])) - - if not errors: - if "metadata.yaml" not in col: - errors.append("Missing metadata.yaml", collection["name"]) - else: +class SeqAnalyzer: + + def __init__(self, api, keepclient, + uploader_project, + pangenome_analysis_project, + fastq_project, + validated_project, + workflow_def_project, + pangenome_workflow_uuid, + fastq_workflow_uuid, + exclude_list, + latest_result_collection): + self.api = api + self.keepclient = keepclient + self.uploader_project = uploader_project + self.pangenome_analysis_project = pangenome_analysis_project + self.fastq_project = fastq_project + self.validated_project = validated_project + self.workflow_def_project = workflow_def_project + self.pangenome_workflow_uuid = pangenome_workflow_uuid + self.fastq_workflow_uuid = fastq_workflow_uuid + self.exclude_list = exclude_list + self.latest_result_uuid = latest_result_collection + self.schema_ref = None + + def validate_upload(self, collection, revalidate): + col = arvados.collection.Collection(collection["uuid"], api_client=self.api, keep_client=self.keepclient) + + if not revalidate and collection["properties"].get("status") in ("validated", "rejected"): + return False + + # validate the collection here. Check metadata, etc. + logging.info("Validating upload '%s' (%s)" % (collection["name"], collection["uuid"])) + + errors = [] + + if collection["owner_uuid"] != self.validated_project: + dup = self.api.collections().list(filters=[["owner_uuid", "=", self.validated_project], + ["portable_data_hash", "=", col.portable_data_hash()]]).execute() + if dup["items"]: + # This exact collection has been uploaded before. + errors.append("Duplicate of %s" % ([d["uuid"] for d in dup["items"]])) + + if not errors: + if "metadata.yaml" not in col: + errors.append("Missing metadata.yaml", collection["name"]) + else: + try: + with col.open("metadata.yaml") as md: + metadata_content = ruamel.yaml.round_trip_load(md) + metadata_content["id"] = "http://arvados.org/keep:%s/metadata.yaml" % collection["portable_data_hash"] + sample_id = metadata_content["sample"]["sample_id"] + add_lc_filename(metadata_content, metadata_content["id"]) + valid = qc_metadata(metadata_content) + if not valid: + errors.append("Failed metadata qc") + except Exception as e: + errors.append(str(e)) + + if not errors: try: - metadata_content = ruamel.yaml.round_trip_load(col.open("metadata.yaml")) - metadata_content["id"] = "http://arvados.org/keep:%s/metadata.yaml" % collection["portable_data_hash"] - sample_id = metadata_content["sample"]["sample_id"] - add_lc_filename(metadata_content, metadata_content["id"]) - valid = qc_metadata(metadata_content) - if not valid: - errors.append("Failed metadata qc") - except Exception as e: - errors.append(str(e)) - - if not errors: - try: - tgt = None - paired = {"reads_1.fastq": "reads.fastq", "reads_1.fastq.gz": "reads.fastq.gz"} - for n in ("sequence.fasta", "reads.fastq", "reads.fastq.gz", "reads_1.fastq", "reads_1.fastq.gz"): - if n not in col: - continue - with col.open(n, 'rb') as qf: - tgt = qc_fasta(qf)[0] - if tgt != n and tgt != paired.get(n): - errors.append("Expected %s but magic says it should be %s", n, tgt) - elif tgt in ("reads.fastq", "reads.fastq.gz", "reads_1.fastq", "reads_1.fastq.gz"): - start_fastq_to_fasta(api, collection, fastq_project, fastq_workflow_uuid, n, sample_id) - return False - if tgt is None: - errors.append("Upload '%s' does not contain sequence.fasta, reads.fastq or reads_1.fastq", collection["name"]) - except Exception as v: - errors.append(str(v)) - - - if not errors: - # Move it to the "validated" project to be included in the next analysis - if "errors" in collection["properties"]: - del collection["properties"]["errors"] - collection["properties"]["status"] = "validated" - api.collections().update(uuid=collection["uuid"], body={ - "owner_uuid": validated_project, - "name": "%s (%s)" % (collection["name"], time.asctime(time.gmtime())), - "properties": collection["properties"]}).execute() - logging.info("Added '%s' to validated sequences" % collection["name"]) - return True - else: - # It is invalid - logging.warn("'%s' (%s) has validation errors: %s" % ( - collection["name"], collection["uuid"], "\n".join(errors))) - collection["properties"]["status"] = "rejected" - collection["properties"]["errors"] = errors - api.collections().update(uuid=collection["uuid"], body={"properties": collection["properties"]}).execute() - return False - - -def run_workflow(api, parent_project, workflow_uuid, name, inputobj): - project = api.groups().create(body={ - "group_class": "project", - "name": name, - "owner_uuid": parent_project, - }, ensure_unique_name=True).execute() - - with tempfile.NamedTemporaryFile() as tmp: - tmp.write(json.dumps(inputobj, indent=2).encode('utf-8')) - tmp.flush() - cmd = ["arvados-cwl-runner", - "--submit", - "--no-wait", - "--project-uuid=%s" % project["uuid"], - "arvwf:%s" % workflow_uuid, - tmp.name] - logging.info("Running %s" % ' '.join(cmd)) - comp = subprocess.run(cmd, capture_output=True) - logging.info("Submitted %s", comp.stdout) - if comp.returncode != 0: - logging.error(comp.stderr.decode('utf-8')) - - return project - - -def start_fastq_to_fasta(api, collection, - analysis_project, - fastq_workflow_uuid, - tgt, - sample_id): - - params = { - "metadata": { - "class": "File", - "location": "keep:%s/metadata.yaml" % collection["portable_data_hash"] - }, - "ref_fasta": { - "class": "File", - "location": "keep:ffef6a3b77e5e04f8f62a7b6f67264d1+556/SARS-CoV2-NC_045512.2.fasta" - }, - "sample_id": sample_id - } - - if tgt.startswith("reads.fastq"): - params["fastq_forward"] = { - "class": "File", - "location": "keep:%s/%s" % (collection["portable_data_hash"], tgt) - } - elif tgt.startswith("reads_1.fastq"): - params["fastq_forward"] = { - "class": "File", - "location": "keep:%s/reads_1.%s" % (collection["portable_data_hash"], tgt[8:]) - } - params["fastq_reverse"] = { - "class": "File", - "location": "keep:%s/reads_2.%s" % (collection["portable_data_hash"], tgt[8:]) + tgt = None + paired = {"reads_1.fastq": "reads.fastq", "reads_1.fastq.gz": "reads.fastq.gz"} + for n in ("sequence.fasta", "reads.fastq", "reads.fastq.gz", "reads_1.fastq", "reads_1.fastq.gz"): + if n not in col: + continue + with col.open(n, 'rb') as qf: + tgt = qc_fasta(qf)[0] + if tgt != n and tgt != paired.get(n): + errors.append("Expected %s but magic says it should be %s", n, tgt) + elif tgt in ("reads.fastq", "reads.fastq.gz", "reads_1.fastq", "reads_1.fastq.gz"): + self.start_fastq_to_fasta(collection, n, sample_id) + return False + if tgt is None: + errors.append("Upload '%s' does not contain sequence.fasta, reads.fastq or reads_1.fastq", collection["name"]) + except Exception as v: + errors.append(str(v)) + + + if not errors: + # Move it to the "validated" project to be included in the next analysis + if "errors" in collection["properties"]: + del collection["properties"]["errors"] + collection["properties"]["status"] = "validated" + self.api.collections().update(uuid=collection["uuid"], body={ + "owner_uuid": self.validated_project, + "name": "%s (%s)" % (collection["name"], time.asctime(time.gmtime())), + "properties": collection["properties"]}).execute() + logging.info("Added '%s' to validated sequences" % collection["name"]) + return True + else: + # It is invalid + logging.warn("'%s' (%s) has validation errors: %s" % ( + collection["name"], collection["uuid"], "\n".join(errors))) + collection["properties"]["status"] = "rejected" + collection["properties"]["errors"] = errors + self.api.collections().update(uuid=collection["uuid"], body={"properties": collection["properties"]}).execute() + return False + + + def run_workflow(self, parent_project, workflow_uuid, name, inputobj): + project = self.api.groups().create(body={ + "group_class": "project", + "name": name, + "owner_uuid": parent_project, + }, ensure_unique_name=True).execute() + + with tempfile.NamedTemporaryFile() as tmp: + tmp.write(json.dumps(inputobj, indent=2).encode('utf-8')) + tmp.flush() + cmd = ["arvados-cwl-runner", + "--submit", + "--no-wait", + "--project-uuid=%s" % project["uuid"], + "arvwf:%s" % workflow_uuid, + tmp.name] + logging.info("Running %s" % ' '.join(cmd)) + comp = subprocess.run(cmd, capture_output=True) + logging.info("Submitted %s", comp.stdout) + if comp.returncode != 0: + logging.error(comp.stderr.decode('utf-8')) + + return project + + + def start_fastq_to_fasta(self, collection, + tgt, + sample_id): + + params = { + "metadata": { + "class": "File", + "location": "keep:%s/metadata.yaml" % collection["portable_data_hash"] + }, + "ref_fasta": { + "class": "File", + "location": "keep:ffef6a3b77e5e04f8f62a7b6f67264d1+556/SARS-CoV2-NC_045512.2.fasta" + }, + "sample_id": sample_id } - newproject = run_workflow(api, analysis_project, fastq_workflow_uuid, "FASTQ to FASTA", params) - api.collections().update(uuid=collection["uuid"], - body={"owner_uuid": newproject["uuid"]}).execute() - -def start_pangenome_analysis(api, - analysis_project, - pangenome_workflow_uuid, - validated_project, - schema_ref, - exclude_list): - validated = arvados.util.list_all(api.collections().list, filters=[ - ["owner_uuid", "=", validated_project], - ["properties.status", "=", "validated"]]) - inputobj = { - "inputReads": [], - "metadata": [], - "subjects": [], - "metadataSchema": { - "class": "File", - "location": schema_ref - }, - "exclude": { - "class": "File", - "location": exclude_list + if tgt.startswith("reads.fastq"): + params["fastq_forward"] = { + "class": "File", + "location": "keep:%s/%s" % (collection["portable_data_hash"], tgt) + } + elif tgt.startswith("reads_1.fastq"): + params["fastq_forward"] = { + "class": "File", + "location": "keep:%s/reads_1.%s" % (collection["portable_data_hash"], tgt[8:]) + } + params["fastq_reverse"] = { + "class": "File", + "location": "keep:%s/reads_2.%s" % (collection["portable_data_hash"], tgt[8:]) + } + + newproject = self.run_workflow(self.fastq_project, self.fastq_workflow_uuid, "FASTQ to FASTA", params) + self.api.collections().update(uuid=collection["uuid"], + body={"owner_uuid": newproject["uuid"]}).execute() + + def start_pangenome_analysis(self): + + if self.schema_ref is None: + self.upload_schema() + + validated = arvados.util.list_all(self.api.collections().list, filters=[ + ["owner_uuid", "=", self.validated_project], + ["properties.status", "=", "validated"]]) + inputobj = { + "inputReads": [], + "metadata": [], + "subjects": [], + "metadataSchema": { + "class": "File", + "location": self.schema_ref + }, + "exclude": { + "class": "File", + "location": self.exclude_list + } } - } - validated.sort(key=lambda v: v["portable_data_hash"]) - for v in validated: - inputobj["inputReads"].append({ - "class": "File", - "location": "keep:%s/sequence.fasta" % v["portable_data_hash"] - }) - inputobj["metadata"].append({ - "class": "File", - "location": "keep:%s/metadata.yaml" % v["portable_data_hash"] - }) - inputobj["subjects"].append("http://collections.lugli.arvadosapi.com/c=%s/sequence.fasta" % v["portable_data_hash"]) - run_workflow(api, analysis_project, pangenome_workflow_uuid, "Pangenome analysis", inputobj) - - -def get_workflow_output_from_project(api, uuid): - cr = api.container_requests().list(filters=[['owner_uuid', '=', uuid], - ["requesting_container_uuid", "=", None]]).execute() - if cr["items"] and cr["items"][0]["output_uuid"]: - container = api.containers().get(uuid=cr["items"][0]["container_uuid"]).execute() - if container["state"] == "Complete" and container["exit_code"] == 0: - return cr["items"][0] - return None - - -def copy_most_recent_result(api, analysis_project, latest_result_uuid): - most_recent_analysis = api.groups().list(filters=[['owner_uuid', '=', analysis_project]], - order="created_at desc").execute() - for m in most_recent_analysis["items"]: - wf = get_workflow_output_from_project(api, m["uuid"]) - if wf: - src = api.collections().get(uuid=wf["output_uuid"]).execute() - dst = api.collections().get(uuid=latest_result_uuid).execute() - if src["portable_data_hash"] != dst["portable_data_hash"]: - logging.info("Copying latest result from '%s' to %s", m["name"], latest_result_uuid) - api.collections().update(uuid=latest_result_uuid, - body={"manifest_text": src["manifest_text"], - "description": "Result from %s %s" % (m["name"], wf["uuid"])}).execute() - break - + validated.sort(key=lambda v: v["portable_data_hash"]) + for v in validated: + inputobj["inputReads"].append({ + "class": "File", + "location": "keep:%s/sequence.fasta" % v["portable_data_hash"] + }) + inputobj["metadata"].append({ + "class": "File", + "location": "keep:%s/metadata.yaml" % v["portable_data_hash"] + }) + inputobj["subjects"].append("http://collections.lugli.arvadosapi.com/c=%s/sequence.fasta" % v["portable_data_hash"]) + self.run_workflow(self.pangenome_analysis_project, self.pangenome_workflow_uuid, "Pangenome analysis", inputobj) + + + def get_workflow_output_from_project(self, uuid): + cr = self.api.container_requests().list(filters=[['owner_uuid', '=', uuid], + ["requesting_container_uuid", "=", None]]).execute() + if cr["items"] and cr["items"][0]["output_uuid"]: + container = self.api.containers().get(uuid=cr["items"][0]["container_uuid"]).execute() + if container["state"] == "Complete" and container["exit_code"] == 0: + return cr["items"][0] + return None + + + def copy_most_recent_result(self): + most_recent_analysis = self.api.groups().list(filters=[['owner_uuid', '=', self.pangenome_analysis_project]], + order="created_at desc").execute() + for m in most_recent_analysis["items"]: + wf = self.get_workflow_output_from_project(m["uuid"]) + if wf: + src = self.api.collections().get(uuid=wf["output_uuid"]).execute() + dst = self.api.collections().get(uuid=self.latest_result_uuid).execute() + if src["portable_data_hash"] != dst["portable_data_hash"]: + logging.info("Copying latest result from '%s' to %s", m["name"], self.latest_result_uuid) + self.api.collections().update(uuid=self.latest_result_uuid, + body={"manifest_text": src["manifest_text"], + "description": "Result from %s %s" % (m["name"], wf["uuid"])}).execute() + break + + + def move_fastq_to_fasta_results(self): + projects = self.api.groups().list(filters=[['owner_uuid', '=', self.fastq_project], + ["properties.moved_output", "!=", True]], + order="created_at desc",).execute() + for p in projects["items"]: + wf = self.get_workflow_output_from_project(p["uuid"]) + if not wf: + continue -def move_fastq_to_fasta_results(api, analysis_project, uploader_project): - projects = api.groups().list(filters=[['owner_uuid', '=', analysis_project], - ["properties.moved_output", "!=", True]], - order="created_at desc",).execute() - for p in projects["items"]: - wf = get_workflow_output_from_project(api, p["uuid"]) - if wf: logging.info("Moving completed fastq2fasta result %s back to uploader project", wf["output_uuid"]) - api.collections().update(uuid=wf["output_uuid"], - body={"owner_uuid": uploader_project}).execute() + self.api.collections().update(uuid=wf["output_uuid"], + body={"owner_uuid": self.uploader_project}).execute() + + col = arvados.collection.Collection(wf["output_uuid"], api_client=self.api, keep_client=self.keepclient) + with col.open("metadata.yaml") as md: + metadata_content = ruamel.yaml.round_trip_load(md) + p["properties"]["moved_output"] = True - api.groups().update(uuid=p["uuid"], body={"properties": p["properties"]}).execute() + p["properties"]["sequence_label"] = metadata_content["sample"]["sample_id"] + self.api.groups().update(uuid=p["uuid"], body={"properties": p["properties"]}).execute() break -def upload_schema(api, workflow_def_project): - schema_resource = pkg_resources.resource_stream('bh20sequploader.qc_metadata', "bh20seq-schema.yml") - c = arvados.collection.Collection() - with c.open("schema.yml", "wb") as f: - f.write(schema_resource.read()) - pdh = c.portable_data_hash() - wd = api.collections().list(filters=[["owner_uuid", "=", workflow_def_project], - ["portable_data_hash", "=", pdh]]).execute() - if len(wd["items"]) == 0: - c.save_new(owner_uuid=workflow_def_project, name="Metadata schema", ensure_unique_name=True) - return "keep:%s/schema.yml" % pdh - - -def print_status(api, uploader_project, fmt): - pending = arvados.util.list_all(api.collections().list, filters=[["owner_uuid", "=", uploader_project]]) - out = [] - status = {} - for p in pending: - prop = p["properties"] - out.append(prop) - if "status" not in prop: - prop["status"] = "pending" - prop["created_at"] = p["created_at"] - prop["uuid"] = p["uuid"] - status[prop["status"]] = status.get(prop["status"], 0) + 1 - if fmt == "html": - print( -""" - - -""") - print("

Total collections in upload project %s

" % len(out)) - print("

Status %s

" % status) - print( -""" - - - - - -""") - for r in out: - print("") - print("" % (r["uuid"], r["uuid"])) - print("" % r["sequence_label"]) - print("" % r["status"]) - print("" % "\n".join(r.get("errors", []))) - print("") - print( -""" -
CollectionSequence labelStatusErrors
%s%s%s
%s
- - -""") - else: - print(json.dumps(out, indent=2)) + def upload_schema(self): + schema_resource = pkg_resources.resource_stream('bh20sequploader.qc_metadata', "bh20seq-schema.yml") + c = arvados.collection.Collection(api_client=self.api, keep_client=self.keepclient) + with c.open("schema.yml", "wb") as f: + f.write(schema_resource.read()) + pdh = c.portable_data_hash() + wd = self.api.collections().list(filters=[["owner_uuid", "=", self.workflow_def_project], + ["portable_data_hash", "=", pdh]]).execute() + if len(wd["items"]) == 0: + c.save_new(owner_uuid=self.workflow_def_project, name="Metadata schema", ensure_unique_name=True) + self.schema_ref = "keep:%s/schema.yml" % pdh + + + def print_status(self, fmt): + pending = arvados.util.list_all(self.api.collections().list, filters=[["owner_uuid", "=", self.uploader_project]]) + out = [] + status = {} + for p in pending: + prop = p["properties"] + out.append(prop) + if "status" not in prop: + prop["status"] = "pending" + prop["created_at"] = p["created_at"] + prop["uuid"] = p["uuid"] + status[prop["status"]] = status.get(prop["status"], 0) + 1 + if fmt == "html": + print( + """ + + + """) + print("

Total collections in upload project %s

" % len(out)) + print("

Status %s

" % status) + print( + """ + + + + + + """) + for r in out: + print("") + print("" % (r["uuid"], r["uuid"])) + print("" % r["sequence_label"]) + print("" % r["status"]) + print("" % "\n".join(r.get("errors", []))) + print("") + print( + """ +
CollectionSequence labelStatusErrors
%s%s%s
%s
+ + + """) + else: + print(json.dumps(out, indent=2)) def main(): parser = argparse.ArgumentParser(description='Analyze collections uploaded to a project') @@ -310,50 +339,42 @@ def main(): args = parser.parse_args() api = arvados.api() - - - - schema_ref = upload_schema(api, args.workflow_def_project) + keepclient = arvados.keep.KeepClient(api_client=api) + + seqanalyzer = SeqAnalyzer(api, keepclient, + args.uploader_project, + args.pangenome_analysis_project, + args.fastq_project, + args.validated_project, + args.workflow_def_project, + args.pangenome_workflow_uuid, + args.fastq_workflow_uuid, + args.exclude_list, + args.latest_result_collection) if args.kickoff: logging.info("Starting a single analysis run") - start_pangenome_analysis(api, - args.pangenome_analysis_project, - args.pangenome_workflow_uuid, - args.validated_project, - schema_ref, - args.exclude_list) + seqanalyzer.start_pangenome_analysis() return if args.print_status: - print_status(api, args.uploader_project, args.print_status) + seqanalyzer.print_status(args.print_status) exit(0) logging.info("Starting up, monitoring %s for uploads" % (args.uploader_project)) while True: - move_fastq_to_fasta_results(api, args.fastq_project, args.uploader_project) + seqanalyzer.move_fastq_to_fasta_results() new_collections = arvados.util.list_all(api.collections().list, filters=[["owner_uuid", "=", args.uploader_project]]) at_least_one_new_valid_seq = False for c in new_collections: - at_least_one_new_valid_seq = validate_upload(api, c, - args.validated_project, - args.fastq_project, - args.fastq_workflow_uuid, - args.revalidate) or at_least_one_new_valid_seq + at_least_one_new_valid_seq = seqanalyzer.validate_upload(c, args.revalidate) or at_least_one_new_valid_seq if at_least_one_new_valid_seq and not args.no_start_analysis: - start_pangenome_analysis(api, - args.pangenome_analysis_project, - args.pangenome_workflow_uuid, - args.validated_project, - schema_ref, - args.exclude_list) - - copy_most_recent_result(api, - args.pangenome_analysis_project, - args.latest_result_collection) + seqanalyzer.start_pangenome_analysis() + + seqanalyzer.copy_most_recent_result() if args.once: break diff --git a/bh20simplewebuploader/main.py b/bh20simplewebuploader/main.py index 8089883..3173d60 100644 --- a/bh20simplewebuploader/main.py +++ b/bh20simplewebuploader/main.py @@ -479,10 +479,13 @@ def pending_table(output, items): for r in items: if r["status"] != "pending": continue - output.write("") - output.write("%s" % (r["uuid"], r["uuid"])) - output.write("%s" % Markup.escape(r["sequence_label"])) - output.write("") + try: + output.write("") + output.write("%s" % (r["uuid"], r["uuid"])) + output.write("%s" % Markup.escape(r.get("sequence_label"))) + output.write("") + except: + pass output.write( """ @@ -497,13 +500,16 @@ def rejected_table(output, items): Errors """) for r in items: - if r["status"] != "rejected": - continue - output.write("") - output.write("%s" % (r["uuid"], r["uuid"])) - output.write("%s" % Markup.escape(r["sequence_label"])) - output.write("
%s
" % Markup.escape("\n".join(r.get("errors", [])))) - output.write("") + try: + if r["status"] != "rejected": + continue + output.write("") + output.write("%s" % (r["uuid"], r["uuid"])) + output.write("%s" % Markup.escape(r.get("sequence_label"))) + output.write("
%s
" % Markup.escape("\n".join(r.get("errors", [])))) + output.write("") + except: + pass output.write( """ -- cgit v1.2.3 From 15624e038e0f368d2be4c9a76ace77da4d673fdd Mon Sep 17 00:00:00 2001 From: Peter Amstutz Date: Thu, 16 Jul 2020 14:21:40 -0400 Subject: Improve upload form layout. Arvados-DCO-1.1-Signed-off-by: Peter Amstutz --- bh20simplewebuploader/main.py | 86 ++++++++++++++++------------- bh20simplewebuploader/static/main.css | 17 ++++-- bh20simplewebuploader/templates/footer.html | 5 +- 3 files changed, 64 insertions(+), 44 deletions(-) (limited to 'bh20simplewebuploader/main.py') diff --git a/bh20simplewebuploader/main.py b/bh20simplewebuploader/main.py index 3173d60..62b68d9 100644 --- a/bh20simplewebuploader/main.py +++ b/bh20simplewebuploader/main.py @@ -8,7 +8,7 @@ import os import sys import re import string -import yaml +import ruamel.yaml as yaml import pkg_resources from flask import Flask, request, redirect, send_file, send_from_directory, render_template, jsonify import os.path @@ -16,6 +16,9 @@ import requests import io import arvados from markupsafe import Markup +from schema_salad.sourceline import add_lc_filename +from schema_salad.schema import shortname +from typing import MutableSequence, MutableMapping ARVADOS_API = 'lugli.arvadosapi.com' ANONYMOUS_TOKEN = '5o42qdxpxp5cj15jqjf7vnxx5xduhm4ret703suuoa3ivfglfh' @@ -47,6 +50,8 @@ def type_to_heading(type_name): Turn a type name like "sampleSchema" from the metadata schema into a human-readable heading. """ + type_name = shortname(type_name) + print(type_name,file=sys.stderr) # Remove camel case decamel = re.sub('([A-Z])', r' \1', type_name) @@ -78,7 +83,7 @@ def is_iri(string): return string.startswith('http') -def generate_form(schema, options): +def generate_form(components, options): """ Linearize the schema into a list of dicts. @@ -101,9 +106,6 @@ def generate_form(schema, options): IRI. """ - # Get the list of form components, one of which is the root - components = schema.get('$graph', []) - # Find the root root_name = None # And also index components by type name @@ -131,14 +133,25 @@ def generate_form(schema, options): # First make a heading, if we aren't the very root of the form yield {'heading': type_to_heading(type_name)} - for field_name, field_type in by_name.get(type_name, {}).get('fields', {}).items(): + for field in by_name.get(type_name, {}).get('fields', []): + field_name = shortname(field["name"]) + field_type = field["type"] # For each field ref_iri = None docstring = None - if not isinstance(field_type, str): - # If the type isn't a string + optional = False + is_list = False + + if isinstance(field_type, MutableSequence): + if field_type[0] == "null" and len(field_type) == 2: + optional = True + field_type = field_type[1] + else: + raise Exception("Can't handle it") + + if isinstance(field_type, MutableMapping): # It may have documentation docstring = field_type.get('doc', None) @@ -161,25 +174,13 @@ def generate_form(schema, options): ref_iri = field_value break - - # Now overwrite the field type with the actual type string - field_type = field_type.get('type', '') - - # Decide if the field is optional (type ends in ?) - optional = False - if field_type.endswith('?'): - # It's optional - optional = True - # Drop the ? - field_type = field_type[:-1] - - # Decide if the field is a list (type ends in []) - is_list = False - if field_type.endswith('[]'): - # It's a list - is_list = True - # Reduce to the normal type - field_type = field_type[:-2] + if field_type["type"] == "array": + # Now replace the field type with the actual type string + is_list = True + field_type = field_type.get('items', '') + else: + field_type = field_type.get('type', '') + pass if field_type in by_name: # This is a subrecord. We need to recurse @@ -227,15 +228,24 @@ def generate_form(schema, options): return list(walk_fields(root_name)) -# At startup, we need to load the metadata schema from the uploader module, so we can make a form for it -if os.path.isfile("bh20sequploader/bh20seq-schema.yml"): - METADATA_SCHEMA = yaml.safe_load(open("bh20sequploader/bh20seq-schema.yml","r").read()) - METADATA_OPTION_DEFINITIONS = yaml.safe_load(open("bh20sequploader/bh20seq-options.yml","r").read()) -else: - METADATA_SCHEMA = yaml.safe_load(pkg_resources.resource_stream("bh20sequploader", "bh20seq-schema.yml")) - METADATA_OPTION_DEFINITIONS = yaml.safe_load(pkg_resources.resource_stream("bh20sequploader", "bh20seq-options.yml")) -# print(METADATA_SCHEMA,file=sys.stderr) -FORM_ITEMS = generate_form(METADATA_SCHEMA, METADATA_OPTION_DEFINITIONS) +import schema_salad.schema +def load_schema_generate_form(): + # At startup, we need to load the metadata schema from the uploader module, so we can make a form for it + if os.path.isfile("bh20sequploader/bh20seq-schema.yml"): + METADATA_SCHEMA = yaml.round_trip_load(open("bh20sequploader/bh20seq-schema.yml","r").read()) + METADATA_OPTION_DEFINITIONS = yaml.safe_load(open("bh20sequploader/bh20seq-options.yml","r").read()) + else: + METADATA_SCHEMA = yaml.round_trip_load(pkg_resources.resource_stream("bh20sequploader", "bh20seq-schema.yml")) + METADATA_OPTION_DEFINITIONS = yaml.safe_load(pkg_resources.resource_stream("bh20sequploader", "bh20seq-options.yml")) + + METADATA_SCHEMA["name"] = "bh20seq-schema.yml" + add_lc_filename(METADATA_SCHEMA, "bh20seq-schema.yml") + metaschema_names, _metaschema_doc, metaschema_loader = schema_salad.schema.get_metaschema() + schema_doc, schema_metadata = metaschema_loader.resolve_ref(METADATA_SCHEMA, "") + + return generate_form(schema_doc, METADATA_OPTION_DEFINITIONS) + +FORM_ITEMS = load_schema_generate_form() @app.route('/') def send_home(): @@ -543,10 +553,10 @@ def status_page(): for s in (("passed", "/download"), ("pending", "#pending"), ("rejected", "#rejected")): output.write("

%s sequences QC %s

" % (s[1], status.get(s[0], 0), s[0])) - output.write("

Pending

") + output.write("

Pending

") pending_table(output, out) - output.write("

Rejected

") + output.write("

Rejected

") rejected_table(output, out) return render_template('status.html', table=Markup(output.getvalue()), menu='STATUS') diff --git a/bh20simplewebuploader/static/main.css b/bh20simplewebuploader/static/main.css index 47fb408..b28ee9c 100644 --- a/bh20simplewebuploader/static/main.css +++ b/bh20simplewebuploader/static/main.css @@ -178,7 +178,7 @@ span.dropt:hover {text-decoration: none; background: #ffffff; z-index: 6; } .about { display: grid; - grid-template-columns: repeat(2, 1fr); + grid-template-columns: 1fr 1fr; grid-auto-flow: row; } @@ -229,7 +229,7 @@ a { #metadata_fill_form { column-count: 4; margin-top: 0.5em; - column-width: 250px; + column-width: 15em; } .record, .record .field-group, .record .field-group .field { @@ -238,6 +238,8 @@ a { -webkit-column-break-inside: avoid; /* Chrome, Safari, Opera */ page-break-inside: avoid; /* Firefox */ break-inside: avoid; + display: block; + width: 90%; } .record { @@ -258,6 +260,10 @@ a { width: max-content; } +.control { + width: 100%; +} + .filter-options { width: 100%; } @@ -304,9 +310,10 @@ footer { } .sponsors img { - width: 80%; - display:block; - margin:auto; + width: auto; + display: block; + margin: auto; + height: 4em; } .loader { diff --git a/bh20simplewebuploader/templates/footer.html b/bh20simplewebuploader/templates/footer.html index 37a6b64..5a1f3c9 100644 --- a/bh20simplewebuploader/templates/footer.html +++ b/bh20simplewebuploader/templates/footer.html @@ -21,11 +21,14 @@
- +
+
+ +
-- cgit v1.2.3 From d34374f0e822edd1539ea5de6f8522f2b761de3f Mon Sep 17 00:00:00 2001 From: Peter Amstutz Date: Thu, 16 Jul 2020 14:48:22 -0400 Subject: Improve uploader reporting. Arvados-DCO-1.1-Signed-off-by: Peter Amstutz --- bh20sequploader/main.py | 22 ++++++++++------------ bh20simplewebuploader/main.py | 4 ++-- bh20simplewebuploader/templates/error.html | 2 +- bh20simplewebuploader/templates/success.html | 2 +- 4 files changed, 14 insertions(+), 16 deletions(-) (limited to 'bh20simplewebuploader/main.py') diff --git a/bh20sequploader/main.py b/bh20sequploader/main.py index f744a8c..6049bf9 100644 --- a/bh20sequploader/main.py +++ b/bh20sequploader/main.py @@ -29,11 +29,10 @@ def qc_stuff(metadata, sequence_p1, sequence_p2, do_qc=True): try: log.debug("Checking metadata" if do_qc else "Skipping metadata check") if do_qc and not qc_metadata(metadata.name): - log.warning("Failed metadata qc") + log.warning("Failed metadata QC") failed = True except Exception as e: - log.debug(e) - print(e) + log.exception("Failed metadata QC") failed = True target = [] @@ -45,8 +44,7 @@ def qc_stuff(metadata, sequence_p1, sequence_p2, do_qc=True): target[0] = ("reads_1."+target[0][0][6:], target[0][1]) target[1] = ("reads_2."+target[1][0][6:], target[0][1]) except Exception as e: - log.debug(e) - print(e) + log.exception("Failed sequence QC") failed = True if failed: @@ -82,7 +80,7 @@ def main(): seqlabel = target[0][1] if args.validate: - print("Valid") + log.info("Valid") exit(0) col = arvados.collection.Collection(api_client=api) @@ -91,10 +89,10 @@ def main(): if args.sequence_p2: upload_sequence(col, target[1], args.sequence_p2) - print("Reading metadata") + log.info("Reading metadata") with col.open("metadata.yaml", "w") as f: r = args.metadata.read(65536) - print(r[0:20]) + log.info(r[0:20]) while r: f.write(r) r = args.metadata.read(65536) @@ -118,7 +116,7 @@ def main(): ["portable_data_hash", "=", col.portable_data_hash()]]).execute() if dup["items"]: # This exact collection has been uploaded before. - print("Duplicate of %s" % ([d["uuid"] for d in dup["items"]])) + log.error("Duplicate of %s" % ([d["uuid"] for d in dup["items"]])) exit(1) if args.trusted: @@ -131,9 +129,9 @@ def main(): (seqlabel, properties['upload_user'], properties['upload_ip']), properties=properties, ensure_unique_name=True) - print("Saved to %s" % col.manifest_locator()) - - print("Done") + log.info("Saved to %s" % col.manifest_locator()) + log.info("Done") + exit(0) if __name__ == "__main__": main() diff --git a/bh20simplewebuploader/main.py b/bh20simplewebuploader/main.py index 62b68d9..c814f30 100644 --- a/bh20simplewebuploader/main.py +++ b/bh20simplewebuploader/main.py @@ -445,12 +445,12 @@ def receive_files(): if result.returncode != 0: # It didn't work. Complain. - error_message="Uploader returned value {} and said:".format(result.returncode) + str(result.stderr.decode('utf-8')) + error_message="Uploader returned value {} and said:\n".format(result.returncode) + str(result.stderr.decode('utf-8')) print(error_message, file=sys.stderr) return (render_template('error.html', error_message=error_message), 403) else: # It worked. Say so. - return render_template('success.html', log=result.stdout.decode('utf-8', errors='replace')) + return render_template('success.html', log=result.stderr.decode('utf-8', errors='replace')) finally: shutil.rmtree(dest_dir) diff --git a/bh20simplewebuploader/templates/error.html b/bh20simplewebuploader/templates/error.html index b1d9402..fc08aed 100644 --- a/bh20simplewebuploader/templates/error.html +++ b/bh20simplewebuploader/templates/error.html @@ -15,7 +15,7 @@

- Click here to try again. + Click here to try again.


diff --git a/bh20simplewebuploader/templates/success.html b/bh20simplewebuploader/templates/success.html index 9f0987c..c2302fa 100644 --- a/bh20simplewebuploader/templates/success.html +++ b/bh20simplewebuploader/templates/success.html @@ -9,7 +9,7 @@

Upload Successful


- Your files have been uploaded. They should soon appear as output of the Public SARS-CoV-2 Sequence Resource. + Your files have been uploaded. You can track their QC status, once validated they will be part of the Public SARS-CoV-2 Sequence Resource.

The upload log was: -- cgit v1.2.3 From d49f6b5e11a41a51cb257bbafdcba410544f8486 Mon Sep 17 00:00:00 2001 From: Peter Amstutz Date: Thu, 16 Jul 2020 16:27:32 -0400 Subject: Add "validated" and "running workflows" tables to status Arvados-DCO-1.1-Signed-off-by: Peter Amstutz --- bh20seqanalyzer/main.py | 12 +-- bh20simplewebuploader/main.py | 112 +++++++++++++++++++------ bh20simplewebuploader/templates/status.html | 3 +- bh20simplewebuploader/templates/validated.html | 17 ++++ 4 files changed, 114 insertions(+), 30 deletions(-) create mode 100644 bh20simplewebuploader/templates/validated.html (limited to 'bh20simplewebuploader/main.py') diff --git a/bh20seqanalyzer/main.py b/bh20seqanalyzer/main.py index f18a93a..b3a439d 100644 --- a/bh20seqanalyzer/main.py +++ b/bh20seqanalyzer/main.py @@ -240,24 +240,26 @@ class SeqAnalyzer: def move_fastq_to_fasta_results(self): projects = self.api.groups().list(filters=[['owner_uuid', '=', self.fastq_project], ["properties.moved_output", "!=", True]], - order="created_at desc",).execute() + order="created_at asc",).execute() for p in projects["items"]: wf = self.get_workflow_output_from_project(p["uuid"]) if not wf: continue logging.info("Moving completed fastq2fasta result %s back to uploader project", wf["output_uuid"]) - self.api.collections().update(uuid=wf["output_uuid"], - body={"owner_uuid": self.uploader_project}).execute() col = arvados.collection.Collection(wf["output_uuid"], api_client=self.api, keep_client=self.keepclient) with col.open("metadata.yaml") as md: metadata_content = ruamel.yaml.round_trip_load(md) + colprop = col.get_properties() + colprop["sequence_label"] = metadata_content["sample"]["sample_id"] + self.api.collections().update(uuid=wf["output_uuid"], + body={"owner_uuid": self.uploader_project, + "properties": colprop}).execute() + p["properties"]["moved_output"] = True - p["properties"]["sequence_label"] = metadata_content["sample"]["sample_id"] self.api.groups().update(uuid=p["uuid"], body={"properties": p["properties"]}).execute() - break def upload_schema(self): diff --git a/bh20simplewebuploader/main.py b/bh20simplewebuploader/main.py index c814f30..7dd07fe 100644 --- a/bh20simplewebuploader/main.py +++ b/bh20simplewebuploader/main.py @@ -144,6 +144,28 @@ def generate_form(components, options): optional = False is_list = False + # It may have documentation + docstring = field.get('doc', None) + + # See if it has a more info/what goes here URL + predicate = field.get('jsonldPredicate', {}) + # Predicate may be a URL, a dict with a URL in _id, maybe a + # dict with a URL in _type, or a dict with _id and _type but no + # URLs anywhere. Some of these may not technically be allowed + # by the format, but if they occur, we might as well try to + # handle them. + if isinstance(predicate, str): + if is_iri(predicate): + ref_iri = predicate + else: + # Assume it's a dict. Look at the fields we know about. + for field in ['_id', 'type']: + field_value = predicate.get(field, None) + if isinstance(field_value, str) and is_iri(field_value) and ref_iri is None: + # Take the first URL-looking thing we find + ref_iri = field_value + break + if isinstance(field_type, MutableSequence): if field_type[0] == "null" and len(field_type) == 2: optional = True @@ -152,28 +174,6 @@ def generate_form(components, options): raise Exception("Can't handle it") if isinstance(field_type, MutableMapping): - # It may have documentation - docstring = field_type.get('doc', None) - - # See if it has a more info/what goes here URL - predicate = field_type.get('jsonldPredicate', {}) - # Predicate may be a URL, a dict with a URL in _id, maybe a - # dict with a URL in _type, or a dict with _id and _type but no - # URLs anywhere. Some of these may not technically be allowed - # by the format, but if they occur, we might as well try to - # handle them. - if isinstance(predicate, str): - if is_iri(predicate): - ref_iri = predicate - else: - # Assume it's a dict. Look at the fields we know about. - for field in ['_id', 'type']: - field_value = predicate.get(field, None) - if isinstance(field_value, str) and is_iri(field_value) and ref_iri is None: - # Take the first URL-looking thing we find - ref_iri = field_value - break - if field_type["type"] == "array": # Now replace the field type with the actual type string is_list = True @@ -525,6 +525,54 @@ def rejected_table(output, items): """) +def workflows_table(output, items): + output.write( +""" + + + + + + + +""") + for r in items: + output.write("") + try: + sid = r["mounts"]["/var/lib/cwl/cwl.input.json"]["content"]["sample_id"] + output.write("" % Markup.escape(r["name"])) + output.write("" % Markup.escape(sid)) + output.write("" % Markup.escape(r["created_at"])) + output.write("" % (r["uuid"], r["uuid"])) + except: + pass + output.write("") + output.write( +""" +
NameSample idStartedContainer request
%s%s%s%s
+""") + +def validated_table(output, items): + output.write( +""" + + + + + +""") + for r in items: + try: + output.write("") + output.write("" % (r["uuid"], r["uuid"])) + output.write("" % Markup.escape(r["properties"].get("sequence_label"))) + output.write("") + except: + pass + output.write( +""" +
CollectionSequence label
%s%s
+""") @app.route('/status') def status_page(): @@ -545,22 +593,39 @@ def status_page(): prop["uuid"] = p["uuid"] status[prop["status"]] = status.get(prop["status"], 0) + 1 + workflows = arvados.util.list_all(api.container_requests().list, + filters=[["name", "in", ["fastq2fasta.cwl"]], ["state", "=", "Committed"]], + order="created_at asc") + output = io.StringIO() validated = api.collections().list(filters=[["owner_uuid", "=", VALIDATED_PROJECT]], limit=1).execute() status["passed"] = validated["items_available"] - for s in (("passed", "/download"), ("pending", "#pending"), ("rejected", "#rejected")): + for s in (("passed", "/validated"), ("pending", "#pending"), ("rejected", "#rejected")): output.write("

%s sequences QC %s

" % (s[1], status.get(s[0], 0), s[0])) + output.write("

%s analysis workflows running

" % ('#workflows', len(workflows))) + output.write("

Pending

") pending_table(output, out) output.write("

Rejected

") rejected_table(output, out) + output.write("

Running Workflows

") + workflows_table(output, workflows) + return render_template('status.html', table=Markup(output.getvalue()), menu='STATUS') +@app.route('/validated') +def validated_page(): + api = arvados.api(host=ARVADOS_API, token=ANONYMOUS_TOKEN, insecure=True) + output = io.StringIO() + validated = arvados.util.list_all(api.collections().list, filters=[["owner_uuid", "=", VALIDATED_PROJECT]]) + validated_table(output, validated) + return render_template('validated.html', table=Markup(output.getvalue()), menu='STATUS') + @app.route('/demo') def demo_page(): return render_template('demo.html',menu='DEMO') @@ -585,7 +650,6 @@ def map_page(): return render_template('map.html',menu='DEMO') - ## Dynamic API functions starting here ## This is quick and dirty for now, just to get something out and demonstrate the queries ## Feel free to rename the functions/endpoints, feel free to process result so we get nicer JSON diff --git a/bh20simplewebuploader/templates/status.html b/bh20simplewebuploader/templates/status.html index a1cf28f..e89437e 100644 --- a/bh20simplewebuploader/templates/status.html +++ b/bh20simplewebuploader/templates/status.html @@ -7,7 +7,8 @@

Sequence upload processing status

-
+
+ {{ table }}
diff --git a/bh20simplewebuploader/templates/validated.html b/bh20simplewebuploader/templates/validated.html new file mode 100644 index 0000000..cee94bd --- /dev/null +++ b/bh20simplewebuploader/templates/validated.html @@ -0,0 +1,17 @@ + + + {% include 'header.html' %} + + {% include 'banner.html' %} + {% include 'menu.html' %} + +

Validated sequences

+ +
+ {{ table }} +
+ +{% include 'footer.html' %} + + + -- cgit v1.2.3 From 7a0a05a8df8d12eb55e6a2e6392d4d384f481c7c Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Thu, 16 Jul 2020 11:37:47 +0100 Subject: Remove extra exclamation mark --- bh20simplewebuploader/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'bh20simplewebuploader/main.py') diff --git a/bh20simplewebuploader/main.py b/bh20simplewebuploader/main.py index 7dd07fe..1147176 100644 --- a/bh20simplewebuploader/main.py +++ b/bh20simplewebuploader/main.py @@ -456,7 +456,7 @@ def receive_files(): def edit_button(url,text="Edit text!"): - return '

'+text+'!

' + return '

'+text+'

' def get_html_body(fn,source="https://github.com/arvados/bh20-seq-resource/tree/master/doc"): buf = edit_button(source) -- cgit v1.2.3 From d3fa51ee16d902fc0bfa414611d5e0bae6618009 Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Fri, 17 Jul 2020 09:09:23 +0100 Subject: Refactoring map code --- bh20simplewebuploader/main.py | 7 +- bh20simplewebuploader/static/main.js | 149 ++++++++------------------ bh20simplewebuploader/static/map.js | 67 ++++++++++++ bh20simplewebuploader/templates/demo-run.html | 26 ----- bh20simplewebuploader/templates/demo.html | 30 +++++- bh20simplewebuploader/templates/footer.html | 3 + bh20simplewebuploader/templates/header.html | 18 ---- bh20simplewebuploader/templates/map.html | 24 ++++- 8 files changed, 164 insertions(+), 160 deletions(-) create mode 100644 bh20simplewebuploader/static/map.js (limited to 'bh20simplewebuploader/main.py') diff --git a/bh20simplewebuploader/main.py b/bh20simplewebuploader/main.py index 1147176..e8bb507 100644 --- a/bh20simplewebuploader/main.py +++ b/bh20simplewebuploader/main.py @@ -628,7 +628,7 @@ def validated_page(): @app.route('/demo') def demo_page(): - return render_template('demo.html',menu='DEMO') + return render_template('demo.html',menu='DEMO',load_map=True) @app.route('/blog',methods=['GET']) def blog_page(): @@ -644,11 +644,6 @@ def about_page(): buf = get_html_body('doc/web/about.html','https://github.com/arvados/bh20-seq-resource/blob/master/doc/web/about.org') return render_template('about.html',menu='ABOUT',embed=buf) -## -@app.route('/map') -def map_page(): - return render_template('map.html',menu='DEMO') - ## Dynamic API functions starting here ## This is quick and dirty for now, just to get something out and demonstrate the queries diff --git a/bh20simplewebuploader/static/main.js b/bh20simplewebuploader/static/main.js index 4703047..1633c25 100644 --- a/bh20simplewebuploader/static/main.js +++ b/bh20simplewebuploader/static/main.js @@ -13,70 +13,41 @@ function myFunction() { } } -let map = L.map( 'map', { - center: [37.0902, -95.7129], // Default to U.S.A - minZoom: 3, - zoom: 0 -}); -L.tileLayer( 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { - attribution: '© OpenStreetMap', - subdomains: ['a','b','c'] -}).addTo( map ); - -let markers = L.markerClusterGroup().addTo(map) - - function fetchAPI(apiEndPoint) { - fetch(scriptRoot + apiEndPoint) - .then(response => { - return response.json(); - }) - .then(data => { - console.log(data); - markers.clearLayers(); - document.getElementById("results").classList.remove("invisible"); - document.getElementById("loader").classList.add("invisible"); - if (!(apiEndPoint === "/api/getAllaccessions")) { - for (let i = 0; i < data.length; i++) { - let {"count": fastaCount, GPS, LocationLabel: label } = data[i]; - let coordinates = GPS.split(" "); - if (!(coordinates == null)) { - let lat, lon; - [lon, lat] = coordinates.map(parseFloat); - let point = L.point() - let marker = L.marker([lat, lon]); - marker.bindPopup("" + label + "
" + "FastaCount: " +fastaCount); - markers.addLayer(marker) - }} - } - // Reload the map - map.invalidateSize(); - }); - document.getElementById("results").classList.add("invisible"); - document.getElementById("loader").classList.remove("invisible"); - -} - -// Copy from function above but now added as table instead of plain json -function fetchAPIV2(apiEndPoint) { - fetch(scriptRoot + apiEndPoint) - .then(response => { - return response.json(); - }) - .then(data => { - console.log(data) - htmlString="" - - // Depending on what we want to explore we'd have to call a different function ....? But how to Include that? - for (var i=0; i" - } - htmlString=htmlString+"
"+data[i]["label"]+""+data[i]["count"]+"
" - - document.getElementById("table").innerHTML = htmlString - }); - - document.getElementById("results").classList.add("invisible"); + fetch(scriptRoot + apiEndPoint) + .then(response => { + return response.json(); + }) + .then(data => { + console.log(data); + }); + document.getElementById("map_view").classList.add("invisible"); + document.getElementById("loader").classList.remove("invisible"); +} + +// Copy from function above but now output HTML table instead of plain json +function fetchHTMLTable(apiEndPoint) { + fetch(scriptRoot + apiEndPoint) + .then(response => { + return response.json(); + }) + .then(data => { + console.log(data) + htmlString="" + + // Depending on what we want to explore we'd have to call a different function ....? But how to Include that? + /* + for (var i=0; i" + } +*/ + for (var i=0; i" + } + htmlString=htmlString+"
"+data[i]["label"]+""+data[i]["count"]+"
"+data[i]["label"]+""+data[i]["count"]+"
" + + document.getElementById("table").innerHTML = htmlString + }); } @@ -85,36 +56,39 @@ let search = () => { fetchAPI(scriptRoot + "/api/getDetailsForSeq?seq=" + encodeURIComponent(m)); } +// Get count from Arvados let fetchCount = () => { fetchAPI("/api/getCount"); } +// Get count from Virtuoso let fetchCountDB = () => { fetchAPI("/api/getCountDB"); } let fetchSEQCountBySpecimen = () => { - fetchAPIV2("/api/getSEQCountbySpecimenSource"); + fetchHTMLTable("/api/getSEQCountbySpecimenSource"); } let fetchSEQCountByLocation = () => { - fetchAPIV2("/api/getSEQCountbyLocation"); + fetchHTMLTable("/api/getSEQCountbyLocation"); } let fetchSEQCountByTech = () => { - fetchAPIV2("/api/getSEQCountbytech"); + fetchHTMLTable("/api/getSEQCountbytech"); } let fetchAllaccessions = () => { - fetchAPI("/api/getAllaccessions"); + fetchHTMLTable("/api/getAllaccessions"); }; -let fetchCountByGPS = () => { - fetchAPI("/api/getCountByGPS"); +let fetchMap = () => { + fetchAPI("/api/getCountByGPS"); + updateMapMarkers(); }; let fetchSEQCountbyLocation = () => { - fetchAPIV2("/api/getSEQCountbyLocation"); + fetchHTMLTable("/api/getSEQCountbyLocation"); }; let fetchSEQByLocation = () => { @@ -122,7 +96,7 @@ let fetchSEQByLocation = () => { }; let fetchSEQCountbyContinent = () => { - fetchAPIV2("/api/getSEQCountbyContinent"); + fetchHTMLTable("/api/getSEQCountbyContinent"); } @@ -252,36 +226,3 @@ function on_submit_button() { return false; } } - - - -// - -function drawMap(){ - -// initialize the map on the "map" div with a given center and zoom -var mymap = L.map('mapid').setView([51.505, -0.09], 1); - -L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { - attribution: '© OpenStreetMap contributors' -}).addTo(mymap); - -fetch(scriptRoot + "api/getCountByGPS") - .then(response => { - console.log(response) - return response.json(); - }) - .then(data => { - - for (var i=0; iOpenStreetMap', + subdomains: ['a','b','c'] +}).addTo( map ); + +let markers = L.markerClusterGroup().addTo(map) + + +function drawMap(){ + +// initialize the map on the "map" div with a given center and zoom +var mymap = L.map('mapid').setView([51.505, -0.09], 1); + +L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { + attribution: '© OpenStreetMap contributors' +}).addTo(mymap); + +fetch(scriptRoot + "api/getCountByGPS") + .then(response => { + console.log(response) + return response.json(); + }) + .then(data => { + + for (var i=0; i" + label + "
" + "FastaCount: " +fastaCount); + markers.addLayer(marker) + }} + // Reload the map + map.invalidateSize(); + document.getElementById("map_view").classList.add("invisible"); + document.getElementById("loader").classList.add("invisible"); +} diff --git a/bh20simplewebuploader/templates/demo-run.html b/bh20simplewebuploader/templates/demo-run.html index a8f9edc..e69de29 100644 --- a/bh20simplewebuploader/templates/demo-run.html +++ b/bh20simplewebuploader/templates/demo-run.html @@ -1,26 +0,0 @@ -
-
-

[Demo] Display content sequences by:

-
- - - - - - - -
- -
- -
- - - - -
-
-
diff --git a/bh20simplewebuploader/templates/demo.html b/bh20simplewebuploader/templates/demo.html index 44aded0..2e290c6 100644 --- a/bh20simplewebuploader/templates/demo.html +++ b/bh20simplewebuploader/templates/demo.html @@ -5,8 +5,34 @@ {% include 'banner.html' %} {% include 'menu.html' %} {% include 'search.html' %} -

The Virtuoso database contains public sequences!

- {% include 'demo-run.html' %} +

The Virtuoso database contains public sequences!

+ +
+
+

[Demo] Display content sequences by:

+
+ + + + + + +
+ +
+ +
+ + + + +
+
+
+ {% include 'footer.html' %} +{% endif %} - - diff --git a/bh20simplewebuploader/templates/map.html b/bh20simplewebuploader/templates/map.html index 595af0c..4aa22b9 100644 --- a/bh20simplewebuploader/templates/map.html +++ b/bh20simplewebuploader/templates/map.html @@ -1,7 +1,26 @@ {% include 'header.html' %} - + + + + + + + + + @@ -11,9 +30,6 @@ {% include 'footer.html' %} - - - -- cgit v1.2.3 From 06e3922a5541641077b18016e272cddc7e50205b Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Fri, 17 Jul 2020 09:59:32 +0100 Subject: Map refactoring, now shows on HOME --- bh20simplewebuploader/main.py | 2 +- bh20simplewebuploader/static/map.js | 14 ++++++++------ bh20simplewebuploader/templates/demo-run.html | 0 bh20simplewebuploader/templates/demo.html | 21 +-------------------- bh20simplewebuploader/templates/home.html | 15 ++++++++++++++- bh20simplewebuploader/templates/map.html | 0 bh20simplewebuploader/templates/mapheader.html | 16 ++++++++++++++++ 7 files changed, 40 insertions(+), 28 deletions(-) delete mode 100644 bh20simplewebuploader/templates/demo-run.html delete mode 100644 bh20simplewebuploader/templates/map.html create mode 100644 bh20simplewebuploader/templates/mapheader.html (limited to 'bh20simplewebuploader/main.py') diff --git a/bh20simplewebuploader/main.py b/bh20simplewebuploader/main.py index e8bb507..206f884 100644 --- a/bh20simplewebuploader/main.py +++ b/bh20simplewebuploader/main.py @@ -253,7 +253,7 @@ def send_home(): Send the front page. """ - return render_template('home.html', menu='HOME') + return render_template('home.html', menu='HOME', load_map=True) @app.route('/upload') diff --git a/bh20simplewebuploader/static/map.js b/bh20simplewebuploader/static/map.js index e1a4289..8b8ecba 100644 --- a/bh20simplewebuploader/static/map.js +++ b/bh20simplewebuploader/static/map.js @@ -31,6 +31,7 @@ function drawMap(){ radius: parseInt(data[i]["count"]) //not working for whatever reason }).addTo(mymap); } + // updateMapMarkers(data); }); document.getElementById("map_view").classList.remove("invisible"); @@ -42,11 +43,11 @@ function drawMap(){ /* This function updates the map with markers * */ -function updateMapMarkers() { +function updateMapMarkers(data) { // markers.clearLayers(); // remove all markers // document.getElementById("results").classList.remove("invisible"); - document.getElementById("loader").classList.add("invisible"); - /* + // document.getElementById("loader").classList.add("invisible"); + for (let i = 0; i < data.length; i++) { let {"count": fastaCount, GPS, LocationLabel: label } = data[i]; let coordinates = GPS.split(" "); @@ -57,10 +58,11 @@ function updateMapMarkers() { let marker = L.marker([lat, lon]); marker.bindPopup("" + label + "
" + "FastaCount: " +fastaCount); // markers.addLayer(marker) - }} - */ + } + } + // Reload the map - map.invalidateSize(); + // map.invalidateSize(); // document.getElementById("map_view").classList.add("invisible"); // document.getElementById("loader").classList.add("invisible"); } diff --git a/bh20simplewebuploader/templates/demo-run.html b/bh20simplewebuploader/templates/demo-run.html deleted file mode 100644 index e69de29..0000000 diff --git a/bh20simplewebuploader/templates/demo.html b/bh20simplewebuploader/templates/demo.html index 3a80abf..65ba462 100644 --- a/bh20simplewebuploader/templates/demo.html +++ b/bh20simplewebuploader/templates/demo.html @@ -1,25 +1,7 @@ {% include 'header.html' %} - - - - - - - - - + {% include 'mapheader.html' %} {% include 'banner.html' %} {% include 'menu.html' %} @@ -36,7 +18,6 @@ -
diff --git a/bh20simplewebuploader/templates/home.html b/bh20simplewebuploader/templates/home.html index b90a18d..42b08c0 100644 --- a/bh20simplewebuploader/templates/home.html +++ b/bh20simplewebuploader/templates/home.html @@ -1,6 +1,7 @@ {% include 'header.html' %} + {% include 'mapheader.html' %} {% include 'banner.html' %} {% include 'menu.html' %} @@ -44,7 +45,19 @@ -{% include 'footer.html' %} + + + {% include 'footer.html' %} + + + diff --git a/bh20simplewebuploader/templates/map.html b/bh20simplewebuploader/templates/map.html deleted file mode 100644 index e69de29..0000000 diff --git a/bh20simplewebuploader/templates/mapheader.html b/bh20simplewebuploader/templates/mapheader.html new file mode 100644 index 0000000..ca62051 --- /dev/null +++ b/bh20simplewebuploader/templates/mapheader.html @@ -0,0 +1,16 @@ + + + + + + -- cgit v1.2.3