Skip to content

Commit 736781d

Browse files
committed
Download images from s3
1 parent 07c6c3c commit 736781d

2 files changed

Lines changed: 31 additions & 15 deletions

File tree

bioformats/formatreader.py

Lines changed: 30 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
import numpy as np
3333
import os
3434
import sys
35+
import re
3536

3637
if sys.version_info.major == 3:
3738
from urllib.request import urlopen, urlparse, url2pathname
@@ -49,6 +50,7 @@
4950
import bioformats
5051
from . import metadatatools as metadatatools
5152
import javabridge as javabridge
53+
import boto3
5254

5355
OMERO_READER_IMPORTED = False
5456
try:
@@ -607,21 +609,7 @@ def __init__(self, path=None, url=None, perform_init=True):
607609
#
608610
# Other URLS, copy them to a tempfile location
609611
#
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)
625613
else:
626614
if sys.platform.startswith("win"):
627615
self.path = self.path.replace("/", os.path.sep)
@@ -685,6 +673,33 @@ def __init__(self, path=None, url=None, perform_init=True):
685673
if perform_init:
686674
self.init_reader()
687675

676+
def download(self, url):
677+
scheme = urlparse(url).scheme
678+
ext = url[url.rfind("."):]
679+
680+
if scheme == 's3':
681+
client = boto3.client('s3')
682+
bucket_name, filename = re.compile('s3://([\w\d\-\.]+)/(.*)').search(url).groups()
683+
url = client.generate_presigned_url(
684+
'get_object',
685+
Params={'Bucket': bucket_name, 'Key': filename},
686+
ExpiresIn=86400
687+
)
688+
689+
src = urlopen(url)
690+
dest_fd, self.path = tempfile.mkstemp(suffix=ext)
691+
try:
692+
with os.fdopen(dest_fd, 'wb') as dest:
693+
shutil.copyfileobj(src, dest)
694+
except:
695+
os.remove(self.path)
696+
finally:
697+
src.close()
698+
self.using_temp_file = True
699+
urlpath = urlparse(url)[2]
700+
filename = unquote(urlpath.split("/")[-1])
701+
return filename
702+
688703
def __enter__(self):
689704
return self
690705

setup.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
]
2020
},
2121
install_requires=[
22+
"boto3",
2223
"future",
2324
"javabridge>=1.0"
2425
],

0 commit comments

Comments
 (0)