|
| 1 | +import logging |
| 2 | +import requests |
| 3 | +from pprint import pprint |
| 4 | + |
| 5 | +from django.conf import settings |
| 6 | + |
| 7 | +from creator.decorators import task |
| 8 | +from creator.files.models import Version |
| 9 | +from creator.analyses.analyzer import extract_data |
| 10 | +from creator.dewrangle.client import DewrangleClient |
| 11 | +from kf_lib_data_ingest.common.io import read_df |
| 12 | + |
| 13 | +DATAFRAME_CHUNK_SIZE = 100 |
| 14 | +KNOWN_FORMATS = { |
| 15 | + ".csv": {"reader": pandas.read_csv, "sep": ","}, |
| 16 | + ".tsv": {"reader": pandas.read_csv, "sep": "\t"}, |
| 17 | + ".txt": {"reader": pandas.read_csv, "sep": None}, |
| 18 | +} |
| 19 | +FILE_UPLOAD_MANIFEST_SCHEMA = { |
| 20 | + "required": [ |
| 21 | + "Source File Name", |
| 22 | + "Hash", |
| 23 | + "Hash Algorithm", |
| 24 | + "Size", |
| 25 | + ], |
| 26 | + "optional": [ |
| 27 | + "Patient IDs", |
| 28 | + "Specimen IDs" |
| 29 | + ] |
| 30 | +} |
| 31 | + |
| 32 | +logger = logginer.getLogger(__name__) |
| 33 | + |
| 34 | + |
| 35 | +class ExtractDataError(Exception): |
| 36 | + pass |
| 37 | + |
| 38 | + |
| 39 | +def is_file_upload_manifest(version): |
| 40 | + """ |
| 41 | + Check whether this file version conforms to the File Upload Manifest schema |
| 42 | + """ |
| 43 | + header = { |
| 44 | + "_".join(c.split(" ")).lower() |
| 45 | + for c in read_df(version.key, nrows=0).columns |
| 46 | + } |
| 47 | + expected = ["_".join(c.split(" ")).lower() |
| 48 | + for c in FILE_UPLOAD_MANIFEST_SCHEMA["required"]] |
| 49 | + return expected <= header |
| 50 | + |
| 51 | + |
| 52 | +def chunked_dataframe_reader(version): |
| 53 | + """ |
| 54 | + Read a tabular file into chunks of Dataframes and yield chunks |
| 55 | + """ |
| 56 | + # Need to set storage location for study bucket if using S3 backend |
| 57 | + if settings.DEFAULT_FILE_STORAGE == "django_s3_storage.storage.S3Storage": |
| 58 | + if version.study is not None: |
| 59 | + study = version.study |
| 60 | + elif version.root_file is not None: |
| 61 | + study = version.root_file.study |
| 62 | + else: |
| 63 | + raise GraphQLError("Version must be part of a study.") |
| 64 | + |
| 65 | + version.key.storage = S3Storage(aws_s3_bucket_name=study.bucket) |
| 66 | + |
| 67 | + # Check file format |
| 68 | + _, ext = os.path.splitext(version.key.name) |
| 69 | + if ext not in KNOWN_FORMATS: |
| 70 | + raise IOError( |
| 71 | + "Unsupported file format. Unable to read file upload manifest: " |
| 72 | + f"{version.pk} {version.file_name}" |
| 73 | + ) |
| 74 | + |
| 75 | + # Read file into chunks (DataFrames) |
| 76 | + reader = KNOWN_FORMATS[ext]["reader"] |
| 77 | + delim = KNOWN_FORMATS[ext]["sep"] |
| 78 | + try: |
| 79 | + for i, chunk in enumerate( |
| 80 | + reader(version.key, sep=delim, chunksize=DATAFRAME_CHUNK_SIZE) |
| 81 | + ): |
| 82 | + logger.info( |
| 83 | + f"Reading {DATAFRAME_CHUNK_SIZE} rows from " |
| 84 | + f"{version.file_name} into DataFrame" |
| 85 | + ) |
| 86 | + yield chunk |
| 87 | + except Exception as e: |
| 88 | + er_msg = ( |
| 89 | + f"Error in parsing {version.pk}: {version.file_name}" |
| 90 | + " content into a DataFrame." |
| 91 | + ) |
| 92 | + raise ExtractDataError from e |
| 93 | + |
| 94 | + |
| 95 | +def dataframe_to_invoices(df): |
| 96 | + """ |
| 97 | + Helper to convert a file upload manifest DataFrame into a list of |
| 98 | + FileUploadInvoice dicts in preparation to send to Dewrangle API |
| 99 | + """ |
| 100 | + extract_cols = { |
| 101 | + c: "_".join(c.split(" ")).lower() |
| 102 | + for c in ( |
| 103 | + FILE_UPLOAD_MANIFEST_SCHEMA["required"] + |
| 104 | + FILE_UPLOAD_MANIFEST_SCHEMA["optional"] |
| 105 | + ) |
| 106 | + } |
| 107 | + df = df[[c for c in extract_cols if c in df.columns]] |
| 108 | + |
| 109 | + mapping = { |
| 110 | + "source_file_name": "fileName", |
| 111 | + "hash": "hash", |
| 112 | + "hash_algorithm": "hashAlgorithm", |
| 113 | + "size": "size", |
| 114 | + "patient_ids": "patientIds", |
| 115 | + "specimen_ids": "specimenIds" |
| 116 | + } |
| 117 | + df = df.rename(columns=mapped_cols) |
| 118 | + |
| 119 | + return df.to_dict(orient="records") |
| 120 | + |
| 121 | + |
| 122 | +@task("push_to_dewrangle") |
| 123 | +def push_to_dewrangle(version_id): |
| 124 | + """ |
| 125 | + Push the records in a file upload manifest to the Dewrangle API |
| 126 | + where they will processed to produce an audit report of files in |
| 127 | + cloud storage |
| 128 | + """ |
| 129 | + try: |
| 130 | + dewrangle = DewrangleClient() |
| 131 | + for df in chunked_dataframe_reader(version): |
| 132 | + logger.info( |
| 133 | + f"Submitting {df.shape[0]} file upload invoices to" |
| 134 | + f" {dewrangle.url}" |
| 135 | + ) |
| 136 | + pprint(dataframe_to_invoices(df)) |
| 137 | + # result = dewrangle.bulk_create_file_upload_invoices({ |
| 138 | + # "studyId": version.study.pk, |
| 139 | + # "fileUploadInvoices": dataframe_to_invoices(df) |
| 140 | + # }) |
| 141 | + logger.info( |
| 142 | + f"Success. Created: {result['created']} invoices. Total:" |
| 143 | + f" {results['total']} invoices" |
| 144 | + ) |
| 145 | + |
| 146 | + except Exception as e: |
| 147 | + # TODO Set Version.submitted_for_audit = fail |
| 148 | + raise |
| 149 | + |
| 150 | + # TODO |
| 151 | + # set Version.submitted_for_audit = completed |
0 commit comments