gentroutils 0.1.5__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- gentroutils/__init__.py +44 -0
- gentroutils/commands/__init__.py +7 -0
- gentroutils/commands/update_gwas_curation_metadata.py +313 -0
- gentroutils/commands/utils.py +135 -0
- gentroutils-0.1.5.dist-info/METADATA +71 -0
- gentroutils-0.1.5.dist-info/RECORD +9 -0
- gentroutils-0.1.5.dist-info/WHEEL +4 -0
- gentroutils-0.1.5.dist-info/entry_points.txt +2 -0
- gentroutils-0.1.5.dist-info/licenses/LICENSE +201 -0
gentroutils/__init__.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Cli for gentroutils."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import time
|
|
7
|
+
|
|
8
|
+
import click
|
|
9
|
+
import pyfiglet
|
|
10
|
+
|
|
11
|
+
from gentroutils.commands.update_gwas_curation_metadata import (
|
|
12
|
+
update_gwas_curation_metadata_command,
|
|
13
|
+
)
|
|
14
|
+
from gentroutils.commands.utils import set_log_file, set_log_lvl, teardown_cli
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger("gentroutils")
|
|
17
|
+
logger.setLevel(logging.DEBUG)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@click.group()
|
|
21
|
+
@click.option("-d", "--dry-run", is_flag=True, default=False)
|
|
22
|
+
@click.option(
|
|
23
|
+
"-v",
|
|
24
|
+
count=True,
|
|
25
|
+
default=0,
|
|
26
|
+
callback=set_log_lvl,
|
|
27
|
+
help="Increase verbosity of the logging. Can be used multiple times. The default log level is ERROR, -v is INFO, -vv is DEBUG",
|
|
28
|
+
)
|
|
29
|
+
@click.option("-q", "--log-file", callback=set_log_file, required=False)
|
|
30
|
+
@click.pass_context
|
|
31
|
+
def cli(ctx: click.Context, **kwargs: dict[str, str]) -> None:
|
|
32
|
+
r"""Gentroutils Command Line Interface."""
|
|
33
|
+
ascii_art = pyfiglet.Figlet(font="serifcap").renderText("Gentroutils")
|
|
34
|
+
click.echo(click.style(ascii_art, fg="blue"))
|
|
35
|
+
ctx.max_content_width = 200
|
|
36
|
+
ctx.ensure_object(dict)
|
|
37
|
+
ctx.obj["dry_run"] = kwargs["dry_run"]
|
|
38
|
+
ctx.obj["execution_start"] = time.time()
|
|
39
|
+
ctx.call_on_close(lambda: teardown_cli(ctx))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
cli.add_command(update_gwas_curation_metadata_command)
|
|
43
|
+
|
|
44
|
+
__all__ = ["cli"]
|
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
"""Update gwas catalog metadata."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import io
|
|
7
|
+
import logging
|
|
8
|
+
import re
|
|
9
|
+
import sys
|
|
10
|
+
from ftplib import FTP
|
|
11
|
+
from urllib.parse import ParseResult, urlparse
|
|
12
|
+
|
|
13
|
+
import click
|
|
14
|
+
import requests
|
|
15
|
+
from google.cloud import storage
|
|
16
|
+
|
|
17
|
+
from gentroutils.commands.utils import coro
|
|
18
|
+
|
|
19
|
+
logger = logging.getLogger("gentroutils")
|
|
20
|
+
MAX_CONCURRENT_CONNECTIONS = 10
|
|
21
|
+
CURATED_INPUTS = (
|
|
22
|
+
(
|
|
23
|
+
"ftp://ftp.ebi.ac.uk/pub/databases/gwas/releases/latest/gwas-catalog-associations_ontology-annotated.tsv",
|
|
24
|
+
"gs://gwas_catalog_data/curated_inputs/gwas_catalog_associations_ontology_annotated.tsv",
|
|
25
|
+
),
|
|
26
|
+
(
|
|
27
|
+
"ftp://ftp.ebi.ac.uk/pub/databases/gwas/releases/latest/gwas-catalog-download-studies-v1.0.3.1.txt",
|
|
28
|
+
"gs://gwas_catalog_data/curated_inputs/gwas_catalog_download_studies.tsv",
|
|
29
|
+
),
|
|
30
|
+
(
|
|
31
|
+
"ftp://ftp.ebi.ac.uk/pub/databases/gwas/releases/latest/gwas-catalog-unpublished-studies-v1.0.3.1.tsv",
|
|
32
|
+
"gs://gwas_catalog_data/curated_inputs/gwas_catalog_unpublished_studies.tsv",
|
|
33
|
+
),
|
|
34
|
+
(
|
|
35
|
+
"ftp://ftp.ebi.ac.uk/pub/databases/gwas/releases/latest/gwas-catalog-download-ancestries-v1.0.3.1.txt",
|
|
36
|
+
"gs://gwas_catalog_data/curated_inputs/gwas_catalog_download_ancestries.tsv",
|
|
37
|
+
),
|
|
38
|
+
(
|
|
39
|
+
"ftp://ftp.ebi.ac.uk/pub/databases/gwas/releases/latest/gwas-catalog-unpublished-ancestries-v1.0.3.1.tsv",
|
|
40
|
+
"gs://gwas_catalog_data/curated_inputs/gwas_catalog_unpublished_ancestries.tsv",
|
|
41
|
+
),
|
|
42
|
+
(
|
|
43
|
+
"ftp://ftp.ebi.ac.uk/pub/databases/gwas/summary_statistics/harmonised_list.txt",
|
|
44
|
+
"gs://gwas_catalog_data/curated_inputs/harmonised_list.txt",
|
|
45
|
+
),
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@click.command(name="update-gwas-curation-metadata")
|
|
50
|
+
@click.option(
|
|
51
|
+
"--file-to-transfer",
|
|
52
|
+
"-f",
|
|
53
|
+
metavar="<ftp_file|http(s) file> <gcp_file>",
|
|
54
|
+
type=(str, str),
|
|
55
|
+
multiple=True,
|
|
56
|
+
default=CURATED_INPUTS,
|
|
57
|
+
)
|
|
58
|
+
@click.option(
|
|
59
|
+
"--gwas-catalog-release-info-url",
|
|
60
|
+
"-g",
|
|
61
|
+
metavar="<url>",
|
|
62
|
+
default="https://www.ebi.ac.uk/gwas/api/search/stats",
|
|
63
|
+
type=click.STRING,
|
|
64
|
+
)
|
|
65
|
+
@click.pass_context
|
|
66
|
+
@coro
|
|
67
|
+
async def update_gwas_curation_metadata_command(
|
|
68
|
+
ctx: click.Context,
|
|
69
|
+
file_to_transfer: list[tuple[str, str]],
|
|
70
|
+
gwas_catalog_release_info_url: str,
|
|
71
|
+
) -> None:
|
|
72
|
+
"""Update GWAS Catalog metadata directly to cloud bucket.
|
|
73
|
+
|
|
74
|
+
\b
|
|
75
|
+
This is the script to fetch the latest GWAS Catalog data files that include:
|
|
76
|
+
- [x] gwas-catalog-associations_ontology-annotated.tsv - list of associations with ontology annotations by GWAS Catalog
|
|
77
|
+
- [x] gwas-catalog-download-studies-v1.0.3.1.txt - list of published studies by GWAS Catalog
|
|
78
|
+
- [x] gwas-catalog-unpublished-studies-v1.0.3.1.tsv - list of unpublished studies by GWAS Catalog
|
|
79
|
+
- [x] gwas-catalog-download-ancestries-v1.0.3.1.txt - list of published studies by GWAS Catalog
|
|
80
|
+
- [x] gwas-catalog-unpublished-ancestries-v1.0.3.1.tsv - list of unpublished studies by GWAS Catalog
|
|
81
|
+
|
|
82
|
+
\b
|
|
83
|
+
By default all GWAS Catalog data files are uploaded from GWAS Catalog FTP server to Open Targets GCP bucket.
|
|
84
|
+
The script also captures the latest release metadata from GWAS Catalog release info url.
|
|
85
|
+
One can overwrite this script to sync data files from FTP or HTTP(s) to GCP bucket. The example usage is as follows:
|
|
86
|
+
|
|
87
|
+
\b
|
|
88
|
+
gentroutils --log-file gs://gwas_catalog_data/curated_inputs/log.txt update-gwas-curation-metadata \\
|
|
89
|
+
-f ftp://ftp.ebi.ac.uk/pub/databases/gwas/releases/latest/gwas-catalog-associations_ontology-annotated.tsv gs://gwas_catalog_data/curated_inputs/gwas_catalog_associations_ontology_annotated.tsv \\
|
|
90
|
+
-f ftp://ftp.ebi.ac.uk/pub/databases/gwas/releases/latest/gwas-catalog-download-studies-v1.0.3.1.txt gs://gwas_catalog_data/curated_inputs/gwas_catalog_download_studies.tsv \\
|
|
91
|
+
-f ftp://ftp.ebi.ac.uk/pub/databases/gwas/releases/latest/gwas-catalog-unpublished-studies-v1.0.3.1.tsv gs://gwas_catalog_data/curated_inputs/gwas_catalog_unpublished_studies.tsv \\
|
|
92
|
+
-f ftp://ftp.ebi.ac.uk/pub/databases/gwas/releases/latest/gwas-catalog-download-ancestries-v1.0.3.1.txt gs://gwas_catalog_data/curated_inputs/gwas_catalog_download_ancestries.tsv \\
|
|
93
|
+
-f ftp://ftp.ebi.ac.uk/pub/databases/gwas/releases/latest/gwas-catalog-unpublished-ancestries-v1.0.3.1.tsv gs://gwas_catalog_data/curated_inputs/gwas_catalog_unpublished_ancestries.tsv \\
|
|
94
|
+
-f ftp://ftp.ebi.ac.uk/pub/databases/gwas/summary_statistics/harmonised_list.txt gs://gwas_catalog_data/curated_inputs/harmonised_list.txt \\
|
|
95
|
+
-f https://raw.githubusercontent.com/opentargets/curation/master/genetics/GWAS_Catalog_study_curation.tsv gs://gwas_catalog_data/manifests/gwas_catalog_study_curation.tsv \\
|
|
96
|
+
-g https://www.ebi.ac.uk/gwas/api/search/stats
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
To preserve the logs from this command, you can specify the log file path using `--log-file` option. The log file can point to local or GCP path.
|
|
100
|
+
Currently only FTP and HTTP(s) protocols are supported for input and GCP protocol is supported for output.
|
|
101
|
+
"""
|
|
102
|
+
# we always want to have the logs from this command uploaded to the target bucket
|
|
103
|
+
logger.debug("Running gwas_curation_update step.")
|
|
104
|
+
dry_run = ctx.obj["dry_run"]
|
|
105
|
+
if len(file_to_transfer) > MAX_CONCURRENT_CONNECTIONS:
|
|
106
|
+
logger.error(
|
|
107
|
+
"File transfer limit exceeded! Max %s connections allowed.",
|
|
108
|
+
MAX_CONCURRENT_CONNECTIONS,
|
|
109
|
+
)
|
|
110
|
+
sys.exit(1)
|
|
111
|
+
uri_map = [
|
|
112
|
+
{"input": urlparse(ftp_file), "output": urlparse(gcp_file)}
|
|
113
|
+
for ftp_file, gcp_file in file_to_transfer
|
|
114
|
+
]
|
|
115
|
+
transfer_tasks = generate_transfer_tasks(uri_map, dry_run)
|
|
116
|
+
|
|
117
|
+
# capture latest release metadata
|
|
118
|
+
with requests.get(gwas_catalog_release_info_url) as response:
|
|
119
|
+
if not response.ok:
|
|
120
|
+
logger.error("Failed to fetch release info.")
|
|
121
|
+
sys.exit(1)
|
|
122
|
+
release_info = response.json()
|
|
123
|
+
for key, value in release_info.items():
|
|
124
|
+
logger.debug("%s: %s", key, value)
|
|
125
|
+
|
|
126
|
+
efo_version = release_info.get("efoversion")
|
|
127
|
+
logger.info("Diseases were mapped to %s EFO release.", efo_version)
|
|
128
|
+
logger.info("EFO version: %s", efo_version)
|
|
129
|
+
ensembl_build = release_info.get("ensemblbuild")
|
|
130
|
+
logger.info("Genes were mapped to v%s Ensembl release.", ensembl_build)
|
|
131
|
+
|
|
132
|
+
results = await asyncio.gather(*transfer_tasks)
|
|
133
|
+
if not dry_run:
|
|
134
|
+
logger.info("Transferred %s files.", len(results))
|
|
135
|
+
logger.info("gwas_curation_update step completed.")
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def generate_transfer_tasks(
|
|
139
|
+
uri_map: list[dict[str, ParseResult]], dry_run: bool
|
|
140
|
+
) -> list[asyncio.Task[None]]:
|
|
141
|
+
"""Generate transfer tasks.
|
|
142
|
+
|
|
143
|
+
Args:
|
|
144
|
+
uri_map (list[dict[str, ParseResult]]): list of transferable tasks, each should have `input` and `output` keys.
|
|
145
|
+
dry_run (bool): dry run flag.
|
|
146
|
+
|
|
147
|
+
Returns:
|
|
148
|
+
list[asyncio.Task[None]]: list of asyncio tasks.
|
|
149
|
+
"""
|
|
150
|
+
ftp_transfer_list = []
|
|
151
|
+
http_transfer_list = []
|
|
152
|
+
for uri in uri_map:
|
|
153
|
+
if uri["input"].scheme != "ftp" and not uri["input"].scheme.startswith("http"):
|
|
154
|
+
logger.error("Only FTP and HTTP(s) protocols is supported at input.")
|
|
155
|
+
sys.exit(1)
|
|
156
|
+
if uri["output"].scheme != "gs":
|
|
157
|
+
logger.error("Only GCP protocol is supported at output.")
|
|
158
|
+
sys.exit(1)
|
|
159
|
+
in_server = uri["input"].netloc
|
|
160
|
+
out_server = uri["output"].netloc
|
|
161
|
+
in_prefix = "/".join(uri["input"].path.strip("/").split("/")[:-1])
|
|
162
|
+
in_file = uri["input"].path.strip("/").split("/")[-1]
|
|
163
|
+
out_prefix = "/".join(uri["output"].path[1:-1].split("/")[:-1])
|
|
164
|
+
out_bucket = uri["output"].path.split("/")[-1]
|
|
165
|
+
if uri["input"].scheme == "ftp":
|
|
166
|
+
ftp_transfer_list.append(
|
|
167
|
+
{
|
|
168
|
+
"ftp_server": in_server,
|
|
169
|
+
"ftp_prefix": in_prefix,
|
|
170
|
+
"ftp_filename": in_file,
|
|
171
|
+
"gcp_bucket": out_server,
|
|
172
|
+
"gcp_prefix": out_prefix,
|
|
173
|
+
"gcp_filename": out_bucket,
|
|
174
|
+
}
|
|
175
|
+
)
|
|
176
|
+
if uri["input"].scheme.startswith("http"):
|
|
177
|
+
http_transfer_list.append(
|
|
178
|
+
{
|
|
179
|
+
"http_url": uri["input"].geturl(),
|
|
180
|
+
"gcp_bucket": out_server,
|
|
181
|
+
"gcp_prefix": out_prefix,
|
|
182
|
+
"gcp_filename": out_bucket,
|
|
183
|
+
}
|
|
184
|
+
)
|
|
185
|
+
transfer_tasks = []
|
|
186
|
+
for transfer_obj in ftp_transfer_list:
|
|
187
|
+
transfer_tasks.append(
|
|
188
|
+
asyncio.create_task(
|
|
189
|
+
sync_from_ftp_to_gcp(
|
|
190
|
+
transfer_obj["ftp_server"],
|
|
191
|
+
transfer_obj["ftp_prefix"],
|
|
192
|
+
transfer_obj["ftp_filename"],
|
|
193
|
+
transfer_obj["gcp_bucket"],
|
|
194
|
+
transfer_obj["gcp_prefix"],
|
|
195
|
+
transfer_obj["gcp_filename"],
|
|
196
|
+
dry_run=dry_run,
|
|
197
|
+
)
|
|
198
|
+
)
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
for transfer_obj in http_transfer_list:
|
|
202
|
+
transfer_tasks.append(
|
|
203
|
+
asyncio.create_task(
|
|
204
|
+
sync_from_http_to_gcp(
|
|
205
|
+
transfer_obj["http_url"],
|
|
206
|
+
transfer_obj["gcp_bucket"],
|
|
207
|
+
transfer_obj["gcp_prefix"],
|
|
208
|
+
transfer_obj["gcp_filename"],
|
|
209
|
+
dry_run=dry_run,
|
|
210
|
+
)
|
|
211
|
+
)
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
return transfer_tasks
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
async def sync_from_http_to_gcp(
|
|
218
|
+
url: str, gcp_bucket: str, gcp_prefix: str, gcp_file: str, *, dry_run: bool = True
|
|
219
|
+
) -> None:
|
|
220
|
+
"""Sync file from HTTP and upload to GCP.
|
|
221
|
+
|
|
222
|
+
This function fetches the data from the provided HTTP URL and uploads the content
|
|
223
|
+
directly to provided GCP bucket blob.
|
|
224
|
+
|
|
225
|
+
Args:
|
|
226
|
+
url (str): HTTP URL to fetch the data.
|
|
227
|
+
gcp_bucket (str): GCP bucket name.
|
|
228
|
+
gcp_prefix (str): GCP prefix.
|
|
229
|
+
gcp_file (str): GCP file name.
|
|
230
|
+
dry_run (bool, optional): Dry run flag. Defaults to True.
|
|
231
|
+
"""
|
|
232
|
+
if dry_run:
|
|
233
|
+
logger.info(
|
|
234
|
+
"Attempting to transfer data from %s to gs://%s/%s/%s.",
|
|
235
|
+
url,
|
|
236
|
+
gcp_bucket,
|
|
237
|
+
gcp_prefix,
|
|
238
|
+
gcp_file,
|
|
239
|
+
)
|
|
240
|
+
return
|
|
241
|
+
logger.info("Retriving data from: %s.", url)
|
|
242
|
+
response = requests.get(url)
|
|
243
|
+
if not response.ok:
|
|
244
|
+
logger.error("Failed to fetch data from %s.", url)
|
|
245
|
+
return
|
|
246
|
+
|
|
247
|
+
content = response.content
|
|
248
|
+
bucket = storage.Client().bucket(gcp_bucket)
|
|
249
|
+
gcp_path = f"{gcp_prefix}/{gcp_file}" if gcp_prefix else gcp_file
|
|
250
|
+
|
|
251
|
+
blob = bucket.blob(gcp_path)
|
|
252
|
+
logger.info("Uploading the data to: gs://%s/%s.", gcp_bucket, gcp_path)
|
|
253
|
+
blob.upload_from_string(content.decode("utf-8"))
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
async def sync_from_ftp_to_gcp(
|
|
257
|
+
ftp_server: str,
|
|
258
|
+
ftp_prefix: str,
|
|
259
|
+
ftp_file: str,
|
|
260
|
+
gcp_bucket: str,
|
|
261
|
+
gcp_prefix: str,
|
|
262
|
+
gcp_file: str,
|
|
263
|
+
*,
|
|
264
|
+
dry_run: bool = True,
|
|
265
|
+
) -> None:
|
|
266
|
+
"""Fetch files from FTP and upload to GCP.
|
|
267
|
+
|
|
268
|
+
This function fetches the data from the provided FTP server and uploads the content directly
|
|
269
|
+
to the provided GCP bucket blob.
|
|
270
|
+
|
|
271
|
+
Args:
|
|
272
|
+
ftp_server (str): FTP server.
|
|
273
|
+
ftp_prefix (str): FTP prefix.
|
|
274
|
+
ftp_file (str): FTP file name.
|
|
275
|
+
gcp_bucket (str): GCP bucket name.
|
|
276
|
+
gcp_prefix (str): GCP prefix.
|
|
277
|
+
gcp_file (str): GCP file name.
|
|
278
|
+
dry_run (bool, optional): Dry run flag. Defaults to True.
|
|
279
|
+
|
|
280
|
+
"""
|
|
281
|
+
if dry_run:
|
|
282
|
+
logger.info(
|
|
283
|
+
"Attempting to transfer data from ftp://%s/%s/%s to gs://%s/%s/%s.",
|
|
284
|
+
ftp_server,
|
|
285
|
+
ftp_prefix,
|
|
286
|
+
ftp_file,
|
|
287
|
+
gcp_bucket,
|
|
288
|
+
gcp_prefix,
|
|
289
|
+
gcp_file,
|
|
290
|
+
)
|
|
291
|
+
return
|
|
292
|
+
with FTP(ftp_server) as ftp:
|
|
293
|
+
ftp.login()
|
|
294
|
+
bucket = storage.Client().bucket(gcp_bucket)
|
|
295
|
+
gcp_path = f"{gcp_prefix}/{gcp_file}" if gcp_prefix else gcp_file
|
|
296
|
+
blob = bucket.blob(gcp_path)
|
|
297
|
+
logger.info("Changing directory to %s.", ftp_prefix)
|
|
298
|
+
ftp.cwd(ftp_prefix)
|
|
299
|
+
dir_match = re.match(r"^.*(?P<release_date>\d{4}\/\d{2}\/\d{2}){1}$", ftp.pwd())
|
|
300
|
+
if dir_match:
|
|
301
|
+
logger.info("Found release date!: %s", dir_match.group("release_date"))
|
|
302
|
+
buffer = io.BytesIO()
|
|
303
|
+
logger.info(
|
|
304
|
+
"Retrieving data from: ftp://%s/%s/%s.", ftp_server, ftp_prefix, ftp_file
|
|
305
|
+
)
|
|
306
|
+
ftp.retrbinary(f"RETR {ftp_file}", lambda x: buffer.write(x))
|
|
307
|
+
content = buffer.getvalue().decode("utf-8")
|
|
308
|
+
buffer.close()
|
|
309
|
+
logger.info("Uploading data to: gs://%s/%s.", gcp_bucket, gcp_path)
|
|
310
|
+
blob.upload_from_string("".join(content))
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
__all__ = ["update_gwas_curation_metadata_command"]
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
"""Ütility functions for the CLI."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import logging
|
|
5
|
+
import sys
|
|
6
|
+
import time
|
|
7
|
+
from functools import wraps
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from urllib.parse import urlparse
|
|
10
|
+
|
|
11
|
+
import click
|
|
12
|
+
from google.cloud import storage
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger("gentroutils")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def set_log_file(ctx: click.Context, param: click.Option, log_file: str) -> str:
|
|
18
|
+
"""Set logging file based on provided `log-file` flag.
|
|
19
|
+
|
|
20
|
+
This is a callback function called by the click.Option [--log-file] flag.
|
|
21
|
+
In case of the `log_file` being path to the GCP bucket the returned value
|
|
22
|
+
will be the local temporary file path. both log file paths (remote and local)
|
|
23
|
+
will be stored in the click context object for further reference at the end of the CLI run.
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
Args:
|
|
27
|
+
ctx (click.Context): click context
|
|
28
|
+
param (click.Option): click option
|
|
29
|
+
log_file (str): log file path
|
|
30
|
+
|
|
31
|
+
Raises:
|
|
32
|
+
click.BadParameter: If the log file is a directory or the URI scheme is not GCS.
|
|
33
|
+
|
|
34
|
+
Returns:
|
|
35
|
+
str: log file path
|
|
36
|
+
"""
|
|
37
|
+
ctx.ensure_object(dict)
|
|
38
|
+
if not log_file:
|
|
39
|
+
return ""
|
|
40
|
+
logger.info("Extracting log file from the %s", param)
|
|
41
|
+
upload_to_gcp = False
|
|
42
|
+
if "://" in log_file:
|
|
43
|
+
upload_to_gcp = True
|
|
44
|
+
if upload_to_gcp:
|
|
45
|
+
parsed_uri = urlparse(log_file)
|
|
46
|
+
ctx.obj["gcp_log_file"] = log_file
|
|
47
|
+
if parsed_uri.scheme != "gs":
|
|
48
|
+
raise click.BadParameter("Only GCS is supported for logging upload")
|
|
49
|
+
log_file = parsed_uri.path.strip("/")
|
|
50
|
+
ctx.obj["local_log_file"] = log_file
|
|
51
|
+
ctx.obj["upload_to_gcp"] = upload_to_gcp
|
|
52
|
+
|
|
53
|
+
local_file = Path(log_file)
|
|
54
|
+
if local_file.exists() and local_file.is_dir():
|
|
55
|
+
raise click.BadParameter("Log file is a directory")
|
|
56
|
+
if local_file.exists() and local_file.is_file():
|
|
57
|
+
local_file.unlink()
|
|
58
|
+
if not local_file.exists():
|
|
59
|
+
local_file.touch()
|
|
60
|
+
logger.info("Logging to %s", local_file)
|
|
61
|
+
handler = logging.FileHandler(local_file)
|
|
62
|
+
formatter = logging.Formatter(
|
|
63
|
+
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
|
64
|
+
)
|
|
65
|
+
handler.setFormatter(formatter)
|
|
66
|
+
handler.setLevel(logging.DEBUG)
|
|
67
|
+
logger.addHandler(handler)
|
|
68
|
+
return str(local_file)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def teardown_cli(ctx: click.Context) -> None:
|
|
72
|
+
"""Teardown the gentroutils cli.
|
|
73
|
+
|
|
74
|
+
This function is used to as a teardown function for the CLI.
|
|
75
|
+
This will upload the log file to the GCP bucket if the `upload_to_gcp` flag is set in the context object.
|
|
76
|
+
|
|
77
|
+
Args:
|
|
78
|
+
ctx (click.Context): click context
|
|
79
|
+
"""
|
|
80
|
+
if "upload_to_gcp" in ctx.obj and ctx.obj["upload_to_gcp"]:
|
|
81
|
+
gcp_file = ctx.obj["gcp_log_file"]
|
|
82
|
+
local_file = ctx.obj["local_log_file"]
|
|
83
|
+
client = storage.Client()
|
|
84
|
+
bucket_name = urlparse(gcp_file).netloc
|
|
85
|
+
bucket = client.bucket(bucket_name=bucket_name)
|
|
86
|
+
blob = bucket.blob(Path(local_file).name)
|
|
87
|
+
logger.info("Uploading %s to %s", local_file, gcp_file)
|
|
88
|
+
blob.upload_from_filename(local_file)
|
|
89
|
+
Path(local_file).unlink()
|
|
90
|
+
logger.info(
|
|
91
|
+
"Finished, elapsed time %s seconds", time.time() - ctx.obj["execution_start"]
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def set_log_lvl(_: click.Context, param: click.Option, value: int) -> int:
|
|
96
|
+
"""Set logging level based on the number of provided `v` flags.
|
|
97
|
+
|
|
98
|
+
This is a callback function called by the click.Option [-v] flag.
|
|
99
|
+
For example
|
|
100
|
+
`-vv` - DEBUG
|
|
101
|
+
`-v` - INFO
|
|
102
|
+
`no flag - ERROR
|
|
103
|
+
|
|
104
|
+
Args:
|
|
105
|
+
param (click.Option): click option
|
|
106
|
+
value (int): logging level
|
|
107
|
+
|
|
108
|
+
Returns:
|
|
109
|
+
int: logging level
|
|
110
|
+
"""
|
|
111
|
+
logger.info("Extracting log level from the %s", param)
|
|
112
|
+
log_lvls = {0: logging.ERROR, 1: logging.INFO, 2: logging.DEBUG}
|
|
113
|
+
log_lvl = log_lvls.get(value, logging.DEBUG)
|
|
114
|
+
handler = logging.StreamHandler(sys.stdout)
|
|
115
|
+
formatter = logging.Formatter(
|
|
116
|
+
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
|
117
|
+
)
|
|
118
|
+
handler.setFormatter(formatter)
|
|
119
|
+
handler.setLevel(log_lvl)
|
|
120
|
+
logger.addHandler(handler)
|
|
121
|
+
return log_lvl
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def coro(f):
|
|
125
|
+
"""Corutine wrapper for synchronous functions."""
|
|
126
|
+
|
|
127
|
+
@wraps(f)
|
|
128
|
+
def wrapper(*args, **kwargs):
|
|
129
|
+
"""Wrapper around the synchronous function."""
|
|
130
|
+
return asyncio.run(f(*args, **kwargs))
|
|
131
|
+
|
|
132
|
+
return wrapper
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
__all__ = ["set_log_file", "set_log_lvl", "coro", "logger", "teardown_cli"]
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: gentroutils
|
|
3
|
+
Version: 0.1.5
|
|
4
|
+
Summary: Add your description here
|
|
5
|
+
Author-email: Szymon Szyszkowski <ss60@mib117351s.internal.sanger.ac.uk>
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Requires-Python: >=3.10
|
|
8
|
+
Requires-Dist: click>=8.1.7
|
|
9
|
+
Requires-Dist: google-cloud-storage>=2.18.1
|
|
10
|
+
Requires-Dist: pyfiglet>=1.0.2
|
|
11
|
+
Requires-Dist: requests>=2.32.3
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
|
|
14
|
+
# gentroutils
|
|
15
|
+
|
|
16
|
+
[](https://github.com/opentargets/gentroutils/actions/workflows/test.yaml)
|
|
17
|
+

|
|
18
|
+
|
|
19
|
+
Set of Command Line Interface tools to process Open Targets Genetics GWAS data.
|
|
20
|
+
|
|
21
|
+
## Installation
|
|
22
|
+
|
|
23
|
+
```
|
|
24
|
+
pip install gentroutils
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Available commands
|
|
28
|
+
|
|
29
|
+
To see all available commands after installation run
|
|
30
|
+
|
|
31
|
+
```{bash}
|
|
32
|
+
gentroutils --help
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Contribute
|
|
36
|
+
|
|
37
|
+
To be able to contribute to the project you need to set it up. This project
|
|
38
|
+
runs on:
|
|
39
|
+
|
|
40
|
+
- [x] python 3.10.8
|
|
41
|
+
- [x] rye (package manager)
|
|
42
|
+
- [x] uv (dependency manager)
|
|
43
|
+
|
|
44
|
+
To set up the project run
|
|
45
|
+
|
|
46
|
+
```{bash}
|
|
47
|
+
make dev
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
The command will install above dependencies (initial requirements are curl and bash) if not present and
|
|
51
|
+
install all python dependencies listed in `pyproject.toml`. Finally the command will install `pre-commit` hooks
|
|
52
|
+
requred to be run before the commit is created.
|
|
53
|
+
|
|
54
|
+
The project has additional `dev` dependencies that include the list of packages used for testing purposes.
|
|
55
|
+
All of the `dev` depnendencies are automatically installed by `rye`.
|
|
56
|
+
|
|
57
|
+
To see all available dev commands
|
|
58
|
+
|
|
59
|
+
Run following command to see all available dev commands
|
|
60
|
+
|
|
61
|
+
```{bash}
|
|
62
|
+
make help
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
### Manual testing of CLI module
|
|
66
|
+
|
|
67
|
+
To check CLI execution manually you need to run
|
|
68
|
+
|
|
69
|
+
```{bash}
|
|
70
|
+
rye run gentroutils
|
|
71
|
+
```
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
gentroutils/__init__.py,sha256=aHDzbBMrnsgdcO_FfsYCbbPXProynwB7_2nfyc4UGp8,1281
|
|
2
|
+
gentroutils/commands/__init__.py,sha256=avkqzwa1ck__rLVN0Wqfpr3eHtKS6TvyPeeaHcguJuw,210
|
|
3
|
+
gentroutils/commands/update_gwas_curation_metadata.py,sha256=7pBBkB6JF3VfT12xiP78MT_pmn0Wv4CF7Tm5TPgBXf8,12525
|
|
4
|
+
gentroutils/commands/utils.py,sha256=9Wyptjww9hiAufCFILdnjdDOE6X6TdtyTWJOTkoIRqg,4316
|
|
5
|
+
gentroutils-0.1.5.dist-info/METADATA,sha256=9PFlHuJakF2bnJfF9d6kPepH0jdRJM3g70GevV5Q7fM,1795
|
|
6
|
+
gentroutils-0.1.5.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87
|
|
7
|
+
gentroutils-0.1.5.dist-info/entry_points.txt,sha256=IvxZyBBD71Ota0aPMtVaJzI9OSX5_f-iH4ZJx6sY53w,48
|
|
8
|
+
gentroutils-0.1.5.dist-info/licenses/LICENSE,sha256=RFhQPdSOiMTguUX7JSoIuTxA7HVzCbj_p8WU36HjUQQ,10947
|
|
9
|
+
gentroutils-0.1.5.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|