Skip to content

Commit 73fd06c

Browse files
authored
Merge pull request #98 from CellProfiler/issues/cp-3507
Download images from s3
2 parents 07c6c3c + f31a5e6 commit 73fd06c

File tree

2 files changed

+32
-15
lines changed

2 files changed

+32
-15
lines changed

bioformats/formatreader.py

+31-15
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,34 @@ 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)[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+
688704
def __enter__(self):
689705
return self
690706

setup.py

+1
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)