|
32 | 32 | import numpy as np |
33 | 33 | import os |
34 | 34 | import sys |
| 35 | +import re |
35 | 36 |
|
36 | 37 | if sys.version_info.major == 3: |
37 | 38 | from urllib.request import urlopen, urlparse, url2pathname |
|
49 | 50 | import bioformats |
50 | 51 | from . import metadatatools as metadatatools |
51 | 52 | import javabridge as javabridge |
| 53 | +import boto3 |
52 | 54 |
|
53 | 55 | OMERO_READER_IMPORTED = False |
54 | 56 | try: |
@@ -607,21 +609,7 @@ def __init__(self, path=None, url=None, perform_init=True): |
607 | 609 | # |
608 | 610 | # Other URLS, copy them to a tempfile location |
609 | 611 | # |
610 | | - ext = url[url.rfind("."):] |
611 | | - src = urlopen(url) |
612 | | - dest_fd, self.path = tempfile.mkstemp(suffix=ext) |
613 | | - try: |
614 | | - dest = os.fdopen(dest_fd, 'wb') |
615 | | - shutil.copyfileobj(src, dest) |
616 | | - except: |
617 | | - src.close() |
618 | | - dest.close() |
619 | | - os.remove(self.path) |
620 | | - self.using_temp_file = True |
621 | | - src.close() |
622 | | - dest.close() |
623 | | - urlpath = urlparse(url)[2] |
624 | | - filename = unquote(urlpath.split("/")[-1]) |
| 612 | + filename = self.download(url) |
625 | 613 | else: |
626 | 614 | if sys.platform.startswith("win"): |
627 | 615 | self.path = self.path.replace("/", os.path.sep) |
@@ -685,6 +673,34 @@ def __init__(self, path=None, url=None, perform_init=True): |
685 | 673 | if perform_init: |
686 | 674 | self.init_reader() |
687 | 675 |
|
| 676 | + def download(self, url): |
| 677 | + scheme = urlparse(url)[0] |
| 678 | + ext = url[url.rfind("."):] |
| 679 | + urlpath = urlparse(url)[2] |
| 680 | + filename = unquote(urlpath.split("/")[-1]) |
| 681 | + |
| 682 | + self.using_temp_file = True |
| 683 | + |
| 684 | + if scheme == 's3': |
| 685 | + client = boto3.client('s3') |
| 686 | + bucket_name, key = re.compile('s3://([\w\d\-\.]+)/(.*)').search(url).groups() |
| 687 | + url = client.generate_presigned_url( |
| 688 | + 'get_object', |
| 689 | + Params={'Bucket': bucket_name, 'Key': key.replace("+", " ")} |
| 690 | + ) |
| 691 | + |
| 692 | + src = urlopen(url) |
| 693 | + dest_fd, self.path = tempfile.mkstemp(suffix=ext) |
| 694 | + try: |
| 695 | + with os.fdopen(dest_fd, 'wb') as dest: |
| 696 | + shutil.copyfileobj(src, dest) |
| 697 | + except: |
| 698 | + os.remove(self.path) |
| 699 | + finally: |
| 700 | + src.close() |
| 701 | + |
| 702 | + return filename |
| 703 | + |
688 | 704 | def __enter__(self): |
689 | 705 | return self |
690 | 706 |
|
|
0 commit comments